Skip to main content

lib_jsl_random/
mcmc.rs

1//! Markov chain Monte Carlo: random-walk Metropolis-Hastings.
2//!
3//! See the book entry [Markov chain Monte Carlo](https://jwkunz.github.io/lib_jsl/book/random/mcmc.html).
4
5use crate::distributions::gaussian::gaussian_distribution_box_muller;
6use crate::uniform_generator::UniformGenerator;
7use lib_jsl_core::ErrorsJSL;
8
9/// Settings for [`metropolis_hastings`].
10#[derive(Debug, Clone)]
11pub struct MetropolisOptions {
12    /// Standard deviation of the Gaussian proposal per coordinate; empty means 1 for every
13    /// coordinate (the default, which adaptive burn-in then tunes).
14    pub proposal_scale: Vec<f64>,
15    /// Retained samples.
16    pub samples: usize,
17    /// Initial iterations discarded while the chain forgets its starting point.
18    pub burn_in: usize,
19    /// Keep every `thin`-th state (1 keeps all), reducing autocorrelation and storage.
20    pub thin: usize,
21    /// During burn-in, rescale the proposal every 100 steps towards an acceptance rate near the
22    /// optimal 0.234 for random-walk proposals in many dimensions (0.44 in one).
23    pub adapt_during_burn_in: bool,
24}
25
26impl Default for MetropolisOptions {
27    /// 10 000 retained samples after 1 000 adaptive burn-in steps, no thinning, unit proposals.
28    fn default() -> Self {
29        MetropolisOptions { proposal_scale: Vec::new(), samples: 10_000, burn_in: 1_000, thin: 1, adapt_during_burn_in: true }
30    }
31}
32
33/// A Markov chain.
34#[derive(Debug, Clone)]
35pub struct MarkovChain {
36    pub samples: Vec<Vec<f64>>,
37    /// The fraction of proposals accepted after burn-in.
38    pub acceptance_rate: f64,
39    /// The proposal scale actually used after any adaptation.
40    pub proposal_scale: Vec<f64>,
41}
42
43impl MarkovChain {
44    /// The sample mean of each coordinate.
45    pub fn mean(&self) -> Vec<f64> {
46        let d = self.samples[0].len();
47        let m = self.samples.len() as f64;
48        (0..d).map(|i| self.samples.iter().map(|s| s[i]).sum::<f64>() / m).collect()
49    }
50
51    /// The normalized autocorrelation of coordinate `i` at `lag`.
52    pub fn autocorrelation(&self, i: usize, lag: usize) -> f64 {
53        let x: Vec<f64> = self.samples.iter().map(|s| s[i]).collect();
54        let m = x.len();
55        if lag >= m {
56            return 0.0;
57        }
58        let mean = x.iter().sum::<f64>() / m as f64;
59        let var: f64 = x.iter().map(|v| (v - mean).powi(2)).sum();
60        (0..m - lag).map(|k| (x[k] - mean) * (x[k + lag] - mean)).sum::<f64>() / var
61    }
62}
63
64// ANCHOR: metropolis
65/// Samples from the density proportional to `exp(log_density(x))` by random-walk
66/// Metropolis-Hastings: propose `x' = x + σ ⊙ z` with `z` standard normal, accept with
67/// probability `min(1, p(x')/p(x))`. Only an unnormalised log-density is needed; returning
68/// `−∞` marks points outside the support.
69pub fn metropolis_hastings<F, U>(log_density: F, initial: Vec<f64>, options: MetropolisOptions, rng: &mut U) -> Result<MarkovChain, ErrorsJSL>
70where
71    F: Fn(&[f64]) -> f64,
72    U: UniformGenerator,
73{
74    let d = initial.len();
75    let unit_scale = vec![1.0; d];
76    let proposal_scale = if options.proposal_scale.is_empty() { &unit_scale } else { &options.proposal_scale };
77    if d == 0 || proposal_scale.len() != d || options.samples == 0 || options.thin == 0 {
78        return Err(ErrorsJSL::InvalidInputRange("Need a non-empty start, a matching proposal scale, samples and thin >= 1."));
79    }
80    if proposal_scale.iter().any(|s| s.is_nan() || *s <= 0.0) {
81        return Err(ErrorsJSL::InvalidInputRange("Proposal scales must be positive."));
82    }
83    let mut x = initial;
84    let mut log_p = log_density(&x);
85    if log_p.is_nan() || log_p == f64::NEG_INFINITY {
86        return Err(ErrorsJSL::InvalidInputRange("The initial point must have positive density."));
87    }
88    let mut scale = proposal_scale.clone();
89    let target = if d == 1 { 0.44 } else { 0.234 };
90    let total = options.burn_in + options.samples * options.thin;
91    let mut samples = Vec::with_capacity(options.samples);
92    let (mut accepted, mut window_accepted) = (0usize, 0usize);
93    let mut z = Vec::with_capacity(d + 1);
94    for step in 0..total {
95        z.clear();
96        while z.len() < d {
97            let (a, b) = gaussian_distribution_box_muller(rng, 0.0, 1.0);
98            z.push(a);
99            z.push(b);
100        }
101        let proposal: Vec<f64> = (0..d).map(|i| x[i] + scale[i] * z[i]).collect();
102        let log_q = log_density(&proposal);
103        let accept = log_q > f64::NEG_INFINITY && (log_q >= log_p || rng.next_f64().ln() < log_q - log_p);
104        if accept {
105            x = proposal;
106            log_p = log_q;
107            window_accepted += 1;
108            if step >= options.burn_in {
109                accepted += 1;
110            }
111        }
112        if step < options.burn_in {
113            if options.adapt_during_burn_in && (step + 1) % 100 == 0 {
114                let rate = window_accepted as f64 / 100.0;
115                let factor = ((rate - target) * 2.0).exp();
116                scale.iter_mut().for_each(|s| *s *= factor);
117                window_accepted = 0;
118            }
119        } else if (step - options.burn_in) % options.thin == options.thin - 1 {
120            samples.push(x.clone());
121        }
122    }
123    Ok(MarkovChain { samples, acceptance_rate: accepted as f64 / (options.samples * options.thin) as f64, proposal_scale: scale })
124}
125// ANCHOR_END: metropolis
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::uniform_generator::UniformRNG;
131
132    #[test]
133    fn recovers_a_correlated_gaussian() {
134        // N(μ, Σ) with Σ = [[1, 0.8], [0.8, 1]], log-density up to a constant.
135        let mu = [1.0, -2.0];
136        let det = 1.0 - 0.64;
137        let log_density = |x: &[f64]| {
138            let (a, b) = (x[0] - mu[0], x[1] - mu[1]);
139            -0.5 * (a * a - 1.6 * a * b + b * b) / det
140        };
141        let options = MetropolisOptions { proposal_scale: vec![0.1, 0.1], samples: 40_000, burn_in: 5_000, thin: 5, adapt_during_burn_in: true };
142        let chain = metropolis_hastings(log_density, vec![5.0, 5.0], options, &mut UniformRNG::from_seed(3)).unwrap();
143        let m = chain.mean();
144        assert!((m[0] - mu[0]).abs() < 0.05 && (m[1] - mu[1]).abs() < 0.05, "{m:?}");
145        let n = chain.samples.len() as f64;
146        let cov = chain.samples.iter().map(|s| (s[0] - m[0]) * (s[1] - m[1])).sum::<f64>() / n;
147        let var0 = chain.samples.iter().map(|s| (s[0] - m[0]).powi(2)).sum::<f64>() / n;
148        assert!((cov - 0.8).abs() < 0.06 && (var0 - 1.0).abs() < 0.08, "cov {cov} var {var0}");
149        // Adaptation steered the acceptance rate towards 0.234 and grew the tiny initial step.
150        assert!(chain.acceptance_rate > 0.15 && chain.acceptance_rate < 0.35, "{}", chain.acceptance_rate);
151        assert!(chain.proposal_scale[0] > 0.3);
152        assert!(chain.autocorrelation(0, 1) < 0.9 && chain.autocorrelation(0, 50) < 0.1);
153    }
154
155    #[test]
156    fn respects_the_support_and_validates() {
157        // Exponential(1) on x > 0: mean 1.
158        let log_density = |x: &[f64]| if x[0] > 0.0 { -x[0] } else { f64::NEG_INFINITY };
159        let options = MetropolisOptions { proposal_scale: vec![1.0], samples: 50_000, burn_in: 2_000, thin: 2, adapt_during_burn_in: false };
160        let chain = metropolis_hastings(log_density, vec![1.0], options.clone(), &mut UniformRNG::from_seed(4)).unwrap();
161        assert!(chain.samples.iter().all(|s| s[0] > 0.0));
162        assert!((chain.mean()[0] - 1.0).abs() < 0.05, "{:?}", chain.mean());
163        assert!(metropolis_hastings(log_density, vec![-1.0], options.clone(), &mut UniformRNG::from_seed(4)).is_err());
164        assert!(metropolis_hastings(log_density, vec![1.0, 2.0], options, &mut UniformRNG::from_seed(4)).is_err());
165    }
166}