bayes-rs
A comprehensive Rust library for Bayesian inference with MCMC samplers, featuring robust statistical distributions and advanced diagnostic tools.
Features
- MCMC Samplers: Metropolis-Hastings, Gibbs, and Hamiltonian Monte Carlo (HMC)
- Statistical Distributions: Normal, Multivariate Normal, Gamma, Beta, Exponential, Uniform, Student's t
- MCMC Diagnostics: Effective sample size, R-hat statistic, MCSE summaries, autocorrelation analysis, trace plots
- Multi-chain workflows: Run multiple seeded chains with a shared warmup/sample schedule
- Best Practices: Comprehensive error handling, extensive testing, performance benchmarks
- Easy to Use: Clean API with extensive documentation and examples
Quick Start
Add this to your Cargo.toml:
[]
= "0.2.0"
Enable the optional serde feature when you want to serialize user-facing MCMC output:
[]
= { = "0.2.0", = ["serde"] }
Simple Example
use ;
use DVector;
// Define a log posterior function
let log_posterior = ;
// Set up sampler
let initial_state = from_vec;
let proposal_std = from_vec;
let mut sampler = new.unwrap;
// Generate samples after discarding warmup iterations
let samples = sampler.sample_with_warmup;
println!;
sample_with_warmup discards initial iterations and resets sampler statistics before collecting the returned samples; it does not adapt proposal scales or other tuning parameters automatically.
MCMC Samplers
Metropolis-Hastings
The workhorse of MCMC sampling with adaptive proposal tuning:
use ;
let mut sampler = new?;
// Run pilot adaptation before collecting samples
for _ in 0..1_000
sampler.reset_statistics;
let samples = sampler.sample;
println!;
Hamiltonian Monte Carlo (HMC)
Efficient sampling using gradient information:
use ;
let gradient_fn = ;
let mut hmc_sampler = new?;
let samples = hmc_sampler.sample;
Gibbs Sampling
For models with known conditional distributions:
use ;
let conditional_samplers = vec!;
let mut gibbs_sampler = new?;
Statistical Distributions
Univariate Distributions
use *;
// Normal distribution
let normal = new?;
println!;
println!;
// Gamma distribution
let gamma = new?;
println!;
// Beta distribution
let beta = new?;
println!;
// Student's t-distribution
let t_dist = new?;
println!;
Multivariate Distributions
use MultivariateNormal;
use ;
let mu = from_vec;
let cov = from_vec;
let mvn = new?;
let x = from_vec;
println!;
MCMC Diagnostics
Comprehensive diagnostic tools to assess convergence and sample quality:
use ;
// Single chain diagnostics
let diagnostics = from_single_chain?;
println!;
println!;
println!;
// Multiple chain diagnostics (includes R-hat)
let diagnostics = from_multiple_chains?;
let summary = diagnostics.summary;
if let Some = &diagnostics.r_hat
println!;
// Run multiple pre-configured, independently seeded samplers and summarize in one step.
// The slice must contain at least two samplers of the same concrete sampler type,
// and at least two retained samples per chain are required for R-hat.
use run_multiple_chains;
let mut seeded_chains = ;
let output = run_multiple_chains?;
println!;
// Trace plots
let trace_plot = new?; // Parameter 0
// Use trace_plot.values and trace_plot.iterations for visualization
With the optional serde feature enabled, McmcDiagnostics, McmcDiagnosticSummary,
ParameterDiagnosticSummary, TracePlot, and MultiChainOutput derive Serialize for
JSON or other serde formats:
let summary_json = to_string_pretty?;
Add serde_json or another serde format crate to your application to emit a concrete format.
These structs use Rust field names in their serialized form. Treat that JSON shape as a
convenient interchange format for the current API, not as a long-term storage schema.
JSON serializers may reject non-finite diagnostics such as NaN or Infinity from
degenerate chains; handle those cases before persisting JSON output.
Real-World Example: Bayesian Linear Regression
use ;
// Usage
let x_data = vec!;
let y_data = vec!;
let samples = bayesian_linear_regression?;
let diagnostics = from_single_chain?;
println!;
println!;
Performance
Run benchmarks to see performance characteristics:
The library is optimized for:
- Efficient matrix operations using
nalgebra - Minimal memory allocations during sampling
- Fast distribution computations with precomputed constants
Error Handling
The library uses comprehensive error handling with the BayesError enum:
use ;
match new
Testing
Run the comprehensive test suite:
# Unit tests
# Integration tests
# All tests with output
Examples
See the examples/ directory for complete examples:
# Bayesian linear regression example
Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Development Setup
License
This project is licensed under the MIT License - see the LICENSE file for details.
Citation
If you use this library in your research, please cite: