Algorithmadvanced
Cyclostationary feature detection
Also called cyclic spectrum detection.
Detects a modulated signal from peaks of its spectral correlation at cyclic frequencies, which noise does not have.
- Solves
- Spectrum sensing
- Time
- O(N) worstO(N log N) scan
- Space
- O(1) extraO(N) scan
- Where
- N = the number of samples
- Model
- Real RAM
- Properties
- asymptotic false alarm ratedeterministicneeds cycle frequencynot needs noise power
- Evidence
- Proof sketchCode in 1 languages
- Origin
- William A. Gardner, 1988
Cyclostationary feature detection decides whether a band holds a modulated signal by looking for a correlation that only the signal has. A modulated signal repeats its statistics with the carrier, the symbol rate or the block length: its cyclic autocorrelation is not zero at certain cycle frequencies , while for stationary noise it is zero at every . The detector estimates from samples at a cycle frequency of the signal it looks for, normalizes it by the measured power, and compares the result with a threshold. The statistic does not change when the samples are scaled, so the test needs no noise power, and an error in the noise power does not give it the SNR wall of the energy detector. It also tells signals apart: a BPSK signal has a feature at twice its carrier that QPSK and noise lack. The price is that the cycle frequency must be known or searched, and with exact noise power it needs about to times the samples of the energy detector.
In plain words
Noise has no pattern in time. A radio signal has one: its symbols come at a fixed rate on a fixed carrier, so some products of its samples keep the same phase from sample to sample. The detector multiplies the samples in the way that brings out this pattern, turns them back by the expected phase step, and adds them up. For noise, the terms point in random directions and the sum stays small. For the signal, the terms line up and the sum grows. The detector divides by the measured power, so a louder or quieter receiver gives the same answer. It must know, or search for, the rate of the pattern it looks for.
The problem
The receiver has complex baseband samples . Under , they are white circular complex Gaussian noise of unknown power . Under , they hold a signal plus that noise, and the signal is cyclostationary: for a known cycle frequency and lag , its conjugate cyclic autocorrelation
is not zero. The non-conjugate form uses in place of . For a target false alarm rate , decide between and without knowing .
The algorithm
CYCLIC-FEATURE-DETECT(y[0..N-1], α, τ, P_fa)- 1
λ ← -ln P_fa - 2
R ← 0; M ← N - τ - 3
for n ← 0 to M - 1 do R ← R + y[n + τ] y[n] e^{-j2παn} - 4
P ← (1/N) Σ_n |y[n]|² - 5
R ← R / M - 6
T ← M |R|² / (c P²), with c = 2 if τ = 0 and c = 1 otherwise - 7
if T > λ then return "signal present" - 8
return "noise only"
For the non-conjugate form, line L3 uses and needs , and . When the carrier, and so , is unknown, compute at all by one DFT of the products and compare the largest with , the threshold on the largest of independent unit exponentials.
Cycle frequencies of common signals. A BPSK signal with has without noise, so the conjugate feature at is at with . This is the same line at twice the carrier that a squaring loop for carrier recovery uses. QPSK has no conjugate feature at , because the square of a QPSK symbol is with mean zero. An OFDM signal with a cyclic prefix of samples on blocks of has a non-conjugate feature at lag and cycle frequencies , because each prefix sample repeats a sample positions later.
Example
Without noise. Take eight BPSK samples , with carrier and symbols . At and , each term of line L3 is , so , and . For , , and the detector declares a signal. At the wrong cycle frequency , the terms are , which add to zero over eight samples, and .
With noise. For BPSK at and large , is about with complex Gaussian of unit variance and mean , where , and is the SNR. The table gives for , next to the energy detector with the exact noise power:
| SNR | energy detector, / / | |||
|---|---|---|---|---|
| dB | 0.973 | 1.000 | 1.000 | 1.000 / 1.000 / 1.000 |
| dB | 0.378 | 0.945 | 1.000 | 0.731 / 0.997 / 1.000 |
| dB | 0.091 | 0.235 | 0.744 | 0.199 / 0.463 / 0.921 |
For and , the cyclic test needs , and samples at , and dB, against , and for the energy detector. Both grow like . But if the noise power is only known within dB, the energy detector cannot reach any SNR below dB, while the cyclic test is not changed at all.
Correctness
Claim. Under , as , tends in law to a unit exponential, so , for every noise power. Under with , grows like , and .
Key steps. Under , the terms have mean zero, since circular noise has and distinct samples are independent. They are uncorrelated with each other, and : for , , and for , the two factors are independent. They are also circular. The sequence is -dependent, so the central limit theorem for -dependent sequences gives , whose squared magnitude is a unit exponential. The law of large numbers gives , and so has the same limit. Under , and tends to the total power, so tends to a positive constant. Scaling by any multiplies and by , so does not depend on the noise power. The full proof is in the proofs folder.
Proof: Correctness of cyclostationary feature detectionfull
We prove that the statistic does not depend on the noise power, that under white circular Gaussian noise it tends in law to a unit exponential, so the threshold gives false alarm rate in the limit, that a signal with a nonzero cyclic autocorrelation is detected with probability tending to , and that the DFT scan computes the same estimates at the grid frequencies.
Setting. For samples , a cycle frequency and a lag , let and
where in the conjugate form and in the non-conjugate form, which requires . The statistic is , with for the conjugate form at and otherwise, and if .
Lemma 1 (scale invariance)
For every complex , the samples give the same .
Proof. Each is multiplied by (conjugate form) or by (non-conjugate form), so is multiplied by . is multiplied by , so is multiplied by , and the ratio does not change.
So under the law of is the same for every noise power , and we may take .
Lemma 2 (moments under noise)
Let the be independent . Then for all in : , , , and .
Proof. A circular variable has , , , and . In general, a moment is zero unless , because and have the same law, which multiplies the moment by for every .
Each expectation is a product, over the distinct indices involved, of such moments of independent variables. It is zero unless, at each index, the number of unconjugated factors equals the number of conjugated ones.
- : for , the factor is alone at its index. For (conjugate form), the moment is .
- with : the index carries an unconjugated factor from . To balance it, must supply a conjugated factor at . Its conjugated factors sit at , and, in the conjugate form, at . In the non-conjugate form, the factor of at is unconjugated. So balance needs the conjugate form and with . Then the index carries the unconjugated from , and has conjugated factors only at and , both above . So nothing balances it. For , has and has no factor at .
- and : in the conjugate form, all factors are unconjugated, so the moment is zero. In the non-conjugate form, has unconjugated factors at and , and conjugated ones at and . Balance needs as multisets, which is impossible for since the largest index appears only on the left.
- : for , it is . For (conjugate form), it is .
Theorem 3 (false alarm rate)
Under , as with and fixed, tends in law to a unit exponential, and .
Proof. By Lemma 1, take . Write . By Lemma 2, and for all , which gives and . The sequence is -dependent, since is a function of and only, and its terms are bounded in fourth moment uniformly in . The rotation changes neither the moments of Lemma 2 nor the dependence. By the central limit theorem for -dependent sequences, applied to every fixed real combination and then by the Cramér-Wold device, the vector tends to two independent standard normals. Hence tends to , and tends to a unit exponential (Lemma 1 of the energy detector proof: for is a unit exponential).
Now . By the law of large numbers, almost surely, so by Slutsky's theorem tends in law to the same unit exponential. The exponential law is continuous, so for every , and for .
Theorem 4 (detection)
Suppose that under the estimate converges, , and , both in probability. Then in probability, and the detection probability at any fixed threshold tends to .
Proof. in probability, and .
For BPSK, with , , and independent . Take the conjugate form, and . Then and for every . The other two terms have mean zero and are independent over given , with bounded variance, so their average tends to zero, and , with . Also . Theorem 4 applies.
The large- detection probability used on the page. Given and , the sum is plus the sum of , rotated. Those terms are circular, with variance each, and uncorrelated with each other, since . Approximating the noise sum by a complex Gaussian and by , with ,
For , (Theorem 3 of the energy detector proof with ). This is an approximation, not an exact law. The test file checks it against a simulation at and dB within a Wilson interval.
Proposition 5 (the scan)
Let for and , so . Then is the estimate at , for every .
Proof. Substitute in the definition of .
Under , the are uncorrelated with equal variance, since by Lemma 2 and the orthogonality of the DFT. If the statistics were independent unit exponentials, the largest would exceed with probability , and setting this to gives the scan threshold of the page. The bins are uncorrelated but only approximately independent and exponential at finite , so this threshold is an approximation; the test file checks that the rate under noise does not exceed for .
The code
The code updates the rotation by multiplying by at each step, which equals up to rounding that grows like times the unit roundoff. The test file checks the direct sum against the DFT at all grid frequencies to .
Complexity
In the real RAM, one cycle frequency and one lag take time: lines L3 and L4 each pass over the samples once, and the rotation is updated by one multiplication per sample. The extra space is . A scan over all cycle frequencies is one DFT of the products, with the FFT; the reference code uses the direct DFT. A full spectral correlation map over many cycle frequencies and many lags or frequency bins costs much more, which is why practical detectors test a few known features.
Properties
- No noise power needed. is invariant to scaling of the samples, so the threshold holds for any white noise level, and an error in the noise power gives no SNR wall.
- Asymptotic false alarm rate. The rate tends to as grows. At finite , by the Cauchy-Schwarz inequality, so its far tail is lighter than the exponential law. In simulations with and samples, the scan over all bins had a false alarm rate below its target of .
- Selective. It reacts only to signals with a feature at the tested , so it can tell BPSK from QPSK, or a primary user from other users of the band with different symbol rates or carriers.
- Slower than the energy detector with exact noise power. The sample count also grows like , with a constant about to times larger in the cases above.
Variants and improvements
- Several lags and frequencies. Dandawate and Giannakis test a vector of cyclic correlations at several lags with an estimated covariance; the statistic is asymptotically chi-square with twice the number of lags as degrees of freedom.
- Spectral correlation. Estimate the spectral correlation density , the Fourier transform of in , by the FFT accumulation method or the strip spectral correlation analyzer, and look for peaks off the line .
- Non-conjugate features. For signals without conjugate features, such as QPSK or OFDM, use the non-conjugate form at the symbol rate, which needs pulse shaping with excess bandwidth, or at the block rate of a cyclic prefix.
- Pilot and preamble features. Some standards add a feature on purpose, for example a repeated pilot pattern, so that a detector can find the signal at low SNR.
- Two-stage sensing. Use the energy detector to find candidate bands, then a feature detector to confirm and classify them.
When to use it
Use it when the noise power is uncertain or drifts, when the signal of interest has a known feature, or when the detector must separate the signal from other signals in the same band. For a single wideband scan with a well calibrated noise floor, the energy detector is simpler and needs fewer samples. When a full known preamble is present, a matched filter needs fewer samples than both.
Pitfalls
- Cycle frequency errors. An error in makes the terms rotate by per sample, and the sum cancels once is about . A carrier offset of the receiver moves the conjugate feature of BPSK by twice the offset. Search a small range of , with the scan threshold.
- Colored noise and interference with features. The threshold assumes white noise. Spurs, narrowband interferers and adjacent signals can have features at the same .
- Wrong form. QPSK and most higher-order signals have no conjugate feature at ; a test for one will not see them.
- Small samples. The exponential law is a large- result. Check the rate by simulation for the and in use, especially for small .
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)
cyclostationary_feature_detection.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cyclostationary-feature-detection/. The authors are listed in prov/XYTR6D.jsonl.
"""Cyclostationary feature detection from the cyclic autocorrelation.
For samples y[0..N-1], a cycle frequency alpha (in cycles per sample) and a lag
tau >= 0, the conjugate cyclic autocorrelation estimate is
R = (1 / N') sum_{n < N'} y[n + tau] y[n] e^(-j 2 pi alpha n), N' = N - tau,
and the non-conjugate one uses conj(y[n]) in place of y[n]. With P = (1 / N)
sum |y[n]|^2, the statistic is T = N' |R|^2 / (c P^2), with c = 2 for the
conjugate form at tau = 0 and c = 1 otherwise. Under white circular complex
Gaussian noise of any power, T tends to a unit exponential law as N grows, so
the threshold -ln(P_fa) needs no noise power. A BPSK signal on a carrier f_c
has a conjugate feature at alpha = 2 f_c, tau = 0, which noise does not have.
"""
import cmath
import math
from cbb import dft
def _product(y: list[complex], n: int, tau: int, conjugate: bool) -> complex:
return y[n + tau] * (y[n] if conjugate else y[n].conjugate())
def _check(y: list[complex], tau: int, conjugate: bool) -> int:
if tau < 0 or tau >= len(y):
raise ValueError("need 0 <= tau < len(y)")
if tau == 0 and not conjugate:
raise ValueError("the non-conjugate form needs tau >= 1")
return len(y) - tau
def cyclic_autocorrelation(y: list[complex], alpha: float, tau: int, conjugate: bool = True) -> complex:
"""The estimate R of the cyclic autocorrelation at cycle frequency alpha and lag tau."""
m = _check(y, tau, conjugate)
r = 0j # @line L2
step = cmath.exp(-2j * math.pi * alpha)
rot = 1 + 0j # e^(-j 2 pi alpha n), updated by one multiplication per sample
for n in range(m): # @line L3
r += _product(y, n, tau, conjugate) * rot
rot *= step
return r / m # @line L5
def cyclic_statistic(y: list[complex], alpha: float, tau: int, conjugate: bool = True) -> float:
"""T = N' |R|^2 / (c P^2), where P is the mean power of y. It does not change if y is scaled."""
m = _check(y, tau, conjugate)
r = cyclic_autocorrelation(y, alpha, tau, conjugate)
p = sum(v.real * v.real + v.imag * v.imag for v in y) / len(y) # @line L4
if p == 0.0:
return 0.0
c = 2.0 if conjugate and tau == 0 else 1.0
return m * abs(r) ** 2 / (c * p * p) # @line L6
def cyclic_detect(
y: list[complex], alpha: float, tau: int, pfa: float, conjugate: bool = True
) -> tuple[bool, float, float]:
"""Test one cycle frequency and lag. Return (signal present, T, threshold)."""
if not 0.0 < pfa < 1.0:
raise ValueError("pfa must be in (0, 1)")
lam = -math.log(pfa) # @line L1
t = cyclic_statistic(y, alpha, tau, conjugate)
if t > lam: # @line L7
return True, t, lam
return False, t, lam # @line L8
def cyclic_scan(y: list[complex], tau: int, conjugate: bool = True) -> list[complex]:
"""R at all cycle frequencies alpha = k / N' for k = 0..N'-1, from one DFT of the lag products."""
m = _check(y, tau, conjugate)
return [v / m for v in dft([_product(y, n, tau, conjugate) for n in range(m)])]
def scan_threshold(pfa: float, bins: int) -> float:
"""The threshold on the largest of `bins` independent unit exponentials with false alarm rate pfa.
P(max > lam) = 1 - (1 - e^(-lam))^bins, so lam = -ln(1 - (1 - pfa)^(1 / bins)).
"""
if not 0.0 < pfa < 1.0 or bins < 1:
raise ValueError("need 0 < pfa < 1 and bins >= 1")
return -math.log(-math.expm1(math.log1p(-pfa) / bins))
def scan_detect(
y: list[complex], tau: int, pfa: float, conjugate: bool = True
) -> tuple[bool, int, float, float]:
"""Search all cycle frequencies k / N' for an unknown carrier.
Return (signal present, best k, largest T, threshold).
"""
m = _check(y, tau, conjugate)
rs = cyclic_scan(y, tau, conjugate)
p = sum(v.real * v.real + v.imag * v.imag for v in y) / len(y)
c = 2.0 if conjugate and tau == 0 else 1.0
ts = [m * abs(r) ** 2 / (c * p * p) if p > 0.0 else 0.0 for r in rs]
k = max(range(m), key=lambda i: ts[i])
lam = scan_threshold(pfa, m)
return ts[k] > lam, k, ts[k], lam
def _ncx_tail(mu: float, x: float) -> float:
"""P(|Z|^2 > x) for Z ~ CN(sqrt(mu), 1), as a Poisson mixture of Gamma(j + 1, 1) tails."""
if x <= 0.0:
return 1.0
if mu <= 0.0:
return math.exp(-x)
# The Poisson weights outside [jlo, jhi] are negligible. If jlo is far above x, every
# Gamma(j + 1, 1) tail with j >= jlo is 1 to double precision.
spread = 12.0 * math.sqrt(mu) + 40.0
jlo = max(0, int(mu - spread))
jhi = int(mu + spread)
if jlo < x + 12.0 * math.sqrt(x) + 40.0:
jlo = 0
lmu, lx = math.log(mu), math.log(x)
total = 0.0
tail = 1.0 if jlo > 0 else math.exp(-x) # P(Gamma(jlo + 1, 1) > x)
for j in range(jlo, jhi + 1):
total += math.exp(-mu + j * lmu - math.lgamma(j + 1)) * tail
if tail < 1.0:
# P(Gamma(j + 2, 1) > x) = P(Gamma(j + 1, 1) > x) + e^(-x) x^(j + 1) / (j + 1)!
tail = min(1.0, tail + math.exp(-x + (j + 1) * lx - math.lgamma(j + 2)))
return min(1.0, total)
def pd_bpsk(n: int, snr: float, pfa: float) -> float:
"""The large-N detection probability of the conjugate test at alpha = 2 f_c, tau = 0, for BPSK.
The BPSK signal sqrt(S) a[n] e^(j (2 pi f_c n + phi)) with a[n] = +-1 has y^2 terms with mean
S e^(j 2 phi) e^(j 2 pi alpha n). The noise part of the sum has variance N (4 S s2 + 2 s2^2), and
P tends to S + s2. With gamma = S / s2 this gives T ~ k |Z|^2, Z ~ CN(sqrt(mu), 1), with
mu = N gamma^2 / (4 gamma + 2) and k = (2 gamma + 1) / (1 + gamma)^2.
"""
if snr < 0.0 or n < 1:
raise ValueError("need snr >= 0 and n >= 1")
mu = n * snr * snr / (4.0 * snr + 2.0)
k = (2.0 * snr + 1.0) / (1.0 + snr) ** 2
return _ncx_tail(mu, -math.log(pfa) / k)
test_cyclostationary_feature_detection.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cyclostationary-feature-detection/. The authors are listed in prov/XYTR6D.jsonl.
import cmath
import math
import random
import pytest
from cbb import cn, undb, wilson
from cyclostationary_feature_detection import (
_ncx_tail,
cyclic_autocorrelation,
cyclic_detect,
cyclic_scan,
cyclic_statistic,
pd_bpsk,
scan_detect,
scan_threshold,
)
def bpsk(rng: random.Random, n: int, power: float, fc: float) -> list[complex]:
"""BPSK symbols, one per sample, on carrier fc with a random phase."""
ph = rng.uniform(0.0, 2.0 * math.pi)
return [math.sqrt(power) * rng.choice((-1, 1)) * cmath.exp(1j * (2 * math.pi * fc * i + ph)) for i in range(n)]
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_page_example() -> None:
# eight noiseless BPSK samples on carrier 1/8: y[n]^2 e^(-j 2 pi n / 4) = 1 for every n
y = [(1 if i % 3 else -1) * cmath.exp(1j * math.pi * i / 4) for i in range(8)]
assert cyclic_autocorrelation(y, 0.25, 0) == pytest.approx(1.0)
present, t, lam = cyclic_detect(y, 0.25, 0, 0.05)
assert t == pytest.approx(4.0)
assert lam == pytest.approx(-math.log(0.05))
assert present
# at the wrong cycle frequency 1/8 the rotations cancel over the eight samples
assert cyclic_statistic(y, 0.125, 0) == pytest.approx(0.0, abs=1e-20)
def test_scan_matches_direct_sum() -> None:
rng = random.Random(3)
y = [cn(rng, 1.0) for _ in range(16)]
rs = cyclic_scan(y, 0)
for k in range(16):
assert rs[k] == pytest.approx(cyclic_autocorrelation(y, k / 16, 0), abs=1e-12)
rs = cyclic_scan(y, 2, conjugate=False)
assert len(rs) == 14
for k in range(14):
assert rs[k] == pytest.approx(cyclic_autocorrelation(y, k / 14, 2, conjugate=False), abs=1e-12)
def test_no_noise_power_needed() -> None:
rng = random.Random(4)
y = [cn(rng, 1.0) for _ in range(40)]
for c in (1e-3, 3.7j, 250.0):
z = [c * v for v in y]
assert cyclic_statistic(z, 0.2, 0) == pytest.approx(cyclic_statistic(y, 0.2, 0), rel=1e-9)
assert cyclic_statistic(z, 0.1, 3, conjugate=False) == pytest.approx(
cyclic_statistic(y, 0.1, 3, conjugate=False), rel=1e-9
)
def test_false_alarm_rate() -> None:
rng = random.Random(5)
n, pfa, trials = 128, 0.1, 1500
lam = -math.log(pfa)
# the conjugate test at tau = 0, noise power 1
hits = sum(cyclic_statistic([cn(rng, 1.0) for _ in range(n)], 0.2, 0) > lam for _ in range(trials))
lo, hi = wilson(hits, trials)
assert lo <= pfa <= hi
# the non-conjugate test at tau = 3, noise power 4, with the same threshold
hits = sum(
cyclic_statistic([cn(rng, 4.0) for _ in range(n)], 0.13, 3, conjugate=False) > lam for _ in range(trials)
)
lo, hi = wilson(hits, trials)
assert lo <= pfa <= hi
def test_bpsk_detection() -> None:
rng = random.Random(6)
n, pfa, trials, fc = 64, 0.1, 1000, 0.1
snr = undb(-5.0)
p = pd_bpsk(n, snr, pfa)
assert p == pytest.approx(0.5074, abs=1e-4)
hits = 0
for _ in range(trials):
y = [v + cn(rng, 1.0) for v in bpsk(rng, n, snr, fc)]
hits += cyclic_detect(y, 2 * fc, 0, pfa)[0]
lo, hi = wilson(hits, trials)
assert lo <= p <= hi
def test_qpsk_has_no_conjugate_feature() -> None:
# QPSK symbols squared are +-j with mean 0, so a strong QPSK signal does not raise T like BPSK does
rng = random.Random(7)
n, pfa, trials, fc = 128, 0.1, 1000, 0.1
power = undb(10.0)
hits_qpsk = hits_bpsk = 0
for _ in range(trials):
q = [
math.sqrt(power) * cmath.exp(1j * (math.pi / 4 * (2 * rng.randrange(4) + 1) + 2 * math.pi * fc * i))
for i in range(n)
]
hits_qpsk += cyclic_detect([v + cn(rng, 1.0) for v in q], 2 * fc, 0, pfa)[0]
for _ in range(100):
hits_bpsk += cyclic_detect([v + cn(rng, 1.0) for v in bpsk(rng, n, power, fc)], 2 * fc, 0, pfa)[0]
lo, hi = wilson(hits_qpsk, trials)
assert hi < pfa
assert hits_bpsk == 100
def test_cyclic_prefix_feature() -> None:
# blocks of 16 Gaussian samples with a cyclic prefix of 4: y[n + 16] conj(y[n]) has period 20
rng = random.Random(8)
body, cp, blocks, trials = 16, 4, 20, 300
hits = 0
for _ in range(trials):
x = []
for _ in range(blocks):
b = [cn(rng, 1.0) for _ in range(body)]
x += b[body - cp :] + b
y = [v + cn(rng, 1.0) for v in x]
hits += cyclic_detect(y, 1 / (body + cp), body, 0.05, conjugate=False)[0]
lo, hi = wilson(hits, trials)
assert lo > 0.5
def test_scan() -> None:
assert scan_threshold(0.1, 1) == pytest.approx(-math.log(0.1))
lam = scan_threshold(0.05, 64)
assert 1 - (1 - math.exp(-lam)) ** 64 == pytest.approx(0.05, rel=1e-12)
rng = random.Random(9)
# unknown carrier 5/64: the feature is at alpha = 10/64
y = [v + cn(rng, 1.0) for v in bpsk(rng, 64, undb(3.0), 5 / 64)]
present, k, t, lam = scan_detect(y, 0, 0.05)
assert present and k == 10
# under noise only, the max over 64 bins keeps the rate at or below P_fa
trials, hits = 400, 0
for _ in range(trials):
hits += scan_detect([cn(rng, 1.0) for _ in range(64)], 0, 0.1)[0]
lo, hi = wilson(hits, trials)
assert lo <= 0.1
def test_noncentral_tail_and_sample_count() -> None:
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 _ncx_tail(mu, x) == pytest.approx(simpson(dens, x, 60.0, 6000), rel=1e-8)
assert _ncx_tail(0.0, 2.0) == pytest.approx(math.exp(-2.0))
assert pd_bpsk(100, 0.0, 0.05) == pytest.approx(0.05)
snr = undb(-10.0)
assert pd_bpsk(1263, snr, 0.1) >= 0.9 > pd_bpsk(1262, snr, 0.1)
def test_errors() -> None:
y = [1 + 0j, 1j, -1 + 0j]
with pytest.raises(ValueError):
cyclic_statistic(y, 0.1, 0, conjugate=False)
with pytest.raises(ValueError):
cyclic_statistic(y, 0.1, 3)
with pytest.raises(ValueError):
cyclic_detect(y, 0.1, 0, 1.0)
History
The theory of cyclostationary signals in communications grew from the work of Gardner and others in the 1970s and 1980s, who showed that modulated signals have spectral correlation at cycle frequencies tied to the carrier and the symbol rate. Gardner (1988) set out feature detection for signal interception, and his 1991 survey listed the features of common modulations. Dandawate and Giannakis (1994) gave asymptotic chi-square tests for the presence of cyclostationarity. With cognitive radio in the 2000s, feature detection became the main alternative to energy detection for spectrum sensing at low SNR.
References
- William A. Gardner, Signal interception: a unifying theoretical framework for feature detection, IEEE Transactions on Communications 36(8), 1988, pages 897 to 906, the cyclic autocorrelation and the spectral correlation density, and detectors that measure them at the cycle frequencies of the signal
- William A. Gardner, Exploitation of spectral redundancy in cyclostationary signals, IEEE Signal Processing Magazine 8(2), 1991, pages 14 to 36, the cycle frequencies of common modulations, among them the conjugate feature at twice the carrier of BPSK, and the tolerance of feature detectors to noise and interference
- Amod V. Dandawate and Georgios B. Giannakis, Statistical tests for presence of cyclostationarity, IEEE Transactions on Signal Processing 42(9), 1994, pages 2355 to 2369, the estimate of the cyclic correlation, its asymptotic normal law, and the chi-square test for a nonzero cyclic correlation at a given cycle frequency
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 XYTR6D Edit this page History Report an error Markdown