MaCh3  2.8.0
Reference Guide
Public Member Functions | Private Attributes | List of all members
MinuitFit Class Reference

Implementation of Minuit fitting algorithm [22]. More...

#include <Fitters/Algorithms/MinuitFit.h>

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

Public Member Functions

 MinuitFit (Manager *const fitMan)
 Constructor. More...
 
virtual ~MinuitFit ()
 Destructor. More...
 
void RunMCMC () final
 Actual implementation of Minuit Fit algorithm. More...
 
- Public Member Functions inherited from LikelihoodFit
 LikelihoodFit (Manager *const fitMan)
 Constructor. More...
 
virtual ~LikelihoodFit ()
 Destructor. More...
 
virtual double CalcChi2 (const double *x)
 Chi2 calculation over all included samples and syst objects. More...
 
int GetNPars () const
 Get total number of params, this sums over all covariance objects. 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...
 
virtual void StartFromPreviousFit (const std::string &FitName)
 Allow to start from previous fit/chain. More...
 
std::string GetName () const
 Get name of class. More...
 
virtual std::string GetFancyName () const
 This name is to get include some special algorithm extensions. More...
 

Private Attributes

std::unique_ptr< ROOT::Math::Minimizer > minuit
 Pointer to minimizer, which most often is Minuit. More...
 

Additional Inherited Members

- Protected Member Functions inherited from LikelihoodFit
void PrepareFit ()
 prepare output and perform sanity checks 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...
 
std::vector< double > CalculateBinEdges (double lowerlimit, double upperlimit, int n_points) const
 
- Protected Attributes inherited from LikelihoodFit
int NPars
 Number of all parameters from all covariances. More...
 
int NParsPCA
 Number of all parameters from all covariances in PCA base. More...
 
bool fMirroring
 Flag telling if mirroring is used or not. More...
 
- Protected Attributes inherited from FitterBase
Manager * fitMan
 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...
 
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 Minuit fitting algorithm [22].

Author
Kamil Skwarczynski

Definition at line 18 of file MinuitFit.h.

Constructor & Destructor Documentation

◆ MinuitFit()

MinuitFit::MinuitFit ( Manager *const  fitMan)

Constructor.

Todo:
KS: Make this in future configurable, for more see: https://root.cern.ch/doc/master/classROOT_1_1Math_1_1Minimizer.html

Definition at line 5 of file MinuitFit.cpp.

5  : LikelihoodFit(man) {
6 // *******************
7  AlgorithmName = "MinuitFit";
9  // Minimizer type: determines the underlying implementation.
10  // Available types include:
11  // - "Minuit2" (recommended modern option)
12  // - "Minuit" (legacy)
13  // - "Fumili"
14  // - "GSLMultiMin" (for gradient-free minimization)
15  // - "GSLMultiFit"
16  // - "GSLSimAn" (Simulated Annealing)
17  const std::string MinimizerType = "Minuit2";
18  // Minimizer algorithm (specific to the selected type).
19  // For Minuit2, the following algorithms are available:
20  // - "Migrad" : gradient-based minimization (default)
21  // - "Simplex" : Nelder-Mead simplex method (derivative-free)
22  // - "Combined" : combination of Simplex and Migrad
23  // - "Scan" : parameter grid scan
24  const std::string MinimizerAlgo = "Migrad";
25 
26  MACH3LOG_INFO("Creating instance of Minimizer with {} and {}", MinimizerType, MinimizerAlgo);
27 
28  minuit = std::unique_ptr<ROOT::Math::Minimizer>(
29  ROOT::Math::Factory::CreateMinimizer(MinimizerType.c_str(), MinimizerAlgo.c_str()));
30 
31  std::string Features = gROOT->GetConfigFeatures();
32  if (Features.find("minuit2_omp") != std::string::npos) {
33  MACH3LOG_ERROR("Minuit in ROOT has been compiled with OMP support");
34  MACH3LOG_ERROR("Since MaCh3 uses OMP for reweight this could cause terrible clash");
35  throw MaCh3Exception(__FILE__ , __LINE__ );
36  }
37 }
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
std::string AlgorithmName
Name of fitting algorithm that is being used.
Definition: FitterBase.h:177
LikelihoodFit(Manager *const fitMan)
Constructor.
Custom exception class used throughout MaCh3.
std::unique_ptr< ROOT::Math::Minimizer > minuit
Pointer to minimizer, which most often is Minuit.
Definition: MinuitFit.h:29

◆ ~MinuitFit()

MinuitFit::~MinuitFit ( )
virtual

Destructor.

Definition at line 41 of file MinuitFit.cpp.

41  {
42 // *************************
43 }

Member Function Documentation

◆ RunMCMC()

void MinuitFit::RunMCMC ( )
finalvirtual

Actual implementation of Minuit Fit algorithm.

Implements FitterBase.

Definition at line 47 of file MinuitFit.cpp.

47  {
48 // *******************
49  PrepareFit();
50 
51  // Remove obsolete memory and make other checks before fit starts
53 
54  //KS: For none PCA this will be equal to normal parameters
55  const int NparsMinuitFull = NPars;
56  const int NparsMinuit = NParsPCA;
57 
58  //KS: Set SetFunction we will Minimize
59  ROOT::Math::Functor fChi2(this, &MinuitFit::CalcChi2, NparsMinuit);
60  minuit->SetFunction(fChi2);
61 
62  //KS: add config or something
63  minuit->SetPrintLevel(2);
64  minuit->SetTolerance(0.01);
65  minuit->SetMaxFunctionCalls(Get<unsigned>(fitMan->raw()["General"]["Minuit2"]["NSteps"], __FILE__, __LINE__));
66  minuit->SetMaxIterations(10000);
67 
68  // Save the adaptive MCMC
69  for (const auto &syst : systematics)
70  {
71  if (syst->GetDoAdaption())
72  {
73  MACH3LOG_ERROR("Param Handler {} has enabled Adaption, this is not needed for Minuit so please turn it off", syst->GetDoAdaption());
74  throw MaCh3Exception(__FILE__ , __LINE__ );
75  }
76  }
77 
78  MACH3LOG_INFO("Preparing Minuit");
79  int ParCounter = 0;
80  for (std::vector<ParameterHandlerBase*>::iterator it = systematics.begin(); it != systematics.end(); ++it)
81  {
82  if(!(*it)->IsPCA())
83  {
84  for(int i = 0; i < (*it)->GetNumParams(); ++i, ++ParCounter)
85  {
86  // KS: Index, name, prior, step scale [different to MCMC],
87  // divide by 10 because this is what BANFF used to do...
88  minuit->SetVariable(ParCounter, ((*it)->GetParName(i)), (*it)->GetParPreFit(i), (*it)->GetDiagonalError(i)/10);
89  minuit->SetVariableValue(ParCounter, (*it)->GetParPreFit(i));
90  //KS: lower bound, upper bound, if Mirroring enabled then ignore
91  if(!fMirroring) minuit->SetVariableLimits(ParCounter, (*it)->GetLowerBound(i), (*it)->GetUpperBound(i));
92  if((*it)->IsParameterFixed(i))
93  {
94  minuit->FixVariable(ParCounter);
95  }
96  }
97  }
98  else
99  {
100  for(int i = 0; i < (*it)->GetNParameters(); ++i, ++ParCounter)
101  {
102  // KS: Index, name, prior, step scale [different to MCMC],
103  // divide by 10 because this is what BANFF used to do...
104  minuit->SetVariable(ParCounter, Form("%i_PCA", i), (*it)->GetPCAHandler()->GetParPropPCA(i), (*it)->GetPCAHandler()->GetEigenValuesMaster()[i]/10);
105  if((*it)->GetPCAHandler()->IsParameterFixedPCA(i))
106  {
107  minuit->FixVariable(ParCounter);
108  }
109  }
110  }
111  }
112 
113  minuit->SetPrintLevel(2);
114 
115  MACH3LOG_INFO("Starting MIGRAD");
116  minuit->Minimize();
117 
118  MACH3LOG_INFO("Starting HESSE");
119  minuit->Hesse();
120  outputFile->cd();
121 
122  TVectorD* MinuitParValue = new TVectorD(NparsMinuitFull);
123  TVectorD* MinuitParError = new TVectorD(NparsMinuitFull);
124  TMatrixDSym* Postmatrix = new TMatrixDSym(NparsMinuitFull);
125 
126  for(int i = 0; i < NparsMinuitFull; ++i)
127  {
128  (*MinuitParValue)(i) = 0;
129  (*MinuitParError)(i) = 0;
130  for(int j = 0; j < NparsMinuitFull; ++j)
131  {
132  (*Postmatrix)(i,j) = 0;
133  (*Postmatrix)(i,j) = minuit->CovMatrix(i,j);
134  }
135  }
136 
137  ParCounter = 0;
138  const double *X = minuit->X();
139  const double *err = minuit->Errors();
140  for (std::vector<ParameterHandlerBase*>::iterator it = systematics.begin(); it != systematics.end(); ++it)
141  {
142  if(!(*it)->IsPCA())
143  {
144  for(int i = 0; i < (*it)->GetNumParams(); ++i, ++ParCounter)
145  {
146  double ParVal = X[ParCounter];
147  //KS: Basically apply mirroring for parameters out of bounds
148  if(fMirroring)
149  {
150  if(ParVal < (*it)->GetLowerBound(i))
151  {
152  ParVal = (*it)->GetLowerBound(i) + ((*it)->GetLowerBound(i) - ParVal);
153  }
154  else if (ParVal > (*it)->GetUpperBound(i))
155  {
156  ParVal = (*it)->GetUpperBound(i) - ( ParVal - (*it)->GetUpperBound(i));
157  }
158  }
159  (*MinuitParValue)(ParCounter) = ParVal;
160  (*MinuitParError)(ParCounter) = err[ParCounter];
161  //KS: For fixed params HESS will not calculate error so we need to pass prior error
162  if((*it)->IsParameterFixed(i))
163  {
164  (*MinuitParError)(ParCounter) = (*it)->GetDiagonalError(i);
165  (*Postmatrix)(ParCounter,ParCounter) = (*MinuitParError)(ParCounter) * (*MinuitParError)(ParCounter);
166  }
167  }
168  }
169  else
170  {
171  //KS: We need to convert parameters from PCA to normal base
172  TVectorD ParVals((*it)->GetNumParams());
173  TVectorD ParVals_PCA((*it)->GetNParameters());
174 
175  TVectorD ErrorVals((*it)->GetNumParams());
176  TVectorD ErrorVals_PCA((*it)->GetNParameters());
177 
178  TMatrixD MatrixVals((*it)->GetNumParams(), (*it)->GetNumParams());
179  TMatrixD MatrixVals_PCA((*it)->GetNParameters(), (*it)->GetNParameters());
180 
181  //First save them
182  //KS: This code is super convoluted as MaCh3 can store separate matrices while Minuit has one matrix. In future this will be simplified, keep it like this for now.
183  const int StartVal = ParCounter;
184  for(int i = 0; i < (*it)->GetNParameters(); ++i, ++ParCounter)
185  {
186  ParVals_PCA(i) = X[ParCounter];
187  ErrorVals_PCA(i) = err[ParCounter];
188  int ParCounterMatrix = StartVal;
189  for(int j = 0; j < (*it)->GetNParameters(); ++j, ++ParCounterMatrix)
190  {
191  MatrixVals_PCA(i,j) = minuit->CovMatrix(ParCounter,ParCounterMatrix);
192  }
193  }
194  ParVals = ((*it)->GetPCAHandler()->GetTransferMatrix())*ParVals_PCA;
195  ErrorVals = ((*it)->GetPCAHandler()->GetTransferMatrix())*ErrorVals_PCA;
196  MatrixVals.Mult(((*it)->GetPCAHandler()->GetTransferMatrix()),MatrixVals_PCA);
197 
198  ParCounter = StartVal;
199  //KS: Now after going from PCA to normal let';s save it
200  for(int i = 0; i < (*it)->GetNumParams(); ++i, ++ParCounter)
201  {
202  (*MinuitParValue)(ParCounter) = ParVals(i);
203  (*MinuitParError)(ParCounter) = std::fabs(ErrorVals(i));
204  int ParCounterMatrix = StartVal;
205  for(int j = 0; j < (*it)->GetNumParams(); ++j, ++ParCounterMatrix)
206  {
207  (*Postmatrix)(ParCounter,ParCounterMatrix) = MatrixVals(i,j);
208  }
209  //If fixed take prior
210  if((*it)->GetPCAHandler()->IsParameterFixedPCA(i))
211  {
212  (*MinuitParError)(ParCounter) = (*it)->GetDiagonalError(i);
213  (*Postmatrix)(ParCounter,ParCounter) = (*MinuitParError)(ParCounter) * (*MinuitParError)(ParCounter);
214  }
215  }
216  }
217  }
218 
219  MinuitParValue->Write("MinuitParValue");
220  MinuitParError->Write("MinuitParError");
221  Postmatrix->Write("Postmatrix");
222  delete MinuitParValue;
223  delete MinuitParError;
224  delete Postmatrix;
225  // Save all the output
226  SaveOutput();
227 }
void SaveOutput()
Save output and close files.
Definition: FitterBase.cpp:233
TFile * outputFile
Output.
Definition: FitterBase.h:156
Manager * fitMan
The manager for configuration handling.
Definition: FitterBase.h:120
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
int NParsPCA
Number of all parameters from all covariances in PCA base.
Definition: LikelihoodFit.h:25
int NPars
Number of all parameters from all covariances.
Definition: LikelihoodFit.h:23
void PrepareFit()
prepare output and perform sanity checks
bool fMirroring
Flag telling if mirroring is used or not.
Definition: LikelihoodFit.h:27
virtual double CalcChi2(const double *x)
Chi2 calculation over all included samples and syst objects.
YAML::Node const & raw() const
Return config.
Definition: Manager.h:48

Member Data Documentation

◆ minuit

std::unique_ptr<ROOT::Math::Minimizer> MinuitFit::minuit
private

Pointer to minimizer, which most often is Minuit.

Definition at line 29 of file MinuitFit.h.


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