Skip to main content

anamnesis/
scoring.rs

1//! Proper scoring rules and calibration diagnostics.
2//!
3//! Everything in this module is pure: it takes a slice of resolved
4//! [`Sample`]s — a probability you assigned and what actually happened — and
5//! returns numbers. No I/O, no randomness, no hidden state. That purity is the
6//! point: the conclusions a person reaches about their own judgement should be
7//! reproducible and auditable, not the verdict of a black box.
8//!
9//! References (verified against the literature, see the project README):
10//!   * Brier, G.W. (1950). *Verification of forecasts expressed in terms of
11//!     probability.* Monthly Weather Review.
12//!   * Murphy, A.H. (1973). *A new vector partition of the probability score.*
13//!     The reliability–resolution–uncertainty decomposition implemented here.
14//!   * Lichtenstein, Fischhoff & Phillips (1982). Calibration / the
15//!     over/under-confidence gap (mean confidence minus proportion correct).
16
17use std::collections::BTreeMap;
18
19/// A resolved forecast: the probability assigned to an event, and whether the
20/// event happened (`1.0`) or did not (`0.0`).
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub struct Sample {
23    /// Forecaster's probability that the event is true, in `[0, 1]`.
24    pub prob: f64,
25    /// Ground truth: `1.0` if the event happened, `0.0` otherwise.
26    pub outcome: f64,
27}
28
29impl Sample {
30    pub fn new(prob: f64, happened: bool) -> Self {
31        Sample {
32            prob,
33            outcome: if happened { 1.0 } else { 0.0 },
34        }
35    }
36}
37
38/// Mean **Brier score**: the mean squared error of probabilistic forecasts.
39///
40/// `0.0` is perfect. Always saying `0.5` on truly 50/50 events scores `0.25`.
41/// Being confidently, maximally wrong every time scores `1.0`. Lower is better.
42/// Returns `None` for an empty sample.
43pub fn brier(samples: &[Sample]) -> Option<f64> {
44    if samples.is_empty() {
45        return None;
46    }
47    let sum: f64 = samples.iter().map(|s| (s.prob - s.outcome).powi(2)).sum();
48    Some(sum / samples.len() as f64)
49}
50
51/// **Stake-weighted Brier**: the Brier score with each forecast weighted by how
52/// much it *mattered*. `weights[i]` scales `samples[i]`; weights `≤ 0` drop out,
53/// and a length mismatch or no positive weight yields `None`. With all weights
54/// equal this reduces to [`brier`]. The point is to surface whether you are
55/// miscalibrated on the calls that carry consequences, not merely on average.
56pub fn brier_weighted(samples: &[Sample], weights: &[f64]) -> Option<f64> {
57    if samples.is_empty() || samples.len() != weights.len() {
58        return None;
59    }
60    let mut num = 0.0;
61    let mut den = 0.0;
62    for (s, &w) in samples.iter().zip(weights) {
63        if w > 0.0 {
64            num += w * (s.prob - s.outcome).powi(2);
65            den += w;
66        }
67    }
68    (den > 0.0).then_some(num / den)
69}
70
71/// Mean **logarithmic (Good) score**: the average negative log-likelihood of
72/// the outcomes under your forecasts. Lower is better.
73///
74/// The log score is *strictly* proper and punishes confident errors far more
75/// harshly than Brier does — one `p = 0.999` forecast on an event that does not
76/// happen is brutal. Because a single confident miss would otherwise yield
77/// `+∞`, probabilities are clamped into `[eps, 1 - eps]`. A reasonable `eps` is
78/// `1e-6`; passing `0.0` recovers the unclamped score.
79pub fn log_score(samples: &[Sample], eps: f64) -> Option<f64> {
80    if samples.is_empty() {
81        return None;
82    }
83    let sum: f64 = samples
84        .iter()
85        .map(|s| {
86            let p = s.prob.clamp(eps, 1.0 - eps);
87            -(s.outcome * p.ln() + (1.0 - s.outcome) * (1.0 - p).ln())
88        })
89        .sum();
90    Some(sum / samples.len() as f64)
91}
92
93/// The **base rate**: the fraction of sampled events that actually happened.
94/// This is the climatology a useful forecaster must beat.
95pub fn base_rate(samples: &[Sample]) -> Option<f64> {
96    if samples.is_empty() {
97        return None;
98    }
99    Some(samples.iter().map(|s| s.outcome).sum::<f64>() / samples.len() as f64)
100}
101
102/// Murphy's three-way partition of the Brier score.
103///
104/// `brier == reliability - resolution + uncertainty`, exactly (see
105/// [`decompose`]).
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub struct Decomposition {
108    /// **Reliability** (calibration error). How far your stated probabilities
109    /// drift from the frequencies that actually followed them. Lower is better;
110    /// `0` means perfect calibration.
111    pub reliability: f64,
112    /// **Resolution** (discrimination). How much your forecasts move *with*
113    /// reality away from the base rate. Higher is better; `0` means you said
114    /// the same thing regardless of what was true.
115    pub resolution: f64,
116    /// **Uncertainty.** The irreducible variance of the outcomes themselves,
117    /// `base_rate * (1 - base_rate)`. Nobody can score below this by skill
118    /// alone; it is the difficulty of the questions you chose.
119    pub uncertainty: f64,
120    /// The Brier score reconstructed from the three parts above.
121    pub brier: f64,
122}
123
124/// Decompose the Brier score into reliability, resolution and uncertainty.
125///
126/// Forecasts are grouped by their *exact* probability value, which makes the
127/// identity `BS = REL - RES + UNC` hold to floating-point precision rather than
128/// approximately. (Binning into ranges, as a reliability diagram does, would
129/// introduce a within-bin term and only approximate equality.) This exactness
130/// is asserted in the test suite.
131pub fn decompose(samples: &[Sample]) -> Option<Decomposition> {
132    if samples.is_empty() {
133        return None;
134    }
135    let n = samples.len() as f64;
136    let o_bar = base_rate(samples).unwrap();
137
138    // Group by the exact bit pattern of the forecast probability. Each group
139    // shares a single representative forecast value `f_k`.
140    // value = (representative prob, sum of outcomes, count)
141    let mut groups: BTreeMap<u64, (f64, f64, f64)> = BTreeMap::new();
142    for s in samples {
143        let e = groups.entry(s.prob.to_bits()).or_insert((s.prob, 0.0, 0.0));
144        e.1 += s.outcome;
145        e.2 += 1.0;
146    }
147
148    let mut reliability = 0.0;
149    let mut resolution = 0.0;
150    for (f_k, sum_o, n_k) in groups.values() {
151        let o_k = sum_o / n_k; // observed frequency within this forecast value
152        reliability += n_k * (f_k - o_k).powi(2);
153        resolution += n_k * (o_k - o_bar).powi(2);
154    }
155    reliability /= n;
156    resolution /= n;
157    let uncertainty = o_bar * (1.0 - o_bar);
158
159    Some(Decomposition {
160        reliability,
161        resolution,
162        uncertainty,
163        brier: reliability - resolution + uncertainty,
164    })
165}
166
167/// **Brier skill score**: `1 - brier / uncertainty`.
168///
169/// `0` means you did exactly as well as always predicting the base rate.
170/// Positive means skill; negative means you would have been better off
171/// parroting climatology. Returns `None` when uncertainty is `0` (every event
172/// resolved the same way, so there was nothing to be skillful about).
173pub fn skill_score(samples: &[Sample]) -> Option<f64> {
174    let d = decompose(samples)?;
175    if d.uncertainty == 0.0 {
176        return None;
177    }
178    Some(1.0 - d.brier / d.uncertainty)
179}
180
181/// One cell of a reliability diagram.
182#[derive(Clone, Copy, Debug)]
183pub struct Bin {
184    /// Inclusive lower edge of the probability range.
185    pub lo: f64,
186    /// Exclusive upper edge (the final bin is closed on the right).
187    pub hi: f64,
188    /// How many forecasts fell in this bin.
189    pub count: usize,
190    /// Mean forecast probability among those forecasts.
191    pub mean_pred: f64,
192    /// Observed frequency of "true" among those forecasts. `NaN` when empty.
193    pub observed: f64,
194}
195
196/// Bucket forecasts into `n_bins` equal-width bins over `[0, 1]` and report,
197/// per bin, the mean predicted probability versus the observed frequency. This
198/// is the data behind a reliability diagram: on a perfectly calibrated record
199/// every populated bin has `mean_pred == observed`.
200pub fn calibration_curve(samples: &[Sample], n_bins: usize) -> Vec<Bin> {
201    let n_bins = n_bins.max(1);
202    // (count, sum_pred, sum_outcome)
203    let mut acc = vec![(0usize, 0.0f64, 0.0f64); n_bins];
204    for s in samples {
205        let mut idx = (s.prob * n_bins as f64).floor() as isize;
206        idx = idx.clamp(0, n_bins as isize - 1); // p == 1.0 lands in the last bin
207        let cell = &mut acc[idx as usize];
208        cell.0 += 1;
209        cell.1 += s.prob;
210        cell.2 += s.outcome;
211    }
212    acc.into_iter()
213        .enumerate()
214        .map(|(i, (count, sum_pred, sum_out))| {
215            let lo = i as f64 / n_bins as f64;
216            let hi = (i + 1) as f64 / n_bins as f64;
217            let (mean_pred, observed) = if count > 0 {
218                (sum_pred / count as f64, sum_out / count as f64)
219            } else {
220                ((lo + hi) / 2.0, f64::NAN)
221            };
222            Bin {
223                lo,
224                hi,
225                count,
226                mean_pred,
227                observed,
228            }
229        })
230        .collect()
231}
232
233/// **Discrimination**, as the area under the ROC curve (AUC): the probability
234/// that a randomly chosen event that *did* happen was given a higher forecast
235/// than a randomly chosen event that did *not*. Ties contribute `0.5`.
236///
237/// `0.5` is no discriminating skill (you may still be perfectly calibrated!);
238/// `1.0` is perfect separation. Returns `None` when every outcome is the same,
239/// because AUC is undefined without both a positive and a negative case.
240///
241/// Calibration and discrimination are genuinely different virtues: a forecaster
242/// who always reports the true base rate is perfectly calibrated yet useless
243/// (AUC `0.5`). This metric measures the part calibration cannot see.
244///
245/// Computed in `O(n log n)` via the Wilcoxon–Mann–Whitney rank identity
246/// `AUC = (R₊ − n₊(n₊+1)/2) / (n₊·n₋)`, where `R₊` is the sum of the ranks of
247/// the positive cases using *average ranks* for ties. (A self-evidently correct
248/// `O(n²)` pairwise version lives in the tests and is asserted to agree exactly,
249/// ties included.)
250pub fn auc(samples: &[Sample]) -> Option<f64> {
251    let n_pos = samples.iter().filter(|s| s.outcome >= 0.5).count();
252    let n_neg = samples.len() - n_pos;
253    if n_pos == 0 || n_neg == 0 {
254        return None;
255    }
256
257    // Rank by forecast probability, ascending, ranks 1..=N. total_cmp gives a
258    // panic-free total order; tie groups (equal prob) share their average rank.
259    let mut order: Vec<usize> = (0..samples.len()).collect();
260    order.sort_by(|&a, &b| samples[a].prob.total_cmp(&samples[b].prob));
261    let mut rank = vec![0.0f64; samples.len()];
262    let mut i = 0;
263    while i < order.len() {
264        let mut j = i;
265        while j + 1 < order.len() && samples[order[j + 1]].prob == samples[order[i]].prob {
266            j += 1;
267        }
268        let avg = ((i + 1) + (j + 1)) as f64 / 2.0; // average of ranks (i+1)..=(j+1)
269        for k in i..=j {
270            rank[order[k]] = avg;
271        }
272        i = j + 1;
273    }
274
275    let r_pos: f64 = samples
276        .iter()
277        .zip(&rank)
278        .filter(|(s, _)| s.outcome >= 0.5)
279        .map(|(_, r)| *r)
280        .sum();
281    let (np, nn) = (n_pos as f64, n_neg as f64);
282    Some((r_pos - np * (np + 1.0) / 2.0) / (np * nn))
283}
284
285/// The classic over/under-confidence statistic (Lichtenstein–Fischhoff).
286#[derive(Clone, Copy, Debug, PartialEq)]
287pub struct Overconfidence {
288    /// Mean *boldness*: the average of `max(p, 1 - p)` — how far, on average,
289    /// you stood from a coin-flip.
290    pub mean_confidence: f64,
291    /// Proportion of the side you leaned toward that turned out correct. A
292    /// forecast of exactly `0.5` is scored as half-right.
293    pub accuracy: f64,
294    /// `mean_confidence - accuracy`. Positive ⇒ overconfident (you were bolder
295    /// than you were right). Negative ⇒ underconfident.
296    pub gap: f64,
297}
298
299/// Compute the over/under-confidence gap: mean confidence minus the proportion
300/// of leaned-toward sides that came true. This is the headline number behind
301/// "most people are overconfident": across decades of studies the gap is
302/// reliably positive.
303pub fn overconfidence(samples: &[Sample]) -> Option<Overconfidence> {
304    if samples.is_empty() {
305        return None;
306    }
307    let n = samples.len() as f64;
308    let mut conf = 0.0;
309    let mut hits = 0.0;
310    for s in samples {
311        conf += s.prob.max(1.0 - s.prob);
312        let hit = if (s.prob - 0.5).abs() < 1e-12 {
313            0.5 // no side chosen; half credit
314        } else if s.prob > 0.5 {
315            s.outcome // leaned "yes"
316        } else {
317            1.0 - s.outcome // leaned "no"
318        };
319        hits += hit;
320    }
321    Some(Overconfidence {
322        mean_confidence: conf / n,
323        accuracy: hits / n,
324        gap: (conf - hits) / n,
325    })
326}
327
328/// Calibration-in-the-large: mean forecast minus base rate. A directional bias
329/// detector — positive means you systematically said "more likely" than reality
330/// delivered, independent of how bold any individual call was.
331pub fn directional_bias(samples: &[Sample]) -> Option<f64> {
332    Some(
333        samples.iter().map(|s| s.prob).sum::<f64>() / samples.len().max(1) as f64
334            - base_rate(samples)?,
335    )
336}
337
338// ───────────────── selection / missingness diagnostics ──────────────────────
339
340/// Mean **boldness** `mean(max(p, 1−p))` of a set of stated probabilities — how far
341/// from a 50/50 shrug they sit, computed *without outcomes*. Because it needs no
342/// resolution, it can be taken over your still-*open* claims as well as your graded
343/// ones, which is what lets the report check whether the calls you actually resolved
344/// are a fair sample of the calls you *made*. `None` for an empty slice.
345pub fn mean_boldness(probs: &[f64]) -> Option<f64> {
346    if probs.is_empty() {
347        return None;
348    }
349    let sum: f64 = probs
350        .iter()
351        .map(|&p| {
352            let p = p.clamp(0.0, 1.0);
353            p.max(1.0 - p)
354        })
355        .sum();
356    Some(sum / probs.len() as f64)
357}
358
359/// **Absolute standardized mean difference** between two samples — `|mean_a − mean_b|`
360/// divided by their pooled standard deviation. The standard covariate-balance /
361/// missing-not-at-random diagnostic: a value above `≈ 0.1` means the two groups
362/// differ enough on this variable that their split is unlikely to be random. It is
363/// an *effect size*, not a hypothesis test, so it does not false-alarm at small `n`
364/// the way a t/KS test would. `None` when either group has fewer than two points or
365/// there is no spread to standardize against.
366pub fn asmd(a: &[f64], b: &[f64]) -> Option<f64> {
367    if a.len() < 2 || b.len() < 2 {
368        return None;
369    }
370    let mean = |xs: &[f64]| xs.iter().sum::<f64>() / xs.len() as f64;
371    // Sample variance (Bessel's n−1 correction).
372    let var = |xs: &[f64], m: f64| {
373        xs.iter().map(|x| (x - m).powi(2)).sum::<f64>() / (xs.len() as f64 - 1.0)
374    };
375    let (ma, mb) = (mean(a), mean(b));
376    let pooled_sd = ((var(a, ma) + var(b, mb)) / 2.0).sqrt();
377    if pooled_sd < 1e-12 {
378        return None; // no spread — standardization undefined
379    }
380    Some((ma - mb).abs() / pooled_sd)
381}
382
383// ───────────────────────── numeric / interval forecasts ─────────────────────
384
385/// A resolved *numeric* forecast: a central credible interval `[low, high]`
386/// stated at confidence `level` (e.g. `0.80` for an 80% interval), and the
387/// value that actually occurred. This is the quantity-forecasting analogue of
388/// [`Sample`].
389#[derive(Clone, Copy, Debug, PartialEq)]
390pub struct NumericSample {
391    pub low: f64,
392    pub high: f64,
393    /// Nominal coverage in `(0, 1)`.
394    pub level: f64,
395    pub value: f64,
396}
397
398impl NumericSample {
399    pub fn width(&self) -> f64 {
400        (self.high - self.low).max(0.0)
401    }
402    pub fn contains(&self) -> bool {
403        self.value >= self.low && self.value <= self.high
404    }
405    /// `α = 1 − level`, clamped away from `0` so the penalty stays finite.
406    pub fn alpha(&self) -> f64 {
407        (1.0 - self.level).clamp(1e-9, 1.0)
408    }
409}
410
411/// **Winkler interval score** for one numeric forecast. Lower is better.
412///
413/// Inside the interval the score is simply its width; outside, the width plus a
414/// `2/α` penalty proportional to how far the truth fell beyond the nearer edge.
415/// It is a strictly proper scoring rule for central prediction intervals, and it
416/// captures the right trade-off: narrow intervals are rewarded, but only if they
417/// keep catching the outcome.
418pub fn winkler(s: &NumericSample) -> f64 {
419    let width = s.high - s.low;
420    let two_over_alpha = 2.0 / s.alpha();
421    if s.value < s.low {
422        width + two_over_alpha * (s.low - s.value)
423    } else if s.value > s.high {
424        width + two_over_alpha * (s.value - s.high)
425    } else {
426        width
427    }
428}
429
430/// The Winkler score expressed as a **multiple of the interval's own width**.
431///
432/// The raw Winkler score carries the units of the quantity being predicted, so
433/// averaging across claims lets the largest-magnitude question dominate the
434/// headline: one estimate in milliseconds and one in dollars are added together
435/// as if they were the same thing, and "your interval score is 4127" tells the
436/// reader nothing except which claim had the biggest numbers.
437///
438/// Dividing by the width removes the units. `1.0` means the value landed inside
439/// the interval; anything above 1 is the miss penalty, in units of your own
440/// stated width. `None` for a zero-width interval, where the ratio is undefined.
441pub fn winkler_ratio(s: &NumericSample) -> Option<f64> {
442    let width = s.high - s.low;
443    if width <= 0.0 {
444        return None;
445    }
446    Some(winkler(s) / width)
447}
448
449/// Empirical **coverage**: the fraction of intervals that actually contained
450/// their outcome. Compared with the nominal level, this is interval calibration:
451/// 80% intervals that catch the truth far less than 80% of the time are too
452/// narrow — the numeric face of overconfidence.
453pub fn coverage(samples: &[NumericSample]) -> Option<f64> {
454    if samples.is_empty() {
455        return None;
456    }
457    Some(samples.iter().filter(|s| s.contains()).count() as f64 / samples.len() as f64)
458}
459
460/// **Conformal interval recalibration** — the multiplicative correction for your
461/// credible intervals, the numeric analogue of [`fit_recalibration`].
462///
463/// For each forecast the *standardized residual* `r = |value − center| / half_width`
464/// is how many half-widths the truth fell from the interval's midpoint; the interval
465/// covered exactly when `r ≤ 1`. Scaling every half-width by a factor `m` makes an
466/// interval cover iff `r ≤ m`, so the fraction covered after scaling is the fraction
467/// of residuals `≤ m`. To hit a target coverage we therefore set `m` to the empirical
468/// quantile of the residuals at that target — the split-conformal construction (the
469/// `(1−α)`-quantile of the nonconformity scores), distribution-free and valid in
470/// finite samples. The target is the mean nominal level across the pool, so `m > 1`
471/// means "your intervals are too narrow — multiply their half-widths by `m`" and
472/// `m < 1` means they are too wide.
473///
474/// Pooled and scale-only by design: it assumes a single common width error, which is
475/// the honest amount of structure to fit from one agent's handful of intervals.
476/// Zero-width intervals carry no scale information and are skipped. Returns `None`
477/// with fewer than three usable samples, where the quantile would be meaningless.
478pub fn conformal_width_factor(samples: &[NumericSample]) -> Option<f64> {
479    let mut residuals: Vec<f64> = Vec::with_capacity(samples.len());
480    let mut level_sum = 0.0;
481    for s in samples {
482        let hw = s.width() / 2.0;
483        if hw <= 0.0 {
484            continue; // degenerate point interval — no scale information
485        }
486        let center = (s.low + s.high) / 2.0;
487        residuals.push((s.value - center).abs() / hw);
488        level_sum += s.level;
489    }
490    if residuals.len() < 3 {
491        return None;
492    }
493    let target = level_sum / residuals.len() as f64;
494    residuals.sort_by(f64::total_cmp);
495    Some(quantile_sorted(&residuals, target))
496}
497
498// ───────────────────────── small-sample uncertainty ─────────────────────────
499
500/// **Wilson score interval** for a binomial proportion `successes / n`.
501///
502/// A confidence interval on a rate that, unlike the normal ("Wald") approximation,
503/// stays inside `[0, 1]` and keeps sensible coverage at small `n` and extreme
504/// proportions — exactly the regime a single agent or session lives in, where the
505/// literature warns the central-limit approximation is unsafe. `z` is the
506/// standard-normal quantile (≈ `1.96` for 95%). Returns `None` for `n == 0`.
507pub fn wilson_interval(successes: f64, n: usize, z: f64) -> Option<(f64, f64)> {
508    if n == 0 {
509        return None;
510    }
511    let n = n as f64;
512    let p = (successes / n).clamp(0.0, 1.0);
513    let z2 = z * z;
514    let denom = 1.0 + z2 / n;
515    let center = (p + z2 / (2.0 * n)) / denom;
516    let margin = (z / denom) * ((p * (1.0 - p) / n) + (z2 / (4.0 * n * n))).sqrt();
517    Some(((center - margin).max(0.0), (center + margin).min(1.0)))
518}
519
520/// **Empirical-Bayes-style shrinkage** of a rate toward a prior mean.
521///
522/// `(successes + strength·prior_mean) / (n + strength)` — equivalently a
523/// `Beta(strength·prior_mean, strength·(1−prior_mean))` prior updated by the
524/// data. At small `n` the estimate is pulled toward `prior_mean` (borrowing
525/// strength); as `n` grows it converges to the raw rate. This is what keeps a
526/// single fluky resolution from dominating a per-kind calibration number — the
527/// literature finds shrinkage beats both raw rates and fixed pseudocounts.
528pub fn shrink_toward(successes: f64, n: usize, prior_mean: f64, strength: f64) -> f64 {
529    (successes + strength * prior_mean) / (n as f64 + strength)
530}
531
532// ─────────────────────── anytime-valid calibration test ─────────────────────
533
534/// Fixed symmetric grid of betting fractions λ used by the mixture e-process.
535/// `|λ| < 1` guarantees every factor `1 + λ(y − p)` is non-negative (since
536/// `y − p ∈ [−1, 1]`), so each `∏(1 + λ(yᵢ − pᵢ))` is a valid non-negative test
537/// martingale; averaging over a symmetric grid gives two-sided power without any
538/// data-dependent tuning of λ.
539const EPROCESS_LAMBDAS: [f64; 10] = [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9];
540
541/// **Anytime-valid calibration e-value** — a betting / test-martingale statistic
542/// for the null hypothesis "these forecasts are calibrated."
543///
544/// Under calibration each outcome behaves like a draw with the stated
545/// probability, so `E[yᵢ − pᵢ | past] = 0` and, for each betting fraction λ, the
546/// wealth `∏ᵢ (1 + λ(yᵢ − pᵢ))` is a non-negative martingale starting at `1`.
547/// This returns the mean wealth over [`EPROCESS_LAMBDAS`], itself a valid
548/// e-process. By Ville's inequality the value exceeds `1/α` with probability at
549/// most `α` *under the null at any stopping time* — so, unlike a fixed-n test
550/// (Spiegelhalter's Z, a t-test), it stays valid even though you peek at it every
551/// session. Read it as evidence of *mis*calibration: `≈ 1` is none, `≥ 20` is
552/// "significant at α = 0.05", and it grows without bound as miscalibration
553/// accumulates. Samples are consumed in the given order, so pass them
554/// chronologically (the order outcomes were learned). `None` for an empty record.
555pub fn calibration_eprocess(samples: &[Sample]) -> Option<f64> {
556    if samples.is_empty() {
557        return None;
558    }
559    let mut wealth = [1.0f64; EPROCESS_LAMBDAS.len()];
560    for s in samples {
561        let z = s.outcome - s.prob; // mean zero under the calibration null
562        for (w, &lam) in wealth.iter_mut().zip(EPROCESS_LAMBDAS.iter()) {
563            *w *= 1.0 + lam * z;
564        }
565    }
566    Some(wealth.iter().sum::<f64>() / EPROCESS_LAMBDAS.len() as f64)
567}
568
569/// Convert an e-value to an **anytime-valid p-value** via the canonical e→p
570/// calibrator `1/e` (capped at `1`). Valid under optional stopping.
571pub fn eprocess_pvalue(e: f64) -> f64 {
572    (1.0 / e).min(1.0)
573}
574
575// ─────────────────────────── recalibration map ──────────────────────────────
576
577fn sigmoid(x: f64) -> f64 {
578    if x >= 0.0 {
579        1.0 / (1.0 + (-x).exp())
580    } else {
581        let e = x.exp();
582        e / (1.0 + e)
583    }
584}
585
586fn logit(p: f64) -> f64 {
587    (p / (1.0 - p)).ln()
588}
589
590/// A learned **recalibration map** `p ↦ σ(a + b·logit p)` — the post-hoc
591/// correction that turns your stated probabilities into ones that match your
592/// realised frequencies.
593///
594/// `a` is bias on the log-odds scale (`≠ 0` ⇒ over/under-confident on average);
595/// `b` is the slope (`b < 1` ⇒ forecasts too extreme, `b > 1` ⇒ too timid).
596/// Perfect calibration is `(a, b) = (0, 1)`, the identity. Apply it with
597/// [`Recalibration::apply`].
598#[derive(Clone, Copy, Debug, PartialEq)]
599pub struct Recalibration {
600    pub a: f64,
601    pub b: f64,
602    /// How many resolved samples the fit rests on — i.e. how far to trust it.
603    pub n: usize,
604}
605
606impl Recalibration {
607    /// The identity map — "no correction yet", the small-`n` fallback.
608    pub fn identity(n: usize) -> Self {
609        Recalibration { a: 0.0, b: 1.0, n }
610    }
611
612    /// Correct a single probability through the map.
613    pub fn apply(&self, p: f64) -> f64 {
614        sigmoid(self.a + self.b * logit(p.clamp(1e-6, 1.0 - 1e-6)))
615    }
616}
617
618/// Which shape the correction map actually took.
619///
620/// Surfaced because a collapsed map is indistinguishable from a broken one at the
621/// call site: once `b` hits `0`, `decide --prob 0.99` and `decide --prob 0.55`
622/// return the same act, and a user who is not told why will file a bug. It is not
623/// a bug — it is the fit reporting that the stated numbers carried no information
624/// about the outcomes — but it has to say so out loud.
625#[derive(Clone, Copy, Debug, PartialEq, Eq)]
626pub enum MapKind {
627    /// No correction earned yet (or none applied): the stated probability is used
628    /// exactly as given.
629    Identity,
630    /// A fitted `sigma(a + b*logit p)` with `b > 0` — the ordinary case, where
631    /// your ranking is kept and only the level is moved.
632    Logistic,
633    /// The slope collapsed to `b = 0`. Your stated confidence did not track the
634    /// outcomes, so every input maps to the same corrected number: your base rate.
635    Constant,
636}
637
638impl MapKind {
639    /// The stable wire name, for `--json` and the MCP tools.
640    pub fn as_str(self) -> &'static str {
641        match self {
642            MapKind::Identity => "identity",
643            MapKind::Logistic => "logistic",
644            MapKind::Constant => "constant",
645        }
646    }
647}
648
649impl Recalibration {
650    /// Which shape this map took — see [`MapKind`].
651    pub fn kind(&self) -> MapKind {
652        if self.b == 0.0 {
653            MapKind::Constant
654        } else if self.a == 0.0 && self.b == 1.0 {
655            MapKind::Identity
656        } else {
657            MapKind::Logistic
658        }
659    }
660}
661
662/// Fit a **ridge-regularised logistic recalibration** `σ(a + b·logit p)` by
663/// Newton–Raphson, penalising departure from the identity `(0, 1)` with strength
664/// `ridge`.
665///
666/// The penalty is what makes the fit safe at small `n`: with few resolutions the
667/// map barely leaves the identity (you have not *earned* a correction yet), and
668/// it only develops real bias/slope as evidence accumulates — the same
669/// borrow-strength logic as [`shrink_toward`]. The ridge also tames the separable
670/// case (every bold call right), where the unpenalised MLE would diverge to
671/// infinity. Returns `None` for an empty record.
672pub fn fit_recalibration(samples: &[Sample], ridge: f64) -> Option<Recalibration> {
673    if samples.is_empty() {
674        return None;
675    }
676    let xs: Vec<f64> = samples
677        .iter()
678        .map(|s| logit(s.prob.clamp(1e-6, 1.0 - 1e-6)))
679        .collect();
680    // The penalised objective: NLL + (ridge/2)·[a² + (b−1)²]. Newton is only
681    // trusted as far as this actually decreases.
682    let objective = |a: f64, b: f64| -> f64 {
683        let mut acc = 0.5 * ridge * (a * a + (b - 1.0).powi(2));
684        for (x, s) in xs.iter().zip(samples) {
685            let z = a + b * x;
686            // softplus(z) − y·z, computed so that large |z| cannot overflow.
687            let softplus = if z > 0.0 {
688                z + (-z).exp().ln_1p()
689            } else {
690                z.exp().ln_1p()
691            };
692            acc += softplus - s.outcome * z;
693        }
694        acc
695    };
696
697    let (mut a, mut b) = (0.0f64, 1.0f64);
698    let mut converged = false;
699    for _ in 0..100 {
700        // Gradient g and Hessian H of the objective above.
701        let (mut ga, mut gb) = (ridge * a, ridge * (b - 1.0));
702        let (mut haa, mut hab, mut hbb) = (ridge, 0.0, ridge);
703        for (x, s) in xs.iter().zip(samples) {
704            let mu = sigmoid(a + b * x);
705            let w = mu * (1.0 - mu);
706            let r = mu - s.outcome;
707            ga += r;
708            gb += r * x;
709            haa += w;
710            hab += w * x;
711            hbb += w * x * x;
712        }
713        // At the b = 0 boundary, a positive gb means the objective wants to push
714        // b further negative; the constraint holds it, and that is optimal.
715        let gb_free = if b <= 0.0 && gb > 0.0 { 0.0 } else { gb };
716        if ga.abs() < 1e-10 && gb_free.abs() < 1e-10 {
717            converged = true;
718            break;
719        }
720        let det = haa * hbb - hab * hab;
721        if !(det.is_finite() && det > 1e-12) {
722            break;
723        }
724        let da = (hbb * ga - hab * gb) / det;
725        let db = (haa * gb - hab * ga) / det;
726
727        // Backtracking line search. The undamped Newton step this used to take
728        // DIVERGES whenever the fit wanders into the saturated region: there
729        // every mu is ~0 or ~1, so the Hessian weights w = mu(1−mu) vanish while
730        // the gradient does not, and the step overshoots further each time.
731        //
732        // Measured on 200 calls all stated at 0.9 that came true half the time —
733        // an agent with a narrow confidence vocabulary, which the report's own
734        // "confidence vocab" line exists to notice — it returned a = 66, b = 146,
735        // a map that corrects 0.9 UP to 1.0 for a forecaster who is right half
736        // the time. Exactly the direction of error this tool exists to catch.
737        let f0 = objective(a, b);
738        let mut step = 1.0;
739        let mut moved = false;
740        for _ in 0..40 {
741            // Projected Newton: the slope is constrained to b >= 0, because a
742            // recalibration map must be non-decreasing. Higher stated confidence
743            // mapping to a LOWER corrected probability is not a correction, it is
744            // an inversion, and handing one to `decide` would be worse than
745            // handing it nothing.
746            //
747            // An unconstrained fit reaches b < 0 whenever the observed
748            // frequencies do not rise with the forecast — which at small n is
749            // usually noise. Measured on a 15-claim fixture where twelve 0.9s
750            // failed and a lone 0.6 came true, it converged to b = -0.69.
751            // Pinning b at 0 there collapses the map to a constant, which is
752            // exactly what the isotonic fit does with the same data when
753            // pool-adjacent-violators merges the whole range into one block.
754            let (na, nb) = (a - step * da, (b - step * db).max(0.0));
755            if na.is_finite() && nb.is_finite() && objective(na, nb) <= f0 {
756                if (na - a).abs() < 1e-15 && (nb - b).abs() < 1e-15 {
757                    break; // the projection pinned us; no progress available
758                }
759                a = na;
760                b = nb;
761                moved = true;
762                break;
763            }
764            step *= 0.5;
765        }
766        if !moved {
767            // No downhill step of any size: we are at the optimum to numerical
768            // precision, or the problem is degenerate.
769            converged = true;
770            break;
771        }
772        if (step * da).abs() < 1e-10 && (step * db).abs() < 1e-10 {
773            converged = true;
774            break;
775        }
776    }
777
778    // Refuse to hand back a correction the solver did not actually find. The
779    // identity map says "no correction", which is the honest answer when the fit
780    // will not settle — never a confidently wrong one.
781    let candidate = Recalibration {
782        a,
783        b,
784        n: samples.len(),
785    };
786    if converged && a.is_finite() && b.is_finite() && recalibration_is_sane(&candidate, samples) {
787        Some(candidate)
788    } else {
789        Some(Recalibration::identity(samples.len()))
790    }
791}
792
793/// Three cheap invariants a usable recalibration map must satisfy.
794///
795/// This is belt-and-braces on top of the line search, and it is here because of
796/// how this function failed: a diverged fit does not error, it returns a
797/// confident number pointing the wrong way, and the evidence gate had already
798/// decided to trust it. Every other defect in this program fails passively; this
799/// one pushed a 50%-accurate forecaster's stated 0.9 up to 1.0.
800///
801/// 1. The map must send `[0,1]` into `[0,1]` — free, given it is a sigmoid, but
802///    it also catches a non-finite `a` or `b` slipping through.
803/// 2. It must be **monotone non-decreasing**: correcting a higher stated
804///    probability to a lower corrected one is never a calibration correction.
805/// 3. It must agree in direction with the **isotonic (PAV) fit** that [`corp_brier`]
806///    already computes. PAV cannot diverge by construction — it is the
807///    least-squares monotone fit, not an iterative solve — so it is a free oracle
808///    for what the correction ought to look like. If the parametric map says
809///    "raise this" where the isotonic curve says "lower it", the parametric one
810///    is wrong.
811fn recalibration_is_sane(r: &Recalibration, samples: &[Sample]) -> bool {
812    // 1 + 2: sample the map across the unit interval.
813    let grid: [f64; 11] = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];
814    let mut prev = f64::NEG_INFINITY;
815    for p in grid {
816        let q = r.apply(p);
817        if !q.is_finite() || !(0.0..=1.0).contains(&q) {
818            return false;
819        }
820        if q + 1e-9 < prev {
821            return false; // non-monotone
822        }
823        prev = q;
824    }
825
826    // 3: cross-check the direction against the isotonic fit on the same data.
827    let Some(corp) = corp_brier(samples) else {
828        return true;
829    };
830    let (mut checked, mut disagreements) = (0usize, 0usize);
831    for (s, &iso) in samples.iter().zip(corp.recalibrated.iter()) {
832        let parametric = r.apply(s.prob) - s.prob;
833        let isotonic = iso - s.prob;
834        // Only meaningful where both say something worth saying.
835        if parametric.abs() < 0.02 || isotonic.abs() < 0.02 {
836            continue;
837        }
838        checked += 1;
839        if parametric.signum() != isotonic.signum() {
840            disagreements += 1;
841        }
842    }
843    // The isotonic fit is noisy at small n, so a handful of local disagreements
844    // are expected; a majority of them means the parametric fit points the wrong
845    // way overall, which is the failure being guarded against.
846    checked == 0 || (disagreements * 2) <= checked
847}
848
849// ─────────────────────────── decision gate ──────────────────────────────────
850
851/// What to do with a stated probability once the stakes are taken into account —
852/// the *operational* end of calibration, where a number becomes an action.
853#[derive(Clone, Copy, Debug, PartialEq, Eq)]
854pub enum Act {
855    /// Corrected confidence clears the bar for the stakes — commit.
856    Proceed,
857    /// In the doubt zone — gather more evidence before you commit.
858    Verify,
859    /// More likely to fail than succeed *after correction* — replan or escalate
860    /// rather than spend a verification cycle on a probable dead end.
861    Abstain,
862}
863
864/// A recommendation for one prospective action: what to do, the corrected
865/// probability it rests on, and how much room there was in the call.
866#[derive(Clone, Copy, Debug, PartialEq)]
867pub struct Decision {
868    pub act: Act,
869    /// The probability the decision actually used: your stated `p` after the
870    /// track-record correction (or the raw `p` when no correction was earned).
871    pub adjusted_p: f64,
872    /// Chow's break-even confidence to proceed without verifying,
873    /// `1 − verify_cost/stake`. Rises toward `1` as the stakes grow.
874    pub proceed_threshold: f64,
875    /// `adjusted_p − proceed_threshold`; `≥ 0` ⇒ proceed. The room you had.
876    pub margin: f64,
877    /// Which correction was applied to get from the stated `p` to `adjusted_p`.
878    /// [`MapKind::Constant`] is the one worth reading aloud: the act no longer
879    /// depends on the number you passed in.
880    pub map_kind: MapKind,
881}
882
883/// Within Chow's reject region, the boundary between *verify* and *abstain*: below
884/// an even-odds corrected probability the action is more likely to fail than
885/// succeed, so replanning beats verifying. Parameter-free by design.
886const ABSTAIN_BELOW: f64 = 0.5;
887
888/// **Decision gate** — turn a stated probability into an action under stakes.
889///
890/// This is the step the calibration literature finds agents skip: they can *state*
891/// their uncertainty yet still barrel into an irreversible action. The gate closes
892/// that loop in two principled moves:
893///
894/// 1. **Correct the number.** Verbalized confidence is the least reliable signal, so
895///    the stated `p` is first pushed through the learned [`Recalibration`] map (pass
896///    `Some` only once the e-process has *earned* it; `None` leaves `p` untouched) —
897///    your best estimate of the true success probability given your track record.
898/// 2. **Threshold by the stakes.** By Chow's optimal reject rule, proceeding is worth
899///    it only when the expected cost of a wrong action, `(1 − p̂)·stake`, is below the
900///    cost of a verification step — i.e. when `p̂ ≥ 1 − verify_cost/stake`. The
901///    threshold climbs toward `1` as `stake` grows: the more irreversible the action,
902///    the closer to certain you must be to skip the check. Below the threshold the
903///    gate says *verify*, unless the corrected odds are worse than even, where it says
904///    *abstain* (replan) instead.
905///
906/// `stake` is the cost of a wrong proceed relative to one verification (`1.0` =
907/// ordinary; raise it for consequential or irreversible calls). `verify_cost` is the
908/// cost of that check in the same unit. Pure: no I/O, no ledger — the caller supplies
909/// the (evidence-gated) map.
910pub fn decide(p: f64, recal: Option<Recalibration>, stake: f64, verify_cost: f64) -> Decision {
911    let p = p.clamp(0.0, 1.0);
912    let (adjusted_p, map_kind) = match recal {
913        Some(r) => (r.apply(p), r.kind()),
914        None => (p, MapKind::Identity),
915    };
916    let stake = stake.max(0.0);
917    // Chow's reject threshold for a one-sided act/verify decision. With nothing at
918    // stake there is nothing to verify against, so proceed.
919    let proceed_threshold = if stake > 0.0 {
920        (1.0 - verify_cost.max(0.0) / stake).clamp(0.0, 1.0)
921    } else {
922        0.0
923    };
924    let margin = adjusted_p - proceed_threshold;
925    let act = if adjusted_p >= proceed_threshold {
926        Act::Proceed
927    } else if adjusted_p >= ABSTAIN_BELOW {
928        Act::Verify
929    } else {
930        Act::Abstain
931    };
932    Decision {
933        act,
934        adjusted_p,
935        proceed_threshold,
936        margin,
937        map_kind,
938    }
939}
940
941// ───────────────────────── small-sample / over-time bands ───────────────────
942
943/// A tiny, dependency-free SplitMix64 PRNG — enough for a reproducible bootstrap.
944fn splitmix64(state: &mut u64) -> u64 {
945    *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
946    let mut z = *state;
947    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
948    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
949    z ^ (z >> 31)
950}
951
952/// Linear-interpolated quantile of an already-sorted slice.
953fn quantile_sorted(sorted: &[f64], q: f64) -> f64 {
954    let q = q.clamp(0.0, 1.0);
955    let pos = q * (sorted.len() as f64 - 1.0);
956    let lo = pos.floor() as usize;
957    let hi = pos.ceil() as usize;
958    let frac = pos - lo as f64;
959    sorted[lo] * (1.0 - frac) + sorted[hi] * frac
960}
961
962/// **Bootstrap percentile interval** for the Brier score — an intuitive band on
963/// "how far luck alone could move this number." Deterministic given `seed`, so the
964/// report is reproducible run-to-run. `level` is the two-sided coverage (e.g.
965/// `0.95`); `resamples` ≥ ~2000 is sensible. Returns `None` for fewer than two
966/// samples (a one-sample band is meaningless).
967///
968/// Note: the percentile interval skews a touch *narrow* at very small `n`, so
969/// treat it as a rough band — the rigorous, optional-stopping-valid calibration
970/// call is [`calibration_eprocess`], not this.
971pub fn brier_ci_bootstrap(
972    samples: &[Sample],
973    level: f64,
974    resamples: usize,
975    seed: u64,
976) -> Option<(f64, f64)> {
977    let n = samples.len();
978    if n < 2 || resamples == 0 {
979        return None;
980    }
981    let mut state = seed;
982    let mut briers = Vec::with_capacity(resamples);
983    for _ in 0..resamples {
984        let mut sum = 0.0;
985        for _ in 0..n {
986            let idx = (splitmix64(&mut state) % n as u64) as usize;
987            let s = &samples[idx];
988            sum += (s.prob - s.outcome).powi(2);
989        }
990        briers.push(sum / n as f64);
991    }
992    briers.sort_by(f64::total_cmp);
993    let alpha = (1.0 - level) / 2.0;
994    Some((
995        quantile_sorted(&briers, alpha),
996        quantile_sorted(&briers, 1.0 - alpha),
997    ))
998}
999
1000/// **Recency-weighted (EWMA) Brier** over the samples in the given order, with the
1001/// given `half_life` in samples (the lag at which a forecast's weight halves).
1002/// Pass samples chronologically: this is the "how am I doing *lately*" number, to
1003/// be read against the lifetime Brier as a trend. `None` for an empty record.
1004///
1005/// Deliberately *not* a control-chart drift alarm: at the few-dozen-sample scale
1006/// an agent lives in, hard EWMA/CUSUM limits false-alarm. This is a descriptive
1007/// trend, not a significance test.
1008pub fn ewma_brier(samples: &[Sample], half_life: f64) -> Option<f64> {
1009    let first = samples.first()?;
1010    let lambda = 1.0 - 0.5_f64.powf(1.0 / half_life.max(1e-9));
1011    let mut ewma = (first.prob - first.outcome).powi(2);
1012    for s in &samples[1..] {
1013        let b = (s.prob - s.outcome).powi(2);
1014        ewma = lambda * b + (1.0 - lambda) * ewma;
1015    }
1016    Some(ewma)
1017}
1018
1019/// How many **distinct forecast probabilities** appear. A coarse confidence
1020/// vocabulary (you only ever say 0.5/0.7/0.9) caps the resolution you can
1021/// achieve — the LLM-calibration literature finds verbalized confidence clusters
1022/// on a few round numbers. Grouped by exact bit pattern.
1023pub fn distinct_forecasts(samples: &[Sample]) -> usize {
1024    samples
1025        .iter()
1026        .map(|s| s.prob.to_bits())
1027        .collect::<std::collections::BTreeSet<_>>()
1028        .len()
1029}
1030
1031// ───────────────────────── selective prediction ─────────────────────────────
1032
1033/// The 0/1 *directional* error of one forecast: you lean "yes" when `p > 0.5`
1034/// and "no" when `p < 0.5`; the call is wrong when the leaned side did not happen.
1035/// An exact `0.5` picks no side and scores half-error.
1036fn directional_error(s: &Sample) -> f64 {
1037    if (s.prob - 0.5).abs() < 1e-12 {
1038        0.5
1039    } else if s.prob > 0.5 {
1040        1.0 - s.outcome // leaned yes → wrong if it did not happen
1041    } else {
1042        s.outcome // leaned no → wrong if it happened
1043    }
1044}
1045
1046/// A risk–coverage curve: how your error rate falls as you abstain from your
1047/// least-confident calls.
1048#[derive(Clone, Debug)]
1049pub struct RiskCoverage {
1050    /// `(coverage, risk)` points, coverage ascending from `1/n` (act only on the
1051    /// single most-confident call) to `1.0` (act on everything).
1052    pub points: Vec<(f64, f64)>,
1053    /// Area under the risk–coverage curve (mean risk across coverage levels).
1054    /// **Lower is better**: your confident calls really are your reliable ones.
1055    pub aurcc: f64,
1056    /// Error rate at full coverage — acting on every call.
1057    pub risk_at_full: f64,
1058}
1059
1060impl RiskCoverage {
1061    /// Risk (error rate) when acting only on the most-confident `target` fraction
1062    /// of calls — the smallest coverage point `≥ target`.
1063    pub fn risk_at(&self, target: f64) -> f64 {
1064        self.points
1065            .iter()
1066            .find(|(c, _)| *c >= target)
1067            .or_else(|| self.points.last())
1068            .map(|(_, r)| *r)
1069            .unwrap_or(0.0)
1070    }
1071}
1072
1073/// **Selective prediction**: rank forecasts by *boldness* (`max(p, 1-p)`) and, for
1074/// each coverage level, report the directional error among the calls you would
1075/// keep. This answers "how good am I when I only commit to my surest calls?" — the
1076/// agent's version of knowing *when to act on its own judgement versus flag
1077/// uncertainty*. On a forecaster whose confidence means something, risk falls as
1078/// coverage shrinks; if it does not (or rises), the confidence ranking is noise.
1079/// Returns `None` for an empty record.
1080pub fn risk_coverage(samples: &[Sample]) -> Option<RiskCoverage> {
1081    if samples.is_empty() {
1082        return None;
1083    }
1084    let n = samples.len();
1085    let mut order: Vec<usize> = (0..n).collect();
1086    // Most confident first; total_cmp keeps it panic-free and ties stable-ish.
1087    order.sort_by(|&a, &b| {
1088        let ca = samples[a].prob.max(1.0 - samples[a].prob);
1089        let cb = samples[b].prob.max(1.0 - samples[b].prob);
1090        cb.total_cmp(&ca)
1091    });
1092    let mut points = Vec::with_capacity(n);
1093    let mut cum_err = 0.0;
1094    for (k, &i) in order.iter().enumerate() {
1095        cum_err += directional_error(&samples[i]);
1096        let coverage = (k + 1) as f64 / n as f64;
1097        points.push((coverage, cum_err / (k + 1) as f64));
1098    }
1099    let risk_at_full = points.last().map(|&(_, r)| r).unwrap_or(0.0);
1100    let aurcc = points.iter().map(|&(_, r)| r).sum::<f64>() / n as f64;
1101    Some(RiskCoverage {
1102        points,
1103        aurcc,
1104        risk_at_full,
1105    })
1106}
1107
1108// ───────────────────────── elicitation aids ─────────────────────────────────
1109
1110/// **Dialectical aggregation** of two of your own estimates — Herzog & Hertwig's
1111/// "crowd within" (2009). Make a first estimate, then a second that deliberately
1112/// assumes the first is wrong ("consider the opposite — give two reasons it might
1113/// be off"), and average them: the arithmetic mean recovers roughly half the
1114/// accuracy gain of consulting a *second person*. This is a pre-resolution input
1115/// aid, not a score; the inputs are clamped to `[0, 1]`.
1116pub fn dialectical_mean(p1: f64, p2: f64) -> f64 {
1117    (p1.clamp(0.0, 1.0) + p2.clamp(0.0, 1.0)) / 2.0
1118}
1119
1120// ───────────────────────── CORP decomposition (P0-4) ────────────────────────
1121
1122/// The **CORP** decomposition of the Brier score (Dimitriadis, Gneiting & Jordan,
1123/// PNAS 2021): *Consistent, Optimally binned, Reproducible, Pool-adjacent-violators*.
1124///
1125/// [`decompose`] groups forecasts by their exact value, which is what makes its
1126/// identity exact — but at an agent's sample sizes most exact-value groups hold
1127/// one or two claims, and a group of one always has observed frequency 0 or 1,
1128/// so its "calibration error" is the largest it could possibly be. Simulating a
1129/// *perfectly calibrated* forecaster using two-decimal probabilities, where the
1130/// true calibration error is zero:
1131///
1132/// | n | exact-value reliability | CORP MCB |
1133/// |---|---|---|
1134/// | 50 | 0.138 | 0.034 |
1135/// | 200 | 0.073 | 0.014 |
1136///
1137/// The shipped number told a well-calibrated user they had a calibration problem.
1138///
1139/// CORP replaces binning with isotonic regression (pool-adjacent-violators): the
1140/// best *non-decreasing* recalibration of the forecasts. Then
1141///
1142/// - `MCB` (miscalibration) `= S(forecast) − S(recalibrated)`
1143/// - `DSC` (discrimination) `= S(base rate) − S(recalibrated)`
1144/// - `UNC` (uncertainty) `= S(base rate)`
1145///
1146/// and `S = MCB − DSC + UNC` still holds exactly, with no bins and no tuning
1147/// parameter — the "exact decomposition" property survives intact. There is no
1148/// free lunch: MCB is optimistically biased because the isotonic fit is chosen on
1149/// the same data, which is exactly why [`mcb_null_quantile`] exists to say how
1150/// large it would be for someone with no calibration error at all.
1151#[derive(Clone, Debug, PartialEq)]
1152pub struct Corp {
1153    /// Miscalibration: how much score you would save by relabelling your
1154    /// probabilities with the frequencies that actually followed them.
1155    pub mcb: f64,
1156    /// Discrimination: how much your (recalibrated) forecasts beat the base
1157    /// rate. `0` means your confidence carries no information about which of
1158    /// your calls come true.
1159    pub dsc: f64,
1160    /// Uncertainty: the irreducible difficulty of the questions you chose.
1161    pub unc: f64,
1162    /// The Brier score of the forecasts as stated.
1163    pub score: f64,
1164    /// The PAV-recalibrated probability for each sample, in input order — the
1165    /// reliability curve, with no bin-width choice to argue about.
1166    pub recalibrated: Vec<f64>,
1167}
1168
1169/// Compute the [`Corp`] decomposition. `None` for an empty sample.
1170pub fn corp_brier(samples: &[Sample]) -> Option<Corp> {
1171    let n = samples.len();
1172    if n == 0 {
1173        return None;
1174    }
1175    // 1) Sort by forecast, pooling exact ties into groups of (prob, Σy, count).
1176    let mut idx: Vec<usize> = (0..n).collect();
1177    idx.sort_by(|&a, &b| samples[a].prob.total_cmp(&samples[b].prob));
1178    let mut groups: Vec<(f64, f64, usize)> = Vec::new();
1179    for &i in &idx {
1180        let s = &samples[i];
1181        match groups.last_mut() {
1182            Some(g) if g.0 == s.prob => {
1183                g.1 += s.outcome;
1184                g.2 += 1;
1185            }
1186            _ => groups.push((s.prob, s.outcome, 1)),
1187        }
1188    }
1189    // 2) Pool adjacent violators. Blocks carry (Σy, Σcount, #groups merged).
1190    let mut blocks: Vec<(f64, usize, usize)> = Vec::with_capacity(groups.len());
1191    for &(_, sy, c) in &groups {
1192        blocks.push((sy, c, 1));
1193        while blocks.len() > 1 {
1194            let (s2, c2, g2) = blocks[blocks.len() - 1];
1195            let (s1, c1, _) = blocks[blocks.len() - 2];
1196            if s1 / c1 as f64 > s2 / c2 as f64 {
1197                blocks.pop();
1198                let last = blocks.last_mut().unwrap();
1199                last.0 += s2;
1200                last.1 += c2;
1201                last.2 += g2;
1202            } else {
1203                break;
1204            }
1205        }
1206    }
1207    // 3) Expand the fitted values back into the original sample order.
1208    let mut group_fit = Vec::with_capacity(groups.len());
1209    for &(sy, c, g) in &blocks {
1210        group_fit.extend(std::iter::repeat_n(sy / c as f64, g));
1211    }
1212    let mut recalibrated = vec![0.0; n];
1213    let mut k = 0usize;
1214    for (gi, &(_, _, c)) in groups.iter().enumerate() {
1215        for _ in 0..c {
1216            recalibrated[idx[k]] = group_fit[gi];
1217            k += 1;
1218        }
1219    }
1220    // 4) The three terms, each a Brier score against the same outcomes.
1221    let ybar = samples.iter().map(|s| s.outcome).sum::<f64>() / n as f64;
1222    let (mut score, mut s_cal, mut unc) = (0.0, 0.0, 0.0);
1223    for (i, s) in samples.iter().enumerate() {
1224        score += (s.prob - s.outcome).powi(2);
1225        s_cal += (recalibrated[i] - s.outcome).powi(2);
1226        unc += (ybar - s.outcome).powi(2);
1227    }
1228    let nf = n as f64;
1229    let (score, s_cal, unc) = (score / nf, s_cal / nf, unc / nf);
1230    Some(Corp {
1231        mcb: score - s_cal,
1232        dsc: unc - s_cal,
1233        unc,
1234        score,
1235        recalibrated,
1236    })
1237}
1238
1239/// The **noise floor** for [`Corp::mcb`]: the `q`-quantile of the miscalibration
1240/// a *perfectly calibrated* forecaster would score while making exactly these
1241/// calls, at exactly this sample size.
1242///
1243/// This is the number that turns "your calibration error is 0.034" from a verdict
1244/// into evidence. MCB is fitted on the same data it scores, so it is never zero,
1245/// and how far above zero it sits depends on n and on the spread of the
1246/// forecasts — quantities the user cannot hold in their head. Drawing
1247/// `y ~ Bernoulli(p)` from the user's own forecasts and re-running CORP answers
1248/// it directly.
1249///
1250/// Deterministic: the same samples and seed always give the same floor, so a
1251/// report never changes underneath a user who re-runs it. `None` below two
1252/// samples.
1253pub fn mcb_null_quantile(samples: &[Sample], draws: usize, q: f64, seed: u64) -> Option<f64> {
1254    if samples.len() < 2 || draws == 0 {
1255        return None;
1256    }
1257    let mut state = seed;
1258    let mut sim: Vec<Sample> = samples.to_vec();
1259    let mut mcbs = Vec::with_capacity(draws);
1260    for _ in 0..draws {
1261        for (t, s) in sim.iter_mut().zip(samples) {
1262            let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1263            t.outcome = if u < s.prob { 1.0 } else { 0.0 };
1264        }
1265        mcbs.push(corp_brier(&sim)?.mcb);
1266    }
1267    mcbs.sort_by(f64::total_cmp);
1268    Some(quantile_sorted(&mcbs, q))
1269}
1270
1271// ──────────────────── multi-strategy e-process (P0-3a) ──────────────────────
1272
1273/// Bets on the overall sign of `y − p`: the original single strategy. Detects a
1274/// forecaster who is too high (or too low) *on the whole*.
1275fn bet_bias(_p: f64) -> f64 {
1276    1.0
1277}
1278
1279/// Bets on the *extremity* of the forecast rather than its direction: it flips
1280/// sign at `p = 0.5`, so being too sure when saying 0.9 and too sure when saying
1281/// 0.1 push the wealth the same way instead of cancelling.
1282fn bet_extremity(p: f64) -> f64 {
1283    if p < 0.5 {
1284        1.0
1285    } else if p > 0.5 {
1286        -1.0
1287    } else {
1288        0.0
1289    }
1290}
1291
1292/// The same idea weighted by how extreme the forecast is, so a 0.99 counts for
1293/// more than a 0.51.
1294fn bet_extremity_scaled(p: f64) -> f64 {
1295    2.0 * (0.5 - p)
1296}
1297
1298/// The betting strategies `h(p)`, each bounded by `1` in absolute value and each
1299/// a function of the **stated forecast only**.
1300///
1301/// That restriction is what keeps the guarantee: `p` is fixed before the outcome
1302/// is seen, so `E[h(p)(y − p) | past] = 0` under the calibration null and every
1303/// wealth process remains a non-negative martingale. Averaging e-processes
1304/// computed on the same data sequence is again an e-process, so mixing over
1305/// strategies costs validity nothing and buys power against patterns a single
1306/// strategy cannot see.
1307const STRATEGIES: [fn(f64) -> f64; 3] = [bet_bias, bet_extremity, bet_extremity_scaled];
1308
1309/// Natural log of the mixture e-process over [`STRATEGIES`] × [`EPROCESS_LAMBDAS`].
1310///
1311/// Computed in log space because real miscalibration produces e-values with
1312/// dozens of digits, which overflow `f64` long before they stop being
1313/// meaningful. Every factor is at least `0.1`, so the logs stay finite.
1314///
1315/// This supersedes [`calibration_eprocess`], which bets only on the overall sign
1316/// of `y − p` and is therefore **blind to symmetric overconfidence**: a
1317/// forecaster who says 90% when the truth is 65% *and* says 10% when the truth is
1318/// 35% has errors that cancel exactly. Measured on such a ledger at n = 1000, the
1319/// single-strategy version returns 0.087 — no evidence at all — where this one
1320/// returns a number with 65 digits. That case is not exotic; it is what an agent
1321/// looks like the moment it starts logging "this will fail" at 0.15 alongside
1322/// "this will pass" at 0.85.
1323pub fn calibration_log_eprocess(samples: &[Sample]) -> Option<f64> {
1324    let steps: Vec<Step> = samples
1325        .iter()
1326        .map(|s| Step::graded(s.prob, s.outcome))
1327        .collect();
1328    calibration_log_eprocess_seq(&steps)
1329}
1330
1331/// One step of the evidence sequence: what you said, and what happened — or
1332/// `None` when the claim is due but still ungraded.
1333#[derive(Clone, Copy, Debug, PartialEq)]
1334pub struct Step {
1335    /// The stated probability, fixed before the outcome.
1336    pub prob: f64,
1337    /// `1.0`/`0.0` once graded; `None` while the claim is an open gap.
1338    pub outcome: Option<f64>,
1339}
1340
1341impl Step {
1342    pub fn graded(prob: f64, outcome: f64) -> Self {
1343        Step {
1344            prob,
1345            outcome: Some(outcome),
1346        }
1347    }
1348    /// A due-but-ungraded claim — a gap in the record.
1349    pub fn gap(prob: f64) -> Self {
1350        Step {
1351            prob,
1352            outcome: None,
1353        }
1354    }
1355}
1356
1357/// The mixture e-process over a sequence that may contain **gaps**.
1358///
1359/// A graded step contributes its ordinary factor `1 + λ·h(p)·(y − p)`. An
1360/// ungraded step contributes the smallest factor it could possibly have
1361/// contributed,
1362///
1363/// ```text
1364/// min over y in {0,1} of  1 + λ·h(p)·(y − p)
1365/// ```
1366///
1367/// taken **per mixture component**, since each `(strategy, λ)` pair is its own
1368/// wealth process.
1369///
1370/// # Why this is valid
1371///
1372/// The two candidate factors are `1 + λh(1−p)` (had it resolved YES) and
1373/// `1 − λhp` (had it resolved NO). Under the calibration null the outcome is YES
1374/// with probability exactly `p`, so their `p`-weighted average is
1375///
1376/// ```text
1377/// p(1 + λh(1−p)) + (1−p)(1 − λhp) = 1
1378/// ```
1379///
1380/// identically. A weighted average of two numbers is at least their minimum, so
1381/// **the min is ≤ 1**, and it is also ≤ the true factor whichever outcome the
1382/// claim would have had. The gap-filled wealth is therefore pointwise ≤ the
1383/// fully-graded martingale at every `n`, and is itself a non-negative
1384/// supermartingale starting at `1`. Ville's inequality covers supermartingales,
1385/// so the bound `P(∃k : M_k ≥ 1/α) ≤ α` carries over unchanged — and across
1386/// repeated views, whatever is ungraded at view time `t` still satisfies
1387/// `W'(t) ≤ M_n` for one fixed process `M`. The argument in `crate::evidence`
1388/// keeps its shape; this extends it by one sentence.
1389///
1390/// # Why it replaced stopping at the first gap
1391///
1392/// Stopping is the wrong response to gaps. Any prefix rule yields about
1393/// `(1−g)/g` claims for an ungraded rate `g`, so at 35% ungraded the sequence is
1394/// ~2 claims long no matter how much you have logged — and partitioning does not
1395/// rescue it, because K partitions give K short sequences and a K-fold mixture
1396/// penalty that cancels the gain. Measured at n = 300, alarm `e ≥ 20`, peeking
1397/// every 5:
1398///
1399/// | graded | rule | usable n | P(detect) | P(false alarm) |
1400/// |---|---|---|---|---|
1401/// | 100% | either | 300 | 1.000 | 0.013 |
1402/// | 90% | stop at gap | 10.1 | 0.047 | 0.000 |
1403/// | 90% | gap-filled | 270.1 | 1.000 | 0.000 |
1404/// | 65% | stop at gap | 2.0 | 0.000 | 0.000 |
1405/// | 65% | gap-filled | 194.7 | 1.000 | 0.000 |
1406///
1407/// False alarms cannot rise, because wealth only ever shrinks relative to the
1408/// graded process. The cost is real, though, and it is not free power: against a
1409/// *diffuse* alternative (per-claim discrepancy ≤ 0.135 rather than 0.25),
1410/// detection falls from 0.587 at full grading to 0.003 at 65%. Gaps are priced,
1411/// not forgiven.
1412///
1413/// Two properties worth keeping: with `|λ| ≤ 0.9` every factor is at least `0.1`,
1414/// so a gap costs wealth rather than zeroing the process; and the cost scales
1415/// with how bold the ungraded claim was — an ungraded `0.95` costs more than an
1416/// ungraded `0.55`, which is the right incentive.
1417///
1418/// An undisciplined user's e-value therefore drifts down, so gaps can *hide*
1419/// miscalibration. They could already do that by freezing the test under the old
1420/// stopping rule, and neither direction can manufacture a false alarm.
1421pub fn calibration_log_eprocess_seq(steps: &[Step]) -> Option<f64> {
1422    if steps.is_empty() {
1423        return None;
1424    }
1425    let mut logw = [[0.0f64; EPROCESS_LAMBDAS.len()]; STRATEGIES.len()];
1426    for st in steps {
1427        for (k, h) in STRATEGIES.iter().enumerate() {
1428            let hp = h(st.prob);
1429            for (lw, &lam) in logw[k].iter_mut().zip(EPROCESS_LAMBDAS.iter()) {
1430                *lw += match st.outcome {
1431                    // mean zero under the calibration null
1432                    Some(y) => (lam * hp * (y - st.prob)).ln_1p(),
1433                    None => {
1434                        let yes = 1.0 + lam * hp * (1.0 - st.prob);
1435                        let no = 1.0 + lam * hp * (0.0 - st.prob);
1436                        yes.min(no).ln()
1437                    }
1438                };
1439            }
1440        }
1441    }
1442    // log-sum-exp, then divide by the number of mixture components.
1443    let all: Vec<f64> = logw.iter().flatten().copied().collect();
1444    let max = all.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1445    let lse = max + all.iter().map(|v| (v - max).exp()).sum::<f64>().ln();
1446    Some(lse - (all.len() as f64).ln())
1447}
1448
1449/// [`calibration_log_eprocess_seq`] on the natural scale, capped like
1450/// [`calibration_eprocess_v2`].
1451pub fn calibration_eprocess_seq(steps: &[Step]) -> Option<f64> {
1452    calibration_log_eprocess_seq(steps).map(|l| l.min(EPROCESS_LOG_CAP).exp())
1453}
1454
1455/// The evidence bar a recalibration map must clear before it is applied, and the
1456/// minimum record it must be fitted on.
1457///
1458/// These live here, in the pure core, rather than in the reporting layer, because
1459/// the CLI, the MCP tools, the report and the Python binding must all agree about
1460/// when a correction has been earned — and "defined once" is only true if there is
1461/// literally one definition.
1462pub const RECAL_MIN_E: f64 = 3.0;
1463pub const RECAL_MIN_N: usize = 6;
1464
1465/// Fit a recalibration map and decide whether the evidence has **earned** it.
1466///
1467/// `fit_on` is every graded call (more data makes a better correction);
1468/// `evidence` is the outcome-independent sequence the e-process may consume (see
1469/// `crate::evidence`). Separating them matters: the map is a description, and may
1470/// use everything; the gate is a test, and may only use a sequence whose order
1471/// was fixed before the outcomes were known.
1472///
1473/// Returns the fitted map, whether to apply it, and the e-value behind that call.
1474/// The map is returned either way — `earned` is the part that says to trust it.
1475pub fn gate_recalibration(
1476    fit_on: &[Sample],
1477    evidence: &[Sample],
1478    ridge: f64,
1479) -> (Option<Recalibration>, bool, Option<f64>) {
1480    let steps: Vec<Step> = evidence
1481        .iter()
1482        .map(|s| Step::graded(s.prob, s.outcome))
1483        .collect();
1484    gate_recalibration_seq(fit_on, &steps, ridge)
1485}
1486
1487/// [`gate_recalibration`] over a sequence that may contain gaps.
1488///
1489/// The minimum-`n` bar counts **graded** steps only: a gap carries no outcome, so
1490/// it is evidence about discipline, never about calibration, and must not buy a
1491/// correction the record has not earned.
1492pub fn gate_recalibration_seq(
1493    fit_on: &[Sample],
1494    evidence: &[Step],
1495    ridge: f64,
1496) -> (Option<Recalibration>, bool, Option<f64>) {
1497    let e = calibration_eprocess_seq(evidence);
1498    let recal = fit_recalibration(fit_on, ridge);
1499    let graded = evidence.iter().filter(|s| s.outcome.is_some()).count();
1500    let earned = recal.is_some() && e.is_some_and(|ev| ev >= RECAL_MIN_E) && graded >= RECAL_MIN_N;
1501    (recal, earned, e)
1502}
1503
1504/// The largest log e-value worth printing. Above this the exact figure is
1505/// meaningless — it already says "certain" far more emphatically than any
1506/// decision needs — and `exp` would produce `inf`, which serialises to `null`.
1507pub const EPROCESS_LOG_CAP: f64 = 27.63; // ≈ ln(10^12)
1508
1509/// **Sensitivity of the calibration test at this record**: of `sims` simulated forecasters
1510/// who made exactly these forecasts, in this order and with these gaps, but whose true
1511/// chance on each call was `0.5 + (1 − shrink)·(p − 0.5)`, the share the e-process flags
1512/// (final e-value at or above `alarm`). `shrink = 0.3` is a forecaster whose numbers are
1513/// 30% too far from 50/50.
1514///
1515/// A quiet test reads as a clean bill of health unless it says how loud a real error would
1516/// have been. Measured on the 0.4.2 binary by an outside review: 60 calls 30% too extreme
1517/// were caught in 0 of 40 runs. This is that measurement, on the reader's own forecasts.
1518/// Reproducible: the same `seed` gives the same rate. `None` when no step is graded or
1519/// `sims` is zero.
1520pub fn detection_rate(
1521    steps: &[Step],
1522    shrink: f64,
1523    alarm: f64,
1524    sims: usize,
1525    seed: u64,
1526) -> Option<f64> {
1527    if sims == 0 || !steps.iter().any(|s| s.outcome.is_some()) {
1528        return None;
1529    }
1530    let log_alarm = alarm.ln();
1531    let mut state = seed;
1532    let mut sim = steps.to_vec();
1533    let mut hits = 0usize;
1534    for _ in 0..sims {
1535        for (st, orig) in sim.iter_mut().zip(steps) {
1536            if orig.outcome.is_some() {
1537                let truth = (0.5 + (1.0 - shrink) * (orig.prob - 0.5)).clamp(0.0, 1.0);
1538                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1539                st.outcome = Some(if u < truth { 1.0 } else { 0.0 });
1540            }
1541        }
1542        if calibration_log_eprocess_seq(&sim).is_some_and(|l| l >= log_alarm) {
1543            hits += 1;
1544        }
1545    }
1546    Some(hits as f64 / sims as f64)
1547}
1548
1549/// The mixture e-value on the natural scale, capped at `10^12` so the report
1550/// never has to print a 66-digit integer or the word `inf`.
1551///
1552/// Use [`calibration_log_eprocess`] when comparing magnitudes; use this when a
1553/// number has to be shown or compared against a threshold like 20.
1554pub fn calibration_eprocess_v2(samples: &[Sample]) -> Option<f64> {
1555    calibration_log_eprocess(samples).map(|l| l.min(EPROCESS_LOG_CAP).exp())
1556}
1557
1558#[cfg(test)]
1559mod tests {
1560    use super::*;
1561
1562    fn approx(a: f64, b: f64) {
1563        assert!((a - b).abs() < 1e-9, "expected {a} ≈ {b}");
1564    }
1565
1566    // ───────────────────────── CORP (P0-4) ─────────────────────────
1567
1568    #[test]
1569    fn winkler_ratio_is_invariant_to_units() {
1570        // The same forecast and the same relative miss, in two units 1000x apart.
1571        // The raw score differs by 1000x; the ratio does not.
1572        let ns = |low, high, value| NumericSample {
1573            low,
1574            high,
1575            level: 0.8,
1576            value,
1577        };
1578        let small = ns(10.0, 20.0, 25.0);
1579        let large = ns(10_000.0, 20_000.0, 25_000.0);
1580        assert!((winkler(&large) - winkler(&small) * 1000.0).abs() < 1e-6);
1581        approx(
1582            winkler_ratio(&small).unwrap(),
1583            winkler_ratio(&large).unwrap(),
1584        );
1585        // A hit scores exactly 1.0: the width itself, and nothing more.
1586        approx(winkler_ratio(&ns(10.0, 20.0, 15.0)).unwrap(), 1.0);
1587        // A zero-width interval has no ratio to give.
1588        assert!(winkler_ratio(&ns(5.0, 5.0, 5.0)).is_none());
1589    }
1590
1591    #[test]
1592    fn recalibration_does_not_diverge_on_a_narrow_vocabulary() {
1593        // 200 calls, all stated at 0.9, that came true half the time. Every mu
1594        // saturates, the Hessian weights vanish, and the undamped Newton step
1595        // used to oscillate off to a = 66, b = 146 — a map that "corrects" 0.9
1596        // UP to 1.0 for a forecaster who is right half the time.
1597        let mut state = 11u64;
1598        let samples: Vec<Sample> = (0..200)
1599            .map(|_| {
1600                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1601                Sample::new(0.9, u < 0.5)
1602            })
1603            .collect();
1604        let r = fit_recalibration(&samples, 1.5).unwrap();
1605        assert!(r.a.is_finite() && r.b.is_finite());
1606        let corrected = r.apply(0.9);
1607        assert!(
1608            corrected < 0.75,
1609            "0.9 must be corrected DOWN toward the true 0.5, got {corrected}"
1610        );
1611        assert!(
1612            (corrected - 0.5).abs() < 0.2,
1613            "and should land near the truth, got {corrected}"
1614        );
1615    }
1616
1617    #[test]
1618    fn the_fitted_slope_is_never_negative() {
1619        // Twelve calls at 0.9 that all failed, plus one lucky 0.6. The observed
1620        // frequencies do not rise with the forecast, so an unconstrained fit
1621        // converges to b = -0.69 — a map that would correct a 0.9 to BELOW what
1622        // it corrects a 0.5 to. At n = 15 that is noise, and inverting the
1623        // ordering is not a calibration correction.
1624        let mut samples = vec![
1625            Sample::new(0.6, true),
1626            Sample::new(0.5, false),
1627            Sample::new(0.7, true),
1628        ];
1629        for _ in 0..12 {
1630            samples.push(Sample::new(0.9, false));
1631        }
1632        let r = fit_recalibration(&samples, 1.5).unwrap();
1633        assert!(r.b >= 0.0, "slope must not invert, got {}", r.b);
1634        // Pinned at zero it collapses to a constant — which is exactly what
1635        // pool-adjacent-violators does with the same data.
1636        assert!((r.apply(0.9) - r.apply(0.5)).abs() < 1e-9);
1637        // And it still does the job: a stated 0.9 is pulled a long way down.
1638        assert!(r.apply(0.9) < 0.5, "got {}", r.apply(0.9));
1639        // Crucially it is NOT the identity — falling back to "no correction"
1640        // here would make `decide` blind to the case it exists for.
1641        assert!(r.apply(0.9) < 0.89);
1642    }
1643
1644    #[test]
1645    fn a_diverged_map_is_rejected_even_if_the_solver_claims_success() {
1646        // The invariants must hold independently of the line search, because the
1647        // failure mode is a confidently wrong answer rather than an error.
1648        let samples: Vec<Sample> = (0..50).map(|i| Sample::new(0.9, i % 2 == 0)).collect();
1649
1650        // The exact map the old code returned on this shape of data.
1651        let diverged = Recalibration {
1652            a: 66.0,
1653            b: 146.017,
1654            n: samples.len(),
1655        };
1656        assert!(
1657            !recalibration_is_sane(&diverged, &samples),
1658            "a map that sends 0.9 to 1.0 for a 50%-accurate forecaster must be rejected"
1659        );
1660
1661        // A map running backwards is rejected on monotonicity alone.
1662        let inverted = Recalibration {
1663            a: 0.0,
1664            b: -1.0,
1665            n: samples.len(),
1666        };
1667        assert!(!recalibration_is_sane(&inverted, &samples));
1668
1669        // The identity always passes.
1670        assert!(recalibration_is_sane(
1671            &Recalibration::identity(samples.len()),
1672            &samples
1673        ));
1674    }
1675
1676    #[test]
1677    fn gaps_cost_wealth_and_can_never_manufacture_an_alarm() {
1678        // The whole validity argument in one assertion: whatever the ungraded
1679        // claim would have turned out to be, pricing it at its worst case can
1680        // only lower the wealth relative to actually knowing.
1681        let probs = [0.9, 0.2, 0.55, 0.95, 0.1, 0.75];
1682        for &p in &probs {
1683            for &y in &[0.0, 1.0] {
1684                let graded = calibration_log_eprocess_seq(&[Step::graded(p, y)]).unwrap();
1685                let gap = calibration_log_eprocess_seq(&[Step::gap(p)]).unwrap();
1686                assert!(
1687                    gap <= graded + 1e-12,
1688                    "a gap at p={p} must not beat the graded outcome y={y}"
1689                );
1690                assert!(gap <= 1e-12, "and must never exceed 1 (log 0)");
1691            }
1692        }
1693
1694        // Gaps are priced by boldness: an ungraded 0.95 costs more than a 0.55.
1695        let bold = calibration_log_eprocess_seq(&[Step::gap(0.95)]).unwrap();
1696        let timid = calibration_log_eprocess_seq(&[Step::gap(0.55)]).unwrap();
1697        assert!(
1698            bold < timid,
1699            "a bold ungraded call must cost more wealth than a cautious one"
1700        );
1701
1702        // But a gap never zeroes the process: |lambda| <= 0.9 keeps every factor
1703        // at or above 0.1, so the record survives a backlog instead of dying.
1704        let many: Vec<Step> = (0..50).map(|_| Step::gap(0.99)).collect();
1705        let e = calibration_log_eprocess_seq(&many).unwrap();
1706        assert!(e.is_finite(), "50 bold gaps must not produce -inf");
1707        assert!(e >= 50.0 * (0.1f64).ln() - 1e-9);
1708
1709        // An all-graded sequence is exactly the old computation.
1710        let samples = [
1711            Sample::new(0.9, true),
1712            Sample::new(0.2, false),
1713            Sample::new(0.6, true),
1714        ];
1715        let steps: Vec<Step> = samples
1716            .iter()
1717            .map(|s| Step::graded(s.prob, s.outcome))
1718            .collect();
1719        approx(
1720            calibration_log_eprocess_seq(&steps).unwrap(),
1721            calibration_log_eprocess(&samples).unwrap(),
1722        );
1723    }
1724
1725    #[test]
1726    fn gap_filling_sees_what_stopping_at_the_first_gap_cannot() {
1727        // A symmetrically overconfident forecaster: 0.9 when the truth is 0.65,
1728        // 0.1 when it is 0.35. Every third claim is left ungraded, which is the
1729        // measured discipline of a real agent ledger.
1730        let mut steps = Vec::new();
1731        let mut graded_prefix = Vec::new();
1732        let mut seen_gap = false;
1733        for i in 0..300 {
1734            let p = if i % 2 == 0 { 0.9 } else { 0.1 };
1735            // deterministic stand-in for the 0.65/0.35 truth
1736            let y = if i % 2 == 0 {
1737                if i % 20 < 13 {
1738                    1.0
1739                } else {
1740                    0.0
1741                }
1742            } else if i % 20 < 7 {
1743                1.0
1744            } else {
1745                0.0
1746            };
1747            if i % 3 == 2 {
1748                steps.push(Step::gap(p));
1749                seen_gap = true;
1750            } else {
1751                steps.push(Step::graded(p, y));
1752                if !seen_gap {
1753                    graded_prefix.push(Sample {
1754                        prob: p,
1755                        outcome: y,
1756                    });
1757                }
1758            }
1759        }
1760        let stopping = calibration_log_eprocess(&graded_prefix).unwrap();
1761        let gapfilled = calibration_log_eprocess_seq(&steps).unwrap();
1762        assert!(
1763            graded_prefix.len() <= 3,
1764            "stopping at the first gap leaves almost nothing: {}",
1765            graded_prefix.len()
1766        );
1767        assert!(
1768            stopping < EPROCESS_LOG_CAP,
1769            "the truncated prefix cannot establish anything"
1770        );
1771        assert!(
1772            gapfilled > 20.0f64.ln(),
1773            "gap-filled must clear the alarm on 300 claims: log e = {gapfilled}"
1774        );
1775    }
1776
1777    #[test]
1778    fn a_collapsed_map_says_it_collapsed() {
1779        // A forecaster whose stated confidence is anti-correlated with the truth.
1780        // The projected fit cannot use an inverted ranking, so it flattens to the
1781        // base rate — which is right, but makes every `decide` answer identical.
1782        let samples: Vec<Sample> = (0..60)
1783            .map(|i| Sample::new(if i % 2 == 0 { 0.9 } else { 0.1 }, i % 2 != 0))
1784            .collect();
1785        let r = fit_recalibration(&samples, 1.0).unwrap();
1786        assert_eq!(r.b, 0.0, "an inverted ranking must project to a flat map");
1787        assert_eq!(r.kind(), MapKind::Constant);
1788
1789        // The point of naming it: the act no longer depends on the input.
1790        let hi = decide(0.99, Some(r), 10.0, 2.0);
1791        let lo = decide(0.55, Some(r), 10.0, 2.0);
1792        assert_eq!(hi.map_kind, MapKind::Constant);
1793        assert!(
1794            (hi.adjusted_p - lo.adjusted_p).abs() < 1e-12,
1795            "a constant map returns the same number for any stated p"
1796        );
1797        assert_eq!(hi.act, lo.act);
1798
1799        // The ordinary cases still report themselves as what they are.
1800        assert_eq!(Recalibration::identity(10).kind(), MapKind::Identity);
1801        assert_eq!(decide(0.7, None, 1.0, 0.2).map_kind, MapKind::Identity);
1802        assert_eq!(
1803            Recalibration {
1804                a: 0.3,
1805                b: 0.8,
1806                n: 40
1807            }
1808            .kind(),
1809            MapKind::Logistic
1810        );
1811    }
1812
1813    #[test]
1814    fn recalibration_still_recovers_a_known_slope() {
1815        // The well-conditioned case must be unaffected by the line search: an
1816        // agent whose truth is sigma(0.4 * logit p) should get a slope pulling
1817        // its stated numbers toward the middle.
1818        let mut state = 5u64;
1819        let samples: Vec<Sample> = (0..600)
1820            .map(|_| {
1821                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1822                let p = ((u * 0.9 + 0.05) * 100.0).round() / 100.0;
1823                let truth = sigmoid(0.4 * logit(p));
1824                let v = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1825                Sample::new(p, v < truth)
1826            })
1827            .collect();
1828        let r = fit_recalibration(&samples, 1.5).unwrap();
1829        assert!(
1830            r.b < 1.0,
1831            "slope should say the forecasts run too extreme: {}",
1832            r.b
1833        );
1834        assert!(r.apply(0.9) < 0.9);
1835        assert!(r.apply(0.1) > 0.1);
1836    }
1837
1838    #[test]
1839    fn corp_identity_holds_exactly() {
1840        // S = MCB - DSC + UNC, to the last bit, on messy real-shaped input.
1841        let mut state = 7u64;
1842        let samples: Vec<Sample> = (0..300)
1843            .map(|_| {
1844                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1845                let p = ((u * 0.96 + 0.02) * 100.0).round() / 100.0;
1846                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1847                Sample::new(p, u < p)
1848            })
1849            .collect();
1850        let c = corp_brier(&samples).unwrap();
1851        let residual = (c.score - (c.mcb - c.dsc + c.unc)).abs();
1852        assert!(residual < 1e-12, "identity residual {residual:e}");
1853    }
1854
1855    #[test]
1856    fn corp_agrees_with_exact_decomposition_when_frequencies_are_monotone() {
1857        // When observed frequencies already rise with the forecast, isotonic
1858        // regression changes nothing, so MCB = REL and DSC = RES. This is what
1859        // keeps the old "exact decomposition" promise true where it was true.
1860        let samples = vec![
1861            Sample::new(0.2, false),
1862            Sample::new(0.2, false),
1863            Sample::new(0.2, true),
1864            Sample::new(0.5, false),
1865            Sample::new(0.5, true),
1866            Sample::new(0.9, true),
1867            Sample::new(0.9, true),
1868            Sample::new(0.9, false),
1869        ];
1870        let corp = corp_brier(&samples).unwrap();
1871        let old = decompose(&samples).unwrap();
1872        approx(corp.mcb, old.reliability);
1873        approx(corp.dsc, old.resolution);
1874        approx(corp.unc, old.uncertainty);
1875    }
1876
1877    #[test]
1878    fn corp_reports_zero_discrimination_when_confidence_carries_no_information() {
1879        // 50 calls at 0.9 on coin flips + 50 at 0.6 on sure things. Higher
1880        // confidence went with a LOWER hit rate, so after isotonic regression
1881        // both groups collapse to one value: the forecasts order nothing.
1882        let mut samples: Vec<Sample> = Vec::new();
1883        for i in 0..50 {
1884            samples.push(Sample::new(0.9, i % 2 == 0));
1885        }
1886        for _ in 0..50 {
1887            samples.push(Sample::new(0.6, true));
1888        }
1889        let c = corp_brier(&samples).unwrap();
1890        assert!(
1891            c.dsc.abs() < 1e-12,
1892            "DSC should be exactly 0, got {}",
1893            c.dsc
1894        );
1895        // And the miscalibration is far above what luck alone would produce.
1896        let floor = mcb_null_quantile(&samples, 400, 0.95, 0xA11CE).unwrap();
1897        assert!(c.mcb > floor * 3.0, "mcb {} vs floor {floor}", c.mcb);
1898    }
1899
1900    #[test]
1901    fn corp_is_quieter_than_exact_grouping_on_a_calibrated_forecaster() {
1902        // The defect that made this necessary: with two-decimal probabilities
1903        // most exact-value groups hold one claim, whose observed frequency is
1904        // always 0 or 1, so the old reliability term reports a large calibration
1905        // error for someone who has none.
1906        let mut state = 99u64;
1907        let samples: Vec<Sample> = (0..200)
1908            .map(|_| {
1909                let p = (((splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64) * 0.96
1910                    + 0.02)
1911                    * 100.0;
1912                let p = p.round() / 100.0;
1913                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1914                Sample::new(p, u < p)
1915            })
1916            .collect();
1917        let corp = corp_brier(&samples).unwrap();
1918        let old = decompose(&samples).unwrap();
1919        assert!(
1920            corp.mcb < old.reliability * 0.5,
1921            "CORP MCB {} should be far below exact-group REL {}",
1922            corp.mcb,
1923            old.reliability
1924        );
1925        // And it sits at or below its own noise floor: nothing to report.
1926        let floor = mcb_null_quantile(&samples, 400, 0.95, 0xA11CE).unwrap();
1927        assert!(corp.mcb <= floor, "mcb {} floor {floor}", corp.mcb);
1928    }
1929
1930    #[test]
1931    fn mcb_null_quantile_is_deterministic() {
1932        let samples: Vec<Sample> = (0..50).map(|i| Sample::new(0.7, i % 3 != 0)).collect();
1933        let a = mcb_null_quantile(&samples, 200, 0.95, 1234).unwrap();
1934        let b = mcb_null_quantile(&samples, 200, 0.95, 1234).unwrap();
1935        assert_eq!(a, b, "the noise floor must not move under a re-run");
1936        assert!(mcb_null_quantile(&samples[..1], 200, 0.95, 1234).is_none());
1937    }
1938
1939    // ─────────────────── multi-strategy e-process (P0-3a) ───────────────────
1940
1941    #[test]
1942    fn eprocess_v2_detects_symmetric_overconfidence_that_v1_misses() {
1943        // Says 90% when the truth is 65%; says 10% when the truth is 35%. The
1944        // two errors cancel in the single-strategy statistic.
1945        let mut state = 5u64;
1946        let samples: Vec<Sample> = (0..200)
1947            .map(|i| {
1948                let p = if i % 2 == 0 { 0.9 } else { 0.1 };
1949                let truth = if i % 2 == 0 { 0.65 } else { 0.35 };
1950                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1951                Sample::new(p, u < truth)
1952            })
1953            .collect();
1954        let v1 = calibration_eprocess(&samples).unwrap();
1955        let v2 = calibration_eprocess_v2(&samples).unwrap();
1956        assert!(v1 < 20.0, "v1 was supposed to be blind here, got {v1}");
1957        assert!(v2 >= 20.0, "v2 must find it, got {v2}");
1958    }
1959
1960    #[test]
1961    fn eprocess_v2_stays_quiet_on_a_calibrated_forecaster() {
1962        // The property that matters more than power: it must not cry wolf.
1963        let mut state = 31u64;
1964        let samples: Vec<Sample> = (0..500)
1965            .map(|_| {
1966                let p = (((splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64) * 0.9
1967                    + 0.05)
1968                    * 100.0;
1969                let p = p.round() / 100.0;
1970                let u = (splitmix64(&mut state) >> 11) as f64 / (1u64 << 53) as f64;
1971                Sample::new(p, u < p)
1972            })
1973            .collect();
1974        // Anytime-valid: check at EVERY prefix, which is the whole point.
1975        for k in 1..=samples.len() {
1976            let e = calibration_eprocess_v2(&samples[..k]).unwrap();
1977            assert!(e < 20.0, "false alarm at n={k}: e={e}");
1978        }
1979    }
1980
1981    #[test]
1982    fn eprocess_v2_never_returns_infinity() {
1983        // Extreme, perfectly wrong forecasts: the log form must stay printable.
1984        let samples: Vec<Sample> = (0..2000).map(|_| Sample::new(0.99, false)).collect();
1985        let e = calibration_eprocess_v2(&samples).unwrap();
1986        assert!(e.is_finite(), "e must be finite, got {e}");
1987        assert!(e <= EPROCESS_LOG_CAP.exp() + 1.0);
1988        assert!(calibration_log_eprocess(&samples).unwrap() > 100.0);
1989    }
1990
1991    #[test]
1992    fn shrinkage_pulls_small_n_toward_prior() {
1993        // 1/1 with a 0.5 prior, strength 4 → (1+2)/(1+4) = 0.6, not 1.0.
1994        approx(shrink_toward(1.0, 1, 0.5, 4.0), 0.6);
1995        // Large n barely moves: 80/100 shrunk toward 0.5 stays ≈ 0.79.
1996        let s = shrink_toward(80.0, 100, 0.5, 4.0);
1997        assert!(s > 0.78 && s < 0.80, "s={s}");
1998        // strength 0 recovers the raw rate.
1999        approx(shrink_toward(3.0, 4, 0.5, 0.0), 0.75);
2000    }
2001
2002    #[test]
2003    fn wilson_interval_known_and_bounded() {
2004        // 1 of 2 at 95%: symmetric about 0.5 and wide, as small n demands.
2005        let (lo, hi) = wilson_interval(1.0, 2, 1.96).unwrap();
2006        assert!((lo - 0.0945).abs() < 1e-3, "lo={lo}");
2007        assert!((hi - 0.9055).abs() < 1e-3, "hi={hi}");
2008        // 0 of 5: clamps at 0 below, stays strictly inside (0,1) above.
2009        let (lo0, hi0) = wilson_interval(0.0, 5, 1.96).unwrap();
2010        assert_eq!(lo0, 0.0);
2011        assert!(hi0 > 0.0 && hi0 < 1.0, "hi0={hi0}");
2012        // The interval always brackets the point estimate.
2013        let (lo2, hi2) = wilson_interval(7.0, 10, 1.96).unwrap();
2014        assert!(lo2 < 0.7 && 0.7 < hi2, "[{lo2},{hi2}] should bracket 0.7");
2015        // n = 0 → undefined.
2016        assert!(wilson_interval(0.0, 0, 1.96).is_none());
2017    }
2018
2019    #[test]
2020    fn brier_known_values() {
2021        // Perfect, confident, correct.
2022        approx(
2023            brier(&[Sample::new(1.0, true), Sample::new(0.0, false)]).unwrap(),
2024            0.0,
2025        );
2026        // Always 0.5: squared error 0.25 every time.
2027        approx(
2028            brier(&[Sample::new(0.5, true), Sample::new(0.5, false)]).unwrap(),
2029            0.25,
2030        );
2031        // Confidently, maximally wrong.
2032        approx(
2033            brier(&[Sample::new(0.0, true), Sample::new(1.0, false)]).unwrap(),
2034            1.0,
2035        );
2036        assert!(brier(&[]).is_none());
2037    }
2038
2039    #[test]
2040    fn log_score_known_values() {
2041        // p = 0.5 every time ⇒ -ln(0.5) = ln 2.
2042        approx(
2043            log_score(&[Sample::new(0.5, true), Sample::new(0.5, false)], 0.0).unwrap(),
2044            std::f64::consts::LN_2,
2045        );
2046        // Perfect & confident with clamping ⇒ ~0.
2047        let s = log_score(&[Sample::new(1.0, true), Sample::new(0.0, false)], 1e-12).unwrap();
2048        assert!(s < 1e-9, "near-perfect log score should be tiny, got {s}");
2049    }
2050
2051    #[test]
2052    fn decomposition_identity_holds_exactly() {
2053        // The whole reason for grouping by exact forecast value: REL - RES + UNC
2054        // must reproduce the empirical Brier to floating-point precision, for
2055        // arbitrary data. Exercise a deterministic but irregular spread.
2056        let mut samples = Vec::new();
2057        let probs = [0.05, 0.2, 0.35, 0.5, 0.65, 0.8, 0.95, 0.5, 0.8, 0.2];
2058        for (i, &p) in probs.iter().cycle().take(137).enumerate() {
2059            // pseudo-random-ish but deterministic outcome
2060            let happened = ((i * 2654435761usize) >> 13) & 1 == 0;
2061            samples.push(Sample::new(p, happened));
2062        }
2063        let d = decompose(&samples).unwrap();
2064        let b = brier(&samples).unwrap();
2065        approx(d.brier, b);
2066        approx(d.reliability - d.resolution + d.uncertainty, b);
2067        // Components are non-negative.
2068        assert!(d.reliability >= -1e-12);
2069        assert!(d.resolution >= -1e-12);
2070        assert!(d.uncertainty >= -1e-12);
2071    }
2072
2073    #[test]
2074    fn perfect_calibration_has_zero_reliability() {
2075        // 100 forecasts at p=0.7, exactly 70 of which come true.
2076        let mut samples = Vec::new();
2077        for i in 0..100 {
2078            samples.push(Sample::new(0.7, i < 70));
2079        }
2080        let d = decompose(&samples).unwrap();
2081        approx(d.reliability, 0.0); // perfectly calibrated at this value
2082    }
2083
2084    #[test]
2085    fn auc_separates_and_handles_degenerate() {
2086        // Perfect separation: every true got a higher prob than every false.
2087        let s = [
2088            Sample::new(0.9, true),
2089            Sample::new(0.8, true),
2090            Sample::new(0.2, false),
2091            Sample::new(0.1, false),
2092        ];
2093        approx(auc(&s).unwrap(), 1.0);
2094        // Reversed ranking ⇒ AUC 0.0.
2095        let r = [
2096            Sample::new(0.1, true),
2097            Sample::new(0.2, true),
2098            Sample::new(0.8, false),
2099            Sample::new(0.9, false),
2100        ];
2101        approx(auc(&r).unwrap(), 0.0);
2102        // All ties at 0.5 ⇒ AUC 0.5.
2103        let t = [Sample::new(0.5, true), Sample::new(0.5, false)];
2104        approx(auc(&t).unwrap(), 0.5);
2105        // No negatives ⇒ undefined.
2106        assert!(auc(&[Sample::new(0.6, true)]).is_none());
2107    }
2108
2109    /// Self-evidently-correct `O(n²)` reference, kept only to validate the fast
2110    /// rank-based `auc`.
2111    fn auc_pairwise(samples: &[Sample]) -> Option<f64> {
2112        let pos: Vec<f64> = samples
2113            .iter()
2114            .filter(|s| s.outcome >= 0.5)
2115            .map(|s| s.prob)
2116            .collect();
2117        let neg: Vec<f64> = samples
2118            .iter()
2119            .filter(|s| s.outcome < 0.5)
2120            .map(|s| s.prob)
2121            .collect();
2122        if pos.is_empty() || neg.is_empty() {
2123            return None;
2124        }
2125        let mut wins = 0.0;
2126        for &p in &pos {
2127            for &q in &neg {
2128                if p > q {
2129                    wins += 1.0;
2130                } else if p == q {
2131                    wins += 0.5;
2132                }
2133            }
2134        }
2135        Some(wins / (pos.len() as f64 * neg.len() as f64))
2136    }
2137
2138    #[test]
2139    fn auc_rank_matches_pairwise_reference_with_ties() {
2140        // Deterministic datasets deliberately full of tied probabilities, so the
2141        // average-rank tie handling is actually exercised against the oracle.
2142        let probs = [0.1, 0.1, 0.4, 0.5, 0.5, 0.5, 0.7, 0.7, 0.9, 0.95];
2143        for seed in 0u64..64 {
2144            let samples: Vec<Sample> = probs
2145                .iter()
2146                .enumerate()
2147                .map(|(i, &p)| Sample::new(p, ((seed >> (i % 6)) & 1) == 0))
2148                .collect();
2149            match (auc(&samples), auc_pairwise(&samples)) {
2150                (Some(a), Some(b)) => approx(a, b),
2151                (None, None) => {}
2152                (x, y) => panic!("AUC definedness disagrees: {x:?} vs {y:?}"),
2153            }
2154        }
2155    }
2156
2157    #[test]
2158    fn overconfidence_detects_boldness_gap() {
2159        // Bold (0.9) but right only half the time ⇒ overconfident by ~0.4.
2160        let mut samples = Vec::new();
2161        for i in 0..100 {
2162            samples.push(Sample::new(0.9, i < 50));
2163        }
2164        let o = overconfidence(&samples).unwrap();
2165        approx(o.mean_confidence, 0.9);
2166        approx(o.accuracy, 0.5);
2167        approx(o.gap, 0.4);
2168        // A perfectly calibrated bold forecaster has gap ~0.
2169        let mut cal = Vec::new();
2170        for i in 0..100 {
2171            cal.push(Sample::new(0.9, i < 90));
2172        }
2173        approx(overconfidence(&cal).unwrap().gap, 0.0);
2174    }
2175
2176    #[test]
2177    fn skill_score_zero_for_base_rate_forecaster() {
2178        // Always predicting the base rate (0.6) ⇒ no skill ⇒ BSS == 0.
2179        let mut samples = Vec::new();
2180        for i in 0..100 {
2181            samples.push(Sample::new(0.6, i < 60));
2182        }
2183        approx(skill_score(&samples).unwrap(), 0.0);
2184    }
2185
2186    #[test]
2187    fn calibration_curve_bins_correctly() {
2188        let samples = [
2189            Sample::new(0.05, false),
2190            Sample::new(0.15, false),
2191            Sample::new(0.95, true),
2192            Sample::new(1.0, true), // must land in the last bin, not overflow
2193        ];
2194        let bins = calibration_curve(&samples, 10);
2195        assert_eq!(bins.len(), 10);
2196        assert_eq!(bins[0].count, 1);
2197        assert_eq!(bins[1].count, 1);
2198        assert_eq!(bins[9].count, 2); // 0.95 and 1.0
2199        approx(bins[9].observed, 1.0);
2200    }
2201
2202    #[test]
2203    fn winkler_inside_is_width_outside_is_penalised() {
2204        let inside = NumericSample {
2205            low: 10.0,
2206            high: 20.0,
2207            level: 0.8,
2208            value: 15.0,
2209        };
2210        approx(winkler(&inside), 10.0); // just the width
2211
2212        // width 10 + (2/0.2)*(10 - 5) = 10 + 10*5 = 60
2213        let below = NumericSample {
2214            low: 10.0,
2215            high: 20.0,
2216            level: 0.8,
2217            value: 5.0,
2218        };
2219        approx(winkler(&below), 60.0);
2220        let above = NumericSample {
2221            low: 10.0,
2222            high: 20.0,
2223            level: 0.8,
2224            value: 25.0,
2225        };
2226        approx(winkler(&above), 60.0);
2227
2228        // A tighter nominal level (larger α) penalises a miss less.
2229        let loose = NumericSample {
2230            low: 10.0,
2231            high: 20.0,
2232            level: 0.5,
2233            value: 5.0,
2234        };
2235        // 10 + (2/0.5)*5 = 10 + 4*5 = 30
2236        approx(winkler(&loose), 30.0);
2237    }
2238
2239    #[test]
2240    fn coverage_counts_contained_intervals() {
2241        let s = [
2242            NumericSample {
2243                low: 0.0,
2244                high: 10.0,
2245                level: 0.8,
2246                value: 5.0,
2247            }, // in
2248            NumericSample {
2249                low: 0.0,
2250                high: 10.0,
2251                level: 0.8,
2252                value: 50.0,
2253            }, // out
2254            NumericSample {
2255                low: 0.0,
2256                high: 10.0,
2257                level: 0.8,
2258                value: 0.0,
2259            }, // edge = in
2260        ];
2261        approx(coverage(&s).unwrap(), 2.0 / 3.0);
2262        assert!(coverage(&[]).is_none());
2263    }
2264
2265    #[test]
2266    fn conformal_width_factor_scales_to_hit_nominal() {
2267        // Helper: an interval centred at 0 with half-width 1, so the standardized
2268        // residual equals |value|. level is the nominal coverage of the interval.
2269        let mk = |value: f64, level: f64| NumericSample {
2270            low: -1.0,
2271            high: 1.0,
2272            level,
2273            value,
2274        };
2275
2276        // Residuals {0.2, 0.4, 0.6, 0.8}, target 0.5 → the 0.5-quantile is the
2277        // midpoint of 0.4 and 0.6 = 0.5. Scaling half-widths by 0.5 leaves exactly
2278        // the two residuals ≤ 0.5 covered = 50% = nominal. Intervals are too wide.
2279        let wide = [mk(0.2, 0.5), mk(0.4, 0.5), mk(0.6, 0.5), mk(0.8, 0.5)];
2280        approx(conformal_width_factor(&wide).unwrap(), 0.5);
2281
2282        // Residuals {0.5, 0.9, 1.3, 1.7, 2.1}, target 0.8 → 0.8-quantile sits at
2283        // pos 3.2 between 1.7 and 2.1 = 1.78. m > 1: intervals are too narrow.
2284        let narrow = [
2285            mk(0.5, 0.8),
2286            mk(0.9, 0.8),
2287            mk(1.3, 0.8),
2288            mk(1.7, 0.8),
2289            mk(2.1, 0.8),
2290        ];
2291        let m = conformal_width_factor(&narrow).unwrap();
2292        assert!((m - 1.78).abs() < 1e-9, "m={m}");
2293
2294        // Fewer than three usable samples, or only degenerate point intervals → None.
2295        assert!(conformal_width_factor(&wide[..2]).is_none());
2296        let points =
2297            [mk(0.0, 0.5), mk(0.0, 0.5), mk(0.0, 0.5)].map(|s| NumericSample { high: -1.0, ..s }); // width 0 ⇒ all skipped
2298        assert!(conformal_width_factor(&points).is_none());
2299    }
2300
2301    #[test]
2302    fn decide_thresholds_on_chow_rule_and_stakes() {
2303        // Ordinary stake 1, a check costs 0.2 → break-even τ = 1 − 0.2/1 = 0.80.
2304        let d = decide(0.85, None, 1.0, 0.2);
2305        approx(d.proceed_threshold, 0.80);
2306        assert_eq!(d.act, Act::Proceed); // 0.85 ≥ 0.80
2307        approx(d.margin, 0.05);
2308
2309        // Same call at 0.70 lands in the doubt zone → verify (0.5 ≤ 0.70 < 0.80).
2310        assert_eq!(decide(0.70, None, 1.0, 0.2).act, Act::Verify);
2311
2312        // Raise the stakes and the bar climbs: τ = 1 − 0.2/4 = 0.95, so even 0.90
2313        // is no longer good enough to skip the check.
2314        let hi = decide(0.90, None, 4.0, 0.2);
2315        approx(hi.proceed_threshold, 0.95);
2316        assert_eq!(hi.act, Act::Verify);
2317
2318        // Below even odds (after any correction) → abstain, not verify.
2319        assert_eq!(decide(0.40, None, 1.0, 0.2).act, Act::Abstain);
2320    }
2321
2322    #[test]
2323    fn decide_applies_the_track_record_correction_first() {
2324        // A map that says "your 0.70s are really ~0.34" (overconfident history).
2325        let overconf = Recalibration {
2326            a: -1.5,
2327            b: 1.0,
2328            n: 12,
2329        };
2330        // Raw 0.70 on an ordinary call would only *verify*…
2331        assert_eq!(decide(0.70, None, 1.0, 0.2).act, Act::Verify);
2332        // …but corrected to 0.34 it drops below even odds → abstain. The gate acts
2333        // on the de-biased number, exactly the point.
2334        let d = decide(0.70, Some(overconf), 1.0, 0.2);
2335        assert!(d.adjusted_p < 0.5, "adjusted={}", d.adjusted_p);
2336        assert_eq!(d.act, Act::Abstain);
2337    }
2338
2339    #[test]
2340    fn decide_degenerate_costs_are_sane() {
2341        // Nothing at stake → just proceed, even on a long shot.
2342        assert_eq!(decide(0.10, None, 0.0, 0.2).act, Act::Proceed);
2343        // A check costing as much as the worst case → never worth it, proceed.
2344        assert_eq!(decide(0.30, None, 1.0, 1.0).proceed_threshold, 0.0);
2345        assert_eq!(decide(0.30, None, 1.0, 1.0).act, Act::Proceed);
2346        // A free check → demand near-certainty; 0.99 still verifies.
2347        approx(decide(0.99, None, 1.0, 0.0).proceed_threshold, 1.0);
2348        assert_eq!(decide(0.99, None, 1.0, 0.0).act, Act::Verify);
2349    }
2350
2351    #[test]
2352    fn mean_boldness_measures_distance_from_a_coin_flip() {
2353        // max(p,1−p) of 0.9, 0.5, 0.2 → 0.9, 0.5, 0.8 → mean 0.7333.
2354        approx(mean_boldness(&[0.9, 0.5, 0.2]).unwrap(), 2.2 / 3.0);
2355        approx(mean_boldness(&[0.5]).unwrap(), 0.5); // a pure shrug
2356        assert!(mean_boldness(&[]).is_none());
2357    }
2358
2359    #[test]
2360    fn asmd_is_a_standardized_gap_robust_to_degeneracy() {
2361        // means 0.7 vs 0.8, each sd 0.2, pooled 0.2 → ASMD = 0.1/0.2 = 0.5.
2362        approx(asmd(&[0.5, 0.7, 0.9], &[0.6, 0.8, 1.0]).unwrap(), 0.5);
2363        // Identical groups → zero gap.
2364        approx(asmd(&[0.4, 0.6], &[0.4, 0.6]).unwrap(), 0.0);
2365        // No spread to standardize against, or a group too small → None, not NaN.
2366        assert!(asmd(&[0.5, 0.5], &[0.6, 0.6]).is_none());
2367        assert!(asmd(&[0.5], &[0.6, 0.8]).is_none());
2368    }
2369
2370    #[test]
2371    fn eprocess_finds_no_evidence_on_calibrated_data() {
2372        // Alternating outcomes at p=0.5: calibration-in-the-large holds, and a
2373        // fixed (non-predictable) bettor cannot profit → wealth never grows.
2374        let s: Vec<Sample> = (0..60).map(|i| Sample::new(0.5, i % 2 == 0)).collect();
2375        let e = calibration_eprocess(&s).unwrap();
2376        assert!(
2377            e < 5.0,
2378            "calibrated data should not accumulate evidence, e={e}"
2379        );
2380        assert!(eprocess_pvalue(e) > 0.05);
2381    }
2382
2383    #[test]
2384    fn eprocess_detects_gross_miscalibration() {
2385        // "10% sure" every time, but it always happens → wildly underconfident.
2386        let s: Vec<Sample> = (0..40).map(|_| Sample::new(0.1, true)).collect();
2387        let e = calibration_eprocess(&s).unwrap();
2388        assert!(
2389            e >= 20.0,
2390            "gross miscalibration should be significant, e={e}"
2391        );
2392        assert!(eprocess_pvalue(e) < 0.05);
2393    }
2394
2395    #[test]
2396    fn eprocess_is_finite_at_extremes_and_none_when_empty() {
2397        assert!(calibration_eprocess(&[]).is_none());
2398        // p exactly 0/1 and wrong: factors stay non-negative, wealth finite.
2399        let s = vec![Sample::new(1.0, false), Sample::new(0.0, true)];
2400        let e = calibration_eprocess(&s).unwrap();
2401        assert!(e.is_finite() && e > 0.0, "e={e}");
2402    }
2403
2404    #[test]
2405    fn recalibration_is_identity_on_calibrated_data() {
2406        // Forecasts that match realised frequencies ⇒ map ≈ identity.
2407        let mut s = Vec::new();
2408        for i in 0..100 {
2409            s.push(Sample::new(0.7, i < 70)); // 0.7 happens 70%
2410        }
2411        for i in 0..100 {
2412            s.push(Sample::new(0.3, i < 30)); // 0.3 happens 30%
2413        }
2414        let r = fit_recalibration(&s, 1.0).unwrap();
2415        assert!(
2416            (r.apply(0.7) - 0.7).abs() < 0.05,
2417            "apply(0.7)={}",
2418            r.apply(0.7)
2419        );
2420        assert!(
2421            (r.apply(0.3) - 0.3).abs() < 0.05,
2422            "apply(0.3)={}",
2423            r.apply(0.3)
2424        );
2425    }
2426
2427    #[test]
2428    fn recalibration_corrects_underconfidence() {
2429        // Stated 0.6 but true rate 0.9; stated 0.4 but true rate 0.1 → too timid.
2430        let mut s = Vec::new();
2431        for i in 0..100 {
2432            s.push(Sample::new(0.6, i < 90));
2433        }
2434        for i in 0..100 {
2435            s.push(Sample::new(0.4, i < 10));
2436        }
2437        let r = fit_recalibration(&s, 1.0).unwrap();
2438        assert!(r.b > 1.0, "slope should exceed 1 (too timid), b={}", r.b);
2439        assert!(
2440            r.apply(0.6) > 0.75,
2441            "0.6 should be pushed up, got {}",
2442            r.apply(0.6)
2443        );
2444        assert!(
2445            r.apply(0.4) < 0.25,
2446            "0.4 should be pushed down, got {}",
2447            r.apply(0.4)
2448        );
2449    }
2450
2451    #[test]
2452    fn recalibration_stays_near_identity_at_small_n() {
2453        // One lucky hit must not yield a confident correction.
2454        let r = fit_recalibration(&[Sample::new(0.6, true)], 2.0).unwrap();
2455        assert!(
2456            (r.apply(0.6) - 0.6).abs() < 0.12,
2457            "apply(0.6)={}",
2458            r.apply(0.6)
2459        );
2460    }
2461
2462    #[test]
2463    fn recalibration_survives_perfect_separation() {
2464        // Unpenalised MLE would diverge; the ridge keeps it finite and monotone.
2465        let s = [
2466            Sample::new(0.2, false),
2467            Sample::new(0.3, false),
2468            Sample::new(0.7, true),
2469            Sample::new(0.8, true),
2470        ];
2471        let r = fit_recalibration(&s, 1.0).unwrap();
2472        assert!(r.a.is_finite() && r.b.is_finite(), "a={}, b={}", r.a, r.b);
2473        assert!(r.apply(0.8) > r.apply(0.2), "map should stay increasing");
2474        assert!(fit_recalibration(&[], 1.0).is_none());
2475    }
2476
2477    #[test]
2478    fn bootstrap_ci_brackets_point_and_is_deterministic() {
2479        let s: Vec<Sample> = (0..40).map(|i| Sample::new(0.7, i % 10 < 7)).collect();
2480        let b = brier(&s).unwrap();
2481        let (lo, hi) = brier_ci_bootstrap(&s, 0.95, 2000, 42).unwrap();
2482        assert!(
2483            lo <= b && b <= hi,
2484            "CI [{lo},{hi}] should bracket point {b}"
2485        );
2486        assert!((0.0..=1.0).contains(&lo) && (0.0..=1.0).contains(&hi));
2487        // Same seed ⇒ identical interval (reproducible reports).
2488        assert_eq!((lo, hi), brier_ci_bootstrap(&s, 0.95, 2000, 42).unwrap());
2489        // One sample (or zero) is not enough for a band.
2490        assert!(brier_ci_bootstrap(&[Sample::new(0.5, true)], 0.95, 100, 1).is_none());
2491    }
2492
2493    #[test]
2494    fn ewma_brier_rewards_recent_improvement() {
2495        // Wrong early (Brier 1.0), perfect late (Brier 0.0): recency < lifetime 0.5.
2496        let mut s = Vec::new();
2497        for _ in 0..10 {
2498            s.push(Sample::new(0.0, true));
2499        }
2500        for _ in 0..10 {
2501            s.push(Sample::new(1.0, true));
2502        }
2503        let life = brier(&s).unwrap();
2504        let recent = ewma_brier(&s, 5.0).unwrap();
2505        assert!(
2506            recent < life,
2507            "recency should reward recent gains: {recent} vs {life}"
2508        );
2509        // Constant performance ⇒ EWMA equals that Brier.
2510        let c: Vec<Sample> = (0..20).map(|_| Sample::new(0.5, true)).collect();
2511        approx(ewma_brier(&c, 5.0).unwrap(), 0.25);
2512        assert!(ewma_brier(&[], 5.0).is_none());
2513    }
2514
2515    #[test]
2516    fn distinct_forecasts_counts_unique_values() {
2517        let s = [
2518            Sample::new(0.6, true),
2519            Sample::new(0.6, false),
2520            Sample::new(0.3, true),
2521        ];
2522        assert_eq!(distinct_forecasts(&s), 2);
2523        assert_eq!(distinct_forecasts(&[]), 0);
2524    }
2525
2526    #[test]
2527    fn risk_coverage_rewards_a_good_confidence_ranking() {
2528        // The confident calls are right; the unsure ones are the errors.
2529        let mut s = Vec::new();
2530        for _ in 0..10 {
2531            s.push(Sample::new(0.95, true)); // confident & correct
2532        }
2533        for _ in 0..10 {
2534            s.push(Sample::new(0.55, false)); // unsure & wrong (leaned yes, didn't happen)
2535        }
2536        let rc = risk_coverage(&s).unwrap();
2537        approx(rc.risk_at_full, 0.5); // act on all → 10/20 wrong
2538        assert!(
2539            rc.risk_at(0.5) < 0.05,
2540            "the most-confident half should be near-perfect, got {}",
2541            rc.risk_at(0.5)
2542        );
2543        assert!(
2544            rc.aurcc < rc.risk_at_full,
2545            "being selective should beat acting on everything"
2546        );
2547    }
2548
2549    #[test]
2550    fn risk_coverage_flags_inverted_confidence() {
2551        // Confidence is anti-informative: the bold calls are the wrong ones.
2552        let mut s = Vec::new();
2553        for _ in 0..10 {
2554            s.push(Sample::new(0.95, false)); // confident & wrong
2555        }
2556        for _ in 0..10 {
2557            s.push(Sample::new(0.55, true)); // unsure & right
2558        }
2559        let rc = risk_coverage(&s).unwrap();
2560        assert!(
2561            rc.risk_at(0.5) > rc.risk_at_full,
2562            "surest-half error should exceed overall when ranking is inverted"
2563        );
2564        assert!(risk_coverage(&[]).is_none());
2565    }
2566
2567    #[test]
2568    fn dialectical_mean_averages_the_crowd_within() {
2569        approx(dialectical_mean(0.7, 0.5), 0.6);
2570        approx(dialectical_mean(0.9, 0.9), 0.9);
2571        approx(dialectical_mean(1.5, -0.2), 0.5); // clamps out-of-range inputs
2572    }
2573
2574    #[test]
2575    fn weighted_brier_emphasises_high_stake_calls() {
2576        // A cheap perfect call and a costly blown one: unweighted Brier is 0.5…
2577        let s = [Sample::new(1.0, true), Sample::new(0.0, true)]; // briers 0 and 1
2578        approx(brier_weighted(&s, &[1.0, 1.0]).unwrap(), 0.5);
2579        // …but weight the blown call 9× and it rightly dominates.
2580        approx(brier_weighted(&s, &[1.0, 9.0]).unwrap(), 0.9);
2581        // Equal weights reproduce the plain Brier.
2582        approx(brier_weighted(&s, &[2.0, 2.0]).unwrap(), brier(&s).unwrap());
2583        // No positive weight, or a length mismatch ⇒ None.
2584        assert!(brier_weighted(&s, &[0.0, 0.0]).is_none());
2585        assert!(brier_weighted(&s, &[1.0]).is_none());
2586    }
2587
2588    #[test]
2589    fn detection_rate_is_rare_for_a_calibrated_forecaster_and_grows_with_the_error() {
2590        let probs = [0.9, 0.8, 0.7, 0.95, 0.85, 0.6, 0.75, 0.9, 0.8, 0.65];
2591        let steps: Vec<Step> = (0..200).map(|i| Step::graded(probs[i % 10], 1.0)).collect();
2592        let calibrated = detection_rate(&steps, 0.0, 20.0, 400, 7).unwrap();
2593        // Ville: a calibrated forecaster reaches 20 at most one time in 20, at any n.
2594        assert!(calibrated <= 0.05 + 0.03, "calibrated flagged {calibrated}");
2595        let mild = detection_rate(&steps, 0.3, 20.0, 400, 7).unwrap();
2596        let strong = detection_rate(&steps, 0.6, 20.0, 400, 7).unwrap();
2597        assert!(
2598            calibrated < mild && mild < strong,
2599            "{calibrated} {mild} {strong}"
2600        );
2601        assert!(strong > 0.9, "strong {strong}");
2602        // reproducible
2603        assert_eq!(detection_rate(&steps, 0.3, 20.0, 400, 7).unwrap(), mild);
2604        // a gap stays a gap, and it can only lower the rate
2605        let mut gapped = steps.clone();
2606        for s in gapped.iter_mut().step_by(4) {
2607            *s = Step::gap(s.prob);
2608        }
2609        assert!(detection_rate(&gapped, 0.3, 20.0, 400, 7).unwrap() <= mild + 0.05);
2610        assert_eq!(detection_rate(&[Step::gap(0.9)], 0.3, 20.0, 10, 7), None);
2611        assert_eq!(detection_rate(&steps, 0.3, 20.0, 0, 7), None);
2612    }
2613}