Algorithm Search⌘K

Algorithmcore

Cell-averaging CFAR

Also called CA-CFAR.

Sets the threshold of each cell as a multiple of the sum of nearby reference cells, skipping guard cells, with a running sum. Pfa = (1 + tau)^(-N) for every noise power.

Time
Θ(n) worst · average · best
Space
Θ(1) extra
Where
N = the number of reference cells; n = the number of cells
Properties
constant false alarm rate in homogeneous noisedeterministicexact for rational inputonlinescale invariant
Origin
H. M. Finn, R. S. Johnson, 1968

Cell-averaging CFAR (CA-CFAR) is the standard CFAR detector of radar. For each range cell it adds the powers of NN reference cells around it, skips a few guard cells next to it, and declares a target when the cell's power is more than τ\tau times that sum. With a running sum the cost is O(1)O(1) per cell. In homogeneous exponential noise the false alarm probability is exactly (1+τ)−N(1 + \tau)^{-N}, whatever the noise power, so τ=Pfa−1/N−1\tau = P_{fa}^{-1/N} - 1. It is the best CFAR rule in that model, and it fails in a known way when a second target or a clutter edge enters the window.

In plain words

Slide a window along the list of powers. The window has a hole in the middle: the cell you test, plus a guard cell or two on each side, so that the target's own energy does not leak into the noise estimate. Add up the cells in the two halves of the window. If the tested cell is larger than a fixed multiple of that total, report a target. To move the window one cell, add the cell that enters each half and subtract the cell that leaves. The multiple depends only on the number of reference cells and the false alarm rate you want.

The problem

The input is a list x[0],…,x[n−1]x[0], \dots, x[n-1] of square-law powers, an even number N=2hN = 2h of reference cells, a number G≥0G \ge 0 of guard cells on each side and a factor τ>0\tau > 0. For a cell ii with G+h≤i≤n−1−G−hG + h \le i \le n - 1 - G - h, the reference window is the lagging cells i−G−h,…,i−G−1i - G - h, \dots, i - G - 1 and the leading cells i+G+1,…,i+G+hi + G + 1, \dots, i + G + h. Its sum is ZiZ_i. The output is the list of cells ii with x[i]>τZix[i] > \tau Z_i. Cells closer than G+hG + h to an end have no full window and are not tested. The design value PfaP_{fa} sets τ=Pfa−1/N−1\tau = P_{fa}^{-1/N} - 1, and the threshold on the mean of the reference cells is α=Nτ\alpha = N\tau.

The algorithm

  1. CA-CFAR(x[0..n-1], N, G, tau)
  2. 1h <- N / 2
  3. 2z <- sum of x[0 .. h-1] + sum of x[2G+h+1 .. 2G+2h] ▷ the window of the first cell i = G + h
  4. 3for i <- G + h to n - 1 - G - h
  5. 4t <- tau * z
  6. 5if x[i] > t then report i
  7. 6z <- z + x[i - G] - x[i - G - h] ▷ the lagging half moves one cell right
  8. 7z <- z + x[i + G + h + 1] - x[i + G + 1] ▷ the leading half moves one cell right

Line L2 sums the window of the first testable cell. Lines L4 and L5 compare the cell with the threshold. Lines L6 and L7 change zz to the sum of the next window: the cell i−Gi - G leaves the guard zone and enters the lagging half, the cell i+G+1i + G + 1 leaves the leading half and enters the guard zone, and one cell leaves at each outer edge. After the last cell, lines L6 and L7 are skipped, because the next window would run past the end.

Example

Take x=(3,1,2,2,1,30,9,2,1,3,2,1,2)x = (3, 1, 2, 2, 1, 30, 9, 2, 1, 3, 2, 1, 2), so n=13n = 13, with N=4N = 4, G=1G = 1 and Pfa=10−2P_{fa} = 10^{-2}. Then h=2h = 2 and τ=102/4−1=2.16228\tau = 10^{2/4} - 1 = 2.16228. Cells 3 to 9 have a full window.

ii lagging cells leading cells ZiZ_i τZi\tau Z_i x[i]x[i] decision
3 3, 1 30, 9 43 92.98 2 no
4 1, 2 9, 2 14 30.27 1 no
5 2, 2 2, 1 7 15.14 30 target
6 2, 1 1, 3 7 15.14 9 no
7 1, 30 3, 2 36 77.84 2 no
8 30, 9 2, 1 42 90.82 1 no
9 9, 2 1, 2 14 30.27 3 no

At the end of the iteration for i=4i = 4, line L6 adds x[3]=2x[3] = 2 and subtracts x[1]=1x[1] = 1, and line L7 adds x[8]=1x[8] = 1 and subtracts x[6]=9x[6] = 9. So zz goes from 14 to 14+1−8=714 + 1 - 8 = 7, the sum of the window of cell 5. The guard cells keep the 30 out of the windows of cells 4 and 6. Cells 7 and 8 have high thresholds because the 30 is in their windows, which is the start of the masking problem described below.

Correctness

The invariant of the loop is z=Ziz = Z_i at the start of the iteration for cell ii. Line L2 sets it for the first cell. The window of i+1i + 1 differs from the window of ii by one cell in and one cell out at each half, and lines L6 and L7 add and subtract exactly those four cells. So lines L4 and L5 compare x[i]x[i] with τZi\tau Z_i for every testable ii, and the output is the definition. With integer or rational powers the result is exact.

In the homogeneous model, the cell under test and the reference cells are independent and exponential with the same mean μ\mu. Then ZiZ_i is a gamma variable, P(x[i]>τz)=e−τz/μP(x[i] > \tau z) = e^{-\tau z/\mu}, and the expectation over ZiZ_i is (1+τ)−N(1 + \tau)^{-N}: μ\mu cancels. A Swerling 1 target of mean SNR SS gives Pd=(1+τ/(1+S))−NP_d = (1 + \tau/(1+S))^{-N}. The full proofs are in the correctness proof.

Proof: The running sum of CA-CFAR equals the window sum, and its false alarm probability is (1 + tau)^(-N) for every noise powerfull

The notation is that of the page. The input is x[0],…,x[n−1]x[0], \dots, x[n-1], one power value per range cell. N=2hN = 2h is the even number of reference cells, G≥0G \ge 0 the number of guard cells on each side and τ>0\tau > 0 the factor on the sum. For a cell ii with G+h≤i≤n−1−G−hG + h \le i \le n - 1 - G - h, the reference window is

Wi={i−G−h,…,i−G−1}∪{i+G+1,…,i+G+h},W_i = \{i - G - h, \dots, i - G - 1\} \cup \{i + G + 1, \dots, i + G + h\},

and the window sum is Zi=∑c∈Wix[c]Z_i = \sum_{c \in W_i} x[c]. The detector reports cell ii if and only if x[i]>τZix[i] > \tau Z_i. Write f=G+hf = G + h and ℓ=n−1−G−h\ell = n - 1 - G - h for the first and the last cell that has a full window.

Lemma 1 (the running sum). If f≤ℓf \le \ell, then at the start of the iteration for cell ii of the loop in line L3, z=Ziz = Z_i.

Proof. By induction on ii.

Base, i=fi = f. Line L2 sets zz to the sum of x[f−G−h],…,x[f−G−1]x[f - G - h], \dots, x[f - G - 1] and x[f+G+1],…,x[f+G+h]x[f + G + 1], \dots, x[f + G + h]. These are the cells of WfW_f, so z=Zfz = Z_f. All indices are inside 0,…,n−10, \dots, n-1, because f−G−h=0f - G - h = 0 and f+G+h=2f≤f+ℓ≤n−1f + G + h = 2f \le f + \ell \le n - 1.

Step. Assume z=Ziz = Z_i at the start of the iteration for ii, with i<ℓi < \ell. The lagging part of Wi+1W_{i+1} is {i+1−G−h,…,i−G}\{i + 1 - G - h, \dots, i - G\}. It is the lagging part of WiW_i without i−G−hi - G - h and with i−Gi - G. The leading part of Wi+1W_{i+1} is {i+G+2,…,i+G+h+1}\{i + G + 2, \dots, i + G + h + 1\}. It is the leading part of WiW_i without i+G+1i + G + 1 and with i+G+h+1i + G + h + 1. So

Zi+1=Zi+x[i−G]−x[i−G−h]+x[i+G+h+1]−x[i+G+1].Z_{i+1} = Z_i + x[i - G] - x[i - G - h] + x[i + G + h + 1] - x[i + G + 1].

Line L6 adds the first difference and line L7 the second, so at the start of the iteration for i+1i + 1, z=Zi+1z = Z_{i+1}. Line L7 reads x[i+G+h+1]x[i + G + h + 1], and i+1≤ℓi + 1 \le \ell gives i+G+h+1≤n−1i + G + h + 1 \le n - 1, so the index is valid. Line L6 reads x[i−G−h]x[i - G - h], and i≥fi \ge f gives i−G−h≥0i - G - h \ge 0. □\square

Theorem 1 (the output). For every input, the detector reports exactly the cells ii with f≤i≤ℓf \le i \le \ell and x[i]>τZix[i] > \tau Z_i, in increasing order, and it gives no decision for the other cells.

Proof. The loop of line L3 visits i=f,…,ℓi = f, \dots, \ell in increasing order, once each. By Lemma 1 line L4 computes t=τZit = \tau Z_i, and line L5 reports ii exactly when x[i]>τZix[i] > \tau Z_i. If f>ℓf > \ell, no cell has a full window and the loop does not run. □\square

With integer or rational cells and a rational τ\tau, each value of zz is exact, so Theorem 1 holds with no rounding. With floating point cells, the running sum can differ from a fresh sum by rounding, which the page discusses under Pitfalls.

Lemma 2 (the Laplace transform of a gamma sum). Let Y1,…,YNY_1, \dots, Y_N be independent and exponential with mean μ\mu, that is with density e−y/μ/μe^{-y/\mu}/\mu on y≥0y \ge 0, and Z=Y1+⋯+YNZ = Y_1 + \dots + Y_N. Then for every s≥0s \ge 0, E e−sZ=(1+sμ)−NE\, e^{-sZ} = (1 + s\mu)^{-N}.

Proof. For one cell, E e−sY=∫0∞e−sye−y/μ dy/μ=1/μs+1/μ=(1+sμ)−1E\, e^{-sY} = \int_0^\infty e^{-sy} e^{-y/\mu}\, dy / \mu = \frac{1/\mu}{s + 1/\mu} = (1 + s\mu)^{-1}. The cells are independent, so the transform of the sum is the product of NN equal factors. □\square

Theorem 2 (constant false alarm rate). Assume the homogeneous noise model: the cell under test and its NN reference cells are independent and exponential with the same mean μ>0\mu > 0. This is the output of a square-law detector, ∣w∣2|w|^2, for circular complex Gaussian noise w∼CN(0,μ)w \sim \mathcal{CN}(0, \mu). Then

P(x[i]>τZi)=(1+τ)−N,P(x[i] > \tau Z_i) = (1 + \tau)^{-N},

which does not depend on μ\mu. So τ=Pfa−1/N−1\tau = P_{fa}^{-1/N} - 1 gives the false alarm probability PfaP_{fa} for every noise power.

Proof. The cell under test X=x[i]X = x[i] is independent of Z=ZiZ = Z_i. Given Z=zZ = z, P(X>τz)=e−τz/μP(X > \tau z) = e^{-\tau z/\mu}, because XX is exponential with mean μ\mu. Take the expectation over ZZ and use Lemma 2 with s=τ/μs = \tau/\mu:

P(X>τZ)=E e−(τ/μ)Z=(1+(τ/μ)μ)−N=(1+τ)−N.P(X > \tau Z) = E\, e^{-(\tau/\mu) Z} = (1 + (\tau/\mu)\mu)^{-N} = (1 + \tau)^{-N}.

The value μ\mu cancels. Solving (1+τ)−N=Pfa(1 + \tau)^{-N} = P_{fa} for τ>0\tau > 0 gives τ=Pfa−1/N−1\tau = P_{fa}^{-1/N} - 1. □\square

Theorem 3 (detection of a Swerling 1 target). In the same model, let the cell under test hold a Swerling 1 target of mean signal to noise ratio SS, so that XX is exponential with mean μ(1+S)\mu(1 + S) and independent of the reference cells. Then

Pd=P(X>τZ)=(1+τ1+S)−N.P_d = P(X > \tau Z) = \left(1 + \frac{\tau}{1 + S}\right)^{-N}.

Proof. As in Theorem 2, P(X>τz)=e−τz/(μ(1+S))P(X > \tau z) = e^{-\tau z / (\mu(1 + S))}. Lemma 2 with s=τ/(μ(1+S))s = \tau / (\mu(1 + S)) gives (1+τ/(1+S))−N(1 + \tau/(1 + S))^{-N}. □\square

Theorem 4 (scale invariance). If every cell is multiplied by the same c>0c > 0, the detector reports the same cells.

Proof. ZiZ_i is linear in the cells, so c x[i]>τ cZic\, x[i] > \tau\, c Z_i holds exactly when x[i]>τZix[i] > \tau Z_i. By Theorem 1 the output depends only on these comparisons. □\square

Theorem 4 is the reason for the constant false alarm rate. Theorem 2 needs the exponential model, but Theorem 4 holds for every input, so a change of the noise power alone never changes a decision. ■\blacksquare

Complexity

Time. Line L2 reads NN cells once. Each of the n−2G−Nn - 2G - N iterations of the loop does a fixed number of additions, one multiplication and one comparison. The total is Θ(n)\Theta(n) for N≤nN \le n, in the best, average and worst case alike, because no step depends on the values. Recomputing the sum for each cell would cost Θ(nN)\Theta(nN).

Space. Θ(1)\Theta(1) beyond the input and the list of detections.

Properties

  • Constant false alarm rate (theorem, homogeneous exponential noise). Pfa=(1+τ)−NP_{fa} = (1 + \tau)^{-N} for every noise power. In a simulation with N=8N = 8, G=1G = 1 and Pfa=0.05P_{fa} = 0.05, 4000 windows each at noise powers 1 and 50 (seed 4103), the design value was inside the 99.9 percent Wilson interval of the measured rate for both powers.
  • Scale invariance (theorem, any input). Multiplying all powers by the same c>0c > 0 does not change any decision.
  • The CFAR loss (closed form). At Pfa=10−6P_{fa} = 10^{-6}, α\alpha is 36.99 for N=8N = 8, 21.94 for N=16N = 16, 17.28 for N=32N = 32 and 15.42 for N=64N = 64, against the ideal ln⁡(106)=13.82\ln(10^6) = 13.82. For a Swerling 1 target with N=16N = 16, Pd=0.9P_d = 0.9 needs 23.15 dB against 21.14 dB with a known noise power, a loss of 2.01 dB. At 20 dB, PdP_d is 0.806 against 0.872.
  • Optimal in its model (theorem). For a Swerling 1 target in homogeneous exponential noise, Gandhi and Kassam (1994) proved that CA-CFAR is a uniformly most powerful CFAR detector.
  • The sum is a sufficient statistic for μ\mu in the exponential model, which is why averaging is the right noise estimate there (see sufficient statistic).

Variants and improvements

  • Greatest of (GO-CFAR). Use 2max⁡(Zlag,Zlead)2\max(Z_{\text{lag}}, Z_{\text{lead}}) in place of ZZ, with a new τ\tau. It limits false alarms at the edge of a clutter region, at a small extra loss.
  • Smallest of (SO-CFAR). Use the smaller half. It keeps a second target in one half from masking the first, but it gives many false alarms at clutter edges.
  • Ordered statistic. Use the kk-th smallest reference value: see ordered-statistic CFAR. It resists up to N−kN - k interfering targets at a loss of about 0.5 to 1 dB in homogeneous noise.
  • Censored or trimmed mean. Drop the largest few reference values and average the rest.
  • Two dimensions. On the output of range-Doppler processing, the window is a ring of cells around the cell under test in range and Doppler. A two-dimensional prefix sum gives each window sum in O(1)O(1).
  • Noncoherent integration. If each cell is a sum of MM pulses, the noise is gamma with shape MM, and τ\tau must be computed from that distribution, not from (1+τ)−N(1 + \tau)^{-N}.

When to use it

Use CA-CFAR when the noise is close to homogeneous over the window, for example thermal noise or wide areas of uniform clutter, and targets are sparse. It has the smallest loss and the lowest cost of the common rules. Use OS-CFAR when targets come in groups, for example in automotive radar or in dense traffic, and GO-CFAR when clutter edges cause false alarms. Choose NN as large as the extent of homogeneous clutter allows: 16 to 32 cells is common.

Pitfalls

  • The factor on the sum and the factor on the mean. Line L4 multiplies the sum by τ=Pfa−1/N−1\tau = P_{fa}^{-1/N} - 1. Using α=Nτ\alpha = N\tau with the sum, or τ\tau with the mean, puts the threshold NN times too high or too low. Using the known-noise value ln⁡(1/Pfa)\ln(1/P_{fa}) on the mean gives too many false alarms: with N=16N = 16 the real rate is (1+13.82/16)−16=4.8×10−5(1 + 13.82/16)^{-16} = 4.8 \times 10^{-5}, not 10−610^{-6}.
  • Updating the window too early. Lines L6 and L7 must come after line L5. If they run before line L4, cell ii is compared with the window of cell i+1i + 1, and with G=0G = 0 that window holds x[i]x[i] itself.
  • Wrong indices in lines L6 and L7. Adding x[i−G+1]x[i - G + 1] in line L6, or x[i+G]x[i + G] in line L7, lets a guard cell or the cell under test into the window. A strong target then raises its own threshold. The tests compare the running sum with a fresh sum on 600 random inputs, exactly.
  • Masking by a second target. With x=(2,1,3,1,2,1,2,30,1,2,24,2,1,3,1,2,1,2)x = (2, 1, 3, 1, 2, 1, 2, 30, 1, 2, 24, 2, 1, 3, 1, 2, 1, 2), N=8N = 8, G=1G = 1 and Pfa=10−2P_{fa} = 10^{-2}, the target 24 at cell 10 has the 30 in its window, the threshold is 31.91, and CA-CFAR misses it. Ordered-statistic CFAR finds both.
  • Drift of the running sum in floating point. After a very large value enters and leaves the window, the subtraction leaves a rounding error, which can make zz slightly wrong or even negative in a quiet region. Recompute the sum from scratch every few thousand cells, or use integer powers.
  • The wrong noise model. (1+τ)−N(1 + \tau)^{-N} assumes exponential cells, which is a square-law detector on complex Gaussian noise. With a linear detector, integrated pulses, or Weibull or K-distributed clutter, the false alarm rate is different.

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)
cell_averaging_cfar.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cell-averaging-cfar/. The authors are listed in prov/AFY7TQ.jsonl.

"""Cell-averaging CFAR (Finn and Johnson, 1968) with a running sum.

The input x[0..n-1] is the output of a square-law detector along range, one
power value per cell. For the cell under test i, the reference window holds
h = N / 2 cells on each side, after G guard cells:

    lagging cells   i - G - h .. i - G - 1
    leading cells   i + G + 1 .. i + G + h

Z is the sum of the N reference cells, and the cell is declared a target when
x[i] > tau Z. In homogeneous noise with i.i.d. exponential cells of any mean,
the false alarm probability is (1 + tau)^(-N), so tau = Pfa^(-1/N) - 1.

The arithmetic is generic: with int or Fraction cells and a Fraction tau every
comparison is exact. Cells closer than G + h to either end have no full
window and are not tested.
"""

from fractions import Fraction
from typing import Sequence


def threshold_factor(n_ref: int, pfa: float) -> float:
    """tau = Pfa^(-1/N) - 1, the factor on the sum of the N reference cells. Cost: O(1)."""
    if n_ref < 1 or not 0.0 < pfa < 1.0:
        raise ValueError("need N >= 1 and 0 < Pfa < 1")
    return pfa ** (-1.0 / n_ref) - 1.0


def false_alarm_probability(n_ref: int, tau) -> float:
    """The closed form Pfa = (1 + tau)^(-N) for i.i.d. exponential cells."""
    return (1 + tau) ** (-n_ref)


def detection_probability_swerling1(n_ref: int, tau, snr) -> float:
    """Pd = (1 + tau / (1 + S))^(-N) for a Swerling 1 target of mean SNR S (a power ratio)."""
    return (1 + tau / (1 + snr)) ** (-n_ref)


def ca_cfar(x: Sequence, n_ref: int, guard: int, tau) -> tuple[list[int], list]:
    """Run CA-CFAR along x and return (detections, thresholds).

    n_ref is the even number N of reference cells, guard the number G of guard
    cells on each side, and tau the factor on the sum. thresholds[i] is tau Z
    for every cell with a full window, and None for the cells near the ends.
    detections lists the indices i with x[i] > tau Z, in increasing order.
    Cost: O(n) time for n cells (O(1) per cell after the first window), O(n)
    space for the output.
    """
    if n_ref < 2 or n_ref % 2 or guard < 0:
        raise ValueError("need an even N >= 2 and G >= 0")
    n = len(x)
    h = n_ref // 2  # @line L1
    thresholds: list = [None] * n
    detections: list[int] = []
    first, last = guard + h, n - 1 - guard - h
    if first > last:
        return detections, thresholds
    z = sum(x[first - guard - h:first - guard]) + sum(x[first + guard + 1:first + guard + h + 1])  # @line L2
    for i in range(first, last + 1):  # @line L3
        t = tau * z  # @line L4
        thresholds[i] = t
        if x[i] > t:  # @line L5
            detections.append(i)
        if i < last:
            z += x[i - guard] - x[i - guard - h]  # @line L6
            z += x[i + guard + h + 1] - x[i + guard + 1]  # @line L7
    return detections, thresholds


def ca_cfar_direct(x: Sequence, n_ref: int, guard: int, tau) -> tuple[list[int], list]:
    """The same detector with the window sum recomputed for every cell: O(n N) time."""
    n = len(x)
    h = n_ref // 2
    thresholds: list = [None] * n
    detections: list[int] = []
    for i in range(guard + h, n - guard - h):
        z = sum(x[i - guard - h:i - guard]) + sum(x[i + guard + 1:i + guard + h + 1])
        thresholds[i] = tau * z
        if x[i] > tau * z:
            detections.append(i)
    return detections, thresholds


def exact_tau(n_ref: int, pfa_root: Fraction) -> Fraction:
    """A rational tau for the design Pfa = pfa_root^N: tau = 1 / pfa_root - 1."""
    return 1 / Fraction(pfa_root) - 1
test_cell_averaging_cfar.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cell-averaging-cfar/. The authors are listed in prov/AFY7TQ.jsonl.

import math
import random
from fractions import Fraction

import pytest

from cbb import cn, wilson
from cell_averaging_cfar import (
    ca_cfar,
    ca_cfar_direct,
    detection_probability_swerling1,
    exact_tau,
    false_alarm_probability,
    threshold_factor,
)


def test_check_values():
    tau = threshold_factor(16, 1e-6)
    assert abs(tau - 1.37137) < 1e-5
    assert abs(16 * tau - 21.942) < 1e-3
    # Rohling 1983, Table I: the factor on the mean for Pfa = 1e-6.
    assert abs(32 * threshold_factor(32, 1e-6) - 17.28) < 5e-3
    assert abs(64 * threshold_factor(64, 1e-6) - 15.42) < 5e-3
    assert abs(false_alarm_probability(16, tau) - 1e-6) < 1e-15


def test_worked_example():
    x = [3, 1, 2, 2, 1, 30, 9, 2, 1, 3, 2, 1, 2]
    tau = threshold_factor(4, 1e-2)
    assert abs(tau - 2.16228) < 1e-5
    det, thr = ca_cfar(x, 4, 1, tau)
    assert det == [5]
    sums = [43, 14, 7, 7, 36, 42, 14]
    for i, z in zip(range(3, 10), sums):
        assert thr[i] == pytest.approx(tau * z, rel=1e-12)
    assert thr[:3] == [None] * 3 and thr[10:] == [None] * 3


def test_short_and_empty_inputs():
    assert ca_cfar([], 4, 1, 2.0) == ([], [])
    det, thr = ca_cfar([5, 1, 1, 1, 1, 1], 4, 1, 2.0)
    assert det == [] and thr == [None] * 6
    det, thr = ca_cfar([1, 1, 1, 9, 1, 1, 1], 6, 0, 1.0)
    assert det == [3] and thr[3] == 6
    with pytest.raises(ValueError):
        ca_cfar([1] * 10, 3, 1, 1.0)


def test_running_sum_equals_direct_sum_exactly():
    rng = random.Random(4101)
    for _ in range(600):
        n_ref = rng.choice([2, 4, 6, 8])
        guard = rng.randint(0, 3)
        x = [rng.randint(0, 20) for _ in range(rng.randint(0, 40))]
        tau = Fraction(rng.randint(1, 40), rng.randint(1, 20))
        assert ca_cfar(x, n_ref, guard, tau) == ca_cfar_direct(x, n_ref, guard, tau)


def test_scale_invariance_exact():
    rng = random.Random(4102)
    tau = exact_tau(8, Fraction(2, 3))
    for _ in range(200):
        x = [rng.randint(1, 30) for _ in range(30)]
        c = rng.randint(2, 1000)
        assert ca_cfar(x, 8, 2, tau)[0] == ca_cfar([c * v for v in x], 8, 2, tau)[0]


def gamma_pdf(z, n):
    return math.exp((n - 1) * math.log(z) - z - math.lgamma(n)) if z > 0 else 0.0


@pytest.mark.parametrize("n_ref,pfa", [(4, 1e-2), (16, 1e-6), (24, 1e-4)])
def test_pfa_closed_form_against_integral(n_ref, pfa):
    """Pfa = E exp(-tau Z) with Z ~ Gamma(N, 1), by Simpson's rule on [0, 120]."""
    tau = threshold_factor(n_ref, pfa)
    m, top = 6000, 120.0
    hstep = top / m
    s = 0.0
    for i in range(m + 1):
        z = i * hstep
        f = math.exp(-tau * z) * gamma_pdf(z, n_ref)
        s += f * (1 if i in (0, m) else (4 if i % 2 else 2))
    assert s * hstep / 3 == pytest.approx(pfa, rel=1e-6)


def square_law(rng, power):
    return abs(cn(rng, power)) ** 2


def false_alarms(rng, n_ref, guard, tau, power, trials):
    cells = n_ref + 2 * guard + 1
    mid = cells // 2
    k = 0
    for _ in range(trials):
        x = [square_law(rng, power) for _ in range(cells)]
        det, _ = ca_cfar(x, n_ref, guard, tau)
        k += det == [mid]
    return k


def test_false_alarm_rate_by_simulation_for_two_noise_powers():
    # N = 8, G = 1, design Pfa = 0.05; n = 4000 independent windows per noise
    # power, about 200 expected false alarms, seed 4103, Wilson z = 3.29.
    n_ref, guard, pfa, n = 8, 1, 0.05, 4000
    tau = threshold_factor(n_ref, pfa)
    rng = random.Random(4103)
    for power in (1.0, 50.0):
        k = false_alarms(rng, n_ref, guard, tau, power, n)
        lo, hi = wilson(k, n, 3.29)
        assert lo <= pfa <= hi


def test_swerling1_detection_probability_by_simulation():
    # N = 8, G = 1, Pfa = 0.05, mean SNR 10: Pd = (1 + tau / 11)^(-8) = 0.723.
    # n = 2000 windows (about 550 misses expected), seed 4104, Wilson z = 3.29.
    n_ref, guard, n, snr = 8, 1, 2000, 10.0
    tau = threshold_factor(n_ref, 0.05)
    pd = detection_probability_swerling1(n_ref, tau, snr)
    assert abs(pd - 0.723) < 1e-3
    rng = random.Random(4104)
    cells = n_ref + 2 * guard + 1
    mid = cells // 2
    k = 0
    for _ in range(n):
        x = [square_law(rng, 1.0) for _ in range(cells)]
        x[mid] = square_law(rng, 1.0 + snr)
        k += ca_cfar(x, n_ref, guard, tau)[0] == [mid]
    lo, hi = wilson(k, n, 3.29)
    assert lo <= pd <= hi


def test_masking_by_a_second_target():
    tau = threshold_factor(8, 1e-2)
    x = [2, 1, 3, 1, 2, 1, 2, 30, 1, 2, 24, 2, 1, 3, 1, 2, 1, 2]
    det, thr = ca_cfar(x, 8, 1, tau)
    assert 7 in det
    assert 10 not in det and thr[10] > 24
    alone = list(x)
    alone[7] = 2
    assert 10 in ca_cfar(alone, 8, 1, tau)[0]


def test_guard_cells_keep_target_spill_out_of_the_window():
    tau = threshold_factor(4, 1e-2)
    x = [2, 1, 2, 1, 2, 30, 25, 1, 2, 1, 2, 1]
    assert 5 not in ca_cfar(x, 4, 0, tau)[0]
    assert 5 in ca_cfar(x, 4, 1, tau)[0]

History

H. M. Finn and R. S. Johnson described the cell-averaging threshold in 1968, in the RCA Review, and computed its loss against a fixed threshold. In the 1970s and 1980s, the GO and SO variants were analyzed for clutter edges and multiple targets. H. Rohling introduced the ordered statistic rule in 1983. P. P. Gandhi and S. A. Kassam compared the processors in nonhomogeneous backgrounds in 1988, and in 1994 proved that the cell-averaging detector is a uniformly most powerful CFAR detector for a Swerling 1 target in exponential noise.

References

  1. Adaptive detection mode with threshold control as a function of spatially sampled clutter-level estimates, the whole paper (the threshold from the mean of the reference cells, and its loss against a fixed threshold)
  2. Optimality of the cell averaging CFAR detector, the whole paper (CA-CFAR is a uniformly most powerful CFAR detector for a Swerling 1 target in exponential noise of unknown power)
  3. Analysis of CFAR processors in nonhomogeneous background, the whole paper (the CA, GO and SO processors at clutter edges and with interfering targets)
  4. Mark A. Richards, Fundamentals of Radar Signal Processing, McGraw-Hill, 2005, Chapter 7, Section 7.2 (cell-averaging CFAR, the threshold and the CFAR loss) and Section 7.4 (interfering targets and clutter edges)

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