Skip to main content

gam_models/fit_orchestration/
fit_config.rs

1use super::*;
2
3fn normalize_optional_column(value: Option<String>, field: &str) -> Result<Option<String>, String> {
4    value
5        .map(|value| {
6            let value = value.trim();
7            if value.is_empty() {
8                Err(format!("{field} must be a non-empty column name"))
9            } else {
10                Ok(value.to_string())
11            }
12        })
13        .transpose()
14}
15
16/// Validate the survival baseline fields shared by every front end.
17pub fn validate_survival_baseline_config(
18    likelihood_mode: SurvivalLikelihoodMode,
19    baseline_target: &str,
20    baseline_scale: Option<f64>,
21    baseline_shape: Option<f64>,
22    baseline_rate: Option<f64>,
23    baseline_makeham: Option<f64>,
24) -> Result<(), String> {
25    if likelihood_mode == SurvivalLikelihoodMode::Weibull {
26        if baseline_rate.is_some() || baseline_makeham.is_some() {
27            return Err(
28                "survival likelihood 'weibull' does not use baseline_rate or baseline_makeham"
29                    .to_string(),
30            );
31        }
32        if !matches!(baseline_target, "linear" | "weibull") {
33            return Err(
34                "survival likelihood 'weibull' supports only baseline_target 'linear' or 'weibull'"
35                    .to_string(),
36            );
37        }
38        return Ok(());
39    }
40
41    match baseline_target {
42        "linear" => {
43            if baseline_scale.is_some()
44                || baseline_shape.is_some()
45                || baseline_rate.is_some()
46                || baseline_makeham.is_some()
47            {
48                return Err("baseline_target 'linear' does not use baseline parameters".to_string());
49            }
50        }
51        "weibull" => {
52            if baseline_rate.is_some() || baseline_makeham.is_some() {
53                return Err(
54                    "baseline_target 'weibull' does not use baseline_rate or baseline_makeham"
55                        .to_string(),
56                );
57            }
58        }
59        "gompertz" => {
60            if baseline_scale.is_some() || baseline_makeham.is_some() {
61                return Err(
62                    "baseline_target 'gompertz' does not use baseline_scale or baseline_makeham"
63                        .to_string(),
64                );
65            }
66        }
67        "gompertz-makeham" => {
68            if baseline_scale.is_some() {
69                return Err(
70                    "baseline_target 'gompertz-makeham' does not use baseline_scale".to_string(),
71                );
72            }
73        }
74        other => {
75            return Err(format!(
76                "unsupported baseline_target '{other}'; use linear, weibull, gompertz, or gompertz-makeham"
77            ));
78        }
79    }
80    Ok(())
81}
82
83impl FitConfig {
84    /// Normalize and validate the canonical configuration contract.
85    ///
86    /// CLI and JSON layers translate syntax only. Model-family legality and
87    /// cross-field invariants live here so direct Rust callers cannot bypass
88    /// the same rules enforced by application front ends.
89    pub fn resolve(mut self) -> Result<Self, String> {
90        self.family = self.family.and_then(|value| {
91            let value = value.trim();
92            (!value.eq_ignore_ascii_case("auto")).then(|| value.to_string())
93        });
94        self.survival_likelihood = self
95            .survival_likelihood
96            .map(|value| value.trim().to_ascii_lowercase());
97        self.baseline_target = self.baseline_target.trim().to_ascii_lowercase();
98        self.link = self.link.and_then(|value| {
99            let value = value.trim();
100            (!value.is_empty()).then(|| value.to_string())
101        });
102        self.offset_column = normalize_optional_column(self.offset_column, "offset_column")?;
103        self.noise_offset_column =
104            normalize_optional_column(self.noise_offset_column, "noise_offset_column")?;
105        self.weight_column = normalize_optional_column(self.weight_column, "weight_column")?;
106        self.z_column = normalize_optional_column(self.z_column, "z_column")?;
107
108        if !self.ridge_lambda.is_finite() || self.ridge_lambda < 0.0 {
109            return Err("ridge_lambda must be finite and >= 0".to_string());
110        }
111        if self.outer_max_iter == Some(0) {
112            return Err("outer_max_iter must be >= 1".to_string());
113        }
114        self.frailty.validate().map_err(|error| error.to_string())?;
115        self.spatial_optimization.validate()?;
116        let likelihood_mode = parse_survival_likelihood_mode(self.resolved_survival_likelihood())?;
117        validate_survival_baseline_config(
118            likelihood_mode,
119            &self.baseline_target,
120            self.baseline_scale,
121            self.baseline_shape,
122            self.baseline_rate,
123            self.baseline_makeham,
124        )?;
125        Ok(self)
126    }
127
128    /// The survival likelihood mode this config resolves to for a `Surv(...)`
129    /// fit.
130    ///
131    /// `survival_likelihood` is `None` by default — there is no library-side
132    /// string default (#2301). An explicit `Some(mode)` selects that mode; an
133    /// unset `None` resolves to the single canonical default `"transformation"`
134    /// (Royston-Parmar), the same default the CLI documents. This is the ONE
135    /// resolution point: the `Surv(...)` materialization seam, the CLI survival
136    /// path, and the pyffi survival path all consult it, so the default lives in
137    /// exactly one place. A non-`Surv()` formula never calls this — `Some(_)` on
138    /// a non-survival response is a typed configuration error rejected by
139    /// [`reject_survival_likelihood_for_nonsurvival`], and `None` is unset.
140    pub fn resolved_survival_likelihood(&self) -> &str {
141        self.survival_likelihood
142            .as_deref()
143            .unwrap_or("transformation")
144    }
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn resolve_normalizes_front_end_spellings() {
153        let resolved = FitConfig {
154            family: Some(" AUTO ".to_string()),
155            survival_likelihood: Some(" Transformation ".to_string()),
156            baseline_target: " Linear ".to_string(),
157            ..FitConfig::default()
158        }
159        .resolve()
160        .unwrap();
161        assert_eq!(resolved.family, None);
162        assert_eq!(resolved.survival_likelihood.as_deref(), Some("transformation"));
163        assert_eq!(resolved.baseline_target, "linear");
164    }
165
166    #[test]
167    fn resolve_rejects_invalid_shared_fields() {
168        assert!(
169            FitConfig {
170                ridge_lambda: f64::NAN,
171                ..FitConfig::default()
172            }
173            .resolve()
174            .is_err()
175        );
176        assert!(
177            FitConfig {
178                outer_max_iter: Some(0),
179                ..FitConfig::default()
180            }
181            .resolve()
182            .is_err()
183        );
184        assert!(
185            FitConfig {
186                weight_column: Some("   ".to_string()),
187                ..FitConfig::default()
188            }
189            .resolve()
190            .is_err()
191        );
192    }
193}