master
|
a Code for the Combination of Indirect and Direct Constraints on High Energy Physics Models
|
|
A class for Monte Carlo.
More...
#include <MonteCarlo.h>
A class for Monte Carlo.
- Author
- HEPfit Collaboration
- Copyright
- GNU General Public License
This class is responsible for the MCMC runs using the MCMCEngine class together with input parameters from the InputParser class. The Monte Carlo mode is the default run mode if the –noMC flag is not specified. The settings for the Monte Carlo run can be fixed in in the format specified in the MonteCarlo.conf file, the name of this configuration file should be specified as the second argument to the executable.
- Examples
- MCMC.cpp, and myModel_MCMC.cpp.
Definition at line 35 of file MonteCarlo.h.
|
| void | addCustomObservableType (const std::string name, boost::function< Observable *() > funct) |
| |
| std::map< std::string, BCH1D > | getHistograms1D () const |
| |
| std::map< std::string, BCH2D > | getHistograms2D () const |
| |
| | MonteCarlo (ModelFactory &ModelF, ThObsFactory &ThObsF, const std::string &ModelConf_i, const std::string &MonteCarloConf_i, const std::string &OutFile_i, const std::string &JobTag_i) |
| | Constructor. More...
|
| |
| void | Run (const int rank) |
| | This member is responsible for setting the Monte Carlo run parameters and conducting the Monte Carlo run including initiating all output generation. More...
|
| |
| void | TestRun (int rank) |
| | This member is used for test runa to generate a single event. More...
|
| |
| virtual | ~MonteCarlo () |
| | The default destructor. More...
|
| |
◆ MonteCarlo()
| MonteCarlo::MonteCarlo |
( |
ModelFactory & |
ModelF, |
|
|
ThObsFactory & |
ThObsF, |
|
|
const std::string & |
ModelConf_i, |
|
|
const std::string & |
MonteCarloConf_i, |
|
|
const std::string & |
OutFile_i, |
|
|
const std::string & |
JobTag_i |
|
) |
| |
Constructor.
The default constructor sets the names of the configuration files and the names of the output root file and specific output directory if a job ID is specified as an argument to the executable. The constructor also sets the default values of some flags related to the Monte Carlo run. The boolean flags (FindModeWithMinuit, PrintAllMarginalized, PrintCorrelationMatrix, PrintKnowledgeUpdatePlots, PrintParameterPlot) attain their run time values after the MonteCarlo.conf file is parsed by MonteCarlo::Run().
- Parameters
-
| [in] | ModelF | |
| [in] | ThObsF | |
| [in] | ModelConf_i | the name of the input configuration file for the model name, the model parameters and observables to be calculated (Observables, Observables2D, Model Parameters vs. Observables and Correlated Gaussian Observables) |
| [in] | MonteCarloConf_i | the name of the Monte Carlo configuration file that specifies the parameters of the Monte Carlo run like no. of chains, no. of pre run iterations etc. |
| [in] | OutFile_i | the name of the root output file to be given without the .root extention |
| [in] | JobTag_i | optional job tag that might be specified |
Definition at line 26 of file MonteCarlo.cpp.
36 if (OutFile_i.compare(
"") == 0)
OutFile =
"MCout" +
JobTag +
".root";
◆ ~MonteCarlo()
| MonteCarlo::~MonteCarlo |
( |
| ) |
|
|
virtual |
The default destructor.
Definition at line 53 of file MonteCarlo.cpp.
56 boost::ptr_vector<Observable>().swap(
Obs);
◆ addCustomObservableType()
| void MonteCarlo::addCustomObservableType |
( |
const std::string |
name, |
|
|
boost::function< Observable *() > |
funct |
|
) |
| |
◆ getHistograms1D()
| std::map<std::string, BCH1D> MonteCarlo::getHistograms1D |
( |
| ) |
const |
|
inline |
◆ getHistograms2D()
| std::map<std::string, BCH2D> MonteCarlo::getHistograms2D |
( |
| ) |
const |
|
inline |
◆ ParseMCMCConfig()
| void MonteCarlo::ParseMCMCConfig |
( |
std::string |
file | ) |
|
|
private |
Definition at line 478 of file MonteCarlo.cpp.
480 std::ifstream ifile(file.c_str());
481 if (!ifile.is_open())
482 throw std::runtime_error(
"\nERROR: " +
MCMCConf +
" does not exist. Make sure to specify a valid Monte Carlo configuration file.\n");
486 IsEOF = getline(ifile, line).eof();
487 if (*line.rbegin() ==
'\r') line.erase(line.length() - 1);
488 if (line.empty() || line.at(0) ==
'#')
490 boost::char_separator<char> sep(
" \t");
491 boost::tokenizer<boost::char_separator<char> > tok(line, sep);
492 boost::tokenizer<boost::char_separator<char> >::iterator beg = tok.begin();
493 if (beg->compare(
"NChains") == 0) {
495 if (isdigit(beg->at(0)) && atoi((*beg).c_str()) > 0)
MCEngine.
setNChains(atoi((*beg).c_str()));
496 else if (isdigit(beg->at(0)) && atoi((*beg).c_str()) == 0)
498 else throw std::runtime_error(
"\nERROR: NChains in the MonteCarlo configuration file: " +
MCMCConf +
" can only be an integer > 0.\n");
500 throw std::runtime_error(
"\nERROR: NChains in the MonteCarlo configuration file: " +
MCMCConf +
" can only be an integer >= 0.\n");
501 }
else if (beg->compare(
"PrerunMaxIter") == 0) {
503 if (isdigit(beg->at(0)) && atoi((*beg).c_str()) > 0)
MCEngine.SetNIterationsPreRunMax(atoi((*beg).c_str()));
505 throw std::runtime_error(
"\nERROR: PrerunMaxIter in the MonteCarlo configuration file: " +
MCMCConf +
" can only be an integer > 0.\n");
506 }
else if (beg->compare(
"NIterationsUpdateMax") == 0) {
508 if (isdigit(beg->at(0)) && atoi((*beg).c_str()) > 0)
MCEngine.SetNIterationsPreRunCheck(atoi((*beg).c_str()));
510 throw std::runtime_error(
"\nERROR: NIterationsUpdateMax in the MonteCarlo configuration file: " +
MCMCConf +
" can only be an integer > 0.\n");
511 }
else if (beg->compare(
"Seed") == 0) {
513 if (!isdigit(beg->at(0)))
throw std::runtime_error(
"\nERROR: Seed in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a number.\n");
514 int seed = atoi((*beg).c_str());
517 }
else if (beg->compare(
"Iterations") == 0) {
519 if (isdigit(beg->at(0)))
MCEngine.SetNIterationsRun(atoi((*beg).c_str()));
521 throw std::runtime_error(
"\nERROR: Iterations in the MonteCarlo configuration file: " +
MCMCConf +
" can only be an integer.\n");
522 }
else if (beg->compare(
"MinimumEfficiency") == 0) {
524 double efficiency = atof((*beg).c_str());
525 if (efficiency > 0. && efficiency <= 1.)
MCEngine.SetMinimumEfficiency(efficiency);
527 throw std::runtime_error(
"\nERROR: MinimumEfficiency in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a real number greater than 0.0 and less than or equal to 1.0.\n");
528 }
else if (beg->compare(
"MaximumEfficiency") == 0) {
530 double efficiency = atof((*beg).c_str());
531 if (efficiency > 0. && efficiency <= 1.)
MCEngine.SetMaximumEfficiency(efficiency);
533 throw std::runtime_error(
"\nERROR: MaximumEfficiency in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a real number greater than 0.0 and less than or equal to 1.0.\n");
534 }
else if (beg->compare(
"RValueForConvergence") == 0) {
536 double rvalue = atof((*beg).c_str());
537 if (rvalue > 1. )
MCEngine.SetRValueParametersCriterion(rvalue);
539 throw std::runtime_error(
"\nERROR: RValueForConvergence in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a real number greater than 1.0.\n");
540 }
else if (beg->compare(
"WriteChain") == 0) {
542 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
writechains = (beg->compare(
"true") == 0);
544 throw std::runtime_error(
"\nERROR: WriteChain in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
545 }
else if (beg->compare(
"FindModeWithMinuit") == 0) {
547 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
FindModeWithMinuit = (beg->compare(
"true") == 0);
549 throw std::runtime_error(
"\nERROR: FindModeWithMinuit in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
550 }
else if (beg->compare(
"RunMinuitOnly") == 0) {
552 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
RunMinuitOnly = (beg->compare(
"true") == 0);
554 throw std::runtime_error(
"\nERROR: RunMinuitOnly in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
555 }
else if (beg->compare(
"CalculateNormalization") == 0) {
559 throw std::runtime_error(
"\nERROR: CalculateNormalization in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
560 }
else if (beg->compare(
"NIterationNormalizationMC") == 0) {
564 throw std::runtime_error(
"\nERROR: NIterationNormalizationMC in the MonteCarlo configuration file: " +
MCMCConf +
" can only be an integer.\n");
565 }
else if (beg->compare(
"PrintAllMarginalized") == 0) {
567 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
PrintAllMarginalized = (beg->compare(
"true") == 0);
569 throw std::runtime_error(
"\nERROR: PrintAllMarginalized in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
570 }
else if (beg->compare(
"PrintCorrelationMatrix") == 0) {
572 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
PrintCorrelationMatrix = (beg->compare(
"true") == 0);
574 throw std::runtime_error(
"\nERROR: PrintCorrelationMatrix in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
575 }
else if (beg->compare(
"PrintKnowledgeUpdatePlots") == 0) {
579 throw std::runtime_error(
"\nERROR: PrintKnowledgeUpdatePlots in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
580 }
else if (beg->compare(
"PrintParameterPlot") == 0) {
582 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
PrintParameterPlot = (beg->compare(
"true") == 0);
584 throw std::runtime_error(
"\nERROR: PrintParameterPlot in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
585 }
else if (beg->compare(
"PrintTrianglePlot") == 0) {
587 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
PrintTrianglePlot = (beg->compare(
"true") == 0);
589 throw std::runtime_error(
"\nERROR: PrintTrianglePlot in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
590 }
else if (beg->compare(
"WritePreRunData") == 0) {
592 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
WritePreRunData = (beg->compare(
"true") == 0);
594 throw std::runtime_error(
"\nERROR: WritePreRunData in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
595 }
else if (beg->compare(
"ReadPreRunData") == 0) {
598 }
else if (beg->compare(
"MultivariateProposal") == 0) {
600 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
MCEngine.SetProposeMultivariate((beg->compare(
"true") == 0));
602 throw std::runtime_error(
"\nERROR: MultivariateProposal in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
603 }
else if (beg->compare(
"Histogram1DSmooth") == 0) {
605 if (beg->compare(
"true") == 0) {
607 }
else if (beg->compare(
"false") == 0) {
609 }
else if (isdigit(beg->at(0))) {
610 if (atoi((*beg).c_str()) >= 0 && atoi((*beg).c_str()) <= 5)
MCEngine.
setSmooth(atoi((*beg).c_str()));
612 throw std::runtime_error(
"\nERROR: Histogram1DSmooth in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true', 'false' or an integer from 0 to 5.\n");
613 }
else if (beg->compare(
"Histogram2DType") == 0) {
615 if (!isdigit(beg->at(0)))
616 throw std::runtime_error(
"\nERROR: Histogram2DType in the MonteCarlo configuration file : " +
MCMCConf +
"can only be an integer amongst 1001 -> Lego, 101 -> Filled, 1 -> Contour.\n");
617 int type = atoi((*beg).c_str());
618 if (type == 1 || type == 101 || type == 1001) {
621 throw std::runtime_error(
"\nERROR: Histogram2DType in the MonteCarlo configuration file : " +
MCMCConf +
"can only be an integer amongst 1001 -> Lego, 101 -> Filled, 1 -> Contour.\n");
622 }
else if (beg->compare(
"MCMCInitialPosition") == 0) {
624 if (beg->compare(
"Center") == 0) {
625 MCEngine.SetInitialPositionScheme(BCEngineMCMC::kInitCenter);
626 }
else if (beg->compare(
"RandomUniform") == 0) {
627 MCEngine.SetInitialPositionScheme(BCEngineMCMC::kInitRandomUniform);
628 }
else if (beg->compare(
"RandomPrior") == 0) {
629 MCEngine.SetInitialPositionScheme(BCEngineMCMC::kInitRandomPrior);
631 throw std::runtime_error(
"\nERROR: MCMCInitialPosition in MonteCarlo config file: " +
MCMCConf +
" can only be 'Center', 'RandomUniform' or 'RandomPrior'.\n");
632 }
else if (beg->compare(
"PrintLogo") == 0) {
634 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
MCEngine.
setPrintLogo((beg->compare(
"true") == 0));
636 throw std::runtime_error(
"\nERROR: PrintLogo in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
637 }
else if (beg->compare(
"NoHistogramLegend") == 0) {
639 if (beg->compare(
"true") == 0 || beg->compare(
"false") == 0)
MCEngine.
setNoLegend((beg->compare(
"true") == 0));
641 throw std::runtime_error(
"\nERROR: PrintLogo in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
642 }
else if (beg->compare(
"PrintLoglikelihoodPlots") == 0) {
646 throw std::runtime_error(
"\nERROR: PrintLoglikelihoodPlots in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
647 if (beg->compare(
"true") == 0) gSystem->MakeDirectory((
ObsDirName +
"/LogLikelihoodPlots").c_str());
648 }
else if (beg->compare(
"WriteLogLikelihoodChain") == 0) {
652 throw std::runtime_error(
"\nERROR: WriteLogLikelihoodChain in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
653 }
else if (beg->compare(
"WriteParametersChains") == 0) {
657 throw std::runtime_error(
"\nERROR: WriteParametersChain in the MonteCarlo configuration file: " +
MCMCConf +
" can only be 'true' or 'false'.\n");
658 }
else if (beg->compare(
"Histogram2DAlpha") == 0) {
660 double alpha = atof((*beg).c_str());
663 throw std::runtime_error(
"\nERROR: Histogram2DAlpha in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a real number greater than 0.0 and less than or equal to 1.0.\n");
664 }
else if (beg->compare(
"NBinsHistogram1D") == 0) {
666 unsigned int nBins1D = atoi((*beg).c_str());
668 else throw std::runtime_error(
"\nERROR: NBinsHistogram1D in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a integer greater than 0 or 0 to set to default value (100).\n");
669 }
else if (beg->compare(
"NBinsHistogram2D") == 0) {
671 unsigned int nBins2D = atoi((*beg).c_str());
673 else throw std::runtime_error(
"\nERROR: NBinsHistogram2D in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a integer greater than 0 or 0 to set to default value (100).\n");
674 }
else if (beg->compare(
"InitialPositionAttemptLimit") == 0) {
676 unsigned int max_tries = atoi((*beg).c_str());
677 if (max_tries > 0)
MCEngine.SetInitialPositionAttemptLimit(max_tries);
678 else if (max_tries == 0)
MCEngine.SetInitialPositionAttemptLimit(10000);
679 else throw std::runtime_error(
"\nERROR: InitialPositionAttemptLimit in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a integer greater than 0 or 0 to set to default value (100).\n");
680 }
else if (beg->compare(
"SignificantDigits") == 0) {
682 unsigned int significants = atoi((*beg).c_str());
684 else throw std::runtime_error(
"\nERROR: SignificantDigits in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a integer greater than 0 or 0 to set to default values.\n");
685 }
else if (beg->compare(
"HistogramBufferSize") == 0) {
687 unsigned int histogramBufferSize = atoi((*beg).c_str());
689 else throw std::runtime_error(
"\nERROR: HistogramBufferSize in the MonteCarlo configuration file: " +
MCMCConf +
" can only be a integer greater than 0 or 0 to set to default values.\n");
691 throw std::runtime_error(
"\nERROR: Wrong keyword in MonteCarlo config file: " +
MCMCConf +
"\n Make sure to specify a valid Monte Carlo configuration file.\n");
694 MCEngine.SetOptimizationMethod(BCIntegrate::kOptMinuit);
696 throw std::runtime_error(
"\nERROR: MaximumEfficiency (default 0.5) must be greater than MaximumEfficiency (default 0.15) in the MonteCarlo configuration file: " +
MCMCConf +
".\n");
698 throw std::runtime_error((
"\nMonteCarlo ERROR: CalculateNormalization cannot be set to MC without setting NIterationNormalizationMC > 0 in " +
MCMCConf +
" .\n").c_str());
◆ ReadPreRunData()
| void MonteCarlo::ReadPreRunData |
( |
std::string |
file | ) |
|
|
private |
Definition at line 701 of file MonteCarlo.cpp.
703 std::ifstream ifile(file.c_str());
704 if (!ifile.is_open())
705 throw std::runtime_error(
"\nMonteCarlo::ReadPreRunData ERROR: " + file +
" does not exist.\n");
708 std::vector<double> mode;
709 std::vector<double> scale;
711 IsEOF = getline(ifile, line).eof();
714 boost::char_separator<char> sep(
" ");
715 boost::tokenizer<boost::char_separator<char> > tok(line, sep);
716 boost::tokenizer<boost::char_separator<char> >::iterator beg = tok.begin();
718 mode.push_back(atof((*beg).c_str()));
720 scale.push_back(atof((*beg).c_str()));
722 if (mode.size() !=
MCEngine.GetNParameters())
723 throw std::runtime_error(
"\nMonteCarlo::ReadPreRunData ERROR: wrong data size.\n");
724 std::vector<double> mode_all;
725 std::vector<double> scale_all;
726 for (
unsigned int i = 0; i <
MCEngine.GetNChains(); i++){
727 mode_all.insert(mode_all.end(), mode.begin(), mode.end());
728 scale_all.insert(scale_all.end(), scale.begin(), scale.end());
730 MCEngine.SetInitialPositions(mode_all);
731 MCEngine.SetInitialScaleFactors(scale_all);
◆ Run()
| void MonteCarlo::Run |
( |
const int |
rank | ) |
|
This member is responsible for setting the Monte Carlo run parameters and conducting the Monte Carlo run including initiating all output generation.
The algorithm implemented by this member is as follows:
- Initiate InputParser::ReadParameters() which read the SomeModel.conf file for setting the model parameters and the observables to be generated. This call also passes on the name of the model to the private member ModelName.
- Map the model parameter mean values with the map DP and calculate buffsize which can be used for implementing MPI runs. The variable buffsize is incremented only for those model parameters that are varied in the Monte Carlo run.
- Initiate the model using the map DP checking for consistency between required model parameters and the ones supplied in the SomeModel.conf file
- Set the model name and initialize the MCMC engine with the model at hand.
- For MPI runs, send the evaluates of the loglikelihood for the prerun to the slave processes (rank != 0)
- The master in an MPI run or the process in a serial run then parses the MonterCarlo.conf file to read the parameters for the Monte Carlo run.
- The root output file is handed over to the object out of type BCModelOutput and some BAT options are set for the log and output histograms.
- The MCMC is run and all the out put is generated according to the options set in the MonteCarlo.conf file.
- For a MPI run, the final call to the MPI class prepares the processes for finalizing.
The details for BCSummaryTool, BCLog, BCAux and BCModelOutput can be found in the BAT website. These are used mainly to generate logs and output.
The details of the object MCEngine of type MonteCarloEngine which overloads the BCEngineMCMC class can be found in our documentation of the former class.
- Parameters
-
| [in] | rank | = MPI::COMM_WORLD.Get_rank(), specifies the rank of the process. This carries a non zero value only when the executable is compiled with the parallelized version of BAT and run as parallel processes with MPI. |
- Examples
- MCMC.cpp, and myModel_MCMC.cpp.
Definition at line 128 of file MonteCarlo.cpp.
130 if (rank == 0)
throw std::runtime_error(
"ERROR: MonteCarlo::Run() cannot be called after calling MonteCarlo::TestRun().\n");
141 std::map<std::string, double> DP;
142 for (std::vector<ModelParameter>::iterator it =
ModPars.begin(); it <
ModPars.end(); it++) {
143 if (it->geterrg() > 0. || it->geterrf() > 0.)
145 if (it->IsCorrelated()) {
146 for (
unsigned int i = 0; i <
CGP.size(); i++) {
147 if (
CGP[i].getName().compare(it->getCgp_name()) == 0) {
148 std::string index = it->getname().substr(
CGP[i].getName().size());
149 long int lindex = strtol(index.c_str(), NULL, 10);
151 DP[
CGP[i].getPar(lindex - 1).getname()] =
CGP[i].getPar(lindex - 1).getave();
153 std::stringstream out;
154 out << it->getname();
155 throw std::runtime_error(
"MonteCarlo::Run(): " + out.str() +
"seems to be part of a CorrelatedGaussianParameters object, but I couldn't find the corresponding object");
160 DP[it->getname()] = it->getave();
163 if (rank == 0)
throw std::runtime_error(
"No parameters being varied. Aborting MCMC run.\n");
169 if (rank == 0) std::cout <<
"\nPlease set the following parameters in the model configuration files:\n" << std::endl;
171 if (rank == 0) std::cout <<
"ModelParameter\t" << *it << std::endl;
173 std::cout << std::endl;
177 if (rank == 0)
throw std::runtime_error(
"\nERROR: " +
ModelName +
" cannot be initialized.\n");
180 int discardbuffer = 0;
182 for (std::vector<ModelParameter>::iterator it =
ModPars.begin(); it <
ModPars.end(); it++) {
183 if (std::find(unknownParameters.begin(), unknownParameters.end(), it->getname()) != unknownParameters.end()) {
184 if (it->geterrg() > 0. || it->geterrf() > 0.) {
186 if (rank == 0) std::cout <<
"\nWARNING: " << it->getname() <<
" has a flat or Gaussian error in the configuration file even though it is an unknown parameter!!!\n";
190 buffsize = buffsize - discardbuffer;
192 if (rank == 0)
throw std::runtime_error(
"No relevant parameters being varied. Aborting MCMC run.\n");
199 if (gSystem->GetPathInfo(
ObsDirName.c_str(), info) != 0) {
200 if (gSystem->MakeDirectory(
ObsDirName.c_str()) == 0) std::cout <<
ObsDirName <<
" directory has been created." << std::endl;
201 else throw std::runtime_error(
"ERROR: " +
ObsDirName +
" directory cannot be created.\n");
207 MCEngine.SetInitialPositionAttemptLimit(10000);
210 double *recvbuff =
new double[buffsize];
215 double **sendbuff =
new double*[1];
216 sendbuff[0] =
new double[1];
218 std::vector<double> pars;
219 int obsbuffsize =
Obs.size() + 2 *
Obs2D.size();
220 for (std::vector<CorrelatedGaussianObservables>::iterator it1 =
CGO.begin(); it1 <
CGO.end(); it1++)
221 obsbuffsize += it1->getObs().size();
224 MPI_Scatter(sendbuff[0], buffsize, MPI_DOUBLE, recvbuff, buffsize, MPI_DOUBLE, 0, MPI_COMM_WORLD);
226 if (recvbuff[0] == 0.) {
228 MPI_Gather(&ll, 1, MPI_DOUBLE, sendbuff[0], 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
229 }
else if (recvbuff[0] == 1.) {
230 pars.assign(recvbuff + 1, recvbuff + buffsize);
232 MPI_Gather(&ll, 1, MPI_DOUBLE, sendbuff[0], 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
233 }
else if (recvbuff[0] == 2.) {
234 double sbuff[obsbuffsize];
235 std::map<std::string, double> DPars;
236 pars.assign(recvbuff + 1, recvbuff + buffsize);
241 for (boost::ptr_vector<Observable>::iterator it =
Obs.begin(); it <
Obs.end(); it++) {
242 sbuff[k++] = it->computeTheoryValue();
244 for (std::vector<Observable2D>::iterator it =
Obs2D.begin(); it <
Obs2D.end(); it++) {
245 sbuff[k++] = it->computeTheoryValue();
246 sbuff[k++] = it->computeTheoryValue2();
249 for (std::vector<CorrelatedGaussianObservables>::iterator it1 =
CGO.begin(); it1 <
CGO.end(); it1++) {
250 std::vector<Observable> pino(it1->getObs());
251 for (std::vector<Observable>::iterator it = pino.begin(); it != pino.end(); ++it)
252 sbuff[k++] = it->computeTheoryValue();
254 MPI_Gather(sbuff, obsbuffsize, MPI_DOUBLE, sendbuff[0], obsbuffsize, MPI_DOUBLE, 0, MPI_COMM_WORLD);
255 }
else if (recvbuff[0] == 3.) {
256 double sbuff[obsbuffsize];
257 MPI_Gather(sbuff, obsbuffsize, MPI_DOUBLE, sendbuff[0], obsbuffsize, MPI_DOUBLE, 0, MPI_COMM_WORLD);
258 }
else if (recvbuff[0] == -1.)
261 std::cout <<
"recvbuff = " << recvbuff[0] <<
" rank " << rank << std::endl;
262 throw std::runtime_error(
"MonteCarlo::Run(): error in MPI message!\n");
270 if (!
RunMinuitOnly) std::cout << std::endl <<
"\nRunning in MonteCarlo mode...\n" << std::endl;
271 else std::cout << std::endl <<
"\nRunning Minuit Minimizer..." << std::endl;
272 std::cout << std::endl;
273 if (
ModPars.size() > 0) std::cout <<
ModPars.size() - unknownParameters.size() <<
" parameters defined." << std::endl;
274 if (
Obs.size() > 0) std::cout <<
Obs.size() <<
" observables defined." << std::endl;
275 if (
Obs2D.size() > 0) std::cout <<
Obs2D.size() <<
" 2D observables defined." << std::endl;
276 if (
CGO.size() > 0) std::cout <<
CGO.size() <<
" correlated gaussian observables defined:" << std::endl;
277 for (std::vector<CorrelatedGaussianObservables>::iterator it1 =
CGO.begin();
278 it1 !=
CGO.end(); ++it1)
279 std::cout <<
" " << it1->getName() <<
" containing "
280 << it1->getObs().size() <<
" observables." << std::endl;
281 std::cout << std::endl;
284 BCLog::OpenLog((
"MinuitMinimizationResults" +
JobTag +
".txt").c_str(), BCLog::debug, BCLog::debug);
285 RedirectHandle_t * rHandle = NULL;
286 gSystem->RedirectOutput((
"MinuitMinimizationResults" +
JobTag +
".txt").c_str(),
"a", rHandle);
287 std::time_t ti = std::time(NULL);
288 #if __GNUC__ >= 5 || defined __clang__
289 std::cout <<
"\nMinuit Minimization started at " << std::put_time(std::localtime(&ti),
"%c %Z") <<
" (" << ti <<
"s since the Epoch)" <<
"\n" << std::endl;
292 strftime(mitime,
sizeof(mitime),
"%c %Z", std::localtime(&ti));
293 std::cout <<
"\nMinuit Minimization started at " << mitime <<
" (" << ti <<
"s since the Epoch)" <<
"\n" << std::endl;
295 std::cout <<
" " <<std::endl;
296 std::cout <<
"\t\t*** Minimizer Options ***" << std::endl;
297 MCEngine.GetMinuit().Options().Print();
298 std::cout <<
" " <<std::endl;
300 std::time_t tf = std::time(NULL);
301 #if __GNUC__ >= 5 || defined __clang__
302 std::cout <<
"\nMinuit Minimization ended at " << std::put_time(std::localtime(&tf),
"%c %Z") <<
" (" << tf <<
"s since the Epoch)" <<
"\n" << std::endl;
305 strftime(mitime,
sizeof(mftime),
"%c %Z", std::localtime(&tf));
306 std::cout <<
"\nMinuit Minimization ended at " << mftime <<
" (" << tf <<
"s since the Epoch)" <<
"\n" << std::endl;
308 gSystem->RedirectOutput(0);
309 BCLog::OutSummary((
"Minuit results printed in MinuitMinimizationResults" +
JobTag +
".txt").c_str());
310 BCLog::SetPrefix(
false);
311 BCLog::OutSummary(
"");
312 BCLog::SetPrefix(
true);
314 MCEngine.GetMinuit().PrintResults();
315 std::cout << std::endl;
327 MCEngine.InitializeMarkovChainTree();
328 MCEngine.WriteMarkovChainRun(
false);
329 MCEngine.WriteMarkovChainPreRun(
false);
333 std::time_t ti = std::time(NULL);
334 #if __GNUC__ >= 5 || defined __clang__
335 std::cout <<
"\nMCMC run started at " << std::put_time(std::localtime(&ti),
"%c %Z") <<
" (" << ti <<
"s since the Epoch)" <<
"\n" << std::endl;
338 strftime(mitime,
sizeof(mitime),
"%c %Z", std::localtime(&ti));
339 std::cout <<
"\nMCMC run started at " << mitime <<
" (" << ti <<
"s since the Epoch)" <<
"\n" << std::endl;
342 BCLog::OpenLog((
"log" +
JobTag +
".txt").c_str(), BCLog::debug, BCLog::debug);
344 MCEngine.BCIntegrate::SetNbins(NBINSMODELPARS);
345 MCEngine.SetMarginalizationMethod(BCIntegrate::kMargMetropolis);
347 std::time_t tf = std::time(NULL);
348 #if __GNUC__ >= 5 || defined __clang__
349 std::cout <<
"\nMCMC run ended at " << std::put_time(std::localtime(&tf),
"%c %Z") <<
" (" << tf <<
"s since the Epoch)" << std::endl;
352 strftime(mftime,
sizeof(mftime),
"%c %Z", std::localtime(&tf));
353 std::cout <<
"\nMCMC run ended at " << mftime <<
" (" << tf <<
"s since the Epoch)" <<
"\n" << std::endl;
355 int hour = (tf-ti)/3600;
356 int min = ((tf-ti)%3600) / 60;
357 int sec = ((tf-ti)%3600) % 60;
358 std::cout <<
"Time taken by the MCMC run: ";
359 std::cout << std::setfill(
'0') << std::setw(2) << hour <<
":";
360 std::cout << std::setfill(
'0') << std::setw(2) << min <<
":" ;
361 std::cout << std::setfill(
'0') << std::setw(2) <<
sec <<
"\n" << std::endl;
374 MCEngine.PrintCorrelationMatrix((
"CorrelationMatrix" +
JobTag +
".pdf").c_str());
375 MCEngine.PrintCorrelationMatrix((
"CorrelationMatrix" +
JobTag +
".tex").c_str());
389 std::ofstream outHistoLog;
390 outHistoLog.open((
ObsDirName +
"/HistoLog" +
JobTag +
".txt").c_str(), std::ios::out);
395 std::ofstream outStatLog;
396 outStatLog.open((
ObsDirName +
"/Statistics" +
JobTag +
".txt").c_str(), std::ios::out);
402 std::ofstream outPreRun;
403 outPreRun.open((
"PreRun" +
JobTag +
".txt").c_str(), std::ios::out);
409 std::stringstream ss;
411 BCLog::SetPrefix(
false);
412 BCLog::OutSummary(ss.str().c_str());
413 BCLog::SetPrefix(
true);
415 BCLog::OutSummary(ss.str().c_str());
418 BCLog::OutSummary(ss.str().c_str());
423 BCLog::SetPrefix(
false);
424 BCLog::OpenLog((
"MonteCarlo_results" +
JobTag +
".txt").c_str(), BCLog::summary, BCLog::nothing);
430 std::ofstream outStatLog;
431 outStatLog.open((
ObsDirName +
"/Statistics" +
JobTag +
".txt").c_str(), std::ios::app);
440 outStatLog <<
"\nNormalization for " <<
ModelName.c_str() <<
": " << normalizationMC[0] <<
" +- " << normalizationMC[1] <<
"\n" << std::endl;
443 throw std::runtime_error((
"\n ERROR: Normalization method" +
CalculateNormalization +
" not implemented.\n").c_str());
451 BCLog::OpenLog((
"log_CorrelationPlots" +
JobTag +
".txt").c_str(), BCLog::debug, BCLog::debug);
452 MCEngine.PrintCorrelationPlot(
"CorrelationPlots" +
JobTag +
".pdf");
458 double ** sendbuff =
new double *[
MCEngine.procnum];
459 sendbuff[0] =
new double[
MCEngine.procnum * buffsize];
460 for (
int il = 1; il <
MCEngine.procnum; il++) {
461 sendbuff[il] = sendbuff[il - 1] + buffsize;
462 sendbuff[il][0] = -1.;
464 MPI_Scatter(sendbuff[0], buffsize, MPI_DOUBLE, recvbuff, buffsize, MPI_DOUBLE, 0, MPI_COMM_WORLD);
472 }
catch (std::string message) {
473 std::cerr << message << std::endl;
◆ TestRun()
| void MonteCarlo::TestRun |
( |
int |
rank | ) |
|
This member is used for test runa to generate a single event.
The values of the parameters that are used to generate the single event is the average value passed from the SomeModel.conf file.
The algorithm implemented by this member is as follows:
- Initiate InputParser::ReadParameters() which read the SomeModel.conf file for setting the model parameters and the observables to be generated. This call also passes on the name of the model to the private member ModelName.
- Map the model parameter mean values with the map DP and calculate buffsize which can be used for implementing MPI runs. The variable buffsize is incremented only for those model parameters that are varied in the Monte Carlo run.
- Initiate the model using the map DP checking for consistency between required model parameters and the ones supplied in the SomeModel.conf file
- Generate a single set of observables and correlated Gaussian observables as listed in the SomeModel.conf file. The output is passes to the standard output.
- Parameters
-
| [in] | rank | = MPI::COMM_WORLD.Get_rank(), specifies the rank of the process. This carries a non zero value only when the executable is compiled with the parallelized version of BAT and run as parallel processes with MPI. |
- Examples
- MCMC.cpp.
Definition at line 59 of file MonteCarlo.cpp.
61 if (rank == 0)
throw std::runtime_error(
"ERROR: MonteCarlo::TestRun() cannot be called after calling MonteCarlo::Run().\n");
69 std::map<std::string, double> DP;
70 if (
Obs.size() == 0 &&
CGO.size() == 0)
throw std::runtime_error(
"\nMonteCarlo::TestRun(): No observables or correlated Gaussian observables defined in SomeModel.conf file\n");
72 for (std::vector<ModelParameter>::iterator it =
ModPars.begin(); it <
ModPars.end(); it++) {
73 if (it->IsCorrelated()) {
74 for (
unsigned int i = 0; i <
CGP.size(); i++) {
75 if (
CGP[i].getName().compare(it->getCgp_name()) == 0) {
76 std::string index = it->getname().substr(
CGP[i].getName().size());
77 long int lindex = strtol(index.c_str(), NULL, 10);
79 DP[
CGP[i].getPar(lindex - 1).getname()] =
CGP[i].getPar(lindex - 1).getave();
81 std::stringstream out;
83 throw std::runtime_error(
"MonteCarlo::Run(): " + out.str() +
"seems to be part of a CorrelatedGaussianParameters object, but I couldn't find the corresponding object");
88 DP[it->getname()] = it->getave();
93 std::cout <<
"\nPlease set the following parameters in the model configuration files:\n" << std::endl;
95 std::cout <<
"ModelParameter\t" << *it << std::endl;
97 std::cout << std::endl;
100 if (rank == 0)
throw std::runtime_error(
"ERROR: Parameter(s) missing in model initialization. \n");
104 if (unknownParameters.size() > 0 && rank == 0) {
105 std::cout <<
"\n" << std::endl;
106 for (std::vector<std::string>::iterator it = unknownParameters.begin(); it != unknownParameters.end(); it++)
107 std::cout <<
"WARNING: unknown parameter " << *it <<
" not added to MCMC Test Run" << std::endl;
109 if (
Obs.size() > 0) std::cout <<
"\nObservables: \n" << std::endl;
110 for (boost::ptr_vector<Observable>::iterator it =
Obs.begin(); it <
Obs.end(); it++) {
111 double th = it->computeTheoryValue();
112 std::cout << it->getName() <<
" = " << th << std::endl;
115 if (
CGO.size() > 0) std::cout <<
"\nCorrelated Gaussian Observables: \n" << std::endl;
116 for (std::vector<CorrelatedGaussianObservables>::iterator it1 =
CGO.begin(); it1 <
CGO.end(); it1++) {
117 std::cout << it1->getName() <<
":" << std::endl;
118 std::vector<Observable> ObsInCGO = it1->getObs();
119 for (std::vector<Observable>::iterator it2 = ObsInCGO.begin(); it2 < ObsInCGO.end(); it2++) {
120 double th = it2->computeTheoryValue();
121 std::cout << it2->getName() <<
" = " << th << std::endl;
123 std::cout << std::endl;
◆ CalculateNormalization
| std::string MonteCarlo::CalculateNormalization |
|
private |
< Flag for calculating the evidence.
Definition at line 170 of file MonteCarlo.h.
◆ CGO
Vector for the Correlated Gaussian Observables defined in SomeModel.conf.
Definition at line 161 of file MonteCarlo.h.
◆ CGP
Vector for the Correlated Gaussian Parameters defined in SomeModel.conf.
Definition at line 162 of file MonteCarlo.h.
◆ checkrun
| bool MonteCarlo::checkrun |
|
private |
◆ FindModeWithMinuit
| bool MonteCarlo::FindModeWithMinuit |
|
private |
Flag for using Minuit libraries.
Definition at line 168 of file MonteCarlo.h.
◆ JobTag
| std::string MonteCarlo::JobTag |
|
private |
String for the optional JobTag argument to be passes to the executable.
Definition at line 166 of file MonteCarlo.h.
◆ MCEngine
◆ MCMCConf
| std::string MonteCarlo::MCMCConf |
|
private |
String for the name of the MonteCarlo.conf file.
Definition at line 164 of file MonteCarlo.h.
◆ ModelConf
| std::string MonteCarlo::ModelConf |
|
private |
String for the name of the SomeModel.conf file.
Definition at line 163 of file MonteCarlo.h.
◆ ModelName
| std::string MonteCarlo::ModelName |
|
private |
◆ ModPars
Vector for the model parameters defined in SomeModel.conf.
Definition at line 158 of file MonteCarlo.h.
◆ myInputParser
◆ NIterationNormalizationMC
| int MonteCarlo::NIterationNormalizationMC |
|
private |
< Number of iterations for MC integral done to compute normalization of a model
Definition at line 171 of file MonteCarlo.h.
◆ Obs
Vector for the observables defined in SomeModel.conf.
Definition at line 159 of file MonteCarlo.h.
◆ Obs2D
Vector for the Observables2D defined in SomeModel.conf.
Definition at line 160 of file MonteCarlo.h.
◆ ObsDirName
| std::string MonteCarlo::ObsDirName |
|
private |
String for the output directory name.
Definition at line 167 of file MonteCarlo.h.
◆ OutFile
| std::string MonteCarlo::OutFile |
|
private |
String for the name of the output root file without the .root extension.
Definition at line 165 of file MonteCarlo.h.
◆ PrintAllMarginalized
| bool MonteCarlo::PrintAllMarginalized |
|
private |
Flag for printing all Marginalized distributions to be passed on to the BAT routines.
Definition at line 172 of file MonteCarlo.h.
◆ PrintCorrelationMatrix
| bool MonteCarlo::PrintCorrelationMatrix |
|
private |
Flag for printing the correlation matrix.
Definition at line 173 of file MonteCarlo.h.
◆ PrintKnowledgeUpdatePlots
| bool MonteCarlo::PrintKnowledgeUpdatePlots |
|
private |
Flag for printing plots to compare prior vs. posterior knowledge of parameters.
Definition at line 174 of file MonteCarlo.h.
◆ PrintParameterPlot
| bool MonteCarlo::PrintParameterPlot |
|
private |
Flag for printing the overview parameter plots.
Definition at line 175 of file MonteCarlo.h.
◆ PrintTrianglePlot
| bool MonteCarlo::PrintTrianglePlot |
|
private |
Flag for printing the triangle plot.
Definition at line 176 of file MonteCarlo.h.
◆ RunMinuitOnly
| bool MonteCarlo::RunMinuitOnly |
|
private |
◆ writechains
| bool MonteCarlo::writechains |
|
private |
Flag for writing the chains of paramters and observables during the MCMC run.
Definition at line 179 of file MonteCarlo.h.
◆ WritePreRunData
| bool MonteCarlo::WritePreRunData |
|
private |
Flag for printing the overview parameter plots.
Definition at line 177 of file MonteCarlo.h.
The documentation for this class was generated from the following files:
complex sec(const complex &z)
bool checkrun
A check to make sure TestRun()and Run() are not called consecutively.
std::string ObsDirName
String for the output directory name.
void setAlpha2D(double alpha)
A set method to toggle the printing of legends in 1D and 2D histograms.
std::string CalculateNormalization
< Flag for calculating the evidence.
void PrintHistogram(std::string &OutFile, Observable &it, const std::string OutputDir)
Overloaded from PrintHistogram(BCModelOutput&, const std::string) to print histogram for observables.
bool RunMinuitOnly
Flag for running Minuit only.
void CreateHistogramMaps()
Creation of the histogram maps for Observables, Observable2D and Correlated Gaussian Observable.
InputParser myInputParser
An object of the InputParser class.
std::vector< std::string > getmissingModelParameters()
void setHistogramBufferSize(unsigned int histogramBufferSize_i)
A set method to set the size of the buffer used by the histograms.
std::string JobTag
String for the optional JobTag argument to be passes to the executable.
void PrintCorrelationMatrixToLaTeX(const std::string filename)
This member generates the correlation matrix using BCH2D from the BAT libraries.
bool PrintAllMarginalized
Flag for printing all Marginalized distributions to be passed on to the BAT routines.
bool getWriteLogLikelihoodChain()
A get method to get the value of the bool the writing of Loglikelihood in the ROOT tree.
complex log(const complex &z)
int NIterationNormalizationMC
< Number of iterations for MC integral done to compute normalization of a model
void AddChains()
A method to add the observable values and weights to the chain information.
void setPrintLogo(bool print)
A set method to toggle the printing of logo on the histogram pdf.
void setNBins1D(unsigned int nbins)
A set method to set the number of bins for a 1D histograms.
int getMPIWorldSize()
A get method to get the number of MPI world size.
std::vector< Observable2D > Obs2D
Vector for the Observables2D defined in SomeModel.conf.
virtual bool Init(const std::map< std::string, double > &DPars)
A method to initialize the model parameters.
void setNBins2D(unsigned int nbins)
A set method to set the number of bins for a 2D histograms.
int getchainedObsSize() const
A get method to access the number of Observable chains requested.
std::vector< CorrelatedGaussianParameters > CGP
Vector for the Correlated Gaussian Parameters defined in SomeModel.conf.
bool PrintTrianglePlot
Flag for printing the triangle plot.
void setDParsFromParameters(const std::vector< double > ¶meters, std::map< std::string, double > &DPars_i)
A method to rotate the diagonalized parameters to the original basis for correlated parameters.
std::string OutFile
String for the name of the output root file without the .root extension.
int getNumOfUsedEvents() const
A get method to access the number of events used in the MCMC run.
bool writechains
Flag for writing the chains of paramters and observables during the MCMC run.
void ParseMCMCConfig(std::string file)
bool PrintCorrelationMatrix
Flag for printing the correlation matrix.
double computeNormalizationLME()
A method to calculate the normalization based on the Laplace-Metropolis Estimator.
boost::ptr_vector< Observable > Obs
Vector for the observables defined in SomeModel.conf.
std::string computeStatistics()
A get method to compute the mean and rms of the computed observables.
void setHistogram2DType(int type)
A set method to set the band fill type for 2D histograms.
std::vector< ModelParameter > ModPars
Vector for the model parameters defined in SomeModel.conf.
bool WritePreRunData
Flag for printing the overview parameter plots.
std::string writePreRunData()
A method to write in a text file the best fit parameters and the prerun scale factors.
void setNChains(unsigned int i)
A set method to fix the number of chains.
void ReadPreRunData(std::string file)
std::vector< CorrelatedGaussianObservables > CGO
Vector for the Correlated Gaussian Observables defined in SomeModel.conf.
MonteCarloEngine MCEngine
An object of the MonteCarloEngine class.
bool PrintKnowledgeUpdatePlots
Flag for printing plots to compare prior vs. posterior knowledge of parameters.
std::string getHistoLog() const
A get method to access the stream that stores the log messages coming from histogram printing and che...
std::map< std::string, BCH2D > getHistograms2D() const
A get method to access the map of 2D histograms.
bool PrintParameterPlot
Flag for printing the overview parameter plots.
void setNoLegend(bool legend)
A set method to toggle the printing of legends in 1D and 2D histograms.
bool FindModeWithMinuit
Flag for using Minuit libraries.
std::vector< double > computeNormalizationMC(int NIterationNormalizationMC)
A method to calculate the normalization based on the Monte Carlo Simulation.
virtual bool Update(const std::map< std::string, double > &DPars)
The update method for StandardModel.
std::map< std::string, BCH1D > getHistograms1D() const
A get method to access the map of 1D histograms.
void setSmooth(int int_N)
A set method to set the number of smoothing passes for ROOT in 1D histograms.
std::string ModelConf
String for the name of the SomeModel.conf file.
void setSignificants(unsigned int significants_i)
A set method to set the number of significant digits in the output.
bool getWriteParametersChain()
A get method to get the value of the bool the writing of parameters in the ROOT tree.
void setWriteParametersChain(bool LL)
A set method to toggle the writing of parameters in the ROOT tree.
std::string MCMCConf
String for the name of the MonteCarlo.conf file.
void Initialize(StandardModel *Mod_i)
Initialization of the Monte Carlo Engine.
void setWriteLogLikelihoodChain(bool LL)
A set method to toggle the writing of Loglikelihood in the ROOT tree.
std::string ModelName
The name of the model.
std::vector< std::string > getUnknownParameters()
A method to get the vector of the parameters that have been specified in the configuration file but n...
int getNumOfDiscardedEvents() const
A get method to access the number of events discarded due to failure to update model....
void setPrintLoglikelihoodPlots(bool plot)
A set method to toggle the printing of Parameters vs. Loglikelihood.