Algorithm Search⌘K

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
Properties
deterministicfirst order loopneeds acquisitionnoncoherent
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 Aejϕc(t−τk)+w(t)A e^{j\phi} c(t - \tau_k) + w(t), where c(t)c(t) is the code waveform with rectangular chips, time is in chips, the delay τk\tau_k changes slowly from block to block, and the amplitude AA and the carrier phase ϕ\phi are unknown. An initial estimate τ^0\hat\tau_0 with ∣τ0−τ^0∣|\tau_0 - \hat\tau_0| less than about half a chip comes from acquisition. The task is to produce estimates τ^k\hat\tau_k that follow τk\tau_k, block by block, with small error.

The algorithm

  1. DLL(blocks r_1, r_2, …, code c, τ̂_0, δ, g, k_d)
  2. 1τ̂ ← τ̂_0
  3. 2for each block r do
  4. 3E ← ⟨c(· - τ̂ + δ), r⟩; L ← ⟨c(· - τ̂ - δ), r⟩ ▷ early and late correlators
  5. 4D ← (|L| - |E|) / (|L| + |E|) ▷ normalized early minus late envelope
  6. 5τ̂ ← τ̂ + g · D / k_d ▷ loop gain g, S-curve slope k_d
  7. 6return the estimates τ̂ after each block

Here EE is the correlation with the code delayed by τ^−δ\hat\tau - \delta and LL with the code delayed by τ^+δ\hat\tau + \delta, so E=AejϕR(ε+δ)E = A e^{j\phi} R(\varepsilon + \delta) and L=AejϕR(ε−δ)L = A e^{j\phi} R(\varepsilon - \delta), where ε=τ−τ^\varepsilon = \tau - \hat\tau is the delay error and RR is the autocorrelation of the code waveform. For an m-sequence of length NN with rectangular chips, R(x)=1−∣x∣(N+1)/NR(x) = 1 - |x|(N + 1)/N for ∣x∣≤1|x| \le 1 and −1/N-1/N beyond. The envelopes ∣E∣|E| and ∣L∣|L| do not depend on the carrier phase, so the loop works before the carrier is locked. The amplitude AA cancels in the ratio, so the loop gain does not depend on the signal level. Near lock, the S-curve is the line

D(ε)=kd ε,kd=N+1N−(N+1)δ,D(\varepsilon) = k_d\, \varepsilon, \qquad k_d = \frac{N + 1}{N - (N + 1)\delta},

for ∣ε∣≤min⁡(δ,N/(N+1)−δ)|\varepsilon| \le \min(\delta, N/(N + 1) - \delta). With D/kd=εD/k_d = \varepsilon, the update L5 is a first-order loop: ε←(1−g) ε\varepsilon \leftarrow (1 - g)\, \varepsilon.

Example

S-curve. For the GPS C/A code, N=1023N = 1023, with δ=1/2\delta = 1/2 chip, the slope is kd=2.0039k_d = 2.0039.

ε\varepsilon (chips) 0 0.1 0.25 0.4 0.5 0.75 1.0 1.25 1.5
D(ε)D(\varepsilon) 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 11, and drops to 00 at 1.51.5 chips, where both correlators see only the floor 1/N1/N. The output is odd: D(−ε)=−D(ε)D(-\varepsilon) = -D(\varepsilon). At lock, each correlator is half a chip from the peak and sees R(1/2)=0.4995R(1/2) = 0.4995 of the peak amplitude, 6.036.03 dB less than the prompt correlator.

Pull-in. Without noise and with g=1/2g = 1/2, an initial error of 0.30.3 chip becomes 0.150.15, 0.0750.075, 0.03750.0375 and 0.018750.01875 chip after four blocks: the error halves at each block.

Jitter. For a code of length N=31N = 31 sampled 127 times per period with noise variance 22 per sample, the discriminator noise D/kdD/k_d at zero error has a standard deviation of 0.06050.0605 chip. With g=0.2g = 0.2, the linear theory σε2=gσv2/(2−g)\sigma_\varepsilon^2 = g\sigma_v^2/(2 - g) gives 0.02020.0202 chip, and a simulation of the loop gives 0.02030.0203 chip.

Drift. If the delay grows by 0.0040.004 chip per block, a first-order loop with g=0.2g = 0.2 follows it with a constant lag of 0.004/0.2=0.020.004/0.2 = 0.02 chip.

Correctness

The correlation of the code with a shifted copy of itself is (1−f)ρ(i)+fρ(i+1)(1 - f)\rho(i) + f\rho(i + 1) for a shift i+fi + f, where ρ\rho is the periodic autocorrelation of the chip sequence. This gives the triangle RR above. Inside the linear region both lags δ±ε\delta \pm \varepsilon fall on the rising part of the triangle, so ∣L∣−∣E∣=2aε|L| - |E| = 2a\varepsilon and ∣L∣+∣E∣=2(1−aδ)|L| + |E| = 2(1 - a\delta) with a=(N+1)/Na = (N + 1)/N, and D=kdεD = k_d \varepsilon. Then L5 gives εk+1=(1−g)εk\varepsilon_{k+1} = (1 - g)\varepsilon_k, which goes to zero for 0<g<20 < g < 2. Outside the linear region, a case analysis on the triangle shows that DD still has the sign of ε\varepsilon for 0<∣ε∣<δ+(N−1)/(N+1)0 < |\varepsilon| < \delta + (N - 1)/(N + 1), so the loop moves the right way. With independent noise vkv_k per block, εk+1=(1−g)εk−gvk\varepsilon_{k+1} = (1 - g)\varepsilon_k - g v_k has the stationary variance gσv2/(2−g)g\sigma_v^2/(2 - g). 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 c0,…,cN−1∈{+1,−1}c_0, \ldots, c_{N-1} \in \{+1, -1\} with periodic autocorrelation ρ(0)=1\rho(0) = 1 and ρ(i)=−1/N\rho(i) = -1/N for i≢0(modN)i \not\equiv 0 \pmod N, and c(t)=c⌊t⌋ mod Nc(t) = c_{\lfloor t \rfloor \bmod N} is the code waveform with rectangular chips. One block is one code period of the received signal Aejϕc(t−τ)A e^{j\phi} c(t - \tau). The correlator with a replica delayed by dd returns

corr(d)=1N∫0NAejϕ c(t−τ) c(t−d) dt.\mathrm{corr}(d) = \frac{1}{N} \int_0^N A e^{j\phi}\, c(t - \tau)\, c(t - d)\, dt.

The implementation replaces the integral by the mean over MM samples at tk=kN/Mt_k = k N / M, a Riemann sum of the same integral. Write ε=τ−τ^\varepsilon = \tau - \hat\tau for the delay error, a=(N+1)/Na = (N + 1)/N, and let 0<δ<N/(N+1)0 < \delta < N/(N + 1) be the early-late offset. The loop computes E=corr(τ^−δ)E = \mathrm{corr}(\hat\tau - \delta) and L=corr(τ^+δ)L = \mathrm{corr}(\hat\tau + \delta) (L3), the discriminator D=(∣L∣−∣E∣)/(∣L∣+∣E∣)D = (|L| - |E|)/(|L| + |E|) (L4), and the update τ^←τ^+gD/kd\hat\tau \leftarrow \hat\tau + g D / k_d (L5), with kd=a/(1−aδ)k_d = a/(1 - a\delta).

Lemma 1 (autocorrelation of the waveform). corr(d)=AejϕR(τ−d)\mathrm{corr}(d) = A e^{j\phi} R(\tau - d), where RR is even, has period NN, and on [0,N/2][0, N/2] equals

R(x)=1−ax(0≤x≤1),R(x)=−1/N(1≤x≤N/2).R(x) = 1 - a x \quad (0 \le x \le 1), \qquad R(x) = -1/N \quad (1 \le x \le N/2).

Proof. Substitute s=t−τs = t - \tau; by periodicity, corr(d)=Aejϕ1N∫0Nc(s) c(s−x) ds\mathrm{corr}(d) = A e^{j\phi} \frac{1}{N} \int_0^N c(s)\, c(s - x)\, ds with x=τ−dx = \tau - d. Write x=i+fx = i + f with an integer ii and 0≤f<10 \le f < 1. On the chip [n,n+1)[n, n + 1), c(s)=cnc(s) = c_n, and c(s−x)c(s - x) equals cn−ic_{n - i} on a part of length 1−f1 - f and cn−i−1c_{n - i - 1} on a part of length ff. Summing over the chips,

1N∫0Nc(s)c(s−x) ds=(1−f) ρ(i)+f ρ(i+1).\frac{1}{N}\int_0^N c(s) c(s - x)\, ds = (1 - f)\, \rho(i) + f\, \rho(i + 1).

For 0≤x<10 \le x < 1 this is (1−x)⋅1+x⋅(−1/N)=1−ax(1 - x) \cdot 1 + x \cdot (-1/N) = 1 - a x, and at x=1x = 1 it is −1/N=1−a-1/N = 1 - a. For 1≤x≤N/21 \le x \le N/2 both ρ\rho values are −1/N-1/N. The function is even because the integral is symmetric under exchanging the two factors. □\square

So ∣E∣=∣A∣ ∣R(ε+δ)∣|E| = |A|\, |R(\varepsilon + \delta)| and ∣L∣=∣A∣ ∣R(ε−δ)∣|L| = |A|\, |R(\varepsilon - \delta)|, and DD depends only on ε\varepsilon; call it D(ε)D(\varepsilon), the S-curve. The carrier phase ϕ\phi and the amplitude AA cancel.

Lemma 2 (linear region). If ∣ε∣≤ℓ=min⁡(δ, N/(N+1)−δ)|\varepsilon| \le \ell = \min(\delta,\ N/(N + 1) - \delta), then D(ε)=kd εD(\varepsilon) = k_d\, \varepsilon.

Proof. Since ∣ε∣≤δ|\varepsilon| \le \delta, the two lags are ∣ε−δ∣=δ−ε|\varepsilon - \delta| = \delta - \varepsilon and ∣ε+δ∣=δ+ε|\varepsilon + \delta| = \delta + \varepsilon, and both are at most ∣ε∣+δ≤N/(N+1)=1/a|\varepsilon| + \delta \le N/(N + 1) = 1/a. On [0,1/a][0, 1/a], R(x)=1−ax≥0R(x) = 1 - a x \ge 0, so the absolute values can be dropped:

∣L∣−∣E∣=(1−a(δ−ε))−(1−a(δ+ε))=2aε,∣L∣+∣E∣=2(1−aδ).|L| - |E| = (1 - a(\delta - \varepsilon)) - (1 - a(\delta + \varepsilon)) = 2 a \varepsilon, \qquad |L| + |E| = 2(1 - a\delta).

Their ratio is aε/(1−aδ)=kdεa\varepsilon/(1 - a\delta) = k_d \varepsilon. □\square

Lemma 3 (sign of the S-curve). If 0<∣ε∣<δ+(N−1)/(N+1)0 < |\varepsilon| < \delta + (N - 1)/(N + 1) and ∣ε∣+δ≤N/2|\varepsilon| + \delta \le N/2, then D(ε)D(\varepsilon) is nonzero and has the sign of ε\varepsilon.

Proof. RR is even, so D(−ε)=−D(ε)D(-\varepsilon) = -D(\varepsilon), and it is enough to take ε>0\varepsilon > 0. Let xL=∣ε−δ∣x_L = |\varepsilon - \delta| and xE=ε+δx_E = \varepsilon + \delta; then xL<xE≤N/2x_L < x_E \le N/2. We show ∣R(xL)∣>∣R(xE)∣|R(x_L)| > |R(x_E)|, which gives ∣L∣>∣E∣|L| > |E| and D>0D > 0. By Lemma 1, ∣R(x)∣=1−ax|R(x)| = 1 - a x on [0,1/a][0, 1/a], ∣R(x)∣=ax−1≤1/N|R(x)| = a x - 1 \le 1/N on [1/a,1][1/a, 1], and ∣R(x)∣=1/N|R(x)| = 1/N on [1,N/2][1, N/2]. Also, ∣R(x)∣>1/N|R(x)| > 1/N exactly when x<(N−1)/(N+1)x < (N - 1)/(N + 1).

  • If xE≤1/ax_E \le 1/a: ∣R∣|R| is strictly decreasing on [0,xE][0, x_E], and xL<xEx_L < x_E.
  • If xE>1/ax_E > 1/a and ε≥δ\varepsilon \ge \delta: then ∣R(xE)∣≤1/N|R(x_E)| \le 1/N, and the hypothesis gives xL=ε−δ<(N−1)/(N+1)x_L = \varepsilon - \delta < (N - 1)/(N + 1), so ∣R(xL)∣>1/N|R(x_L)| > 1/N.
  • If 1/a<xE≤11/a < x_E \le 1 and ε<δ\varepsilon < \delta: then xL=δ−ε<1/ax_L = \delta - \varepsilon < 1/a and xL+xE=2δx_L + x_E = 2\delta, so ∣R(xL)∣−∣R(xE)∣=2−a(xL+xE)=2(1−aδ)>0|R(x_L)| - |R(x_E)| = 2 - a(x_L + x_E) = 2(1 - a\delta) > 0.
  • If xE>1x_E > 1 and ε<δ\varepsilon < \delta: then ε>1−δ\varepsilon > 1 - \delta, so xL=δ−ε<2δ−1<2N/(N+1)−1=(N−1)/(N+1)x_L = \delta - \varepsilon < 2\delta - 1 < 2N/(N + 1) - 1 = (N - 1)/(N + 1), and ∣R(xL)∣>1/N=∣R(xE)∣|R(x_L)| > 1/N = |R(x_E)|. □\square

So the discriminator always pushes the estimate toward the true delay inside a pull-in range of about 1+δ1 + \delta chips. Outside it, both correlators see the floor 1/N1/N and D=0D = 0: the loop has lost lock.

Theorem 1 (convergence without noise). Let the delay τ\tau be constant, 0<g<20 < g < 2, and ∣ε0∣≤ℓ|\varepsilon_0| \le \ell. Then the error after kk blocks is εk=(1−g)kε0\varepsilon_k = (1 - g)^k \varepsilon_0, which tends to 00.

Proof. By L5, εk+1=τ−τ^k+1=εk−gD(εk)/kd\varepsilon_{k+1} = \tau - \hat\tau_{k+1} = \varepsilon_k - g D(\varepsilon_k)/k_d. If ∣εk∣≤ℓ|\varepsilon_k| \le \ell, Lemma 2 gives εk+1=(1−g)εk\varepsilon_{k+1} = (1 - g)\varepsilon_k, and ∣1−g∣<1|1 - g| < 1 keeps ∣εk+1∣≤ℓ|\varepsilon_{k+1}| \le \ell. Induction on kk gives the formula, and (1−g)k→0(1 - g)^k \to 0. □\square

Theorem 2 (jitter in the linear model). Suppose that near lock the discriminator output is D/kd=εk+vkD/k_d = \varepsilon_k + v_k, where the vkv_k are independent with mean 00 and variance σv2\sigma_v^2, one per block. Then for 0<g<20 < g < 2 the variance of εk\varepsilon_k tends to

σε2=g σv22−g.\sigma_\varepsilon^2 = \frac{g\, \sigma_v^2}{2 - g}.

Proof. The update gives εk+1=(1−g)εk−gvk\varepsilon_{k+1} = (1 - g)\varepsilon_k - g v_k. Since vkv_k is independent of εk\varepsilon_k, which depends only on v0,…,vk−1v_0, \ldots, v_{k-1} and the start, the variances satisfy sk+1=(1−g)2sk+g2σv2s_{k+1} = (1 - g)^2 s_k + g^2 \sigma_v^2. With (1−g)2<1(1 - g)^2 < 1, sks_k tends to the fixed point g2σv2/(1−(1−g)2)=g2σv2/(g(2−g))g^2\sigma_v^2 / (1 - (1 - g)^2) = g^2 \sigma_v^2 / (g(2 - g)), which is the stated value. □\square

Theorem 3 (lag under a constant drift). If τk=τ0+kv\tau_k = \tau_0 + k v and the loop stays in the linear region, the error before the update tends to v/gv/g.

Proof. With ek=τk−τ^ke_k = \tau_k - \hat\tau_k, L5 gives τ^k+1=τ^k+gek\hat\tau_{k+1} = \hat\tau_k + g e_k, so ek+1=τk+v−τ^k−gek=(1−g)ek+ve_{k+1} = \tau_k + v - \hat\tau_k - g e_k = (1 - g) e_k + v. The fixed point is v/gv/g, and the difference ek−v/ge_k - v/g is multiplied by 1−g1 - g at each step. □\square

Cost. Each block needs two correlations of MM samples (L3) and O(1)O(1) further operations (L4 and L5), so BB blocks cost Θ(BM)\Theta(B M) operations, with Θ(1)\Theta(1) extra space beyond the replicas.

Complexity

In the real RAM model, each block of MM samples costs two correlations of MM multiply-adds (L3) and a constant number of further operations (L4 and L5). Over BB blocks the cost is Θ(BM)\Theta(B M), with Θ(1)\Theta(1) 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. D(0)=0D(0) = 0 and DD has the sign of ε\varepsilon in the pull-in range, so the true delay is the only stable point near lock.
  • Carrier independent. The envelope discriminator uses ∣E∣|E| and ∣L∣|L|, so the carrier phase and small frequency errors do not affect it.
  • Normalized gain. Dividing by ∣L∣+∣E∣|L| + |E| removes the amplitude. Without the division, the loop gain changes with the signal level.
  • Bandwidth and noise. The loop gain gg trades the speed of response against the jitter gσv2/(2−g)g\sigma_v^2/(2 - g). A smaller gg 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 v/gv/g. A second-order loop follows it with zero steady error.

Variants and improvements

  • Other discriminators. Borre and coauthors list the coherent IE−ILI_E - I_L, the early minus late power ∣E∣2−∣L∣2|E|^2 - |L|^2, 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 δ\delta, such as 0.10.1 chip, lowers the noise and the error from multipath, since only reflections less than about 1+δ1 + \delta 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 1+δ1 + \delta chips, both correlators see only the floor, D=0D = 0, and the loop does not move.
  • Wrong slope. The update divides by kdk_d, which depends on δ\delta and on the shape of the correlation. A band-limited receiver rounds the triangle and lowers the slope. A wrong kdk_d changes the effective loop gain.
  • Multipath bias. A reflected copy that arrives less than about 1+δ1 + \delta 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 g≥2g \ge 2 the linear loop is unstable. Even for gg near 11, the jitter is large, because the loop uses only the latest block.
  • Envelope at low SNR. At low signal-to-noise ratio, noise biases ∣E∣|E| and ∣L∣|L| 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.

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

  1. 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
  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 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.

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