Algorithm Search⌘K

Algorithmcore

Range-Doppler processing

Also called pulse-Doppler processing, range-Doppler map.

Applies the matched filter to each pulse in fast time, then a windowed FFT across the pulses at each range bin, which gives a map of target power over range and Doppler.

Time
Θ(P N L + N P log P) worst · average · best
Space
Θ(P N) extra
Where
L = the length of the pulse; N = the number of samples per pulse; P = the number of pulses, a power of two
Properties
coherentdeterministiclinear

Range-Doppler processing turns the returns of a train of PP coherent pulses into a two-dimensional map of power over range and radial speed. For each pulse it applies the matched filter of the transmitted pulse along fast time, which is pulse compression, and then, for each range bin, it takes a windowed FFT across the pulses along slow time. A point target gives a peak at its delay and its Doppler bin, with the coherent gain LPL P over the noise of one sample. The CFAR detector then runs on the map. The page range-Doppler algorithm has a similar name but is a SAR image formation algorithm, which focuses a synthetic aperture image, not the detection map of range and speed described here.

In plain words

A radar sends the same pulse PP times, at a fixed interval. Put the samples of each echo in a row of a table, so that the columns are the ranges. First, correlate each row with the pulse, so that each target becomes a sharp peak at its range. Then look down each column. A target that moves turns its phase by the same step from one pulse to the next, so down the column you see a complex sinusoid. Its frequency is the Doppler shift, and an FFT down the column finds it. Each column becomes a spectrum, and the table becomes a map: one axis is range, the other is speed. Fixed clutter goes to the zero speed row, and moving targets go to other rows.

The problem

The input is a P×NP \times N array x[p][n]x[p][n] of complex baseband samples, pulse p=0,…,P−1p = 0, \dots, P - 1 (slow time, one row per pulse repetition interval) and sample n=0,…,N−1n = 0, \dots, N - 1 (fast time), the pulse s[0],…,s[L−1]s[0], \dots, s[L-1] with 1≤L≤N1 \le L \le N, and a window w[0],…,w[P−1]w[0], \dots, w[P-1]. PP is a power of two. The output is the map

D[k][r]=∑p=0P−1w[p](∑l=0L−1s[l]‾ x[p][r+l])e−j2πkp/PD[k][r] = \sum_{p=0}^{P-1} w[p] \left( \sum_{l=0}^{L-1} \overline{s[l]}\, x[p][r + l] \right) e^{-j 2\pi k p / P}

for the Doppler bins k=0,…,P−1k = 0, \dots, P - 1 and the range bins r=0,…,N−Lr = 0, \dots, N - L. Bin kk is the Doppler frequency k PRF/Pk\,\mathrm{PRF}/P for k<P/2k < P/2 and (k−P) PRF/P(k - P)\,\mathrm{PRF}/P for k≥P/2k \ge P/2, and the radial speed is v=fdλ/2v = f_d \lambda / 2.

The algorithm

  1. RANGE-DOPPLER(x[0..P-1][0..N-1], s[0..L-1], w[0..P-1])
  2. 1for p <- 0 to P - 1 ▷ fast time: matched filter of each pulse
  3. 2for r <- 0 to N - L
  4. 3z[p][r] <- sum over l = 0, ..., L - 1 of conj(s[l]) * x[p][r + l]
  5. 4for r <- 0 to N - L ▷ slow time: Doppler spectrum of each range bin
  6. 5u[p] <- w[p] * z[p][r] for p = 0, ..., P - 1
  7. 6D[0..P-1][r] <- FFT(u)
  8. 7return D

Lines L1 to L3 compress each pulse: the correlation with the conjugated pulse is the matched filter, and only the N−L+1N - L + 1 lags where the whole pulse fits in the samples are kept. Line L5 applies the window along slow time, and line L6 takes the FFT of length PP of each column. The implementation uses an iterative radix-2 FFT with a bit reversal permutation. For long pulses, lines L1 to L3 are also done with FFTs: a fast convolution of each row.

Example

Take P=4P = 4 pulses of N=5N = 5 samples, the pulse s=(1,1)s = (1, 1) of length L=2L = 2, a rectangular window, and one target with amplitude 1, delay 1 and Doppler fd=PRF/4f_d = \mathrm{PRF}/4. The target turns a quarter cycle per pulse, so x[p][n]=jps[n−1]x[p][n] = j^p s[n - 1], and row pp is (0,jp,jp,0,0)(0, j^p, j^p, 0, 0).

step r=0r = 0 r=1r = 1 r=2r = 2 r=3r = 3
z[p][r]z[p][r] after line L3 jpj^p 2jp2 j^p jpj^p 00
D[0][r]D[0][r] 0 0 0 0
D[1][r]D[1][r] 4 8 4 0
D[2][r]D[2][r] 0 0 0 0
D[3][r]D[3][r] 0 0 0 0

The FFT of (1,j,−1,−j)(1, j, -1, -j) is (0,4,0,0)(0, 4, 0, 0), so all the energy goes to Doppler bin 1. The peak is D[1][1]=8=EsPD[1][1] = 8 = E_s P, with the pulse energy Es=2E_s = 2, at the true delay. The values 4 at r=0r = 0 and r=2r = 2 are the range sidelobes of the pulse, the autocorrelation (1,2,1)(1, 2, 1) of ss.

A larger case: at 10 GHz with a PRF of 10 kHz and P=16P = 16, the Doppler bins are 10 000/16=62510\,000/16 = 625 Hz apart, which is 9.37 m/s. Bin 3 is 1875 Hz, or 28.11 m/s, and bin 13 is bin −3-3, a target moving away at 28.11 m/s. The unambiguous speeds are ±74.95\pm 74.95 m/s and the unambiguous range is c/(2 PRF)=14.99c/(2\,\mathrm{PRF}) = 14.99 km. With the 13-chip Barker code, the gain is LP=208L P = 208, or 23.18 dB.

Correctness

Lines L1 to L3 compute the inner sum of the definition for every pair (p,r)(p, r), and every index r+lr + l is at most N−1N - 1. The radix-2 FFT returns the DFT of its input, which is proved by induction on the block size after the bit reversal. Line L6 applies it to w[p]z[p][r]w[p] z[p][r], which gives the outer sum. For a point target a ej2πϕps[n−r0]a\, e^{j 2\pi \phi p} s[n - r_0], the Cauchy-Schwarz inequality bounds ∣z[p][r]∣|z[p][r]| by ∣a∣Es|a| E_s, with equality at r=r0r = r_0. When ϕ=k0/P\phi = k_0/P, the column at r0r_0 is a sampled sinusoid on a DFT bin, so the map has the value aEsPa E_s P at (k0,r0)(k_0, r_0) for a rectangular window and 0 in the other bins of that column. White noise of power N0N_0 gives E∣D∣2=N0Es∑p∣w[p]∣2E|D|^2 = N_0 E_s \sum_p |w[p]|^2. The correctness proof gives the full arguments.

Proof: Range-Doppler processing computes the matched filter in fast time and the DFT in slow time, puts a point target at its delay and Doppler bin with gain E_s P, and has the noise gain N0 E_s sum of w^2full

The notation is that of the page. X[p][n]X[p][n] is the complex sample n=0,…,N−1n = 0, \dots, N-1 (fast time) of pulse p=0,…,P−1p = 0, \dots, P-1 (slow time), with P=2νP = 2^\nu. The pulse is s[0],…,s[L−1]s[0], \dots, s[L-1] with 1≤L≤N1 \le L \le N, and its energy is Es=∑l∣s[l]∣2>0E_s = \sum_l |s[l]|^2 > 0. The slow-time window is w[0],…,w[P−1]w[0], \dots, w[P-1]. Lines L1 to L3 compute, for r=0,…,N−Lr = 0, \dots, N - L,

z[p][r]=∑l=0L−1s[l]‾ X[p][r+l],z[p][r] = \sum_{l=0}^{L-1} \overline{s[l]}\, X[p][r + l],

and lines L4 to L6 compute, for every rr, the FFT of u[p]=w[p] z[p][r]u[p] = w[p]\, z[p][r]. The claim is that the output is

D[k][r]=∑p=0P−1w[p] z[p][r] e−j2πkp/P,k=0,…,P−1.D[k][r] = \sum_{p=0}^{P-1} w[p]\, z[p][r]\, e^{-j 2\pi k p / P}, \qquad k = 0, \dots, P-1.

Lemma 1 (the radix-2 FFT). For a list xx of length P=2νP = 2^\nu, the function fft returns x^[k]=∑t=0P−1x[t] e−j2πkt/P\hat{x}[k] = \sum_{t=0}^{P-1} x[t]\, e^{-j 2\pi k t / P} for every kk.

Proof. Let rev(i)\mathrm{rev}(i) be the integer whose ν\nu bits are those of ii in reverse order. The first loop is the standard bit reversal permutation, so after it a[i]=x[rev(i)]a[i] = x[\mathrm{rev}(i)]. If s=2ms = 2^m divides bb and 0≤u<s0 \le u < s, the low mm bits of b+ub + u are those of uu, and they become the high bits of the reversed index, so rev(b+u)=rev(b)+revm(u) P/s\mathrm{rev}(b + u) = \mathrm{rev}(b) + \mathrm{rev}_m(u)\, P/s, with revm\mathrm{rev}_m the reversal of mm bits.

We show by induction on mm that after the stages up to block size s=2ms = 2^m, every block that starts at a multiple bb of ss holds

a[b+k]=∑t=0s−1x ⁣[rev(b)+t Ps]e−j2πkt/s,k=0,…,s−1.a[b + k] = \sum_{t=0}^{s-1} x\!\left[\mathrm{rev}(b) + t\, \tfrac{P}{s}\right] e^{-j 2\pi k t / s}, \qquad k = 0, \dots, s - 1.

Base, s=1s = 1. a[b]=x[rev(b)]a[b] = x[\mathrm{rev}(b)], the DFT of length 1.

Step, ss to 2s2s. Let bb be a multiple of 2s2s and g[t′]=x[rev(b)+t′P/(2s)]g[t'] = x[\mathrm{rev}(b) + t' P/(2s)] for t′=0,…,2s−1t' = 0, \dots, 2s - 1. Bit mm of b+sb + s is set and bit mm of bb is not, so rev(b+s)=rev(b)+P/(2s)\mathrm{rev}(b + s) = \mathrm{rev}(b) + P/(2s). By the hypothesis, a[b+k]a[b + k] is the DFT of length ss of g[2t]g[2t] and a[b+s+k]a[b + s + k] is the DFT of length ss of g[2t+1]g[2t + 1]. Call them E[k]E[k] and O[k]O[k]. Split the DFT of length 2s2s of gg into the even and the odd t′t':

g^[k]=E[k]+e−j2πk/(2s)O[k],g^[k+s]=E[k]−e−j2πk/(2s)O[k],\hat{g}[k] = E[k] + e^{-j 2\pi k/(2s)} O[k], \qquad \hat{g}[k + s] = E[k] - e^{-j 2\pi k/(2s)} O[k],

for k=0,…,s−1k = 0, \dots, s - 1, because e−j2π(k+s)/(2s)=−e−j2πk/(2s)e^{-j 2\pi (k + s)/(2s)} = -e^{-j 2\pi k/(2s)} and e−j2π(k+s)2t/(2s)=e−j2πkt/se^{-j 2\pi (k+s) 2t/(2s)} = e^{-j 2\pi k t / s}. The stage of size 2s2s in the code has the twiddle tw[k]=e−j2πk/(2s)\mathrm{tw}[k] = e^{-j 2\pi k/(2s)} and writes exactly these two values into a[b+k]a[b + k] and a[b+s+k]a[b + s + k]. So the claim holds for 2s2s.

At s=Ps = P there is one block, b=0b = 0, rev(0)=0\mathrm{rev}(0) = 0, and a[k]=x^[k]a[k] = \hat{x}[k]. □\square

Theorem 1 (the map). The function returns D[k][r]D[k][r] as defined above, for k=0,…,P−1k = 0, \dots, P - 1 and r=0,…,N−Lr = 0, \dots, N - L.

Proof. Lines L1 to L3 visit every pair (p,r)(p, r) once and form the sum of the definition of zz. Every index r+lr + l is at most N−L+L−1=N−1N - L + L - 1 = N - 1. Line L5 forms u[p]=w[p]z[p][r]u[p] = w[p] z[p][r] and line L6 applies fft, which by Lemma 1 returns ∑pu[p]e−j2πkp/P\sum_p u[p] e^{-j 2\pi k p/P} in entry kk. The code stores entry kk in D[k][r]D[k][r]. □\square

Theorem 2 (a point target). Let X[p][n]=a ej2πϕp s[n−r0]X[p][n] = a\, e^{j 2\pi \phi p}\, s[n - r_0], with s[m]=0s[m] = 0 outside 0≤m≤L−10 \le m \le L-1, a complex amplitude a≠0a \ne 0, a delay 0≤r0≤N−L0 \le r_0 \le N - L and the normalized Doppler ϕ=fd/PRF\phi = f_d / \mathrm{PRF}. Then:

  1. ∣D[k][r]∣≤∣a∣ Es∑p∣w[p]∣|D[k][r]| \le |a|\, E_s \sum_p |w[p]| for all kk and rr.
  2. z[p][r0]=a Es ej2πϕpz[p][r_0] = a\, E_s\, e^{j 2\pi \phi p}, so the bound of part 1 is reached at r=r0r = r_0 if w≥0w \ge 0 and ϕ=k0/P\phi = k_0/P for an integer k0k_0, in the bin k=k0 mod Pk = k_0 \bmod P.
  3. With w[p]=1w[p] = 1 for all pp and ϕ=k0/P\phi = k_0/P, D[k][r0]=0D[k][r_0] = 0 for every k≠k0 mod Pk \ne k_0 \bmod P, and D[k0 mod P][r0]=a Es PD[k_0 \bmod P][r_0] = a\, E_s\, P.
  4. ϕ\phi and ϕ+1\phi + 1 give the same input, so they give the same map.

Proof. z[p][r]=a ej2πϕp∑ls[l]‾ s[l+r−r0]z[p][r] = a\, e^{j 2\pi \phi p} \sum_l \overline{s[l]}\, s[l + r - r_0]. By the Cauchy-Schwarz inequality, the sum has magnitude at most EsEs=Es\sqrt{E_s}\sqrt{E_s} = E_s, with the value EsE_s at r=r0r = r_0. So ∣z[p][r]∣≤∣a∣Es|z[p][r]| \le |a| E_s and the triangle inequality gives part 1. Part 2 is the case r=r0r = r_0. At ϕ=k0/P\phi = k_0/P and w≥0w \ge 0,

D[k][r0]=a Es∑pw[p] ej2π(k0−k)p/P,D[k][r_0] = a\, E_s \sum_p w[p]\, e^{j 2\pi (k_0 - k) p/P},

and for k≡k0(modP)k \equiv k_0 \pmod P every exponential is 1, so ∣D∣=∣a∣Es∑pw[p]|D| = |a| E_s \sum_p w[p]. For part 3, with w=1w = 1 and k≢k0k \not\equiv k_0, the sum is a geometric series with ratio q=ej2π(k0−k)/P≠1q = e^{j 2\pi (k_0 - k)/P} \ne 1 and qP=1q^P = 1, so it is (1−qP)/(1−q)=0(1 - q^P)/(1 - q) = 0. For part 4, ej2π(ϕ+1)p=ej2πϕpe^{j 2\pi (\phi + 1) p} = e^{j 2\pi \phi p} for every integer pp. □\square

Theorem 3 (the noise gain). Let X[p][n]X[p][n] be independent CN(0,N0)\mathcal{CN}(0, N_0) samples. Then E ∣D[k][r]∣2=N0 Es∑p∣w[p]∣2E\, |D[k][r]|^2 = N_0\, E_s \sum_p |w[p]|^2 for every kk and rr.

Proof. z[p][r]z[p][r] is a linear combination of independent zero-mean samples with coefficients s[l]‾\overline{s[l]}, so E∣z[p][r]∣2=N0∑l∣s[l]∣2=N0EsE|z[p][r]|^2 = N_0 \sum_l |s[l]|^2 = N_0 E_s. Different pulses use different samples, so z[0][r],…,z[P−1][r]z[0][r], \dots, z[P-1][r] are independent with zero mean. D[k][r]D[k][r] is their combination with coefficients w[p]e−j2πkp/Pw[p] e^{-j 2\pi k p/P}, of magnitude ∣w[p]∣|w[p]|, which gives the variance N0Es∑p∣w[p]∣2N_0 E_s \sum_p |w[p]|^2. □\square

With w=1w = 1, a unit-modulus pulse (Es=LE_s = L) and an on-bin target, Theorems 2 and 3 give the peak signal to noise ratio ∣a∣2L2P2/(N0LP)=LP ∣a∣2/N0|a|^2 L^2 P^2 / (N_0 L P) = L P\, |a|^2 / N_0: the input ratio per sample times LPL P. ■\blacksquare

Complexity

Time. Lines L1 to L3 do LL multiplications for each of the P(N−L+1)P (N - L + 1) outputs, which is Θ(PNL)\Theta(P N L) for L≤N/2L \le N/2. The FFT of line L6 costs Θ(Plog⁡P)\Theta(P \log P), and it runs N−L+1N - L + 1 times, which is Θ(NPlog⁡P)\Theta(N P \log P). The total is Θ(PNL+NPlog⁡P)\Theta(P N L + N P \log P) in every case. With fast convolution, the matched filter costs O(PNlog⁡N)O(P N \log N) instead. A direct DFT in place of line L6 would cost Θ(NP2)\Theta(N P^2); the tests use that form as the reference.

Space. Θ(PN)\Theta(P N) for the compressed data zz, beyond the input and the map.

Properties

  • The peak and the gain (theorem). A target on a Doppler bin gives ∣D∣=∣a∣Es∑pw[p]|D| = |a| E_s \sum_p w[p] at its delay. With a unit-modulus pulse and a rectangular window, the signal to noise ratio at the peak is LPL P times the ratio of one input sample.
  • Doppler resolution and ambiguity. The bins are PRF/P\mathrm{PRF}/P apart, and the Doppler is known only modulo the PRF: fdf_d and fd+PRFf_d + \mathrm{PRF} give the same map. The range is known only modulo c/(2 PRF)c/(2\,\mathrm{PRF}). A low PRF gives a long unambiguous range and a small unambiguous speed, and a high PRF gives the reverse.
  • Straddle loss. A target between two bins loses gain. Half way between, the rectangular window loses 20log⁡10(π/2)=3.9220 \log_{10}(\pi/2) = 3.92 dB.
  • Windows trade resolution for sidelobes. A Hamming window lowers the Doppler sidelobes to about −43-43 dB from −13-13 dB, at the cost of a wider peak and a loss in signal to noise ratio by the factor (∑w)2/(P∑w2)(\sum w)^2 / (P \sum w^2), 1.44 dB for a Hamming window of 32 pulses. In the tests, with P=32P = 32 and a target half way between bins 5 and 6, the Hamming map is more than 40 dB down at 8 or more bins from the target, and the rectangular map is not. See spectral leakage.
  • Linear. The map of a sum of targets is the sum of their maps, so weak targets can hide in the sidelobes of strong ones.

Variants and improvements

  • Zero padding. Pad each column to a length larger than PP before the FFT. This samples the spectrum more finely and lowers the straddle loss, but it does not improve the resolution.
  • MTI first. Apply a two- or three-pulse MTI canceller along slow time before the FFT, to lower the zero Doppler clutter before it can leak into other bins through the sidelobes.
  • Multiple PRFs. Process several dwells at different PRFs and solve for the true range and Doppler with the Chinese remainder theorem or a search.
  • FMCW radar. In an FMCW radar the range FFT of the beat signal of each chirp replaces lines L1 to L3, and the Doppler FFT across chirps is the same as line L6.
  • Range migration. If the target moves more than one range bin during the dwell, its energy spreads over several columns. Keystone processing or a search over speed corrects this.
  • Adaptive processing. With several antennas, space-time adaptive processing replaces the fixed window and FFT with adaptive weights over angle and Doppler.

When to use it

Use range-Doppler processing when a radar has a coherent train of many pulses on the same target, for example 16 to 256 pulses, and needs both the range and the radial speed: airborne and ground surveillance, weather radar, automotive radar and the tracking modes of military radars. With only two or three pulses per dwell, use MTI. For an image of a fixed scene from a moving platform, use SAR processing instead.

Pitfalls

  • No conjugate in line L3. The matched filter correlates with s‾\overline{s}. For a real code such as Barker the conjugate does nothing, so a test with Barker codes alone will not find this bug. For a complex pulse, such as an LFM chirp or a Frank code, a missing conjugate gives a smeared peak at the wrong place.
  • The FFT along the wrong axis in line L6. The Doppler FFT is down each column (over pp at a fixed rr). An FFT along each row (over range) gives a meaningless spectrum.
  • Reading the bins as positive speeds. Bins k≥P/2k \ge P/2 are negative Doppler frequencies, targets moving away. Shift the map by P/2P/2 for display, and do not compute the speed as k PRF/Pk\,\mathrm{PRF}/P for every kk.
  • No window in line L5. With w=1w = 1, the first Doppler sidelobe is only 13 dB down. Strong clutter at zero Doppler then leaks into every bin and masks weak moving targets.
  • Range bins near the end of the row. Line L2 stops at N−LN - L. Lags beyond that would read past the end of the row, or, with circular convolution by FFT, wrap the end of the row onto its start.
  • A noise floor that changes with the window. The noise in the map is N0Es∑p∣w[p]∣2N_0 E_s \sum_p |w[p]|^2, not N0EsPN_0 E_s P. A CFAR threshold set for one window is wrong for another unless it is set from the data.

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)
range_doppler_processing.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/range-doppler-processing/. The authors are listed in prov/YRN86W.jsonl.

"""Range-Doppler processing of a coherent pulse train.

X[p][n] is the complex baseband sample n (fast time, n = 0 .. N-1) of pulse p
(slow time, p = 0 .. P-1). The transmitted pulse is s[0..L-1], L <= N.

1. Fast time: the matched filter of each pulse, written as a correlation,
   z[p][r] = sum over l of conj(s[l]) X[p][r + l], r = 0 .. N - L.
   An echo that starts at sample r0 peaks at r = r0.
2. Slow time: in each range bin, a window w[p] and a DFT over the P pulses,
   D[k][r] = sum over p of w[p] z[p][r] e^(-j 2 pi k p / P), by a radix-2 FFT.

A target with Doppler frequency f_d at the pulse repetition frequency PRF
falls in Doppler bin round(f_d P / PRF) mod P. The DFT has no 1/P factor.
"""

import cmath
import math
from typing import Sequence


def fft(x: Sequence[complex]) -> list[complex]:
    """X[k] = sum_n x[n] e^(-j 2 pi k n / P), iterative radix-2, P a power of two.

    Cost: Theta(P log P) complex operations, Theta(P) space.
    """
    n = len(x)
    if n == 0 or n & (n - 1):
        raise ValueError("the length must be a power of two")
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):  # bit reversal permutation
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        step = cmath.exp(-2j * math.pi / size)
        half = size // 2
        tw = [step ** t for t in range(half)]
        for start in range(0, n, size):
            for t in range(half):
                u = a[start + t]
                v = a[start + t + half] * tw[t]
                a[start + t] = u + v
                a[start + t + half] = u - v
        size *= 2
    return a


def hamming(p_count: int) -> list[float]:
    """The Hamming window 0.54 - 0.46 cos(2 pi p / (P - 1)), p = 0 .. P-1."""
    if p_count == 1:
        return [1.0]
    return [0.54 - 0.46 * math.cos(2 * math.pi * p / (p_count - 1)) for p in range(p_count)]


def range_doppler(x: Sequence[Sequence[complex]], s: Sequence[complex],
                  w: Sequence[float] | None = None) -> list[list[complex]]:
    """The range-Doppler map D[k][r], k = 0 .. P-1 (Doppler bin), r = 0 .. N-L (range bin).

    x holds P pulses of N samples each, P a power of two; s is the pulse of
    length L <= N; w is the slow-time window (default: all ones).
    Cost: Theta(P (N - L + 1) L) for the matched filters plus
    Theta((N - L + 1) P log P) for the FFTs; Theta(P N) space.
    """
    p_count = len(x)
    if p_count == 0:
        return []
    n = len(x[0])
    length = len(s)
    if not 1 <= length <= n or any(len(row) != n for row in x):
        raise ValueError("need 1 <= L <= N and pulses of equal length")
    if w is None:
        w = [1.0] * p_count
    sc = [complex(v).conjugate() for v in s]
    bins = n - length + 1
    z = [[0j] * bins for _ in range(p_count)]
    for p in range(p_count):  # @line L1
        row = x[p]
        for r in range(bins):  # @line L2
            z[p][r] = sum(sc[l] * row[r + l] for l in range(length))  # @line L3
    d =[[0j] * bins for _ in range(p_count)]
    for r in range(bins):  # @line L4
        u = [w[p] * z[p][r] for p in range(p_count)]  # @line L5
        col = fft(u)  # @line L6
        for k in range(p_count):
            d[k][r] = col[k]
    return d  # @line L7


def range_doppler_direct(x, s, w=None) -> list[list[complex]]:
    """The same map by the double sum over pulses and pulse samples, without an FFT."""
    p_count, n, length = len(x), len(x[0]), len(s)
    if w is None:
        w = [1.0] * p_count
    bins = n - length + 1
    out = [[0j] * bins for _ in range(p_count)]
    for k in range(p_count):
        for r in range(bins):
            acc = 0j
            for p in range(p_count):
                ph = cmath.exp(-2j * math.pi * k * p / p_count)
                for l in range(length):
                    acc += w[p] * complex(s[l]).conjugate() * x[p][r + l] * ph
            out[k][r] = acc
    return out


def point_target(p_count: int, n: int, s: Sequence[complex], delay: int, fd_over_prf: float,
                 amplitude: complex = 1.0) -> list[list[complex]]:
    """The echo a s[n - delay] e^(j 2 pi f_d p / PRF) of one point target, with no noise."""
    out = []
    for p in range(p_count):
        ph = amplitude * cmath.exp(2j * math.pi * fd_over_prf * p)
        out.append([ph * s[i - delay] if 0 <= i - delay < len(s) else 0j for i in range(n)])
    return out


def doppler_bin(fd: float, prf: float, p_count: int) -> int:
    """The Doppler bin round(f_d P / PRF) mod P of a target with Doppler frequency f_d."""
    return round(fd * p_count / prf) % p_count


def radial_velocity(fd: float, wavelength: float) -> float:
    """v = f_d lambda / 2, positive for an approaching target."""
    return fd * wavelength / 2.0
test_range_doppler_processing.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/range-doppler-processing/. The authors are listed in prov/YRN86W.jsonl.

import math
import random

import pytest

from cbb import cn, dft
from range_doppler_processing import (
    doppler_bin,
    fft,
    hamming,
    point_target,
    radial_velocity,
    range_doppler,
    range_doppler_direct,
)

C = 299792458.0
BARKER13 = [1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1]


def close(a, b, tol=1e-9):
    return all(abs(u - v) <= tol * (1 + abs(v)) for ra, rb in zip(a, b) for u, v in zip(ra, rb))


def test_fft_matches_direct_dft():
    rng = random.Random(7101)
    for _ in range(300):
        n = 2 ** rng.randint(0, 8)
        x = [cn(rng, 1.0) for _ in range(n)]
        got, want = fft(x), dft(x)
        assert all(abs(a - b) < 1e-9 * n for a, b in zip(got, want))


def test_fft_rejects_other_lengths():
    for n in (0, 3, 6, 12):
        with pytest.raises(ValueError):
            fft([1.0] * n)


def test_worked_example():
    # Pulse s = [1, 1], P = 4 pulses of N = 5 samples, a target at delay 1 with f_d = PRF / 4.
    x = point_target(4, 5, [1, 1], 1, 0.25)
    d = range_doppler(x, [1, 1])
    want = [[0, 0, 0, 0], [4, 8, 4, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
    assert close(d, want, 1e-12)


def test_map_matches_double_sum():
    rng = random.Random(7102)
    for _ in range(500):
        p_count = 2 ** rng.randint(0, 3)
        n = rng.randint(1, 9)
        length = rng.randint(1, min(n, 4))
        x = [[cn(rng, 1.0) for _ in range(n)] for _ in range(p_count)]
        s = [cn(rng, 1.0) for _ in range(length)]
        w = [rng.uniform(0.1, 1.0) for _ in range(p_count)] if rng.random() < 0.5 else None
        assert close(range_doppler(x, s, w), range_doppler_direct(x, s, w))


def test_point_target_peak_and_bins():
    p_count, n, delay = 16, 24, 5
    for k in (0, 3, 7, 12):
        a = 0.5 - 2j
        d = range_doppler(point_target(p_count, n, BARKER13, delay, k / p_count, a), BARKER13)
        mags = [[abs(v) for v in row] for row in d]
        best = max((mags[q][r], q, r) for q in range(p_count) for r in range(len(d[0])))
        assert (best[1], best[2]) == (k, delay)
        assert best[0] == pytest.approx(abs(a) * 13 * p_count)
        # An on-bin target leaves the other Doppler bins of its range bin empty.
        assert all(mags[q][delay] < 1e-9 for q in range(p_count) if q != k)


def test_negative_doppler_and_aliasing():
    p_count, n, delay = 16, 20, 3
    base = range_doppler(point_target(p_count, n, BARKER13, delay, 3 / p_count), BARKER13)
    neg = range_doppler(point_target(p_count, n, BARKER13, delay, -3 / p_count), BARKER13)
    assert abs(neg[p_count - 3][delay]) == pytest.approx(13 * p_count)
    alias = range_doppler(point_target(p_count, n, BARKER13, delay, 3 / p_count + 1), BARKER13)
    assert close(alias, base, 1e-9)


def test_hamming_window_gain_and_sidelobes():
    p_count, n, delay = 32, 16, 1
    w = hamming(p_count)
    x = point_target(p_count, n, BARKER13, delay, 5.5 / p_count)
    rect = [abs(row[delay]) for row in range_doppler(x, BARKER13)]
    ham = [abs(row[delay]) for row in range_doppler(x, BARKER13, w)]
    on = range_doppler(point_target(p_count, n, BARKER13, delay, 5 / p_count), BARKER13, w)
    assert abs(on[5][delay]) == pytest.approx(13 * sum(w))
    # Far from the target (8 or more bins away), the Hamming window keeps the leak
    # below -40 dB of the peak; the rectangular window does not.
    far = [q for q in range(p_count) if min((q - 5.5) % p_count, (5.5 - q) % p_count) >= 8]
    assert max(ham[q] for q in far) / max(ham) < 10 ** (-40 / 20)
    assert max(rect[q] for q in far) / max(rect) > 10 ** (-40 / 20)


def test_noise_gain_is_n0_times_pulse_energy_times_p():
    # Noise only, N0 = 2, P = 8, Barker 13: E |D|^2 = N0 * 13 * 8 = 208. 150 maps, seed 7103.
    rng = random.Random(7103)
    p_count, n, n0 = 8, 20, 2.0
    acc, count = 0.0, 0
    for _ in range(150):
        x = [[cn(rng, n0) for _ in range(n)] for _ in range(p_count)]
        for row in range_doppler(x, BARKER13):
            acc += sum(abs(v) ** 2 for v in row)
            count += len(row)
    assert acc / count == pytest.approx(n0 * 13 * p_count, rel=0.06)


def test_check_values():
    wavelength, prf, p_count = C / 10e9, 10e3, 16
    assert prf / p_count == 625.0
    assert radial_velocity(prf / p_count, wavelength) == pytest.approx(9.37, abs=0.01)
    assert radial_velocity(prf / 2, wavelength) == pytest.approx(74.95, abs=0.01)
    assert C / (2 * prf) == pytest.approx(14990, abs=1)
    assert doppler_bin(1875.0, prf, p_count) == 3
    assert doppler_bin(-1875.0, prf, p_count) == 13
    assert radial_velocity(1875.0, wavelength) == pytest.approx(28.11, abs=0.01)
    assert 10 * math.log10(13 * 16) == pytest.approx(23.18, abs=0.01)


def test_bad_input():
    assert range_doppler([], [1]) == []
    with pytest.raises(ValueError):
        range_doppler([[1, 2]], [1, 1, 1])
    with pytest.raises(ValueError):
        range_doppler([[1, 2], [1]], [1])

History

Radars that measure range and Doppler together with a coherent pulse train came into use in airborne radars, to see targets against ground clutter. The Doppler filters were first analog filter banks, and the FFT, published by Cooley and Tukey in 1965, later made digital Doppler filter banks practical. Skolnik and Richards describe this processing in their textbooks.

References

  1. Mark A. Richards, Fundamentals of Radar Signal Processing, McGraw-Hill, 2005, Chapter 5, Section 5.3 (the DFT of the slow-time data, windows, straddle loss and Doppler ambiguity)
  2. Merrill I. Skolnik, Introduction to Radar Systems, third edition, McGraw-Hill, 2001, Chapter 3, MTI and Pulse Doppler Radar (pulse Doppler radar, range and Doppler ambiguities)

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • 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
  • History with a source
  • at least three sources
  • a scene preset for the example