gam_models/fit_orchestration/entry.rs
1use super::*;
2
3/// Request-specific inputs to the canonical standard-fit `FitOptions`.
4///
5/// Everything in here varies per call (the link state extracted from the
6/// formula/config, the linear constraints synthesized from `bounded()` /
7/// shape-constrained terms, the Firth / adaptive-regularization toggles read
8/// off the `FitConfig`). Every *policy* field of `FitOptions` — the ones that
9/// decide HOW the outer REML optimization behaves (`compute_inference`,
10/// `skip_rho_posterior_inference`, `tol`, the `max_iter` default, the penalty
11/// shrinkage floor) — is filled in by [`canonical_standard_fit_options`] and is
12/// NOT settable here, so the CLI binary and the Python/PyO3 path cannot resolve
13/// a different optimization policy for the same model (#1196). Before this seam
14/// existed the CLI hand-built `FitOptions` with `tol: 1e-6` /
15/// `skip_rho_posterior_inference: false` while the formula path used
16/// `tol: 1e-10` / `skip_rho_posterior_inference: true`, so the identical model
17/// fit *differently* depending on which entry point you called it from — the
18/// exact class of divergence #1191 surfaced.
19#[derive(Default)]
20pub struct StandardFitOptionsInputs {
21 pub latent_cloglog: Option<LatentCLogLogState>,
22 pub mixture_link: Option<MixtureLinkSpec>,
23 pub optimize_mixture: bool,
24 pub sas_link: Option<SasLinkSpec>,
25 pub optimize_sas: bool,
26 pub linear_constraints: Option<gam_solve::pirls::LinearInequalityConstraints>,
27 pub firth_bias_reduction: bool,
28 pub adaptive_regularization: Option<AdaptiveRegularizationOptions>,
29 /// `Some` only when a caller (the forced-Firth CLI branch) overrides the
30 /// canonical default. `None` keeps the single-source default `Some(1e-6)`.
31 pub penalty_shrinkage_floor_override: Option<Option<f64>>,
32 pub persist_warm_start_disk: bool,
33}
34
35/// The single source of truth for standard-fit `FitOptions` *policy*.
36///
37/// Both standard-fit entry points — `materialize_standard` (the formula /
38/// Python / PyO3 path) and the `gam` CLI's `run_fit` — construct their
39/// `StandardFitRequest` options through this function, so the outer REML
40/// optimization policy (`compute_inference`, `skip_rho_posterior_inference`,
41/// `tol`, `max_iter` default, `penalty_shrinkage_floor`) is identical by
42/// construction. New policy fields must be set HERE, never re-derived at a call
43/// site, which is what makes Python/CLI behavioral divergence structurally
44/// impossible rather than enforced by parallel-but-equal code (#1196).
45pub fn canonical_standard_fit_options(
46 config: &FitConfig,
47 inputs: StandardFitOptionsInputs,
48) -> FitOptions {
49 FitOptions {
50 latent_cloglog: inputs.latent_cloglog,
51 mixture_link: inputs.mixture_link,
52 optimize_mixture: inputs.optimize_mixture,
53 sas_link: inputs.sas_link,
54 optimize_sas: inputs.optimize_sas,
55 // Posterior covariance is always computed so `predict --uncertainty`
56 // works for every family (the `COV_MAX_P` diagonal fallback caps cost).
57 compute_inference: true,
58 // Formula/CLI fits are the interactive/default path: keep coefficient
59 // covariance and the smoothing correction, but do not run the optional
60 // live-rho posterior certificate/escalation, which can launch NUTS over
61 // rho and turn ordinary fits into sampler benchmarks. Lower-level
62 // callers that explicitly need the rho posterior opt in elsewhere.
63 skip_rho_posterior_inference: true,
64 max_iter: config.outer_max_iter.unwrap_or(200),
65 // Outer REML/LAML smoothing-selection tolerance. `1e-10` (effective
66 // projected-gradient threshold ≈ 1e-7) resolves λ̂ to optimiser
67 // precision and restores the `w=c ⇔ c-fold replication` invariance in
68 // smoothing selection (gam#893). The CLI previously used the stale
69 // `1e-6`, which over-smoothed relative to the formula path.
70 tol: 1e-10,
71 nullspace_dims: vec![],
72 linear_constraints: inputs.linear_constraints,
73 firth_bias_reduction: inputs.firth_bias_reduction,
74 adaptive_regularization: inputs.adaptive_regularization,
75 penalty_shrinkage_floor: inputs
76 .penalty_shrinkage_floor_override
77 .unwrap_or(Some(1e-6)),
78 rho_prior: Default::default(),
79 kronecker_penalty_system: None,
80 kronecker_factored: None,
81 persist_warm_start_disk: inputs.persist_warm_start_disk,
82 }
83}
84
85pub fn fit_model(request: FitRequest<'_>) -> Result<FitResult, WorkflowError> {
86 // Disk warm-start persistence is opt-in. The always-on in-memory warm start
87 // remains inside the fit engines, but the workflow dispatcher must not open
88 // the shared WarmStartStore for ordinary formula fits: refit-heavy quality
89 // tests get no cross-process reuse and previously paid cache lookup,
90 // checkpoint, and eviction scans on every replicate (#1082/#1114).
91 let request = request;
92 // Each `fit_*_model` helper still returns `Result<_, String>` internally;
93 // the boundary conversion happens here so the public API returns
94 // `WorkflowError::IntegrationFailed` carrying the underlying solver text.
95 let wrap_solver_err =
96 |reason: String| -> WorkflowError { WorkflowError::IntegrationFailed { reason } };
97 match request {
98 FitRequest::Standard(request) => fit_standard_model(request)
99 .map(FitResult::Standard)
100 .map_err(wrap_solver_err),
101 FitRequest::GaussianLocationScale(request) => fit_gaussian_location_scale_model(request)
102 .map(FitResult::GaussianLocationScale)
103 .map_err(wrap_solver_err),
104 FitRequest::BinomialLocationScale(request) => fit_binomial_location_scale_model(request)
105 .map(FitResult::BinomialLocationScale)
106 .map_err(wrap_solver_err),
107 FitRequest::DispersionLocationScale(request) => {
108 fit_dispersion_location_scale_model(request)
109 .map(FitResult::DispersionLocationScale)
110 .map_err(wrap_solver_err)
111 }
112 FitRequest::SurvivalLocationScale(request) => fit_survival_location_scale_model(request)
113 .map(FitResult::SurvivalLocationScale)
114 .map_err(wrap_solver_err),
115 FitRequest::SurvivalTransformation(request) => fit_survival_transformation_model(request)
116 .map(FitResult::SurvivalTransformation)
117 .map_err(wrap_solver_err),
118 FitRequest::BernoulliMarginalSlope(request) => fit_bernoulli_marginal_slope_model(request)
119 .map(FitResult::BernoulliMarginalSlope)
120 .map_err(wrap_solver_err),
121 FitRequest::SurvivalMarginalSlope(request) => fit_survival_marginal_slope_model(request)
122 .map(FitResult::SurvivalMarginalSlope)
123 .map_err(wrap_solver_err),
124 FitRequest::LatentSurvival(request) => fit_latent_survival_model(request)
125 .map(FitResult::LatentSurvival)
126 .map_err(wrap_solver_err),
127 FitRequest::LatentBinary(request) => fit_latent_binary_model(request)
128 .map(FitResult::LatentBinary)
129 .map_err(wrap_solver_err),
130 FitRequest::TransformationNormal(request) => fit_transformation_normal_model(request)
131 .map(FitResult::TransformationNormal)
132 .map_err(wrap_solver_err),
133 }
134}
135/// Resolve the [`gam_runtime::resource::ResourcePolicy`] backing term construction
136/// for a given [`FitConfig`] + dataset.
137///
138/// If the caller hasn't supplied an explicit policy override, derive one from
139/// the shape of the problem via
140/// [`gam_runtime::resource::ResourcePolicy::for_problem`]. At large scale (n_rows
141/// >= 100k or the marginal-slope large-scale path active) this returns
142/// > `analytic_operator_required` so that any silent dense materialization in
143/// > the term-construction layer fails fast rather than allocating tens of GiB;
144/// > at small scale it falls through to the permissive default-library policy
145/// > so that non-operator bases still build cleanly.
146///
147/// `p_estimate = 0` because the per-block coefficient count isn't known until
148/// the spec has been built; the n_rows and hints triggers are sufficient to
149/// flip strict mode for every shape that needs it.
150pub(crate) fn resolved_resource_policy(
151 config: &FitConfig,
152 data: &Dataset,
153 hints: gam_runtime::resource::ProblemHints,
154) -> gam_runtime::resource::ResourcePolicy {
155 if let Some(p) = config.resource_policy.clone() {
156 return p;
157 }
158 gam_runtime::resource::ResourcePolicy::for_problem(data.values.nrows(), 0, hints)
159}
160
161pub(crate) fn marginal_slope_hints(config: &FitConfig) -> gam_runtime::resource::ProblemHints {
162 gam_runtime::resource::ProblemHints {
163 marginal_slope_large_scale_active: config.logslope_formula.is_some()
164 || config.z_column.is_some(),
165 }
166}
167/// Parse, materialize, and fit a model in one call.
168/// Resolve the expectile asymmetry `τ` requested by `config`, if any.
169///
170/// Returns `Ok(Some(τ))` when `config.family` is `"expectile"` (optionally with
171/// an inline asymmetry, `"expectile(0.9)"`), `Ok(None)` for every other family,
172/// and `Err` when an expectile request carries an out-of-range `τ`. The inline
173/// form takes precedence over the explicit [`FitConfig::expectile_tau`] field
174/// only when both are present and disagree is rejected as a contradiction; when
175/// neither pins `τ`, the median expectile `τ = 0.5` (the ordinary mean fit) is
176/// the default.
177fn expectile_tau_for_config(config: &FitConfig) -> Result<Option<f64>, WorkflowError> {
178 let Some(raw) = config.family.as_deref() else {
179 return Ok(None);
180 };
181 let trimmed = raw.trim();
182 let lower = trimmed.to_ascii_lowercase();
183 if !(lower == "expectile" || lower.starts_with("expectile(")) {
184 return Ok(None);
185 }
186 let invalid = |reason: String| WorkflowError::InvalidConfig { reason };
187 // Optional inline asymmetry: `expectile(0.9)`.
188 let inline_tau = if let Some(rest) = lower.strip_prefix("expectile(") {
189 let inner = rest.strip_suffix(')').ok_or_else(|| {
190 invalid(format!(
191 "expectile family asymmetry must be written as `expectile(τ)`; got `{trimmed}`"
192 ))
193 })?;
194 let value: f64 = inner.trim().parse().map_err(|_| {
195 invalid(format!(
196 "expectile asymmetry `{}` is not a finite number",
197 inner.trim()
198 ))
199 })?;
200 Some(value)
201 } else {
202 None
203 };
204 let tau = match (inline_tau, config.expectile_tau) {
205 (Some(a), Some(b)) if (a - b).abs() > 0.0 => {
206 return Err(invalid(format!(
207 "expectile asymmetry given both inline (`expectile({a})`) and via expectile_tau \
208 ({b}); supply exactly one"
209 )));
210 }
211 (Some(a), _) => a,
212 (None, Some(b)) => b,
213 (None, None) => 0.5,
214 };
215 if !(tau.is_finite() && tau > 0.0 && tau < 1.0) {
216 return Err(invalid(format!(
217 "expectile asymmetry τ must be finite and strictly in (0, 1); got {tau}"
218 )));
219 }
220 Ok(Some(tau))
221}
222
223/// Per-row asymmetric LAWS weight `wᵢ(τ) = τ` if `yᵢ > μᵢ` else `1 − τ`, scaled
224/// by the base prior weight. At the boundary `yᵢ = μᵢ` the two half-weights
225/// agree in the limit only at `τ = 0.5`; the convention `yᵢ > μᵢ ⇒ τ` (strict)
226/// matches Newey–Powell's lower-closed asymmetric loss and is what `expectreg`
227/// uses. The fixed point is independent of the tie convention because ties form
228/// a measure-zero set under any continuous response.
229fn expectile_row_weights(
230 y: ArrayView1<f64>,
231 mu: ArrayView1<f64>,
232 base: ArrayView1<f64>,
233 tau: f64,
234) -> Array1<f64> {
235 Array1::from_shape_fn(y.len(), |i| {
236 let asym = if y[i] > mu[i] { tau } else { 1.0 - tau };
237 base[i] * asym
238 })
239}
240
241fn constant_gaussian_standard_fit(
242 request: &StandardFitRequest<'_>,
243) -> Result<StandardFitResult, WorkflowError> {
244 if !request.family.is_gaussian_identity() || request.y.is_empty() {
245 return Err(WorkflowError::InvalidConfig {
246 reason: "constant Gaussian shortcut requires a non-empty Gaussian identity request"
247 .to_string(),
248 });
249 }
250 if request.y.iter().any(|value| !value.is_finite())
251 || request.offset.iter().any(|value| !value.is_finite())
252 || request
253 .weights
254 .iter()
255 .any(|value| !value.is_finite() || *value < 0.0)
256 {
257 return Err(WorkflowError::InvalidConfig {
258 reason: "constant Gaussian shortcut requires finite response, offset, and non-negative weights"
259 .to_string(),
260 });
261 }
262 let weight_sum = request.weights.sum();
263 if !(weight_sum.is_finite() && weight_sum > 0.0) {
264 return Err(WorkflowError::InvalidConfig {
265 reason: "constant Gaussian shortcut requires positive total weight".to_string(),
266 });
267 }
268 let mut centered_sum = 0.0_f64;
269 for i in 0..request.y.len() {
270 centered_sum += request.weights[i] * (request.y[i] - request.offset[i]);
271 }
272 let intercept = centered_sum / weight_sum;
273 let design =
274 build_term_collection_design(request.data.view(), &request.spec).map_err(|err| {
275 WorkflowError::InvalidConfig {
276 reason: format!("constant Gaussian shortcut could not rebuild design: {err}"),
277 }
278 })?;
279 let p = design.design.ncols();
280 let mut beta = Array1::<f64>::zeros(p);
281 for col in design.intercept_range.clone() {
282 if col < p {
283 beta[col] = intercept;
284 }
285 }
286 let lambdas = Array1::<f64>::ones(design.penalties.len());
287 let log_lambdas = Array1::<f64>::zeros(design.penalties.len());
288 let fit =
289 gam_solve::estimate::UnifiedFitResult::try_from_parts(gam_solve::estimate::UnifiedFitResultParts {
290 blocks: vec![gam_solve::estimate::FittedBlock {
291 beta: beta.clone(),
292 role: gam_problem::BlockRole::Mean,
293 edf: design.intercept_range.len() as f64,
294 lambdas: lambdas.clone(),
295 }],
296 log_lambdas,
297 lambdas,
298 likelihood_family: Some(request.family.clone()),
299 likelihood_scale: gam_problem::LikelihoodScaleMetadata::ProfiledGaussian,
300 log_likelihood_normalization: gam_problem::LogLikelihoodNormalization::UserProvided,
301 log_likelihood: 0.0,
302 deviance: 0.0,
303 reml_score: 0.0,
304 stable_penalty_term: 0.0,
305 penalized_objective: 0.0,
306 used_device: false,
307 outer_iterations: 0,
308 outer_converged: true,
309 outer_gradient_norm: Some(0.0),
310 standard_deviation: 0.0,
311 covariance_conditional: None,
312 covariance_corrected: None,
313 inference: None,
314 fitted_link: gam_solve::estimate::FittedLinkState::Standard(None),
315 geometry: None,
316 block_states: Vec::new(),
317 pirls_status: gam_solve::pirls::PirlsStatus::Converged,
318 max_abs_eta: intercept.abs(),
319 constraint_kkt: None,
320 artifacts: gam_solve::estimate::FitArtifacts {
321 pirls: None,
322 ..Default::default()
323 },
324 inner_cycles: 0,
325 })
326 .map_err(|err| WorkflowError::IntegrationFailed {
327 reason: format!("constant Gaussian shortcut produced invalid fit: {err}"),
328 })?;
329 let resolvedspec =
330 freeze_term_collection_from_design(&request.spec, &design).map_err(|err| {
331 WorkflowError::InvalidConfig {
332 reason: format!("constant Gaussian shortcut could not freeze design: {err}"),
333 }
334 })?;
335 Ok(StandardFitResult {
336 fit,
337 design,
338 resolvedspec,
339 adaptive_diagnostics: None,
340 kappa_timing: None,
341 saved_link_state: gam_solve::estimate::FittedLinkState::Standard(None),
342 wiggle_knots: None,
343 wiggle_degree: None,
344 wiggle_saved_warp_beta: None,
345 })
346}
347
348fn gaussian_response_is_constant(request: &StandardFitRequest<'_>) -> bool {
349 if !request.family.is_gaussian_identity()
350 || request.y.is_empty()
351 || request.y.iter().any(|value| !value.is_finite())
352 {
353 return false;
354 }
355 let (lo, hi) = request
356 .y
357 .iter()
358 .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &value| {
359 (lo.min(value), hi.max(value))
360 });
361 (hi - lo).abs() <= 1.0e-12 * hi.abs().max(1.0)
362}
363
364pub fn fit_from_formula(
365 formula: &str,
366 data: &Dataset,
367 config: &FitConfig,
368) -> Result<FitResult, WorkflowError> {
369 // Expectile regression (Newey–Powell asymmetric least squares): when the
370 // family resolves to "expectile", the τ-expectile of `y | x` is the
371 // minimizer of `Σ wᵢ(τ)·(yᵢ − μᵢ)²`, `wᵢ(τ) = τ` if `yᵢ > μᵢ` else `1 − τ`
372 // — the smooth analogue of the τ-quantile. The minimizer is a Least
373 // Asymmetrically Weighted Squares (LAWS) fixed point: iterate the penalized
374 // Gaussian-identity GAM with `wᵢ(τ)` recomputed from the current `μᵢ` until
375 // the residual-sign pattern stabilizes. REML λ-selection runs inside each
376 // inner Gaussian solve, so every gam smooth/tensor/spatial basis becomes a
377 // penalized expectile smooth with data-driven smoothing for free. This is a
378 // genuine estimator route, not a silent swap: it fires only on the explicit
379 // `family = "expectile"`. Every other family falls through unchanged.
380 if let Some(tau) = expectile_tau_for_config(config)? {
381 return fit_expectile_laws(formula, data, config, tau);
382 }
383 let mat = materialize(formula, data, config)?;
384 // Exact O(n) spline-scan fast path (#1030): when the materialized request
385 // is the single 1-D Gaussian-identity penalized-smooth shape the
386 // state-space scan solves exactly, route through it and return the
387 // scan-bearing model directly — the same penalized posterior at O(n) per
388 // λ-trial instead of the dense design/Gram route. Detection is structural
389 // and conservative (see `spline_scan_fast_path`); every other shape falls
390 // through to the dense `fit_model` path unchanged. Mirrors the CLI
391 // (main.rs run_fit) and FFI consumers, which build the persistence payload
392 // from this same `SplineScanFit`.
393 if let FitRequest::Standard(request) = &mat.request {
394 if gaussian_response_is_constant(request) {
395 return constant_gaussian_standard_fit(request).map(FitResult::Standard);
396 }
397 if let Some(inputs) = spline_scan_fast_path(request) {
398 let scan = gam_solve::spline_scan::fit_spline_scan(
399 &inputs.x,
400 &inputs.y,
401 &inputs.w,
402 inputs.order,
403 )
404 .map_err(|reason| WorkflowError::IntegrationFailed { reason })?;
405 return Ok(FitResult::SplineScan(scan));
406 }
407 // O(n log n) multiresolution residual-cascade fast path (#1032): a
408 // scattered low-d Gaussian-identity Duchon/Matérn smooth past the
409 // dense-kernel cliff. UNLIKE the scan, the cascade is a DIFFERENT
410 // posterior from the dense radial term, so it only ever fires as an
411 // explicit alternative estimator on the exact structural signature
412 // (`residual_cascade_fast_path`) AND when the in-cascade quasi-uniformity
413 // guard certifies the metric — a rejected metric or any ineligible shape
414 // falls through to the dense `fit_model` path (a genuine estimator
415 // choice, never a silent swap). The save paths build the persistence
416 // payload from this `ResidualCascadeFit`'s `to_state` snapshot.
417 if let Some(inputs) = residual_cascade_fast_path(request) {
418 let coord_refs: Vec<&[f64]> = inputs.coords.iter().map(Vec::as_slice).collect();
419 if let Ok(fit) = gam_solve::residual_cascade::fit_residual_cascade(
420 &coord_refs,
421 &inputs.y,
422 &inputs.w,
423 &inputs.metric,
424 inputs.sobolev_s,
425 ) {
426 return Ok(FitResult::ResidualCascade(fit));
427 }
428 // The quasi-uniformity guard (caveat 2) or any degenerate-design
429 // signal surfaces as a build/solve error; fall through to the dense
430 // kernel path rather than failing the fit outright.
431 }
432 }
433 // `fit_model` already returns `WorkflowError` end-to-end; propagate it
434 // directly instead of stringifying then re-wrapping.
435 fit_model(mat.request)
436}
437
438/// Least Asymmetrically Weighted Squares (LAWS) driver for expectile GAMs.
439///
440/// The τ-expectile surface minimizes `Σ wᵢ(τ)·(yᵢ − μᵢ)²` with the residual-
441/// sign asymmetric weight `wᵢ(τ)`. Because that weight is piecewise-constant in
442/// `sign(yᵢ − μᵢ)`, the objective is the supremum of a finite family of
443/// weighted least-squares problems and its minimizer is the unique fixed point
444/// of: *solve the penalized WLS with weights frozen at the current sign
445/// pattern, then recompute the sign pattern from the new fit*. The asymmetric
446/// loss is strictly convex (weights bounded in `[min(τ,1−τ), max(τ,1−τ)] > 0`),
447/// so this monotone-descent iteration converges, and since the sign pattern
448/// takes finitely many values it stabilizes in finitely many steps (Schnabel &
449/// Eilers 2009; the same Newton/IRLS-for-expectiles `expectreg` runs).
450///
451/// Each inner solve is the FULL standard Gaussian-identity GAM: any basis,
452/// tensor, spatial smooth, by-variable, random effect, plus REML λ-selection on
453/// the current asymmetric weights. The returned fit is an ordinary
454/// [`FitResult::Standard`] whose coefficients ARE the penalized τ-expectile —
455/// every downstream consumer (predict, posterior bands, persistence) works
456/// unchanged. The reported scale is the asymmetric working variance, so
457/// expectile standard errors are the sandwich-free Gaussian-form bands of the
458/// converged weighted problem (a deliberate first-rung choice; see #1100).
459fn fit_expectile_laws(
460 formula: &str,
461 data: &Dataset,
462 config: &FitConfig,
463 tau: f64,
464) -> Result<FitResult, WorkflowError> {
465 use gam_linalg::matrix::LinearOperator;
466
467 // Inner fits are ordinary Gaussian-identity GAMs; the τ asymmetry lives
468 // entirely in the per-iteration prior weights this driver injects.
469 let gaussian_config = FitConfig {
470 family: Some("gaussian".to_string()),
471 link: Some("identity".to_string()),
472 expectile_tau: None,
473 ..config.clone()
474 };
475
476 // Materialize once to capture the fixed training design, response, offset,
477 // and base prior weights. The design (basis, penalties, identifiability
478 // transforms) does not depend on the prior weights, so it is reused across
479 // every LAWS iteration; only the weight vector and the resulting β change.
480 let base_mat = materialize(formula, data, &gaussian_config)?;
481 let FitRequest::Standard(base_request) = base_mat.request else {
482 return Err(WorkflowError::InvalidConfig {
483 reason: "expectile regression is only defined for standard (non-survival, \
484 non-location-scale) responses"
485 .to_string(),
486 });
487 };
488 let StandardFitRequest {
489 data: design_data,
490 y,
491 weights: base_weights,
492 offset,
493 spec,
494 family: materialized_family,
495 options,
496 kappa_options,
497 wiggle,
498 coefficient_groups,
499 penalty_block_gamma_priors,
500 latent_coord,
501 _marker,
502 } = base_request;
503 // The materializer already resolved the inner family to Gaussian-identity
504 // from `gaussian_config`; assert it so a future materializer change that
505 // silently picked a different family for `"gaussian"` is caught here rather
506 // than producing a non-expectile fit.
507 if !materialized_family.is_gaussian_identity() {
508 return Err(WorkflowError::InvalidConfig {
509 reason: format!(
510 "expectile LAWS requires a Gaussian-identity inner family; materializer produced {}",
511 materialized_family.name()
512 ),
513 });
514 }
515
516 if wiggle.is_some() || latent_coord.is_some() {
517 return Err(WorkflowError::InvalidConfig {
518 reason: "expectile regression does not support flexible-link wiggle or latent \
519 coordinates"
520 .to_string(),
521 });
522 }
523
524 let n = y.len();
525 let gaussian_family = LikelihoodSpec::gaussian_identity();
526 // Cold start: τ = 0.5 (symmetric) weights ⇒ the first inner fit is the OLS
527 // mean GAM, the natural warm start for any τ.
528 let mut weights = base_weights.clone();
529 let mut last_sign: Option<Vec<bool>> = None;
530 let mut last_result: Option<StandardFitResult> = None;
531
532 // The sign pattern has 2ⁿ values but LAWS visits a monotone-descent subset;
533 // empirically a handful of iterations suffice. The cap is a safety guard:
534 // on the rare oscillation between two equal-objective sign patterns (only
535 // possible when rows sit exactly on the fitted surface) the last fit is a
536 // valid τ-expectile of the perturbation-stable problem, so returning it is
537 // correct rather than an error.
538 const MAX_LAWS_ITERS: usize = 50;
539
540 for _iter in 0..MAX_LAWS_ITERS {
541 let request = StandardFitRequest {
542 data: design_data.clone(),
543 y: y.clone(),
544 weights: weights.clone(),
545 offset: offset.clone(),
546 spec: spec.clone(),
547 family: gaussian_family.clone(),
548 options: options.clone(),
549 kappa_options: kappa_options.clone(),
550 wiggle: None,
551 coefficient_groups: coefficient_groups.clone(),
552 penalty_block_gamma_priors: penalty_block_gamma_priors.clone(),
553 latent_coord: None,
554 _marker,
555 };
556 let result = fit_standard_model(request)
557 .map_err(|reason| WorkflowError::IntegrationFailed { reason })?;
558
559 // Training-scale fitted mean μ = X·β (identity link, zero-checked
560 // offset folded by the design path). The design columns match the
561 // combined coefficient vector exactly (the same contract `predict`
562 // and the safety tests rely on).
563 let mu = result.design.design.apply(&result.fit.beta);
564 if mu.len() != n {
565 return Err(WorkflowError::IntegrationFailed {
566 reason: format!(
567 "expectile LAWS: fitted mean length {} disagrees with response length {n}",
568 mu.len()
569 ),
570 });
571 }
572 let mut mu_off = mu;
573 mu_off += &offset;
574
575 let sign: Vec<bool> = (0..n).map(|i| y[i] > mu_off[i]).collect();
576 let converged = last_sign.as_ref().is_some_and(|prev| prev == &sign);
577 weights = expectile_row_weights(y.view(), mu_off.view(), base_weights.view(), tau);
578 last_sign = Some(sign);
579 last_result = Some(result);
580 if converged {
581 break;
582 }
583 }
584
585 let result = last_result.ok_or_else(|| WorkflowError::IntegrationFailed {
586 reason: "expectile LAWS produced no fit".to_string(),
587 })?;
588 Ok(FitResult::Standard(result))
589}
590/// Detection seam for the exact O(n) cubic-smoothing-spline fast path.
591///
592/// This is the EARLIEST point in the standard workflow where a materialized
593/// fit request carries everything needed to prove the model is exactly the
594/// problem the scan solves: a Gaussian likelihood with identity link over
595/// `intercept + one 1-D cubic-class penalized smooth` — i.e. the penalized
596/// least-squares problem `min Σ w_i (y_i − f(x_i))² + λ∫f″²` with an
597/// unpenalized `{1, x}` null space. The Kalman/RTS scan computes that
598/// posterior (mean, pointwise variance, exact diffuse REML for λ) in O(n) per
599/// λ-trial instead of the dense design/Gram O(n·k²) + O(k³) route.
600///
601/// Returns `Some` only when ALL of the following hold; everything else falls
602/// through to the dense path:
603/// - family is Gaussian + identity link;
604/// - no link wiggle, no latent coordinates, no coefficient groups, no penalty
605/// hyperpriors, no linear/box constraints, no Firth, no adaptive
606/// regularization, no Kronecker systems, no externally injected null-space
607/// dims;
608/// - the term collection is exactly one smooth term — no linear terms, no
609/// random effects, no by-variables / factor interactions;
610/// - that smooth is a plain 1-D B-spline whose penalty order is compatible
611/// with the exact scan and whose null space is unshrunk
612/// (`double_penalty=false`). `double_penalty` (mgcv `select = TRUE`) on a free
613/// B-spline emits a second REML coordinate — the Marra & Wood (2011) null-space
614/// shrinkage block — that the scan cannot represent (its polynomial null space
615/// is an improper diffuse prior it can never shrink); routing such a fit
616/// through the scan would silently drop that penalty and select λ from the
617/// bending penalty alone, which is exactly the EDF inflation #1266 reports.
618/// Those fits fall through to the dense two-rho path, which owns both penalties
619/// jointly;
620/// - the offset is identically zero and every weight is finite and positive;
621/// - at least 3 distinct finite abscissae (the scan's diffuse rank plus one).
622///
623/// λ-mapping note: the scan's penalty is exactly `λ∫f″²` (state-space
624/// `q = 1/λ` at unit σ²). The dense 1-D B-spline path penalizes the same
625/// cubic class through a reduced-rank discrete-difference Gram whose
626/// normalization differs by a basis-dependent constant, so a λ selected by
627/// one parameterization does not transfer numerically to the other. The scan
628/// therefore always re-selects λ by its own exact diffuse REML criterion
629/// (the optimizer of the same restricted likelihood, expressed in the scan's
630/// parameterization); user-pinned smoothing parameters are not representable
631/// at this seam (the formula DSL exposes none for this term class), so no
632/// pinned-λ mapping arises.
633///
634/// Identifiability transforms on the smooth (centering / linear-trend
635/// removal / orthogonality-to-intercept) are accepted as eligible: they only
636/// re-coordinate the unpenalized null space against the implicit intercept
637/// and do not change the fitted posterior of `E[y|x]`, which is what the
638/// scan returns directly.
639pub fn spline_scan_fast_path(request: &StandardFitRequest<'_>) -> Option<SplineScanInputs> {
640 if !request.family.is_gaussian_identity() {
641 return None;
642 }
643 if request.wiggle.is_some()
644 || request.latent_coord.is_some()
645 || !request.coefficient_groups.is_empty()
646 || !request.penalty_block_gamma_priors.is_empty()
647 {
648 return None;
649 }
650 let options = &request.options;
651 if options.latent_cloglog.is_some()
652 || options.mixture_link.is_some()
653 || options.sas_link.is_some()
654 || options.linear_constraints.is_some()
655 || options.adaptive_regularization.is_some()
656 || options.kronecker_penalty_system.is_some()
657 || options.kronecker_factored.is_some()
658 || options.firth_bias_reduction
659 || !options.nullspace_dims.is_empty()
660 {
661 return None;
662 }
663 let spec = &request.spec;
664 if !spec.linear_terms.is_empty()
665 || !spec.random_effect_terms.is_empty()
666 || spec.smooth_terms.len() != 1
667 {
668 return None;
669 }
670 let term = &spec.smooth_terms[0];
671 if !matches!(term.shape, gam_terms::smooth::ShapeConstraint::None)
672 || term.joint_null_rotation.is_some()
673 {
674 return None;
675 }
676 let gam_terms::smooth::SmoothBasisSpec::BSpline1D {
677 feature_col,
678 spec: bspec,
679 } = &term.basis
680 else {
681 return None;
682 };
683 // Smoothing-spline order m = penalty_order ∈ {1, 2, 3}. The exact scan
684 // integrates the order-m integrated-Wiener prior whose natural spline has
685 // degree 2m−1 (m=1 → linear, m=2 → cubic, m=3 → quintic), so require that
686 // degree to match user intent. The de Jong exact diffuse leading-block
687 // smoother (#1044) handles the m−1 partially-diffuse leading nodes for all
688 // m ≤ MAX_ORDER; m > MAX_ORDER falls through to the dense path.
689 let order = bspec.penalty_order;
690 // Double-penalty (mgcv `select = TRUE`) is NOT representable by the scan and
691 // must fall through to the dense two-rho path (#1266). On a free B-spline the
692 // double penalty emits a *second* REML coordinate — the Marra & Wood (2011)
693 // null-space shrinkage block `Z Zᵀ` (see `bspline_penalty_candidates`) —
694 // whose entire purpose is to let REML shrink the unpenalized `{1, x, …}`
695 // polynomial null space toward `EDF → 0` for an unsupported term. The scan,
696 // by construction, carries that null space as an *improper diffuse* prior it
697 // can never shrink (its EDF floor is the null-space dimension `order`), so
698 // routing a `double_penalty` fit through it silently DROPS the second penalty
699 // and selects λ from the single bending penalty alone. The scan's own exact
700 // diffuse REML then genuinely prefers a mildly wiggly fit at finite λ for
701 // some noise realizations (an interior REML optimum, EDF ≈ 3–4), which is the
702 // EDF inflation #1266 reports. The dense path owns both penalties jointly and
703 // its outer REML, seeded into the over-smoothing basin, drives the null space
704 // out (EDF → null-space dim) when the data are truly polynomial. Excluding
705 // `double_penalty` here keeps such a fit on the dense path; single-penalty
706 // and boundary-conditioned single-penalty B-splines keep the exact O(n) scan.
707 if !(1..=3).contains(&order)
708 || bspec.degree != 2 * order - 1
709 || bspec.double_penalty
710 || !bspec.boundary_conditions.is_free()
711 || !matches!(bspec.boundary, gam_terms::basis::OneDimensionalBoundary::Open)
712 || matches!(
713 bspec.knotspec,
714 gam_terms::basis::BSplineKnotSpec::PeriodicUniform { .. }
715 )
716 {
717 return None;
718 }
719 if request.offset.iter().any(|&v| v != 0.0) {
720 return None;
721 }
722 if request.weights.iter().any(|&v| !(v.is_finite() && v > 0.0)) {
723 return None;
724 }
725 if *feature_col >= request.data.ncols() || request.y.len() != request.data.nrows() {
726 return None;
727 }
728 let x: Vec<f64> = request.data.column(*feature_col).iter().copied().collect();
729 let y: Vec<f64> = request.y.iter().copied().collect();
730 let w: Vec<f64> = request.weights.iter().copied().collect();
731 if x.iter().any(|v| !v.is_finite()) || y.iter().any(|v| !v.is_finite()) {
732 return None;
733 }
734 // The diffuse polynomial null space consumes `order` innovations; the scan
735 // needs at least one proper innovation beyond them to profile σ².
736 let mut sorted = x.clone();
737 sorted.sort_by(f64::total_cmp);
738 sorted.dedup();
739 if sorted.len() < order + 1 {
740 return None;
741 }
742 Some(SplineScanInputs { x, y, w, order })
743}
744
745/// Formula-level entry for the exact O(n) cubic-smoothing-spline fast path.
746///
747/// Materializes the formula exactly like [`fit_from_formula`], then runs the
748/// [`spline_scan_fast_path`] detection on the resulting standard request.
749/// When detection fires the fit is routed through
750/// [`gam_solve::spline_scan::fit_spline_scan`] — the exact diffuse
751/// REML Kalman/RTS scan — and the full in-memory posterior
752/// ([`gam_solve::spline_scan::SplineScanFit`]: knots, smoothed
753/// states, pointwise variances, lag-one gains, σ², log λ, exact EDF, and an
754/// exact `predict`) is returned. `Ok(None)` means the model is not the
755/// scan-eligible shape and the caller should use the dense
756/// [`fit_from_formula`] path; this keeps every persistence-bearing consumer
757/// (model save, CLI, FFI) transparently on the dense fit, whose saved payload
758/// the scan does not yet have a schema for.
759pub fn fit_spline_scan_from_formula(
760 formula: &str,
761 data: &Dataset,
762 config: &FitConfig,
763) -> Result<Option<gam_solve::spline_scan::SplineScanFit>, WorkflowError> {
764 let mat = materialize(formula, data, config)?;
765 let FitRequest::Standard(request) = mat.request else {
766 return Ok(None);
767 };
768 let Some(inputs) = spline_scan_fast_path(&request) else {
769 return Ok(None);
770 };
771 gam_solve::spline_scan::fit_spline_scan(&inputs.x, &inputs.y, &inputs.w, inputs.order)
772 .map(Some)
773 .map_err(|reason| WorkflowError::IntegrationFailed { reason })
774}
775
776/// #1464 diagnostic entry point: evaluate the EXACT production fixed-κ
777/// profiled-REML criterion (`fixed_kappa_profiled_reml_score`, the same one the
778/// joint-fit κ-sign scan uses) at a list of pinned κ values for the first
779/// constant-curvature term of `formula`, materialised from `data`/`config`
780/// exactly like [`fit_from_formula`]. Returns `(κ, V_p(κ))` pairs.
781///
782/// This settles solver-vs-criterion for the railing bug: if `V_p(+κ) < V_p(−κ)`
783/// for a genuinely HYPERBOLIC dataset, the criterion itself prefers the collapsed
784/// +κ corner — the bug is in the constant-curvature REML/Occam term, not the
785/// optimiser. If `V_p(−κ) < V_p(+κ)` yet the full fit still returns +κ, the bug
786/// is in the solver/readback. The profiled fit pins κ and profiles only ρ
787/// (κ-optimisation disabled), so each returned score is the negative-log-evidence
788/// the outer loop minimises.
789pub fn constant_curvature_profiled_reml_scores(
790 formula: &str,
791 data: &Dataset,
792 config: &FitConfig,
793 kappas: &[f64],
794) -> Result<Vec<(f64, f64)>, WorkflowError> {
795 let mat = materialize(formula, data, config)?;
796 let FitRequest::Standard(request) = mat.request else {
797 return Err(WorkflowError::IntegrationFailed {
798 reason: "constant_curvature_profiled_reml_scores: formula did not materialise to a \
799 standard fit request"
800 .to_string(),
801 });
802 };
803 let term_idx = *crate::fit_orchestration::drivers::constant_curvature_term_indices(&request.spec)
804 .first()
805 .ok_or_else(|| WorkflowError::IntegrationFailed {
806 reason: "constant_curvature_profiled_reml_scores: formula has no constant-curvature \
807 curv() term"
808 .to_string(),
809 })?;
810 let mut out = Vec::with_capacity(kappas.len());
811 for &kappa in kappas {
812 let score = crate::fit_orchestration::drivers::fixed_kappa_profiled_reml_score(
813 request.data.view(),
814 request.y.view(),
815 request.weights.view(),
816 request.offset.view(),
817 &request.spec,
818 term_idx,
819 kappa,
820 request.family.clone(),
821 &request.options,
822 )
823 .map_err(|e| WorkflowError::IntegrationFailed {
824 reason: format!(
825 "constant_curvature_profiled_reml_scores: fixed-κ fit at κ={kappa} failed: {e}"
826 ),
827 })?;
828 out.push((kappa, score));
829 }
830 Ok(out)
831}
832
833/// Derived dense-kernel cliff: the cascade auto-route fires only once the dense
834/// radial basis the smooth would otherwise use has SATURATED at its center cap
835/// (`default_num_centers == K_MAX`), so the dense `O(n·K² + K³)` kernel solve
836/// can no longer grow resolution with `n` and the streaming cascade's
837/// `O(n·polylog)` is the only path that keeps improving. This is the structural
838/// "past the dense-kernel cliff" condition the issue names — derived from the
839/// dense sizing rule, NOT a magic n constant or a user flag.
840fn past_dense_kernel_cliff(n: usize, d: usize) -> bool {
841 // `default_num_centers` clamps to K_MAX = 2000; equality means the dense
842 // basis is pinned at the cap and cannot densify further with n.
843 const DENSE_CENTER_CAP: usize = 2000;
844 gam_terms::basis::default_num_centers(n, d) >= DENSE_CENTER_CAP
845}
846
847/// Map a Duchon/Matérn smoothness order onto the cascade's Sobolev order,
848/// clamped into the Wendland-(3,1) native window `(d/2, (d+3)/2]` (issue
849/// caveat 1: the multilevel frame can only represent up to `H^{(d+3)/2}`).
850fn cascade_sobolev_order(requested: f64, d: usize) -> f64 {
851 let lo = d as f64 / 2.0;
852 let hi = (d as f64 + 3.0) / 2.0;
853 // Nudge strictly inside the open lower bound when the request lands on it.
854 let eps = 1e-6 * (hi - lo);
855 requested.clamp(lo + eps, hi)
856}
857
858/// Detection seam for the O(n log n) multiresolution residual-cascade fast path
859/// (issue #1032).
860///
861/// This mirrors [`spline_scan_fast_path`] in shape but carries one CRITICAL
862/// difference dictated by the issue: the cascade is **not** the same posterior
863/// as the Duchon/Matérn term it stands in for (a different finite basis — the
864/// multilevel Wendland frame, not the reduced-rank radial kernel). So unlike
865/// the 1-D scan, which silently swaps an identical posterior, this path must
866/// only fire as an explicit alternative estimator on the structural signature
867/// the issue names, never as a transparent replacement. It returns `Some` only
868/// when ALL of the following hold:
869/// - family is Gaussian + identity link (the scattered low-d smooth the
870/// cascade solves);
871/// - none of the exotic-link / constraint / Firth / Kronecker / coefficient-
872/// group / hyperprior machinery is engaged;
873/// - the model is exactly one smooth term — no linear terms, no random
874/// effects, no by-variables;
875/// - that smooth is a scattered radial spatial smooth (`Duchon` or `Matern`)
876/// over `d ∈ {2, 3}` coordinates with no shape constraint;
877/// - the offset is identically zero and every weight is finite and positive;
878/// - `n` is past the derived dense-kernel cliff
879/// ([`past_dense_kernel_cliff`]) — below it the dense radial path is both
880/// exact-posterior and cheap, so there is no reason to change estimators.
881///
882/// The returned [`ResidualCascadeInputs`] carry a unit per-axis metric (the
883/// spec's isotropic radial distance); the quasi-uniformity guard inside
884/// [`gam_solve::residual_cascade::fit_residual_cascade`] (issue caveat 2)
885/// is the no-regression gate that refuses the iterative solve — and forces the
886/// caller back to the dense path — when a near-degenerate metric would break
887/// the BPX iteration bound.
888pub fn residual_cascade_fast_path(
889 request: &StandardFitRequest<'_>,
890) -> Option<ResidualCascadeInputs> {
891 if !request.family.is_gaussian_identity() {
892 return None;
893 }
894 if request.wiggle.is_some()
895 || request.latent_coord.is_some()
896 || !request.coefficient_groups.is_empty()
897 || !request.penalty_block_gamma_priors.is_empty()
898 {
899 return None;
900 }
901 let options = &request.options;
902 if options.latent_cloglog.is_some()
903 || options.mixture_link.is_some()
904 || options.sas_link.is_some()
905 || options.linear_constraints.is_some()
906 || options.adaptive_regularization.is_some()
907 || options.kronecker_penalty_system.is_some()
908 || options.kronecker_factored.is_some()
909 || options.firth_bias_reduction
910 || !options.nullspace_dims.is_empty()
911 {
912 return None;
913 }
914 let spec = &request.spec;
915 if !spec.linear_terms.is_empty()
916 || !spec.random_effect_terms.is_empty()
917 || spec.smooth_terms.len() != 1
918 {
919 return None;
920 }
921 let term = &spec.smooth_terms[0];
922 if !matches!(term.shape, gam_terms::smooth::ShapeConstraint::None)
923 || term.joint_null_rotation.is_some()
924 {
925 return None;
926 }
927 // Only scattered radial spatial smooths (Duchon / Matérn) over 2–3 axes.
928 // The Duchon spectral power `p + s` and the Matérn order set the requested
929 // Sobolev smoothness; both clamp into the Wendland native window.
930 let (feature_cols, requested_s) = match &term.basis {
931 gam_terms::smooth::SmoothBasisSpec::Duchon {
932 feature_cols, spec, ..
933 } => {
934 // Pure-Duchon native order is `p + s` (kernel exponent 2(p+s)−d);
935 // the multilevel frame targets the same continuum smoothness. `p`
936 // is the polynomial nullspace degree, `s` the spectral power.
937 let p = match spec.nullspace_order {
938 gam_terms::basis::DuchonNullspaceOrder::Zero => 0.0,
939 gam_terms::basis::DuchonNullspaceOrder::Linear => 1.0,
940 gam_terms::basis::DuchonNullspaceOrder::Degree(k) => k as f64,
941 };
942 (feature_cols, spec.power + p)
943 }
944 gam_terms::smooth::SmoothBasisSpec::Matern {
945 feature_cols, spec, ..
946 } => {
947 // Matérn smoothness ν sets native Sobolev order ν + d/2; the cascade
948 // frame represents up to (d+3)/2, so the clamp below applies the
949 // ceiling. (d is known just below from feature_cols.)
950 let nu = spec.nu.half_integer_value();
951 (feature_cols, nu + feature_cols.len() as f64 / 2.0)
952 }
953 _ => return None,
954 };
955 let d = feature_cols.len();
956 if !(2..=3).contains(&d) {
957 return None;
958 }
959 if request.offset.iter().any(|&v| v != 0.0) {
960 return None;
961 }
962 if request.weights.iter().any(|&v| !(v.is_finite() && v > 0.0)) {
963 return None;
964 }
965 let n = request.y.len();
966 if n != request.data.nrows() || feature_cols.iter().any(|&c| c >= request.data.ncols()) {
967 return None;
968 }
969 if !past_dense_kernel_cliff(n, d) {
970 return None;
971 }
972 let coords: Vec<Vec<f64>> = feature_cols
973 .iter()
974 .map(|&c| request.data.column(c).iter().copied().collect())
975 .collect();
976 let y: Vec<f64> = request.y.iter().copied().collect();
977 let w: Vec<f64> = request.weights.iter().copied().collect();
978 if coords
979 .iter()
980 .any(|axis| axis.iter().any(|v| !v.is_finite()))
981 || y.iter().any(|v| !v.is_finite())
982 {
983 return None;
984 }
985 let metric = vec![1.0_f64; d];
986 let sobolev_s = cascade_sobolev_order(requested_s, d);
987 Some(ResidualCascadeInputs {
988 coords,
989 y,
990 w,
991 metric,
992 sobolev_s,
993 })
994}
995
996/// Formula-level library entry for the O(n log n) residual-cascade fast path
997/// (issue #1032).
998///
999/// Materializes the formula exactly like [`fit_from_formula`], runs the
1000/// [`residual_cascade_fast_path`] detection, and — when it fires AND the
1001/// quasi-uniformity guard inside the cascade certifies the metric — returns the
1002/// certified [`ResidualCascadeFit`](gam_solve::residual_cascade::ResidualCascadeFit).
1003/// `Ok(None)` means EITHER the model is not the cascade-eligible shape OR the
1004/// quasi-uniformity guard rejected the metric; in both cases the caller falls
1005/// back to the dense [`fit_from_formula`] path (the cascade is a different
1006/// posterior, so the fallback is a genuine estimator choice, never a silent
1007/// swap). This keeps every persistence-bearing consumer on the dense fit until
1008/// the cascade payload schema lands.
1009pub fn fit_residual_cascade_from_formula(
1010 formula: &str,
1011 data: &Dataset,
1012 config: &FitConfig,
1013) -> Result<Option<gam_solve::residual_cascade::ResidualCascadeFit>, WorkflowError> {
1014 let mat = materialize(formula, data, config)?;
1015 let FitRequest::Standard(request) = mat.request else {
1016 return Ok(None);
1017 };
1018 let Some(inputs) = residual_cascade_fast_path(&request) else {
1019 return Ok(None);
1020 };
1021 let coord_refs: Vec<&[f64]> = inputs.coords.iter().map(Vec::as_slice).collect();
1022 match gam_solve::residual_cascade::fit_residual_cascade(
1023 &coord_refs,
1024 &inputs.y,
1025 &inputs.w,
1026 &inputs.metric,
1027 inputs.sobolev_s,
1028 ) {
1029 Ok(fit) => Ok(Some(fit)),
1030 // The quasi-uniformity guard (caveat 2) and any degenerate-design
1031 // signal both surface as a build/solve error; treat them as "not
1032 // cascade-eligible" so the caller falls back to the dense kernel path
1033 // rather than failing the fit outright.
1034 Err(_) => Ok(None),
1035 }
1036}
1037
1038/// Parse a formula, resolve it against a dataset, and produce a ready-to-fit `FitRequest`.
1039pub fn materialize<'a>(
1040 formula: &str,
1041 data: &'a Dataset,
1042 config: &FitConfig,
1043) -> Result<MaterializedModel<'a>, WorkflowError> {
1044 gam_gpu::configure_global_policy(config.gpu_policy);
1045 let parsed = parse_formula(formula)?;
1046 let col_map = data.column_map();
1047
1048 if let Some((left_col, right_col, event_col)) = parse_surv_interval_response(&parsed.response)?
1049 {
1050 if config.transformation_normal {
1051 return Err(WorkflowError::InvalidConfig {
1052 reason:
1053 "transformation_normal cannot be combined with a SurvInterval(...) response"
1054 .to_string(),
1055 });
1056 }
1057 // Interval censoring `T ∈ (L, R]` is only defined for the latent
1058 // hazard-window survival likelihood, whose kernel carries the
1059 // `log[S(L) − S(R)]` interval contribution. Route the left boundary `L`
1060 // through the standard exit channel and the right boundary `R` through
1061 // the dedicated interval-right channel; `event_col` distinguishes
1062 // bracketed (interval) rows from right-censored rows beyond the last
1063 // inspection (which carry an infinite/sentinel `R`).
1064 materialize_survival(
1065 &parsed,
1066 data,
1067 &col_map,
1068 config,
1069 None,
1070 &left_col,
1071 &event_col,
1072 Some(&right_col),
1073 )
1074 } else if let Some((entry_col, exit_col, event_col)) = parse_surv_response(&parsed.response)? {
1075 if config.transformation_normal {
1076 return Err(WorkflowError::InvalidConfig {
1077 reason: "transformation_normal cannot be combined with a Surv(...) response"
1078 .to_string(),
1079 });
1080 }
1081 // `materialize_*` now return `WorkflowError` directly so the typed
1082 // `ColumnNotFound` payload (and any future variant-typed leaf
1083 // errors) survive the dispatcher hop instead of being flattened
1084 // into `IntegrationFailed { reason: String }`.
1085 materialize_survival(
1086 &parsed,
1087 data,
1088 &col_map,
1089 config,
1090 entry_col.as_deref(),
1091 &exit_col,
1092 &event_col,
1093 None,
1094 )
1095 } else {
1096 // Non-survival response: `timewiggle(...)` and `survmodel(...)` are
1097 // structurally meaningless (there is no baseline hazard / time axis to
1098 // wiggle and no survival likelihood to configure). They are parsed into
1099 // `ParsedFormula` but consumed *only* by `materialize_survival`; without
1100 // this guard every non-survival materializer below would silently drop
1101 // them, fitting an ordinary GAM while the user believes they requested a
1102 // time-varying / survival model (#371). Reject here — the single
1103 // chokepoint for all non-survival paths — mirroring the symmetric
1104 // auxiliary-formula rejection in `validate_auxiliary_formula_controls`.
1105 reject_survival_only_terms_for_nonsurvival(&parsed)?;
1106 if config.transformation_normal {
1107 // Issue #789A: a Bernoulli marginal-slope request with
1108 // `transformation_normal=true` used to dispatch as a CTN fit while
1109 // retaining marginal-slope controls, leaving the transformation path
1110 // in a non-advancing loop. CTN score calibration now uses the
1111 // explicit `ctn_stage1` recipe instead, so the legacy boolean is a
1112 // hard configuration error for marginal-slope requests.
1113 reject_marginal_slope_controls_for_transformation_normal(config)?;
1114 if config.noise_formula.is_some() {
1115 return Err(WorkflowError::InvalidConfig {
1116 reason: "transformation_normal cannot be combined with noise_formula"
1117 .to_string(),
1118 });
1119 }
1120 materialize_transformation_normal(&parsed, data, &col_map, config)
1121 } else if config.logslope_formula.is_some() || config.z_column.is_some() {
1122 materialize_bernoulli_marginal_slope(&parsed, data, &col_map, config)
1123 } else if config.noise_formula.is_some() {
1124 materialize_location_scale(&parsed, data, &col_map, config)
1125 } else {
1126 materialize_standard(&parsed, data, &col_map, config)
1127 }
1128 }
1129}
1130
1131#[cfg(test)]
1132mod sz_factor_smooth_recovery_tests {
1133 // `super::*` brings in `Dataset` (= gam_data::EncodedDataset), `FitConfig`,
1134 // `FitResult`, `StandardFitResult`, and `fit_from_formula`.
1135 use super::*;
1136
1137 const NOISE_SD: f64 = 0.20;
1138 const N: usize = 4000;
1139 const N_GROUPS: usize = 4;
1140
1141 /// A simple deterministic LCG so the dataset is reproducible without pulling
1142 /// an RNG dependency into the test.
1143 struct Lcg(u64);
1144 impl Lcg {
1145 fn next_u64(&mut self) -> u64 {
1146 // Numerical Recipes LCG constants.
1147 self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1148 self.0
1149 }
1150 /// Uniform in [0, 1).
1151 fn unif(&mut self) -> f64 {
1152 (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
1153 }
1154 /// Standard normal via Box–Muller (one of the pair).
1155 fn normal(&mut self) -> f64 {
1156 let u1 = (self.unif()).max(1e-12);
1157 let u2 = self.unif();
1158 (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
1159 }
1160 }
1161
1162 /// Data drawn from EXACTLY the `sz` model class: a shared smooth `f0(x)` plus
1163 /// zero-sum per-group deviations `d_g(x)` (phase-shifted sinusoids whose
1164 /// cross-group mean is removed at every `x`), plus observation noise. This
1165 /// mirrors the (blocked) Python bug-hunt test `tests/bug_hunt_sz_factor_
1166 /// smooth_underfits_own_model_class_test.py`.
1167 ///
1168 /// Written to a CSV and loaded through the real `load_dataset_projected`
1169 /// inferer so the grouping column `g` (string levels) is encoded as a genuine
1170 /// categorical exactly as production does — hand-built `EncodedDataset`s do
1171 /// not carry the categorical level map the factor-smooth level resolver needs.
1172 fn sz_class_dataset() -> (Dataset, tempfile::TempDir) {
1173 let mut rng = Lcg(0x5326_2026_0628_1605);
1174 let phases: Vec<f64> = (0..N_GROUPS)
1175 .map(|k| 1.2 * k as f64 / (N_GROUPS as f64 - 1.0))
1176 .collect();
1177 let deviations = |xi: f64| -> Vec<f64> {
1178 let vals: Vec<f64> = phases
1179 .iter()
1180 .map(|p| 0.6 * (std::f64::consts::TAU * xi + std::f64::consts::TAU * p).sin())
1181 .collect();
1182 let mean = vals.iter().sum::<f64>() / vals.len() as f64;
1183 vals.iter().map(|v| v - mean).collect()
1184 };
1185
1186 let mut csv = String::from("y,x,g\n");
1187 for _ in 0..N {
1188 let x = rng.unif();
1189 // Use the HIGH bits (via `unif`) for the group draw — an LCG's low
1190 // bits have a tiny period and would collapse `% N_GROUPS` to a near
1191 // constant.
1192 let g = ((rng.unif() * N_GROUPS as f64) as usize).min(N_GROUPS - 1);
1193 let f0 = (std::f64::consts::TAU * x).sin();
1194 let mu = f0 + deviations(x)[g];
1195 let y = mu + NOISE_SD * rng.normal();
1196 csv.push_str(&format!("{y},{x},g{g}\n"));
1197 }
1198 let td = tempfile::tempdir().expect("tempdir");
1199 let path = td.path().join("sz_class.csv");
1200 std::fs::write(&path, csv).expect("write sz-class csv");
1201 // Force `g` into a categorical role exactly as the formula intends so the
1202 // factor-smooth level resolver sees all `N_GROUPS` distinct levels.
1203 let mut roles = std::collections::HashSet::new();
1204 roles.insert("g");
1205 let data = gam_data::load_dataset_projected_with_categorical_roles(
1206 &path,
1207 &["y".to_string(), "x".to_string(), "g".to_string()],
1208 &roles,
1209 )
1210 .expect("load sz-class dataset");
1211 (data, td)
1212 }
1213
1214 fn gaussian_config() -> FitConfig {
1215 FitConfig { family: Some("gaussian".to_string()), ..FitConfig::default() }
1216 }
1217
1218 /// In-sample residual sd of a fitted standard GAM: `sd(y − Xβ̂)`.
1219 fn residual_sd(fit: &StandardFitResult, data: &Dataset) -> f64 {
1220 let beta = &fit.fit.beta;
1221 let design = &fit.design.design;
1222 let n = design.nrows();
1223 assert_eq!(design.ncols(), beta.len(), "design/beta width mismatch");
1224 let mut fitted = vec![0.0f64; n];
1225 // `try_row_chunk` materializes contiguous row blocks of whatever design
1226 // storage the fit used (dense or block-lazy) — robust to the storage kind.
1227 const CHUNK: usize = 512;
1228 let mut start = 0usize;
1229 while start < n {
1230 let end = (start + CHUNK).min(n);
1231 let block = design
1232 .try_row_chunk(start..end)
1233 .expect("materialize design row chunk");
1234 for (r, row) in block.rows().into_iter().enumerate() {
1235 let mut acc = 0.0;
1236 for (c, &xv) in row.iter().enumerate() {
1237 acc += xv * beta[c];
1238 }
1239 fitted[start + r] = acc;
1240 }
1241 start = end;
1242 }
1243 let y = data.values.column(0);
1244 let resid: Vec<f64> = y.iter().zip(fitted.iter()).map(|(&yi, &fi)| yi - fi).collect();
1245 let mean = resid.iter().sum::<f64>() / resid.len() as f64;
1246 let var = resid.iter().map(|r| (r - mean).powi(2)).sum::<f64>() / resid.len() as f64;
1247 var.sqrt()
1248 }
1249
1250 fn fit_standard(formula: &str, data: &Dataset) -> StandardFitResult {
1251 match fit_from_formula(formula, data, &gaussian_config())
1252 .unwrap_or_else(|e| panic!("fit `{formula}` failed: {e:?}"))
1253 {
1254 FitResult::Standard(r) => r,
1255 other => panic!("expected Standard fit for `{formula}`, got a different variant: {}",
1256 std::any::type_name_of_val(&other)),
1257 }
1258 }
1259
1260 /// #1605 (gold standard, end-to-end REML fit): the sum-to-zero factor smooth
1261 /// `s(x) + s(g, x, bs="sz")` must RECOVER data drawn from its own model class
1262 /// to the observation-noise floor, exactly as the strictly-more-general
1263 /// `s(x, g, bs="fs")` superset provably does.
1264 ///
1265 /// The recovery gap (`sz` resid ≈ 0.43 ≈ 2.1× the 0.20 floor while `fs`
1266 /// reaches the floor) was closed by THREE mgcv-faithful corrections, each
1267 /// necessary, that this end-to-end fit jointly exercises:
1268 /// 1. marginal basis (baef17e): cr → curvature-capable B-spline, so a
1269 /// deviation with non-zero boundary curvature is representable;
1270 /// 2. ownership/overlap residualization (b49bb5c): the `sz` deviation is
1271 /// sum-to-zero ACROSS the grouping factor, hence orthogonal to a
1272 /// factor-independent owner like the shared `s(x)`. Residualizing it
1273 /// against `s(x)`'s realized span (the #978 chart) collapsed every
1274 /// group's curve to a flat per-group contrast; skipping that ownership
1275 /// (same family as the #1276 factor-`by` level gate) restores the curve
1276 /// shape and stops REML railing the shared `s(x)` wiggliness λ;
1277 /// 3. null-space ridge (this change): the `sz` deviation blocks now carry
1278 /// the per-null-dimension ridge structure of `fs`, mapped into the
1279 /// zero-sum contrast space, so the {const, linear} null space is
1280 /// shrinkable per dimension (the #700/#712/#713 partial-pooling form)
1281 /// rather than left free — without breaking the zero-sum constraint.
1282 ///
1283 /// This is the gold-standard verification: it drives the real
1284 /// `fit_from_formula` REML λ-selection on data drawn from exactly the `sz`
1285 /// model class and asserts `sz` reaches the floor (and a `fs` control does
1286 /// too). It failed before the fixes and passes after.
1287 #[test]
1288 fn sz_factor_smooth_recovers_its_own_model_class_end_to_end() {
1289 let (data, _td) = sz_class_dataset();
1290
1291 // Control: bs="fs", a strict superset of the sz span, must reach the
1292 // noise floor — proves the data is well-posed and pins the floor.
1293 let fs_fit = fit_standard("y ~ s(x, g, bs='fs')", &data);
1294 let fs_resid = residual_sd(&fs_fit, &data);
1295 assert!(
1296 fs_resid < 1.2 * NOISE_SD,
1297 "control bs='fs' did not reach the noise floor: resid_sd={fs_resid:.4} \
1298 vs noise_sd={NOISE_SD} (data/floor sanity check)",
1299 );
1300
1301 // The documented sz idiom on data drawn from the sz model class.
1302 let sz_fit = fit_standard("y ~ s(x) + s(g, x, bs='sz')", &data);
1303 let sz_resid = residual_sd(&sz_fit, &data);
1304
1305 // A smoother whose span contains the truth, fit at large n, must explain
1306 // the systematic structure and leave ~only observation noise.
1307 assert!(
1308 sz_resid < 1.4 * NOISE_SD,
1309 "bs='sz' under-fits its own model class: resid_sd={sz_resid:.4} \
1310 ({:.2}x the noise floor {NOISE_SD}); the bs='fs' superset reached \
1311 {fs_resid:.4}. The sz fit leaves systematic signal in the residual.",
1312 sz_resid / NOISE_SD,
1313 );
1314
1315 // Comparative guard: sz must not be dramatically worse than the fs
1316 // superset that recovers the same data.
1317 assert!(
1318 sz_resid < 1.5 * fs_resid,
1319 "bs='sz' residual {sz_resid:.4} is {:.2}x the bs='fs' residual \
1320 {fs_resid:.4} on identical sz-class data",
1321 sz_resid / fs_resid,
1322 );
1323 }
1324}