MaCh3  2.6.0
Reference Guide
Public Member Functions | Protected Member Functions | Protected Attributes | List of all members
DelayedMR2T2 Class Reference

Implementation of delayed rejection for MR2T2. More...

#include <Fitters/DelayedMR2T2.h>

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

Public Member Functions

 DelayedMR2T2 (Manager *const fitMan)
 Constructor. More...
 
virtual ~DelayedMR2T2 ()=default
 Destructor. More...
 
- Public Member Functions inherited from MR2T2
 MR2T2 (Manager *const FitManager)
 Constructor. More...
 
virtual ~MR2T2 ()=default
 Destructor. More...
 
- Public Member Functions inherited from MCMCBase
 MCMCBase (Manager *const fitMan)
 Constructor. More...
 
virtual ~MCMCBase ()=default
 Destructor. More...
 
void RunMCMC () final
 Actual implementation of MCMC fitting algorithm. More...
 
void StartFromPreviousFit (const std::string &FitName) final
 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 (SampleHandlerInterface *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 RunLLHMap ()
 Perform a general multi-dimensional likelihood scan. More...
 
void GetStepScaleBasedOnLLHScan (const std::string &filename="")
 LLH scan is good first estimate of step scale. More...
 
void Run2DLLHScan ()
 Perform a 2D likelihood scan. More...
 
void RunSigmaVar ()
 Perform a 1D/2D sigma var for all samples. More...
 
std::string GetName () const
 Get name of class. More...
 

Protected Member Functions

double AcceptanceProbability () final
 Step acceptance probability. More...
 
void DoStep () final
 The MCMC step proposal. More...
 
void StoreCurrentStep ()
 Store information about the current proposed step. More...
 
void PrepareOutput ()
 override to add in rejection information to output More...
 
void ResetSystScale ()
 Reset scale after delay process. More...
 
void ScaleSystematics (const double scale)
 Set parameter scale to be original_scale* scale. More...
 
bool ProbabilisticDelay () const
 if delay has a chance of occurring More...
 
- Protected Member Functions inherited from MR2T2
void DoStep () override
 The MCMC step proposal and acceptance. More...
 
void ProposeStep () final
 Propose a step. More...
 
double AcceptanceProbability () override
 Step acceptance probability. More...
 
- Protected Member Functions inherited from MCMCBase
void DoMCMCStep ()
 The full StartStep->DoStep->EndStep chain. More...
 
void PreStepProcess ()
 Actions before step proposal [start stopwatch]. More...
 
void PostStepProcess ()
 Actions after step proposal [end stopwatch, fill tree]. 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 (const bool StepsPrint=true)
 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 GetScanRange (std::map< std::string, std::vector< double >> &scanRanges) const
 YSP: Set up a mapping to store parameters with user-specified ranges, suggested by D. Barrow. More...
 
void GetParameterScanRange (const ParameterHandlerBase *cov, const int i, double &CentralValue, double &lower, double &upper, const int n_points, const std::string &suffix="") const
 Helper function to get parameter scan range, central value. 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) const
 For comparison with other fitting frameworks (like P-Theta) we usually have to apply different parameter values then usual 1, 3 sigma. More...
 

Protected Attributes

std::vector< std::vector< double > > current_step_vals
 Store information about the current proposed step. More...
 
std::vector< double > start_step_scale
 Stores the initial scale for all parameters. More...
 
double initial_scale
 Scale for (non-delayed) step is initial_scale * start_step_scale. More...
 
double decay_rate
 How much to decrease the step scale each step. More...
 
int max_rejections
 How many rejections allowed? More...
 
double MinLogLikelihood
 Minimum (negative) log-likelihood of proposed steps. More...
 
bool accepted_delayed
 Was the step we just accepted delayed? More...
 
bool delay_on_oob_only
 Delay only if we go out of bounds. More...
 
double delay_probability
 Can delay with probability instead. More...
 
- Protected Attributes inherited from MCMCBase
std::unique_ptr< MulticanonicalMCMCHandlermulticanonicalHandler
 multicanonical handler for umbrella sampling
More...
 
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...
 
bool multicanonical
 multi-canonical method toggle on/off More...
 
- Protected Attributes inherited from FitterBase
ManagerfitMan
 The manager for configuration handling. 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< SampleHandlerInterface * > samples
 Sample holder. More...
 
unsigned int TotalNSamples
 Total number of samples used, single SampleHandler can store more than one analysis sample! 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

Implementation of delayed rejection for MR2T2.

Author
Henry Wallace [16]

Quick Introduction

Delayed rejection is a method to increase the efficiency of MCMC. It is useful if your chain is not mixing well or if adaptive MCMC is struggling. The idea is to propose increasingly small steps centered on the last rejected step.

Configuration

To enable delayed rejection, add the following to your config.yaml file:

Delayed MCMC will work "as is" but there are additional options which are set in General::MCMC

Scaling Options

Parameters
DecayRateThis should be less than 1 and tells your algorithm how quickly to decrease the step size. By default this is 0.1
MaxRejectionsHow many steps to delayed-reject before moving on. By default this is 1 and increasing is not recommended
InitialScaleThe initial scale of your proposed steps. I.e. propose step with InitialScale*scale in parameter handler. This allows for a really large/small first step to be proposed. Testing finds the default value of 1 to be most effective with adaptive MCMC

Delay Triggers

Parameters
DelayOnlyOutBoundsHere delaying only happens if a step is thrown out of bounds
DelayProbabilityIn order to mitigate the slowness of delayed MCMC, there is a probability of proposing a delayed step. By default this is 1
Note
Delayed rejection MCMC can significantly improve chain mixing but may increase computational overhead per step.

Definition at line 44 of file DelayedMR2T2.h.

Constructor & Destructor Documentation

◆ DelayedMR2T2()

DelayedMR2T2::DelayedMR2T2 ( Manager *const  fitMan)

Constructor.

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

Definition at line 4 of file DelayedMR2T2.cpp.

4  : MR2T2(FitManager) {
5 // *************************
6  AlgorithmName = "DelayedMR2T2";
7  auto Config = fitMan->raw();
8  // Step scale for delayed step = step scale prev delay * decay_rate
9  decay_rate = GetFromManager<double>(Config["General"]["MCMC"]["DecayRate"], 0.1, __FILE__, __LINE__);
10  // Maximum number of rejections
11  max_rejections = GetFromManager<int>(Config["General"]["MCMC"]["MaxRejections"], 1, __FILE__, __LINE__);
12  // How big is the first step scale. This scales parameter step by initial_scale * <step scale in ParameterHandler>
13  initial_scale = GetFromManager<int>(Config["General"]["MCMC"]["InitialScale"], 1, __FILE__, __LINE__);
14  // On delayed on out of bounds steps. This saves some compute time and possibly regains efficiency
15  delay_on_oob_only = GetFromManager<bool>(Config["General"]["MCMC"]["DelayOnlyOutBounds"], false, __FILE__, __LINE__);
16  // Allow to intrude another delayed rejection based on defined here probability
17  delay_probability = GetFromManager<double>(Config["General"]["MCMC"]["DelayProbability"], 1.0, __FILE__, __LINE__);
18 
19  if(delay_probability > 1.0){
20  MACH3LOG_WARN("Probability of delaying steps > 1, setting to 1");
21  delay_probability = 1.0;
22  }
23  if(delay_probability <= 0.0){
24  MACH3LOG_CRITICAL("Probability of delaying steps <= 0, setting to 0, delay will no longer have an impact!");
25  delay_probability = 0.0;
26  // Since we're not delaying at all set max_rejections = 0 to save time
27  max_rejections = 0;
28  }
29  MACH3LOG_INFO("Using Delayed MCMC with decay rate: {} and {} allowed rejections", decay_rate, max_rejections);
30 }
#define MACH3LOG_CRITICAL
Definition: MaCh3Logger.h:38
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
int max_rejections
How many rejections allowed?
Definition: DelayedMR2T2.h:87
double delay_probability
Can delay with probability instead.
Definition: DelayedMR2T2.h:98
bool delay_on_oob_only
Delay only if we go out of bounds.
Definition: DelayedMR2T2.h:96
double decay_rate
How much to decrease the step scale each step.
Definition: DelayedMR2T2.h:85
double initial_scale
Scale for (non-delayed) step is initial_scale * start_step_scale.
Definition: DelayedMR2T2.h:83
std::string AlgorithmName
Name of fitting algorithm that is being used.
Definition: FitterBase.h:173
Manager * fitMan
The manager for configuration handling.
Definition: FitterBase.h:113
MR2T2(Manager *const FitManager)
Constructor.
Definition: MR2T2.cpp:5
YAML::Node const & raw() const
Return config.
Definition: Manager.h:47

◆ ~DelayedMR2T2()

virtual DelayedMR2T2::~DelayedMR2T2 ( )
virtualdefault

Destructor.

Member Function Documentation

◆ AcceptanceProbability()

double DelayedMR2T2::AcceptanceProbability ( )
finalprotectedvirtual

Step acceptance probability.

Implements MCMCBase.

Definition at line 85 of file DelayedMR2T2.cpp.

85  {
86 // *************************
87  // From https://arxiv.org/pdf/2010.04190 and DRAM Matlab implementation
88  const double numerator = std::max(0.0, std::exp(MinLogLikelihood - logLProp) - 1.0);
89  const double denominator = std::exp(MinLogLikelihood - logLCurr) - 1.0;
90  if (denominator <= 0.0) return 1.0;
91 
92  // Large enough that the the minus 1 will make NO difference so the max term cancels
93  if(std::isinf(numerator) || std::isinf(denominator) ){
95  }
96 
97  return std::min(numerator / denominator, 1.0);
98 }
double MinLogLikelihood
Minimum (negative) log-likelihood of proposed steps.
Definition: DelayedMR2T2.h:90
double logLProp
proposed likelihood
Definition: FitterBase.h:120
double logLCurr
current likelihood
Definition: FitterBase.h:118
double AcceptanceProbability() override
Step acceptance probability.
Definition: MR2T2.cpp:126

◆ DoStep()

void DelayedMR2T2::DoStep ( )
finalprotectedvirtual

The MCMC step proposal.

OOB Check

Probabilistic condition

Implements MCMCBase.

Definition at line 101 of file DelayedMR2T2.cpp.

101  {
102 // *************************
103  // Set the initial rejection to false
105 
106  // Apply initial scale
108 
109  bool accepted = false;
110  bool delay = false;
111  accepted_delayed = false;
112 
114 
115  for(int i = 0; i<= max_rejections; ++i)
116  {
117  ProposeStep();
118 
119  // Small hack to ensure we can "leapfrog"
120  for (auto &syst : systematics)
121  {
122  syst->AcceptStep();
123  }
124 
126  continue;
127  }
128 
129  if(i == 0){
131  }
132  else{
134  delay = true;
135  }
136  if(IsStepAccepted(accProb)){
137  AcceptStep();
138  accepted = true;
139 
140  // Keep track of if step is delayed + accepted for storage
141  accepted_delayed = delay;
142 
143  // Update
144  break;
145  }
148  // If we are not out of bounds and only delaying on out of bounds steps
149  // We can skip the delay
150  break;
151  }
152 
154  if (!ProbabilisticDelay()) {
155  break;
156  }
157 
158 
159  // Temporary, means we can "leapfrog"
162  }
163 
164  // If we reject we need to reset everything [this is probably a tad too slow...
165  // especially in PCA...
166  if(!accepted){
167  for(int i=0; i<static_cast<int>(systematics.size()); ++i){
168  for(int j=0; j<static_cast<int>(systematics[i]->GetParCurrVec().size()); ++j){
169  systematics[i]->SetParCurrProp(j, current_step_vals[i][j]);
170  }
171  }
172  }
173  ResetSystScale();
174 }
bool accepted_delayed
Was the step we just accepted delayed?
Definition: DelayedMR2T2.h:93
bool ProbabilisticDelay() const
if delay has a chance of occurring
void StoreCurrentStep()
Store information about the current proposed step.
void ResetSystScale()
Reset scale after delay process.
double AcceptanceProbability() final
Step acceptance probability.
void ScaleSystematics(const double scale)
Set parameter scale to be original_scale* scale.
std::vector< std::vector< double > > current_step_vals
Store information about the current proposed step.
Definition: DelayedMR2T2.h:77
double accProb
current acceptance prob
Definition: FitterBase.h:122
std::vector< ParameterHandlerBase * > systematics
Systematic holder.
Definition: FitterBase.h:139
void AcceptStep()
Accept a step.
Definition: MCMCBase.cpp:226
bool out_of_bounds
Do we reject based on hitting boundaries in systs.
Definition: MCMCBase.h:64
bool IsStepAccepted(const double acc_prob)
Is step accepted?
Definition: MCMCBase.cpp:208
void ProposeStep() final
Propose a step.
Definition: MR2T2.cpp:25
constexpr static const double _LARGE_LOGL_
Large Likelihood is used it parameter go out of physical boundary, this indicates in MCMC that such s...
Definition: Core.h:80

◆ PrepareOutput()

void DelayedMR2T2::PrepareOutput ( )
protected

override to add in rejection information to output

Definition at line 51 of file DelayedMR2T2.cpp.

51  {
52 // *************************
54 
55  for(size_t i = 0; i < systematics.size(); ++i){
56  if(systematics[i]->GetDoAdaption()){
57  if(systematics[i]->GetAdaptiveHandler()->GetUseRobbinsMonro()){
58  MACH3LOG_ERROR("Right now Robbins-Monro doesn't work with Delayed MCMC");
59  MACH3LOG_ERROR("Usual adaptive works fine though");
60  MACH3LOG_ERROR("Ask Dr Wallace for details");
61  throw MaCh3Exception(__FILE__ , __LINE__ );
62  }
63  }
64  }
65  // Store delayed specific settings
66  outTree->Branch("DelayedStep", &accepted_delayed, "DelayedStep/B");
67 }
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
void PrepareOutput()
Prepare the output file.
Definition: FitterBase.cpp:151
TTree * outTree
Output tree with posteriors.
Definition: FitterBase.h:158
Custom exception class used throughout MaCh3.

◆ ProbabilisticDelay()

bool DelayedMR2T2::ProbabilisticDelay ( ) const
protected

if delay has a chance of occurring

Definition at line 177 of file DelayedMR2T2.cpp.

177  {
178 // *************************
179  // We can delay probabilistically
180  return (random->Rndm() > delay_probability);
181 }
std::unique_ptr< TRandom3 > random
Random number.
Definition: FitterBase.h:149

◆ ResetSystScale()

void DelayedMR2T2::ResetSystScale ( )
protected

Reset scale after delay process.

Definition at line 42 of file DelayedMR2T2.cpp.

42  {
43 // *************************
44  for (int i = 0; i < static_cast<int>(systematics.size()); ++i)
45  {
46  systematics[i]->SetStepScale(start_step_scale[i], false);
47  }
48 }
std::vector< double > start_step_scale
Stores the initial scale for all parameters.
Definition: DelayedMR2T2.h:80

◆ ScaleSystematics()

void DelayedMR2T2::ScaleSystematics ( const double  scale)
protected

Set parameter scale to be original_scale* scale.

Parameters
scaleMultiplicative scale factor

Definition at line 33 of file DelayedMR2T2.cpp.

33  {
34 // *************************
35  for (auto &syst : systematics)
36  {
37  syst->SetStepScale(scale*syst->GetGlobalStepScale(), false);
38  }
39 }

◆ StoreCurrentStep()

void DelayedMR2T2::StoreCurrentStep ( )
protected

Store information about the current proposed step.

Definition at line 70 of file DelayedMR2T2.cpp.

70  {
71 // *********************************************
72  // Stores values from step
73  // Ensure vector is correctly sized
74  current_step_vals.resize(systematics.size());
75  start_step_scale.resize(systematics.size());
76 
77  // Fill with old proposed step, need to copy to avoid using the same step twice
78  for(int i=0; i<static_cast<int>(systematics.size()); ++i){
79  current_step_vals[i] = std::vector<double>(systematics[i]->GetParCurrVec());
80  start_step_scale[i] = systematics[i]->GetGlobalStepScale();
81  }
82 }

Member Data Documentation

◆ accepted_delayed

bool DelayedMR2T2::accepted_delayed
protected

Was the step we just accepted delayed?

Definition at line 93 of file DelayedMR2T2.h.

◆ current_step_vals

std::vector<std::vector<double> > DelayedMR2T2::current_step_vals
protected

Store information about the current proposed step.

Definition at line 77 of file DelayedMR2T2.h.

◆ decay_rate

double DelayedMR2T2::decay_rate
protected

How much to decrease the step scale each step.

Definition at line 85 of file DelayedMR2T2.h.

◆ delay_on_oob_only

bool DelayedMR2T2::delay_on_oob_only
protected

Delay only if we go out of bounds.

Definition at line 96 of file DelayedMR2T2.h.

◆ delay_probability

double DelayedMR2T2::delay_probability
protected

Can delay with probability instead.

Definition at line 98 of file DelayedMR2T2.h.

◆ initial_scale

double DelayedMR2T2::initial_scale
protected

Scale for (non-delayed) step is initial_scale * start_step_scale.

Definition at line 83 of file DelayedMR2T2.h.

◆ max_rejections

int DelayedMR2T2::max_rejections
protected

How many rejections allowed?

Definition at line 87 of file DelayedMR2T2.h.

◆ MinLogLikelihood

double DelayedMR2T2::MinLogLikelihood
protected

Minimum (negative) log-likelihood of proposed steps.

Definition at line 90 of file DelayedMR2T2.h.

◆ start_step_scale

std::vector<double> DelayedMR2T2::start_step_scale
protected

Stores the initial scale for all parameters.

Definition at line 80 of file DelayedMR2T2.h.


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