Skip to main content

mixeff_rs/
lib.rs

1//! Mixed-effects models in Rust.
2//!
3//! This crate provides types and algorithms for fitting linear and
4//! generalized linear mixed-effects models. It is developed against Julia's
5//! [MixedModels.jl](https://github.com/JuliaStats/MixedModels.jl) as the
6//! reference and parity target — the same PLS/PIRLS formulation, cross-checked
7//! numerically — but is an independent implementation with deliberate
8//! divergences (notably optimizer selection and the fallback strategy), not a
9//! line-for-line port.
10//!
11//! # Tutorial
12//!
13//! New to the crate? Read the [`guide`] module — five short, doctested
14//! pages:
15//!
16//! 1. [Getting started](crate::guide::getting_started) — build a frame,
17//!    parse a formula, fit an LMM.
18//! 2. [Reading results](crate::guide::reading_results) — coefficients,
19//!    variance components, summaries, Wald vs. profile vs. bootstrap CIs.
20//! 3. [GLMMs](crate::guide::glmms) — families, links, and the GLMM
21//!    estimation semantics.
22//! 4. [When the crate refuses](crate::guide::when_the_crate_refuses) —
23//!    typed errors and typed inference refusals (the no-fake-statistics
24//!    contract from a caller's POV).
25//! 5. [What is supported](crate::guide::what_is_supported) — a concrete
26//!    inventory: model classes, families/links, formula syntax, inference
27//!    paths, and what is deliberately out of scope.
28//!
29//! # Quick start
30//!
31//! Fit a linear mixed model `y ~ 1 + x + (1 | g)` on a small balanced dataset.
32//! The [`prelude`] pulls in the common types and the
33//! [`LinearMixedModelBuilder`](crate::model::LinearMixedModelBuilder)
34//! collapses construction and the ML/REML choice into one chain:
35//!
36//! ```
37//! use mixeff_rs::prelude::*;
38//! use mixeff_rs::model::{FitOptions, LinearMixedModelBuilder};
39//!
40//! # fn main() -> Result<()> {
41//! let group_offsets = [-3.0, -1.5, 0.5, 2.0, -2.0, 1.0, 3.0, -0.5];
42//! let jitter = [0.12, -0.20, 0.05, 0.17, -0.09, 0.22];
43//!
44//! let mut y = Vec::new();
45//! let mut x = Vec::new();
46//! let mut g = Vec::new();
47//! for (gi, off) in group_offsets.iter().enumerate() {
48//!     for (k, j) in jitter.iter().enumerate() {
49//!         let xv = k as f64;
50//!         x.push(xv);
51//!         y.push(2.0 + 1.5 * xv + off + j);
52//!         g.push(format!("g{gi}"));
53//!     }
54//! }
55//!
56//! let mut df = DataFrame::new();
57//! df.add_numeric("y", y)?;
58//! df.add_numeric("x", x)?;
59//! df.add_categorical("g", g)?;
60//!
61//! let model = LinearMixedModelBuilder::new(parse_formula("y ~ 1 + x + (1 | g)")?, &df)
62//!     .fit(FitOptions::reml())?; // or FitOptions::ml()
63//!
64//! let coef = model.coef(); // fixed effects, ~[2.0, 1.5]
65//! assert_eq!(coef.len(), 2);
66//! assert!(coef.iter().all(|v| v.is_finite()));
67//! # Ok(())
68//! # }
69//! ```
70//!
71//! The lower-level form (`LinearMixedModel::new(formula, &df, None)?` then
72//! `model.fit(false)`) remains available; the builder is purely additive.
73
74#![warn(rustdoc::broken_intra_doc_links)]
75#![warn(rustdoc::bare_urls)]
76// Clippy allowlist policy (v1.0 — see docs/v1_0_release_roadmap.md Phase D #18).
77//
78// This crate is a numerically-faithful implementation of the MixedModels.jl
79// algorithms. Style-lint exceptions that protect reference-algorithm structure
80// are kept next to the affected kernel, with a reason naming the index or
81// accumulation invariant. The remaining crate-wide exceptions cover API and
82// boundary contracts that genuinely span modules:
83//
84// - `too_many_arguments`: solver/optimizer entry points mirror the reference
85//   API surface (θ, β, weights, blocks, …) and the inference contract docs;
86//   bundling into ad-hoc structs would diverge from that contract.
87// - `type_complexity`: blocked-factor return tuples (`Vec<MatrixBlock>`, …) are
88//   intrinsic; aliasing them adds indirection without improving clarity.
89// - `float_equality_without_abs` / `neg_cmp_op_on_partial_ord`: optimizer and
90//   boundary logic compare against exact values (e.g. θ exactly at the lower
91//   bound `0.0`) and use partial-order comparisons deliberately; an `abs()`
92//   tolerance or total-order wrapper would change boundary/sentinel semantics.
93#![allow(clippy::too_many_arguments)]
94#![allow(clippy::type_complexity)]
95#![allow(clippy::float_equality_without_abs)]
96#![allow(clippy::neg_cmp_op_on_partial_ord)]
97
98// Re-exported so downstream code can name the exact `nalgebra` this crate
99// builds against (it appears in public signatures, e.g. `DMatrix`/`DVector`)
100// without pinning its own dependency to our minor version.
101pub use nalgebra;
102
103/// Declare one or more methods that belong to the **unstable internal**
104/// surface.
105///
106/// Each wrapped method is emitted as `pub` only when the opt-in
107/// `unstable-internals` Cargo feature is enabled; otherwise it is emitted as
108/// `pub(crate)`. This is the per-item analogue of the module-level
109/// `#[cfg(feature = "unstable-internals")] pub mod / pub(crate) mod` pattern
110/// used for `compiler` / `datasets` / `pathology`. Raw numerical solver entry
111/// points (`update_l`, `objective_at`, the Kenward-Roger builders, the KKT
112/// certificate, …) leak PLS internals and so must not be part of the stable
113/// 1.0 surface, but in-tree benches/examples and the `unstable-internals`
114/// consumers still need them. See docs/semver_policy.md.
115///
116/// Apply `unstable-internals`-gated visibility to a method.
117///
118/// Each invocation re-emits a single method with `pub` when the
119/// `unstable-internals` feature is on and `pub(crate)` otherwise, by token
120/// substitution on the leading visibility keyword. Write the method with a
121/// placeholder `unstable_vis` where the visibility would go:
122///
123/// ```ignore
124/// unstable_internal_method! {
125///     /// docs
126///     unstable_vis fn foo(&self) -> u32 { 1 }
127/// }
128/// ```
129macro_rules! unstable_internal_method {
130    ( $(#[$attr:meta])* unstable_vis $($rest:tt)* ) => {
131        #[cfg(feature = "unstable-internals")]
132        $(#[$attr])*
133        pub $($rest)*
134
135        #[cfg(not(feature = "unstable-internals"))]
136        $(#[$attr])*
137        pub(crate) $($rest)*
138    };
139}
140
141// `compiler`, `datasets`, and `pathology` are NOT part of the stable 1.0
142// public API (the compiler/IR is still in flux; dataset provenance metadata
143// churns). They are public only under the opt-in `unstable-internals`
144// feature so that every IR refinement is not a SemVer-major break. Internal
145// crate code always reaches them via `pub(crate)`. See
146// docs/semver_policy.md and docs/v1_0_release_roadmap.md Phase A.
147#[cfg(feature = "unstable-internals")]
148pub mod compiler;
149#[cfg(not(feature = "unstable-internals"))]
150pub(crate) mod compiler;
151
152#[cfg(feature = "unstable-internals")]
153pub mod datasets;
154#[cfg(not(feature = "unstable-internals"))]
155pub(crate) mod datasets;
156
157pub mod error;
158pub mod formula;
159/// Narrative tutorial pages (rendered on docs.rs, doctested in CI).
160pub mod guide;
161// Numerical primitives (blocked Cholesky, pivoted QR, rank updates). Internal
162// to the crate's fit path; not part of the stable public API. Demoted from
163// `pub` for v1.0 — see docs/v1_0_release_roadmap.md Phase A.
164pub(crate) mod linalg;
165pub mod model;
166mod optimizer;
167pub(crate) mod parallel;
168
169#[cfg(feature = "unstable-internals")]
170pub mod pathology;
171#[cfg(not(feature = "unstable-internals"))]
172pub(crate) mod pathology;
173
174pub mod stats;
175pub mod types;
176
177/// Common imports for fitting and inspecting mixed models.
178///
179/// Glob-importing the prelude pulls in the handful of types needed to
180/// build a [`DataFrame`](crate::model::DataFrame), parse a formula, fit a
181/// model, and read its estimates:
182///
183/// ```
184/// use mixeff_rs::prelude::*;
185///
186/// # fn main() -> Result<()> {
187/// let mut df = DataFrame::new();
188/// df.add_numeric("y", vec![1.0, 2.1, 3.0, 4.2, 5.1, 6.0])?;
189/// df.add_numeric("x", vec![0.0, 1.0, 0.0, 1.0, 0.0, 1.0])?;
190/// df.add_categorical(
191///     "g",
192///     vec!["a", "a", "b", "b", "c", "c"]
193///         .into_iter()
194///         .map(str::to_string)
195///         .collect(),
196/// )?;
197///
198/// let formula = parse_formula("y ~ 1 + x + (1 | g)")?;
199/// let mut model = LinearMixedModel::new(formula, &df, None)?;
200/// model.fit(false)?;
201/// assert_eq!(model.coef().len(), 2);
202/// # Ok(())
203/// # }
204/// ```
205pub mod prelude {
206    pub use crate::error::{MixedModelError, Result};
207    pub use crate::formula::parse_formula;
208    pub use crate::model::{
209        DataFrame, Family, GeneralizedLinearMixedModel, LinearMixedModel, LinkFunction,
210        MixedModelFit,
211    };
212}
213
214// Compile and run the README's Rust examples as doctests so the quick start
215// cannot drift from the public API.
216#[cfg(doctest)]
217#[doc = include_str!("../README.md")]
218pub struct ReadmeDoctests;