logicaffeine_compile/codegen_ana/wta.rs
1//! Winner-take-all — the O7 stretch: the MARGIN CERTIFICATE arrives before the tile does.
2//!
3//! A WTA circuit picks the largest of n currents; near ties it picks WRONG, because each
4//! competitor carries an input-referred offset. The honest theorem: with per-cell offsets
5//! bounded by the k·σ envelope, the physical winner equals the ideal winner whenever the
6//! certified top-two margin EXCEEDS the resolution band `2·k·σ_offset/s` (both competitors
7//! can shift toward each other by k·σ at most). [`wta_winner`] states exactly that — a
8//! provable flag, never an unconditional claim — and the lock's fixed-seed Monte-Carlo shows
9//! both sides: provable margins never flip, and a near-tie really does flip on real dies.
10//! `ArgMax` STAYS in `KNOWN_PLANNED`: the tile lowers when the margin replay reaches the
11//! independent checker.
12
13use super::nonideal::{NonIdealityModel, KSIGMA};
14
15/// One judged winner-take-all readout.
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct WtaOutcome {
18 /// The ideal argmax.
19 pub winner: usize,
20 /// The certified top-two margin (math domain).
21 pub margin: f64,
22 /// The k·σ resolution band the margin must clear (math domain).
23 pub band: f64,
24 /// TRUE iff the winner is provable on every die inside the modeled envelope.
25 pub provable: bool,
26}
27
28/// Judge an ideal value vector at block scale `s`: argmax, top-two margin, and whether the
29/// margin clears the offset resolution band. `None` for fewer than two competitors.
30pub fn wta_winner(values: &[f64], model: &NonIdealityModel, s: f64) -> Option<WtaOutcome> {
31 if values.len() < 2 || values.iter().any(|v| !v.is_finite()) || !(s > 0.0) {
32 return None;
33 }
34 let mut idx: Vec<usize> = (0..values.len()).collect();
35 idx.sort_by(|a, b| values[*b].partial_cmp(&values[*a]).unwrap());
36 let (w, second) = (idx[0], idx[1]);
37 let margin = values[w] - values[second];
38 let band = (2.0 * KSIGMA * model.offset_sigma_v.0 / s).next_up();
39 Some(WtaOutcome {
40 winner: w,
41 margin,
42 band,
43 provable: margin > band,
44 })
45}