MaCh3  2.8.0
Reference Guide
MCMCBase.cpp
Go to the documentation of this file.
2 
3 // *************************
4 // Initialise the Manager and make it an object of mcmc class
5 // Now we can dump Manager settings to the output file
7 // *************************
8  // Beginning step number
9  stepStart = 0;
10 
11  // Starting parameters should be thrown
12  out_of_bounds = false;
13  chainLength = Get<unsigned>(fitMan->raw()["General"]["MCMC"]["NSteps"], __FILE__, __LINE__);
14  if (chainLength < 10){
15  MACH3LOG_ERROR("MCMC chain length must be at least 10 steps, otherwise this will result in a floating point exception.");
16  throw MaCh3Exception(__FILE__, __LINE__);
17  }
18 }
19 
20 // *******************
21 // Run the Markov chain with all the systematic objects added
23 // *******************
24  // Multicanonical method toggle from yaml config
25  multicanonical = false;
26  // Need to check if multicanonical itself exists first
27  if(CheckNodeExists(fitMan->raw()["General"]["MCMC"]["Multicanonical"])){
28  multicanonical = GetFromManager<bool>(fitMan->raw()["General"]["MCMC"]["Multicanonical"]["Enabled"], false, __FILE__, __LINE__);
29  }
30  MACH3LOG_INFO("Multicanonical Method: {}", multicanonical);
31 
32  if (multicanonical) {
34  multicanonicalHandler = std::make_unique<MulticanonicalMCMCHandler>();
35 
36  // Initialize the multicanonical handler with the systematics
37  multicanonicalHandler->InitializeMulticanonicalHandlerConfig(fitMan, systematics);
38 #ifdef MACH3_DEBUG
39  // Enable debug output stream for multicanonical handler if debug is enabled
40  multicanonicalHandler->setDebugStream(&debugFile, debug);
41 #endif
42  }
43 
44  // Save the settings into the output file
45  SaveSettings();
46 
47  // Prepare the output branches
48  PrepareOutput();
49 
50  // Remove obsolete memory and make other checks before fit starts
52 
53  // Print Progress before Propose Step
54  PrintProgress(false);
55 
56  // Only propose step if we are running fresh chain. If we are running from previous chain then it's not needed and we can use usual pipeline
57  if(stepStart == 0) {
58  // Reconfigure the samples, systematics and oscillation for first weight
59  // ProposeStep sets logLProp
60  ProposeStep();
61 
62  // Initialise the value of the multicanonical parameter to the centres of the umbrellas
63  if (multicanonical){
64  multicanonicalHandler->InitializeMulticanonicalParams(systematics);
65  }
66  // Set the current logL to the proposed logL for the 0th step
67  // Accept the first step to set logLCurr: this shouldn't affect the MCMC because we ignore the first N steps in burn-in
69  }
70 
71  // Begin MCMC
72  const auto StepEnd = stepStart + chainLength;
73  for (step = stepStart; step < StepEnd; ++step)
74  {
75  DoMCMCStep();
76  }
77  // Save all the MCMC output
78  SaveOutput();
79 
80  // Process MCMC
81  ProcessMCMC();
82 
83  // Save the adaptive MCMC
84  for (const auto &syst : systematics)
85  {
86  if (syst->GetDoAdaption())
87  {
88  auto adaptive_handler = syst->GetAdaptiveHandler();
89  adaptive_handler->SaveAdaptiveToFile(adaptive_handler->GetOutFileName(), syst->GetName(), true);
90  }
91  }
92 }
93 
94 // *******************
96 // *******************
100  DoStep();
102  PostStepProcess();
103 }
104 
105 // *******************
107 // *******************
108  stepClock->Start();
109  out_of_bounds = false;
110 
111  // Print 10 steps in total
112  if ((step - stepStart) % (chainLength / 10) == 0)
113  {
115  PrintProgress();
116  }
117 }
118 
119 // *************************
121 // *************************
122  //KS: Some version of ROOT keep spamming about accessing already deleted object which is wrong and not helpful...
123  int originalErrorLevel = gErrorIgnoreLevel;
124  gErrorIgnoreLevel = kFatal;
125 
126  stepClock->Stop();
127  stepTime = stepClock->RealTime();
128 
129  // Write step to output tree
130  outTree->Fill();
131 
132  // Do Adaptive MCMC
133  AdaptiveStep();
134 
135  if (step % auto_save == 0){
136  outTree->AutoSave();
137  }
138  gErrorIgnoreLevel = originalErrorLevel;
139 }
140 
141 // *******************
142 // Print the fit output progress
143 void MCMCBase::PrintProgress(bool StepsPrint) {
144 // *******************
145  if(StepsPrint) MACH3LOG_INFO("Step:\t{}/{}, current: {:.2f}, proposed: {:.2f}", step - stepStart, chainLength, logLCurr, logLProp);
146  if(StepsPrint) MACH3LOG_INFO("Accepted/Total steps: {}/{} = {:.2f}", accCount, step - stepStart, static_cast<double>(accCount) / static_cast<double>(step - stepStart));
147 
148  for (size_t i = 0; i < samples.size(); ++i) {
149  samples[i]->PrintRates();
150  }
151 
152  for (ParameterHandlerBase *cov : systematics) {
153  cov->PrintPreFitCurrPropValues();
154  }
155 #ifdef MACH3_DEBUG
156  if (debug)
157  {
158  debugFile << "\n-------------------------------------------------------" << std::endl;
159  debugFile << "Step:\t" << step + 1 << "/" << chainLength << " | current: " << logLCurr << " proposed: " << logLProp << std::endl;
160  }
161 #endif
162 }
163 
164 // *******************
165 // Handles warnings for low acceptance rates
167 // *******************
168  const auto StepEnd = stepStart + chainLength;
169 
170  // Skip check for reallllly early steps
171  if(step - stepStart < std::min(10.0, static_cast<double>(StepEnd)/10)) {
172  return;
173  }
174  // KS: Do not add "throw", this can crash CI or some short dummy chains for testing
175  if(accCount==0 && step - stepStart > StepEnd/10) {
176  MACH3LOG_CRITICAL("No steps were accepted in the MCMC chain after {} steps. Please check your step sizes.", step - stepStart);
177  }
178 
179  double acc_rate = static_cast<double>(accCount) / static_cast<double>(step - stepStart);
180 
181  if (acc_rate < 0.01) {
182  MACH3LOG_WARN("Acceptance rate is very low: {:.4f}. This may indicate that the proposal distribution is not well-tuned. Consider reducing the step size.", acc_rate);
183  } else if (acc_rate > 0.5) {
184  MACH3LOG_WARN("Acceptance rate is very high: {:.4f}. This may indicate that the proposal distribution is too narrow. Consider increasing the step sizes.", acc_rate);
185  }
186 }
187 
188 // *******************
189 void MCMCBase::StartFromPreviousFit(const std::string &FitName) {
190 // *******************
191  // Use base class
193 
194  // For MCMC we also need to set stepStart
195  TFile *infile = M3::Open(FitName, "READ", __FILE__, __LINE__);
196  TTree *posts = infile->Get<TTree>("posteriors");
197  unsigned int step_val = 0;
198 
199  posts->SetBranchAddress("step", &step_val);
200  posts->GetEntry(posts->GetEntries() - 1);
201 
202  stepStart = step_val;
203  // KS: Also update number of steps if using adaption
204  for (unsigned int i = 0; i < systematics.size(); ++i) {
205  if (systematics[i]->GetDoAdaption()) {
206  systematics[i]->SetNumberOfSteps(stepStart);
207  }
208  }
209  infile->Close();
210  delete infile;
211 }
212 
213 // *************************
215 // *************************
216  // Save the Adaptive output
217  for (const auto &syst : systematics)
218  {
219  if (syst->GetDoAdaption()){
220  syst->UpdateAdaptiveCovariance();
221  }
222  }
223 }
224 
225 // *************************
226 bool MCMCBase::IsStepAccepted(const double acc_prob) {
227 // *************************
228  // Get the random number
229  const double fRandom = M3::rand::Uniform();
230  // Do the accept/reject
231  #ifdef MACH3_DEBUG
232  debugFile << " logLProp: " << logLProp << " logLCurr: " << logLCurr << " acc_prob: " << acc_prob << " fRandom: " << fRandom << std::endl;
233  #endif
234 
235  if (fRandom > acc_prob)
236  {
237  // Reject
238  return false;
239  }
240  return true;
241 }
242 
243 // *************************
245 // *************************
246  ++accCount;
247  logLCurr = logLProp;
248 
249  // Loop over systematics and accept
250  for (size_t s = 0; s < systematics.size(); ++s)
251  {
252  systematics[s]->AcceptStep();
253  }
254 }
255 
256 // *************************
257 std::string MCMCBase::GetFancyName() const {
258 // *************************
259  auto originalName = GetName();
260  std::string OutName = "";
261  if(multicanonical){
262  OutName += "MultiCanonical_";
263  }
264 
265  for(unsigned int i = 0; i < systematics.size(); ++i){
266  if(systematics[i]->GetDoAdaption()){
267  if(systematics[i]->GetAdaptiveHandler()->GetUseRobbinsMonro()){
268  OutName += "RobbinsMonro_";
269  }
270  OutName += "Adaptive_";
271  break;
272  }
273  }
274 
275  OutName += originalName;
276  return OutName;
277 }
#define MACH3LOG_CRITICAL
Definition: MaCh3Logger.h:38
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
bool CheckNodeExists(const YAML::Node &node, Args... args)
KS: Wrapper function to call the recursive helper.
Definition: YamlHelper.h:59
Base class for implementing fitting algorithms.
Definition: FitterBase.h:29
std::string GetName() const
Get name of class.
Definition: FitterBase.h:75
double logLProp
proposed likelihood
Definition: FitterBase.h:127
void ProcessMCMC()
Process MCMC output.
Definition: FitterBase.cpp:408
int accCount
counts accepted steps
Definition: FitterBase.h:131
void SaveOutput()
Save output and close files.
Definition: FitterBase.cpp:233
void SaveSettings()
Save the settings that the MCMC was run with.
Definition: FitterBase.cpp:79
unsigned int step
current state
Definition: FitterBase.h:123
void PrepareOutput()
Prepare the output file.
Definition: FitterBase.cpp:155
virtual void StartFromPreviousFit(const std::string &FitName)
Allow to start from previous fit/chain.
Definition: FitterBase.cpp:350
std::vector< SampleHandlerInterface * > samples
Sample holder.
Definition: FitterBase.h:141
double stepTime
Time of single step.
Definition: FitterBase.h:153
Manager * fitMan
The manager for configuration handling.
Definition: FitterBase.h:120
unsigned int stepStart
step start, by default 0 if we start from previous chain then it will be different
Definition: FitterBase.h:133
std::unique_ptr< TStopwatch > stepClock
tells how long single step/fit iteration took
Definition: FitterBase.h:151
double logLCurr
current likelihood
Definition: FitterBase.h:125
int auto_save
auto save every N steps
Definition: FitterBase.h:164
TTree * outTree
Output tree with posteriors.
Definition: FitterBase.h:162
void SanitiseInputs()
Remove obsolete memory and make other checks before fit starts.
Definition: FitterBase.cpp:225
std::vector< ParameterHandlerBase * > systematics
Systematic holder.
Definition: FitterBase.h:146
std::unique_ptr< MulticanonicalMCMCHandler > multicanonicalHandler
multicanonical handler for umbrella sampling
Definition: MCMCBase.h:67
MCMCBase(Manager *const fitMan)
Constructor.
Definition: MCMCBase.cpp:6
void RunMCMC() final
Actual implementation of MCMC fitting algorithm.
Definition: MCMCBase.cpp:22
unsigned int chainLength
number of steps in chain
Definition: MCMCBase.h:76
void StartFromPreviousFit(const std::string &FitName) final
Allow to start from previous fit/chain.
Definition: MCMCBase.cpp:189
void AcceptStep()
Accept a step.
Definition: MCMCBase.cpp:244
std::string GetFancyName() const final
This name is to get include some special algorithm extensions.
Definition: MCMCBase.cpp:257
bool out_of_bounds
Do we reject based on hitting boundaries in systs.
Definition: MCMCBase.h:70
bool IsStepAccepted(const double acc_prob)
Is step accepted?
Definition: MCMCBase.cpp:226
void DoMCMCStep()
The full StartStep->DoStep->EndStep chain.
Definition: MCMCBase.cpp:95
void PreStepProcess()
Actions before step proposal [start stopwatch].
Definition: MCMCBase.cpp:106
bool multicanonical
multi-canonical method toggle on/off
Definition: MCMCBase.h:79
virtual void ProposeStep()=0
Propose a step.
void CheckAcceptanceRates()
Check the acceptance rates.
Definition: MCMCBase.cpp:166
void PrintProgress(const bool StepsPrint=true)
Print the progress.
Definition: MCMCBase.cpp:143
virtual void DoStep()=0
The MCMC step proposal and acceptance.
void PostStepProcess()
Actions after step proposal [end stopwatch, fill tree].
Definition: MCMCBase.cpp:120
void AdaptiveStep()
Adaptive MCMC step.
Definition: MCMCBase.cpp:214
Custom exception class used throughout MaCh3.
The manager class is responsible for managing configurations and settings.
Definition: Manager.h:17
YAML::Node const & raw() const
Return config.
Definition: Manager.h:48
Base class for handling systematic uncertainty parameters.
double Uniform(const double min=0.0, const double max=1.0)
Generate a uniform random number in [min, max).
Definition: Random.h:116