Skip to main content

gam_models/
gamlss.rs

1//! Multi-parameter GAMLSS family stack, organized into real concern modules.
2//!
3//! The historical single-file module was split textually with `include!`; this
4//! is the genuine module decomposition. The fitting math is one tightly-coupled
5//! namespace (families share layouts, the location-scale joint-ψ machinery, and
6//! the numeric foundation), so the concern submodules each open with
7//! `use super::*;` and this parent re-exports their cross-concern items flat via
8//! `pub(crate) use <module>::*`. That keeps every intra-stack reference resolving
9//! without a web of explicit per-symbol imports, while each file now holds a
10//! single concern:
11//!
12//! - `errors`    — `GamlssError`, module-wide numeric constants, the low-level
13//!                   row-map / design-resolution / joint-ψ-direction helpers, and
14//!                   the `ParameterLink` link-identifier enum (the shared
15//!                   foundation every family builds on).
16//! - `builders`  — block/penalty construction, term specs, fit-result types,
17//!                   the `LocationScaleFamilyBuilder` strategy + its four builders,
18//!                   and the public `fit_*` entry points (construction &
19//!                   orchestration).
20//! - `gaussian`  — the Gaussian location-scale family (+ its wiggle variant),
21//!                   the shared location-scale joint-ψ trait/workspace, the
22//!                   Gaussian joint-Hessian assembly, the matrix-free
23//!                   `RowCoeffOperator`, and the Poisson/Gamma log-link families.
24//! - `binomial`  — the binomial location-scale numeric kernel (q-algebra,
25//!                   towers, directional coefficients) and the binomial
26//!                   location-scale / wiggle / mean-wiggle families plus their
27//!                   exact-Newton Hessian workspaces.
28//!
29//! Pre-existing leaf concerns keep their own modules: `dispersion_family`,
30//! `binomial_q_derivs`, `binomial_q_coeffs`, `validation`,
31//! `weighted_design_products`, `row_linalg`, and `joint_packing`.
32
33use gam_terms::basis::{ActivePenaltyInfo, BasisOptions, PenaltySource};
34
35use crate::custom_family::{
36    AdditiveBlockJacobian, BlockEffectiveJacobian, BlockWorkingSet, BlockwiseFitOptions,
37    ConstraintSet, CustomFamily, CustomFamilyBlockPsiDerivative, CustomFamilyJointDesignChannel,
38    CustomFamilyJointDesignPairContribution, CustomFamilyJointPsiOperator,
39    CustomFamilyPsiDesignAction, CustomFamilyPsiLinearMapRef, CustomFamilyPsiSecondDesignAction,
40    CustomFamilyWarmStart, ExactNewtonJointGradientEvaluation, ExactNewtonJointHessianWorkspace,
41    ExactNewtonJointPsiDirectCache, FamilyEvaluation, ParameterBlockSpec, ParameterBlockState,
42    PenaltyMatrix, PsiDesignMap, evaluate_custom_family_joint_hyper,
43    evaluate_custom_family_joint_hyper_efs, evaluate_custom_family_joint_hyper_efs_owned,
44    evaluate_custom_family_joint_hyper_owned, fit_custom_family,
45    fit_custom_family_fixed_log_lambdas_from_owned_mode,
46    resolve_custom_family_x_psi_map, resolve_custom_family_x_psi_psi_map,
47    second_psi_linear_map, shared_dense_arc, weighted_crossprod_psi_maps,
48};
49use gam_problem::{ExactNewtonJointPsiSecondOrderTerms, ExactNewtonJointPsiWorkspace};
50
51use crate::model_types::UnifiedFitResult;
52
53use gam_linalg::faer_ndarray::{fast_ab, fast_atv, fast_av, fast_joint_hessian_2x2};
54
55use crate::block_layout::block_count::validate_block_count;
56
57use crate::location_scale_engine::build_location_scale_exact_joint_setup;
58
59use crate::parameter_block::ParameterBlockInput;
60
61use crate::scale_design::{build_scale_deviation_operator, build_scale_deviation_transform_design};
62
63use crate::sigma_link::{
64    LOGB_SIGMA_FLOOR, SigmaJet1, exp_sigma_derivs_up_to_fourth_scalar,
65    exp_sigma_derivs_up_to_third, exp_sigma_from_eta_scalar, exp_sigma_jet1_scalar,
66    logb_sigma_from_eta_scalar, logb_sigma_jet1_scalar, safe_exp,
67};
68
69use crate::spatial_psi_bridge::build_block_spatial_psi_derivatives;
70
71// The monotone-wiggle helpers live in the neutral `families::wiggle` module
72// (decoupling refactor); this block imports only the ones gamlss's own non-test
73// code uses. Symbols used solely by this module's `#[cfg(test)]` block
74// (`initializewiggle_knots_from_seed`, `monotone_wiggle_internal_degree`,
75// `split_wiggle_penalty_orders`) are imported inside that block instead, so they
76// are not flagged unused in a non-test `--lib` build; downstream consumers import
77// from `families::wiggle` directly.
78use crate::wiggle::{
79    SelectedWiggleBasis, WiggleBlockConfig, buildwiggle_block_input_from_knots,
80    monotone_wiggle_basis_with_derivative_order,
81    monotone_wiggle_nonnegative_constraints, project_monotone_wiggle_beta_nonnegative,
82    select_wiggle_basis_from_seed, validate_monotone_wiggle_beta_nonnegative,
83};
84
85use crate::inference::generative::{CustomFamilyGenerative, GenerativeSpec, NoiseModel};
86
87use gam_linalg::matrix::SymmetricMatrix;
88
89use gam_linalg::matrix::{DenseDesignOperator, DesignMatrix};
90
91use gam_solve::mixture_link::inverse_link_jet_for_inverse_link;
92
93use crate::probability::{normal_logcdf, normal_logsf, standard_normal_quantile};
94
95use crate::fit_orchestration::drivers::{
96    ExactJointEfsEvaluation, ExactJointEvaluation, ExactJointHyperSetup, SpatialFitProvenance,
97    freeze_term_collection_from_design, optimize_spatial_length_scale_exact_joint,
98    spatial_dims_per_term, spatial_length_scale_term_indices,
99};
100use gam_terms::smooth::{
101    BlockwisePenalty, PenaltyBlockInfo, SpatialLengthScaleOptimizationOptions,
102    SpatialLogKappaCoords, TermCollectionDesign, TermCollectionSpec,
103};
104// #1521: relocated DOWN into gam_terms::smooth (was drivers::build_term_collection_design).
105use gam_terms::smooth::build_term_collection_design;
106
107use crate::model_types::validate_all_finite_estimation;
108
109// #1521: relocated DOWN into gam-model-kernels (was gamlss::builders). The
110// penalized-WLS projection carries no gamlss type, so the family stack consumes
111// it from the base kernel crate; this re-export keeps the gamlss-internal
112// (`builders`/`dispersion_family`) call sites resolving unchanged.
113pub(crate) use crate::penalized_projection::solve_penalizedweighted_projection;
114
115use gam_problem::{InverseLink, StandardLink};
116
117use ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis, s};
118
119use rayon::prelude::*;
120
121use std::borrow::Cow;
122
123use std::collections::{HashMap, hash_map::DefaultHasher};
124
125use std::hash::{Hash, Hasher};
126
127use std::sync::atomic::AtomicUsize;
128
129use std::sync::{Arc, Mutex};
130
131// ---------------------------------------------------------------------------
132// Leaf concern modules (pre-existing real modules; their public surface is
133// folded into the flat gamlss namespace here so the family code can name them
134// unqualified, exactly as it did under the prior `include!` layout).
135// ---------------------------------------------------------------------------
136
137mod dispersion_family;
138pub use dispersion_family::{
139    DispersionAloRowGeometry, DispersionFamilyKind, DispersionGlmLocationScaleTermSpec,
140    FAMILY_BETA_LOCATION_SCALE, FAMILY_GAMMA_LOCATION_SCALE, FAMILY_NEGBIN_LOCATION_SCALE,
141    FAMILY_TWEEDIE_LOCATION_SCALE, dispersion_alo_row_geometry,
142    fit_dispersion_glm_location_scale_terms,
143};
144
145mod binomial_q_derivs;
146use binomial_q_derivs::{
147    binomial_neglog_q_derivatives_dispatch, binomial_neglog_q_fourth_derivative_dispatch,
148};
149
150mod binomial_q_coeffs;
151use binomial_q_coeffs::{
152    hessian_coeff_fromobjective_q_terms, mean_wiggle_directional_coefficients,
153    mean_wiggle_second_directional_coefficients,
154};
155mod validation;
156use validation::{
157    minimum_monotone_wiggle_knot_count, validate_binomial_location_scale_termspec,
158    validate_binomial_location_scalewiggle_termspec, validate_binomial_response,
159    validate_blockrows, validate_gaussian_location_scale_termspec,
160    validate_gaussian_location_scalewiggle_termspec, validate_len_match, validate_term_weights,
161    validateweights,
162};
163
164mod weighted_design_products;
165use weighted_design_products::{
166    mirror_upper_to_lower, scaled_outer_add, xt_diag_x_dense, xt_diag_x_design, xt_diag_y_dense,
167    xt_diag_y_design,
168};
169
170mod row_linalg;
171use row_linalg::scale_matrix_rows;
172
173mod joint_packing;
174use joint_packing::{
175    binomial_pack_mean_wiggle_joint_score, binomial_pack_mean_wiggle_joint_symmetrichessian,
176    gaussian_pack_joint_score, gaussian_pack_joint_symmetrichessian,
177    gaussian_pack_wiggle_joint_score, gaussian_pack_wiggle_joint_symmetrichessian,
178};
179
180// ---------------------------------------------------------------------------
181// Concern modules of the family stack itself. Each opens with `use super::*;`
182// and exposes its cross-concern items as `pub(crate)`; re-exporting them flat
183// here lets the stack reference any concern's symbols unqualified.
184// ---------------------------------------------------------------------------
185
186// `pub use … ::*` re-exports each concern's items at their own visibility:
187// `pub` family/spec/result types stay crate-public (the binary crate reaches
188// them via `gam::gamlss::…`), while `pub(crate)` helpers stay crate-internal.
189mod errors;
190pub use errors::*;
191
192mod builders;
193pub use builders::*;
194
195mod gaussian;
196pub use gaussian::*;
197
198mod binomial;
199pub use binomial::*;
200
201mod alo_replay;
202pub use alo_replay::{
203    BinomialLocationScaleAloRowInput, GaussianLocationScaleAloRowInput,
204    LocationScaleAloRowGeometry, binomial_location_scale_alo_row_geometry,
205    gaussian_location_scale_alo_row_geometry,
206};
207
208#[cfg(test)]
209mod test_support;
210
211#[cfg(test)]
212mod tests;
213
214#[cfg(test)]
215mod tests_outer_derivatives;
216
217#[cfg(test)]
218mod tests_dispersion_tower;