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
86 double recoverFromNaN = 10.; // RooAbsMinimizerFcn config
87 int printEvalErrors = 10; // RooAbsMinimizerFcn config
88 int doEEWall = 1; // RooAbsMinimizerFcn config
89 int offsetting = -1; // RooAbsMinimizerFcn config
90 const char *logf = nullptr; // RooAbsMinimizerFcn config
91
92 // RooAbsMinimizerFcn config that can only be set in constructor, 0 means no parallelization (default),
93 // -1 is parallelization with the number of workers controlled by RooFit::MultiProcess which
94 // defaults to the number of available processors, n means parallelization with n CPU's
95 int parallelize = 0;
96
97 // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
98 // argument is ignored when parallelize is 0
100
101 // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
102 // argument is ignored when parallelize is 0
104
105 bool verbose = false; // local config
106 bool profile = false; // local config
107 bool timingAnalysis = false; // local config
108 std::string minimizerType; // local config
109
110 bool setInitialCovariance = false; // Use covariance matrix provided by user
111 };
112
113 // For backwards compatibility with when the RooMinimizer used the ROOT::Math::Fitter.
115 public:
117 : _config{config}, _minimizer{minimizer}, _result{result}
118 {
119 }
120
121 ROOT::Fit::FitConfig &Config() const { return *_config; }
123 const FitResult &Result() const { return *_result; }
124
125 private:
128 FitResult const *_result = nullptr;
129 };
130
131 explicit RooMinimizer(RooAbsReal &function, Config const &cfg = {});
132
133 ~RooMinimizer() override;
134
135 enum Strategy { Speed = 0, Balance = 1, Robustness = 2 };
136 enum PrintLevel { None = -1, Reduced = 0, Normal = 1, ExtraForProblem = 2, Maximum = 3 };
137
138 // Setters on _theFitter
139 void setStrategy(int istrat);
140 void setErrorLevel(double level);
141 void setEps(double eps);
142 void setMaxIterations(int n);
143 void setMaxFunctionCalls(int n);
144 void setPrintLevel(int newLevel);
145
146 // Setters on _fcn
147 void optimizeConst(int flag);
150 void setOffsetting(bool flag);
151 void setPrintEvalErrors(int numEvalErrors) { _cfg.printEvalErrors = numEvalErrors; }
152 void setVerbose(bool flag = true) { _cfg.verbose = flag; }
153 bool setLogFile(const char *logf = nullptr);
154
155 int migrad();
156 int hesse();
157 int minos();
158 int minos(const RooArgSet &minosParamList);
159 int seek();
160 int simplex();
161 int improve();
162
163 int minimize(const char *type, const char *alg = nullptr);
164
165 RooFit::OwningPtr<RooFitResult> save(const char *name = nullptr, const char *title = nullptr);
166 RooPlot *contour(RooRealVar &var1, RooRealVar &var2, double n1 = 1.0, double n2 = 2.0, double n3 = 0.0,
167 double n4 = 0.0, double n5 = 0.0, double n6 = 0.0, unsigned int npoints = 50);
168
169 void setProfile(bool flag = true) { _cfg.profile = flag; }
170
171 int getPrintLevel();
172
173 void setMinimizerType(std::string const &type);
174 std::string const &minimizerType() const { return _cfg.minimizerType; }
175
177
178 void saveStatus(const char *label, int status) { _statusHistory.emplace_back(label, status); }
179
180 /// Clears the Minuit status history.
182
183 int evalCounter() const;
184 void zeroEvalCount();
185
186 /// Return underlying ROOT fitter object
187 inline auto fitter() { return std::make_unique<FitterInterface>(&_config, _minimizer.get(), _result.get()); }
188
189 int getNPar() const;
190
191 void applyCovarianceMatrix(TMatrixDSym const &V);
192
193private:
194 friend class RooAbsMinimizerFcn;
195 friend class RooMinimizerFcn;
197
198 std::unique_ptr<RooAbsReal::EvalErrorContext> makeEvalErrorContext() const;
199
201
202 void profileStart();
203 void profileStop();
204
205 std::ofstream *logfile();
206 double &maxFCN();
207 double &fcnOffset() const;
208
209 // constructor helper functions
211 void initMinimizerFcnDependentPart(double defaultErrorLevel);
212
214
215 int exec(std::string const &algoName, std::string const &statusName);
216
217 bool fitFCN();
218
219 bool calculateHessErrors();
221
222 void initMinimizer();
223 void updateFitConfig();
225
226 void fillResult(bool isValid);
227 bool update(bool isValid);
228
230 void updateErrors();
231
232 ROOT::Fit::FitConfig _config; ///< fitter configuration (options and parameter settings)
233 std::unique_ptr<FitResult> _result; ///<! pointer to the object containing the result of the fit
234 std::unique_ptr<ROOT::Math::Minimizer> _minimizer; ///<! pointer to used minimizer
235 int _status = -99;
236 bool _profileStart = false;
239 std::unique_ptr<TMatrixDSym> _extV;
240 std::unique_ptr<RooAbsMinimizerFcn> _fcn;
241 std::vector<std::pair<std::string, int>> _statusHistory;
242 RooMinimizer::Config _cfg; // local config object
243
244 ClassDefOverride(RooMinimizer, 0) // RooFit interface to ROOT::Math::Minimizer
245};
246
247#endif
#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:110
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 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.
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 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: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 CodegenImpl.h:67
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