Algorithmcore
Delay-locked loop
Also called DLL, code tracking loop.
Tracks the code delay of a spread-spectrum signal after acquisition. Early and late correlators give an error signal that is zero at the true delay, and a loop moves the local code replica.
- Time
- Θ(B M) worst
- Space
- Θ(1) extra
- Where
- B = the number of blocks; M = the number of samples per block
- Model
- Real RAM
- Properties
- deterministicfirst order loopneeds acquisitionnoncoherent
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James J. Spilker Jr., D. T. Magill, 1961
A delay-locked loop (DLL) keeps the local copy of a spreading code aligned with the received code once acquisition has found the delay to within about half a chip. It computes two correlations, one with the replica a little early and one a little late. When the replica is aligned, the two have the same size. When the received code is later than the replica, the late correlation is larger, and the loop moves the replica later; when it is earlier, the loop moves it earlier. The difference of the two, normalized, is the discriminator, and its plot against the delay error is the S-curve. The DLL does for the code what a phase-locked loop does for the carrier. A third, prompt correlator at the estimated delay gives the despread data and the carrier phase. The same early-late idea for symbol timing is the early-late gate synchronizer.
In plain words
After the receiver has found roughly where the code starts, the signal keeps drifting, because the transmitter and the receiver move and their clocks differ. The receiver must follow the drift.
It listens with two copies of the code, one slightly ahead of its best guess and one slightly behind it. If the guess is right, both copies match the signal equally well. If the copy behind matches better, the true signal is later than the guess, so the receiver moves its guess later. If the copy ahead matches better, it moves the guess earlier.
It repeats this for each new piece of the signal. Each step moves the guess only part of the way, so that noise does not throw it around.
The problem
The received signal is , where is the code waveform with rectangular chips, time is in chips, the delay changes slowly from block to block, and the amplitude and the carrier phase are unknown. An initial estimate with less than about half a chip comes from acquisition. The task is to produce estimates that follow , block by block, with small error.
The algorithm
DLL(blocks r_1, r_2, …, code c, τ̂_0, δ, g, k_d)- 1
τ̂ ← τ̂_0 - 2
for each block r do - 3
E ← ⟨c(· - τ̂ + δ), r⟩; L ← ⟨c(· - τ̂ - δ), r⟩ ▷ early and late correlators - 4
D ← (|L| - |E|) / (|L| + |E|) ▷ normalized early minus late envelope - 5
τ̂ ← τ̂ + g · D / k_d ▷ loop gain g, S-curve slope k_d - 6
return the estimates τ̂ after each block
Here is the correlation with the code delayed by and with the code delayed by , so and , where is the delay error and is the autocorrelation of the code waveform. For an m-sequence of length with rectangular chips, for and beyond. The envelopes and do not depend on the carrier phase, so the loop works before the carrier is locked. The amplitude cancels in the ratio, so the loop gain does not depend on the signal level. Near lock, the S-curve is the line
for . With , the update L5 is a first-order loop: .
Example
S-curve. For the GPS C/A code, , with chip, the slope is .
| (chips) | 0 | 0.1 | 0.25 | 0.4 | 0.5 | 0.75 | 1.0 | 1.25 | 1.5 |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.2004 | 0.5010 | 0.8016 | 0.9980 | 0.9974 | 0.9961 | 0.9922 | 0 |
The curve is linear up to about half a chip, then stays near , and drops to at chips, where both correlators see only the floor . The output is odd: . At lock, each correlator is half a chip from the peak and sees of the peak amplitude, dB less than the prompt correlator.
Pull-in. Without noise and with , an initial error of chip becomes , , and chip after four blocks: the error halves at each block.
Jitter. For a code of length sampled 127 times per period with noise variance per sample, the discriminator noise at zero error has a standard deviation of chip. With , the linear theory gives chip, and a simulation of the loop gives chip.
Drift. If the delay grows by chip per block, a first-order loop with follows it with a constant lag of chip.
Correctness
The correlation of the code with a shifted copy of itself is for a shift , where is the periodic autocorrelation of the chip sequence. This gives the triangle above. Inside the linear region both lags fall on the rising part of the triangle, so and with , and . Then L5 gives , which goes to zero for . Outside the linear region, a case analysis on the triangle shows that still has the sign of for , so the loop moves the right way. With independent noise per block, has the stationary variance . The full proof is in the proofs folder.
Proof: The early-late discriminator is linear near lock, and the loop drives the delay error to zerofull
Model. Time is in chips. The code is an m-sequence with periodic autocorrelation and for , and is the code waveform with rectangular chips. One block is one code period of the received signal . The correlator with a replica delayed by returns
The implementation replaces the integral by the mean over samples at , a Riemann sum of the same integral. Write for the delay error, , and let be the early-late offset. The loop computes and (L3), the discriminator (L4), and the update (L5), with .
Lemma 1 (autocorrelation of the waveform). , where is even, has period , and on equals
Proof. Substitute ; by periodicity, with . Write with an integer and . On the chip , , and equals on a part of length and on a part of length . Summing over the chips,
For this is , and at it is . For both values are . The function is even because the integral is symmetric under exchanging the two factors.
So and , and depends only on ; call it , the S-curve. The carrier phase and the amplitude cancel.
Lemma 2 (linear region). If , then .
Proof. Since , the two lags are and , and both are at most . On , , so the absolute values can be dropped:
Their ratio is .
Lemma 3 (sign of the S-curve). If and , then is nonzero and has the sign of .
Proof. is even, so , and it is enough to take . Let and ; then . We show , which gives and . By Lemma 1, on , on , and on . Also, exactly when .
- If : is strictly decreasing on , and .
- If and : then , and the hypothesis gives , so .
- If and : then and , so .
- If and : then , so , and .
So the discriminator always pushes the estimate toward the true delay inside a pull-in range of about chips. Outside it, both correlators see the floor and : the loop has lost lock.
Theorem 1 (convergence without noise). Let the delay be constant, , and . Then the error after blocks is , which tends to .
Proof. By L5, . If , Lemma 2 gives , and keeps . Induction on gives the formula, and .
Theorem 2 (jitter in the linear model). Suppose that near lock the discriminator output is , where the are independent with mean and variance , one per block. Then for the variance of tends to
Proof. The update gives . Since is independent of , which depends only on and the start, the variances satisfy . With , tends to the fixed point , which is the stated value.
Theorem 3 (lag under a constant drift). If and the loop stays in the linear region, the error before the update tends to .
Proof. With , L5 gives , so . The fixed point is , and the difference is multiplied by at each step.
Cost. Each block needs two correlations of samples (L3) and further operations (L4 and L5), so blocks cost operations, with extra space beyond the replicas.
Complexity
In the real RAM model, each block of samples costs two correlations of multiply-adds (L3) and a constant number of further operations (L4 and L5). Over blocks the cost is , with extra space. The prompt correlator, which every receiver also needs for the data, adds one more correlation per block.
Properties
- Odd S-curve with a stable zero. and has the sign of in the pull-in range, so the true delay is the only stable point near lock.
- Carrier independent. The envelope discriminator uses and , so the carrier phase and small frequency errors do not affect it.
- Normalized gain. Dividing by removes the amplitude. Without the division, the loop gain changes with the signal level.
- Bandwidth and noise. The loop gain trades the speed of response against the jitter . A smaller gives less noise but a larger lag under drift.
- Lag under drift. A first-order loop follows a delay that changes at a constant rate with a constant error . A second-order loop follows it with zero steady error.
Variants and improvements
- Other discriminators. Borre and coauthors list the coherent , the early minus late power , the normalized envelope used here, and the dot product of early minus late with prompt. The coherent form needs a locked carrier and has lower noise.
- Narrow correlator. A smaller spacing , such as chip, lowers the noise and the error from multipath, since only reflections less than about chips late move the zero of the S-curve. It needs a wide receiver bandwidth.
- Carrier aiding. The carrier loop measures the Doppler shift much more precisely than the code loop. Scaling it by the ratio of the chip rate to the carrier frequency and adding it to the code rate removes most of the drift, so the DLL can use a small gain.
- Higher-order loop filters. A loop filter with an integrator, as in a phase-locked loop, removes the lag under a constant drift.
- Kalman tracking. A Kalman filter with a state of delay and delay rate can replace the fixed loop filter, with gains matched to the noise and the dynamics.
When to use it
Use a DLL in every direct-sequence receiver after acquisition, to keep the code aligned while the delay changes. GNSS receivers use it for every satellite, together with a carrier loop. CDMA receivers use one per rake finger. The DLL needs an initial error inside the pull-in range, so it cannot replace acquisition, and when it loses lock the receiver must search again.
Pitfalls
- Starting too far away. If the initial error is larger than about chips, both correlators see only the floor, , and the loop does not move.
- Wrong slope. The update divides by , which depends on and on the shape of the correlation. A band-limited receiver rounds the triangle and lowers the slope. A wrong changes the effective loop gain.
- Multipath bias. A reflected copy that arrives less than about chips after the direct one changes the shape of the correlation, and the zero of the S-curve moves away from the true delay.
- Gain too large. For the linear loop is unstable. Even for near , the jitter is large, because the loop uses only the latest block.
- Envelope at low SNR. At low signal-to-noise ratio, noise biases and upward and flattens the S-curve, so the actual gain is lower than the design value.
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)
delay_locked_loop.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delay-locked-loop/. The authors are listed in prov/WXMG9W.jsonl.
"""A noncoherent delay-locked loop that tracks the code delay of a spread-spectrum signal.
Model: time is measured in chips. One block holds one code period of N chips,
sampled M times at t_k = k N / M, with M and N coprime so that the chip
edges fall at many different sample offsets:
r_k = A e^(j phi) c[floor(t_k - tau) mod N] + w_k, w_k ~ CN(0, n0).
The early and late replicas are the code delayed by tau_hat - delta and tau_hat + delta.
"""
import cmath
import math
import random
from typing import Iterable
from cbb import cn
def replica(c: list[int], d: float, m: int) -> list[int]:
"""The code delayed by d chips, sampled at t_k = k N / M."""
n = len(c)
return [c[math.floor(k * n / m - d) % n] for k in range(m)]
def correlate(r: list[complex], c: list[int], d: float) -> complex:
"""(1/M) sum over k of r_k times the replica delayed by d (the replica is real)."""
m = len(r)
rep = replica(c, d, m)
return sum(rk * v for rk, v in zip(r, rep)) / m
def received_block(
rng: random.Random, c: list[int], tau: float, m: int, amp: float = 1.0, phase: float = 0.0, n0: float = 0.0
) -> list[complex]:
"""One code period with the code delayed by tau chips, a carrier phase, and CN(0, n0) noise per sample."""
sig = [amp * cmath.exp(1j * phase) * v for v in replica(c, tau, m)]
if n0 > 0:
sig = [v + cn(rng, n0) for v in sig]
return sig
def discriminator(e: complex, l: complex) -> float:
"""The normalized early minus late envelope (|L| - |E|) / (|L| + |E|)."""
s = abs(l) + abs(e)
return 0.0 if s == 0 else (abs(l) - abs(e)) / s
def dll(blocks: Iterable[list[complex]], c: list[int], tau0: float, delta: float, g: float, kd: float) -> list[float]:
"""Run the loop over the blocks. Returns the estimate after each block, starting with tau0."""
tau_hat = tau0 # @line L1
history = [tau_hat]
for r in blocks: # @line L2
e, l = correlate(r, c, tau_hat - delta), correlate(r, c, tau_hat + delta) # @line L3
d = discriminator(e, l) # @line L4
tau_hat = tau_hat + g * d / kd # @line L5
history.append(tau_hat)
return history # @line L6
def mseq_autocorrelation(x: float, n: int) -> float:
"""The periodic autocorrelation of an m-sequence with rectangular chips at a lag of x chips."""
x = (x + n / 2) % n - n / 2
if abs(x) <= 1:
return 1 - abs(x) * (n + 1) / n
return -1 / n
def s_curve(eps: float, delta: float, n: int) -> float:
"""The noiseless discriminator output at the error eps = tau - tau_hat, for continuous time."""
e = mseq_autocorrelation(eps + delta, n)
l = mseq_autocorrelation(eps - delta, n)
return discriminator(complex(e), complex(l))
def slope(delta: float, n: int) -> float:
"""k_d: the slope of the S-curve at eps = 0, (N + 1) / (N - (N + 1) delta), for 0 < delta < N / (N + 1)."""
return (n + 1) / (n - (n + 1) * delta)
def mseq_bits(exps: list[int]) -> list[int]:
"""One period of an m-sequence as chips +1 and -1."""
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)
return [1 - 2 * v for v in s]
test_delay_locked_loop.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/delay-locked-loop/. The authors are listed in prov/WXMG9W.jsonl.
import math
import random
from delay_locked_loop import (
correlate,
discriminator,
dll,
mseq_autocorrelation,
mseq_bits,
received_block,
s_curve,
slope,
)
C31 = mseq_bits([5, 2, 0])
N = 31
def test_autocorrelation_matches_the_sampled_code() -> None:
m = 31 * 64
r = received_block(random.Random(0), C31, 0.0, m)
for x in (0.0, 0.25, 0.5, 0.75, 1.0, 1.5, 3.0, -0.5):
got = correlate(r, C31, x).real
assert abs(got - mseq_autocorrelation(x, N)) < 1e-12
def test_s_curve_is_linear_inside_the_early_late_window() -> None:
delta = 0.5
kd = slope(delta, N)
assert abs(kd - 32 / 15) < 1e-12
for eps in (-0.45, -0.3, -0.1, 0.0, 0.2, 0.4):
assert abs(s_curve(eps, delta, N) - kd * eps) < 1e-12
# Far from the peak both correlators see the floor and the output is zero.
for eps in (1.6, 2.5, -3.0):
assert s_curve(eps, delta, N) == 0.0
def test_sampled_discriminator_follows_the_s_curve() -> None:
rng = random.Random(1)
m = 499
for eps in (-0.4, -0.2, 0.0, 0.1, 0.3):
r = received_block(rng, C31, 10.0 + eps, m, 1.0, rng.uniform(0, 2 * math.pi))
d = discriminator(correlate(r, C31, 10.0 - 0.5), correlate(r, C31, 10.0 + 0.5))
assert abs(d - s_curve(eps, 0.5, N)) < 0.02
def test_converges_from_a_third_of_a_chip() -> None:
rng = random.Random(2)
m, tau = 499, 7.3
blocks = (received_block(rng, C31, tau, m, 1.0, rng.uniform(0, 2 * math.pi)) for _ in range(30))
hist = dll(blocks, C31, 7.0, 0.5, 0.5, slope(0.5, N))
assert abs(tau - hist[0]) > 0.29
assert all(abs(tau - h) < 0.02 for h in hist[10:])
def test_lag_of_a_first_order_loop_under_drift() -> None:
rng = random.Random(3)
m, v, g = 499, 0.004, 0.2
taus = [5.0 + v * k for k in range(201)]
blocks = (received_block(rng, C31, taus[k], m) for k in range(200))
hist = dll(blocks, C31, 5.0, 0.5, g, slope(0.5, N))
# The estimate after block k used the block with delay taus[k]; the lag settles at v (1 - g) / g.
lags = [taus[k] - hist[k + 1] for k in range(100, 200)]
expected = v * (1 - g) / g
assert abs(sum(lags) / len(lags) - expected) < 0.005
def test_jitter_matches_the_linear_loop_theory() -> None:
rng = random.Random(4)
m, n0, delta, g, tau = 127, 2.0, 0.5, 0.2, 3.0
kd = slope(delta, N)
# Open loop: the noise of D / kd at zero error.
v = []
for _ in range(1500):
r = received_block(rng, C31, tau, m, 1.0, rng.uniform(0, 2 * math.pi), n0)
v.append(discriminator(correlate(r, C31, tau - delta), correlate(r, C31, tau + delta)) / kd)
mean_v = sum(v) / len(v)
var_v = sum((x - mean_v) ** 2 for x in v) / (len(v) - 1)
assert abs(mean_v) < 0.01
# Closed loop: eps(k + 1) = (1 - g) eps(k) - g v(k) has variance g var_v / (2 - g).
blocks = (received_block(rng, C31, tau, m, 1.0, rng.uniform(0, 2 * math.pi), n0) for _ in range(2000))
hist = dll(blocks, C31, tau, delta, g, kd)
errs = [tau - h for h in hist[100:]]
me = sum(errs) / len(errs)
var_e = sum((x - me) ** 2 for x in errs) / (len(errs) - 1)
ratio = var_e / (g * var_v / (2 - g))
assert 0.5 < ratio < 2.0
History
James Spilker and D. T. Magill presented the delay-lock discriminator in the Proceedings of the IRE in 1961, as a feedback loop that tracks the delay of a received signal by correlating it with delayed copies of a reference. With the development of spread-spectrum ranging and of GPS, the early-late code tracking loop became a standard part of direct-sequence and satellite navigation receivers; Borre and coauthors describe its form in a software GPS receiver.
References
- J. J. Spilker, Jr. and D. T. Magill, The delay-lock discriminator, an optimum tracking device, Proceedings of the IRE 49(9), 1961, pp. 1403 to 1416
- 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 7.5, p. 96 (code tracking with early, prompt and late replicas half a chip apart); Table 7.2, p. 99 (the DLL discriminators)
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 WXMG9W Edit this page History Report an error Markdown