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