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 rand feature enables the sampling API in family and corresponds to
the gamlss-family/rand feature.
§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; - 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, Identity, _, _>::linear(
DenseDesign::from_rows(&[[1.0, 0.0], [1.0, 1.0], [1.0, 2.0]]),
NoPenalty,
0,
),
ParameterBlock::<Sigma, Log, _, _>::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
§Два уровня API
В библиотеке есть два основных уровня API.
§Низкоуровневое typed API
Низкоуровневое API — основной слой проекта. Оно строится вокруг типизированных parameter blocks, links, families и compiled models:
gamlss-coreзадает базовые абстракции: link functions, parameter markers,ParameterBlock,ParameterBlocks, objective/model traits и compiled model evaluation;gamlss-familyсодержит распределения, likelihoods, score helpers и CDF/quantile utilities;gamlss-specialсодержит special functions и общие численные helpers для likelihood/CDF/quantile кода;gamlss-splineсодержит spline/Fourier predictors, penalties и metadata;gamlss-transformсодержит target transforms и persisted transform state;gamlss-diagnosticsсодержит post-fit diagnostics поверх fitted distributional models.
Этот уровень рассчитан на код, где важны compile-time guarantees, явный layout параметров, отсутствие строковых lookup-ов в hot path и минимальные зависимости. Именно typed API является базовой поверхностью для integration layers, optimizer adapters и более высокоуровневых builders.
§Высокоуровневое API
Высокоуровневое API — convenience layer для более компактного описания модели. Сейчас оно представлено optional crate-ом gamlss-formula, который доступен из facade crate gamlss при включенной feature formula.
gamlss-formula принимает runtime specifications и curated builder descriptions, затем компилирует их в typed core models. Этот слой предназначен для удобных workflows, но он не является заменой низкоуровневому API и не обязан зеркалировать все combinations of families, links, penalties и custom parameterizations, доступные напрямую через gamlss-core и соседние crate-ы.
§Facade crate gamlss
Crate gamlss — основная точка входа для большинства пользователей. Он реэкспортирует основные workspace crate-ы:
coreдля typed ядра;familyдля distributions и likelihoods;specialдля special functions и численных helpers;splineдля spline predictors и penalties;transformдля target preprocessing;diagnosticsдля post-fit diagnostics;formulaдля experimental formula/builder API, если включена featureformula.
Также facade crate предоставляет prelude, где собраны наиболее часто используемые типы.
§Поток данных
Типичный низкоуровневый workflow выглядит так:
- Пользователь выбирает distribution family из
gamlss-family. - Для каждого параметра распределения создается свой
ParameterBlockс parameter marker, link function, design/predictor и penalty. - Несколько блоков объединяются в
ParameterBlocks, который задает общий layout beta-вектора. gamlss-coreкомпилирует family, blocks, response и optional weights в objective/model object.- Внешний optimizer работает с objective/gradient surface, не владея modeling logic.
- После fit-а пользователь вызывает prediction и diagnostics helpers.
Высокоуровневый builder слой должен в итоге приводить к той же compiled typed модели, а не выполнять отдельную интерпретацию формулы в hot path.
§Границы зависимостей
gamlss-core намеренно остается легким и независимым от optimizer crates, dataframe libraries и тяжелых matrix backends. Более тяжелые integrations должны жить за optional features или в отдельных integration crate-ах.
Это разделение позволяет использовать core abstractions в разных окружениях: от небольших embedded-style numeric loops до более крупных ML pipelines с собственными matrix backends и optimizer stacks.
Re-exports§
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.