Algorithm Search⌘K

Algorithmcore

Moving target indication

Also called MTI, MTI canceller.

Subtracts the returns of consecutive pulses at each range with the binomial filter (1 - 1/z)^(L-1), which removes stationary clutter and leaves blind speeds at multiples of lambda PRF / 2.

Time
Θ(L P M) worst · average · best
Space
Θ(L) extra
Where
L = the number of pulses in the canceller; M = the number of range bins; P = the number of pulses
Properties
deterministicexact for integer inputlinearonlineremoves zero doppler

Moving target indication (MTI) removes the echo of stationary clutter, such as ground, buildings and sea, from the returns of a pulsed radar. At each range bin it takes the samples of LL consecutive pulses and forms the weighted difference with the binomial weights of (1−z−1)L−1(1 - z^{-1})^{L-1}: x[p]−x[p−1]x[p] - x[p-1] for the two-pulse canceller and x[p]−2x[p−1]+x[p−2]x[p] - 2x[p-1] + x[p-2] for the three-pulse canceller. Clutter that does not move gives the same sample from pulse to pulse and is removed exactly. A target with a Doppler shift fdf_d changes phase from pulse to pulse and passes with the gain (2∣sin⁡(πfd/PRF)∣)L−1(2|\sin(\pi f_d / \mathrm{PRF})|)^{L-1}. Targets at the blind speeds nλ PRF/2n \lambda\, \mathrm{PRF}/2 are removed too. MTI does not measure the speed; range-Doppler processing does that with a DFT over the pulses.

In plain words

A radar sends the same pulse again and again. A building gives the same echo every time. A car moves a little between pulses, so its echo comes back with a different phase each time. If you subtract the echo of the previous pulse from the echo of this pulse, the building cancels and the car does not. Subtracting twice (the difference of differences) removes clutter whose echo changes slowly, as well, and gives a deeper notch at zero speed. The cost is one subtraction per pulse and range bin per stage. If the car moves exactly a half wavelength, or a multiple of it, between pulses, its echo has the same phase each time and it cancels too: that speed is blind.

The problem

The input is a P×MP \times M array x[p][r]x[p][r] of complex baseband samples, pulse p=0,…,P−1p = 0, \dots, P-1 (slow time) and range bin r=0,…,M−1r = 0, \dots, M-1 (fast time), and the canceller length L≥1L \ge 1. The output is the (P−L+1)×M(P - L + 1) \times M array

y[p][r]=∑i=0L−1w[i] x[p−i][r],w[i]=(−1)i(L−1i),y[p][r] = \sum_{i=0}^{L-1} w[i]\, x[p - i][r], \qquad w[i] = (-1)^i \binom{L-1}{i},

for p=L−1,…,P−1p = L - 1, \dots, P - 1. The weights are (1,−1)(1, -1) for L=2L = 2, (1,−2,1)(1, -2, 1) for L=3L = 3 and (1,−3,3,−1)(1, -3, 3, -1) for L=4L = 4. The pulse repetition frequency is PRF and the wavelength is λ\lambda, and a target of radial speed vv has the Doppler shift fd=2v/λf_d = 2v/\lambda and the normalized Doppler f=fd/PRFf = f_d/\mathrm{PRF}.

The algorithm

  1. MTI-CANCEL(x[0..P-1][0..M-1], L)
  2. 1w[i] <- (-1)^i * C(L - 1, i) for i = 0, ..., L - 1 ▷ binomial weights
  3. 2for p <- L - 1 to P - 1
  4. 3for r <- 0 to M - 1
  5. 4y[p - L + 1][r] <- sum over i = 0, ..., L - 1 of w[i] * x[p - i][r]
  6. 5return y

Line L1 builds the weights from one row of Pascal's triangle with alternating signs. Lines L2 and L3 visit each output pulse and range bin. Line L4 is a short FIR filter along slow time: each range bin is filtered on its own, and the filter reads only the current pulse and the L−1L - 1 pulses before it. Line L2 starts at p=L−1p = L - 1, because the first L−1L - 1 pulses do not have enough earlier pulses. In a real radar the loop over pp runs as the pulses arrive, and L−1L - 1 earlier pulses are kept in memory.

Example

Take P=5P = 5 pulses and M=3M = 3 range bins. Bin 0 holds clutter of amplitude 5, bin 2 holds clutter of amplitude 3, and bin 1 holds clutter of amplitude 5 plus a target 2jp2 j^p, which has f=1/4f = 1/4 (the target turns a quarter cycle from pulse to pulse). So x[p]=(5,5+2jp,3)x[p] = (5, 5 + 2j^p, 3).

pp x[p][1]x[p][1] two-pulse yy three-pulse yy
0 77
1 5+2j5 + 2j −2+2j-2 + 2j
2 33 −2−2j-2 - 2j 3−2(5+2j)+7=−4j3 - 2(5 + 2j) + 7 = -4j
3 5−2j5 - 2j 2−2j2 - 2j 44
4 77 2+2j2 + 2j 4j4j

In bins 0 and 2 every output is 0: the clutter is removed exactly. In bin 1 the two-pulse output has magnitude 22=2⋅2sin⁡(π/4)2\sqrt{2} = 2 \cdot 2\sin(\pi/4) and the three-pulse output has magnitude 4=2⋅(2sin⁡(π/4))24 = 2 \cdot (2\sin(\pi/4))^2, as the response formula says. The clutter of amplitude 5 in bin 1 is gone in both.

Correctness

By the binomial theorem, ∑iw[i]z−i=(1−z−1)L−1\sum_i w[i] z^{-i} = (1 - z^{-1})^{L-1}, so line L4 applies the two-pulse difference L−1L - 1 times. For an input c ej2πfpc\, e^{j 2\pi f p} the output is the input times H(f)=(1−e−j2πf)L−1H(f) = (1 - e^{-j 2\pi f})^{L-1}, and ∣1−e−j2πf∣=2∣sin⁡(πf)∣|1 - e^{-j 2\pi f}| = 2|\sin(\pi f)|. So the gain is (2∣sin⁡(πf)∣)L−1(2|\sin(\pi f)|)^{L-1}, which is 0 exactly at integer ff: the blind speeds vn=nλ PRF/2v_n = n\lambda\,\mathrm{PRF}/2. A difference lowers the degree of a polynomial by one, so L−1L - 1 differences remove any clutter sequence that is a polynomial in pp of degree at most L−2L - 2. For wide-sense stationary clutter with normalized autocorrelation ρk\rho_k, the improvement factor (the gain in signal to clutter ratio averaged over the target Doppler) is ∑iw[i]2/∑i,mw[i]w[m]ρ∣i−m∣\sum_i w[i]^2 / \sum_{i,m} w[i] w[m] \rho_{|i-m|}. The correctness proof gives the full arguments.

Proof: The L-pulse MTI canceller is the filter (1 - z^-1)^(L-1) in slow time, with response (2 |sin(pi f)|)^(L-1), blind speeds n lambda PRF / 2 and the stated improvement factorfull

The notation is that of the page. X[p][r]X[p][r] is the complex sample of pulse p=0,…,P−1p = 0, \dots, P-1 at range bin r=0,…,M−1r = 0, \dots, M-1. The canceller has L≥1L \ge 1 pulses and the weights w[i]=(−1)i(L−1i)w[i] = (-1)^i \binom{L-1}{i}, i=0,…,L−1i = 0, \dots, L-1 (line L1). For p=L−1,…,P−1p = L-1, \dots, P-1 and every rr, lines L2 to L4 compute

y[p][r]=∑i=0L−1w[i] X[p−i][r].y[p][r] = \sum_{i=0}^{L-1} w[i]\, X[p-i][r].

The implementation stores this value in output row p−L+1p - L + 1. Write f=fd/PRFf = f_d / \mathrm{PRF} for the Doppler frequency normalized by the pulse repetition frequency.

Lemma 1 (the weights). ∑iw[i]z−i=(1−z−1)L−1\sum_{i} w[i] z^{-i} = (1 - z^{-1})^{L-1} for every complex z≠0z \ne 0.

Proof. This is the binomial theorem: (1−z−1)L−1=∑i=0L−1(L−1i)(−z−1)i(1 - z^{-1})^{L-1} = \sum_{i=0}^{L-1} \binom{L-1}{i} (-z^{-1})^i. □\square

So the canceller is the FIR filter with transfer function (1−z−1)L−1(1 - z^{-1})^{L-1}: the two-pulse canceller X[p]−X[p−1]X[p] - X[p-1] applied L−1L - 1 times in a row. Each output is the (L−1)(L-1)-th backward difference of the slow-time sequence of one range bin.

Theorem 1 (the output). The canceller returns exactly the values y[p][r]y[p][r] above, for all pp with L−1≤p≤P−1L - 1 \le p \le P - 1 and all rr, and no row when P<LP < L.

Proof. Line L2 runs over p=L−1,…,P−1p = L-1, \dots, P-1, line L3 over every rr, and line L4 forms the sum of the definition, which reads only the rows p−L+1,…,pp - L + 1, \dots, p, all inside 0,…,P−10, \dots, P-1. When P<LP < L the range of line L2 is empty. □\square

Theorem 2 (the Doppler response). If X[p][r]=c ej2πfpX[p][r] = c\, e^{j 2\pi f p} for one range bin rr, then y[p][r]=c ej2πfpH(f)y[p][r] = c\, e^{j 2\pi f p} H(f) with

H(f)=∑iw[i]e−j2πfi=(1−e−j2πf)L−1,∣H(f)∣=(2 ∣sin⁡(πf)∣)L−1.H(f) = \sum_{i} w[i] e^{-j 2\pi f i} = \left(1 - e^{-j 2\pi f}\right)^{L-1}, \qquad |H(f)| = \left(2\, |\sin(\pi f)|\right)^{L-1}.

Proof. y[p][r]=∑iw[i] c ej2πf(p−i)=c ej2πfp∑iw[i]e−j2πfiy[p][r] = \sum_i w[i]\, c\, e^{j 2\pi f (p - i)} = c\, e^{j 2\pi f p} \sum_i w[i] e^{-j 2\pi f i}, and Lemma 1 with z=ej2πfz = e^{j 2\pi f} gives the product form. Next, 1−e−j2πf=e−jπf(ejπf−e−jπf)=2j e−jπfsin⁡(πf)1 - e^{-j 2\pi f} = e^{-j\pi f}(e^{j\pi f} - e^{-j\pi f}) = 2j\, e^{-j\pi f} \sin(\pi f), whose magnitude is 2∣sin⁡(πf)∣2|\sin(\pi f)|. □\square

Corollary 1 (blind speeds). For L≥2L \ge 2, H(f)=0H(f) = 0 exactly when ff is an integer. A target of radial speed vv has fd=2v/λf_d = 2v/\lambda, so the canceller output is zero for every pulse exactly at the blind speeds vn=nλ PRF/2v_n = n \lambda\, \mathrm{PRF} / 2, n=0,±1,±2,…n = 0, \pm 1, \pm 2, \dots. The largest gain, 2L−12^{L-1}, is at the half-integer values of ff.

Proof. sin⁡(πf)=0\sin(\pi f) = 0 exactly for integer ff, and f=2v/(λ PRF)=nf = 2v / (\lambda\, \mathrm{PRF}) = n gives v=nλ PRF/2v = n\lambda\, \mathrm{PRF}/2. ∣sin⁡(πf)∣=1|\sin(\pi f)| = 1 exactly at the half integers. □\square

Theorem 3 (polynomial clutter). If, for one range bin, X[p][r]=q(p)X[p][r] = q(p) for a polynomial qq of degree at most L−2L - 2, then y[p][r]=0y[p][r] = 0 for all pp.

Proof. Let Δ\Delta be the backward difference, (Δu)[p]=u[p]−u[p−1](\Delta u)[p] = u[p] - u[p-1]. If u[p]=q(p)u[p] = q(p) with qq of degree d≥1d \ge 1 and leading coefficient aa, then q(p)−q(p−1)q(p) - q(p-1) has degree d−1d - 1, because the terms apda p^d cancel and the next term is ad pd−1a d\, p^{d-1}. A constant gives 0. So L−1L - 1 differences of a polynomial of degree at most L−2L - 2 give 0, and by Lemma 1, y=ΔL−1Xy = \Delta^{L-1} X in each range bin. □\square

Stationary clutter of constant amplitude is the case of degree 0, which every canceller with L≥2L \ge 2 removes exactly.

Theorem 4 (the improvement factor). Let the clutter of one range bin be a wide-sense stationary sequence with power σc2\sigma_c^2 and normalized autocorrelation ρk=E[c[p] c[p−k]‾]/σc2\rho_k = E[c[p]\, \overline{c[p-k]}]/\sigma_c^2, real and with ρ0=1\rho_0 = 1. Let the target be ej2πfpe^{j 2\pi f p} with ff uniform on [0,1)[0, 1). With real weights, the ratio of the output signal to clutter ratio to the input signal to clutter ratio, averaged over the target Doppler, is

I=∑iw[i]2∑i∑mw[i] w[m] ρ∣i−m∣.I = \frac{\sum_i w[i]^2}{\sum_{i}\sum_{m} w[i]\, w[m]\, \rho_{|i-m|}}.

For L=2L = 2, I=1/(1−ρ1)I = 1/(1 - \rho_1). For L=3L = 3, I=6/(6−8ρ1+2ρ2)I = 6/(6 - 8\rho_1 + 2\rho_2).

Proof. The output clutter power is E∣∑iw[i]c[p−i]∣2=∑i∑mw[i]w[m]E[c[p−i]c[p−m]‾]=σc2∑i,mw[i]w[m]ρ∣i−m∣E|\sum_i w[i] c[p-i]|^2 = \sum_i \sum_m w[i] w[m] E[c[p-i]\overline{c[p-m]}] = \sigma_c^2 \sum_{i,m} w[i] w[m] \rho_{|i-m|}, because ρ−k=ρk‾=ρk\rho_{-k} = \overline{\rho_k} = \rho_k for a real ρ\rho. The input clutter power is σc2\sigma_c^2. By Theorem 2 the target power gain at Doppler ff is ∣H(f)∣2|H(f)|^2, and

∫01∣H(f)∣2 df=∑i∑mw[i]w[m]∫01e−j2πf(i−m) df=∑iw[i]2,\int_0^1 |H(f)|^2\, df = \sum_i \sum_m w[i] w[m] \int_0^1 e^{-j 2\pi f (i - m)}\, df = \sum_i w[i]^2,

because the integral is 1 for i=mi = m and 0 otherwise. The input target power is 1. Divide the two ratios to get II. For L=2L = 2 the weights are (1,−1)(1, -1), the numerator is 2 and the denominator is 2−2ρ12 - 2\rho_1. For L=3L = 3 the weights are (1,−2,1)(1, -2, 1), the numerator is 6 and the denominator is 6+2(−2ρ1−2ρ1+ρ2)=6−8ρ1+2ρ26 + 2(-2\rho_1 - 2\rho_1 + \rho_2) = 6 - 8\rho_1 + 2\rho_2. ■\blacksquare

Complexity

Time. Line L4 does LL multiplications and additions for each of the (P−L+1)M(P - L + 1) M outputs, so the time is Θ(LPM)\Theta(L P M) for L≤P/2L \le P/2, in every case. With the cascade form (L−1L - 1 passes of the two-pulse difference) only additions are needed. LL is 2 or 3 in practice, so the cost is a few operations per sample.

Space. Θ(L)\Theta(L) for the weights, beyond the input and the output. A real-time canceller stores L−1L - 1 earlier pulses, Θ(LM)\Theta(L M) samples.

Properties

  • Exact cancellation of fixed clutter (theorem). A constant at a range bin gives 0 for every L≥2L \ge 2, and a polynomial of degree at most L−2L - 2 gives 0. With integer input the output is exact.
  • The response (theorem). ∣H(f)∣=(2∣sin⁡(πf)∣)L−1|H(f)| = (2|\sin(\pi f)|)^{L-1}, with ∣H(f)∣2=4sin⁡2(πf)|H(f)|^2 = 4\sin^2(\pi f) for two pulses and 16sin⁡4(πf)16\sin^4(\pi f) for three. The largest gain, 2L−12^{L-1}, is at f=1/2f = 1/2.
  • Blind speeds (theorem). vn=nλ PRF/2v_n = n\lambda\,\mathrm{PRF}/2. At 3 GHz (λ=0.0999\lambda = 0.0999 m) with a PRF of 1 kHz, the first blind speed is 49.97 m/s.
  • The improvement factor (closed form). I=1/(1−ρ1)I = 1/(1 - \rho_1) for two pulses and I=6/(6−8ρ1+2ρ2)I = 6/(6 - 8\rho_1 + 2\rho_2) for three. For a Gaussian clutter spectrum, ρk=e−2π2σc2k2/PRF2\rho_k = e^{-2\pi^2 \sigma_c^2 k^2/\mathrm{PRF}^2}. With σc=10\sigma_c = 10 Hz and a PRF of 1 kHz, II is 27.05 dB for two pulses and 51.10 dB for three; with σc=20\sigma_c = 20 Hz, 21.04 dB and 39.10 dB. A wider clutter spectrum, from wind or from the motion of the radar, lowers II quickly. For AR(1) clutter with ρk=0.9k\rho_k = 0.9^k, II is 10 and 14.29, and the tests measure these values by simulation within 6 percent.
  • Linear and time-invariant along slow time. MTI commutes with pulse compression, so the two can run in either order.

Variants and improvements

  • Staggered PRF. Change the interval between pulses in a fixed pattern. The blind speeds of the different intervals do not coincide, so the first common blind speed moves far above the target speeds. The filter weights then change from pulse to pulse.
  • Recursive cancellers. An IIR filter with feedback gives a sharper notch and a flatter passband than the binomial FIR, at the cost of a long transient.
  • Clutter-matched weights. Choose ww to maximize the improvement factor for a known ρk\rho_k. With the target Doppler averaged as above, it is an eigenvector problem: the best ww is the eigenvector of the clutter correlation matrix with the smallest eigenvalue.
  • Moving target detection (MTD). Follow a short canceller with a bank of Doppler filters (a short DFT over the pulses) and a CFAR in each filter. This is between MTI and full range-Doppler processing.
  • Airborne MTI. For a moving radar, the clutter Doppler depends on the angle. A fixed notch at zero Doppler no longer fits, and space-time adaptive processing filters jointly in angle and Doppler.

When to use it

Use MTI in a ground-based radar that must see moving targets against strong fixed clutter, when only a few pulses fall on each target, or when the hardware must be simple. Use range-Doppler processing when you have many pulses per dwell and want the speed of the target as well, and STAP when the radar moves. MTI is usually followed by a CFAR detector on the canceller output.

Pitfalls

  • Weights that are not binomial in line L1. The weights (1,−1,1)(1, -1, 1) look like a three-pulse canceller but sum to 1, so they pass fixed clutter with gain 1. The weights must sum to 0 to null zero Doppler, and the binomial weights also null the first L−2L - 2 derivatives.
  • Starting the loop of line L2 at p=0p = 0. Then line L4 reads x[−1]x[-1], x[−2]x[-2], and so on. In C this reads outside the array. In Python a negative index silently reads the last pulses, and the first outputs mix the start and the end of the dwell. The first L−1L - 1 outputs are not valid and must not reach the detector.
  • Filtering across range in line L4. The difference is along the pulse index pp at a fixed range bin rr. Subtracting adjacent range bins of one pulse is a high-pass filter in range, and it does not remove clutter.
  • Blind speeds. A target at a blind speed disappears. With one PRF, a 3 GHz radar at 1 kHz is blind at 49.97 m/s, 99.93 m/s and so on, which are common aircraft speeds. Use staggered or multiple PRFs.
  • Amplitude and phase instability. The cancellation is exact only if the transmitter phase, the timing and the receiver gain are the same for every pulse. A phase jitter of ϵ\epsilon radians leaves a residue of about ϵ2\epsilon^2 of the clutter power, which limits II in practice to the stability of the radar.
  • Clutter spectral width. The improvement factor falls fast as the clutter spreads in Doppler. Going from σc=10\sigma_c = 10 Hz to 20 Hz costs 6 dB for two pulses and 12 dB for three.

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)
moving_target_indication.py 83 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moving-target-indication/. The authors are listed in prov/YMQQ6D.jsonl.

"""The L-pulse MTI canceller, a binomial FIR filter in slow time.

X[p][r] is the complex sample of pulse p (slow time, p = 0 .. P-1) at range
bin r (fast time, r = 0 .. M-1). The canceller with L pulses has the weights
w[i] = (-1)^i C(L-1, i), the coefficients of (1 - z^-1)^(L-1), and gives

    y[q][r] = sum over i = 0 .. L-1 of w[i] X[q + L - 1 - i][r],   q = 0 .. P - L.

The two-pulse canceller (L = 2) is X[p] - X[p-1]. Its response to a Doppler
frequency f_d at the pulse repetition frequency PRF has magnitude
(2 |sin(pi f_d / PRF)|)^(L-1). It is zero at f_d = n PRF, so the blind speeds
are v_n = n lambda PRF / 2.

With int input the output is exact.
"""

import cmath
import math
from typing import Sequence


def canceller_weights(n_pulses: int) -> list[int]:
    """w[i] = (-1)^i C(L-1, i) for i = 0 .. L-1. L = 2 gives [1, -1], L = 3 gives [1, -2, 1]."""
    if n_pulses < 1:
        raise ValueError("need L >= 1")
    return [(-1) ** i * math.comb(n_pulses - 1, i) for i in range(n_pulses)]


def mti_cancel(x: Sequence[Sequence], n_pulses: int) -> list[list]:
    """Apply the L-pulse canceller along slow time, in every range bin.

    x is a list of P pulses, each a list of M samples. The output has P - L + 1
    rows (none if P < L). Cost: Theta(L P M) operations, O(L) extra space.
    """
    w = canceller_weights(n_pulses)  # @line L1
    n_rows = len(x)
    m = len(x[0]) if x else 0
    if any(len(row) != m for row in x):
        raise ValueError("every pulse needs the same number of range bins")
    y = []
    for p in range(n_pulses - 1, n_rows):  # @line L2
        out = []
        for r in range(m):  # @line L3
            out.append(sum(w[i] * x[p - i][r] for i in range(n_pulses)))  # @line L4
        y.append(out)
    return y  # @line L5


def response(n_pulses: int, f_norm: float) -> complex:
    """H(f) = sum_i w[i] e^(-j 2 pi f i), with f = f_d / PRF, by the direct sum."""
    w = canceller_weights(n_pulses)
    return sum(c * cmath.exp(-2j * math.pi * f_norm * i) for i, c in enumerate(w))


def response_magnitude(n_pulses: int, f_norm: float) -> float:
    """The closed form |H(f)| = (2 |sin(pi f)|)^(L-1)."""
    return (2.0 * abs(math.sin(math.pi * f_norm))) ** (n_pulses - 1)


def blind_speeds(wavelength: float, prf: float, count: int) -> list[float]:
    """The first count blind speeds v_n = n lambda PRF / 2, n = 1 .. count, in m/s."""
    return [n * wavelength * prf / 2.0 for n in range(1, count + 1)]


def improvement_factor(n_pulses: int, rho: Sequence[float]) -> float:
    """I = (sum of w^2) / (sum over i, k of w[i] w[k] rho[|i - k|]).

    rho[0] = 1, rho[1], ... is the normalized autocorrelation of the clutter
    from pulse to pulse. The numerator is the average gain for a target whose
    Doppler is uniform over one PRF interval.
    """
    w = canceller_weights(n_pulses)
    num = sum(c * c for c in w)
    den = sum(w[i] * w[k] * rho[abs(i - k)] for i in range(n_pulses) for k in range(n_pulses))
    return num / den


def gaussian_clutter_rho(sigma_f: float, prf: float, lags: int) -> list[float]:
    """rho_k = exp(-2 pi^2 sigma_f^2 k^2 / PRF^2) for a Gaussian clutter spectrum of std sigma_f in Hz."""
    return [math.exp(-2.0 * math.pi ** 2 * sigma_f ** 2 * k * k / prf ** 2) for k in range(lags)]
test_moving_target_indication.py 128 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moving-target-indication/. The authors are listed in prov/YMQQ6D.jsonl.

import cmath
import math
import random

import pytest

from cbb import cn, conv
from moving_target_indication import (
    blind_speeds,
    canceller_weights,
    gaussian_clutter_rho,
    improvement_factor,
    mti_cancel,
    response,
    response_magnitude,
)

C = 299792458.0


def test_weights():
    assert canceller_weights(1) == [1]
    assert canceller_weights(2) == [1, -1]
    assert canceller_weights(3) == [1, -2, 1]
    assert canceller_weights(4) == [1, -3, 3, -1]
    assert sum(canceller_weights(7)) == 0


def test_worked_example():
    # Range bin 0: clutter 5. Bin 1: clutter 5 plus a target 2 j^p (f_d = PRF / 4). Bin 2: clutter 3.
    x = [[5, 5 + 2 * (1j ** p), 3] for p in range(5)]
    y2 = mti_cancel(x, 2)
    assert [row[1] for row in y2] == [-2 + 2j, -2 - 2j, 2 - 2j, 2 + 2j]
    assert all(row[0] == 0 and row[2] == 0 for row in y2)
    y3 = mti_cancel(x, 3)
    assert [row[1] for row in y3] == [-4j, 4, 4j]
    assert all(abs(row[1]) == 4 for row in y3)


def test_short_input():
    assert mti_cancel([], 2) == []
    assert mti_cancel([[1, 2, 3]], 2) == []
    with pytest.raises(ValueError):
        mti_cancel([[1, 2], [3]], 2)


def test_polynomial_clutter_is_removed_exactly():
    """The L-pulse canceller removes every clutter sequence that is a polynomial of degree L - 2 in p."""
    rng = random.Random(6101)
    for _ in range(300):
        n_pulses = rng.randint(2, 5)
        p_count, m = rng.randint(n_pulses, 12), rng.randint(1, 4)
        coef = [[rng.randint(-50, 50) for _ in range(n_pulses - 1)] for _ in range(m)]
        x = [[sum(c * p ** d for d, c in enumerate(coef[r])) for r in range(m)] for p in range(p_count)]
        assert all(v == 0 for row in mti_cancel(x, n_pulses) for v in row)


def test_matches_convolution_in_slow_time():
    rng = random.Random(6102)
    for _ in range(500):
        n_pulses = rng.randint(1, 5)
        p_count, m = rng.randint(n_pulses, 10), rng.randint(1, 3)
        x = [[cn(rng, 1.0) for _ in range(m)] for _ in range(p_count)]
        y = mti_cancel(x, n_pulses)
        for r in range(m):
            ref = conv([row[r] for row in x], [complex(v) for v in canceller_weights(n_pulses)])
            got = [row[r] for row in y]
            want = ref[n_pulses - 1:p_count]
            assert len(got) == len(want)
            assert all(abs(a - b) < 1e-12 for a, b in zip(got, want))


def test_doppler_response_matches_closed_form():
    rng = random.Random(6103)
    for _ in range(300):
        n_pulses = rng.randint(2, 5)
        f = rng.uniform(-1.5, 1.5)
        x = [[cmath.exp(2j * math.pi * f * p)] for p in range(n_pulses + 6)]
        for row in mti_cancel(x, n_pulses):
            assert abs(abs(row[0]) - response_magnitude(n_pulses, f)) < 1e-12
        assert abs(abs(response(n_pulses, f)) - response_magnitude(n_pulses, f)) < 1e-12


def test_blind_speeds():
    wavelength, prf = C / 3e9, 1000.0
    v = blind_speeds(wavelength, prf, 3)
    assert v[0] == pytest.approx(49.965, abs=1e-3)
    for n_pulses in (2, 3, 4):
        for k, speed in enumerate(v, start=1):
            fd = 2.0 * speed / wavelength
            assert fd / prf == pytest.approx(k)
            x = [[cmath.exp(2j * math.pi * fd * p / prf)] for p in range(10)]
            assert all(abs(row[0]) < 1e-9 for row in mti_cancel(x, n_pulses))
        # Half way between blind speeds the gain is the largest, 2^(L-1).
        fd = 2.0 * (v[0] / 2) / wavelength
        x = [[cmath.exp(2j * math.pi * fd * p / prf)] for p in range(10)]
        assert all(abs(abs(row[0]) - 2 ** (n_pulses - 1)) < 1e-9 for row in mti_cancel(x, n_pulses))


def test_improvement_factor_closed_forms():
    for r1, r2 in ((0.9, 0.81), (0.99, 0.95), (0.5, 0.1)):
        assert improvement_factor(2, [1.0, r1]) == pytest.approx(1 / (1 - r1))
        assert improvement_factor(3, [1.0, r1, r2]) == pytest.approx(6 / (6 - 8 * r1 + 2 * r2))
    rho = gaussian_clutter_rho(10.0, 1000.0, 3)
    assert 10 * math.log10(improvement_factor(2, rho)) == pytest.approx(27.05, abs=0.01)
    assert 10 * math.log10(improvement_factor(3, rho)) == pytest.approx(51.10, abs=0.01)


def test_improvement_factor_by_simulation_ar1_clutter():
    # AR(1) clutter c[p] = a c[p-1] + sqrt(1 - a^2) w[p] with a = 0.9 has rho_k = a^k.
    # 30000 pulses, seed 6104; the measured power ratio must be within 6 percent.
    a, n = 0.9, 30000
    rng = random.Random(6104)
    c = [cn(rng, 1.0)]
    for _ in range(n - 1):
        c.append(a * c[-1] + math.sqrt(1 - a * a) * cn(rng, 1.0))
    x = [[v] for v in c]
    p_in = sum(abs(v) ** 2 for v in c) / n
    for n_pulses in (2, 3):
        w = canceller_weights(n_pulses)
        y = mti_cancel(x, n_pulses)
        p_out = sum(abs(row[0]) ** 2 for row in y) / len(y)
        measured = sum(v * v for v in w) * p_in / p_out
        want = improvement_factor(n_pulses, [a ** k for k in range(n_pulses)])
        assert measured == pytest.approx(want, rel=0.06)

History

Pulse cancellers are among the oldest radar signal processing methods. Early MTI radars used analog delay lines, for example mercury or quartz lines, to hold the echo of one pulse until the next one arrived, so that the two could be subtracted. Digital memories later replaced the delay lines and made higher order and staggered cancellers easy to build. Skolnik and Richards describe the canceller, its blind speeds and its improvement factor in their textbooks.

References

  1. Merrill I. Skolnik, Introduction to Radar Systems, third edition, McGraw-Hill, 2001, Chapter 3, MTI and Pulse Doppler Radar (the delay-line canceller, blind speeds, staggered PRFs and the improvement factor)
  2. Mark A. Richards, Fundamentals of Radar Signal Processing, McGraw-Hill, 2005, Chapter 5, Section 5.2 (pulse cancellers, their frequency response and blind speeds in 5.2.1, and the improvement factor in 5.2.4 and 5.2.5)

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