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