gam-problem 0.3.156

Neutral solver/criterion contract types for the gam penalized-likelihood engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
use ndarray::{Array1, ArrayView1};
use serde::{Deserialize, Serialize};
use std::ops::{Deref, DerefMut};

pub use gam_linalg::RidgePolicy;

pub use gam_spec::*;

/// Storage form of the ridge penalty matrix.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RidgeMatrixForm {
    /// Ridge matrix is `delta * I`.
    ScaledIdentity,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvalidStabilization {
    reason: String,
}

impl InvalidStabilization {
    fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
        }
    }

    pub fn reason(&self) -> &str {
        &self.reason
    }
}

impl std::fmt::Display for InvalidStabilization {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "invalid stabilization metadata: {}", self.reason)
    }
}

impl std::error::Error for InvalidStabilization {}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
struct RidgePassportWire {
    delta: f64,
    matrix_form: RidgeMatrixForm,
    policy: RidgePolicy,
}

/// Validated ridge metadata stamped into a fitted PIRLS result.
///
/// Construction and deserialization both reject non-finite or negative
/// magnitudes; fields are private so invalid state cannot be assembled with a
/// literal.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "RidgePassportWire", into = "RidgePassportWire")]
pub struct RidgePassport {
    delta: f64,
    matrix_form: RidgeMatrixForm,
    policy: RidgePolicy,
}

impl RidgePassport {
    pub fn scaled_identity(delta: f64, policy: RidgePolicy) -> Result<Self, InvalidStabilization> {
        if !(delta.is_finite() && delta >= 0.0) {
            return Err(InvalidStabilization::new(format!(
                "ridge delta must be finite and non-negative, got {delta:?}"
            )));
        }
        Ok(Self {
            delta: if delta == 0.0 { 0.0 } else { delta },
            matrix_form: RidgeMatrixForm::ScaledIdentity,
            policy,
        })
    }

    /// Exact zero-ridge passport; this fixed sentinel has no unchecked input.
    pub const fn zero(policy: RidgePolicy) -> Self {
        Self {
            delta: 0.0,
            matrix_form: RidgeMatrixForm::ScaledIdentity,
            policy,
        }
    }

    #[inline]
    pub const fn delta(self) -> f64 {
        self.delta
    }

    #[inline]
    pub const fn matrix_form(self) -> RidgeMatrixForm {
        self.matrix_form
    }

    #[inline]
    pub const fn policy(self) -> RidgePolicy {
        self.policy
    }

    #[inline]
    pub const fn penalty_logdet_ridge(self) -> f64 {
        if self.policy.accounts_for_objective() {
            self.delta
        } else {
            0.0
        }
    }

}

impl TryFrom<RidgePassportWire> for RidgePassport {
    type Error = InvalidStabilization;

    fn try_from(wire: RidgePassportWire) -> Result<Self, Self::Error> {
        let mut passport = Self::scaled_identity(wire.delta, wire.policy)?;
        passport.matrix_form = wire.matrix_form;
        Ok(passport)
    }
}

impl From<RidgePassport> for RidgePassportWire {
    fn from(passport: RidgePassport) -> Self {
        Self {
            delta: passport.delta,
            matrix_form: passport.matrix_form,
            policy: passport.policy,
        }
    }
}

// ============================================================================
// StabilizationLedger: canonical accounting for every fixed/heuristic ridge
// added anywhere in the solver, linear-algebra, or family code paths.
//
// Five semantically distinct ridge uses must NEVER be conflated:
//   1. SolverDampingOnly      — Levenberg/trust-region damping; never enters
//                               objective, gradient, logdet, Hessian, or any
//                               saved/serialized model artifact.
//   2. NumericalPerturbation  — added strictly so a linear solve is well-
//                               posed (e.g. Cholesky of a near-singular
//                               matrix). Carries an optional backward-error
//                               bound. Does NOT change the objective.
//   3. ExplicitPrior          — model-level `delta * I` (or block-diagonal)
//                               prior. Appears in quadratic, log normalizer,
//                               Laplace Hessian, serialization, diagnostics.
//   4. ApproximationOnly      — changes a named downstream approximation
//                               (for example sigma-point cubature covariance)
//                               but not the fitted model or its objective.
//   5. ObjectiveStabilization — algorithm-selected ridge consistently included
//                               in the fitted objective, preserving exact versus
//                               approximate determinant provenance.
//
// `RidgePassport` above already encodes the inclusion-flag matrix for the
// PIRLS Laplace ridge specifically; this ledger is the broader sibling for
// every declared solver, approximation, and model ridge, so a downstream consumer can ask
// `ledger.quadratic_delta()` rather than rediscovering the policy. The three
// inclusion bits were lifted into the `StabilizationKind` discriminant so the
// (kind, inclusion-flags) invariant is enforced statically — heterogeneous
// combinations like "ExplicitPrior with quadratic excluded" no longer typecheck.
// ============================================================================

/// Inertia of a symmetric matrix (count of positive / zero / negative
/// eigenvalues). Used by `bump_with_matrix` and other indefinite-aware
/// stabilization rules to drive δ from spectral evidence rather than a
/// condition-number heuristic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "InertiaWire", into = "InertiaWire")]
pub struct Inertia {
    positive: usize,
    zero: usize,
    negative: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct InertiaWire {
    positive: usize,
    zero: usize,
    negative: usize,
}

impl Inertia {
    pub fn new(
        positive: usize,
        zero: usize,
        negative: usize,
    ) -> Result<Self, InvalidStabilization> {
        let total = positive
            .checked_add(zero)
            .and_then(|value| value.checked_add(negative))
            .ok_or_else(|| InvalidStabilization::new("inertia count sum overflows usize"))?;
        if total == 0 {
            return Err(InvalidStabilization::new(
                "inertia must describe a non-empty matrix",
            ));
        }
        Ok(Self {
            positive,
            zero,
            negative,
        })
    }

    pub const fn positive(self) -> usize {
        self.positive
    }

    pub const fn zero(self) -> usize {
        self.zero
    }

    pub const fn negative(self) -> usize {
        self.negative
    }

    pub fn total(self) -> usize {
        self.positive + self.zero + self.negative
    }
}

impl TryFrom<InertiaWire> for Inertia {
    type Error = InvalidStabilization;

    fn try_from(wire: InertiaWire) -> Result<Self, Self::Error> {
        Self::new(wire.positive, wire.zero, wire.negative)
    }
}

impl From<Inertia> for InertiaWire {
    fn from(inertia: Inertia) -> Self {
        Self {
            positive: inertia.positive,
            zero: inertia.zero,
            negative: inertia.negative,
        }
    }
}

/// Why a stabilization δ was chosen at this site.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum StabilizationRule {
    /// δ is a hard-coded constant in the source.
    FixedConstant,
    /// δ chosen so the SPD floor τ is met: δ = max(0, τ - λ_min(H)).
    InertiaTarget { spd_floor: f64 },
    /// δ chosen via a condition-number / sqrt-ratio heuristic.
    Heuristic,
    /// User- or family-specified prior precision.
    UserSpecified,
    /// δ derived from a back-off escalation after a factorization failure.
    BackoffEscalation { attempts: usize },
}

/// Semantically distinct flavours a ridge δ can have.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum StabilizationKind {
    None,
    /// LM/TR damping. NEVER enters the objective, gradient, logdet, Hessian,
    /// or any saved model artifact. Lives only inside the trust-region step.
    SolverDampingOnly,
    /// Added strictly so a linear solve succeeds. The objective/Hessian the
    /// caller sees is unchanged; the perturbation is a property of the
    /// solver, not the model. Its optional backward-error bound lives on the
    /// enclosing ledger.
    NumericalPerturbation,
    /// An explicit part of a downstream approximation, not of the fitted
    /// model. Unlike `NumericalPerturbation`, consumers must not report the
    /// result as if the unperturbed estimand had been evaluated.
    ApproximationOnly,
    /// Algorithm-selected ridge consistently included in the fitted objective.
    /// The ledger's objective policy preserves determinant provenance.
    ObjectiveStabilization,
    /// Part of the model. Enters quadratic, log normalizer, Hessian,
    /// serialization, and user-visible summaries.
    ExplicitPrior,
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
struct StabilizationLedgerWire {
    kind: StabilizationKind,
    delta: f64,
    matrix_form: RidgeMatrixForm,
    chosen_by: StabilizationRule,
    objective_policy: Option<RidgePolicy>,
    backward_error_bound: Option<f64>,
    inertia_before: Option<Inertia>,
    inertia_after: Option<Inertia>,
}

/// Canonical validated record of one stabilization applied at one site.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "StabilizationLedgerWire", into = "StabilizationLedgerWire")]
pub struct StabilizationLedger {
    kind: StabilizationKind,
    delta: f64,
    matrix_form: RidgeMatrixForm,
    chosen_by: StabilizationRule,
    objective_policy: Option<RidgePolicy>,
    backward_error_bound: Option<f64>,
    inertia_before: Option<Inertia>,
    inertia_after: Option<Inertia>,
}

impl StabilizationLedger {
    /// "No stabilization applied at this site" sentinel.
    pub const fn none() -> Self {
        Self {
            kind: StabilizationKind::None,
            delta: 0.0,
            matrix_form: RidgeMatrixForm::ScaledIdentity,
            chosen_by: StabilizationRule::FixedConstant,
            objective_policy: None,
            backward_error_bound: None,
            inertia_before: None,
            inertia_after: None,
        }
    }

    fn try_new(
        kind: StabilizationKind,
        delta: f64,
        chosen_by: StabilizationRule,
        backward_error_bound: Option<f64>,
    ) -> Result<Self, InvalidStabilization> {
        if matches!(kind, StabilizationKind::None) {
            return Err(InvalidStabilization::new(
                "None stabilization must be constructed with StabilizationLedger::none",
            ));
        }
        if !(delta.is_finite() && delta >= 0.0) {
            return Err(InvalidStabilization::new(format!(
                "stabilization delta must be finite and non-negative, got {delta:?}"
            )));
        }
        Self::validate_rule(chosen_by)?;
        if let Some(bound) = backward_error_bound
            && !(bound.is_finite() && bound >= 0.0)
        {
            return Err(InvalidStabilization::new(format!(
                "backward-error bound must be finite and non-negative, got {bound:?}"
            )));
        }
        if !matches!(kind, StabilizationKind::NumericalPerturbation)
            && backward_error_bound.is_some()
        {
            return Err(InvalidStabilization::new(
                "only a numerical perturbation may carry a backward-error bound",
            ));
        }
        Ok(Self {
            kind,
            delta: if delta == 0.0 { 0.0 } else { delta },
            matrix_form: RidgeMatrixForm::ScaledIdentity,
            chosen_by,
            objective_policy: None,
            backward_error_bound,
            inertia_before: None,
            inertia_after: None,
        })
    }

    fn validate_rule(rule: StabilizationRule) -> Result<(), InvalidStabilization> {
        match rule {
            StabilizationRule::InertiaTarget { spd_floor }
                if !(spd_floor.is_finite() && spd_floor > 0.0) =>
            {
                Err(InvalidStabilization::new(format!(
                    "inertia-target SPD floor must be finite and strictly positive, got {spd_floor:?}"
                )))
            }
            StabilizationRule::BackoffEscalation { attempts } if attempts == 0 => Err(
                InvalidStabilization::new("backoff escalation must record at least one attempt"),
            ),
            _ => Ok(()),
        }
    }

    pub fn with_inertia(
        mut self,
        before: Option<Inertia>,
        after: Option<Inertia>,
    ) -> Result<Self, InvalidStabilization> {
        if before.is_some() != after.is_some() {
            return Err(InvalidStabilization::new(
                "inertia diagnostics must record both the pre- and post-stabilization matrix",
            ));
        }
        if let (Some(before), Some(after)) = (before, after)
            && before.total() != after.total()
        {
            return Err(InvalidStabilization::new(format!(
                "inertia dimensions disagree: before={}, after={}",
                before.total(),
                after.total()
            )));
        }
        if matches!(self.chosen_by, StabilizationRule::InertiaTarget { .. }) {
            let Some(after) = after else {
                return Err(InvalidStabilization::new(
                    "inertia-target stabilization must record post-stabilization inertia",
                ));
            };
            if after.zero() != 0 || after.negative() != 0 {
                return Err(InvalidStabilization::new(format!(
                    "inertia-target stabilization did not certify SPD curvature: zero={}, negative={}",
                    after.zero(),
                    after.negative()
                )));
            }
        }
        self.inertia_before = before;
        self.inertia_after = after;
        Ok(self)
    }

    pub const fn kind(self) -> StabilizationKind {
        self.kind
    }

    pub const fn delta(self) -> f64 {
        self.delta
    }

    pub const fn matrix_form(self) -> RidgeMatrixForm {
        self.matrix_form
    }

    pub const fn chosen_by(self) -> StabilizationRule {
        self.chosen_by
    }

    /// Exact determinant/objective provenance for an explicit prior or
    /// objective-accounted algorithmic stabilization. `None` for every
    /// solver-only, numerical, and approximation-only perturbation.
    pub const fn objective_policy(self) -> Option<RidgePolicy> {
        self.objective_policy
    }

    pub const fn backward_error_bound(self) -> Option<f64> {
        self.backward_error_bound
    }

    pub const fn inertia_before(self) -> Option<Inertia> {
        self.inertia_before
    }

    pub const fn inertia_after(self) -> Option<Inertia> {
        self.inertia_after
    }

}

impl TryFrom<StabilizationLedgerWire> for StabilizationLedger {
    type Error = InvalidStabilization;

    fn try_from(wire: StabilizationLedgerWire) -> Result<Self, Self::Error> {
        if matches!(wire.kind, StabilizationKind::None) {
            if wire.delta != 0.0
                || wire.chosen_by != StabilizationRule::FixedConstant
                || wire.objective_policy.is_some()
                || wire.backward_error_bound.is_some()
                || wire.inertia_before.is_some()
                || wire.inertia_after.is_some()
            {
                return Err(InvalidStabilization::new(
                    "None stabilization must have zero delta and no diagnostic payload",
                ));
            }
            return Ok(Self::none());
        }
        let mut ledger = Self::try_new(
            wire.kind,
            wire.delta,
            wire.chosen_by,
            wire.backward_error_bound,
        )?;
        if matches!(wire.kind, StabilizationKind::ExplicitPrior)
            && wire.chosen_by != StabilizationRule::UserSpecified
        {
            return Err(InvalidStabilization::new(
                "an explicit prior must be recorded as user specified",
            ));
        }
        match (wire.kind, wire.objective_policy) {
            (
                StabilizationKind::ExplicitPrior | StabilizationKind::ObjectiveStabilization,
                Some(policy),
            ) if policy.accounts_for_objective() => {
                ledger.objective_policy = Some(policy);
            }
            (StabilizationKind::ExplicitPrior | StabilizationKind::ObjectiveStabilization, _) => {
                return Err(InvalidStabilization::new(
                    "objective-accounted stabilization must preserve its ridge policy",
                ));
            }
            (_, Some(_)) => {
                return Err(InvalidStabilization::new(
                    "only objective-accounted stabilization may carry objective ridge provenance",
                ));
            }
            (_, None) => {}
        }
        ledger.matrix_form = wire.matrix_form;
        ledger.with_inertia(wire.inertia_before, wire.inertia_after)
    }
}

impl From<StabilizationLedger> for StabilizationLedgerWire {
    fn from(ledger: StabilizationLedger) -> Self {
        Self {
            kind: ledger.kind,
            delta: ledger.delta,
            matrix_form: ledger.matrix_form,
            chosen_by: ledger.chosen_by,
            objective_policy: ledger.objective_policy,
            backward_error_bound: ledger.backward_error_bound,
            inertia_before: ledger.inertia_before,
            inertia_after: ledger.inertia_after,
        }
    }
}
/// Generate a `#[repr(transparent)]` `Array1<f64>` newtype with the
/// `new`/`Deref`/`DerefMut`/`AsRef`/`From` boilerplate used by unconstrained
/// numeric vectors in this module.
macro_rules! array1_f64_newtype {
    ($name:ident) => {
        #[repr(transparent)]
        #[derive(Clone, Debug, PartialEq)]
        pub struct $name(pub Array1<f64>);

        impl $name {
            #[inline]
            pub fn new(values: Array1<f64>) -> Self {
                Self(values)
            }

            #[inline]
            pub fn zeros(len: usize) -> Self {
                Self(Array1::zeros(len))
            }
        }

        impl Deref for $name {
            type Target = Array1<f64>;
            #[inline]
            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl DerefMut for $name {
            #[inline]
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.0
            }
        }

        impl AsRef<Array1<f64>> for $name {
            #[inline]
            fn as_ref(&self) -> &Array1<f64> {
                &self.0
            }
        }

        impl From<Array1<f64>> for $name {
            #[inline]
            fn from(values: Array1<f64>) -> Self {
                Self(values)
            }
        }

        impl From<$name> for Array1<f64> {
            #[inline]
            fn from(values: $name) -> Self {
                values.0
            }
        }
    };
}

array1_f64_newtype!(Coefficients);
array1_f64_newtype!(LinearPredictor);

/// Index into `TermCollectionSpec::smooth_terms` (and the parallel
/// `TermCollectionDesign::smooth.terms` slice produced from it).
///
/// This is **not** a penalty/ρ index, **not** a column index, and **not** a
/// coefficient-offset index. Keeping it behind a `#[repr(transparent)]`
/// newtype makes those confusables a compile error: a `SmoothTermIdx` cannot
/// be silently used to index `rho`, `beta`, or a design column.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SmoothTermIdx(usize);

impl SmoothTermIdx {
    #[inline]
    pub const fn new(idx: usize) -> Self {
        Self(idx)
    }

    /// Sentinel used by transient builders that must allocate a coord config
    /// before the smooth term it references has been positioned in the spec.
    /// Every code path that constructs a sentinel must overwrite it before
    /// the value escapes the builder.
    #[inline]
    pub const fn placeholder() -> Self {
        Self(usize::MAX)
    }

    #[inline]
    pub const fn get(self) -> usize {
        self.0
    }

}

impl std::fmt::Display for SmoothTermIdx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Index into the canonical penalty list `&[CanonicalPenalty]` — equivalently,
/// the position of a smoothing parameter in the ρ / λ vector.
///
/// Penalty/ρ indices are not interchangeable with `SmoothTermIdx` (a smooth
/// term can carry multiple canonical penalties — e.g. tensor-product double
/// penalties — and structural penalties don't correspond to any smooth term).
/// Keeping them as separate newtypes makes the historical bug pattern
/// "indexed `rho` with a smooth-term ordinal" impossible to express.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PenaltyIdx(usize);

impl PenaltyIdx {
    #[inline]
    pub const fn new(idx: usize) -> Self {
        Self(idx)
    }

    #[inline]
    pub const fn get(self) -> usize {
        self.0
    }
}

impl std::fmt::Display for PenaltyIdx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Index into a single smooth term's set of basis functions — i.e. the `k`
/// in "the k-th basis function `B_k(x)` of this term".
///
/// Distinct from:
///   * [`SmoothTermIdx`] — selects *which* smooth term in the spec.
///   * [`PenaltyIdx`]    — selects *which* ρ/λ entry / canonical penalty.
///   * A design-matrix column index — which lives in the *combined* layout
///     after intercept/parametric blocks and per-term offsets are applied;
///     a `BasisIdx` is term-local, a column index is model-global.
///
/// Keeping this as its own `#[repr(transparent)]` newtype makes the
/// historically-easy confusion "indexed a global column slice with a
/// term-local basis ordinal" (or vice versa) a compile error.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct BasisIdx(usize);

impl BasisIdx {
    #[inline]
    pub const fn new(idx: usize) -> Self {
        Self(idx)
    }

    #[inline]
    pub const fn get(self) -> usize {
        self.0
    }
}

impl std::fmt::Display for BasisIdx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Index into the user-facing design matrix `data: Array2<f64>` — i.e. the
/// position of a covariate column in the raw input frame, *before* any
/// per-family basis expansion or intercept/parametric layout is applied.
///
/// Distinct from:
///   * [`BasisIdx`] — term-local basis-function ordinal `k` of `B_k(x)`.
///   * [`SmoothTermIdx`] — position in `TermCollectionSpec::smooth_terms`.
///   * A coefficient-vector offset `β[i]` — spans the combined design after
///     expansion, which is much wider than the user-facing data matrix.
///
/// Keeping this as its own `#[repr(transparent)]` newtype rules out the easy
/// confusion of indexing the raw data frame with an expanded-column offset.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ColIdx(usize);

impl ColIdx {
    #[inline]
    pub const fn new(idx: usize) -> Self {
        Self(idx)
    }

    #[inline]
    pub const fn get(self) -> usize {
        self.0
    }
}

impl std::fmt::Display for ColIdx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Index of an observation (row) in the user-facing data frame / design
/// matrix — i.e. the `i` in "the i-th observation".
///
/// Distinct from every column-type index in this module ([`ColIdx`],
/// [`BasisIdx`], [`SmoothTermIdx`], [`PenaltyIdx`]) and from coefficient
/// offsets. Keeping rows behind their own `#[repr(transparent)]` newtype
/// makes the classic `data[[col, row]]` transposition a compile error.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct RowIdx(usize);

impl RowIdx {
    #[inline]
    pub const fn new(idx: usize) -> Self {
        Self(idx)
    }

    #[inline]
    pub const fn get(self) -> usize {
        self.0
    }
}

impl std::fmt::Display for RowIdx {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[repr(transparent)]
#[derive(Clone, Copy, Debug)]
pub struct LogSmoothingParamsView<'a>(ArrayView1<'a, f64>);

impl<'a> LogSmoothingParamsView<'a> {
    /// Borrow a smoothing vector only after every coordinate satisfies the
    /// exact shared logarithmic-strength contract.
    pub fn new(values: ArrayView1<'a, f64>) -> Result<Self, crate::IndexedLogStrengthDomainError> {
        crate::validate_log_strengths(values.iter().copied())?;
        Ok(Self(values))
    }

    /// Exact physical strengths for this already-validated vector.
    pub fn exact_exp(&self) -> Array1<f64> {
        // `new` established the private invariant; the borrow prevents the
        // source array from being mutated for this view's lifetime.
        self.0.mapv(f64::exp)
    }
}

impl<'a> Deref for LogSmoothingParamsView<'a> {
    type Target = ArrayView1<'a, f64>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(test)]
mod newtype_tests {
    use super::*;
    use ndarray::array;

    #[test]
    fn smooth_term_idx_ordering() {
        let a = SmoothTermIdx::new(1);
        let b = SmoothTermIdx::new(2);
        assert!(a < b);
        assert_eq!(a, SmoothTermIdx::new(1));
    }

    #[test]
    fn coefficients_zeros_and_deref() {
        let c = Coefficients::zeros(3);
        assert_eq!(c.len(), 3);
        assert!(c.iter().all(|&v| v == 0.0));
    }

    #[test]
    fn coefficients_from_array1() {
        let arr = array![1.0, 2.0, 3.0];
        let c = Coefficients::from(arr.clone());
        assert_eq!(*c, arr);
    }

    #[test]
    fn log_smoothing_params_view_is_validated_and_exponentiates_exactly() {
        let arr = array![crate::LOG_STRENGTH_MIN, 0.0, crate::LOG_STRENGTH_MAX];
        let rho = LogSmoothingParamsView::new(arr.view()).expect("closed domain");
        for (actual, expected) in rho.exact_exp().iter().zip(arr.iter()) {
            assert_eq!(actual.to_bits(), expected.exp().to_bits());
        }

        let invalid = array![0.0, crate::LOG_STRENGTH_MAX + 1.0];
        let error = LogSmoothingParamsView::new(invalid.view()).unwrap_err();
        assert_eq!(error.coordinate, 1);
        assert_eq!(error.value, crate::LOG_STRENGTH_MAX + 1.0);
    }

    #[test]
    fn linear_predictor_zeros_and_deref() {
        let lp = LinearPredictor::zeros(4);
        assert_eq!(lp.len(), 4);
        assert!(lp.iter().all(|&v| v == 0.0));
    }
}

#[cfg(test)]
mod ridge_policy_tests {
    use super::{RidgePassport, RidgePolicy, StabilizationLedger};
    use serde_json::json;

    #[test]
    fn serde_cannot_bypass_passport_validation() {
        let negative = json!({
            "delta": -1.0,
            "matrix_form": "ScaledIdentity",
            "policy": "SolverOnly"
        });
        assert!(serde_json::from_value::<RidgePassport>(negative).is_err());

        let passport = RidgePassport::scaled_identity(
            2.5e-7,
            RidgePolicy::exact_full_objective(),
        )
        .expect("valid ridge");
        let roundtrip: RidgePassport =
            serde_json::from_value(serde_json::to_value(passport).expect("serialize passport"))
                .expect("deserialize validated passport");
        assert_eq!(roundtrip, passport);
    }

    #[test]
    fn serde_cannot_bypass_ledger_semantics() {
        let invalid_none = json!({
            "kind": "None",
            "delta": 1.0,
            "matrix_form": "ScaledIdentity",
            "chosen_by": "FixedConstant",
            "objective_policy": null,
            "backward_error_bound": null,
            "inertia_before": null,
            "inertia_after": null
        });
        assert!(serde_json::from_value::<StabilizationLedger>(invalid_none).is_err());

        let invalid_prior_rule = json!({
            "kind": "ExplicitPrior",
            "delta": 1.0,
            "matrix_form": "ScaledIdentity",
            "chosen_by": "Heuristic",
            "objective_policy": "ExactFullObjective",
            "backward_error_bound": null,
            "inertia_before": null,
            "inertia_after": null
        });
        assert!(serde_json::from_value::<StabilizationLedger>(invalid_prior_rule).is_err());

        let bound_on_wrong_kind = json!({
            "kind": "ApproximationOnly",
            "delta": 1.0,
            "matrix_form": "ScaledIdentity",
            "chosen_by": "FixedConstant",
            "objective_policy": null,
            "backward_error_bound": 1.0e-10,
            "inertia_before": null,
            "inertia_after": null
        });
        assert!(serde_json::from_value::<StabilizationLedger>(bound_on_wrong_kind).is_err());
    }

}