Expand description
§markov-chain-monte-carlo

Research-oriented Metropolis-Hastings tools in Rust for ordinary numeric states, large combinatorial state spaces, and proposal implementations that need rollback-safe mutation or delayed commits.
§📐 Introduction
This library implements composable Metropolis-Hastings sampling in Rust for workflows where the state space, proposal mechanism, and measurement strategy are application-specific. It is designed for research code where proposal kernels, observables, and scientific validity checks live in domain code, while the sampler owns the transition bookkeeping.
The Metropolis-Hastings contract is explicit: targets return unnormalized natural log weights, proposals describe the same concrete transition they generate, and proposal asymmetry stays in the Hastings correction. The crate is useful for simple numeric examples, spin systems, triangulation moves, and other large combinatorial state spaces where cloning, rollback, or delayed commits matter.
🚧 Pre-release (0.x) — This is research software under active development. APIs may change before 1.0.
Use this crate when you want:
- a generic Metropolis-Hastings chain over user-defined state spaces
- by-value, in-place, and delayed-commit proposal APIs
- log-space acceptance calculations with NaN/+infinity checks
- additive target composition for bias potentials, energy/action terms, externally supplied learned regularizers, and other log-weight modifiers
- observable measurement APIs, streaming statistics, and binning-based uncertainty estimates for correlated samples
- trace recording and CSV export for downstream MCMC diagnostics
- thinning helpers for long sampler runs
- optional
serdecheckpointing with validated resume flows - detailed-balance diagnostics for proposal development
This crate provides the sampler mechanics; proposal correctness, ergodicity, convergence assessment, and scientific model choice remain domain-specific responsibilities.
§🧪 Scientific basis
The acceptance rule is the standard Metropolis-Hastings correction:
alpha(x, y) = min(1, exp(log pi(y) - log pi(x) + log q(x | y) - log q(y | x)))Target<S> supplies log pi(s) up to an additive constant. Proposal implementations either use the default symmetric correction or supply the proposal ratio
for the same concrete transition they generate. For asymmetric combinatorial moves, that usually means accounting for move-kind probabilities, valid-site
counts, reverse-site counts, and invalid-move handling.
Physics actions and externally supplied learned regularizer terms fit the same target interface: implement Target::log_prob as an unnormalized log weight, or
as -E(state) when working in energy/action form. Training learned energies or adaptive proposal policies is outside the current crate scope.
The crate checks local transition mechanics: log-space acceptance, invalid floating-point values, rollback for in-place proposals, delayed commits, counters, checkpoints, and empirical detailed-balance diagnostics for representative discrete transitions. It does not prove that a proposal is ergodic, that a chain has mixed, or that a scientific model is appropriate for a downstream study.
For the detailed contract, see the scientific basis and scope guide.
§✨ Features
- Generic
Chain<S>over user-defined state spaces with explicit accepted/rejected counters. - Log-space Metropolis-Hastings acceptance with typed errors for NaN and positive-infinite target or proposal values.
AdditiveTargetfor composing model and bias log-weight terms without mixing them into proposal-ratio corrections.- Three proposal workflows: by-value
Proposal, rollback-safe in-placeProposalMut, and delayed-commitDelayedProposal. Samplerhelpers for repeated and chunked runs, iterator-style sampling, thinning, observations, and counter resets after burn-in.- Streaming
OnlineStatsandBinningAnalysisfor long correlated runs without retaining every sample. TraceRecorderandTracefor numeric observable traces with chain IDs, accept/reject metadata, and CSV export.ChainCheckpointrestore APIs that recompute cached log-probabilities against the resumed target.- Optional
serdesupport for serializing chains, samplers, and portable checkpoints. - Detailed-balance diagnostics for proposal tests on representative discrete transitions.
§Contents
- 📐 Introduction
- 🧪 Scientific basis
- ✨ Features
- 🚀 Quick start
- 🧭 Choosing an API
- 📦 Cargo features
- 🧪 Examples
- 📖 Documentation
- 👀 Reviewer guide
- 🧩 Ecosystem
- 🤝 Contributing
- 📚 Citation
- 🔎 References
- 🤖 AI-assisted development
- 📜 License
§🚀 Quick start
Add the library to your crate:
cargo add markov-chain-monte-carloEnable checkpoint serialization when needed:
cargo add markov-chain-monte-carlo --features serdeRust 1.97.1 or newer is required.
Minimal by-value Metropolis-Hastings sampler. This example demonstrates the transition mechanics; convergence assessment remains a separate analysis step.
use markov_chain_monte_carlo::prelude::by_value::*;
use rand::{Rng, RngExt, SeedableRng, rngs::StdRng};
#[derive(Clone)]
struct Scalar(f64);
struct Normal;
impl Target<Scalar> for Normal {
fn log_prob(&self, state: &Scalar) -> f64 {
-0.5 * state.0 * state.0
}
}
struct RandomWalk {
width: f64,
}
impl Proposal<Scalar> for RandomWalk {
fn propose<R: Rng + ?Sized>(&self, current: &Scalar, rng: &mut R) -> Scalar {
let delta = rng.random_range(-self.width..self.width);
Scalar(current.0 + delta)
}
}
fn main() -> Result<(), McmcError> {
let mut rng = StdRng::seed_from_u64(42);
let mut chain = Chain::new(Scalar(0.0), &Normal)?;
let proposal = RandomWalk { width: 1.0 };
for _ in 0..1000 {
chain.step(&Normal, &proposal, &mut rng)?;
}
assert!(chain.acceptance_rate() > 0.0);
Ok(())
}§🧭 Choosing an API
- Start with
ProposalandChain::stepwhen state cloning is cheap. - Use
ProposalMutandChain::step_mutwhen cloning state is expensive and rollback is simple; itsInfometadata is returned in structuredSteptelemetry for accepted and rejected proposals.StepOutcome::NoProposalcarries metadata only whenProposalMut::no_proposal_infoprovides it. - Drive
Sampler::step_mutexplicitly when every transition needs metadata. BulkSampler::run_mut*methods deliberately skipInfoconstruction and proposal telemetry hooks, so metadata that would be discarded is not constructed. - Use
DelayedProposalandChain::step_delayedwhen you need to plan and score a concrete move before mutating state. - Use
AdditiveTargetwhen the target log weight is the sum of model, bias, energy, action, or externally supplied regularizer terms. - Use
DelayedSteptelemetry,StepOutcome, andDelayedProposal::no_plan_infowhen delayed proposals need domain-specific per-step records. - Use
Samplerwhen you want ergonomic repeated runs, resumable chunks, iterator-based sampling, or observing helpers. - Parse raw positive thinning counts with
ThinningInterval::new, then reuse the validated interval acrossSampler::*_with_thinningcalls. - Use
Sampler::run_delayed_chunk_observingto record per-step delayed telemetry and post-step state while resuming chunked runs from aChainCheckpoint. - Use
TraceRecorderwhen you need reusable numeric traces with chain IDs, acceptance metadata, target log-probabilities, and CSV export. - Use
verify_detailed_balance*helpers in proposal tests for representative discrete transitions. - Use
OnlineStatsandBinningAnalysiswhen long runs should stream statistics instead of retaining every sample.
When migrating from the previous in-place API, add ProposalMut::Info, implement info (and optionally no_proposal_info), make proposal mutation hooks
accept &mut self, and read the Step returned by Chain::step_mut or Sampler::step_mut instead of a boolean. Rejection must restore both the state and
proposal-internal transition state. Keep telemetry hooks observational because bulk execution may skip them. For earlier thinning and
delayed-telemetry APIs, replace raw thinning usize arguments with a parsed ThinningInterval, handle the underlying sampler or observation error directly
instead of matching ThinningError::Run, and replace Step field reads with the corresponding outcome(), info(), log_prob_before(),
log_prob_after(), and log_alpha() accessors.
§📦 Cargo features
serde— enableserde::SerializeforChainandSampler, plusChainCheckpointserialization/deserialization for validated resume flows.
§🧪 Examples
Complete runnable examples live in examples/:
examples/normal_1d.rs— by-value random-walk sampler for a normal targetexamples/ising_1d.rs— in-place spin-flip proposals for a non-CloneIsing state, with energy/magnetization trace CSV exportexamples/iterator_sampling.rs—Sampleras an iteratorexamples/detailed_balance.rs— by-value, in-place, delayed, and batch detailed-balance checksexamples/delayed_chunked_telemetry.rs— per-step delayed telemetry and post-step state recorded across resumable chunksexamples/additive_target_bias.rs— model and bias log-weight terms composed withAdditiveTarget
Run them with:
just examplesFor proposal-specific testing patterns, see the proposal validation guide.
The Ising trace notebook lives at
notebooks/ising_trace_analysis.ipynb. Run
just notebook-check to generate target/ising_1d_trace.csv, validate the source notebook, and write a headlessly executed copy under target/notebooks/.
§📖 Documentation
- docs.rs API documentation
- Reviewer guide
- Changelog
- Scientific basis and scope
- Proposal validation guide
- Roadmap
- Code organization guide
- Rust development workflow
- Release process
- Security policy
§👀 Reviewer guide
For a short reading path through the repository’s scientific contract, validation strategy, roadmap boundaries, and reproducible local checks, see
docs/reviewer_guide.md.
§🧩 Ecosystem
This crate is part of a broader Rust ecosystem for computational geometry and simulation:
causal-triangulations— CDT physics and simulationdelaunay— geometric primitives and triangulationsla-stack— fixed-size linear algebra
The long-term architecture separates:
- Geometry: triangulations and geometric predicates
- Sampling: this crate
- Physics: CDT actions, observables, and domain-specific dynamics
§🤝 Contributing
See CONTRIBUTING.md for the full contributor guide (project layout,
development workflow, code style, testing, documentation layout, performance/benchmarking, and the release process). Community expectations live in
CODE_OF_CONDUCT.md. AI assistants should follow
AGENTS.md.
Quick local workflow: run just setup once, then run just check before opening a pull request. For the full command list, run just --list.
§📚 Citation
If you use this crate in academic work or downstream research software, please cite it using
CITATION.cff or GitHub’s “Cite this repository” feature.
§🔎 References
For canonical background references for Metropolis-Hastings, MCMC, and the example models, see
REFERENCES.md.
§🤖 AI-assisted development
This repository contains an AGENTS.md file, which defines the rules and invariants for AI coding assistants and autonomous agents working on this codebase.
Portions of this library were developed with the assistance of AI tools including ChatGPT, Claude, Codex, and CodeRabbit.
All accepted code and documentation changes are reviewed, edited, and validated by the author.
For tool citation metadata, see the
AI-assisted development tools section of
REFERENCES.md.
§📜 License
This project is licensed under the BSD 3-Clause License.
§API contract
Target::log_prob should return an unnormalized natural log-probability
or log-density. Additive constants are fine because Metropolis-Hastings
only uses differences, but arbitrary scores or logits will sample a
different distribution.
Each transition uses the standard Metropolis-Hastings acceptance rule:
alpha(x, y) = min(1, exp(log pi(y) - log pi(x) + log q(x | y) - log q(y | x)))Proposal implementations must describe the same concrete transition in both
the generated move and log_q_ratio. Irreducibility, convergence, and the
scientific meaning of observables remain caller responsibilities.
§Additive target terms
Bias potentials, umbrella-sampling weights, softened constraints, auxiliary
energy/action terms, externally supplied learned regularizer terms, and
other target modifiers should be sampled as part of the target distribution,
not applied as ad hoc rejection filters after a proposal has been generated.
Use AdditiveTarget when model and bias terms are easiest to express as
separate log-weight components. The crate treats learned regularizers as
already supplied log-weight terms; it does not train learned energies or
adaptive proposal policies.
If a downstream model is written in action form, implement each component
with the same sign convention: return -S_component(state). Then the
acceptance calculation uses the combined action delta naturally:
log pi(y) - log pi(x) = -(Delta S_model + Delta S_bias)The Hastings correction remains independent and is still supplied through
Proposal::log_q_ratio, ProposalMut::log_q_ratio, or
DelayedProposal::log_q_ratio:
log_alpha = -(Delta S_model + Delta S_bias) + log q(x | y) - log q(y | x)§Numerical semantics
The core Metropolis-Hastings acceptance calculation is performed in log
space using f64. Domain-specific code may use exact arithmetic internally
for predicates or invariant checks, but targets and proposal ratios cross the
crate boundary as log weights:
- finite values represent unnormalized log probability mass/density
f64::NEG_INFINITYrepresents an impossible or zero-probability stateNaNlog-probabilities and log proposal ratios are rejected withMcmcError+∞log-probabilities and log proposal ratios are rejected withMcmcError- acceptance ratios that become
NaNduring arithmetic, such as-∞ - (-∞), are treated as rejection
§Long runs and parallelism
Chain, Sampler, proposal values, and RNGs are ordinary per-instance
values; the crate does not use global mutable state. Run independent chains
in parallel by giving each worker its own chain, proposal state, and RNG
stream. This keeps reproducibility and RNG stream splitting under caller
control.
Bulk observing methods return a SampleBuffer, which stores one output
per step. For production runs with many samples, use compact observables or
single-step observing loops when retaining every measurement is unnecessary.
OnlineStats and BinningAnalysis provide constant-memory statistics
for those streaming measurement loops. Samplers also provide
*_with_thinning variants to collect cloned states or measurements only
every k-th completed step while still advancing the chain on every step.
Parse raw positive intervals once with ThinningInterval::new, then pass
the proof-bearing interval to any thinned method.
For workflows that choose the next step budget from the updated state, use
Sampler::run_chunk, Sampler::run_mut_chunk, or
Sampler::run_delayed_chunk. They run the next chunk on the same RNG
stream and return a checkpoint-compatible view containing the current state
and counters.
§Resumable chunked runs
Chunked runs advance the chain by a chosen number of steps, then return a
checkpoint-compatible continuation so a caller can inspect the updated state,
choose the next chunk length, and resume without losing RNG state or
counters. Reusing the same Sampler preserves the RNG stream, so a
sequence of chunks reproduces an equivalent one-shot run with the same seed.
Measurements stay on the caller side: keep domain-specific statistics in your
own buffers and accumulate them across chunks rather than having the sampler
own a measurement buffer. The delayed observing variant
Sampler::run_delayed_chunk_observing hands each step’s DelayedStep
telemetry and post-step state to a callback while still returning the
continuation, so the chain keeps ownership of the accept/reject draw and
counters. Between chunks a caller can size the next chunk from the current
state and stop on an elapsed-time budget.
use core::convert::Infallible;
use markov_chain_monte_carlo::prelude::delayed::*;
use rand::{Rng, SeedableRng, rngs::StdRng};
let mut rng = StdRng::seed_from_u64(42);
let mut proposal = Advance;
let chain = Chain::new(0, &Flat).map_err(DelayedStepError::Mcmc)?;
let mut sampler = Sampler::new(chain, &Flat, &mut proposal, &mut rng)
.map_err(DelayedStepError::Mcmc)?;
// Domain-specific measurements stay outside the generic sampler.
let mut samples: Vec<i32> = Vec::new();
let mut next_chunk = 4;
for _ in 0..3 {
let continuation = sampler.run_delayed_chunk_observing(next_chunk, |_step, state| {
samples.push(*state);
})?;
// Size the next chunk from the updated state and resume on the same RNG
// stream. A real caller can also break here on an elapsed-time budget.
next_chunk = usize::try_from(**continuation.state()).unwrap_or(1).max(1);
}
assert_eq!(sampler.chain_ref().total_steps(), samples.len());§Proposal validation
The verify_detailed_balance family of helpers gives proposal authors a
test-facing diagnostic for representative discrete transitions. Use
verify_detailed_balance for by-value Proposal implementations,
verify_detailed_balance_mut for rollback-based ProposalMut
implementations, and verify_detailed_balance_delayed for
DelayedProposal plans. The companion batch helpers collect all
per-transition failures in a DetailedBalanceBatchReport, which is useful
when checking a small graph, move table, or list of local states.
These helpers are empirical diagnostics for exact endpoint hits, not a proof of ergodicity or convergence. They are intended for tests, examples, and proposal-development checks over discrete or otherwise exactly comparable states.
Enable the optional serde feature to serialize Chain<S> checkpoints
when S implements serde’s traits. Restore checkpoint data with
Chain::from_checkpoint so the cached log-probability is recomputed from
the target used for resumed sampling. Sampler also derives
serialization when all stored handles support it, but targets, proposals,
and RNG streams are reconstructed by the caller for portable resumes.
use approx::assert_relative_eq;
use markov_chain_monte_carlo::prelude::*;
struct Normal;
impl Target<f64> for Normal {
fn log_prob(&self, state: &f64) -> f64 { -0.5 * state * state }
}
let chain = Chain::new(1.0, &Normal)?;
let checkpoint = chain.checkpoint();
let checkpoint = serde_json::to_string(&checkpoint)?;
let checkpoint: ChainCheckpoint<f64> = serde_json::from_str(&checkpoint)?;
let restored = Chain::from_checkpoint(checkpoint, &Normal)?;
assert_relative_eq!(
restored.log_prob(),
Normal.log_prob(restored.state()),
epsilon = 1e-12
);§In-place mutation with rollback
For state spaces where cloning is expensive, use ProposalMut with
Chain::step_mut. The proposal mutates the state in place and returns
a small undo token for rollback on rejection. Each completed step returns
Step telemetry containing the proposal’s ProposalMut::Info, outcome,
and acceptance numerics:
use markov_chain_monte_carlo::prelude::in_place::*;
use rand::{Rng, RngExt, SeedableRng, rngs::StdRng};
/// A lattice of spins (not Clone — only mutated in place).
struct SpinChain { spins: Vec<i8> }
/// Energy = −Σ s_i · s_{i+1} (1-D Ising, no field).
struct Ising;
impl Target<SpinChain> for Ising {
fn log_prob(&self, state: &SpinChain) -> f64 {
let s = &state.spins;
let energy: f64 = s.windows(2)
.map(|w| -f64::from(w[0]) * f64::from(w[1]))
.sum();
-energy // log_prob = −E (T = 1)
}
}
/// Flip one random spin; undo token is the site index.
struct SpinFlip;
impl ProposalMut<SpinChain> for SpinFlip {
type Undo = usize;
type Info = usize;
fn propose_mut<R: Rng + ?Sized>(&mut self, state: &mut SpinChain, rng: &mut R) -> Option<usize> {
if state.spins.is_empty() { return None; }
let idx = rng.random_range(0..state.spins.len());
state.spins[idx] *= -1;
Some(idx)
}
fn info(&self, _state: &SpinChain, idx: &usize) -> usize { *idx }
fn undo(&mut self, state: &mut SpinChain, idx: usize) {
state.spins[idx] *= -1; // flipping twice = identity
}
}
fn main() -> Result<(), McmcError> {
let mut rng = StdRng::seed_from_u64(42);
let state = SpinChain { spins: vec![1; 20] };
let mut chain = Chain::new(state, &Ising)?;
let mut proposal = SpinFlip;
for _ in 0..1000 {
let _ = chain.step_mut(&Ising, &mut proposal, &mut rng)?;
}
assert!(chain.acceptance_rate() > 0.0);
Ok(())
}For bulk in-place sampling, use Sampler::run_mut instead.
§Delayed commit proposals
Use DelayedProposal with Chain::step_delayed when a proposal can
plan and score a move before mutating the state, then commit only after the
Metropolis-Hastings decision accepts it.
The plan should describe a concrete transition, such as a move kind plus the
local site or handle needed to apply it. If no valid site can be selected,
return Ok(None) from DelayedProposal::propose_plan; that is an ordinary
rejection, while DelayedProposal::commit errors are reserved for
exceptional failures applying an already accepted concrete move.
Delayed steps return DelayedStep telemetry with a StepOutcome. Use
Step::rejection_reason when you only need rejected-step categories.
Implement
DelayedProposal::no_plan_info when a no-plan self-loop should still
report proposal-family metadata.
Use DiscreteProposalRatio when a delayed combinatorial proposal chooses
a move family and then samples uniformly among that family’s valid concrete
sites.
use core::convert::Infallible;
use markov_chain_monte_carlo::prelude::delayed::*;
use rand::{Rng, SeedableRng, rngs::StdRng};
struct TargetLine;
impl Target<i32> for TargetLine {
fn log_prob(&self, state: &i32) -> f64 {
-f64::from(state.abs())
}
}
struct MoveRight;
impl DelayedProposal<i32> for MoveRight {
type Plan = i32;
type Info = i32;
type Error = Infallible;
fn propose_plan<R: Rng + ?Sized>(
&mut self,
_state: &i32,
_rng: &mut R,
) -> Result<Option<i32>, Self::Error> {
Ok(Some(1))
}
fn proposed_log_prob<T: Target<i32>>(
&self,
state: &i32,
plan: &i32,
target: &T,
) -> Result<f64, Self::Error> {
Ok(target.log_prob(&(*state + *plan)))
}
fn info(&self, plan: &i32) -> i32 {
*plan
}
fn commit<R: Rng + ?Sized>(
&mut self,
state: &mut i32,
plan: i32,
_rng: &mut R,
) -> Result<(), Self::Error> {
*state += plan;
Ok(())
}
}
fn main() -> Result<(), DelayedStepError<Infallible>> {
let target = TargetLine;
let mut proposal = MoveRight;
let mut rng = StdRng::seed_from_u64(42);
let mut chain = Chain::new(-1, &target).map_err(DelayedStepError::Mcmc)?;
let step = chain.step_delayed(&target, &mut proposal, &mut rng)?;
assert_eq!(step.outcome(), StepOutcome::Accepted);
assert_eq!(*chain.state(), 0);
Ok(())
}§Ergonomic sampling with Sampler
Sampler bundles a chain with its target, proposal, and RNG so you
don’t have to pass them on every step:
use markov_chain_monte_carlo::prelude::by_value::*;
use rand::{Rng, RngExt, SeedableRng, rngs::StdRng};
let mut rng = StdRng::seed_from_u64(42);
let chain = Chain::new(Scalar(0.0), &Normal)?;
let mut sampler = Sampler::new(chain, &Normal, &Walk, &mut rng)?;
// Burn-in
sampler.run(1000)?;
sampler.reset_counters();
// Production
sampler.run(10_000)?;
assert!(sampler.chain_ref().acceptance_rate() > 0.0);§Observables and measurements
Use Observable or a closure with Sampler::run_observing to compute
derived quantities during sampling without storing full state histories:
use markov_chain_monte_carlo::prelude::by_value::*;
use rand::{Rng, RngExt, SeedableRng, rngs::StdRng};
let mut rng = StdRng::seed_from_u64(42);
let chain = Chain::new(Scalar(0.0), &Normal)?;
let mut sampler = Sampler::new(chain, &Normal, &Walk, &mut rng)?;
let mut energy = |state: &Scalar| 0.5 * state.0 * state.0;
let samples: SampleBuffer<f64> = sampler.run_observing(256, &mut energy)?;
assert_eq!(samples.len(), 256);§Streaming statistics
Use OnlineStats for Welford mean and variance updates, and
BinningAnalysis for autocorrelation-aware standard-error estimates:
use markov_chain_monte_carlo::prelude::*;
let mut energy = OnlineStats::new();
energy.try_extend([1.0, 2.0, 3.0, 4.0])?;
assert_eq!(energy.mean(), Some(2.5));
let mut bins = BinningAnalysis::new();
bins.try_extend([1.0, 2.0, 3.0, 4.0])?;
assert!(bins.standard_error().is_some());Sampler can also stream observations directly into these accumulators:
use core::convert::Infallible;
use markov_chain_monte_carlo::prelude::by_value::*;
use rand::{Rng, SeedableRng, rngs::StdRng};
let mut rng = StdRng::seed_from_u64(42);
let chain = Chain::new(0.0, &T).map_err(ObservedStreamError::Step)?;
let mut sampler = Sampler::new(chain, &T, &P, &mut rng)
.map_err(ObservedStreamError::Step)?;
let mut coordinate = |state: &f64| *state;
let mut stats = OnlineStats::new();
sampler.run_observing_into(4, &mut coordinate, &mut stats)?;
assert_eq!(stats.count(), 4);Modules§
- prelude
- Convenience re-exports for common usage.
Structs§
- Additive
Target - Additive composition of two target log-weight components.
- Binning
Analysis - Streaming binning analysis for autocorrelation-corrected error estimates.
- Binning
Estimate - Standard-error estimate at one binning level.
- Chain
- A single MCMC chain.
- Chain
Checkpoint - Portable checkpoint data for a
Chain. - ChainId
- Stable identifier for one recorded Markov chain.
- Detailed
Balance Batch Report - Batch detailed-balance report that preserves every failure.
- Detailed
Balance Config - Configuration for empirical detailed-balance verification.
- Detailed
Balance Delayed Transition - One delayed-commit transition to check in a batch.
- Detailed
Balance Failure - One failed detailed-balance check in a batch.
- Detailed
Balance Report - Empirical detailed-balance verification report.
- Discrete
Proposal Ratio - Hastings correction for a discrete proposal with weighted move families and uniformly sampled concrete sites.
- Invalid
Thinning Interval - Error returned when parsing a zero
ThinningInterval. - Online
Stats - Online mean and variance accumulator using Welford’s algorithm.
- Sample
Buffer - In-memory collection of observation outputs.
- Sampler
- Bundles a
Chainwith its target, proposal, and RNG for ergonomic sampling. - Step
- Telemetry for a single Metropolis-Hastings step.
- Thinning
Interval - Positive interval between retained samples in a thinned run.
- Trace
- Multi-chain numeric trace with shared observable columns.
- Trace
Record - One recorded post-step trace row.
- Trace
Recorder - Recorder for one chain within a multi-chain trace.
- Trace
Step Outcome - Acceptance/proposal outcome recorded for one trace row.
Enums§
- Delayed
Step Error - Errors from a delayed-commit Metropolis-Hastings step.
- Detailed
Balance Direction - Direction of an empirical detailed-balance check.
- Detailed
Balance Error - Error returned by detailed-balance configuration and verification.
- Detailed
Balance State - State role in an empirical detailed-balance check.
- Discrete
Proposal Ratio Error - Errors from constructing a
DiscreteProposalRatio. - Mcmc
Error - Errors that can occur during MCMC operations.
- Observed
Step Error - Error from a sampling step paired with a fallible observation.
- Observed
Stream Error - Error from a sampling step, observation, or accumulation sink.
- Statistics
Error - Errors from fallible statistical accumulation.
- Step
Outcome - Outcome of a completed Metropolis-Hastings step.
- Step
Rejection Reason - Reason a completed step was counted as a rejection.
- Trace
Error - Errors returned while constructing trace data.
Traits§
- Delayed
Proposal - Proposal distribution for accept-before-mutation workflows.
- Observable
- Measurement computed from the current chain state.
- Proposal
- Proposal distribution for generating new states by value.
- Proposal
Mut - In-place proposal distribution with rollback.
- Target
- Target distribution.
- TryAccumulator
- Fallible sink for streaming observation outputs.
- TryObservable
- Fallible measurement computed from the current chain state.
Functions§
- verify_
detailed_ balance - Empirically verify detailed balance for one discrete by-value transition.
- verify_
detailed_ balance_ delayed - Empirically verify detailed balance for one delayed-commit transition.
- verify_
detailed_ balance_ delayed_ many - Verify many delayed-commit transitions and return every transition violation.
- verify_
detailed_ balance_ many - Verify many by-value transitions and return every transition violation.
- verify_
detailed_ balance_ mut - Empirically verify detailed balance for one in-place transition.
- verify_
detailed_ balance_ mut_ many - Verify many in-place transitions and return every transition violation.
Type Aliases§
- Delayed
Step - Telemetry for a delayed-commit Metropolis-Hastings step.
- Observed
Delayed Into RunResult - Result returned by infallible-observation delayed streaming runs.
- Observed
Delayed Step - Delayed-step telemetry paired with a measurement from the resulting state.
- Observed
Delayed Step Result - Result returned by delayed observing steps.
- Observed
Into RunResult - Result returned by infallible-observation streaming runs.
- Observed
MutStep - In-place step telemetry paired with a measurement from the resulting state.
- Thinned
Observed Delayed Into RunResult - Result returned by thinned infallible-observation delayed streaming runs.
- Thinned
Observed Into RunResult - Result returned by thinned infallible-observation streaming runs.
- Thinned
RunResult - Result returned by thinned sampler runs.
- TryObserved
Delayed Into RunResult - Result returned by fallible-observation delayed streaming runs.
- TryObserved
Delayed RunResult - Result returned by fallible delayed observing runs.
- TryObserved
Delayed Step Result - Result returned by fallible delayed observing steps.
- TryObserved
Into RunResult - Result returned by fallible-observation streaming runs.
- TryObserved
MutStep Result - Result returned by fallible in-place observing steps.
- TryObserved
RunResult - Result returned by fallible by-value or in-place observing runs.
- TryObserved
Step Result - Result returned by fallible by-value observing steps.
- TryThinned
Observed Delayed Into RunResult - Result returned by thinned fallible-observation delayed streaming runs.
- TryThinned
Observed Into RunResult - Result returned by thinned fallible-observation streaming runs.
- TryThinned
Observed RunResult - Result returned by thinned fallible-observation runs.