Expand description
High-level crate for Rust-native GAMLSS.
gamlss re-exports the typed core, ready-made distribution families,
spline/predictor building blocks, special functions and target transforms.
The primary approach is a low-level typed API through core, family,
spline and transform.
When the formula feature is enabled, the formula namespace is also
available. This layer is an experimental optional convenience API: it compiles
curated high-level builder specifications into typed core models, but is not
the primary API and does not promise to cover all distributions, links and
parameterizations from the low-level crates.
The bayes feature enables normalized coefficient priors and posterior
potentials through the bayes namespace. It is intentionally disabled by
default so non-Bayesian users do not acquire that API surface.
The rand feature enables the sampling API in family and corresponds to
the gamlss-family/rand feature.
The multivariate feature enables optional multivariate distribution
families in family.
§Key features
- typed
core::ParameterBlockfor each distribution parameter; core::ParameterBlocksfor automatic layout offsets in the common beta vector;- unweighted and weighted models via
core::Gamlss::try_newandcore::Gamlss::try_new_weighted; - prediction API for training rows and compatible prediction blocks;
- post-fit diagnostics namespace via
diagnostics; - optional normalized coefficient priors and posterior potentials with the
bayesfeature; - experimental formula builders via
formula::ModelSpecwhen theformulafeature is enabled.
§Example
use gamlss::prelude::*;
let y = [0.0, 1.0, 2.0];
let weights = [1.0, 0.5, 1.0];
let blocks = ParameterBlocks::try_new((
ParameterBlock::<Mu, _, _>::linear(
DenseDesign::from_rows(&[[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]),
NoPenalty,
0,
),
ParameterBlock::<Sigma, _, _>::linear(
DenseDesign::intercept(y.len()),
NoPenalty,
0,
),
))?;
let model = Gamlss::try_new_weighted(
gamlss::family::NormalMuSigma::new(),
blocks,
&y,
&weights,
)?;
let parameters = model.initial_parameters()?;
let fitted_theta = model.predict_theta(¶meters)?;
assert_eq!(fitted_theta.len(), y.len());§Структура проекта и уровни API
§Layout workspace
Workspace состоит из facade crate-а gamlss в корне репозитория и набора специализированных crate-ов:
gamlss— основная публичная точка входа, re-exports и общийprelude;gamlss-bayes— lightweight Bayesian boundary: normalized coefficient priors, posterior potential и pointwise log-likelihood без sampler backend;gamlss-core— type-driven ядро: links, parameter markers,ParameterBlock,ParameterBlocks, predictor contracts, observation views, objectives, compiled models, prediction helpers и typed family/model interfaces;gamlss-family— distribution-specific слой: univariate families, optional multivariate families, likelihoods, analytical score helpers, CDF/quantile/density/CRPS capability implementations и optional sampling API;gamlss-special— shared scalarf64special functions и численные helpers для likelihood, CDF, quantile и transform кода;gamlss-spline— spline/Fourier predictor blocks, row-basis helpers, sparse row metadata, tensor products и smoothness/shape penalties;gamlss-transform— target transforms, fitted transform state и domain-aware inverse transforms;gamlss-diagnostics— post-fit extension APIs поверх compiled models и prediction views: PIT/CDF values, normalized quantile residuals, CRPS values/summaries и reusable diagnostics views;gamlss-formula— experimental optional formula/builder layer, который читает runtime data/specifications, материализует predictor designs и компилирует curated workflows в typed core models.
В репозитории также есть examples для end-to-end примеров, tests для facade/public API проверок, crate-local tests для контрактов и численных проверок, docs для документации, .github/workflows для CI и issues для проектных заметок.
§Два уровня API
В библиотеке есть два основных уровня API.
§Низкоуровневое typed API
Низкоуровневое API — основной слой проекта. Оно строится вокруг типизированных parameter blocks, links, families, observations, objectives и compiled models:
gamlss-coreзадает базовые абстракции и не владеет конкретными распределениями;gamlss-familyреализует конкретные family contracts из core и хранит distribution-specific likelihood, score, chain-rule и domain logic;gamlss-specialсодержит общие численные building blocks, которые не должны дублироваться внутри families;gamlss-splineпредоставляет predictor blocks и penalties, совместимые с typedParameterBlock;gamlss-transformживет вокруг target preprocessing и persisted state, а не внутри compiled model hot path;gamlss-diagnosticsдобавляет post-fit вычисления через extension traits, не расширяя базовыйFamilycontract сверх необходимости.
Этот уровень рассчитан на код, где важны compile-time guarantees, явный layout параметров, отсутствие строковых lookup-ов в hot path, optimizer-agnostic objective surface и минимальные зависимости. Именно typed API является базовой поверхностью для integration layers, optimizer adapters, diagnostics и более высокоуровневых builders.
§Высокоуровневое API
Высокоуровневое API — convenience layer для более компактного описания модели. Сейчас оно представлено crate-ом gamlss-formula, который доступен из facade crate gamlss при включенной feature formula; эта feature включена по умолчанию.
gamlss-formula принимает typed runtime inputs через DataView и Col<T>, собирает curated term builders вроде intercept, linear, factor, interaction, offsets, P-splines, cyclic splines, Fourier terms, monotone terms и tensor P-splines, затем компилирует их в typed core models. Сейчас этот слой покрывает выбранные specs для normal, beta, gamma, inverse Gaussian, log-normal и Weibull workflows.
Этот слой предназначен для удобных workflows, но он не является заменой низкоуровневому API и намеренно не содержит string formula parser, fitting loop, optimizer integration, diagnostics, dataframe adapters или полного зеркала всех combinations of families, links, penalties и custom parameterizations, доступных напрямую через typed crates.
§Facade crate gamlss
Crate gamlss — основная точка входа для большинства пользователей. Он реэкспортирует основные workspace crate-ы:
coreдля typed ядра;familyдля distributions и likelihoods;specialдля special functions и численных helpers;splineдля spline/Fourier predictors и penalties;transformдля target preprocessing;diagnosticsдля post-fit diagnostics;bayesдля normalized coefficient priors и posterior potential, если включена featurebayes;formulaдля experimental formula/builder API, если включена featureformula.
Также facade crate предоставляет prelude, где собраны наиболее часто используемые типы из core, family, spline, transform и diagnostics, а при включённых соответствующих features — bayes и formula.
§Cargo features
Facade crate сейчас имеет четыре feature:
formulaвключена по умолчанию и добавляет re-export namespacegamlss::formula;bayesдобавляет opt-in re-export namespacegamlss::bayesи Bayesian-типы вgamlss::prelude;randпробрасываетgamlss-family/randи включает sampling API для families, где он реализован;multivariateпробрасываетgamlss-family/multivariateи включает optional multivariate distribution families.
Если нужен более строгий low-level dependency surface без experimental builder layer, можно использовать gamlss с default-features = false или зависеть от отдельных crate-ов напрямую.
§Поток данных
Типичный низкоуровневый workflow выглядит так:
- Пользователь при необходимости подготавливает response через
gamlss-transformи сохраняет fitted transform state рядом с модельными артефактами. - Пользователь выбирает distribution family из
gamlss-familyили реализует custom family поверх contracts изgamlss-core. - Для каждого параметра распределения создается свой
ParameterBlockс parameter marker, design/predictor и penalty; links принадлежат family и не дублируются в block type. - Несколько блоков объединяются в
ParameterBlocks, который задает общий layout beta-вектора и offsets. gamlss-coreкомпилирует family, blocks, response и optional weights вGamlss/workspace-backed model object через constructors вродеtry_new,try_new_weightedили strict observation paths.- Внешний optimizer работает с
Objective/gradient surface и не владеет modeling logic. - После fit-а пользователь вызывает prediction helpers для training rows или compatible prediction blocks, затем diagnostics extension APIs из
gamlss-diagnostics, если family exposes нужные capability traits.
Высокоуровневый builder слой должен приводить к той же compiled typed модели, а не выполнять отдельную интерпретацию formula/specification в hot path.
§Capability boundaries
Capabilities выражаются traits вместо глобальных runtime flags. Например, distribution functions, density/log-density, quantile, CRPS, simulation и multivariate transforms доступны только там, где family реализует соответствующий trait или включена нужная Cargo feature.
Compiled fitting является opt-in. CompilableFamily связывает family с sealed static shape tree (Scalar, Vector, Lower, StrictLower, Simplex, Product, Repeated, Broadcast), а DynamicallyCompilableFamily обслуживает отдельный runtime-dimensional path через DynamicParameterBlocks. Оба пути переиспользуют общую optimizer-independent модель и не переносят links или likelihood math в predictors.
Diagnostics построены поверх prediction views и capability traits вроде CDF/CRPS, поэтому их можно расширять без утяжеления базового family contract. Optimizer adapters должны оставаться тонкими: они адаптируют objective/gradient API, но не переносят modeling logic в optimizer crate.
§Границы зависимостей
gamlss-core намеренно остается легким и независимым от optimizer crates, dataframe libraries и тяжелых matrix backends. Более тяжелые integrations должны жить за optional features или в отдельных integration crate-ах.
gamlss-family зависит от core и special; sampling остается за optional rand. gamlss-spline зависит от core и реализует predictor/penalty pieces, а не отдельный modeling layer. gamlss-transform зависит от special для численных helpers и хранит transform-specific state отдельно от compiled model. gamlss-formula может быть динамическим boundary layer, но compiled model evaluation должна оставаться типизированной и эффективной.
Это разделение позволяет использовать core abstractions в разных окружениях: от небольших embedded-style numeric loops до более крупных ML pipelines с собственными matrix backends, dataframe adapters и optimizer stacks.
Re-exports§
pub use gamlss_bayes as bayes;pub use gamlss_core as core;pub use gamlss_diagnostics as diagnostics;pub use gamlss_family as family;pub use gamlss_special as special;pub use gamlss_spline as spline;pub use gamlss_transform as transform;pub use gamlss_formula as formula;
Modules§
- prelude
- Most commonly used imports.