Skip to main content

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(result) = fit_expectile_if_requested(formula, data, config)? {
381        return Ok(FitResult::Standard(result));
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/// THE single dispatch seam for the expectile (Newey–Powell LAWS) family.
439///
440/// Returns `Ok(Some(result))` with the converged τ-expectile as an ordinary
441/// [`StandardFitResult`] when `config.family` selects the expectile family
442/// (`"expectile"` or `"expectile(τ)"`, optionally pinned by
443/// [`FitConfig::expectile_tau`]), `Ok(None)` for every other family — in which
444/// case the caller runs its normal materialize/`fit_model` path — and `Err` on a
445/// malformed expectile request or an inner-fit failure.
446///
447/// Every public entry point that resolves a family routes through this seam
448/// *before* materializing: the in-process [`fit_from_formula`], the Python FFI
449/// (`gam-pyffi`), and the `gam` CLI. Centralizing the dispatch here is what makes
450/// the estimator reachable from every interface instead of only the library
451/// call — and what prevents the class of bug where a newly-added outer estimator
452/// is wired into one entry point and silently bypassed by the others (#1777).
453/// The returned [`StandardFitResult`] carries the full design / resolved spec /
454/// fit, so each caller builds its persistence payload from it exactly as it does
455/// for any other standard fit.
456pub fn fit_expectile_if_requested(
457    formula: &str,
458    data: &Dataset,
459    config: &FitConfig,
460) -> Result<Option<StandardFitResult>, WorkflowError> {
461    match expectile_tau_for_config(config)? {
462        Some(tau) => Ok(Some(fit_expectile_laws(formula, data, config, tau)?)),
463        None => Ok(None),
464    }
465}
466
467/// Least Asymmetrically Weighted Squares (LAWS) driver for expectile GAMs.
468///
469/// The τ-expectile surface minimizes `Σ wᵢ(τ)·(yᵢ − μᵢ)²` with the residual-
470/// sign asymmetric weight `wᵢ(τ)`. Because that weight is piecewise-constant in
471/// `sign(yᵢ − μᵢ)`, the objective is the supremum of a finite family of
472/// weighted least-squares problems and its minimizer is the unique fixed point
473/// of: *solve the penalized WLS with weights frozen at the current sign
474/// pattern, then recompute the sign pattern from the new fit*. The asymmetric
475/// loss is strictly convex (weights bounded in `[min(τ,1−τ), max(τ,1−τ)] > 0`),
476/// so this monotone-descent iteration converges, and since the sign pattern
477/// takes finitely many values it stabilizes in finitely many steps (Schnabel &
478/// Eilers 2009; the same Newton/IRLS-for-expectiles `expectreg` runs).
479///
480/// Each inner solve is the FULL standard Gaussian-identity GAM: any basis,
481/// tensor, spatial smooth, by-variable, random effect, plus REML λ-selection on
482/// the current asymmetric weights. The returned fit is an ordinary
483/// [`FitResult::Standard`] whose coefficients ARE the penalized τ-expectile —
484/// every downstream consumer (predict, posterior bands, persistence) works
485/// unchanged. The reported scale is the asymmetric working variance, so
486/// expectile standard errors are the sandwich-free Gaussian-form bands of the
487/// converged weighted problem (a deliberate first-rung choice; see #1100).
488fn fit_expectile_laws(
489    formula: &str,
490    data: &Dataset,
491    config: &FitConfig,
492    tau: f64,
493) -> Result<StandardFitResult, WorkflowError> {
494    use gam_linalg::matrix::LinearOperator;
495
496    // Inner fits are ordinary Gaussian-identity GAMs; the τ asymmetry lives
497    // entirely in the per-iteration prior weights this driver injects.
498    let gaussian_config = FitConfig {
499        family: Some("gaussian".to_string()),
500        link: Some("identity".to_string()),
501        expectile_tau: None,
502        // The inner Gaussian-identity design carries no frailty; the CLI always
503        // populates `frailty = Some(FrailtySpec::None)`, which the standard
504        // materializer's guard rejects (`config.frailty is not supported for
505        // standard family`). Clear it explicitly so the inner fit routes through
506        // the standard family (#1780). Guarded by the CLI regression test
507        // `bug_hunt_expectile_cli_fit_aborts_on_frailty_guard`.
508        frailty: None,
509        ..config.clone()
510    };
511
512    // Materialize once to capture the fixed training design, response, offset,
513    // and base prior weights. The design (basis, penalties, identifiability
514    // transforms) does not depend on the prior weights, so it is reused across
515    // every LAWS iteration; only the weight vector and the resulting β change.
516    let base_mat = materialize(formula, data, &gaussian_config)?;
517    let FitRequest::Standard(base_request) = base_mat.request else {
518        return Err(WorkflowError::InvalidConfig {
519            reason: "expectile regression is only defined for standard (non-survival, \
520                     non-location-scale) responses"
521                .to_string(),
522        });
523    };
524    let StandardFitRequest {
525        data: design_data,
526        y,
527        weights: base_weights,
528        offset,
529        spec,
530        family: materialized_family,
531        options,
532        kappa_options,
533        wiggle,
534        coefficient_groups,
535        penalty_block_gamma_priors,
536        latent_coord,
537        _marker,
538    } = base_request;
539    // The materializer already resolved the inner family to Gaussian-identity
540    // from `gaussian_config`; assert it so a future materializer change that
541    // silently picked a different family for `"gaussian"` is caught here rather
542    // than producing a non-expectile fit.
543    if !materialized_family.is_gaussian_identity() {
544        return Err(WorkflowError::InvalidConfig {
545            reason: format!(
546                "expectile LAWS requires a Gaussian-identity inner family; materializer produced {}",
547                materialized_family.name()
548            ),
549        });
550    }
551
552    if wiggle.is_some() || latent_coord.is_some() {
553        return Err(WorkflowError::InvalidConfig {
554            reason: "expectile regression does not support flexible-link wiggle or latent \
555                     coordinates"
556                .to_string(),
557        });
558    }
559
560    let n = y.len();
561    let gaussian_family = LikelihoodSpec::gaussian_identity();
562    // Cold start: τ = 0.5 (symmetric) weights ⇒ the first inner fit is the OLS
563    // mean GAM, the natural warm start for any τ.
564    let mut weights = base_weights.clone();
565    let mut last_sign: Option<Vec<bool>> = None;
566    let mut last_result: Option<StandardFitResult> = None;
567
568    // The sign pattern has 2ⁿ values but LAWS visits a monotone-descent subset;
569    // empirically a handful of iterations suffice. The cap is a safety guard:
570    // on the rare oscillation between two equal-objective sign patterns (only
571    // possible when rows sit exactly on the fitted surface) the last fit is a
572    // valid τ-expectile of the perturbation-stable problem, so returning it is
573    // correct rather than an error.
574    const MAX_LAWS_ITERS: usize = 50;
575
576    for _iter in 0..MAX_LAWS_ITERS {
577        let request = StandardFitRequest {
578            data: design_data.clone(),
579            y: y.clone(),
580            weights: weights.clone(),
581            offset: offset.clone(),
582            spec: spec.clone(),
583            family: gaussian_family.clone(),
584            options: options.clone(),
585            kappa_options: kappa_options.clone(),
586            wiggle: None,
587            coefficient_groups: coefficient_groups.clone(),
588            penalty_block_gamma_priors: penalty_block_gamma_priors.clone(),
589            latent_coord: None,
590            _marker,
591        };
592        let result = fit_standard_model(request)
593            .map_err(|reason| WorkflowError::IntegrationFailed { reason })?;
594
595        // Training-scale fitted mean μ = X·β (identity link, zero-checked
596        // offset folded by the design path). The design columns match the
597        // combined coefficient vector exactly (the same contract `predict`
598        // and the safety tests rely on).
599        let mu = result.design.design.apply(&result.fit.beta);
600        if mu.len() != n {
601            return Err(WorkflowError::IntegrationFailed {
602                reason: format!(
603                    "expectile LAWS: fitted mean length {} disagrees with response length {n}",
604                    mu.len()
605                ),
606            });
607        }
608        let mut mu_off = mu;
609        mu_off += &offset;
610
611        let sign: Vec<bool> = (0..n).map(|i| y[i] > mu_off[i]).collect();
612        let converged = last_sign.as_ref().is_some_and(|prev| prev == &sign);
613        weights = expectile_row_weights(y.view(), mu_off.view(), base_weights.view(), tau);
614        last_sign = Some(sign);
615        last_result = Some(result);
616        if converged {
617            break;
618        }
619    }
620
621    let result = last_result.ok_or_else(|| WorkflowError::IntegrationFailed {
622        reason: "expectile LAWS produced no fit".to_string(),
623    })?;
624    Ok(result)
625}
626/// Detection seam for the exact O(n) cubic-smoothing-spline fast path.
627///
628/// This is the EARLIEST point in the standard workflow where a materialized
629/// fit request carries everything needed to prove the model is exactly the
630/// problem the scan solves: a Gaussian likelihood with identity link over
631/// `intercept + one 1-D cubic-class penalized smooth` — i.e. the penalized
632/// least-squares problem `min Σ w_i (y_i − f(x_i))² + λ∫f″²` with an
633/// unpenalized `{1, x}` null space. The Kalman/RTS scan computes that
634/// posterior (mean, pointwise variance, exact diffuse REML for λ) in O(n) per
635/// λ-trial instead of the dense design/Gram O(n·k²) + O(k³) route.
636///
637/// Returns `Some` only when ALL of the following hold; everything else falls
638/// through to the dense path:
639/// - family is Gaussian + identity link;
640/// - no link wiggle, no latent coordinates, no coefficient groups, no penalty
641///   hyperpriors, no linear/box constraints, no Firth, no adaptive
642///   regularization, no Kronecker systems, no externally injected null-space
643///   dims;
644/// - the term collection is exactly one smooth term — no linear terms, no
645///   random effects, no by-variables / factor interactions;
646/// - that smooth is a plain 1-D B-spline whose penalty order is compatible
647///   with the exact scan and whose null space is unshrunk
648///   (`double_penalty=false`). `double_penalty` (mgcv `select = TRUE`) on a free
649///   B-spline emits a second REML coordinate — the Marra & Wood (2011) null-space
650///   shrinkage block — that the scan cannot represent (its polynomial null space
651///   is an improper diffuse prior it can never shrink); routing such a fit
652///   through the scan would silently drop that penalty and select λ from the
653///   bending penalty alone, which is exactly the EDF inflation #1266 reports.
654///   Those fits fall through to the dense two-rho path, which owns both penalties
655///   jointly;
656/// - the offset is identically zero and every weight is finite and positive;
657/// - at least 3 distinct finite abscissae (the scan's diffuse rank plus one).
658///
659/// λ-mapping note: the scan's penalty is exactly `λ∫f″²` (state-space
660/// `q = 1/λ` at unit σ²). The dense 1-D B-spline path penalizes the same
661/// cubic class through a reduced-rank discrete-difference Gram whose
662/// normalization differs by a basis-dependent constant, so a λ selected by
663/// one parameterization does not transfer numerically to the other. The scan
664/// therefore always re-selects λ by its own exact diffuse REML criterion
665/// (the optimizer of the same restricted likelihood, expressed in the scan's
666/// parameterization); user-pinned smoothing parameters are not representable
667/// at this seam (the formula DSL exposes none for this term class), so no
668/// pinned-λ mapping arises.
669///
670/// Identifiability transforms on the smooth (centering / linear-trend
671/// removal / orthogonality-to-intercept) are accepted as eligible: they only
672/// re-coordinate the unpenalized null space against the implicit intercept
673/// and do not change the fitted posterior of `E[y|x]`, which is what the
674/// scan returns directly.
675pub fn spline_scan_fast_path(request: &StandardFitRequest<'_>) -> Option<SplineScanInputs> {
676    if !request.family.is_gaussian_identity() {
677        return None;
678    }
679    if request.wiggle.is_some()
680        || request.latent_coord.is_some()
681        || !request.coefficient_groups.is_empty()
682        || !request.penalty_block_gamma_priors.is_empty()
683    {
684        return None;
685    }
686    let options = &request.options;
687    if options.latent_cloglog.is_some()
688        || options.mixture_link.is_some()
689        || options.sas_link.is_some()
690        || options.linear_constraints.is_some()
691        || options.adaptive_regularization.is_some()
692        || options.kronecker_penalty_system.is_some()
693        || options.kronecker_factored.is_some()
694        || options.firth_bias_reduction
695        || !options.nullspace_dims.is_empty()
696    {
697        return None;
698    }
699    let spec = &request.spec;
700    if !spec.linear_terms.is_empty()
701        || !spec.random_effect_terms.is_empty()
702        || spec.smooth_terms.len() != 1
703    {
704        return None;
705    }
706    let term = &spec.smooth_terms[0];
707    if !matches!(term.shape, gam_terms::smooth::ShapeConstraint::None)
708        || term.joint_null_rotation.is_some()
709    {
710        return None;
711    }
712    let gam_terms::smooth::SmoothBasisSpec::BSpline1D {
713        feature_col,
714        spec: bspec,
715    } = &term.basis
716    else {
717        return None;
718    };
719    // Smoothing-spline order m = penalty_order ∈ {1, 2, 3}. The exact scan
720    // integrates the order-m integrated-Wiener prior whose natural spline has
721    // degree 2m−1 (m=1 → linear, m=2 → cubic, m=3 → quintic), so require that
722    // degree to match user intent. The de Jong exact diffuse leading-block
723    // smoother (#1044) handles the m−1 partially-diffuse leading nodes for all
724    // m ≤ MAX_ORDER; m > MAX_ORDER falls through to the dense path.
725    let order = bspec.penalty_order;
726    // Double-penalty (mgcv `select = TRUE`) is NOT representable by the scan and
727    // must fall through to the dense two-rho path (#1266). On a free B-spline the
728    // double penalty emits a *second* REML coordinate — the Marra & Wood (2011)
729    // null-space shrinkage block `Z Zᵀ` (see `bspline_penalty_candidates`) —
730    // whose entire purpose is to let REML shrink the unpenalized `{1, x, …}`
731    // polynomial null space toward `EDF → 0` for an unsupported term. The scan,
732    // by construction, carries that null space as an *improper diffuse* prior it
733    // can never shrink (its EDF floor is the null-space dimension `order`), so
734    // routing a `double_penalty` fit through it silently DROPS the second penalty
735    // and selects λ from the single bending penalty alone. The scan's own exact
736    // diffuse REML then genuinely prefers a mildly wiggly fit at finite λ for
737    // some noise realizations (an interior REML optimum, EDF ≈ 3–4), which is the
738    // EDF inflation #1266 reports. The dense path owns both penalties jointly and
739    // its outer REML, seeded into the over-smoothing basin, drives the null space
740    // out (EDF → null-space dim) when the data are truly polynomial. Excluding
741    // `double_penalty` here keeps such a fit on the dense path; single-penalty
742    // and boundary-conditioned single-penalty B-splines keep the exact O(n) scan.
743    if !(1..=3).contains(&order)
744        || bspec.degree != 2 * order - 1
745        || bspec.double_penalty
746        || !bspec.boundary_conditions.is_free()
747        || !matches!(bspec.boundary, gam_terms::basis::OneDimensionalBoundary::Open)
748        || matches!(
749            bspec.knotspec,
750            gam_terms::basis::BSplineKnotSpec::PeriodicUniform { .. }
751        )
752    {
753        return None;
754    }
755    if request.offset.iter().any(|&v| v != 0.0) {
756        return None;
757    }
758    if request.weights.iter().any(|&v| !(v.is_finite() && v > 0.0)) {
759        return None;
760    }
761    if *feature_col >= request.data.ncols() || request.y.len() != request.data.nrows() {
762        return None;
763    }
764    let x: Vec<f64> = request.data.column(*feature_col).iter().copied().collect();
765    let y: Vec<f64> = request.y.iter().copied().collect();
766    let w: Vec<f64> = request.weights.iter().copied().collect();
767    if x.iter().any(|v| !v.is_finite()) || y.iter().any(|v| !v.is_finite()) {
768        return None;
769    }
770    // The diffuse polynomial null space consumes `order` innovations; the scan
771    // needs at least one proper innovation beyond them to profile σ².
772    let mut sorted = x.clone();
773    sorted.sort_by(f64::total_cmp);
774    sorted.dedup();
775    if sorted.len() < order + 1 {
776        return None;
777    }
778    Some(SplineScanInputs { x, y, w, order })
779}
780
781/// Formula-level entry for the exact O(n) cubic-smoothing-spline fast path.
782///
783/// Materializes the formula exactly like [`fit_from_formula`], then runs the
784/// [`spline_scan_fast_path`] detection on the resulting standard request.
785/// When detection fires the fit is routed through
786/// [`gam_solve::spline_scan::fit_spline_scan`] — the exact diffuse
787/// REML Kalman/RTS scan — and the full in-memory posterior
788/// ([`gam_solve::spline_scan::SplineScanFit`]: knots, smoothed
789/// states, pointwise variances, lag-one gains, σ², log λ, exact EDF, and an
790/// exact `predict`) is returned. `Ok(None)` means the model is not the
791/// scan-eligible shape and the caller should use the dense
792/// [`fit_from_formula`] path; this keeps every persistence-bearing consumer
793/// (model save, CLI, FFI) transparently on the dense fit, whose saved payload
794/// the scan does not yet have a schema for.
795pub fn fit_spline_scan_from_formula(
796    formula: &str,
797    data: &Dataset,
798    config: &FitConfig,
799) -> Result<Option<gam_solve::spline_scan::SplineScanFit>, WorkflowError> {
800    let mat = materialize(formula, data, config)?;
801    let FitRequest::Standard(request) = mat.request else {
802        return Ok(None);
803    };
804    let Some(inputs) = spline_scan_fast_path(&request) else {
805        return Ok(None);
806    };
807    gam_solve::spline_scan::fit_spline_scan(&inputs.x, &inputs.y, &inputs.w, inputs.order)
808        .map(Some)
809        .map_err(|reason| WorkflowError::IntegrationFailed { reason })
810}
811
812/// #1464 diagnostic entry point: evaluate the EXACT production fixed-κ
813/// profiled-REML criterion (`fixed_kappa_profiled_reml_score`, the same one the
814/// joint-fit κ-sign scan uses) at a list of pinned κ values for the first
815/// constant-curvature term of `formula`, materialised from `data`/`config`
816/// exactly like [`fit_from_formula`]. Returns `(κ, V_p(κ))` pairs.
817///
818/// This settles solver-vs-criterion for the railing bug: if `V_p(+κ) < V_p(−κ)`
819/// for a genuinely HYPERBOLIC dataset, the criterion itself prefers the collapsed
820/// +κ corner — the bug is in the constant-curvature REML/Occam term, not the
821/// optimiser. If `V_p(−κ) < V_p(+κ)` yet the full fit still returns +κ, the bug
822/// is in the solver/readback. The profiled fit pins κ and profiles only ρ
823/// (κ-optimisation disabled), so each returned score is the negative-log-evidence
824/// the outer loop minimises.
825pub fn constant_curvature_profiled_reml_scores(
826    formula: &str,
827    data: &Dataset,
828    config: &FitConfig,
829    kappas: &[f64],
830) -> Result<Vec<(f64, f64)>, WorkflowError> {
831    let mat = materialize(formula, data, config)?;
832    let FitRequest::Standard(request) = mat.request else {
833        return Err(WorkflowError::IntegrationFailed {
834            reason: "constant_curvature_profiled_reml_scores: formula did not materialise to a \
835                     standard fit request"
836                .to_string(),
837        });
838    };
839    let term_idx = *crate::fit_orchestration::drivers::constant_curvature_term_indices(&request.spec)
840        .first()
841        .ok_or_else(|| WorkflowError::IntegrationFailed {
842            reason: "constant_curvature_profiled_reml_scores: formula has no constant-curvature \
843                     curv() term"
844                .to_string(),
845        })?;
846    let mut out = Vec::with_capacity(kappas.len());
847    for &kappa in kappas {
848        let score = crate::fit_orchestration::drivers::fixed_kappa_profiled_reml_score(
849            request.data.view(),
850            request.y.view(),
851            request.weights.view(),
852            request.offset.view(),
853            &request.spec,
854            term_idx,
855            kappa,
856            request.family.clone(),
857            &request.options,
858        )
859        .map_err(|e| WorkflowError::IntegrationFailed {
860            reason: format!(
861                "constant_curvature_profiled_reml_scores: fixed-κ fit at κ={kappa} failed: {e}"
862            ),
863        })?;
864        out.push((kappa, score));
865    }
866    Ok(out)
867}
868
869/// Derived dense-kernel cliff: the cascade auto-route fires only once the dense
870/// radial basis the smooth would otherwise use has SATURATED at its center cap
871/// (`default_num_centers == K_MAX`), so the dense `O(n·K² + K³)` kernel solve
872/// can no longer grow resolution with `n` and the streaming cascade's
873/// `O(n·polylog)` is the only path that keeps improving. This is the structural
874/// "past the dense-kernel cliff" condition the issue names — derived from the
875/// dense sizing rule, NOT a magic n constant or a user flag.
876fn past_dense_kernel_cliff(n: usize, d: usize) -> bool {
877    // `default_num_centers` clamps to K_MAX = 2000; equality means the dense
878    // basis is pinned at the cap and cannot densify further with n.
879    const DENSE_CENTER_CAP: usize = 2000;
880    gam_terms::basis::default_num_centers(n, d) >= DENSE_CENTER_CAP
881}
882
883/// Map a Duchon/Matérn smoothness order onto the cascade's Sobolev order,
884/// clamped into the Wendland-(3,1) native window `(d/2, (d+3)/2]` (issue
885/// caveat 1: the multilevel frame can only represent up to `H^{(d+3)/2}`).
886fn cascade_sobolev_order(requested: f64, d: usize) -> f64 {
887    let lo = d as f64 / 2.0;
888    let hi = (d as f64 + 3.0) / 2.0;
889    // Nudge strictly inside the open lower bound when the request lands on it.
890    let eps = 1e-6 * (hi - lo);
891    requested.clamp(lo + eps, hi)
892}
893
894/// Detection seam for the O(n log n) multiresolution residual-cascade fast path
895/// (issue #1032).
896///
897/// This mirrors [`spline_scan_fast_path`] in shape but carries one CRITICAL
898/// difference dictated by the issue: the cascade is **not** the same posterior
899/// as the Duchon/Matérn term it stands in for (a different finite basis — the
900/// multilevel Wendland frame, not the reduced-rank radial kernel). So unlike
901/// the 1-D scan, which silently swaps an identical posterior, this path must
902/// only fire as an explicit alternative estimator on the structural signature
903/// the issue names, never as a transparent replacement. It returns `Some` only
904/// when ALL of the following hold:
905/// - family is Gaussian + identity link (the scattered low-d smooth the
906///   cascade solves);
907/// - none of the exotic-link / constraint / Firth / Kronecker / coefficient-
908///   group / hyperprior machinery is engaged;
909/// - the model is exactly one smooth term — no linear terms, no random
910///   effects, no by-variables;
911/// - that smooth is a scattered radial spatial smooth (`Duchon` or `Matern`)
912///   over `d ∈ {2, 3}` coordinates with no shape constraint;
913/// - the offset is identically zero and every weight is finite and positive;
914/// - `n` is past the derived dense-kernel cliff
915///   ([`past_dense_kernel_cliff`]) — below it the dense radial path is both
916///   exact-posterior and cheap, so there is no reason to change estimators.
917///
918/// The returned [`ResidualCascadeInputs`] carry a unit per-axis metric (the
919/// spec's isotropic radial distance); the quasi-uniformity guard inside
920/// [`gam_solve::residual_cascade::fit_residual_cascade`] (issue caveat 2)
921/// is the no-regression gate that refuses the iterative solve — and forces the
922/// caller back to the dense path — when a near-degenerate metric would break
923/// the BPX iteration bound.
924pub fn residual_cascade_fast_path(
925    request: &StandardFitRequest<'_>,
926) -> Option<ResidualCascadeInputs> {
927    if !request.family.is_gaussian_identity() {
928        return None;
929    }
930    if request.wiggle.is_some()
931        || request.latent_coord.is_some()
932        || !request.coefficient_groups.is_empty()
933        || !request.penalty_block_gamma_priors.is_empty()
934    {
935        return None;
936    }
937    let options = &request.options;
938    if options.latent_cloglog.is_some()
939        || options.mixture_link.is_some()
940        || options.sas_link.is_some()
941        || options.linear_constraints.is_some()
942        || options.adaptive_regularization.is_some()
943        || options.kronecker_penalty_system.is_some()
944        || options.kronecker_factored.is_some()
945        || options.firth_bias_reduction
946        || !options.nullspace_dims.is_empty()
947    {
948        return None;
949    }
950    let spec = &request.spec;
951    if !spec.linear_terms.is_empty()
952        || !spec.random_effect_terms.is_empty()
953        || spec.smooth_terms.len() != 1
954    {
955        return None;
956    }
957    let term = &spec.smooth_terms[0];
958    if !matches!(term.shape, gam_terms::smooth::ShapeConstraint::None)
959        || term.joint_null_rotation.is_some()
960    {
961        return None;
962    }
963    // Only scattered radial spatial smooths (Duchon / Matérn) over 2–3 axes.
964    // The Duchon spectral power `p + s` and the Matérn order set the requested
965    // Sobolev smoothness; both clamp into the Wendland native window.
966    let (feature_cols, requested_s) = match &term.basis {
967        gam_terms::smooth::SmoothBasisSpec::Duchon {
968            feature_cols, spec, ..
969        } => {
970            // Pure-Duchon native order is `p + s` (kernel exponent 2(p+s)−d);
971            // the multilevel frame targets the same continuum smoothness. `p`
972            // is the polynomial nullspace degree, `s` the spectral power.
973            let p = match spec.nullspace_order {
974                gam_terms::basis::DuchonNullspaceOrder::Zero => 0.0,
975                gam_terms::basis::DuchonNullspaceOrder::Linear => 1.0,
976                gam_terms::basis::DuchonNullspaceOrder::Degree(k) => k as f64,
977            };
978            (feature_cols, spec.power + p)
979        }
980        gam_terms::smooth::SmoothBasisSpec::Matern {
981            feature_cols, spec, ..
982        } => {
983            // Matérn smoothness ν sets native Sobolev order ν + d/2; the cascade
984            // frame represents up to (d+3)/2, so the clamp below applies the
985            // ceiling. (d is known just below from feature_cols.)
986            let nu = spec.nu.half_integer_value();
987            (feature_cols, nu + feature_cols.len() as f64 / 2.0)
988        }
989        _ => return None,
990    };
991    let d = feature_cols.len();
992    if !(2..=3).contains(&d) {
993        return None;
994    }
995    if request.offset.iter().any(|&v| v != 0.0) {
996        return None;
997    }
998    if request.weights.iter().any(|&v| !(v.is_finite() && v > 0.0)) {
999        return None;
1000    }
1001    let n = request.y.len();
1002    if n != request.data.nrows() || feature_cols.iter().any(|&c| c >= request.data.ncols()) {
1003        return None;
1004    }
1005    if !past_dense_kernel_cliff(n, d) {
1006        return None;
1007    }
1008    let coords: Vec<Vec<f64>> = feature_cols
1009        .iter()
1010        .map(|&c| request.data.column(c).iter().copied().collect())
1011        .collect();
1012    let y: Vec<f64> = request.y.iter().copied().collect();
1013    let w: Vec<f64> = request.weights.iter().copied().collect();
1014    if coords
1015        .iter()
1016        .any(|axis| axis.iter().any(|v| !v.is_finite()))
1017        || y.iter().any(|v| !v.is_finite())
1018    {
1019        return None;
1020    }
1021    let metric = vec![1.0_f64; d];
1022    let sobolev_s = cascade_sobolev_order(requested_s, d);
1023    Some(ResidualCascadeInputs {
1024        coords,
1025        y,
1026        w,
1027        metric,
1028        sobolev_s,
1029    })
1030}
1031
1032/// Formula-level library entry for the O(n log n) residual-cascade fast path
1033/// (issue #1032).
1034///
1035/// Materializes the formula exactly like [`fit_from_formula`], runs the
1036/// [`residual_cascade_fast_path`] detection, and — when it fires AND the
1037/// quasi-uniformity guard inside the cascade certifies the metric — returns the
1038/// certified [`ResidualCascadeFit`](gam_solve::residual_cascade::ResidualCascadeFit).
1039/// `Ok(None)` means EITHER the model is not the cascade-eligible shape OR the
1040/// quasi-uniformity guard rejected the metric; in both cases the caller falls
1041/// back to the dense [`fit_from_formula`] path (the cascade is a different
1042/// posterior, so the fallback is a genuine estimator choice, never a silent
1043/// swap). This keeps every persistence-bearing consumer on the dense fit until
1044/// the cascade payload schema lands.
1045pub fn fit_residual_cascade_from_formula(
1046    formula: &str,
1047    data: &Dataset,
1048    config: &FitConfig,
1049) -> Result<Option<gam_solve::residual_cascade::ResidualCascadeFit>, WorkflowError> {
1050    let mat = materialize(formula, data, config)?;
1051    let FitRequest::Standard(request) = mat.request else {
1052        return Ok(None);
1053    };
1054    let Some(inputs) = residual_cascade_fast_path(&request) else {
1055        return Ok(None);
1056    };
1057    let coord_refs: Vec<&[f64]> = inputs.coords.iter().map(Vec::as_slice).collect();
1058    match gam_solve::residual_cascade::fit_residual_cascade(
1059        &coord_refs,
1060        &inputs.y,
1061        &inputs.w,
1062        &inputs.metric,
1063        inputs.sobolev_s,
1064    ) {
1065        Ok(fit) => Ok(Some(fit)),
1066        // The quasi-uniformity guard (caveat 2) and any degenerate-design
1067        // signal both surface as a build/solve error; treat them as "not
1068        // cascade-eligible" so the caller falls back to the dense kernel path
1069        // rather than failing the fit outright.
1070        Err(_) => Ok(None),
1071    }
1072}
1073
1074/// Parse a formula, resolve it against a dataset, and produce a ready-to-fit `FitRequest`.
1075pub fn materialize<'a>(
1076    formula: &str,
1077    data: &'a Dataset,
1078    config: &FitConfig,
1079) -> Result<MaterializedModel<'a>, WorkflowError> {
1080    gam_gpu::configure_global_policy(config.gpu_policy);
1081    let parsed = parse_formula(formula)?;
1082    let col_map = data.column_map();
1083
1084    if let Some((left_col, right_col, event_col)) = parse_surv_interval_response(&parsed.response)?
1085    {
1086        if config.transformation_normal {
1087            return Err(WorkflowError::InvalidConfig {
1088                reason:
1089                    "transformation_normal cannot be combined with a SurvInterval(...) response"
1090                        .to_string(),
1091            });
1092        }
1093        // Interval censoring `T ∈ (L, R]` is only defined for the latent
1094        // hazard-window survival likelihood, whose kernel carries the
1095        // `log[S(L) − S(R)]` interval contribution. Route the left boundary `L`
1096        // through the standard exit channel and the right boundary `R` through
1097        // the dedicated interval-right channel; `event_col` distinguishes
1098        // bracketed (interval) rows from right-censored rows beyond the last
1099        // inspection (which carry an infinite/sentinel `R`).
1100        materialize_survival(
1101            &parsed,
1102            data,
1103            &col_map,
1104            config,
1105            None,
1106            &left_col,
1107            &event_col,
1108            Some(&right_col),
1109        )
1110    } else if let Some((entry_col, exit_col, event_col)) = parse_surv_response(&parsed.response)? {
1111        if config.transformation_normal {
1112            return Err(WorkflowError::InvalidConfig {
1113                reason: "transformation_normal cannot be combined with a Surv(...) response"
1114                    .to_string(),
1115            });
1116        }
1117        // `materialize_*` now return `WorkflowError` directly so the typed
1118        // `ColumnNotFound` payload (and any future variant-typed leaf
1119        // errors) survive the dispatcher hop instead of being flattened
1120        // into `IntegrationFailed { reason: String }`.
1121        materialize_survival(
1122            &parsed,
1123            data,
1124            &col_map,
1125            config,
1126            entry_col.as_deref(),
1127            &exit_col,
1128            &event_col,
1129            None,
1130        )
1131    } else {
1132        // Non-survival response: `timewiggle(...)` and `survmodel(...)` are
1133        // structurally meaningless (there is no baseline hazard / time axis to
1134        // wiggle and no survival likelihood to configure). They are parsed into
1135        // `ParsedFormula` but consumed *only* by `materialize_survival`; without
1136        // this guard every non-survival materializer below would silently drop
1137        // them, fitting an ordinary GAM while the user believes they requested a
1138        // time-varying / survival model (#371). Reject here — the single
1139        // chokepoint for all non-survival paths — mirroring the symmetric
1140        // auxiliary-formula rejection in `validate_auxiliary_formula_controls`.
1141        reject_survival_only_terms_for_nonsurvival(&parsed)?;
1142        // Symmetrically, the `config.survival_likelihood` *knob* selects a
1143        // survival likelihood mode read only by `materialize_survival`. On this
1144        // non-survival branch a non-default value (e.g. "weibull") would be
1145        // discarded and the fit would silently degrade to an ordinary GAM
1146        // (#1767). Reject it at the same chokepoint.
1147        reject_survival_likelihood_for_nonsurvival(config)?;
1148        if config.transformation_normal {
1149            // Issue #789A: a Bernoulli marginal-slope request with
1150            // `transformation_normal=true` used to dispatch as a CTN fit while
1151            // retaining marginal-slope controls, leaving the transformation path
1152            // in a non-advancing loop. CTN score calibration now uses the
1153            // explicit `ctn_stage1` recipe instead, so the legacy boolean is a
1154            // hard configuration error for marginal-slope requests.
1155            reject_marginal_slope_controls_for_transformation_normal(config)?;
1156            if config.noise_formula.is_some() {
1157                return Err(WorkflowError::InvalidConfig {
1158                    reason: "transformation_normal cannot be combined with noise_formula"
1159                        .to_string(),
1160                });
1161            }
1162            materialize_transformation_normal(&parsed, data, &col_map, config)
1163        } else if config.logslope_formula.is_some() || config.z_column.is_some() {
1164            materialize_bernoulli_marginal_slope(&parsed, data, &col_map, config)
1165        } else if config.noise_formula.is_some() {
1166            materialize_location_scale(&parsed, data, &col_map, config)
1167        } else {
1168            materialize_standard(&parsed, data, &col_map, config)
1169        }
1170    }
1171}
1172
1173#[cfg(test)]
1174mod sz_factor_smooth_recovery_tests {
1175    // `super::*` brings in `Dataset` (= gam_data::EncodedDataset), `FitConfig`,
1176    // `FitResult`, `StandardFitResult`, and `fit_from_formula`.
1177    use super::*;
1178
1179    const NOISE_SD: f64 = 0.20;
1180    const N: usize = 4000;
1181    const N_GROUPS: usize = 4;
1182
1183    /// A simple deterministic LCG so the dataset is reproducible without pulling
1184    /// an RNG dependency into the test.
1185    struct Lcg(u64);
1186    impl Lcg {
1187        fn next_u64(&mut self) -> u64 {
1188            // Numerical Recipes LCG constants.
1189            self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1190            self.0
1191        }
1192        /// Uniform in [0, 1).
1193        fn unif(&mut self) -> f64 {
1194            (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
1195        }
1196        /// Standard normal via Box–Muller (one of the pair).
1197        fn normal(&mut self) -> f64 {
1198            let u1 = (self.unif()).max(1e-12);
1199            let u2 = self.unif();
1200            (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
1201        }
1202    }
1203
1204    /// Data drawn from EXACTLY the `sz` model class: a shared smooth `f0(x)` plus
1205    /// zero-sum per-group deviations `d_g(x)` (phase-shifted sinusoids whose
1206    /// cross-group mean is removed at every `x`), plus observation noise. This
1207    /// mirrors the (blocked) Python bug-hunt test `tests/bug_hunt_sz_factor_
1208    /// smooth_underfits_own_model_class_test.py`.
1209    ///
1210    /// Written to a CSV and loaded through the real `load_dataset_projected`
1211    /// inferer so the grouping column `g` (string levels) is encoded as a genuine
1212    /// categorical exactly as production does — hand-built `EncodedDataset`s do
1213    /// not carry the categorical level map the factor-smooth level resolver needs.
1214    fn sz_class_dataset() -> (Dataset, tempfile::TempDir) {
1215        let mut rng = Lcg(0x5326_2026_0628_1605);
1216        let phases: Vec<f64> = (0..N_GROUPS)
1217            .map(|k| 1.2 * k as f64 / (N_GROUPS as f64 - 1.0))
1218            .collect();
1219        let deviations = |xi: f64| -> Vec<f64> {
1220            let vals: Vec<f64> = phases
1221                .iter()
1222                .map(|p| 0.6 * (std::f64::consts::TAU * xi + std::f64::consts::TAU * p).sin())
1223                .collect();
1224            let mean = vals.iter().sum::<f64>() / vals.len() as f64;
1225            vals.iter().map(|v| v - mean).collect()
1226        };
1227
1228        let mut csv = String::from("y,x,g\n");
1229        for _ in 0..N {
1230            let x = rng.unif();
1231            // Use the HIGH bits (via `unif`) for the group draw — an LCG's low
1232            // bits have a tiny period and would collapse `% N_GROUPS` to a near
1233            // constant.
1234            let g = ((rng.unif() * N_GROUPS as f64) as usize).min(N_GROUPS - 1);
1235            let f0 = (std::f64::consts::TAU * x).sin();
1236            let mu = f0 + deviations(x)[g];
1237            let y = mu + NOISE_SD * rng.normal();
1238            csv.push_str(&format!("{y},{x},g{g}\n"));
1239        }
1240        let td = tempfile::tempdir().expect("tempdir");
1241        let path = td.path().join("sz_class.csv");
1242        std::fs::write(&path, csv).expect("write sz-class csv");
1243        // Force `g` into a categorical role exactly as the formula intends so the
1244        // factor-smooth level resolver sees all `N_GROUPS` distinct levels.
1245        let mut roles = std::collections::HashSet::new();
1246        roles.insert("g");
1247        let data = gam_data::load_dataset_projected_with_categorical_roles(
1248            &path,
1249            &["y".to_string(), "x".to_string(), "g".to_string()],
1250            &roles,
1251        )
1252        .expect("load sz-class dataset");
1253        (data, td)
1254    }
1255
1256    fn gaussian_config() -> FitConfig {
1257        FitConfig { family: Some("gaussian".to_string()), ..FitConfig::default() }
1258    }
1259
1260    /// In-sample residual sd of a fitted standard GAM: `sd(y − Xβ̂)`.
1261    fn residual_sd(fit: &StandardFitResult, data: &Dataset) -> f64 {
1262        let beta = &fit.fit.beta;
1263        let design = &fit.design.design;
1264        let n = design.nrows();
1265        assert_eq!(design.ncols(), beta.len(), "design/beta width mismatch");
1266        let mut fitted = vec![0.0f64; n];
1267        // `try_row_chunk` materializes contiguous row blocks of whatever design
1268        // storage the fit used (dense or block-lazy) — robust to the storage kind.
1269        const CHUNK: usize = 512;
1270        let mut start = 0usize;
1271        while start < n {
1272            let end = (start + CHUNK).min(n);
1273            let block = design
1274                .try_row_chunk(start..end)
1275                .expect("materialize design row chunk");
1276            for (r, row) in block.rows().into_iter().enumerate() {
1277                let mut acc = 0.0;
1278                for (c, &xv) in row.iter().enumerate() {
1279                    acc += xv * beta[c];
1280                }
1281                fitted[start + r] = acc;
1282            }
1283            start = end;
1284        }
1285        let y = data.values.column(0);
1286        let resid: Vec<f64> = y.iter().zip(fitted.iter()).map(|(&yi, &fi)| yi - fi).collect();
1287        let mean = resid.iter().sum::<f64>() / resid.len() as f64;
1288        let var = resid.iter().map(|r| (r - mean).powi(2)).sum::<f64>() / resid.len() as f64;
1289        var.sqrt()
1290    }
1291
1292    fn fit_standard(formula: &str, data: &Dataset) -> StandardFitResult {
1293        match fit_from_formula(formula, data, &gaussian_config())
1294            .unwrap_or_else(|e| panic!("fit `{formula}` failed: {e:?}"))
1295        {
1296            FitResult::Standard(r) => r,
1297            other => panic!("expected Standard fit for `{formula}`, got a different variant: {}",
1298                std::any::type_name_of_val(&other)),
1299        }
1300    }
1301
1302    /// #1605 (gold standard, end-to-end REML fit): the sum-to-zero factor smooth
1303    /// `s(x) + s(g, x, bs="sz")` must RECOVER data drawn from its own model class
1304    /// to the observation-noise floor, exactly as the strictly-more-general
1305    /// `s(x, g, bs="fs")` superset provably does.
1306    ///
1307    /// The recovery gap (`sz` resid ≈ 0.43 ≈ 2.1× the 0.20 floor while `fs`
1308    /// reaches the floor) was closed by THREE mgcv-faithful corrections, each
1309    /// necessary, that this end-to-end fit jointly exercises:
1310    ///   1. marginal basis (baef17e): cr → curvature-capable B-spline, so a
1311    ///      deviation with non-zero boundary curvature is representable;
1312    ///   2. ownership/overlap residualization (b49bb5c): the `sz` deviation is
1313    ///      sum-to-zero ACROSS the grouping factor, hence orthogonal to a
1314    ///      factor-independent owner like the shared `s(x)`. Residualizing it
1315    ///      against `s(x)`'s realized span (the #978 chart) collapsed every
1316    ///      group's curve to a flat per-group contrast; skipping that ownership
1317    ///      (same family as the #1276 factor-`by` level gate) restores the curve
1318    ///      shape and stops REML railing the shared `s(x)` wiggliness λ;
1319    ///   3. null-space ridge (this change): the `sz` deviation blocks now carry
1320    ///      the per-null-dimension ridge structure of `fs`, mapped into the
1321    ///      zero-sum contrast space, so the {const, linear} null space is
1322    ///      shrinkable per dimension (the #700/#712/#713 partial-pooling form)
1323    ///      rather than left free — without breaking the zero-sum constraint.
1324    ///
1325    /// This is the gold-standard verification: it drives the real
1326    /// `fit_from_formula` REML λ-selection on data drawn from exactly the `sz`
1327    /// model class and asserts `sz` reaches the floor (and a `fs` control does
1328    /// too). It failed before the fixes and passes after.
1329    #[test]
1330    fn sz_factor_smooth_recovers_its_own_model_class_end_to_end() {
1331        let (data, _td) = sz_class_dataset();
1332
1333        // Control: bs="fs", a strict superset of the sz span, must reach the
1334        // noise floor — proves the data is well-posed and pins the floor.
1335        let fs_fit = fit_standard("y ~ s(x, g, bs='fs')", &data);
1336        let fs_resid = residual_sd(&fs_fit, &data);
1337        assert!(
1338            fs_resid < 1.2 * NOISE_SD,
1339            "control bs='fs' did not reach the noise floor: resid_sd={fs_resid:.4} \
1340             vs noise_sd={NOISE_SD} (data/floor sanity check)",
1341        );
1342
1343        // The documented sz idiom on data drawn from the sz model class.
1344        let sz_fit = fit_standard("y ~ s(x) + s(g, x, bs='sz')", &data);
1345        let sz_resid = residual_sd(&sz_fit, &data);
1346
1347        // A smoother whose span contains the truth, fit at large n, must explain
1348        // the systematic structure and leave ~only observation noise.
1349        assert!(
1350            sz_resid < 1.4 * NOISE_SD,
1351            "bs='sz' under-fits its own model class: resid_sd={sz_resid:.4} \
1352             ({:.2}x the noise floor {NOISE_SD}); the bs='fs' superset reached \
1353             {fs_resid:.4}. The sz fit leaves systematic signal in the residual.",
1354            sz_resid / NOISE_SD,
1355        );
1356
1357        // Comparative guard: sz must not be dramatically worse than the fs
1358        // superset that recovers the same data.
1359        assert!(
1360            sz_resid < 1.5 * fs_resid,
1361            "bs='sz' residual {sz_resid:.4} is {:.2}x the bs='fs' residual \
1362             {fs_resid:.4} on identical sz-class data",
1363            sz_resid / fs_resid,
1364        );
1365    }
1366}