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