Basic Features
The basic features of the MCMCSimulationLib are covered by the following modules and allow to set up, to run and to evaluate a Markov chain Monte Carlo (MCMC) simulation:
Markov chain Monte Carlo systems: Two CRTP base classes,
mcmc::simulation::SystemBaseandmcmc::simulation::MeasureSystemBase, provide all necessary functions for running a MCMC simulation. The directorytemplates/contain templates which can be used to set up your own system.Execution modes: Modules to specify details of the simulation. The library features a computation of expectation values, of the autocorrelation time and of the time the system needs to be in equilibrium (to reach a steady state distribution). Results of previously executed simulations can be passed as an input to subsequent simulations.
Measurement processing: Modules to handle the collection and processing of measurements during the MCMC simulation. At the moment, there is only one class,
mcmc::measures::ReadableMeasure, which writes the simulation data in a readable format into a .txt file.Simulation: Core class of the MCMC simulation providing the possibilities to run and evaluate simulations in different settings.
Predefined measures: Standard measures on MCMC configurations, which can be used in combination with the
mcmc::simulation::MeasureSystemBase().
Note that all classes inherit from param_helper::params::Parameters
providing the possibility to store all parameters of the respective class in
.json files. This property allows for an automatic tracking of the
simulation parameters and enables to rerun the simulation at a later point.
Additionally, it is straightforward to bind the C++ modules into Python via pybind11. This gives the possibility to execute the entire simulation solely from Python.
Tutorials
Setting up a simulation
The main.cpp program for running a Markov chain Monte Carlo simulation
consists of the following building blocks:
Include important header files, define the relative path to the project root dir (in our case with respect to the build directory) and initialize Python if the CMake variable
RUN_WITH_PYTHON_BACKENDhas been set toON. The latter is required for evaluations of the MCMC simulation directly from C++ code:
#include "../include/mcmcsystem/config.h"
#include <mcmc/mcmc_simulation/header.hpp>
#include <mcmc/mcmc_simulation/util/intervals.hpp>
#include <mcmc/modes/mode_header.hpp>
#include <mcmc/mcmc_simulation/util/random.hpp>
#include "../include/mcmcsystem/mcmcsystem.hpp"
int main(int argc, char **argv) {
// Initialize project dependent parameters
param_helper::proj::set_relative_path_to_project_root_dir("../");
#ifdef PYTHON_BACKEND
mcmc::util::initialize_python(PYTHON_SCRIPTS_PATH);
#endif
Define directories for storing the data and the results of the simulation, set up the MCMC system and initialize a measurement processor and an execution mode. In addition to the
measuresvariable, there is the possibility to compute measures over the configurations by thepost_measuresvariable, further details on that can be found in the Custom measure and data loading functions section:
// Name of the simulation
const std::string target_name = "MCMCSystemSimulation";
// Directory for storing the results
std::string rel_results_dir = "/results/" + target_name + "/";
// Directory for storing the simulation data
std::string rel_data_dir = "/data/" + target_name + "/";
// Setting up the system
MCMCSystem system({1.0, 2.0, -1.5}, 1.0, 0.002);
// Setting up measurement processor
typedef mcmc::measures::ReadableMeasure ReadableMeasureProcessor;
ReadableMeasureProcessor readable_measures(rel_data_dir);
// Setting up the execution mode
typedef mcmc::mode::ExpectationValue ExpectationValueParams; ExpectationValueParams expectation_value_parameters(
10, // measure_interval
100000, // number_of_measurements
100, // start_measuring
{"Config", "Mean"}, // measures
{}, // post_measures
"hot", // starting_mode
"statistical" // error_type
);
Initialize the simulation class and use it to run and/or evaluate the MCMC simulation. The definition of a running parameter, specified by the variables
running_parameter_kindandrunning_parameterprovides the possibility to execute the same simulation for different values of this parameter, defined by the vectorrp_intervals. If these variables are omitted, the simulation only runs for the parameters defined when the system was initialized:
// Prepare the simulation
auto sigma_intervals = mcmc::util::linspace(0.2, 1.0, 9);
auto expectation_value_simulation = mcmc::simulation::Simulation<
MCMCSystem, ExpectationValueParams,
ReadableMeasureProcessor>::generate_simulation(
system,
expectation_value_parameters,
readable_measures,
"systembase", // running_parameter_kind
"sigma", // running parameter (rp)
sigma_intervals // rp_intervals
);
// Run and evaluate the simulation expectation_value_simulation.run();
expectation_value_simulation.eval(rel_results_dir);
Finalize the program:
// Finalization
#ifdef PYTHON_BACKEND
mcmc::util::finalize_python();
#endif
return 0;
}
A full example with a simulation and computation of the time the system needs to
be in equilibrium, of the autocorrelation time and of expectation values can be
found in main.cpp of a project generated with the
generate_application.py script, with standard as -mt parameter and
in the example code of the scalar theory.
Furthermore, note that each class implements a write_to_file(const std::string
rel_root_dir) function, which outputs .json file in the provided directory.
The simulation class provides several overloaded static constructors providing
the possibility to load simulations partially from configuration parameters
stored in these .json files. This feature is heavily used by the advanced
features of the library allowing for a simulation solely from the command line.
Writing your first Markov chain Monte Carlo system
The two files system.hpp and measures_system.hpp in the templates/
directory can be used as a starting point to implement your own MCMC system. The
declaration of the classes can also be found here and here.
Note that these templates are also used by the generate_application.py
script.
Evaluating results in Python
Evaluation module and PyTorch support
MCMCEvaluationLib provides support for loading and computing/recomputing
measures and simulation data generated with the help of the MCMCSimulationLib.
Possible evaluation tools are summarized in the EvaluationModule class.
Examples for using this class can be found in the python_examples/evaluation.py file of generated projects and of the scalar theory example.
Furthermore, examples in the pytorch_support/ of these projects demonstrate
how the sampled MCMC configurations can be processed in the Deep Learning
framework PyTorch.
Custom measure and data loading functions
There is the possibility to define custom functions for loading data from file
and for defining custom measure functions. The former is useful if your data is
stored in a different format than the support ones. The latter can be helpful if
you want to compute expectation values for a measure that have not been tracked
by the C++ implementation (based on the measure parameters).
The support for this functionality is implemented in the
mcmctools.loading.custom_function_support.py file of the MCMCEvaluationLib.
In particular, it looks for a module named custom_modules.py with the
declaration of the following two functions:
""" Input:
data: pandas dataframe containing the MCMC configurations
measure_name: Name of the measure
custom_measures_args: Optional additional arguments; when called from C++ this refers to the serialized simulation parameters
"""
def compute_measures(data, measure_name, custom_measures_args):
import json
sim_params = json.loads(custom_measures_args)
pass
""" Input:
rel_data_dir: rel_data_dir to sim_base_dir
running_parameter: running_parameter
identifier: string indicating the type of performed execution mode ("equilibrium_time", "correlationtime" or "expectation_value"), sim_base_dir: when called from C++, this refers to the project_root_dir
rp_values: list of values for the running_parameter
custom_load_data_args: Optional additional arguments; when called from C++ this refers to the serialized simulation parameters
"""
def custom_load_data(rel_data_dir, identifier, running_parameter,
rp_values, sim_base_dir, custom_load_data_args):
pass
For an evaluation based on the post_measures to work, one needs to store the
data which measures are supposed to be evaluated on, for example, the MCMC
configurations.
Additionally, the path to the custom_modules.py needs to be appended to the
Python sys.path. When running from C++, this can be done by passing the
CMake variable PYTHON_SCRIPTS_PATH to cmake, for more details see also:
Building the application.
Examples can be found in the examples/ directory or in the template
project generated with the generate_application.py script.
Integrating pybind11
As indicated in the Generate your first application section, the library
supports an easy integration of your MCMC system into Python. The magic for this
happens in the python_pybind/ directory of the generated project. The scalar
theory example also implements a respective binding of C++ functions and
contains example code for different use cases.
If the constructor of your MCMC system is different to the one of the generated
project, the .py and .cpp need to be adapted according to this changes.
Example code for using the python wrappers can be found in the
python_examples/ directory of the scalar theory example and of the template
project.
Markov chain Monte Carlo systems
The following possible declarations of Markov chain Monte Carlo systems without and with the usage of predefined measures serve as a good starting point for the implementation of your own MCMC system.
MCMC system without the usage of predefined measures
#ifndef MCMCSYSTEM_HPP
#define MCMCSYSTEM_HPP
#include <mcmc/mcmc_simulation/header.hpp>
#include <mcmc/mcmc_simulation/util/random.hpp>
// Template implementation for a MCMC system
class MCMCSystem : public mcmc::simulation::SystemBase<MCMCSystem>
{
public:
explicit MCMCSystem(const json params):
SystemBase(params),
// Configuration parameters
mu_(get_entry<std::vector<double>>("mu", {0.0, 1.0})),
sigma_(get_entry<double>("sigma", 0.4)),
dt_(get_entry<double>("dt", 0.01)),
// Further member variables
normal_(std::normal_distribution<double>(0.0, 1.0)),
system_(std::vector<double>(mu_.size(), 0.0))
{}
MCMCSystem(const std::vector<double> mu={0.0, 1.0}, const double sigma=0.4, const double dt=0.01) : MCMCSystem(json{
{"mu", mu},
{"sigma", sigma},
{"dt", dt}
})
{}
void initialize(std::string starting_mode)
{
// Called before every MCMC simulation for initalizing the system representation, starting mode can be "hot" or "cold", for example,
if(starting_mode == "hot")
std::transform(mu_.begin(), mu_.end(), system_.begin(), [this] (const double param) -> double { return param + this->sigma_ * this->normal_(mcmc::util::random::g_gen); });
else
std::fill(system_.begin(), system_.end(), 0);
}
void update_step(uint measure_interval=1)
{
// Called every MCMC step
for(auto i = 0; i < get_size(); i++)
system_[i] = system_[i] - dt_ * (system_[i] - mu_[i]) / std::pow(sigma_, 2.0) + std::sqrt(2.0 * dt_) * normal_(mcmc::util::random::g_gen);
}
uint16_t get_size() const
{
// Returns the size of the system, for example,
return system_.size();
}
auto at(int i) const
{
// Read system state i of the system representation, for example,
return system_[i];
}
auto& at(int i)
{
// Return system state i of the system representation, for example,
return system_[i];
}
auto get_system_representation() const
{
// Returns the entire MCMC system representation, for example,
return system_;
}
auto& get_system_representation()
{
// Returns the entire MCMC system representation, for example,
return system_;
}
void initialize_measurements(std::string starting_mode, uint rep=1)
{}
auto perform_measurements()
{
std::vector<std::variant<int, double, std::string>> results;
for(const auto measure_name: this->measure_names())
{
if(measure_name == "Mean")
{
auto mean = std::accumulate(system_.begin(), system_.end(), 0.0);
results.push_back(mean / get_size());
}
else if(measure_name == "Config")
{
std::string config = std::to_string(system_[0]);
for (uint idx = 1; idx < get_size(); idx++)
config += ", " + std::to_string(system_[idx]);
results.push_back(config);
}
}
return results;
}
void finalize_measurements(std::string starting_mode, uint rep=1)
{}
private:
std::vector<double> mu_;
double sigma_;
double dt_;
std::vector<double> system_; // Or any other system representation
std::normal_distribution<double> normal_;
};
#endif //MCMCSYSTEM_HPP
MCMC system with the usage of predefined measures
#ifndef MCMCMEASURESYSTEM_HPP
#define MCMCMEASURESYSTEM_HPP
#include <mcmc/mcmc_simulation/header.hpp>
#include <mcmc/mcmc_simulation/util/random.hpp>
// Template implementation for a MCMC measure system
class MCMCMeasureSystem : public mcmc::simulation::MeasureSystemBase<MCMCMeasureSystem>
{
public:
explicit MCMCMeasureSystem(const json params):
MeasureSystemBase(params),
// Configuration parameters
mu_(get_entry<std::vector<double>>("mu", {0.0, 1.0})),
sigma_(get_entry<double>("sigma", 0.4)),
dt_(get_entry<double>("dt", 0.01)),
// Further member variables
normal_(std::normal_distribution<double>(0.0, 1.0)),
system_(std::vector<double>(mu_.size(), 0.0))
{}
MCMCMeasureSystem(const std::vector<double> mu={0.0, 1.0}, const double sigma=0.4, const double dt=0.01) : MCMCMeasureSystem(json{
{"mu", mu},
{"sigma", sigma},
{"dt", dt}
})
{}
void initialize(std::string starting_mode)
{
// It is important to generate the predefined measures based on the virtual method of the base class - Note that this method can,
// of course also be overloaded.
generate_measures(measures_);
// Called before every MCMC simulation for initalizing the system representation, starting mode can be "hot" or "cold", for example,
if(starting_mode == "hot")
std::transform(mu_.begin(), mu_.end(), system_.begin(), [this] (const double param) -> double { return param + this->sigma_ * this->normal_(mcmc::util::random::g_gen); });
else
std::fill(system_.begin(), system_.end(), 0);
}
void update_step(uint measure_interval=1)
{
// Called every MCMC step
for(auto i = 0; i < get_size(); i++)
system_[i] = system_[i] - dt_ * (system_[i] - mu_[i]) / std::pow(sigma_, 2.0) + std::sqrt(2.0 * dt_) * normal_(mcmc::util::random::g_gen);
}
uint16_t get_size() const
{
// Returns the size of the system, for example,
return system_.size();
}
auto at(int i) const
{
// Read system state i of the system representation, for example,
return system_[i];
}
auto& at(int i)
{
// Return system state i of the system representation, for example,
return system_[i];
}
auto get_system_representation() const
{
// Returns the entire MCMC system representation, for example,
return system_;
}
auto& get_system_representation()
{
// Returns the entire MCMC system representation, for example,
return system_;
}
private:
std::vector<double> mu_;
double sigma_;
double dt_;
std::vector<double> system_; // Or any other system representation
std::normal_distribution<double> normal_;
};
#endif //MCMCMEASURESYSTEM_HPP
Execution modes
The library features the following execution modes.
EquilibriumTime
-
class mcmc::mode::EquilibriumTime : public Parameters
Prepares the computation of the necessary number of Monte Carlo sweeps for the system to be in equilibrium.
The class defines necessary parameters for running a MCMC simulation for determining the number of Monte Carlo sweeps the system needs to be in equilibrium. Note that some of the parameters are only needed for the respective evaluation which is executed afterwards in Python.
The time to equilibrium is evaluated by performing several simulations from a hot and a cold start. As soon as the distance between the average evolutions of the hot and the cold ensemble are within a certain confidence range, the configurations are expected to be in equilibrium. The additional parameter
confidence_windowallows to perform a smoothening of the averaged evolution based on a local convolution. The reduces the maximum number of Monte Carlo sweeps to be in equilibrium tomax(confidence_window, number_of_steps) - min(confidence_window, number_of_steps) + 1.Public Functions
-
inline EquilibriumTime(uint sample_size = 100, uint number_of_steps = 1000, double confidence_range = 0.1, uint confidence_window = 10, std::string measure = "Mean")
Constructor defining all important parameters for a computation of the time to equilibrium.
- Parameters
sample_size – Number of independent Monte Carlo simulations used to compute the ensemble average evolution from a cold and a hot initial configuration
number_of_steps – Number of performed Monte Carlo sweeps
confidence_range – Confidence range between the hot and the cold ensemble average
confidence_window – Size of the window in computer time (MCMC sweeps) used to smoothing the measured observable over time
measure – Measure used to evalute the time to equilibrium
-
inline void write_to_file(const std::string &rel_root_dir) const
Write the equilibrium time parameters as
equilibrium_time_params.jsonintorel_root_dir.- Parameters
rel_root_dir – Relative path to the
project_root_dirfor storing configuration files- Returns
None
-
inline void evaluate(const std::string &rel_data_dir, const std::string &rel_results_dir, const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0}, const json simparams_json = {}) const
Evaluates the equilibrium times by calling the respective Python functions and writes the results to file.
For the evaluation to work, one needs to enable Python in CMake and initialize Python by
mcmc::util::initialize_python(PYTHON_SCRIPTS_PATH)in the main function.- Parameters
rel_data_dir – Relative path to the
project_root_dir(set byparam_helper::proj::set_relative_path_to_project_root_dir("../")) for storing the MCMC simulation datarel_results_dir – Relative path to the
project_root_dirfor storing the resultsrunning_parameter – Name of the running parameter (default:
"None")rp_intervals – List of values for the running parameter
- Returns
None
-
inline EquilibriumTime(uint sample_size = 100, uint number_of_steps = 1000, double confidence_range = 0.1, uint confidence_window = 10, std::string measure = "Mean")
CorrelationTime
-
class mcmc::mode::CorrelationTime : public Parameters
Computes the autocorrelation time of the studied system.
The class defines necessary parameters for running a MCMC simulation for determining the autocorrelation of the model according to Eq. (3.21) from Newman - Monte Carlo Methods in Statistical Physics:
\[\begin{split}\begin{eqnarray*} \chi(t) &=& \frac{1}{t_{\text{max}} - t}\sum_{t'=0}^{t_{\text{max}} - t} m(t') m(t' + t) \\&&- \frac{1}{t_{\text{max}} - t}\sum_{t'=0}^{t_{\text{max}} - t} m(t') \times \frac{1}{t_{\text{max}} - t}\sum_{t'=0}^{t_{\text{max}} - t} m(t' + t)\,, \end{eqnarray*}\end{split}\]where \(t\) refers to the computer time, \(t_{\text{max}}\) to themaximum_correlation_timeand \(m\) to themeasureused to evaluate the autocorrelation time.Note that some of the parameters are only needed for the respective evaluation which is executed afterwards in Python.
Public Functions
-
inline CorrelationTime(uint minimum_sample_size = 100, uint maximum_correlation_time = 1000, uint start_measuring = 0, std::string measure = "Mean", std::string starting_mode = "hot")
Constructor defining all important parameters for the computation of the correlation time.
- Parameters
minimum_sample_size – Minimum number of Monte Carlo samples used to compute an average of the considered measure
maximum_correlation_time – Maximum measurable correlation time
start_measuring – Number of Monte Carlo sweeps before starting with the first measurement
measure – Measure used to evalute the autocorrelation time
starting_mode – Defines how the Markov chain is initialized. Possible values are
"hot"or"cold".
-
inline CorrelationTime(uint minimum_sample_size, uint maximum_correlation_time, std::string equilibrium_time_rel_results_dir, std::string measure = "Mean", std::string starting_mode = "hot")
Same as above with the exception that the time to equilibrium before the first measurement, which can be computed by the EquilibriumTime mode, is loaded from file.
- Parameters
minimum_sample_size – Minimum number of Monte Carlo samples used to compute an average of the considered measure
maximum_correlation_time – Maximum measurable correlation time
equilibrium_time_rel_results_dir – Relative path (with respect to the top-level directory of the project) to the
equilibrium_time_results.jsonresults filemeasure – Measure used to evalute the autocorrelation time
starting_mode – Defines how the Markov chain is initialized. Possible values are
"hot"or"cold".
-
inline void write_to_file(const std::string &rel_root_dir) const
Write the correlation time parameters as
correlation_time_params.jsonintorel_root_dir.- Parameters
rel_root_dir – Relative path to the
project_root_dirfor storing configuration files- Returns
None
-
inline void evaluate(const std::string &rel_data_dir, const std::string &rel_results_dir, const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0}, const json simparams_json = {}) const
Evaluates the correlation time by calling the respective Python functions and writes the results to file.
For the evaluation to work, one needs to enable Python in CMake and initialize Python by
mcmc::util::initialize_python(PYTHON_SCRIPTS_PATH)in the main function.- Parameters
rel_data_dir – Relative path to the
project_root_dir(set byparam_helper::proj::set_relative_path_to_project_root_dir("../")) for storing the MCMC simulation datarel_results_dir – Relative path to the
project_root_dirfor storing the resultsrunning_parameter – Name of the running parameter (default:
"None")rp_intervals – List of values for the running parameter
- Returns
None
-
inline CorrelationTime(uint minimum_sample_size = 100, uint maximum_correlation_time = 1000, uint start_measuring = 0, std::string measure = "Mean", std::string starting_mode = "hot")
ExpectationValue
-
class mcmc::mode::ExpectationValue : public Parameters
Prepares the computation of expectation values.
The class defines necessary parameters for running a MCMC simulation for computing expectation values. Note that some of the parameters are only needed for the respective evaluation which is executed afterwards in Python.
Public Functions
-
inline ExpectationValue(uint measure_interval = 1, uint number_of_measurements = 1000, uint start_measuring = 0, std::vector<std::string> measures = {"Mean"}, std::vector<std::string> post_measures = {}, std::string starting_mode = "hot", std::string error_type = "statistical", uint n_means_bootstrap = 0)
Standard constructor with custom values for all important parameters.
- Parameters
measure_interval – Number of Monte Carlo sweeps between measurements (autocorrelation time)
number_of_measurements – Total number of measurements
start_measuring – Number of Monte Carlo sweeps before starting with the first measurement
measures – Measures to be made during the simulation
post_measures – Measures which should be computed afterwards in Python. Note that for this work the configurations have to be stored as well which can be achieved by adding
"Config"to measuresstarting_mode – Defines how the Markov chain is initialized. Possible values are
"hot"or"cold".error_type – Method used to estimate the standard error of the expectation value
n_means_bootstrap – Number of bootstrap samples to compute the mean and the error of the measurements, if it is set to zero, the error is computed according to the standard error
-
inline ExpectationValue(std::string correlation_time_rel_results_dir, uint number_of_measurements, uint start_measuring, std::vector<std::string> measures, std::vector<std::string> post_measures = {}, std::string starting_mode = "hot", std::string error_type = "statistical", uint n_means_bootstrap = 0)
Same as above with the exception that the autocorrelation time, which can be computed by the CorrelationTime mode, is loaded from file.
- Parameters
correlation_time_rel_results_dir – Relative path (with respect to the top-level directory of the project) to the
correlation_time_results.jsonfilenumber_of_measurements – Total number of measurements
start_measuring – Number of Monte Carlo sweeps before starting with the first measurement
measures – Measures to be made during the simulation
post_measures – Measures which should be computed afterwards in Python. Note that for this work the configurations have to be stored as well which can be achieved by adding
"Config"to measuresstarting_mode – Defines how the Markov chain is initialized. Possible values are
"hot"or"cold".error_type – Method used to estimate the standard error of the expectation value
n_means_bootstrap – Number of bootstrap samples to compute the mean and the error of the measurements, if it is set to zero, the error is computed according to the standard error
-
inline ExpectationValue(uint measure_interval, uint number_of_measurements, std::string equilibrium_time_rel_results_dir, std::vector<std::string> measures, std::vector<std::string> post_measures = {}, std::string starting_mode = "hot", std::string error_type = "statistical", uint n_means_bootstrap = 0)
Same as above with the exception that the time to equilibrium before the first measurement, which can be computed by the EquilibriumTime mode, is loaded from file.
- Parameters
measure_interval – Number of Monte Carlo sweeps between measurements (autocorrelation time)
number_of_measurements – Total number of measurements
equilibrium_time_rel_results_dir – Relative path (with respect to the top-level directory of the project) to the
equilibrium_time_results.jsonresults filemeasures – Measures to be made during the simulation
post_measures – Measures which should be computed afterwards in Python. Note that for this work the configurations have to be stored as well which can be achieved by adding
"Config"to measuresstarting_mode – Defines how the Markov chain is initialized. Possible values are
"hot"or"cold".error_type – Method used to estimate the standard error of the expectation value
n_means_bootstrap – Number of bootstrap samples to compute the mean and the error of the measurements, if it is set to zero, the error is computed according to the standard error
-
inline ExpectationValue(std::string correlation_time_rel_results_dir, uint number_of_measurements, std::string equilibrium_time_rel_results_dir, std::vector<std::string> measures, std::vector<std::string> post_measures = {}, std::string starting_mode = "hot", std::string error_type = "statistical", uint n_means_bootstrap = 0)
Same as above with the exception that the time to equilibrium before the first measurement as well as the autocorrelation time are loaded from file. Both need to be computed beforhand with the EquilibriumTime and CorrelationTime mode.
- Parameters
correlation_time_rel_results_dir – Relative path (with respect to the top-level directory of the project) to the
correlation_time_results.jsonresults filenumber_of_measurements – Total number of measurements
equilibrium_time_rel_results_dir – Relative path (with respect to the top-level directory of the project) to the
equilibrium_time_results.jsonresults filemeasures – Measures to be made during the simulation
post_measures – Measures which should be computed afterwards in Python. Note that for this work the configurations have to be stored as well which can be achieved by adding
"Config"to measuresstarting_mode – Defines how the Markov chain is initialized. Possible values are
"hot"or"cold".error_type – Method used to estimate the standard error of the expectation value
n_means_bootstrap – Number of bootstrap samples to compute the mean and the error of the measurements, if it is set to zero, the error is computed according to the standard error
-
inline void write_to_file(const std::string &rel_root_dir) const
Write the expectation values as expectation_value_params.json into rel_root_dir.
- Parameters
rel_root_dir – Relative path to the project_root_dir for storing configuration files
- Returns
None
-
inline void evaluate(const std::string &rel_data_dir, const std::string &rel_results_dir, const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0}, const json simparams_json = {}) const
Evaluates expectation values by calling the respective Python functions and writes the results to file.
For the evaluation to work, one needs to enable Python in CMake and initialize Python by
mcmc::util::initialize_python(PYTHON_SCRIPTS_PATH)in the main function.- Parameters
rel_data_dir – Relative path to the
project_root_dir(set byparam_helper::proj::set_relative_path_to_project_root_dir("../")) for storing the MCMC simulation datarel_results_dir – Relative path to the
project_root_dirfor storing the resultsrunning_parameter – Name of the running parameter (default:
"None")rp_intervals – List of values for the running parameter
- Returns
None
-
inline ExpectationValue(uint measure_interval = 1, uint number_of_measurements = 1000, uint start_measuring = 0, std::vector<std::string> measures = {"Mean"}, std::vector<std::string> post_measures = {}, std::string starting_mode = "hot", std::string error_type = "statistical", uint n_means_bootstrap = 0)
Measurement processing
So far, there is only one class to process measurements.
Readable measures
-
struct mcmc::measures::ReadableMeasure : public Parameters
Class taking care of initalizing and writing measurements to file.
Public Functions
-
explicit ReadableMeasure(std::string rel_data_dir = "./data/")
Prepare directory for writing simulation data to file.
- Parameters
rel_data_dir – Relative path to the
project_root_dir(set byparam_helper::proj::set_relative_path_to_project_root_dir("../")) for storing the MCMC simulation data
-
void write_to_file(const std::string &rel_root_dir) const
Write the readable measure parameters as
readable_measuse_params.jsonintorel_root_dir.- Parameters
rel_root_dir – Relative path to the
project_root_dirfor storing configuration files- Returns
None
-
explicit ReadableMeasure(std::string rel_data_dir = "./data/")
Simulation
The simulation class represents the main module for preparing, running and evaluating simulations.
-
template<typename SB, typename EP = mcmc::mode::FromFilePreparation, typename MS = mcmc::measures::ReadableMeasure>
class mcmc::simulation::Simulation : public Parameters Class for performing the MCMC simulation as well as for computing simulation results based on different evaluation modes.
The class features different constructores allowing for running simulations based on the same system, execution and measure parameters from configuration files.
The static constructor Simulation::generate_simulation is overloaded to allow for various combinations of parameters defined in C++ or loaded from file. The list of possible parameters is as follows:
Parameters:
systembase Object of a systembase parameter class
execution_mode Object of an execution mode parameter class
measurement Object of a measure parameter class handling gathering and writing the simulation data to file
running_parameter_kind Parent configuration module key, providing the program with the necessary information of where to find the running parameter. If none is given, the simulation is only executed for the original set of parameters (default:
"None")running_parameter Name of the running parameter (default:
"None")rp_intervals List of values for the running parameter. A MCMC simulation is executed for each of these values one by one (default:
std::vector<double>{0.0})rel_systembase_params_path Relative path to the
project_root_dirof the simulation pointing to thesystembase_params.jsonfilerel_execution_mode_path Relative path to the
project_root_dirof the simulation pointing to the execution mode params.jsonfilerel_measurement_path Relative path to the
project_root_dirof the simulation pointing to the measurement processing params.jsonfile
Respective constructors and constructors for generating simulations entirely from file are listed below.
Public Functions
-
inline void write_to_file(const std::string &rel_config_dir)
Write the simulation parameters as
sim_params.json to file.- Parameters
rel_config_dir – Relative path to the
project_root_dirdefined byparam_helper::proj::set_relative_path_to_project_root_dir("../").
-
inline void run()
Runs the MCMC simulation and processes all measuremnts based on the provided measurement processor.
-
inline void eval(std::string rel_results_dir)
Executes the respective Python functions for evaluating the MCMC simulation and stores the results in
rel_results_dir.For the evaluation to work, one needs to enable Python in CMake and initialize Python by
mcmc::util::initialize_python(PYTHON_SCRIPTS_PATH)in the main function.- Parameters
rel_results_dir – Relative path to the
project_root_dirfor storing the results
Public Static Functions
-
static inline Simulation generate_simulation(SB &systembase, EP &execution_mode, MS &measurement, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation based on systembase parameters, execution parameters and measure parameters.
-
static inline Simulation generate_simulation(const std::string &rel_systembase_params_path, EP &execution_mode, MS &measurement, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation based on execution parameters and measure parameters, where systembase parameters are loaded from
rel_systembase_params_path.
-
static inline Simulation generate_simulation(SB &systembase, const std::string &rel_execution_mode_path, MS &measurement, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation based on systembase parameters and measure parameters, where execution parameters are loaded from
rel_execution_mode_path.
-
static inline Simulation generate_simulation(const std::string &rel_systembase_params_path, const std::string &rel_execution_mode_path, MS &measurement, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation based on measure parameters, where systembase parameters are loaded from
rel_systembase_params_pathand execution parameters fromrel_execution_mode_path.
-
static inline Simulation generate_simulation(SB &systembase, EP &execution_mode, const std::string &rel_measurement_path, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation based on systembase parameters and execution parameters, where measure parameters are loaded from
rel_measurement_path.
-
static inline Simulation generate_simulation(const std::string &rel_systembase_params_path, EP &execution_mode, const std::string &rel_measurement_path, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation based on execution parameters, where systembase parameters are loaded from
rel_systembase_params_pathand measure parameters fromrel_measurement_path.
-
static inline Simulation generate_simulation(SB &systembase, const std::string &rel_execution_mode_path, const std::string &rel_measurement_path, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation based on systembase parameters, where execution parameters are loaded from
rel_execution_mode_pathand measure parameters fromrel_measurement_path.
-
static inline Simulation generate_simulation(const std::string &rel_systembase_params_path, const std::string &rel_execution_mode_path, const std::string &rel_measurement_path, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Simulation, where systembase parameters are loaded from
rel_systembase_params_path, execution parameters fromrel_execution_mode_pathand measure parameters fromrel_measurement_path.
-
static inline Simulation prepare_simulation_from_file(SB &systembase, MS &measurement, const std::string &running_parameter_kind = "None", const std::string &running_parameter = "None", const std::vector<double> &rp_intervals = std::vector<double>{0.0})
Prepare a simulation that will be executed from file.
- Parameters
systembase – Object of a systembase parameter class
measurement – Object of a measure parameter class handling gathering and writing the simulation data to file
running_parameter_kind – Parent configuration module key, providing the program with the necessary information of where to find the running parameter. If none is given, the simulation is only executed for the original set of parameters (default:
"None")running_parameter – Name of the running parameter (default:
"None")rp_intervals – List of values for the running parameter. A MCMC simulation is executed for each of these values one by one (default:
std::vector<double>{0.0})
-
static inline Simulation generate_simulation_from_file(const std::string &rel_sim_params_path, const std::string &rel_execution_mode_path = "", const std::string &rel_measurement_path = "")
Generate a simulation solely from file.
Uses the given paths to load an entire simulation - It is important that the template parameters are in concordance with the simulation parameter file.
- Parameters
rel_sim_params_path – Relative path to the
project_root_dirof the simulation pointing to thesim_params.json filerel_execution_mode_path – Relative path to the
project_root_dirof the simulation pointing to the execution mode params.jsonfile. If no path is provided, the default path is the one provided in sim_params.json.rel_measurement_path – Relative path to the
project_root_dirof the simulation pointing to the measurement processing params.jsonfile. if no path is provided, the default path is the one provided insim_params.json.
Predefined measures
List of predefined measures, which can be used in combination with the
mcmc::simulation::MeasureSystemBase class.
Measure base class
-
template<typename SB>
struct mcmc::measures::Measure Base policy class for defining measures.
In addition to the two virtual classes, most of the measures provide a static function called
compute_measure, which returns the measure as a number instead of a string.Subclassed by mcmc::measures::Abs< SB >, mcmc::measures::AbsMean< SB >, mcmc::measures::Config< SB >, mcmc::measures::FourthMoment< SB >, mcmc::measures::Mean< SB >, mcmc::measures::SecondMoment< SB >, mcmc::measures::Variance< SB >
Public Functions
-
virtual std::string measure(const SB &system) = 0
Returns the measure; Note that for complex types, the
mcmc_simulation/util/complex_type.hppheader overloadsstd::to_string.- Parameters
system – Instance of a systembase class
- Returns
The measurement as a string
-
virtual std::string name() = 0
Returns the name used as an identifier for the measure.
-
virtual std::string measure(const SB &system) = 0