Algorithm Search⌘K

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.

Time
O(N) worstO(N log N) scan
Space
O(1) extraO(N) scan
Where
N = the number of samples
Properties
asymptotic false alarm ratedeterministicneeds cycle frequencynot needs noise power
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 Rα(τ)R^\alpha(\tau) is not zero at certain cycle frequencies α\alpha, while for stationary noise it is zero at every α≠0\alpha \ne 0. The detector estimates Rα(τ)R^\alpha(\tau) from NN 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 1.61.6 to 2.12.1 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 NN complex baseband samples y[0],…,y[N−1]y[0], \ldots, y[N-1]. Under H0H_0, they are white circular complex Gaussian noise of unknown power σ2\sigma^2. Under H1H_1, they hold a signal plus that noise, and the signal is cyclostationary: for a known cycle frequency α≠0\alpha \ne 0 and lag τ\tau, its conjugate cyclic autocorrelation

Rα(τ)=lim⁡M→∞1M∑n<ME[y[n+τ] y[n]]e−j2παnR^\alpha(\tau) = \lim_{M \to \infty} \frac{1}{M}\sum_{n < M} \mathbb E\big[y[n + \tau]\, y[n]\big] e^{-j 2\pi \alpha n}

is not zero. The non-conjugate form uses y[n]∗y[n]^* in place of y[n]y[n]. For a target false alarm rate PfaP_{fa}, decide between H0H_0 and H1H_1 without knowing σ2\sigma^2.

The algorithm

  1. CYCLIC-FEATURE-DETECT(y[0..N-1], α, τ, P_fa)
  2. 1λ ← -ln P_fa
  3. 2R ← 0; M ← N - τ
  4. 3for n ← 0 to M - 1 do R ← R + y[n + τ] y[n] e^{-j2παn}
  5. 4P ← (1/N) Σ_n |y[n]|²
  6. 5R ← R / M
  7. 6T ← M |R|² / (c P²), with c = 2 if τ = 0 and c = 1 otherwise
  8. 7if T > λ then return "signal present"
  9. 8return "noise only"

For the non-conjugate form, line L3 uses y[n]∗y[n]^* and needs τ≥1\tau \ge 1, and c=1c = 1. When the carrier, and so α\alpha, is unknown, compute RR at all α=k/M\alpha = k/M by one DFT of the products y[n+τ] y[n]y[n + \tau]\,y[n] and compare the largest TT with λ=−ln⁡(1−(1−Pfa)1/M)\lambda = -\ln\big(1 - (1 - P_{fa})^{1/M}\big), the threshold on the largest of MM independent unit exponentials.

Cycle frequencies of common signals. A BPSK signal S a[n]ej(2πfcn+ϕ)\sqrt S\, a[n] e^{j(2\pi f_c n + \phi)} with a[n]=±1a[n] = \pm 1 has y[n]2=Sej2ϕej2π(2fc)ny[n]^2 = S e^{j2\phi} e^{j 2\pi (2 f_c) n} without noise, so the conjugate feature at τ=0\tau = 0 is at α=2fc\alpha = 2 f_c with ∣R∣=S|R| = S. This is the same line at twice the carrier that a squaring loop for carrier recovery uses. QPSK has no conjugate feature at τ=0\tau = 0, because the square of a QPSK symbol is ±j\pm j with mean zero. An OFDM signal with a cyclic prefix of DD samples on blocks of LL has a non-conjugate feature at lag τ=L\tau = L and cycle frequencies k/(L+D)k/(L + D), because each prefix sample repeats a sample LL positions later.

Example

Without noise. Take eight BPSK samples y[n]=a[n]ejπn/4y[n] = a[n] e^{j\pi n/4}, with carrier fc=1/8f_c = 1/8 and symbols a=(−1,1,1,−1,1,1,−1,1)a = (-1, 1, 1, -1, 1, 1, -1, 1). At α=2fc=1/4\alpha = 2f_c = 1/4 and τ=0\tau = 0, each term of line L3 is a[n]2ejπn/2e−jπn/2=1a[n]^2 e^{j\pi n/2} e^{-j\pi n/2} = 1, so R=1R = 1, P=1P = 1 and T=8⋅1/(2⋅1)=4T = 8 \cdot 1/(2 \cdot 1) = 4. For Pfa=0.05P_{fa} = 0.05, λ=−ln⁡0.05=2.996\lambda = -\ln 0.05 = 2.996, and the detector declares a signal. At the wrong cycle frequency α=1/8\alpha = 1/8, the terms are ej2πn/8e^{j2\pi n/8}, which add to zero over eight samples, and T=0T = 0.

With noise. For BPSK at α=2fc\alpha = 2 f_c and large NN, TT is about k ∣Z∣2k\,|Z|^2 with ZZ complex Gaussian of unit variance and mean μ\sqrt\mu, where μ=Nγ2/(4γ+2)\mu = N\gamma^2/(4\gamma + 2), k=(2γ+1)/(1+γ)2k = (2\gamma + 1)/(1 + \gamma)^2 and γ\gamma is the SNR. The table gives PdP_d for Pfa=0.05P_{fa} = 0.05, next to the energy detector with the exact noise power:

SNR N=64N = 64 N=256N = 256 N=1024N = 1024 energy detector, N=64N = 64 / 256256 / 10241024
00 dB 0.973 1.000 1.000 1.000 / 1.000 / 1.000
−5-5 dB 0.378 0.945 1.000 0.731 / 0.997 / 1.000
−10-10 dB 0.091 0.235 0.744 0.199 / 0.463 / 0.921

For Pfa=0.1P_{fa} = 0.1 and Pd=0.9P_d = 0.9, the cyclic test needs 179179, 1,2631{,}263 and 11,12711{,}127 samples at −5-5, −10-10 and −15-15 dB, against 8585, 721721 and 6,7756{,}775 for the energy detector. Both grow like 1/SNR21/\mathrm{SNR}^2. But if the noise power is only known within 11 dB, the energy detector cannot reach any SNR below −3.3-3.3 dB, while the cyclic test is not changed at all.

Correctness

Claim. Under H0H_0, as N→∞N \to \infty, TT tends in law to a unit exponential, so Pr⁡[T>−ln⁡Pfa]→Pfa\Pr[T > -\ln P_{fa}] \to P_{fa}, for every noise power. Under H1H_1 with Rα(τ)≠0R^\alpha(\tau) \ne 0, TT grows like NN, and Pd→1P_d \to 1.

Key steps. Under H0H_0, the terms un=y[n+τ]y[n]e−j2παnu_n = y[n + \tau] y[n] e^{-j2\pi\alpha n} have mean zero, since circular noise has E[w2]=0\mathbb E[w^2] = 0 and distinct samples are independent. They are uncorrelated with each other, and E∣un∣2=cσ4\mathbb E|u_n|^2 = c\sigma^4: for τ=0\tau = 0, E∣w∣4=2σ4\mathbb E|w|^4 = 2\sigma^4, and for τ≥1\tau \ge 1, the two factors are independent. They are also circular. The sequence is τ\tau-dependent, so the central limit theorem for mm-dependent sequences gives ∑nun/Mcσ4→CN(0,1)\sum_n u_n / \sqrt{M c\sigma^4} \to \mathcal{CN}(0, 1), whose squared magnitude is a unit exponential. The law of large numbers gives P→σ2P \to \sigma^2, and so T=∣∑nun∣2/(McP2)T = |\sum_n u_n|^2/(M c P^2) has the same limit. Under H1H_1, R→Rα(τ)≠0R \to R^\alpha(\tau) \ne 0 and PP tends to the total power, so T/MT/M tends to a positive constant. Scaling yy by any a≠0a \ne 0 multiplies ∣R∣2|R|^2 and P2P^2 by ∣a∣4|a|^4, so TT 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 −ln⁡Pfa-\ln P_{fa} gives false alarm rate PfaP_{fa} in the limit, that a signal with a nonzero cyclic autocorrelation is detected with probability tending to 11, and that the DFT scan computes the same estimates at the grid frequencies.

Setting. For samples y[0..N−1]y[0..N-1], a cycle frequency α\alpha and a lag 0≤τ<N0 \le \tau < N, let M=N−τM = N - \tau and

un=y[n+τ] y~[n] e−j2παn,R=1M∑n<Mun,P=1N∑n<N∣y[n]∣2,u_n = y[n + \tau]\, \tilde y[n]\, e^{-j2\pi\alpha n}, \qquad R = \frac1M \sum_{n < M} u_n, \qquad P = \frac1N \sum_{n < N} |y[n]|^2,

where y~[n]=y[n]\tilde y[n] = y[n] in the conjugate form and y~[n]=y[n]∗\tilde y[n] = y[n]^* in the non-conjugate form, which requires τ≥1\tau \ge 1. The statistic is T=M∣R∣2/(cP2)T = M|R|^2/(cP^2), with c=2c = 2 for the conjugate form at τ=0\tau = 0 and c=1c = 1 otherwise, and T=0T = 0 if P=0P = 0.

Lemma 1 (scale invariance)

For every complex a≠0a \ne 0, the samples a y[n]a\,y[n] give the same TT.

Proof. Each unu_n is multiplied by a2a^2 (conjugate form) or by ∣a∣2|a|^2 (non-conjugate form), so ∣R∣2|R|^2 is multiplied by ∣a∣4|a|^4. PP is multiplied by ∣a∣2|a|^2, so P2P^2 is multiplied by ∣a∣4|a|^4, and the ratio does not change. □\square

So under H0H_0 the law of TT is the same for every noise power σ2\sigma^2, and we may take σ2=1\sigma^2 = 1.

Lemma 2 (moments under noise)

Let the y[n]y[n] be independent CN(0,1)\mathcal{CN}(0, 1). Then for all n≠mn \ne m in [0,M)[0, M): E[un]=0\mathbb E[u_n] = 0, E[unum∗]=0\mathbb E[u_n u_m^*] = 0, E[unum]=0\mathbb E[u_n u_m] = 0, E[un2]=0\mathbb E[u_n^2] = 0 and E∣un∣2=c\mathbb E|u_n|^2 = c.

Proof. A circular variable w∼CN(0,1)w \sim \mathcal{CN}(0, 1) has E[w]=0\mathbb E[w] = 0, E[w2]=0\mathbb E[w^2] = 0, E∣w∣2=1\mathbb E|w|^2 = 1, E[w4]=E[w3w∗]=0\mathbb E[w^4] = \mathbb E[w^3 w^*] = 0 and E∣w∣4=2\mathbb E|w|^4 = 2. In general, a moment E[wp(w∗)q]\mathbb E[w^p (w^*)^q] is zero unless p=qp = q, because ww and ejθwe^{j\theta}w have the same law, which multiplies the moment by ej(p−q)θe^{j(p - q)\theta} for every θ\theta.

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.

  • E[un]\mathbb E[u_n]: for τ≥1\tau \ge 1, the factor y[n+τ]y[n + \tau] is alone at its index. For τ=0\tau = 0 (conjugate form), the moment is E[y[n]2]=0\mathbb E[y[n]^2] = 0.
  • E[unum∗]\mathbb E[u_n u_m^*] with n≠mn \ne m: the index n+τn + \tau carries an unconjugated factor from unu_n. To balance it, um∗u_m^* must supply a conjugated factor at n+τn + \tau. Its conjugated factors sit at m+τ≠n+τm + \tau \ne n + \tau, and, in the conjugate form, at mm. In the non-conjugate form, the factor of um∗u_m^* at mm is unconjugated. So balance needs the conjugate form and m=n+τm = n + \tau with τ≥1\tau \ge 1. Then the index nn carries the unconjugated y[n]y[n] from unu_n, and um∗u_m^* has conjugated factors only at mm and m+τm + \tau, both above nn. So nothing balances it. For τ=0\tau = 0, unu_n has y[n]2y[n]^2 and um∗u_m^* has no factor at nn.
  • E[unum]\mathbb E[u_n u_m] and E[un2]\mathbb E[u_n^2]: in the conjugate form, all factors are unconjugated, so the moment is zero. In the non-conjugate form, unumu_n u_m has unconjugated factors at n+τn + \tau and m+τm + \tau, and conjugated ones at nn and mm. Balance needs {n+τ,m+τ}={n,m}\{n + \tau, m + \tau\} = \{n, m\} as multisets, which is impossible for τ≥1\tau \ge 1 since the largest index max⁡(n,m)+τ\max(n, m) + \tau appears only on the left.
  • E∣un∣2\mathbb E|u_n|^2: for τ≥1\tau \ge 1, it is E∣y[n+τ]∣2 E∣y[n]∣2=1\mathbb E|y[n + \tau]|^2\, \mathbb E|y[n]|^2 = 1. For τ=0\tau = 0 (conjugate form), it is E∣y[n]∣4=2\mathbb E|y[n]|^4 = 2. □\square

Theorem 3 (false alarm rate)

Under H0H_0, as N→∞N \to \infty with τ\tau and α\alpha fixed, TT tends in law to a unit exponential, and Pr⁡[T>−ln⁡Pfa]→Pfa\Pr[T > -\ln P_{fa}] \to P_{fa}.

Proof. By Lemma 1, take σ2=1\sigma^2 = 1. Write un=an+jbnu_n = a_n + j b_n. By Lemma 2, E[unum∗]=c δnm\mathbb E[u_n u_m^*] = c\,\delta_{nm} and E[unum]=0\mathbb E[u_n u_m] = 0 for all n,mn, m, which gives E[anam]=E[bnbm]=c2δnm\mathbb E[a_n a_m] = \mathbb E[b_n b_m] = \frac c2 \delta_{nm} and E[anbm]=0\mathbb E[a_n b_m] = 0. The sequence (an,bn)(a_n, b_n) is τ\tau-dependent, since unu_n is a function of y[n]y[n] and y[n+τ]y[n + \tau] only, and its terms are bounded in fourth moment uniformly in nn. The rotation e−j2παne^{-j2\pi\alpha n} changes neither the moments of Lemma 2 nor the dependence. By the central limit theorem for mm-dependent sequences, applied to every fixed real combination s an+t bns\,a_n + t\,b_n and then by the Cramér-Wold device, the vector 1Mc/2(∑an,∑bn)\frac{1}{\sqrt{M c/2}}\big(\sum a_n, \sum b_n\big) tends to two independent standard normals. Hence S=∑nun/McS = \sum_n u_n / \sqrt{Mc} tends to CN(0,1)\mathcal{CN}(0, 1), and ∣S∣2|S|^2 tends to a unit exponential (Lemma 1 of the energy detector proof: ∣w∣2|w|^2 for w∼CN(0,1)w \sim \mathcal{CN}(0, 1) is a unit exponential).

Now T=M∣R∣2/(cP2)=∣S∣2/P2T = M|R|^2/(cP^2) = |S|^2 / P^2. By the law of large numbers, P→1P \to 1 almost surely, so by Slutsky's theorem TT tends in law to the same unit exponential. The exponential law is continuous, so Pr⁡[T>λ]→e−λ\Pr[T > \lambda] \to e^{-\lambda} for every λ\lambda, and e−λ=Pfae^{-\lambda} = P_{fa} for λ=−ln⁡Pfa\lambda = -\ln P_{fa}. □\square

Theorem 4 (detection)

Suppose that under H1H_1 the estimate converges, R→ρ≠0R \to \rho \ne 0, and P→Pˉ>0P \to \bar P > 0, both in probability. Then T→∞T \to \infty in probability, and the detection probability at any fixed threshold tends to 11.

Proof. T/M=∣R∣2/(cP2)→∣ρ∣2/(cPˉ2)>0T / M = |R|^2/(cP^2) \to |\rho|^2/(c\bar P^2) > 0 in probability, and M→∞M \to \infty. □\square

For BPSK, y[n]=s[n]+w[n]y[n] = s[n] + w[n] with s[n]=S a[n]ej(2πfcn+ϕ)s[n] = \sqrt S\, a[n] e^{j(2\pi f_c n + \phi)}, a[n]=±1a[n] = \pm 1, and ww independent CN(0,σ2)\mathcal{CN}(0, \sigma^2). Take the conjugate form, τ=0\tau = 0 and α=2fc\alpha = 2 f_c. Then y[n]2=s[n]2+2s[n]w[n]+w[n]2y[n]^2 = s[n]^2 + 2 s[n] w[n] + w[n]^2 and s[n]2e−j2παn=Sej2ϕs[n]^2 e^{-j 2\pi\alpha n} = S e^{j2\phi} for every nn. The other two terms have mean zero and are independent over nn given aa, with bounded variance, so their average tends to zero, and R→Sej2ϕR \to S e^{j2\phi}, with ∣ρ∣=S>0|\rho| = S > 0. Also P→S+σ2P \to S + \sigma^2. Theorem 4 applies.

The large-NN detection probability used on the page. Given aa and ϕ\phi, the sum ∑ny[n]2e−j2παn\sum_n y[n]^2 e^{-j2\pi\alpha n} is NSej2ϕN S e^{j2\phi} plus the sum of 2s[n]w[n]+w[n]22 s[n] w[n] + w[n]^2, rotated. Those terms are circular, with variance 4Sσ2+2σ44 S\sigma^2 + 2\sigma^4 each, and uncorrelated with each other, since E[sw⋅(w2)∗]=s E[w(w∗)2]=0\mathbb E[s w \cdot (w^2)^*] = s\,\mathbb E[w (w^*)^2] = 0. Approximating the noise sum by a complex Gaussian and PP by S+σ2S + \sigma^2, with γ=S/σ2\gamma = S/\sigma^2,

T≈(4γ+2)2(1+γ)2 ∣Z∣2,Z∼CN(Nγ24γ+2,1).T \approx \frac{(4\gamma + 2)}{2(1 + \gamma)^2}\, |Z|^2, \qquad Z \sim \mathcal{CN}\Big(\sqrt{\tfrac{N\gamma^2}{4\gamma + 2}}, 1\Big).

For Z∼CN(μ,1)Z \sim \mathcal{CN}(\sqrt\mu, 1), Pr⁡[∣Z∣2>x]=∑j≥0e−μμjj!Pr⁡[Gamma(j+1,1)>x]\Pr[|Z|^2 > x] = \sum_{j \ge 0} e^{-\mu}\frac{\mu^j}{j!}\Pr[\mathrm{Gamma}(j + 1, 1) > x] (Theorem 3 of the energy detector proof with N=1N = 1). This is an approximation, not an exact law. The test file checks it against a simulation at N=64N = 64 and −5-5 dB within a Wilson interval.

Proposition 5 (the scan)

Let vn=y[n+τ] y~[n]v_n = y[n + \tau]\,\tilde y[n] for n<Mn < M and V=DFT(v)V = \mathrm{DFT}(v), so V[k]=∑nvne−j2πkn/MV[k] = \sum_n v_n e^{-j2\pi k n/M}. Then V[k]/MV[k]/M is the estimate RR at α=k/M\alpha = k/M, for every kk.

Proof. Substitute α=k/M\alpha = k/M in the definition of RR. □\square

Under H0H_0, the V[k]V[k] are uncorrelated with equal variance, since E[V[k]V[l]∗]=∑n,mE[vnvm∗]e−j2π(kn−lm)/M=cMσ4δkl\mathbb E[V[k] V[l]^*] = \sum_{n, m} \mathbb E[v_n v_m^*] e^{-j2\pi(kn - lm)/M} = cM\sigma^4 \delta_{kl} by Lemma 2 and the orthogonality of the DFT. If the MM statistics were independent unit exponentials, the largest would exceed λ\lambda with probability 1−(1−e−λ)M1 - (1 - e^{-\lambda})^M, and setting this to PfaP_{fa} gives the scan threshold of the page. The bins are uncorrelated but only approximately independent and exponential at finite MM, so this threshold is an approximation; the test file checks that the rate under noise does not exceed PfaP_{fa} for M=64M = 64.

The code

The code updates the rotation by multiplying by e−j2παe^{-j2\pi\alpha} at each step, which equals e−j2παne^{-j2\pi\alpha n} up to rounding that grows like nn times the unit roundoff. The test file checks the direct sum against the DFT at all grid frequencies to 10−1210^{-12}.

Complexity

In the real RAM, one cycle frequency and one lag take O(N)O(N) time: lines L3 and L4 each pass over the samples once, and the rotation e−j2παne^{-j2\pi\alpha n} is updated by one multiplication per sample. The extra space is O(1)O(1). A scan over all MM cycle frequencies k/Mk/M is one DFT of the products, O(Nlog⁡N)O(N \log N) with the FFT; the reference code uses the direct O(N2)O(N^2) 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. TT 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 PfaP_{fa} as NN grows. At finite NN, T≤N2/(cM)T \le N^2/(cM) by the Cauchy-Schwarz inequality, so its far tail is lighter than the exponential law. In simulations with 6464 and 128128 samples, the scan over all bins had a false alarm rate below its target of 0.10.1.
  • Selective. It reacts only to signals with a feature at the tested (α,τ)(\alpha, \tau), 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 1/SNR21/\mathrm{SNR}^2, with a constant about 1.61.6 to 2.12.1 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 Sα(f)S^\alpha(f), the Fourier transform of Rα(τ)R^\alpha(\tau) in τ\tau, by the FFT accumulation method or the strip spectral correlation analyzer, and look for peaks off the line α=0\alpha = 0.
  • 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 δ\delta in α\alpha makes the terms rotate by 2πδ2\pi\delta per sample, and the sum cancels once NδN\delta is about 11. A carrier offset of the receiver moves the conjugate feature of BPSK by twice the offset. Search a small range of α\alpha, 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 α\alpha.
  • Wrong form. QPSK and most higher-order signals have no conjugate feature at τ=0\tau = 0; a test for one will not see them.
  • Small samples. The exponential law is a large-NN result. Check the rate by simulation for the NN and PfaP_{fa} in use, especially for small PfaP_{fa}.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

cbb.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the communications pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Complex baseband tools for the communications pages.

Vectors are lists of complex numbers. Matrices are lists of rows. The
functions here are plain building blocks: small linear algebra, convolution,
the DFT as a direct sum, the Gaussian Q function, dB conversion, complex
Gaussian noise and the Wilson score interval. No page algorithm (equalizer,
estimator, synchronizer, detector, precoder, demapper or power allocation)
lives in this file.

Conventions (prompts of the communications area):
- dft is X[k] = sum_n x[n] e^(-j 2 pi k n / N) with no factor; idft has 1/N.
- udft and uidft are the unitary pair, with 1/sqrt(N) on both sides.
- qfunc(x) = 0.5 erfc(x / sqrt(2)); it never computes 1 - Phi(x).
- cn(rng, var) draws CN(0, var): real and imaginary parts are independent
  with variance var / 2 each, so E|w|^2 = var.
"""

import cmath
import math
import random


# ---------------------------------------------------------------- vectors and matrices


def zeros(rows: int, cols: int | None = None) -> list:
    """A zero vector of length rows, or a rows by cols zero matrix."""
    if cols is None:
        return [0j] * rows
    return [[0j] * cols for _ in range(rows)]


def eye(n: int) -> list[list[complex]]:
    """The n by n identity matrix."""
    return [[1 + 0j if i == k else 0j for k in range(n)] for i in range(n)]


def add(a: list, b: list) -> list:
    """Elementwise a + b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [add(r, s) for r, s in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a: list, b: list) -> list:
    """Elementwise a - b for two vectors or two matrices of the same shape."""
    if len(a) != len(b):
        raise ValueError("shapes differ")
    if a and isinstance(a[0], list):
        return [sub(r, s) for r, s in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c: complex, a: list) -> list:
    """The scalar c times a vector or a matrix."""
    if a and isinstance(a[0], list):
        return [scale(c, r) for r in a]
    return [c * x for x in a]


def matmul(a: list[list[complex]], b: list[list[complex]]) -> list[list[complex]]:
    """The matrix product a b."""
    if not a or not b or len(a[0]) != len(b):
        raise ValueError("inner dimensions differ")
    cols = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in cols] for row in a]


def matvec(a: list[list[complex]], x: list[complex]) -> list[complex]:
    """The matrix times vector product a x."""
    if a and len(a[0]) != len(x):
        raise ValueError("inner dimensions differ")
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def herm(a: list) -> list:
    """The conjugate transpose of a matrix. A vector gives its conjugate."""
    if a and isinstance(a[0], list):
        return [[complex(a[i][k]).conjugate() for i in range(len(a))] for k in range(len(a[0]))]
    return [complex(x).conjugate() for x in a]


def dot(x: list[complex], y: list[complex]) -> complex:
    """The inner product x^H y = sum of conj(x_i) y_i."""
    if len(x) != len(y):
        raise ValueError("lengths differ")
    return sum(complex(p).conjugate() * q for p, q in zip(x, y))


def norm2(x: list) -> float:
    """The squared Euclidean norm sum |x_i|^2 (squared Frobenius norm for a matrix)."""
    if x and isinstance(x[0], list):
        return sum(norm2(r) for r in x)
    return sum(abs(v) ** 2 for v in x)


# ---------------------------------------------------------------- linear systems


def _lu(a: list[list[complex]]) -> tuple[list[list[complex]], list[int], int]:
    """LU factorization with partial pivoting. Returns (lu, perm, sign)."""
    n = len(a)
    if any(len(r) != n for r in a):
        raise ValueError("matrix is not square")
    m = [[complex(v) for v in r] for r in a]
    perm = list(range(n))
    sign = 1
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(m[i][k]))
        if abs(m[p][k]) == 0.0:
            raise ValueError("matrix is singular")
        if p != k:
            m[k], m[p] = m[p], m[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        for i in range(k + 1, n):
            f = m[i][k] / m[k][k]
            m[i][k] = f
            if f != 0:
                rk, ri = m[k], m[i]
                for c in range(k + 1, n):
                    ri[c] -= f * rk[c]
    return m, perm, sign


def _lu_solve(lu: list[list[complex]], perm: list[int], b: list[complex]) -> list[complex]:
    n = len(lu)
    y = [complex(b[perm[i]]) for i in range(n)]
    for i in range(n):
        for c in range(i):
            y[i] -= lu[i][c] * y[c]
    for i in range(n - 1, -1, -1):
        for c in range(i + 1, n):
            y[i] -= lu[i][c] * y[c]
        y[i] /= lu[i][i]
    return y


def solve(a: list[list[complex]], b: list) -> list:
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector, or a matrix whose columns are right-hand sides.
    Raises ValueError if a is singular.
    """
    lu, perm, _ = _lu(a)
    if b and isinstance(b[0], list):
        cols = [list(c) for c in zip(*b)]
        xs = [_lu_solve(lu, perm, c) for c in cols]
        return [list(r) for r in zip(*xs)]
    if len(b) != len(a):
        raise ValueError("lengths differ")
    return _lu_solve(lu, perm, b)


def inv(a: list[list[complex]]) -> list[list[complex]]:
    """The inverse of a square matrix."""
    return solve(a, eye(len(a)))


def det(a: list[list[complex]]) -> complex:
    """The determinant of a square matrix (0 for a singular matrix)."""
    try:
        lu, _, sign = _lu(a)
    except ValueError as e:
        if "singular" in str(e):
            return 0j
        raise
    d = complex(sign)
    for i in range(len(lu)):
        d *= lu[i][i]
    return d


def cholesky(a: list[list[complex]]) -> list[list[complex]]:
    """The lower triangular L with a = L L^H, for a Hermitian positive definite a.

    Raises ValueError if a is not positive definite (to rounding).
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for k in range(i + 1):
            s = complex(a[i][k]) - sum(low[i][c] * low[k][c].conjugate() for c in range(k))
            if i == k:
                if s.real <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = complex(math.sqrt(s.real))
            else:
                low[i][k] = s / low[k][k].real
    return low


# ---------------------------------------------------------------- convolution and the DFT


def conv(a: list[complex], b: list[complex]) -> list[complex]:
    """Linear convolution, of length len(a) + len(b) - 1."""
    if not a or not b:
        return []
    out = [0j] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[i + k] += x * y
    return out


def cconv(a: list[complex], b: list[complex], n: int | None = None) -> list[complex]:
    """Circular convolution of length n (default: the longer length).

    Both inputs are padded with zeros to length n, or must not be longer than n.
    """
    if n is None:
        n = max(len(a), len(b))
    if len(a) > n or len(b) > n:
        raise ValueError("input longer than n")
    out = [0j] * n
    for i, x in enumerate(a):
        for k, y in enumerate(b):
            out[(i + k) % n] += x * y
    return out


def _twiddles(n: int, sign: int) -> list[complex]:
    return [cmath.exp(sign * 2j * math.pi * t / n) for t in range(n)]


def dft(x: list[complex]) -> list[complex]:
    """X[k] = sum over n of x[n] e^(-j 2 pi k n / N), as a direct O(N^2) sum."""
    n = len(x)
    w = _twiddles(n, -1)
    return [sum(x[t] * w[(k * t) % n] for t in range(n)) for k in range(n)]


def idft(xf: list[complex]) -> list[complex]:
    """x[n] = (1/N) sum over k of X[k] e^(j 2 pi k n / N), the inverse of dft."""
    n = len(xf)
    w = _twiddles(n, 1)
    return [sum(xf[k] * w[(k * t) % n] for k in range(n)) / n for t in range(n)]


def udft(x: list[complex]) -> list[complex]:
    """The unitary DFT: dft(x) / sqrt(N)."""
    s = 1.0 / math.sqrt(len(x)) if x else 1.0
    return [v * s for v in dft(x)]


def uidft(xf: list[complex]) -> list[complex]:
    """The unitary inverse DFT: sqrt(N) idft(X), the inverse of udft."""
    s = math.sqrt(len(xf)) if xf else 1.0
    return [v * s for v in idft(xf)]


# ---------------------------------------------------------------- Q function and dB


def qfunc(x: float) -> float:
    """Q(x) = P(Z > x) for a standard normal Z, computed as 0.5 erfc(x / sqrt(2))."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def qinv(p: float) -> float:
    """The x with Q(x) = p, for 0 < p < 1, by bisection on Q (which decreases)."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    lo, hi = -40.0, 40.0
    for _ in range(200):
        mid = 0.5 * (lo + hi)
        if qfunc(mid) > p:
            lo = mid
        else:
            hi = mid
        if hi - lo <= 1e-15 * max(1.0, abs(mid)):
            break
    return 0.5 * (lo + hi)


def db(x: float) -> float:
    """10 log10(x), for a ratio of powers or energies."""
    return 10.0 * math.log10(x)


def undb(d: float) -> float:
    """10^(d / 10), the inverse of db."""
    return 10.0 ** (d / 10.0)


# ---------------------------------------------------------------- noise and statistics


def cn(rng: random.Random, var: float) -> complex:
    """One sample of CN(0, var): independent real and imaginary parts of variance var / 2."""
    s = math.sqrt(var / 2.0)
    return complex(rng.gauss(0.0, s), rng.gauss(0.0, s))


def awgn(rng: random.Random, x: list[complex], n0: float) -> list[complex]:
    """x plus independent CN(0, n0) noise on each sample."""
    return [v + cn(rng, n0) for v in x]


def wilson(k: int, n: int, z: float = 3.29) -> tuple[float, float]:
    """The Wilson score interval for k successes in n trials (z = 3.29 is about 0.999 two-sided)."""
    if n <= 0 or not 0 <= k <= n:
        raise ValueError("need 0 <= k <= n and n > 0")
    p = k / n
    z2 = z * z
    den = 1.0 + z2 / n
    mid = (p + z2 / (2 * n)) / den
    half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / den
    return max(0.0, mid - half), min(1.0, mid + half)
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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.scan
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of space.scan
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example