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