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.
- Solves
- CFAR detection
- Time
- Θ(n N) worst · averageO(n N) best
- Space
- Θ(N) extra
- Where
- N = the number of reference cells; n = the number of cells
- Model
- Real RAM
- Properties
- constant false alarm rate in homogeneous noisedeterministicexact for rational inputonlinerobust to interfering targetsscale invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hermann Rohling, 1983
Ordered-statistic CFAR (OS-CFAR) is a CFAR detector that takes the noise estimate of each cell from the -th smallest of its reference cells, in place of their sum. A strong second target in the window then cannot raise the threshold: up to such values only push larger values to the top of the sorted list. In homogeneous exponential noise the false alarm probability is the product , independent of the noise power. The price is a loss of about 1 dB against cell-averaging CFAR and a sorted window, which costs per cell with a list or 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 , which is often about three quarters of the way up. Multiply it by a factor 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 . 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 of square-law powers, an even number of reference cells, a number of guard cells on each side, a rank and a factor . The reference window of cell is the lagging cells and the leading cells . Let be the -th smallest value of this multiset. The output is the list of cells , with , for which . For a design value , is the unique root of .
The algorithm
OS-CFAR(x[0..n-1], N, G, k, T)- 1
w <- sorted list of the reference cells of the first cell i = G + h, with h = N / 2 - 2
for i <- G + h to n - 1 - G - h - 3
z <- w[k] ▷ the k-th smallest value, counted from 1 - 4
t <- T * z - 5
if x[i] > t then report i - 6
remove one copy of x[i - G - h] from w; insert x[i - G] into w in order - 7
remove 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 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 , so , with two targets of 30 and 24 at cells 7 and 10. Use , , and . The root of is . Cells 5 to 12 have a full window. The last column gives the threshold of cell-averaging CFAR with the same window and , which is times the sum.
| lagging | leading | sorted window | 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 , is the sorted list of the multiset of the reference values of cell . Line L1 sets it. The windows of and 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 , 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 of a Swerling 1 target, and the bound on interferers: if at most reference cells hold interference, is at most the -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 , one power value per range cell. is the even number of reference cells, the number of guard cells on each side, the rank with and the factor. For a cell with , the reference window is
Let be the multiset of the values for , and its -th smallest element, counted with multiplicity. The detector reports cell exactly when .
Lemma 1 (the sorted window). If , then at the start of the iteration for cell of the loop in line L2, the list is sorted and holds the multiset .
Proof. By induction on .
Base, . Line L1 sorts the values of the cells of , so is sorted and holds .
Step. Assume the claim for . As in the proof for CA-CFAR, is without the cells and , and with the cells and . The two cells that leave are different, and both are in . So
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 is the same as removing the cell . Line L6 removes one copy of , which is in , and inserts . Line L7 removes one copy of and inserts . The value is still in when line L7 runs, because line L6 removed one copy of a different cell's value and 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, is sorted and holds .
Theorem 1 (the output). For every input, the detector reports exactly the cells with and , in increasing order.
Proof. The loop visits in order. By Lemma 1, is the sorted list of , so the element read by line L3 (index from 0) is . Lines L4 and L5 compare with .
Lemma 2 (the spacings of exponential order statistics). Let be independent and exponential with mean , with order statistics , and put . Then the spacings , , are independent, and is exponential with mean .
Proof. The joint density of the order statistics is on . The map from to the spacings is linear with a triangular matrix of ones on the diagonal, so its Jacobian is 1, and it maps the ordered region onto . Each is , so , because is part of . With the joint density of the spacings is
a product of exponential densities with means .
Theorem 2 (constant false alarm rate). Assume that the cell under test and its reference cells are independent and exponential with the same mean . Then
which does not depend on . falls strictly from 1 to 0 as goes from 0 to , so each in has exactly one .
Proof. By Lemma 2, with independent exponential of means . The cell under test is independent of the window, and given , . So
by the transform of an exponential of mean . Put to get the product of the statement. Each factor is positive, equals 1 at , falls strictly in and goes to 0, so the product does the same.
The product equals Rohling's closed form for integer . Write and .
Theorem 3 (detection of a Swerling 1 target). If the cell under test is exponential with mean and the reference cells are as in Theorem 2, then .
Proof. Given , . This is the computation of Theorem 2 with in place of .
Theorem 4 (interfering targets). Assume that at most reference cells of hold interference, with any values, and let be the sorted values of the other cells. Then . If moreover every interfering value is at least , then , the same value as in a window of the clean cells alone.
Proof. The cells with the values are cells of the window with values at most . So at least elements of are at most , and the -th smallest is at most . If every interfering value is at least , every element of below is one of , so fewer than elements are below and .
So up to strong interferers in the window cannot raise the threshold above . For CA-CFAR, one interferer of power adds to the sum and raises the threshold without a limit.
Complexity
Time. Line L1 sorts values in . In each of the iterations, the four searches of lines L6 and L7 take comparisons, but each insertion or deletion in an array list moves the elements after its position, up to of them. On random input the average move is about . So the loop costs in the worst and the average case, and in all cases. The tests compare the sliding window with a fresh sort of each window, which costs . With a balanced binary search tree or an order statistic tree that stores subtree sizes, each step is and the total is . Computing from scratch with quickselect costs expected per cell.
Space. for the sorted window, beyond the input and the output.
Properties
- Constant false alarm rate (theorem, homogeneous exponential noise). , independent of the noise power. For integer it equals Rohling's form , and the tests check the two forms exactly for all , and .
- The factor (closed form). At : for , ; for , ; for , . These match Rohling's Table II to the printed decimal.
- The loss. The average threshold is 27.19 for , , against 21.94 for CA-CFAR: 0.93 dB more. For a Swerling 1 target at , OS needs 24.08 dB and CA needs 23.15 dB.
- Robust to interfering targets (theorem). Up to reference cells can hold any values, and the threshold is still at most times the -th smallest clean value. For CA-CFAR one interferer of power adds to the sum, with no limit.
- Scale invariant (theorem). Multiplying all cells by multiplies by , so no decision changes.
Variants and improvements
- The choice of . Rohling's average threshold table uses , a common choice. A larger lowers the loss in homogeneous noise but tolerates fewer interferers. A smaller 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 smallest and largest values and sum the rest. With and it is CA, and with and it is OS.
- Censored mean. Drop the largest values and average the 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 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]. Readingw[k]takes the -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 . 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. comes from the product , not from , and it multiplies one cell, not a sum. For and , for , while the CA factor on the sum is 1.37 and on the mean is 21.94.
- More interferers than . With , line L3 takes the maximum, and one interferer sets the threshold. In the tests, interferers of make the threshold .
- Clutter edges. If the clutter fills more than 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 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.
# 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 and the average threshold for several and , 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
- 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)
- Analysis of CFAR processors in nonhomogeneous background, the whole paper (CA and OS processors at clutter edges and with interfering targets)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3GCSWG Edit this page History Report an error Markdown