Algorithm Search⌘K

Algorithmadvanced

Space-time adaptive processing

Also called STAP.

Filters radar data jointly over M antennas and P pulses with the weight R^-1 v, R estimated from training cells, to detect slow targets in the clutter of a moving radar.

Time
Θ(T M^2 P^2 + M^3 P^3) worst · average · best
Space
Θ(M^2 P^2) extra
Where
M = the number of antenna elements; P = the number of pulses; T = the number of training snapshots
Properties
adaptiveconstant false alarm rate with known covariancedeterministiclinear filterneeds training data
Origin
L. E. Brennan, I. S. Reed, 1973

Space-time adaptive processing (STAP) detects targets with a radar that moves, usually on an aircraft, where the ground clutter has a Doppler shift that depends on its angle. It stacks the samples of MM antenna elements over PP pulses at one range into a snapshot of length D=MPD = MP, estimates the covariance RR of clutter, jamming and noise from TT nearby range cells, and applies the weight w=R−1vw = R^{-1} v for the space-time steering vector vv of the target. This weight gives the largest output signal to interference plus noise ratio (SINR) of all linear filters. It puts a null along the whole clutter ridge in angle and Doppler, which a fixed beamformer followed by a Doppler filter, or an MTI canceller, cannot do. In space only (P=1P = 1), the same weight is the Capon beamformer.

In plain words

On a moving aircraft, the ground straight ahead comes closer fast and the ground to the side does not, so the clutter has a different Doppler shift in each direction. A slow target can have the same Doppler shift as the ground in some other direction, and a Doppler filter alone cannot separate them. But the target and that patch of ground are in different directions. If you use several antennas and several pulses together, you can cancel the ground in every direction at its own Doppler and keep the target. The weights that do this depend on the clutter, so you measure the clutter in cells near the one you test, compute its covariance, and solve a linear system with it.

The problem

The input is TT training snapshots x1,…,xT∈CDx_1, \dots, x_T \in \mathbb{C}^D from range cells near the cell under test, assumed to hold the same interference and no target, the snapshot xx of the cell under test, the steering vector vv and a loading δ≥0\delta \ge 0. Entry pM+mpM + m of a snapshot is pulse pp at element mm. For a uniform linear array, a target at spatial frequency fsf_s and normalized Doppler ftf_t has v[pM+m]=ej2π(ftp+fsm)v[pM + m] = e^{j 2\pi (f_t p + f_s m)}, the Kronecker product of a temporal and a spatial steering vector. The output is the weight ww with (R^+δI)w=v(\hat{R} + \delta I) w = v, where R^=1T∑txtxtH\hat{R} = \frac{1}{T} \sum_t x_t x_t^H, the filter output y=wHxy = w^H x and the statistic Λ=∣y∣2/(vHw)\Lambda = |y|^2 / (v^H w), which is compared with a threshold.

The algorithm

  1. SMI-STAP(x_1..x_T, v, x, delta)
  2. 1R <- (1/T) * sum over t of x_t x_t^H ▷ the sample covariance, D x D
  3. 2R[i][i] <- R[i][i] + delta for i = 0, ..., D - 1 ▷ diagonal loading
  4. 3G <- CHOLESKY(R) ▷ R = G G^H, G lower triangular
  5. 4w <- solve G a = v forward, then G^H w = a backward
  6. 5y <- w^H x
  7. 6Lambda <- |y|^2 / Re(v^H w) ▷ the adaptive matched filter statistic
  8. 7return w, y, Lambda

Line L1 is the sample matrix of sample matrix inversion (SMI). Line L2 adds a small multiple of the identity, which keeps the matrix positive definite when T<DT < D and lowers the noise in the weight. Line L3 is the Cholesky decomposition, which exists because the matrix is Hermitian and positive definite. Line L4 solves for ww by two triangular substitutions; the inverse is never formed. Line L6 normalizes the output power by its value under interference only, so that a threshold on Λ\Lambda gives a known false alarm rate.

Example

A toy case with D=2D = 2 and T=2T = 2: the training snapshots are (3,3)(3, 3) and (1,−1)(1, -1), so

R^=12([9999]+[1−1−11])=[5445].\hat{R} = \tfrac{1}{2}\left( \begin{bmatrix} 9 & 9 \\ 9 & 9 \end{bmatrix} + \begin{bmatrix} 1 & -1 \\ -1 & 1 \end{bmatrix} \right) = \begin{bmatrix} 5 & 4 \\ 4 & 5 \end{bmatrix}.

The strong component along (1,1)(1, 1) plays the role of a jammer or of clutter. Take the target v=(1,j)v = (1, j) and δ=0\delta = 0.

step value
L3 G=[2.23601.7891.342]G = \begin{bmatrix} 2.236 & 0 \\ 1.789 & 1.342 \end{bmatrix}, that is 5\sqrt{5}, 4/54/\sqrt{5} and 3/53/\sqrt{5}
L4 w=R^−1v=((5−4j)/9, (−4+5j)/9)w = \hat{R}^{-1} v = \left( (5 - 4j)/9,\ (-4 + 5j)/9 \right)
vHw=10/9v^H w = 10/9, the optimum SINR vHR^−1vv^H \hat{R}^{-1} v
the gain on the jammer: ∣wH(1,1)∣2=2/81\lvert w^H (1, 1) \rvert^2 = 2/81
the SINR of the plain matched filter w=vw = v: ∣vHv∣2/(vHR^v)=4/10=0.4\lvert v^H v \rvert^2 / (v^H \hat{R} v) = 4/10 = 0.4

The adaptive weight gives an SINR of 10/910/9 against 0.40.4 for the matched filter, a gain of 4.4 dB, because it almost nulls the direction (1,1)(1, 1).

A larger case: an array of M=4M = 4 elements and P=4P = 4 pulses, the clutter on the ridge ft=fsf_t = f_s (that is β=1\beta = 1), 64 clutter patches and a clutter to noise ratio of 40 dB. For a target off the ridge at fs=0f_s = 0, ft=0.5f_t = 0.5, the optimum SINR is 0.833D0.833 D, close to the noise-only value DD. For a target on the ridge, at fs=ft=0.125f_s = f_t = 0.125, it is about 4×10−5D4 \times 10^{-5} D: a target with the speed and direction of the clutter cannot be seen. The non-adaptive weight vv gives about 0.0004D0.0004 D off the ridge, because the clutter enters through its sidelobes.

Correctness

The matrix of line L3 is Hermitian positive semidefinite, and it is positive definite if δ>0\delta > 0 or if the training snapshots span CD\mathbb{C}^D, which needs T≥DT \ge D. So the Cholesky factor exists, and the two substitutions of line L4 give the unique solution of (R^+δI)w=v(\hat{R} + \delta I) w = v. With the true covariance RR, the Cauchy-Schwarz inequality in the inner product aHRba^H R b gives ∣uHv∣2/(uHRu)≤vHR−1v|u^H v|^2 / (u^H R u) \le v^H R^{-1} v for every weight uu, with equality exactly for multiples of R−1vR^{-1} v, so this weight maximizes the SINR. With the true RR and Gaussian interference, Λ\Lambda is exponential with mean 1, so P(Λ>η)=e−ηP(\Lambda > \eta) = e^{-\eta} for every RR. For a clutter ridge ft=βfsf_t = \beta f_s with an integer 1≤β≤M1 \le \beta \le M, the clutter covariance has rank M+β(P−1)M + \beta(P - 1) (Brennan's rule). The correctness proof gives the arguments.

Proof: SMI space-time adaptive processing solves R w = v, the weight R^-1 v gives the largest output SINR, the AMF statistic has a constant false alarm rate when R is known, and Brennan's rule gives the clutter rank for an integer betafull

The notation is that of the page. An array of MM elements receives PP pulses, and a snapshot is a vector of length D=MPD = MP, indexed by pM+mpM + m for pulse pp and element mm. The steering vector of the target is v≠0v \ne 0. Line L1 forms R^=1T∑t=1TxtxtH\hat{R} = \frac{1}{T}\sum_{t=1}^{T} x_t x_t^H from TT training snapshots, line L2 adds δI\delta I with δ≥0\delta \ge 0, line L3 factors R^+δI=GGH\hat{R} + \delta I = G G^H with GG lower triangular, line L4 solves for ww, line L5 forms y=wHxy = w^H x for the cell under test, and line L6 forms Λ=∣y∣2/(vHw)\Lambda = |y|^2 / (v^H w).

Lemma 1 (the matrix of line L3 is positive definite). R^\hat{R} is Hermitian and positive semidefinite. R^+δI\hat{R} + \delta I is positive definite if δ>0\delta > 0, or if δ=0\delta = 0 and the training snapshots span CD\mathbb{C}^D, which needs T≥DT \ge D.

Proof. Each xtxtHx_t x_t^H is Hermitian, and uHxtxtHu=∣xtHu∣2≥0u^H x_t x_t^H u = |x_t^H u|^2 \ge 0. So uHR^u=1T∑t∣xtHu∣2≥0u^H \hat{R} u = \frac{1}{T} \sum_t |x_t^H u|^2 \ge 0. With δ>0\delta > 0, uH(R^+δI)u≥δ∥u∥2>0u^H(\hat{R} + \delta I)u \ge \delta \|u\|^2 > 0 for u≠0u \ne 0. With δ=0\delta = 0, the sum is zero only if uu is orthogonal to every xtx_t, which for spanning snapshots means u=0u = 0. TT vectors span at most TT dimensions. □\square

So the Cholesky factor GG of line L3 exists, with a positive real diagonal, and the implementation raises an error when the matrix is not positive definite.

Lemma 2 (line L4). The forward substitution ai=(vi−∑k<iGikak)/Giia_i = (v_i - \sum_{k<i} G_{ik} a_k)/G_{ii} and the back substitution wi=(ai−∑k>iGki‾ wk)/Gii‾w_i = (a_i - \sum_{k>i} \overline{G_{ki}}\, w_k)/\overline{G_{ii}} give the unique ww with (R^+δI)w=v(\hat{R} + \delta I) w = v.

Proof. Row ii of Ga=vGa = v is ∑k≤iGikak=vi\sum_{k \le i} G_{ik} a_k = v_i, and the forward step solves it for aia_i once a0,…,ai−1a_0, \dots, a_{i-1} are known; Gii≠0G_{ii} \ne 0. GHG^H is upper triangular with (GH)ik=Gki‾(G^H)_{ik} = \overline{G_{ki}}, and row ii of GHw=aG^H w = a is ∑k≥iGki‾ wk=ai\sum_{k \ge i} \overline{G_{ki}}\, w_k = a_i, solved in the order i=D−1,…,0i = D-1, \dots, 0. Then GGHw=Ga=vG G^H w = G a = v. GG is invertible, so the solution is unique. □\square

Theorem 1 (the optimum weight). Let RR be a Hermitian positive definite covariance of the interference plus noise, and define the output SINR of a weight u≠0u \ne 0 for a target vv of unit power as SINR(u)=∣uHv∣2/(uHRu)\mathrm{SINR}(u) = |u^H v|^2 / (u^H R u). Then

SINR(u)≤vHR−1v,\mathrm{SINR}(u) \le v^H R^{-1} v,

with equality if and only if uu is a nonzero multiple of R−1vR^{-1} v.

Proof. ⟨a,b⟩R=aHRb\langle a, b \rangle_R = a^H R b is an inner product. Put g=R−1vg = R^{-1} v, so uHv=uHRg=⟨u,g⟩Ru^H v = u^H R g = \langle u, g \rangle_R. The Cauchy-Schwarz inequality gives ∣uHv∣2≤(uHRu)(gHRg)=(uHRu)(vHR−1v)|u^H v|^2 \le (u^H R u)(g^H R g) = (u^H R u)(v^H R^{-1} v), with equality exactly when uu and gg are proportional. □\square

By Lemma 2, SMI returns the optimum weight for the matrix R^+δI\hat{R} + \delta I that it estimates. Its SINR in the true RR is SINR(w)\mathrm{SINR}(w), and the ratio ρ=SINR(w)/(vHR−1v)≤1\rho = \mathrm{SINR}(w) / (v^H R^{-1} v) \le 1 is the loss of the estimate. For δ=0\delta = 0, T≥DT \ge D and Gaussian training data with covariance RR, Reed, Mallett and Brennan (1974) showed that ρ\rho has a beta distribution with mean (T+2−D)/(T+1)(T + 2 - D)/(T + 1). We do not reprove that result here. The tests check the mean by simulation.

Theorem 2 (the AMF statistic with a known covariance). Let w=R−1vw = R^{-1} v for the true RR, and let the cell under test hold only interference, x∼CN(0,R)x \sim \mathcal{CN}(0, R). Then Λ=∣wHx∣2/(vHw)\Lambda = |w^H x|^2 / (v^H w) is exponential with mean 1, so P(Λ>η)=e−ηP(\Lambda > \eta) = e^{-\eta} for every RR.

Proof. y=wHxy = w^H x is a linear function of a circular Gaussian vector, so y∼CN(0,wHRw)y \sim \mathcal{CN}(0, w^H R w) and wHRw=vHR−1RR−1v=vHR−1v=vHww^H R w = v^H R^{-1} R R^{-1} v = v^H R^{-1} v = v^H w. So Λ=∣y∣2/E∣y∣2\Lambda = |y|^2 / E|y|^2, and the squared magnitude of a CN(0,1)\mathcal{CN}(0, 1) variable is exponential with mean 1. □\square

Λ\Lambda does not change when ww is multiplied by a nonzero constant, so the scale of the weight does not matter.

Theorem 3 (Brennan's rule for an integer beta). Let the clutter patches c=1,…,Qc = 1, \dots, Q have spatial frequencies fcf_c, distinct modulo 1, the Doppler βfc\beta f_c with an integer 1≤β≤M1 \le \beta \le M, and powers γc>0\gamma_c > 0. The steering vector of patch cc is vc[pM+m]=ej2πfc(βp+m)v_c[pM + m] = e^{j 2\pi f_c (\beta p + m)}. Then Rc=∑cγcvcvcHR_c = \sum_c \gamma_c v_c v_c^H has rank min⁡(Q,K)\min(Q, K) with K=M+β(P−1)K = M + \beta(P - 1).

Proof. The entry pM+mpM + m of vcv_c depends only on q=βp+mq = \beta p + m, which runs over 0,…,K−10, \dots, K - 1. Let ec[q]=ej2πfcqe_c[q] = e^{j 2\pi f_c q} for q=0,…,K−1q = 0, \dots, K-1, and let SS be the D×KD \times K matrix with S[pM+m][βp+m]=1S[pM + m][\beta p + m] = 1 and zeros elsewhere, so vc=Secv_c = S e_c. Each qq in 0,…,K−10, \dots, K-1 is βp+m\beta p + m for some valid pp and mm: if q≤β(P−1)q \le \beta(P-1), take p=⌊q/β⌋p = \lfloor q/\beta \rfloor and m=q−βp<β≤Mm = q - \beta p < \beta \le M; otherwise take p=P−1p = P - 1 and m=q−β(P−1)≤M−1m = q - \beta(P - 1) \le M - 1. So each column of SS has a 1, the columns have disjoint supports, and SS has rank KK. Then Rc=SVΓVHSHR_c = S V \Gamma V^H S^H, where VV is the K×QK \times Q matrix with columns ece_c and Γ=diag(γc)\Gamma = \mathrm{diag}(\gamma_c). VV is a Vandermonde matrix in the distinct nodes ej2πfce^{j 2\pi f_c}, so its rank is min⁡(Q,K)\min(Q, K). VΓVH=(VΓ1/2)(VΓ1/2)HV \Gamma V^H = (V\Gamma^{1/2})(V\Gamma^{1/2})^H has the rank of VV, and multiplying by SS on the left and SHS^H on the right keeps the rank, because SS has full column rank. □\square

For a non-integer β\beta the rank is close to M+β(P−1)M + \beta(P-1) in the sense that the other eigenvalues are small, which is the form of Brennan's rule used in practice. Theorem 3 covers only the exact case. ■\blacksquare

Complexity

Time. Line L1 adds TT outer products of size D×DD \times D: Θ(TD2)\Theta(T D^2). Line L3 costs Θ(D3)\Theta(D^3), and line L4 costs Θ(D2)\Theta(D^2). With D=MPD = MP the total is Θ(TM2P2+M3P3)\Theta(T M^2 P^2 + M^3 P^3) in every case, and with the usual T≈2DT \approx 2D, it is Θ(M3P3)\Theta(M^3 P^3). One weight serves all the cells that share its training data, and lines L5 and L6 cost Θ(D)\Theta(D) per cell.

Space. Θ(M2P2)\Theta(M^2 P^2) for R^\hat{R} and GG.

For M=16M = 16 elements and P=32P = 32 pulses, D=512D = 512. With T=2DT = 2D training cells, line L1 needs about 2.7×1082.7 \times 10^8 multiplications and line L3 about 4.5×1074.5 \times 10^7, for each set of training cells. Line L4 then costs about 5×1055 \times 10^5 for each steering vector. This cost is the reason for the reduced-rank and partially adaptive variants below.

Properties

  • Optimum SINR (theorem). With the true RR, w=R−1vw = R^{-1} v maximizes the output SINR, and the maximum is vHR−1vv^H R^{-1} v. The scale of ww does not matter.
  • The loss of SMI (theorem, Reed, Mallett and Brennan 1974). With T≥DT \ge D independent Gaussian training snapshots and no loading, the ratio ρ\rho of the SINR of the SMI weight to the optimum has a beta distribution with mean (T+2−D)/(T+1)(T + 2 - D)/(T + 1). So T=2D−3T = 2D - 3 gives a mean loss of exactly 3 dB. T=2DT = 2D gives 1.76 dB for D=4D = 4, 2.63 dB for D=16D = 16 and 2.91 dB for D=64D = 64. The tests check the mean by simulation for T=5T = 5 and T=8T = 8 with D=4D = 4.
  • Clutter rank (theorem for integer β\beta, rule otherwise). The clutter covariance of a side-looking linear array has rank about M+β(P−1)M + \beta(P - 1), with β=2vpTr/d\beta = 2 v_p T_r / d for the platform speed vpv_p, the pulse interval TrT_r and the element spacing dd. The tests check the exact rank for (M,P,β)=(4,4,1)(M, P, \beta) = (4, 4, 1), (4,4,2)(4, 4, 2), (3,4,1)(3, 4, 1) and (4,3,2)(4, 3, 2).
  • Constant false alarm rate with a known covariance (theorem). Λ\Lambda is exponential with mean 1 under interference only. With R^\hat{R} in place of RR the false alarm rate still does not depend on RR, but its value changes with TT.
  • The steering vector is separable. v=vt⊗vsv = v_t \otimes v_s, which the tests check.

Variants and improvements

  • Diagonal loading. Line L2 with δ\delta near the noise power. It lets TT be much smaller than 2D2D, close to twice the clutter rank, at a small loss.
  • Reduced-rank STAP. Project onto the principal eigenvectors of R^\hat{R} (the clutter subspace) and null that subspace, as in the principal components method. The rank M+β(P−1)M + \beta(P - 1) is much smaller than MPMP.
  • Partially adaptive STAP. First apply fixed Doppler filters or beams, then adapt over a few of them: factored STAP adapts over the elements in each Doppler bin, and the extended factored method over a few adjacent bins. This cuts DD from MPMP to a small multiple of MM.
  • Matrix updates. When the training window slides by one cell, update R^−1\hat{R}^{-1} with the Woodbury identity in O(D2)O(D^2).
  • Knowledge-aided STAP. Use maps of the terrain or a model of the clutter to build part of RR, when there are few homogeneous training cells.
  • Space only and time only. With P=1P = 1 the method is the adaptive spatial beamformer, the Capon beamformer. With M=1M = 1 it is an adaptive Doppler filter.

When to use it

Use STAP on an airborne or spaceborne radar that must detect slow ground or air targets in strong clutter, for example ground moving target indication from an aircraft, when the clutter spreads over many Doppler bins because the platform moves. It is also the tool when jamming and clutter are present together. For a fixed radar, MTI and range-Doppler processing are enough. When the training cells are few or not homogeneous, use loading, reduced-rank or partially adaptive forms.

Pitfalls

  • Too few training snapshots in line L1. With T<DT < D and δ=0\delta = 0, R^\hat{R} is singular and line L3 fails. With TT only a little above DD, the weight is noisy and the mean loss (T+2−D)/(T+1)(T + 2 - D)/(T + 1) is large: for T=DT = D it is 2/(D+1)2/(D + 1), which is 9.3 dB for D=16D = 16. Use T≥2DT \ge 2D or loading.
  • The target in the training data of line L1. If the cell under test, or a cell with the same target, is in the training set, R^\hat{R} learns the target and the weight nulls it. Leave guard cells around the cell under test, as in CFAR.
  • Inverting the matrix in line L4. Forming R^−1\hat{R}^{-1} explicitly and multiplying costs more and loses accuracy when the clutter to noise ratio is large, because R^\hat{R} is then badly conditioned. Solve with the Cholesky factor.
  • The wrong order of the snapshot entries. The steering vector and the snapshots must use the same order, here pulse major, pM+mpM + m. If the data are element major and vv is pulse major, the weight is the optimum for a different target and the clutter null lands in the wrong place.
  • Heterogeneous training. Clutter changes from land to water and with range for a forward-looking array. If the training cells do not match the cell under test, the null is in the wrong place and false alarms rise. The theory of the SMI loss assumes independent and identically distributed training.
  • Using the real part in line L6 only by habit. vHwv^H w is real and positive in exact arithmetic, because R^+δI\hat{R} + \delta I is positive definite. A rounding error can leave a tiny imaginary part, and the code takes the real part. A negative value means the matrix was not positive definite.

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)
space_time_adaptive_processing.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/space-time-adaptive-processing/. The authors are listed in prov/STKZ5N.jsonl.

"""Sample matrix inversion (SMI) space-time adaptive processing.

An array of M elements receives P pulses. One range bin gives a space-time
snapshot x of length D = M P, ordered as x[p M + m] (pulse p, element m).
The target steering vector is v = b(f_t) kron a(f_s), with the spatial
vector a[m] = e^(j 2 pi f_s m) and the temporal vector b[p] = e^(j 2 pi f_t p);
f_s = (d / lambda) sin(theta) and f_t = f_d / PRF are normalized frequencies.

SMI estimates the clutter plus noise covariance from T training snapshots
of nearby range bins, R = (1/T) sum x_t x_t^H, adds diagonal loading delta I,
and uses the weight w = R^-1 v. The output is y = w^H x and the adaptive
matched filter (AMF) statistic is |w^H x|^2 / (v^H w).
"""

import cmath
import math
from typing import Sequence

from cbb import cholesky


def steering(m_count: int, p_count: int, fs: float, ft: float) -> list[complex]:
    """v[p M + m] = e^(j 2 pi (ft p + fs m)), that is b(ft) kron a(fs)."""
    return [cmath.exp(2j * math.pi * (ft * p + fs * m)) for p in range(p_count) for m in range(m_count)]


def sample_covariance(training: Sequence[Sequence[complex]]) -> list[list[complex]]:
    """R = (1/T) sum over t of x_t x_t^H. Cost Theta(T D^2)."""
    t_count = len(training)
    d = len(training[0])
    r = [[0j] * d for _ in range(d)]
    for x in training:
        for i in range(d):
            xi = x[i]
            ri = r[i]
            for k in range(d):
                ri[k] += xi * x[k].conjugate()
    return [[v / t_count for v in row] for row in r]


def cholesky_solve(g: list[list[complex]], v: Sequence[complex]) -> list[complex]:
    """Solve G G^H w = v for a lower triangular G, by a forward and a back substitution."""
    d = len(g)
    a = [0j] * d
    for i in range(d):
        a[i] = (v[i] - sum(g[i][k] * a[k] for k in range(i))) / g[i][i]
    w = [0j] * d
    for i in range(d - 1, -1, -1):
        w[i] = (a[i] - sum(g[k][i].conjugate() * w[k] for k in range(i + 1, d))) / g[i][i].conjugate()
    return w


def smi_stap(training: Sequence[Sequence[complex]], v: Sequence[complex], x: Sequence[complex],
             loading: float = 0.0) -> tuple[list[complex], complex, float]:
    """Return (w, y, amf) for the cell under test x.

    training holds T snapshots of length D; v is the steering vector of length D.
    T >= D is needed when loading is 0, or R is singular.
    Cost: Theta(T D^2 + D^3) time and Theta(D^2) space, with D = M P.
    """
    if not training or any(len(t) != len(v) for t in training) or len(x) != len(v):
        raise ValueError("need T >= 1 snapshots of the length of v")
    d = len(v)
    r = sample_covariance(training)  # @line L1
    for i in range(d):
        r[i][i] += loading  # @line L2
    g = cholesky(r)  # @line L3
    w = cholesky_solve(g, v)  # @line L4
    y = sum(wi.conjugate() * xi for wi, xi in zip(w, x))  # @line L5
    amf = abs(y) ** 2 / sum(vi.conjugate() * wi for vi, wi in zip(v, w)).real  # @line L6
    return w, y, amf  # @line L7


def clutter_covariance(m_count: int, p_count: int, beta: float, patches: int, cnr: float,
                       noise: float = 1.0) -> list[list[complex]]:
    """R = noise I + sum over patches of c v_c v_c^H for a side-looking array.

    Patch c has spatial frequency fs_c spread evenly over [-0.5, 0.5) and the
    Doppler ft_c = beta fs_c (the clutter ridge). The total clutter power over
    all patches, per element and pulse, is cnr * noise.
    """
    d = m_count * p_count
    r = [[complex(noise) if i == k else 0j for k in range(d)] for i in range(d)]
    c = cnr * noise / patches
    for q in range(patches):
        fs = -0.5 + q / patches
        vc = steering(m_count, p_count, fs, beta * fs)
        for i in range(d):
            for k in range(d):
                r[i][k] += c * vc[i] * vc[k].conjugate()
    return r


def sinr(w: Sequence[complex], v: Sequence[complex], r: Sequence[Sequence[complex]]) -> float:
    """|w^H v|^2 / (w^H R w): the output SINR for a unit-power target."""
    num = abs(sum(a.conjugate() * b for a, b in zip(w, v))) ** 2
    rw = [sum(r[i][k] * w[k] for k in range(len(w))) for i in range(len(w))]
    return num / sum(a.conjugate() * b for a, b in zip(w, rw)).real


def brennan_rank(m_count: int, p_count: int, beta: float) -> int:
    """Brennan's rule for the clutter rank: round(M + beta (P - 1))."""
    return round(m_count + beta * (p_count - 1))


def rmb_mean_loss(d: int, t_count: int) -> float:
    """The mean SINR loss of SMI without loading, E rho = (T + 2 - D) / (T + 1), for T >= D."""
    return (t_count + 2 - d) / (t_count + 1)
test_space_time_adaptive_processing.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/space-time-adaptive-processing/. The authors are listed in prov/STKZ5N.jsonl.

import random

import pytest

from cbb import cholesky, cn, solve
from space_time_adaptive_processing import (
    brennan_rank,
    cholesky_solve,
    clutter_covariance,
    rmb_mean_loss,
    sample_covariance,
    sinr,
    smi_stap,
    steering,
)


def dot(a, b):
    return sum(x.conjugate() * y for x, y in zip(a, b))


def numeric_rank(a, rel=1e-9):
    """Rank by Gaussian elimination with complete pivoting and a relative tolerance."""
    m = [[complex(v) for v in row] for row in a]
    rows, cols = len(m), len(m[0])
    top = max(abs(v) for row in m for v in row)
    rank = 0
    for c in range(min(rows, cols)):
        best, bi, bk = 0.0, -1, -1
        for i in range(c, rows):
            for k in range(c, cols):
                if abs(m[i][k]) > best:
                    best, bi, bk = abs(m[i][k]), i, k
        if best <= rel * top:
            break
        m[c], m[bi] = m[bi], m[c]
        for row in m:
            row[c], row[bk] = row[bk], row[c]
        for i in range(c + 1, rows):
            f = m[i][c] / m[c][c]
            for k in range(c, cols):
                m[i][k] -= f * m[c][k]
        rank += 1
    return rank


def random_hpd(rng, d):
    t = d + rng.randint(1, 4)
    r = sample_covariance([[cn(rng, 1.0) for _ in range(d)] for _ in range(t)])
    return r


def draw(rng, g):
    z = [cn(rng, 1.0) for _ in range(len(g))]
    return [sum(g[i][k] * z[k] for k in range(i + 1)) for i in range(len(g))]


def test_worked_example():
    # Two elements, one pulse. Training [3, 3] (a jammer at broadside) and [1, -1]
    # give R = [[5, 4], [4, 5]]. The target is at f_s = 0.25, so v = [1, j].
    training = [[3, 3], [1, -1]]
    assert sample_covariance(training) == [[5, 4], [4, 5]]
    v = [1, 1j]
    w, y, amf = smi_stap(training, v, v)
    assert all(abs(a - b) < 1e-12 for a, b in zip(w, [(5 - 4j) / 9, (-4 + 5j) / 9]))
    assert y == pytest.approx(10 / 9) and amf == pytest.approx(10 / 9)
    assert abs(dot(w, [1, 1])) ** 2 == pytest.approx(2 / 81)
    r = [[5, 4], [4, 5]]
    assert sinr(w, v, r) == pytest.approx(10 / 9)
    assert sinr(v, v, r) == pytest.approx(0.4)


def test_cholesky_solve_matches_gaussian_elimination():
    rng = random.Random(8101)
    for _ in range(500):
        d = rng.randint(1, 6)
        r = random_hpd(rng, d)
        v = [cn(rng, 1.0) for _ in range(d)]
        got = cholesky_solve(cholesky(r), v)
        want = solve(r, v)
        assert all(abs(a - b) < 1e-8 * (1 + abs(b)) for a, b in zip(got, want))


def test_loading_is_added_to_the_diagonal():
    rng = random.Random(8104)
    for _ in range(100):
        d = rng.randint(2, 6)
        t = rng.randint(1, d - 1)
        training = [[cn(rng, 1.0) for _ in range(d)] for _ in range(t)]
        v = [cn(rng, 1.0) for _ in range(d)]
        delta = rng.uniform(0.1, 3.0)
        w, _, _ = smi_stap(training, v, v, delta)
        r = sample_covariance(training)
        for i in range(d):
            r[i][i] += delta
        assert all(abs(a - b) < 1e-8 * (1 + abs(b)) for a, b in zip(w, solve(r, v)))
    with pytest.raises(ValueError):
        smi_stap([[1, 1]], [1, 1], [1, 1])  # T < D without loading: R is singular


def test_optimum_weight_beats_random_weights():
    rng = random.Random(8102)
    for _ in range(300):
        d = rng.randint(1, 6)
        r = random_hpd(rng, d)
        v = [cn(rng, 1.0) for _ in range(d)]
        w = solve(r, v)
        best = dot(v, w).real
        assert sinr(w, v, r) == pytest.approx(best, rel=1e-8)
        u = [cn(rng, 1.0) for _ in range(d)]
        assert sinr(u, v, r) <= best * (1 + 1e-9)


@pytest.mark.parametrize("m,p,beta,want", [(4, 4, 1, 7), (4, 4, 2, 10), (3, 4, 1, 6), (4, 3, 2, 8)])
def test_brennan_rule_for_integer_beta(m, p, beta, want):
    assert brennan_rank(m, p, beta) == want
    r = clutter_covariance(m, p, beta, 3 * m * p, 1.0)
    rc = [[v - (1 if i == k else 0) for k, v in enumerate(row)] for i, row in enumerate(r)]
    assert numeric_rank(rc) == want


def test_clutter_ridge_is_nulled():
    m, p, beta = 4, 4, 1.0
    d = m * p
    r = clutter_covariance(m, p, beta, 64, 10 ** 4)  # CNR 40 dB, noise power 1
    off = steering(m, p, 0.0, 0.5)
    on = steering(m, p, 0.125, 0.125)
    opt_off = sinr(solve(r, off), off, r)
    opt_on = sinr(solve(r, on), on, r)
    assert opt_off > 0.8 * d  # within 1 dB of the noise-only value D
    assert opt_on < 1e-3 * d  # a target on the clutter ridge is lost
    # The non-adaptive filter v lets the clutter in through its sidelobes: more than 20 dB worse.
    assert sinr(off, off, r) < 0.01 * opt_off


@pytest.mark.parametrize("t_count", [5, 8])
def test_rmb_mean_loss(t_count):
    # D = 4 (M = 2, P = 2), 600 trials, seed 8103; E rho = (T + 2 - D) / (T + 1).
    m, p = 2, 2
    d = m * p
    r = clutter_covariance(m, p, 1.0, 8, 100.0)
    g = cholesky(r)
    v = steering(m, p, 0.1, -0.3)
    best = dot(v, solve(r, v)).real
    rng = random.Random(8103 + t_count)
    total, trials = 0.0, 600
    for _ in range(trials):
        training = [draw(rng, g) for _ in range(t_count)]
        w, _, _ = smi_stap(training, v, v)
        total += sinr(w, v, r) / best
    assert total / trials == pytest.approx(rmb_mean_loss(d, t_count), abs=0.03)


def test_rmb_closed_form_values():
    assert rmb_mean_loss(4, 5) == pytest.approx(0.5)
    assert rmb_mean_loss(16, 29) == pytest.approx(0.5)
    assert rmb_mean_loss(4, 8) == pytest.approx(2 / 3)


def test_steering_is_a_kronecker_product():
    rng = random.Random(8105)
    for _ in range(100):
        m, p = rng.randint(1, 5), rng.randint(1, 5)
        fs, ft = rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)
        a = steering(m, 1, fs, 0.0)
        b = steering(1, p, 0.0, ft)
        v = steering(m, p, fs, ft)
        assert all(abs(v[q * m + k] - b[q] * a[k]) < 1e-12 for q in range(p) for k in range(m))

History

L. E. Brennan and I. S. Reed published the theory of adaptive radar in 1973: the optimum weight over antenna elements and pulses and its SINR. In 1974, Reed, Mallett and Brennan derived the distribution of the SINR of the sample matrix inversion weight, which gave the rule that about twice as many training snapshots as degrees of freedom keep the loss within 3 dB on average. J. Ward's 1994 report at MIT Lincoln Laboratory set out the clutter model, the clutter ridge and the processing architectures that most later work uses. The large cost of full STAP led to the reduced-rank and partially adaptive methods.

References

  1. Theory of adaptive radar, L. E. Brennan and I. S. Reed, IEEE Transactions on Aerospace and Electronic Systems 9(2), 1973, pp. 237 to 252 (the optimum space-time weight and its SINR)
  2. Rapid convergence rate in adaptive arrays, I. S. Reed, J. D. Mallett and L. E. Brennan, IEEE Transactions on Aerospace and Electronic Systems 10(6), 1974, pp. 853 to 863 (the distribution of the SINR loss of the sample matrix inversion weight)
  3. Space-time adaptive processing for airborne radar, the whole report (the clutter model, the clutter ridge, the clutter rank and the processing architectures)
  4. Mark A. Richards, Fundamentals of Radar Signal Processing, McGraw-Hill, 2005, Chapter 9, Sections 9.4 to 9.6 (the optimum space-time filter, the clutter rank, sample matrix inversion and the training data)

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
  • a scene preset for the example