Logo ROOT  
Reference Guide
FitResult.h
Go to the documentation of this file.
1// @(#)root/mathcore:$Id$
2// Author: L. Moneta Wed Aug 30 11:05:34 2006
3
4/**********************************************************************
5 * *
6 * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
7 * *
8 * *
9 **********************************************************************/
10
11// Header file for class FitResult
12
13#ifndef ROOT_Fit_FitResult
14#define ROOT_Fit_FitResult
15
16#include "Math/IFunctionfwd.h"
18
19#include <vector>
20#include <map>
21#include <string>
22#include <cmath>
23#include <memory>
24
25namespace ROOT {
26
27 namespace Math {
28 class Minimizer;
29 }
30
31
32 namespace Fit {
33
34 class FitConfig;
35 class FitData;
36 class BinData;
37
38//___________________________________________________________________________________
39/**
40 class containg the result of the fit and all the related information
41 (fitted parameter values, error, covariance matrix and minimizer result information)
42 Contains a pointer also to the fitted (model) function, modified with the fit parameter values.
43 When the fit is valid, it is constructed from a Minimizer and a model function pointer
44
45 @ingroup FitMain
46*/
47class FitResult {
48
49public:
50
52
53 /**
54 Default constructor for an empty (non valid) fit result
55 */
56 FitResult ();
57
58 /**
59 Constructor from a fit-config for a dummy fit
60 (e.g. when only one fcn evaluation is done)
61 */
62 FitResult (const FitConfig & fconfig);
63
64
65 /**
66 Copy constructor.
67 */
68 FitResult(const FitResult & rhs);
69
70 /**
71 Assignment operator
72 */
73 FitResult & operator = (const FitResult & rhs);
74
75 /**
76 Destructor
77 */
78 virtual ~FitResult ();
79
80
81public:
82
83 /**
84 Fill the fit result from a Minimizer instance after fitting
85 Run also Minos if requested from the configuration
86 */
87 void FillResult(const std::shared_ptr<ROOT::Math::Minimizer> & min, const FitConfig & fconfig, const std::shared_ptr<IModelFunction> & f,
88 bool isValid, unsigned int sizeOfData = 0, bool binFit = true, const ROOT::Math::IMultiGenFunction * chi2func = 0, unsigned int ncalls = 0);
89
90
91 /**
92 Update the fit result with a new minimization status
93 To be run only if same fit is performed with same configuration
94 Note that in this case MINOS is not re-run. If one wants to run also MINOS
95 a new result must be created
96 */
97 bool Update(const std::shared_ptr<ROOT::Math::Minimizer> & min, const ROOT::Fit::FitConfig & fconfig, bool isValid, unsigned int ncalls = 0);
98
99 /** minimization quantities **/
100
101 /// minimizer type
102 const std::string & MinimizerType() const { return fMinimType; }
103
104 /**
105 True if fit successful, otherwise false.
106 A fit is considered successful if the minimizer succeded in finding the
107 minimum. It could happen that subsequent operations like error analysis (e.g. Minos)
108 failed. In that case the status can be still true if the original minimization algorithm
109 succeeded in finding the minimum.
110 One can query in that case the minimizer return status using Status().
111 It is responability to the Minimizer class to tag a found minimum as valid or not
112 and to produce also a status code.
113 */
114 bool IsValid() const { return fValid; }
115
116 /// True if a fit result does not exist (even invalid) with parameter values
117 bool IsEmpty() const { return (fParams.size() == 0); }
118
119 /// Return value of the objective function (chi2 or likelihood) used in the fit
120 double MinFcnValue() const { return fVal; }
121
122 ///Number of function calls to find minimum
123 unsigned int NCalls() const { return fNCalls; }
124
125 ///Expected distance from minimum
126 double Edm() const { return fEdm; }
127
128 /// get total number of parameters
129 unsigned int NTotalParameters() const { return fParams.size(); }
130 /// total number of parameters (abbreviation)
131 unsigned int NPar() const { return NTotalParameters(); }
132
133 /// get total number of free parameters
134 unsigned int NFreeParameters() const { return fNFree; }
135
136 /// minimizer status code
137 int Status() const { return fStatus; }
138
139 ///covariance matrix status code
140 /// using Minuit convention : =0 not calculated, =1 approximated, =2 made pos def , =3 accurate
141
142 int CovMatrixStatus() const { return fCovStatus; }
143
144 /** fitting quantities **/
145
146 /// Return pointer to model (fit) function with fitted parameter values.
147 /// Pointer is managed internally. I must not be deleted
149 return fFitFunc.get();
150 }
151
152 /// return BinData used in the fit (return a nullptr in case a different fit is done
153 /// or the data are not available
154 /// Pointer is managed internally, it must not be deleted
155 const BinData * FittedBinData() const;
156
157
158 /// Chi2 fit value
159 /// in case of likelihood must be computed ?
160 double Chi2() const { return fChi2; }
161
162 /// Number of degree of freedom
163 unsigned int Ndf() const { return fNdf; }
164
165 /// p value of the fit (chi2 probability)
166 double Prob() const;
167
168 /// parameter errors (return st::vector)
169 const std::vector<double> & Errors() const { return fErrors; }
170 /// parameter errors (return const pointer)
171 const double * GetErrors() const { return (fErrors.empty()) ? 0 : &fErrors.front(); }
172
173 /// parameter values (return std::vector)
174 const std::vector<double> & Parameters() const { return fParams; }
175 /// parameter values (return const pointer)
176 const double * GetParams() const { return &fParams.front(); }
177
178 /// parameter value by index
179 double Value(unsigned int i) const { return fParams[i]; }
180 /// parameter value by index
181 double Parameter(unsigned int i) const { return fParams[i]; }
182
183 /// parameter error by index
184 // (NOTE: this due to conflict with TObject::Error cannot used in derived class which
185 // inherits from TObject. Use instead ParError (or Errors()[i] )
186 double Error(unsigned int i) const {
187 return (i < fErrors.size() ) ? fErrors[i] : 0;
188 }
189 /// parameter error by index
190 double ParError(unsigned int i) const {
191 return (i < fErrors.size() ) ? fErrors[i] : 0;
192 }
193
194 /// name of the parameter
195 std::string ParName(unsigned int i) const;
196
197 /// set the Minos errors for parameter i (called by the Fitter class when running Minos)
198 void SetMinosError(unsigned int i, double elow, double eup);
199
200 /// query if parameter i has the Minos error
201 bool HasMinosError(unsigned int i) const;
202
203 /// lower Minos error. If Minos has not run for parameter i return the parabolic error
204 double LowerError(unsigned int i) const;
205
206 /// upper Minos error. If Minos has not run for parameter i return the parabolic error
207 double UpperError(unsigned int i) const;
208
209 /// parameter global correlation coefficient
210 double GlobalCC(unsigned int i) const {
211 return (i < fGlobalCC.size() ) ? fGlobalCC[i] : -1;
212 }
213
214
215 /// retrieve covariance matrix element
216 double CovMatrix (unsigned int i, unsigned int j) const {
217 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
218 if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits
219 if ( j < i )
220 return fCovMatrix[j + i* (i+1) / 2];
221 else
222 return fCovMatrix[i + j* (j+1) / 2];
223 }
224
225 /// retrieve correlation elements
226 double Correlation(unsigned int i, unsigned int j ) const {
227 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
228 if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits
229 double tmp = CovMatrix(i,i)*CovMatrix(j,j);
230 return ( tmp > 0) ? CovMatrix(i,j)/ std::sqrt(tmp) : 0;
231 }
232
233 /// fill covariance matrix elements using a generic matrix class implementing operator(i,j)
234 /// the matrix must be previously allocates with right size (npar * npar)
235 template<class Matrix>
236 void GetCovarianceMatrix(Matrix & mat) const {
237 unsigned int npar = fErrors.size();
238 if (fCovMatrix.size() != npar*(npar+1)/2 ) return; // do nothing
239 for (unsigned int i = 0; i< npar; ++i) {
240 for (unsigned int j = 0; j<=i; ++j) {
241 mat(i,j) = fCovMatrix[j + i*(i+1)/2 ];
242 if (i != j) mat(j,i) = mat(i,j);
243 }
244 }
245 }
246
247 /// fill a correlation matrix elements using a generic symmetric matrix class implementing operator(i,j)
248 /// the matrix must be previously allocates with right size (npar * npar)
249 template<class Matrix>
250 void GetCorrelationMatrix(Matrix & mat) const {
251 unsigned int npar = fErrors.size();
252 if (fCovMatrix.size() != npar*(npar+1)/2) return; // do nothing
253 for (unsigned int i = 0; i< npar; ++i) {
254 for (unsigned int j = 0; j<=i; ++j) {
255 double tmp = fCovMatrix[i * (i +3)/2 ] * fCovMatrix[ j * (j+3)/2 ];
256 mat(i,j) = (tmp > 0) ? fCovMatrix[j + i*(i+1)/2 ] / std::sqrt(tmp) : 0;
257 if (i != j) mat(j,i) = mat(i,j);
258 }
259 }
260 }
261
262 /**
263 get confidence intervals for an array of n points x.
264 stride1 indicates the stride in the coordinate space while stride2 the stride in dimension space.
265 For 1-dim points : stride1=1, stride2=1
266 for multi-dim points arranged as (x0,x1,...,xN,y0,....yN) stride1=1 stride2=n
267 for multi-dim points arraged as (x0,y0,..,x1,y1,...,xN,yN,..) stride1=ndim, stride2=1
268
269 the confidence interval are returned in the array ci
270 cl is the desired confidedence interval value
271 norm is a flag to control if the intervals need to be normalized to the chi2/ndf value
272 The intervals can be corrected optionally using the chi2/ndf value of the fit if a chi2 fit is performed.
273 This has changed since ROOT 6.14, before the interval were corrected by default.
274 */
275 void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl=0.95, bool norm = false ) const;
276
277 /**
278 evaluate confidence interval for the point specified in the passed data sets
279 the confidence interval are returned in the array ci
280 cl is the desired confidence interval value.
281 This method is mantained for backward compatibility and will be deprecated
282 */
283 void GetConfidenceIntervals(const BinData & data, double * ci, double cl=0.95, bool norm = false ) const;
284
285 /**
286 evaluate confidence interval for the data set used in the last fit
287 the confidence interval are returned as a vector of data points
288 */
289 std::vector<double> GetConfidenceIntervals(double cl=0.95, bool norm = false ) const;
290
291 /**
292 scan likelihood value of parameter and fill the given graph.
293 */
294 bool Scan(unsigned int ipar, unsigned int &npoints, double *pntsx, double *pntsy, double xmin = 0, double xmax = 0);
295
296 /**
297 create contour of two parameters around the minimum
298 pass as option confidence level: default is a value of 0.683
299 */
300 bool Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *pntsx, double *pntsy, double confLevel = 0.683);
301
302 /// get index for parameter name (return -1 if not found)
303 int Index(const std::string & name) const;
304
305 ///normalize errors using chi2/ndf for chi2 fits
306 void NormalizeErrors();
307
308 /// flag to chek if errors are normalized
309 bool NormalizedErrors() const { return fNormalized; }
310
311 /// print the result and optionaly covariance matrix and correlations
312 void Print(std::ostream & os, bool covmat = false) const;
313
314 ///print error matrix and correlations
315 void PrintCovMatrix(std::ostream & os) const;
316
317 /// query if a parameter is bound
318 bool IsParameterBound(unsigned int ipar) const;
319
320 /// query if a parameter is fixed
321 bool IsParameterFixed(unsigned int ipar) const;
322
323 /// retrieve parameter bounds - return false if parameter is not bound
324 bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const;
325
326
327 /// get name of parameter (deprecated)
328 std::string GetParameterName(unsigned int ipar) const {
329 return ParName(ipar);
330 }
331
332
333protected:
334
335
336 /// Return pointer non const pointer to model (fit) function with fitted parameter values.
337 /// used by Fitter class
338 std::shared_ptr<IModelFunction> ModelFunction() { return fFitFunc; }
339 void SetModelFunction(const std::shared_ptr<IModelFunction> & func) { fFitFunc = func; }
340
341 friend class Fitter;
342
343
344 bool fValid; // flag for indicating valid fit
345 bool fNormalized; // flag for indicating is errors are normalized
346 unsigned int fNFree; // number of fit free parameters (total parameters are in size of parameter vector)
347 unsigned int fNdf; // number of degree of freedom
348 unsigned int fNCalls; // number of function calls
349 int fStatus; // minimizer status code
350 int fCovStatus; // covariance matrix status code
351 double fVal; // minimum function value
352 double fEdm; // expected distance from mimimum
353 double fChi2; // fit chi2 value (different than fval in case of chi2 fits)
354 std::shared_ptr<ROOT::Math::Minimizer> fMinimizer; //! minimizer object used for fitting
355 std::shared_ptr<ROOT::Math::IMultiGenFunction> fObjFunc; //! objective function used for fitting
356 std::shared_ptr<IModelFunction> fFitFunc; //! model function resulting from the fit.
357 std::shared_ptr<FitData> fFitData; //! data set used in the fit
358 std::map<unsigned int, bool> fFixedParams; // list of fixed parameters
359 std::map<unsigned int, unsigned int> fBoundParams; // list of limited parameters
360 std::vector<std::pair<double,double> > fParamBounds; // parameter bounds
361 std::vector<double> fParams; // parameter values. Size is total number of parameters
362 std::vector<double> fErrors; // errors
363 std::vector<double> fCovMatrix; // covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
364 std::vector<double> fGlobalCC; // global Correlation coefficient
365 std::map<unsigned int, std::pair<double,double> > fMinosErrors; // map contains the two Minos errors
366 std::string fMinimType; // string indicating type of minimizer
367 std::vector<std::string> fParNames; // parameter names (only with FCN only fits, when fFitFunc=0)
368
369};
370
371
372 } // end namespace Fit
373
374} // end namespace ROOT
375
376
377
378
379
380#endif /* ROOT_Fit_FitResult */
#define f(i)
Definition: RSha256.hxx:104
char name[80]
Definition: TGX11.cxx:110
float xmin
Definition: THbookFile.cxx:95
float xmax
Definition: THbookFile.cxx:95
double sqrt(double)
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:52
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition: FitConfig.h:47
class containg the result of the fit and all the related information (fitted parameter values,...
Definition: FitResult.h:47
std::vector< double > fGlobalCC
Definition: FitResult.h:364
bool IsValid() const
True if fit successful, otherwise false.
Definition: FitResult.h:114
bool IsEmpty() const
True if a fit result does not exist (even invalid) with parameter values.
Definition: FitResult.h:117
unsigned int fNFree
Definition: FitResult.h:346
bool Update(const std::shared_ptr< ROOT::Math::Minimizer > &min, const ROOT::Fit::FitConfig &fconfig, bool isValid, unsigned int ncalls=0)
Update the fit result with a new minimization status To be run only if same fit is performed with sam...
Definition: FitResult.cxx:275
std::map< unsigned int, unsigned int > fBoundParams
Definition: FitResult.h:359
const BinData * FittedBinData() const
return BinData used in the fit (return a nullptr in case a different fit is done or the data are not ...
Definition: FitResult.cxx:675
double ParError(unsigned int i) const
parameter error by index
Definition: FitResult.h:190
double UpperError(unsigned int i) const
upper Minos error. If Minos has not run for parameter i return the parabolic error
Definition: FitResult.cxx:383
void FillResult(const std::shared_ptr< ROOT::Math::Minimizer > &min, const FitConfig &fconfig, const std::shared_ptr< IModelFunction > &f, bool isValid, unsigned int sizeOfData=0, bool binFit=true, const ROOT::Math::IMultiGenFunction *chi2func=0, unsigned int ncalls=0)
Fill the fit result from a Minimizer instance after fitting Run also Minos if requested from the conf...
Definition: FitResult.cxx:100
FitResult & operator=(const FitResult &rhs)
Assignment operator.
Definition: FitResult.cxx:232
std::vector< double > fErrors
Definition: FitResult.h:362
bool NormalizedErrors() const
flag to chek if errors are normalized
Definition: FitResult.h:309
const std::vector< double > & Errors() const
parameter errors (return st::vector)
Definition: FitResult.h:169
const double * GetErrors() const
parameter errors (return const pointer)
Definition: FitResult.h:171
std::shared_ptr< ROOT::Math::Minimizer > fMinimizer
Definition: FitResult.h:354
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
Definition: FitResult.cxx:409
unsigned int fNdf
Definition: FitResult.h:347
const double * GetParams() const
parameter values (return const pointer)
Definition: FitResult.h:176
ROOT::Math::IParamMultiFunction IModelFunction
Definition: FitResult.h:51
double Error(unsigned int i) const
parameter error by index
Definition: FitResult.h:186
double CovMatrix(unsigned int i, unsigned int j) const
retrieve covariance matrix element
Definition: FitResult.h:216
void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double *x, double *ci, double cl=0.95, bool norm=false) const
get confidence intervals for an array of n points x.
Definition: FitResult.cxx:550
double Value(unsigned int i) const
parameter value by index
Definition: FitResult.h:179
bool Scan(unsigned int ipar, unsigned int &npoints, double *pntsx, double *pntsy, double xmin=0, double xmax=0)
scan likelihood value of parameter and fill the given graph.
Definition: FitResult.cxx:683
const std::vector< double > & Parameters() const
parameter values (return std::vector)
Definition: FitResult.h:174
FitResult()
Default constructor for an empty (non valid) fit result.
Definition: FitResult.cxx:45
std::shared_ptr< FitData > fFitData
model function resulting from the fit.
Definition: FitResult.h:357
const std::string & MinimizerType() const
minimization quantities
Definition: FitResult.h:102
std::string GetParameterName(unsigned int ipar) const
get name of parameter (deprecated)
Definition: FitResult.h:328
bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const
retrieve parameter bounds - return false if parameter is not bound
Definition: FitResult.cxx:413
unsigned int Ndf() const
Number of degree of freedom.
Definition: FitResult.h:163
double Chi2() const
Chi2 fit value in case of likelihood must be computed ?
Definition: FitResult.h:160
std::vector< double > fParams
Definition: FitResult.h:361
std::vector< double > fCovMatrix
Definition: FitResult.h:363
void SetMinosError(unsigned int i, double elow, double eup)
set the Minos errors for parameter i (called by the Fitter class when running Minos)
Definition: FitResult.cxx:390
void Print(std::ostream &os, bool covmat=false) const
print the result and optionaly covariance matrix and correlations
Definition: FitResult.cxx:433
double LowerError(unsigned int i) const
lower Minos error. If Minos has not run for parameter i return the parabolic error
Definition: FitResult.cxx:376
std::shared_ptr< IModelFunction > ModelFunction()
Return pointer non const pointer to model (fit) function with fitted parameter values.
Definition: FitResult.h:338
void PrintCovMatrix(std::ostream &os) const
print error matrix and correlations
Definition: FitResult.cxx:491
unsigned int fNCalls
Definition: FitResult.h:348
bool Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *pntsx, double *pntsy, double confLevel=0.683)
create contour of two parameters around the minimum pass as option confidence level: default is a val...
Definition: FitResult.cxx:704
void GetCorrelationMatrix(Matrix &mat) const
fill a correlation matrix elements using a generic symmetric matrix class implementing operator(i,...
Definition: FitResult.h:250
bool HasMinosError(unsigned int i) const
query if parameter i has the Minos error
Definition: FitResult.cxx:369
std::vector< std::pair< double, double > > fParamBounds
Definition: FitResult.h:360
double MinFcnValue() const
Return value of the objective function (chi2 or likelihood) used in the fit.
Definition: FitResult.h:120
unsigned int NPar() const
total number of parameters (abbreviation)
Definition: FitResult.h:131
int CovMatrixStatus() const
covariance matrix status code using Minuit convention : =0 not calculated, =1 approximated,...
Definition: FitResult.h:142
double Edm() const
Expected distance from minimum.
Definition: FitResult.h:126
std::shared_ptr< IModelFunction > fFitFunc
objective function used for fitting
Definition: FitResult.h:356
std::map< unsigned int, bool > fFixedParams
data set used in the fit
Definition: FitResult.h:358
std::string fMinimType
Definition: FitResult.h:366
unsigned int NCalls() const
Number of function calls to find minimum.
Definition: FitResult.h:123
double Correlation(unsigned int i, unsigned int j) const
retrieve correlation elements
Definition: FitResult.h:226
std::shared_ptr< ROOT::Math::IMultiGenFunction > fObjFunc
minimizer object used for fitting
Definition: FitResult.h:355
unsigned int NTotalParameters() const
get total number of parameters
Definition: FitResult.h:129
virtual ~FitResult()
Destructor.
Definition: FitResult.cxx:220
int Index(const std::string &name) const
get index for parameter name (return -1 if not found)
Definition: FitResult.cxx:395
double Prob() const
p value of the fit (chi2 probability)
Definition: FitResult.cxx:364
std::string ParName(unsigned int i) const
name of the parameter
Definition: FitResult.cxx:426
void GetCovarianceMatrix(Matrix &mat) const
fill covariance matrix elements using a generic matrix class implementing operator(i,...
Definition: FitResult.h:236
void NormalizeErrors()
normalize errors using chi2/ndf for chi2 fits
Definition: FitResult.cxx:350
void SetModelFunction(const std::shared_ptr< IModelFunction > &func)
Definition: FitResult.h:339
unsigned int NFreeParameters() const
get total number of free parameters
Definition: FitResult.h:134
bool IsParameterBound(unsigned int ipar) const
query if a parameter is bound
Definition: FitResult.cxx:405
double Parameter(unsigned int i) const
parameter value by index
Definition: FitResult.h:181
int Status() const
minimizer status code
Definition: FitResult.h:137
std::vector< std::string > fParNames
Definition: FitResult.h:367
std::map< unsigned int, std::pair< double, double > > fMinosErrors
Definition: FitResult.h:365
const IModelFunction * FittedFunction() const
fitting quantities
Definition: FitResult.h:148
double GlobalCC(unsigned int i) const
parameter global correlation coefficient
Definition: FitResult.h:210
Fitter class, entry point for performing all type of fits.
Definition: Fitter.h:77
Documentation for the abstract class IBaseFunctionMultiDim.
Definition: IFunction.h:62
RooCmdArg Minimizer(const char *type, const char *alg=0)
Double_t x[n]
Definition: legend1.C:17
const Int_t n
Definition: legend1.C:16
TFitResultPtr Fit(FitObject *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
Definition: HFitImpl.cxx:133
Namespace for new Math classes and functions.
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...