14. CFAR and Real-Time Packet Detection¶
PySDR’s Detection chapter ends with the problem every burst receiver has: packets arrive at unknown times in an endless stream of samples, and we must find each one’s first sample without being fooled by noise. Its solution has four parts: correlate with the known preamble, set an adaptive threshold with a cell-averaging CFAR detector, pick the peaks, and run all of it in buffers of 100 000 samples that overlap by one preamble so that no packet falls between two buffers. The Python code then needs extra logic to convert buffer indices to global ones and to remove packets that were found twice, once in each overlapping buffer.
This chapter builds the same detector as one streaming object. The buffer logic disappears because every stage keeps its own state; the CFAR threshold costs two additions per sample instead of a loop over 100 cells; and the detector reports absolute sample indices. Comparing it with PySDR’s code on the same recording also turns up a small inconsistency in PySDR’s threshold, and shows why the detector misses two of the five packets (it is not a bug).
The code is in code/include/cppsdr/cfar.hpp and code/tests/test_cfar.cpp. figure-generating-scripts/cfar_reference.py runs PySDR’s Steps 1 to 6 verbatim, with two changes: a fixed seed, and a sample rate of 100 kHz instead of 1 MHz so that the recording (still five packets about one second apart) is small enough to ship as test data. It stores the stream as a SigMF recording with 16-bit samples and one annotation per packet, so the C++ test reads the signal and its ground truth with the reader from IQ Files Without Copies, and SigMF, and PySDR’s detector runs on exactly the same quantized samples.
One Formula, One Source of Truth¶
A CA-CFAR detector estimates the local noise power as the mean of \(N\) training cells around the cell under test, and declares a detection when the cell exceeds \(\alpha\) times that mean. If the cells are independent and the noise is complex Gaussian (so each power cell is exponentially distributed), the false-alarm probability per cell is
which reads: the more cells we average, the more reliable the noise estimate, and the closer \(\alpha\) can get to the value we would use if we knew the noise exactly (\(-\ln P_{FA}\), about 13.8 for \(10^{-6}\)). PySDR’s first CFAR example uses this formula with num_train meaning the total number of training cells. Its streaming example, ca_cfar_1d, takes num_train as the number of cells on each side:
alpha = num_train * (pfa**(-1/num_train) - 1) # N = 50 ...
train_start_left = max(0, i - num_guard - num_train) # ... but 50 cells on each side
...
noise_est = np.mean(train_cells) # mean of 100 cells
so \(\alpha\) is computed for 50 cells while 100 are averaged. The threshold comes out 7 % higher than intended (\(\alpha = 15.9\) instead of 14.8), and the false-alarm probability per cell is \(3.9 \cdot 10^{-7}\) instead of the requested \(10^{-6}\). It errs on the safe side, and it is easy to miss because both meanings of “number of training cells” are common.
The C++ detector avoids the ambiguity by never letting the caller supply both numbers. The configuration names the cells per side, and \(\alpha\) is computed from the cells actually averaged:
struct config {
std::size_t train = 50; // training cells per side
std::size_t guard = 10; // guard cells per side
double pfa = 1e-6; // per-lag false-alarm probability
...
};
alpha_ = ca_alpha(2 * cfg_.train, cfg_.pfa); // the cells we actually average
Both directions of the formula are constexpr, so the test can state the discrepancy as a compile-time fact:
static_assert(near_rel(ca_pfa(100, ca_alpha(100, 1e-6)), 1e-6, 1e-9));
static_assert(near_rel(ca_pfa(100, ca_alpha(50, 1e-6)), 3.9e-7, 0.02), "the actual Pfa is 3.9e-7, not 1e-6");
Window Sums in Constant Time¶
PySDR’s ca_cfar_1d computes each threshold from scratch: build the training array with np.concatenate, then take its mean. For 100 training cells that is 100 additions and an allocation per sample. But neighbouring windows share all but two cells. For a block of data, the classic trick is a prefix sum: once \(S_i = p_0 + \dots + p_{i-1}\) is known, the sum of any window \([a, b)\) is \(S_b - S_a\). The standard library computes prefix sums with std::inclusive_scan:
std::vector<double> S(n + 1, 0.0);
std::inclusive_scan(p.begin(), p.end(), S.begin() + 1);
for (std::size_t i = 0; i < n; ++i) {
// lagging window [l0, l1) and leading window [r0, r1), clamped at the edges like PySDR's
const std::size_t count = (l1 - l0) + (r1 - r0);
if (count) t[i] = alpha * ((S[l1] - S[l0]) + (S[r1] - S[r0])) / double(count);
}
The windows are clamped at the array ends exactly as in PySDR’s loop, so this ca_threshold reproduces PySDR’s thresholds for a whole 10 063-cell buffer, edges included, to \(1.4 \cdot 10^{-13}\) (relative). The sums are in double. A prefix sum over millions of cells in float would lose the small differences between large partial sums, which is exactly the subtraction the trick relies on.
The Detector as a Stream¶
For a stream, prefix sums would grow forever, so the streaming detector uses their incremental form, running sums: when the cell under test advances by one, each training window gains one cell and loses one. The detector keeps the last \(2(T+G)+2\) power cells in a ring (one more than the CFAR window, so that the cell leaving the lagging window is still there when it is subtracted) and updates the two sums with two additions and two subtractions. Running sums accumulate rounding error, because each subtraction does not exactly cancel the earlier addition. So every 65 536 cells the detector recomputes both sums from the ring, which costs \(2T\) additions every 65 536 samples:
if (newest == W_ - 1 || ++since_resync_ == 1u << 16) {
resync(c); // first window, and periodically against rounding drift
} else {
lag_ += ring_[(c - G - 1) % R]; // the lagging window gains c-G-1 ...
lag_ -= ring_[(c - G - T - 1) % R]; // ... and loses c-G-T-1
}
const double thr = alpha_ * (lag_ + lead_) / double(2 * T);
The other two stages carry their state the same way. The correlator keeps the last \(L\) samples in a mirrored buffer (each sample written twice, \(L\) apart), so the window of the last 63 samples is always contiguous, the layout from FIR Filters in C++. The peak picker keeps the current run of above-threshold cells and reports its maximum once min_spacing cells have passed without another crossing:
if (run_ && c - last_above_ > cfg_.min_spacing) on_detection(*run_), run_.reset();
if (cut > thr) {
if (!run_ || (cfg_.peak == peak_policy::maximum && cut > run_->power))
run_ = detection{c, float(cut), float(thr)};
last_above_ = c;
}
Because each power cell is indexed by the first sample of the correlation window, the cell index already is the packet start. PySDR’s correction for mode='same' (“peak occurs at len(preamble)//2 after true start”) has no counterpart. The caller writes:
cppsdr::cfar::packet_detector det(preamble, {});
while (auto block = sdr.read()) // any block size
det.process(block, [](detection d) { report(d.start); }); // absolute sample index
There is no buffer size, no overlap, and no duplicate removal, because nothing is ever split. The test demonstrates it the way every chapter in this book does: feeding the recording in random blocks of 1 to 7 samples, or 1 to 5000, gives exactly the detections of a single call. The price is latency. A packet is reported \(T + G\) cells after its peak (the leading training window must be filled), plus min_spacing cells to be sure the run is over, about 1.2 ms at 100 kHz. PySDR’s buffered version reports it when the buffer is processed, up to one buffer (100 ms) later.
GNU Radio’s correlation block, corr_est_cc in gr-digital, makes a different choice that is instructive. In its dynamic-threshold mode it estimates the noise as the mean correlator power over the current work() call, that is, over whatever number of samples the scheduler happens to pass in, and its peak search stops at the end of that chunk. The threshold therefore depends on scheduling, which the block author does not control. A ring of training cells makes the result independent of how the stream is cut, which is the property our test checks.
Against PySDR’s Detector¶
On the recording, PySDR’s detector finds three of the five packets, at samples 169 758, 358 011 and 444 438, each with zero timing error. Given PySDR’s \(\alpha\) through a configuration override, the C++ detector finds exactly the same three, at the same indices, with either peak policy. So the port is faithful.
Why are two packets missed? At an SNR of \(-5\) dB per sample, correlating over 63 samples gives a peak about \(63 \times 10^{-0.5} \approx 20\) times the mean noise power (13 dB), while the threshold factor is about 15 (11.7 dB). A packet clears the threshold only if the noise helps a little. For the two missed packets the correlation peak reached 11.2 and 11.4 times the local noise estimate. This is the detector working as designed at the edge of its sensitivity, and PySDR’s tuning advice applies: a longer preamble, a higher \(P_{FA}\), or more SNR.
With the corrected \(\alpha\) the C++ detector finds the same three packets plus one detection at sample 423 276, where there is no packet. Is that a defect? The recording has 531 822 cells, and at \(P_{FA} = 10^{-6}\) per cell the expected number of false alarms is 0.53. One is what we asked for. This is PySDR’s distinction between per-lag and system-level false-alarm rates, made concrete: \(10^{-6}\) per lag sounds tiny, but at 100 000 lags per second it is one false alarm every ten seconds, and at PySDR’s 1 MHz, one per second.
Is the False-Alarm Rate Constant?¶
The point of CFAR is in its name: the false-alarm rate should not depend on the noise level. The test checks the formula and that promise separately, with \(P_{FA} = 10^{-3}\) so that two million cells give enough crossings to count:
On independent, exponentially distributed cells fed directly into the CFAR stage (
process_cells), the measured rate is \(0.97 \cdot 10^{-3}\), as the formula promises.On the correlator output for pure complex noise, it is \(0.82 \cdot 10^{-3}\), lower than the target. A quick NumPy check on independent data gives the same split (\(1.04 \cdot 10^{-3}\) for independent cells, \(0.85 \cdot 10^{-3}\) after the correlator), so it is a property of the signal, not of the code. The correlator’s output cells are not independent: neighbouring outputs share 62 of their 63 input samples, and the Zadoff-Chu preamble’s aperiodic autocorrelation has sidelobes up to 0.3. The formula assumes independence.
The same noise realization at two levels 3000 times apart produces the same crossings, rate for rate. The test statistic is a ratio of powers, so scaling the input cannot change a single decision. That is the “constant” in CFAR, and it holds exactly.
Key Takeaways¶
Derive the CFAR threshold factor from the number of cells actually averaged; never let two parameters mean “training cells”. PySDR’s streaming example computes \(\alpha\) for 50 cells but averages 100, giving \(P_{FA} = 3.9 \cdot 10^{-7}\) instead of \(10^{-6}\).
Window sums are prefix-sum differences (
std::inclusive_scan, indouble) for blocks, and running sums with periodic resynchronization for streams: \(O(1)\) per sample instead of \(O(N)\).A detector whose stages carry their own state needs no buffers, overlaps or duplicate removal, and reports absolute sample indices. Test it by cutting the stream at random.
Per-lag \(P_{FA}\) times lags per second is the false alarms per second; at \(10^{-6}\) and 1 MHz, that is one per second.
CFAR’s constancy is exact under scaling; its absolute \(P_{FA}\) assumes independent cells, which a correlator output is not.