Skip to main content

gam_problem/
diagnostics.rs

1//! Analytic diagnostic helpers for LAML/REML optimization.
2//!
3//! Production diagnostics inspect analytic invariants only. Runtime fitting,
4//! prediction, and diagnostic APIs must consume quantities the optimizer
5//! already computes. This module implements diagnostic strategies that identify
6//! root causes of gradient pathologies from those analytic quantities:
7//!
8//! 1. KKT Audit (Envelope Theorem Check): Detects violations of the stationarity
9//!    assumption used in implicit differentiation.
10//!
11//! 2. Spectral Bleed Trace: Detects when truncated eigenspace corrections are
12//!    inconsistent with the penalty's energy in that subspace.
13//!
14//! 3. Dual-Ridge Consistency Check: Verifies that the ridge used by the inner
15//!    solver (PIRLS) matches what the outer gradient calculation assumes.
16
17use ndarray::Array1;
18use std::collections::BTreeMap;
19use std::fmt;
20use std::sync::atomic::{AtomicI32, AtomicUsize, Ordering};
21
22// =============================================================================
23// Rate-Limited Diagnostic Output
24// =============================================================================
25// These helpers prevent diagnostic spam while ensuring important messages are seen.
26// Pattern: show first occurrence, then every Nth occurrence, with count indicator.
27
28/// Rate-limited diagnostic for Hessian minimum eigenvalue warnings
29pub static H_MIN_EIG_LOG_BUCKET: AtomicI32 = AtomicI32::new(i32::MIN);
30/// Count of `should_emit_h_min_eig_diag` invocations that have ever been
31/// considered for emission; used together with `H_MIN_EIG_LOG_BUCKET` to
32/// rate-limit one diagnostic per decade-magnitude bucket and per
33/// `MIN_EIG_DIAG_EVERY` repeats within the same bucket.
34pub static H_MIN_EIG_LOG_COUNT: AtomicUsize = AtomicUsize::new(0);
35/// Repeat period within a magnitude bucket for the Hessian-minimum-eigenvalue
36/// diagnostic: after the first emission for a bucket, every Nth subsequent
37/// invocation also emits.
38pub const MIN_EIG_DIAG_EVERY: usize = 200;
39/// Threshold below which a positive Hessian minimum eigenvalue is treated as
40/// nearly-singular and routed through the rate-limited diagnostic.
41pub const MIN_EIG_DIAG_THRESHOLD: f64 = 1e-4;
42
43/// Diagnostic formatter shared across the outer optimizer and the custom-family
44/// fitter: shows the `max_items` entries of `values` with largest absolute
45/// value, formatted as `label=[i:value, ...]`.
46pub fn format_top_abs(values: &Array1<f64>, label: &str, max_items: usize) -> String {
47    if values.is_empty() {
48        return format!("{label}=<empty>");
49    }
50    let mut ranked: Vec<(usize, f64)> = values.iter().copied().enumerate().collect();
51    ranked.sort_by(|(_, left), (_, right)| {
52        right
53            .abs()
54            .partial_cmp(&left.abs())
55            .unwrap_or(std::cmp::Ordering::Equal)
56    });
57    let parts: Vec<String> = ranked
58        .into_iter()
59        .take(max_items)
60        .map(|(idx, value)| format!("{idx}:{value:.3e}"))
61        .collect();
62    format!("{label}=[{}]", parts.join(", "))
63}
64
65/// Rate-limited check for Hessian minimum eigenvalue diagnostics.
66/// Returns true if this eigenvalue warrants a diagnostic message.
67pub fn should_emit_h_min_eig_diag(min_eig: f64) -> bool {
68    if !min_eig.is_finite() || min_eig <= 0.0 {
69        return true;
70    }
71    if min_eig >= MIN_EIG_DIAG_THRESHOLD {
72        return false;
73    }
74    let bucket = if min_eig.is_finite() && min_eig > 0.0 {
75        min_eig.log10().floor() as i32
76    } else {
77        i32::MIN
78    };
79    let last = H_MIN_EIG_LOG_BUCKET.load(Ordering::Relaxed);
80    let count = H_MIN_EIG_LOG_COUNT.fetch_add(1, Ordering::Relaxed);
81    if bucket != last || count.is_multiple_of(MIN_EIG_DIAG_EVERY) {
82        H_MIN_EIG_LOG_BUCKET.store(bucket, Ordering::Relaxed);
83        true
84    } else {
85        false
86    }
87}
88
89// =============================================================================
90// Formatting Utilities for Diagnostic Output
91// =============================================================================
92
93/// Configuration for gradient diagnostics
94#[derive(Clone, Debug)]
95pub struct DiagnosticConfig {
96    /// Tolerance for KKT residual norm (envelope theorem violation)
97    pub kkt_tolerance: f64,
98    /// Relative error threshold for flagging issues
99    pub rel_error_threshold: f64,
100    /// Whether to emit warnings to stderr
101    pub emitwarnings: bool,
102}
103
104impl Default for DiagnosticConfig {
105    fn default() -> Self {
106        Self {
107            kkt_tolerance: 1e-4,
108            rel_error_threshold: 0.1,
109            emitwarnings: true,
110        }
111    }
112}
113
114/// Result of envelope theorem (KKT) audit
115#[derive(Clone, Debug)]
116pub struct EnvelopeAudit {
117    /// Norm of the inner KKT residual ∇_β L(β*, ρ)
118    pub kkt_residual_norm: f64,
119    /// Ridge used by the inner solver
120    pub innerridge: f64,
121    /// Ridge assumed by the outer gradient calculation
122    pub outerridge: f64,
123    /// Whether the envelope theorem is violated
124    pub isviolated: bool,
125    /// Human-readable diagnostic message
126    pub message: String,
127}
128
129impl fmt::Display for EnvelopeAudit {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        write!(f, "{}", self.message)
132    }
133}
134
135/// Result of spectral bleed trace diagnostic
136#[derive(Clone, Debug)]
137pub struct SpectralBleedResult {
138    pub penalty_k: usize,
139    /// Energy of penalty S_k in the truncated subspace: trace(U_⊥' S_k U_⊥)
140    pub truncated_energy: f64,
141    /// Correction term actually applied in the gradient
142    pub applied_correction: f64,
143    /// Whether there's a spectral bleed issue
144    pub has_bleed: bool,
145    /// Human-readable diagnostic message
146    pub message: String,
147}
148
149impl fmt::Display for SpectralBleedResult {
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        write!(f, "{}", self.message)
152    }
153}
154
155/// Result of dual-ridge consistency check
156#[derive(Clone, Debug)]
157pub struct DualRidgeResult {
158    /// Ridge used during P-IRLS optimization
159    pub pirlsridge: f64,
160    /// Ridge used in LAML cost function
161    pub costridge: f64,
162    /// Ridge used in gradient calculation
163    pub gradientridge: f64,
164    /// Effective ridge impact: ||ridge * β||
165    pub ridge_impact: f64,
166    /// Phantom penalty contribution: 0.5 * ridge * ||β||²
167    pub phantom_penalty: f64,
168    /// Whether there's a ridge mismatch
169    pub has_mismatch: bool,
170    /// Human-readable diagnostic message
171    pub message: String,
172}
173
174impl fmt::Display for DualRidgeResult {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        write!(f, "{}", self.message)
177    }
178}
179
180/// Residual diagnostics for observed values and predicted means.
181#[derive(Clone, Debug, PartialEq)]
182pub struct PredictionDiagnostics {
183    pub n_obs: usize,
184    pub mae: f64,
185    pub rmse: f64,
186    pub bias: f64,
187    pub r_squared: Option<f64>,
188    pub residuals: Vec<f64>,
189}
190
191/// Probability clipping used by the bundled classification diagnostic panel.
192/// Individual log-loss and Nagelkerke APIs accept an explicit clipping value;
193/// this named policy keeps the combined Rust/Python diagnostic contract in one
194/// core location.
195pub const DEFAULT_PROBABILITY_CLIP: f64 = 1.0e-12;
196
197/// Smallest standard deviation used by the bundled Gaussian score panel.
198pub const DEFAULT_GAUSSIAN_SCALE_FLOOR: f64 = 1.0e-12;
199
200/// Number of equal-width probability bins in the bundled expected-calibration
201/// error diagnostic.
202pub const DEFAULT_CALIBRATION_BINS: usize = 20;
203
204/// Production classification scores computed from one prediction vector.
205#[derive(Clone, Debug, PartialEq)]
206pub struct ClassificationPredictionMetrics {
207    pub auc: f64,
208    pub precision_recall_auc: f64,
209    pub brier: f64,
210    pub log_loss: f64,
211    pub nagelkerke_r_squared: Option<f64>,
212    pub expected_calibration_error: f64,
213}
214
215fn validate_metric_inputs(
216    metric: &str,
217    observed: &[f64],
218    predicted_mean: &[f64],
219) -> Result<(), String> {
220    if observed.is_empty() {
221        return Err(format!("{metric} requires at least one observation"));
222    }
223    if observed.len() != predicted_mean.len() {
224        return Err(format!(
225            "{metric} length mismatch: observed={} predicted={}",
226            observed.len(),
227            predicted_mean.len()
228        ));
229    }
230    if let Some((index, value)) = observed
231        .iter()
232        .copied()
233        .enumerate()
234        .find(|(_, value)| !value.is_finite())
235    {
236        return Err(format!(
237            "{metric}: observed[{index}] must be finite; got {value}"
238        ));
239    }
240    if let Some((index, value)) = predicted_mean
241        .iter()
242        .copied()
243        .enumerate()
244        .find(|(_, value)| !value.is_finite())
245    {
246        return Err(format!(
247            "{metric}: predicted_mean[{index}] must be finite; got {value}"
248        ));
249    }
250    Ok(())
251}
252
253fn validate_probability_clip(metric: &str, probability_clip: f64) -> Result<(), String> {
254    if !(probability_clip.is_finite() && probability_clip > 0.0 && probability_clip < 0.5) {
255        return Err(format!(
256            "{metric}: probability_clip must be finite and in (0, 0.5); got {probability_clip}"
257        ));
258    }
259    Ok(())
260}
261
262fn validate_probability_inputs(
263    metric: &str,
264    observed: &[f64],
265    predicted_mean: &[f64],
266) -> Result<(), String> {
267    validate_metric_inputs(metric, observed, predicted_mean)?;
268    if let Some((index, value)) = observed
269        .iter()
270        .copied()
271        .enumerate()
272        .find(|(_, value)| *value < 0.0 || *value > 1.0)
273    {
274        return Err(format!(
275            "{metric}: observed[{index}] must be in [0, 1]; got {value}"
276        ));
277    }
278    if let Some((index, value)) = predicted_mean
279        .iter()
280        .copied()
281        .enumerate()
282        .find(|(_, value)| *value < 0.0 || *value > 1.0)
283    {
284        return Err(format!(
285            "{metric}: predicted_mean[{index}] must be in [0, 1]; got {value}"
286        ));
287    }
288    Ok(())
289}
290
291/// Tie-aware Mann-Whitney AUC. Observations greater than `0.5` are the
292/// positive class, matching the package's binomial response convention.
293pub fn auc_from_predictions(observed: &[f64], predicted_mean: &[f64]) -> Result<f64, String> {
294    weighted_auc_from_predictions(observed, predicted_mean, None)
295}
296
297/// Weighted tie-aware Mann-Whitney AUC. Each positive/negative pair carries
298/// weight `w_positive * w_negative`; `None` is exactly the unit-weight score.
299pub fn weighted_auc_from_predictions(
300    observed: &[f64],
301    predicted_mean: &[f64],
302    weights: Option<&[f64]>,
303) -> Result<f64, String> {
304    validate_metric_inputs("auc", observed, predicted_mean)?;
305    if let Some(weights) = weights {
306        if weights.len() != observed.len() {
307            return Err(format!(
308                "auc length mismatch: observed={} weights={}",
309                observed.len(),
310                weights.len()
311            ));
312        }
313        if let Some((index, value)) = weights
314            .iter()
315            .copied()
316            .enumerate()
317            .find(|(_, value)| !value.is_finite() || *value < 0.0)
318        {
319            return Err(format!(
320                "auc: weights[{index}] must be finite and non-negative; got {value}"
321            ));
322        }
323    }
324
325    let weight_at = |index: usize| weights.map_or(1.0, |values| values[index]);
326    let mut pairs: Vec<(f64, bool, f64)> = observed
327        .iter()
328        .zip(predicted_mean)
329        .enumerate()
330        .map(|(index, (&y, &prediction))| (prediction, y > 0.5, weight_at(index)))
331        .collect();
332    // AUC is invariant to independent positive/negative class weight scales,
333    // so divide each class by its own MAXIMUM weight. That is what keeps a
334    // harmless common factor near `f64::MAX` from overflowing the pair
335    // products: every scaled weight is then <= 1, so the concordant total is
336    // bounded by `n_positive * n_negative` and the denominator by the same.
337    //
338    // The class TOTAL is deliberately NOT folded in here. It used to be, and
339    // dividing before summing destroyed the statistic's exactness: with unit
340    // weights each row contributed `1/n`, and n copies of `1/n` do not sum to
341    // 1.0 unless n is a power of two. A perfectly separable ranking — whose
342    // Mann-Whitney value is exactly 1 — came back as 0.9999999999999986,
343    // failing `test_gamclassifier_score_is_auc_and_metrics_panel_is_sane`'s
344    // `assert perfect == 1.0`. Dividing ONCE at the end instead keeps the
345    // unit-weight accumulation in exact integer-and-half arithmetic (every
346    // term is a whole number or a whole number plus 0.5, all exact in f64 well
347    // past any realistic row count), so the exact rational answer is returned
348    // exactly.
349    let positive_scale = pairs
350        .iter()
351        .filter(|(_, positive, _)| *positive)
352        .map(|(_, _, weight)| weight)
353        .copied()
354        .fold(0.0_f64, f64::max);
355    let negative_scale = pairs
356        .iter()
357        .filter(|(_, positive, _)| !*positive)
358        .map(|(_, _, weight)| weight)
359        .copied()
360        .fold(0.0_f64, f64::max);
361    if positive_scale <= 0.0 || negative_scale <= 0.0 {
362        return Ok(0.5);
363    }
364    let positive_weight: f64 = pairs
365        .iter()
366        .filter(|(_, positive, _)| *positive)
367        .map(|(_, _, weight)| weight / positive_scale)
368        .sum();
369    let negative_weight: f64 = pairs
370        .iter()
371        .filter(|(_, positive, _)| !*positive)
372        .map(|(_, _, weight)| weight / negative_scale)
373        .sum();
374    pairs.sort_by(|(left, _, _), (right, _, _)| left.total_cmp(right));
375
376    let mut concordant = 0.0_f64;
377    let mut negative_weight_below = 0.0_f64;
378    let mut start = 0usize;
379    while start < pairs.len() {
380        let mut end = start + 1;
381        while end < pairs.len() && pairs[end].0 == pairs[start].0 {
382            end += 1;
383        }
384        let positive_in_group: f64 = pairs[start..end]
385            .iter()
386            .filter(|(_, positive, _)| *positive)
387            .map(|(_, _, weight)| weight / positive_scale)
388            .sum();
389        let negative_in_group: f64 = pairs[start..end]
390            .iter()
391            .filter(|(_, positive, _)| !*positive)
392            .map(|(_, _, weight)| weight / negative_scale)
393            .sum();
394        concordant += positive_in_group * negative_weight_below;
395        concordant += 0.5 * positive_in_group * negative_in_group;
396        negative_weight_below += negative_in_group;
397        start = end;
398    }
399    // One division, at the end. `positive_weight` and `negative_weight` are
400    // both strictly positive here: each class maximum is > 0 (checked above), so
401    // the row achieving it contributes exactly 1.0 to its class total.
402    let auc = concordant / (positive_weight * negative_weight);
403    if auc.is_finite() {
404        Ok(auc)
405    } else {
406        Err("auc: weighted pair total is not representable in f64".to_string())
407    }
408}
409
410/// Mean squared probability error.
411pub fn brier_from_predictions(observed: &[f64], predicted_mean: &[f64]) -> Result<f64, String> {
412    validate_probability_inputs("brier", observed, predicted_mean)?;
413    let diagnostics = diagnostics_from_predictions(observed, predicted_mean)?;
414    Ok(diagnostics.rmse * diagnostics.rmse)
415}
416
417/// Mean Bernoulli log loss with a caller-selected probability clip.
418pub fn binary_log_loss_from_predictions(
419    observed: &[f64],
420    predicted_mean: &[f64],
421    probability_clip: f64,
422) -> Result<f64, String> {
423    validate_probability_inputs("log_loss", observed, predicted_mean)?;
424    validate_probability_clip("log_loss", probability_clip)?;
425    let loss = observed
426        .iter()
427        .zip(predicted_mean)
428        .map(|(&y, &prediction)| {
429            let probability = prediction.clamp(probability_clip, 1.0 - probability_clip);
430            -(y * probability.ln() + (1.0 - y) * (1.0 - probability).ln())
431        })
432        .sum::<f64>()
433        / observed.len() as f64;
434    if loss.is_finite() {
435        Ok(loss)
436    } else {
437        Err("log_loss: result is not representable in f64".to_string())
438    }
439}
440
441/// Nagelkerke's rescaling of Cox-Snell R² from model/null log likelihoods.
442/// Returns `None` when the null normalization is undefined.
443pub fn nagelkerke_r_squared_from_log_likelihoods(
444    model_log_likelihood: f64,
445    null_log_likelihood: f64,
446    n_observations: usize,
447) -> Option<f64> {
448    if n_observations == 0 || !model_log_likelihood.is_finite() || !null_log_likelihood.is_finite()
449    {
450        return None;
451    }
452    let scale = 2.0 / n_observations as f64;
453    let cox_snell = -(scale * (null_log_likelihood - model_log_likelihood)).exp_m1();
454    let maximum_cox_snell = -(scale * null_log_likelihood).exp_m1();
455    if cox_snell.is_finite() && maximum_cox_snell.is_finite() && maximum_cox_snell > 0.0 {
456        Some(cox_snell / maximum_cox_snell)
457    } else {
458        None
459    }
460}
461
462/// Nagelkerke R² for binomial predictions against an explicit null mean.
463pub fn nagelkerke_r_squared_from_predictions(
464    observed: &[f64],
465    predicted_mean: &[f64],
466    null_mean: f64,
467    probability_clip: f64,
468) -> Result<Option<f64>, String> {
469    if observed.is_empty() {
470        return Ok(None);
471    }
472    validate_probability_inputs("nagelkerke_r_squared", observed, predicted_mean)?;
473    validate_probability_clip("nagelkerke_r_squared", probability_clip)?;
474    if !null_mean.is_finite() || null_mean <= 0.0 || null_mean >= 1.0 {
475        return Ok(None);
476    }
477
478    let log_null = null_mean.ln();
479    let log_not_null = (1.0 - null_mean).ln();
480    let null_log_likelihood = observed
481        .iter()
482        .map(|&y| y * log_null + (1.0 - y) * log_not_null)
483        .sum::<f64>();
484    let model_log_likelihood = observed
485        .iter()
486        .zip(predicted_mean)
487        .map(|(&y, &prediction)| {
488            let probability = prediction.clamp(probability_clip, 1.0 - probability_clip);
489            y * probability.ln() + (1.0 - y) * (1.0 - probability).ln()
490        })
491        .sum::<f64>();
492    Ok(nagelkerke_r_squared_from_log_likelihoods(
493        model_log_likelihood,
494        null_log_likelihood,
495        observed.len(),
496    ))
497}
498
499/// Trapezoidal area under the precision-recall curve. Equal predicted scores
500/// enter as one threshold group, so row order within a tie cannot change the
501/// score.
502pub fn precision_recall_auc_from_predictions(
503    observed: &[f64],
504    predicted_mean: &[f64],
505) -> Result<f64, String> {
506    validate_metric_inputs("precision_recall_auc", observed, predicted_mean)?;
507    let mut pairs: Vec<(f64, bool)> = observed
508        .iter()
509        .zip(predicted_mean)
510        .map(|(&y, &prediction)| (prediction, y > 0.5))
511        .collect();
512    let positives = pairs.iter().filter(|(_, positive)| *positive).count();
513    if positives == 0 {
514        return Ok(0.0);
515    }
516    pairs.sort_by(|(left, _), (right, _)| right.total_cmp(left));
517    let mut true_positives = 0usize;
518    let mut false_positives = 0usize;
519    let mut previous_precision = 1.0_f64;
520    let mut previous_recall = 0.0_f64;
521    let mut area = 0.0_f64;
522    let mut start = 0usize;
523    while start < pairs.len() {
524        let score = pairs[start].0;
525        let mut end = start;
526        while end < pairs.len() && pairs[end].0 == score {
527            if pairs[end].1 {
528                true_positives += 1;
529            } else {
530                false_positives += 1;
531            }
532            end += 1;
533        }
534        let precision = true_positives as f64 / (true_positives + false_positives) as f64;
535        let recall = true_positives as f64 / positives as f64;
536        area += 0.5 * (precision + previous_precision) * (recall - previous_recall);
537        previous_precision = precision;
538        previous_recall = recall;
539        start = end;
540    }
541    Ok(area)
542}
543
544/// Equal-width-bin expected calibration error.
545pub fn expected_calibration_error_from_predictions(
546    observed: &[f64],
547    predicted_mean: &[f64],
548    n_bins: usize,
549) -> Result<f64, String> {
550    validate_probability_inputs("expected_calibration_error", observed, predicted_mean)?;
551    if n_bins == 0 {
552        return Err("expected_calibration_error requires at least one bin".to_string());
553    }
554    // Only occupied bins need storage. A dense `vec![..; n_bins]` lets an
555    // otherwise valid diagnostic request allocate independently of the data
556    // size, whereas at most `observed.len()` bins can be occupied.
557    let mut bins: BTreeMap<usize, (usize, f64, f64)> = BTreeMap::new();
558    for (&y, &prediction) in observed.iter().zip(predicted_mean) {
559        let index = ((prediction.clamp(0.0, 1.0) * n_bins as f64).floor() as usize).min(n_bins - 1);
560        let bin = bins.entry(index).or_insert((0, 0.0, 0.0));
561        bin.0 += 1;
562        bin.1 += y;
563        bin.2 += prediction;
564    }
565    let n = observed.len() as f64;
566    Ok(bins
567        .into_values()
568        .map(|(count, observed_sum, predicted_sum)| {
569            let count = count as f64;
570            (count / n) * ((observed_sum / count) - (predicted_sum / count)).abs()
571        })
572        .sum())
573}
574
575/// Gaussian negative log predictive density, allowing either one shared
576/// standard deviation or one per observation.
577pub fn gaussian_log_loss_from_predictions(
578    observed: &[f64],
579    predicted_mean: &[f64],
580    sigma: &[f64],
581    sigma_floor: f64,
582) -> Result<f64, String> {
583    validate_metric_inputs("gaussian_log_loss", observed, predicted_mean)?;
584    if sigma.len() != 1 && sigma.len() != observed.len() {
585        return Err(format!(
586            "gaussian_log_loss: sigma length must be 1 or {}; got {}",
587            observed.len(),
588            sigma.len()
589        ));
590    }
591    if !(sigma_floor.is_finite() && sigma_floor > 0.0) {
592        return Err(format!(
593            "gaussian_log_loss: sigma_floor must be finite and positive; got {sigma_floor}"
594        ));
595    }
596    let shared_sigma = sigma.len() == 1;
597    let mut total = 0.0_f64;
598    for (index, (&y, &mean)) in observed.iter().zip(predicted_mean).enumerate() {
599        let raw_sigma = if shared_sigma { sigma[0] } else { sigma[index] };
600        if !raw_sigma.is_finite() || raw_sigma <= 0.0 {
601            return Err(format!(
602                "gaussian_log_loss: sigma[{}] must be finite and positive; got {raw_sigma}",
603                if shared_sigma { 0 } else { index }
604            ));
605        }
606        let sigma = raw_sigma.max(sigma_floor);
607        let standardized_residual = (y - mean) / sigma;
608        total += 0.5 * std::f64::consts::TAU.ln()
609            + sigma.ln()
610            + 0.5 * standardized_residual * standardized_residual;
611    }
612    let loss = total / observed.len() as f64;
613    if loss.is_finite() {
614        Ok(loss)
615    } else {
616        Err("gaussian_log_loss: result is not representable in f64".to_string())
617    }
618}
619
620/// The package's standard classification diagnostic panel.
621pub fn classification_metrics_from_predictions(
622    observed: &[f64],
623    predicted_mean: &[f64],
624    null_mean: f64,
625) -> Result<ClassificationPredictionMetrics, String> {
626    validate_probability_inputs("classification_metrics", observed, predicted_mean)?;
627    Ok(ClassificationPredictionMetrics {
628        auc: auc_from_predictions(observed, predicted_mean)?,
629        precision_recall_auc: precision_recall_auc_from_predictions(observed, predicted_mean)?,
630        brier: brier_from_predictions(observed, predicted_mean)?,
631        log_loss: binary_log_loss_from_predictions(
632            observed,
633            predicted_mean,
634            DEFAULT_PROBABILITY_CLIP,
635        )?,
636        nagelkerke_r_squared: nagelkerke_r_squared_from_predictions(
637            observed,
638            predicted_mean,
639            null_mean,
640            DEFAULT_PROBABILITY_CLIP,
641        )?,
642        expected_calibration_error: expected_calibration_error_from_predictions(
643            observed,
644            predicted_mean,
645            DEFAULT_CALIBRATION_BINS,
646        )?,
647    })
648}
649
650/// Compute prediction residual diagnostics from observed values and predicted means.
651pub fn diagnostics_from_predictions(
652    observed: &[f64],
653    predicted_mean: &[f64],
654) -> Result<PredictionDiagnostics, String> {
655    if observed.is_empty() {
656        return Err("diagnostics_from_predictions requires at least one observation".to_string());
657    }
658    if observed.len() != predicted_mean.len() {
659        return Err(format!(
660            "diagnostics_from_predictions length mismatch: observed has {} values but predicted mean has {}",
661            observed.len(),
662            predicted_mean.len()
663        ));
664    }
665    if observed.iter().any(|value| !value.is_finite()) {
666        return Err("observed values must contain only finite numbers".to_string());
667    }
668    if predicted_mean.iter().any(|value| !value.is_finite()) {
669        return Err("predicted mean values must contain only finite numbers".to_string());
670    }
671
672    let n_obs = observed.len();
673    let n_obs_f = n_obs as f64;
674    let mut residuals = Vec::with_capacity(n_obs);
675    let mut abs_sum = 0.0_f64;
676    let mut residual_sum = 0.0_f64;
677    let mut residual_sum_squares = 0.0_f64;
678    let mut observed_sum = 0.0_f64;
679    for (obs, pred) in observed.iter().zip(predicted_mean.iter()) {
680        let residual = obs - pred;
681        residuals.push(residual);
682        abs_sum += residual.abs();
683        residual_sum += residual;
684        residual_sum_squares += residual * residual;
685        observed_sum += obs;
686    }
687
688    let observed_mean = observed_sum / n_obs_f;
689    let total_sum_squares = observed
690        .iter()
691        .map(|value| {
692            let centered = value - observed_mean;
693            centered * centered
694        })
695        .sum::<f64>();
696    let r_squared = if total_sum_squares > 0.0 {
697        Some(1.0 - residual_sum_squares / total_sum_squares)
698    } else {
699        None
700    };
701
702    Ok(PredictionDiagnostics {
703        n_obs,
704        mae: abs_sum / n_obs_f,
705        rmse: (residual_sum_squares / n_obs_f).sqrt(),
706        bias: residual_sum / n_obs_f,
707        r_squared,
708        residuals,
709    })
710}
711
712/// Complete diagnostic report for a gradient evaluation
713#[derive(Clone, Debug, Default)]
714pub struct GradientDiagnosticReport {
715    /// Envelope theorem audit results
716    pub envelopeaudit: Option<EnvelopeAudit>,
717    /// Spectral bleed results for each penalty
718    pub spectral_bleed: Vec<SpectralBleedResult>,
719    /// Dual-ridge consistency result
720    pub dualridge: Option<DualRidgeResult>,
721}
722
723impl GradientDiagnosticReport {
724    /// Create an empty report
725    pub fn new() -> Self {
726        Self::default()
727    }
728
729    /// Generate a summary string of all issues found
730    pub fn summary(&self) -> String {
731        let mut lines = Vec::new();
732
733        if let Some(ref audit) = self.envelopeaudit
734            && audit.isviolated
735        {
736            lines.push(format!("[DIAG] {}", audit));
737        }
738
739        for bleed in &self.spectral_bleed {
740            if bleed.has_bleed {
741                lines.push(format!("[DIAG] {}", bleed));
742            }
743        }
744
745        if let Some(ref ridge) = self.dualridge
746            && ridge.has_mismatch
747        {
748            lines.push(format!("[DIAG] {}", ridge));
749        }
750
751        if lines.is_empty() {
752            "No gradient diagnostic issues detected.".to_string()
753        } else {
754            lines.join("\n")
755        }
756    }
757}
758
759// =============================================================================
760// Strategy 1: Envelope Theorem (KKT) Audit
761// =============================================================================
762
763/// Compute the inner KKT residual to detect envelope theorem violations.
764///
765/// The analytic gradient calculation assumes that P-IRLS found an exact stationary
766/// point where ∇_β L = 0. If this is not true (due to stabilization ridge, Firth
767/// adjustments, or early termination), the "indirect term" of the chain rule becomes
768/// significant and the gradient will be wrong.
769///
770/// # Arguments
771/// * `kkt_residual_norm` - Norm of the full inner gradient ||∇_β L|| at the PIRLS solution
772/// * `referencegradient` - Reference gradient scale (typically S_λ β) for relative normalization
773/// * `ridge_used` - Ridge added by PIRLS for stabilization
774/// * `beta` - Current coefficient estimate
775/// * `tolerance` - Threshold for flagging violations
776pub fn compute_envelopeaudit(
777    kkt_residual_norm: f64,
778    referencegradient: &Array1<f64>,
779    ridge_used: f64,
780    ridge_assumed: f64,
781    beta: &Array1<f64>,
782    abs_tolerance: f64,
783    rel_tolerance: f64,
784) -> EnvelopeAudit {
785    let kkt_norm = kkt_residual_norm;
786    let penalty_norm = referencegradient.dot(referencegradient).sqrt();
787    let beta_norm = beta.dot(beta).sqrt();
788    let scale = penalty_norm.max((ridge_assumed.abs() * beta_norm).max(1e-12));
789    let rel_kkt = if scale > 0.0 { kkt_norm / scale } else { 0.0 };
790    let ridge_mismatch = (ridge_used - ridge_assumed).abs() > 1e-12;
791    let kktviolation = kkt_norm > abs_tolerance && rel_kkt > rel_tolerance;
792    let isviolated = kktviolation || ridge_mismatch;
793
794    let message = if ridge_mismatch && kktviolation {
795        format!(
796            "Envelope Violation: Inner solver ridge = {:.2e}, Outer gradient assumes ridge = {:.2e}. \
797             KKT residual norm = {:.2e} (abs tol = {:.2e}, rel tol = {:.2e}). Unaccounted gradient energy: {:.2e}",
798            ridge_used, ridge_assumed, kkt_norm, abs_tolerance, rel_tolerance, kkt_norm
799        )
800    } else if ridge_mismatch {
801        format!(
802            "Ridge Mismatch: PIRLS optimized for H + {:.2e}*I, but Gradient calculated for H + {:.2e}*I",
803            ridge_used, ridge_assumed
804        )
805    } else if kktviolation {
806        format!(
807            "Envelope Violation: KKT residual ||∇_β L|| = {:.2e} (rel {:.2e}) exceeds tolerances (abs {:.2e}, rel {:.2e}). \
808             Inner solver may not have converged to true stationary point.",
809            kkt_norm, rel_kkt, abs_tolerance, rel_tolerance
810        )
811    } else {
812        format!(
813            "Envelope OK: KKT residual = {:.2e} (rel {:.2e}), ridge match = {:.2e}",
814            kkt_norm, rel_kkt, ridge_used
815        )
816    };
817
818    EnvelopeAudit {
819        kkt_residual_norm: kkt_norm,
820        innerridge: ridge_used,
821        outerridge: ridge_assumed,
822        isviolated,
823        message,
824    }
825}
826
827// =============================================================================
828// Strategy 4: Dual-Ridge Consistency Check
829// =============================================================================
830
831/// Check consistency between the ridge used in different stages of computation.
832///
833/// When the Hessian is non-positive-definite, ensure_positive_definitewithridge
834/// adds a stabilization ridge during P-IRLS. This ridge changes the objective
835/// surface being optimized. If the gradient calculation uses a different ridge
836/// value, it will point in the wrong direction.
837///
838/// # Arguments
839/// * `pirlsridge` - Ridge actually used during P-IRLS iteration
840/// * `costridge` - Ridge used when computing LAML cost
841/// * `gradientridge` - Ridge assumed when computing analytic gradient
842/// * `beta` - Current coefficient estimate
843pub fn compute_dualridge_check(
844    pirlsridge: f64,
845    costridge: f64,
846    gradientridge: f64,
847    beta: &Array1<f64>,
848) -> DualRidgeResult {
849    let beta_norm_sq = beta.dot(beta);
850    let beta_norm = beta_norm_sq.sqrt();
851
852    let ridge_impact = pirlsridge * beta_norm;
853    let phantom_penalty = 0.5 * pirlsridge * beta_norm_sq;
854
855    let pirlscost_mismatch = (pirlsridge - costridge).abs() > 1e-12;
856    let pirlsgrad_mismatch = (pirlsridge - gradientridge).abs() > 1e-12;
857    let costgrad_mismatch = (costridge - gradientridge).abs() > 1e-12;
858    let has_mismatch = pirlscost_mismatch || pirlsgrad_mismatch || costgrad_mismatch;
859
860    let message = if has_mismatch {
861        let mut mismatches = Vec::new();
862        if pirlscost_mismatch {
863            mismatches.push(format!(
864                "PIRLS({:.2e}) vs Cost({:.2e})",
865                pirlsridge, costridge
866            ));
867        }
868        if pirlsgrad_mismatch {
869            mismatches.push(format!(
870                "PIRLS({:.2e}) vs Gradient({:.2e})",
871                pirlsridge, gradientridge
872            ));
873        }
874        if costgrad_mismatch {
875            mismatches.push(format!(
876                "Cost({:.2e}) vs Gradient({:.2e})",
877                costridge, gradientridge
878            ));
879        }
880        format!(
881            "Ridge Mismatch detected: {}. Effective ridge impact on ||β|| = {:.2e}. \
882             Phantom penalty = {:.2e}. The surface being differentiated differs from \
883             the surface being optimized.",
884            mismatches.join(", "),
885            ridge_impact,
886            phantom_penalty
887        )
888    } else if pirlsridge > 0.0 {
889        format!(
890            "Ridge Consistency OK: All stages use ridge = {:.2e}. ||β|| = {:.2e}, phantom penalty = {:.2e}",
891            pirlsridge, beta_norm, phantom_penalty
892        )
893    } else {
894        "Ridge Consistency OK: No stabilization ridge required.".to_string()
895    };
896
897    DualRidgeResult {
898        pirlsridge,
899        costridge,
900        gradientridge,
901        ridge_impact,
902        phantom_penalty,
903        has_mismatch,
904        message,
905    }
906}
907
908/// Three-way classification of why the cert refused, computed from the
909/// H_pen spectrum and the projected residual at the refusing iterate.
910/// `RankDeficientHPen` is the regression canary the nullspace lead's
911/// smooth-construction rework is intended to eliminate; keep this variant
912/// intact when extending — it doubles as the user-facing signal for
913/// "an unconstrained polynomial null space slipped past absorption."
914///
915/// Relocated from `gam-solve`'s `custom_family/joint_newton.rs` (issue #1521
916/// crate carve): this is the neutral diagnostic carrier that `gam-solve`'s
917/// REML/PIRLS core consumes when classifying a custom-family cert refusal,
918/// so it must live BELOW both the core and the (extracted) custom-family
919/// subsystem.
920#[derive(Clone, Copy, Debug, PartialEq, Eq)]
921pub enum KktRefusalDiagnosis {
922    RankDeficientHPen,
923    PhantomMultiplierWithWellConditionedH,
924    ActiveSetIncomplete,
925    /// Cross-block identifiability aliasing surfaced mid-inner-solve
926    /// (e.g., a binding active set materialised a 2-way alias that
927    /// the pre-fit audit could not see at the cold design). The fix
928    /// is structural — drop or reparameterise the aliased block;
929    /// rho-anneal will not recover.
930    AliasingDetectedAtFit,
931}
932
933impl KktRefusalDiagnosis {
934    pub fn as_str(&self) -> &'static str {
935        match self {
936            KktRefusalDiagnosis::RankDeficientHPen => "rank_deficient_H_pen",
937            KktRefusalDiagnosis::PhantomMultiplierWithWellConditionedH => {
938                "phantom_multiplier_with_well_conditioned_H"
939            }
940            KktRefusalDiagnosis::ActiveSetIncomplete => "active_set_incomplete",
941            KktRefusalDiagnosis::AliasingDetectedAtFit => "aliasing_detected_at_fit",
942        }
943    }
944
945    /// Parse the textual `diagnosis:` field embedded in the structured
946    /// bubbled error string. Returns `None` when no recognised label is
947    /// present (legacy / non-cert-refusal error strings).
948    pub fn parse_from_error(message: &str) -> Option<Self> {
949        let marker = "diagnosis: ";
950        let start = message.rfind(marker)? + marker.len();
951        let tail = &message[start..];
952        let end = tail
953            .find(|c: char| c == ';' || c == '\n' || c == ' ')
954            .unwrap_or(tail.len());
955        match &tail[..end] {
956            "rank_deficient_H_pen" => Some(KktRefusalDiagnosis::RankDeficientHPen),
957            "phantom_multiplier_with_well_conditioned_H" => {
958                Some(KktRefusalDiagnosis::PhantomMultiplierWithWellConditionedH)
959            }
960            "active_set_incomplete" => Some(KktRefusalDiagnosis::ActiveSetIncomplete),
961            "aliasing_detected_at_fit" => Some(KktRefusalDiagnosis::AliasingDetectedAtFit),
962            _ => None,
963        }
964    }
965
966    pub fn guidance(self) -> &'static str {
967        match self {
968            KktRefusalDiagnosis::RankDeficientHPen => {
969                "check whether the named block has a structural or numerical null direction \
970                 not identified by the likelihood/penalty combination; for Duchon-style \
971                 smooths this may be a polynomial null space, while marginal-slope fits can \
972                 also expose callback-owned weak directions"
973            }
974            KktRefusalDiagnosis::PhantomMultiplierWithWellConditionedH => {
975                "check whether the named block has a near-separated or weakly identified \
976                 direction despite a well-conditioned penalized Hessian; in marginal-slope \
977                 fits this often indicates marginal/logslope coupling rather than a \
978                 Matérn/Duchon polynomial-nullspace failure"
979            }
980            KktRefusalDiagnosis::ActiveSetIncomplete => {
981                "check whether the named block's linear constraints need an additional \
982                 active row or a tighter constrained re-solve; this is an active-set \
983                 certification failure, not a polynomial-nullspace diagnosis"
984            }
985            KktRefusalDiagnosis::AliasingDetectedAtFit => {
986                "check whether the named block aliases another block after runtime \
987                 constraints or callbacks materialize; drop or reparameterize the aliased \
988                 direction before fitting"
989            }
990        }
991    }
992}
993
994#[cfg(test)]
995mod tests {
996    use super::*;
997    use ndarray::arr1;
998
999    #[test]
1000    fn test_envelopeaudit_noviolation() {
1001        let reference = arr1(&[0.0, 0.0, 0.0]);
1002        let beta = arr1(&[0.1, 0.2, 0.3]);
1003        let result = compute_envelopeaudit(0.0, &reference, 0.0, 0.0, &beta, 1e-8, 1e-6);
1004
1005        assert!(!result.isviolated);
1006    }
1007
1008    #[test]
1009    fn test_envelopeaudit_detects_ridge_mismatch() {
1010        let reference = arr1(&[1.0, 0.0, 0.0]);
1011        let beta = arr1(&[0.1, 0.2, 0.3]);
1012        let result = compute_envelopeaudit(1e-10, &reference, 0.1, 0.0, &beta, 1e-8, 1e-6);
1013
1014        assert!(result.isviolated);
1015        assert!(result.message.contains("Ridge Mismatch"));
1016    }
1017
1018    #[test]
1019    fn test_dualridge_check_no_mismatch() {
1020        let beta = arr1(&[0.1, 0.2, 0.3]);
1021        let result = compute_dualridge_check(0.0, 0.0, 0.0, &beta);
1022
1023        assert!(!result.has_mismatch);
1024    }
1025
1026    #[test]
1027    fn test_dualridge_check_detects_mismatch() {
1028        let beta = arr1(&[0.1, 0.2, 0.3]);
1029        let result = compute_dualridge_check(1e-4, 0.0, 0.0, &beta);
1030
1031        assert!(result.has_mismatch);
1032        assert!(result.message.contains("Ridge Mismatch detected"));
1033    }
1034
1035    #[test]
1036    fn diagnostics_from_predictions_computes_residual_metrics() {
1037        let observed = [1.0, 2.0, 4.0];
1038        let predicted = [1.5, 1.5, 3.0];
1039
1040        let result = diagnostics_from_predictions(&observed, &predicted).unwrap();
1041
1042        assert_eq!(result.residuals, vec![-0.5, 0.5, 1.0]);
1043        assert_eq!(result.n_obs, 3);
1044        assert_eq!(result.mae, 2.0 / 3.0);
1045        assert_eq!(result.bias, 1.0 / 3.0);
1046        assert_eq!(result.rmse, (1.5_f64 / 3.0).sqrt());
1047        assert_eq!(result.r_squared, Some(1.0 - 1.5 / (14.0 / 3.0)));
1048    }
1049
1050    #[test]
1051    fn diagnostics_from_predictions_omits_r_squared_for_constant_observed() {
1052        let observed = [2.0, 2.0];
1053        let predicted = [1.0, 3.0];
1054
1055        let result = diagnostics_from_predictions(&observed, &predicted).unwrap();
1056
1057        assert_eq!(result.r_squared, None);
1058    }
1059
1060    #[test]
1061    fn diagnostics_from_predictions_rejects_invalid_inputs() {
1062        assert_eq!(
1063            diagnostics_from_predictions(&[], &[]),
1064            Err("diagnostics_from_predictions requires at least one observation".to_string())
1065        );
1066        assert_eq!(
1067            diagnostics_from_predictions(&[1.0], &[1.0, 2.0]),
1068            Err(
1069                "diagnostics_from_predictions length mismatch: observed has 1 values but predicted mean has 2"
1070                    .to_string()
1071            )
1072        );
1073        assert_eq!(
1074            diagnostics_from_predictions(&[f64::NAN], &[1.0]),
1075            Err("observed values must contain only finite numbers".to_string())
1076        );
1077        assert_eq!(
1078            diagnostics_from_predictions(&[1.0], &[f64::INFINITY]),
1079            Err("predicted mean values must contain only finite numbers".to_string())
1080        );
1081    }
1082
1083    #[test]
1084    fn auc_is_tie_aware_and_weighted_auc_reduces_to_unit_weights() {
1085        let observed = [0.0, 1.0, 0.0, 1.0];
1086        let predicted = [0.1, 0.8, 0.8, 0.9];
1087        let auc = auc_from_predictions(&observed, &predicted).unwrap();
1088        assert_eq!(auc, 0.875);
1089        assert_eq!(
1090            weighted_auc_from_predictions(&observed, &predicted, Some(&[1.0; 4])).unwrap(),
1091            auc
1092        );
1093
1094        let weighted = weighted_auc_from_predictions(
1095            &[1.0, 0.0, 1.0],
1096            &[0.5, 0.5, 0.9],
1097            Some(&[2.0, 3.0, 1.0]),
1098        )
1099        .unwrap();
1100        assert_eq!(weighted, 2.0 / 3.0);
1101        assert!(
1102            weighted_auc_from_predictions(&[0.0, 1.0], &[0.2, 0.8], Some(&[1.0, -1.0])).is_err()
1103        );
1104        assert_eq!(
1105            weighted_auc_from_predictions(&[1.0, 0.0], &[0.5, 0.5], Some(&[f64::MAX, f64::MAX]),)
1106                .unwrap(),
1107            0.5
1108        );
1109    }
1110
1111    /// A perfect ranking has Mann-Whitney AUC exactly 1, and the estimator must
1112    /// return exactly that — not 1 - 6ulp.
1113    ///
1114    /// The old accumulation divided each row by its class TOTAL before summing,
1115    /// so it added `n` copies of `1/n`; that equals 1.0 only when `n` is a power
1116    /// of two. `n = 100` (and 97, and 63) are the ordinary cases where it does
1117    /// not, and `test_gamclassifier_score_is_auc_and_metrics_panel_is_sane` had
1118    /// been failing on exactly this: `separable ranking must give AUC 1.0; got
1119    /// 0.9999999999999986`.
1120    ///
1121    /// The class sizes below are deliberately NOT powers of two, and are
1122    /// unequal, so the test would have failed before the fix and cannot pass by
1123    /// accident of a representable denominator.
1124    #[test]
1125    fn a_perfectly_separable_ranking_scores_exactly_one() {
1126        for (negatives, positives) in [(100usize, 100usize), (97, 63), (13, 501)] {
1127            let mut observed = Vec::with_capacity(negatives + positives);
1128            let mut predicted = Vec::with_capacity(negatives + positives);
1129            for index in 0..negatives {
1130                observed.push(0.0);
1131                predicted.push(index as f64);
1132            }
1133            for index in 0..positives {
1134                observed.push(1.0);
1135                predicted.push((negatives + index) as f64);
1136            }
1137            let auc = auc_from_predictions(&observed, &predicted).unwrap();
1138            assert_eq!(
1139                auc, 1.0,
1140                "separable ranking with {negatives} negatives and {positives} positives \
1141                 must score exactly 1.0, got {auc:?}"
1142            );
1143
1144            // The mirror image is exactly 0 by the same argument; an estimator
1145            // that is exact at one end and not the other is still rounding.
1146            let reversed: Vec<f64> = observed.iter().map(|y| 1.0 - y).collect();
1147            let auc_reversed = auc_from_predictions(&reversed, &predicted).unwrap();
1148            assert_eq!(auc_reversed, 0.0, "reversed ranking must score exactly 0.0");
1149        }
1150    }
1151
1152    /// Unit weights must remain the identity of the weighted path after the
1153    /// normalization change, at a size where the old per-row division rounded.
1154    #[test]
1155    fn unit_weights_match_the_unweighted_score_at_scale() {
1156        let observed: Vec<f64> = (0..200).map(|i| f64::from(i % 3 == 0)).collect();
1157        let predicted: Vec<f64> = (0..200).map(|i| ((i * 37) % 101) as f64).collect();
1158        let plain = auc_from_predictions(&observed, &predicted).unwrap();
1159        let unit =
1160            weighted_auc_from_predictions(&observed, &predicted, Some(&vec![1.0; 200])).unwrap();
1161        assert_eq!(plain, unit);
1162        // A common positive factor is a no-op: AUC is scale-invariant per class.
1163        let doubled =
1164            weighted_auc_from_predictions(&observed, &predicted, Some(&vec![2.0; 200])).unwrap();
1165        assert_eq!(plain, doubled);
1166    }
1167
1168    #[test]
1169    fn precision_recall_auc_consumes_ties_as_one_threshold() {
1170        let first = precision_recall_auc_from_predictions(&[1.0, 0.0], &[0.5, 0.5]).unwrap();
1171        let reversed = precision_recall_auc_from_predictions(&[0.0, 1.0], &[0.5, 0.5]).unwrap();
1172        assert_eq!(first, 0.75);
1173        assert_eq!(first, reversed);
1174    }
1175
1176    #[test]
1177    fn probability_scores_match_closed_forms() {
1178        let observed = [0.0, 1.0];
1179        let predicted = [0.5, 0.5];
1180        let log_loss =
1181            binary_log_loss_from_predictions(&observed, &predicted, DEFAULT_PROBABILITY_CLIP)
1182                .unwrap();
1183        assert!((log_loss - std::f64::consts::LN_2).abs() < 1.0e-15);
1184        assert_eq!(brier_from_predictions(&observed, &predicted).unwrap(), 0.25);
1185        assert_eq!(
1186            expected_calibration_error_from_predictions(&observed, &predicted, 2).unwrap(),
1187            0.0
1188        );
1189        assert!(
1190            binary_log_loss_from_predictions(&observed, &predicted, 0.5).is_err(),
1191            "a clip that collapses the probability interval must be rejected"
1192        );
1193        assert!(classification_metrics_from_predictions(&observed, &[0.5, 2.0], 0.5).is_err());
1194        assert!(classification_metrics_from_predictions(&[-0.1, 1.0], &predicted, 0.5).is_err());
1195    }
1196
1197    #[test]
1198    fn nagelkerke_and_classification_panel_share_the_core_kernels() {
1199        let observed = [0.0, 0.0, 1.0, 1.0];
1200        let predicted = [0.1, 0.2, 0.8, 0.9];
1201        let metrics = classification_metrics_from_predictions(&observed, &predicted, 0.5).unwrap();
1202        assert_eq!(metrics.auc, 1.0);
1203        assert_eq!(metrics.precision_recall_auc, 1.0);
1204        assert_eq!(
1205            metrics.nagelkerke_r_squared,
1206            nagelkerke_r_squared_from_predictions(
1207                &observed,
1208                &predicted,
1209                0.5,
1210                DEFAULT_PROBABILITY_CLIP,
1211            )
1212            .unwrap()
1213        );
1214        assert!(metrics.nagelkerke_r_squared.unwrap() > 0.8);
1215        assert_eq!(
1216            nagelkerke_r_squared_from_predictions(
1217                &observed,
1218                &predicted,
1219                1.0,
1220                DEFAULT_PROBABILITY_CLIP,
1221            )
1222            .unwrap(),
1223            None
1224        );
1225    }
1226
1227    #[test]
1228    fn gaussian_log_loss_matches_closed_form_and_rejects_invalid_sigma() {
1229        let observed = [1.0, 2.0, 3.0, 4.0];
1230        let predicted = observed;
1231        let sigma = [1.5];
1232        let got = gaussian_log_loss_from_predictions(
1233            &observed,
1234            &predicted,
1235            &sigma,
1236            DEFAULT_GAUSSIAN_SCALE_FLOOR,
1237        )
1238        .unwrap();
1239        let expected = 0.5 * (std::f64::consts::TAU * 1.5 * 1.5).ln();
1240        assert!((got - expected).abs() < 1.0e-12);
1241        assert!(
1242            gaussian_log_loss_from_predictions(
1243                &observed,
1244                &predicted,
1245                &[1.0, 2.0],
1246                DEFAULT_GAUSSIAN_SCALE_FLOOR,
1247            )
1248            .is_err()
1249        );
1250        assert!(
1251            gaussian_log_loss_from_predictions(
1252                &observed,
1253                &predicted,
1254                &[0.0],
1255                DEFAULT_GAUSSIAN_SCALE_FLOOR,
1256            )
1257            .is_err()
1258        );
1259    }
1260}