JS8Call-Improved master
Loading...
Searching...
No Matches
whitening_processor.h
Go to the documentation of this file.
1
5
6#pragma once
7
9
10#include <QDebug>
11#include <QLoggingCategory>
12
13#include <algorithm>
14#include <array>
15#include <cmath>
16#include <cstdlib>
17#include <limits>
18#include <numeric>
19#include <optional>
20#include <sstream>
21#include <vector>
22
23Q_DECLARE_LOGGING_CATEGORY(decoder_js8);
24
25namespace js8 {
34template <int NROWS, int ND, int N> class WhiteningProcessor {
35 public:
36 // Retained for paired benchmarks of the previous decoder behavior.
37 enum class Normalization { None, FrameSigma283 };
48 struct Result {
49 std::array<float, 3 * ND> llr0;
50 std::array<float, 3 * ND> llr1;
53 std::size_t erasures;
54 double avgAbsPre;
55 double avgAbsPost;
56 };
57
87 static Result process(std::array<std::array<float, ND>, NROWS> const &s1,
88 std::array<int, ND> const &symbolWinners,
89 float erasureThreshold, bool debug,
90 std::optional<CoherentBlend<NROWS, ND>> const
91 &coherentBlend = std::nullopt,
92 float llrScale = 1.0f,
93 Normalization normalization = Normalization::None) {
94 if (!(llrScale > 0.0f) || !std::isfinite(llrScale))
95 llrScale = 1.0f;
96 auto const median =
97 [](std::vector<float> &values) -> std::optional<float> {
98 if (values.empty())
99 return std::nullopt;
100
101 auto const mid = values.size() / 2;
102
103 std::nth_element(values.begin(), values.begin() + mid,
104 values.end());
105 float med = values[mid];
106
107 if ((values.size() % 2) == 0 && mid > 0) {
108 std::nth_element(values.begin(), values.begin() + (mid - 1),
109 values.end());
110 med = 0.5f * (med + values[mid - 1]);
111 }
112
113 return med;
114 };
115
116 // Estimate per-tone noise using non-winning tone magnitudes across the
117 // frame.
118 auto const toneNoise =
119 [&]() -> std::optional<std::array<float, NROWS>> {
120 std::array<std::vector<float>, NROWS> toneSamples;
121 std::array<float, NROWS> noise = {};
122
123 // Collect non-winning magnitudes for each tone.
124 for (int j = 0; j < ND; ++j) {
125 int const winner = symbolWinners[j];
126
127 for (int i = 0; i < NROWS; ++i) {
128 if (i != winner)
129 toneSamples[i].push_back(s1[i][j]);
130 }
131 }
132
133 bool ok = true;
134
135 for (int i = 0; i < NROWS; ++i) {
136 if (auto m = median(toneSamples[i]); m) {
137 noise[i] = *m;
138 } else {
139 ok = false;
140 break;
141 }
142 }
143
144 if (!ok)
145 return std::nullopt;
146
147 return noise;
148 }();
149
150 if (toneNoise && debug) {
151 std::ostringstream oss;
152
153 oss << "toneNoise:";
154 for (auto const value : *toneNoise)
155 oss << ' ' << value;
156
157 qCDebug(decoder_js8).noquote() << oss.str().c_str();
158 }
159
160 // Estimate per-symbol noise using non-winning tone magnitudes per
161 // symbol.
162 auto const symbolNoise = [&]() -> std::optional<std::vector<float>> {
163 std::vector<float> noise;
164 noise.reserve(ND);
165
166 for (int j = 0; j < ND; ++j) {
167 std::vector<float> bins;
168 bins.reserve(NROWS - 1);
169
170 int const winner = symbolWinners[j];
171
172 for (int i = 0; i < NROWS; ++i) {
173 if (i != winner)
174 bins.push_back(s1[i][j]);
175 }
176
177 if (auto m = median(bins); m) {
178 noise.push_back(*m);
179 } else {
180 return std::nullopt;
181 }
182 }
183
184 return noise;
185 }();
186
187 if (symbolNoise && !symbolNoise->empty() && debug) {
188 auto const [minIt, maxIt] =
189 std::minmax_element(symbolNoise->begin(), symbolNoise->end());
190 float const avg = std::accumulate(symbolNoise->begin(),
191 symbolNoise->end(), 0.0f) /
192 static_cast<float>(symbolNoise->size());
193
194 qCDebug(decoder_js8)
195 << "symbolNoise avg/min/max" << avg << *minIt << *maxIt;
196 }
197
198 Result result{};
199
200 bool const disableWhitening =
201 std::getenv("JS8_DISABLE_WHITENING") != nullptr;
202 // Coherent data is used only when the whole blended input validates:
203 // any non-finite numerator, amplitude, or weight falls back to the
204 // noncoherent path bit-identically (partial blends could otherwise
205 // produce a mix of incompatible evidence within one frame).
206 bool coherentUsable = false;
207 float coherentAlpha = 0.0f;
208 if (coherentBlend && coherentBlend->alpha > 0.0f &&
209 std::isfinite(coherentBlend->alpha) &&
210 std::isfinite(coherentBlend->amplitude) &&
211 coherentBlend->amplitude > 0.0f) {
212 coherentUsable = true;
213 for (auto const &row : coherentBlend->numerators) {
214 for (float const value : row) {
215 if (!std::isfinite(value)) {
216 coherentUsable = false;
217 break;
218 }
219 }
220 if (!coherentUsable)
221 break;
222 }
223 if (coherentUsable)
224 coherentAlpha =
225 std::clamp(coherentBlend->alpha, 0.0f, 1.0f);
226 }
227 bool const whiteningAvailable = toneNoise && symbolNoise &&
228 !symbolNoise->empty() &&
229 !disableWhitening;
230 bool const applyErasureInWhitening =
231 whiteningAvailable && erasureThreshold > 0.0f;
232 double sumAbsPre = 0.0;
233 double sumAbsPost = 0.0;
234 std::size_t erasures = 0;
235
236 for (int j = 0; j < ND; ++j) {
237 int const i1 = 3 * j; // First column (matches Fortran's i1)
238 int const i2 = 3 * j + 1; // Second column (matches Fortran's i2)
239 int const i4 = 3 * j + 2; // Third column (matches Fortran's i4)
240
241 std::array<float, NROWS> ps;
242
243 for (int i = 0; i < NROWS; ++i)
244 ps[i] = s1[i][j];
245
246 // Common per-symbol noise-power estimate. When whitening is
247 // unavailable, fall back to unit variance so the calculation stays
248 // a Gaussian power likelihood rather than degenerating.
249 float const invSigma2 = whiteningAvailable ? 1.0f /
250 ((std::max(0.0f, (*toneNoise)[symbolWinners[j]]) *
251 std::max(0.0f, (*symbolNoise)[j])) +
252 1e-12f)
253 : 1.0f;
254
255 // Noise-normalized tone power. Under an AWGN model with per-symbol
256 // noise power sigma^2 = toneNoise * symbolNoise, ps^2/(2*sigma^2)
257 // is used as the Gaussian soft-likelihood metric for tone i.
258 std::array<float, NROWS> w;
259
260 for (int i = 0; i < NROWS; ++i) {
261 float const power = ps[i] * ps[i];
262 w[i] = 0.5f * power * invSigma2;
263 }
264 auto const noncoherent = w;
265
266 // Optionally blend conservatively estimated coherent numerators.
267 // Both families share this symbol's invSigma2, so reliability
268 // information in their magnitudes is preserved; no symbol is ever
269 // renormalized. With no usable blend input, `w` above is used
270 // untouched, preserving the legacy path exactly.
271 if (coherentUsable) {
272 std::array<float, NROWS> coherentScores;
273 for (int i = 0; i < NROWS; ++i)
274 coherentScores[i] =
275 (*coherentBlend).numerators[i][j] * invSigma2;
276 std::array<float, NROWS> blended{};
277 if (js8::blendToneScores(w, coherentScores, coherentAlpha,
278 blended))
279 w = blended;
280 }
281
282 // Stable log-sum-exp of the tones whose natural-binary encoding has
283 // bit `bit` set (given by `shift`) or clear, for a single bit group.
284 auto logSumExp = [](std::array<float, NROWS> const &scores,
285 int shift, int bit) -> float {
286 float m = -std::numeric_limits<float>::infinity();
287
288 for (int i = 0; i < NROWS; ++i)
289 if (((i >> shift) & 1) == bit && scores[i] > m)
290 m = scores[i];
291
292 if (std::isinf(m))
293 return 0.0f; // empty group: contributes 0 to the diff
294
295 float s = 0.0f;
296
297 for (int i = 0; i < NROWS; ++i)
298 if (((i >> shift) & 1) == bit)
299 s += std::exp(scores[i] - m);
300
301 return m + std::log(s);
302 };
303
304 // Each symbol emits three LLRs (one per bit) as the logsum-exp
305 // difference across the two bit groups, combining all tones in each
306 // group rather than using only the single largest magnitude.
307 for (int bit = 0; bit < 3; ++bit) {
308 int const shift = 2 - bit;
309 result.llr0[i1 + bit] =
310 (logSumExp(w, shift, 1) - logSumExp(w, shift, 0)) * llrScale;
311 result.llr1[i1 + bit] = coherentUsable
312 ? (logSumExp(noncoherent, shift, 1) -
313 logSumExp(noncoherent, shift, 0)) * llrScale
314 : result.llr0[i1 + bit];
315 }
316
317 if (whiteningAvailable) {
318 // The LLRs are already noise-normalized through invSigma2, so
319 // no further division is required here; only erasure and the
320 // pre/post magnitude metrics are collected.
321 auto const applyWhitening = [&](float &value) {
322 float const pre = std::abs(value);
323 sumAbsPre += pre;
324
325 if (applyErasureInWhitening &&
326 std::abs(value) < erasureThreshold) {
327 value = 0.0f;
328 ++erasures;
329 }
330
331 sumAbsPost += std::abs(value);
332 };
333
334 applyWhitening(result.llr0[i1]);
335 applyWhitening(result.llr0[i2]);
336 applyWhitening(result.llr0[i4]);
337 applyWhitening(result.llr1[i1]);
338 applyWhitening(result.llr1[i2]);
339 applyWhitening(result.llr1[i4]);
340 }
341 }
342
343 auto const normalizeLLR = [](auto &llr) {
344 float sum = 0.0f;
345 float sum_of_squares = 0.0f;
346
347 for (auto const value : llr) {
348 sum += value;
349 sum_of_squares += value * value;
350 }
351
352 float const llrav = sum / llr.size();
353 float const llr2av = sum_of_squares / llr.size();
354 float const variance = llr2av - llrav * llrav;
355 float const llrsig = std::sqrt(variance > 0.0f ? variance : llr2av);
356
357 if (llrsig > 0.0f && std::isfinite(llrsig))
358 for (float &val : llr)
359 val = (val / llrsig) * 2.83f;
360 };
361
362 // Only the opt-in baseline reproduces the former per-frame rescaling.
363 if (normalization == Normalization::FrameSigma283) {
364 normalizeLLR(result.llr0);
365 normalizeLLR(result.llr1);
366 }
367
368 if (whiteningAvailable && debug) {
369 auto const total =
370 static_cast<double>(result.llr0.size() + result.llr1.size());
371 double const avgPre = total > 0.0 ? sumAbsPre / total : 0.0;
372 double const avgPost = total > 0.0 ? sumAbsPost / total : 0.0;
373
374 qCDebug(decoder_js8) << "LLR whitening applied"
375 << "avg|LLR| pre/post:" << avgPre << avgPost
376 << "erasures:" << erasures;
377 }
378
379 result.whiteningApplied = whiteningAvailable;
380 result.erasureApplied = applyErasureInWhitening;
381 result.erasures = erasures;
382 result.avgAbsPre = sumAbsPre;
383 result.avgAbsPost = sumAbsPost;
384 return result;
385 }
386};
387} // namespace js8
Compute per-tone/symbol noise medians and whiten LLRs for a JS8 frame.
Definition whitening_processor.h:34
static Result process(std::array< std::array< float, ND >, NROWS > const &s1, std::array< int, ND > const &symbolWinners, float erasureThreshold, bool debug, std::optional< CoherentBlend< NROWS, ND > > const &coherentBlend=std::nullopt, float llrScale=1.0f, Normalization normalization=Normalization::None)
Compute primary and noncoherent fallback LLRs for a candidate frame.
Definition whitening_processor.h:87
Conservative coherent 8-FSK likelihood support for the JS8 decoder.
JS8 namespace for Kalman filter-based trackers.
Definition bp_math.h:12
bool blendToneScores(std::array< float, Tones > const &noncoherent, std::array< float, Tones > const &coherent, float alpha, std::array< float, Tones > &out)
Definition coherent_likelihood.h:480
Definition coherent_likelihood.h:643
Result of a whitening/LLR pass.
Definition whitening_processor.h:48
std::size_t erasures
Number of LLR elements erased.
Definition whitening_processor.h:53
bool erasureApplied
True when erasure was applied.
Definition whitening_processor.h:52
double avgAbsPost
Aggregate |LLR| after whitening.
Definition whitening_processor.h:55
bool whiteningApplied
True when whitening was applied.
Definition whitening_processor.h:51
std::array< float, 3 *ND > llr1
Noncoherent fallback LLRs.
Definition whitening_processor.h:50
double avgAbsPre
Aggregate |LLR| before whitening.
Definition whitening_processor.h:54
std::array< float, 3 *ND > llr0
Primary, possibly coherent LLRs.
Definition whitening_processor.h:49