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
20#include <RooAbsReal.h>
21
22#include <TStopwatch.h>
23#include <TMatrixDSymfwd.h>
24
25#include <Fit/FitConfig.h>
26
27#include <fstream>
28#include <map>
29#include <memory>
30#include <string>
31#include <utility>
32#include <vector>
33
35class RooFitResult;
36class RooArgList;
37class RooRealVar;
38class RooArgSet;
39class RooPlot;
40namespace RooFit {
41namespace TestStatistics {
42class LikelihoodGradientJob;
43}
44} // namespace RooFit
45
46class RooMinimizer : public TObject {
47public:
48 // Internal struct for the temporary fit result.
49 struct FitResult {
50
51 FitResult() = default;
53
54 double error(unsigned int i) const { return (i < fErrors.size()) ? fErrors[i] : 0; }
55 double lowerError(unsigned int i) const;
56 double upperError(unsigned int i) const;
57
58 double Edm() const { return fEdm; }
59 bool IsValid() const { return fValid; }
60 int Status() const { return fStatus; }
62
63 bool isParameterFixed(unsigned int ipar) const;
64
65 bool fValid = false; ///< flag for indicating valid fit
66 int fStatus = -1; ///< minimizer status code
67 int fCovStatus = -1; ///< covariance matrix status code
68 double fVal = 0; ///< minimum function value
69 double fEdm = -1; ///< expected distance from minimum
70 std::map<unsigned int, bool> fFixedParams; ///< list of fixed parameters
71 std::vector<double> fParams; ///< parameter values. Size is total number of parameters
72 std::vector<double> fErrors; ///< errors
73 std::vector<double> fCovMatrix; ///< covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
74 std::vector<double> fGlobalCC; ///< global Correlation coefficient
75 std::map<unsigned int, std::pair<double, double>> fMinosErrors; ///< map contains the two Minos errors
76 std::string fMinimType; ///< string indicating type of minimizer
77 };
78
79 /// Config argument to RooMinimizer constructor.
80 struct Config {
81
82 Config() {}
83
84 bool useGradient = true; // Use the gradient provided by the RooAbsReal, if there is one.
85 bool useHessian = false; // Use the Hessian provided by the RooAbsReal, if there is one.
86
87 double recoverFromNaN = 10.; // RooAbsMinimizerFcn config
88 int printEvalErrors = 10; // RooAbsMinimizerFcn config
89 int doEEWall = 1; // RooAbsMinimizerFcn config
90 int offsetting = -1; // RooAbsMinimizerFcn config
91 const char *logf = nullptr; // RooAbsMinimizerFcn config
92
93 // RooAbsMinimizerFcn config that can only be set in constructor, 0 means no parallelization (default),
94 // -1 is parallelization with the number of workers controlled by RooFit::MultiProcess which
95 // defaults to the number of available processors, n means parallelization with n CPU's
96 int parallelize = 0;
97
98 // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
99 // argument is ignored when parallelize is 0
101
102 // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
103 // argument is ignored when parallelize is 0
105
106 bool verbose = false; // local config
107 bool profile = false; // local config
108 bool timingAnalysis = false; // local config
109 std::string minimizerType; // local config
110
111 bool setInitialCovariance = false; // Use covariance matrix provided by user
112 };
113
114 // For backwards compatibility with when the RooMinimizer used the ROOT::Math::Fitter.
116 public:
118 : _config{config}, _minimizer{minimizer}, _result{result}
119 {
120 }
121
122 ROOT::Fit::FitConfig &Config() const { return *_config; }
124 const FitResult &Result() const { return *_result; }
125
126 private:
129 FitResult const *_result = nullptr;
130 };
131
132 explicit RooMinimizer(RooAbsReal &function, Config const &cfg = {});
133
134 ~RooMinimizer() override;
135
136 enum Strategy { Speed = 0, Balance = 1, Robustness = 2 };
137 enum PrintLevel { None = -1, Reduced = 0, Normal = 1, ExtraForProblem = 2, Maximum = 3 };
138
139 // Setters on _theFitter
140 void setStrategy(int istrat);
141 void setErrorLevel(double level);
142 void setEps(double eps);
143 void setMaxIterations(int n);
144 void setMaxFunctionCalls(int n);
145 void setPrintLevel(int newLevel);
146
147 // Setters on _fcn
148 void optimizeConst(int flag)
149#ifndef ROOFIT_BUILDS_ITSELF
150 R__DEPRECATED(6, 42, "Please use the default \"cpu\" likelihood evaluation backend if you want all optimizations.")
151#endif
152 ;
155 void setOffsetting(bool flag);
156 void setPrintEvalErrors(int numEvalErrors) { _cfg.printEvalErrors = numEvalErrors; }
157 void setVerbose(bool flag = true) { _cfg.verbose = flag; }
158 bool setLogFile(const char *logf = nullptr);
159
160 int migrad();
161 int hesse();
162 int minos();
163 int minos(const RooArgSet &minosParamList);
164 int seek();
165 int simplex();
166 int improve();
167
168 int minimize(const char *type, const char *alg = nullptr);
169
170 RooFit::OwningPtr<RooFitResult> save(const char *name = nullptr, const char *title = nullptr);
171 RooPlot *contour(RooRealVar &var1, RooRealVar &var2, double n1 = 1.0, double n2 = 2.0, double n3 = 0.0,
172 double n4 = 0.0, double n5 = 0.0, double n6 = 0.0, unsigned int npoints = 50);
173
174 void setProfile(bool flag = true) { _cfg.profile = flag; }
175
176 int getPrintLevel();
177
178 void setMinimizerType(std::string const &type);
179 std::string const &minimizerType() const { return _cfg.minimizerType; }
180
182
183 void saveStatus(const char *label, int status) { _statusHistory.emplace_back(label, status); }
184
185 /// Clears the Minuit status history.
187
188 int evalCounter() const;
189 void zeroEvalCount();
190
191 /// Return underlying ROOT fitter object
192 inline auto fitter() { return std::make_unique<FitterInterface>(&_config, _minimizer.get(), _result.get()); }
193
194 int getNPar() const;
195
196 void applyCovarianceMatrix(TMatrixDSym const &V);
197
198private:
199 friend class RooAbsMinimizerFcn;
200 friend class RooMinimizerFcn;
202
203 std::unique_ptr<RooAbsReal::EvalErrorContext> makeEvalErrorContext() const;
204
206
207 void profileStart();
208 void profileStop();
209
210 std::ofstream *logfile();
211 double &maxFCN();
212 double &fcnOffset() const;
213
214 // constructor helper functions
216 void initMinimizerFcnDependentPart(double defaultErrorLevel);
217
219
220 int exec(std::string const &algoName, std::string const &statusName);
221
222 bool fitFCN();
223
224 bool calculateHessErrors();
226
227 void initMinimizer();
228 void updateFitConfig();
230
231 void fillResult(bool isValid);
232 bool update(bool isValid);
233
235 void updateErrors();
236
237 ROOT::Fit::FitConfig _config; ///< fitter configuration (options and parameter settings)
238 std::unique_ptr<FitResult> _result; ///<! pointer to the object containing the result of the fit
239 std::unique_ptr<ROOT::Math::Minimizer> _minimizer; ///<! pointer to used minimizer
240 int _status = -99;
241 bool _profileStart = false;
244 std::unique_ptr<TMatrixDSym> _extV;
245 std::unique_ptr<RooAbsMinimizerFcn> _fcn;
246 std::vector<std::pair<std::string, int>> _statusHistory;
247 RooMinimizer::Config _cfg; // local config object
248
249 ClassDefOverride(RooMinimizer, 0) // RooFit interface to ROOT::Math::Minimizer
250};
251
252#endif
#define R__DEPRECATED(MAJOR, MINOR, REASON)
Definition RConfig.hxx:510
#define ClassDefOverride(name, id)
Definition Rtypes.h:348
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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:145
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition FitConfig.h:49
Abstract Minimizer class, defining the interface for the various minimizer (like Minuit2,...
Definition Minimizer.h:124
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
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.
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 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.
friend class RooMinimizerFcn
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 optimizeConst(int flag) R__DEPRECATED(6
If flag is true, perform constant term optimization on function being minimized.
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
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.
std::unique_ptr< RooAbsReal::EvalErrorContext > makeEvalErrorContext() const
void setVerbose(bool flag=true)
void setPrintEvalErrors(int numEvalErrors)
RooMinimizer(RooAbsReal &function, Config const &cfg={})
Construct MINUIT interface to given function.
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:42
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 CodegenImpl.h:72
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