Skip to main content

gam_terms/inference/
smooth_test.rs

1//! Wood-style smooth-component Wald tests.
2//!
3//! The test follows the rank-truncated covariance inverse used by Wood (2013):
4//! the term's coefficient block is mapped into fitted-value space by the
5//! design-whitening `R` (`RᵀR = X'WX`) and tested with a rank-`round(edf)`
6//! spectral pseudo-inverse of the whitened covariance `R·V·Rᵀ`. The whitening
7//! is essential — truncating the raw coefficient covariance keeps the
8//! largest-variance (heavily-penalized, signal-free) directions and discards
9//! the fitted function; whitening restores the generalized `(V, X'WX)`
10//! eigenbasis whose leading directions are the least-penalized modes that carry
11//! the fit (issue #2142). The reference degrees of freedom use the
12//! coefficient-space influence block `F_jj = (H⁻¹ X'WX)_jj`.
13//!
14//! Bartlett and Lawley mean corrections are likelihood-ratio corrections, so
15//! they are not applied here. In the ordinary unpenalized Gaussian model the
16//! Wald statistic satisfies `T / q ~ F(q, ν)` exactly, while under a ridge
17//! penalty even the one-parameter statistic becomes `(n / (n + λ))χ²₁` rather
18//! than a central χ²/F reference target.
19
20use gam_linalg::faer_ndarray::FaerEigh;
21use ndarray::{Array1, Array2, ArrayView1, s};
22use statrs::distribution::{ChiSquared, ContinuousCDF, FisherSnedecor};
23use std::ops::Range;
24
25/// Whether the residual dispersion `φ` is known or estimated from the
26/// fit.  Selects the reference distribution for the Wald p-value: `Known`
27/// → `χ²_{ref_df}` (e.g. binomial/Poisson), `Estimated` → `F_{ref_df,
28/// residual_df}` (e.g. Gaussian where `φ̂` carries its own sampling
29/// variability).
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum SmoothTestScale {
32    Known,
33    Estimated,
34}
35
36/// Inputs to `wood_smooth_test`. `beta` is the full coefficient vector;
37/// the term block being tested is `beta[coeff_range]`. `covariance` is the
38/// matching posterior covariance Σ̂ (full p×p; the diagonal block is sliced
39/// out). **`covariance` must be the scale-included posterior covariance**
40/// (mgcv `Vb`/`Vp`, i.e. `H⁻¹` already multiplied by the dispersion `φ̂`),
41/// so the Wald statistic `T = β̂'·Σ̂⁻·β̂` is dimensionless — the residual
42/// dispersion has already been divided out and the F-statistic is `T/ref_df`
43/// with *no* further `φ̂` factor. `influence_matrix` is the optional
44/// coefficient-space influence `F = H⁻¹ X'WX`; when present
45/// `tr(F_jj)² / tr(F_jj²)` is used as the Wood-corrected reference d.f.
46/// `whitening_gram` is the optional term-block-aligned weighted design Gram
47/// `G = X'WX` (`H − S(λ)`, full `p×p`, same coefficient layout as
48/// `covariance`); when present the covariance is mapped into the Wood (2013)
49/// *fitted-value* space `R·V·Rᵀ` (`RᵀR = G`) before the rank-`r` truncation, so
50/// the pseudo-inverse keeps the directions that carry the estimated function
51/// rather than the raw largest-variance (heavily-penalized) coefficient
52/// directions. When absent the raw coefficient covariance is truncated directly
53/// — a graceful fallback for persisted models whose Gram was not serialized.
54/// `edf` is the smooth's effective d.f. (rank of the truncated pseudo-inverse);
55/// `nullspace_dim` is the fixed-effect (unpenalized) leading dimension within
56/// the block, used as a floor on the truncation rank (those directions are
57/// never shrunk and must always be tested). `residual_df` is the denominator
58/// d.f. for the `Estimated`-scale F branch.
59#[derive(Debug, Clone)]
60pub struct SmoothTestInput<'a> {
61    pub beta: ArrayView1<'a, f64>,
62    pub covariance: &'a Array2<f64>,
63    pub influence_matrix: Option<&'a Array2<f64>>,
64    pub whitening_gram: Option<&'a Array2<f64>>,
65    pub coeff_range: Range<usize>,
66    pub edf: f64,
67    pub nullspace_dim: usize,
68    pub residual_df: f64,
69    pub scale: SmoothTestScale,
70}
71
72/// Output of `wood_smooth_test`: the Wald statistic
73/// `T = f̂ᵀ·Vf⁻ᵣ·f̂` (rank-`r` truncated pseudo-inverse of the design-whitened
74/// covariance `Vf = R·V·Rᵀ`), the reference d.f. used to compute the tail
75/// probability, and the resulting `p_value` (clamped to `[0,1]`).
76#[derive(Debug, Clone)]
77pub struct SmoothTestResult {
78    pub statistic: f64,
79    pub ref_df: f64,
80    pub p_value: f64,
81}
82
83/// Wood (2013) rank-truncated Wald smooth-component test.
84///
85/// Maps the term block `beta[coeff_range]` (and its posterior covariance
86/// subblock) into the fitted-value space `f = R·β` — where `RᵀR = G` is the
87/// term's weighted design Gram `G = X'WX` supplied in `whitening_gram` — and
88/// tests it with the rank-`r` spectral pseudo-inverse of the whitened
89/// covariance `Vf = R·V·Rᵀ`, `r = round(edf)` (floored at `nullspace_dim` and
90/// at 1). The statistic `T = f̂ᵀ·Vf⁻ᵣ·f̂` is compared against `χ²_{ref_df}`
91/// when the scale is `Known`, or `F = T/ref_df` against
92/// `F_{ref_df, residual_df}` when `Estimated`.
93///
94/// The whitening is the crux of Wood (2013): the raw coefficient covariance `V`
95/// orders its eigen-directions by *coefficient* variance, which for a genuinely
96/// wiggly smooth places the estimated signal in the small-variance
97/// best-determined directions — so truncating `V` directly and keeping its
98/// *largest* eigenvalues discards exactly the fitted function and reports a
99/// dominant term as non-significant (issue #2142). Whitening by the design Gram
100/// restores the generalized eigenbasis of `(V, G)`, in which the largest
101/// whitened-variance directions are the least-penalized modes that carry the
102/// fit; the rank-`r` truncation then keeps the signal. The statistic is
103/// invariant to any uniform rescaling of `G`, so whether the Gram carries the
104/// dispersion `φ̂` is irrelevant. When `whitening_gram` is `None` the raw
105/// covariance is truncated unchanged (graceful fallback for persisted models
106/// whose Gram was dropped).
107///
108/// Because `covariance` is the scale-included posterior covariance, `T`
109/// already has the dispersion `φ̂` divided out (it is a proper Wald χ²);
110/// the estimated-scale F-statistic is therefore `T/ref_df` with no extra
111/// `φ̂` factor. Dividing by `φ̂` a second time — the historical defect
112/// fixed in issue #675 — makes the p-value scale as `1/φ̂` and so depend on
113/// the units of the response. Returns `None` on degenerate inputs (empty
114/// block, non-finite EDF, non-finite stat, or non-positive residual d.f.
115/// in the F branch).
116pub fn wood_smooth_test(input: SmoothTestInput<'_>) -> Option<SmoothTestResult> {
117    let start = input.coeff_range.start;
118    let end = input.coeff_range.end;
119    if start >= end
120        || end > input.beta.len()
121        || end > input.covariance.nrows()
122        || end > input.covariance.ncols()
123        || !input.edf.is_finite()
124        || input.edf <= 0.0
125    {
126        return None;
127    }
128    let k = end - start;
129    let beta = input.beta.slice(s![start..end]).to_owned();
130    let cov = block(input.covariance, start, end)?;
131    let null_dim = input.nullspace_dim.min(k);
132
133    // Two regimes, selected by whether the design Gram is supplied:
134    //
135    //   * With `whitening_gram` (the `summary()` paths): the genuine Wood (2013)
136    //     test. Map `(β, V)` into fitted-value space `(R·β, R·V·Rᵀ)`
137    //     (`RᵀR = X'WX`) and take a single rank-`round(edf)` truncated
138    //     pseudo-inverse of the whitened covariance. The unpenalized null-space
139    //     directions carry the *largest* whitened variance, so the top-`round(edf)`
140    //     cut keeps them automatically (edf ≥ null_dim structurally); the floor
141    //     at `null_dim` and at 1 only guards rounding / boundary degeneracy.
142    //   * Without it (persisted models, ANOVA-binding / multinomial callers whose
143    //     covariance is already in a projected frame): the legacy null/penalized
144    //     split on the raw covariance — a full-rank quadratic over the leading
145    //     `null_dim` unpenalized coordinates plus a rank-`round(edf − null_dim)`
146    //     truncation of the trailing penalized block. Preserved byte-for-byte so
147    //     no non-summary caller shifts.
148    //
149    // `rank_used` (returned by both) is the number of covariance directions
150    // actually summed; it can fall below the requested rank on a rank-deficient
151    // block. The χ²/F reference d.f. is floored at it so a boundary-shrunk term
152    // (whose Wood influence-trace d.f. collapses toward 0) is never judged
153    // against a degenerate ~0-d.f. reference — the mechanism that turned a *zero*
154    // Wald statistic into p≈0 for a term the fit removed (#1360).
155    let (statistic, rank_used) = match input
156        .whitening_gram
157        .and_then(|g| block(g, start, end))
158        .and_then(|g| whiten_to_fitted_space(&beta, &cov, &g))
159    {
160        Some((beta_w, cov_w)) => {
161            let rank = (input.edf.round() as usize)
162                .max(null_dim)
163                .clamp(1, cov_w.nrows());
164            truncated_quadratic(&beta_w, &cov_w, rank)?
165        }
166        None => legacy_split_quadratic(&beta, &cov, null_dim, input.edf)?,
167    };
168
169    if rank_used == 0 {
170        // No estimable direction in the block (every covariance eigenmode is
171        // numerically null): the term carries no testable signal.
172        return None;
173    }
174    // Wood (2013) influence-trace participation d.f. when available, but never
175    // below `rank_used`. The historical fallback to `edf` collapsed to ~0 for a
176    // shrunk term, making `χ²_{ref_df→0}` degenerate.
177    let ref_df = match reference_df(input.influence_matrix, start, end) {
178        Some(rd) if rd.is_finite() && rd > 0.0 => rd.max(rank_used as f64),
179        _ => rank_used as f64,
180    };
181    if !statistic.is_finite() || statistic < 0.0 || !ref_df.is_finite() || ref_df <= 0.0 {
182        return None;
183    }
184    let p_value = match input.scale {
185        SmoothTestScale::Known => {
186            let dist = ChiSquared::new(ref_df).ok()?;
187            1.0 - dist.cdf(statistic)
188        }
189        SmoothTestScale::Estimated => {
190            if !input.residual_df.is_finite() || input.residual_df <= 0.0 {
191                return None;
192            }
193            // `statistic` is already a dispersion-free Wald χ² (the covariance
194            // is scale-included), so the estimated-scale F-statistic is the
195            // χ² divided by its reference d.f. only — mgcv's `Tr/rank`. Dividing
196            // by `φ̂` again would re-introduce a response-unit dependence (#675).
197            let f_stat = statistic / ref_df;
198            let dist = FisherSnedecor::new(ref_df, input.residual_df).ok()?;
199            1.0 - dist.cdf(f_stat)
200        }
201    };
202    if !p_value.is_finite() {
203        return None;
204    }
205    Some(SmoothTestResult {
206        statistic,
207        ref_df,
208        p_value: p_value.clamp(0.0, 1.0),
209    })
210}
211
212fn block(matrix: &Array2<f64>, start: usize, end: usize) -> Option<Array2<f64>> {
213    if start >= end || end > matrix.nrows() || end > matrix.ncols() {
214        return None;
215    }
216    Some(matrix.slice(s![start..end, start..end]).to_owned())
217}
218
219/// Legacy raw-covariance smooth test used when no design Gram is available:
220/// a full-rank quadratic over the leading `null_dim` unpenalized coordinates
221/// plus a rank-`round(edf − null_dim)` truncation of the trailing penalized
222/// block, both on the raw coefficient covariance. Returns the summed statistic
223/// and the total number of covariance directions actually used. This is a
224/// reparameterization-*dependent* approximation of Wood (2013) — the whitened
225/// path supersedes it — but it is retained bit-for-bit for the ANOVA-binding,
226/// multinomial and persisted-model callers that never carry `X'WX`.
227fn legacy_split_quadratic(
228    beta: &Array1<f64>,
229    cov: &Array2<f64>,
230    null_dim: usize,
231    edf: f64,
232) -> Option<(f64, usize)> {
233    let k = beta.len();
234    let null_dim = null_dim.min(k);
235    let pen_dim = k.saturating_sub(null_dim);
236    let mut statistic = 0.0;
237    let mut rank_used = 0usize;
238    if null_dim > 0 {
239        let beta_null = beta.slice(s![0..null_dim]).to_owned();
240        let cov_null = cov.slice(s![0..null_dim, 0..null_dim]).to_owned();
241        let (q, used) = truncated_quadratic(&beta_null, &cov_null, null_dim)?;
242        statistic += q;
243        rank_used += used;
244    }
245    if pen_dim > 0 {
246        let beta_pen = beta.slice(s![null_dim..k]).to_owned();
247        let cov_pen = cov.slice(s![null_dim..k, null_dim..k]).to_owned();
248        let rank = truncated_rank(edf - null_dim as f64, pen_dim);
249        if rank > 0 {
250            let (q, used) = truncated_quadratic(&beta_pen, &cov_pen, rank)?;
251            statistic += q;
252            rank_used += used;
253        }
254    }
255    Some((statistic, rank_used))
256}
257
258fn truncated_rank(edf_pen: f64, pen_dim: usize) -> usize {
259    if pen_dim == 0 || !edf_pen.is_finite() || edf_pen <= 0.0 {
260        return 0;
261    }
262    (edf_pen.round() as usize).clamp(1, pen_dim)
263}
264
265/// Map a term's coefficient-space `(β, V)` into its Wood (2013) fitted-value
266/// space using the weighted design Gram `G = X'WX` (`G = RᵀR`). Returns
267/// `(R·β, R·V·Rᵀ)`, where `R` has one row `√μ_i · u_iᵀ` per eigenpair
268/// `(μ_i, u_i)` of `G` whose eigenvalue clears a relative tolerance. A
269/// rank-deficient Gram (degenerate design, collinear tensor margins) therefore
270/// yields a lower-dimensional fitted space rather than a failure; `None` only
271/// when `G` has no positive eigenvalue (no estimable fitted direction) or the
272/// shapes disagree. `R·V·Rᵀ` is symmetrized to absorb round-off so the
273/// downstream eigendecomposition sees an exactly symmetric matrix.
274fn whiten_to_fitted_space(
275    beta: &Array1<f64>,
276    cov: &Array2<f64>,
277    gram: &Array2<f64>,
278) -> Option<(Array1<f64>, Array2<f64>)> {
279    let k = beta.len();
280    if gram.nrows() != k || gram.ncols() != k || cov.nrows() != k || cov.ncols() != k {
281        return None;
282    }
283    let (evals, evecs) = gram.to_owned().eigh(faer::Side::Lower).ok()?;
284    let max_ev = evals
285        .iter()
286        .copied()
287        .fold(0.0_f64, |acc, v| acc.max(v.abs()));
288    if max_ev <= 0.0 {
289        return None;
290    }
291    let tol = max_ev * 1e-10;
292    let rows: Vec<usize> = (0..evals.len()).filter(|&i| evals[i] > tol).collect();
293    if rows.is_empty() {
294        return None;
295    }
296    // R (r×k): row i = √μ_i · u_iᵀ, so RᵀR = Σ μ_i u_i u_iᵀ = G (up to the
297    // dropped near-null modes) and R maps coefficients to fitted-value coords.
298    let mut r_mat = Array2::<f64>::zeros((rows.len(), k));
299    for (ri, &i) in rows.iter().enumerate() {
300        let scale = evals[i].sqrt();
301        let u = evecs.column(i);
302        for j in 0..k {
303            r_mat[[ri, j]] = scale * u[j];
304        }
305    }
306    let beta_w = r_mat.dot(beta);
307    let mut cov_w = r_mat.dot(cov).dot(&r_mat.t());
308    gam_linalg::matrix::symmetrize_in_place(&mut cov_w);
309    Some((beta_w, cov_w))
310}
311
312/// Returns the rank-`rank` truncated Wald quadratic together with the number of
313/// covariance directions (eigenmodes above the relative tolerance) that were
314/// actually summed into it. The `used` count is the *effective rank of the
315/// statistic*: it can fall below `rank` when the covariance subblock is itself
316/// rank-deficient. Callers fold it into the χ² reference degrees of freedom so
317/// the tail probability is never evaluated against a degenerate ~0 d.f.
318fn truncated_quadratic(beta: &Array1<f64>, cov: &Array2<f64>, rank: usize) -> Option<(f64, usize)> {
319    if beta.is_empty() || cov.nrows() != beta.len() || cov.ncols() != beta.len() || rank == 0 {
320        return None;
321    }
322    let (evals, evecs) = cov.to_owned().eigh(faer::Side::Lower).ok()?;
323    let mut order: Vec<usize> = (0..evals.len()).collect();
324    order.sort_by(|&a, &b| evals[b].total_cmp(&evals[a]));
325    let tol = evals
326        .iter()
327        .copied()
328        .fold(0.0_f64, |acc, v| acc.max(v.abs()))
329        * 1e-10;
330    let mut q = 0.0;
331    let mut used = 0usize;
332    for idx in order {
333        let lambda = evals[idx];
334        if lambda <= tol {
335            continue;
336        }
337        let v = evecs.column(idx);
338        let proj = beta.dot(&v);
339        q += proj * proj / lambda;
340        used += 1;
341        if used >= rank {
342            break;
343        }
344    }
345    (used > 0 && q.is_finite()).then_some((q.max(0.0), used))
346}
347
348fn reference_df(influence: Option<&Array2<f64>>, start: usize, end: usize) -> Option<f64> {
349    let f = influence?;
350    let f_block = block(f, start, end)?;
351    let tr = (0..f_block.nrows()).map(|i| f_block[[i, i]]).sum::<f64>();
352    let tr2 = f_block.dot(&f_block).diag().sum();
353    if tr.is_finite() && tr2.is_finite() && tr > 0.0 && tr2 > 0.0 {
354        Some((tr * tr / tr2).max(1e-12))
355    } else {
356        None
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363    use ndarray::array;
364    use statrs::distribution::{ChiSquared, ContinuousCDF};
365
366    #[test]
367    fn reference_df_uses_trace_correction() {
368        let beta = array![1.0, 2.0];
369        let cov = array![[2.0, 0.0], [0.0, 3.0]];
370        let f = array![[0.5, 0.0], [0.0, 0.25]];
371        let out = wood_smooth_test(SmoothTestInput {
372            beta: beta.view(),
373            covariance: &cov,
374            influence_matrix: Some(&f),
375            whitening_gram: None,
376            coeff_range: 0..2,
377            edf: 1.0,
378            nullspace_dim: 0,
379            residual_df: 20.0,
380            scale: SmoothTestScale::Known,
381        })
382        .expect("smooth test");
383        assert!((out.ref_df - 1.8).abs() < 1e-12);
384        assert!(out.statistic > 0.0);
385        assert!((0.0..=1.0).contains(&out.p_value));
386    }
387
388    #[test]
389    fn known_scale_branch_reports_plain_wald_chi_square() {
390        let beta = array![1.0, 2.0];
391        let cov = array![[2.0, 0.0], [0.0, 3.0]];
392        let f = array![[0.5, 0.0], [0.0, 0.25]];
393        let out = wood_smooth_test(SmoothTestInput {
394            beta: beta.view(),
395            covariance: &cov,
396            influence_matrix: Some(&f),
397            whitening_gram: None,
398            coeff_range: 0..2,
399            edf: 1.0,
400            nullspace_dim: 0,
401            residual_df: 20.0,
402            scale: SmoothTestScale::Known,
403        })
404        .expect("smooth test");
405
406        let dist = ChiSquared::new(out.ref_df).expect("chi-square");
407        let expected = 1.0 - dist.cdf(out.statistic);
408        assert!((out.p_value - expected).abs() < 1e-15);
409    }
410
411    /// Rescaling the response by `c` is `β → c·β`, `Σ → c²·Σ` (the covariance
412    /// is scale-included). The Wald statistic `T = β'Σ⁻β` is then invariant,
413    /// and — because the estimated-scale F-statistic is `T/ref_df` with no
414    /// further `φ̂` factor — so is the p-value. This is the unit-level guard
415    /// for issue #675: the historical `T/(ref_df·φ̂)` made the p-value scale
416    /// as `1/c²` even though `T` did not move.
417    #[test]
418    fn estimated_scale_pvalue_is_response_unit_invariant() {
419        let beta = array![2.5, -3.5, 1.8];
420        let cov = array![[2.0, 0.3, 0.0], [0.3, 1.5, 0.1], [0.0, 0.1, 0.9]];
421        let f = array![[0.7, 0.0, 0.0], [0.0, 0.6, 0.0], [0.0, 0.0, 0.4]];
422
423        let run = |c: f64| {
424            let beta_c = &beta * c;
425            let cov_c = &cov * (c * c);
426            wood_smooth_test(SmoothTestInput {
427                beta: beta_c.view(),
428                covariance: &cov_c,
429                influence_matrix: Some(&f),
430                whitening_gram: None,
431                coeff_range: 0..3,
432                edf: 2.0,
433                nullspace_dim: 0,
434                residual_df: 50.0,
435                scale: SmoothTestScale::Estimated,
436            })
437            .expect("smooth test")
438        };
439
440        let base = run(1.0);
441        assert!(base.statistic > 0.0);
442        // A non-trivial, clearly-significant p-value so the invariance check is
443        // not vacuously comparing two values pinned at a boundary.
444        assert!(base.p_value > 0.0 && base.p_value < 0.05);
445        for c in [1e-3, 0.1, 10.0, 1e3, 1e6] {
446            let scaled = run(c);
447            let rel_stat = (scaled.statistic - base.statistic).abs() / base.statistic;
448            assert!(
449                rel_stat < 1e-9,
450                "Wald statistic not scale-invariant at c={c}: {} vs {}",
451                scaled.statistic,
452                base.statistic
453            );
454            let rel_p = (scaled.p_value - base.p_value).abs() / base.p_value;
455            assert!(
456                rel_p < 1e-9,
457                "estimated-scale p-value not scale-invariant at c={c}: {} vs {}",
458                scaled.p_value,
459                base.p_value
460            );
461        }
462    }
463
464    /// A term the fit drove to the penalty boundary (coefficients ≈ 0, EDF → 0)
465    /// must read as *not* significant. The defect (#1360): the reference d.f.
466    /// fell back to `edf` and collapsed toward 0, so the χ² tail of a *zero*
467    /// statistic evaluated at ~0 d.f. degenerated to p ≈ 0 — an overwhelming
468    /// false positive for a term that was removed. The reference d.f. is now
469    /// floored at the rank actually summed (≥ 1), so a zero statistic returns
470    /// p ≈ 1.
471    #[test]
472    fn boundary_shrunk_term_is_not_significant() {
473        // Near-zero coefficients with a well-conditioned (non-degenerate)
474        // covariance: the Wald statistic is ~0 regardless of how the reference
475        // d.f. is formed.
476        let beta = array![1e-9, -2e-9, 5e-10];
477        let cov = array![[0.04, 0.0, 0.0], [0.0, 0.05, 0.0], [0.0, 0.0, 0.06]];
478        // A degenerate influence block (sign-flipped near-zero leverages) so the
479        // Wood trace correction is unavailable and the fallback is exercised.
480        let f = array![[1e-9, 0.0, 0.0], [0.0, -1e-9, 0.0], [0.0, 0.0, 1e-12]];
481        for scale in [SmoothTestScale::Known, SmoothTestScale::Estimated] {
482            let out = wood_smooth_test(SmoothTestInput {
483                beta: beta.view(),
484                covariance: &cov,
485                influence_matrix: Some(&f),
486                whitening_gram: None,
487                coeff_range: 0..3,
488                edf: 1e-6,
489                nullspace_dim: 0,
490                residual_df: 500.0,
491                scale,
492            })
493            .expect("boundary term still produces a result");
494            assert!(
495                out.ref_df >= 1.0,
496                "reference d.f. must not collapse below the tested rank: {}",
497                out.ref_df
498            );
499            assert!(
500                out.statistic < 1e-6,
501                "boundary statistic should be ~0: {}",
502                out.statistic
503            );
504            assert!(
505                out.p_value > 0.5,
506                "shrunk boundary term must not be significant (p={}, scale={:?})",
507                out.p_value,
508                scale
509            );
510        }
511    }
512
513    /// Flooring the reference d.f. at the tested rank must not weaken a genuinely
514    /// significant term: a large statistic with a healthy influence block keeps
515    /// its small p-value (the floor only raises a *degenerate* sub-1 d.f.).
516    #[test]
517    fn floor_does_not_blunt_a_real_signal() {
518        let beta = array![6.0, -5.0];
519        let cov = array![[1.0, 0.0], [0.0, 1.0]];
520        let f = array![[0.9, 0.0], [0.0, 0.9]];
521        let out = wood_smooth_test(SmoothTestInput {
522            beta: beta.view(),
523            covariance: &cov,
524            influence_matrix: Some(&f),
525            whitening_gram: None,
526            coeff_range: 0..2,
527            edf: 2.0,
528            nullspace_dim: 2,
529            residual_df: 500.0,
530            scale: SmoothTestScale::Known,
531        })
532        .expect("smooth test");
533        assert!(out.statistic > 40.0, "statistic={}", out.statistic);
534        assert!(
535            out.p_value < 1e-6,
536            "a strong term must stay significant: p={}",
537            out.p_value
538        );
539    }
540
541    /// The #2142 root cause, isolated: a dominant smooth whose fitted signal
542    /// lives in the *best-determined* (small raw-variance) coefficient direction
543    /// while an orthogonal, signal-free direction carries all the raw variance.
544    /// Truncating the raw covariance to rank 1 keeps the large-variance
545    /// direction — projecting the signal onto ~0 and reporting p ≈ 1 — whereas
546    /// the design-whitened truncation keeps the least-penalized (large
547    /// whitened-variance) direction that actually holds the fit, recovering a
548    /// tiny p. Same `(β, V)`; the only difference is whether the weighted Gram
549    /// is supplied.
550    #[test]
551    fn whitening_recovers_signal_the_raw_truncation_discards() {
552        // Direction 0 (e0) is tightly determined (small posterior variance) and
553        // holds all the coefficient signal; direction 1 (e1) is loose and empty.
554        let beta = array![5.0, 0.0];
555        let cov = array![[0.01, 0.0], [0.0, 1.0]];
556        // Weighted Gram: e0 carries far more Fisher information (X'WX_00 ≫ _11),
557        // which is precisely *why* its posterior variance is small. Whitening by
558        // it makes the whitened variance of e0 (g0·V00 = 4) exceed that of e1
559        // (g1·V11 = 1), so the rank-1 cut keeps e0.
560        let gram = array![[400.0, 0.0], [0.0, 1.0]];
561
562        let raw = wood_smooth_test(SmoothTestInput {
563            beta: beta.view(),
564            covariance: &cov,
565            influence_matrix: None,
566            whitening_gram: None,
567            coeff_range: 0..2,
568            edf: 1.0,
569            nullspace_dim: 0,
570            residual_df: 100.0,
571            scale: SmoothTestScale::Known,
572        })
573        .expect("raw smooth test");
574        assert!(
575            raw.statistic < 1e-6 && raw.p_value > 0.5,
576            "raw truncation must keep the empty large-variance direction (the bug): stat={}, p={}",
577            raw.statistic,
578            raw.p_value
579        );
580
581        let whitened = wood_smooth_test(SmoothTestInput {
582            beta: beta.view(),
583            covariance: &cov,
584            influence_matrix: None,
585            whitening_gram: Some(&gram),
586            coeff_range: 0..2,
587            edf: 1.0,
588            nullspace_dim: 0,
589            residual_df: 100.0,
590            scale: SmoothTestScale::Known,
591        })
592        .expect("whitened smooth test");
593        assert!(
594            whitened.statistic > 100.0 && whitened.p_value < 1e-6,
595            "whitened truncation must keep the signal direction: stat={}, p={}",
596            whitened.statistic,
597            whitened.p_value
598        );
599    }
600
601    /// The Wald statistic is invariant to any uniform rescaling `G → c·G` of the
602    /// whitening Gram: `R → √c·R` scales `R·β` by `√c` and `R·V·Rᵀ` by `c`, and
603    /// the two factors cancel in `(R·β)ᵀ (R·V·Rᵀ)⁻ (R·β)`. This is why passing
604    /// the raw `X'WX` (no `φ̂`) is correct even though the covariance is
605    /// scale-included.
606    #[test]
607    fn whitening_statistic_is_invariant_to_gram_scaling() {
608        let beta = array![2.0, -1.5, 0.7];
609        let cov = array![[0.02, 0.0, 0.0], [0.0, 0.3, 0.0], [0.0, 0.0, 0.9]];
610        let gram_base = array![[50.0, 1.0, 0.0], [1.0, 8.0, 0.5], [0.0, 0.5, 2.0]];
611        let run = |c: f64| {
612            let g = &gram_base * c;
613            wood_smooth_test(SmoothTestInput {
614                beta: beta.view(),
615                covariance: &cov,
616                influence_matrix: None,
617                whitening_gram: Some(&g),
618                coeff_range: 0..3,
619                edf: 2.0,
620                nullspace_dim: 0,
621                residual_df: 100.0,
622                scale: SmoothTestScale::Known,
623            })
624            .expect("whitened smooth test")
625        };
626        let base = run(1.0);
627        assert!(base.statistic > 0.0);
628        for c in [1e-6, 1e-2, 7.0, 1e3, 1e6] {
629            let scaled = run(c);
630            let rel = (scaled.statistic - base.statistic).abs() / base.statistic;
631            assert!(
632                rel < 1e-9,
633                "statistic not Gram-scale-invariant at c={c}: {} vs {}",
634                scaled.statistic,
635                base.statistic
636            );
637        }
638    }
639
640    /// A rank-deficient whitening Gram (e.g. a collinear/degenerate term design)
641    /// must degrade gracefully to a lower-dimensional fitted space rather than
642    /// error: the surviving direction is still tested and yields a finite result.
643    #[test]
644    fn whitening_tolerates_rank_deficient_gram() {
645        let beta = array![3.0, 1.0];
646        let cov = array![[0.05, 0.0], [0.0, 0.4]];
647        // Rank-1 Gram: only the e0 fitted direction is estimable.
648        let gram = array![[9.0, 0.0], [0.0, 0.0]];
649        let out = wood_smooth_test(SmoothTestInput {
650            beta: beta.view(),
651            covariance: &cov,
652            influence_matrix: None,
653            whitening_gram: Some(&gram),
654            coeff_range: 0..2,
655            edf: 2.0,
656            nullspace_dim: 0,
657            residual_df: 100.0,
658            scale: SmoothTestScale::Known,
659        })
660        .expect("rank-deficient Gram still yields a result");
661        // Only one fitted direction survives, so the reference d.f. is 1.
662        assert!((out.ref_df - 1.0).abs() < 1e-9, "ref_df={}", out.ref_df);
663        assert!(out.statistic.is_finite() && out.statistic > 0.0);
664        assert!((0.0..=1.0).contains(&out.p_value));
665    }
666}