Algorithm Search⌘K

Algorithmadvanced

Ordered-statistic CFAR

Also called OS-CFAR.

Sets the threshold from the k-th smallest reference cell, kept in a sorted sliding window. Up to N - k interfering targets in the window cannot raise the threshold.

Time
Θ(n N) worst · averageO(n N) best
Space
Θ(N) extra
Where
N = the number of reference cells; n = the number of cells
Properties
constant false alarm rate in homogeneous noisedeterministicexact for rational inputonlinerobust to interfering targetsscale invariant
Origin
Hermann Rohling, 1983

Ordered-statistic CFAR (OS-CFAR) is a CFAR detector that takes the noise estimate of each cell from the kk-th smallest of its NN reference cells, in place of their sum. A strong second target in the window then cannot raise the threshold: up to N−kN - k such values only push larger values to the top of the sorted list. In homogeneous exponential noise the false alarm probability is the product ∏m=0k−1(N−m)/(N−m+T)\prod_{m=0}^{k-1} (N - m)/(N - m + T), independent of the noise power. The price is a loss of about 1 dB against cell-averaging CFAR and a sorted window, which costs O(N)O(N) per cell with a list or O(log⁡N)O(\log N) with a balanced tree.

In plain words

Look at the cells around the one you test, skip the guard cells, and sort the rest. Take the value at position kk, which is often about three quarters of the way up. Multiply it by a factor TT and compare the tested cell with the result. If one or two of the reference cells hold other targets, they go to the top of the sorted list and do not change the value at position kk. To move to the next cell, take out the two values that leave the window and put in the two that enter, each at its place in the sorted order.

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, a rank 1≤k≤N1 \le k \le N and a factor T>0T > 0. The reference window of cell ii 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. Let X(k)(i)X_{(k)}(i) be the kk-th smallest value of this multiset. The output is the list of cells ii, with G+h≤i≤n−1−G−hG + h \le i \le n - 1 - G - h, for which x[i]>TX(k)(i)x[i] > T X_{(k)}(i). For a design value PfaP_{fa}, TT is the unique root of ∏m=0k−1(N−m)/(N−m+T)=Pfa\prod_{m=0}^{k-1} (N - m)/(N - m + T) = P_{fa}.

The algorithm

  1. OS-CFAR(x[0..n-1], N, G, k, T)
  2. 1w <- sorted list of the reference cells of the first cell i = G + h, with h = N / 2
  3. 2for i <- G + h to n - 1 - G - h
  4. 3z <- w[k] ▷ the k-th smallest value, counted from 1
  5. 4t <- T * z
  6. 5if x[i] > t then report i
  7. 6remove one copy of x[i - G - h] from w; insert x[i - G] into w in order
  8. 7remove one copy of x[i + G + 1] from w; insert x[i + G + h + 1] into w in order

Line L1 sorts the first window. Line L3 reads the order statistic in O(1)O(1) time, because the list is sorted. Lines L6 and L7 move the window one cell to the right: in the lagging half the oldest cell leaves and the cell next to the guard zone enters, and in the leading half the cell next to the guard zone leaves and a new outer cell enters. Each removal and each insertion finds its position by binary search. After the last cell, lines L6 and L7 are skipped.

Example

Take 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), so n=18n = 18, with two targets of 30 and 24 at cells 7 and 10. Use N=8N = 8, G=1G = 1, k=6k = 6 and Pfa=10−2P_{fa} = 10^{-2}. The root of ∏m=05(8−m)/(8−m+T)=10−2\prod_{m=0}^{5} (8 - m)/(8 - m + T) = 10^{-2} is T=5.8696T = 5.8696. Cells 5 to 12 have a full window. The last column gives the threshold of cell-averaging CFAR with the same window and PfaP_{fa}, which is 0.77830.7783 times the sum.

ii lagging leading sorted window X(6)X_{(6)} TX(6)T X_{(6)} x[i]x[i] OS CA threshold
5 2, 1, 3, 1 30, 1, 2, 24 1, 1, 1, 2, 2, 3, 24, 30 3 17.61 1 no 49.81
6 1, 3, 1, 2 1, 2, 24, 2 1, 1, 1, 2, 2, 2, 3, 24 2 11.74 2 no 28.02
7 3, 1, 2, 1 2, 24, 2, 1 1, 1, 1, 2, 2, 2, 3, 24 2 11.74 30 target 28.02
8 1, 2, 1, 2 24, 2, 1, 3 1, 1, 1, 2, 2, 2, 3, 24 2 11.74 1 no 28.02
9 2, 1, 2, 30 2, 1, 3, 1 1, 1, 1, 2, 2, 2, 3, 30 2 11.74 2 no 32.69
10 1, 2, 30, 1 1, 3, 1, 2 1, 1, 1, 1, 2, 2, 3, 30 2 11.74 24 target 31.91
11 2, 30, 1, 2 3, 1, 2, 1 1, 1, 1, 2, 2, 2, 3, 30 2 11.74 2 no 32.69
12 30, 1, 2, 24 1, 2, 1, 2 1, 1, 1, 2, 2, 2, 24, 30 2 11.74 1 no 49.03

OS-CFAR reports cells 7 and 10. The other target is always in the top two places of the sorted window, so the sixth value stays at 2 or 3. CA-CFAR detects the 30 but misses the 24, because the 30 in the window of cell 10 raises the CA threshold to 31.91.

Correctness

The invariant of the loop is that at the start of the iteration for cell ii, ww is the sorted list of the multiset of the reference values of cell ii. Line L1 sets it. The windows of ii and i+1i + 1 differ by exactly the two cells removed and the two cells inserted in lines L6 and L7, and removing one copy of a value and inserting a value in order keeps a sorted list sorted. So line L3 reads X(k)(i)X_{(k)}(i), and the output is the definition. The correctness proof gives the details. It also proves the false alarm probability, through the exponential spacings of order statistics, the detection probability Pd=Pfa(T/(1+S))P_d = P_{fa}(T/(1+S)) of a Swerling 1 target, and the bound on interferers: if at most N−kN - k reference cells hold interference, X(k)(i)X_{(k)}(i) is at most the kk-th smallest of the clean cells, with equality when the interferers are at least that large.

Proof: The sliding sorted window of OS-CFAR gives the k-th smallest reference value, its false alarm probability is a product that does not depend on the noise power, and few interferers cannot raise the thresholdfull

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, kk the rank with 1≤k≤N1 \le k \le N and T>0T > 0 the factor. For a cell ii with f=G+h≤i≤ℓ=n−1−G−hf = G + h \le i \le \ell = 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\}.

Let MiM_i be the multiset of the values x[c]x[c] for c∈Wic \in W_i, and X(k)(i)X_{(k)}(i) its kk-th smallest element, counted with multiplicity. The detector reports cell ii exactly when x[i]>TX(k)(i)x[i] > T X_{(k)}(i).

Lemma 1 (the sorted window). If f≤ℓf \le \ell, then at the start of the iteration for cell ii of the loop in line L2, the list ww is sorted and holds the multiset MiM_i.

Proof. By induction on ii.

Base, i=fi = f. Line L1 sorts the values of the cells of WfW_f, so ww is sorted and holds MfM_f.

Step. Assume the claim for i<ℓi < \ell. As in the proof for CA-CFAR, Wi+1W_{i+1} is WiW_i without the cells i−G−hi - G - h and i+G+1i + G + 1, and with the cells i−Gi - G and i+G+h+1i + G + h + 1. The two cells that leave are different, and both are in WiW_i. So

Mi+1=Mi−{x[i−G−h]}+{x[i−G]}−{x[i+G+1]}+{x[i+G+h+1]},M_{i+1} = M_i - \{x[i - G - h]\} + \{x[i - G]\} - \{x[i + G + 1]\} + \{x[i + G + h + 1]\},

where −- removes one copy of a value and ++ adds one. Two copies of the same value cannot be told apart in a multiset, so removing one copy of the value x[c]x[c] is the same as removing the cell cc. Line L6 removes one copy of x[i−G−h]x[i - G - h], which is in ww, and inserts x[i−G]x[i - G]. Line L7 removes one copy of x[i+G+1]x[i + G + 1] and inserts x[i+G+h+1]x[i + G + h + 1]. The value x[i+G+1]x[i + G + 1] is still in ww when line L7 runs, because line L6 removed one copy of a different cell's value and MiM_i held a copy for each cell. A binary search finds a copy of the value in a sorted list, and deleting it keeps the list sorted. Inserting at the position that a binary search gives also keeps it sorted. So after line L7, ww is sorted and holds Mi+1M_{i+1}. □\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]>TX(k)(i)x[i] > T X_{(k)}(i), in increasing order.

Proof. The loop visits i=f,…,ℓi = f, \dots, \ell in order. By Lemma 1, ww is the sorted list of MiM_i, so the element w[k−1]w[k-1] read by line L3 (index from 0) is X(k)(i)X_{(k)}(i). Lines L4 and L5 compare x[i]x[i] with TX(k)(i)T X_{(k)}(i). □\square

Lemma 2 (the spacings of exponential order statistics). Let Y1,…,YNY_1, \dots, Y_N be independent and exponential with mean μ\mu, with order statistics Y(1)≤⋯≤Y(N)Y_{(1)} \le \dots \le Y_{(N)}, and put Y(0)=0Y_{(0)} = 0. Then the spacings Dj=Y(j)−Y(j−1)D_j = Y_{(j)} - Y_{(j-1)}, j=1,…,Nj = 1, \dots, N, are independent, and DjD_j is exponential with mean μ/(N−j+1)\mu / (N - j + 1).

Proof. The joint density of the order statistics is N! ∏jμ−1e−yj/μN!\, \prod_{j} \mu^{-1} e^{-y_j/\mu} on 0≤y1≤⋯≤yN0 \le y_1 \le \dots \le y_N. The map from (y1,…,yN)(y_1, \dots, y_N) to the spacings dj=yj−yj−1d_j = y_j - y_{j-1} is linear with a triangular matrix of ones on the diagonal, so its Jacobian is 1, and it maps the ordered region onto dj≥0d_j \ge 0. Each yjy_j is d1+⋯+djd_1 + \dots + d_j, so ∑jyj=∑j(N−j+1)dj\sum_j y_j = \sum_j (N - j + 1) d_j, because djd_j is part of yj,…,yNy_j, \dots, y_N. With N!=∏j=1N(N−j+1)N! = \prod_{j=1}^{N} (N - j + 1) the joint density of the spacings is

∏j=1NN−j+1μ e−(N−j+1)dj/μ,\prod_{j=1}^{N} \frac{N - j + 1}{\mu}\, e^{-(N - j + 1) d_j / \mu},

a product of exponential densities with means μ/(N−j+1)\mu/(N - j + 1). □\square

Theorem 2 (constant false alarm rate). Assume that the cell under test and its NN reference cells are independent and exponential with the same mean μ>0\mu > 0. Then

Pfa(T)=P(x[i]>TX(k))=∏m=0k−1N−mN−m+T,P_{fa}(T) = P(x[i] > T X_{(k)}) = \prod_{m=0}^{k-1} \frac{N - m}{N - m + T},

which does not depend on μ\mu. Pfa(T)P_{fa}(T) falls strictly from 1 to 0 as TT goes from 0 to ∞\infty, so each PfaP_{fa} in (0,1)(0, 1) has exactly one TT.

Proof. By Lemma 2, X(k)=D1+⋯+DkX_{(k)} = D_1 + \dots + D_k with independent exponential DjD_j of means μ/(N−j+1)\mu/(N - j + 1). The cell under test XX is independent of the window, and given X(k)=zX_{(k)} = z, P(X>Tz)=e−Tz/μP(X > Tz) = e^{-Tz/\mu}. So

Pfa(T)=E e−TX(k)/μ=∏j=1kE e−(T/μ)Dj=∏j=1k(1+TN−j+1)−1,P_{fa}(T) = E\, e^{-T X_{(k)}/\mu} = \prod_{j=1}^{k} E\, e^{-(T/\mu) D_j} = \prod_{j=1}^{k} \left(1 + \frac{T}{N - j + 1}\right)^{-1},

by the transform E e−sD=(1+sν)−1E\, e^{-sD} = (1 + s\nu)^{-1} of an exponential of mean ν\nu. Put m=j−1m = j - 1 to get the product of the statement. Each factor is positive, equals 1 at T=0T = 0, falls strictly in TT and goes to 0, so the product does the same. □\square

The product equals Rohling's closed form k(Nk)(k−1)! (T+N−k)!/(T+N)!k \binom{N}{k} (k-1)!\, (T + N - k)! / (T + N)! for integer TT. Write k(Nk)(k−1)!=N!/(N−k)!=∏m<k(N−m)k \binom{N}{k} (k-1)! = N!/(N-k)! = \prod_{m<k} (N - m) and (T+N)!/(T+N−k)!=∏m<k(N−m+T)(T + N)!/(T + N - k)! = \prod_{m<k} (N - m + T).

Theorem 3 (detection of a Swerling 1 target). If the cell under test is exponential with mean μ(1+S)\mu(1 + S) and the reference cells are as in Theorem 2, then Pd=Pfa(T/(1+S))P_d = P_{fa}(T/(1 + S)).

Proof. Given X(k)=zX_{(k)} = z, P(X>Tz)=e−Tz/(μ(1+S))P(X > Tz) = e^{-Tz/(\mu(1+S))}. This is the computation of Theorem 2 with T/(1+S)T/(1+S) in place of TT. □\square

Theorem 4 (interfering targets). Assume that at most r≤N−kr \le N - k reference cells of WiW_i hold interference, with any values, and let c1≤c2≤…c_1 \le c_2 \le \dots be the sorted values of the other N−r≥kN - r \ge k cells. Then X(k)(i)≤ckX_{(k)}(i) \le c_k. If moreover every interfering value is at least ckc_k, then X(k)(i)=ckX_{(k)}(i) = c_k, the same value as in a window of the N−rN - r clean cells alone.

Proof. The cells with the values c1,…,ckc_1, \dots, c_k are kk cells of the window with values at most ckc_k. So at least kk elements of MiM_i are at most ckc_k, and the kk-th smallest is at most ckc_k. If every interfering value is at least ckc_k, every element of MiM_i below ckc_k is one of c1,…,ck−1c_1, \dots, c_{k-1}, so fewer than kk elements are below ckc_k and X(k)(i)≥ckX_{(k)}(i) \ge c_k. □\square

So up to N−kN - k strong interferers in the window cannot raise the threshold above TckT c_k. For CA-CFAR, one interferer of power AA adds AA to the sum and raises the threshold without a limit. ■\blacksquare

Complexity

Time. Line L1 sorts NN values in Θ(Nlog⁡N)\Theta(N \log N). In each of the n−2G−Nn - 2G - N iterations, the four searches of lines L6 and L7 take O(log⁡N)O(\log N) comparisons, but each insertion or deletion in an array list moves the elements after its position, up to NN of them. On random input the average move is about N/2N/2. So the loop costs Θ(nN)\Theta(nN) in the worst and the average case, and O(nN)O(nN) in all cases. The tests compare the sliding window with a fresh sort of each window, which costs Θ(nNlog⁡N)\Theta(nN \log N). With a balanced binary search tree or an order statistic tree that stores subtree sizes, each step is O(log⁡N)O(\log N) and the total is O(nlog⁡N)O(n \log N). Computing X(k)X_{(k)} from scratch with quickselect costs O(N)O(N) expected per cell.

Space. Θ(N)\Theta(N) for the sorted window, beyond the input and the output.

Properties

  • Constant false alarm rate (theorem, homogeneous exponential noise). Pfa=∏m=0k−1(N−m)/(N−m+T)P_{fa} = \prod_{m=0}^{k-1} (N - m)/(N - m + T), independent of the noise power. For integer TT it equals Rohling's form k(Nk)(k−1)! (T+N−k)!/(T+N)!k \binom{N}{k} (k-1)!\, (T + N - k)!/(T + N)!, and the tests check the two forms exactly for all N≤12N \le 12, k≤Nk \le N and T≤14T \le 14.
  • The factor (closed form). At Pfa=10−6P_{fa} = 10^{-6}: T=46.70T = 46.70 for N=8N = 8, k=6k = 6; T=20.95T = 20.95 for N=16N = 16, k=12k = 12; T=16.29T = 16.29 for N=24N = 24, k=18k = 18. These match Rohling's Table II to the printed decimal.
  • The loss. The average threshold T E[X(k)]/μT\, E[X_{(k)}]/\mu is 27.19 for N=16N = 16, k=12k = 12, against 21.94 for CA-CFAR: 0.93 dB more. For a Swerling 1 target at Pd=0.9P_d = 0.9, OS needs 24.08 dB and CA needs 23.15 dB.
  • Robust to interfering targets (theorem). Up to N−kN - k reference cells can hold any values, and the threshold is still at most TT times the kk-th smallest clean value. For CA-CFAR one interferer of power AA adds AA to the sum, with no limit.
  • Scale invariant (theorem). Multiplying all cells by c>0c > 0 multiplies X(k)X_{(k)} by cc, so no decision changes.

Variants and improvements

  • The choice of kk. Rohling's average threshold table uses k=3N/4k = 3N/4, a common choice. A larger kk lowers the loss in homogeneous noise but tolerates fewer interferers. A smaller kk tolerates more interferers but has a larger loss and more false alarms at a clutter edge.
  • OS on each half. Take an order statistic of each half and use the larger (OSGO) or the smaller (OSSO), which mixes the clutter edge behavior of GO and SO with the robustness of OS.
  • Trimmed mean (TM-CFAR). Sort the window, drop the r1r_1 smallest and r2r_2 largest values and sum the rest. With r1=0r_1 = 0 and r2=0r_2 = 0 it is CA, and with r1=k−1r_1 = k - 1 and r2=N−kr_2 = N - k it is OS.
  • Censored mean. Drop the N−kN - k largest values and average the kk smallest.
  • Two dimensions. On the output of range-Doppler processing, the window is a ring of cells in range and Doppler. Automotive radar often uses OS on the range axis of each Doppler bin, because targets at the same range are common there.
  • A faster window. A sliding median structure (see sliding window median) generalizes to any rank kk with two heaps or an order statistic tree.

When to use it

Use OS-CFAR when targets come in groups, so that a second target is often in the window of the first: road traffic, formations of aircraft, or ships in a harbor. Also use it when clutter is spiky and a few reference cells are much larger than the rest. In thermal noise with sparse targets, cell-averaging CFAR has a smaller loss and a lower cost.

Pitfalls

  • An index off by one in line L3. The pseudocode counts from 1. In a language that counts from 0, line L3 must read w[k - 1]. Reading w[k] takes the (k+1)(k+1)-th value, raises the threshold, and gives a false alarm rate below the design value, with a larger loss.
  • Removing every copy of a value in lines L6 and L7. Powers from integer counts or quantized samples repeat. Line L6 must remove exactly one copy of x[i−G−h]x[i - G - h]. A removal that deletes all equal values shrinks the window and makes line L3 read the wrong rank, or an index that does not exist. The tests use small integer values, with many repeats, on 600 random inputs and compare the result with a fresh sort of each window.
  • The factor of CA-CFAR in line L4. TT comes from the product ∏m<k(N−m)/(N−m+T)\prod_{m<k} (N - m)/(N - m + T), not from (1+τ)−N(1 + \tau)^{-N}, and it multiplies one cell, not a sum. For N=16N = 16 and Pfa=10−6P_{fa} = 10^{-6}, T=20.95T = 20.95 for k=12k = 12, while the CA factor on the sum is 1.37 and on the mean is 21.94.
  • More interferers than N−kN - k. With k=Nk = N, line L3 takes the maximum, and one interferer sets the threshold. In the tests, N−k+1N - k + 1 interferers of 10610^6 make the threshold T⋅106T \cdot 10^6.
  • Clutter edges. If the clutter fills more than N−kN - k reference cells on one side and the cell under test is in the quiet region, the threshold comes from the clutter and the cell is masked. If the cell is in the clutter and more than kk cells are quiet, the threshold is too low and false alarms follow.

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)
ordered_statistic_cfar.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ordered-statistic-cfar/. The authors are listed in prov/3GCSWG.jsonl.

"""Ordered-statistic CFAR (Rohling, 1983) with a sliding sorted window.

The input x[0..n-1] is the output of a square-law detector along range. For
the cell under test i, the reference window holds h = N / 2 cells on each
side, after G guard cells. The N reference values are kept in a sorted list.
The k-th smallest of them, X_(k), estimates the noise level, and the cell is a
target when x[i] > T X_(k).

For i.i.d. exponential cells of any mean, the false alarm probability is

    Pfa(T) = prod over i = 0 .. k-1 of (N - i) / (N - i + T),

which falls strictly in T, so T for a design Pfa is found by bisection.

The sorted window is updated with bisect: two removals and two insertions per
cell, each O(N) for the list shifts. With int or Fraction cells and a Fraction
T every comparison is exact.
"""

from bisect import bisect_left, insort
from fractions import Fraction
from math import comb, factorial
from typing import Sequence


def false_alarm_probability(n_ref: int, k: int, t):
    """Pfa = prod_{i<k} (N - i) / (N - i + T). Exact for int or Fraction T."""
    p = Fraction(1) if isinstance(t, (int, Fraction)) else 1.0
    for i in range(k):
        p = p * (n_ref - i) / (n_ref - i + t)
    return p


def false_alarm_probability_rohling(n_ref: int, k: int, t: int) -> Fraction:
    """Rohling's equation (14) for an integer T: k C(N, k) (k-1)! (T + N - k)! / (T + N)!."""
    return Fraction(k * comb(n_ref, k) * factorial(k - 1) * factorial(t + n_ref - k), factorial(t + n_ref))


def threshold_factor(n_ref: int, k: int, pfa: float) -> float:
    """The T with Pfa(T) = pfa, by bisection (Pfa falls strictly in T). Cost: O(k) per step."""
    if not 1 <= k <= n_ref or not 0.0 < pfa < 1.0:
        raise ValueError("need 1 <= k <= N and 0 < Pfa < 1")
    lo, hi = 0.0, 1.0
    while false_alarm_probability(n_ref, k, hi) > pfa:
        hi *= 2.0
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if false_alarm_probability(n_ref, k, mid) > pfa:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-13 * hi:
            break
    return 0.5 * (lo + hi)


def mean_order_statistic(n_ref: int, k: int) -> float:
    """E X_(k) / mu = sum_{j=1..k} 1 / (N - k + j) for i.i.d. exponential cells of mean mu."""
    return sum(1.0 / (n_ref - k + j) for j in range(1, k + 1))


def detection_probability_swerling1(n_ref: int, k: int, t, snr) -> float:
    """Pd for a Swerling 1 target of mean SNR S: Pfa with T replaced by T / (1 + S)."""
    return false_alarm_probability(n_ref, k, t / (1 + snr))


def _remove(w: list, v) -> None:
    del w[bisect_left(w, v)]


def os_cfar(x: Sequence, n_ref: int, guard: int, k: int, t) -> tuple[list[int], list]:
    """Run OS-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, k the rank (1 <= k <= N) and t the factor T. The
    threshold of cell i is T times the k-th smallest reference value, or None
    near the ends. Cost: O(n N) time with the sorted list, O(N) extra space.
    """
    if n_ref < 2 or n_ref % 2 or guard < 0 or not 1 <= k <= n_ref:
        raise ValueError("need an even N >= 2, G >= 0 and 1 <= k <= N")
    n = len(x)
    h = n_ref // 2
    thresholds: list = [None] * n
    detections: list[int] = []
    first, last = guard + h, n - 1 - guard - h
    if first > last:
        return detections, thresholds
    w = sorted(list(x[first - guard - h:first - guard]) + list(x[first + guard + 1:first + guard + h + 1]))  # @line L1
    for i in range(first, last + 1):  # @line L2
        z = w[k - 1]  # @line L3
        thresholds[i] = t * z  # @line L4
        if x[i] > t * z:  # @line L5
            detections.append(i)
        if i < last:
            _remove(w, x[i - guard - h])  # @line L6
            insort(w, x[i - guard])  # @line L6
            _remove(w, x[i + guard + 1])  # @line L7
            insort(w, x[i + guard + h + 1])  # @line L7
    return detections, thresholds


def os_cfar_direct(x: Sequence, n_ref: int, guard: int, k: int, t) -> tuple[list[int], list]:
    """The same detector with each window sorted from scratch: O(n N log 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):
        w = sorted(list(x[i - guard - h:i - guard]) + list(x[i + guard + 1:i + guard + h + 1]))
        thresholds[i] = t * w[k - 1]
        if x[i] > thresholds[i]:
            detections.append(i)
    return detections, thresholds
test_ordered_statistic_cfar.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ordered-statistic-cfar/. The authors are listed in prov/3GCSWG.jsonl.

import math
import random
from fractions import Fraction

import pytest

from cbb import cn, wilson
from ordered_statistic_cfar import (
    detection_probability_swerling1,
    false_alarm_probability,
    false_alarm_probability_rohling,
    mean_order_statistic,
    os_cfar,
    os_cfar_direct,
    threshold_factor,
)


@pytest.mark.parametrize("n_ref,k,t", [(16, 12, 20.9), (24, 18, 16.3), (32, 24, 14.4), (8, 6, 46.7)])
def test_rohling_table_values(n_ref, k, t):
    """Rohling 1983, Table II: T for Pfa = 1e-6, to the one decimal printed there."""
    assert abs(threshold_factor(n_ref, k, 1e-6) - t) < 0.06


@pytest.mark.parametrize("n_ref,k,adt", [(16, 12, 27.2), (24, 18, 21.6), (32, 24, 19.3)])
def test_rohling_average_threshold(n_ref, k, adt):
    """Rohling 1983, Table IV: the average threshold T E X_(k) / mu for k = 3N/4."""
    t = threshold_factor(n_ref, k, 1e-6)
    assert abs(t * mean_order_statistic(n_ref, k) - adt) < 0.06


def test_product_equals_rohling_equation_14_exactly():
    for n_ref in range(1, 13):
        for k in range(1, n_ref + 1):
            for t in range(0, 15):
                assert false_alarm_probability(n_ref, k, t) == false_alarm_probability_rohling(n_ref, k, t)


def os_density(x, n_ref, k):
    """The density of X_(k) for N i.i.d. unit exponentials."""
    return k * math.comb(n_ref, k) * (1 - math.exp(-x)) ** (k - 1) * math.exp(-x * (n_ref - k + 1))


@pytest.mark.parametrize("n_ref,k,t", [(8, 6, 5.87), (16, 12, 20.95), (24, 3, 4.0)])
def test_pfa_against_integral(n_ref, k, t):
    """Pfa = E exp(-T X_(k)), by Simpson's rule on [0, 20]."""
    m, top = 20000, 20.0
    hstep = top / m
    s = 0.0
    for i in range(m + 1):
        x = i * hstep
        s += math.exp(-t * x) * os_density(x, n_ref, k) * (1 if i in (0, m) else (4 if i % 2 else 2))
    assert s * hstep / 3 == pytest.approx(false_alarm_probability(n_ref, k, t), rel=1e-6)


def test_worked_example():
    x = [2, 1, 3, 1, 2, 1, 2, 30, 1, 2, 24, 2, 1, 3, 1, 2, 1, 2]
    t = threshold_factor(8, 6, 1e-2)
    assert abs(t - 5.8696) < 1e-4
    det, thr = os_cfar(x, 8, 1, 6, t)
    assert det == [7, 10]
    assert thr[5] == pytest.approx(3 * t) and thr[10] == pytest.approx(2 * t)


def test_edges_and_bad_arguments():
    assert os_cfar([], 4, 1, 3, 2.0) == ([], [])
    assert os_cfar([1] * 6, 4, 1, 3, 2.0) == ([], [None] * 6)
    with pytest.raises(ValueError):
        os_cfar([1] * 10, 4, 1, 5, 2.0)
    with pytest.raises(ValueError):
        os_cfar([1] * 10, 5, 1, 2, 2.0)


def test_sliding_window_equals_sorting_each_window_exactly():
    rng = random.Random(5101)
    for _ in range(600):
        n_ref = rng.choice([2, 4, 6, 8, 10])
        guard = rng.randint(0, 3)
        k = rng.randint(1, n_ref)
        x = [rng.randint(0, 12) for _ in range(rng.randint(0, 40))]
        t = Fraction(rng.randint(1, 50), rng.randint(1, 10))
        assert os_cfar(x, n_ref, guard, k, t) == os_cfar_direct(x, n_ref, guard, k, t)


def test_up_to_n_minus_k_interferers_leave_a_noise_value_as_threshold():
    """With r <= N - k strong interferers, X_(k) is the k-th smallest of the N - r noise cells."""
    rng = random.Random(5102)
    n_ref, guard, k, big = 16, 1, 12, 10 ** 6
    i = guard + n_ref // 2
    for _ in range(300):
        x = [rng.randint(1, 10) for _ in range(2 * guard + n_ref + 1)]
        ref = [j for j in range(len(x)) if abs(j - i) > guard]
        r = rng.randint(0, n_ref - k + 1)
        hit = set(rng.sample(ref, r))
        y = [big if j in hit else v for j, v in enumerate(x)]
        thr = os_cfar(y, n_ref, guard, k, 3)[1][i]
        if r <= n_ref - k:
            noise = sorted(x[j] for j in ref if j not in hit)
            assert thr == 3 * noise[k - 1] and thr <= 30
        else:
            assert thr == 3 * big


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


def test_false_alarm_rate_by_simulation_for_two_noise_powers():
    # N = 8, k = 6, G = 1, design Pfa = 0.05; n = 4000 independent windows per
    # noise power, about 200 expected false alarms, seed 5103, Wilson z = 3.29.
    n_ref, k, guard, pfa, n = 8, 6, 1, 0.05, 4000
    t = threshold_factor(n_ref, k, pfa)
    rng = random.Random(5103)
    cells = n_ref + 2 * guard + 1
    for power in (1.0, 50.0):
        hits = 0
        for _ in range(n):
            x = [square_law(rng, power) for _ in range(cells)]
            hits += os_cfar(x, n_ref, guard, k, t)[0] == [cells // 2]
        lo, hi = wilson(hits, n, 3.29)
        assert lo <= pfa <= hi


def test_swerling1_detection_probability_by_simulation():
    # N = 8, k = 6, G = 1, Pfa = 0.05, mean SNR 10; n = 2000 windows, seed 5104.
    n_ref, k, guard, n, snr = 8, 6, 1, 2000, 10.0
    t = threshold_factor(n_ref, k, 0.05)
    pd = detection_probability_swerling1(n_ref, k, t, snr)
    rng = random.Random(5104)
    cells = n_ref + 2 * guard + 1
    mid = cells // 2
    hits = 0
    for _ in range(n):
        x = [square_law(rng, 1.0) for _ in range(cells)]
        x[mid] = square_law(rng, 1.0 + snr)
        hits += os_cfar(x, n_ref, guard, k, t)[0] == [mid]
    lo, hi = wilson(hits, n, 3.29)
    assert lo <= pd <= hi

History

Hermann Rohling published OS-CFAR in 1983 in the IEEE Transactions on Aerospace and Electronic Systems. He gave the false alarm probability in closed form, tabulated the factor TT and the average threshold for several NN and kk, and studied the detector in clutter and with several targets. P. P. Gandhi and S. A. Kassam compared CA, GO, SO and OS processors at clutter edges and with interfering targets in 1988. OS-CFAR is now common in automotive radar.

References

  1. Radar CFAR thresholding in clutter and multiple target situations, H. Rohling, IEEE Transactions on Aerospace and Electronic Systems 19(4), 1983, pp. 608 to 621: equations 14 and 15 (the false alarm and detection probabilities) and Tables I to IV (the factor T and the average threshold)
  2. Analysis of CFAR processors in nonhomogeneous background, the whole paper (CA and OS processors at clutter edges and with interfering targets)
  3. Mark A. Richards, Fundamentals of Radar Signal Processing, McGraw-Hill, 2005, Chapter 7, Section 7.4 (interfering targets and clutter edges) and Section 7.6 (order statistic CFAR)

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