MaCh3  2.2.3
Reference Guide
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
MCMCBase Class Referenceabstract

Base class for MCMC fitting algorithms. More...

#include <Fitters/MCMCBase.h>

Inheritance diagram for MCMCBase:
[legend]
Collaboration diagram for MCMCBase:
[legend]

Public Member Functions

 MCMCBase (manager *const fitMan)
 Constructor. More...
 
virtual ~MCMCBase ()=default
 Destructor. More...
 
void RunMCMC () override
 Actual implementation of MCMC fitting algorithm. More...
 
void StartFromPreviousFit (const std::string &FitName) override
 Allow to start from previous fit/chain. More...
 
void setChainLength (unsigned int L)
 Set how long chain should be. More...
 
- Public Member Functions inherited from FitterBase
 FitterBase (manager *const fitMan)
 Constructor. More...
 
virtual ~FitterBase ()
 Destructor for the FitterBase class. More...
 
void AddSampleHandler (SampleHandlerBase *sample)
 This function adds a sample PDF object to the analysis framework. The sample PDF object will be utilized in fitting procedures or likelihood scans. More...
 
void AddSystObj (ParameterHandlerBase *cov)
 This function adds a Covariance object to the analysis framework. The Covariance object will be utilized in fitting procedures or likelihood scans. More...
 
void DragRace (const int NLaps=100)
 Calculates the required time for each sample or covariance object in a drag race simulation. Inspired by Dan's feature. More...
 
void RunLLHScan ()
 Perform a 1D likelihood scan. More...
 
void GetStepScaleBasedOnLLHScan ()
 LLH scan is good first estimate of step scale. More...
 
void Run2DLLHScan ()
 Perform a 2D likelihood scan. More...
 
void RunSigmaVar ()
 Perform a 2D and 1D sigma var for all samples. More...
 
void RunSigmaVarFD ()
 Perform a 1D sigma var for all samples. More...
 
std::string GetName () const
 Get name of class. More...
 

Protected Member Functions

void DoMCMCStep ()
 The full StartStep->DoStep->EndStep chain. More...
 
virtual void ProposeStep ()=0
 Propose a step. More...
 
void PreStepProcess ()
 Actions before step proposal [start stopwatch]. More...
 
void PostStepProcess ()
 Actions after step proposal [end stopwatch, fill tree]. More...
 
virtual void DoStep ()=0
 The MCMC step proposal and acceptance. More...
 
virtual double AcceptanceProbability ()=0
 Step acceptance probability. More...
 
bool IsStepAccepted (const double acc_prob)
 Is step accepted? More...
 
void AcceptStep ()
 Accept a step. More...
 
void AdaptiveStep ()
 Adaptive MCMC step. More...
 
void PrintProgress ()
 Print the progress. More...
 
- Protected Member Functions inherited from FitterBase
void ProcessMCMC ()
 Process MCMC output. More...
 
void PrepareOutput ()
 Prepare the output file. More...
 
void SaveOutput ()
 Save output and close files. More...
 
void SanitiseInputs ()
 Remove obsolete memory and make other checks before fit starts. More...
 
void SaveSettings ()
 Save the settings that the MCMC was run with. More...
 
bool GetScaneRange (std::map< std::string, std::vector< double >> &scanRanges)
 YSP: Set up a mapping to store parameters with user-specified ranges, suggested by D. Barrow. More...
 
bool CheckSkipParameter (const std::vector< std::string > &SkipVector, const std::string &ParamName) const
 KS: Check whether we want to skip parameter using skip vector. More...
 
void CustomRange (const std::string &ParName, const double sigma, double &ParamShiftValue)
 For comparison with P-Theta we usually have to apply different parameter values then usual 1, 3 sigma. More...
 

Protected Attributes

bool out_of_bounds
 Do we reject based on hitting boundaries in systs. More...
 
bool accept
 Accept. More...
 
unsigned int chainLength
 number of steps in chain More...
 
bool anneal
 simulated annealing More...
 
double AnnealTemp
 simulated annealing temperature More...
 
- Protected Attributes inherited from FitterBase
managerfitMan
 The manager. More...
 
unsigned int step
 current state More...
 
double logLCurr
 current likelihood More...
 
double logLProp
 proposed likelihood More...
 
double accProb
 current acceptance prob More...
 
int accCount
 counts accepted steps More...
 
unsigned int stepStart
 step start, by default 0 if we start from previous chain then it will be different More...
 
std::vector< double > sample_llh
 store the llh breakdowns More...
 
std::vector< double > syst_llh
 systematic llh breakdowns More...
 
std::vector< SampleHandlerBase * > samples
 Sample holder. More...
 
unsigned int TotalNSamples
 Total number of samples used. More...
 
std::vector< ParameterHandlerBase * > systematics
 Systematic holder. More...
 
std::unique_ptr< TStopwatch > clock
 tells global time how long fit took More...
 
std::unique_ptr< TStopwatch > stepClock
 tells how long single step/fit iteration took More...
 
double stepTime
 Time of single step. More...
 
std::unique_ptr< TRandom3 > random
 Random number. More...
 
TFile * outputFile
 Output. More...
 
TDirectory * CovFolder
 Output cov folder. More...
 
TDirectory * SampleFolder
 Output sample folder. More...
 
TTree * outTree
 Output tree with posteriors. More...
 
int auto_save
 auto save every N steps More...
 
bool fTestLikelihood
 Necessary for some fitting algorithms like PSO. More...
 
bool FileSaved
 Checks if file saved not repeat some operations. More...
 
bool SettingsSaved
 Checks if setting saved not repeat some operations. More...
 
bool OutputPrepared
 Checks if output prepared not repeat some operations. More...
 
std::string AlgorithmName
 Name of fitting algorithm that is being used. More...
 

Detailed Description

Base class for MCMC fitting algorithms.

Inherits from FitterBase and defines the interface for MCMC-based fitting, including chain management and step handling.

Author
Asher Kaboth

Definition at line 8 of file MCMCBase.h.

Constructor & Destructor Documentation

◆ MCMCBase()

MCMCBase::MCMCBase ( manager *const  fitMan)

Constructor.

Parameters
fitManA pointer to a manager object, which will handle all settings.

Definition at line 6 of file MCMCBase.cpp.

6  : FitterBase(man) {
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 
15  AnnealTemp = GetFromManager<double>(fitMan->raw()["General"]["MCMC"]["AnnealTemp"], -999);
16  if (AnnealTemp < 0)
17  anneal = false;
18  else
19  {
20  MACH3LOG_INFO("Enabling simulated annealing with T = {}", AnnealTemp);
21  anneal = true;
22  }
23 }
MaCh3Plotting::PlottingManager * man
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:25
manager * fitMan
The manager.
Definition: FitterBase.h:110
unsigned int stepStart
step start, by default 0 if we start from previous chain then it will be different
Definition: FitterBase.h:123
FitterBase(manager *const fitMan)
Constructor.
Definition: FitterBase.cpp:16
bool anneal
simulated annealing
Definition: MCMCBase.h:70
unsigned int chainLength
number of steps in chain
Definition: MCMCBase.h:67
double AnnealTemp
simulated annealing temperature
Definition: MCMCBase.h:72
bool out_of_bounds
Do we reject based on hitting boundaries in systs.
Definition: MCMCBase.h:61
YAML::Node const & raw()
Return config.
Definition: Manager.h:41

◆ ~MCMCBase()

virtual MCMCBase::~MCMCBase ( )
virtualdefault

Destructor.

Member Function Documentation

◆ AcceptanceProbability()

virtual double MCMCBase::AcceptanceProbability ( )
protectedpure virtual

Step acceptance probability.

Implemented in MR2T2, and DelayedMR2T2.

◆ AcceptStep()

void MCMCBase::AcceptStep ( )
protected

Accept a step.

Definition at line 178 of file MCMCBase.cpp.

178  {
179 // *************************
180  ++accCount;
181  logLCurr = logLProp;
182 
183  // Loop over systematics and accept
184  for (size_t s = 0; s < systematics.size(); ++s)
185  {
186  systematics[s]->AcceptStep();
187  }
188 }
double logLProp
proposed likelihood
Definition: FitterBase.h:117
int accCount
counts accepted steps
Definition: FitterBase.h:121
double logLCurr
current likelihood
Definition: FitterBase.h:115
std::vector< ParameterHandlerBase * > systematics
Systematic holder.
Definition: FitterBase.h:136

◆ AdaptiveStep()

void MCMCBase::AdaptiveStep ( )
inlineprotected

Adaptive MCMC step.

Definition at line 148 of file MCMCBase.cpp.

148  {
149 // *************************
150  // Save the Adaptive output
151  for (const auto &syst : systematics)
152  {
153  if (syst->GetDoAdaption()){
154  syst->UpdateAdaptiveCovariance();
155  }
156  }
157 }

◆ DoMCMCStep()

void MCMCBase::DoMCMCStep ( )
inlineprotected

The full StartStep->DoStep->EndStep chain.

Starts step timer, prints progress

Step proposal, acceptance etc

Tree filling etc.

Definition at line 60 of file MCMCBase.cpp.

60  {
61 // *******************
65  DoStep();
68 }
void PreStepProcess()
Actions before step proposal [start stopwatch].
Definition: MCMCBase.cpp:71
virtual void DoStep()=0
The MCMC step proposal and acceptance.
void PostStepProcess()
Actions after step proposal [end stopwatch, fill tree].
Definition: MCMCBase.cpp:84

◆ DoStep()

virtual void MCMCBase::DoStep ( )
protectedpure virtual

The MCMC step proposal and acceptance.

Implemented in MR2T2, and DelayedMR2T2.

◆ IsStepAccepted()

bool MCMCBase::IsStepAccepted ( const double  acc_prob)
protected

Is step accepted?

Parameters
acc_probused for telling whether step is accepted or not

Definition at line 160 of file MCMCBase.cpp.

160  {
161 // *************************
162  // Get the random number
163  const double fRandom = random->Rndm();
164  // Do the accept/reject
165  #ifdef DEBUG
166  debugFile << " logLProp: " << logLProp << " logLCurr: " << logLCurr << " acc_prob: " << acc_prob << " fRandom: " << fRandom << std::endl;
167  #endif
168 
169  if (fRandom > acc_prob)
170  {
171  // Reject
172  return false;
173  }
174  return true;
175 }
std::unique_ptr< TRandom3 > random
Random number.
Definition: FitterBase.h:146

◆ PostStepProcess()

void MCMCBase::PostStepProcess ( )
inlineprotected

Actions after step proposal [end stopwatch, fill tree].

Definition at line 84 of file MCMCBase.cpp.

84  {
85 // *************************
86  stepClock->Stop();
87  stepTime = stepClock->RealTime();
88 
89  // Write step to output tree
90  outTree->Fill();
91 
92  // Do Adaptive MCMC
93  AdaptiveStep();
94 
95  if (step % auto_save == 0){
96  outTree->AutoSave();
97  }
98 }
unsigned int step
current state
Definition: FitterBase.h:113
double stepTime
Time of single step.
Definition: FitterBase.h:143
std::unique_ptr< TStopwatch > stepClock
tells how long single step/fit iteration took
Definition: FitterBase.h:141
int auto_save
auto save every N steps
Definition: FitterBase.h:157
TTree * outTree
Output tree with posteriors.
Definition: FitterBase.h:155
void AdaptiveStep()
Adaptive MCMC step.
Definition: MCMCBase.cpp:148

◆ PreStepProcess()

void MCMCBase::PreStepProcess ( )
inlineprotected

Actions before step proposal [start stopwatch].

Definition at line 71 of file MCMCBase.cpp.

71  {
72 // *******************
73  stepClock->Start();
74  out_of_bounds = false;
75 
76  // Print 10 steps in total
77  if ((step - stepStart) % (chainLength / 10) == 0)
78  {
79  PrintProgress();
80  }
81 }
void PrintProgress()
Print the progress.
Definition: MCMCBase.cpp:102

◆ PrintProgress()

void MCMCBase::PrintProgress ( )
inlineprotected

Print the progress.

Definition at line 102 of file MCMCBase.cpp.

102  {
103 // *******************
104  MACH3LOG_INFO("Step:\t{}/{}, current: {:.2f}, proposed: {:.2f}", step - stepStart, chainLength, logLCurr, logLProp);
105  MACH3LOG_INFO("Accepted/Total steps: {}/{} = {:.2f}", accCount, step - stepStart, static_cast<double>(accCount) / static_cast<double>(step - stepStart));
106 
107  for (ParameterHandlerBase *cov : systematics)
108  {
109  cov->PrintNominalCurrProp();
110  }
111 #ifdef DEBUG
112  if (debug)
113  {
114  debugFile << "\n-------------------------------------------------------" << std::endl;
115  debugFile << "Step:\t" << step + 1 << "/" << chainLength << " | current: " << logLCurr << " proposed: " << logLProp << std::endl;
116  }
117 #endif
118 }
Base class responsible for handling of systematic error parameters. Capable of using PCA or using ada...

◆ ProposeStep()

virtual void MCMCBase::ProposeStep ( )
protectedpure virtual

Propose a step.

Implemented in MR2T2.

◆ RunMCMC()

void MCMCBase::RunMCMC ( )
overridevirtual

Actual implementation of MCMC fitting algorithm.

Implements FitterBase.

Definition at line 28 of file MCMCBase.cpp.

28  {
29 // *******************
30  // Save the settings into the output file
31  SaveSettings();
32 
33  // Prepare the output branches
34  PrepareOutput();
35 
36  // Remove obsolete memory and make other checks before fit starts
38 
39  // Reconfigure the samples, systematics and oscillation for first weight
40  // ProposeStep sets logLProp
41  ProposeStep();
42  // Set the current logL to the proposed logL for the 0th step
43  // Accept the first step to set logLCurr: this shouldn't affect the MCMC because we ignore the first N steps in burn-in
45 
46  // Begin MCMC
47  const auto StepEnd = stepStart + chainLength;
48  for (step = stepStart; step < StepEnd; ++step)
49  {
50  DoMCMCStep();
51  }
52  // Save all the MCMC output
53  SaveOutput();
54 
55  // Process MCMC
56  ProcessMCMC();
57 }
void ProcessMCMC()
Process MCMC output.
Definition: FitterBase.cpp:371
void SaveOutput()
Save output and close files.
Definition: FitterBase.cpp:230
void SaveSettings()
Save the settings that the MCMC was run with.
Definition: FitterBase.cpp:84
void PrepareOutput()
Prepare the output file.
Definition: FitterBase.cpp:155
void SanitiseInputs()
Remove obsolete memory and make other checks before fit starts.
Definition: FitterBase.cpp:222
void DoMCMCStep()
The full StartStep->DoStep->EndStep chain.
Definition: MCMCBase.cpp:60
virtual void ProposeStep()=0
Propose a step.

◆ setChainLength()

void MCMCBase::setChainLength ( unsigned int  L)
inline

Set how long chain should be.

Parameters
Lnew chain length

Definition at line 27 of file MCMCBase.h.

27 { chainLength = L; };

◆ StartFromPreviousFit()

void MCMCBase::StartFromPreviousFit ( const std::string &  FitName)
overridevirtual

Allow to start from previous fit/chain.

Parameters
FitNameName of previous chain
Todo:
implement some check that number of params matches etc

Reimplemented from FitterBase.

Definition at line 121 of file MCMCBase.cpp.

121  {
122 // *******************
123  // Use base class
125 
126  // For MCMC we also need to set stepStart
127  TFile *infile = new TFile(FitName.c_str(), "READ");
128  TTree *posts = infile->Get<TTree>("posteriors");
129  unsigned int step_val = 0;
130 
131  posts->SetBranchAddress("step", &step_val);
132  posts->GetEntry(posts->GetEntries() - 1);
133 
134  stepStart = step_val;
135  // KS: Also update number of steps if using adaption
136  for (unsigned int i = 0; i < systematics.size(); ++i)
137  {
138  if (systematics[i]->GetDoAdaption())
139  {
140  systematics[i]->SetNumberOfSteps(step_val);
141  }
142  }
143  infile->Close();
144  delete infile;
145 }
virtual void StartFromPreviousFit(const std::string &FitName)
Allow to start from previous fit/chain.
Definition: FitterBase.cpp:304

Member Data Documentation

◆ accept

bool MCMCBase::accept
protected

Accept.

Definition at line 64 of file MCMCBase.h.

◆ anneal

bool MCMCBase::anneal
protected

simulated annealing

Definition at line 70 of file MCMCBase.h.

◆ AnnealTemp

double MCMCBase::AnnealTemp
protected

simulated annealing temperature

Definition at line 72 of file MCMCBase.h.

◆ chainLength

unsigned int MCMCBase::chainLength
protected

number of steps in chain

Definition at line 67 of file MCMCBase.h.

◆ out_of_bounds

bool MCMCBase::out_of_bounds
protected

Do we reject based on hitting boundaries in systs.

Definition at line 61 of file MCMCBase.h.


The documentation for this class was generated from the following files: