tpt_sci_ppl/lib.rs
1//! # tpt-sci-ppl
2//!
3//! Probabilistic programming for the `tpt-science` pillar: a small model/DSL
4//! layer and a from-scratch NUTS (No-U-Turn Sampler) Hamiltonian Monte Carlo
5//! backend.
6//!
7//! The original `spec.txt` planned to wrap `nuts-rs`; per the project's
8//! "build our own internals" direction this crate implements NUTS directly on
9//! top of the `tpt-math` substrate — reverse-mode gradients come from
10//! [`tpt_math_autodiff_rev`] and randomness from `tpt-math-prob` — so there is
11//! no external sampler dependency to audit or license-check.
12//!
13//! Priors are expressed as reverse-mode differentiable closures (so the NUTS
14//! gradient is exact). They can be written directly with the parameter
15//! `autodiff` variable, or derived from a typed distribution in
16//! `tpt-math-prob-bayes` ([`Gaussian`], [`Beta`], [`Gamma`]) via
17//! [`ModelBuilder::gaussian_prior`], [`ModelBuilder::beta_prior`], and
18//! [`ModelBuilder::gamma_prior`]. The likelihood is a second differentiable
19//! closure over the parameters and the observed data.
20//!
21//! ## Example
22//!
23//! ```rust
24//! use tpt_sci_ppl::ModelBuilder;
25//! use tpt_math_prob_core::SplitMix64;
26//!
27//! // mu ~ N(0, 5), data | mu ~ N(mu, 1)
28//! let data = [2.0, 3.0, 2.5, 3.5, 3.0];
29//! let mut m = ModelBuilder::new();
30//! m.gaussian_parameter(0.0, 5.0);
31//! m.set_data(data.to_vec());
32//! m.likelihood(|t, v, d| {
33//! let mut s = t.constant(0.0);
34//! for &x in d.iter() {
35//! let z = (v[0] - x) / 1.0;
36//! s = s + (-0.5 * z * z);
37//! }
38//! s
39//! });
40//! let model = m.build().unwrap();
41//! let mut rng = SplitMix64::seed_from_u64(1);
42//! let trace = model.fit(&mut rng, 500).unwrap();
43//! let samples = trace.combined_samples();
44//! let mean: f64 = samples.iter().map(|s| s[0]).sum::<f64>() / samples.len() as f64;
45//! assert!((mean - 2.8).abs() < 0.6);
46//! ```
47//!
48//! The same prior written from a typed [`Gaussian`]:
49//!
50//! ```rust
51//! use tpt_sci_ppl::{ModelBuilder, Gaussian};
52//! use tpt_math_prob_core::SplitMix64;
53//!
54//! let data = [2.0, 3.0, 2.5, 3.5, 3.0];
55//! let mut m = ModelBuilder::new();
56//! m.gaussian_prior(Gaussian::new(0.0, 5.0));
57//! m.set_data(data.to_vec());
58//! m.likelihood(|t, v, d| {
59//! let mut s = t.constant(0.0);
60//! for &x in d.iter() {
61//! let z = (v[0] - x) / 1.0;
62//! s = s + (-0.5 * z * z);
63//! }
64//! s
65//! });
66//! let model = m.build().unwrap();
67//! let mut rng = SplitMix64::seed_from_u64(1);
68//! let _ = model.fit(&mut rng, 50).unwrap();
69//! ```
70
71pub mod error;
72pub mod gradient;
73pub mod model;
74pub mod nuts;
75pub mod trace;
76
77pub use error::PplError;
78pub use model::{Model, ModelBuilder};
79pub use nuts::{NutsOptions, Target, nuts, nuts_with_options};
80pub use tpt_math_autodiff_rev::{GradientTape, Variable};
81pub use tpt_math_prob_bayes::{Beta, Gamma, Gaussian};
82pub use tpt_math_prob_core::Rng;
83pub use trace::Trace;