Skip to main content

gam_models/fit_orchestration/
request.rs

1use super::*;
2
3#[derive(Clone, Debug)]
4pub struct LinkWiggleConfig {
5    pub degree: usize,
6    pub num_internal_knots: usize,
7    pub penalty_orders: Vec<usize>,
8    pub double_penalty: bool,
9}
10
11/// Configuration for the second-stage binomial-mean wiggle fit appended to a
12/// standard pilot. The blockwise refit options live inside this struct so the
13/// pilot config (`link_kind` + `wiggle`) and its required `refit_options` can
14/// never disagree: either the whole standard-wiggle request is `Some`, or it
15/// is `None`. The previous shape had two sibling `Option` fields on
16/// `StandardFitRequest`, which allowed the materialize path to construct an
17/// inconsistent state (#320: linkwiggle config without blockwise options).
18#[derive(Clone)]
19pub struct StandardBinomialWiggleConfig {
20    pub link_kind: InverseLink,
21    pub wiggle: LinkWiggleConfig,
22    pub refit_options: BlockwiseFitOptions,
23}
24
25pub struct StandardFitRequest<'a> {
26    pub data: Array2<f64>,
27    pub y: Array1<f64>,
28    pub weights: Array1<f64>,
29    pub offset: Array1<f64>,
30    pub spec: TermCollectionSpec,
31    pub family: LikelihoodSpec,
32    pub options: FitOptions,
33    pub kappa_options: SpatialLengthScaleOptimizationOptions,
34    pub wiggle: Option<StandardBinomialWiggleConfig>,
35    pub coefficient_groups: Vec<CoefficientGroupSpec>,
36    pub penalty_block_gamma_priors: Vec<(String, f64, f64)>,
37    pub latent_coord: Option<StandardLatentCoordConfig>,
38    #[doc(hidden)]
39    pub _marker: std::marker::PhantomData<&'a ()>,
40}
41
42pub struct GaussianLocationScaleFitRequest<'a> {
43    pub data: ArrayView2<'a, f64>,
44    pub spec: GaussianLocationScaleTermSpec,
45    pub wiggle: Option<LinkWiggleConfig>,
46    pub options: BlockwiseFitOptions,
47    pub kappa_options: SpatialLengthScaleOptimizationOptions,
48}
49
50pub struct BinomialLocationScaleFitRequest<'a> {
51    pub data: ArrayView2<'a, f64>,
52    pub spec: BinomialLocationScaleTermSpec,
53    pub wiggle: Option<LinkWiggleConfig>,
54    pub options: BlockwiseFitOptions,
55    pub kappa_options: SpatialLengthScaleOptimizationOptions,
56}
57
58pub struct DispersionLocationScaleFitRequest<'a> {
59    pub data: ArrayView2<'a, f64>,
60    pub spec: DispersionGlmLocationScaleTermSpec,
61    pub options: BlockwiseFitOptions,
62    pub kappa_options: SpatialLengthScaleOptimizationOptions,
63}
64
65pub struct SurvivalLocationScaleFitRequest<'a> {
66    pub data: ArrayView2<'a, f64>,
67    pub spec: SurvivalLocationScaleTermSpec,
68    pub wiggle: Option<LinkWiggleConfig>,
69    pub kappa_options: SpatialLengthScaleOptimizationOptions,
70    pub optimize_inverse_link: bool,
71    /// See [`gam_custom_family::BlockwiseFitOptions::cache_session`].
72    /// Threaded into the internally constructed `BlockwiseFitOptions` by
73    /// `fit_survival_location_scale_model`.
74    pub cache_session: Option<std::sync::Arc<gam_runtime::warm_start::Session>>,
75}
76
77pub struct SurvivalTransformationFitRequest<'a> {
78    pub data: ArrayView2<'a, f64>,
79    pub spec: SurvivalTransformationTermSpec,
80    /// See [`gam_custom_family::BlockwiseFitOptions::cache_session`].
81    /// Threaded into the internally constructed `BlockwiseFitOptions` by
82    /// `fit_survival_transformation_model`.
83    pub cache_session: Option<std::sync::Arc<gam_runtime::warm_start::Session>>,
84}
85
86#[derive(Clone)]
87pub struct SurvivalTransformationTermSpec {
88    pub age_entry: Array1<f64>,
89    pub age_exit: Array1<f64>,
90    pub event_target: Array1<u8>,
91    pub weights: Array1<f64>,
92    pub covariate_spec: TermCollectionSpec,
93    pub covariate_offset: Array1<f64>,
94    pub baseline_cfg: crate::survival::SurvivalBaselineConfig,
95    pub likelihood_mode: crate::survival::SurvivalLikelihoodMode,
96    pub time_anchor: f64,
97    pub time_build: crate::survival::SurvivalTimeBuildOutput,
98    pub timewiggle: Option<LinkWiggleFormulaSpec>,
99    pub weibull_seed: Option<(f64, f64)>,
100    pub ridge_lambda: f64,
101    pub penalty_block_gamma_priors: Vec<(String, f64, f64)>,
102}
103pub struct BernoulliMarginalSlopeFitRequest<'a> {
104    pub data: ArrayView2<'a, f64>,
105    pub spec: BernoulliMarginalSlopeTermSpec,
106    pub options: BlockwiseFitOptions,
107    pub kappa_options: SpatialLengthScaleOptimizationOptions,
108    pub policy: gam_runtime::resource::ResourcePolicy,
109}
110
111pub struct SurvivalMarginalSlopeFitRequest<'a> {
112    pub data: ArrayView2<'a, f64>,
113    pub spec: SurvivalMarginalSlopeTermSpec,
114    pub options: BlockwiseFitOptions,
115    pub kappa_options: SpatialLengthScaleOptimizationOptions,
116}
117pub struct LatentSurvivalFitRequest<'a> {
118    pub data: ArrayView2<'a, f64>,
119    pub spec: LatentSurvivalTermSpec,
120    pub frailty: FrailtySpec,
121    pub options: BlockwiseFitOptions,
122}
123
124pub struct LatentBinaryFitRequest<'a> {
125    pub data: ArrayView2<'a, f64>,
126    pub spec: LatentBinaryTermSpec,
127    pub frailty: FrailtySpec,
128    pub options: BlockwiseFitOptions,
129}
130
131pub struct TransformationNormalFitRequest<'a> {
132    pub data: ArrayView2<'a, f64>,
133    pub response: Array1<f64>,
134    pub weights: Array1<f64>,
135    pub offset: Array1<f64>,
136    pub covariate_spec: TermCollectionSpec,
137    pub config: TransformationNormalConfig,
138    pub options: BlockwiseFitOptions,
139    pub kappa_options: SpatialLengthScaleOptimizationOptions,
140    pub warm_start: Option<TransformationWarmStart>,
141}
142pub enum FitRequest<'a> {
143    Standard(StandardFitRequest<'a>),
144    GaussianLocationScale(GaussianLocationScaleFitRequest<'a>),
145    BinomialLocationScale(BinomialLocationScaleFitRequest<'a>),
146    DispersionLocationScale(DispersionLocationScaleFitRequest<'a>),
147    SurvivalLocationScale(SurvivalLocationScaleFitRequest<'a>),
148    SurvivalTransformation(SurvivalTransformationFitRequest<'a>),
149    BernoulliMarginalSlope(BernoulliMarginalSlopeFitRequest<'a>),
150    SurvivalMarginalSlope(SurvivalMarginalSlopeFitRequest<'a>),
151    LatentSurvival(LatentSurvivalFitRequest<'a>),
152    LatentBinary(LatentBinaryFitRequest<'a>),
153    TransformationNormal(TransformationNormalFitRequest<'a>),
154}
155
156pub struct StandardFitResult {
157    pub fit: UnifiedFitResult,
158    pub design: TermCollectionDesign,
159    pub resolvedspec: TermCollectionSpec,
160    pub adaptive_diagnostics: Option<AdaptiveRegularizationDiagnostics>,
161    pub kappa_timing: Option<SpatialLengthScaleOptimizationTiming>,
162    pub saved_link_state: FittedLinkState,
163    pub wiggle_knots: Option<Array1<f64>>,
164    pub wiggle_degree: Option<usize>,
165}
166
167pub struct SurvivalLocationScaleFitResult {
168    pub fit: SurvivalLocationScaleTermFitResult,
169    pub inverse_link: InverseLink,
170    pub wiggle_knots: Option<Array1<f64>>,
171    pub wiggle_degree: Option<usize>,
172}
173
174pub struct SurvivalTransformationFitResult {
175    pub fit: UnifiedFitResult,
176    pub resolvedspec: TermCollectionSpec,
177    pub baseline_cfg: crate::survival::SurvivalBaselineConfig,
178    pub likelihood_mode: crate::survival::SurvivalLikelihoodMode,
179    /// Persistable snapshot of the time basis used during the fit. Replaces
180    /// six previously flat fields (basisname / degree / knots / keep_cols /
181    /// smooth_lambda / anchor) so the FFI save path consumes a single
182    /// source-of-truth value rather than threading siblings independently.
183    pub time_basis: crate::survival::SavedSurvivalTimeBasis,
184    pub time_base_ncols: usize,
185    pub baseline_timewiggle: Option<TimeWiggleBlockInput>,
186}
187
188pub enum FitResult {
189    Standard(StandardFitResult),
190    GaussianLocationScale(GaussianLocationScaleFitResult),
191    BinomialLocationScale(BinomialLocationScaleFitResult),
192    DispersionLocationScale(DispersionLocationScaleFitResult),
193    SurvivalLocationScale(SurvivalLocationScaleFitResult),
194    SurvivalTransformation(SurvivalTransformationFitResult),
195    BernoulliMarginalSlope(BernoulliMarginalSlopeFitResult),
196    SurvivalMarginalSlope(SurvivalMarginalSlopeFitResult),
197    LatentSurvival(LatentSurvivalTermFitResult),
198    LatentBinary(LatentBinaryTermFitResult),
199    TransformationNormal(TransformationNormalFitResult),
200    /// Exact O(n) state-space cubic/linear/quintic smoothing-spline scan
201    /// (#1030/#1034). A scan-bearing model IS a Gaussian-identity model with a
202    /// different (exact) representation: rather than a dense design + coefficient
203    /// vector it carries the Durbin–Koopman smoother posterior directly (knots,
204    /// smoothed states, pointwise variances, σ², log λ, exact diffuse-REML EDF,
205    /// and an exact per-row `predict`). Library callers that want the fitted
206    /// posterior get it here without paying the dense O(n·k²)+O(k³) route; the
207    /// CLI/FFI save paths build the persistence payload from the same
208    /// `SplineScanFit` via `assemble_spline_scan_payload`.
209    SplineScan(gam_solve::spline_scan::SplineScanFit),
210    /// O(n log n) multiresolution residual-cascade smooth (#1032). UNLIKE the
211    /// 1-D scan, the cascade is NOT the same posterior as the Duchon/Matérn term
212    /// it stands in for (a different finite basis — the multilevel Wendland
213    /// frame), so it is never a silent swap: this variant is produced only when
214    /// the structural detector [`residual_cascade_fast_path`] fires on an
215    /// eligible scattered-low-d Gaussian fit past the dense-kernel cliff AND the
216    /// in-cascade quasi-uniformity guard certifies the metric; every other shape
217    /// (and a rejected metric) falls through to the dense `fit_model` path. The
218    /// cascade-bearing model carries the
219    /// [`ResidualCascadeFit`](gam_solve::residual_cascade::ResidualCascadeFit)
220    /// directly — knots-free nested geometry, coefficients, the factored
221    /// precision, and an exact per-row `predict`; the CLI/FFI save paths build
222    /// the persistence payload from its `to_state` snapshot.
223    ResidualCascade(gam_solve::residual_cascade::ResidualCascadeFit),
224}
225
226/// Result of a dispersion-channel GAMLSS location-scale fit (#913). Wraps the
227/// shared two-block [`BlockwiseTermFitResult`] (mean + log-precision designs
228/// and coefficients) plus the family kind so the save path can stamp the right
229/// likelihood. These families have no link-wiggle and no response
230/// standardization, so the result is a thin wrapper.
231pub struct DispersionLocationScaleFitResult {
232    pub fit: BlockwiseTermFitResult,
233    pub kind: DispersionFamilyKind,
234}
235
236/// Out-of-fold Stage-1 latent score and its score-influence Jacobian for a
237/// CTN → marginal-slope chain. `z_oof` (length n) replaces the in-sample `z`
238/// the Stage-2 model consumes; `jac_oof` (n × p₁) is fed to the Stage-2 spec's
239/// `score_influence_jacobian` so the joint solve absorbs the realized leakage
240/// directions `Z_infl = diag(s_f·β̂₀)·J`.
241pub struct CrossFitScoreCalibration {
242    pub z_oof: Array1<f64>,
243    pub jac_oof: Array2<f64>,
244}
245
246/// Internal recipe describing the CTN Stage-1 fit that produced a Stage-2 `z`
247/// column. This is in-process plumbing — never a CLI flag, env var, or feature
248/// gate. The orchestration layer populates [`FitConfig::ctn_stage1`] when (and
249/// only when) the marginal-slope `z` was generated by a transformation-normal
250/// Stage-1 fit; its presence is the sole auto-enable signal for cross-fitted
251/// orthogonalization (design §5). When absent, Stage-2 falls back to the free
252/// 1-D `score_warp` spline (which spans only the x-free leakage column).
253#[derive(Clone, Debug)]
254pub struct CtnStage1Recipe {
255    /// Stage-1 response column name (the `y` the CTN transforms).
256    pub response_column: String,
257    /// Stage-1 covariate-side formula right-hand side (e.g. `"s(pc1) + s(pc2)"`),
258    /// with no `~` and no response symbol. [`crossfit_score_calibration`] parses
259    /// it and builds the CTN covariate basis exactly as
260    /// `materialize_transformation_normal` does, then FREEZES that basis once on
261    /// the full data and reuses the frozen spec for every fold's refit — so the
262    /// rebuilt covariate design has an identical column geometry across folds,
263    /// keeping `J`'s `p₁ = p_resp · p_cov` columns aligned (design §3).
264    ///
265    /// The recipe carries the formula RHS (a primitive string) rather than a
266    /// resolved [`TermCollectionSpec`] because this struct is populated both via
267    /// [`CtnStage1Recipe::new`] (set on [`FitConfig::ctn_stage1`], then
268    /// [`fit_from_formula`]) and by the gamfit FFI marshaller
269    /// (`gamfit/_calibrated_slope.py`), which can only serialize primitives over
270    /// the JSON boundary — a `TermCollectionSpec` is not serializable. Freezing on
271    /// the full Stage-2 data is equivalent to
272    /// freezing on the Stage-1 data whenever the two stages share a frame (the
273    /// calibrated-chain contract), so the column geometry still matches Stage-1.
274    pub covariate_formula_rhs: String,
275    /// Stage-1 CTN config (response basis degree / knot count / penalties).
276    /// Its `response_num_internal_knots` is the FIXED response-basis size; the
277    /// cross-fit pins it across folds so `p_resp` (and hence `p₁`) is
278    /// fold-invariant (design §3).
279    pub config: TransformationNormalConfig,
280    /// Optional Stage-1 weight column name.
281    pub weight_column: Option<String>,
282    /// Optional Stage-1 offset column name.
283    pub offset_column: Option<String>,
284}
285
286impl CtnStage1Recipe {
287    /// Build a Stage-1 CTN recipe from the Stage-1 description. This is the public
288    /// way to populate [`FitConfig::ctn_stage1`] — set it on a marginal-slope
289    /// config and run [`fit_from_formula`] (the entry IS `fit_from_formula` with
290    /// `ctn_stage1` set; there is no separate combined entry function). The
291    /// materializer then cross-fits the CTN and installs the leakage-projection
292    /// block; supplying the recipe *is* the request for orthogonalization.
293    ///
294    /// `response` is the Stage-1 CTN response column; `covariates` is the
295    /// covariate-side formula right-hand side (e.g. `"s(pc1) + s(pc2)"` — no `~`,
296    /// no response symbol). Validates both are non-empty and that `covariates`
297    /// is an RHS only.
298    pub fn new(
299        response: &str,
300        covariates: &str,
301        config: TransformationNormalConfig,
302        weight_column: Option<&str>,
303        offset_column: Option<&str>,
304    ) -> Result<Self, String> {
305        let response_column = response.trim().to_string();
306        if response_column.is_empty() {
307            return Err("CtnStage1Recipe requires a non-empty Stage-1 response column".to_string());
308        }
309        let covariate_formula_rhs = covariates.trim().to_string();
310        if covariate_formula_rhs.is_empty() {
311            return Err(
312                "CtnStage1Recipe requires a non-empty Stage-1 covariate formula RHS".to_string(),
313            );
314        }
315        if covariate_formula_rhs.contains('~') {
316            return Err(
317                "CtnStage1Recipe covariates is a right-hand side only; pass 's(pc1) + s(pc2)', \
318                 not 'score ~ s(pc1) + s(pc2)'"
319                    .to_string(),
320            );
321        }
322        Ok(Self {
323            response_column,
324            covariate_formula_rhs,
325            config,
326            weight_column: weight_column
327                .map(str::to_string)
328                .filter(|s| !s.trim().is_empty()),
329            offset_column: offset_column
330                .map(str::to_string)
331                .filter(|s| !s.trim().is_empty()),
332        })
333    }
334}
335#[derive(Clone, Debug)]
336pub struct FitConfig {
337    /// Family: "gaussian", "binomial", "poisson", "negative-binomial",
338    /// "gamma", "tweedie" (alias "tw"; variance power fixed at p = 1.5), or
339    /// None for auto-detect.
340    pub family: Option<String>,
341    /// Fixed size/overdispersion parameter for `family="negative-binomial"`.
342    pub negative_binomial_theta: Option<f64>,
343    /// Link: "identity", "logit", "probit", "cloglog", "sas", "beta-logistic", or None.
344    pub link: Option<String>,
345    /// Whether to use flexible (wiggle-augmented) link.
346    pub flexible_link: bool,
347    /// Optional additive offset column for the primary linear predictor.
348    pub offset_column: Option<String>,
349    /// Optional additive offset column for the noise/log-scale predictor.
350    pub noise_offset_column: Option<String>,
351    /// Optional family-level frailty modifier.
352    pub frailty: Option<FrailtySpec>,
353
354    // Survival-specific
355    /// Baseline target: "linear", "weibull", "gompertz", "gompertz-makeham".
356    pub baseline_target: String,
357    pub baseline_scale: Option<f64>,
358    pub baseline_shape: Option<f64>,
359    pub baseline_rate: Option<f64>,
360    pub baseline_makeham: Option<f64>,
361    /// Time basis: "ispline" or "none".
362    pub time_basis: String,
363    pub time_degree: usize,
364    pub time_num_internal_knots: usize,
365    pub time_smooth_lambda: f64,
366    /// Survival likelihood mode: "location-scale", "transformation", "weibull",
367    /// "marginal-slope", "latent", or "latent-binary".
368    pub survival_likelihood: String,
369    /// Residual distribution: "gaussian", "logistic", "gumbel".
370    pub survival_distribution: String,
371    pub threshold_time_k: Option<usize>,
372    pub threshold_time_degree: usize,
373    pub sigma_time_k: Option<usize>,
374    pub sigma_time_degree: usize,
375
376    // Location-scale (GAMLSS)
377    /// If set, fit a location-scale model with this formula for the noise parameter.
378    pub noise_formula: Option<String>,
379
380    // Marginal-slope
381    /// Formula for the log-slope model (survival marginal-slope or Bernoulli marginal-slope).
382    pub logslope_formula: Option<String>,
383    /// Column name for the z (exposure/dose) variable in marginal-slope models.
384    pub z_column: Option<String>,
385    /// Optional non-negative per-row training weights column.
386    pub weight_column: Option<String>,
387    /// Expectile asymmetry `τ ∈ (0, 1)` for `family = "expectile"`.
388    ///
389    /// When `family` resolves to `"expectile"` the fit minimizes the
390    /// Newey–Powell asymmetric squared loss `Σ wᵢ(τ)·(yᵢ − μᵢ)²` with
391    /// `wᵢ(τ) = τ` if `yᵢ > μᵢ` else `1 − τ`, tracing the conditional
392    /// `τ`-expectile — the smooth analogue of the `τ`-quantile. `τ = 0.5`
393    /// reduces exactly to the Gaussian-identity mean fit. The whole penalized
394    /// smooth + REML `λ`-selection machinery is reused via a Least
395    /// Asymmetrically Weighted Squares (LAWS) outer loop. `None` defaults to
396    /// the median expectile `τ = 0.5` when the family is `"expectile"`; it is
397    /// ignored for every other family. The asymmetry may also be written inline
398    /// as `family = "expectile(0.9)"`, which fills this field at resolve time.
399    pub expectile_tau: Option<f64>,
400    /// Internal CTN Stage-1 provenance for the marginal-slope `z` column.
401    ///
402    /// When the marginal-slope `z` was generated by a transformation-normal
403    /// Stage-1 fit, the orchestration layer fills this with the Stage-1 recipe.
404    /// Its presence is the sole auto-enable signal for cross-fitted, Neyman-
405    /// orthogonal score calibration (#461): the materializer cross-fits the CTN
406    /// to produce out-of-fold `z` and the score-influence Jacobian `J`, replaces
407    /// the raw `z` with `z_oof`, and absorbs `J` as a leakage-projection block in
408    /// Stage-2. This is in-process plumbing only — there is no CLI flag, env var,
409    /// or feature gate. `None` ⇒ raw `z` with the free-warp `score_warp`
410    /// fallback. See [`CtnStage1Recipe`].
411    pub ctn_stage1: Option<CtnStage1Recipe>,
412
413    // Fitting options
414    pub scale_dimensions: bool,
415    /// Enable exact spatial adaptive regularization for standard formula fits.
416    /// `None` uses the quality-first automatic policy. The current automatic
417    /// policy leaves LAREG off unless explicitly requested because the
418    /// optimizer's REML-selected local weights can over-regularize small
419    /// high-yield spatial signals.
420    pub adaptive_regularization: Option<bool>,
421    pub ridge_lambda: f64,
422
423    /// Route the fit through the transformation-normal family.  When set, the
424    /// formula terms are treated as the covariate side of the transformation
425    /// model and the response basis is built internally.  Incompatible with
426    /// `noise_formula` and with `Surv(...)` responses.
427    pub transformation_normal: bool,
428
429    /// Enable Firth bias reduction for standard single-parameter families.
430    pub firth: bool,
431    /// Optional cap on the REML/LAML outer smoothing-parameter iterations for
432    /// standard formula fits. `None` uses the production default.
433    pub outer_max_iter: Option<usize>,
434    /// Optional wall-clock budget (seconds) for the outer smoothing search
435    /// (gam#979). Threaded to the survival marginal-slope fit, whose constrained
436    /// joint-Newton can fail to certify convergence and otherwise grind without
437    /// bound; with this set the fit returns its best-so-far iterate (or a
438    /// catchable error) within the budget instead of hanging. `None` keeps the
439    /// generous built-in default for that path and is unbounded elsewhere.
440    pub outer_wall_clock_budget_secs: Option<f64>,
441
442    /// GPU backend selection policy. `Auto` uses supported device kernels for
443    /// large workloads, `Off` pins execution to CPU kernels, and `Force` fails
444    /// loudly when a requested GPU kernel has no compiled backend.
445    pub gpu_policy: gam_gpu::GpuPolicy,
446    /// Optional override of the [`gam_runtime::resource::ResourcePolicy`] used when
447    /// planning spatial bases (TPS / Matern / Duchon) during term construction.
448    /// When `None`, the default-library policy is used.
449    pub resource_policy: Option<gam_runtime::resource::ResourcePolicy>,
450
451    /// Optional per-group metadata supplied by the caller. Fitting ignores this
452    /// field; saved-model builders pass it through so deployment consumers can
453    /// recover group provenance.
454    pub group_metadata: Option<BTreeMap<String, JsonValue>>,
455
456    /// Optional user-defined coefficient groups with separate precision
457    /// parameters. Group-local priors, including catalog-metadata-informed
458    /// Gamma precision hyperpriors, are resolved during design setup.
459    pub coefficient_groups: Vec<CoefficientGroupSpec>,
460
461    /// Optional per-existing-penalty-block Gamma(shape, rate) precision
462    /// hyperpriors keyed by penalty-block label. This is the
463    /// catalog-metadata-informed-prior hook for models that do not need a new
464    /// user-defined coefficient group.
465    pub penalty_block_gamma_priors: Vec<(String, f64, f64)>,
466
467    /// Python `gamfit.fit(..., latents={...})` configuration. This reaches
468    /// the standard formula workflow as an owned latent-coordinate block:
469    /// the named smooth's synthetic covariates are rebuilt from `t`, and
470    /// joint REML optimizes `[rho, vec(t)]` through latent design hyper-dirs.
471    pub latents: Option<JsonValue>,
472    /// Python `gamfit.fit(..., penalties=[...])` analytic-penalty descriptors,
473    /// validated against the declared latent-coordinate blocks before a
474    /// standard latent fit starts.
475    pub analytic_penalties: Option<JsonValue>,
476    /// Formula-path latent topology selector descriptor. The selector itself
477    /// fits candidates through the ordinary workflow; this slot lets callers
478    /// request and validate that path from the same config registry.
479    pub topology_auto_selector: Option<gam_solve::topology_selector::TopologyAutoSelector>,
480    /// `gamfit.fit(..., smooths={...})` Python kwarg routed through the FFI
481    /// bridge. JSON object keyed by formula symbol (single column name or
482    /// comma-joined tuple) → smooth descriptor (`{"kind": "duchon",
483    /// "centers": [[...], ...], ...}`). Applied as a post-processing step on
484    /// the [`TermCollectionSpec`] produced by the formula DSL: each smooth
485    /// term whose `feature_cols` match a registry key has its kind-specific
486    /// tunables (centers, knots, kernel hyperparameters) overridden with the
487    /// user-supplied values. The single canonical lowering path guarantees
488    /// `smooths={"x": Duchon(centers=K)}` (integer) produces a bit-identical
489    /// block spec to writing `duchon(x, centers=K)` in the formula; only
490    /// explicit array-valued `centers=` differs, routing through
491    /// `CenterStrategy::UserProvided` instead of `FarthestPoint`/`EqualMass`.
492    pub smooth_overrides: Option<JsonValue>,
493    /// Engage the cross-process ON-DISK persistent warm-start layer (#1082).
494    ///
495    /// Default `false`: only the always-on in-memory warm start runs, so a
496    /// single fit and throwaway/replicate/CI-coverage loops pay zero disk I/O
497    /// (no `WarmStartStore` dir/eviction scan, no record load/store). Set
498    /// `true` to engage cross-process / repeat-fit resume: the flag threads
499    /// `FitConfig → FitOptions → ExternalOptimOptions` down to the standard
500    /// `RemlState`, which then calls `enable_persistent_warm_start_disk()`.
501    pub persist_warm_start_disk: bool,
502}
503
504impl Default for FitConfig {
505    fn default() -> Self {
506        Self {
507            family: None,
508            negative_binomial_theta: None,
509            link: None,
510            flexible_link: false,
511            offset_column: None,
512            noise_offset_column: None,
513            frailty: None,
514            baseline_target: "linear".into(),
515            baseline_scale: None,
516            baseline_shape: None,
517            baseline_rate: None,
518            baseline_makeham: None,
519            time_basis: "ispline".into(),
520            time_degree: 3,
521            time_num_internal_knots: 8,
522            time_smooth_lambda: 1e-2,
523            survival_likelihood: "transformation".into(),
524            survival_distribution: "gaussian".into(),
525            threshold_time_k: None,
526            threshold_time_degree: 3,
527            sigma_time_k: None,
528            sigma_time_degree: 3,
529            noise_formula: None,
530            logslope_formula: None,
531            z_column: None,
532            weight_column: None,
533            expectile_tau: None,
534            ctn_stage1: None,
535            scale_dimensions: false,
536            adaptive_regularization: None,
537            ridge_lambda: 1e-6,
538            transformation_normal: false,
539            firth: false,
540            outer_max_iter: None,
541            outer_wall_clock_budget_secs: None,
542            gpu_policy: gam_gpu::GpuPolicy::Auto,
543            resource_policy: None,
544            group_metadata: None,
545            coefficient_groups: Vec::new(),
546            penalty_block_gamma_priors: Vec::new(),
547            latents: None,
548            analytic_penalties: None,
549            topology_auto_selector: None,
550            smooth_overrides: None,
551            persist_warm_start_disk: false,
552        }
553    }
554}
555/// The result of materializing a formula + config against a dataset.
556pub struct MaterializedModel<'a> {
557    pub request: FitRequest<'a>,
558    pub inference_notes: Vec<String>,
559}
560pub struct SplineScanInputs {
561    /// Abscissae of the single 1-D smooth (training rows of its feature column).
562    pub x: Vec<f64>,
563    /// Gaussian response.
564    pub y: Vec<f64>,
565    /// Observation weights (variance is `σ²/w`).
566    pub w: Vec<f64>,
567    /// Smoothing-spline order `m = penalty_order ∈ {1, 2, 3}`: `m = 1` the
568    /// random-walk/linear smoother (penalty `λ∫f′²`), `m = 2` the cubic
569    /// smoother (penalty `λ∫f″²`), `m = 3` the quintic smoother (penalty
570    /// `λ∫(f‴)²`).
571    pub order: usize,
572}
573pub struct ResidualCascadeInputs {
574    /// One slice per coordinate axis (2 or 3) of the single scattered smooth.
575    pub coords: Vec<Vec<f64>>,
576    /// Gaussian response.
577    pub y: Vec<f64>,
578    /// Observation weights (variance is `σ²/w`).
579    pub w: Vec<f64>,
580    /// Per-axis positive metric scaling `diag(metric)` of `z = diag(metric)·x`.
581    pub metric: Vec<f64>,
582    /// Sobolev smoothness order `s` of the multilevel Wendland-(3,1) prior,
583    /// clamped into the native-space window `(d/2, (d+3)/2]` (issue caveat 1).
584    pub sobolev_s: f64,
585}