Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooMinimizer.h
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * File: $Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * AL, Alfio Lazzaro, INFN Milan, alfio.lazzaro@mi.infn.it *
9 * PB, Patrick Bos, NL eScience Center, p.bos@esciencecenter.nl *
10 * *
11 * *
12 * Redistribution and use in source and binary forms, *
13 * with or without modification, are permitted according to the terms *
14 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15 *****************************************************************************/
16
17#ifndef ROO_MINIMIZER
18#define ROO_MINIMIZER
19
23
24#include <TStopwatch.h>
25#include <TMatrixDSymfwd.h>
26
27#include <Fit/FitConfig.h>
28
29#include <fstream>
30#include <memory>
31#include <string>
32#include <utility>
33#include <vector>
34
36class RooAbsReal;
37class RooFitResult;
38class RooArgList;
39class RooRealVar;
40class RooArgSet;
41class RooPlot;
42namespace RooFit {
43namespace TestStatistics {
44class LikelihoodGradientJob;
45}
46} // namespace RooFit
47
48class RooMinimizer : public TObject {
49public:
50 // Internal struct for the temporary fit result.
51 struct FitResult {
52
53 FitResult() = default;
54 FitResult(const ROOT::Fit::FitConfig &fconfig);
55
56 double error(unsigned int i) const { return (i < fErrors.size()) ? fErrors[i] : 0; }
57 double lowerError(unsigned int i) const;
58 double upperError(unsigned int i) const;
59
60 double Edm() const { return fEdm; }
61 bool IsValid() const { return fValid; }
62 int Status() const { return fStatus; }
63 void GetCovarianceMatrix(TMatrixDSym &cov) const;
64
65 bool isParameterFixed(unsigned int ipar) const;
66
67 bool fValid = false; ///< flag for indicating valid fit
68 int fStatus = -1; ///< minimizer status code
69 int fCovStatus = -1; ///< covariance matrix status code
70 double fVal = 0; ///< minimum function value
71 double fEdm = -1; ///< expected distance from minimum
72 std::map<unsigned int, bool> fFixedParams; ///< list of fixed parameters
73 std::vector<double> fParams; ///< parameter values. Size is total number of parameters
74 std::vector<double> fErrors; ///< errors
75 std::vector<double> fCovMatrix; ///< covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
76 std::vector<double> fGlobalCC; ///< global Correlation coefficient
77 std::map<unsigned int, std::pair<double, double>> fMinosErrors; ///< map contains the two Minos errors
78 std::string fMinimType; ///< string indicating type of minimizer
79 };
80
81 /// Config argument to RooMinimizer constructor.
82 struct Config {
83
84 Config() {}
85
86 bool useGradient = true; // Use the gradient provided by the RooAbsReal, if there is one.
87
88 double recoverFromNaN = 10.; // RooAbsMinimizerFcn config
89 int printEvalErrors = 10; // RooAbsMinimizerFcn config
90 int doEEWall = 1; // RooAbsMinimizerFcn config
91 int offsetting = -1; // RooAbsMinimizerFcn config
92 const char *logf = nullptr; // RooAbsMinimizerFcn config
93
94 // RooAbsMinimizerFcn config that can only be set in constructor, 0 means no parallelization (default),
95 // -1 is parallelization with the number of workers controlled by RooFit::MultiProcess which
96 // defaults to the number of available processors, n means parallelization with n CPU's
97 int parallelize = 0;
98
99 // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
100 // argument is ignored when parallelize is 0
102
103 // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
104 // argument is ignored when parallelize is 0
106
107 bool verbose = false; // local config
108 bool profile = false; // local config
109 bool timingAnalysis = false; // local config
110 std::string minimizerType; // local config
111
112 bool setInitialCovariance = false; // Use covariance matrix provided by user
113 };
114
115 // For backwards compatibility with when the RooMinimizer used the ROOT::Math::Fitter.
117 public:
119 : _config{config}, _minimizer{minimizer}, _result{result}
120 {
121 }
122
123 ROOT::Fit::FitConfig &Config() const { return *_config; }
125 const FitResult &Result() const { return *_result; }
126
127 private:
130 FitResult const *_result = nullptr;
131 };
132
133 explicit RooMinimizer(RooAbsReal &function, Config const &cfg = {});
134
135 ~RooMinimizer() override;
136
137 enum Strategy { Speed = 0, Balance = 1, Robustness = 2 };
138 enum PrintLevel { None = -1, Reduced = 0, Normal = 1, ExtraForProblem = 2, Maximum = 3 };
139
140 // Setters on _theFitter
141 void setStrategy(int istrat);
142 void setErrorLevel(double level);
143 void setEps(double eps);
144 void setMaxIterations(int n);
145 void setMaxFunctionCalls(int n);
146 void setPrintLevel(int newLevel);
147
148 // Setters on _fcn
149 void optimizeConst(int flag);
150 void setEvalErrorWall(bool flag) { _cfg.doEEWall = flag; }
151 void setRecoverFromNaNStrength(double strength);
152 void setOffsetting(bool flag);
153 void setPrintEvalErrors(int numEvalErrors) { _cfg.printEvalErrors = numEvalErrors; }
154 void setVerbose(bool flag = true) { _cfg.verbose = flag; }
155 bool setLogFile(const char *logf = nullptr);
156
157 int migrad();
158 int hesse();
159 int minos();
160 int minos(const RooArgSet &minosParamList);
161 int seek();
162 int simplex();
163 int improve();
164
165 int minimize(const char *type, const char *alg = nullptr);
166
167 RooFit::OwningPtr<RooFitResult> save(const char *name = nullptr, const char *title = nullptr);
168 RooPlot *contour(RooRealVar &var1, RooRealVar &var2, double n1 = 1.0, double n2 = 2.0, double n3 = 0.0,
169 double n4 = 0.0, double n5 = 0.0, double n6 = 0.0, unsigned int npoints = 50);
170
171 void setProfile(bool flag = true) { _cfg.profile = flag; }
172
173 int getPrintLevel();
174
175 void setMinimizerType(std::string const &type);
176 std::string const &minimizerType() const { return _cfg.minimizerType; }
177
179
180 void saveStatus(const char *label, int status) { _statusHistory.emplace_back(label, status); }
181
182 /// Clears the Minuit status history.
184
185 int evalCounter() const;
186 void zeroEvalCount();
187
188 /// Return underlying ROOT fitter object
189 inline auto fitter() { return std::make_unique<FitterInterface>(&_config, _minimizer.get(), _result.get()); }
190
192
193 int getNPar() const;
194
195 void applyCovarianceMatrix(TMatrixDSym const &V);
196
197private:
198 friend class RooAbsMinimizerFcn;
199 friend class RooMinimizerFcn;
201
202 std::unique_ptr<RooAbsReal::EvalErrorContext> makeEvalErrorContext() const;
203
205
206 void profileStart();
207 void profileStop();
208
209 std::ofstream *logfile();
210 double &maxFCN();
211 double &fcnOffset() const;
212
213 // constructor helper functions
215 void initMinimizerFcnDependentPart(double defaultErrorLevel);
216
217 void determineStatus(bool fitterReturnValue);
218
219 int exec(std::string const &algoName, std::string const &statusName);
220
221 bool fitFCN(const ROOT::Math::IMultiGenFunction &fcn);
222
223 bool calculateHessErrors();
225
226 void initMinimizer();
227 void updateFitConfig();
228 bool updateMinimizerOptions(bool canDifferentMinim = true);
229
230 void fillResult(bool isValid);
231 bool update(bool isValid);
232
233 void fillCorrMatrix(RooFitResult &fitRes);
234 void updateErrors();
235
236 ROOT::Fit::FitConfig _config; ///< fitter configuration (options and parameter settings)
237 std::unique_ptr<FitResult> _result; ///<! pointer to the object containing the result of the fit
238 std::unique_ptr<ROOT::Math::Minimizer> _minimizer; ///<! pointer to used minimizer
239 int _status = -99;
240 bool _profileStart = false;
243 std::unique_ptr<TMatrixDSym> _extV;
244 std::unique_ptr<RooAbsMinimizerFcn> _fcn;
245 std::vector<std::pair<std::string, int>> _statusHistory;
246 RooMinimizer::Config _cfg; // local config object
247
248 ClassDefOverride(RooMinimizer, 0) // RooFit interface to ROOT::Math::Minimizer
249};
250
251#endif
#define ClassDefOverride(name, id)
Definition Rtypes.h:346
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:110
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition FitConfig.h:47
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:61
Abstract Minimizer class, defining the interface for the various minimizer (like Minuit2,...
Definition Minimizer.h:119
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
RooMinimizerFcn is an interface to the ROOT::Math::IBaseFunctionMultiDim, a function that ROOT's mini...
ROOT::Math::Minimizer * GetMinimizer() const
ROOT::Fit::FitConfig * _config
ROOT::Math::Minimizer * _minimizer
const FitResult & Result() const
ROOT::Fit::FitConfig & Config() const
FitterInterface(ROOT::Fit::FitConfig *config, ROOT::Math::Minimizer *minimizer, FitResult const *result)
Wrapper class around ROOT::Math::Minimizer that provides a seamless interface between the minimizer f...
void setRecoverFromNaNStrength(double strength)
Try to recover from invalid function values.
int getPrintLevel()
Get the MINUIT internal printing level.
void optimizeConst(int flag)
If flag is true, perform constant term optimization on function being minimized.
void initMinimizerFirstPart()
Initialize the part of the minimizer that is independent of the function to be minimized.
std::ofstream * logfile()
auto fitter()
Return underlying ROOT fitter object.
int simplex()
Execute SIMPLEX.
std::unique_ptr< TMatrixDSym > _extV
void setMinimizerType(std::string const &type)
Choose the minimizer algorithm.
RooFit::OwningPtr< RooFitResult > save(const char *name=nullptr, const char *title=nullptr)
Save and return a RooFitResult snapshot of current minimizer status.
std::vector< std::pair< std::string, int > > _statusHistory
void profileStart()
Start profiling timer.
void setProfile(bool flag=true)
RooPlot * contour(RooRealVar &var1, RooRealVar &var2, double n1=1.0, double n2=2.0, double n3=0.0, double n4=0.0, double n5=0.0, double n6=0.0, unsigned int npoints=50)
Create and draw a TH2 with the error contours in the parameters var1 and var2.
std::unique_ptr< ROOT::Math::Minimizer > _minimizer
! pointer to used minimizer
bool setLogFile(const char *logf=nullptr)
void initMinimizerFcnDependentPart(double defaultErrorLevel)
Initialize the part of the minimizer that is dependent on the function to be minimized.
void fillCorrMatrix(RooFitResult &fitRes)
double & fcnOffset() const
ROOT::Fit::FitConfig _config
fitter configuration (options and parameter settings)
void profileStop()
Stop profiling timer and report results of last session.
int minos()
Execute MINOS.
double & maxFCN()
bool calculateHessErrors()
int hesse()
Execute HESSE.
bool calculateMinosErrors()
void setErrorLevel(double level)
Set the level for MINUIT error analysis to the given value.
void determineStatus(bool fitterReturnValue)
void setEvalErrorWall(bool flag)
int migrad()
Execute MIGRAD.
bool update(bool isValid)
int seek()
Execute SEEK.
bool updateMinimizerOptions(bool canDifferentMinim=true)
void setEps(double eps)
Change MINUIT epsilon.
void setPrintLevel(int newLevel)
Change the MINUIT internal printing level.
std::string const & minimizerType() const
void fillResult(bool isValid)
int exec(std::string const &algoName, std::string const &statusName)
int improve()
Execute IMPROVE.
void setOffsetting(bool flag)
Enable internal likelihood offsetting for enhanced numeric precision.
TStopwatch _timer
RooMinimizer::Config _cfg
bool fitFCN(const ROOT::Math::IMultiGenFunction &fcn)
std::unique_ptr< FitResult > _result
! pointer to the object containing the result of the fit
RooFit::OwningPtr< RooFitResult > lastMinuitFit()
void saveStatus(const char *label, int status)
~RooMinimizer() override
Destructor.
int minimize(const char *type, const char *alg=nullptr)
Minimise the function passed in the constructor.
void clearStatusHistory()
Clears the Minuit status history.
ROOT::Math::IMultiGenFunction * getMultiGenFcn() const
std::unique_ptr< RooAbsReal::EvalErrorContext > makeEvalErrorContext() const
void setVerbose(bool flag=true)
void setPrintEvalErrors(int numEvalErrors)
void setMaxFunctionCalls(int n)
Change maximum number of likelihood function class from MINUIT (RooMinimizer default 500 * #parameter...
void setStrategy(int istrat)
Change MINUIT strategy to istrat.
int evalCounter() const
TStopwatch _cumulTimer
int getNPar() const
void setMaxIterations(int n)
Change maximum number of MINUIT iterations (RooMinimizer default 500 * #parameters)
void addParamsToProcessTimer()
Add parameters in metadata field to process timer.
std::unique_ptr< RooAbsMinimizerFcn > _fcn
void applyCovarianceMatrix(TMatrixDSym const &V)
Apply results of given external covariance matrix.
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
Variable that can be changed from the outside.
Definition RooRealVar.h:37
Mother of all ROOT objects.
Definition TObject.h:41
Stopwatch class.
Definition TStopwatch.h:28
const Int_t n
Definition legend1.C:16
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition JSONIO.h:26
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
Definition Config.h:35
Config argument to RooMinimizer constructor.
std::string minimizerType
bool fValid
flag for indicating valid fit
std::vector< double > fGlobalCC
global Correlation coefficient
std::map< unsigned int, std::pair< double, double > > fMinosErrors
map contains the two Minos errors
double upperError(unsigned int i) const
std::string fMinimType
string indicating type of minimizer
std::vector< double > fErrors
errors
double error(unsigned int i) const
std::vector< double > fParams
parameter values. Size is total number of parameters
double fEdm
expected distance from minimum
double fVal
minimum function value
void GetCovarianceMatrix(TMatrixDSym &cov) const
std::map< unsigned int, bool > fFixedParams
list of fixed parameters
bool isParameterFixed(unsigned int ipar) const
int fCovStatus
covariance matrix status code
std::vector< double > fCovMatrix
covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
int fStatus
minimizer status code
double lowerError(unsigned int i) const