Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
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 containing 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 // default copy constructor and assignment can be used
65
66 /**
67 Destructor
68 */
69 virtual ~FitResult () {}
70
71
72public:
73
74 /**
75 Fill the fit result from a Minimizer instance after fitting
76 Run also Minos if requested from the configuration
77 */
78 void FillResult(const std::shared_ptr<ROOT::Math::Minimizer> & min, const FitConfig & fconfig, const std::shared_ptr<IModelFunction> & f,
79 bool isValid, unsigned int sizeOfData = 0, int fitType = 1, const ROOT::Math::IMultiGenFunction *chi2func = nullptr, unsigned int ncalls = 0);
80
81
82 /**
83 Update the fit result with a new minimization status
84 To be run only if same fit is performed with same configuration
85 Note that in this case MINOS is not re-run. If one wants to run also MINOS
86 a new result must be created
87 */
88 bool Update(const std::shared_ptr<ROOT::Math::Minimizer> & min, const ROOT::Fit::FitConfig & fconfig, bool isValid, unsigned int ncalls = 0);
89
90 /** minimization quantities **/
91
92 /// minimizer type
93 const std::string & MinimizerType() const { return fMinimType; }
94
95 /**
96 True if fit successful, otherwise false.
97 A fit is considered successful if the minimizer succeeded in finding the
98 minimum. It could happen that subsequent operations like error analysis (e.g. Minos)
99 failed. In that case the status can be still true if the original minimization algorithm
100 succeeded in finding the minimum.
101 One can query in that case the minimizer return status using Status().
102 It is responsibility to the Minimizer class to tag a found minimum as valid or not
103 and to produce also a status code.
104 */
105 bool IsValid() const { return fValid; }
106
107 /// True if a fit result does not exist (even invalid) with parameter values
108 bool IsEmpty() const { return (fParams.size() == 0); }
109
110 /// Return value of the objective function (chi2 or likelihood) used in the fit
111 double MinFcnValue() const { return fVal; }
112
113 ///Number of function calls to find minimum
114 unsigned int NCalls() const { return fNCalls; }
115
116 ///Expected distance from minimum
117 double Edm() const { return fEdm; }
118
119 /// get total number of parameters
120 unsigned int NTotalParameters() const { return fParams.size(); }
121 /// total number of parameters (abbreviation)
122 unsigned int NPar() const { return NTotalParameters(); }
123
124 /// get total number of free parameters
125 unsigned int NFreeParameters() const { return fNFree; }
126
127 /// minimizer status code
128 int Status() const { return fStatus; }
129
130 ///covariance matrix status code
131 /// using Minuit convention : =0 not calculated, =1 approximated, =2 made pos def , =3 accurate
132
133 int CovMatrixStatus() const { return fCovStatus; }
134
135 /** fitting quantities **/
136
137 /// Return pointer to model (fit) function with fitted parameter values.
138 /// Pointer is managed internally. I must not be deleted
140 return fFitFunc.get();
141 }
142
143 /// return BinData used in the fit (return a nullptr in case a different fit is done
144 /// or the data are not available
145 /// Pointer is managed internally, it must not be deleted
146 const BinData * FittedBinData() const;
147
148
149 /// Chi2 fit value
150 /// in case of likelihood must be computed ?
151 double Chi2() const { return fChi2; }
152
153 /// Number of degree of freedom
154 unsigned int Ndf() const { return fNdf; }
155
156 /// p value of the fit (chi2 probability)
157 double Prob() const;
158
159 /// parameter errors (return st::vector)
160 const std::vector<double> & Errors() const { return fErrors; }
161 /// parameter errors (return const pointer)
162 const double * GetErrors() const { return fErrors.empty() ? nullptr : &fErrors.front(); }
163
164 /// parameter values (return std::vector)
165 const std::vector<double> & Parameters() const { return fParams; }
166 /// parameter values (return const pointer)
167 const double * GetParams() const { return &fParams.front(); }
168
169 /// parameter value by index
170 double Value(unsigned int i) const { return fParams[i]; }
171 /// parameter value by index
172 double Parameter(unsigned int i) const { return fParams[i]; }
173
174 /// parameter error by index
175 // (NOTE: this due to conflict with TObject::Error cannot used in derived class which
176 // inherits from TObject. Use instead ParError (or Errors()[i] )
177 double Error(unsigned int i) const {
178 return (i < fErrors.size() ) ? fErrors[i] : 0;
179 }
180 /// parameter error by index
181 double ParError(unsigned int i) const {
182 return (i < fErrors.size() ) ? fErrors[i] : 0;
183 }
184
185 /// name of the parameter
186 std::string ParName(unsigned int i) const;
187
188 /// set the Minos errors for parameter i (called by the Fitter class when running Minos)
189 void SetMinosError(unsigned int i, double elow, double eup);
190
191 /// Set the chi2 and the ndf
192 /// This function should be called when using an external FCN for fitting
193 /// and one provides the chi2 and the number of fitting data points) to store
194 /// and have them printed in the FitResult class
195 void SetChi2AndNdf(double chi2, unsigned int npoints);
196
197 /// query if parameter i has the Minos error
198 bool HasMinosError(unsigned int i) const;
199
200 /// lower Minos error. If Minos has not run for parameter i return the parabolic error
201 double LowerError(unsigned int i) const;
202
203 /// upper Minos error. If Minos has not run for parameter i return the parabolic error
204 double UpperError(unsigned int i) const;
205
206 /// parameter global correlation coefficient
207 double GlobalCC(unsigned int i) const {
208 return (i < fGlobalCC.size() ) ? fGlobalCC[i] : -1;
209 }
210
211
212 /// retrieve covariance matrix element
213 double CovMatrix (unsigned int i, unsigned int j) const {
214 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
215 if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits
216 if ( j < i )
217 return fCovMatrix[j + i* (i+1) / 2];
218 else
219 return fCovMatrix[i + j* (j+1) / 2];
220 }
221
222 /// retrieve correlation elements
223 double Correlation(unsigned int i, unsigned int j ) const {
224 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
225 if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits
226 double tmp = CovMatrix(i,i)*CovMatrix(j,j);
227 return ( tmp > 0) ? CovMatrix(i,j)/ std::sqrt(tmp) : 0;
228 }
229
230 /// fill covariance matrix elements using a generic matrix class implementing operator(i,j)
231 /// the matrix must be previously allocates with right size (npar * npar)
232 template<class Matrix>
233 void GetCovarianceMatrix(Matrix & mat) const {
234 unsigned int npar = fErrors.size();
235 if (fCovMatrix.size() != npar*(npar+1)/2 ) return; // do nothing
236 for (unsigned int i = 0; i< npar; ++i) {
237 for (unsigned int j = 0; j<=i; ++j) {
238 mat(i,j) = fCovMatrix[j + i*(i+1)/2 ];
239 if (i != j) mat(j,i) = mat(i,j);
240 }
241 }
242 }
243
244 /// fill a correlation matrix elements using a generic symmetric matrix class implementing operator(i,j)
245 /// the matrix must be previously allocates with right size (npar * npar)
246 template<class Matrix>
247 void GetCorrelationMatrix(Matrix & mat) const {
248 unsigned int npar = fErrors.size();
249 if (fCovMatrix.size() != npar*(npar+1)/2) return; // do nothing
250 for (unsigned int i = 0; i< npar; ++i) {
251 for (unsigned int j = 0; j<=i; ++j) {
252 double tmp = fCovMatrix[i * (i +3)/2 ] * fCovMatrix[ j * (j+3)/2 ];
253 mat(i,j) = (tmp > 0) ? fCovMatrix[j + i*(i+1)/2 ] / std::sqrt(tmp) : 0;
254 if (i != j) mat(j,i) = mat(i,j);
255 }
256 }
257 }
258
259 /**
260 get confidence intervals for an array of n points x.
261 stride1 indicates the stride in the coordinate space while stride2 the stride in dimension space.
262 For 1-dim points : stride1=1, stride2=1
263 for multi-dim points arranged as (x0,x1,...,xN,y0,....yN) stride1=1 stride2=n
264 for multi-dim points arranged as (x0,y0,..,x1,y1,...,xN,yN,..) stride1=ndim, stride2=1
265
266 the confidence interval are returned in the array ci
267 cl is the desired confidence interval value
268 norm is a flag to control if the intervals need to be normalized to the chi2/ndf value
269 The intervals can be corrected optionally using the chi2/ndf value of the fit if a chi2 fit is performed.
270 This has changed since ROOT 6.14, before the interval were corrected by default.
271 */
272 void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl=0.95, bool norm = false ) const;
273
274 /**
275 evaluate confidence interval for the point specified in the passed data sets
276 the confidence interval are returned in the array ci
277 cl is the desired confidence interval value.
278 This method is maintained for backward compatibility and will be deprecated
279 */
280 void GetConfidenceIntervals(const BinData & data, double * ci, double cl=0.95, bool norm = false ) const;
281
282 /**
283 evaluate confidence interval for the data set used in the last fit
284 the confidence interval are returned as a vector of data points
285 */
286 std::vector<double> GetConfidenceIntervals(double cl=0.95, bool norm = false ) const;
287
288 /**
289 scan likelihood value of parameter and fill the given graph.
290 */
291 bool Scan(unsigned int ipar, unsigned int &npoints, double *pntsx, double *pntsy, double xmin = 0, double xmax = 0);
292
293 /**
294 create contour of two parameters around the minimum
295 pass as option confidence level: default is a value of 0.683
296 */
297 bool Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *pntsx, double *pntsy, double confLevel = 0.683);
298
299 /// get index for parameter name (return -1 if not found)
300 int Index(const std::string & name) const;
301
302 ///normalize errors using chi2/ndf for chi2 fits
303 void NormalizeErrors();
304
305 /// flag to check if errors are normalized
306 bool NormalizedErrors() const { return fNormalized; }
307
308 /// print the result and optionally covariance matrix and correlations
309 void Print(std::ostream & os, bool covmat = false) const;
310
311 ///print error matrix and correlations
312 void PrintCovMatrix(std::ostream & os) const;
313
314 /// query if a parameter is bound
315 bool IsParameterBound(unsigned int ipar) const;
316
317 /// query if a parameter is fixed
318 bool IsParameterFixed(unsigned int ipar) const;
319
320 /// retrieve parameter bounds - return false if parameter is not bound
321 bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const;
322
323
324 /// get name of parameter (deprecated)
325 std::string GetParameterName(unsigned int ipar) const {
326 return ParName(ipar);
327 }
328
329
330protected:
331
332
333 /// Return pointer non const pointer to model (fit) function with fitted parameter values.
334 /// used by Fitter class
335 std::shared_ptr<IModelFunction> ModelFunction() { return fFitFunc; }
336 void SetModelFunction(const std::shared_ptr<IModelFunction> & func) { fFitFunc = func; }
337
338 friend class Fitter;
339
340
341 bool fValid; ///< flag for indicating valid fit
342 bool fNormalized; ///< flag for indicating is errors are normalized
343 unsigned int fNFree; ///< number of fit free parameters (total parameters are in size of parameter vector)
344 unsigned int fNdf; ///< number of degree of freedom
345 unsigned int fNCalls; ///< number of function calls
346 int fStatus; ///< minimizer status code
347 int fCovStatus; ///< covariance matrix status code
348 double fVal; ///< minimum function value
349 double fEdm; ///< expected distance from minimum
350 double fChi2; ///< fit chi2 value (different than fval in case of chi2 fits)
351 std::shared_ptr<ROOT::Math::Minimizer> fMinimizer; ///<! minimizer object used for fitting
352 std::shared_ptr<ROOT::Math::IMultiGenFunction> fObjFunc; ///<! objective function used for fitting
353 std::shared_ptr<IModelFunction> fFitFunc; ///<! model function resulting from the fit.
354 std::shared_ptr<FitData> fFitData; ///<! data set used in the fit
355 std::map<unsigned int, bool> fFixedParams; ///< list of fixed parameters
356 std::map<unsigned int, unsigned int> fBoundParams; ///< list of limited parameters
357 std::vector<std::pair<double,double> > fParamBounds; ///< parameter bounds
358 std::vector<double> fParams; ///< parameter values. Size is total number of parameters
359 std::vector<double> fErrors; ///< errors
360 std::vector<double> fCovMatrix; ///< covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
361 std::vector<double> fGlobalCC; ///< global Correlation coefficient
362 std::map<unsigned int, std::pair<double,double> > fMinosErrors; ///< map contains the two Minos errors
363 std::string fMinimType; ///< string indicating type of minimizer
364 std::vector<std::string> fParNames; ///< parameter names (only with FCN only fits, when fFitFunc=0)
365
366};
367
368
369 } // end namespace Fit
370
371} // end namespace ROOT
372
373
374
375
376
377#endif /* ROOT_Fit_FitResult */
#define f(i)
Definition RSha256.hxx:104
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
char name[80]
Definition TGX11.cxx:110
float xmin
float xmax
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 containing the result of the fit and all the related information (fitted parameter values,...
Definition FitResult.h:47
std::vector< double > fGlobalCC
global Correlation coefficient
Definition FitResult.h:361
bool IsValid() const
True if fit successful, otherwise false.
Definition FitResult.h:105
bool IsEmpty() const
True if a fit result does not exist (even invalid) with parameter values.
Definition FitResult.h:108
unsigned int fNFree
number of fit free parameters (total parameters are in size of parameter vector)
Definition FitResult.h:343
std::map< unsigned int, unsigned int > fBoundParams
list of limited parameters
Definition FitResult.h:356
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 ...
double ParError(unsigned int i) const
parameter error by index
Definition FitResult.h:181
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, int fitType=1, const ROOT::Math::IMultiGenFunction *chi2func=nullptr, unsigned int ncalls=0)
Fill the fit result from a Minimizer instance after fitting Run also Minos if requested from the conf...
double UpperError(unsigned int i) const
upper Minos error. If Minos has not run for parameter i return the parabolic error
double fVal
minimum function value
Definition FitResult.h:348
double fEdm
expected distance from minimum
Definition FitResult.h:349
std::vector< double > fErrors
errors
Definition FitResult.h:359
bool NormalizedErrors() const
flag to check if errors are normalized
Definition FitResult.h:306
const std::vector< double > & Errors() const
parameter errors (return st::vector)
Definition FitResult.h:160
const double * GetErrors() const
parameter errors (return const pointer)
Definition FitResult.h:162
std::shared_ptr< ROOT::Math::Minimizer > fMinimizer
! minimizer object used for fitting
Definition FitResult.h:351
bool fValid
flag for indicating valid fit
Definition FitResult.h:341
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
unsigned int fNdf
number of degree of freedom
Definition FitResult.h:344
const double * GetParams() const
parameter values (return const pointer)
Definition FitResult.h:167
ROOT::Math::IParamMultiFunction IModelFunction
Definition FitResult.h:51
double Error(unsigned int i) const
parameter error by index
Definition FitResult.h:177
double CovMatrix(unsigned int i, unsigned int j) const
retrieve covariance matrix element
Definition FitResult.h:213
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.
double Value(unsigned int i) const
parameter value by index
Definition FitResult.h:170
int fCovStatus
covariance matrix status code
Definition FitResult.h:347
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.
const std::vector< double > & Parameters() const
parameter values (return std::vector)
Definition FitResult.h:165
FitResult()
Default constructor for an empty (non valid) fit result.
Definition FitResult.cxx:45
std::shared_ptr< FitData > fFitData
! data set used in the fit
Definition FitResult.h:354
const std::string & MinimizerType() const
minimization quantities
Definition FitResult.h:93
std::string GetParameterName(unsigned int ipar) const
get name of parameter (deprecated)
Definition FitResult.h:325
bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const
retrieve parameter bounds - return false if parameter is not bound
unsigned int Ndf() const
Number of degree of freedom.
Definition FitResult.h:154
double Chi2() const
Chi2 fit value in case of likelihood must be computed ?
Definition FitResult.h:151
std::vector< double > fParams
parameter values. Size is total number of parameters
Definition FitResult.h:358
std::vector< double > fCovMatrix
covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
Definition FitResult.h:360
void SetMinosError(unsigned int i, double elow, double eup)
set the Minos errors for parameter i (called by the Fitter class when running Minos)
void Print(std::ostream &os, bool covmat=false) const
print the result and optionally covariance matrix and correlations
double LowerError(unsigned int i) const
lower Minos error. If Minos has not run for parameter i return the parabolic error
virtual ~FitResult()
Destructor.
Definition FitResult.h:69
std::shared_ptr< IModelFunction > ModelFunction()
Return pointer non const pointer to model (fit) function with fitted parameter values.
Definition FitResult.h:335
void PrintCovMatrix(std::ostream &os) const
print error matrix and correlations
unsigned int fNCalls
number of function calls
Definition FitResult.h:345
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...
void GetCorrelationMatrix(Matrix &mat) const
fill a correlation matrix elements using a generic symmetric matrix class implementing operator(i,...
Definition FitResult.h:247
bool HasMinosError(unsigned int i) const
query if parameter i has the Minos error
std::vector< std::pair< double, double > > fParamBounds
parameter bounds
Definition FitResult.h:357
int fStatus
minimizer status code
Definition FitResult.h:346
double MinFcnValue() const
Return value of the objective function (chi2 or likelihood) used in the fit.
Definition FitResult.h:111
unsigned int NPar() const
total number of parameters (abbreviation)
Definition FitResult.h:122
int CovMatrixStatus() const
covariance matrix status code using Minuit convention : =0 not calculated, =1 approximated,...
Definition FitResult.h:133
double fChi2
fit chi2 value (different than fval in case of chi2 fits)
Definition FitResult.h:350
double Edm() const
Expected distance from minimum.
Definition FitResult.h:117
std::shared_ptr< IModelFunction > fFitFunc
! model function resulting from the fit.
Definition FitResult.h:353
std::map< unsigned int, bool > fFixedParams
list of fixed parameters
Definition FitResult.h:355
std::string fMinimType
string indicating type of minimizer
Definition FitResult.h:363
unsigned int NCalls() const
Number of function calls to find minimum.
Definition FitResult.h:114
double Correlation(unsigned int i, unsigned int j) const
retrieve correlation elements
Definition FitResult.h:223
std::shared_ptr< ROOT::Math::IMultiGenFunction > fObjFunc
! objective function used for fitting
Definition FitResult.h:352
unsigned int NTotalParameters() const
get total number of parameters
Definition FitResult.h:120
double Prob() const
p value of the fit (chi2 probability)
std::string ParName(unsigned int i) const
name of the parameter
void GetCovarianceMatrix(Matrix &mat) const
fill covariance matrix elements using a generic matrix class implementing operator(i,...
Definition FitResult.h:233
void NormalizeErrors()
normalize errors using chi2/ndf for chi2 fits
void SetModelFunction(const std::shared_ptr< IModelFunction > &func)
Definition FitResult.h:336
unsigned int NFreeParameters() const
get total number of free parameters
Definition FitResult.h:125
bool fNormalized
flag for indicating is errors are normalized
Definition FitResult.h:342
bool IsParameterBound(unsigned int ipar) const
query if a parameter is bound
double Parameter(unsigned int i) const
parameter value by index
Definition FitResult.h:172
int Status() const
minimizer status code
Definition FitResult.h:128
std::vector< std::string > fParNames
parameter names (only with FCN only fits, when fFitFunc=0)
Definition FitResult.h:364
std::map< unsigned int, std::pair< double, double > > fMinosErrors
map contains the two Minos errors
Definition FitResult.h:362
void SetChi2AndNdf(double chi2, unsigned int npoints)
Set the chi2 and the ndf This function should be called when using an external FCN for fitting and on...
const IModelFunction * FittedFunction() const
fitting quantities
Definition FitResult.h:139
double GlobalCC(unsigned int i) const
parameter global correlation coefficient
Definition FitResult.h:207
Fitter class, entry point for performing all type of fits.
Definition Fitter.h:77
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:61
RooCmdArg Minimizer(const char *type, const char *alg=nullptr)
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.
This file contains a specialised ROOT message handler to test for diagnostic in unit tests.