Algorithmcore
Energy detector
Also called radiometer, Urkowitz energy detector.
Declares a signal present when the energy of the received samples over a window exceeds a threshold set by the noise level.
- Solves
- Spectrum sensing
- Time
- O(N) worst
- Space
- O(1) extra
- Where
- N = the number of samples
- Model
- Real RAM
- Properties
- deterministicexact false alarm rateneeds noise powernot needs signal knowledge
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Harry Urkowitz, 1967
The energy detector, or radiometer, decides whether a band holds a signal by adding the energy of received samples and comparing the sum with a threshold. It needs no knowledge of the signal: not its waveform, its modulation or its timing, only the noise power , which sets the threshold. With complex Gaussian noise, the normalized energy has a gamma law under noise only, so the threshold for a target false alarm rate can be computed exactly. The detector is the likelihood ratio test for a white Gaussian signal of any power, and the generalized likelihood ratio test for a fully unknown signal. It is the standard first test for spectrum sensing. Its two weak points are that the number of samples grows like , against for a matched filter, and that an error in shifts the threshold, which creates an SNR wall below which no number of samples is enough.
In plain words
To find out whether someone is sending in a radio band, the receiver listens for a short time and adds up how much energy it picked up. If there is only noise, the total is close to a known value. If someone is sending, the total is larger. The receiver compares the total with a limit chosen so that noise alone passes it only rarely, for example once in twenty tries. Above the limit, it says a signal is present. The method needs no idea of what the signal looks like. But it must know how strong the noise is. If it gets the noise level a little wrong, very weak signals can never be told apart from noise, however long it listens.
The problem
The receiver has complex baseband samples. Under , with independent and known. Under , , where nothing is known about except that it is independent of the noise. The SNR is the signal power per sample over . For a target false alarm rate , decide between and with exactly, and report the detection probability for the signals of interest.
The algorithm
ENERGY-DETECTOR(y[0..N-1], σ², P_fa)- 1
λ ← the root of e^{-λ} Σ_{k<N} λ^k / k! = P_fa - 2
T ← 0 - 3
for n ← 0 to N - 1 do T ← T + |y[n]|² - 4
T ← T / σ² - 5
if T > λ then return "signal present" - 6
return "noise only"
Line L1 depends only on and , so it is computed once and stored. The left side decreases in , from at to , so bisection finds the root. For large , the central limit theorem gives .
Example
Take samples and . Line L1 gives : under noise only, has mean and standard deviation , and the threshold is standard deviations above the mean.
| SNR | , Gaussian signal | , QPSK signal |
|---|---|---|
| dB | 0.3235 | 0.3213 |
| dB | 0.8752 | 0.9104 |
| dB | 0.9998 | 1.0000 |
With the threshold is , and at dB the detection probabilities rise to and . A signal of constant power (QPSK) is a little easier to detect than a Gaussian one of the same mean power at medium SNR, because its energy does not fluctuate.
Samples for a target. For and with a Gaussian signal, the normal approximation gives , , and samples at , , and dB. With the exact threshold, these sample counts give between and .
The SNR wall. Suppose the true noise power is only known to lie in , with for an uncertainty of dB. To keep for every noise level, the threshold must assume . A signal of power in the smallest noise gives above this only if . For dB the wall is , or dB. With samples and , a Gaussian signal at dB, just below the wall, is detected with probability below in the smallest noise, while at dB it is detected with probability above .
Correctness
Claim. Under , has the law, , and so the detector has false alarm rate exactly . With a complex Gaussian signal of SNR , white and independent of the noise, . With a fixed signal of total energy , .
Key steps. For , is half a chi-square with degrees of freedom, which is a unit exponential. The sum of independent unit exponentials is : it is the time of the -th event of a Poisson process of rate , so it exceeds exactly when fewer than events fall in , which has probability . The tail is continuous and strictly decreasing, so the root of line L1 gives the exact rate. With a Gaussian signal, , and the same argument applies to . With a fixed signal, is a noncentral chi-square with degrees of freedom and noncentrality , whose law is a Poisson mixture of central ones. The full proof is in the proofs folder.
Optimality. For a Gaussian signal with covariance , the log-likelihood ratio is plus a constant, increasing in for every . By the Neyman-Pearson lemma, the energy detector is the most powerful test at its , uniformly in .
Proof: Correctness of the energy detectorfull
We prove that the threshold of line L1 gives the false alarm rate exactly, derive the detection probability for a Gaussian signal and for a fixed signal, show that the energy detector is the most powerful test for a white Gaussian signal, and derive the normal-approximation sample count and the SNR wall.
Setting. The receiver has . Under , with the independent and . The statistic is , and the detector declares a signal when . Write for .
Lemma 1 (one sample)
If , then has the unit exponential law.
Proof. Write with and independent standard normal. Then . The pair has density in polar coordinates , so . Hence for .
Lemma 2 (the sum)
If are independent unit exponentials, then for all .
Proof. By induction on . For , . Suppose it holds for , and let , with density . Differentiating, , since the sum telescopes, so . Then
Theorem 1 (exact false alarm rate)
Under , . The function is continuous and strictly decreasing on , from to , so for each line L1 has exactly one root, and the detector has false alarm rate exactly .
Proof. The terms are independent unit exponentials by Lemma 1, so the first claim is Lemma 2. , as because each term does, and for . By the intermediate value theorem, has exactly one root.
The bisection of the code keeps the invariant , which holds at the start since and is far in the tail, so the root stays in as the interval halves.
Theorem 2 (Gaussian signal)
Let with independent , independent of the noise. Then .
Proof. A sum of independent circular complex Gaussian variables is circular complex Gaussian with the sum of the variances, so , independent over . By Lemmas 1 and 2 applied with , has tail , and .
Since decreases, increases in and is above for every .
Theorem 3 (fixed signal)
Let with fixed and . Then
Proof. Rotate the coordinates. Let be a unitary matrix whose first row is (if the claim is Theorem 1). The noise is circular white, so has the same law as , and with . So with independent , and the law of depends on only through .
For the first term, write . The density of at is, by integrating the Gaussian density over the circle of radius ,
using . So is a Poisson mixture: given with , is . Adding the other unit exponentials, independent of , gives by Lemma 2, and the formula follows by total probability.
The code sums up to ; the Poisson weights beyond this are below , and each . It updates , which is the definition of .
Theorem 4 (optimality for a Gaussian signal)
For a known , the most powerful test of against the Gaussian signal of Theorem 2 at false alarm rate is . Since this test does not depend on , it is uniformly most powerful over .
Proof. The densities are with and . The log-likelihood ratio is
a strictly increasing function of . By the Neyman-Pearson lemma, the most powerful test at level rejects when this ratio exceeds a constant, that is, when , and the level fixes by Theorem 1. Since has a continuous law, no randomization is needed.
Proposition 5 (sample count by the normal approximation)
Under , has mean and variance ; under the Gaussian signal of Theorem 2, mean and variance . Approximating both laws by normal laws, the smallest that reaches and is
Proof. A unit exponential has mean and variance , so the moments follow from Theorem 2. With normal laws, the threshold for is , and . Setting this to gives , and dividing by gives .
For small , , which is the law. This is an approximation; the test file checks that with the exact threshold these sample counts give within of the target at the four SNRs of the page.
Proposition 6 (SNR wall)
Suppose the true noise power is only known to lie in for some , and the threshold must keep the false alarm rate at most for every noise power in that interval. Let the signal be Gaussian with power . If , then as when the true noise is ; if , then for every noise power in the interval.
Proof. With the statistic normalized by the nominal , under with true noise , , and is largest for . So the threshold must be , where is the root of Theorem 1, and by the law of large numbers. With the signal and true noise , almost surely, by the law of large numbers, while . If , then ; if it is , then . The left side is smallest at , which gives the wall .
For (1 dB), the wall is , or dB. The test file checks the finite case , : at dB, below the wall, in the smallest noise, and at dB, above it, .
The tail computation
The code computes with . The ratio is above for and below after, so the largest term with is at . The code computes with the log-gamma function, sums the ratios outward from in both directions by the recurrence, and multiplies. Every ratio is at most , so there is no overflow, and the walk stops when a ratio drops below of the running sum. In each direction the step ratios and decrease, so the neglected terms are bounded by a geometric series that starts below of the sum. For the sizes in the tests this is far below the rounding error of double precision.
Complexity
In the real RAM, lines L2 to L5 take squared magnitudes and additions: time and extra space, and the statistic can be updated as samples arrive. The threshold of line L1 takes per evaluation of the tail, or if the sum starts at its largest term, times about steps of bisection, once for each pair . In hardware, the energy of a band is often computed from FFT bins, as a sum of periodogram values, at for all subbands at once.
Properties
- Blind. It needs no knowledge of the signal: modulation, bandwidth inside the band, timing and carrier phase can all be unknown.
- Exact false alarm rate. With known and white Gaussian noise, the threshold gives exactly for every .
- Optimal for Gaussian signals. It is the most powerful test for a white Gaussian signal of any power, and the generalized likelihood ratio test for an unknown deterministic signal.
- Slow at low SNR. For fixed and , the number of samples grows like , because the signal shifts the mean of by while its standard deviation is .
- Not robust to noise power errors. An error of a factor in creates the SNR wall .
Variants and improvements
- Real-valued samples. For real samples with noise , is chi-square with degrees of freedom; Urkowitz's model of a record of time and bandwidth has about degrees of freedom.
- Estimated noise power. Estimate from a band known to be empty, or from reference cells as in CFAR detection; the threshold then follows an F law, and the SNR wall moves with the quality of the estimate.
- Frequency-domain energy. Sum the periodogram over the bins of a subband to test many subbands at once, or weight the bins by the expected signal spectrum, which brings the test closer to the likelihood ratio test for a colored signal.
- Two-stage sensing. Use the energy detector to find candidate bands quickly, then a cyclostationary feature detector or a matched filter on those bands.
- Fading and diversity. Average over the fading law, or combine the energies of several antennas or sensors; combining the energies of sensors is an energy detector with samples.
When to use it
Use it when nothing reliable is known about the signal and the noise power is well calibrated, for example for listen-before-talk in unlicensed bands, for a first scan of wide bands, or when the SNR is moderate. When a pilot or preamble is known, a matched filter needs far fewer samples. When the noise power is uncertain and the SNR is low, use a test that does not depend on it, such as a cyclostationary or eigenvalue test.
Pitfalls
- Wrong noise power. A noise estimate that is dB too low raises far above its target; one that is too high hides weak signals. Calibrate often, as it drifts with temperature and gain.
- Colored noise and interference. The threshold assumes white Gaussian noise; spurs, adjacent-channel leakage and impulsive interference all look like signal.
- Long records do not fix everything. Below the SNR wall, more samples do not help, and the time variation of the noise limits how long a record is useful.
- Signals that only occupy part of the band or the record. A narrow or bursty signal adds little to the total energy; split the band or the record into pieces and test each.
- Real versus complex samples. The threshold for complex samples uses ; for real samples it uses chi-square with degrees of freedom. Mixing the two gives the wrong .
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)
energy_detector.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/energy-detector/. The authors are listed in prov/T2T7RR.jsonl.
"""The energy detector (radiometer) for complex baseband samples.
The receiver takes N samples y[0..N-1] with complex Gaussian noise CN(0, s2)
of known power s2. It computes T = sum |y[n]|^2 / s2 and declares a signal
present when T > lam. Under noise only, T is a sum of N independent unit
exponentials, so T ~ Gamma(N, 1) and
P_fa = P(T > lam) = e^(-lam) sum_{k < N} lam^k / k!.
The threshold lam is the root of this equation for the target P_fa. With a
complex Gaussian signal of SNR snr, T / (1 + snr) ~ Gamma(N, 1). With a fixed
signal of total energy mu * s2, T is a noncentral gamma variable, a Poisson
mixture of Gamma(N + j, 1) laws with weights Poisson(j; mu).
"""
import math
from cbb import qinv
def gamma_tail(n: int, x: float) -> float:
"""P(Gamma(n, 1) > x) = e^(-x) sum_{k < n} x^k / k!.
The terms x^k / k! grow while k < x and then shrink, so the sum starts at the
largest term k = min(n - 1, floor(x)), computed in the log domain, and walks away
from it in both directions with the ratio x / k until the terms are negligible.
"""
if n < 1:
raise ValueError("n must be at least 1")
if x <= 0.0:
return 1.0
m = min(n - 1, int(x))
log_top = -x + m * math.log(x) - math.lgamma(m + 1)
s, t = 1.0, 1.0
for k in range(m + 1, n):
t *= x / k
s += t
if t < 1e-18 * s:
break
t = 1.0
for k in range(m, 0, -1):
t *= k / x
s += t
if t < 1e-18 * s:
break
return min(1.0, math.exp(log_top) * s)
def threshold(n: int, pfa: float) -> float:
"""The lam with gamma_tail(n, lam) = pfa, by bisection (gamma_tail decreases in lam)."""
if not 0.0 < pfa < 1.0:
raise ValueError("pfa must be in (0, 1)")
lo, hi = 0.0, n + 40.0 * math.sqrt(n) + 100.0
for _ in range(200):
mid = 0.5 * (lo + hi)
if gamma_tail(n, mid) > pfa:
lo = mid
else:
hi = mid
if hi - lo <= 1e-13 * hi:
break
return 0.5 * (lo + hi)
def statistic(y: list[complex], noise_var: float) -> float:
"""T = sum |y[n]|^2 / noise_var."""
if noise_var <= 0.0:
raise ValueError("noise_var must be positive")
t = 0.0 # @line L2
for v in y: # @line L3
t += v.real * v.real + v.imag * v.imag
return t / noise_var # @line L4
def energy_detect(y: list[complex], noise_var: float, pfa: float) -> tuple[bool, float, float]:
"""Run the detector. Return (signal present, T, lam)."""
lam = threshold(len(y), pfa) # @line L1
t = statistic(y, noise_var)
if t > lam: # @line L5
return True, t, lam
return False, t, lam # @line L6
def pd_gaussian(n: int, snr: float, lam: float) -> float:
"""P_d for a complex Gaussian signal of SNR snr per sample: P(Gamma(n, 1) > lam / (1 + snr))."""
return gamma_tail(n, lam / (1.0 + snr))
def pd_deterministic(n: int, mu: float, lam: float) -> float:
"""P_d for a fixed signal with sum |s[n]|^2 / noise_var = mu, as a Poisson mixture of gamma tails.
2T is noncentral chi-square with 2n degrees of freedom and noncentrality 2 mu, and
P(T > lam) = sum_j e^(-mu) mu^j / j! * gamma_tail(n + j, lam).
"""
if mu < 0.0:
raise ValueError("mu must be nonnegative")
if mu == 0.0:
return gamma_tail(n, lam)
jmax = int(mu + 12.0 * math.sqrt(mu) + 40.0)
tail = gamma_tail(n, lam)
total = 0.0
lx, lm = math.log(lam) if lam > 0 else -math.inf, math.log(mu)
for j in range(jmax + 1):
total += math.exp(-mu + j * lm - math.lgamma(j + 1)) * tail
# gamma_tail(n + j + 1, lam) = gamma_tail(n + j, lam) + e^(-lam) lam^(n + j) / (n + j)!
if lam > 0:
tail = min(1.0, tail + math.exp(-lam + (n + j) * lx - math.lgamma(n + j + 1)))
return min(1.0, total)
def clt_samples(snr: float, pfa: float, pd: float) -> float:
"""The normal-approximation sample count for a complex Gaussian signal.
Under H0, T has mean N and variance N; under H1, mean N (1 + snr) and variance N (1 + snr)^2.
Equating the threshold N + sqrt(N) Q^-1(pfa) = N (1 + snr) + sqrt(N) (1 + snr) Q^-1(pd)
gives N = ((Q^-1(pfa) - (1 + snr) Q^-1(pd)) / snr)^2.
"""
if snr <= 0.0:
raise ValueError("snr must be positive")
return ((qinv(pfa) - (1.0 + snr) * qinv(pd)) / snr) ** 2
def snr_wall(uncertainty_db: float) -> float:
"""The SNR wall rho - 1 / rho (linear) for noise power known within a factor rho = 10^(x / 10)."""
rho = 10.0 ** (uncertainty_db / 10.0)
return rho - 1.0 / rho
test_energy_detector.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/energy-detector/. The authors are listed in prov/T2T7RR.jsonl.
import cmath
import math
import random
import pytest
from cbb import cn, undb, wilson
from energy_detector import (
clt_samples,
energy_detect,
gamma_tail,
pd_deterministic,
pd_gaussian,
snr_wall,
statistic,
threshold,
)
def simpson(f, a: float, b: float, steps: int = 4000) -> float:
h = (b - a) / steps
s = f(a) + f(b)
for i in range(1, steps):
s += (4 if i % 2 else 2) * f(a + i * h)
return s * h / 3
def test_gamma_tail_small_cases() -> None:
for x in (0.1, 1.0, 5.0, 30.0):
assert gamma_tail(1, x) == pytest.approx(math.exp(-x), rel=1e-12)
assert gamma_tail(2, x) == pytest.approx(math.exp(-x) * (1 + x), rel=1e-12)
assert gamma_tail(4, 0.0) == 1.0
# against the integral of the Gamma(5, 1) density x^4 e^(-x) / 24 from 7 to 80
tail = simpson(lambda t: t ** 4 * math.exp(-t) / 24, 7.0, 80.0)
assert gamma_tail(5, 7.0) == pytest.approx(tail, rel=1e-9)
def test_threshold() -> None:
for n in (1, 4, 16, 200, 5000):
for pfa in (0.5, 0.1, 0.01, 1e-4):
lam = threshold(n, pfa)
assert gamma_tail(n, lam) == pytest.approx(pfa, rel=1e-9)
assert threshold(1, 0.05) == pytest.approx(-math.log(0.05), rel=1e-12)
assert threshold(16, 0.05) == pytest.approx(23.0971, abs=1e-4)
with pytest.raises(ValueError):
threshold(4, 0.0)
def test_statistic_and_decision() -> None:
y = [1 + 1j, 2 + 0j, 0 - 1j]
assert statistic(y, 2.0) == pytest.approx((2 + 4 + 1) / 2)
present, t, lam = energy_detect(y, 2.0, 0.05)
assert t == pytest.approx(3.5)
assert present == (t > lam)
def test_false_alarm_rate() -> None:
rng = random.Random(1967)
n, pfa, trials = 16, 0.05, 20000
lam = threshold(n, pfa)
hits = sum(statistic([cn(rng, 2.0) for _ in range(n)], 2.0) > lam for _ in range(trials))
lo, hi = wilson(hits, trials)
assert lo <= pfa <= hi
def test_detection_gaussian_signal() -> None:
rng = random.Random(8)
n, trials = 16, 4000
lam = threshold(n, 0.05)
snr = undb(0.0)
p = pd_gaussian(n, snr, lam)
assert p == pytest.approx(0.8752, abs=1e-4)
hits = sum(statistic([cn(rng, snr) + cn(rng, 1.0) for _ in range(n)], 1.0) > lam for _ in range(trials))
lo, hi = wilson(hits, trials)
assert lo <= p <= hi
def test_detection_fixed_signal() -> None:
rng = random.Random(9)
n, trials = 16, 4000
lam = threshold(n, 0.05)
snr = undb(0.0)
p = pd_deterministic(n, n * snr, lam)
assert p == pytest.approx(0.9104, abs=1e-4)
hits = 0
for _ in range(trials):
# QPSK symbols of power snr: the energy is fixed, the phases are random
s = [math.sqrt(snr) * cmath.exp(1j * math.pi / 4 * (2 * rng.randrange(4) + 1)) for _ in range(n)]
hits += statistic([v + cn(rng, 1.0) for v in s], 1.0) > lam
lo, hi = wilson(hits, trials)
assert lo <= p <= hi
def test_noncentral_mixture() -> None:
lam = threshold(8, 0.1)
assert pd_deterministic(8, 0.0, lam) == pytest.approx(0.1, rel=1e-9)
prev = 0.1
for mu in (0.5, 2.0, 8.0, 32.0):
p = pd_deterministic(8, mu, lam)
assert p > prev
prev = p
# one sample: 2T is noncentral chi-square with 2 degrees of freedom; check by integrating its density
mu, x = 3.0, 4.0
dens = lambda t: math.exp(-t - mu) * sum((mu * t) ** j / math.factorial(j) ** 2 for j in range(60))
assert pd_deterministic(1, mu, x) == pytest.approx(simpson(dens, x, 60.0, 6000), rel=1e-8)
def test_sample_counts() -> None:
table = {-5: 89, -10: 725, -15: 6779, -20: 66354}
for snr_db, n_page in table.items():
snr = undb(snr_db)
n = math.ceil(clt_samples(snr, 0.1, 0.9))
assert n == n_page
lam = threshold(n, 0.1)
assert pd_gaussian(n, snr, lam) == pytest.approx(0.9, abs=0.005)
def test_snr_wall() -> None:
walls = {0.1: -13.367, 0.5: -6.368, 1.0: -3.329, 2.0: -0.205}
for x, w in walls.items():
assert 10 * math.log10(snr_wall(x)) == pytest.approx(w, abs=1e-3)
# threshold set for the worst noise rho s2; the true noise is s2 / rho; Gaussian signal of power snr s2
rho = undb(1.0)
n = 100000
lam = threshold(n, 0.1)
below, above = undb(-4.0), undb(-2.5)
assert gamma_tail(n, lam * rho / (1 / rho + below)) < 1e-6
assert gamma_tail(n, lam * rho / (1 / rho + above)) > 0.999999
History
Urkowitz (1967) gave the first detailed analysis of the energy detector for an unknown deterministic signal in band-limited white Gaussian noise. He used the sampling theorem to write the energy of a record of length and bandwidth as a sum of about squared samples, with a central chi-square law under noise and a noncentral one with a signal, and gave the curves of against SNR. The radiometer itself was older, from radio astronomy and radar. With cognitive radio in the 2000s it became the standard sensing test, and Tandra and Sahai (2008) showed that noise uncertainty gives it an SNR wall.
References
- Harry Urkowitz, Energy detection of unknown deterministic signals, Proceedings of the IEEE 55(4), 1967, pages 523 to 531, the energy of a band-limited record as a sum of about 2TW squared samples, its central and noncentral chi-square laws, and the curves of detection probability against SNR
- Rahul Tandra and Anant Sahai, SNR walls for signal detection, IEEE Journal of Selected Topics in Signal Processing 2(1), 2008, pages 4 to 17, the sample count of the radiometer that grows like 1 over SNR squared, the noise uncertainty model with factor rho, and the SNR wall rho - 1/rho
- Steven M. Kay, Fundamentals of Statistical Signal Processing, Volume II: Detection Theory, Prentice Hall, 1998, Chapter 5 (detection of random signals: the energy detector for a white Gaussian signal and its chi-square performance) and Chapter 7 (the generalized likelihood ratio test for an unknown deterministic signal)
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.
| 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 T2T7RR Edit this page History Report an error Markdown