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
64 bool isParameterFixed(unsigned int ipar) const;
65
66 bool fValid = false; ///< flag for indicating valid fit
67 int fStatus = -1; ///< minimizer status code
68 int fCovStatus = -1; ///< covariance matrix status code
69 double fVal = 0; ///< minimum function value
70 double fEdm = -1; ///< expected distance from minimum
71 std::map<unsigned int, bool> fFixedParams; ///< list of fixed parameters
72 std::vector<double> fParams; ///< parameter values. Size is total number of parameters
73 std::vector<double> fErrors; ///< errors
74 std::vector<double> fCovMatrix; ///< covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
75 std::vector<double> fGlobalCC; ///< global Correlation coefficient
76 std::map<unsigned int, std::pair<double, double>> fMinosErrors; ///< map contains the two Minos errors
77 std::string fMinimType; ///< string indicating type of minimizer
78 };
79
80 /// Config argument to RooMinimizer constructor.
81 struct Config {
82
83 Config() {}
84
85 bool useGradient = true; // Use the gradient 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
112 // For backwards compatibility with when the RooMinimizer used the ROOT::Math::Fitter.
114 public:
116 : _config{config}, _minimizer{minimizer}, _result{result}
117 {
118 }
119
120 ROOT::Fit::FitConfig &Config() const { return *_config; }
122 const FitResult &Result() const { return *_result; }
123
124 private:
127 FitResult const *_result = nullptr;
128 };
129
130 explicit RooMinimizer(RooAbsReal &function, Config const &cfg = {});
131
132 ~RooMinimizer() override;
133
134 enum Strategy { Speed = 0, Balance = 1, Robustness = 2 };
135 enum PrintLevel { None = -1, Reduced = 0, Normal = 1, ExtraForProblem = 2, Maximum = 3 };
136
137 // Setters on _theFitter
138 void setStrategy(int istrat);
139 void setErrorLevel(double level);
140 void setEps(double eps);
141 void setMaxIterations(int n);
142 void setMaxFunctionCalls(int n);
143 void setPrintLevel(int newLevel);
144
145 // Setters on _fcn
146 void optimizeConst(int flag);
147 void setEvalErrorWall(bool flag) { _cfg.doEEWall = flag; }
148 void setRecoverFromNaNStrength(double strength);
149 void setOffsetting(bool flag);
150 void setPrintEvalErrors(int numEvalErrors) { _cfg.printEvalErrors = numEvalErrors; }
151 void setVerbose(bool flag = true) { _cfg.verbose = flag; }
152 bool setLogFile(const char *logf = nullptr);
153
154 int migrad();
155 int hesse();
156 int minos();
157 int minos(const RooArgSet &minosParamList);
158 int seek();
159 int simplex();
160 int improve();
161
162 int minimize(const char *type, const char *alg = nullptr);
163
164 RooFit::OwningPtr<RooFitResult> save(const char *name = nullptr, const char *title = nullptr);
165 RooPlot *contour(RooRealVar &var1, RooRealVar &var2, double n1 = 1.0, double n2 = 2.0, double n3 = 0.0,
166 double n4 = 0.0, double n5 = 0.0, double n6 = 0.0, unsigned int npoints = 50);
167
168 void setProfile(bool flag = true) { _cfg.profile = flag; }
169
170 int getPrintLevel();
171
172 void setMinimizerType(std::string const &type);
173 std::string const &minimizerType() const { return _cfg.minimizerType; }
174
176
177 void saveStatus(const char *label, int status) { _statusHistory.emplace_back(label, status); }
178
179 /// Clears the Minuit status history.
181
182 int evalCounter() const;
183 void zeroEvalCount();
184
185 /// Return underlying ROOT fitter object
186 inline auto fitter() { return std::make_unique<FitterInterface>(&_config, _minimizer.get(), _result.get()); }
187
189
190 int getNPar() const;
191
192 void applyCovarianceMatrix(TMatrixDSym const &V);
193
194private:
195 friend class RooAbsMinimizerFcn;
196 friend class RooMinimizerFcn;
198
199 std::unique_ptr<RooAbsReal::EvalErrorContext> makeEvalErrorContext() const;
200
202
203 void profileStart();
204 void profileStop();
205
206 std::ofstream *logfile();
207 double &maxFCN();
208 double &fcnOffset() const;
209
210 // constructor helper functions
212 void initMinimizerFcnDependentPart(double defaultErrorLevel);
213
214 void determineStatus(bool fitterReturnValue);
215
216 int exec(std::string const &algoName, std::string const &statusName);
217
218 bool fitFCN(const ROOT::Math::IMultiGenFunction &fcn);
219
220 bool calculateHessErrors();
222
223 void initMinimizer();
224 void updateFitConfig();
225 bool updateMinimizerOptions(bool canDifferentMinim = true);
226
227 void fillResult(bool isValid);
228 bool update(bool isValid);
229
230 void fillCorrMatrix(RooFitResult &fitRes);
231 void updateErrors();
232
233 ROOT::Fit::FitConfig _config; ///< fitter configuration (options and parameter settings)
234 std::unique_ptr<FitResult> _result; ///<! pointer to the object containing the result of the fit
235 std::unique_ptr<ROOT::Math::Minimizer> _minimizer; ///<! pointer to used minimizer
236 int _status = -99;
237 bool _profileStart = false;
240 std::unique_ptr<TMatrixDSym> _extV;
241 std::unique_ptr<RooAbsMinimizerFcn> _fcn;
242 std::vector<std::pair<std::string, int>> _statusHistory;
243 RooMinimizer::Config _cfg; // local config object
244
245 ClassDefOverride(RooMinimizer, 0) // RooFit interface to ROOT::Math::Minimizer
246};
247
248#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:45
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
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