Skip to main content

gam_terms/
term_builder.rs

1//! Term construction: bridge from parsed formula terms to `TermCollectionSpec`.
2//!
3//! This module takes the AST produced by `inference::formula_dsl` and a loaded
4//! dataset, resolves column references, infers knot counts and center strategies,
5//! and produces a `TermCollectionSpec` ready for `build_term_collection_design`.
6
7use std::collections::{BTreeMap, BTreeSet, HashMap};
8use std::path::PathBuf;
9
10use ndarray::{Array2, ArrayView1};
11
12use crate::basis::{
13    BSplineBasisSpec, BSplineBoundaryConditions, BSplineEndpointBoundaryCondition,
14    BSplineIdentifiability, BSplineKnotSpec, CenterCountRequest, CenterStrategy,
15    ConstantCurvatureBasisSpec, ConstantCurvatureIdentifiability, DuchonBasisSpec,
16    DuchonNullspaceOrder, DuchonOperatorPenaltySpec, MaternBasisSpec, MaternIdentifiability,
17    MaternNu, MeasureJetBasisSpec, MeasureJetIdentifiability, OneDimensionalBoundary,
18    SpatialIdentifiability, SphereMethod, SphereWahbaKernel, SphericalSplineBasisSpec,
19    SphericalSplineIdentifiability, ThinPlateBasisSpec, auto_spatial_center_strategy,
20    default_num_centers, default_spatial_center_strategy, default_spherical_harmonic_degree,
21    plan_spatial_basis, thin_plate_penalty_order,
22};
23use crate::inference::formula_dsl::{
24    ParsedTerm, SmoothKind, option_bool, option_f64, option_f64_strict, option_usize,
25    option_usize_any, option_usize_any_strict, option_usize_strict, strip_quotes,
26};
27use crate::smooth::{
28    ByVarKind, FactorSmoothFlavour, FactorSmoothSpec, LinearCoefficientGeometry, LinearTermSpec,
29    RandomEffectTermSpec, ShapeConstraint, SmoothBasisSpec, SmoothTermSpec,
30    TensorBSplineIdentifiability, TensorBSplinePenaltyDecomposition, TensorBSplineSpec,
31    TermCollectionSpec,
32};
33use gam_problem::types::ColIdx;
34use gam_data::{ColumnKindTag, DataError, EncodedDataset as Dataset};
35use gam_runtime::resource::ResourcePolicy;
36
37/// Default B-spline degree when a smooth's `degree=` option is absent. Cubic
38/// (degree 3) is the standard GAM convention: C² continuity with a low knot
39/// count.
40const DEFAULT_BSPLINE_DEGREE: usize = 3;
41
42/// Default difference-penalty order when a smooth's `penalty_order=` (alias
43/// `m=`) option is absent. Second-order (curvature) is the standard P-spline
44/// convention.
45const DEFAULT_PENALTY_ORDER: usize = 2;
46
47/// Default basis dimension for one-dimensional cyclic cubic P-splines.
48///
49/// Periodic smooths spend no coefficients on free endpoints, so they should not
50/// inherit the larger open B-spline knot ceiling by default.  This is still only
51/// a default: callers can request a richer periodic space with `k=`.
52const CYCLIC_DEFAULT_BASIS_DIM: usize = 12;
53
54/// Default shared-marginal basis dimension for `bs="fs"`/`bs="sz"` factor smooths,
55/// matching mgcv's factor-smooth default `k=10`. A factor smooth shares one
56/// marginal across all levels; a modest basis recovers the shared signal without
57/// over-fitting each group's within-group noise (gam#903). Overridden by an
58/// explicit `k`/`basis_dim`.
59const FACTOR_SMOOTH_DEFAULT_BASIS_DIM: usize = 10;
60
61/// Default row-chunk size for the out-of-core PCA-basis smooth when the
62/// `chunk_size=` option is absent. Streams the design in row blocks to bound
63/// peak memory independent of the dataset row count.
64const DEFAULT_PCA_CHUNK_SIZE: usize = 4096;
65
66// ---------------------------------------------------------------------------
67// Typed errors
68// ---------------------------------------------------------------------------
69
70/// Typed errors emitted by term-builder helpers. `Display` reproduces the exact
71/// pre-refactor `format!(...)` text byte-for-byte, so callers that string-match
72/// on the message (tests, log assertions) keep working unchanged. Public-API
73/// functions still return `Result<_, String>` and use `.to_string()` shims at
74/// their boundary to stay compatible with callers in protected modules.
75#[derive(Clone, Debug)]
76pub enum TermBuilderError {
77    /// Column-resolution / column-kind lookup failures whose context is purely
78    /// internal (column-kind table out-of-sync, alias map missing an entry,
79    /// etc.). User-facing "this formula references a column that doesn't
80    /// exist" diagnostics use the dedicated `ColumnNotFound` variant so the
81    /// FFI boundary can lift the structured payload into a Python
82    /// `ColumnNotFoundError` without parsing prose.
83    MissingColumn { reason: String },
84    /// A formula referenced a column that is not present in the input data.
85    /// Mirrors `DataError::ColumnNotFound` field-for-field so the conversion
86    /// across module boundaries is a pure data move (no re-derivation, no
87    /// string re-parsing). Public callers see byte-identical `Display`
88    /// output to the legacy `missing_column_message` text.
89    ColumnNotFound {
90        name: String,
91        role: Option<String>,
92        available: Vec<String>,
93        similar: Vec<String>,
94        tsv_hint: bool,
95    },
96    /// User-specified configuration is internally inconsistent (e.g. too few
97    /// variables for a smooth type, conflicting size options, requested basis
98    /// dimension below the polynomial nullspace).
99    IncompatibleConfig { reason: String },
100    /// Option parsing failure: malformed numeric expression, unknown option
101    /// key, out-of-range integer, list-length mismatch, etc.
102    InvalidOption { reason: String },
103    /// User requested a feature that is intentionally not supported (unknown
104    /// smooth type / method / kernel / identifiability, non-zero anchor,
105    /// internal-only token, etc.).
106    UnsupportedFeature { reason: String },
107    /// Input data is degenerate for the requested term (constant column,
108    /// non-finite categorical entries, ...).
109    DegenerateData { reason: String },
110    /// Term-collection-stage formula error — a node that the caller was
111    /// supposed to resolve upstream reached the builder.
112    MalformedFormula { reason: String },
113}
114
115impl std::fmt::Display for TermBuilderError {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        match self {
118            TermBuilderError::MissingColumn { reason }
119            | TermBuilderError::IncompatibleConfig { reason }
120            | TermBuilderError::InvalidOption { reason }
121            | TermBuilderError::UnsupportedFeature { reason }
122            | TermBuilderError::DegenerateData { reason }
123            | TermBuilderError::MalformedFormula { reason } => f.write_str(reason),
124            // Delegate to the canonical `DataError::ColumnNotFound` formatter
125            // so a single source of truth defines the human text. The
126            // intermediate `DataError` constructed here owns its strings only
127            // for the duration of the Display call — no allocation cost
128            // beyond the original payload that this variant already holds.
129            TermBuilderError::ColumnNotFound {
130                name,
131                role,
132                available,
133                similar,
134                tsv_hint,
135            } => {
136                let canonical = DataError::ColumnNotFound {
137                    name: name.clone(),
138                    role: role.clone(),
139                    available: available.clone(),
140                    similar: similar.clone(),
141                    tsv_hint: *tsv_hint,
142                };
143                std::fmt::Display::fmt(&canonical, f)
144            }
145        }
146    }
147}
148
149impl From<TermBuilderError> for String {
150    fn from(err: TermBuilderError) -> String {
151        err.to_string()
152    }
153}
154
155/// Catchall lift for the term-builder's internal `Result<_, String>` helpers
156/// (numeric expression parsing, option lookup, boundary-condition parsing,
157/// ...) that flow into `build_termspec` via `?`. Maps to
158/// `IncompatibleConfig`, which is the most appropriate generic bucket for
159/// option/config-style failures — leaf sites that emit structured payloads
160/// (`From<DataError>` for column-not-found) bypass this fallback.
161impl From<String> for TermBuilderError {
162    fn from(reason: String) -> Self {
163        Self::IncompatibleConfig { reason }
164    }
165}
166
167/// Typed lift from data-layer errors. `DataError::ColumnNotFound` becomes
168/// `TermBuilderError::ColumnNotFound` field-for-field — no stringification,
169/// no information loss — so the FFI boundary downstream can dispatch on
170/// the typed variant. Other `DataError` variants degrade into
171/// `MissingColumn` since they describe column-resolution-time failures
172/// without a dedicated structured destination.
173impl From<DataError> for TermBuilderError {
174    fn from(err: DataError) -> Self {
175        match err {
176            DataError::ColumnNotFound {
177                name,
178                role,
179                available,
180                similar,
181                tsv_hint,
182            } => Self::ColumnNotFound {
183                name,
184                role,
185                available,
186                similar,
187                tsv_hint,
188            },
189            DataError::SchemaMismatch { reason }
190            | DataError::ParseError { reason }
191            | DataError::EncodingFailure { reason }
192            | DataError::EmptyInput { reason }
193            | DataError::InvalidValue { reason } => Self::MissingColumn { reason },
194        }
195    }
196}
197
198// Constructor helpers — keep error-site code compact and consistent.
199impl TermBuilderError {
200    #[inline]
201    fn missing_column(reason: impl Into<String>) -> Self {
202        TermBuilderError::MissingColumn {
203            reason: reason.into(),
204        }
205    }
206    #[inline]
207    fn incompatible_config(reason: impl Into<String>) -> Self {
208        TermBuilderError::IncompatibleConfig {
209            reason: reason.into(),
210        }
211    }
212    #[inline]
213    fn invalid_option(reason: impl Into<String>) -> Self {
214        TermBuilderError::InvalidOption {
215            reason: reason.into(),
216        }
217    }
218    #[inline]
219    fn unsupported_feature(reason: impl Into<String>) -> Self {
220        TermBuilderError::UnsupportedFeature {
221            reason: reason.into(),
222        }
223    }
224    #[inline]
225    fn degenerate_data(reason: impl Into<String>) -> Self {
226        TermBuilderError::DegenerateData {
227            reason: reason.into(),
228        }
229    }
230    #[inline]
231    fn malformed_formula(reason: impl Into<String>) -> Self {
232        TermBuilderError::MalformedFormula {
233            reason: reason.into(),
234        }
235    }
236}
237
238// ---------------------------------------------------------------------------
239// Column resolution
240// ---------------------------------------------------------------------------
241
242/// Resolve a bare column name to its index, returning a typed
243/// `DataError::ColumnNotFound` on miss so the FFI boundary can surface a
244/// structured `gamfit.ColumnNotFoundError(column=…, available=…)` rather
245/// than rely on string-classification of human prose. Internal callers that
246/// still flow `Result<_, String>` get byte-identical text via
247/// `From<DataError> for String`.
248pub fn resolve_col(col_map: &HashMap<String, usize>, name: &str) -> Result<usize, DataError> {
249    col_map
250        .get(name)
251        .copied()
252        .ok_or_else(|| DataError::column_not_found(col_map, name, None))
253}
254
255/// Like `resolve_col` but tags the missing-column payload with a role label
256/// (`"response"`, `"entry"`, `"exit"`, `"event"`, `"z"`, `"id"`, …) so the
257/// boundary-side Python exception can disambiguate which formula slot held
258/// the bad reference.
259pub fn resolve_role_col(
260    col_map: &HashMap<String, usize>,
261    name: &str,
262    role: &str,
263) -> Result<usize, DataError> {
264    col_map
265        .get(name)
266        .copied()
267        .ok_or_else(|| DataError::column_not_found(col_map, name, Some(role)))
268}
269
270fn encoded_levels_for_column(ds: &Dataset, col: ColIdx) -> Vec<(u64, String)> {
271    let mut seen = BTreeSet::<u64>::new();
272    for value in ds.values.column(col.get()) {
273        if value.is_finite() {
274            seen.insert(value.to_bits());
275        }
276    }
277    let schema_levels = ds
278        .schema
279        .columns
280        .get(col.get())
281        .map(|column| column.levels.as_slice())
282        .unwrap_or(&[]);
283    seen.into_iter()
284        .enumerate()
285        .map(|(idx, bits)| {
286            let fallback = format!("level{}", idx + 1);
287            let label = schema_levels.get(idx).cloned().unwrap_or(fallback);
288            (bits, label)
289        })
290        .collect()
291}
292
293pub fn column_map_with_alias(
294    col_map: &HashMap<String, usize>,
295    alias: &str,
296    target_column: &str,
297) -> HashMap<String, usize> {
298    let mut aliased = col_map.clone();
299    if let Some(idx) = col_map.get(target_column).copied() {
300        aliased.entry(alias.to_string()).or_insert(idx);
301    }
302    aliased
303}
304
305// ---------------------------------------------------------------------------
306// ParsedTerm[] + Dataset → TermCollectionSpec
307// ---------------------------------------------------------------------------
308
309pub fn build_termspec(
310    terms: &[ParsedTerm],
311    ds: &Dataset,
312    col_map: &HashMap<String, usize>,
313    inference_notes: &mut Vec<String>,
314    policy: &ResourcePolicy,
315) -> Result<TermCollectionSpec, TermBuilderError> {
316    let mut linear_terms = Vec::<LinearTermSpec>::new();
317    let mut random_terms = Vec::<RandomEffectTermSpec>::new();
318    let mut smooth_terms = Vec::<SmoothTermSpec>::new();
319    let smooth_coordinate_count = terms
320        .iter()
321        .map(|term| match term {
322            ParsedTerm::Smooth { vars, .. } => vars.len(),
323            _ => 0,
324        })
325        .sum::<usize>();
326
327    for t in terms {
328        match t {
329            ParsedTerm::Linear {
330                name,
331                explicit,
332                coefficient_min,
333                coefficient_max,
334            } => {
335                let col = resolve_col(col_map, name)?;
336                let auto_kind = ds.column_kinds.get(col).copied().ok_or_else(|| {
337                    TermBuilderError::missing_column(format!(
338                        "internal column-kind lookup failed for '{name}'"
339                    ))
340                    .to_string()
341                })?;
342                if *explicit {
343                    linear_terms.push(LinearTermSpec {
344                        name: name.clone(),
345                        feature_col: col,
346                        feature_cols: vec![col],
347                        categorical_levels: vec![],
348                        // Parametric linear terms are unpenalized by default
349                        // (MLE, matching mgcv/glm); see #749.
350                        double_penalty: false,
351                        coefficient_geometry: LinearCoefficientGeometry::Unconstrained,
352                        coefficient_min: *coefficient_min,
353                        coefficient_max: *coefficient_max,
354                    });
355                } else {
356                    match auto_kind {
357                        ColumnKindTag::Continuous | ColumnKindTag::Binary => {
358                            linear_terms.push(LinearTermSpec {
359                                name: name.clone(),
360                                feature_col: col,
361                                feature_cols: vec![col],
362                                categorical_levels: vec![],
363                                // Unpenalized parametric effect by default (#749).
364                                double_penalty: false,
365                                coefficient_geometry: LinearCoefficientGeometry::Unconstrained,
366                                coefficient_min: *coefficient_min,
367                                coefficient_max: *coefficient_max,
368                            });
369                        }
370                        ColumnKindTag::Categorical => {
371                            if coefficient_min.is_some() || coefficient_max.is_some() {
372                                return Err(TermBuilderError::incompatible_config(format!(
373                                    "coefficient constraints are not supported for categorical auto-random-effect term '{name}'; use group({name}) or an unconstrained numeric term"
374                                )));
375                            }
376                            random_terms.push(RandomEffectTermSpec {
377                                name: name.clone(),
378                                feature_col: col,
379                                drop_first_level: false,
380                                penalized: true,
381                                frozen_levels: None,
382                            });
383                        }
384                    }
385                }
386            }
387            ParsedTerm::BoundedLinear {
388                name,
389                min,
390                max,
391                prior,
392            } => {
393                let col = resolve_col(col_map, name)?;
394                let auto_kind = ds.column_kinds.get(col).copied().ok_or_else(|| {
395                    TermBuilderError::missing_column(format!(
396                        "internal column-kind lookup failed for '{name}'"
397                    ))
398                    .to_string()
399                })?;
400                if !matches!(auto_kind, ColumnKindTag::Continuous | ColumnKindTag::Binary) {
401                    return Err(TermBuilderError::incompatible_config(format!(
402                        "bounded() currently supports only numeric columns, got categorical '{name}'"
403                    )));
404                }
405                linear_terms.push(LinearTermSpec {
406                    name: name.clone(),
407                    feature_col: col,
408                    feature_cols: vec![col],
409                    categorical_levels: vec![],
410                    double_penalty: false,
411                    coefficient_geometry: LinearCoefficientGeometry::Bounded {
412                        min: *min,
413                        max: *max,
414                        prior: prior.clone(),
415                    },
416                    coefficient_min: None,
417                    coefficient_max: None,
418                });
419            }
420            ParsedTerm::RandomEffect { name } => {
421                let col = resolve_col(col_map, name)?;
422                random_terms.push(RandomEffectTermSpec {
423                    name: name.clone(),
424                    feature_col: col,
425                    drop_first_level: false,
426                    penalized: true,
427                    frozen_levels: None,
428                });
429            }
430            ParsedTerm::Smooth {
431                label,
432                vars,
433                kind,
434                options,
435            } => {
436                let smooth_vars = vars.clone();
437                let by_name = options.get("by").cloned();
438                // `bs="sz"` (sum-to-zero), like `bs="fs"`/`bs="re"`, is a
439                // factor-smooth family handled natively by `build_smooth_basis`'s
440                // fs/sz/re path: it detects the categorical factor among the
441                // variables and emits a `SmoothBasisSpec::FactorSmooth { Sz }`
442                // with the correct single-penalty marginal and modest default
443                // basis. Route sz straight through `build_smooth_basis` rather
444                // than intercepting it into a legacy `FactorSumToZero` envelope
445                // here (which left `sz(fac, x)` mis-typed as `FactorSumToZero`
446                // instead of the expected `FactorSmooth { Sz }`).
447                let cols = smooth_vars
448                    .iter()
449                    .map(|v| resolve_col(col_map, v))
450                    .collect::<Result<Vec<_>, _>>()?;
451                let mut inner_options = options.clone();
452                inner_options.remove("by");
453                // `ordered=` is consumed here (ByVarKind::Factor routing) and
454                // must not propagate to the inner basis builder, which has no
455                // allow-list entry for it and would reject it as an unknown option.
456                inner_options.remove("ordered");
457                // Pop the shape constraint before `build_smooth_basis` runs so
458                // it never reaches the per-kind `validate_known_options`
459                // allow-lists (the constraint is a property of the smooth term,
460                // not of any one basis kind). Basis-incompatible requests still
461                // fail loudly downstream via `shape_supports_basis`.
462                let shape = match inner_options.remove("shape") {
463                    None => ShapeConstraint::None,
464                    Some(raw) => crate::smooth::parse_shape_constraint(&raw)
465                        .map_err(TermBuilderError::invalid_option)?,
466                };
467                let inner_basis = build_smooth_basis(
468                    *kind,
469                    &smooth_vars,
470                    &cols,
471                    &inner_options,
472                    ds,
473                    inference_notes,
474                    policy,
475                    smooth_coordinate_count,
476                )?;
477                if let Some(by_name) = by_name {
478                    let by_col = resolve_col(col_map, &by_name)?;
479                    match ds.column_kinds.get(by_col).copied().ok_or_else(|| {
480                        format!("internal column-kind lookup failed for by variable '{by_name}'")
481                    })? {
482                        ColumnKindTag::Categorical => {
483                            let levels = encoded_levels_for_column(ds, ColIdx::new(by_col));
484                            // A penalized random block for this factor already
485                            // owns its full level offsets when EITHER an explicit
486                            // `group(factor)` appears, OR a *bare* categorical
487                            // `+ factor` does — the latter is auto-promoted to a
488                            // penalized random-effect block (see the
489                            // `ParsedTerm::Linear` / `ColumnKindTag::Categorical`
490                            // arm above, `penalized: true`). Both representations
491                            // carry the same per-level offsets, so #1457: the
492                            // `by=` branch must NOT additionally add its own
493                            // unpenalized treatment-coded main effect, which would
494                            // double-represent the factor (two `g` design blocks +
495                            // a spurious extra smoothing parameter).
496                            let penalized_group_owner_present =
497                                terms.iter().any(|other| match other {
498                                    ParsedTerm::RandomEffect { name } => name == &by_name,
499                                    ParsedTerm::Linear {
500                                        name,
501                                        explicit: false,
502                                        ..
503                                    } if name == &by_name => col_map
504                                        .get(name)
505                                        .and_then(|c| ds.column_kinds.get(*c).copied())
506                                        .map(|kind| matches!(kind, ColumnKindTag::Categorical))
507                                        .unwrap_or(false),
508                                    _ => false,
509                                });
510                            // Add an unpenalized treatment-coded fixed main
511                            // effect for a standalone factor-by smooth, unless
512                            // the same factor already has an explicit
513                            // `group(factor)` term OR a bare categorical `+
514                            // factor` that was auto-promoted to a penalized
515                            // random block (#1457).  In those mixed-model forms
516                            // the penalized random intercept is the coherent
517                            // owner of level offsets; adding a no-pooling fixed
518                            // factor effect would bypass random-effect
519                            // shrinkage and degrade BLUP-style predictions.
520                            if !random_terms.iter().any(|rt| rt.name == by_name)
521                                && !penalized_group_owner_present
522                            {
523                                random_terms.push(RandomEffectTermSpec {
524                                    name: by_name.clone(),
525                                    feature_col: by_col,
526                                    drop_first_level: true,
527                                    penalized: false,
528                                    frozen_levels: None,
529                                });
530                            }
531                            // Route to a single BySmooth::Factor term with
532                            // frozen levels pre-populated from the training data.
533                            // Design building later gates each level into its own
534                            // column block (see build_by_smooth_local in term_specs).
535                            let frozen_levels: Vec<u64> =
536                                levels.iter().map(|(bits, _)| *bits).collect();
537                            smooth_terms.push(SmoothTermSpec {
538                                name: label.clone(),
539                                basis: SmoothBasisSpec::BySmooth {
540                                    smooth: Box::new(inner_basis),
541                                    by_kind: ByVarKind::Factor {
542                                        feature_col: by_col,
543                                        ordered: option_bool(options, "ordered").unwrap_or(false),
544                                        frozen_levels: Some(frozen_levels),
545                                    },
546                                },
547                                shape,
548                                joint_null_rotation: None,
549                            });
550                        }
551                        ColumnKindTag::Binary | ColumnKindTag::Continuous => {
552                            smooth_terms.push(SmoothTermSpec {
553                                name: label.clone(),
554                                basis: SmoothBasisSpec::BySmooth {
555                                    smooth: Box::new(inner_basis),
556                                    by_kind: ByVarKind::Numeric {
557                                        feature_col: by_col,
558                                    },
559                                },
560                                shape,
561                                joint_null_rotation: None,
562                            });
563                        }
564                    }
565                } else {
566                    smooth_terms.push(SmoothTermSpec {
567                        name: label.clone(),
568                        basis: inner_basis,
569                        shape,
570                        joint_null_rotation: None,
571                    });
572                }
573            }
574            ParsedTerm::LinkWiggle { .. }
575            | ParsedTerm::TimeWiggle { .. }
576            | ParsedTerm::LinkConfig { .. }
577            | ParsedTerm::SurvivalConfig { .. } => {
578                // Consumed at formula level, not design terms.
579            }
580            ParsedTerm::LogSlopeSurface { .. } => {
581                return Err(TermBuilderError::malformed_formula(
582                    "logslope(...) declarations must be resolved by the marginal-slope formula path before building a term spec",
583                ));
584            }
585            ParsedTerm::Interaction { vars } => {
586                // A linear `:` interaction realizes one design column equal to
587                // the elementwise product of its operands. Numeric (continuous/
588                // binary) operands multiply directly; a categorical operand is
589                // a factor, so the product is expanded factor-aware: one design
590                // column per surviving cell of the factor(s), each an indicator
591                // `1[factor == level]` gating the numeric product.
592                //
593                // Coding is MARGINALITY-AWARE (gam#1158, gam#1159). A categorical
594                // operand `g` is treatment-coded (its lexicographically first
595                // reference level dropped) ONLY when the lower-order term obtained
596                // by removing `g` from this interaction is also present in the
597                // model — that lower-order term is what makes the dropped level
598                // identifiable, exactly mgcv's marginality rule. When that parent
599                // is ABSENT (the interaction-only form), dropping the reference
600                // level instead pins a group to the reference fit (a rank-deficient
601                // design), so we keep ALL levels (full dummy coding) and rely on a
602                // single intercept cell-drop below for identifiability:
603                //   * `y ~ x:g` with no `x` main effect → "common intercept,
604                //     separate slopes": every group keeps its own x-slope.
605                //   * `y ~ g:h` with no `g`/`h` main effects → the saturated
606                //     cell-means model: full cross of all levels minus one
607                //     reference cell absorbed by the intercept.
608                // When the parents ARE present (`x + x:g`, or `g*h` = `g + h +
609                // g:h`), the historical treatment coding is preserved so those
610                // forms stay correct.
611                //
612                // A main effect for var V is a `Linear`/`BoundedLinear`/
613                // `RandomEffect` ParsedTerm whose referenced name is V (an
614                // auto-detected categorical `Linear` becomes a RandomEffect main
615                // effect; either spelling counts). We only treat such standalone
616                // main-effect terms as parents — not V appearing inside another
617                // interaction.
618                let main_effect_present = |target: &str| -> bool {
619                    terms.iter().any(|other| match other {
620                        ParsedTerm::Linear { name, .. }
621                        | ParsedTerm::BoundedLinear { name, .. }
622                        | ParsedTerm::RandomEffect { name } => name == target,
623                        _ => false,
624                    })
625                };
626                // The lower-order parent of dropping operand `drop_var` from this
627                // interaction is present iff EVERY other operand is a main effect.
628                // For the two cases we care about (`x:g`, `g:h`) the interaction
629                // has two operands, so this reduces to "is the single remaining
630                // operand a main effect"; the general form handles any arity.
631                let parent_present = |drop_var: &str| -> bool {
632                    vars.iter()
633                        .filter(|v| v.as_str() != drop_var)
634                        .all(|v| main_effect_present(v))
635                };
636
637                let mut numeric_cols = Vec::<usize>::new();
638                // Per categorical operand: (var name, col, kept levels, was the
639                // reference level dropped / treatment-coded?).
640                let mut categorical_factors =
641                    Vec::<(String, usize, Vec<(u64, String)>, bool)>::new();
642                for var in vars {
643                    let col = resolve_col(col_map, var)?;
644                    let kind = ds.column_kinds.get(col).copied().ok_or_else(|| {
645                        TermBuilderError::missing_column(format!(
646                            "internal column-kind lookup failed for '{var}'"
647                        ))
648                        .to_string()
649                    })?;
650                    match kind {
651                        ColumnKindTag::Continuous | ColumnKindTag::Binary => numeric_cols.push(col),
652                        ColumnKindTag::Categorical => {
653                            let mut levels = encoded_levels_for_column(ds, ColIdx::new(col));
654                            // Treatment-code (drop the reference level) only when
655                            // the marginal parent that identifies it is present;
656                            // otherwise keep every level (full dummy coding).
657                            let treatment_coded = parent_present(var);
658                            if treatment_coded && levels.len() > 1 {
659                                levels.remove(0);
660                            }
661                            if levels.is_empty() {
662                                return Err(TermBuilderError::incompatible_config(format!(
663                                    "interaction `{}` references categorical column `{var}` with no usable levels",
664                                    vars.join(":")
665                                )));
666                            }
667                            categorical_factors.push((var.clone(), col, levels, treatment_coded));
668                        }
669                    }
670                }
671
672                let label = vars.join(":");
673
674                if categorical_factors.is_empty() {
675                    // Pure numeric `:` interaction — single product column,
676                    // identical to the historical behaviour.
677                    linear_terms.push(LinearTermSpec {
678                        name: label,
679                        feature_col: numeric_cols[0],
680                        feature_cols: numeric_cols,
681                        categorical_levels: vec![],
682                        // Parametric `:` interaction column is unpenalized by
683                        // default, same as any other linear term (#749).
684                        double_penalty: false,
685                        coefficient_geometry: LinearCoefficientGeometry::Unconstrained,
686                        coefficient_min: None,
687                        coefficient_max: None,
688                    });
689                    inference_notes.push(format!(
690                        "wired linear interaction `{}` as product of numeric columns",
691                        vars.join(":")
692                    ));
693                } else {
694                    // Factor-aware expansion: cartesian product over the kept
695                    // levels of every categorical operand. Each cell yields one
696                    // column gating the numeric product (or, with no numeric
697                    // operand, a pure cell indicator).
698                    let mut cells: Vec<Vec<(usize, u64, String)>> = vec![Vec::new()];
699                    for (_var, col, levels, _treatment_coded) in &categorical_factors {
700                        let mut next = Vec::with_capacity(cells.len() * levels.len());
701                        for cell in &cells {
702                            for (bits, level_label) in levels {
703                                let mut extended = cell.clone();
704                                extended.push((*col, *bits, level_label.clone()));
705                                next.push(extended);
706                            }
707                        }
708                        cells = next;
709                    }
710
711                    // Intercept-identifiability cell drop. When the cells are PURE
712                    // INDICATORS (no numeric operand) and at least one factor was
713                    // dummy-coded (kept all its levels), the full set of cell
714                    // columns sums to the all-ones intercept and is rank-deficient
715                    // against it. Drop exactly ONE reference cell — the cell where
716                    // every factor sits at its reference (lexicographically first)
717                    // level — so the remaining saturated cells are identifiable
718                    // (rank n_g*n_h - 1 cells + intercept). With a numeric operand
719                    // the cells gate `x` and sum to `x`, not the intercept, so no
720                    // cell is dropped (the collinearity there is with the absent
721                    // `x` main effect, which is exactly why full coding is right).
722                    let any_dummy_coded = categorical_factors
723                        .iter()
724                        .any(|(_, _, _, treatment_coded)| !*treatment_coded);
725                    if numeric_cols.is_empty() && any_dummy_coded {
726                        // The reference cell pairs each factor's column with the
727                        // bits of its lexicographically-first (index 0) level.
728                        let reference_cell: Vec<(usize, u64)> = categorical_factors
729                            .iter()
730                            .map(|(_, col, _, _)| {
731                                let levels = encoded_levels_for_column(ds, ColIdx::new(*col));
732                                (*col, levels[0].0)
733                            })
734                            .collect();
735                        cells.retain(|cell| {
736                            !reference_cell.iter().all(|(rcol, rbits)| {
737                                cell.iter()
738                                    .any(|(col, bits, _)| col == rcol && bits == rbits)
739                            })
740                        });
741                    }
742
743                    let n_cells = cells.len();
744                    for cell in cells {
745                        let cell_suffix = cell
746                            .iter()
747                            .map(|(_, _, level_label)| level_label.as_str())
748                            .collect::<Vec<_>>()
749                            .join(":");
750                        let categorical_levels =
751                            cell.iter().map(|(col, bits, _)| (*col, *bits)).collect();
752                        // `feature_col` is required to point at a real column;
753                        // use the first numeric operand when present, otherwise
754                        // the first categorical column (its raw value is never
755                        // multiplied — `realized_design_column` starts from ones
756                        // and only gates by the level indicators).
757                        let feature_col = numeric_cols
758                            .first()
759                            .copied()
760                            .unwrap_or(categorical_factors[0].1);
761                        linear_terms.push(LinearTermSpec {
762                            name: format!("{label}:{cell_suffix}"),
763                            feature_col,
764                            feature_cols: numeric_cols.clone(),
765                            categorical_levels,
766                            double_penalty: false,
767                            coefficient_geometry: LinearCoefficientGeometry::Unconstrained,
768                            coefficient_min: None,
769                            coefficient_max: None,
770                        });
771                    }
772                    let all_treatment_coded = !any_dummy_coded;
773                    let coding = if all_treatment_coded {
774                        "treatment-coded"
775                    } else {
776                        "marginality-aware (full dummy / saturated)"
777                    };
778                    inference_notes.push(format!(
779                        "wired factor-aware linear interaction `{}` as {} {} cell column(s)",
780                        vars.join(":"),
781                        n_cells,
782                        coding
783                    ));
784                }
785            }
786        }
787    }
788
789    Ok(TermCollectionSpec {
790        linear_terms,
791        random_effect_terms: random_terms,
792        smooth_terms,
793    })
794}
795
796fn split_list_option(raw: &str) -> Vec<String> {
797    let t = raw.trim();
798    // Accept the Python/JSON list form `[a, b]` AND mgcv's R-vector forms
799    // `c(a, b)` / `(a, b)` as bracketed wrappers around a comma-separated body.
800    // mgcv-style formulas pass per-margin numeric options as `k=c(5,5)` /
801    // `period=c(2*pi, pi)`; without R-vector peeling here those entries were
802    // split into `["c(5", "5)"]` and the downstream numeric parser then
803    // misreported the leading garbage as the invalid digit.
804    let inner = t
805        .strip_prefix('[')
806        .and_then(|u| u.strip_suffix(']'))
807        .or_else(|| {
808            t.strip_prefix("c(")
809                .or_else(|| t.strip_prefix("C("))
810                .or_else(|| t.strip_prefix('('))
811                .and_then(|u| u.strip_suffix(')'))
812        })
813        .unwrap_or(t);
814    inner
815        .split(',')
816        .map(|v| v.trim().to_string())
817        .filter(|v| !v.is_empty())
818        .collect()
819}
820
821fn parse_numeric_expr(raw: &str) -> Result<f64, String> {
822    let mut acc = 1.0f64;
823    let normalized = raw.replace(' ', "");
824    if normalized.eq_ignore_ascii_case("none") {
825        return Err("None is not numeric".to_string());
826    }
827    for factor in normalized.split('*') {
828        if factor.is_empty() {
829            return Err(format!("invalid numeric expression '{raw}'"));
830        }
831        let value = if factor.eq_ignore_ascii_case("pi") || factor == "π" {
832            std::f64::consts::PI
833        } else if factor.eq_ignore_ascii_case("tau") || factor == "τ" {
834            std::f64::consts::TAU
835        } else if let Some(prefix) = factor
836            .strip_suffix("pi")
837            .or_else(|| factor.strip_suffix("π"))
838        {
839            let coefficient = if prefix.is_empty() {
840                1.0
841            } else {
842                prefix
843                    .parse::<f64>()
844                    .map_err(|err| format!("invalid numeric expression '{raw}': {err}"))?
845            };
846            coefficient * std::f64::consts::PI
847        } else if let Some(prefix) = factor
848            .strip_suffix("tau")
849            .or_else(|| factor.strip_suffix("τ"))
850        {
851            let coefficient = if prefix.is_empty() {
852                1.0
853            } else {
854                prefix
855                    .parse::<f64>()
856                    .map_err(|err| format!("invalid numeric expression '{raw}': {err}"))?
857            };
858            coefficient * std::f64::consts::TAU
859        } else {
860            factor
861                .parse::<f64>()
862                .map_err(|err| format!("invalid numeric expression '{raw}': {err}"))?
863        };
864        acc *= value;
865    }
866    Ok(acc)
867}
868
869/// Read an endpoint/period option as a numeric *expression* (`2*pi`, `tau`,
870/// `0.5*tau`, `6.283185307179586`, ...) — the same grammar that `period=` and
871/// `origin=` already accept via [`parse_numeric_expr`].
872///
873/// Returns `Ok(None)` when the key is absent, `Ok(Some(v))` when it parses, and
874/// a hard `Err` when the key is *present but unparseable*. The crucial contrast
875/// is with the lenient [`option_f64`], which collapses an unparseable value to
876/// `None` and lets the caller silently substitute the data range — wrapping a
877/// cyclic smooth at the wrong period with no diagnostic (the #815 failure mode).
878fn option_numeric_expr(
879    options: &BTreeMap<String, String>,
880    key: &str,
881) -> Result<Option<f64>, String> {
882    match options.get(key) {
883        None => Ok(None),
884        Some(raw) => parse_numeric_expr(raw)
885            .map(Some)
886            .map_err(|err| format!("option `{key}={raw}` is not a valid numeric value: {err}")),
887    }
888}
889
890fn parse_periods_option(
891    options: &BTreeMap<String, String>,
892    dim: usize,
893) -> Result<Option<Vec<Option<f64>>>, String> {
894    let Some(raw) = options.get("period") else {
895        return Ok(None);
896    };
897    let values = split_list_option(raw);
898    let mut periods = vec![None; dim];
899    if values.len() == 1 && dim == 1 {
900        periods[0] = Some(parse_numeric_expr(&values[0])?);
901    } else {
902        if values.len() != dim {
903            return Err(format!(
904                "period list length {} must match smooth dimension {}",
905                values.len(),
906                dim
907            ));
908        }
909        for (i, v) in values.iter().enumerate() {
910            if v.eq_ignore_ascii_case("none") {
911                continue;
912            }
913            periods[i] = Some(parse_numeric_expr(v)?);
914        }
915    }
916    Ok(Some(periods))
917}
918
919fn parse_periodic_axes_option(
920    options: &BTreeMap<String, String>,
921    dim: usize,
922) -> Result<Option<Vec<Option<f64>>>, String> {
923    let Some(raw_axes) = options.get("periodic") else {
924        return Ok(None);
925    };
926    let mut periods = parse_periods_option(options, dim)?.unwrap_or_else(|| vec![None; dim]);
927    // Scalar boolean form (`periodic=true` / `false`, `yes` / `no`) applies to
928    // every axis — the documented per-axis-flag broadcast (see the doc on
929    // `parse_periodic_axes`, the tensor sibling that already accepts it). A
930    // 1-D `duchon(x, periodic=true)` lands here: the cyclic *domain* is then
931    // resolved from the data range by `parse_cyclic_boundary` (the 1-D builder
932    // consults `boundary` first), so a finite explicit period is NOT required —
933    // we only need to NOT mis-read "true" as an axis index (#1074). `false`
934    // means no axis is periodic.
935    let lowered = raw_axes.trim().to_ascii_lowercase();
936    match lowered.as_str() {
937        "true" | "yes" | "y" => return Ok(Some(periods)),
938        "false" | "no" | "n" => return Ok(Some(vec![None; dim])),
939        _ => {}
940    }
941    let axes = split_list_option(raw_axes);
942    if axes.is_empty() {
943        return Ok(Some(periods));
944    }
945
946    // Boolean forms `periodic=true` / `periodic=[true, false, ...]`, mirroring
947    // `parse_tensor_periodic_axes`. The radial 1-D builders (`duchon`/`tps`/
948    // `matern`) intentionally DERIVE the wrap period from the closed center
949    // lattice when none is supplied (`prepare_periodic_duchon_centers_1d_with_period`,
950    // gam#580: `None => span`), so a boolean-selected periodic axis legitimately
951    // omits `period`. Without this branch, `duchon(x, periodic=true)`-style
952    // radial formulas failed with the misleading "invalid periodic axis 'true'".
953    let is_bool = |t: &str| {
954        matches!(
955            t.to_ascii_lowercase().as_str(),
956            "true" | "yes" | "y" | "false" | "no" | "n"
957        )
958    };
959    let is_truthy = |t: &str| matches!(t.to_ascii_lowercase().as_str(), "true" | "yes" | "y");
960
961    // Scalar boolean: `periodic=true` / `periodic=false`.
962    if axes.len() == 1 && is_bool(&axes[0]) {
963        if !is_truthy(&axes[0]) {
964            // Non-periodic: return None so the 1-D builder (which routes on
965            // `spec.periodic.is_some()`) does NOT take the periodic path.
966            return Ok(None);
967        }
968        // Every axis periodic; honor any explicit per-axis period, else leave
969        // `None` for the caller (formula arm) / builder to derive the span.
970        return Ok(Some(periods));
971    }
972
973    // Per-axis boolean list: `periodic=[true, false, ...]` (length must match dim).
974    if axes.iter().all(|a| is_bool(a)) {
975        if axes.len() != dim {
976            return Err(format!(
977                "periodic flag list length {} must match smooth dimension {dim}",
978                axes.len()
979            ));
980        }
981        if !axes.iter().any(|a| is_truthy(a)) {
982            return Ok(None);
983        }
984        for (i, a) in axes.iter().enumerate() {
985            if !is_truthy(a) {
986                periods[i] = None;
987            }
988        }
989        return Ok(Some(periods));
990    }
991
992    // Index-list form: `periodic=[0, 2]`. Each listed axis must carry an
993    // explicit finite period — an index gives no per-axis span-derive hint.
994    for a in &axes {
995        let axis = a
996            .parse::<usize>()
997            .map_err(|err| format!("invalid periodic axis '{a}': {err}"))?;
998        if axis >= dim {
999            return Err(format!(
1000                "periodic axis {axis} out of range for {dim}D smooth"
1001            ));
1002        }
1003        if periods[axis].is_none() {
1004            return Err(format!(
1005                "periodic axis {axis} requires period[{axis}] to be finite"
1006            ));
1007        }
1008    }
1009    // Axes not listed are non-periodic even if period list has a finite placeholder.
1010    let listed: std::collections::BTreeSet<usize> = axes
1011        .iter()
1012        .filter_map(|a| a.parse::<usize>().ok())
1013        .collect();
1014    for i in 0..dim {
1015        if !listed.contains(&i) {
1016            periods[i] = None;
1017        }
1018    }
1019    Ok(Some(periods))
1020}
1021
1022// ---------------------------------------------------------------------------
1023// Smooth basis spec construction
1024// ---------------------------------------------------------------------------
1025
1026fn parse_option_list(raw: &str) -> Vec<String> {
1027    let trimmed = raw.trim();
1028    // Accept both the Python/JSON list form `[a, b]` and mgcv's R vector form
1029    // `c(a, b)` (and a bare `(a, b)`) as the bracketed wrapper around a
1030    // comma-separated option list. mgcv writes per-margin options as
1031    // `bs=c('tp','tp')` / `m=c(2,2)`, so the `c(...)` form must round-trip
1032    // through the same splitter the `[...]` form uses.
1033    let inner = trimmed
1034        .strip_prefix('[')
1035        .and_then(|v| v.strip_suffix(']'))
1036        .or_else(|| {
1037            trimmed
1038                .strip_prefix("c(")
1039                .or_else(|| trimmed.strip_prefix("C("))
1040                .or_else(|| trimmed.strip_prefix('('))
1041                .and_then(|v| v.strip_suffix(')'))
1042        })
1043        .unwrap_or(trimmed);
1044    inner
1045        .split(',')
1046        .map(|v| {
1047            v.trim()
1048                .trim_matches('"')
1049                .trim_matches('\'')
1050                .to_ascii_lowercase()
1051        })
1052        .filter(|v| !v.is_empty())
1053        .collect()
1054}
1055
1056fn parse_periodic_axes(
1057    options: &BTreeMap<String, String>,
1058    dim: usize,
1059) -> Result<Vec<bool>, String> {
1060    let mut axes = vec![false; dim];
1061    if let Some(raw) = options.get("periodic").or_else(|| options.get("cyclic")) {
1062        let lowered = raw.trim().to_ascii_lowercase();
1063        match lowered.as_str() {
1064            "true" | "yes" | "y" => {
1065                axes.fill(true);
1066                return Ok(axes);
1067            }
1068            "false" | "no" | "n" => return Ok(axes),
1069            _ => {}
1070        }
1071        for axis_raw in parse_option_list(raw) {
1072            let axis = axis_raw
1073                .parse::<usize>()
1074                .map_err(|err| format!("invalid periodic axis '{axis_raw}': {err}"))?;
1075            if axis >= dim {
1076                return Err(format!(
1077                    "periodic axis {axis} out of range for {dim}D smooth"
1078                ));
1079            }
1080            axes[axis] = true;
1081        }
1082    }
1083    if let Some(raw) = options.get("boundary").or_else(|| options.get("bc")) {
1084        let boundary = parse_option_list(raw);
1085        if boundary.len() == dim {
1086            for (axis, value) in boundary.iter().enumerate() {
1087                if matches!(value.as_str(), "periodic" | "cyclic" | "cc") {
1088                    axes[axis] = true;
1089                }
1090            }
1091        } else if dim == 1
1092            && matches!(
1093                boundary.first().map(String::as_str),
1094                Some("periodic" | "cyclic" | "cc")
1095            )
1096        {
1097            axes[0] = true;
1098        }
1099    }
1100    Ok(axes)
1101}
1102
1103fn parse_optional_numeric_list(
1104    options: &BTreeMap<String, String>,
1105    keys: &[&str],
1106    dim: usize,
1107) -> Result<Vec<Option<f64>>, String> {
1108    let Some(raw) = keys.iter().find_map(|key| options.get(*key)) else {
1109        return Ok(vec![None; dim]);
1110    };
1111    let values = split_list_option(raw);
1112    let mut out = vec![None; dim];
1113    if values.len() == 1 && dim == 1 {
1114        if !values[0].eq_ignore_ascii_case("none") {
1115            out[0] = Some(parse_numeric_expr(&values[0])?);
1116        }
1117        return Ok(out);
1118    }
1119    if values.len() != dim {
1120        return Err(format!(
1121            "numeric option list length {} must match smooth dimension {}",
1122            values.len(),
1123            dim
1124        ));
1125    }
1126    for (i, value) in values.iter().enumerate() {
1127        if !value.eq_ignore_ascii_case("none") {
1128            out[i] = Some(parse_numeric_expr(value)?);
1129        }
1130    }
1131    Ok(out)
1132}
1133
1134fn parse_periods(
1135    options: &BTreeMap<String, String>,
1136    periodic_axes: &[bool],
1137) -> Result<Vec<Option<f64>>, String> {
1138    let dim = periodic_axes.len();
1139    // Broadcast a single-element `period=[v]` onto the lone periodic axis
1140    // of a multi-axis smooth (e.g. `te(th, h, bc=['periodic','natural'],
1141    // period=[2*pi])`): with only one periodic margin, the value can only
1142    // belong there.
1143    let lone_periodic_broadcast = options
1144        .get("period")
1145        .or_else(|| options.get("periods"))
1146        .and_then(|raw| {
1147            let values = split_list_option(raw);
1148            if values.len() != 1 || dim <= 1 {
1149                return None;
1150            }
1151            let mut iter = periodic_axes.iter().enumerate().filter(|(_, p)| **p);
1152            let first = iter.next()?;
1153            if iter.next().is_some() {
1154                return None;
1155            }
1156            Some((first.0, values.into_iter().next().unwrap()))
1157        });
1158    let periods = if let Some((axis, value)) = lone_periodic_broadcast {
1159        let mut out = vec![None; dim];
1160        if !value.eq_ignore_ascii_case("none") {
1161            out[axis] = Some(parse_numeric_expr(&value)?);
1162        }
1163        out
1164    } else {
1165        parse_optional_numeric_list(options, &["period", "periods"], dim)?
1166    };
1167    for (axis, (periodic, period)) in periodic_axes.iter().zip(periods.iter()).enumerate() {
1168        if *periodic
1169            && let Some(value) = period
1170            && (!value.is_finite() || *value <= 0.0)
1171        {
1172            return Err(format!(
1173                "period for periodic axis {axis} must be finite and positive, got {value}"
1174            ));
1175        }
1176    }
1177    Ok(periods)
1178}
1179
1180fn parse_period_origins(
1181    options: &BTreeMap<String, String>,
1182    periodic_axes: &[bool],
1183) -> Result<Vec<Option<f64>>, String> {
1184    parse_optional_numeric_list(
1185        options,
1186        &[
1187            "origin",
1188            "origins",
1189            "period_origin",
1190            "period-origin",
1191            "domain_origin",
1192        ],
1193        periodic_axes.len(),
1194    )
1195}
1196
1197/// Parse a per-axis periodic flag list for tensor smooths. Accepts three forms:
1198/// - `periodic=true` / `periodic=false` (scalar applied to every axis),
1199/// - `periodic=[true, false, ...]` (one flag per axis, length `dim`),
1200/// - `periodic=c(1, 1)` / `c(0, 0)` (a length-`dim` 0/1 mask, mgcv's
1201///   per-margin spelling — distinguished from an axis-index list by the
1202///   repeated 0/1 value), and
1203/// - `periodic=[0, 2, ...]` (axis indices that are periodic; others are not).
1204///
1205/// `boundary=[..., "periodic"/"cyclic"/"cc", ...]` may also flip individual
1206/// axes on; non-matching tokens leave the existing flag unchanged.
1207fn parse_tensor_periodic_axes(
1208    options: &BTreeMap<String, String>,
1209    dim: usize,
1210) -> Result<Vec<bool>, String> {
1211    let mut axes = vec![false; dim];
1212    if let Some(raw) = options.get("periodic").or_else(|| options.get("cyclic")) {
1213        let lowered = raw.trim().to_ascii_lowercase();
1214        match lowered.as_str() {
1215            "true" | "yes" | "y" => {
1216                axes.fill(true);
1217            }
1218            "false" | "no" | "n" => {
1219                // Already false; allow `boundary=` below to flip axes if set.
1220            }
1221            _ => {
1222                let entries = parse_option_list(raw);
1223                let all_bool = !entries.is_empty()
1224                    && entries.iter().all(|v| {
1225                        matches!(
1226                            v.as_str(),
1227                            "true" | "yes" | "y" | "false" | "no" | "n" | "none"
1228                        )
1229                    });
1230                // mgcv writes per-margin flag vectors as `periodic=c(1,1)` /
1231                // `periodic=c(0,0)` — a length-`dim` mask where each entry is a
1232                // 0/1 flag for THAT margin, not an axis index. A bare axis-index
1233                // list (`periodic=[0,1]`, `periodic=[0]`) lists DISTINCT margin
1234                // indices to turn on. The two collide only when the list is all
1235                // 0/1 of length `dim`; disambiguate by the repeated-value
1236                // signature `c(1,1)`/`c(0,0)` (a valid axis-index set never
1237                // repeats an index), which is the canonical mask spelling. This
1238                // is what makes the leading tensor margin honor its periodic flag
1239                // (#1751: `periodic=c(1,1)` previously parsed `1,1` as axis
1240                // indices, marking only axis 1 and dropping axis 0).
1241                let all_zero_one = !entries.is_empty()
1242                    && entries.iter().all(|v| v == "0" || v == "1");
1243                let has_repeat = {
1244                    let mut seen = std::collections::BTreeSet::new();
1245                    !entries.iter().all(|v| seen.insert(v.clone()))
1246                };
1247                let numeric_mask = all_zero_one && entries.len() == dim && has_repeat;
1248                if all_bool || numeric_mask {
1249                    if entries.len() != dim {
1250                        return Err(format!(
1251                            "periodic list length {} must match smooth dimension {}",
1252                            entries.len(),
1253                            dim
1254                        ));
1255                    }
1256                    for (i, v) in entries.iter().enumerate() {
1257                        axes[i] = matches!(v.as_str(), "true" | "yes" | "y" | "1");
1258                    }
1259                } else {
1260                    for axis_raw in entries {
1261                        let axis = axis_raw
1262                            .parse::<usize>()
1263                            .map_err(|err| format!("invalid periodic axis '{axis_raw}': {err}"))?;
1264                        if axis >= dim {
1265                            return Err(format!(
1266                                "periodic axis {axis} out of range for {dim}D smooth"
1267                            ));
1268                        }
1269                        axes[axis] = true;
1270                    }
1271                }
1272            }
1273        }
1274    }
1275    if let Some(raw) = options.get("boundary").or_else(|| options.get("bc")) {
1276        let boundary = parse_option_list(raw);
1277        if boundary.len() == dim {
1278            for (axis, value) in boundary.iter().enumerate() {
1279                if matches!(value.as_str(), "periodic" | "cyclic" | "cc") {
1280                    axes[axis] = true;
1281                }
1282            }
1283        }
1284    }
1285    // A per-margin basis vector (`bs=c('cc','ps')` / `type=[...]`) declares each
1286    // margin's basis family, and a cyclic family (`cc`/`cp`/`cyclic`) makes THAT
1287    // margin periodic — exactly as the 1-D `s(x, bs='cc')` smooth wraps its lone
1288    // axis. Without this, the per-margin `cc` token was validated but discarded:
1289    // every `bs=c(...)` spelling collapsed to the same open B-spline tensor
1290    // (#1752). Only honor the vector form here; a scalar `bs='cc'` on a tensor is
1291    // ambiguous about which margins wrap, so it does not flip any axis on.
1292    if let Some(raw) = options.get("bs").or_else(|| options.get("type"))
1293        && bs_selector_is_vector(raw)
1294    {
1295        let per_margin = parse_option_list(raw);
1296        if per_margin.len() == dim {
1297            for (axis, margin_bs) in per_margin.iter().enumerate() {
1298                if matches!(
1299                    canonicalize_smooth_type(margin_bs),
1300                    "cc" | "cp" | "cyclic"
1301                ) {
1302                    axes[axis] = true;
1303                }
1304            }
1305        }
1306    }
1307    Ok(axes)
1308}
1309
1310/// Reject endpoint boundary conditions (`clamped`/`anchored`) requested on a
1311/// tensor-product margin.
1312///
1313/// Tensor smooths support `bc=`/`boundary=` only for *periodic* margin
1314/// selection (`periodic`/`cyclic`/`cc`), which [`parse_tensor_periodic_axes`]
1315/// consumes. Endpoint boundary conditions are a 1-D B-spline structural
1316/// reparameterization and are NOT implemented for tensor margins, but the
1317/// periodic-axes parser silently ignores every non-periodic token — so
1318/// `te(x, y, bc=['clamped', 'natural'])` used to be accepted as a no-op and
1319/// fit an ordinary unconstrained tensor, dropping the user's clamp without a
1320/// word. Surface it as a clean, explicit error instead of a silent drop. The
1321/// inert margin tokens (`natural`/`free`/`none`/empty) and the periodic
1322/// selectors are accepted; anything else is an unsupported endpoint BC.
1323fn reject_tensor_endpoint_boundary_conditions(
1324    options: &BTreeMap<String, String>,
1325    dim: usize,
1326) -> Result<(), String> {
1327    let Some(raw) = options.get("boundary").or_else(|| options.get("bc")) else {
1328        return Ok(());
1329    };
1330    let entries = parse_option_list(raw);
1331    for (axis, value) in entries.iter().enumerate() {
1332        let inert = matches!(
1333            value.as_str(),
1334            "natural" | "free" | "none" | "" | "periodic" | "cyclic" | "cc"
1335        );
1336        if !inert {
1337            return Err(TermBuilderError::unsupported_feature(format!(
1338                "tensor smooth margin {axis} endpoint boundary condition '{value}' is not supported \
1339                 (got bc/boundary={raw:?} on a {dim}-D tensor); tensor margins accept only periodic \
1340                 selection (periodic/cyclic/cc) or the inert natural/free token. Apply clamped/anchored \
1341                 endpoint boundary conditions with a 1-D s(x, bc=...) term instead."
1342            ))
1343            .to_string());
1344        }
1345    }
1346    Ok(())
1347}
1348
1349fn tensor_k_axis_option_axis(
1350    key: &str,
1351    cols: &[usize],
1352    ds: &Dataset,
1353) -> Result<Option<usize>, String> {
1354    let Some(suffix) = key.strip_prefix("k_") else {
1355        return Ok(None);
1356    };
1357    if suffix.is_empty() {
1358        return Err("tensor k axis option must be named k_<axis> or k_<variable>".to_string());
1359    }
1360    if let Ok(axis) = suffix.parse::<usize>() {
1361        return if axis < cols.len() {
1362            Ok(Some(axis))
1363        } else {
1364            Err(format!(
1365                "tensor k axis option `{key}` references axis {axis}, but the smooth has {} margins",
1366                cols.len()
1367            ))
1368        };
1369    }
1370
1371    let mut matches = cols
1372        .iter()
1373        .enumerate()
1374        .filter(|(_, col)| ds.headers.get(**col).is_some_and(|name| name == suffix))
1375        .map(|(axis, _)| axis);
1376    let first = matches.next();
1377    if matches.next().is_some() {
1378        return Err(format!(
1379            "tensor k axis option `{key}` matches more than one margin named `{suffix}`"
1380        ));
1381    }
1382    first.map(Some).ok_or_else(|| {
1383        let margin_names = cols
1384            .iter()
1385            .enumerate()
1386            .map(|(axis, col)| {
1387                let name = ds
1388                    .headers
1389                    .get(*col)
1390                    .map(String::as_str)
1391                    .unwrap_or("<unnamed>");
1392                format!("{axis}:{name}")
1393            })
1394            .collect::<Vec<_>>()
1395            .join(", ");
1396        format!(
1397            "tensor k axis option `{key}` does not match a margin index or name; tensor margins are [{margin_names}]"
1398        )
1399    })
1400}
1401
1402fn is_tensor_k_axis_option_key(key: &str) -> bool {
1403    key.strip_prefix("k_")
1404        .is_some_and(|suffix| !suffix.is_empty())
1405}
1406
1407/// Parse a per-margin basis dimension list (`k=<scalar>`, `k=[k0, k1, ...]`,
1408/// or axis aliases like `k_x=...` / `k_0=...`). A scalar is broadcast across
1409/// all axes; `None` returns the heuristic from the data column.
1410fn parse_tensor_k_list(
1411    options: &BTreeMap<String, String>,
1412    cols: &[usize],
1413    ds: &Dataset,
1414) -> Result<(Vec<usize>, bool), String> {
1415    let mut axis_values = vec![None; cols.len()];
1416    let mut saw_axis_alias = false;
1417    for (key, value) in options {
1418        let Some(axis) = tensor_k_axis_option_axis(key, cols, ds)? else {
1419            continue;
1420        };
1421        saw_axis_alias = true;
1422        if axis_values[axis].is_some() {
1423            return Err(format!("tensor k axis {axis} is specified more than once"));
1424        }
1425        let k: usize = value
1426            .parse()
1427            .map_err(|err| format!("invalid tensor k option `{key}={value}`: {err}"))?;
1428        axis_values[axis] = Some(k);
1429    }
1430
1431    let raw = options
1432        .get("k")
1433        .or_else(|| options.get("basis_dim"))
1434        .or_else(|| options.get("basis-dim"))
1435        .or_else(|| options.get("basisdim"));
1436    if saw_axis_alias {
1437        if raw.is_some() {
1438            return Err(
1439                "tensor k axis aliases cannot be combined with k= or basis_dim=".to_string(),
1440            );
1441        }
1442        if let Some(missing_axis) = axis_values.iter().position(Option::is_none) {
1443            let margin_name = cols
1444                .get(missing_axis)
1445                .and_then(|col| ds.headers.get(*col))
1446                .map(String::as_str)
1447                .unwrap_or("<unnamed>");
1448            return Err(format!(
1449                "tensor k axis aliases must specify every margin; missing axis {missing_axis} ({margin_name})"
1450            ));
1451        }
1452        return Ok((
1453            axis_values
1454                .into_iter()
1455                .map(|k| k.expect("missing axis values rejected above"))
1456                .collect(),
1457            false,
1458        ));
1459    }
1460    let Some(raw) = raw else {
1461        let inferred = heuristic_tensor_margin_knots(cols, ds);
1462        return Ok((inferred, true));
1463    };
1464    let entries = split_list_option(raw);
1465    if entries.len() == 1 {
1466        let k: usize = entries[0]
1467            .parse()
1468            .map_err(|err| format!("invalid tensor k '{}': {err}", entries[0]))?;
1469        return Ok((vec![k; cols.len()], false));
1470    }
1471    if entries.len() != cols.len() {
1472        return Err(format!(
1473            "tensor k list length {} must match smooth dimension {}",
1474            entries.len(),
1475            cols.len()
1476        ));
1477    }
1478    let mut out = Vec::with_capacity(entries.len());
1479    for entry in entries {
1480        let k: usize = entry
1481            .parse()
1482            .map_err(|err| format!("invalid tensor k '{entry}': {err}"))?;
1483        out.push(k);
1484    }
1485    Ok((out, false))
1486}
1487
1488/// Parse the `identifiability=` option for tensor-product smooths. Mirrors the
1489/// vocabulary of the Matern/Duchon parsers so the formula DSL is consistent.
1490///
1491/// `kind` selects the default identifiability when no explicit
1492/// `identifiability=` option is supplied: `te(...)` ([`SmoothKind::Te`]) keeps
1493/// the full-tensor sum-to-zero default, while `ti(...)` ([`SmoothKind::Ti`])
1494/// defaults to per-margin sum-to-zero so the marginal main effects are excluded
1495/// (the mgcv tensor-interaction semantics). An explicit option always wins.
1496fn parse_tensor_identifiability(
1497    options: &BTreeMap<String, String>,
1498    kind: SmoothKind,
1499) -> Result<TensorBSplineIdentifiability, String> {
1500    let Some(raw) = options.get("identifiability").map(String::as_str) else {
1501        return Ok(match kind {
1502            SmoothKind::Ti => TensorBSplineIdentifiability::MarginalSumToZero,
1503            _ => TensorBSplineIdentifiability::default(),
1504        });
1505    };
1506    match raw.trim().to_ascii_lowercase().as_str() {
1507        "none" => Ok(TensorBSplineIdentifiability::None),
1508        "sum_tozero" | "sum-to-zero" | "center_sum_tozero" | "center-sum-to-zero" | "centered"
1509        | "sumtozero" => Ok(TensorBSplineIdentifiability::SumToZero),
1510        "marginal_sum_tozero" | "marginal-sum-to-zero" | "marginal_sumtozero"
1511        | "marginalsumtozero" | "interaction" => {
1512            Ok(TensorBSplineIdentifiability::MarginalSumToZero)
1513        }
1514        other => Err(TermBuilderError::unsupported_feature(format!(
1515            "invalid tensor identifiability '{other}'; expected one of: none, sum_tozero, marginal_sum_tozero"
1516        ))
1517        .to_string()),
1518    }
1519}
1520
1521fn bspline_boundary_declares_periodic_axis(options: &BTreeMap<String, String>) -> bool {
1522    options
1523        .get("boundary")
1524        .or_else(|| options.get("bc"))
1525        .map(|raw| {
1526            parse_option_list(raw)
1527                .into_iter()
1528                .any(|value| matches!(value.as_str(), "periodic" | "cyclic" | "cc"))
1529        })
1530        .unwrap_or(false)
1531}
1532
1533/// Canonical-name lookup for the `bs=`/`type=` smooth selector.
1534///
1535/// User-facing names — including mgcv-compatible spellings whose semantics
1536/// match an existing gamfit smooth exactly — collapse to the engine-internal
1537/// canonical names used by the dispatch in [`build_smooth_basis`]. Adding a
1538/// new exactly-equivalent alias is a one-line entry here; the match arms
1539/// below remain the single dispatch site.
1540///
1541/// Aliases listed here MUST be true semantic equivalents of the canonical
1542/// target, not approximations. mgcv names whose semantics differ from any
1543/// gamfit smooth (e.g. `bs="ts"` shrinkage thin-plate, `bs="ad"` adaptive)
1544/// are intentionally NOT mapped here — they should reach the unsupported-type
1545/// path so users get a real diagnostic instead of a silent semantic
1546/// substitution. mgcv's `bs="cr"`/`"cs"` (cubic regression and its shrinkage
1547/// twin) are handled directly in the [`build_smooth_basis`] dispatch — they
1548/// are not aliased here because the `cr`/`cs` distinction controls a default
1549/// (`double_penalty`) that the canonical-name layer cannot see.
1550///
1551/// Unrecognised inputs pass through unchanged so the dispatch can produce its
1552/// usual "unsupported smooth type" error, preserving the existing diagnostic
1553/// surface for genuine typos.
1554pub(crate) fn canonicalize_smooth_type(raw: &str) -> &str {
1555    match raw {
1556        // Thin-plate spline. mgcv `bs="tp"` is the default thin-plate
1557        // regression spline — exact semantic equivalent of gamfit's `"tps"`.
1558        "tp" => "tps",
1559        // Gaussian process / Matérn. mgcv `bs="gp"` defaults to a Matérn
1560        // covariance kernel with REML smoothing parameter selection, which
1561        // matches gamfit's `"matern"` exactly (same kernel-Gram identity,
1562        // same REML route).
1563        "gp" => "matern",
1564        // Constant-curvature (M_κ) geodesic-kernel smooth (#944). All aliases
1565        // collapse to one canonical type so `bs="curv"`/`bs="mkappa"` cannot
1566        // diverge from `curv(...)`.
1567        "curv" | "constant_curvature" | "mkappa" => "curvature",
1568        // Measure-jet spline: multiscale local-jet-residual energy of the
1569        // empirical measure. No mgcv equivalent (mgcv has no measure-learned
1570        // geometry smooth), so no mgcv alias is mapped.
1571        "mjs" | "measure_jet" | "web" => "measurejet",
1572        other => other,
1573    }
1574}
1575
1576/// Is `margin_bs` a per-margin basis name that the tensor builder realizes as a
1577/// penalized 1-D B-spline margin?
1578///
1579/// gam's tensor product is built from penalized B-spline marginals. mgcv's
1580/// thin-plate (`tp`/`tps`), P-spline (`ps`), B-spline (`bs`), cubic-regression
1581/// (`cr`/`cs`), and cyclic (`cc`/`cp`/`cyclic`) marginals are all penalized
1582/// splines spanning the same per-axis smoothing space, so a B-spline margin
1583/// reproduces the same tensor smoothing class. Margin kinds with fundamentally
1584/// different structure (adaptive, random-effect, sphere) are NOT accepted as
1585/// tensor margins.
1586pub(crate) fn tensor_margin_bs_is_supported(margin_bs: &str) -> bool {
1587    matches!(
1588        canonicalize_smooth_type(margin_bs),
1589        "tps" | "ps" | "bs" | "bspline" | "cr" | "cs" | "cc" | "cp" | "cyclic"
1590    )
1591}
1592
1593/// Does the smooth request a periodic/cyclic axis via its options?
1594///
1595/// Mirrors the boundary-condition reading used by the periodic-aware dispatch
1596/// branches. Factored out so the type resolver and `build_smooth_basis` agree
1597/// on a single notion of "periodic requested".
1598pub(crate) fn smooth_options_declare_periodic(options: &BTreeMap<String, String>) -> bool {
1599    options.contains_key("periodic")
1600        || options.contains_key("cyclic")
1601        || options
1602            .get("boundary")
1603            .or_else(|| options.get("bc"))
1604            .map(|boundary| {
1605                boundary.to_ascii_lowercase().contains("periodic")
1606                    || boundary.to_ascii_lowercase().contains("cyclic")
1607            })
1608            .unwrap_or(false)
1609}
1610
1611/// Resolve the canonical engine-internal smooth-type name for a term.
1612///
1613/// Reads the user-facing `type=`/`bs=` selector and collapses mgcv-compatible
1614/// aliases (`tp`→`tps`, `gp`→`matern`) via [`canonicalize_smooth_type`], or
1615/// derives the default from the smooth kind/arity when no selector is given.
1616/// This is the single source of truth for the dispatch in
1617/// [`build_smooth_basis`]; other call sites (e.g. predictor-specific basis
1618/// policy) use it so the classification never drifts from the dispatch.
1619/// Is the raw `bs=`/`type=` selector a vector literal (`c('tp','tp')`,
1620/// `['tp','tp']`, `(tp, tp)`) rather than a scalar smooth-type name?
1621///
1622/// mgcv's tensor smooths take a *per-margin* basis vector
1623/// (`te(x1, x2, bs=c('tp','tp'))`). Such a value is not a scalar canonical
1624/// type and must not be fed through [`canonicalize_smooth_type`] — it has to be
1625/// recognized as a tensor request and split into per-margin types. A scalar
1626/// selector (`bs="tp"`) is left untouched.
1627pub(crate) fn bs_selector_is_vector(raw: &str) -> bool {
1628    let trimmed = raw.trim();
1629    let bracketed = (trimmed.starts_with('[') && trimmed.ends_with(']'))
1630        || (trimmed.starts_with("c(") || trimmed.starts_with("C(")) && trimmed.ends_with(')')
1631        || (trimmed.starts_with('(') && trimmed.ends_with(')'));
1632    bracketed && !parse_option_list(trimmed).is_empty()
1633}
1634
1635pub fn resolve_smooth_type_name(
1636    kind: SmoothKind,
1637    n_cols: usize,
1638    options: &BTreeMap<String, String>,
1639) -> String {
1640    let selector = options.get("type").or_else(|| options.get("bs"));
1641    // A per-margin basis vector is a tensor request, never a scalar type. Route
1642    // it to the tensor builder, which reads the per-margin types out of the
1643    // same `bs=` option. (A vector on a non-tensor smooth is ill-formed and
1644    // falls through to the scalar path below so the existing diagnostic fires.)
1645    if let Some(raw) = selector
1646        && bs_selector_is_vector(raw)
1647        && matches!(kind, SmoothKind::Te | SmoothKind::Ti | SmoothKind::T2)
1648    {
1649        return "tensor".to_string();
1650    }
1651    selector
1652        .map(|s| canonicalize_smooth_type(&s.to_ascii_lowercase()).to_string())
1653        .unwrap_or_else(|| match kind {
1654            SmoothKind::Te | SmoothKind::Ti | SmoothKind::T2 => "tensor".to_string(),
1655            SmoothKind::S if n_cols == 1 => "bspline".to_string(),
1656            // Mixed periodic Euclidean radial kernels are not separable on the
1657            // cylinder. Use a tensor product with a cyclic margin so s(theta,h)
1658            // honors seam continuity while preserving the formula-level s(...).
1659            SmoothKind::S if smooth_options_declare_periodic(options) => "tensor".to_string(),
1660            SmoothKind::S => "tps".to_string(),
1661        })
1662}
1663
1664/// Does this canonical smooth type size its basis through the generous spatial
1665/// center heuristic ([`crate::basis::default_num_centers`])?
1666///
1667/// Only the radial spatial bases (thin-plate, Matérn/GP, Duchon) route their
1668/// default basis dimension through `plan_spatial_basis(.., Default, ..)`. The
1669/// B-spline, cyclic, tensor, and factor-smooth bases use their own modest
1670/// knot-based defaults, so they are unaffected by — and must not be perturbed
1671/// by — secondary-predictor basis-parsimony adjustments (#501).
1672pub fn smooth_type_uses_spatial_center_heuristic(canonical_type: &str) -> bool {
1673    matches!(canonical_type, "tps" | "matern" | "duchon")
1674}
1675
1676pub fn build_smooth_basis(
1677    kind: SmoothKind,
1678    vars: &[String],
1679    cols: &[usize],
1680    options: &BTreeMap<String, String>,
1681    ds: &Dataset,
1682    inference_notes: &mut Vec<String>,
1683    policy: &ResourcePolicy,
1684    smooth_coordinate_count: usize,
1685) -> Result<SmoothBasisSpec, String> {
1686    // Fail fast on degenerate input: a smooth whose (non-categorical) coordinate
1687    // columns collapse to a SINGLE distinct point can only ever fit the response
1688    // mean — its design matrix is rank-1. For a UNIVARIATE smooth this is exactly
1689    // "the one column is constant": `smooth(x)`/`matern(x)` on constant `x` would
1690    // otherwise silently fit the mean of `y` with no visible cue (Duchon already
1691    // errors loudly via the basis layer; this makes the diagnosis explicit and
1692    // uniform). For a MULTIVARIATE smooth (tensor, sphere, tps, ...) a single
1693    // constant coordinate is NOT degenerate — the basis still varies along the
1694    // other coordinate(s) and the penalty absorbs the rank-deficient direction
1695    // (e.g. a constant-longitude meridian arc on the sphere is a well-posed 1-D
1696    // slice of S²). Such a term is degenerate only when EVERY coordinate is
1697    // constant at once, i.e. the joint input is a single point. Test the JOINT
1698    // cardinality, not each column independently, so the loud diagnosis still
1699    // fires for the genuinely rank-1 case without rejecting well-posed
1700    // lower-dimensional slices.
1701    let coord_cols: Vec<(&String, usize)> = vars
1702        .iter()
1703        .zip(cols.iter().copied())
1704        .filter(|(_, col)| !matches!(ds.column_kinds.get(*col), Some(ColumnKindTag::Categorical)))
1705        .collect();
1706    if !coord_cols.is_empty() {
1707        let views: Vec<ArrayView1<'_, f64>> = coord_cols
1708            .iter()
1709            .map(|(_, col)| ds.values.column(*col))
1710            .collect();
1711        let n_rows = views[0].len();
1712        let mut distinct_points = std::collections::HashSet::<Vec<u64>>::new();
1713        for r in 0..n_rows {
1714            let key: Vec<u64> = views
1715                .iter()
1716                .map(|v| {
1717                    let x = v[r];
1718                    let norm = if x == 0.0 { 0.0 } else { x };
1719                    norm.to_bits()
1720                })
1721                .collect();
1722            distinct_points.insert(key);
1723            if distinct_points.len() > 1 {
1724                break;
1725            }
1726        }
1727        if distinct_points.len() <= 1 {
1728            return Err(TermBuilderError::degenerate_data(if coord_cols.len() == 1 {
1729                let var = coord_cols[0].0;
1730                format!(
1731                    "smooth term over '{var}' has only one unique value in the training data \
1732                     — a smooth on a constant column is degenerate and would only fit the response mean. \
1733                     Remove `{var}` from the smooth, drop the term, or check the data."
1734                )
1735            } else {
1736                let names = coord_cols
1737                    .iter()
1738                    .map(|(v, _)| v.as_str())
1739                    .collect::<Vec<_>>()
1740                    .join(", ");
1741                format!(
1742                    "smooth term over ({names}) has only one unique joint coordinate in the training \
1743                     data — every coordinate is constant, so the smooth is degenerate and would only \
1744                     fit the response mean. Drop the term or check the data."
1745                )
1746            })
1747            .to_string());
1748        }
1749    }
1750    if let Some(by_name) = options.get("by").cloned() {
1751        let by_col = options
1752            .get("__by_col")
1753            .and_then(|raw| raw.parse::<usize>().ok())
1754            .or_else(|| vars.iter().position(|v| v == &by_name).map(|idx| cols[idx]))
1755            .ok_or_else(|| format!("unknown by= column '{by_name}'"))?;
1756        let mut inner_options = options.clone();
1757        inner_options.remove("by");
1758        inner_options.remove("__by_col");
1759        inner_options.remove("id");
1760        let inner = build_smooth_basis(
1761            kind,
1762            vars,
1763            cols,
1764            &inner_options,
1765            ds,
1766            inference_notes,
1767            policy,
1768            smooth_coordinate_count,
1769        )?;
1770        let by_kind = match ds.column_kinds.get(by_col).copied() {
1771            Some(ColumnKindTag::Categorical) => ByVarKind::Factor {
1772                feature_col: by_col,
1773                ordered: option_bool(options, "ordered").unwrap_or(false),
1774                frozen_levels: None,
1775            },
1776            Some(ColumnKindTag::Continuous | ColumnKindTag::Binary) => ByVarKind::Numeric {
1777                feature_col: by_col,
1778            },
1779            None => {
1780                return Err(format!(
1781                    "internal column-kind lookup failed for by='{by_name}'"
1782                ));
1783            }
1784        };
1785        return Ok(SmoothBasisSpec::BySmooth {
1786            smooth: Box::new(inner),
1787            by_kind,
1788        });
1789    }
1790
1791    let smooth_double_penalty = option_bool(options, "double_penalty").unwrap_or(true);
1792    let type_opt = resolve_smooth_type_name(kind, cols.len(), options);
1793
1794    if matches!(type_opt.as_str(), "fs" | "sz" | "re") {
1795        validate_known_options(
1796            type_opt.as_str(),
1797            options,
1798            &[
1799                "type",
1800                "bs",
1801                "k",
1802                "basis_dim",
1803                "basis-dim",
1804                "basisdim",
1805                "knots",
1806                "knot_placement",
1807                "knot-placement",
1808                "knotplacement",
1809                "degree",
1810                "penalty_order",
1811                "m",
1812                "double_penalty",
1813                "ordered",
1814            ],
1815        )?;
1816        if cols.len() != 2 {
1817            return Err(format!(
1818                "{} factor-smooth currently expects exactly two variables (one numeric, one categorical)",
1819                type_opt
1820            ));
1821        }
1822        let kinds = cols
1823            .iter()
1824            .map(|&c| ds.column_kinds.get(c).copied())
1825            .collect::<Vec<_>>();
1826        let (cont_idx, group_idx) = if type_opt == "re" {
1827            // mgcv random-slope examples are often s(g, x, bs="re").
1828            match (kinds[0], kinds[1]) {
1829                (Some(ColumnKindTag::Categorical), _) => (1usize, 0usize),
1830                (_, Some(ColumnKindTag::Categorical)) => (0usize, 1usize),
1831                _ => (1usize, 0usize),
1832            }
1833        } else {
1834            match (kinds[0], kinds[1]) {
1835                (_, Some(ColumnKindTag::Categorical)) => (0usize, 1usize),
1836                (Some(ColumnKindTag::Categorical), _) => (1usize, 0usize),
1837                _ => {
1838                    return Err(format!(
1839                        "{} factor-smooth requires one categorical factor variable",
1840                        type_opt
1841                    ));
1842                }
1843            }
1844        };
1845        let c = cols[cont_idx];
1846        let (minv, maxv) = col_minmax(ds.values.column(c))?;
1847        let degree = if type_opt == "re" {
1848            1
1849        } else {
1850            option_usize(options, "degree").unwrap_or(DEFAULT_BSPLINE_DEGREE)
1851        };
1852        // For a factor smooth every group's curve is fit from THAT group's rows
1853        // alone, so the marginal's flexibility must respect the least-resolved
1854        // group, not the pooled column. The pooled heuristic can hand the marginal
1855        // a basis that saturates (or exceeds) a small group's sample — e.g. the
1856        // sleepstudy panel has 8 training days per subject, and a default cubic
1857        // basis of 8 functions interpolates each subject's 8 points, leaving no
1858        // room for the wiggliness penalty to collapse the curve toward the
1859        // per-subject line. The factor smooth then fits within-group noise and
1860        // extrapolates badly (held-out forecast worse than the population mean).
1861        //
1862        // Cap the marginal basis below the minimum per-group covariate resolution
1863        // so the penalty always retains residual degrees of freedom to shrink each
1864        // group's curvature toward its linear null space (the random-slope
1865        // estimand). This small-group cap composes with a separate upper bound at
1866        // mgcv's factor-smooth default k=10 (FACTOR_SMOOTH_DEFAULT_BASIS_DIM,
1867        // applied below), so even ample-data groups get the modest SHARED marginal
1868        // a factor smooth wants rather than the full pooled basis. The explicit
1869        // `re` random-effect form takes neither cap: it is a raw linear `[1, x]`
1870        // random effect (0 internal knots), handled in the branch above.
1871        let pooled_internal = heuristic_knots_for_column(ds.values.column(c));
1872        let default_internal = if type_opt == "re" {
1873            // `bs="re"` is a PARAMETRIC random effect, not a smooth of the
1874            // covariate: `s(x, g, bs="re")` is the mgcv random intercept+slope
1875            // `(1 + x | g)`, i.e. a per-group line `[1, x]`, penalized by an iid
1876            // ridge. A degree-1 marginal with ZERO internal knots spans exactly
1877            // that linear space (2 coefficients per group). Using the pooled
1878            // knot heuristic here instead turned the marginal into a
1879            // piecewise-linear B-spline (e.g. 6 functions/group on sleepstudy),
1880            // i.e. a *smooth* with kinks rather than a random slope — many extra
1881            // collinear-across-levels coefficients that ill-condition the joint
1882            // Newton/REML solve (minutes-long fits, and a singular block when
1883            // combined with a separate random intercept `s(g, bs="re")`). The
1884            // raw linear basis is both the correct `re` semantics and fast.
1885            0
1886        } else {
1887            let min_group_resolution =
1888                min_per_group_unique_count(ds.values.column(c), ds.values.column(cols[group_idx]));
1889            // Per-group basis dim = degree + 1 + internal. Hold it well below the
1890            // smallest group's resolution (leave at least two residual points per
1891            // group) so the smooth cannot interpolate that group and the
1892            // wiggliness penalty retains the room to collapse each curve toward
1893            // its linear null space. Never drop below `degree + 2`, which keeps
1894            // exactly the linear span plus a single curvature direction — the
1895            // minimal smoother that can still bend if the data demand it.
1896            let basis_cap = min_group_resolution.saturating_sub(2).max(degree + 2);
1897            let internal_cap = basis_cap.saturating_sub(degree + 1);
1898            let capped = pooled_internal.min(internal_cap.max(1));
1899            // A factor smooth (`fs` AND `sz`) shares ONE marginal across ALL
1900            // levels, each level's curve fit from that group's rows alone. The
1901            // pooled knot heuristic (driven by the full column's sample) hands it
1902            // a much richer basis than the shared signal needs — ~24
1903            // functions/group on the gam#903 factor-smooth-recovery fixtures — so
1904            // REML has the capacity to fit within-group noise and over-fits the
1905            // shared shape (fs: edf 58 vs mgcv's k=10/edf 39; sz: gam 0.068 vs
1906            // mgcv 0.046 truth RMSE), losing the truth-recovery head-to-head with
1907            // the mature tool. mgcv's factor-smooth default `k=10` embodies the
1908            // right convention: a modest shared marginal. Cap the marginal there
1909            // (basis ≈ degree+1+internal ≈ 10) for both flavours when the
1910            // small-group cap above is not already tighter, so REML is not handed
1911            // noise-fitting capacity it does not need. An explicit `k`/`basis_dim`
1912            // overrides this (parse_ps_internal_knots); `re` is the raw linear
1913            // effect handled above.
1914            let fs_default_internal = FACTOR_SMOOTH_DEFAULT_BASIS_DIM
1915                .saturating_sub(degree + 1)
1916                .max(1);
1917            capped.min(fs_default_internal)
1918        };
1919        let (n_knots, _, effective_degree) =
1920            parse_ps_internal_knots(options, degree, default_internal)?;
1921        let penalty_order = option_usize(options, "penalty_order")
1922            .unwrap_or(if effective_degree > 1 { 2 } else { 1 })
1923            .min(effective_degree);
1924        // All factor-smooth flavours (`fs`, `sz`, `re`) place their per-level
1925        // marginal on the SAME penalized B-spline (P-spline) basis. The flavours
1926        // differ ONLY in their penalty/constraint structure (handled below) —
1927        // sz: zero-sum deviation blocks with the per-level null space left
1928        // unpenalized; fs: random-effect double penalty; re: identity ridge.
1929        //
1930        // `sz` USED to route its default-degree marginal to a NATURAL cubic
1931        // regression spline (`cr`), on the belief that mgcv's `bs="sz"` does the
1932        // same and that cr recovers smooth signals more efficiently than the
1933        // (then uncapped) B-spline margin (#1074). That introduced a consistency
1934        // failure (#1605): the `cr` basis enforces the natural boundary
1935        // conditions f''(x_1)=f''(x_k)=0 and extrapolates linearly past the end
1936        // knots, so it CANNOT represent a per-group deviation curve with non-zero
1937        // curvature at the data boundary. Phase-shifted deviation shapes
1938        // (f''(0) = -(2π)² sin(φ) ≠ 0) are then biased toward "free linear +
1939        // anchored wiggle", under-shooting the amplitude — a bias that does NOT
1940        // vanish as n→∞ (n-independent: a genuine consistency failure, not
1941        // finite-sample shrinkage). The earlier #700/#1074 sz fixtures used
1942        // d_g ∝ sin(2πx), whose f'' happens to vanish at x=0 and x=1, so they
1943        // accidentally satisfied the natural BC and never exposed the gap; the
1944        // `fs` sibling, on this very B-spline marginal, recovers the SAME
1945        // phase-shifted data to the noise floor.
1946        //
1947        // The penalized B-spline marginal makes no boundary assumption, so it
1948        // represents arbitrary deviation shapes, and — with the
1949        // FACTOR_SMOOTH_DEFAULT_BASIS_DIM cap above already removing the
1950        // noise-fitting capacity that originally motivated leaving B-splines —
1951        // it recovers the BC-satisfying #700/#1074 signals just as well. Sharing
1952        // one marginal basis across all flavours also lets the B-spline degree/
1953        // knot degradation handle low-cardinality covariates uniformly (what
1954        // `fs` already does), so the `sz`-only cr data-support cap (#1541/#1542)
1955        // — and the asymmetry where only the cr-marginal `sz` spelling hard-
1956        // failed a 3-level ordinal — is no longer needed.
1957        let marginal_knotspec = resolve_nonperiodic_bspline_knotspec(
1958            options,
1959            ds.values.column(c),
1960            (minv, maxv),
1961            effective_degree,
1962            n_knots,
1963        )?;
1964        let marginal = BSplineBasisSpec {
1965            degree: effective_degree,
1966            penalty_order,
1967            knotspec: marginal_knotspec,
1968            // mgcv's `bs="fs"` is a random-effect-style smooth: EVERY per-level
1969            // coefficient, including the marginal null space, is penalized so
1970            // unobserved groups can be predicted — so `fs` keeps the null-space
1971            // (double) penalty. mgcv's `bs="sz"` is a pure across-level
1972            // *deviation* smooth that, under the default `select=FALSE`, leaves
1973            // the per-level null space UNPENALIZED; carrying the double penalty
1974            // there shrinks the genuine deviation signal and over-smooths the
1975            // recovered curves relative to mgcv (gam#700). `re` carries its own
1976            // identity ridge below and ignores this flag. Honour an explicit
1977            // user `double_penalty=` either way.
1978            double_penalty: option_bool(options, "double_penalty")
1979                .unwrap_or(type_opt.as_str() != "sz"),
1980            identifiability: BSplineIdentifiability::None,
1981            boundary_conditions: Default::default(),
1982            boundary: OneDimensionalBoundary::Open,
1983        };
1984        let flavour = match type_opt.as_str() {
1985            "fs" => FactorSmoothFlavour::Fs {
1986                m_null_penalty_orders: vec![
1987                    option_usize(options, "m").unwrap_or(DEFAULT_PENALTY_ORDER),
1988                ],
1989            },
1990            "sz" => FactorSmoothFlavour::Sz,
1991            "re" => FactorSmoothFlavour::Re,
1992            // Outer `matches!` already restricts to fs/sz/re.
1993            other => {
1994                return Err(format!(
1995                    "internal: factor-smooth flavour dispatch reached unexpected type `{}`",
1996                    other
1997                ));
1998            }
1999        };
2000        return Ok(SmoothBasisSpec::FactorSmooth {
2001            spec: FactorSmoothSpec {
2002                continuous_cols: vec![c],
2003                group_col: cols[group_idx],
2004                marginal,
2005                flavour,
2006                group_frozen_levels: None,
2007                frozen_global_orthogonality: None,
2008            },
2009        });
2010    }
2011
2012    match type_opt.as_str() {
2013        "cyclic" | "cc" | "cp" | "cyclic-ps" => {
2014            validate_known_options(
2015                "cyclic",
2016                options,
2017                &[
2018                    "type",
2019                    "bs",
2020                    "by",
2021                    "k",
2022                    "basis_dim",
2023                    "basis-dim",
2024                    "basisdim",
2025                    "degree",
2026                    "penalty_order",
2027                    "period",
2028                    "periods",
2029                    "period_start",
2030                    "period_end",
2031                    "start",
2032                    "end",
2033                    "origin",
2034                    "origins",
2035                    "period_origin",
2036                    "period-origin",
2037                    "domain_origin",
2038                    "double_penalty",
2039                    "id",
2040                    "__by_col",
2041                    "identifiability",
2042                ],
2043            )?;
2044            if cols.len() != 1 {
2045                return Err(format!(
2046                    "periodic smooth expects one variable, got {}",
2047                    cols.len()
2048                ));
2049            }
2050            let c = cols[0];
2051            let (minv, maxv) = col_minmax(ds.values.column(c))?;
2052            let degree = option_usize(options, "degree").unwrap_or(DEFAULT_BSPLINE_DEGREE);
2053            let mut default_internal = heuristic_knots_for_column(ds.values.column(c));
2054            if ds.values.nrows() <= 32 && smooth_coordinate_count >= 5 {
2055                default_internal = default_internal.min(1);
2056            }
2057            // A periodic cubic spline has no free endpoint behaviour to spend
2058            // degrees of freedom on: the wrap constraint removes the ordinary
2059            // boundary wiggle, and the cyclic second-difference penalty leaves
2060            // only the constant direction (handled by the smooth
2061            // identifiability constraint).  An over-rich default would give
2062            // small binomial/continuation-ratio fits a large penalized nuisance
2063            // space whose REML/LAML optimum is driven by finite-sample Bernoulli
2064            // noise rather than the low-frequency periodic signal.  Cap the
2065            // cyclic default in the mgcv `bs="cc"` spirit: a modest basis unless
2066            // the caller explicitly requests `k=...`; high-frequency periodic
2067            // structure remains available through that explicit contract.  Since
2068            // gam#1680 lowered the open-spline univariate default to ≈12
2069            // functions this cap and the open-spline default coincide, so it now
2070            // acts as an explicit floor/guard that keeps the cyclic default lean
2071            // even if the open-spline heuristic is later widened.
2072            let cyclic_default_basis_cap = CYCLIC_DEFAULT_BASIS_DIM.max(degree + 1);
2073            let default_basis = (default_internal + degree + 1).min(cyclic_default_basis_cap);
2074            let num_basis = option_usize_any(options, &["k", "basis_dim", "basis-dim", "basisdim"])
2075                .unwrap_or(default_basis);
2076            if num_basis < degree + 1 {
2077                return Err(format!(
2078                    "periodic smooth: k={} too small for degree {}; expected k >= {}",
2079                    num_basis,
2080                    degree,
2081                    degree + 1
2082                ));
2083            }
2084            // The cyclic arm is periodic on its single axis by construction, so
2085            // resolve the period exactly the way the `s()`/`ps` arm does: honour
2086            // `period=`/`periods=` first (with `origin=` setting the domain
2087            // start), and fall back to the `period_start`/`period_end` endpoint
2088            // form only when `period=` is absent. Previously this arm jumped
2089            // straight to `parse_periodic_domain_1d`, so a `period=<v>`
2090            // declaration was silently dropped and the smooth wrapped at the
2091            // data range (#816). All three helpers route through
2092            // `parse_numeric_expr`, so `period=2*pi` and `period_end=2*pi` parse
2093            // identically (#815).
2094            let periodic_axes = [true];
2095            let periods = parse_periods(options, &periodic_axes)?;
2096            let origins = parse_period_origins(options, &periodic_axes)?;
2097            let (domain_start, period) = if let Some(p) = periods[0] {
2098                (origins[0].unwrap_or(minv), p)
2099            } else {
2100                parse_periodic_domain_1d(options, minv, maxv)?
2101            };
2102            Ok(SmoothBasisSpec::BSpline1D {
2103                feature_col: c,
2104                spec: BSplineBasisSpec {
2105                    degree,
2106                    penalty_order: option_usize(options, "penalty_order")
2107                        .unwrap_or(DEFAULT_PENALTY_ORDER),
2108                    knotspec: BSplineKnotSpec::PeriodicUniform {
2109                        data_range: (domain_start, domain_start + period),
2110                        num_basis,
2111                    },
2112                    double_penalty: smooth_double_penalty,
2113                    identifiability: BSplineIdentifiability::default(),
2114                    boundary_conditions: Default::default(),
2115                    boundary: OneDimensionalBoundary::Cyclic {
2116                        start: domain_start,
2117                        end: domain_start + period,
2118                    },
2119                },
2120            })
2121        }
2122        "bspline" | "ps" | "p-spline" | "cr" | "cs" => {
2123            // mgcv's `bs="cr"` (cubic regression spline) and `bs="cs"` (its
2124            // shrinkage twin) are penalized cubic-regression smooths that span
2125            // the same per-axis function space as gamfit's `bspline` (cubic
2126            // B-spline, second-derivative penalty). Route both through the
2127            // 1-D B-spline arm; the only semantic difference is whether the
2128            // null space is shrunk: `cr` is the no-shrinkage form (mgcv's
2129            // default) and `cs` is the shrinkage form (mgcv's `cs`/gamfit's
2130            // double_penalty). Without this route, a stand-alone
2131            // `s(x, bs='cr')` (which is otherwise a routine 1-D smooth in
2132            // mgcv-compatible formulae) reached the dispatch's default arm
2133            // and aborted the whole fit with `unsupported smooth type 'cr'`,
2134            // even though the same name was already recognized as a tensor
2135            // margin (`tensor_margin_bs_is_supported`).
2136            let validation_name = match type_opt.as_str() {
2137                "cr" => "cr",
2138                "cs" => "cs",
2139                _ => "bspline",
2140            };
2141            validate_known_options(
2142                validation_name,
2143                options,
2144                &[
2145                    "type",
2146                    "bs",
2147                    "by",
2148                    "k",
2149                    "basis_dim",
2150                    "basis-dim",
2151                    "basisdim",
2152                    "knots",
2153                    "knot_placement",
2154                    "knot-placement",
2155                    "knotplacement",
2156                    "degree",
2157                    "penalty_order",
2158                    "boundary",
2159                    "bc",
2160                    "boundary_conditions",
2161                    "bc_left",
2162                    "bc_right",
2163                    "left_bc",
2164                    "right_bc",
2165                    "start_bc",
2166                    "end_bc",
2167                    "side",
2168                    "anchor",
2169                    "anchor_value",
2170                    "value",
2171                    "anchor_left",
2172                    "left_anchor",
2173                    "anchor_right",
2174                    "right_anchor",
2175                    "periodic",
2176                    "period",
2177                    "periods",
2178                    "period_start",
2179                    "period_end",
2180                    "origin",
2181                    "double_penalty",
2182                    "by",
2183                    "id",
2184                    "__by_col",
2185                    "identifiability",
2186                    "by",
2187                ],
2188            )?;
2189            if cols.len() != 1 {
2190                return Err(TermBuilderError::incompatible_config(format!(
2191                    "bspline smooth expects one variable, got {}",
2192                    cols.len()
2193                ))
2194                .to_string());
2195            }
2196            let c = cols[0];
2197            let (minv, maxv) = col_minmax(ds.values.column(c))?;
2198            let degree = option_usize(options, "degree").unwrap_or(DEFAULT_BSPLINE_DEGREE);
2199            let default_internal = heuristic_knots_for_column(ds.values.column(c));
2200            let (mut n_knots, inferred, effective_degree) =
2201                parse_ps_internal_knots(options, degree, default_internal)?;
2202            let periodic_axes = parse_periodic_axes(options, 1).map_err(|e| e.to_string())?;
2203            // Periodic margins still need enough basis functions to wrap, so
2204            // surface the per-axis degree reduction as a config error when the
2205            // user explicitly asked for a periodic-but-too-small basis. The
2206            // non-periodic path silently degrades degree to match mgcv.
2207            if periodic_axes[0] && effective_degree != degree {
2208                return Err(TermBuilderError::invalid_option(format!(
2209                    "periodic smooth: k={} too small for degree {}; expected k >= {}",
2210                    effective_degree + 1,
2211                    degree,
2212                    degree + 1
2213                ))
2214                .to_string());
2215            }
2216            if inferred && ds.values.nrows() <= 32 && smooth_coordinate_count >= 5 {
2217                n_knots = n_knots.min(1);
2218            }
2219            if inferred {
2220                let unique = unique_count_column(ds.values.column(c));
2221                let ceiling = ((unique as f64).cbrt() as usize).max(20);
2222                inference_notes.push(format!(
2223                    "Automatically set {} internal knots for smooth '{}' from {} unique values (rule: clamp(unique/4, 4..max(20, cbrt(unique))) = clamp(unique/4, 4..{})). Override with knots=... or k=....",
2224                    n_knots,
2225                    vars.join(","),
2226                    unique,
2227                    ceiling,
2228                ));
2229            }
2230            let boundary_conditions =
2231                if periodic_axes[0] && bspline_boundary_declares_periodic_axis(options) {
2232                    BSplineBoundaryConditions::default()
2233                } else {
2234                    parse_bspline_boundary_conditions(options).map_err(|e| e.to_string())?
2235                };
2236            let periods = parse_periods(options, &periodic_axes).map_err(|e| e.to_string())?;
2237            let origins =
2238                parse_period_origins(options, &periodic_axes).map_err(|e| e.to_string())?;
2239            let (knotspec, boundary) = if periodic_axes[0] {
2240                if !boundary_conditions.is_free() {
2241                    return Err(TermBuilderError::incompatible_config(
2242                        "periodic B-splines cannot also declare endpoint boundary conditions",
2243                    )
2244                    .to_string());
2245                }
2246                {
2247                    let (domain_start, p_value) = if periods[0].is_some() {
2248                        (origins[0].unwrap_or(minv), periods[0].unwrap())
2249                    } else {
2250                        parse_periodic_domain_1d(options, minv, maxv).map_err(|e| e.to_string())?
2251                    };
2252                    let domain_end = domain_start + p_value;
2253                    (
2254                        BSplineKnotSpec::PeriodicUniform {
2255                            data_range: (domain_start, domain_end),
2256                            num_basis: n_knots + effective_degree + 1,
2257                        },
2258                        OneDimensionalBoundary::Cyclic {
2259                            start: domain_start,
2260                            end: domain_end,
2261                        },
2262                    )
2263                }
2264            } else if type_opt == "cr" || type_opt == "cs" {
2265                // mgcv `bs="cr"`/`"cs"`: a natural cubic regression spline whose
2266                // basis is indexed by `k` values at quantile-placed knots (#1074),
2267                // NOT a B-spline knot vector. Match gam's `k=` convention by
2268                // requesting the same total basis size the B-spline arm would
2269                // produce (`n_knots` internal + degree + 1), floored at the cr
2270                // minimum of 3 knots. `cr` vs `cs` (shrinkage) is carried by the
2271                // `double_penalty` flag resolved below, which the cr builder reads.
2272                //
2273                // Cap that request to the covariate's data support (#1541): a cr
2274                // basis cannot place more value-knots than there are distinct
2275                // covariate values, so an unclamped `k` on a low-cardinality
2276                // predictor (binary indicator, 3-level ordinal, small count) used
2277                // to hard-fail in `select_cr_knots` instead of reducing like mgcv
2278                // and gam's tensor path. Below the cr minimum (a binary covariate)
2279                // degrade to the B-spline marginal the default `s(x, k=..)` basis
2280                // already fits on the same data — never a hard error.
2281                let k_cr = (n_knots + effective_degree + 1).max(CR_MIN_KNOTS);
2282                let knotspec = match capped_cr_marginal_knotspec(
2283                    ds.values.column(c),
2284                    k_cr,
2285                    &vars.join(","),
2286                    inference_notes,
2287                )? {
2288                    Some(cr_knotspec) => cr_knotspec,
2289                    None => resolve_nonperiodic_bspline_knotspec(
2290                        options,
2291                        ds.values.column(c),
2292                        (minv, maxv),
2293                        effective_degree,
2294                        n_knots,
2295                    )?,
2296                };
2297                (knotspec, parse_cyclic_boundary(options, minv, maxv)?)
2298            } else {
2299                (
2300                    resolve_nonperiodic_bspline_knotspec(
2301                        options,
2302                        ds.values.column(c),
2303                        (minv, maxv),
2304                        effective_degree,
2305                        n_knots,
2306                    )?,
2307                    parse_cyclic_boundary(options, minv, maxv)?,
2308                )
2309            };
2310            // mgcv `bs="cr"` does not shrink the linear null space; only `cs`
2311            // (and the gamfit-flavoured `bspline`/`ps`) do. Honour an explicit
2312            // `double_penalty=` either way.
2313            let double_penalty = if type_opt == "cr" {
2314                option_bool(options, "double_penalty").unwrap_or(false)
2315            } else {
2316                smooth_double_penalty
2317            };
2318            // Clamp the marginal difference penalty to `<= effective_degree`
2319            // so it stays well-defined when the per-axis degree was reduced
2320            // (mirrors the tensor margin path: `create_difference_penalty_matrix`
2321            // requires order < num_basis_functions).
2322            let penalty_order = option_usize(options, "penalty_order")
2323                .unwrap_or(DEFAULT_PENALTY_ORDER)
2324                .min(effective_degree);
2325            Ok(SmoothBasisSpec::BSpline1D {
2326                feature_col: c,
2327                spec: BSplineBasisSpec {
2328                    degree: effective_degree,
2329                    penalty_order,
2330                    knotspec,
2331                    double_penalty,
2332                    identifiability: BSplineIdentifiability::default(),
2333                    boundary,
2334                    boundary_conditions,
2335                },
2336            })
2337        }
2338        "tps" | "thinplate" | "thin-plate" => {
2339            validate_known_options(
2340                "thinplate",
2341                options,
2342                &[
2343                    SECONDARY_CENTER_CAP_OPTION,
2344                    "type",
2345                    "bs",
2346                    "by",
2347                    "length_scale",
2348                    "centers",
2349                    "k",
2350                    "basis_dim",
2351                    "basis-dim",
2352                    "basisdim",
2353                    "knots",
2354                    "include_intercept",
2355                    "double_penalty",
2356                    "by",
2357                    "id",
2358                    "__by_col",
2359                    "identifiability",
2360                    "by",
2361                    "periodic",
2362                    "cyclic",
2363                    "period",
2364                    "period_start",
2365                    "period_end",
2366                    "scale_dims",
2367                ],
2368            )?;
2369            let plan = plan_spatial_basis(
2370                ds.values.nrows(),
2371                cols.len(),
2372                CenterCountRequest::Default,
2373                DuchonNullspaceOrder::Linear,
2374                option_bool(options, "scale_dims").unwrap_or(false),
2375                policy,
2376            )
2377            .map_err(|e| e.to_string())?;
2378            // #1074: the mgcv-sized basis cap (`k = 10·3^(d-1)`) that used to live
2379            // here was DELETED. It masked the real defect — the n-scaling default
2380            // over-sizes a thin-plate field, producing a weakly-identified
2381            // two-penalty ρ-surface the outer optimizer stalls on (row-order
2382            // dependent, #1378), and surplus columns REML can't penalize away on
2383            // weak-signal fits. Capping the basis hid that stall instead of fixing
2384            // it. The default now uses the generic spatial center heuristic; the
2385            // root fix (a well-identified ρ-surface / optimizer that doesn't stall)
2386            // is tracked separately. Explicit `k`/`centers` still take full effect.
2387            let default_centers = plan.centers;
2388            let centers = parse_countwith_basis_alias(
2389                options,
2390                "centers",
2391                cap_default_spatial_centers(options, default_centers),
2392            )?;
2393            let center_strategy = if has_explicit_countwith_basis_alias(options, "centers") {
2394                spatial_center_strategy_for_dimension(centers, cols.len())
2395            } else {
2396                auto_spatial_center_strategy(centers, cols.len())
2397            };
2398            Ok(SmoothBasisSpec::ThinPlate {
2399                feature_cols: cols.to_vec(),
2400                spec: ThinPlateBasisSpec {
2401                    center_strategy,
2402                    periodic: parse_periodic_axes_option(options, cols.len())?,
2403                    // Sentinel: leave at 0.0 when the user didn't pass an
2404                    // explicit length_scale so `auto_init_length_scale_in_place`
2405                    // can replace it with a data-derived initialization. The
2406                    // old hard-coded 1.0 was the documented basin (see
2407                    // smooth.rs `auto_init_length_scale_in_place`) that the
2408                    // spatial optimizer could not escape, leaving TPS terms
2409                    // initialized off the data scale.
2410                    length_scale: option_f64(options, "length_scale").unwrap_or(0.0),
2411                    double_penalty: smooth_double_penalty,
2412                    identifiability: parse_spatial_identifiability(options)
2413                        .map_err(|e| e.to_string())?,
2414                    radial_reparam: None,
2415                },
2416                input_scales: None,
2417            })
2418        }
2419        "sphere" | "s2" | "sos" => {
2420            validate_known_options(
2421                "sphere",
2422                options,
2423                &[
2424                    "type",
2425                    "bs",
2426                    "by",
2427                    "centers",
2428                    "k",
2429                    "basis_dim",
2430                    "basis-dim",
2431                    "basisdim",
2432                    "knots",
2433                    "penalty_order",
2434                    "m",
2435                    "double_penalty",
2436                    "id",
2437                    "__by_col",
2438                    "kernel",
2439                    "method",
2440                    "radians",
2441                    "units",
2442                    "degree",
2443                    "l",
2444                    "max_degree",
2445                    "max-degree",
2446                ],
2447            )?;
2448            if cols.len() != 2 {
2449                return Err(format!(
2450                    "sphere smooth expects exactly two variables (lat, lon), got {}",
2451                    cols.len()
2452                ));
2453            }
2454            let radians = option_bool(options, "radians").unwrap_or_else(|| {
2455                options
2456                    .get("units")
2457                    .map(|u| u.eq_ignore_ascii_case("radian") || u.eq_ignore_ascii_case("radians"))
2458                    .unwrap_or(false)
2459            });
2460            // An explicit `degree`/`l`/`max_degree` names a spherical-harmonic
2461            // truncation, so with no explicit kernel/method it selects the
2462            // Harmonic construction (the Wahba kernel ignores `degree` and would
2463            // silently emit a 1-column kernel design). An explicit kernel/method
2464            // still wins.
2465            let degree_requested = options.contains_key("degree")
2466                || options.contains_key("l")
2467                || options.contains_key("max_degree")
2468                || options.contains_key("max-degree");
2469            let kernel = options
2470                .get("kernel")
2471                .or_else(|| options.get("method"))
2472                .map(|raw| strip_quotes(raw).trim().to_ascii_lowercase())
2473                .unwrap_or_else(|| {
2474                    if degree_requested {
2475                        "harmonic".to_string()
2476                    } else {
2477                        "sobolev".to_string()
2478                    }
2479                });
2480            let (method, wahba_kernel) = match kernel.as_str() {
2481                "sobolev" | "wahba" | "wahba_sobolev" | "wahba-sobolev" => {
2482                    (SphereMethod::Wahba, SphereWahbaKernel::Sobolev)
2483                }
2484                "pseudo" | "mgcv" | "sos" | "wahba_pseudo" | "wahba-pseudo" => {
2485                    (SphereMethod::Wahba, SphereWahbaKernel::Pseudo)
2486                }
2487                "harmonic" | "spherical_harmonic" | "spherical-harmonic" => {
2488                    (SphereMethod::Harmonic, SphereWahbaKernel::Sobolev)
2489                }
2490                other => {
2491                    return Err(format!(
2492                        "unsupported sphere kernel '{other}'; expected sobolev, pseudo, or harmonic"
2493                    ));
2494                }
2495            };
2496            let max_degree = if matches!(method, SphereMethod::Harmonic) {
2497                let degree =
2498                    option_usize_any(options, &["degree", "l", "max_degree", "max-degree"])
2499                        .or_else(|| option_usize(options, "centers"))
2500                        .or_else(|| {
2501                            option_usize_any(options, &["k", "basis_dim", "basis-dim", "basisdim"])
2502                                .and_then(|k| (1..=128).find(|&l| l * (l + 2) >= k))
2503                        })
2504                        .unwrap_or_else(|| default_spherical_harmonic_degree(ds.values.nrows()));
2505                if degree == 0 {
2506                    return Err("sphere smooth requires degree/max_degree >= 1".to_string());
2507                }
2508                if degree > 32 {
2509                    return Err(format!(
2510                        "sphere smooth max_degree={} is too large for the dense harmonic engine (limit 32)",
2511                        degree
2512                    ));
2513                }
2514                Some(degree)
2515            } else {
2516                None
2517            };
2518            let penalty_order = option_usize(options, "penalty_order")
2519                .or_else(|| option_usize(options, "m"))
2520                .unwrap_or(DEFAULT_PENALTY_ORDER);
2521            let center_strategy = if matches!(method, SphereMethod::Wahba) {
2522                let mut centers = parse_countwith_basis_alias(
2523                    options,
2524                    "centers",
2525                    default_num_centers(ds.values.nrows(), cols.len()),
2526                )?;
2527                if penalty_order >= 4 {
2528                    centers = centers.max(30);
2529                }
2530                CenterStrategy::FarthestPoint {
2531                    num_centers: centers,
2532                }
2533            } else {
2534                CenterStrategy::FarthestPoint { num_centers: 0 }
2535            };
2536            Ok(SmoothBasisSpec::Sphere {
2537                feature_cols: cols.to_vec(),
2538                spec: SphericalSplineBasisSpec {
2539                    center_strategy,
2540                    penalty_order,
2541                    double_penalty: smooth_double_penalty,
2542                    radians,
2543                    method,
2544                    max_degree,
2545                    wahba_kernel,
2546                    identifiability: SphericalSplineIdentifiability::CenterSumToZero,
2547                },
2548            })
2549        }
2550        "curvature" => {
2551            // Constant-curvature (M_κ) geodesic-kernel smooth (#944): the
2552            // κ-generic sibling of the intrinsic S² smooth above. The feature
2553            // columns are κ-stereographic chart coordinates; `kappa=` is the
2554            // fixed sectional curvature (default 0 = flat), and the geometry
2555            // comes from `geometry::constant_curvature::ConstantCurvature`.
2556            validate_known_options(
2557                "curvature",
2558                options,
2559                &[
2560                    "type",
2561                    "bs",
2562                    "by",
2563                    "centers",
2564                    "k",
2565                    "basis_dim",
2566                    "basis-dim",
2567                    "basisdim",
2568                    "knots",
2569                    "kappa",
2570                    "length_scale",
2571                    "double_penalty",
2572                    "id",
2573                    "__by_col",
2574                ],
2575            )?;
2576            let kappa = option_f64(options, "kappa").unwrap_or(0.0);
2577            if !kappa.is_finite() {
2578                return Err("curvature smooth requires a finite kappa".to_string());
2579            }
2580            let length_scale = option_f64(options, "length_scale").unwrap_or(0.0);
2581            if !length_scale.is_finite() || length_scale < 0.0 {
2582                return Err(format!(
2583                    "curvature smooth length_scale must be positive (or omitted for auto); got {length_scale}"
2584                ));
2585            }
2586            let centers = parse_countwith_basis_alias(
2587                options,
2588                "centers",
2589                default_num_centers(ds.values.nrows(), cols.len()),
2590            )?;
2591            if centers < 2 {
2592                return Err("curvature smooth requires at least 2 centers".to_string());
2593            }
2594            Ok(SmoothBasisSpec::ConstantCurvature {
2595                feature_cols: cols.to_vec(),
2596                spec: ConstantCurvatureBasisSpec {
2597                    center_strategy: CenterStrategy::FarthestPoint {
2598                        num_centers: centers,
2599                    },
2600                    kappa,
2601                    // 0.0 sentinel = κ-independent auto initialization in the
2602                    // basis builder (median chart center spacing, doubled).
2603                    length_scale,
2604                    // Curvature smooth defaults to NO double-penalty ridge
2605                    // (#1464): the curvature-blind ridge `I` absorbs the data fit
2606                    // independently of κ and rails the fitted curvature to the
2607                    // +chart bound (hyperbolic truth recovered as spherical). The
2608                    // RKHS Gram penalty is already full-rank PD, so the ridge adds
2609                    // no stability. Honour an EXPLICIT `double_penalty=` only.
2610                    double_penalty: option_bool(options, "double_penalty").unwrap_or(false),
2611                    identifiability: ConstantCurvatureIdentifiability::CenterSumToZero,
2612                },
2613            })
2614        }
2615        "measurejet" => {
2616            // Measure-jet spline: multiscale local-jet-residual energy of the
2617            // empirical measure. The feature columns are ambient coordinates
2618            // of data concentrated near an unknown low-dimensional set; the
2619            // geometry (centers, masses, scale band) is read off the measure
2620            // at build time — magic by default, every option optional.
2621            validate_known_options(
2622                "measurejet",
2623                options,
2624                &[
2625                    "type",
2626                    "bs",
2627                    "by",
2628                    "centers",
2629                    "k",
2630                    "basis_dim",
2631                    "basis-dim",
2632                    "basisdim",
2633                    "knots",
2634                    "s",
2635                    "alpha",
2636                    "tau",
2637                    "scales",
2638                    "length_scale",
2639                    "double_penalty",
2640                    "multiscale",
2641                    "learn_length_scale",
2642                    "id",
2643                    "__by_col",
2644                ],
2645            )?;
2646            let order_s = option_f64(options, "s").unwrap_or(0.0);
2647            // 0.0 = auto sentinel; explicit values must sit inside the
2648            // admissible order interval of the affine-jet (r = 2) energy.
2649            if !(order_s.is_finite() && (order_s == 0.0 || (order_s > 0.0 && order_s < 2.0))) {
2650                return Err(format!(
2651                    "measurejet smooth s must lie in (0, 2) (or be omitted for auto); got {order_s}"
2652                ));
2653            }
2654            // Default to the spec Default (α = 1, density-WEIGHTED Hessian
2655            // energy — the module-header default). The density-free α = 3/2
2656            // (q^{−2}) over-smooths low-intrinsic-dimension manifolds where the
2657            // local mass q is tiny and varies along the stratum (#1116:
2658            // 13×-worse-than-matérn on a 1-D curve in 3-D); α = 1's q^{−1} is
2659            // gentler and robust across intrinsic dimensions. An explicit
2660            // `alpha=` still overrides for full-dimensional density-free use.
2661            let alpha =
2662                option_f64(options, "alpha").unwrap_or(MeasureJetBasisSpec::default().alpha);
2663            if !alpha.is_finite() {
2664                return Err("measurejet smooth requires a finite alpha".to_string());
2665            }
2666            let tau0 = option_f64(options, "tau").unwrap_or(1e-3);
2667            if !(tau0.is_finite() && tau0 >= 0.0) {
2668                return Err(format!(
2669                    "measurejet smooth tau must be finite and nonnegative; got {tau0}"
2670                ));
2671            }
2672            let num_scales = option_usize(options, "scales").unwrap_or(0);
2673            let length_scale = option_f64(options, "length_scale").unwrap_or(0.0);
2674            if !length_scale.is_finite() || length_scale < 0.0 {
2675                return Err(format!(
2676                    "measurejet smooth length_scale must be positive (or omitted for auto); got {length_scale}"
2677                ));
2678            }
2679            let centers = parse_countwith_basis_alias(
2680                options,
2681                "centers",
2682                default_num_centers(ds.values.nrows(), cols.len()),
2683            )?;
2684            if centers < 3 {
2685                return Err("measurejet smooth requires at least 3 centers".to_string());
2686            }
2687            // Multiscale (per-scale spectral split + (α, lnτ) ψ dials + the
2688            // affine-preserving ridge) is an explicit opt-in (#1116): default
2689            // single-scale at any center count, the Duchon/Matérn footprint.
2690            let multiscale = option_bool(options, "multiscale").unwrap_or(false);
2691            // REML-learning the representer range ℓ is an explicit opt-in.
2692            // The stable default freezes ℓ at the auto/user value; the
2693            // design-moving coordinate is expensive and can overfit low-signal
2694            // surfaces when enabled implicitly.
2695            let learn_length_scale = option_bool(options, "learn_length_scale").unwrap_or(false);
2696            Ok(SmoothBasisSpec::MeasureJet {
2697                feature_cols: cols.to_vec(),
2698                spec: MeasureJetBasisSpec {
2699                    center_strategy: CenterStrategy::FarthestPoint {
2700                        num_centers: centers,
2701                    },
2702                    order_s,
2703                    alpha,
2704                    tau0,
2705                    num_scales,
2706                    // 0.0 sentinel = auto initialization in the basis builder
2707                    // (median nearest-center spacing).
2708                    length_scale,
2709                    double_penalty: smooth_double_penalty,
2710                    learn_length_scale,
2711                    multiscale,
2712                    identifiability: MeasureJetIdentifiability::CenterSumToZero,
2713                    frozen_quadrature: None,
2714                },
2715                input_scales: None,
2716            })
2717        }
2718        "matern" => {
2719            // Catch typos like `lengt_scale=` / `nyu=` / `centerz=` before
2720            // they get silently ignored and the user wonders why their
2721            // option had no effect. The matern() term accepts exactly
2722            // these options.
2723            validate_known_options(
2724                "matern",
2725                options,
2726                &[
2727                    SECONDARY_CENTER_CAP_OPTION,
2728                    "type",
2729                    "bs",
2730                    "by",
2731                    "nu",
2732                    "length_scale",
2733                    "centers",
2734                    "k",
2735                    "basis_dim",
2736                    "basis-dim",
2737                    "basisdim",
2738                    "knots",
2739                    "include_intercept",
2740                    "double_penalty",
2741                    "by",
2742                    "id",
2743                    "__by_col",
2744                    "identifiability",
2745                    "by",
2746                    "periodic",
2747                    "cyclic",
2748                    "period",
2749                    "period_start",
2750                    "period_end",
2751                    "scale_dims",
2752                ],
2753            )?;
2754            let plan = plan_spatial_basis(
2755                ds.values.nrows(),
2756                cols.len(),
2757                CenterCountRequest::Default,
2758                DuchonNullspaceOrder::Zero,
2759                option_bool(options, "scale_dims").unwrap_or(false),
2760                policy,
2761            )
2762            .map_err(|e| e.to_string())?;
2763            let centers = parse_countwith_basis_alias(
2764                options,
2765                "centers",
2766                cap_default_spatial_centers(
2767                    options,
2768                    default_matern_center_count(ds.values.nrows(), cols.len(), plan.centers),
2769                ),
2770            )?;
2771            let center_strategy = if has_explicit_countwith_basis_alias(options, "centers") {
2772                spatial_center_strategy_for_dimension(centers, cols.len())
2773            } else {
2774                auto_spatial_center_strategy(centers, cols.len())
2775            };
2776            let nu = parse_matern_nu(options.get("nu").map(String::as_str).unwrap_or("5/2"))?;
2777            // The exponential (ν = 1/2) Matérn kernel has a singular Laplacian
2778            // at zero in d ≥ 2, so the operator-collocation penalty machinery
2779            // hits a non-invertible matrix during fit. Surface the cause
2780            // up-front instead of letting the user see the generic
2781            // "Matrix conditioning issue detected" wrapper from PIRLS.
2782            if matches!(nu, MaternNu::Half) && cols.len() >= 2 {
2783                return Err(TermBuilderError::unsupported_feature(format!(
2784                    "matern() with nu=1/2 is not supported for d>=2 (got {} covariates): \
2785                     the exponential kernel's Laplacian is singular at center collisions, \
2786                     which makes the operator-collocation penalty non-invertible. \
2787                     Choose nu>=3/2 (e.g. nu=3/2 or the default nu=5/2) for multi-dimensional smooths.",
2788                    cols.len()
2789                ))
2790                .to_string());
2791            }
2792            let aniso_log_scales = if option_bool(options, "scale_dims").unwrap_or(false) {
2793                Some(vec![0.0; cols.len()])
2794            } else {
2795                None
2796            };
2797            Ok(SmoothBasisSpec::Matern {
2798                feature_cols: cols.to_vec(),
2799                spec: MaternBasisSpec {
2800                    center_strategy,
2801                    periodic: parse_periodic_axes_option(options, cols.len())?,
2802                    // Sentinel: leave at 0.0 when the user didn't pass an
2803                    // explicit length_scale so the planner's
2804                    // `auto_init_length_scale_in_place` can replace it with the
2805                    // SAME data-derived wiggly-side initialization the thin-plate
2806                    // path uses (`max_range / sqrt(n)`), then let the κ-optimizer
2807                    // refine from there.
2808                    //
2809                    // gam#1629: the previous `default_matern_length_scale` seeded
2810                    // the FULL data diameter — the maximally over-smoothed corner.
2811                    // Because that value is non-zero, the `0.0`-gated auto-init was
2812                    // a no-op for Matérn, so the κ-optimizer started in the flat
2813                    // over-smoothed basin and parked there, leaving high-frequency
2814                    // 2-D surfaces unresolved (truth-RMSE ~6× worse than
2815                    // thin-plate/tensor on identical data, and insensitive to `k`).
2816                    // Routing Matérn through the same `0.0` sentinel as thin-plate
2817                    // (see the ThinPlate branch above) starts REML in the resolving
2818                    // regime it can actually escape from.
2819                    length_scale: option_f64(options, "length_scale").unwrap_or(0.0),
2820                    nu,
2821                    include_intercept: option_bool(options, "include_intercept").unwrap_or(false),
2822                    double_penalty: smooth_double_penalty,
2823                    identifiability: parse_matern_identifiability(options)
2824                        .map_err(|e| e.to_string())?,
2825                    aniso_log_scales,
2826                    // Cold build: let the bootstrap-κ spectral test decide whether
2827                    // the double-penalty nullspace shrinkage survives; the freeze
2828                    // step then pins that decision into the FrozenTransform so the
2829                    // κ-optimizer's rebuilds keep the count invariant (gam#787/#860).
2830                    nullspace_shrinkage_survived: None,
2831                },
2832                input_scales: None,
2833            })
2834        }
2835        "duchon" => {
2836            validate_known_options(
2837                "duchon",
2838                options,
2839                &[
2840                    SECONDARY_CENTER_CAP_OPTION,
2841                    "type",
2842                    "bs",
2843                    "by",
2844                    "length_scale",
2845                    "centers",
2846                    "k",
2847                    "basis_dim",
2848                    "basis-dim",
2849                    "basisdim",
2850                    "knots",
2851                    "power",
2852                    "p",
2853                    "nullspace_order",
2854                    "order",
2855                    "identifiability",
2856                    "by",
2857                    "periodic",
2858                    "cyclic",
2859                    "period",
2860                    "period_start",
2861                    "period_end",
2862                    "scale_dims",
2863                    "double_penalty",
2864                    "by",
2865                    "id",
2866                    "__by_col",
2867                ],
2868            )?;
2869            if options.contains_key("double_penalty") {
2870                return Err(TermBuilderError::incompatible_config(format!(
2871                    "Duchon smooth '{}' does not support double_penalty; the Duchon smoother already ships its native reproducing-norm penalty plus a null-space shrinkage ridge.",
2872                    vars.join(", ")
2873                ))
2874                .to_string());
2875            }
2876            let requested_nullspace_order = parse_duchon_order(options)?;
2877            let length_scale = option_f64_strict(options, "length_scale")?;
2878            // Resolve `(nullspace_order, power)`. The default (magic) path is a
2879            // structural amplitude/slope/curvature smoother: an affine (`Linear`)
2880            // polynomial nullspace and spectral power `s = (d - 1)/2`, giving the
2881            // cubic kernel `r^3` in 1D. There is no nullspace-order escalation —
2882            // the structural cubic smoother is well-defined for every dimension.
2883            //
2884            // Explicit `power=...` honors the user's value verbatim against their
2885            // requested nullspace order; the kernel validator emits a precise
2886            // diagnostic for any inadmissible combination. In the scale-free
2887            // (non-hybrid) regime fractional powers are admitted and threaded as
2888            // `f64`. The hybrid Duchon-Matérn kernel (`length_scale=Some`) is
2889            // restricted to integer powers.
2890            let (nullspace_order, power) = match parse_duchon_power_policy(options)? {
2891                DuchonPowerPolicy::Explicit(req_power) => {
2892                    if length_scale.is_some() && req_power.fract() != 0.0 {
2893                        return Err(TermBuilderError::incompatible_config(format!(
2894                            "hybrid Duchon-Matern smooth '{}' (length_scale=...) requires an integer power, got power={}; \
2895                             drop length_scale to use the scale-free structural kernel with a fractional power.",
2896                            vars.join(", "),
2897                            req_power,
2898                        ))
2899                        .to_string());
2900                    }
2901                    (requested_nullspace_order, req_power)
2902                }
2903                DuchonPowerPolicy::CubicStructuralDefault => {
2904                    // Magic cubic rule (REQUEST-LAYER default): no explicit power ⇒
2905                    // affine null space + fractional spectral power s = (d-1)/2, i.e.
2906                    // the Duchon kernel φ(r)=r³ in every dimension. An EXPLICIT
2907                    // `power=0` is handled above and is honored as the s=0 Duchon
2908                    // kernel (r²·log r ≡ the thin-plate kernel in even d) — the magic
2909                    // default lives here, not in the basis builder.
2910                    match length_scale {
2911                        None => crate::basis::duchon_cubic_default(cols.len()),
2912                        Some(_) => {
2913                            // The hybrid Matérn-blended kernel (`length_scale=Some`)
2914                            // requires an INTEGER spectral power `s` (the partial-
2915                            // fraction split `1/(ρ^{2p}(κ²+ρ²)^s)` is only defined for
2916                            // integer `s`). The fractional cubic default `s=(d-1)/2` is
2917                            // a half-integer for even `d`, and the basis builder's
2918                            // `power_as_usize` maps a NON-integer to `0` (not its
2919                            // floor) — so for even `d ≥ 4` the realized kernel has
2920                            // `2(p+s) = 2p = 4 ≤ d`, which is non-finite at the origin
2921                            // and crashes the fit (historically a non-finite
2922                            // eigendecomposition; now a fit-time validation error).
2923                            //
2924                            // Rather than emit the fractional cubic and let it truncate
2925                            // into an inadmissible kernel, resolve the SMALLEST
2926                            // admissible integer `(nullspace, s)` at the requested
2927                            // nullspace order, honoring the collocation order of the
2928                            // default operator penalties (mass + tension ⇒ D1). This
2929                            // recovers the canonical thin-plate smoothness order
2930                            // `m = p + s = ⌊d/2⌋ + 1` for the hybrid kernel and agrees
2931                            // with the fractional cubic default for odd `d` (where the
2932                            // collocation floor already forces `s = (d-1)/2`).
2933                            let max_op = crate::basis::duchon_max_active_operator_derivative_order(
2934                                &DuchonOperatorPenaltySpec::default(),
2935                            );
2936                            let (ns, s) = crate::basis::resolve_duchon_orders(
2937                                cols.len(),
2938                                requested_nullspace_order,
2939                                max_op,
2940                                length_scale,
2941                            );
2942                            (ns, s as f64)
2943                        }
2944                    }
2945                }
2946            };
2947            let plan = plan_spatial_basis(
2948                ds.values.nrows(),
2949                cols.len(),
2950                CenterCountRequest::Default,
2951                nullspace_order,
2952                option_bool(options, "scale_dims").unwrap_or(false),
2953                policy,
2954            )
2955            .map_err(|e| e.to_string())?;
2956            let centers_explicit = has_explicit_countwith_basis_alias(options, "centers");
2957            let requested_centers = parse_countwith_basis_alias(
2958                options,
2959                "centers",
2960                cap_default_spatial_centers(options, plan.centers),
2961            )?;
2962            let polynomial_cols = match nullspace_order {
2963                DuchonNullspaceOrder::Zero => 1,
2964                DuchonNullspaceOrder::Linear => cols.len() + 1,
2965                DuchonNullspaceOrder::Degree(degree) => {
2966                    crate::basis::duchon_nullspace_dimension(cols.len(), degree)
2967                }
2968            };
2969            if requested_centers <= polynomial_cols {
2970                return Err(TermBuilderError::incompatible_config(format!(
2971                    "Duchon smooth '{}' requested basis dimension {} but order={:?} in {}D needs {} polynomial null-space columns; choose centers/k > {}",
2972                    vars.join(", "),
2973                    requested_centers,
2974                    nullspace_order,
2975                    cols.len(),
2976                    polynomial_cols,
2977                    polynomial_cols,
2978                ))
2979                .to_string());
2980            }
2981            let mut centers = requested_centers;
2982            if !centers_explicit && ds.values.nrows() <= 32 && smooth_coordinate_count >= 5 {
2983                centers = centers.max(polynomial_cols + 4);
2984            }
2985            let center_strategy = if centers_explicit {
2986                spatial_center_strategy_for_dimension(centers, cols.len())
2987            } else {
2988                auto_spatial_center_strategy(centers, cols.len())
2989            };
2990            let aniso_log_scales = if option_bool(options, "scale_dims").unwrap_or(false) {
2991                Some(vec![0.0; cols.len()])
2992            } else {
2993                None
2994            };
2995            // The default is the full Hilbert scale (curvature `Primary` + trend
2996            // ridge + mass + tension); REML deselects what the data don't support.
2997            let operator_penalties = DuchonOperatorPenaltySpec::default();
2998            // For a 1-D periodic Duchon with no EXPLICIT period, anchor the wrap
2999            // to the covariate DATA range rather than letting the basis builder
3000            // derive it from the (k-subsampled) center span. The center span is a
3001            // strict subset of the data and undershoots the true period, seaming
3002            // the curve (f(0) ≠ f(2π)); the data range is the caller's actual
3003            // domain. Honors any explicit `period=` (parse_periodic_axes_option
3004            // already threaded it) and leaves multi-D / non-periodic untouched.
3005            let mut periodic = parse_periodic_axes_option(options, cols.len())?;
3006            if cols.len() == 1
3007                && let Some(axes) = periodic.as_mut()
3008                && axes.len() == 1
3009                && axes[0].is_none()
3010            {
3011                let (minv, maxv) = col_minmax(ds.values.column(cols[0]))?;
3012                if maxv > minv {
3013                    axes[0] = Some(maxv - minv);
3014                }
3015            }
3016            Ok(SmoothBasisSpec::Duchon {
3017                feature_cols: cols.to_vec(),
3018                spec: DuchonBasisSpec {
3019                    center_strategy,
3020                    periodic,
3021                    length_scale,
3022                    power,
3023                    nullspace_order,
3024                    identifiability: parse_spatial_identifiability(options)
3025                        .map_err(|e| e.to_string())?,
3026                    aniso_log_scales,
3027                    operator_penalties,
3028                    boundary: if cols.len() == 1 {
3029                        let c = cols[0];
3030                        let (minv, maxv) = col_minmax(ds.values.column(c))?;
3031                        parse_cyclic_boundary(options, minv, maxv)?
3032                    } else {
3033                        OneDimensionalBoundary::Open
3034                    },
3035                    radial_reparam: None,
3036                },
3037                input_scales: None,
3038            })
3039        }
3040        "tensor" | "te" | "ti" | "t2" => {
3041            validate_known_options(
3042                "tensor",
3043                options,
3044                &[
3045                    "type",
3046                    "bs",
3047                    "by",
3048                    "k",
3049                    "basis_dim",
3050                    "basis-dim",
3051                    "basisdim",
3052                    "knot_placement",
3053                    "knot-placement",
3054                    "knotplacement",
3055                    "degree",
3056                    "penalty_order",
3057                    "double_penalty",
3058                    "periodic",
3059                    "cyclic",
3060                    "period",
3061                    "periods",
3062                    "period_start",
3063                    "period_end",
3064                    "origin",
3065                    "origins",
3066                    "period_origin",
3067                    "period-origin",
3068                    "domain_origin",
3069                    "boundary",
3070                    "bc",
3071                    "identifiability",
3072                    "id",
3073                    "__by_col",
3074                ],
3075            )?;
3076            if cols.len() < 2 {
3077                return Err(TermBuilderError::incompatible_config(format!(
3078                    "tensor smooth expects at least 2 variables, got {}",
3079                    cols.len()
3080                ))
3081                .to_string());
3082            }
3083            let dim = cols.len();
3084
3085            // Tensor-product contract (#1082). `te(x1, x2, ...)` ALWAYS builds a
3086            // genuine anisotropic tensor product of per-margin bases (the arm
3087            // below), exactly as mgcv's `te()` does — one smoothing parameter per
3088            // margin, a marginal-Kronecker-sum penalty, and the bilinear null
3089            // space left unpenalized under the default `select = FALSE`. A margin
3090            // vector `bs=c('tp','tp')` requests a thin-plate FUNCTION SPACE per
3091            // axis; the tensor realizes each axis as a 1-D penalized B-spline
3092            // margin spanning that same per-axis space (tp/ps/cr/bs/cc all share
3093            // it). We deliberately do NOT silently swap the requested tensor for a
3094            // single multi-D ISOTROPIC thin-plate radial smooth (`s(x,y,bs='tp')`):
3095            // that is a different model — one isotropic smoothing parameter, no
3096            // per-margin anisotropy — and substituting it while the user wrote a
3097            // tensor formula is dishonest. A user who genuinely wants the isotropic
3098            // radial smooth asks for it directly with `s(x1, x2, bs='tp')`.
3099            // Per-margin basis vector (`bs=c('tp','tp')` / `bs=['ps','cr']`):
3100            // validate each requested margin is a penalized-spline basis that
3101            // the tensor product realizes as a 1-D B-spline margin. mgcv's
3102            // `tp`/`ps`/`cr`/`bs`/`cc` margins are all penalized splines over
3103            // the same per-axis function space, so a B-spline margin recovers
3104            // the same tensor smoothing space; genuinely different margin kinds
3105            // (e.g. adaptive `ad`, random `re`) are rejected loudly rather than
3106            // silently substituted.
3107            if let Some(raw) = options.get("bs").or_else(|| options.get("type"))
3108                && bs_selector_is_vector(raw)
3109            {
3110                let per_margin = parse_option_list(raw);
3111                if per_margin.len() != dim {
3112                    return Err(TermBuilderError::invalid_option(format!(
3113                        "tensor smooth per-margin bs vector has {} entries but the smooth has {} margins",
3114                        per_margin.len(),
3115                        dim
3116                    ))
3117                    .to_string());
3118                }
3119                for (axis, margin_bs) in per_margin.iter().enumerate() {
3120                    if !tensor_margin_bs_is_supported(margin_bs) {
3121                        return Err(TermBuilderError::unsupported_feature(format!(
3122                            "tensor smooth margin {axis} basis '{margin_bs}' is not a supported penalized-spline margin; \
3123                             tensor margins accept tp/tps/ps/bs/cr/cc"
3124                        ))
3125                        .to_string());
3126                    }
3127                }
3128            }
3129            let periodic_axes = parse_tensor_periodic_axes(options, dim)?;
3130            reject_tensor_endpoint_boundary_conditions(options, dim)?;
3131            let periods_opt = parse_periods(options, &periodic_axes)?;
3132            let origins_opt = parse_period_origins(options, &periodic_axes)?;
3133            let degree = option_usize(options, "degree").unwrap_or(DEFAULT_BSPLINE_DEGREE);
3134            let penalty_order =
3135                option_usize(options, "penalty_order").unwrap_or(if degree > 1 { 2 } else { 1 });
3136            let (mut k_list, k_inferred) = parse_tensor_k_list(options, cols, ds)?;
3137            if ds.values.nrows() <= 32 && smooth_coordinate_count >= 5 {
3138                for k in &mut k_list {
3139                    *k = (*k).min(degree + 2);
3140                }
3141            }
3142            if k_inferred {
3143                inference_notes.push(format!(
3144                    "Automatically set per-margin basis sizes {:?} for tensor smooth '{}' \
3145                     (dimension-aware tensor budget: total ∏k kept near the mgcv-te default \
3146                     and within the data support, distributed geometrically across margins and \
3147                     capped per margin by each column's resolution). \
3148                     Override with k=<int> or k=[k0,k1,...].",
3149                    k_list,
3150                    vars.join(",")
3151                ));
3152            }
3153            // Per-axis requested marginal basis family. mgcv's `te()`/`ti()`
3154            // default marginal basis is the cubic regression spline (`cr`), and
3155            // the te_3d quality gap (#1074) is precisely the marginal-basis
3156            // resolution at small `k`: a `cr` margin places k value-knots at
3157            // data quantiles (finer interior resolution under natural boundary
3158            // constraints) where the cubic B-spline margin has only
3159            // `k-degree-1` interior knots. Resolve each axis to either an
3160            // explicit per-margin `bs` (vector `bs=c('cr','ps')`), a single
3161            // scalar `bs`, or the unset default — and route
3162            // `cr`/`cs`/unset/`tp`/`tps` margins through the natural cubic
3163            // regression builder (`NaturalCubicRegression` knotspec), keeping
3164            // explicit `ps`/`bs`/`bspline` on the B-spline margin.
3165            let per_axis_bs: Vec<Option<String>> =
3166                match options.get("bs").or_else(|| options.get("type")) {
3167                    Some(raw) if bs_selector_is_vector(raw) => {
3168                        let list = parse_option_list(raw);
3169                        (0..dim).map(|a| list.get(a).cloned()).collect()
3170                    }
3171                    Some(raw) => {
3172                        let scalar = raw
3173                            .trim()
3174                            .trim_matches('"')
3175                            .trim_matches('\'')
3176                            .to_ascii_lowercase();
3177                        vec![Some(scalar); dim]
3178                    }
3179                    None => vec![None; dim],
3180                };
3181            // A margin is realized as a natural cubic regression spline when it
3182            // is the (unset) mgcv default, an explicit `cr`/`cs`, or a
3183            // `tp`/`tps` (same per-axis penalized-spline space). Explicit
3184            // B-spline-family margins (`ps`/`bs`/`bspline`/`p-spline`) keep the
3185            // open B-spline margin.
3186            let margin_wants_cr = |bs: &Option<String>| -> bool {
3187                matches!(
3188                    bs.as_deref(),
3189                    None | Some("cr") | Some("cs") | Some("tp") | Some("tps")
3190                )
3191            };
3192            let mut margins: Vec<BSplineBasisSpec> = Vec::with_capacity(dim);
3193            let mut emitted_periods: Vec<Option<f64>> = Vec::with_capacity(dim);
3194            for axis in 0..dim {
3195                let c = cols[axis];
3196                let (data_min, data_max) = col_minmax(ds.values.column(c))?;
3197                // mgcv reduces a tensor margin's basis dimension to what its data
3198                // can support: a cr or B-spline margin cannot place more value
3199                // knots / basis functions than there are DISTINCT covariate
3200                // values on that axis. Without this cap an explicit `k` on a
3201                // low-cardinality margin — e.g. the binary `badh ∈ {0,1}` in
3202                // `te(age, badh, k=5)` — hard-failed in `select_cr_knots` ("cubic
3203                // regression spline with k=5 requires at least 5 distinct values,
3204                // got 2") instead of degrading to the 2-function (linear) margin
3205                // mgcv builds there. The auto-`k` path already caps per margin via
3206                // `heuristic_tensor_margin_knots`; mirror that for explicit `k`.
3207                // The cap propagates correctly: every per-axis quantity below
3208                // (effective degree, knot set, penalty order) is derived from
3209                // `k_axis`, and the marginal basis size is read from the resulting
3210                // knot spec — never from `k_list`. Floor at 2 so a margin still
3211                // carries at least a linear basis (tensor margins require k >= 2).
3212                let k_requested = k_list[axis];
3213                let n_distinct_axis = unique_count_column(ds.values.column(c));
3214                let k_axis = k_requested.min(n_distinct_axis).max(2);
3215                if k_axis < k_requested {
3216                    log::info!(
3217                        "tensor smooth: margin axis {axis} requested k={k_requested}, but the \
3218                         covariate has only {n_distinct_axis} distinct value(s); reducing this \
3219                         margin to k={k_axis} (mgcv-style data-support cap on the per-axis basis)."
3220                    );
3221                }
3222                // Per-axis effective spline degree. The B-spline basis with `k`
3223                // functions is well-defined for any `degree <= k - 1`; mgcv's
3224                // `te(...)` exploits this so a binary tensor margin
3225                // (`k=2` → linear basis) or a ternary margin (`k=3` → quadratic)
3226                // can coexist with a smoother continuous margin under one
3227                // shared `degree=` request. We mirror that: if the caller
3228                // explicitly asks for `k < degree + 1`, drop the degree on
3229                // THAT axis only to the largest feasible spline, and track the
3230                // penalty order so the marginal difference penalty stays
3231                // well-defined (`order < num_basis_functions` is required by
3232                // `create_difference_penalty_matrix`). Periodic axes still
3233                // need enough basis functions to wrap; reject k there.
3234                if k_axis < 2 {
3235                    return Err(TermBuilderError::invalid_option(format!(
3236                        "tensor smooth: k[{axis}]={k_axis} too small; tensor margins require k >= 2"
3237                    ))
3238                    .to_string());
3239                }
3240                if periodic_axes[axis] && k_axis < degree + 1 {
3241                    return Err(TermBuilderError::invalid_option(format!(
3242                        "tensor smooth: periodic axis {axis} requires k >= {} for degree {degree}, got k={k_axis}",
3243                        degree + 1
3244                    ))
3245                    .to_string());
3246                }
3247                let effective_degree = degree.min(k_axis - 1).max(1);
3248                let effective_penalty_order = penalty_order.min(effective_degree);
3249                // A `cc`/`cp`/`cyclic` per-margin basis declares periodicity
3250                // without necessarily supplying a `period=`: mgcv's `bs="cc"`
3251                // wraps at the covariate's observed data range. Mirror the 1-D
3252                // cyclic fallback (`parse_periodic_domain_1d`) here so a bare
3253                // `te(x, z, bs=c('cc','cc'))` wraps each margin on its own
3254                // [min, max] span instead of hard-erroring (#1752).
3255                let margin_is_cc = matches!(
3256                    canonicalize_smooth_type(per_axis_bs[axis].as_deref().unwrap_or("")),
3257                    "cc" | "cp" | "cyclic"
3258                );
3259                let (knotspec, boundary, axis_period) = if periodic_axes[axis] {
3260                    // A `cc`/`cp`/`cyclic` per-margin basis declares periodicity
3261                    // without necessarily supplying a `period=`; in that case wrap
3262                    // at the covariate's observed [min, max] span, mirroring the
3263                    // 1-D cyclic fallback (`parse_periodic_domain_1d`) so a bare
3264                    // `te(x, z, bs=c('cc','cc'))` wraps each margin on its own
3265                    // range instead of hard-erroring (#1752). An axis made
3266                    // periodic by an explicit `periodic=`/`boundary=` selector
3267                    // (not a cyclic margin basis) still requires an explicit
3268                    // `period=`: a data-derived period there is a sample-dependent
3269                    // off-by-ε seam and is not inferred.
3270                    let (domain_start, period_value) = match periods_opt[axis] {
3271                        Some(period_value) => {
3272                            if !period_value.is_finite() || period_value <= 0.0 {
3273                                return Err(format!(
3274                                    "tensor smooth axis {axis}: period must be a positive finite value, got {period_value}"
3275                                ));
3276                            }
3277                            (origins_opt[axis].unwrap_or(data_min), period_value)
3278                        }
3279                        None if margin_is_cc => {
3280                            let span = data_max - data_min;
3281                            if !span.is_finite() || span <= 0.0 {
3282                                return Err(format!(
3283                                    "tensor smooth axis {axis}: cyclic margin requires a positive \
3284                                     observed data range to derive its period, got [{data_min}, {data_max}]"
3285                                ));
3286                            }
3287                            (origins_opt[axis].unwrap_or(data_min), span)
3288                        }
3289                        None => {
3290                            return Err(format!(
3291                                "tensor smooth axis {axis} is periodic but requires an explicit \
3292                                 period: pass period=<value> (scalar) or period=[..., <value>, ...]. \
3293                                 Deriving the period from the observed data range is sample-dependent \
3294                                 (off-by-ε seam), so it is not inferred."
3295                            ));
3296                        }
3297                    };
3298                    let domain_end = domain_start + period_value;
3299                    (
3300                        BSplineKnotSpec::PeriodicUniform {
3301                            data_range: (domain_start, domain_end),
3302                            num_basis: k_axis,
3303                        },
3304                        OneDimensionalBoundary::Cyclic {
3305                            start: domain_start,
3306                            end: domain_end,
3307                        },
3308                        Some(period_value),
3309                    )
3310                } else if margin_wants_cr(&per_axis_bs[axis]) && k_axis >= 3 {
3311                    // mgcv `te()`/`ti()` default cr margin: place exactly
3312                    // `k_axis` Lancaster–Salkauskas value-knots at data
3313                    // quantiles. The cr basis dimension equals the knot count,
3314                    // so this reproduces the requested per-margin `k` directly.
3315                    // A natural cubic regression spline needs at least 3 knots
3316                    // (one interior); a `k_axis < 3` margin (e.g. a binary
3317                    // tensor axis requesting a linear margin) falls through to
3318                    // the B-spline branch below, exactly as before #1074 — mgcv
3319                    // likewise does not build a `cr` margin below k=3.
3320                    let cr_knots =
3321                        crate::basis::select_cr_knots(ds.values.column(c), k_axis)
3322                            .map_err(|e| e.to_string())?;
3323                    (
3324                        BSplineKnotSpec::NaturalCubicRegression { knots: cr_knots },
3325                        OneDimensionalBoundary::Open,
3326                        None,
3327                    )
3328                } else {
3329                    // `num_internal_knots = k - degree - 1` reproduces the
3330                    // requested basis size exactly when degree was reduced for
3331                    // a low-cardinality margin; keep the legacy `.max(1)`
3332                    // floor on the un-reduced path so the existing knot
3333                    // geometry is unchanged whenever the user already passed
3334                    // k >= degree + 1.
3335                    let num_internal_knots = if effective_degree < degree {
3336                        k_axis.saturating_sub(effective_degree + 1)
3337                    } else {
3338                        k_axis.saturating_sub(degree + 1).max(1)
3339                    };
3340                    let knotspec = match parse_knot_placement(options)? {
3341                        crate::basis::BSplineKnotPlacement::Uniform => BSplineKnotSpec::Generate {
3342                            data_range: (data_min, data_max),
3343                            num_internal_knots,
3344                        },
3345                        crate::basis::BSplineKnotPlacement::Quantile => {
3346                            crate::basis::auto_knot_vector_1d_quantile(
3347                                ds.values.column(c),
3348                                num_internal_knots,
3349                                effective_degree,
3350                            )
3351                            .map_err(|e| e.to_string())?;
3352                            BSplineKnotSpec::Automatic {
3353                                num_internal_knots: Some(num_internal_knots),
3354                                placement: crate::basis::BSplineKnotPlacement::Quantile,
3355                            }
3356                        }
3357                    };
3358                    (knotspec, OneDimensionalBoundary::Open, None)
3359                };
3360                // A `cr` margin fixes cubic regression geometry; the cr builder
3361                // reads only the knot set + `double_penalty`. Enable null-space
3362                // shrinkage for an explicit `cs` margin. B-spline margins keep
3363                // the resolved effective degree / penalty order with no extra
3364                // null-space penalty (mgcv `select = FALSE` tensor default).
3365                let is_cr_margin =
3366                    matches!(knotspec, BSplineKnotSpec::NaturalCubicRegression { .. });
3367                let margin_double_penalty =
3368                    is_cr_margin && matches!(per_axis_bs[axis].as_deref(), Some("cs"));
3369                margins.push(BSplineBasisSpec {
3370                    degree: effective_degree,
3371                    penalty_order: effective_penalty_order,
3372                    knotspec,
3373                    double_penalty: margin_double_penalty,
3374                    identifiability: BSplineIdentifiability::None,
3375                    boundary,
3376                    boundary_conditions: BSplineBoundaryConditions::default(),
3377                });
3378                emitted_periods.push(axis_period);
3379            }
3380            // #1593: canonicalize the margin order so a tensor smooth is invariant
3381            // to the typed order of its covariates. `te(x, z)` and `te(z, x)` span
3382            // the IDENTICAL tensor-product space under the identical per-margin
3383            // penalty family, but the design is the Khatri–Rao product
3384            // `B_first ⊙ B_second`, so the typed order permutes the design columns
3385            // (and the per-margin penalty blocks `S_first⊗I`, `I⊗S_second`). That
3386            // permutation is a pure relabelling in exact arithmetic — REML is
3387            // invariant to it — yet it reorders the penalized normal-equation / REML
3388            // eigen/Cholesky linear algebra, and the resulting sub-ULP differences
3389            // route the outer λ optimizer to a different terminal point in te's flat
3390            // REML valley (the over-smoothed margin rails to the ρ bound while the
3391            // other lands on a materially different λ̂). So the shipped surface
3392            // drifted ~2–6 % of range with a cosmetic swap of the covariate order
3393            // (the #1378 row-permutation / #1456 rotation flat-valley gauge family).
3394            // Sorting the margins by their source feature-column index makes the same
3395            // physical model build the identical problem regardless of typed order,
3396            // so the fit — and every prediction rebuilt from the resolved spec — is
3397            // genuinely order-invariant. `ti`/`t2` share this arm and become exactly
3398            // invariant too (they were already ~1e-5 by centring each margin
3399            // separately; canonicalization makes the swap bit-identical).
3400            let canon_cols: Vec<usize> = {
3401                let mut perm: Vec<usize> = (0..dim).collect();
3402                perm.sort_by_key(|&a| cols[a]);
3403                if perm.iter().enumerate().any(|(i, &a)| i != a) {
3404                    margins = perm.iter().map(|&a| margins[a].clone()).collect();
3405                    emitted_periods = perm.iter().map(|&a| emitted_periods[a]).collect();
3406                }
3407                perm.iter().map(|&a| cols[a]).collect()
3408            };
3409            let any_periodic = emitted_periods.iter().any(|p| p.is_some());
3410            let periods_vec = if any_periodic {
3411                emitted_periods
3412            } else {
3413                Vec::new()
3414            };
3415            // Tensor smooths (`te`/`ti`/`t2`) must match mgcv's DEFAULT
3416            // `select = FALSE`: the joint null space of the per-margin
3417            // penalties — the bilinear, low-order interaction directions that
3418            // no marginal roughness operator can see — is left UNPENALIZED.
3419            // mgcv only adds a null-space shrinkage penalty there under the
3420            // opt-in `select = TRUE` (which gam exposes as `double_penalty`).
3421            //
3422            // The general smooth default (`smooth_double_penalty`, true) is
3423            // calibrated for 1-D `s()` terms; carrying it into tensors silently
3424            // shrinks the genuinely-present bilinear interaction signal, so
3425            // REML places positive weight on the extra ridge and systematically
3426            // OVER-SMOOTHS the recovered surface relative to mgcv's plain
3427            // `te`/`ti` (gam#700/#701/#702/#703). Default tensors to no extra
3428            // null-space penalty; an explicit user `double_penalty=`/`select=`
3429            // still wins.
3430            let tensor_double_penalty = option_bool(options, "double_penalty").unwrap_or(false);
3431            Ok(SmoothBasisSpec::TensorBSpline {
3432                feature_cols: canon_cols,
3433                spec: TensorBSplineSpec {
3434                    marginalspecs: margins,
3435                    periods: periods_vec,
3436                    double_penalty: tensor_double_penalty,
3437                    identifiability: parse_tensor_identifiability(options, kind)?,
3438                    // `t2` selects mgcv's separable (Wood, Scheipl & Faraway
3439                    // 2013) decomposition. It can arrive either as the `t2(...)`
3440                    // function form (`SmoothKind::T2`) or as a `type="t2"` /
3441                    // `bs="t2"` option on an `s(...)`/`te(...)` term, in which
3442                    // case `kind` is *not* `T2` but the resolved type string is
3443                    // "t2". Keying only off `kind` silently aliased the option
3444                    // form to `te`'s Kronecker-sum penalty (gam#1185); key off
3445                    // the resolved type string as well so both routes build the
3446                    // separable penalty.
3447                    penalty_decomposition: if matches!(kind, SmoothKind::T2)
3448                        || type_opt.as_str() == "t2"
3449                    {
3450                        TensorBSplinePenaltyDecomposition::Separable
3451                    } else {
3452                        TensorBSplinePenaltyDecomposition::MarginalKroneckerSum
3453                    },
3454                },
3455            })
3456        }
3457        "pca" => {
3458            validate_known_options(
3459                "pca",
3460                options,
3461                &[
3462                    "type",
3463                    "bs",
3464                    "by",
3465                    "k",
3466                    "basis_dim",
3467                    "basis-dim",
3468                    "basisdim",
3469                    "lazy_path",
3470                    "path",
3471                    "pca_basis_path",
3472                    "chunk_size",
3473                    "smooth_penalty",
3474                    "centered",
3475                    "double_penalty",
3476                    "id",
3477                    "__by_col",
3478                ],
3479            )?;
3480            let path = options
3481                .get("lazy_path")
3482                .or_else(|| options.get("pca_basis_path"))
3483                .or_else(|| options.get("path"))
3484                .map(|raw| PathBuf::from(strip_quotes(raw)));
3485            let Some(path) = path else {
3486                return Err(TermBuilderError::incompatible_config(
3487                    "pca smooth requires lazy_path=... on the formula path",
3488                )
3489                .to_string());
3490            };
3491            let k = option_usize_any(options, &["k", "basis_dim", "basis-dim", "basisdim"])
3492                .unwrap_or(0);
3493            let chunk_size = option_usize(options, "chunk_size").unwrap_or(DEFAULT_PCA_CHUNK_SIZE);
3494            Ok(SmoothBasisSpec::Pca {
3495                feature_cols: cols.to_vec(),
3496                basis_matrix: Array2::<f64>::zeros((cols.len(), k)),
3497                centered: option_bool(options, "centered").unwrap_or(true),
3498                smooth_penalty: option_f64(options, "smooth_penalty").unwrap_or(1.0),
3499                center_mean: None,
3500                pca_basis_path: Some(path),
3501                chunk_size,
3502            })
3503        }
3504        other => Err(TermBuilderError::unsupported_feature(format!(
3505            "unsupported smooth type '{other}'"
3506        ))
3507        .to_string()),
3508    }
3509}
3510
3511/// Initialise per-axis anisotropic log-scales on eligible spatial smooth specs.
3512pub fn enable_scale_dimensions(spec: &mut TermCollectionSpec) {
3513    for smooth in spec.smooth_terms.iter_mut() {
3514        // A multi-axis thin-plate term cannot carry per-axis anisotropy on its
3515        // single curvature penalty, so `scale_dimensions` was historically a
3516        // silent no-op for `bs="tp"` (gam#1676). Rewrite it to the
3517        // mathematically-equivalent anisotropic s=0 Duchon spline first; the
3518        // Duchon arm below then sees an already-seeded `aniso_log_scales` and
3519        // leaves it untouched.
3520        promote_thin_plate_for_scale_dimensions(&mut smooth.basis);
3521        match &mut smooth.basis {
3522            SmoothBasisSpec::Matern {
3523                feature_cols,
3524                spec: matern,
3525                ..
3526            } => {
3527                if matern.aniso_log_scales.is_none() {
3528                    let d = feature_cols.len();
3529                    matern.aniso_log_scales = Some(vec![0.0; d]);
3530                }
3531            }
3532            SmoothBasisSpec::Duchon {
3533                feature_cols,
3534                spec: duchon,
3535                ..
3536            } => {
3537                if duchon.aniso_log_scales.is_none() {
3538                    let d = feature_cols.len();
3539                    duchon.aniso_log_scales = Some(vec![0.0; d]);
3540                }
3541            }
3542            _ => {}
3543        }
3544    }
3545}
3546
3547/// Rewrite a multi-axis thin-plate term into the mathematically-equivalent
3548/// anisotropic s=0 Duchon spline so that `scale_dimensions` genuinely engages
3549/// (gam#1676).
3550///
3551/// ## Why a rewrite rather than a new field on the TPS builder
3552///
3553/// A canonical thin-plate regression spline carries a *single* curvature
3554/// penalty — the exact `∫|Dᵐ f|²` reproducing-kernel Gram. That penalty has no
3555/// per-axis structure to make one direction more or less relevant than another,
3556/// so per-axis anisotropy (`scale_dimensions`) cannot be expressed on it. The
3557/// flag was therefore a silent no-op for `bs="tp"` while it engaged for
3558/// `duchon()`/`matern()`.
3559///
3560/// The thin-plate kernel `r^{2m−d}` (the `r²·log r` log-case in even `d`) is
3561/// *exactly* the s=0 Duchon kernel (`DuchonBasisSpec::power = 0`,
3562/// `length_scale = None`) at the matching polynomial null-space order
3563/// `m = thin_plate_penalty_order(d)`. The Duchon polyharmonic family already
3564/// carries the per-axis tension ARD that `scale_dimensions` requests: its
3565/// isotropic first-order roughness penalty `Σ‖∇f‖²` splits into `d` directional
3566/// penalties `Σ(∂f/∂x_a)²`, each with its own REML `λ_a`
3567/// (`duchon_operator_penalty_candidates`). So the well-posed *anisotropic
3568/// thin-plate spline is the anisotropic s=0 Duchon spline*. Rewriting to that
3569/// representation reuses the battle-tested Duchon anisotropy / ψ-derivative /
3570/// freeze / predict machinery instead of duplicating it onto the TPS metadata
3571/// path, and keeps the polyharmonic family internally consistent. The codebase
3572/// already promotes infeasible-`k` TPS to Duchon for the same reason (the
3573/// canonical TPS single curvature penalty cannot deliver a requested
3574/// capability); per-axis anisotropy is another such capability.
3575///
3576/// This fires *only* when the user opts into `scale_dimensions`; the default
3577/// thin-plate path (`scale_dimensions` off) is left bit-for-bit unchanged.
3578/// A 1-D thin-plate term is left untouched — anisotropy is meaningless on a
3579/// single axis (its `Σ η = 0` contrast vector is empty), exactly as for a 1-D
3580/// Matérn/Duchon term.
3581fn promote_thin_plate_for_scale_dimensions(basis: &mut SmoothBasisSpec) {
3582    let SmoothBasisSpec::ThinPlate {
3583        feature_cols,
3584        spec,
3585        input_scales,
3586    } = &*basis
3587    else {
3588        return;
3589    };
3590    let d = feature_cols.len();
3591    if d <= 1 {
3592        return;
3593    }
3594    // m = thin_plate_penalty_order(d) is the TPS penalty order; the Duchon
3595    // null-space order naming is `Zero → m=1`, `Linear → m=2`,
3596    // `Degree(g) → m=g+1`, so the s=0 Duchon kernel exponent
3597    // `2(p+s) − d = 2m − d` reproduces the TPS kernel exactly.
3598    let m = thin_plate_penalty_order(d);
3599    let nullspace_order = match m {
3600        0 | 1 => DuchonNullspaceOrder::Zero,
3601        2 => DuchonNullspaceOrder::Linear,
3602        _ => DuchonNullspaceOrder::Degree(m - 1),
3603    };
3604    let duchon_spec = DuchonBasisSpec {
3605        center_strategy: spec.center_strategy.clone(),
3606        periodic: spec.periodic.clone(),
3607        // Pure, scale-free Duchon — the thin-plate kernel has no length scale
3608        // (a global TPS kernel scale is non-identifiable once REML learns the
3609        // smoothing penalty: gam#718/#721/#731/#732). The per-axis relevance
3610        // the user asked for is carried by the tension-ARD `λ_a`, not a κ axis.
3611        length_scale: None,
3612        // s = 0  ⇒  thin-plate kernel `r^{2m−d}`.
3613        power: 0.0,
3614        nullspace_order,
3615        identifiability: spec.identifiability.clone(),
3616        // All-zero geometry seed sentinel: `auto_seed_aniso_contrasts` resolves
3617        // it from the (standardized) knot cloud, and the per-axis tension split
3618        // engages on `aniso.is_some()`.
3619        aniso_log_scales: Some(vec![0.0; d]),
3620        operator_penalties: DuchonOperatorPenaltySpec::default(),
3621        boundary: OneDimensionalBoundary::Open,
3622        radial_reparam: None,
3623    };
3624    let feature_cols = feature_cols.clone();
3625    let input_scales = input_scales.clone();
3626    // All borrows of `*basis` (the `&*basis` destructure above) end with the
3627    // clones on the two preceding lines, so the reassignment is sound.
3628    *basis = SmoothBasisSpec::Duchon {
3629        feature_cols,
3630        spec: duchon_spec,
3631        input_scales,
3632    };
3633}
3634
3635// ---------------------------------------------------------------------------
3636// Data-aware helpers
3637// ---------------------------------------------------------------------------
3638
3639pub fn spatial_center_strategy_for_dimension(num_centers: usize, d: usize) -> CenterStrategy {
3640    if d <= 3 {
3641        // In low-dimensional spatial smooths, an explicit `k` is a resolution
3642        // request rather than a request for marginal quantile-midpoint centers.
3643        // Use deterministic maximin geometry so Matérn/GP and Duchon REML see a
3644        // well-resolved native kernel block with small fill distance instead of
3645        // compensating for holes or endpoint under-resolution by over-smoothing
3646        // low-noise signals (#504).
3647        CenterStrategy::FarthestPoint { num_centers }
3648    } else {
3649        default_spatial_center_strategy(num_centers, d)
3650    }
3651}
3652
3653pub fn col_minmax(col: ArrayView1<'_, f64>) -> Result<(f64, f64), String> {
3654    let min = col.iter().fold(f64::INFINITY, |a, &b| a.min(b));
3655    let max = col.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
3656    if !min.is_finite() || !max.is_finite() {
3657        return Err(TermBuilderError::degenerate_data(
3658            "non-finite data encountered while inferring knot range",
3659        )
3660        .to_string());
3661    }
3662    if (max - min).abs() < 1e-12 {
3663        Ok((min, min + 1e-6))
3664    } else {
3665        Ok((min, max))
3666    }
3667}
3668
3669pub fn unique_count_column(col: ArrayView1<'_, f64>) -> usize {
3670    use std::collections::HashSet;
3671    let mut set = HashSet::<u64>::with_capacity(col.len());
3672    for &v in col {
3673        let norm = if v == 0.0 { 0.0 } else { v };
3674        set.insert(norm.to_bits());
3675    }
3676    set.len().max(1)
3677}
3678
3679/// Minimum knot count for a natural cubic regression spline: `select_cr_knots`
3680/// places one value-knot per basis function and needs at least an interior knot,
3681/// so the sparsest representable cr basis is `{const, linear, curvature}` at
3682/// three knots. Below this a cr spline is not constructible and the caller must
3683/// degrade to the linear B-spline marginal.
3684pub(crate) const CR_MIN_KNOTS: usize = 3;
3685
3686/// Build a cubic-regression marginal knot spec capped to the covariate's data
3687/// support, mgcv-style.
3688///
3689/// A `cr`/`cs`/`sz` marginal places exactly one basis function per value-knot,
3690/// so `select_cr_knots` cannot place more knots than the covariate has DISTINCT
3691/// values — it `bail`s with "cubic regression spline with k=N requires at least
3692/// N distinct values" otherwise. An unclamped `k` on an ordinary low-cardinality
3693/// covariate (a binary indicator, a 3-level ordinal/Likert score, a small count)
3694/// therefore hard-failed the whole fit instead of reducing the basis the way
3695/// mgcv — and gam's own tensor-margin path (996f829d7, `term_builder.rs:2986` /
3696/// the `k_axis >= 3` cr gate at `:3047`) — do. This is the univariate / factor-
3697/// smooth sibling of that tensor cap (#1541, #1542).
3698///
3699/// Returns:
3700/// - `Some(NaturalCubicRegression { .. })` with `k = min(k_requested, n_distinct)`
3701///   value-knots when the data supports a cr spline (`n_distinct >= CR_MIN_KNOTS`).
3702///   A cr basis of exactly `n_distinct` knots is full-rank for the data — it can
3703///   represent any per-distinct-value structure (e.g. 3 arbitrary group means on
3704///   a ternary covariate) — so the cap never costs recoverable signal.
3705/// - `None` when `n_distinct < CR_MIN_KNOTS` (a binary covariate): too few
3706///   distinct values for ANY cr spline, so the caller degrades to the linear
3707///   B-spline marginal — exactly what the default `s(x, k=..)` basis already
3708///   builds on the same data, and what the tensor path's `< 3` branch builds.
3709///
3710/// `inference_notes` records any reduction so the user sees that `k` was capped
3711/// (mgcv emits a warning in the same situation).
3712fn capped_cr_marginal_knotspec(
3713    col: ArrayView1<'_, f64>,
3714    k_cr_requested: usize,
3715    label: &str,
3716    inference_notes: &mut Vec<String>,
3717) -> Result<Option<BSplineKnotSpec>, String> {
3718    let n_distinct = unique_count_column(col);
3719    let k_cr = k_cr_requested.min(n_distinct);
3720    if k_cr < CR_MIN_KNOTS {
3721        inference_notes.push(format!(
3722            "Smooth '{label}': cubic-regression ('cr'/'cs'/'sz') basis requested k={k_cr_requested}, \
3723             but the covariate has only {n_distinct} distinct value(s) — too few to support a cubic \
3724             regression spline (needs >= {CR_MIN_KNOTS} distinct values). Degraded to the linear \
3725             B-spline marginal the default basis builds on the same data."
3726        ));
3727        return Ok(None);
3728    }
3729    if k_cr < k_cr_requested {
3730        inference_notes.push(format!(
3731            "Smooth '{label}': cubic-regression ('cr'/'cs'/'sz') basis reduced from k={k_cr_requested} \
3732             to k={k_cr} to match the covariate's {n_distinct} distinct value(s) (mgcv-style \
3733             data-support cap; a cr basis cannot place more value-knots than the data has)."
3734        ));
3735    }
3736    let cr_knots = crate::basis::select_cr_knots(col, k_cr).map_err(|e| e.to_string())?;
3737    Ok(Some(BSplineKnotSpec::NaturalCubicRegression {
3738        knots: cr_knots,
3739    }))
3740}
3741
3742/// Smallest number of distinct covariate values seen within any single group
3743/// of `group_col`. For a factor smooth this is the resolution that bounds the
3744/// marginal basis: a group with `m` distinct covariate values can only inform
3745/// `m` basis coefficients, so a marginal richer than that interpolates the
3746/// group instead of estimating a penalized trend. Bits are compared exactly so
3747/// integer-valued covariates (days, dose levels) collapse to their true count.
3748fn min_per_group_unique_count(
3749    feature_col: ArrayView1<'_, f64>,
3750    group_col: ArrayView1<'_, f64>,
3751) -> usize {
3752    use std::collections::{HashMap, HashSet};
3753    let mut per_group: HashMap<u64, HashSet<u64>> = HashMap::new();
3754    for (xi, gi) in feature_col.iter().zip(group_col.iter()) {
3755        let xnorm = if *xi == 0.0 { 0.0 } else { *xi };
3756        let gnorm = if *gi == 0.0 { 0.0 } else { *gi };
3757        per_group
3758            .entry(gnorm.to_bits())
3759            .or_default()
3760            .insert(xnorm.to_bits());
3761    }
3762    per_group
3763        .values()
3764        .map(|s| s.len())
3765        .min()
3766        .unwrap_or(1)
3767        .max(1)
3768}
3769
3770/// Default internal-knot count for an *additive* univariate smooth, derived
3771/// from the column's unique-value count.
3772///
3773/// The basis dimension is `internal_knots + degree + 1`, so the cap below maps
3774/// to a default cubic basis of ~12 functions — deliberately close to mgcv's
3775/// univariate default (`k = 10`). A penalized smooth controls its wiggliness
3776/// through the *penalty*, not the basis size: REML/LAML shrinks a too-rich
3777/// basis toward the null, but it cannot do so cleanly when the basis is so
3778/// over-sized that the design becomes weakly identified. Growing the basis with
3779/// `n` (the old `n^(1/3)`-ceilinged `unique/4` rule, which pinned to 20 internal
3780/// knots ⇒ a 24-function basis for any column with ≥80 unique values) therefore
3781/// *hurts* recovery on finite, weak-signal fits: a 4-smooth additive model on
3782/// n=120 asks for ~92 coefficients, the outer optimizer stalls on the resulting
3783/// flat two-penalty (range + null-space) REML surface, and the truth leaks into
3784/// surplus columns the penalty can't shrink away (gam#1680; the same defect was
3785/// documented for thin-plate fields in gam#1074). A k-sweep on the #1680 design
3786/// confirms a basis of ~10–15 recovers truth at RMSE ≈ 0.12 while the old
3787/// 24-function default lands at ≈ 0.39 (~3× worse) — *whether or not* the
3788/// covariates are collinear, so this is basis over-richness, not collinearity.
3789///
3790/// The cap is flat in `n`: a user who genuinely needs a wigglier fit raises `k`
3791/// explicitly (mgcv's contract — opt *in* to more flexibility), and the SPEC
3792/// requires the default to allow recovering the null rather than forcing the
3793/// user to opt out of overfitting. The 4-knot floor stays put because we still
3794/// need enough basis functions to fit a non-trivial smooth at all, and the
3795/// `unique/4` growth below the cap keeps small/sparse columns (n ≤ 32, where
3796/// `unique/4 ≤ 8`) on exactly their previous knot count.
3797pub fn heuristic_knots_for_column(col: ArrayView1<'_, f64>) -> usize {
3798    /// Default cubic basis ≈ `MAX_DEFAULT_INTERNAL_KNOTS + degree + 1` = 12
3799    /// functions, matching mgcv's lean univariate default.
3800    const MAX_DEFAULT_INTERNAL_KNOTS: usize = 8;
3801    let unique = unique_count_column(col);
3802    (unique / 4).clamp(4, MAX_DEFAULT_INTERNAL_KNOTS)
3803}
3804
3805/// Per-margin basis sizes for a tensor-product smooth (`te`/`ti`/`t2`).
3806///
3807/// The 1-D heuristic [`heuristic_knots_for_column`] is calibrated for an
3808/// *additive* margin: a well-resolved column asks for the lean univariate
3809/// default (≈12 basis functions, the mgcv-like cap of 8 internal knots; see
3810/// gam#1680), which is sensible for a single `s(x)` term.
3811/// A tensor product, however, multiplies the per-margin sizes:
3812/// `p = ∏_d k_d`. Reusing the 1-D rule per margin makes `p` explode with the
3813/// tensor dimension — a 3-D `te(x,y,z)` at the 1-D ceiling of 12/margin is
3814/// `12³ ≈ 1728` columns, and every REML evaluation pays an O(p³) dense
3815/// penalty reparameterization (the full-tensor sum-to-zero constraint is not
3816/// Kronecker-factorable), turning model selection over tensor candidates into
3817/// a multi-minute single-threaded stall (gam#813). It also requests far more
3818/// coefficients than the data can identify whenever `p ≫ n`.
3819///
3820/// mgcv's `te(...)` uses a small per-margin default (`k = 5`, i.e. `5^d`).
3821/// We match that spirit while staying data-adaptive: budget the *total* tensor
3822/// column count `p_target` and distribute it geometrically across the margins
3823/// so `∏ k_d ≈ p_target`, never asking a margin for more functions than its
3824/// own unique values (and the data set) can support.
3825fn heuristic_tensor_margin_knots(cols: &[usize], ds: &Dataset) -> Vec<usize> {
3826    let d = cols.len().max(1);
3827    let degree = DEFAULT_BSPLINE_DEGREE;
3828    let min_k = degree + 2; // smallest margin that carries a difference penalty
3829    let n = ds.values.nrows();
3830
3831    // Per-margin 1-D ceiling: never request more basis functions than the
3832    // margin's own resolution (unique values) supports. This caps each axis
3833    // independently before the joint budget is applied.
3834    let per_margin_cap: Vec<usize> = cols
3835        .iter()
3836        .map(|&c| heuristic_knots_for_column(ds.values.column(c)).max(min_k))
3837        .collect();
3838
3839    // Total-basis budget. A tensor with ∏k ≫ n coefficients is rank-deficient
3840    // and pure REML cost; cap the product at a generous fraction of n while
3841    // honoring mgcv's small default for the common small-d case. The budget
3842    // grows with n but the geometric split below keeps each margin modest.
3843    //   d=2 → up to ~7²=49 (mgcv-`te`-like), d=3 → ~5³=125, larger d shrinks
3844    // per-margin further so the product never blows past the data support.
3845    let mgcv_like_per_margin = match d {
3846        2 => 7usize,
3847        3 => 5usize,
3848        _ => 4usize,
3849    };
3850    let mgcv_like_total = (mgcv_like_per_margin as f64).powi(d as i32);
3851    let data_budget = (n as f64) * 0.8;
3852    let p_target = mgcv_like_total
3853        .max(min_k.pow(d as u32) as f64)
3854        .min(data_budget);
3855
3856    // Geometric per-margin target so ∏k ≈ p_target, then clamp each margin to
3857    // its own 1-D resolution cap and the difference-penalty floor.
3858    let geo_per_margin = p_target.powf(1.0 / d as f64).round() as usize;
3859    let unclamped: Vec<usize> = per_margin_cap
3860        .iter()
3861        .map(|&cap| geo_per_margin.clamp(min_k, cap))
3862        .collect();
3863
3864    // The per-margin clamps can pull some axes below `geo_per_margin` (a
3865    // low-resolution column), leaving headroom in the joint budget. Redistribute
3866    // that headroom to the margins that can still grow, so the realized ∏k stays
3867    // close to p_target instead of systematically under-shooting it.
3868    let mut k_list = unclamped;
3869    loop {
3870        let product: f64 = k_list.iter().map(|&k| k as f64).product();
3871        if product >= p_target {
3872            break;
3873        }
3874        // Grow the axis with the most remaining headroom (cap − current),
3875        // breaking ties toward the largest cap. Stop when none can grow.
3876        let Some(idx) = k_list
3877            .iter()
3878            .zip(per_margin_cap.iter())
3879            .enumerate()
3880            .filter(|&(_, (k, cap))| k < cap)
3881            .max_by_key(|&(_, (k, cap))| (cap - k, *cap))
3882            .map(|(i, _)| i)
3883        else {
3884            break;
3885        };
3886        k_list[idx] += 1;
3887    }
3888    k_list
3889}
3890
3891pub fn heuristic_centers(n: usize, d: usize) -> usize {
3892    default_num_centers(n, d)
3893}
3894
3895// ---------------------------------------------------------------------------
3896// Smooth option parsers
3897// ---------------------------------------------------------------------------
3898
3899fn parse_endpoint_side(
3900    value: &str,
3901    context: &str,
3902) -> Result<BSplineEndpointBoundaryCondition, String> {
3903    match value.trim().to_ascii_lowercase().as_str() {
3904        "" | "none" | "open" | "unconstrained" | "free" => {
3905            Ok(BSplineEndpointBoundaryCondition::Free)
3906        }
3907        "clamped" | "clamp" | "zero_derivative" | "zero-derivative" => {
3908            Ok(BSplineEndpointBoundaryCondition::Clamped)
3909        }
3910        "anchored" | "anchor" | "zero" | "zero_value" | "zero-value" => {
3911            Ok(BSplineEndpointBoundaryCondition::Anchored { value: 0.0 })
3912        }
3913        other => Err(format!(
3914            "unsupported {context} boundary condition '{other}'; expected free, clamped, or anchored"
3915        )),
3916    }
3917}
3918
3919fn boundary_anchor_value(
3920    options: &BTreeMap<String, String>,
3921    side: &str,
3922    fallback: Option<f64>,
3923) -> Option<f64> {
3924    [
3925        format!("anchor_{side}"),
3926        format!("{side}_anchor"),
3927        format!("anchor-value-{side}"),
3928    ]
3929    .iter()
3930    .find_map(|key| option_f64(options, key))
3931    .or(fallback)
3932}
3933
3934fn apply_anchor_value(
3935    cond: BSplineEndpointBoundaryCondition,
3936    value: Option<f64>,
3937) -> BSplineEndpointBoundaryCondition {
3938    match cond {
3939        BSplineEndpointBoundaryCondition::Anchored { .. } => {
3940            BSplineEndpointBoundaryCondition::Anchored {
3941                value: value.unwrap_or(0.0),
3942            }
3943        }
3944        other => other,
3945    }
3946}
3947
3948fn parse_bspline_boundary_conditions(
3949    options: &BTreeMap<String, String>,
3950) -> Result<BSplineBoundaryConditions, String> {
3951    let fallback_anchor = option_f64(options, "anchor")
3952        .or_else(|| option_f64(options, "anchor_value"))
3953        .or_else(|| option_f64(options, "value"));
3954    let global_boundary_conditions = options
3955        .get("boundary_conditions")
3956        .or_else(|| options.get("bc"));
3957    let mut boundary_conditions = BSplineBoundaryConditions::default();
3958
3959    if let Some(raw_boundary_conditions) = global_boundary_conditions {
3960        let cond = parse_endpoint_side(raw_boundary_conditions, "boundary_conditions")?;
3961        let side = options
3962            .get("side")
3963            .map(|s| s.trim().to_ascii_lowercase())
3964            .unwrap_or_else(|| "both".to_string());
3965        match side.as_str() {
3966            "both" | "all" | "endpoints" => {
3967                boundary_conditions.left = cond;
3968                boundary_conditions.right = cond;
3969            }
3970            "left" | "start" | "lower" => boundary_conditions.left = cond,
3971            "right" | "end" | "upper" => boundary_conditions.right = cond,
3972            other => {
3973                return Err(format!(
3974                    "unsupported B-spline boundary side '{other}'; expected left, right, or both"
3975                ));
3976            }
3977        }
3978    }
3979
3980    if let Some(raw) = options
3981        .get("bc_left")
3982        .or_else(|| options.get("left_bc"))
3983        .or_else(|| options.get("bc_start"))
3984        .or_else(|| options.get("start_bc"))
3985    {
3986        boundary_conditions.left = parse_endpoint_side(raw, "left endpoint")?;
3987    }
3988    if let Some(raw) = options
3989        .get("bc_right")
3990        .or_else(|| options.get("right_bc"))
3991        .or_else(|| options.get("bc_end"))
3992        .or_else(|| options.get("end_bc"))
3993    {
3994        boundary_conditions.right = parse_endpoint_side(raw, "right endpoint")?;
3995    }
3996
3997    boundary_conditions.left = apply_anchor_value(
3998        boundary_conditions.left,
3999        boundary_anchor_value(options, "left", fallback_anchor),
4000    );
4001    boundary_conditions.right = apply_anchor_value(
4002        boundary_conditions.right,
4003        boundary_anchor_value(options, "right", fallback_anchor),
4004    );
4005
4006    // Non-zero anchors require an affine offset term that the current basis
4007    // builder does not synthesize (see `build_bspline_basis_1d` in
4008    // src/terms/basis.rs). Surface the rejection at parse time with the side
4009    // and value in the diagnostic, instead of letting the value-only error
4010    // emerge deep inside the basis builder where the user has no context
4011    // about which anchor key (`anchor`, `left_anchor`, `right_anchor`, …)
4012    // routed into which endpoint.
4013    reject_nonzero_anchor("left", boundary_conditions.left)?;
4014    reject_nonzero_anchor("right", boundary_conditions.right)?;
4015
4016    Ok(boundary_conditions)
4017}
4018
4019fn reject_nonzero_anchor(side: &str, cond: BSplineEndpointBoundaryCondition) -> Result<(), String> {
4020    if let BSplineEndpointBoundaryCondition::Anchored { value } = cond {
4021        if value.abs() > 1e-12 {
4022            return Err(format!(
4023                "non-zero {side} anchor {value} requires an affine offset term that is not yet supported; only anchored value 0 is accepted at parse time"
4024            ));
4025        }
4026    }
4027    Ok(())
4028}
4029
4030/// Resolve the requested internal-knot count and effective spline degree for
4031/// a 1-D penalized B-spline smooth. This mirrors the tensor-margin per-axis
4032/// degree-reduction policy: a 1-D B-spline basis with `k` functions
4033/// is well-defined for any `degree <= k - 1`, so an explicit
4034/// `s(x, bs="ps", k=3)` with default `degree=3` is interpreted as the
4035/// largest representable spline (`effective_degree = k - 1 = 2`, quadratic)
4036/// rather than rejected. The `penalty_order` carried by the caller must be
4037/// clamped to `<= effective_degree` so the marginal difference penalty
4038/// stays well-defined; the returned `effective_degree` makes that explicit.
4039///
4040/// Mirrors the tensor margin treatment in the `te(...)` builder so a
4041/// standalone smooth, a factor smooth, and a tensor margin all interpret
4042/// "small k" the same way.
4043fn parse_ps_internal_knots(
4044    options: &BTreeMap<String, String>,
4045    degree: usize,
4046    default_internal_knots: usize,
4047) -> Result<(usize, bool, usize), String> {
4048    const MIN_EXPRESSIVE_INTERNAL_KNOTS: usize = 2;
4049    // Strict variants: reject `k=-1`, `k=1.5`, `knots=-2` etc. with a
4050    // focused error instead of silently dropping the value and using the
4051    // default. Lenient `option_usize` / `option_usize_any` silently swallow
4052    // unparseable values, which leaves the user thinking they configured
4053    // something when they did not.
4054    // A list-valued `knots=[...]` carries explicit internal positions, not a
4055    // count; it is consumed by `parse_explicit_internal_knots`. Treat it as
4056    // "count not specified" here so the strict integer parse does not reject
4057    // the bracketed value (the Provided path ignores the returned count).
4058    let knots_internal = if knots_option_is_list(options) {
4059        None
4060    } else {
4061        option_usize_strict(options, "knots")?
4062    };
4063    let basis_dim = option_usize_any_strict(options, &["k", "basis_dim", "basis-dim", "basisdim"])?;
4064    if knots_internal.is_some() && basis_dim.is_some() {
4065        return Err(TermBuilderError::incompatible_config(
4066            "ps/bspline smooth: specify either knots=<internal_knots> or k=<basis_dim> (not both)",
4067        )
4068        .to_string());
4069    }
4070    if let Some(k) = basis_dim {
4071        if k < 2 {
4072            return Err(TermBuilderError::invalid_option(format!(
4073                "ps/bspline smooth: k={} too small; B-spline basis requires k >= 2",
4074                k
4075            ))
4076            .to_string());
4077        }
4078        // `degree <= k - 1` is required for the B-spline basis to be
4079        // well-defined; reduce on this axis only when the user asked for
4080        // a smaller k than the cubic default supports. This matches mgcv's
4081        // behaviour (e.g. `s(x, bs="ps", k=3)` becomes a quadratic basis)
4082        // and the per-axis reduction the tensor builder already does.
4083        let effective_degree = degree.min(k - 1).max(1);
4084        let num_internal_knots = if effective_degree < degree {
4085            // Reproduce the requested basis size exactly when degree was
4086            // reduced for a low-cardinality axis: num_basis = k.
4087            k.saturating_sub(effective_degree + 1)
4088        } else {
4089            (k - degree - 1).max(MIN_EXPRESSIVE_INTERNAL_KNOTS)
4090        };
4091        Ok((num_internal_knots, false, effective_degree))
4092    } else {
4093        Ok((
4094            knots_internal.unwrap_or(default_internal_knots),
4095            knots_internal.is_none(),
4096            degree,
4097        ))
4098    }
4099}
4100
4101/// True when the `knots` option value is a *list* literal (`[...]`, `c(...)`,
4102/// or `(...)`) rather than a scalar count. mgcv's `knots=` accepts both: a
4103/// single integer is an internal-knot count, while a vector is explicit
4104/// internal knot positions. We disambiguate purely on the wrapper syntax so a
4105/// bare `knots=5` keeps its historical count meaning.
4106fn knots_option_is_list(options: &BTreeMap<String, String>) -> bool {
4107    options
4108        .get("knots")
4109        .map(|raw| {
4110            let t = raw.trim();
4111            t.starts_with('[') || t.starts_with("c(") || t.starts_with("C(") || t.starts_with('(')
4112        })
4113        .unwrap_or(false)
4114}
4115
4116/// Parse `knots=[k0, k1, ...]` (or `c(...)` / `(...)`) into explicit internal
4117/// knot positions. Returns `Ok(None)` when `knots` is absent or a scalar count
4118/// (handled by [`parse_ps_internal_knots`]); `Ok(Some(positions))` when it is a
4119/// non-empty numeric list; and an error for an empty or unparseable list.
4120fn parse_explicit_internal_knots(
4121    options: &BTreeMap<String, String>,
4122) -> Result<Option<Vec<f64>>, String> {
4123    if !knots_option_is_list(options) {
4124        return Ok(None);
4125    }
4126    let raw = options
4127        .get("knots")
4128        .expect("knots_option_is_list implies the key is present");
4129    let tokens = split_list_option(raw);
4130    if tokens.is_empty() {
4131        return Err(TermBuilderError::invalid_option(format!(
4132            "knots={raw} is an empty list; supply at least one internal knot position \
4133             (e.g. knots=[0.2, 0.5, 0.8]) or a scalar count (e.g. knots=8)"
4134        ))
4135        .to_string());
4136    }
4137    let mut positions = Vec::with_capacity(tokens.len());
4138    for tok in &tokens {
4139        let value = parse_numeric_expr(tok).map_err(|err| {
4140            TermBuilderError::invalid_option(format!(
4141                "knots list entry '{tok}' is not a numeric position: {err}"
4142            ))
4143            .to_string()
4144        })?;
4145        positions.push(value);
4146    }
4147    Ok(Some(positions))
4148}
4149
4150/// Resolve the `knot_placement=` option for an automatically generated knot
4151/// vector. Accepts `"uniform"` (the default, equal spacing on the data range)
4152/// and `"quantile"` (interior knots at empirical data quantiles, better for
4153/// skewed covariates). Unknown values are rejected so typos do not silently
4154/// fall back to uniform.
4155fn parse_knot_placement(
4156    options: &BTreeMap<String, String>,
4157) -> Result<crate::basis::BSplineKnotPlacement, String> {
4158    use crate::basis::BSplineKnotPlacement;
4159    match options
4160        .get("knot_placement")
4161        .or_else(|| options.get("knot-placement"))
4162        .or_else(|| options.get("knotplacement"))
4163    {
4164        None => Ok(BSplineKnotPlacement::Uniform),
4165        Some(raw) => match raw
4166            .trim()
4167            .trim_matches('"')
4168            .trim_matches('\'')
4169            .to_ascii_lowercase()
4170            .as_str()
4171        {
4172            "uniform" | "even" | "equal" => Ok(BSplineKnotPlacement::Uniform),
4173            "quantile" | "quantiles" | "data" | "empirical" => Ok(BSplineKnotPlacement::Quantile),
4174            other => Err(TermBuilderError::invalid_option(format!(
4175                "knot_placement={other} is not recognised; expected \"uniform\" or \"quantile\""
4176            ))
4177            .to_string()),
4178        },
4179    }
4180}
4181
4182/// Build the non-periodic 1D B-spline knot spec for the `ps`/`bspline` and
4183/// factor-smooth marginal paths, honoring (in priority order):
4184///   1. `knots=[...]` explicit internal positions  → [`BSplineKnotSpec::Provided`]
4185///   2. `knot_placement="quantile"`                 → [`BSplineKnotSpec::Automatic`]
4186///   3. uniform generation                          → [`BSplineKnotSpec::Generate`]
4187///
4188/// `data` is the covariate column (used to clamp explicit positions to the
4189/// observed range and to drive quantile placement); `n_knots` is the resolved
4190/// internal-knot count from [`parse_ps_internal_knots`] used for the automatic
4191/// strategies.
4192fn resolve_nonperiodic_bspline_knotspec(
4193    options: &BTreeMap<String, String>,
4194    data: ArrayView1<'_, f64>,
4195    data_range: (f64, f64),
4196    degree: usize,
4197    n_knots: usize,
4198) -> Result<BSplineKnotSpec, String> {
4199    use crate::basis::{BSplineKnotPlacement, clamped_knot_vector_from_internal_positions};
4200    if let Some(positions) = parse_explicit_internal_knots(options)? {
4201        if option_usize_any_strict(options, &["k", "basis_dim", "basis-dim", "basisdim"])?.is_some()
4202        {
4203            return Err(TermBuilderError::incompatible_config(
4204                "ps/bspline smooth: specify either explicit knots=[...] positions or \
4205                 k=<basis_dim> (not both); the basis size is fixed by the knot vector",
4206            )
4207            .to_string());
4208        }
4209        let knots = clamped_knot_vector_from_internal_positions(data_range, &positions, degree)
4210            .map_err(|e| e.to_string())?;
4211        return Ok(BSplineKnotSpec::Provided(knots));
4212    }
4213    match parse_knot_placement(options)? {
4214        BSplineKnotPlacement::Uniform => Ok(BSplineKnotSpec::Generate {
4215            data_range,
4216            num_internal_knots: n_knots,
4217        }),
4218        BSplineKnotPlacement::Quantile => {
4219            // Validate the column up-front so an unfittable request surfaces a
4220            // user-correctable error at parse time rather than deep in basis
4221            // construction. The same data drives the eventual quantile knots.
4222            crate::basis::auto_knot_vector_1d_quantile(data, n_knots, degree)
4223                .map_err(|e| e.to_string())?;
4224            Ok(BSplineKnotSpec::Automatic {
4225                num_internal_knots: Some(n_knots),
4226                placement: BSplineKnotPlacement::Quantile,
4227            })
4228        }
4229    }
4230}
4231
4232/// Reject unknown option keys with a focused error that names the term and
4233/// the offending key, plus suggests near-matches from the known-key list.
4234/// Without this, typos like `lengt_scale=0.1` or `nyu=5/2` are silently
4235/// dropped, the term uses the default, and the user has no idea why their
4236/// option had no effect.
4237pub fn validate_known_options(
4238    term_name: &str,
4239    options: &BTreeMap<String, String>,
4240    known: &[&str],
4241) -> Result<(), String> {
4242    let known_set: std::collections::BTreeSet<&&str> = known.iter().collect();
4243    for key in options.keys() {
4244        if !known_set.contains(&key.as_str()) {
4245            if term_name == "tensor" && is_tensor_k_axis_option_key(key) {
4246                continue;
4247            }
4248            // Suggest near-matches (substring or shared prefix ≥ 3).
4249            let key_l = key.to_ascii_lowercase();
4250            let mut suggestions: Vec<&str> = known
4251                .iter()
4252                .filter(|k| {
4253                    let kl = k.to_ascii_lowercase();
4254                    kl.contains(&key_l) || key_l.contains(&kl) || {
4255                        let n = kl
4256                            .chars()
4257                            .zip(key_l.chars())
4258                            .take_while(|(a, b)| a == b)
4259                            .count();
4260                        n >= 3
4261                    }
4262                })
4263                .copied()
4264                .collect();
4265            suggestions.sort_unstable();
4266            suggestions.dedup();
4267            let hint = if suggestions.is_empty() {
4268                String::new()
4269            } else {
4270                format!(" — did you mean one of [{}]?", suggestions.join(", "))
4271            };
4272            return Err(TermBuilderError::invalid_option(format!(
4273                "{term_name}() does not accept option `{key}`{hint}. Valid options: [{}]",
4274                {
4275                    let mut sorted = known.to_vec();
4276                    sorted.sort_unstable();
4277                    sorted.join(", ")
4278                }
4279            ))
4280            .to_string());
4281        }
4282    }
4283    Ok(())
4284}
4285
4286/// Private (engine-injected) option that caps the *default* spatial center
4287/// count for a secondary (distributional) predictor's smooth — see
4288/// `solver::fit_orchestration::apply_secondary_predictor_basis_parsimony` and #501.
4289///
4290/// It is deliberately NOT one of the user-facing count aliases recognised by
4291/// [`has_explicit_countwith_basis_alias`], so it never flips the spatial basis
4292/// onto the explicit (hard) center-placement strategy: the cap lowers the
4293/// *default* count while the `Auto` strategy is retained, so the count is still
4294/// softly reduced when the data can't support it.
4295pub const SECONDARY_CENTER_CAP_OPTION: &str = "__secondary_center_cap";
4296
4297/// Apply the secondary-predictor center cap to a *default* spatial center
4298/// count. A no-op when the cap option is absent (the common case) or when the
4299/// user supplied an explicit count (then `default_count` is ignored downstream
4300/// by [`parse_countwith_basis_alias`] anyway).
4301pub(crate) fn cap_default_spatial_centers(
4302    options: &BTreeMap<String, String>,
4303    default_count: usize,
4304) -> usize {
4305    match option_usize(options, SECONDARY_CENTER_CAP_OPTION) {
4306        Some(cap) => default_count.min(cap),
4307        None => default_count,
4308    }
4309}
4310
4311fn default_matern_center_count(n: usize, d: usize, planned_count: usize) -> usize {
4312    // #1074: the mgcv-sized basis cap (`k = 10·3^(d-1)`) was DELETED here too — it
4313    // masked the same over-sizing/under-penalization defect by shrinking the basis
4314    // rather than fixing the optimizer. The default now uses the generic n-scaling
4315    // plan. A small-n floor against a numerically-fragile two-column kernel block
4316    // is a legitimate degenerate guard and is kept. Explicit `k`/`centers` still
4317    // take full effect upstream.
4318    let low_n_floor = (d + 4).min(n);
4319    planned_count.max(low_n_floor).max(1)
4320}
4321
4322pub fn parse_countwith_basis_alias(
4323    options: &BTreeMap<String, String>,
4324    primarykey: &str,
4325    default_count: usize,
4326) -> Result<usize, String> {
4327    // Strict: reject unparseable values (e.g. `centers=many`, `centers=-1`,
4328    // `centers=1.5`) instead of silently dropping them and falling through
4329    // to the default. Without this the user gets the auto-inferred count
4330    // silently and never realizes their explicit option was ignored.
4331    let primary = option_usize_strict(options, primarykey)?;
4332    let basis_dim = option_usize_any_strict(
4333        options,
4334        &["k", "basis_dim", "basis-dim", "basisdim", "knots"],
4335    )?;
4336    if primary.is_some() && basis_dim.is_some() {
4337        return Err(TermBuilderError::incompatible_config(format!(
4338            "specify either {}=<count> or k=<basis_dim> (not both)",
4339            primarykey
4340        ))
4341        .to_string());
4342    }
4343    Ok(primary.or(basis_dim).unwrap_or(default_count))
4344}
4345
4346pub fn has_explicit_countwith_basis_alias(
4347    options: &BTreeMap<String, String>,
4348    primarykey: &str,
4349) -> bool {
4350    options.contains_key(primarykey)
4351        || ["k", "basis_dim", "basis-dim", "basisdim", "knots"]
4352            .iter()
4353            .any(|alias| options.contains_key(*alias))
4354}
4355
4356pub fn parse_cyclic_boundary(
4357    options: &BTreeMap<String, String>,
4358    minv: f64,
4359    maxv: f64,
4360) -> Result<OneDimensionalBoundary, String> {
4361    let cyclic = option_bool(options, "cyclic")
4362        .or_else(|| option_bool(options, "periodic"))
4363        .unwrap_or(false);
4364    if !cyclic {
4365        return Ok(OneDimensionalBoundary::Open);
4366    }
4367    let start = match option_numeric_expr(options, "period_start")? {
4368        Some(v) => v,
4369        None => option_numeric_expr(options, "start")?.unwrap_or(minv),
4370    };
4371    let end = match option_numeric_expr(options, "period_end")? {
4372        Some(v) => v,
4373        None => option_numeric_expr(options, "end")?.unwrap_or(maxv),
4374    };
4375    if end <= start {
4376        return Err(format!(
4377            "cyclic smooth requires period_end/end ({end}) > period_start/start ({start})"
4378        ));
4379    }
4380    Ok(OneDimensionalBoundary::Cyclic { start, end })
4381}
4382
4383/// Parse the periodic-uniform domain for a one-dimensional cyclic smooth.
4384///
4385/// Returns the `(domain_start, period)` pair derived from
4386/// `period_start` / `start`, `period_end` / `end`, falling back to the
4387/// data range `[minv, maxv)` when neither bound is provided. The period
4388/// must be strictly positive.
4389pub fn parse_periodic_domain_1d(
4390    options: &BTreeMap<String, String>,
4391    minv: f64,
4392    maxv: f64,
4393) -> Result<(f64, f64), String> {
4394    let start_opt = match option_numeric_expr(options, "period_start")? {
4395        Some(v) => Some(v),
4396        None => option_numeric_expr(options, "start")?,
4397    };
4398    let end_opt = match option_numeric_expr(options, "period_end")? {
4399        Some(v) => Some(v),
4400        None => option_numeric_expr(options, "end")?,
4401    };
4402    // Reject the pure data-range fallback. A B-spline periodic smooth that takes
4403    // its wrap from the observed [min, max] is sample-dependent and silently
4404    // wrong: uniform draws on a true period of 2π land on [ε, 2π−ε], so using
4405    // (max−min) as the period seams the curve with an off-by-ε discontinuity and
4406    // the fit drifts with the sample. (Unlike the radial closed-lattice Duchon
4407    // path, whose centers DO tile a full period, so its span-derive is exact —
4408    // see `parse_periodic_axes_option`.) Require the caller to name the period
4409    // explicitly via `period=`/`period_end`. The end is only defaulted to `maxv`
4410    // when a `period_start`/`start` was given (a half-open declaration); a bare
4411    // periodic smooth with neither bound is an error.
4412    if end_opt.is_none() && start_opt.is_none() {
4413        return Err(
4414            "periodic B-spline smooth requires an explicit period: pass period=<value> \
4415             (e.g. period=2*pi) or period_start=/period_end=. Deriving the period from the \
4416             observed data range is sample-dependent and produces an off-by-ε seam, so it is \
4417             not inferred."
4418                .to_string(),
4419        );
4420    }
4421    let start = start_opt.unwrap_or(minv);
4422    let end = end_opt.unwrap_or(maxv);
4423    if !(start.is_finite() && end.is_finite()) {
4424        return Err(format!(
4425            "periodic smooth domain requires finite endpoints, got ({start}, {end})"
4426        ));
4427    }
4428    if end <= start {
4429        return Err(format!(
4430            "periodic smooth requires period_end/end ({end}) > period_start/start ({start})"
4431        ));
4432    }
4433    Ok((start, end - start))
4434}
4435
4436fn parse_matern_nu(raw: &str) -> Result<MaternNu, String> {
4437    let trimmed = raw.trim();
4438    let lowered = trimmed.to_ascii_lowercase();
4439    match lowered.as_str() {
4440        "1/2" | "0.5" | "half" => return Ok(MaternNu::Half),
4441        "3/2" | "1.5" => return Ok(MaternNu::ThreeHalves),
4442        "5/2" | "2.5" => return Ok(MaternNu::FiveHalves),
4443        "7/2" | "3.5" => return Ok(MaternNu::SevenHalves),
4444        "9/2" | "4.5" => return Ok(MaternNu::NineHalves),
4445        _ => {}
4446    }
4447
4448    let value = if let Some((num, den)) = trimmed.split_once('/') {
4449        let num = num
4450            .trim()
4451            .parse::<f64>()
4452            .map_err(|err| format!("{}: {err}", unsupported_matern_nu_message(raw)))?;
4453        let den = den
4454            .trim()
4455            .parse::<f64>()
4456            .map_err(|err| format!("{}: {err}", unsupported_matern_nu_message(raw)))?;
4457        if den == 0.0 || !num.is_finite() || !den.is_finite() {
4458            return Err(unsupported_matern_nu_message(raw));
4459        }
4460        num / den
4461    } else {
4462        trimmed
4463            .parse::<f64>()
4464            .map_err(|err| format!("{}: {err}", unsupported_matern_nu_message(raw)))?
4465    };
4466
4467    const TOL: f64 = 1e-12;
4468    if (value - 0.5).abs() <= TOL {
4469        Ok(MaternNu::Half)
4470    } else if (value - 1.5).abs() <= TOL {
4471        Ok(MaternNu::ThreeHalves)
4472    } else if (value - 2.5).abs() <= TOL {
4473        Ok(MaternNu::FiveHalves)
4474    } else if (value - 3.5).abs() <= TOL {
4475        Ok(MaternNu::SevenHalves)
4476    } else if (value - 4.5).abs() <= TOL {
4477        Ok(MaternNu::NineHalves)
4478    } else {
4479        Err(unsupported_matern_nu_message(raw))
4480    }
4481}
4482
4483fn unsupported_matern_nu_message(raw: &str) -> String {
4484    TermBuilderError::unsupported_feature(format!(
4485        "unsupported Matern nu '{raw}'; supported half-integer values are 1/2, 3/2, 5/2, 7/2, and 9/2"
4486    ))
4487    .to_string()
4488}
4489
4490#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
4491pub enum DuchonPowerPolicy {
4492    Explicit(f64),
4493    /// No explicit `power=` given: defer to the cubic structural default, which
4494    /// the builder resolves dimension-aware as `s = (d − 1)/2` (so `φ(r) = r³`
4495    /// in every dimension). There is no triple-operator minimum any more.
4496    CubicStructuralDefault,
4497}
4498
4499pub fn parse_duchon_power_policy(
4500    options: &BTreeMap<String, String>,
4501) -> Result<DuchonPowerPolicy, String> {
4502    if let Some(raw_nu) = options.get("nu") {
4503        return Err(TermBuilderError::incompatible_config(format!(
4504            "Duchon smooths use power=<number>, not nu='{}'. Use power=1.5, power=2, etc.",
4505            raw_nu
4506        ))
4507        .to_string());
4508    }
4509    match options.get("power") {
4510        Some(raw) => {
4511            let value = raw.parse::<f64>().map_err(|err| {
4512                TermBuilderError::invalid_option(format!(
4513                    "invalid Duchon power '{}'; expected a non-negative number such as power=1.5 or power=2: {}",
4514                    raw, err
4515                ))
4516                .to_string()
4517            })?;
4518            if !value.is_finite() || value < 0.0 {
4519                return Err(TermBuilderError::invalid_option(format!(
4520                    "invalid Duchon power '{}'; expected a finite non-negative number such as power=1.5 or power=2",
4521                    raw
4522                ))
4523                .to_string());
4524            }
4525            Ok(DuchonPowerPolicy::Explicit(value))
4526        }
4527        None => Ok(DuchonPowerPolicy::CubicStructuralDefault),
4528    }
4529}
4530
4531pub fn parse_duchon_power(options: &BTreeMap<String, String>) -> Result<f64, String> {
4532    match parse_duchon_power_policy(options)? {
4533        DuchonPowerPolicy::Explicit(power) => Ok(power),
4534        // Context-free placeholder: the bare option parser has no column count,
4535        // so it cannot compute the dimension-aware cubic power `s = (d − 1)/2`.
4536        // The dimension-aware resolution happens later in `build_smooth_basis`;
4537        // this 1.5 is only a stand-in for callers that need a concrete number
4538        // without data context (e.g. round-trip parser tests).
4539        DuchonPowerPolicy::CubicStructuralDefault => Ok(1.5),
4540    }
4541}
4542
4543pub fn parse_duchon_order(
4544    options: &BTreeMap<String, String>,
4545) -> Result<DuchonNullspaceOrder, String> {
4546    match options.get("order") {
4547        // Structural cubic Duchon is affine-by-default: an unspecified order is
4548        // the `Linear` (constant + linear) null space, matching the magic
4549        // default. An explicit `order=0` still selects the constant-only space.
4550        None => Ok(DuchonNullspaceOrder::Linear),
4551        Some(raw) => match raw.parse::<usize>() {
4552            Ok(0) => Ok(DuchonNullspaceOrder::Zero),
4553            Ok(1) => Ok(DuchonNullspaceOrder::Linear),
4554            Ok(other) => Ok(DuchonNullspaceOrder::Degree(other)),
4555            Err(_) => Err(TermBuilderError::invalid_option(format!(
4556                "invalid Duchon order '{}'; expected a non-negative integer such as order=0, order=1, or order=2",
4557                raw
4558            ))
4559            .to_string()),
4560        },
4561    }
4562}
4563
4564fn parse_matern_identifiability(
4565    options: &BTreeMap<String, String>,
4566) -> Result<MaternIdentifiability, TermBuilderError> {
4567    let Some(raw) = options.get("identifiability").map(String::as_str) else {
4568        return Ok(MaternIdentifiability::default());
4569    };
4570    match raw.trim().to_ascii_lowercase().as_str() {
4571        "none" => Ok(MaternIdentifiability::None),
4572        "sum_tozero" | "sum-to-zero" | "center_sum_tozero" | "center-sum-to-zero" | "centered" => {
4573            Ok(MaternIdentifiability::CenterSumToZero)
4574        }
4575        "linear" | "center_linear_orthogonal" | "center-linear-orthogonal" => {
4576            Ok(MaternIdentifiability::CenterLinearOrthogonal)
4577        }
4578        other => Err(TermBuilderError::unsupported_feature(format!(
4579            "invalid Matérn identifiability '{other}'; expected one of: none, sum_tozero, linear"
4580        ))),
4581    }
4582}
4583
4584fn parse_spatial_identifiability(
4585    options: &BTreeMap<String, String>,
4586) -> Result<SpatialIdentifiability, TermBuilderError> {
4587    let Some(raw) = options.get("identifiability").map(String::as_str) else {
4588        return Ok(SpatialIdentifiability::default());
4589    };
4590    match raw.trim().to_ascii_lowercase().as_str() {
4591        "none" => Ok(SpatialIdentifiability::None),
4592        "orthogonal"
4593        | "orthogonal_to_parametric"
4594        | "orthogonal-to-parametric"
4595        | "parametric_orthogonal" => Ok(SpatialIdentifiability::OrthogonalToParametric),
4596        "frozen" => Err(TermBuilderError::unsupported_feature(
4597            "spatial identifiability 'frozen' is internal-only; use none or orthogonal_to_parametric",
4598        )),
4599        other => Err(TermBuilderError::unsupported_feature(format!(
4600            "invalid spatial identifiability '{other}'; expected one of: none, orthogonal_to_parametric"
4601        ))),
4602    }
4603}
4604
4605#[cfg(test)]
4606mod tests {
4607    use super::*;
4608    use crate::inference::formula_dsl::parse_formula;
4609    use gam_data::{DataSchema, SchemaColumn};
4610    use ndarray::Array2;
4611    use std::collections::BTreeMap;
4612
4613    fn continuous_dataset(headers: &[&str], rows: Vec<Vec<f64>>) -> Dataset {
4614        let nrows = rows.len();
4615        let ncols = headers.len();
4616        let values = Array2::from_shape_vec(
4617            (nrows, ncols),
4618            rows.into_iter().flat_map(|row| row.into_iter()).collect(),
4619        )
4620        .expect("rectangular test data");
4621        Dataset {
4622            headers: headers.iter().map(|name| name.to_string()).collect(),
4623            values,
4624            schema: DataSchema {
4625                columns: headers
4626                    .iter()
4627                    .map(|name| SchemaColumn {
4628                        name: name.to_string(),
4629                        kind: ColumnKindTag::Continuous,
4630                        levels: vec![],
4631                    })
4632                    .collect(),
4633            },
4634            column_kinds: vec![ColumnKindTag::Continuous; ncols],
4635        }
4636    }
4637
4638    fn factor_dataset() -> Dataset {
4639        let rows = (0..24)
4640            .map(|i| {
4641                let x = i as f64 / 23.0;
4642                let g = (i % 2) as f64;
4643                vec![x + g, x, g]
4644            })
4645            .collect::<Vec<_>>();
4646        Dataset {
4647            headers: vec!["y".into(), "x".into(), "g".into()],
4648            values: Array2::from_shape_vec(
4649                (rows.len(), 3),
4650                rows.into_iter().flat_map(|row| row.into_iter()).collect(),
4651            )
4652            .expect("rectangular factor test data"),
4653            schema: DataSchema {
4654                columns: vec![
4655                    SchemaColumn {
4656                        name: "y".into(),
4657                        kind: ColumnKindTag::Continuous,
4658                        levels: vec![],
4659                    },
4660                    SchemaColumn {
4661                        name: "x".into(),
4662                        kind: ColumnKindTag::Continuous,
4663                        levels: vec![],
4664                    },
4665                    SchemaColumn {
4666                        name: "g".into(),
4667                        kind: ColumnKindTag::Categorical,
4668                        levels: vec!["a".into(), "b".into()],
4669                    },
4670                ],
4671            },
4672            column_kinds: vec![
4673                ColumnKindTag::Continuous,
4674                ColumnKindTag::Continuous,
4675                ColumnKindTag::Categorical,
4676            ],
4677        }
4678    }
4679
4680    /// #1378: the DEFAULT univariate `s(x, bs="tp")` must build a *modest*
4681    /// mgcv-sized basis, not the n-scaled spatial heuristic. The oversized
4682    /// default basis left the two-penalty REML ρ-surface with a flat valley
4683    /// whose optimizer landing point depended on row order, breaking
4684    /// row-permutation invariance. Pin the default 1-D center count so a
4685    /// regression that reinstates the n-scaled default trips here, fast, with
4686    /// no fit/optimizer in the loop.
4687    #[test]
4688    fn default_univariate_thinplate_basis_dim_is_modest() {
4689        // n = 300 (the #1378 scenario): the n-scaled spatial heuristic would
4690        // request ~75 centers here. The modest default must stay near k = 10.
4691        let n = 300usize;
4692        let rows: Vec<Vec<f64>> = (0..n)
4693            .map(|i| {
4694                let x = -3.0 + 6.0 * (i as f64) / ((n - 1) as f64);
4695                vec![x.sin(), x]
4696            })
4697            .collect();
4698        let ds = continuous_dataset(&["y", "x"], rows);
4699
4700        let mut options = BTreeMap::new();
4701        options.insert("bs".to_string(), "tp".to_string());
4702
4703        let mut notes = Vec::new();
4704        let basis = build_smooth_basis(
4705            SmoothKind::S,
4706            &["x".to_string()],
4707            &[1],
4708            &options,
4709            &ds,
4710            &mut notes,
4711            &ResourcePolicy::default_library(),
4712            1,
4713        )
4714        .expect("build default univariate tp smooth");
4715
4716        let centers = match &basis {
4717            SmoothBasisSpec::ThinPlate { spec, .. } => match &spec.center_strategy {
4718                CenterStrategy::Auto(inner) => match inner.as_ref() {
4719                    CenterStrategy::FarthestPoint { num_centers }
4720                    | CenterStrategy::EqualMass { num_centers }
4721                    | CenterStrategy::EqualMassCovarRepresentative { num_centers }
4722                    | CenterStrategy::KMeans { num_centers, .. } => *num_centers,
4723                    other => panic!("unexpected auto inner center strategy: {other:?}"),
4724                },
4725                CenterStrategy::FarthestPoint { num_centers }
4726                | CenterStrategy::EqualMass { num_centers }
4727                | CenterStrategy::EqualMassCovarRepresentative { num_centers }
4728                | CenterStrategy::KMeans { num_centers, .. } => *num_centers,
4729                other => panic!("unexpected center strategy: {other:?}"),
4730            },
4731            other => panic!("expected ThinPlate basis, got {other:?}"),
4732        };
4733
4734        // #1074: the mgcv-sized basis-dim ceiling assertion was removed with the
4735        // cap it tested. The default tp basis is now n-scaled; we only assert it
4736        // still builds a usable basis.
4737        assert!(
4738            centers >= 1,
4739            "default univariate tp must still build a usable basis (centers={centers})",
4740        );
4741    }
4742
4743    /// gam#1629: a default 2-D `matern(x1, x2)` (no explicit `length_scale`)
4744    /// must leave the length-scale at the `0.0` auto sentinel — NOT the full
4745    /// data diameter — so the planner's `auto_init_length_scale_in_place` seeds
4746    /// it on the wiggly/resolving side (`max_range / sqrt(n)`), the same regime
4747    /// thin-plate uses. The previous `default_matern_length_scale` returned the
4748    /// full diameter, which is non-zero, so the `0.0`-gated auto-init was a
4749    /// no-op and the κ-optimizer started in the over-smoothed corner and parked
4750    /// there (truth-RMSE ~6× worse than thin-plate/tensor on identical
4751    /// high-frequency 2-D surfaces, insensitive to `k`). This pins the corrected
4752    /// seed geometry without a fit/optimizer in the loop.
4753    #[test]
4754    fn default_matern_2d_seeds_resolving_length_scale_not_overscaled_diameter() {
4755        // A fine multi-frequency 2-D grid (the #1629 reproduction shape): the
4756        // data diameter is O(1.4) in each axis; the resolving seed must be far
4757        // smaller than the diameter so high-frequency structure stays reachable.
4758        let side = 24usize; // n = 576
4759        let mut rows: Vec<Vec<f64>> = Vec::with_capacity(side * side);
4760        for i in 0..side {
4761            for j in 0..side {
4762                let x1 = i as f64 / (side - 1) as f64; // [0, 1]
4763                let x2 = j as f64 / (side - 1) as f64; // [0, 1]
4764                let y = (6.0 * x1).sin() * (6.0 * x2).cos();
4765                rows.push(vec![y, x1, x2]);
4766            }
4767        }
4768        let n = rows.len();
4769        let ds = continuous_dataset(&["y", "x1", "x2"], rows);
4770
4771        let mut options = BTreeMap::new();
4772        options.insert("bs".to_string(), "gp".to_string()); // gp ⇒ Matérn
4773        let mut notes = Vec::new();
4774        let mut basis = build_smooth_basis(
4775            SmoothKind::S,
4776            &["x1".to_string(), "x2".to_string()],
4777            &[1, 2],
4778            &options,
4779            &ds,
4780            &mut notes,
4781            &ResourcePolicy::default_library(),
4782            1,
4783        )
4784        .expect("build default 2-D matern smooth");
4785
4786        // (1) The builder must emit the auto sentinel, not a baked-in diameter.
4787        let (feature_cols, seeded_length_scale) = match &basis {
4788            SmoothBasisSpec::Matern {
4789                feature_cols, spec, ..
4790            } => (feature_cols.clone(), spec.length_scale),
4791            other => panic!("expected Matern basis, got {other:?}"),
4792        };
4793        assert_eq!(
4794            seeded_length_scale, 0.0,
4795            "default matern() must leave length_scale at the 0.0 auto sentinel \
4796             (got {seeded_length_scale}); a non-zero diameter default re-enters the \
4797             over-smoothed basin and disables the planner's wiggly-side auto-init",
4798        );
4799
4800        // (2) After the shared auto-init runs, the realized length-scale must
4801        // land in the resolving regime: `max_range / sqrt(n)`, far below the
4802        // data diameter. This is the seed the κ-optimizer starts REML from.
4803        crate::smooth::auto_init_length_scale_in_basis(ds.values.view(), &mut basis);
4804        let realized = match &basis {
4805            SmoothBasisSpec::Matern { spec, .. } => spec.length_scale,
4806            other => panic!("expected Matern basis after auto-init, got {other:?}"),
4807        };
4808        let expected =
4809            crate::smooth::auto_initial_length_scale(ds.values.view(), &feature_cols);
4810        assert!(
4811            (realized - expected).abs() <= 1e-12,
4812            "auto-init must seed the wiggly-side length scale max_range/sqrt(n) \
4813             (expected {expected}, got {realized})",
4814        );
4815
4816        // Sanity: the resolving seed is well below the per-axis range (≈1.0).
4817        // Before the fix the seed was the full diameter (≈√2 ≈ 1.414); the
4818        // resolving seed here is ≈ 1.0 / sqrt(576) ≈ 0.042, ~30× smaller.
4819        let max_range = 1.0_f64; // each axis spans [0, 1]
4820        assert!(
4821            realized < max_range / 4.0,
4822            "matern seed length_scale {realized} must be in the resolving regime, \
4823             not the over-smoothed diameter corner (n={n}, max_range≈{max_range})",
4824        );
4825    }
4826
4827    fn inferred_tensor_basis_product(ds: &Dataset) -> usize {
4828        let parsed = parse_formula("y ~ te(theta, h)").expect("parse tensor formula");
4829        let col_map = ds.column_map();
4830        let mut notes = Vec::new();
4831        let terms = build_termspec(
4832            &parsed.terms,
4833            ds,
4834            &col_map,
4835            &mut notes,
4836            &ResourcePolicy::default_library(),
4837        )
4838        .expect("build tensor termspec");
4839        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
4840            panic!("expected tensor smooth");
4841        };
4842        spec.marginalspecs
4843            .iter()
4844            .map(|marginal| match marginal.knotspec {
4845                BSplineKnotSpec::Generate {
4846                    num_internal_knots, ..
4847                } => num_internal_knots + marginal.degree + 1,
4848                BSplineKnotSpec::PeriodicUniform { num_basis, .. } => num_basis,
4849                BSplineKnotSpec::Automatic {
4850                    num_internal_knots: Some(num_internal_knots),
4851                    ..
4852                } => num_internal_knots + marginal.degree + 1,
4853                BSplineKnotSpec::Automatic {
4854                    num_internal_knots: None,
4855                    ..
4856                } => panic!("test helper cannot infer automatic knot count"),
4857                BSplineKnotSpec::Provided(ref knots) => {
4858                    knots.len().saturating_sub(marginal.degree + 1)
4859                }
4860                // cr basis dimension equals the knot count (no degree offset).
4861                BSplineKnotSpec::NaturalCubicRegression { ref knots } => knots.len(),
4862            })
4863            .product()
4864    }
4865
4866    fn tensor_margin_basis_sizes(ds: &Dataset, formula: &str) -> Vec<usize> {
4867        let parsed = parse_formula(formula).expect("parse tensor formula");
4868        let col_map = ds.column_map();
4869        let mut notes = Vec::new();
4870        let terms = build_termspec(
4871            &parsed.terms,
4872            ds,
4873            &col_map,
4874            &mut notes,
4875            &ResourcePolicy::default_library(),
4876        )
4877        .expect("build tensor termspec");
4878        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
4879            panic!("expected tensor smooth");
4880        };
4881        spec.marginalspecs
4882            .iter()
4883            .map(|marginal| match marginal.knotspec {
4884                BSplineKnotSpec::Generate {
4885                    num_internal_knots, ..
4886                } => num_internal_knots + marginal.degree + 1,
4887                BSplineKnotSpec::PeriodicUniform { num_basis, .. } => num_basis,
4888                BSplineKnotSpec::Automatic {
4889                    num_internal_knots: Some(num_internal_knots),
4890                    ..
4891                } => num_internal_knots + marginal.degree + 1,
4892                BSplineKnotSpec::Automatic {
4893                    num_internal_knots: None,
4894                    ..
4895                } => panic!("test helper cannot infer automatic knot count"),
4896                BSplineKnotSpec::Provided(ref knots) => {
4897                    knots.len().saturating_sub(marginal.degree + 1)
4898                }
4899                // cr basis dimension equals the knot count (no degree offset).
4900                BSplineKnotSpec::NaturalCubicRegression { ref knots } => knots.len(),
4901            })
4902            .collect()
4903    }
4904
4905    #[test]
4906    fn validate_known_options_lists_valid_option_names_for_unknown_parameter() {
4907        let mut options = BTreeMap::new();
4908        options.insert("lengt_scale".to_string(), "0.25".to_string());
4909        let err = validate_known_options(
4910            "matern",
4911            &options,
4912            &["type", "bs", "length_scale", "centers", "k", "nu"],
4913        )
4914        .expect_err("unknown smooth option should be rejected");
4915        assert!(
4916            err.contains("matern() does not accept option `lengt_scale`"),
4917            "error should name the invalid option, got: {err}"
4918        );
4919        assert!(
4920            err.contains("did you mean one of [length_scale]"),
4921            "error should suggest the closest valid option, got: {err}"
4922        );
4923        assert!(
4924            err.contains("Valid options: ["),
4925            "error should list valid option names, got: {err}"
4926        );
4927    }
4928
4929    #[test]
4930    fn tensor_k_accepts_square_bracket_per_margin_list() {
4931        let ds = continuous_dataset(
4932            &["y", "x", "z"],
4933            (0..40)
4934                .map(|i| {
4935                    let x = i as f64 / 39.0;
4936                    let z = ((i * 7) % 40) as f64 / 39.0;
4937                    vec![x.sin() + z.cos(), x, z]
4938                })
4939                .collect(),
4940        );
4941
4942        assert_eq!(
4943            tensor_margin_basis_sizes(&ds, "y ~ te(x, z, k=[5, 6])"),
4944            vec![5, 6],
4945            "square-bracket k lists should materialize the requested per-margin values"
4946        );
4947    }
4948
4949    /// #1776 / #1752: a bare doubly-cyclic tensor `te(x, z, bs=c('cc','cc'))`
4950    /// with NO explicit `period=` must build — each cyclic margin wraps on its
4951    /// own observed `[min, max]` data span (mirroring mgcv's `bs="cc"` and the
4952    /// 1-D cyclic fallback), instead of hard-erroring "periodic but requires an
4953    /// explicit period". The periodic-radial refactor (c8c3192fa) replaced that
4954    /// fallback with an unconditional `period=`-required error and orphaned the
4955    /// `margin_is_cc` binding that drives it (the #1776 dead-binding `-D
4956    /// warnings` build break). This pins the restored data-range derivation so a
4957    /// regression that drops the `None if margin_is_cc` branch trips here, fast,
4958    /// with no fit/optimizer in the loop.
4959    #[test]
4960    fn bare_doubly_cyclic_tensor_derives_period_from_data_range_1776() {
4961        let ds = continuous_dataset(
4962            &["y", "x", "z"],
4963            (0..40)
4964                .map(|i| {
4965                    let x = i as f64 / 39.0;
4966                    let z = ((i * 7) % 40) as f64 / 39.0;
4967                    vec![x.sin() + z.cos(), x, z]
4968                })
4969                .collect(),
4970        );
4971
4972        let parsed = parse_formula("y ~ te(x, z, bs=c('cc','cc'))")
4973            .expect("parse doubly-cyclic tensor formula");
4974        let col_map = ds.column_map();
4975        let mut notes = Vec::new();
4976        // Must NOT hard-error: the bare cyclic margins derive their period from
4977        // the observed data range (the restored #1752 fallback).
4978        let terms = build_termspec(
4979            &parsed.terms,
4980            &ds,
4981            &col_map,
4982            &mut notes,
4983            &ResourcePolicy::default_library(),
4984        )
4985        .expect(
4986            "bare cc-cc tensor must build via the data-range period fallback (#1776/#1752), \
4987             not hard-error on a missing explicit period",
4988        );
4989        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
4990            panic!("expected tensor smooth");
4991        };
4992        assert_eq!(
4993            spec.marginalspecs.len(),
4994            2,
4995            "te(x, z) builds exactly two tensor margins"
4996        );
4997        for (axis, marginal) in spec.marginalspecs.iter().enumerate() {
4998            assert!(
4999                matches!(marginal.knotspec, BSplineKnotSpec::PeriodicUniform { .. }),
5000                "cyclic margin {axis} must build a periodic (wrapped) knotspec from the \
5001                 data range, got {:?}",
5002                marginal.knotspec
5003            );
5004        }
5005    }
5006
5007    #[test]
5008    fn parse_cylinder_periodic_options_match_requested_forms() {
5009        let mut opts = BTreeMap::new();
5010        opts.insert("periodic".to_string(), "[0]".to_string());
5011        opts.insert("period".to_string(), "[2*pi, None]".to_string());
5012        let axes = parse_periodic_axes(&opts, 2).expect("axes");
5013        let periods = parse_periods(&opts, &axes).expect("periods");
5014        assert_eq!(axes, vec![true, false]);
5015        assert!((periods[0].unwrap() - 2.0 * std::f64::consts::PI).abs() < 1e-12);
5016        assert_eq!(periods[1], None);
5017
5018        let mut boundary_opts = BTreeMap::new();
5019        boundary_opts.insert(
5020            "boundary".to_string(),
5021            "['periodic', 'natural']".to_string(),
5022        );
5023        boundary_opts.insert("period".to_string(), "[2*pi, None]".to_string());
5024        let boundary_axes = parse_periodic_axes(&boundary_opts, 2).expect("boundary axes");
5025        let boundary_periods =
5026            parse_periods(&boundary_opts, &boundary_axes).expect("boundary periods");
5027        assert_eq!(boundary_axes, vec![true, false]);
5028        assert!((boundary_periods[0].unwrap() - 2.0 * std::f64::consts::PI).abs() < 1e-12);
5029        assert_eq!(boundary_periods[1], None);
5030
5031        let mut unicode_opts = BTreeMap::new();
5032        unicode_opts.insert("periodic".to_string(), "[0,1]".to_string());
5033        unicode_opts.insert("period".to_string(), "[2π, τ]".to_string());
5034        let unicode_axes = parse_periodic_axes(&unicode_opts, 2).expect("unicode axes");
5035        let unicode_periods = parse_periods(&unicode_opts, &unicode_axes).expect("unicode periods");
5036        assert_eq!(unicode_axes, vec![true, true]);
5037        assert!((unicode_periods[0].unwrap() - 2.0 * std::f64::consts::PI).abs() < 1e-12);
5038        assert!((unicode_periods[1].unwrap() - std::f64::consts::TAU).abs() < 1e-12);
5039    }
5040
5041    #[test]
5042    fn parse_single_axis_periodic_zero_as_axis_not_false() {
5043        let mut opts = BTreeMap::new();
5044        opts.insert("periodic".to_string(), "[0]".to_string());
5045        opts.insert("period".to_string(), "2*pi".to_string());
5046        opts.insert("origin".to_string(), "0".to_string());
5047        let axes = parse_periodic_axes(&opts, 1).expect("axes");
5048        let periods = parse_periods(&opts, &axes).expect("periods");
5049        let origins = parse_period_origins(&opts, &axes).expect("origins");
5050        assert_eq!(axes, vec![true]);
5051        assert!((periods[0].unwrap() - 2.0 * std::f64::consts::PI).abs() < 1e-12);
5052        assert_eq!(origins[0], Some(0.0));
5053    }
5054
5055    #[test]
5056    fn one_dimensional_bspline_accepts_boundary_periodic() {
5057        let ds = continuous_dataset(
5058            &["y", "theta"],
5059            (0..16)
5060                .map(|i| {
5061                    let theta = std::f64::consts::TAU * i as f64 / 16.0;
5062                    vec![theta.sin(), theta]
5063                })
5064                .collect(),
5065        );
5066        let parsed = parse_formula("y ~ s(theta, boundary=periodic, period=2*pi, origin=0, k=8)")
5067            .expect("parse");
5068        let col_map = ds.column_map();
5069        let mut notes = Vec::new();
5070        let terms = build_termspec(
5071            &parsed.terms,
5072            &ds,
5073            &col_map,
5074            &mut notes,
5075            &gam_runtime::resource::ResourcePolicy::default_library(),
5076        )
5077        .expect("periodic boundary should build");
5078        let SmoothBasisSpec::BSpline1D { spec, .. } = &terms.smooth_terms[0].basis else {
5079            panic!("expected 1D B-spline");
5080        };
5081        assert!(matches!(
5082            &spec.knotspec,
5083            BSplineKnotSpec::PeriodicUniform {
5084                data_range,
5085                num_basis: 8
5086            } if *data_range == (0.0, std::f64::consts::TAU)
5087        ));
5088    }
5089
5090    #[test]
5091    fn univariate_smooth_accepts_mgcv_cubic_regression_aliases() {
5092        let ds = continuous_dataset(
5093            &["y", "x"],
5094            (0..32)
5095                .map(|i| {
5096                    let x = i as f64 / 31.0;
5097                    vec![x * x, x]
5098                })
5099                .collect(),
5100        );
5101        let col_map = ds.column_map();
5102
5103        for (selector, expect_double_penalty) in [("cr", false), ("cs", true)] {
5104            let formula = format!("y ~ s(x, bs='{selector}')");
5105            let parsed = parse_formula(&formula).expect("parse cr/cs smooth");
5106            let mut notes = Vec::new();
5107            let terms = build_termspec(
5108                &parsed.terms,
5109                &ds,
5110                &col_map,
5111                &mut notes,
5112                &gam_runtime::resource::ResourcePolicy::default_library(),
5113            )
5114            .unwrap_or_else(|err| panic!("bs='{selector}' must build a 1-D smooth, got: {err:?}"));
5115            let SmoothBasisSpec::BSpline1D { spec, .. } = &terms.smooth_terms[0].basis else {
5116                panic!(
5117                    "bs='{selector}' must lower to a BSpline1D; got {:?}",
5118                    terms.smooth_terms[0].basis
5119                );
5120            };
5121            assert_eq!(
5122                spec.double_penalty, expect_double_penalty,
5123                "bs='{selector}' must default double_penalty to mgcv's convention \
5124                 (cr=no-shrinkage, cs=shrinkage); got double_penalty={}",
5125                spec.double_penalty
5126            );
5127        }
5128    }
5129
5130    #[test]
5131    fn univariate_ps_small_k_degree_reduces_through_build(/* gam#1130 */) {
5132        // mgcv accepts `s(x, bs="ps", k=3)` (and the default cubic-regression
5133        // `s(x, k=3)`) by silently reducing the cubic basis to a quadratic.
5134        // The univariate ps/bspline build path used to reject this with
5135        // "k too small for degree 3"; it must now lower to a degree-2 basis
5136        // with zero internal knots (num_basis = k = 3), matching the te(...)
5137        // margin behaviour fixed in b75f55a91. Verified across the ps alias
5138        // and the default (cr) selector that both route through
5139        // parse_ps_internal_knots.
5140        let ds = continuous_dataset(
5141            &["y", "x"],
5142            (0..32)
5143                .map(|i| {
5144                    let x = i as f64 / 31.0;
5145                    vec![x * x, x]
5146                })
5147                .collect(),
5148        );
5149        let col_map = ds.column_map();
5150
5151        for formula in ["y ~ s(x, bs='ps', k=3)", "y ~ s(x, k=3)"] {
5152            let parsed = parse_formula(formula).expect("parse small-k ps/cr smooth");
5153            let mut notes = Vec::new();
5154            let terms = build_termspec(
5155                &parsed.terms,
5156                &ds,
5157                &col_map,
5158                &mut notes,
5159                &gam_runtime::resource::ResourcePolicy::default_library(),
5160            )
5161            .unwrap_or_else(|err| {
5162                panic!("`{formula}` must degree-reduce, not error; got: {err:?}")
5163            });
5164            let SmoothBasisSpec::BSpline1D { spec, .. } = &terms.smooth_terms[0].basis else {
5165                panic!(
5166                    "`{formula}` must lower to a BSpline1D; got {:?}",
5167                    terms.smooth_terms[0].basis
5168                );
5169            };
5170            assert_eq!(
5171                spec.degree, 2,
5172                "`{formula}` must drop the cubic default to a quadratic basis"
5173            );
5174            let num_internal = match &spec.knotspec {
5175                BSplineKnotSpec::Generate {
5176                    num_internal_knots, ..
5177                } => *num_internal_knots,
5178                BSplineKnotSpec::Automatic {
5179                    num_internal_knots: Some(n),
5180                    ..
5181                } => *n,
5182                other => panic!("`{formula}` unexpected knotspec: {other:?}"),
5183            };
5184            assert_eq!(
5185                num_internal, 0,
5186                "`{formula}` must have zero internal knots (num_basis = k = 3)"
5187            );
5188            // Resulting basis dimension is num_internal + degree + 1 = 3 = k.
5189            assert!(
5190                spec.penalty_order >= 1 && spec.penalty_order <= spec.degree,
5191                "`{formula}` penalty_order {} must satisfy 1 <= order <= degree={}",
5192                spec.penalty_order,
5193                spec.degree
5194            );
5195        }
5196    }
5197
5198    #[test]
5199    fn formula_shape_constraint_round_trips_and_rejects_bogus() {
5200        let ds = continuous_dataset(
5201            &["y", "x"],
5202            (0..32)
5203                .map(|i| {
5204                    let x = i as f64 / 31.0;
5205                    vec![x * x, x]
5206                })
5207                .collect(),
5208        );
5209        let col_map = ds.column_map();
5210
5211        let parsed =
5212            parse_formula("y ~ s(x, shape=monotone_increasing)").expect("parse monotone smooth");
5213        let mut notes = Vec::new();
5214        let terms = build_termspec(
5215            &parsed.terms,
5216            &ds,
5217            &col_map,
5218            &mut notes,
5219            &gam_runtime::resource::ResourcePolicy::default_library(),
5220        )
5221        .expect("monotone smooth should build");
5222        assert_eq!(
5223            terms.smooth_terms[0].shape,
5224            ShapeConstraint::MonotoneIncreasing
5225        );
5226
5227        let parsed_bad = parse_formula("y ~ s(x, shape=bogus)").expect("parse bogus shape");
5228        let mut notes_bad = Vec::new();
5229        let err = build_termspec(
5230            &parsed_bad.terms,
5231            &ds,
5232            &col_map,
5233            &mut notes_bad,
5234            &gam_runtime::resource::ResourcePolicy::default_library(),
5235        )
5236        .expect_err("bogus shape must error");
5237        assert!(
5238            format!("{err:?}").contains("unknown shape constraint"),
5239            "got: {err:?}"
5240        );
5241    }
5242
5243    #[test]
5244    fn default_sphere_smooth_uses_spherical_farthest_point_centers() {
5245        let ds = continuous_dataset(
5246            &["y", "lat", "lon"],
5247            (0..24)
5248                .map(|i| {
5249                    let t = i as f64 / 24.0;
5250                    let lat = -60.0 + 120.0 * t;
5251                    let lon = -180.0 + 360.0 * ((7 * i) % 24) as f64 / 24.0;
5252                    vec![lat.to_radians().sin(), lat, lon]
5253                })
5254                .collect(),
5255        );
5256        let parsed = parse_formula("y ~ sphere(lat, lon)").expect("parse");
5257        let col_map = ds.column_map();
5258        let mut notes = Vec::new();
5259        let terms = build_termspec(
5260            &parsed.terms,
5261            &ds,
5262            &col_map,
5263            &mut notes,
5264            &gam_runtime::resource::ResourcePolicy::default_library(),
5265        )
5266        .expect("build sphere termspec");
5267        let SmoothBasisSpec::Sphere { spec, .. } = &terms.smooth_terms[0].basis else {
5268            panic!("expected sphere term");
5269        };
5270        assert!(matches!(
5271            spec.center_strategy,
5272            CenterStrategy::FarthestPoint { .. }
5273        ));
5274    }
5275
5276    #[test]
5277    fn one_dimensional_duchon_defaults_to_scale_free_length_scale() {
5278        let ds = continuous_dataset(
5279            &["y", "x"],
5280            (0..32)
5281                .map(|i| {
5282                    let x = i as f64 / 31.0;
5283                    vec![(std::f64::consts::TAU * x).sin(), x]
5284                })
5285                .collect(),
5286        );
5287        let parsed = parse_formula("y ~ duchon(x)").expect("parse");
5288        let col_map = ds.column_map();
5289        let mut notes = Vec::new();
5290        let terms = build_termspec(
5291            &parsed.terms,
5292            &ds,
5293            &col_map,
5294            &mut notes,
5295            &gam_runtime::resource::ResourcePolicy::default_library(),
5296        )
5297        .expect("build default duchon termspec");
5298        let SmoothBasisSpec::Duchon { spec, .. } = &terms.smooth_terms[0].basis else {
5299            panic!("expected Duchon term");
5300        };
5301        assert_eq!(spec.length_scale, None);
5302    }
5303
5304    #[test]
5305    fn one_dimensional_duchon_length_scale_opts_into_hybrid_mode() {
5306        let ds = continuous_dataset(
5307            &["y", "x"],
5308            (0..32)
5309                .map(|i| {
5310                    let x = i as f64 / 31.0;
5311                    vec![(std::f64::consts::TAU * x).sin(), x]
5312                })
5313                .collect(),
5314        );
5315        let parsed = parse_formula("y ~ duchon(x, length_scale=0.25)").expect("parse");
5316        let col_map = ds.column_map();
5317        let mut notes = Vec::new();
5318        let terms = build_termspec(
5319            &parsed.terms,
5320            &ds,
5321            &col_map,
5322            &mut notes,
5323            &gam_runtime::resource::ResourcePolicy::default_library(),
5324        )
5325        .expect("build hybrid duchon termspec");
5326        let SmoothBasisSpec::Duchon { spec, .. } = &terms.smooth_terms[0].basis else {
5327            panic!("expected Duchon term");
5328        };
5329        assert_eq!(spec.length_scale, Some(0.25));
5330    }
5331
5332    #[test]
5333    fn parse_matern_nu_accepts_equivalent_half_integer_forms() {
5334        let cases = [
5335            ("1/2", MaternNu::Half),
5336            (" 1 / 2 ", MaternNu::Half),
5337            (".5", MaternNu::Half),
5338            ("0.50", MaternNu::Half),
5339            ("half", MaternNu::Half),
5340            ("3 / 2", MaternNu::ThreeHalves),
5341            ("1.50", MaternNu::ThreeHalves),
5342            ("5 / 2", MaternNu::FiveHalves),
5343            ("2.500000000000", MaternNu::FiveHalves),
5344            ("7 / 2", MaternNu::SevenHalves),
5345            ("3.50", MaternNu::SevenHalves),
5346            ("9 / 2", MaternNu::NineHalves),
5347            ("4.50", MaternNu::NineHalves),
5348        ];
5349        for (raw, expected) in cases {
5350            let parsed = parse_matern_nu(raw).expect(raw);
5351            assert!(
5352                matches!(
5353                    (parsed, expected),
5354                    (MaternNu::Half, MaternNu::Half)
5355                        | (MaternNu::ThreeHalves, MaternNu::ThreeHalves)
5356                        | (MaternNu::FiveHalves, MaternNu::FiveHalves)
5357                        | (MaternNu::SevenHalves, MaternNu::SevenHalves)
5358                        | (MaternNu::NineHalves, MaternNu::NineHalves)
5359                ),
5360                "parsed {raw:?} as {parsed:?}, expected {expected:?}"
5361            );
5362        }
5363    }
5364
5365    #[test]
5366    fn parse_matern_nu_rejects_unsupported_or_invalid_values() {
5367        for raw in ["1", "2", "11/2", "1/0", "nan", "fast"] {
5368            let err = parse_matern_nu(raw).expect_err(raw);
5369            assert!(
5370                err.contains("supported half-integer values"),
5371                "unexpected error for {raw:?}: {err}"
5372            );
5373        }
5374    }
5375
5376    #[test]
5377    fn parse_ps_k_promotes_underexpressive_cubic_basis() {
5378        let mut opts = BTreeMap::new();
5379        opts.insert("k".to_string(), "4".to_string());
5380        let (internal, inferred, eff_degree) = parse_ps_internal_knots(&opts, 3, 20).expect("k=4");
5381        assert_eq!(internal, 2);
5382        assert_eq!(eff_degree, 3);
5383        assert!(!inferred);
5384
5385        opts.insert("k".to_string(), "6".to_string());
5386        let (internal, inferred, eff_degree) = parse_ps_internal_knots(&opts, 3, 20).expect("k=6");
5387        assert_eq!(internal, 2);
5388        assert_eq!(eff_degree, 3);
5389        assert!(!inferred);
5390
5391        opts.insert("k".to_string(), "10".to_string());
5392        let (internal, inferred, eff_degree) = parse_ps_internal_knots(&opts, 3, 20).expect("k=10");
5393        assert_eq!(internal, 6);
5394        assert_eq!(eff_degree, 3);
5395        assert!(!inferred);
5396    }
5397
5398    #[test]
5399    fn parse_ps_internal_knots_drops_degree_for_small_k() {
5400        // mgcv's `s(x, bs="ps", k=3)` with the default cubic basis silently
5401        // reduces to a quadratic (`degree=2`) marginal. `k=3, degree=3`
5402        // should yield a quadratic basis with zero internal knots
5403        // (`num_basis = k = 3`).
5404        let mut opts = BTreeMap::new();
5405        opts.insert("k".to_string(), "3".to_string());
5406        let (internal, inferred, eff_degree) = parse_ps_internal_knots(&opts, 3, 20).expect("k=3");
5407        assert_eq!(eff_degree, 2);
5408        assert_eq!(internal, 0);
5409        assert!(!inferred);
5410
5411        // `k=2` reduces to a linear (`degree=1`) marginal — the smallest
5412        // non-trivial spline basis.
5413        opts.insert("k".to_string(), "2".to_string());
5414        let (internal, inferred, eff_degree) = parse_ps_internal_knots(&opts, 3, 20).expect("k=2");
5415        assert_eq!(eff_degree, 1);
5416        assert_eq!(internal, 0);
5417        assert!(!inferred);
5418
5419        // The under-2 case is structurally under-specified and rejected even
5420        // by the degree-reducing variant: no B-spline basis has fewer than
5421        // two functions.
5422        opts.insert("k".to_string(), "1".to_string());
5423        let err = parse_ps_internal_knots(&opts, 3, 20)
5424            .expect_err("k=1 is below the irreducible spline floor");
5425        assert!(err.contains("requires k >= 2"), "unexpected error: {err}");
5426
5427        // When the user already passed `k >= degree+1`, the helper must
5428        // preserve the existing knot geometry exactly.
5429        opts.insert("k".to_string(), "4".to_string());
5430        let (internal, inferred, eff_degree) = parse_ps_internal_knots(&opts, 3, 20).expect("k=4");
5431        assert_eq!(eff_degree, 3);
5432        assert_eq!(internal, 2);
5433        assert!(!inferred);
5434    }
5435
5436    #[test]
5437    fn factor_smooth_marginal_degree_reduces_for_small_k() {
5438        let ds = factor_dataset();
5439        let col_map = ds.column_map();
5440
5441        for (k, expected_degree) in [(3usize, 2usize), (2usize, 1usize)] {
5442            let parsed =
5443                parse_formula(&format!("y ~ s(x, g, bs=fs, k={k})")).expect("parse factor smooth");
5444            let mut notes = Vec::new();
5445            let terms = build_termspec(
5446                &parsed.terms,
5447                &ds,
5448                &col_map,
5449                &mut notes,
5450                &gam_runtime::resource::ResourcePolicy::default_library(),
5451            )
5452            .unwrap_or_else(|err| panic!("fs k={k} should degree-reduce, got: {err:?}"));
5453            let SmoothBasisSpec::FactorSmooth { spec } = &terms.smooth_terms[0].basis else {
5454                panic!(
5455                    "expected factor smooth, got {:?}",
5456                    terms.smooth_terms[0].basis
5457                );
5458            };
5459            assert_eq!(spec.marginal.degree, expected_degree);
5460            assert!(
5461                spec.marginal.penalty_order <= spec.marginal.degree,
5462                "penalty_order {} must be clamped to degree {}",
5463                spec.marginal.penalty_order,
5464                spec.marginal.degree
5465            );
5466            let basis_size = match spec.marginal.knotspec {
5467                BSplineKnotSpec::Generate {
5468                    num_internal_knots, ..
5469                } => num_internal_knots + spec.marginal.degree + 1,
5470                BSplineKnotSpec::Automatic {
5471                    num_internal_knots: Some(num_internal_knots),
5472                    ..
5473                } => num_internal_knots + spec.marginal.degree + 1,
5474                ref other => panic!("unexpected factor-smooth knotspec: {other:?}"),
5475            };
5476            assert_eq!(basis_size, k);
5477        }
5478    }
5479
5480    /// Build a dataset with a ternary continuous covariate `x ∈ {0,1,2}` and a
5481    /// 2-level categorical group `g`, for the low-cardinality cr-cap tests.
5482    fn ternary_factor_dataset() -> Dataset {
5483        let rows = (0..120)
5484            .map(|i| {
5485                let x = (i % 3) as f64;
5486                let g = (i % 2) as f64;
5487                vec![x + g, x, g]
5488            })
5489            .collect::<Vec<_>>();
5490        Dataset {
5491            headers: vec!["y".into(), "x".into(), "g".into()],
5492            values: Array2::from_shape_vec(
5493                (rows.len(), 3),
5494                rows.into_iter().flat_map(|row| row.into_iter()).collect(),
5495            )
5496            .expect("rectangular ternary factor test data"),
5497            schema: DataSchema {
5498                columns: vec![
5499                    SchemaColumn {
5500                        name: "y".into(),
5501                        kind: ColumnKindTag::Continuous,
5502                        levels: vec![],
5503                    },
5504                    SchemaColumn {
5505                        name: "x".into(),
5506                        kind: ColumnKindTag::Continuous,
5507                        levels: vec![],
5508                    },
5509                    SchemaColumn {
5510                        name: "g".into(),
5511                        kind: ColumnKindTag::Categorical,
5512                        levels: vec!["a".into(), "b".into()],
5513                    },
5514                ],
5515            },
5516            column_kinds: vec![
5517                ColumnKindTag::Continuous,
5518                ColumnKindTag::Continuous,
5519                ColumnKindTag::Categorical,
5520            ],
5521        }
5522    }
5523
5524    #[test]
5525    fn univariate_cr_smooth_caps_knots_to_data_support() {
5526        // #1541: `s(x, bs=cr, k=10)` on a ternary covariate (3 distinct values)
5527        // must NOT hard-fail in cr-knot selection ("cubic regression spline with
5528        // k=10 requires at least 10 distinct values, got 3"). The cr basis is
5529        // capped to the data support — exactly 3 value-knots at {0,1,2} — which
5530        // is full-rank for the data, so it can still represent any 3 group means.
5531        let ds = continuous_dataset(
5532            &["y", "x"],
5533            (0..90)
5534                .map(|i| vec![(i % 3) as f64, (i % 3) as f64])
5535                .collect(),
5536        );
5537        let col_map = ds.column_map();
5538        let parsed = parse_formula("y ~ s(x, bs=cr, k=10)").expect("parse cr smooth");
5539        let mut notes = Vec::new();
5540        let terms = build_termspec(
5541            &parsed.terms,
5542            &ds,
5543            &col_map,
5544            &mut notes,
5545            &gam_runtime::resource::ResourcePolicy::default_library(),
5546        )
5547        .expect("cr k=10 must cap to data support instead of erroring");
5548        let SmoothBasisSpec::BSpline1D { spec, .. } = &terms.smooth_terms[0].basis else {
5549            panic!("expected BSpline1D for s(x, bs=cr)");
5550        };
5551        let BSplineKnotSpec::NaturalCubicRegression { knots } = &spec.knotspec else {
5552            panic!("expected cr knotspec, got {:?}", spec.knotspec);
5553        };
5554        // Capped to exactly the 3 distinct covariate values.
5555        assert_eq!(knots.len(), 3, "cr basis not capped to 3 distinct values");
5556        assert_eq!(knots.as_slice().unwrap(), &[0.0, 1.0, 2.0]);
5557        // The reduction is surfaced to the user (mgcv warns in the same case).
5558        assert!(
5559            notes.iter().any(|n| n.contains("data-support cap")),
5560            "cap not reported in inference notes: {notes:?}"
5561        );
5562    }
5563
5564    #[test]
5565    fn univariate_cr_smooth_binary_covariate_degrades_to_bspline() {
5566        // #1541: a BINARY covariate has too few distinct values (2) for ANY cr
5567        // spline (needs >= 3 distinct). `s(x, bs=cr)` must degrade to a B-spline
5568        // marginal — the default basis the same data already fits — NOT hard-fail.
5569        let ds = continuous_dataset(
5570            &["y", "x"],
5571            (0..80)
5572                .map(|i| vec![(i % 2) as f64, (i % 2) as f64])
5573                .collect(),
5574        );
5575        let col_map = ds.column_map();
5576        let parsed = parse_formula("y ~ s(x, bs=cr, k=10)").expect("parse cr smooth");
5577        let mut notes = Vec::new();
5578        let terms = build_termspec(
5579            &parsed.terms,
5580            &ds,
5581            &col_map,
5582            &mut notes,
5583            &gam_runtime::resource::ResourcePolicy::default_library(),
5584        )
5585        .expect("binary cr must degrade to B-spline instead of erroring");
5586        let SmoothBasisSpec::BSpline1D { spec, .. } = &terms.smooth_terms[0].basis else {
5587            panic!("expected BSpline1D for s(x, bs=cr)");
5588        };
5589        assert!(
5590            !matches!(
5591                spec.knotspec,
5592                BSplineKnotSpec::NaturalCubicRegression { .. }
5593            ),
5594            "binary covariate must NOT build a cr basis, got {:?}",
5595            spec.knotspec
5596        );
5597        assert!(
5598            notes
5599                .iter()
5600                .any(|n| n.contains("Degraded to the linear B-spline")),
5601            "degradation not reported in inference notes: {notes:?}"
5602        );
5603    }
5604
5605    #[test]
5606    fn sz_factor_smooth_low_cardinality_uses_bspline_marginal() {
5607        // #1605: the `sz` factor-smooth marginal is the SAME penalized B-spline
5608        // the `fs` sibling uses — NOT a natural cubic regression (`cr`) marginal,
5609        // whose hard natural boundary conditions f''=0 bias curved deviations
5610        // (a consistency failure). #1542 (the reason this test exists) is
5611        // subsumed: with a B-spline marginal a low-cardinality covariate no
5612        // longer needs a special cr data-support cap and can never hard-fail the
5613        // way the old cr-marginal `sz` spelling did — the build just succeeds,
5614        // exactly as `fs` already does on the identical data.
5615        let ds = ternary_factor_dataset();
5616        let col_map = ds.column_map();
5617        let parsed = parse_formula("y ~ s(x, g, bs=sz, k=10)").expect("parse sz factor smooth");
5618        let mut notes = Vec::new();
5619        let terms = build_termspec(
5620            &parsed.terms,
5621            &ds,
5622            &col_map,
5623            &mut notes,
5624            &gam_runtime::resource::ResourcePolicy::default_library(),
5625        )
5626        .expect("sz on a ternary covariate must build (B-spline marginal), not hard-fail");
5627        let SmoothBasisSpec::FactorSmooth { spec } = &terms.smooth_terms[0].basis else {
5628            panic!("expected FactorSmooth for s(x, g, bs=sz)");
5629        };
5630        assert!(
5631            !matches!(
5632                spec.marginal.knotspec,
5633                BSplineKnotSpec::NaturalCubicRegression { .. }
5634            ),
5635            "sz marginal must be a B-spline (curvature-capable), not the \
5636             natural-BC cr basis; got {:?}",
5637            spec.marginal.knotspec
5638        );
5639    }
5640
5641    /// A dataset with a genuinely continuous covariate `x` (many distinct
5642    /// values) and a `L`-level grouping factor `g`, suitable for building a
5643    /// real factor-smooth marginal with a non-trivial {const, linear} null
5644    /// space. `y` is unused by the structural penalty checks below.
5645    fn continuous_x_factor_dataset(n: usize, n_groups: usize) -> Dataset {
5646        let rows = (0..n)
5647            .map(|i| {
5648                let x = i as f64 / (n as f64 - 1.0);
5649                let g = (i % n_groups) as f64;
5650                vec![x + g, x, g]
5651            })
5652            .collect::<Vec<_>>();
5653        let levels: Vec<String> = (0..n_groups).map(|k| format!("g{k}")).collect();
5654        Dataset {
5655            headers: vec!["y".into(), "x".into(), "g".into()],
5656            values: Array2::from_shape_vec(
5657                (rows.len(), 3),
5658                rows.into_iter().flat_map(|row| row.into_iter()).collect(),
5659            )
5660            .expect("rectangular continuous-x factor data"),
5661            schema: DataSchema {
5662                columns: vec![
5663                    SchemaColumn {
5664                        name: "y".into(),
5665                        kind: ColumnKindTag::Continuous,
5666                        levels: vec![],
5667                    },
5668                    SchemaColumn {
5669                        name: "x".into(),
5670                        kind: ColumnKindTag::Continuous,
5671                        levels: vec![],
5672                    },
5673                    SchemaColumn {
5674                        name: "g".into(),
5675                        kind: ColumnKindTag::Categorical,
5676                        levels,
5677                    },
5678                ],
5679            },
5680            column_kinds: vec![
5681                ColumnKindTag::Continuous,
5682                ColumnKindTag::Continuous,
5683                ColumnKindTag::Categorical,
5684            ],
5685        }
5686    }
5687
5688    fn factor_smooth_spec_for(formula: &str, ds: &Dataset) -> FactorSmoothSpec {
5689        let col_map = ds.column_map();
5690        let parsed = parse_formula(formula).expect("parse factor smooth formula");
5691        let mut notes = Vec::new();
5692        let terms = build_termspec(
5693            &parsed.terms,
5694            ds,
5695            &col_map,
5696            &mut notes,
5697            &gam_runtime::resource::ResourcePolicy::default_library(),
5698        )
5699        .expect("build factor smooth term");
5700        let SmoothBasisSpec::FactorSmooth { spec } = &terms.smooth_terms[0].basis else {
5701            panic!("expected FactorSmooth basis for `{formula}`");
5702        };
5703        spec.clone()
5704    }
5705
5706    /// #1605: the sum-to-zero factor smooth `s(x, g, bs="sz")` under-fit data
5707    /// drawn from its own model class because its deviation blocks carried ONLY
5708    /// the marginal wiggliness penalty — the {const, linear} null space of every
5709    /// deviation curve was left completely unpenalized, so the single combined
5710    /// wiggliness λ could not separate per-group intercept/slope variance from
5711    /// curvature variance and REML parked it over-smoothed (same defect class as
5712    /// the closed #700, more severe). mgcv's `bs="fs"` sibling avoids the gap by
5713    /// adding a SEPARATE per-null-dimension ridge (one λ each), the
5714    /// double-penalty `I_L ⊗ S_j` structure. The fix gives `sz` the same
5715    /// null-space-ridge structure, mapped into the zero-sum CONTRAST space so the
5716    /// constraint (and `sz`'s distinctness from `fs`) is preserved.
5717    ///
5718    /// This pins the structural defect: after the fix the `sz` deviation build
5719    /// must carry MORE than just its wiggliness penalty(s) — exactly one extra
5720    /// null-space-ridge penalty per marginal null direction, matching the count
5721    /// that `fs` carries — while keeping the narrower `(L-1)·p` zero-sum design
5722    /// (NOT the `L·p` full-rank `fs` design). Before the fix `sz` carried only
5723    /// the wiggliness penalties and this fails.
5724    #[test]
5725    fn sz_factor_smooth_carries_null_space_ridge_like_fs() {
5726        let ds = continuous_x_factor_dataset(180, 4);
5727        let mut workspace = crate::basis::BasisWorkspace::new();
5728
5729        let sz_spec = factor_smooth_spec_for("y ~ s(x, g, bs=sz, k=8)", &ds);
5730        let sz_built = crate::smooth::build_factor_smooth(
5731            ds.values.view(),
5732            &sz_spec,
5733            "sz_term",
5734            &mut workspace,
5735        )
5736        .expect("build sz factor smooth");
5737
5738        let fs_spec = factor_smooth_spec_for("y ~ s(x, g, bs=fs, k=8)", &ds);
5739        let fs_built = crate::smooth::build_factor_smooth(
5740            ds.values.view(),
5741            &fs_spec,
5742            "fs_term",
5743            &mut workspace,
5744        )
5745        .expect("build fs factor smooth");
5746
5747        // Penalty structure (#1074 + #1605). `fs` is the exchangeable
5748        // random-effect smooth: all `L` level blocks share ONE wiggliness λ per
5749        // marginal penalty, plus one rank-1 null-space ridge per marginal null
5750        // direction (the #1605 double penalty). `sz` is the sum-to-zero factor
5751        // smooth and mgcv's `smooth.construct.sz` emits ONE penalty matrix PER
5752        // LEVEL — `L` independent curvature smoothing parameters — so REML can
5753        // shrink a low-amplitude group's deviation hard while leaving a busy
5754        // group nearly unpenalized. We mirror that: the single marginal
5755        // wiggliness penalty is split into its `L` independent zero-sum-contrast
5756        // summands (`L-1` free per-group blocks `(e_k e_kᵀ)⊗S` + the reference
5757        // coupling block `(11ᵀ)⊗S`), each carrying its own λ, and the null-space
5758        // ridges stay POOLED (the per-group intercept/slope shrinkage mgcv pools
5759        // under one variance even for `sz`).
5760        //
5761        // So with `nw` marginal wiggliness penalties and `nn` marginal null
5762        // directions: fs has `nw + nn` penalties; sz has `L·nw + nn`. sz must
5763        // therefore carry strictly MORE penalties than fs (the per-group split),
5764        // and the surplus must be exactly `(L-1)·nw`.
5765        let n_levels = sz_spec
5766            .group_frozen_levels
5767            .as_ref()
5768            .map(|l| l.len())
5769            .unwrap_or(4);
5770        assert!(n_levels >= 3, "test needs >=3 groups, got {n_levels}");
5771
5772        // fs = nw + nn  ⇒  nn = fs_penalties - nw. The marginal has nw==1
5773        // wiggliness penalty (a single difference/curvature operator), so the
5774        // per-group split adds exactly (L-1)·nw = (L-1) extra penalties on top of
5775        // fs's count.
5776        let nw = 1usize; // one marginal wiggliness penalty for the B-spline marginal
5777        let expected_sz = fs_built.penalties.len() + (n_levels - 1) * nw;
5778        assert_eq!(
5779            sz_built.penalties.len(),
5780            expected_sz,
5781            "sz must split its wiggliness penalty per level (#1074): expected \
5782             fs_count {} + (L-1)·nw {} = {}, but sz had {}",
5783            fs_built.penalties.len(),
5784            (n_levels - 1) * nw,
5785            expected_sz,
5786            sz_built.penalties.len(),
5787        );
5788        assert!(
5789            sz_built.penalties.len() > fs_built.penalties.len(),
5790            "sz must carry strictly more penalties than fs after the per-group \
5791             split (sz={}, fs={})",
5792            sz_built.penalties.len(),
5793            fs_built.penalties.len(),
5794        );
5795
5796        // The null-space ridges must still be present (the #1605 property that
5797        // keeps the deviation curvature un-over-smoothed). After removing the `L`
5798        // per-group wiggliness blocks, the remainder are the pooled null ridges,
5799        // and there must be at least one (a B-spline marginal has a non-empty
5800        // {const, linear} null space).
5801        let n_wiggliness = n_levels * nw; // L per-group blocks
5802        assert!(
5803            sz_built.penalties.len() > n_wiggliness,
5804            "sz deviation block carries no null-space ridge (penalties={}, \
5805             wiggliness blocks={}); the null space is unpenalized and REML \
5806             over-smooths the deviations",
5807            sz_built.penalties.len(),
5808            n_wiggliness,
5809        );
5810
5811        // The zero-sum constraint must be preserved: the sz design must stay the
5812        // NARROWER `(L-1)·p` contrast design, strictly narrower than the fs
5813        // full-rank `L·p` design. This guards against "fixing" sz by making it
5814        // identical to fs (which would break identifiability / sum-to-zero).
5815        assert!(
5816            sz_built.dim < fs_built.dim,
5817            "sz design width {} must be strictly less than fs width {} \
5818             (zero-sum contrast drops one level block)",
5819            sz_built.dim,
5820            fs_built.dim,
5821        );
5822
5823        // Every penalty/metadata vector must stay parallel (length invariant the
5824        // downstream REML assembly relies on).
5825        assert_eq!(sz_built.penalties.len(), sz_built.nullspaces.len());
5826        assert_eq!(sz_built.penalties.len(), sz_built.penaltyinfo.len());
5827        assert_eq!(sz_built.penalties.len(), sz_built.null_eigenvectors.len());
5828    }
5829
5830    /// #1457: `y ~ s(x, by=g) + g` with a BARE categorical `g` must NOT lower to
5831    /// two `g` design blocks. The bare `+ g` is auto-promoted to a single
5832    /// penalized random-effect block owning the factor's full level offsets; the
5833    /// `by=` branch must then recognize that owner and skip adding its own
5834    /// unpenalized treatment-coded main effect. Before the fix the dedup guard
5835    /// recognized only explicit `group(g)` (a `ParsedTerm::RandomEffect`), so the
5836    /// auto-promoted bare-`+ g` block slipped past and a spurious second `g`
5837    /// block (plus an extra smoothing parameter) was added. Assert exactly ONE
5838    /// `g` random/categorical block, and that adding the bare `+ g` introduces no
5839    /// extra `g` blocks beyond `y ~ s(x, by=g)` alone.
5840    fn factor_dataset_l3() -> Dataset {
5841        // `g` is categorical with THREE levels (encoded 0.0/1.0/2.0).
5842        let rows = (0..30)
5843            .map(|i| {
5844                let x = i as f64 / 29.0;
5845                let g = (i % 3) as f64;
5846                vec![x + g, x, g]
5847            })
5848            .collect::<Vec<_>>();
5849        Dataset {
5850            headers: vec!["y".into(), "x".into(), "g".into()],
5851            values: Array2::from_shape_vec(
5852                (rows.len(), 3),
5853                rows.into_iter().flat_map(|row| row.into_iter()).collect(),
5854            )
5855            .expect("rectangular L=3 factor test data"),
5856            schema: DataSchema {
5857                columns: vec![
5858                    SchemaColumn {
5859                        name: "y".into(),
5860                        kind: ColumnKindTag::Continuous,
5861                        levels: vec![],
5862                    },
5863                    SchemaColumn {
5864                        name: "x".into(),
5865                        kind: ColumnKindTag::Continuous,
5866                        levels: vec![],
5867                    },
5868                    SchemaColumn {
5869                        name: "g".into(),
5870                        kind: ColumnKindTag::Categorical,
5871                        levels: vec!["a".into(), "b".into(), "c".into()],
5872                    },
5873                ],
5874            },
5875            column_kinds: vec![
5876                ColumnKindTag::Continuous,
5877                ColumnKindTag::Continuous,
5878                ColumnKindTag::Categorical,
5879            ],
5880        }
5881    }
5882
5883    #[test]
5884    fn factor_by_smooth_plus_bare_categorical_does_not_duplicate_factor_block() {
5885        let ds = factor_dataset_l3();
5886        let col_map = ds.column_map();
5887
5888        let g_blocks = |formula: &str| -> usize {
5889            let parsed = parse_formula(formula).expect("parse by-smooth formula");
5890            let mut notes = Vec::new();
5891            let terms = build_termspec(
5892                &parsed.terms,
5893                &ds,
5894                &col_map,
5895                &mut notes,
5896                &ResourcePolicy::default_library(),
5897            )
5898            .unwrap_or_else(|err| panic!("`{formula}` must build, got: {err:?}"));
5899            terms
5900                .random_effect_terms
5901                .iter()
5902                .filter(|rt| rt.name == "g")
5903                .count()
5904        };
5905
5906        // Baseline: the standalone factor-by smooth carries exactly ONE `g`
5907        // block (the unpenalized treatment-coded factor main effect added by the
5908        // `by=` branch).
5909        let by_only = g_blocks("y ~ s(x, by=g, k=10)");
5910        assert_eq!(
5911            by_only, 1,
5912            "`y ~ s(x, by=g)` must produce exactly one `g` design block"
5913        );
5914
5915        // The bug: adding a bare `+ g` (auto-promoted to a penalized random
5916        // block owning the same level offsets) must NOT introduce a second `g`
5917        // block. Before the fix this was 2.
5918        let by_plus_bare = g_blocks("y ~ s(x, by=g, k=10) + g");
5919        assert_eq!(
5920            by_plus_bare, 1,
5921            "`y ~ s(x, by=g) + g` must collapse to ONE `g` block (#1457): the bare \
5922             `+ g` already owns the factor's level offsets, so the `by=` branch \
5923             must not add a second, treatment-coded main effect"
5924        );
5925
5926        // The bare `+ g` adds no spurious extra `g` block versus the baseline.
5927        assert_eq!(
5928            by_plus_bare, by_only,
5929            "the bare `+ g` collision must add zero extra `g` blocks (#1457)"
5930        );
5931    }
5932
5933    #[test]
5934    fn parse_tensor_periods_and_origins_aliases() {
5935        let mut opts = BTreeMap::new();
5936        opts.insert(
5937            "boundary".to_string(),
5938            "['periodic', 'periodic']".to_string(),
5939        );
5940        opts.insert("periods".to_string(), "[7, 24]".to_string());
5941        opts.insert("origins".to_string(), "[0, -12]".to_string());
5942        let axes = parse_periodic_axes(&opts, 2).expect("axes");
5943        let periods = parse_periods(&opts, &axes).expect("periods");
5944        let origins = parse_period_origins(&opts, &axes).expect("origins");
5945        assert_eq!(axes, vec![true, true]);
5946        assert_eq!(periods, vec![Some(7.0), Some(24.0)]);
5947        assert_eq!(origins, vec![Some(0.0), Some(-12.0)]);
5948    }
5949
5950    #[test]
5951    fn tensor_smooth_honors_per_margin_k_list() {
5952        let ds = continuous_dataset(
5953            &["y", "theta", "h"],
5954            (0..20)
5955                .map(|i| {
5956                    let theta = std::f64::consts::TAU * i as f64 / 20.0;
5957                    let h = -1.0 + 2.0 * (i % 5) as f64 / 4.0;
5958                    vec![theta.cos() + h, theta, h]
5959                })
5960                .collect(),
5961        );
5962        let parsed = parse_formula(
5963            "y ~ te(theta, h, periodic=[0], period=[2*pi, None], origin=[0, None], k=[9,5])",
5964        )
5965        .expect("parse tensor formula");
5966        let col_map = ds.column_map();
5967        let mut notes = Vec::new();
5968        let terms = build_termspec(
5969            &parsed.terms,
5970            &ds,
5971            &col_map,
5972            &mut notes,
5973            &gam_runtime::resource::ResourcePolicy::default_library(),
5974        )
5975        .expect("build tensor terms");
5976        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
5977            panic!("expected tensor B-spline");
5978        };
5979        let dims = spec
5980            .marginalspecs
5981            .iter()
5982            .map(|m| match m.knotspec {
5983                BSplineKnotSpec::PeriodicUniform { num_basis, .. } => num_basis,
5984                BSplineKnotSpec::Generate {
5985                    num_internal_knots, ..
5986                } => num_internal_knots + m.degree + 1,
5987                // The mgcv-default `cr` margin (#1074) reports its basis size as
5988                // the number of value-knots placed.
5989                BSplineKnotSpec::NaturalCubicRegression { ref knots } => knots.len(),
5990                _ => panic!("unexpected tensor marginal knotspec"),
5991            })
5992            .collect::<Vec<_>>();
5993        assert_eq!(dims, vec![9, 5]);
5994    }
5995
5996    #[test]
5997    fn tensor_smooth_honors_per_margin_k_axis_aliases() {
5998        let ds = continuous_dataset(
5999            &["resp", "x", "y"],
6000            (0..12)
6001                .map(|i| {
6002                    let t = i as f64 / 11.0;
6003                    vec![t, t, 1.0 - t]
6004                })
6005                .collect(),
6006        );
6007        assert_eq!(
6008            tensor_margin_basis_sizes(&ds, "resp ~ te(x, y, k_x=9, k_y=5)"),
6009            vec![9, 5],
6010            "k_<margin> aliases should materialize requested per-margin values"
6011        );
6012    }
6013
6014    #[test]
6015    fn tensor_smooth_low_cardinality_axis_falls_back_to_lower_degree_basis() {
6016        // mgcv-style: `te(x, b, k=c(5, 2))` with a BINARY second margin (only
6017        // values {0, 1}) is a legitimate request — the binary axis can hold at
6018        // most a 2-function linear basis. We must NOT reject k=2 with a
6019        // "k too small for degree 3" config error; instead, drop the spline
6020        // degree on the binary axis to k_axis - 1 (here 1, linear) while
6021        // keeping the continuous margin at the requested degree=3, k=5.
6022        let ds = continuous_dataset(
6023            &["y", "x", "b"],
6024            (0..40)
6025                .map(|i| {
6026                    let x = i as f64 / 39.0;
6027                    let b = (i % 2) as f64;
6028                    vec![x.sin() + 0.5 * b, x, b]
6029                })
6030                .collect(),
6031        );
6032        let parsed = parse_formula("y ~ te(x, b, k=[5, 2])").expect("parse tensor with k=[5,2]");
6033        let col_map = ds.column_map();
6034        let mut notes = Vec::new();
6035        let terms = build_termspec(
6036            &parsed.terms,
6037            &ds,
6038            &col_map,
6039            &mut notes,
6040            &gam_runtime::resource::ResourcePolicy::default_library(),
6041        )
6042        .expect("build tensor with binary margin");
6043        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
6044            panic!("expected tensor B-spline for te(x, b)");
6045        };
6046        // Continuous margin keeps requested degree=3 and k=5; binary margin
6047        // drops to degree=1 (linear) so the requested k=2 yields exactly two
6048        // basis functions before tensor-product identifiability is applied.
6049        let continuous = &spec.marginalspecs[0];
6050        let binary = &spec.marginalspecs[1];
6051        assert_eq!(continuous.degree, 3);
6052        assert_eq!(binary.degree, 1);
6053        assert!(
6054            binary.penalty_order >= 1 && binary.penalty_order <= binary.degree,
6055            "binary margin penalty_order {} must satisfy 1 <= order <= degree={}",
6056            binary.penalty_order,
6057            binary.degree
6058        );
6059        let basis_size = |m: &BSplineBasisSpec| match m.knotspec {
6060            BSplineKnotSpec::PeriodicUniform { num_basis, .. } => num_basis,
6061            BSplineKnotSpec::Generate {
6062                num_internal_knots, ..
6063            } => num_internal_knots + m.degree + 1,
6064            BSplineKnotSpec::Automatic {
6065                num_internal_knots: Some(n),
6066                ..
6067            } => n + m.degree + 1,
6068            // The mgcv-default `cr` margin (#1074) reports its basis size as the
6069            // number of value-knots placed.
6070            BSplineKnotSpec::NaturalCubicRegression { ref knots } => knots.len(),
6071            _ => panic!("unexpected tensor marginal knotspec"),
6072        };
6073        assert_eq!(basis_size(continuous), 5);
6074        assert_eq!(basis_size(binary), 2);
6075    }
6076
6077    #[test]
6078    fn tensor_smooth_uniform_k_is_capped_to_a_low_cardinality_margins_distinct_values() {
6079        // Regression: a SINGLE `k=5` applied to every axis of `te(x, b, k=5)`
6080        // with a BINARY second margin (`b ∈ {0, 1}`) must build a valid tensor,
6081        // NOT hard-fail in cr-knot selection ("cubic regression spline with k=5
6082        // requires at least 5 distinct values, got 2"). mgcv caps a margin's
6083        // basis to its data support; the binary axis becomes the 2-function
6084        // (linear) margin, while the continuous axis keeps the requested k=5.
6085        // This is the `te(age, badh, k=5)` real-data case that previously errored.
6086        let ds = continuous_dataset(
6087            &["y", "x", "b"],
6088            (0..40)
6089                .map(|i| {
6090                    let x = i as f64 / 39.0;
6091                    let b = (i % 2) as f64;
6092                    vec![x.sin() + 0.5 * b, x, b]
6093                })
6094                .collect(),
6095        );
6096        let parsed = parse_formula("y ~ te(x, b, k=5)").expect("parse tensor with uniform k=5");
6097        let col_map = ds.column_map();
6098        let mut notes = Vec::new();
6099        let terms = build_termspec(
6100            &parsed.terms,
6101            &ds,
6102            &col_map,
6103            &mut notes,
6104            &gam_runtime::resource::ResourcePolicy::default_library(),
6105        )
6106        .expect("uniform k=5 must auto-cap the binary margin instead of erroring");
6107        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
6108            panic!("expected tensor B-spline for te(x, b)");
6109        };
6110        let basis_size = |m: &BSplineBasisSpec| match &m.knotspec {
6111            BSplineKnotSpec::PeriodicUniform { num_basis, .. } => *num_basis,
6112            BSplineKnotSpec::Generate {
6113                num_internal_knots, ..
6114            } => num_internal_knots + m.degree + 1,
6115            BSplineKnotSpec::Automatic {
6116                num_internal_knots: Some(n),
6117                ..
6118            } => n + m.degree + 1,
6119            BSplineKnotSpec::NaturalCubicRegression { knots } => knots.len(),
6120            other => panic!("unexpected tensor marginal knotspec: {other:?}"),
6121        };
6122        let binary = &spec.marginalspecs[1];
6123        // Binary margin is reduced to the 2-function linear basis its data
6124        // supports (k capped from 5 to 2, degree dropped to 1).
6125        assert_eq!(basis_size(binary), 2);
6126        assert_eq!(binary.degree, 1);
6127        // The continuous margin is unaffected by the cap (40 distinct values).
6128        assert_eq!(basis_size(&spec.marginalspecs[0]), 5);
6129    }
6130
6131    #[test]
6132    fn tensor_all_tp_margins_with_per_margin_k_routes_to_bspline_tensor() {
6133        // `te(x1, x2, bs=c('tp','tp'), k=c(5,5))` is mgcv's per-margin tp tensor
6134        // with per-margin basis sizes — a tensor product of two 1-D bases, each
6135        // of dimension 5. The list-valued `k=c(5,5)` is honored by
6136        // `parse_tensor_k_list`, producing one penalized B-spline margin per axis
6137        // (each spanning the requested per-axis thin-plate function space). This
6138        // is the same anisotropic-tensor routing the scalar/no-`k` case takes —
6139        // a `te()` request is ALWAYS a tensor product, never a silent isotropic
6140        // thin-plate substitution.
6141        let ds = continuous_dataset(
6142            &["y", "x1", "x2"],
6143            (0..32)
6144                .map(|i| {
6145                    let t = i as f64 / 31.0;
6146                    vec![t.sin(), t, 1.0 - t]
6147                })
6148                .collect(),
6149        );
6150        let parsed =
6151            parse_formula("y ~ te(x1, x2, bs=c('tp','tp'), k=c(5,5))").expect("parse tensor");
6152        let col_map = ds.column_map();
6153        let mut notes = Vec::new();
6154        let terms = build_termspec(
6155            &parsed.terms,
6156            &ds,
6157            &col_map,
6158            &mut notes,
6159            &gam_runtime::resource::ResourcePolicy::default_library(),
6160        )
6161        .expect("build tensor terms with per-margin k");
6162        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
6163            panic!(
6164                "expected B-spline tensor when k=c(5,5) is supplied with bs=c('tp','tp'), got {:?}",
6165                terms.smooth_terms[0].basis
6166            );
6167        };
6168        // Since #1074 a `tp` tensor margin (k >= 3) is realized as a
6169        // Lancaster–Salkauskas natural cubic-regression margin (cr basis
6170        // dimension == knot count), not an open `Generate` B-spline. It is
6171        // still a `TensorBSpline` spec with one penalized 1-D margin per axis,
6172        // so the routing assertion above still holds; only the per-margin
6173        // knotspec variant changed. The earlier `_ => panic!` arm pinned the
6174        // pre-#1074 `Generate`-only representation and is stale. Decode every
6175        // margin variant to its basis dimension (mirroring the
6176        // `tensor_margin_basis_sizes` helper).
6177        let dims = spec
6178            .marginalspecs
6179            .iter()
6180            .map(|m| match m.knotspec {
6181                BSplineKnotSpec::Generate {
6182                    num_internal_knots, ..
6183                } => num_internal_knots + m.degree + 1,
6184                BSplineKnotSpec::Automatic {
6185                    num_internal_knots: Some(num_internal_knots),
6186                    ..
6187                } => num_internal_knots + m.degree + 1,
6188                BSplineKnotSpec::PeriodicUniform { num_basis, .. } => num_basis,
6189                BSplineKnotSpec::Provided(ref knots) => {
6190                    knots.len().saturating_sub(m.degree + 1)
6191                }
6192                BSplineKnotSpec::NaturalCubicRegression { ref knots } => knots.len(),
6193                BSplineKnotSpec::Automatic {
6194                    num_internal_knots: None,
6195                    ..
6196                } => panic!("test cannot infer automatic knot count"),
6197            })
6198            .collect::<Vec<_>>();
6199        assert_eq!(dims, vec![5, 5]);
6200    }
6201
6202    #[test]
6203    fn tensor_all_tp_margins_without_per_margin_k_builds_anisotropic_tensor() {
6204        // `te(x1, x2, bs=c('tp','tp'))` is a tensor-product request and must
6205        // build a genuine anisotropic tensor product (one smoothing parameter
6206        // per margin), NOT a silently-substituted multi-D isotropic thin-plate
6207        // radial smooth — that would be a different model (`s(x1,x2,bs='tp')`).
6208        // The routing is now consistent whether or not `k` is list-valued: a tp
6209        // margin vector always realizes each axis as a 1-D penalized B-spline
6210        // margin spanning the same per-axis thin-plate function space (#1082).
6211        let ds = continuous_dataset(
6212            &["y", "x1", "x2"],
6213            (0..32)
6214                .map(|i| {
6215                    let t = i as f64 / 31.0;
6216                    vec![t.sin(), t, 1.0 - t]
6217                })
6218                .collect(),
6219        );
6220        let parsed = parse_formula("y ~ te(x1, x2, bs=c('tp','tp'))").expect("parse tensor");
6221        let col_map = ds.column_map();
6222        let mut notes = Vec::new();
6223        let terms = build_termspec(
6224            &parsed.terms,
6225            &ds,
6226            &col_map,
6227            &mut notes,
6228            &gam_runtime::resource::ResourcePolicy::default_library(),
6229        )
6230        .expect("build tensor terms without per-margin k");
6231        let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
6232            panic!(
6233                "te(...,bs=c('tp','tp')) must route to an anisotropic tensor product, not a \
6234                 silent isotropic thin-plate substitution; got {:?}",
6235                terms.smooth_terms[0].basis
6236            );
6237        };
6238        assert_eq!(
6239            spec.marginalspecs.len(),
6240            2,
6241            "tp tensor must carry one penalized B-spline margin per axis"
6242        );
6243    }
6244
6245    #[test]
6246    fn explicit_basis_sizes_are_not_small_n_clamped() {
6247        let ds = continuous_dataset(
6248            &["y", "x1", "x2", "x3", "x4", "x5"],
6249            (0..12)
6250                .map(|i| {
6251                    let x = i as f64 / 11.0;
6252                    vec![x.sin(), x, x * x, x + 0.1, 1.0 - x, (2.0 * x).sin()]
6253                })
6254                .collect(),
6255        );
6256        let parsed = parse_formula("y ~ s(x1, k=10) + s(x2) + s(x3) + s(x4) + s(x5)")
6257            .expect("parse multi-smooth formula");
6258        let col_map = ds.column_map();
6259        let mut notes = Vec::new();
6260        let terms = build_termspec(
6261            &parsed.terms,
6262            &ds,
6263            &col_map,
6264            &mut notes,
6265            &gam_runtime::resource::ResourcePolicy::default_library(),
6266        )
6267        .expect("build multi-smooth terms");
6268        let SmoothBasisSpec::BSpline1D { spec, .. } = &terms.smooth_terms[0].basis else {
6269            panic!("expected first smooth to be B-spline");
6270        };
6271        assert!(matches!(
6272            &spec.knotspec,
6273            BSplineKnotSpec::Generate {
6274                num_internal_knots: 6,
6275                ..
6276            }
6277        ));
6278    }
6279
6280    #[test]
6281    fn explicit_duchon_centers_are_not_small_n_bumped() {
6282        let ds = continuous_dataset(
6283            &["y", "x1", "x2", "x3", "x4", "x5"],
6284            (0..12)
6285                .map(|i| {
6286                    let x = i as f64 / 11.0;
6287                    vec![x.sin(), x, x * x, x + 0.1, 1.0 - x, (2.0 * x).sin()]
6288                })
6289                .collect(),
6290        );
6291        // Pure 1D Duchon at default options resolves the nullspace to Linear
6292        // (2s < d forces escalation), giving 2 polynomial nullspace columns;
6293        // the well-posedness gate requires num_centers > polynomial_cols, so
6294        // 3 is the smallest valid count. It is still well below the small-N
6295        // bump target of polynomial_cols + 4 = 6, so this exercises the
6296        // "explicit value is honored" path the test name advertises.
6297        let parsed = parse_formula("y ~ duchon(x1, centers=3) + s(x2) + s(x3) + s(x4) + s(x5)")
6298            .expect("parse multi-smooth formula");
6299        let col_map = ds.column_map();
6300        let mut notes = Vec::new();
6301        let terms = build_termspec(
6302            &parsed.terms,
6303            &ds,
6304            &col_map,
6305            &mut notes,
6306            &gam_runtime::resource::ResourcePolicy::default_library(),
6307        )
6308        .expect("build multi-smooth terms");
6309        let SmoothBasisSpec::Duchon { spec, .. } = &terms.smooth_terms[0].basis else {
6310            panic!("expected first smooth to be Duchon");
6311        };
6312        assert!(matches!(
6313            spec.center_strategy,
6314            CenterStrategy::FarthestPoint { num_centers: 3 }
6315        ));
6316    }
6317
6318    #[test]
6319    fn inferred_tensor_basis_cap_uses_coordinate_support_not_duplicate_rows() {
6320        let mut unique_rows = Vec::new();
6321        for i in 0..50 {
6322            let theta = i as f64 / 50.0;
6323            for j in 0..16 {
6324                let h = -1.0 + 2.0 * (j as f64) / 15.0;
6325                let y = theta.cos() + h;
6326                unique_rows.push(vec![y, theta, h]);
6327            }
6328        }
6329        let mut repeated_rows = Vec::new();
6330        for _ in 0..12 {
6331            repeated_rows.extend(unique_rows.iter().cloned());
6332        }
6333
6334        let unique = continuous_dataset(&["y", "theta", "h"], unique_rows);
6335        let repeated = continuous_dataset(&["y", "theta", "h"], repeated_rows);
6336
6337        let unique_basis = inferred_tensor_basis_product(&unique);
6338        let repeated_basis = inferred_tensor_basis_product(&repeated);
6339
6340        assert_eq!(
6341            unique_basis, repeated_basis,
6342            "duplicating existing tensor coordinates must not inflate inferred basis width"
6343        );
6344    }
6345
6346    #[test]
6347    fn inferred_three_dim_tensor_basis_stays_bounded_for_reml_selection() {
6348        // Regression for gam#813: the inferred per-margin k must be
6349        // dimension-aware so the 3-D tensor width p = ∏ k_d does not explode.
6350        // With the old 1-D-per-margin rule a 3-D `te` defaulted to 7³=343 at
6351        // small n and 20³=8000 at larger n, making the (non-Kronecker-factorable)
6352        // full-tensor sum-to-zero penalty's O(p³) REML reparameterization a
6353        // multi-minute stall. The dimension-aware budget keeps the product near
6354        // mgcv's te default (≈5³=125) regardless of n.
6355        let make = |n: usize| -> usize {
6356            let mut rows = Vec::with_capacity(n);
6357            for i in 0..n {
6358                let f = i as f64 / n as f64;
6359                rows.push(vec![f.sin(), f, (2.0 * f).cos(), (3.0 * f) % 1.0]);
6360            }
6361            let ds = continuous_dataset(&["y", "x1", "x2", "x3"], rows);
6362            let parsed = parse_formula("y ~ te(x1, x2, x3)").expect("parse 3-D tensor");
6363            let col_map = ds.column_map();
6364            let mut notes = Vec::new();
6365            let terms = build_termspec(
6366                &parsed.terms,
6367                &ds,
6368                &col_map,
6369                &mut notes,
6370                &ResourcePolicy::default_library(),
6371            )
6372            .expect("build 3-D tensor termspec");
6373            let SmoothBasisSpec::TensorBSpline { spec, .. } = &terms.smooth_terms[0].basis else {
6374                panic!("expected tensor smooth");
6375            };
6376            spec.marginalspecs
6377                .iter()
6378                .map(|m| match m.knotspec {
6379                    BSplineKnotSpec::Generate {
6380                        num_internal_knots, ..
6381                    } => num_internal_knots + m.degree + 1,
6382                    BSplineKnotSpec::Automatic {
6383                        num_internal_knots: Some(num_internal_knots),
6384                        ..
6385                    } => num_internal_knots + m.degree + 1,
6386                    // The mgcv-default `cr` margin (#1074) reports its basis size
6387                    // as the number of value-knots placed.
6388                    BSplineKnotSpec::NaturalCubicRegression { ref knots } => knots.len(),
6389                    _ => panic!("unexpected tensor margin knotspec"),
6390                })
6391                .product()
6392        };
6393
6394        // n=30 (the issue's data): was 7³=343, must now be modest.
6395        assert!(
6396            make(60) <= 216,
6397            "3-D te at small n must stay near the mgcv te default, got {}",
6398            make(60)
6399        );
6400        // Larger n must NOT grow the product toward n³ (was 20³=8000).
6401        assert!(
6402            make(2000) <= 216,
6403            "3-D te at large n must not blow ∏k toward the data size, got {}",
6404            make(2000)
6405        );
6406    }
6407
6408    #[test]
6409    fn parse_bspline_boundary_conditions_and_side_selector() {
6410        // Non-zero anchors are rejected at parse time; the diagnostic must
6411        // name the side and value, which doubles as a check that the
6412        // `side=left` filter routes the global `anchor=` value to the
6413        // left endpoint (not the right).
6414        let mut opts = BTreeMap::new();
6415        opts.insert("boundary_conditions".to_string(), "anchored".to_string());
6416        opts.insert("side".to_string(), "left".to_string());
6417        opts.insert("anchor".to_string(), "2.5".to_string());
6418        let err = parse_bspline_boundary_conditions(&opts)
6419            .expect_err("non-zero left anchor must be rejected")
6420            .to_string();
6421        assert!(
6422            err.contains("left") && err.contains("2.5"),
6423            "rejection should name the affected side and value: {err}"
6424        );
6425
6426        // Side-specific aliases (`start_bc`/`end_bc`) plus the side-specific
6427        // anchor key (`right_anchor`) must funnel the value onto the right
6428        // endpoint — verified through the rejection diagnostic.
6429        let mut opts = BTreeMap::new();
6430        opts.insert("start_bc".to_string(), "clamped".to_string());
6431        opts.insert("end_bc".to_string(), "zero".to_string());
6432        opts.insert("right_anchor".to_string(), "-1.0".to_string());
6433        let err = parse_bspline_boundary_conditions(&opts)
6434            .expect_err("non-zero right anchor must be rejected")
6435            .to_string();
6436        assert!(
6437            err.contains("right") && err.contains("-1"),
6438            "rejection should name the affected side and value: {err}"
6439        );
6440
6441        // With anchors at zero the basis builder accepts the configuration,
6442        // so the same alias plumbing yields a clean `Anchored { value: 0.0 }`
6443        // on the right and `Clamped` on the left.
6444        let mut opts = BTreeMap::new();
6445        opts.insert("start_bc".to_string(), "clamped".to_string());
6446        opts.insert("end_bc".to_string(), "zero".to_string());
6447        let parsed = parse_bspline_boundary_conditions(&opts).expect("boundary conditions");
6448        assert!(matches!(
6449            parsed.left,
6450            BSplineEndpointBoundaryCondition::Clamped
6451        ));
6452        assert!(matches!(
6453            parsed.right,
6454            BSplineEndpointBoundaryCondition::Anchored { value } if value.abs() < 1e-12
6455        ));
6456    }
6457
6458    #[test]
6459    fn categorical_by_numeric_interaction_expands_treatment_coded_cells() {
6460        // `y ~ x:g` is an INTERACTION-ONLY numeric-by-factor model: there is no
6461        // `x` main effect, so the marginal parent that would identify a dropped
6462        // reference level is ABSENT. The expansion must therefore be marginality-
6463        // aware (gam#1158) and DUMMY-code `g` — keep ALL levels — yielding the
6464        // "common intercept, separate slopes" design (one x-slope column per
6465        // group). Treatment-coding here (dropping the reference level) would pin
6466        // the reference group's slope to zero, a rank-deficient fit; that wrong
6467        // behaviour is what this test now guards against. (The treatment-coded
6468        // path is exercised when the `x` parent is present — see
6469        // `categorical_by_numeric_interaction_keeps_treatment_coding_with_parent`.)
6470        let ds = factor_dataset();
6471        // `g` is categorical with two levels (encoded 0.0 → "a", 1.0 → "b").
6472        let parsed = parse_formula("y ~ x:g").expect("parse `y ~ x:g`");
6473        let col_map = ds.column_map();
6474        let mut notes = Vec::new();
6475        let terms = build_termspec(
6476            &parsed.terms,
6477            &ds,
6478            &col_map,
6479            &mut notes,
6480            &ResourcePolicy::default_library(),
6481        )
6482        .expect("factor-aware `x:g` interaction must build, not error");
6483
6484        assert_eq!(
6485            terms.linear_terms.len(),
6486            2,
6487            "interaction-only `x:g` keeps ALL factor levels (full dummy coding): one slope column per group"
6488        );
6489
6490        let x_col = *col_map.get("x").expect("x column");
6491        let g_col = *col_map.get("g").expect("g column");
6492
6493        // Both level gates must appear exactly once across the two cell columns,
6494        // and each cell carries `x` as a product factor (not a raw column for g).
6495        let mut seen_bits = std::collections::HashSet::new();
6496        for term in &terms.linear_terms {
6497            assert!(
6498                term.is_interaction(),
6499                "the categorical-by-numeric cell is a Wilkinson-Rogers interaction"
6500            );
6501            assert_eq!(term.feature_cols, vec![x_col]);
6502            assert_eq!(term.categorical_levels.len(), 1);
6503            let (gate_col, gate_bits) = term.categorical_levels[0];
6504            assert_eq!(gate_col, g_col);
6505            assert!(seen_bits.insert(gate_bits), "each level appears once");
6506
6507            // Realize and check it equals `1[g == gate_bits] * x` row by row.
6508            let column = term
6509                .realized_design_column(ds.values.view())
6510                .expect("realize cell column");
6511            let n = ds.values.nrows();
6512            assert_eq!(column.len(), n);
6513            for row in 0..n {
6514                let x = ds.values[[row, x_col]];
6515                let g = ds.values[[row, g_col]];
6516                let expected = if g.to_bits() == gate_bits { x } else { 0.0 };
6517                assert!(
6518                    (column[row] - expected).abs() < 1e-12,
6519                    "row {row}: g={g}, x={x}, expected {expected}, got {}",
6520                    column[row]
6521                );
6522            }
6523        }
6524        // Both the reference level "a" (0.0) and the non-reference "b" (1.0) are
6525        // kept — the reference level is NOT dropped in the interaction-only form.
6526        assert!(seen_bits.contains(&0.0_f64.to_bits()));
6527        assert!(seen_bits.contains(&1.0_f64.to_bits()));
6528    }
6529
6530    #[test]
6531    fn categorical_by_numeric_interaction_keeps_treatment_coding_with_parent() {
6532        // With the `x` main effect PRESENT (`y ~ x + x:g`), the marginal parent
6533        // that identifies a dropped reference level exists, so `x:g` keeps its
6534        // historical treatment coding: the reference level "a" is dropped and
6535        // only the non-reference slope-deviation column for "b" is emitted. This
6536        // guards that the marginality-aware fix (gam#1158) does NOT regress the
6537        // parent-present form, which must stay column-space-identical to mgcv's
6538        // `x + x:g`.
6539        let ds = factor_dataset();
6540        let parsed = parse_formula("y ~ x + x:g").expect("parse `y ~ x + x:g`");
6541        let col_map = ds.column_map();
6542        let mut notes = Vec::new();
6543        let terms = build_termspec(
6544            &parsed.terms,
6545            &ds,
6546            &col_map,
6547            &mut notes,
6548            &ResourcePolicy::default_library(),
6549        )
6550        .expect("`x + x:g` must build");
6551
6552        // One main-effect `x` column plus one treatment-coded interaction cell.
6553        let x_col = *col_map.get("x").expect("x column");
6554        let g_col = *col_map.get("g").expect("g column");
6555        let interaction_cells: Vec<_> = terms
6556            .linear_terms
6557            .iter()
6558            .filter(|t| t.is_interaction())
6559            .collect();
6560        assert_eq!(
6561            interaction_cells.len(),
6562            1,
6563            "with `x` present, `x:g` is treatment-coded → one cell (reference dropped)"
6564        );
6565        let term = interaction_cells[0];
6566        assert_eq!(term.feature_cols, vec![x_col]);
6567        assert_eq!(term.categorical_levels.len(), 1);
6568        let (gate_col, gate_bits) = term.categorical_levels[0];
6569        assert_eq!(gate_col, g_col);
6570        // The dropped reference is "a" (0.0); the kept gate is "b" (1.0).
6571        assert_eq!(gate_bits, 1.0_f64.to_bits());
6572    }
6573
6574    #[test]
6575    fn categorical_by_categorical_interaction_expands_full_cross_cells() {
6576        // `y ~ f:g` is an INTERACTION-ONLY factor-by-factor model: neither `f`
6577        // nor `g` appears as a main effect, so neither marginal parent is
6578        // present and BOTH factors must be dummy-coded (gam#1159). The correct
6579        // design is the SATURATED cell-means model: the full cross of ALL levels
6580        // (3 * 2 = 6 cells) minus ONE reference cell (the lexicographically-first
6581        // level of every factor, here f0:g0) absorbed by the intercept — rank
6582        // 6-1 = 5 cell columns + intercept, column-space-identical to `f*g`.
6583        // Treatment-coding both factors (the old behaviour) kept only
6584        // (3-1)*(2-1) = 2 cells and collapsed the rest onto the intercept, a
6585        // rank-deficient fit; that is the bug this test now guards against.
6586        let n = 30usize;
6587        let mut rows = Vec::with_capacity(n);
6588        for i in 0..n {
6589            let y = (i as f64).sin();
6590            let f = (i % 3) as f64; // 3 levels: 0,1,2
6591            let g = (i % 2) as f64; // 2 levels: 0,1
6592            rows.push(vec![y, f, g]);
6593        }
6594        let values = Array2::from_shape_vec(
6595            (n, 3),
6596            rows.into_iter().flat_map(|row| row.into_iter()).collect(),
6597        )
6598        .expect("rectangular cross-factor data");
6599        let ds = Dataset {
6600            headers: vec!["y".into(), "f".into(), "g".into()],
6601            values,
6602            schema: DataSchema {
6603                columns: vec![
6604                    SchemaColumn {
6605                        name: "y".into(),
6606                        kind: ColumnKindTag::Continuous,
6607                        levels: vec![],
6608                    },
6609                    SchemaColumn {
6610                        name: "f".into(),
6611                        kind: ColumnKindTag::Categorical,
6612                        levels: vec!["f0".into(), "f1".into(), "f2".into()],
6613                    },
6614                    SchemaColumn {
6615                        name: "g".into(),
6616                        kind: ColumnKindTag::Categorical,
6617                        levels: vec!["g0".into(), "g1".into()],
6618                    },
6619                ],
6620            },
6621            column_kinds: vec![
6622                ColumnKindTag::Continuous,
6623                ColumnKindTag::Categorical,
6624                ColumnKindTag::Categorical,
6625            ],
6626        };
6627
6628        let parsed = parse_formula("y ~ f:g").expect("parse `y ~ f:g`");
6629        let col_map = ds.column_map();
6630        let mut notes = Vec::new();
6631        let terms = build_termspec(
6632            &parsed.terms,
6633            &ds,
6634            &col_map,
6635            &mut notes,
6636            &ResourcePolicy::default_library(),
6637        )
6638        .expect("factor-by-factor `f:g` interaction must build, not error");
6639
6640        assert_eq!(
6641            terms.linear_terms.len(),
6642            5,
6643            "saturated 3*2 = 6 cross cells minus one reference cell (f0:g0) = 5"
6644        );
6645
6646        let f_col = *col_map.get("f").expect("f column");
6647        let g_col = *col_map.get("g").expect("g column");
6648        // The dropped reference cell pairs each factor's lexicographically-first
6649        // level: f0 (0.0) and g0 (0.0). It must NOT appear among the emitted
6650        // cells; every OTHER cross cell must.
6651        let f0 = 0.0_f64.to_bits();
6652        let g0 = 0.0_f64.to_bits();
6653        let mut emitted = std::collections::HashSet::new();
6654        for term in &terms.linear_terms {
6655            // No numeric operand: the realized column is a pure cell indicator.
6656            assert!(term.feature_cols.is_empty());
6657            assert_eq!(term.categorical_levels.len(), 2);
6658            let mut gates = std::collections::HashMap::new();
6659            for &(col, bits) in &term.categorical_levels {
6660                gates.insert(col, bits);
6661            }
6662            let f_bits = *gates.get(&f_col).expect("f gate present");
6663            let g_bits = *gates.get(&g_col).expect("g gate present");
6664            // The reference cell f0:g0 must have been dropped.
6665            assert!(
6666                !(f_bits == f0 && g_bits == g0),
6667                "the reference cell f0:g0 must be absorbed by the intercept, not emitted"
6668            );
6669            emitted.insert((f_bits, g_bits));
6670
6671            let column = term
6672                .realized_design_column(ds.values.view())
6673                .expect("realize cross cell");
6674            for row in 0..n {
6675                let f = ds.values[[row, f_col]];
6676                let g = ds.values[[row, g_col]];
6677                let expected = if f.to_bits() == f_bits && g.to_bits() == g_bits {
6678                    1.0
6679                } else {
6680                    0.0
6681                };
6682                assert!(
6683                    (column[row] - expected).abs() < 1e-12,
6684                    "row {row}: expected {expected}, got {}",
6685                    column[row]
6686                );
6687            }
6688            assert!(
6689                column.iter().any(|&v| v == 1.0),
6690                "each cross cell must be observed in the data"
6691            );
6692        }
6693        // Every non-reference cross cell is present exactly once: all 6 cells
6694        // except f0:g0.
6695        let f_levels = [0.0_f64.to_bits(), 1.0_f64.to_bits(), 2.0_f64.to_bits()];
6696        let g_levels = [0.0_f64.to_bits(), 1.0_f64.to_bits()];
6697        for &fb in &f_levels {
6698            for &gb in &g_levels {
6699                if fb == f0 && gb == g0 {
6700                    continue;
6701                }
6702                assert!(
6703                    emitted.contains(&(fb, gb)),
6704                    "saturated cross cell must be present"
6705                );
6706            }
6707        }
6708    }
6709}