Skip to main content

gam_terms/basis/
types.rs

1use super::*;
2
3/// Wrapper to send a raw pointer across thread boundaries for parallel buffer fills.
4/// SAFETY: every `SendPtr` value must be built from live, properly aligned `f64`
5/// storage whose mutable borrow is held until all worker threads finish; callers
6/// may only dereference offsets that are in-bounds and disjoint across workers.
7#[derive(Clone, Copy)]
8pub(crate) struct SendPtr(pub(crate) *mut f64);
9
10// SAFETY: SendPtr only grants raw-pointer transport. Actual dereferences occur
11// at call sites after row-chunk partitioning proves each thread writes a
12// distinct in-bounds element of the backing Array/Vec allocation.
13unsafe impl Send for SendPtr {}
14
15// SAFETY: shared references to SendPtr are sound because the pointee is never
16// accessed through the wrapper without the call-site disjoint-offset proof.
17unsafe impl Sync for SendPtr {}
18
19impl SendPtr {
20    #[inline(always)]
21    pub(crate) fn add(self, offset: usize) -> *mut f64 {
22        // SAFETY: callers pass offsets within the backing allocation and only
23        // dereference the returned pointer after proving the target element is
24        // uniquely owned by that worker's chunk for the whole parallel region.
25        unsafe { self.0.add(offset) }
26    }
27}
28
29/// Re-export of the neutral basis-error contract. #1521: `BasisError` lives
30/// in `gam-problem` so `EstimationError` can wrap it (`#[from]`) without a
31/// back-edge; gam-terms re-exports it to preserve `gam_terms::basis::BasisError`.
32pub use gam_problem::BasisError;
33
34// ============================================================================
35// Unified Basis Generation API
36// ============================================================================
37
38/// Options for basis generation, controlling derivative order.
39#[derive(Clone, Copy, Debug, Default)]
40pub struct BasisOptions {
41    /// Derivative order: 0 = value (default), 1 = first derivative, 2 = second derivative
42    pub derivative_order: usize,
43    /// Basis family to evaluate.
44    pub basis_family: BasisFamily,
45}
46
47impl BasisOptions {
48    /// Create options for evaluating basis functions (no derivative).
49    pub const fn value() -> Self {
50        Self {
51            derivative_order: 0,
52            basis_family: BasisFamily::BSpline,
53        }
54    }
55
56    /// Create options for evaluating first derivatives of basis functions.
57    pub const fn first_derivative() -> Self {
58        Self {
59            derivative_order: 1,
60            basis_family: BasisFamily::BSpline,
61        }
62    }
63
64    /// Create options for evaluating second derivatives of basis functions.
65    pub const fn second_derivative() -> Self {
66        Self {
67            derivative_order: 2,
68            basis_family: BasisFamily::BSpline,
69        }
70    }
71
72    /// Create options for evaluating M-spline basis values.
73    pub const fn m_spline() -> Self {
74        Self {
75            derivative_order: 0,
76            basis_family: BasisFamily::MSpline,
77        }
78    }
79
80    /// Create options for evaluating I-spline basis values.
81    pub const fn i_spline() -> Self {
82        Self {
83            derivative_order: 0,
84            basis_family: BasisFamily::ISpline,
85        }
86    }
87}
88
89/// Basis-family selector for 1D spline evaluation.
90#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
91pub enum BasisFamily {
92    /// Standard B-splines.
93    #[default]
94    BSpline,
95    /// M-splines: normalized B-splines, M_i = ((k+1)/(t_{i+k+1}-t_i)) B_i.
96    MSpline,
97    /// I-splines: integrated M-splines, implemented by right-cumulative
98    /// sums of B-splines at degree k+1.
99    ISpline,
100}
101
102/// Specifies the source of knots for basis generation.
103#[derive(Clone, Debug)]
104pub enum KnotSource<'a> {
105    /// Use a pre-computed knot vector.
106    Provided(ArrayView1<'a, f64>),
107    /// Generate uniformly spaced knots based on data range.
108    Generate {
109        /// Data range (min, max) for knot placement.
110        data_range: (f64, f64),
111        /// Number of internal knots to place between boundaries.
112        num_internal_knots: usize,
113    },
114}
115/// Thin-plate regression spline basis and penalty (order m=2).
116///
117/// The returned basis has columns `[K_c | P]` where:
118/// - `K_c` is the constrained radial basis block (`K * Z`) with
119///   `P(knots)^T * α = 0` enforced via nullspace projection
120/// - `P` is the TPS polynomial null-space block containing all monomials of
121///   total degree `< m`, where `m = thin_plate_penalty_order(d)` (so `P` is
122///   just `[1, x_1, ..., x_d]` for `d <= 3`)
123///
124/// The returned penalty matrix is block-diagonal with:
125/// - upper-left `Omega_c = Z^T Omega Z` for the constrained radial block
126/// - zero lower-right block for unpenalized polynomial terms.
127///
128/// For double-penalty GAMs, a second ridge penalty `I` is also returned so the
129/// caller can optimize `(lambda_bending, lambdaridge)` jointly.
130#[derive(Debug, Clone)]
131pub struct ThinPlateSplineBasis {
132    pub basis: Array2<f64>,
133    pub penalty_bending: Array2<f64>,
134    pub penalty_ridge: Array2<f64>,
135    pub num_kernel_basis: usize,
136    pub num_polynomial_basis: usize,
137    pub dimension: usize,
138    /// Wood-TPRS radial reparameterization matrix `V`.
139    ///
140    /// Rows live in the side-constrained radial coefficient space. Columns are
141    /// the retained positive bending eigendirections of `Z' Ω Z`; numerically
142    /// near-null radial directions are dropped before the basis is exposed.
143    /// Therefore `V` can be rectangular: design columns are `Φ Z V`, and the
144    /// radial penalty is `diag(Λ_retained)`.
145    pub radial_reparam: Array2<f64>,
146}
147
148/// Matérn smoothness parameter `nu` (half-integer variants with closed forms).
149#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
150pub enum MaternNu {
151    Half,
152    ThreeHalves,
153    FiveHalves,
154    SevenHalves,
155    NineHalves,
156}
157
158impl MaternNu {
159    /// The half-integer smoothness value ν as an `f64` (0.5, 1.5, …).
160    pub const fn half_integer_value(self) -> f64 {
161        match self {
162            MaternNu::Half => 0.5,
163            MaternNu::ThreeHalves => 1.5,
164            MaternNu::FiveHalves => 2.5,
165            MaternNu::SevenHalves => 3.5,
166            MaternNu::NineHalves => 4.5,
167        }
168    }
169}
170
171/// Matérn radial basis and penalties.
172#[derive(Debug, Clone)]
173pub struct MaternSplineBasis {
174    pub basis: Array2<f64>,
175    pub penalty_kernel: Array2<f64>,
176    pub penalty_ridge: Array2<f64>,
177    pub num_kernel_basis: usize,
178    pub num_polynomial_basis: usize,
179    pub dimension: usize,
180}
181
182#[derive(Debug, Clone)]
183pub(crate) struct DuchonBasisDesign {
184    pub(crate) basis: Array2<f64>,
185}
186
187/// Boundary-condition policy for one-dimensional smooth bases.
188#[derive(Debug, Clone, Serialize, Deserialize, Default)]
189pub enum OneDimensionalBoundary {
190    /// Ordinary open interval basis with clamped endpoint behavior.
191    #[default]
192    Open,
193    /// Periodic/cyclic basis over the half-open interval `[start, end)`.
194    ///
195    /// Values are evaluated modulo `period = end - start`; the basis and its
196    /// first `degree - 1` derivatives agree at the two endpoints for B-splines.
197    Cyclic { start: f64, end: f64 },
198}
199
200impl OneDimensionalBoundary {
201    pub(crate) fn period(&self) -> Option<(f64, f64, f64)> {
202        match *self {
203            OneDimensionalBoundary::Open => None,
204            OneDimensionalBoundary::Cyclic { start, end } if end > start => {
205                Some((start, end, end - start))
206            }
207            OneDimensionalBoundary::Cyclic { .. } => None,
208        }
209    }
210}
211
212/// Which knot strategy to use for 1D B-spline bases.
213#[derive(Debug, Clone, Serialize, Deserialize)]
214pub enum BSplineKnotSpec {
215    Generate {
216        data_range: (f64, f64),
217        num_internal_knots: usize,
218    },
219    /// Uniform cyclic B-spline basis on `[data_range.0, data_range.1)`.
220    ///
221    /// The first and last endpoints are identified, so evaluating at `x` and
222    /// `x + m * period` gives identical rows. `num_basis` is the number of
223    /// periodic control sites around the loop and must be at least
224    /// `degree + 1` for an unaliased local support stencil.
225    PeriodicUniform {
226        data_range: (f64, f64),
227        num_basis: usize,
228    },
229    Automatic {
230        num_internal_knots: Option<usize>,
231        placement: BSplineKnotPlacement,
232    },
233    Provided(Array1<f64>),
234    /// Natural cubic regression spline (`bs="cr"`/`"cs"`) knot set (#1074).
235    ///
236    /// Unlike the open-spline variants above, these `knots` are the `k`
237    /// Lancaster–Salkauskas knots `x*_1 < … < x*_k` that *directly* index the
238    /// basis values `β_i = f(x*_i)` — the basis dimension equals `knots.len()`
239    /// (not `knots.len() - degree - 1`). The 1-D builder routes this variant to
240    /// the cubic-regression builder; the cr identity therefore round-trips
241    /// through freeze/reload by virtue of the variant itself (no separate
242    /// metadata marker is required), and tensor margins inherit cr by carrying
243    /// this knotspec into `build_bspline_basis_1d`.
244    NaturalCubicRegression {
245        knots: Array1<f64>,
246    },
247}
248
249/// Internal-knot placement strategy when knots are automatically inferred.
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
251pub enum BSplineKnotPlacement {
252    Uniform,
253    Quantile,
254}
255
256/// 1D B-spline basis configuration.
257#[derive(Debug, Clone, Serialize, Deserialize)]
258pub struct BSplineBasisSpec {
259    pub degree: usize,
260    pub penalty_order: usize,
261    pub knotspec: BSplineKnotSpec,
262    pub double_penalty: bool,
263    pub identifiability: BSplineIdentifiability,
264    #[serde(default)]
265    pub boundary: OneDimensionalBoundary,
266    /// Optional endpoint boundary constraints (Hermite-style pin of value and/or
267    /// derivative at the left/right knot extents). Default = `Free` on both
268    /// sides which is a no-op.
269    #[serde(default)]
270    pub boundary_conditions: BSplineBoundaryConditions,
271}
272
273/// Per-endpoint boundary constraint policy for B-spline 1D bases.
274#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
275pub enum BSplineEndpointBoundaryCondition {
276    /// No endpoint constraint.
277    #[default]
278    Free,
279    /// Pin the first derivative to zero at this endpoint.
280    Clamped,
281    /// Hermite pin: fix the endpoint value to `value` and its first derivative
282    /// to zero.
283    Anchored { value: f64 },
284}
285
286/// Left/right pair of B-spline endpoint constraints.
287#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
288pub struct BSplineBoundaryConditions {
289    #[serde(default)]
290    pub left: BSplineEndpointBoundaryCondition,
291    #[serde(default)]
292    pub right: BSplineEndpointBoundaryCondition,
293}
294
295impl BSplineBoundaryConditions {
296    pub const fn is_free(&self) -> bool {
297        matches!(self.left, BSplineEndpointBoundaryCondition::Free)
298            && matches!(self.right, BSplineEndpointBoundaryCondition::Free)
299    }
300
301    /// Whether either endpoint fixes the function's absolute level.
302    ///
303    /// An anchored endpoint (one *or* both sides) replaces the global intercept
304    /// as the level-setting constraint: the fitted function itself, not only a
305    /// centered deviation, must obey the endpoint pin. Centering that same
306    /// smooth to zero would impose a second, incompatible level constraint and
307    /// exclude every non-zero-mean anchored function from the model space, and a
308    /// free global intercept would float the whole curve off its pin. A
309    /// *two*-sided anchor fixes the level even more strongly than a one-sided
310    /// one, so it must be treated identically here — the earlier XOR (exactly
311    /// one endpoint) silently dropped both pins for the two-sided case (#2297).
312    pub const fn has_anchor(&self) -> bool {
313        matches!(self.left, BSplineEndpointBoundaryCondition::Anchored { .. })
314            || matches!(self.right, BSplineEndpointBoundaryCondition::Anchored { .. })
315    }
316
317    /// Whether either endpoint carries an inhomogeneous value constraint.
318    pub fn has_nonzero_anchor(&self) -> bool {
319        let nonzero = |condition: BSplineEndpointBoundaryCondition| {
320            matches!(
321                condition,
322                BSplineEndpointBoundaryCondition::Anchored { value } if value != 0.0
323            )
324        };
325        nonzero(self.left) || nonzero(self.right)
326    }
327}
328
329/// Per-smooth identifiability policy for 1D B-spline bases.
330///
331/// These constraints are applied directly in the builder via a reparameterization
332/// `B_constrained = B * Z`, and every penalty matrix is projected as
333/// `S_constrained = Z' S Z`, so solver geometry stays consistent.
334#[derive(Debug, Clone, Serialize, Deserialize)]
335pub enum BSplineIdentifiability {
336    /// Keep unconstrained basis columns.
337    None,
338    /// Enforce weighted sum-to-zero: `B' w = 0` (or unweighted when `weights=None`).
339    // Smooth terms are centered by default to avoid intercept confounding.
340    WeightedSumToZero { weights: Option<Array1<f64>> },
341    /// Remove intercept + linear trend in coefficient space using Greville geometry.
342    RemoveLinearTrend,
343    /// Enforce orthogonality to supplied design columns `C` (n x q):
344    /// `B_c' W C = 0` (or unweighted when `weights=None`).
345    ///
346    /// To enforce `[intercept, x, ...]`, provide `columns` with those columns.
347    OrthogonalToDesignColumns {
348        columns: Array2<f64>,
349        weights: Option<Array1<f64>>,
350    },
351    /// Apply an explicit coefficient-space transform `Z` learned at fit time.
352    ///
353    /// This freezes identifiability behavior so prediction cannot drift based on
354    /// new-data distribution. The constrained basis is `B * Z`.
355    FrozenTransform { transform: Array2<f64> },
356}
357
358impl Default for BSplineIdentifiability {
359    fn default() -> Self {
360        BSplineIdentifiability::WeightedSumToZero { weights: None }
361    }
362}
363
364/// Spatial center selection strategy.
365///
366/// `num_centers` is the exact number of knot/center rows selected by the
367/// strategy. Polynomial nullspace columns are added separately by each basis
368/// builder and must never be folded into this count.
369#[derive(Debug, Clone, Serialize, Deserialize)]
370pub enum CenterStrategy {
371    Auto(Box<CenterStrategy>),
372    UserProvided(Array2<f64>),
373    /// Joint multidimensional equal-mass partitioning in the full smooth space.
374    EqualMass {
375        num_centers: usize,
376    },
377    /// Covariate-representative equal-mass partitioning along one selected axis.
378    EqualMassCovarRepresentative {
379        num_centers: usize,
380    },
381    FarthestPoint {
382        num_centers: usize,
383    },
384    KMeans {
385        num_centers: usize,
386        max_iter: usize,
387    },
388    UniformGrid {
389        points_per_dim: usize,
390    },
391}
392
393impl CenterStrategy {
394    /// The number of centers this strategy will select, computed from the
395    /// strategy alone (no data pass). `d` is the smooth's covariate
396    /// dimensionality, needed only by `UniformGrid` whose count is
397    /// `points_per_dim^d`. Adaptive-fit provenance consults this before freeze,
398    /// because the frozen center matrix can contain periodic image expansion
399    /// and therefore is not the requested resolution for the next refit.
400    pub fn planned_num_centers(&self, d: usize) -> usize {
401        match self {
402            Self::Auto(inner) => inner.planned_num_centers(d),
403            Self::UserProvided(centers) => centers.nrows(),
404            Self::EqualMass { num_centers }
405            | Self::EqualMassCovarRepresentative { num_centers }
406            | Self::FarthestPoint { num_centers }
407            | Self::KMeans { num_centers, .. } => *num_centers,
408            Self::UniformGrid { points_per_dim } => {
409                points_per_dim.saturating_pow(d.clamp(1, u32::MAX as usize) as u32)
410            }
411        }
412    }
413}
414
415#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
416pub enum CenterStrategyKind {
417    UserProvided,
418    EqualMass,
419    EqualMassCovarRepresentative,
420    FarthestPoint,
421    KMeans,
422    UniformGrid,
423}
424
425/// Adaptive default center count for spatial smooths (TPS, Duchon, Matérn).
426///
427/// Use this when the user has not explicitly specified a knot/center count.
428/// The basis size is the sub-linear `ceil(8 * d_factor * n^0.4)`, clamped above
429/// at `K_MAX = 2000` and below at a *data-proportional* floor `min(200, n/8)` so
430/// the floor only engages once there are enough observations to support a rich
431/// basis. The result is additionally capped at `n/4` so the penalty matrices
432/// stay well-conditioned relative to the data:
433///
434/// | n      | d=1  | d=2  | d=5  |
435/// |--------|------|------|------|
436/// | 800    | 116  | 134  | 186  |
437/// | 1 000  | 127  | 146  | 200  |
438/// | 2 000  | 200  | 200  | 268  |
439/// | 10 000 | 319  | 367  | 510  |
440/// | 100 000| 801  | 921  | 1281 |
441/// | 400 000| 1393 | 1602 | 2000 |
442/// | 1 000 000| 2000 | 2000 | 2000 |
443///
444/// The flat `200` floor used to inflate moderate-`n` spatial smooths (a few
445/// hundred to ~2000 rows) up to a dense 200-column design even though the raw
446/// sub-linear count — and the mesh/knot density that mgcv and R-INLA use on the
447/// same data — is far smaller. On ~800 rows that turned a single 2-D thin-plate
448/// REML fit into an `O(n·p² + p³)` grind at `p ≈ 200` (#718). Smoothness is
449/// already controlled by REML's penalty weight λ, not by the center count, so a
450/// data-proportional floor recovers the same surface at a fraction of the cost.
451///
452/// # Arguments
453/// * `n` - sample size (number of observations)
454/// * `d` - covariate dimensionality (number of input variables in the smooth)
455pub fn default_num_centers(n: usize, d: usize) -> usize {
456    const K_MIN: usize = 200;
457    const K_MAX: usize = 2000;
458    const ALPHA: f64 = 0.4;
459    const C: f64 = 8.0;
460    /// Per-extra-dimension growth in the center count: each covariate axis
461    /// beyond the first widens the basis by 15% to keep the per-axis mesh
462    /// density roughly constant as the smooth's domain dimensionality grows.
463    const PER_DIM_GROWTH: f64 = 0.15;
464    /// Divisor for the data-proportional floor: the `K_MIN` floor only engages
465    /// once `n` exceeds `K_MIN * FLOOR_N_DIVISOR`, so small samples are not
466    /// forced up to a dense `K_MIN`-column design.
467    const FLOOR_N_DIVISOR: usize = 8;
468    /// Divisor for the conditioning cap: the center count never exceeds `n /
469    /// COND_N_DIVISOR`, keeping the penalty matrices well-conditioned relative
470    /// to the data.
471    const COND_N_DIVISOR: usize = 4;
472
473    let d_factor = 1.0 + PER_DIM_GROWTH * (d.max(1) - 1) as f64;
474    let raw = (C * d_factor * (n as f64).powf(ALPHA)).ceil() as usize;
475
476    // Data-proportional floor: never inflate beyond n/FLOOR_N_DIVISOR, so the
477    // K_MIN-center floor only takes effect once n is large enough (~1600) to
478    // genuinely support that many basis columns.
479    let floor = K_MIN.min(n / FLOOR_N_DIVISOR);
480    let k = raw.clamp(floor, K_MAX);
481
482    // Never exceed n itself; cap at n/COND_N_DIVISOR to keep the penalty
483    // matrices well-conditioned relative to the data.
484    k.min(n).min(n / COND_N_DIVISOR)
485}
486
487/// Conservative center count for a *secondary* (distributional) predictor's
488/// spatial smooth — e.g. the log-σ scale model in a Gaussian location-scale
489/// fit.
490///
491/// The mean is identified directly by the response, so it warrants the
492/// generous [`default_num_centers`] basis. A scale/shape predictor is
493/// identified only through (noisy) squared residuals: handing it a basis sized
494/// for the mean lets REML/LAML smoothing selection over-fit it, because where
495/// the fitted scale is driven small the *observed* information collapses and
496/// the determinant penalty stops holding the wiggle down (#501). This mirrors
497/// standard GAMLSS/mgcv practice of giving distribution parameters a modest
498/// default (mgcv's modest default basis for a 1-D `s()`), grown gently with
499/// dimensionality and never exceeding the generous primary-predictor default.
500pub fn conservative_secondary_centers(n: usize, d: usize) -> usize {
501    const BASE_1D_CENTERS: usize = 15;
502    let modest = BASE_1D_CENTERS.saturating_mul(d.max(1));
503    default_num_centers(n, d).min(modest).max(1)
504}
505
506/// Low-rank starting center count for saturation-driven spatial fitting.
507///
508/// The structural minimum (`d + 1` polynomial directions plus one radial
509/// direction) is only enough to make the algebra identifiable. It is not an
510/// adequate pilot function space: structure orthogonal to that single radial
511/// direction is absorbed into the residual, so REML can legitimately shrink
512/// the direction and report EDF below its ceiling even when the surface is
513/// badly under-resolved (#1689). Start from the project's established
514/// thin-plate-style low-rank resolution `10 * 3^(d - 1)` instead. This is the
515/// same dimension rule already used by the automatic Duchon builder, capped by
516/// [`default_num_centers`] so the pilot never exceeds the validated production
517/// basis at small sample sizes.
518pub fn starting_num_centers(n: usize, d: usize) -> usize {
519    let low_rank_resolution = 10usize
520        .saturating_mul(3usize.saturating_pow(d.saturating_sub(1).min(u32::MAX as usize) as u32));
521    low_rank_resolution
522        .min(default_num_centers(n, d))
523        .min(n)
524        .max(1)
525}
526
527/// Next evidence-backed center count for a saturated spatial basis, bounded by
528/// the already validated production-default resolution.
529///
530/// Growth is geometric so the number of certified refits is logarithmic. The
531/// ceiling is supplied by the owning workflow because it depends on the
532/// spatial family/dimension and resource plan; the standard formula workflow
533/// uses [`default_num_centers`]. Adaptive resolution may therefore avoid work
534/// below the previous default, but can never turn an ordinary fit into an
535/// unvalidated row-rank dense basis. `None` means the validated function-space
536/// ceiling has been reached.
537pub fn expanded_num_centers(current: usize, ceiling: usize) -> Option<usize> {
538    if current >= ceiling {
539        return None;
540    }
541    let expanded = current.saturating_mul(2).min(ceiling);
542    (expanded > current).then_some(expanded)
543}
544
545/// Is a fitted spatial smooth's basis SATURATED — i.e. does its own evidence say
546/// the data wants more resolution than its realized coefficient span provides (#1689)?
547///
548/// The penalizable capacity is `realized_width − nullspace_dim`: the unpenalized
549/// polynomial null space is always fully used, so it is excluded from the "is the
550/// PENALIZED part maxed out?" test. The supplied `edf` is the total term EDF;
551/// subtracting `nullspace_dim` yields its penalized contribution, which rises
552/// toward that capacity exactly as REML drives the penalty
553/// λ toward its floor to chase structure the basis cannot resolve. Saturated ⟺
554/// `edf ≥ capacity − ε`, with the margin `ε` DERIVED from the outer REML
555/// numerical resolution (`ε = capacity · resolution_tol`, floored at
556/// `resolution_tol` so a tiny-capacity block still has a positive margin) rather
557/// than a tuned knob. The workflow derives `resolution_tol` from the maximum of
558/// its outer convergence tolerance and any rho-independent penalty shrinkage
559/// floor, because that floor bounds how closely EDF can approach the algebraic
560/// ceiling even as lambda tends to zero. Non-positive capacity (a block whose
561/// null space already exhausts its columns) is never saturated. The absolute
562/// scale of `ε` is what the MSI truth-recovery sweep
563/// (sin8/kappa/large_scale + #1074) validates — the criterion SHAPE
564/// (edf-vs-capacity, nullspace excluded, tol-tied margin) is the load-bearing
565/// contract this function pins.
566pub fn basis_is_saturated(
567    edf: f64,
568    realized_width: usize,
569    nullspace_dim: usize,
570    resolution_tol: f64,
571) -> bool {
572    let capacity = realized_width.saturating_sub(nullspace_dim) as f64;
573    if !(capacity > 0.0) || !edf.is_finite() {
574        return false;
575    }
576    let penalized_edf = (edf - nullspace_dim as f64).clamp(0.0, capacity);
577    let margin = (capacity * resolution_tol).max(resolution_tol);
578    penalized_edf >= capacity - margin
579}
580
581/// Resource-aware plan for a spatial smooth (Duchon / Matérn / TPS).
582///
583/// Returned by [`plan_spatial_basis`]. Captures the resolved center count,
584/// final basis dimension `p`, the dense byte cost for the value matrix and
585/// each derivative tier, and a recommended storage mode that is consistent
586/// with the supplied [`gam_runtime::resource::ResourcePolicy`].
587#[derive(Clone, Debug)]
588pub struct SpatialBasisPlan {
589    pub n: usize,
590    pub d: usize,
591    pub centers: usize,
592    pub p_final_estimate: usize,
593    pub dense_design_bytes: usize,
594    pub first_derivative_dense_bytes: usize,
595    pub second_derivative_dense_bytes: usize,
596    pub recommended_storage: SpatialStorageMode,
597}
598
599/// Storage mode recommended by [`plan_spatial_basis`].
600///
601/// * `DenseValueDenseDerivatives` — both the value design and its derivative
602///   matrices fit under the policy's single-materialization budget.
603/// * `LazyValueImplicitDerivatives` — the value design fits dense but the
604///   derivative matrices do not; switch derivatives to the implicit operator.
605/// * `OperatorOnly` — neither the design nor its derivatives fit; everything
606///   must be operator-backed.
607#[derive(Clone, Copy, Debug, PartialEq, Eq)]
608pub enum SpatialStorageMode {
609    DenseValueDenseDerivatives,
610    LazyValueImplicitDerivatives,
611    OperatorOnly,
612}
613
614/// How [`plan_spatial_basis`] should pick the spatial center count.
615#[derive(Clone, Copy, Debug)]
616pub enum CenterCountRequest {
617    /// Use the heuristic [`default_num_centers`].
618    Default,
619    /// Use the caller-supplied count exactly.
620    Explicit(usize),
621    /// Use [`default_num_centers`] but cap at `cap` to bound dense cost.
622    HeuristicCapped { cap: usize },
623}
624
625/// Build a resource-aware plan for a spatial smooth basis.
626///
627/// Computes the resolved center count, final basis dimension, dense byte
628/// estimates for the value design and first/second derivative tiers, and a
629/// recommended [`SpatialStorageMode`] derived from `policy`. This is the
630/// resource-aware replacement for ad-hoc calls to [`default_num_centers`] /
631/// [`heuristic_centers`](crate::term_builder::heuristic_centers).
632pub fn plan_spatial_basis(
633    n: usize,
634    d: usize,
635    requested_centers: CenterCountRequest,
636    nullspace_order: DuchonNullspaceOrder,
637    scale_dims: bool,
638    policy: &gam_runtime::resource::ResourcePolicy,
639) -> Result<SpatialBasisPlan, BasisError> {
640    if n == 0 {
641        crate::bail_invalid_basis!("plan_spatial_basis: n must be >= 1");
642    }
643    if d == 0 {
644        crate::bail_invalid_basis!("plan_spatial_basis: d must be >= 1");
645    }
646
647    // 1. Resolve center count.
648    let centers = match requested_centers {
649        CenterCountRequest::Default => default_num_centers(n, d),
650        CenterCountRequest::Explicit(k) => k,
651        CenterCountRequest::HeuristicCapped { cap } => default_num_centers(n, d).min(cap),
652    };
653
654    // 2. Nullspace dimension (Duchon polynomial null space of degree p-1).
655    //    `duchon_p_from_nullspace_order` returns m such that the null space is
656    //    polynomials of total degree < m, matching `duchon_nullspace_dimension`'s
657    //    `max_total_degree = m - 1` argument.
658    let m = duchon_p_from_nullspace_order(nullspace_order);
659    let nullspace_dim = if m == 0 {
660        0
661    } else {
662        duchon_nullspace_dimension(d, m - 1)
663    };
664
665    let p = centers.saturating_add(nullspace_dim);
666
667    // 3. Dense byte estimates.
668    let derivative_axes = if scale_dims { d } else { 0 };
669    let bytes_per_f64 = std::mem::size_of::<f64>();
670    let dense_design_bytes = bytes_per_f64.saturating_mul(n).saturating_mul(p);
671    let first_derivative_dense_bytes = dense_design_bytes.saturating_mul(derivative_axes);
672    // Diagonal second derivatives are also (D × n × p); off-diagonal cross terms
673    // would scale as D^2 but the planner reports the diagonal tier here.
674    let second_derivative_dense_bytes = first_derivative_dense_bytes;
675
676    // 4. Pick storage mode based on policy.
677    let recommended_storage = match policy.derivative_storage_mode {
678        gam_runtime::resource::DerivativeStorageMode::AnalyticOperatorRequired => {
679            SpatialStorageMode::OperatorOnly
680        }
681        gam_runtime::resource::DerivativeStorageMode::MaterializeIfSmall => {
682            let budget = policy.max_single_materialization_bytes;
683            if derivative_axes == 0 {
684                if dense_design_bytes <= budget {
685                    SpatialStorageMode::DenseValueDenseDerivatives
686                } else {
687                    SpatialStorageMode::LazyValueImplicitDerivatives
688                }
689            } else {
690                let total = dense_design_bytes
691                    .saturating_add(first_derivative_dense_bytes)
692                    .saturating_add(second_derivative_dense_bytes);
693                if total <= budget {
694                    SpatialStorageMode::DenseValueDenseDerivatives
695                } else if dense_design_bytes <= budget {
696                    SpatialStorageMode::LazyValueImplicitDerivatives
697                } else {
698                    SpatialStorageMode::OperatorOnly
699                }
700            }
701        }
702        gam_runtime::resource::DerivativeStorageMode::DiagnosticsOnly => {
703            // Diagnostic mode still prefers analytic storage for correctness.
704            SpatialStorageMode::OperatorOnly
705        }
706    };
707
708    Ok(SpatialBasisPlan {
709        n,
710        d,
711        centers,
712        p_final_estimate: p,
713        dense_design_bytes,
714        first_derivative_dense_bytes,
715        second_derivative_dense_bytes,
716        recommended_storage,
717    })
718}
719
720pub const fn default_spatial_center_strategy(num_centers: usize, d: usize) -> CenterStrategy {
721    if d <= 3 {
722        CenterStrategy::FarthestPoint { num_centers }
723    } else {
724        CenterStrategy::EqualMassCovarRepresentative { num_centers }
725    }
726}
727
728pub fn auto_spatial_center_strategy(num_centers: usize, d: usize) -> CenterStrategy {
729    let strategy = if d == 1 {
730        // In one dimension, farthest-point selection is the deterministic
731        // maximin grid over the observed domain. Equal-mass midpoints leave the
732        // low-frequency Duchon radial block slightly under-resolved at the
733        // boundaries, and REML then compensates with an over-smooth λ on
734        // low-noise signals (#504). The maximin grid matches the native
735        // reproducing-kernel interpolation geometry. The default strategy below
736        // extends the same space-filling contract to low-dimensional spatial
737        // GP bases, where kriging accuracy is governed by fill distance rather
738        // than marginal quantile balance.
739        CenterStrategy::FarthestPoint { num_centers }
740    } else {
741        default_spatial_center_strategy(num_centers, d)
742    };
743    CenterStrategy::Auto(Box::new(strategy))
744}
745
746pub const fn center_strategy_is_auto(strategy: &CenterStrategy) -> bool {
747    matches!(strategy, CenterStrategy::Auto(_))
748}
749
750pub(crate) fn realized_center_strategy(strategy: &CenterStrategy) -> &CenterStrategy {
751    match strategy {
752        CenterStrategy::Auto(inner) => inner.as_ref(),
753        other => other,
754    }
755}
756
757pub fn center_strategy_kind(strategy: &CenterStrategy) -> CenterStrategyKind {
758    match strategy {
759        CenterStrategy::Auto(inner) => center_strategy_kind(inner.as_ref()),
760        CenterStrategy::UserProvided(_) => CenterStrategyKind::UserProvided,
761        CenterStrategy::EqualMass { .. } => CenterStrategyKind::EqualMass,
762        CenterStrategy::EqualMassCovarRepresentative { .. } => {
763            CenterStrategyKind::EqualMassCovarRepresentative
764        }
765        CenterStrategy::FarthestPoint { .. } => CenterStrategyKind::FarthestPoint,
766        CenterStrategy::KMeans { .. } => CenterStrategyKind::KMeans,
767        CenterStrategy::UniformGrid { .. } => CenterStrategyKind::UniformGrid,
768    }
769}
770
771pub fn center_strategy_num_centers(strategy: &CenterStrategy) -> Option<usize> {
772    match strategy {
773        CenterStrategy::Auto(inner) => center_strategy_num_centers(inner.as_ref()),
774        CenterStrategy::UserProvided(centers) => Some(centers.nrows()),
775        CenterStrategy::EqualMass { num_centers }
776        | CenterStrategy::EqualMassCovarRepresentative { num_centers }
777        | CenterStrategy::FarthestPoint { num_centers }
778        | CenterStrategy::KMeans { num_centers, .. } => Some(*num_centers),
779        CenterStrategy::UniformGrid { .. } => None,
780    }
781}
782
783pub fn center_strategy_with_num_centers(
784    strategy: &CenterStrategy,
785    num_centers: usize,
786    d: usize,
787) -> Result<CenterStrategy, BasisError> {
788    validate_center_count(num_centers)?;
789    fn rebuild_inner(
790        strategy: &CenterStrategy,
791        num_centers: usize,
792        d: usize,
793    ) -> Result<CenterStrategy, BasisError> {
794        match strategy {
795            CenterStrategy::Auto(inner) => rebuild_inner(inner.as_ref(), num_centers, d),
796            CenterStrategy::EqualMass { .. } => Ok(CenterStrategy::EqualMass { num_centers }),
797            CenterStrategy::EqualMassCovarRepresentative { .. } => {
798                Ok(CenterStrategy::EqualMassCovarRepresentative { num_centers })
799            }
800            CenterStrategy::FarthestPoint { .. } => {
801                Ok(CenterStrategy::FarthestPoint { num_centers })
802            }
803            CenterStrategy::KMeans { max_iter, .. } => Ok(CenterStrategy::KMeans {
804                num_centers,
805                max_iter: *max_iter,
806            }),
807            CenterStrategy::UniformGrid { .. } if d == 1 => Ok(CenterStrategy::UniformGrid {
808                points_per_dim: num_centers,
809            }),
810            CenterStrategy::UserProvided(_) | CenterStrategy::UniformGrid { .. } => {
811                Err(BasisError::InvalidInput(format!(
812                    "cannot replace center count for {:?} strategy",
813                    center_strategy_kind(strategy)
814                )))
815            }
816        }
817    }
818    let rebuilt = rebuild_inner(strategy, num_centers, d)?;
819    Ok(match strategy {
820        CenterStrategy::Auto(_) => CenterStrategy::Auto(Box::new(rebuilt)),
821        _ => rebuilt,
822    })
823}
824
825/// Thin-plate basis configuration.
826#[derive(Debug, Clone, Serialize, Deserialize)]
827pub struct ThinPlateBasisSpec {
828    pub center_strategy: CenterStrategy,
829    #[serde(default)]
830    pub periodic: Option<Vec<Option<f64>>>,
831    pub length_scale: f64,
832    pub double_penalty: bool,
833    #[serde(default)]
834    pub identifiability: SpatialIdentifiability,
835    /// Frozen Wood-TPRS radial reparameterization. When `Some`, the builder
836    /// reuses this `(raw_radial_cols) × (kept_radial_cols)` matrix instead of
837    /// recomputing it from the constrained kernel penalty eigensystem. The
838    /// rectangular case is the truncated regression-spline path; carrying it
839    /// into prediction guarantees identical radial modes to fit-time.
840    #[serde(default)]
841    pub radial_reparam: Option<Array2<f64>>,
842}
843
844/// Per-smooth identifiability policy for spatial (TPS / Duchon) bases.
845///
846/// For a raw local basis `B` and parametric design block `C`, the orthogonalized
847/// basis is `B_c = B Z` where columns of `Z` span `null((B^T C)^T)`. This enforces:
848///   `B_c^T C = 0`
849/// in the unweighted inner product, so spatial effects cannot absorb parametric
850/// directions that actually exist in the model. The standalone basis builder has
851/// only an implicit intercept available, so it centers smooths against that
852/// intercept. The term-collection builder augments `C` with explicit linear
853/// terms when those terms are present in the formula.
854#[derive(Debug, Default, Clone, Serialize, Deserialize)]
855pub enum SpatialIdentifiability {
856    /// Keep unconstrained basis columns.
857    None,
858    /// Orthogonalize the smooth against model-owned parametric columns.
859    // "Magic" default for modular GAMs with explicit parametric block:
860    // keep spatial smooth orthogonal to intercept/linear terms.
861    // ApproxKind: Exact (orthogonalization is an exact projection).
862    #[default]
863    OrthogonalToParametric,
864    /// Freeze a fit-time transform `Z`; prediction uses `B_new * Z` unchanged.
865    FrozenTransform { transform: Array2<f64> },
866}
867
868pub(crate) use sphere_kernels::{
869    wahba_sphere_kernel_derivative_dcos_kind, wahba_sphere_kernel_from_cos_kind,
870    wahba_sphere_kernel_from_cos_simd_kind, wahba_sphere_kernel_sobolev_derivative_dcos,
871};
872
873pub use sphere_spectral::{
874    pseudo_s2_truncated_coefficients, sobolev_s2_truncated_coefficients,
875    sphere_truncated_spectral_eval,
876};
877
878/// User intent and resolved numeric state for a Matérn kernel length scale.
879///
880/// `Auto` remains auto-owned after the planner resolves its data-dependent
881/// numeric seed.  This is deliberately not represented by a magic floating
882/// point value: callers can distinguish an omitted `length_scale` from an
883/// explicit value before and after center planning, and subsequent κ updates
884/// preserve that provenance.
885#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
886pub enum MaternLengthScale {
887    Auto { resolved: Option<f64> },
888    Fixed(f64),
889}
890
891impl MaternLengthScale {
892    pub const fn auto() -> Self {
893        Self::Auto { resolved: None }
894    }
895
896    pub const fn fixed(value: f64) -> Self {
897        Self::Fixed(value)
898    }
899
900    pub const fn is_fixed(self) -> bool {
901        matches!(self, Self::Fixed(_))
902    }
903
904    pub const fn resolved(self) -> Option<f64> {
905        match self {
906            Self::Auto { resolved } => resolved,
907            Self::Fixed(value) => Some(value),
908        }
909    }
910
911    /// Install a numeric value without changing who owns the scale.
912    pub fn set_resolved(&mut self, value: f64) {
913        match self {
914            Self::Auto { resolved } => *resolved = Some(value),
915            Self::Fixed(fixed) => *fixed = value,
916        }
917    }
918
919    /// Resolve an omitted scale exactly once.  Replanning a frozen or
920    /// κ-updated Auto scale must retain its current numeric value.
921    pub fn resolve_auto_once(&mut self, value: f64) {
922        if let Self::Auto { resolved } = self
923            && resolved.is_none()
924        {
925            *resolved = Some(value);
926        }
927    }
928}
929
930/// Matérn basis configuration.
931#[derive(Debug, Clone, Serialize, Deserialize)]
932pub struct MaternBasisSpec {
933    pub center_strategy: CenterStrategy,
934    #[serde(default)]
935    pub periodic: Option<Vec<Option<f64>>>,
936    pub length_scale: MaternLengthScale,
937    pub nu: MaternNu,
938    #[serde(default)]
939    pub include_intercept: bool,
940    pub double_penalty: bool,
941    #[serde(default)]
942    pub identifiability: MaternIdentifiability,
943    /// Per-axis anisotropy log-scales η_a (contrasts with Ση_a = 0).
944    ///
945    /// This implements geometric anisotropy: Λ = κA where A = diag(exp(η_a)),
946    /// det(A) = 1. The kernel is evaluated at r = κ|Ah| instead of r = κ|h|.
947    /// The decomposition preserves the isotropic scaling law for global κ
948    /// and adds d−1 shape parameters for directional relevance.
949    ///
950    /// Conditional positive definiteness is preserved under any invertible
951    /// linear coordinate transform (Schoenberg), so the kernel remains valid.
952    ///
953    /// When Some, the distance is r = √(Σ_a exp(2η_a) · (x_a - c_a)²).
954    /// When None, isotropic distance r = ‖x - c‖ is used.
955    #[serde(default)]
956    pub aniso_log_scales: Option<Vec<f64>>,
957}
958
959/// Per-smooth identifiability policy for Matérn kernel coefficients.
960///
961/// These constraints are geometric (center-based), so they are stable across
962/// train/predict and do not depend on response weights.
963#[derive(Debug, Default, Clone, Serialize, Deserialize)]
964pub enum MaternIdentifiability {
965    /// Keep the unconstrained kernel coefficient space.
966    None,
967    /// Enforce `1^T alpha = 0` at center locations (removes constant drift).
968    // Safe default with model intercepts: prevent kernel block from absorbing
969    // a global mean level.
970    #[default]
971    CenterSumToZero,
972    /// Enforce orthogonality to `[1, c_1, ..., c_d]` at centers.
973    /// Use this when explicit linear terms should own global trends.
974    CenterLinearOrthogonal,
975    /// Freeze a fit-time transform `Z` so prediction cannot drift.
976    FrozenTransform { transform: Array2<f64> },
977}
978
979/// Duchon null-space polynomial degree.
980///
981/// Controls the polynomial null space of the Duchon / polyharmonic spline. The
982/// Duchon seminorm `‖D^m f‖²` annihilates all polynomials of total degree
983/// `< m`, so those polynomials must be handled as explicit unpenalized columns.
984///
985/// The user-facing `order` knob selects the polynomial degree cutoff `r`, and
986/// the resulting polynomial null space has dimension `C(d + r, r)` where `d`
987/// is the covariate dimension.  In the `duchon(...)` formula DSL:
988///
989/// | `order=` | Variant         | max total degree | null-space dim  |
990/// |----------|-----------------|------------------|-----------------|
991/// | `0`      | `Zero`          | 0                | `C(d+0,0) = 1`  |
992/// | `1`      | `Linear`        | 1                | `C(d+1,1) = d+1`|
993/// | `k≥2`    | `Degree(k)`     | k                | `C(d+k,k)`      |
994///
995/// **How the polynomial null space is consumed during basis construction:**
996///
997/// 1. `polynomial_block_from_order` materialises an `(n, C(d+r,r))` block `P`
998///    of monomials up to total degree `r` at the selected `centers`.
999/// 2. `kernel_constraint_nullspace` computes `Z = null(P_centers^T)`, a
1000///    `(k, k − C(d+r,r))` matrix. Reparameterising the radial kernel
1001///    coefficients as `α = Z γ` enforces the side condition `P_centers^T α = 0`
1002///    and yields `k − C(d+r,r)` free kernel parameters.
1003/// 3. The polynomial block `P_data` evaluated at the data rows is appended to
1004///    the kernel block `Φ Z`, giving a total of
1005///    `(k − C(d+r,r)) + C(d+r,r) = k` columns before the spatial
1006///    identifiability transform.  Crucially, the total width equals the
1007///    requested center count `k`, **not** `k + C(d+r,r)`.
1008///
1009/// **Example — `duchon(PC1, PC2, PC3, centers=10, order=1)` (d=3):**
1010///
1011/// - Polynomial null space: `C(3+1,1) = 4` monomials `{1, x₁, x₂, x₃}`.
1012/// - Kernel columns after constraint: `10 − 4 = 6`.
1013/// - Appended polynomial block: 4 columns.
1014/// - Pre-identifiability total: `6 + 4 = 10` columns, i.e. exactly `centers`.
1015///
1016/// The variant naming matches the Duchon `m` parameter:
1017/// `Zero` → `m=1`, `Linear` → `m=2`, `Degree(k)` → `m=k+1`.
1018#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1019pub enum DuchonNullspaceOrder {
1020    Zero,
1021    Linear,
1022    Degree(usize),
1023}
1024
1025/// Duchon-like basis configuration with explicit low-frequency null-space
1026/// control and explicit spectral power.
1027#[derive(Debug, Clone, Serialize, Deserialize)]
1028#[serde(deny_unknown_fields)]
1029pub struct DuchonBasisSpec {
1030    pub center_strategy: CenterStrategy,
1031    #[serde(default)]
1032    pub periodic: Option<Vec<Option<f64>>>,
1033    /// Optional hybrid Matérn width. `None` means pure scale-free Duchon with
1034    /// spectrum `||w||^(2p + 2s)`. `Some(length_scale)` enables the hybrid
1035    /// spectrum `||w||^(2p) * (kappa^2 + ||w||^2)^s`, `kappa = 1/length_scale`.
1036    pub length_scale: Option<f64>,
1037    /// Literal Duchon spectral power `s` (`f64`, fractional values fully
1038    /// threaded end-to-end). The pure-Duchon kernel exponent is `2(p + s) − d`,
1039    /// so this is the knob that sets `φ(r)`: `s = 0` is the integer-order Duchon
1040    /// kernel `r^{2p−d}` (its `r²·log r` log case in even `d`, ≡ the thin-plate
1041    /// kernel); `s = (d − 1)/2` gives the cubic `r³` in every dimension.
1042    ///
1043    /// This field is taken LITERALLY by the basis builder — `power = 0` means
1044    /// `s = 0`, NOT "use a default". The magic cubic default (applied when the
1045    /// user gives no explicit power) is a request-layer choice resolved by the
1046    /// formula / CLI / pyffi front-ends via [`duchon_cubic_default`]; by the time
1047    /// a spec reaches the builder this value is the final intended `s`. The
1048    /// hybrid Duchon–Matérn path (`length_scale = Some`) still requires an
1049    /// integer `s` (read via `spec.power_as_usize()`).
1050    pub power: f64,
1051    pub nullspace_order: DuchonNullspaceOrder,
1052    #[serde(default)]
1053    pub identifiability: SpatialIdentifiability,
1054    /// Per-axis anisotropy log-scales η_a.
1055    ///
1056    /// For hybrid Duchon (`length_scale=Some`), these are centered contrasts in
1057    /// the decomposition Λ = κA with det(A)=1. For pure Duchon
1058    /// (`length_scale=None`), they parameterize shape-only axis warping on the
1059    /// public path and are centered before basis evaluation/writeback so no
1060    /// global length scale is introduced.
1061    ///
1062    /// When Some, the distance is r = √(Σ_a exp(2η_a) · (x_a - c_a)²).
1063    /// When None, isotropic distance r = ‖x - c‖ is used.
1064    #[serde(default)]
1065    pub aniso_log_scales: Option<Vec<f64>>,
1066    #[serde(default)]
1067    pub operator_penalties: DuchonOperatorPenaltySpec,
1068    #[serde(default)]
1069    pub boundary: OneDimensionalBoundary,
1070    /// Data-metric radial reparameterization `V` (#1355), mirroring the
1071    /// thin-plate Wood-TPRS reparam. When `Some`, the constrained kernel
1072    /// transform is folded to `Z·V` so the realized design columns rotate into
1073    /// the `G_c`-orthonormal generalized eigenbasis of `Ω_c v = μ G_c v` and the
1074    /// native penalty becomes the diagonal curvature-per-unit-data-variance
1075    /// spectrum (mgcv's cliff), preventing the REML over-smoothing collapse to
1076    /// EDF = 1. Frozen at the cold dense build and replayed verbatim by the
1077    /// predict / κ-trial / ψ-derivative paths so they stay bit-consistent with
1078    /// the fit-time design. `None` on the lazy/streaming path (huge `n`), which
1079    /// retains the original constrained basis.
1080    #[serde(default)]
1081    pub radial_reparam: Option<Array2<f64>>,
1082}
1083
1084impl DuchonBasisSpec {
1085    /// Integer view of `power` for the existing integer-only downstream chain.
1086    /// Non-finite or non-integer values fall back to `0` (the integer-only
1087    /// validators downstream already reject this case with a clear message).
1088    pub fn power_as_usize(&self) -> usize {
1089        duchon_power_to_usize(self.power)
1090    }
1091}
1092
1093/// Convert a Duchon spectral-power `f64` into the integer view used by the
1094/// closed-form code paths. Non-finite, negative, or fractional values clamp to
1095/// `0` so the validator downstream emits the canonical error.
1096pub fn duchon_power_to_usize(power: f64) -> usize {
1097    if !power.is_finite() || power < 0.0 {
1098        return 0;
1099    }
1100    let rounded = power.round();
1101    if (rounded - power).abs() > 1e-9 {
1102        return 0;
1103    }
1104    rounded as usize
1105}
1106
1107#[derive(Clone, Debug, Serialize, Deserialize)]
1108pub struct DuchonOperatorPenaltySpec {
1109    pub mass: OperatorPenaltySpec,
1110    pub tension: OperatorPenaltySpec,
1111    pub stiffness: OperatorPenaltySpec,
1112}
1113
1114#[derive(Clone, Debug, Serialize, Deserialize)]
1115pub enum OperatorPenaltySpec {
1116    Active {
1117        initial_log_lambda: f64,
1118        prior: Option<RhoPrior>,
1119    },
1120    Disabled,
1121}
1122
1123impl Default for DuchonOperatorPenaltySpec {
1124    fn default() -> Self {
1125        // ALL ON. The Duchon penalty is a Hilbert scale: curvature is the
1126        // always-on exact RKHS `Primary` Gram and the trend ridge is always on;
1127        // the lower orders — mass (amplitude `Σ(f−f̄)²`) and tension (first-order
1128        // roughness `Σ‖∇f‖²`) — are active here, collocated on a density-blind
1129        // data-support sample. REML deselects any the data don't support (SPEC:
1130        // recover the null by default, opt INTO overfitting). Stiffness (`D2`)
1131        // stays off — `Primary` is the exact, superior curvature. (The Matérn
1132        // collocation overlay builds its own `all_active()`; SAE atoms, which
1133        // ship only `Primary`, use `all_disabled()`.)
1134        Self {
1135            mass: OperatorPenaltySpec::Active {
1136                initial_log_lambda: 0.0,
1137                prior: None,
1138            },
1139            tension: OperatorPenaltySpec::Active {
1140                initial_log_lambda: 0.0,
1141                prior: None,
1142            },
1143            stiffness: OperatorPenaltySpec::Disabled,
1144        }
1145    }
1146}
1147
1148impl DuchonOperatorPenaltySpec {
1149    pub fn has_active_operator_penalty(&self) -> bool {
1150        matches!(self.mass, OperatorPenaltySpec::Active { .. })
1151            || matches!(self.tension, OperatorPenaltySpec::Active { .. })
1152            || matches!(self.stiffness, OperatorPenaltySpec::Active { .. })
1153    }
1154
1155    pub fn all_disabled() -> Self {
1156        Self {
1157            mass: OperatorPenaltySpec::Disabled,
1158            tension: OperatorPenaltySpec::Disabled,
1159            stiffness: OperatorPenaltySpec::Disabled,
1160        }
1161    }
1162
1163    /// All three operator dials active — used by the Matérn collocation overlay.
1164    pub fn all_active() -> Self {
1165        let active = || OperatorPenaltySpec::Active {
1166            initial_log_lambda: 0.0,
1167            prior: None,
1168        };
1169        Self {
1170            mass: active(),
1171            tension: active(),
1172            stiffness: active(),
1173        }
1174    }
1175
1176    /// Operator-penalty dials appropriate for a Matérn-ν kernel in dimension `d`.
1177    ///
1178    /// The Matérn-ν RKHS is the Sobolev space `H^m` with `m = ν + d/2`: its
1179    /// squared norm controls the order-`j` derivative in L2 exactly when
1180    /// `j ≤ m`. The collocation overlay penalizes the squared L2 norms of the
1181    /// value (mass, `D0`, j=0), gradient (tension, `D1`, j=1) and Hessian
1182    /// (stiffness, `D2`, j=2). Activating a penalty whose derivative order
1183    /// exceeds the RKHS smoothness (`j > m`) imposes a roughness constraint the
1184    /// true kernel does NOT — it over-smooths the reduced-rank fit relative to
1185    /// the exact GP (mgcv `bs="gp"`, GpGp).
1186    ///
1187    /// The ν=1/2 Ornstein–Uhlenbeck kernel is the sole exception: its cusp at a
1188    /// center makes the collocated gradient/Hessian undefined, so it retains
1189    /// mass only (#707). Every differentiable order uses the inclusive Sobolev
1190    /// boundary. In particular ν=3/2 in d=1 has `m=2`, and its finite `D2`
1191    /// stiffness energy belongs to H². Omitting that block leaves the rough
1192    /// kernel with only mass+tension, inflates EDF, and changes the REML model
1193    /// class relative to its stated RKHS.
1194    pub fn matern_for_smoothness(nu: MaternNu, d: usize) -> Self {
1195        let m = nu.half_integer_value() + 0.5 * d as f64;
1196        // Tolerance keeps the mathematically inclusive `j ≤ m` boundary stable
1197        // under floating-point representation of half-integer orders.
1198        const ORDER_EPS: f64 = 1e-9;
1199        let active = || OperatorPenaltySpec::Active {
1200            initial_log_lambda: 0.0,
1201            prior: None,
1202        };
1203        let gate = |order: f64| {
1204            if !matches!(nu, MaternNu::Half) && m + ORDER_EPS >= order {
1205                active()
1206            } else {
1207                OperatorPenaltySpec::Disabled
1208            }
1209        };
1210        Self {
1211            mass: active(),
1212            tension: gate(1.0),
1213            stiffness: gate(2.0),
1214        }
1215    }
1216}
1217
1218pub fn minimum_duchon_power_for_operator_penalties(
1219    dim: usize,
1220    nullspace_order: DuchonNullspaceOrder,
1221    max_operator_derivative_order: usize,
1222) -> usize {
1223    let p = duchon_p_from_nullspace_order(nullspace_order);
1224    let mut s = 0usize;
1225    while 2 * (p + s) <= dim + max_operator_derivative_order {
1226        s += 1;
1227    }
1228    s
1229}
1230
1231/// Resolve a fully admissible Duchon `(nullspace_order, power)` pair.
1232///
1233/// Three constraints fold into one resolution:
1234///   (a) operator collocation up to `max_op`:        `2(p + s) > d + max_op`
1235///   (b) pure-mode CPD vs polynomial nullspace P_p:  `2s < d`
1236///       (Wendland Thm 8.17: pure polyharmonic kernel of order m = p+s in
1237///        R^d is CPD of order `m − ⌊d/2⌋ + 1[d even, log] / m − (d−1)/2
1238///        [d odd]`, and Duchon interpolation against P_p is well-posed iff
1239///        CPD order ≤ p, which collapses to `2s < d` since 2s, d are
1240///        integers and 2s is even.)
1241///   (a) implies the kernel-existence condition `2(p + s) > d`.
1242///   (b) is dropped when `length_scale` is `Some` (hybrid Matérn-blended
1243///       kernel is strictly PD, CPD order 0).
1244///
1245/// Strategy: at the requested `nullspace_order`, take the smallest `s`
1246/// satisfying (a). If that `s` violates (b) in pure mode, escalate the
1247/// nullspace order by one and retry. Termination: at `p ≥ ⌈(d+max_op)/2⌉ + 1`
1248/// the operator constraint (a) admits `s = 0`, and `0 < d` satisfies (b)
1249/// for any `d ≥ 1`, so escalation always converges.
1250///
1251/// The returned nullspace order is monotone in the request: it never
1252/// decreases the user's requested order — only strengthens it when pure-mode
1253/// CPD requires a richer polynomial absorption space.
1254pub fn resolve_duchon_orders(
1255    dim: usize,
1256    requested_nullspace_order: DuchonNullspaceOrder,
1257    max_operator_derivative_order: usize,
1258    length_scale: Option<f64>,
1259) -> (DuchonNullspaceOrder, usize) {
1260    assert!(dim >= 1, "Duchon basis requires dim >= 1");
1261    let pure = length_scale.is_none();
1262    let mut nullspace = requested_nullspace_order;
1263    // Bounded loop: escalation terminates by the argument above.
1264    for _ in 0..=(dim + max_operator_derivative_order + 1) {
1265        let p = duchon_p_from_nullspace_order(nullspace);
1266        // Smallest s with 2(p + s) > d + max_op:
1267        //   2p > d + max_op            ⇒ s = 0
1268        //   else s = ⌈(d + max_op + 1 − 2p) / 2⌉ = (d + max_op + 2 − 2p) / 2
1269        let s_op = if 2 * p > dim + max_operator_derivative_order {
1270            0
1271        } else {
1272            (dim + max_operator_derivative_order + 2 - 2 * p) / 2
1273        };
1274        if !pure || 2 * s_op < dim {
1275            return (nullspace, s_op);
1276        }
1277        nullspace = duchon_next_nullspace_order(nullspace);
1278    }
1279    // Bounded-loop fallback: by the analysis in the docstring, for
1280    // `p >= ceil((dim + max_op) / 2) + 1` the operator constraint admits
1281    // `s = 0` and (in pure mode) `0 < dim` satisfies the kernel-existence
1282    // condition. The loop above always reaches that regime within the bound,
1283    // so returning the last `nullspace` with `s = 0` is a valid answer.
1284    (nullspace, 0)
1285}
1286
1287#[inline]
1288pub(crate) fn duchon_next_nullspace_order(order: DuchonNullspaceOrder) -> DuchonNullspaceOrder {
1289    match order {
1290        DuchonNullspaceOrder::Zero => DuchonNullspaceOrder::Linear,
1291        DuchonNullspaceOrder::Linear => DuchonNullspaceOrder::Degree(2),
1292        DuchonNullspaceOrder::Degree(k) => DuchonNullspaceOrder::Degree(k + 1),
1293    }
1294}
1295
1296pub(crate) fn duchon_previous_nullspace_order(order: DuchonNullspaceOrder) -> DuchonNullspaceOrder {
1297    match order {
1298        DuchonNullspaceOrder::Zero => DuchonNullspaceOrder::Zero,
1299        DuchonNullspaceOrder::Linear => DuchonNullspaceOrder::Zero,
1300        DuchonNullspaceOrder::Degree(2) => DuchonNullspaceOrder::Linear,
1301        DuchonNullspaceOrder::Degree(k) => DuchonNullspaceOrder::Degree(k - 1),
1302    }
1303}
1304
1305/// Returns the maximum derivative order required by the *active* operator
1306/// penalties: 2 if stiffness is Active, else 1 if tension is Active, else 0.
1307/// Mass-only (or no active operator) penalties only require kernel validity
1308/// (`2(p+s) > d`), tension requires D1 collocation (`2(p+s) > d+1`), and
1309/// stiffness requires D2 collocation (`2(p+s) > d+2`).
1310pub fn duchon_max_active_operator_derivative_order(
1311    operator_penalties: &DuchonOperatorPenaltySpec,
1312) -> usize {
1313    if matches!(
1314        operator_penalties.stiffness,
1315        OperatorPenaltySpec::Active { .. }
1316    ) {
1317        2
1318    } else if matches!(
1319        operator_penalties.tension,
1320        OperatorPenaltySpec::Active { .. }
1321    ) {
1322        1
1323    } else {
1324        0
1325    }
1326}
1327
1328/// Metadata returned by generic basis builders.
1329#[derive(Debug, Clone)]
1330pub enum BasisMetadata {
1331    BSpline1D {
1332        knots: Array1<f64>,
1333        identifiability_transform: Option<Array2<f64>>,
1334        periodic: Option<(f64, f64, usize)>,
1335        /// Effective B-spline polynomial degree carried by `knots`.
1336        ///
1337        /// Persisted alongside `knots` so prediction can reconstruct an
1338        /// evaluator that matches fit-time geometry, even when the fit-time
1339        /// auto-shrink (issue #340) reduced the user's requested degree to
1340        /// fit the available data (`n` too small for cubic ⇒ quadratic ⇒
1341        /// linear). When `None` the consumer should fall back to the
1342        /// upstream `BSplineBasisSpec.degree` (legacy / non-shrunk path).
1343        degree: Option<usize>,
1344        /// Human-readable description of an automatic basis shrink (issue #340)
1345        /// when the user's requested `(degree, num_internal_knots)` exceeded the
1346        /// available evaluation count `n`. `Some(note)` records the before→after
1347        /// configuration; `None` means no auto-shrink occurred for this basis.
1348        auto_shrink_note: Option<String>,
1349        /// Raw-basis particular-solution coefficients `β_p` for a *non-zero*
1350        /// endpoint anchor (#2297), if any. The term carries a fixed affine
1351        /// offset function `B_raw(x) · β_p` in addition to its constrained
1352        /// design `B_raw(x) · Z`; the design assembler realizes that offset into
1353        /// the model's linear predictor at both fit and predict time. `None`
1354        /// for free / clamped / zero-anchor bases (the ordinary pure-linear
1355        /// chart). Recomputed deterministically from the frozen `knots`,
1356        /// `degree` and boundary conditions on every rebuild, so a saved model
1357        /// replays the identical offset; it is serialized here so the assembler
1358        /// need not re-derive it from the spec. This metadata is transient
1359        /// (rebuilt at predict from the serialized frozen spec), not persisted.
1360        anchor_offset_coeffs: Option<Array1<f64>>,
1361    },
1362    /// Natural cubic regression spline (`bs="cr"`/`"cs"`) metadata (#1074).
1363    ///
1364    /// `knots` are the `k` Lancaster–Salkauskas knots that index the basis
1365    /// values directly (basis dim = `knots.len()`). Predict-time rebuilds
1366    /// reconstruct the cr geometry from `knots` and replay the captured
1367    /// `identifiability_transform` exactly, mirroring `BSpline1D`.
1368    CubicRegression1D {
1369        knots: Array1<f64>,
1370        identifiability_transform: Option<Array2<f64>>,
1371    },
1372    ThinPlate {
1373        centers: Array2<f64>,
1374        length_scale: f64,
1375        periodic: Option<Vec<Option<f64>>>,
1376        identifiability_transform: Option<Array2<f64>>,
1377        /// Uniform coordinate scale used for isotropic input standardization.
1378        input_scale: crate::IsotropicScale,
1379        /// Wood-TPRS radial reparameterization carried into prediction so the
1380        /// rotated radial basis at predict-time matches fit-time exactly. `None`
1381        /// in the lazy/streaming path which retains the original basis.
1382        radial_reparam: Option<Array2<f64>>,
1383    },
1384    Sphere {
1385        centers: Array2<f64>,
1386        penalty_order: usize,
1387        method: SphereMethod,
1388        max_degree: Option<usize>,
1389        wahba_kernel: SphereWahbaKernel,
1390        constraint_transform: Option<Array2<f64>>,
1391    },
1392    /// Constant-curvature (`M_κ`) geodesic-kernel smooth (#944). `kappa` and
1393    /// the realized `length_scale` are persisted so predict-time (and the
1394    /// future ψ-channel per-trial) rebuilds replay the exact fit-time
1395    /// geometry; `constraint_transform` is the composed `z · z_parametric`
1396    /// frozen by the global identifiability pipeline (#532 pattern).
1397    ConstantCurvature {
1398        centers: Array2<f64>,
1399        kappa: f64,
1400        length_scale: f64,
1401        constraint_transform: Option<Array2<f64>>,
1402    },
1403    /// Measure-jet spline smooth: multiscale local-jet-residual energy of the
1404    /// empirical measure, quadratured on the center set. `centers` are the
1405    /// REALIZED barycenter nodes; `order_s` stores the spec's order sentinel
1406    /// verbatim as the mode marker (0.0 = per-level/spectral, > 0 = fused
1407    /// pin — persisting a realized default would flip the rebuilt mode). The
1408    /// penalty depends on the FIT data through `masses`, the realized
1409    /// `eps_band`, the support anchors, and the normalization scales, so all
1410    /// are persisted and replayed verbatim by
1411    /// predict-time (and per-ψ-trial) rebuilds — recomputing either from
1412    /// predict rows would change the penalty the coefficients were estimated
1413    /// under. `constraint_transform` is the composed `z · z_parametric`
1414    /// frozen by the global identifiability pipeline (#532 pattern).
1415    MeasureJet {
1416        centers: Array2<f64>,
1417        input_scale: crate::IsotropicScale,
1418        length_scale: f64,
1419        eps_band: Vec<f64>,
1420        order_s: f64,
1421        alpha: f64,
1422        tau0: f64,
1423        masses: Array1<f64>,
1424        support_means: Vec<f64>,
1425        penalty_normalization_scales: Vec<f64>,
1426        raw_penalty_normalization_scales: Vec<f64>,
1427        fused_penalty_normalization_scale: Option<f64>,
1428        constraint_transform: Option<Array2<f64>>,
1429        /// Ambient input-measurement-error scale `σ_coord` (issue #2225): the
1430        /// perpendicular off-manifold residual spread of the fit rows, in the
1431        /// centers' (standardized) frame. `None` when it could not be estimated.
1432        /// Carried into `MeasureJetFrozenQuadrature::sigma_coord` at freeze time.
1433        sigma_coord: Option<f64>,
1434    },
1435    Matern {
1436        centers: Array2<f64>,
1437        length_scale: f64,
1438        periodic: Option<Vec<Option<f64>>>,
1439        nu: MaternNu,
1440        include_intercept: bool,
1441        identifiability_transform: Option<Array2<f64>>,
1442        /// Uniform coordinate scale used for isotropic input standardization.
1443        input_scale: crate::IsotropicScale,
1444        /// Per-axis anisotropy log-scales η_a for geometric anisotropy.
1445        /// When Some, distance is r = √(Σ_a exp(2η_a) · (x_a - c_a)²).
1446        aniso_log_scales: Option<Vec<f64>>,
1447    },
1448    Duchon {
1449        centers: Array2<f64>,
1450        length_scale: Option<f64>,
1451        periodic: Option<Vec<Option<f64>>>,
1452        power: f64,
1453        nullspace_order: DuchonNullspaceOrder,
1454        identifiability_transform: Option<Array2<f64>>,
1455        /// Uniform coordinate scale used for isotropic input standardization.
1456        input_scale: crate::IsotropicScale,
1457        /// Per-axis anisotropy log-scales η_a, stored for prediction.
1458        aniso_log_scales: Option<Vec<f64>>,
1459        /// Support points used to build the active lower-order operator
1460        /// penalties (mass/tension/stiffness). Stored so runtime adaptive
1461        /// caches can rebuild the exact same operator rows instead of guessing
1462        /// from centers.
1463        operator_collocation_points: Option<Array2<f64>>,
1464        /// Data-metric radial reparameterization `V` (#1355). When `Some`, the
1465        /// constrained kernel transform is folded to `Z·V` so predict-time and
1466        /// κ-trial rebuilds replay the exact fit-time rotated radial basis.
1467        /// `None` on the lazy/streaming path (original constrained basis).
1468        radial_reparam: Option<Array2<f64>>,
1469    },
1470    Pca {
1471        feature_cols: Vec<usize>,
1472        basis_matrix: Array2<f64>,
1473        centered: bool,
1474        smooth_penalty: f64,
1475        center_mean: Option<Array1<f64>>,
1476        pca_basis_path: Option<std::path::PathBuf>,
1477        chunk_size: usize,
1478    },
1479    TensorBSpline {
1480        feature_cols: Vec<usize>,
1481        knots: Vec<Array1<f64>>,
1482        degrees: Vec<usize>,
1483        periods: Vec<Option<f64>>,
1484        /// Per-margin flag: `true` when that margin is a natural cubic
1485        /// regression spline (`NaturalCubicRegression` knotspec) rather than an
1486        /// open/periodic B-spline (#1074). Persisted so the tensor freeze
1487        /// rebuilds the cr marginal knotspec (value-at-knot) instead of an open
1488        /// `Provided(knots)` B-spline, keeping predict-time marginals identical
1489        /// to the fit-time cr margins. Defaults to all-`false` (legacy B-spline
1490        /// tensors) when deserialized from an older persisted model (the
1491        /// older-model default is applied on the persisted `SmoothBasisSpec`
1492        /// side; `BasisMetadata` itself is transient builder output and is not
1493        /// serde-serialized, so it carries no `#[serde]` attributes).
1494        is_cr: Vec<bool>,
1495        identifiability_transform: Option<Array2<f64>>,
1496    },
1497    SphereHarmonics {
1498        max_degree: usize,
1499        radians: bool,
1500    },
1501    /// Wrap an inner basis metadata to record a multiplicative `by` (continuous or
1502    /// factor) along a column of the dataset.
1503    BySmooth {
1504        inner: Box<BasisMetadata>,
1505        by_col: usize,
1506        levels: Option<Vec<u64>>,
1507        ordered: bool,
1508    },
1509    /// Factor-by-smooth (mgcv-style `s(x, by=g, bs="fs"|"sz"|"re")`).
1510    FactorSmooth {
1511        continuous_cols: Vec<usize>,
1512        group_col: usize,
1513        knots: Array1<f64>,
1514        degree: usize,
1515        periodic: Option<(f64, f64, usize)>,
1516        group_levels: Vec<u64>,
1517        flavour: String,
1518        /// `true` when the per-level marginal is a cubic regression spline
1519        /// (`NaturalCubicRegression` knotspec, mgcv's `bs="sz"` default marginal,
1520        /// #1074). Predict-time freeze must then restore a cr knotspec from the
1521        /// stored value-knots rather than treating them as a B-spline knot
1522        /// vector. Defaults to `false` (B-spline marginal) for backward compat.
1523        marginal_is_cr: bool,
1524    },
1525}
1526
1527/// Standardized basis build result for engine-level composition.
1528#[derive(Clone)]
1529pub struct BasisBuildResult {
1530    pub design: DesignMatrix,
1531    /// Fixed row-wise contribution carried by an affine basis chart.
1532    ///
1533    /// Ordinary bases are linear in their fitted coefficients and leave this
1534    /// as `None`. An inhomogeneous boundary condition, such as a non-zero
1535    /// B-spline endpoint anchor, realizes the basis as
1536    /// `offset(x) + design(x) * beta`; the known `offset(x)` belongs here, not
1537    /// in a fake coefficient column. Term-collection assembly sums these
1538    /// channels and routes the result through the model's ordinary likelihood
1539    /// offset at fit and prediction time.
1540    pub affine_offset: Option<Array1<f64>>,
1541    /// Canonical active penalties. Matrix, spectral metadata, operator form,
1542    /// and semantic identity are one record so dropping an earlier candidate
1543    /// cannot shift one channel without shifting all of them.
1544    pub active_penalties: Vec<ActivePenalty>,
1545    /// Candidate diagnostics excluded from the active smoothing-parameter
1546    /// layout. Dropped candidates never share a positional container with
1547    /// active matrices.
1548    pub dropped_penalties: Vec<DroppedPenaltyInfo>,
1549    pub metadata: BasisMetadata,
1550    /// Optional factored rowwise-Kronecker representation for tensor-product
1551    /// bases. When present, downstream code can keep the design operator-backed
1552    /// instead of forcing a fully materialized `n x prod(q_j)` block.
1553    pub kronecker_factored: Option<KroneckerFactoredBasis>,
1554    /// Joint-null absorption rotation for this basis, when the basis carries
1555    /// any penalties with a non-trivial joint null space.
1556    ///
1557    /// `Some(rotation)` records `Q = [U_range | U_null]` where `U_null` spans
1558    /// the joint null space `null(Σ_k S_k)` over this basis's active
1559    /// penalties (unscaled — the structural joint null is independent of
1560    /// `λ`). After the basis pipeline applies this rotation, the design
1561    /// becomes `X · Q` and each penalty becomes `Qᵀ S_k Q`, block-diagonal
1562    /// with a guaranteed-zero null tail. The same `Q` must be replayed at
1563    /// prediction time, so it is persisted in the fitted model. `None`
1564    /// indicates either no penalties on this basis, or a full-rank joint
1565    /// penalty (joint nullity = 0). A `Some` value is never recorded with
1566    /// `joint_nullity == 0` — the `None` discriminant is canonical for
1567    /// "nothing to absorb".
1568    ///
1569    /// Stage-2 commit A: this field is plumbed into the struct but neither
1570    /// computed nor applied yet. Stage-2 commit B populates it; Stage-2
1571    /// commit D applies the rotation to `design` and `penalties`.
1572    pub joint_null_rotation: Option<JointNullRotation>,
1573}
1574
1575/// Joint-null absorption rotation, attached to a smooth's basis when the
1576/// basis's joint penalty `Σ_k S_k` has a non-trivial null space.
1577///
1578/// The `rotation` field stores the orthonormal eigenvector matrix
1579/// `Q = [U_range | U_null]` of the symmetric joint penalty: the first
1580/// `range_dim = rotation.ncols() - joint_nullity` columns span
1581/// `range(Σ_k S_k)`; the remaining `joint_nullity` columns span
1582/// `null(Σ_k S_k)`. After the pipeline applies the rotation, the smooth's
1583/// coefficient vector satisfies `β = Q · γ`, the design becomes `X · Q`,
1584/// and each per-block penalty `S_k` becomes `Qᵀ S_k Q`, which is guaranteed
1585/// block-diagonal with a zero `(joint_nullity × joint_nullity)` tail
1586/// (because the joint null annihilates every active `S_k`).
1587#[derive(Clone, Serialize, Deserialize)]
1588pub struct JointNullRotation {
1589    /// `(p_smooth × p_smooth)` orthonormal matrix; range columns first,
1590    /// joint-null columns last.
1591    pub rotation: Array2<f64>,
1592    /// Number of columns at the tail of `rotation` that span the joint
1593    /// null space. Always `> 0` when wrapped in `Some` — the value `0`
1594    /// is encoded as `None`.
1595    pub joint_nullity: usize,
1596}
1597
1598impl std::fmt::Debug for JointNullRotation {
1599    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1600        f.debug_struct("JointNullRotation")
1601            .field(
1602                "rotation",
1603                &format_args!("{}×{}", self.rotation.nrows(), self.rotation.ncols()),
1604            )
1605            .field("joint_nullity", &self.joint_nullity)
1606            .finish()
1607    }
1608}
1609
1610impl std::fmt::Debug for BasisBuildResult {
1611    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1612        f.debug_struct("BasisBuildResult")
1613            .field("design", &self.design)
1614            .field(
1615                "affine_offset_len",
1616                &self.affine_offset.as_ref().map(|offset| offset.len()),
1617            )
1618            .field("active_penalties", &self.active_penalties)
1619            .field("dropped_penalties", &self.dropped_penalties)
1620            .field("metadata", &self.metadata)
1621            .field("kronecker_factored", &self.kronecker_factored)
1622            .field("joint_null_rotation", &self.joint_null_rotation)
1623            .finish()
1624    }
1625}
1626
1627/// Factored tensor-product basis metadata for operator-backed downstream use.
1628#[derive(Debug)]
1629pub struct KroneckerFactoredBasis {
1630    /// Marginal design matrices: `marginal_designs[j]` is `(n, q_j)`.
1631    pub marginal_designs: Vec<Array2<f64>>,
1632    /// Marginal penalty matrices: `marginal_penalties[k]` is `(q_k, q_k)`.
1633    pub marginal_penalties: Vec<Array2<f64>>,
1634    /// Marginal basis dimensions: `[q_0, ..., q_{d-1}]`.
1635    pub marginal_dims: Vec<usize>,
1636    /// Whether the system includes a global ridge (double) penalty.
1637    pub has_double_penalty: bool,
1638    /// λ-invariant tensor structure (marginal eigensystems, reparameterized
1639    /// marginals, shrinkage scale), memoized once per fit. The marginal
1640    /// designs/penalties are fixed for the whole fit, so the expensive marginal
1641    /// `eigh()` and `B_k·U_k` GEMMs only need to run once — every outer REML
1642    /// iterate (50+ on the #1082 tensor cases) then reuses this. Filled lazily
1643    /// on first use via [`Self::invariant_structure`]. NOT serialized and reset
1644    /// to empty on `Clone` (it is purely a within-fit performance cache; a fresh
1645    /// owner recomputes on first demand, keeping every result bit-identical).
1646    invariant: std::sync::OnceLock<std::sync::Arc<crate::kronecker::KroneckerInvariantStructure>>,
1647}
1648
1649impl Clone for KroneckerFactoredBasis {
1650    fn clone(&self) -> Self {
1651        Self {
1652            marginal_designs: self.marginal_designs.clone(),
1653            marginal_penalties: self.marginal_penalties.clone(),
1654            marginal_dims: self.marginal_dims.clone(),
1655            has_double_penalty: self.has_double_penalty,
1656            // Propagate the memoized structure when present so a clone made
1657            // mid-fit keeps the hoist; otherwise start empty (recomputed on
1658            // first demand, identical result).
1659            invariant: match self.invariant.get() {
1660                Some(s) => {
1661                    let cell = std::sync::OnceLock::new();
1662                    cell.get_or_init(|| std::sync::Arc::clone(s));
1663                    cell
1664                }
1665                None => std::sync::OnceLock::new(),
1666            },
1667        }
1668    }
1669}
1670
1671impl KroneckerFactoredBasis {
1672    /// Construct from the fixed marginal data with an empty invariant cache.
1673    pub fn new(
1674        marginal_designs: Vec<Array2<f64>>,
1675        marginal_penalties: Vec<Array2<f64>>,
1676        marginal_dims: Vec<usize>,
1677        has_double_penalty: bool,
1678    ) -> Self {
1679        Self {
1680            marginal_designs,
1681            marginal_penalties,
1682            marginal_dims,
1683            has_double_penalty,
1684            invariant: std::sync::OnceLock::new(),
1685        }
1686    }
1687
1688    /// Lazily compute (once) and return the λ-invariant tensor structure
1689    /// (marginal eigensystems, reparameterized marginals, shrinkage scale).
1690    ///
1691    /// Computed from the fixed marginal designs/penalties, so the result is the
1692    /// same on every call within a fit; the first call pays the `eigh()` cost
1693    /// and every later call is a pointer load. Because the cache is keyed on the
1694    /// fixed marginal data and `marginal_penalties`/`marginal_designs` are
1695    /// immutable for the fit's lifetime, no invalidation is needed.
1696    pub fn invariant_structure(
1697        &self,
1698    ) -> Result<std::sync::Arc<crate::kronecker::KroneckerInvariantStructure>, BasisError> {
1699        // Fast path: already memoized.
1700        if let Some(s) = self.invariant.get() {
1701            return Ok(std::sync::Arc::clone(s));
1702        }
1703        // Compute outside the cell (fallible) and install via `get_or_init`. If a
1704        // concurrent racer already won, `get_or_init` drops our `computed` and
1705        // returns the stored one; either way the value is the unique function of
1706        // the fixed marginal data, so the returned Arc is correct.
1707        let computed = std::sync::Arc::new(crate::kronecker::KroneckerInvariantStructure::compute(
1708            &self.marginal_designs,
1709            &self.marginal_penalties,
1710            &self.marginal_dims,
1711        )?);
1712        let installed = self.invariant.get_or_init(|| computed);
1713        Ok(std::sync::Arc::clone(installed))
1714    }
1715}
1716
1717#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1718pub enum PenaltySource {
1719    Primary,
1720    DoublePenaltyNullspace,
1721    OperatorMass,
1722    OperatorTension,
1723    OperatorStiffness,
1724    /// One per input axis `a` of a multivariate Duchon smooth: the gradient
1725    /// energy along axis `a`, `Σ(∂f/∂x_a)²`, each with its own REML λ_a. REML
1726    /// shrinks an axis's contribution toward flat only when it does not earn
1727    /// its keep — penalty-based ARD / variable relevance, the replacement for
1728    /// brittle kernel-η optimization. Emitted when `scale_dims` is on.
1729    OperatorRelevance {
1730        axis: usize,
1731    },
1732    TensorMarginal {
1733        dim: usize,
1734    },
1735    TensorSeparable {
1736        penalized_margins: Vec<usize>,
1737    },
1738    TensorGlobalRidge,
1739    Other(String),
1740}
1741
1742#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1743pub enum PenaltyDropReason {
1744    ZeroMatrix,
1745    NumericalRankZero,
1746}
1747
1748fn default_normalization_scale() -> f64 {
1749    1.0
1750}
1751
1752/// Metadata for one retained penalty coordinate.
1753///
1754/// This type is active-only by construction. In particular it has no
1755/// `active` flag or optional drop reason: those fields allowed a metadata
1756/// position to exist without a corresponding matrix and made positional
1757/// indexing silently wrong after an earlier candidate was dropped.
1758#[derive(Debug, Clone, Serialize, Deserialize)]
1759pub struct ActivePenaltyInfo {
1760    pub source: PenaltySource,
1761    pub original_index: usize,
1762    pub effective_rank: usize,
1763    #[serde(default = "default_normalization_scale")]
1764    pub normalization_scale: f64,
1765    /// Kronecker factors preserved from tensor penalty construction.
1766    /// When present, spectral decomposition can use per-factor eigendecomposition.
1767    #[serde(skip)]
1768    pub kronecker_factors: Option<Vec<Array2<f64>>>,
1769}
1770
1771/// Diagnostic for one penalty candidate excluded from the optimizer layout.
1772/// It is intentionally a different type from [`ActivePenaltyInfo`] so a
1773/// dropped record cannot be used as an active matrix index.
1774#[derive(Debug, Clone, Serialize, Deserialize)]
1775pub struct DroppedPenaltyInfo {
1776    pub source: PenaltySource,
1777    pub original_index: usize,
1778    pub reason: PenaltyDropReason,
1779    #[serde(default = "default_normalization_scale")]
1780    pub normalization_scale: f64,
1781}
1782
1783/// One atomic active penalty identity.
1784///
1785/// Every field describes the same retained candidate. Consumers may reorder,
1786/// transform, or remove a penalty only by moving the whole record, which makes
1787/// matrix/role/nullity/operator skew unrepresentable.
1788#[derive(Clone)]
1789pub struct ActivePenalty {
1790    pub matrix: Array2<f64>,
1791    pub nullity: usize,
1792    pub null_eigenvectors: Option<Array2<f64>>,
1793    pub op: Option<std::sync::Arc<dyn crate::analytic_penalties::PenaltyOp>>,
1794    pub info: ActivePenaltyInfo,
1795}
1796
1797impl std::fmt::Debug for ActivePenalty {
1798    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1799        f.debug_struct("ActivePenalty")
1800            .field(
1801                "matrix",
1802                &format_args!("{}×{}", self.matrix.nrows(), self.matrix.ncols()),
1803            )
1804            .field("nullity", &self.nullity)
1805            .field(
1806                "null_eigenvectors",
1807                &self
1808                    .null_eigenvectors
1809                    .as_ref()
1810                    .map(|basis| format!("{}×{}", basis.nrows(), basis.ncols())),
1811            )
1812            .field("op_dim", &self.op.as_ref().map(|op| op.dim()))
1813            .field("info", &self.info)
1814            .finish()
1815    }
1816}
1817
1818#[derive(Debug, Clone)]
1819pub struct FilteredPenalties {
1820    pub active: Vec<ActivePenalty>,
1821    pub dropped: Vec<DroppedPenaltyInfo>,
1822}
1823
1824/// A positive-semidefinite quadratic with a construction witness.
1825///
1826/// `factor` is the authoritative representation: for coefficients `β`, the
1827/// penalty is `‖factor · β‖²`, hence its dense matrix is
1828/// `factorᵀ factor` by construction.  The cached dense matrix exists only for
1829/// consumers that require it; rank/null-space logic must use the factor and
1830/// must never attempt to recover PSD provenance from signed eigenvalues of a
1831/// rounded dense congruence (#2318).
1832#[derive(Clone)]
1833pub struct ConstructiveQuadratic {
1834    factor: Array2<f64>,
1835    matrix: Array2<f64>,
1836}
1837
1838impl ConstructiveQuadratic {
1839    /// Construct directly from an energy factor `A`, representing `AᵀA`.
1840    pub fn from_energy_factor(
1841        factor: Array2<f64>,
1842        context: &str,
1843    ) -> Result<Self, BasisError> {
1844        if factor.iter().any(|value| !value.is_finite()) {
1845            crate::bail_invalid_basis!(
1846                "{context}: constructive penalty factor contains a non-finite value"
1847            );
1848        }
1849        let matrix = fast_ata(&factor);
1850        if matrix.iter().any(|value| !value.is_finite()) {
1851            crate::bail_invalid_basis!(
1852                "{context}: constructive penalty Gram is not representable"
1853            );
1854        }
1855        Ok(Self { factor, matrix })
1856    }
1857
1858    /// Checked bridge for legacy dense factories that already produce a PSD
1859    /// function quadratic but do not yet expose their native energy factor.
1860    ///
1861    /// This is deliberately fallible and reconstructs a factor from the
1862    /// canonical range spectrum. Material negative curvature is rejected; a
1863    /// caller can no longer place an unchecked `Array2` in a
1864    /// [`PenaltyCandidate`]. New factories should use
1865    /// [`Self::from_energy_factor`] so PSD is true by construction rather than
1866    /// inferred after dense assembly.
1867    pub fn try_from_dense_psd(
1868        dense: Array2<f64>,
1869        context: &str,
1870    ) -> Result<Self, BasisError> {
1871        if dense.nrows() != dense.ncols() {
1872            crate::bail_dim_basis!(
1873                "{context}: dense penalty must be square, got {}x{}",
1874                dense.nrows(),
1875                dense.ncols()
1876            );
1877        }
1878        if dense.iter().any(|value| !value.is_finite()) {
1879            crate::bail_invalid_basis!("{context}: dense penalty contains a non-finite value");
1880        }
1881        if dense.nrows() == 0 {
1882            return Self::from_energy_factor(Array2::zeros((0, 0)), context);
1883        }
1884        let sym = symmetrize_penalty(&dense);
1885        let (evals, evecs) = FaerEigh::eigh(&sym, Side::Lower)
1886            .map_err(BasisError::LinalgError)?;
1887        let tolerance = spectral_tolerance(&sym, &evals);
1888        if let Some(&negative) = evals.iter().find(|&&value| value < -tolerance) {
1889            return Err(BasisError::IndefinitePenalty {
1890                context: context.to_string(),
1891                min_eigenvalue: negative,
1892                tolerance,
1893                guidance: "supply the native energy factor for a PSD function penalty; negative curvature is not a penalty null direction".to_string(),
1894            });
1895        }
1896        let positive: Vec<usize> = evals
1897            .iter()
1898            .enumerate()
1899            .filter_map(|(index, &value)| (value > tolerance).then_some(index))
1900            .collect();
1901        let mut factor = Array2::<f64>::zeros((positive.len(), dense.nrows()));
1902        for (row, index) in positive.into_iter().enumerate() {
1903            let scale = evals[index].sqrt();
1904            for column in 0..dense.nrows() {
1905                factor[[row, column]] = scale * evecs[[column, index]];
1906            }
1907        }
1908        Self::from_energy_factor(factor, context)
1909    }
1910
1911    /// The authoritative rectangular energy factor.
1912    pub fn factor(&self) -> &Array2<f64> {
1913        &self.factor
1914    }
1915
1916    /// Dense materialization `AᵀA` for consumers that require a matrix.
1917    pub fn dense(&self) -> &Array2<f64> {
1918        &self.matrix
1919    }
1920
1921    /// Consume this quadratic and return its dense materialization.
1922    pub fn into_dense(self) -> Array2<f64> {
1923        self.matrix
1924    }
1925
1926    /// Apply a coefficient gauge to the factor, preserving PSD by
1927    /// construction instead of multiplying the rounded dense Gram twice.
1928    pub fn restricted(
1929        &self,
1930        gauge: &gam_problem::Gauge,
1931        context: &str,
1932    ) -> Result<Self, BasisError> {
1933        Self::from_energy_factor(gauge.restrict_quadratic_factor(&self.factor), context)
1934    }
1935
1936    /// Multiply the represented quadratic by a finite non-negative scalar.
1937    pub fn scaled(&self, scale: f64, context: &str) -> Result<Self, BasisError> {
1938        if !scale.is_finite() || scale < 0.0 {
1939            crate::bail_invalid_basis!(
1940                "{context}: constructive penalty scale must be finite and non-negative, got {scale}"
1941            );
1942        }
1943        let root = scale.sqrt();
1944        Self::from_energy_factor(self.factor.mapv(|value| value * root), context)
1945    }
1946
1947    /// Sum PSD quadratics by vertically concatenating their energy factors.
1948    pub fn sum(terms: &[Self], context: &str) -> Result<Self, BasisError> {
1949        let coefficient_dim = terms
1950            .first()
1951            .map(|term| term.factor.ncols())
1952            .unwrap_or(0);
1953        if terms
1954            .iter()
1955            .any(|term| term.factor.ncols() != coefficient_dim)
1956        {
1957            crate::bail_dim_basis!(
1958                "{context}: constructive penalty sum has inconsistent coefficient dimensions"
1959            );
1960        }
1961        let rows = terms.iter().map(|term| term.factor.nrows()).sum();
1962        let mut factor = Array2::<f64>::zeros((rows, coefficient_dim));
1963        let mut start = 0usize;
1964        for term in terms {
1965            let end = start + term.factor.nrows();
1966            factor.slice_mut(s![start..end, ..]).assign(&term.factor);
1967            start = end;
1968        }
1969        Self::from_energy_factor(factor, context)
1970    }
1971
1972    /// The exact zero quadratic on a coefficient chart of `dimension`.
1973    pub fn zero(dimension: usize) -> Self {
1974        Self {
1975            factor: Array2::zeros((0, dimension)),
1976            matrix: Array2::zeros((dimension, dimension)),
1977        }
1978    }
1979}
1980
1981impl std::fmt::Debug for ConstructiveQuadratic {
1982    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1983        f.debug_struct("ConstructiveQuadratic")
1984            .field(
1985                "factor",
1986                &format_args!("{}×{}", self.factor.nrows(), self.factor.ncols()),
1987            )
1988            .field(
1989                "matrix",
1990                &format_args!("{}×{}", self.matrix.nrows(), self.matrix.ncols()),
1991            )
1992            .finish()
1993    }
1994}
1995
1996impl std::ops::Deref for ConstructiveQuadratic {
1997    type Target = Array2<f64>;
1998
1999    fn deref(&self) -> &Self::Target {
2000        &self.matrix
2001    }
2002}
2003
2004#[derive(Clone)]
2005pub struct PenaltyCandidate {
2006    /// Constructive PSD quadratic. Raw dense matrices cannot inhabit a
2007    /// candidate without passing through a checked constructor.
2008    pub matrix: ConstructiveQuadratic,
2009    pub source: PenaltySource,
2010    pub normalization_scale: f64,
2011    /// Optional Kronecker factors whose product equals `matrix`.
2012    /// When present, spectral decomposition can be done per-factor
2013    /// (O(Σ q_j³) instead of O((Π q_j)³)).
2014    pub kronecker_factors: Option<Vec<Array2<f64>>>,
2015    /// Optional operator-form handle whose `as_dense()` matches `matrix`. When
2016    /// populated by the closed-form factories, this is propagated through to
2017    /// `CanonicalPenaltyBlock` so downstream consumers can use exact matvec
2018    /// algebra without rebuilding the dense Gram. When `None`, only the dense
2019    /// `matrix` path is available.
2020    pub op: Option<std::sync::Arc<dyn crate::analytic_penalties::PenaltyOp>>,
2021}
2022
2023impl std::fmt::Debug for PenaltyCandidate {
2024    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2025        f.debug_struct("PenaltyCandidate")
2026            .field(
2027                "matrix",
2028                &format_args!("{}×{}", self.matrix.nrows(), self.matrix.ncols()),
2029            )
2030            .field("source", &self.source)
2031            .field("normalization_scale", &self.normalization_scale)
2032            .field(
2033                "kronecker_factors",
2034                &self.kronecker_factors.as_ref().map(|v| v.len()),
2035            )
2036            .field("op", &self.op.as_ref().map(|o| o.dim()))
2037            .finish()
2038    }
2039}
2040
2041#[derive(Clone)]
2042pub struct CanonicalPenaltyBlock {
2043    pub sym_penalty: Array2<f64>,
2044    /// Eigenvalues from spectral decomposition (retained to avoid recomputation).
2045    pub eigenvalues: Array1<f64>,
2046    /// Eigenvectors from spectral decomposition (retained to avoid recomputation).
2047    pub eigenvectors: Array2<f64>,
2048    pub rank: usize,
2049    pub nullity: usize,
2050    /// Number of genuine negative-curvature eigendirections (`ev < -tol`).
2051    /// A non-PSD penalty has `negative_dim > 0`; these directions are
2052    /// neither range nor null and are never absorbed as unpenalized (#1425).
2053    pub negative_dim: usize,
2054    pub tol: f64,
2055    pub iszero: bool,
2056    /// Optional operator-form handle that is bit-equivalent to `sym_penalty`.
2057    /// Propagated from `PenaltyCandidate.op` when present so downstream
2058    /// consumers can use matvec without rebuilding the dense Gram.
2059    pub op: Option<std::sync::Arc<dyn crate::analytic_penalties::PenaltyOp>>,
2060}
2061
2062impl std::fmt::Debug for CanonicalPenaltyBlock {
2063    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2064        f.debug_struct("CanonicalPenaltyBlock")
2065            .field(
2066                "sym_penalty",
2067                &format_args!("{}×{}", self.sym_penalty.nrows(), self.sym_penalty.ncols()),
2068            )
2069            .field("eigenvalues", &self.eigenvalues)
2070            .field(
2071                "eigenvectors",
2072                &format_args!(
2073                    "{}×{}",
2074                    self.eigenvectors.nrows(),
2075                    self.eigenvectors.ncols()
2076                ),
2077            )
2078            .field("rank", &self.rank)
2079            .field("nullity", &self.nullity)
2080            .field("negative_dim", &self.negative_dim)
2081            .field("tol", &self.tol)
2082            .field("iszero", &self.iszero)
2083            .field("op", &self.op.as_ref().map(|o| o.dim()))
2084            .finish()
2085    }
2086}
2087
2088#[derive(Debug)]
2089pub struct BasisPsiDerivativeResult {
2090    pub design_derivative: Array2<f64>,
2091    pub penalties_derivative: Vec<Array2<f64>>,
2092    /// Operator-backed design derivative for standalone first-derivative
2093    /// callers. Bundled first+second callers receive the shared operator on
2094    /// `BasisPsiDerivativeBundle` instead.
2095    pub implicit_operator: Option<ImplicitDesignPsiDerivative>,
2096}
2097
2098#[derive(Debug)]
2099pub struct BasisPsiSecondDerivativeResult {
2100    pub designsecond_derivative: Array2<f64>,
2101    pub penaltiessecond_derivative: Vec<Array2<f64>>,
2102    /// Operator-backed design derivative for standalone second-derivative
2103    /// callers. Bundled first+second callers receive the shared operator on
2104    /// `BasisPsiDerivativeBundle` instead.
2105    pub implicit_operator: Option<ImplicitDesignPsiDerivative>,
2106}
2107
2108#[derive(Debug)]
2109pub struct BasisPsiDerivativeBundle {
2110    pub first: BasisPsiDerivativeResult,
2111    pub second: BasisPsiSecondDerivativeResult,
2112    /// Shared operator-backed design derivative for the first and second
2113    /// psi derivatives. Bundled callers consume this once instead of storing
2114    /// duplicate materialized/streaming operators in both derivative payloads.
2115    pub implicit_operator: Option<ImplicitDesignPsiDerivative>,
2116}
2117
2118/// Per-axis psi_a derivative package for anisotropic spatial terms.
2119///
2120/// For a d-dimensional anisotropic term, the kernel phi(r) depends on
2121/// the anisotropic distance r = |Lambda h| where Lambda = diag(kappa_a). Each axis a
2122/// has its own log-scale psi_a = log(kappa_a), yielding d first derivatives,
2123/// d diagonal second derivatives, and d*(d-1)/2 cross second derivatives.
2124///
2125/// The cross second derivative d2 phi/(d psi_a d psi_b) = t * s_a * s_b (a != b)
2126/// is rank-1, so we store the t_values and s_components vectors rather
2127/// than materializing d^2 matrices.
2128#[derive(Clone)]
2129pub struct AnisoBasisPsiDerivatives {
2130    /// d matrices, each (n x p_smooth): dX/d psi_a.
2131    pub design_first: Vec<Array2<f64>>,
2132    /// d matrices, each (n x p_smooth): d2X/d psi_a^2 (diagonal second derivatives).
2133    pub design_second_diag: Vec<Array2<f64>>,
2134    /// Cross second derivatives d2X/(d psi_a d psi_b) for a < b.
2135    pub design_second_cross: Vec<Array2<f64>>,
2136    /// Axis-pair indices corresponding to `design_second_cross`.
2137    pub design_second_cross_pairs: Vec<(usize, usize)>,
2138    /// d x num_penalties: dS_m/d psi_a for each axis a and penalty m.
2139    pub penalties_first: Vec<Vec<Array2<f64>>>,
2140    /// d x num_penalties: d2S_m/d psi_a^2 for each axis a and penalty m.
2141    pub penalties_second_diag: Vec<Vec<Array2<f64>>>,
2142    /// The (a, b) axis pairs supported by the on-demand cross-penalty
2143    /// provider. Only the upper triangle (a < b) is stored.
2144    pub penalties_cross_pairs: Vec<(usize, usize)>,
2145    /// On-demand cross-penalty second-derivative provider. Exact anisotropic
2146    /// cross-axis penalty seconds are streamed one pair at a time rather than
2147    /// stored as a dense upper triangle of blocks.
2148    pub penalties_cross_provider: Option<AnisoPenaltyCrossProvider>,
2149    /// Shared operator-backed representation of the anisotropic kernel-side
2150    /// design derivatives. When `design_first` / `design_second_diag` are empty,
2151    /// callers must use this operator directly; when they are present, this
2152    /// operator still provides exact cross-axis second derivatives without
2153    /// duplicating separate `t` / `s_a` storage layouts.
2154    pub implicit_operator: Option<ImplicitDesignPsiDerivative>,
2155}
2156
2157#[derive(Clone)]
2158pub struct AnisoPenaltyCrossProvider(
2159    std::sync::Arc<
2160        dyn Fn(usize, usize) -> Result<Vec<Array2<f64>>, BasisError> + Send + Sync + 'static,
2161    >,
2162);
2163
2164impl AnisoPenaltyCrossProvider {
2165    pub(crate) fn new<F>(f: F) -> Self
2166    where
2167        F: Fn(usize, usize) -> Result<Vec<Array2<f64>>, BasisError> + Send + Sync + 'static,
2168    {
2169        Self(std::sync::Arc::new(f))
2170    }
2171
2172    pub fn evaluate(&self, axis_a: usize, axis_b: usize) -> Result<Vec<Array2<f64>>, BasisError> {
2173        (self.0)(axis_a, axis_b)
2174    }
2175}
2176
2177// ═══════════════════════════════════════════════════════════════════════════
2178//  Implicit derivative operator for scalable anisotropic REML gradients
2179// ═══════════════════════════════════════════════════════════════════════════
2180
2181pub(crate) const SPATIAL_CENTER_CENTER_MAX_BYTES: usize = 512 * 1024 * 1024; // 512 MiB
2182pub(crate) const DESIGN_CROSS_CHUNK_SIZE: usize = 1024;
2183
2184/// Determine whether implicit operators should be used based on problem size
2185/// and the supplied [`ResourcePolicy`].
2186///
2187/// Returns `true` when the dense materialization of D first-derivative
2188/// matrices would exceed `policy.max_single_materialization_bytes`.
2189///
2190/// For D axes with n data points and p_smooth basis columns, the dense path
2191/// allocates D * n * p_smooth * 8 bytes for first-derivative matrices alone
2192/// (plus a similar amount for second derivatives). The implicit path stores
2193/// only the compact (n * n_knots) radial jets plus (n * n_knots * D) axis
2194/// fractions, which is O(n * k * D) instead of O(n * p * D).
2195pub fn should_use_implicit_operators_with_policy(
2196    n: usize,
2197    p: usize,
2198    d: usize,
2199    policy: &gam_runtime::resource::ResourcePolicy,
2200) -> bool {
2201    // Each first-derivative matrix is (n x p) f64 → n*p*8 bytes.
2202    // We need D of them for first derivatives, D for second diag, plus
2203    // the cross-t matrix and s_components. Conservative estimate: 3*D matrices.
2204    let dense_bytes = 3usize
2205        .saturating_mul(n)
2206        .saturating_mul(p)
2207        .saturating_mul(d)
2208        .saturating_mul(8);
2209    dense_bytes > policy.max_single_materialization_bytes
2210}
2211
2212pub(crate) fn implicit_radial_cache_bytes(n: usize, k: usize, n_axes: usize) -> usize {
2213    n.saturating_mul(k)
2214        .saturating_mul(n_axes.saturating_add(3))
2215        .saturating_mul(8)
2216}
2217
2218pub(crate) fn should_cache_implicit_radial_components(
2219    n: usize,
2220    k: usize,
2221    n_axes: usize,
2222    policy: &gam_runtime::resource::ResourcePolicy,
2223) -> bool {
2224    implicit_radial_cache_bytes(n, k, n_axes) <= policy.max_operator_cache_bytes
2225}
2226
2227pub fn assert_no_dense_derivative_materialization(n: usize, p: usize, d_pc: usize) {
2228    let first = dense_design_bytes(n, p).saturating_mul(d_pc);
2229    let second = dense_design_bytes(n, p).saturating_mul(d_pc.saturating_mul(d_pc));
2230    // Consult the library default ResourcePolicy. Production large-scale runs
2231    // configure `AnalyticOperatorRequired`, which still refuses every dense
2232    // materialization here. The default `MaterializeIfSmall` mode lets tiny
2233    // problems (and small-data/test usage) materialize as long as the combined
2234    // first- and second-order dense bytes fit under the single-materialization
2235    // byte budget. `DiagnosticsOnly` is treated like `MaterializeIfSmall` for
2236    // this guard: it permits dense materialization under the same byte cap.
2237    let policy = gam_runtime::resource::ResourcePolicy::default_library();
2238    let budget = policy.max_single_materialization_bytes;
2239    let needed = first.saturating_add(second);
2240    match policy.derivative_storage_mode {
2241        gam_runtime::resource::DerivativeStorageMode::AnalyticOperatorRequired => {
2242            // SAFETY: this assertion helper exists specifically to enforce
2243            // the large-scale invariant that spatial-PC Duchon derivative
2244            // designs never persist as dense `Array2<f64>` storage. When the
2245            // resource policy is `AnalyticOperatorRequired`, any caller that
2246            // reached this point has materialized something the strict
2247            // operator contract forbids.
2248            // SAFETY: AnalyticOperatorRequired forbids dense derivative materialization.
2249            panic!(
2250                "spatial PC Duchon derivative designs must remain operator-backed; refused persistent dense derivative materialization (n={n}, p={p}, d_pc={d_pc}, first_order={:.1} MiB, second_order={:.1} MiB)",
2251                first as f64 / (1024.0 * 1024.0),
2252                second as f64 / (1024.0 * 1024.0),
2253            );
2254        }
2255        gam_runtime::resource::DerivativeStorageMode::MaterializeIfSmall
2256        | gam_runtime::resource::DerivativeStorageMode::DiagnosticsOnly => {
2257            // SAFETY: exceeding the single-materialization budget here is a
2258            // contract violation by an upstream caller that must route through
2259            // the operator-backed path; failing loudly surfaces it rather than
2260            // silently materializing an oversized dense derivative design.
2261            assert!(
2262                needed <= budget,
2263                "spatial PC Duchon derivative designs would exceed the single-materialization budget; refused persistent dense derivative materialization (n={n}, p={p}, d_pc={d_pc}, first_order={:.1} MiB, second_order={:.1} MiB, budget={:.1} MiB)",
2264                first as f64 / (1024.0 * 1024.0),
2265                second as f64 / (1024.0 * 1024.0),
2266                budget as f64 / (1024.0 * 1024.0),
2267            );
2268        }
2269    }
2270}
2271
2272pub fn assert_spatial_centers_below_large_scale_cap(
2273    d_pc: usize,
2274    centers: ArrayView2<'_, f64>,
2275) -> Result<(), BasisError> {
2276    if centers.ncols() != d_pc {
2277        crate::bail_dim_basis!(
2278            "spatial PC center dimension mismatch: centers have {} columns, expected {d_pc}",
2279            centers.ncols()
2280        );
2281    }
2282    let k = centers.nrows();
2283    let centers_bytes = dense_design_bytes(k, d_pc);
2284    let center_center_bytes = dense_design_bytes(k, k);
2285    if centers_bytes > SPATIAL_CENTER_CENTER_MAX_BYTES {
2286        crate::bail_invalid_basis!(
2287            "spatial PC centers exceed center storage cap: K={k}, d_pc={d_pc}, centers={:.1} MiB, cap={:.1} MiB",
2288            centers_bytes as f64 / (1024.0 * 1024.0),
2289            SPATIAL_CENTER_CENTER_MAX_BYTES as f64 / (1024.0 * 1024.0),
2290        );
2291    }
2292    if center_center_bytes > SPATIAL_CENTER_CENTER_MAX_BYTES {
2293        crate::bail_invalid_basis!(
2294            "spatial PC centers exceed center-center large-scale cap: K={k}, d_pc={d_pc}, KxK={:.1} MiB, cap={:.1} MiB",
2295            center_center_bytes as f64 / (1024.0 * 1024.0),
2296            SPATIAL_CENTER_CENTER_MAX_BYTES as f64 / (1024.0 * 1024.0),
2297        );
2298    }
2299    Ok(())
2300}
2301
2302pub(crate) fn dense_design_bytes(n: usize, p: usize) -> usize {
2303    n.saturating_mul(p)
2304        .saturating_mul(std::mem::size_of::<f64>())
2305}
2306
2307pub(crate) fn should_use_lazy_spatial_design(
2308    n: usize,
2309    p: usize,
2310    policy: &gam_runtime::resource::ResourcePolicy,
2311) -> bool {
2312    matches!(
2313        policy.derivative_storage_mode,
2314        gam_runtime::resource::DerivativeStorageMode::AnalyticOperatorRequired
2315    ) || dense_design_bytes(n, p) > policy.max_single_materialization_bytes
2316}
2317
2318pub(crate) fn wrap_dense_design_with_transform(
2319    design: DesignMatrix,
2320    transform: &Array2<f64>,
2321    label: &str,
2322) -> Result<DesignMatrix, BasisError> {
2323    match design {
2324        DesignMatrix::Dense(inner) => {
2325            let op = CoefficientTransformOperator::new(inner, transform.clone()).map_err(|e| {
2326                BasisError::InvalidInput(format!("{label} coefficient transform failed: {e}"))
2327            })?;
2328            Ok(DesignMatrix::Dense(
2329                gam_linalg::matrix::DenseDesignMatrix::from(Arc::new(op)),
2330            ))
2331        }
2332        DesignMatrix::Sparse(_) => Err(BasisError::InvalidInput(format!(
2333            "{label} coefficient transform requires a dense/operator-backed design"
2334        ))),
2335    }
2336}
2337
2338/// Single-pass `(Bᵀ(W·C), BᵀB)` accumulation over the streamed design.
2339///
2340/// Materialises each row chunk of the design **once** and reuses it for both
2341/// the constraint cross `Bᵀ(W·C)` and the Gram `BᵀB`. On the lazy chunked
2342/// spatial path each `try_row_chunk` re-evaluates all kernel columns for the
2343/// chunk, so accumulating both products in a single sweep halves the per-build
2344/// kernel re-evaluation work (the dominant cost at large scale) versus two
2345/// independent streaming passes — without changing the result beyond
2346/// floating-point reassociation. The cross is masked off (`q == 0`) by the
2347/// caller, which never invokes this when there is no constraint block.
2348pub(crate) fn design_cross_and_gram(
2349    design: &DesignMatrix,
2350    constraint_matrix: ArrayView2<'_, f64>,
2351    weights: Option<ArrayView1<'_, f64>>,
2352) -> Result<(Array2<f64>, Array2<f64>), BasisError> {
2353    let n = design.nrows();
2354    let k = design.ncols();
2355    if constraint_matrix.nrows() != n {
2356        return Err(BasisError::ConstraintMatrixRowMismatch {
2357            basisrows: n,
2358            constraintrows: constraint_matrix.nrows(),
2359        });
2360    }
2361    if let Some(w) = weights
2362        && w.len() != n
2363    {
2364        return Err(BasisError::WeightsDimensionMismatch {
2365            expected: n,
2366            found: w.len(),
2367        });
2368    }
2369    let q = constraint_matrix.ncols();
2370    let mut cross = Array2::<f64>::zeros((k, q));
2371    let mut gram = Array2::<f64>::zeros((k, k));
2372    for start in (0..n).step_by(DESIGN_CROSS_CHUNK_SIZE) {
2373        let end = (start + DESIGN_CROSS_CHUNK_SIZE).min(n);
2374        let basis_chunk = design
2375            .try_row_chunk(start..end)
2376            .map_err(|e| BasisError::InvalidInput(e.to_string()))?;
2377        let mut constraint_chunk = constraint_matrix.slice(s![start..end, ..]).to_owned();
2378        if let Some(w) = weights {
2379            for (mut row, &weight) in constraint_chunk
2380                .axis_iter_mut(Axis(0))
2381                .zip(w.slice(s![start..end]).iter())
2382            {
2383                row *= weight;
2384            }
2385        }
2386        cross += &fast_atb(&basis_chunk, &constraint_chunk);
2387        gram += &fast_atb(&basis_chunk, &basis_chunk);
2388    }
2389    Ok((cross, gram))
2390}
2391
2392pub(crate) fn positive_spectral_whitener_from_gram(
2393    gram: &Array2<f64>,
2394) -> Result<Array2<f64>, BasisError> {
2395    // Inverse-square-root for the positive part of `gram`. Eigenvalues at or
2396    // below the relative rank tolerance `α·ε·n·max_eval` are *dropped*: the
2397    // returned whitener has shape `(n × keep)` where `keep` counts strictly
2398    // positive eigendirections of `gram`.
2399    //
2400    // Dropping (rather than ridging) is what makes the result a true
2401    // square-root inverse on the column space of `gram`. This whitener is
2402    // used by `stabilized_orthogonality_transform_from_gram` to make a
2403    // pre-existing transform `K_raw` orthonormal under the W-inner product:
2404    // when some columns of `K_raw` map to zero (or near-zero) under `B`, the
2405    // constrained Gram `K_raw^T G K_raw` is rank-deficient. Ridging those
2406    // tail directions with `1/sqrt(ε)` produced spurious basis columns
2407    // whose coefficient norms blew up to `~1/sqrt(ε)` while their image in
2408    // `B` was floating-point zero, contaminating downstream linear algebra
2409    // (in particular it forced `smooth.rs` to widen the post-transform
2410    // orthogonality residual tolerance to absorb a `cond ≈ 1/sqrt(ε)`
2411    // rounding floor). Dropping these directions is the right behavior:
2412    // they contribute nothing to `B`'s column space, and removing them
2413    // tightens the orthogonality residual back down to the genuine
2414    // floating-point limit.
2415    let (eigenvalues, eigenvectors) = gram.eigh(Side::Lower).map_err(BasisError::LinalgError)?;
2416    let n = gram.nrows();
2417    let max_eval = eigenvalues.iter().copied().fold(0.0_f64, f64::max);
2418    // Scale-invariant rank tolerance: the cutoff must track the Gram's own
2419    // spectrum (`α·ε·n·max_eval`), not an absolute floor. An earlier `max_eval
2420    // .max(1.0)` clamped the reference scale to 1.0, which is only harmless when
2421    // `max_eval ≥ 1`; for a genuinely well-conditioned but small-magnitude Gram
2422    // (e.g. a Duchon hybrid whose evaluated kernel sits far below unit scale in
2423    // moderate-to-high d) it inflated the tolerance to an absolute `α·ε·n` floor
2424    // that swallows the entire — perfectly valid — spectrum, spuriously reporting
2425    // `keep == 0`. Using the true `max_eval` makes `keep` invariant to a uniform
2426    // rescaling of the Gram (which scales every eigenvalue and the cutoff
2427    // identically). The residual `.max(f64::EPSILON)` only guards the degenerate
2428    // all-zero Gram so that numerical-zero roundoff directions are still dropped.
2429    let tol =
2430        (default_rrqr_rank_alpha() * f64::EPSILON * (n.max(1) as f64) * max_eval).max(f64::EPSILON);
2431    let keep = eigenvalues.iter().filter(|&&ev| ev > tol).count();
2432    if keep == 0 {
2433        let min_ev = eigenvalues.iter().copied().fold(f64::INFINITY, f64::min);
2434        return Err(BasisError::ConstraintNullspaceCollapsed {
2435            site: "positive_spectral_whitener_from_gram",
2436            cross_rank: 0,
2437            coeff_dim: gram.nrows(),
2438            cross_frobenius: gram.iter().map(|v| v * v).sum::<f64>().sqrt(),
2439            gram_spectrum: format!(
2440                "max eigenvalue {max_eval:.3e} (min {min_ev:.3e}, spectral tolerance {tol:.3e})"
2441            ),
2442        });
2443    }
2444    // `eigh` returns eigenvalues in ascending order, so the largest `keep`
2445    // eigenvalues live at the tail.
2446    let eig_start = eigenvalues.len() - keep;
2447    let kept_vectors = eigenvectors.slice(s![.., eig_start..]).to_owned();
2448    let mut inv_sqrt = Array2::<f64>::zeros((keep, keep));
2449    for (out_i, eig_i) in (eig_start..eigenvalues.len()).enumerate() {
2450        inv_sqrt[[out_i, out_i]] = 1.0 / eigenvalues[eig_i].sqrt();
2451    }
2452    Ok(fast_ab(&kept_vectors, &inv_sqrt))
2453}
2454
2455pub(crate) fn stabilized_orthogonality_transform_from_gram(
2456    gram: &Array2<f64>,
2457    transform: &Array2<f64>,
2458) -> Result<Array2<f64>, BasisError> {
2459    let constrained_gram = {
2460        let gt = fast_ab(gram, transform);
2461        fast_atb(transform, &gt)
2462    };
2463    let whitening = positive_spectral_whitener_from_gram(&constrained_gram)?;
2464    Ok(fast_ab(transform, &whitening))
2465}
2466
2467pub(crate) fn orthogonality_transform_from_cross_and_gram(
2468    constraint_cross: &Array2<f64>,
2469    gram: &Array2<f64>,
2470) -> Result<Array2<f64>, BasisError> {
2471    // Compute null(M^T) directly on M = B^T W C (k × q) via column-pivoted QR.
2472    // Working in the original k-dim coefficient space rather than first
2473    // whitening by B^T B avoids a fundamental failure mode: when B is heavily
2474    // collinear, `positive_spectral_whitener_from_gram` truncates the design
2475    // column-space to a `keep`-dim subspace, and if `keep <= q` the subsequent
2476    // nullspace search has no room — even though dim null(M^T) = k - rank(M)
2477    // ≥ k - q is always positive when k > q. The constraint nullspace is a
2478    // property of M alone; conditioning of the design only matters for the
2479    // downstream stabilization of B*K_raw.
2480    let k = constraint_cross.nrows();
2481    if k == 0 {
2482        return Err(BasisError::InsufficientColumnsForConstraint { found: 0 });
2483    }
2484    let (transform_raw, rank) = rrqr_nullspace_basis(constraint_cross, default_rrqr_rank_alpha())
2485        .map_err(BasisError::LinalgError)?;
2486    if rank >= k || transform_raw.ncols() == 0 {
2487        return Err(BasisError::ConstraintNullspaceCollapsed {
2488            site: "orthogonality_transform_from_cross_and_gram",
2489            cross_rank: rank,
2490            coeff_dim: k,
2491            cross_frobenius: constraint_cross.iter().map(|v| v * v).sum::<f64>().sqrt(),
2492            gram_spectrum: "not computed (structural cross-rank collapse: null(Mᵀ) is empty, \
2493                            so no constrained design exists to eigendecompose)"
2494                .to_string(),
2495        });
2496    }
2497
2498    // Make the constrained design B*K_raw orthonormal under the W-inner product.
2499    // If the constrained Gram K_raw^T G K_raw is rank-deficient (because some
2500    // directions in null(M^T) collapse under B), the spectral whitener drops
2501    // them — that is the right behavior: a degenerate column never contributes
2502    // to B's column space and shouldn't appear in the reparameterized basis.
2503    stabilized_orthogonality_transform_from_gram(gram, &transform_raw)
2504}
2505
2506pub fn orthogonality_transform_for_design(
2507    design: &DesignMatrix,
2508    constraint_matrix: ArrayView2<'_, f64>,
2509    weights: Option<ArrayView1<'_, f64>>,
2510) -> Result<Array2<f64>, BasisError> {
2511    let k = design.ncols();
2512    if k == 0 {
2513        return Err(BasisError::InsufficientColumnsForConstraint { found: 0 });
2514    }
2515    let q = constraint_matrix.ncols();
2516    if q == 0 {
2517        return Ok(Array2::eye(k));
2518    }
2519    // Scale every constraint column to unit (weighted) L2 norm before forming the
2520    // design/constraint cross `M = Bᵀ W C`. The downstream rank detection
2521    // (`rrqr_nullspace_basis`) decides HOW MANY parametric directions the smooth
2522    // genuinely spans by testing the pivoted magnitudes of `M` against an
2523    // essentially absolute floor `α·ε·max(k,q)` (the `max(|R₀₀|, 1)` reference
2524    // clamps to 1 whenever the cross is sub-unit). With a RAW constraint column
2525    // that floor is scale-wrong: the all-ones intercept has norm √n, so `M`
2526    // carries a √n factor while the tolerance is referenced to 1. For a
2527    // kernel/radial smooth whose realized design is already (numerically)
2528    // orthogonal to the constant, `‖Bᵀ1‖` is pure floating-point roundoff
2529    // (~ε·‖B‖·√n); the √n inflation lands it right at the floor, so a rigid
2530    // rotation of the covariates — which only perturbs that roundoff — flips the
2531    // detected rank between 0 and 1. A spurious rank 1 then removes an ARBITRARY
2532    // real smooth direction (the pivot of a noise vector), and the fitted
2533    // surface, its EDF, and the REML-selected λ all drift under rotation
2534    // (gam#1818). Measuring the design's overlap with UNIT constraint directions
2535    // turns the test into a genuine rotation-invariant cosine: a real overlap is
2536    // O(1) and always detected, while roundoff-level overlap stays consistently
2537    // below the floor (rank 0). Column scaling of `C` leaves `null(Mᵀ)` — hence
2538    // the constrained-design span and the emitted transform — unchanged wherever
2539    // the rank is unchanged; it only removes the roundoff-driven rank flip.
2540    let normalized_constraint = unit_normalize_constraint_columns(constraint_matrix, weights);
2541    let (constraint_cross, gram) =
2542        design_cross_and_gram(design, normalized_constraint.view(), weights)?;
2543    orthogonality_transform_from_cross_and_gram(&constraint_cross, &gram)
2544}
2545
2546/// Scale each column of a constraint block to unit L2 norm under the inner
2547/// product used to form the identifiability cross — the `weights`-weighted
2548/// product when `Some`, the plain product otherwise. A column that is already
2549/// numerically zero (norm 0 or non-finite) is left untouched: its cross entries
2550/// are zero regardless, so it contributes no rank. The returned owned copy is
2551/// used only to build the cross; the emitted transform and the realized
2552/// constrained design are unaffected (column scaling of `C` preserves
2553/// `null(Mᵀ)`).
2554fn unit_normalize_constraint_columns(
2555    constraint_matrix: ArrayView2<'_, f64>,
2556    weights: Option<ArrayView1<'_, f64>>,
2557) -> Array2<f64> {
2558    let mut c = constraint_matrix.to_owned();
2559    let (n, q) = c.dim();
2560    for col in 0..q {
2561        let mut norm_sq = 0.0_f64;
2562        for row in 0..n {
2563            let v = c[[row, col]];
2564            let w = weights.map_or(1.0, |ws| ws[row]);
2565            norm_sq += w * v * v;
2566        }
2567        let norm = norm_sq.sqrt();
2568        if norm > 0.0 && norm.is_finite() {
2569            let inv = 1.0 / norm;
2570            for row in 0..n {
2571                c[[row, col]] *= inv;
2572            }
2573        }
2574    }
2575    c
2576}
2577
2578#[cfg(test)]
2579mod saturation_escalation_tests {
2580    use super::*;
2581
2582    #[test]
2583    fn starting_count_is_a_supported_low_rank_pilot_capped_by_default() {
2584        assert_eq!(starting_num_centers(800, 2), 30);
2585        assert_eq!(starting_num_centers(100_000, 1), 10);
2586        // The generic conditioning ceiling is `n / 4` and therefore reports
2587        // zero below four rows; the pilot retains the basis-wide one-center
2588        // degenerate minimum, which materialization subsequently raises to the
2589        // exact polynomial floor for the requested family.
2590        assert_eq!(starting_num_centers(3, 5), 1);
2591        assert_eq!(starting_num_centers(1, 2), 1);
2592    }
2593
2594    #[test]
2595    fn saturated_expansion_doubles_then_pins_at_validated_ceiling() {
2596        assert_eq!(expanded_num_centers(30, 157), Some(60));
2597        assert_eq!(expanded_num_centers(120, 157), Some(157));
2598        assert_eq!(expanded_num_centers(157, 157), None);
2599        assert_eq!(
2600            expanded_num_centers(usize::MAX - 1, usize::MAX),
2601            Some(usize::MAX)
2602        );
2603    }
2604
2605    #[test]
2606    fn saturation_excludes_the_nullspace_and_tracks_edf() {
2607        let tol = 1e-4;
2608        // Total term EDF includes the three-dimensional nullspace. Saturation
2609        // means its penalized component spends all 97 remaining directions.
2610        assert!(basis_is_saturated(100.0, 100, 3, tol));
2611        // Half-used basis is NOT saturated.
2612        assert!(!basis_is_saturated(48.5, 100, 3, tol));
2613        // Just below capacity by more than the derived margin: not saturated.
2614        assert!(!basis_is_saturated(90.0, 100, 3, tol));
2615        // A block whose null space already exhausts its columns has no penalizable
2616        // capacity and is never saturated.
2617        assert!(!basis_is_saturated(3.0, 3, 3, tol));
2618        assert!(!basis_is_saturated(f64::NAN, 100, 3, tol));
2619    }
2620
2621    #[test]
2622    fn saturation_is_monotone_in_edf() {
2623        let tol = 1e-3;
2624        let (k, null) = (60usize, 3usize);
2625        let full_width = k as f64;
2626        // Once saturated at some edf, any larger edf stays saturated.
2627        let mut first_true: Option<f64> = None;
2628        let mut e = full_width - 5.0;
2629        while e <= full_width {
2630            let sat = basis_is_saturated(e, k, null, tol);
2631            if sat && first_true.is_none() {
2632                first_true = Some(e);
2633            }
2634            if let Some(t) = first_true {
2635                assert!(
2636                    basis_is_saturated(e.max(t), k, null, tol),
2637                    "saturation must not flip back to false as edf grows"
2638                );
2639            }
2640            e += 0.25;
2641        }
2642        assert!(first_true.is_some(), "edf reaching capacity must saturate");
2643    }
2644}