numerics
Loading...
Searching...
No Matches
mcmc.hpp
Go to the documentation of this file.
1/// @file markov/mcmc.hpp
2/// @brief Metropolis-Hastings MCMC -- template-based, zero-overhead callable dispatch.
3///
4/// The sweep functions accept any callable for delta_energy / acceptance_prob
5/// and apply_flip, so the compiler inlines them at the call site with zero
6/// std::function overhead in the hot loop.
7///
8/// Two sweep variants are provided:
9/// - metropolis_sweep: caller supplies delta_energy (dE); exp(-beta*dE)
10/// is computed internally.
11/// - metropolis_sweep_prob: caller supplies the acceptance probability
12/// directly (e.g. from a precomputed Boltzmann
13/// table), skipping the exp() call entirely.
14///
15/// Typical use (Ising with Boltzmann table):
16/// @code
17/// auto result = num::markov::metropolis_sweep_prob(
18/// n_sites,
19/// [&](idx i) { return boltz[spin_idx(i)][nbr_idx(i)]; },
20/// [&](idx i) { spins[i] = -spins[i]; },
21/// rng);
22/// @endcode
23///
24/// Typical use (general system):
25/// @code
26/// auto result = num::markov::metropolis_sweep(
27/// n_sites,
28/// [&](idx i) { return sys.delta_energy(i); },
29/// [&](idx i) { sys.flip(i); },
30/// beta, rng);
31/// @endcode
32#pragma once
33#include "core/types.hpp"
34
35namespace num::markov {
36
37/// @brief Statistics returned by a single Metropolis sweep.
39 idx accepted = 0; ///< Number of accepted proposals
40 idx total = 0; ///< Total proposals (= n_sites)
42 return total > 0 ? static_cast<real>(accepted) / total : 0.0;
43 }
44};
45
46/// @brief Statistics returned by an umbrella sampling sweep.
48 MetropolisStats mc; ///< Metropolis sweep statistics
49 bool reverted = false; ///< true if state was restored
50 idx order_param = 0; ///< Order parameter value after sweep
51};
52
53/// @brief Window constraint for umbrella sampling.
55 idx lo; ///< Lower bound (inclusive)
56 idx hi; ///< Upper bound (inclusive)
57 bool contains(idx v) const { return v >= lo && v <= hi; }
58};
59
60} // namespace num::markov
61
62// Template definitions (must be visible at instantiation point).
Core type definitions.
double real
Definition types.hpp:10
std::size_t idx
Definition types.hpp:11
Statistics returned by a single Metropolis sweep.
Definition mcmc.hpp:38
idx accepted
Number of accepted proposals.
Definition mcmc.hpp:39
real acceptance_rate() const
Definition mcmc.hpp:41
idx total
Total proposals (= n_sites)
Definition mcmc.hpp:40
Statistics returned by an umbrella sampling sweep.
Definition mcmc.hpp:47
MetropolisStats mc
Metropolis sweep statistics.
Definition mcmc.hpp:48
bool reverted
true if state was restored
Definition mcmc.hpp:49
idx order_param
Order parameter value after sweep.
Definition mcmc.hpp:50
Window constraint for umbrella sampling.
Definition mcmc.hpp:54
idx hi
Upper bound (inclusive)
Definition mcmc.hpp:56
idx lo
Lower bound (inclusive)
Definition mcmc.hpp:55
bool contains(idx v) const
Definition mcmc.hpp:57