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.empty()); }
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 /// Return the Chi2 value after fitting
150 /// In case of unbinned fits (or not defined one, see the documentation of Fitter::FitFCN) return -1
151 /// In case of binned likelihood fits (Poisson Likelihood) return the 2 * negative log-likelihood ratio
152 /// using the definition of Baker-Cousins
153 double Chi2() const { return fChi2; }
154
155 /// Number of degree of freedom
156 unsigned int Ndf() const { return fNdf; }
157
158 /// p value of the fit (chi2 probability)
159 double Prob() const;
160
161 /// parameter errors (return st::vector)
162 const std::vector<double> & Errors() const { return fErrors; }
163 /// parameter errors (return const pointer)
164 const double * GetErrors() const { return fErrors.empty() ? nullptr : &fErrors.front(); }
165
166 /// parameter values (return std::vector)
167 const std::vector<double> & Parameters() const { return fParams; }
168 /// parameter values (return const pointer)
169 const double * GetParams() const { return &fParams.front(); }
170
171 /// parameter value by index
172 double Value(unsigned int i) const { return fParams[i]; }
173 /// parameter value by index
174 double Parameter(unsigned int i) const { return fParams[i]; }
175
176 /// parameter error by index
177 // (NOTE: this due to conflict with TObject::Error cannot used in derived class which
178 // inherits from TObject. Use instead ParError (or Errors()[i] )
179 double Error(unsigned int i) const {
180 return (i < fErrors.size() ) ? fErrors[i] : 0;
181 }
182 /// parameter error by index
183 double ParError(unsigned int i) const {
184 return (i < fErrors.size() ) ? fErrors[i] : 0;
185 }
186
187 /// name of the parameter
188 std::string ParName(unsigned int i) const;
189
190 /// set the Minos errors for parameter i (called by the Fitter class when running Minos)
191 void SetMinosError(unsigned int i, double elow, double eup);
192
193 /// Set the chi2 and the ndf
194 /// This function should be called when using an external FCN for fitting
195 /// and one provides the chi2 and the number of fitting data points) to store
196 /// and have them printed in the FitResult class
197 void SetChi2AndNdf(double chi2, unsigned int npoints);
198
199 /// query if parameter i has the Minos error
200 bool HasMinosError(unsigned int i) const;
201
202 /// lower Minos error. If Minos has not run for parameter i return the parabolic error
203 double LowerError(unsigned int i) const;
204
205 /// upper Minos error. If Minos has not run for parameter i return the parabolic error
206 double UpperError(unsigned int i) const;
207
208 /// parameter global correlation coefficient
209 double GlobalCC(unsigned int i) const {
210 return (i < fGlobalCC.size() ) ? fGlobalCC[i] : -1;
211 }
212
213
214 /// retrieve covariance matrix element
215 double CovMatrix (unsigned int i, unsigned int j) const {
216 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
217 if (fCovMatrix.empty()) return 0; // no matrix is available in case of non-valid fits
218 if ( j < i )
219 return fCovMatrix[j + i* (i+1) / 2];
220 else
221 return fCovMatrix[i + j* (j+1) / 2];
222 }
223
224 /// retrieve correlation elements
225 double Correlation(unsigned int i, unsigned int j ) const {
226 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
227 if (fCovMatrix.empty()) return 0; // no matrix is available in case of non-valid fits
228 double tmp = CovMatrix(i,i)*CovMatrix(j,j);
229 return ( tmp > 0) ? CovMatrix(i,j)/ std::sqrt(tmp) : 0;
230 }
231
232 /// fill covariance matrix elements using a generic matrix class implementing operator(i,j)
233 /// the matrix must be previously allocates with right size (npar * npar)
234 template<class Matrix>
235 void GetCovarianceMatrix(Matrix & mat) const {
236 unsigned int npar = fErrors.size();
237 if (fCovMatrix.size() != npar*(npar+1)/2 ) return; // do nothing
238 for (unsigned int i = 0; i< npar; ++i) {
239 for (unsigned int j = 0; j<=i; ++j) {
240 mat(i,j) = fCovMatrix[j + i*(i+1)/2 ];
241 if (i != j) mat(j,i) = mat(i,j);
242 }
243 }
244 }
245
246 /// fill a correlation matrix elements using a generic symmetric matrix class implementing operator(i,j)
247 /// the matrix must be previously allocates with right size (npar * npar)
248 template<class Matrix>
249 void GetCorrelationMatrix(Matrix & mat) const {
250 unsigned int npar = fErrors.size();
251 if (fCovMatrix.size() != npar*(npar+1)/2) return; // do nothing
252 for (unsigned int i = 0; i< npar; ++i) {
253 for (unsigned int j = 0; j<=i; ++j) {
254 double tmp = fCovMatrix[i * (i +3)/2 ] * fCovMatrix[ j * (j+3)/2 ];
255 mat(i,j) = (tmp > 0) ? fCovMatrix[j + i*(i+1)/2 ] / std::sqrt(tmp) : 0;
256 if (i != j) mat(j,i) = mat(i,j);
257 }
258 }
259 }
260
261 /**
262 get confidence intervals for an array of n points x.
263 stride1 indicates the stride in the coordinate space while stride2 the stride in dimension space.
264 For 1-dim points : stride1=1, stride2=1
265 for multi-dim points arranged as (x0,x1,...,xN,y0,....yN) stride1=1 stride2=n
266 for multi-dim points arranged as (x0,y0,..,x1,y1,...,xN,yN,..) stride1=ndim, stride2=1
267
268 the confidence interval are returned in the array ci
269 cl is the desired confidence interval value
270 norm is a flag to control if the intervals need to be normalized to the chi2/ndf value
271 The intervals can be corrected optionally using the chi2/ndf value of the fit if a chi2 fit is performed.
272 This has changed since ROOT 6.14, before the interval were corrected by default.
273 */
274 void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl=0.95, bool norm = false ) const;
275
276 /**
277 evaluate confidence interval for the point specified in the passed data sets
278 the confidence interval are returned in the array ci
279 cl is the desired confidence interval value.
280 This method is maintained for backward compatibility and will be deprecated
281 */
282 void GetConfidenceIntervals(const BinData & data, double * ci, double cl=0.95, bool norm = false ) const;
283
284 /**
285 evaluate confidence interval for the data set used in the last fit
286 the confidence interval are returned as a vector of data points
287 */
288 std::vector<double> GetConfidenceIntervals(double cl=0.95, bool norm = false ) const;
289
290 /**
291 scan likelihood value of parameter and fill the given graph.
292 */
293 bool Scan(unsigned int ipar, unsigned int &npoints, double *pntsx, double *pntsy, double xmin = 0, double xmax = 0);
294
295 /**
296 create contour of two parameters around the minimum
297 pass as option confidence level: default is a value of 0.683
298 */
299 bool Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *pntsx, double *pntsy, double confLevel = 0.683);
300
301 /// get index for parameter name (return -1 if not found)
302 int Index(const std::string & name) const;
303
304 ///normalize errors using chi2/ndf for chi2 fits
305 void NormalizeErrors();
306
307 /// flag to check if errors are normalized
308 bool NormalizedErrors() const { return fNormalized; }
309
310 /// print the result and optionally covariance matrix and correlations
311 void Print(std::ostream & os, bool covmat = false) const;
312
313 ///print error matrix and correlations
314 void PrintCovMatrix(std::ostream & os) const;
315
316 /// query if a parameter is bound
317 bool IsParameterBound(unsigned int ipar) const;
318
319 /// query if a parameter is fixed
320 bool IsParameterFixed(unsigned int ipar) const;
321
322 /// retrieve parameter bounds - return false if parameter is not bound
323 bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const;
324
325
326 /// get name of parameter (deprecated)
327 std::string GetParameterName(unsigned int ipar) const {
328 return ParName(ipar);
329 }
330
331
332protected:
333
334
335 /// Return pointer non const pointer to model (fit) function with fitted parameter values.
336 /// used by Fitter class
337 std::shared_ptr<IModelFunction> ModelFunction() { return fFitFunc; }
338 void SetModelFunction(const std::shared_ptr<IModelFunction> & func) { fFitFunc = func; }
339
340 friend class Fitter;
341
342
343 bool fValid; ///< flag for indicating valid fit
344 bool fNormalized; ///< flag for indicating is errors are normalized
345 unsigned int fNFree; ///< number of fit free parameters (total parameters are in size of parameter vector)
346 unsigned int fNdf; ///< number of degree of freedom
347 unsigned int fNCalls; ///< number of function calls
348 int fStatus; ///< minimizer status code
349 int fCovStatus; ///< covariance matrix status code
350 double fVal; ///< minimum function value
351 double fEdm; ///< expected distance from minimum
352 double fChi2; ///< fit chi2 value (different than fval in case of chi2 fits)
353 std::shared_ptr<ROOT::Math::Minimizer> fMinimizer; ///<! minimizer object used for fitting
354 std::shared_ptr<ROOT::Math::IMultiGenFunction> fObjFunc; ///<! objective function used for fitting
355 std::shared_ptr<IModelFunction> fFitFunc; ///<! model function resulting from the fit.
356 std::shared_ptr<FitData> fFitData; ///<! data set used in the fit
357 std::map<unsigned int, bool> fFixedParams; ///< list of fixed parameters
358 std::map<unsigned int, unsigned int> fBoundParams; ///< list of limited parameters
359 std::vector<std::pair<double,double> > fParamBounds; ///< parameter bounds
360 std::vector<double> fParams; ///< parameter values. Size is total number of parameters
361 std::vector<double> fErrors; ///< errors
362 std::vector<double> fCovMatrix; ///< covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
363 std::vector<double> fGlobalCC; ///< global Correlation coefficient
364 std::map<unsigned int, std::pair<double,double> > fMinosErrors; ///< map contains the two Minos errors
365 std::string fMinimType; ///< string indicating type of minimizer
366 std::vector<std::string> fParNames; ///< parameter names (only with FCN only fits, when fFitFunc=0)
367
368};
369
370
371 } // end namespace Fit
372
373} // end namespace ROOT
374
375
376
377
378
379#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:363
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:345
std::map< unsigned int, unsigned int > fBoundParams
list of limited parameters
Definition FitResult.h:358
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:183
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:350
double fEdm
expected distance from minimum
Definition FitResult.h:351
std::vector< double > fErrors
errors
Definition FitResult.h:361
bool NormalizedErrors() const
flag to check if errors are normalized
Definition FitResult.h:308
const std::vector< double > & Errors() const
parameter errors (return st::vector)
Definition FitResult.h:162
const double * GetErrors() const
parameter errors (return const pointer)
Definition FitResult.h:164
std::shared_ptr< ROOT::Math::Minimizer > fMinimizer
! minimizer object used for fitting
Definition FitResult.h:353
bool fValid
flag for indicating valid fit
Definition FitResult.h:343
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
unsigned int fNdf
number of degree of freedom
Definition FitResult.h:346
const double * GetParams() const
parameter values (return const pointer)
Definition FitResult.h:169
ROOT::Math::IParamMultiFunction IModelFunction
Definition FitResult.h:51
double Error(unsigned int i) const
parameter error by index
Definition FitResult.h:179
double CovMatrix(unsigned int i, unsigned int j) const
retrieve covariance matrix element
Definition FitResult.h:215
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:172
int fCovStatus
covariance matrix status code
Definition FitResult.h:349
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:167
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:356
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:327
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:156
double Chi2() const
Return the Chi2 value after fitting In case of unbinned fits (or not defined one, see the documentati...
Definition FitResult.h:153
std::vector< double > fParams
parameter values. Size is total number of parameters
Definition FitResult.h:360
std::vector< double > fCovMatrix
covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
Definition FitResult.h:362
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:337
void PrintCovMatrix(std::ostream &os) const
print error matrix and correlations
unsigned int fNCalls
number of function calls
Definition FitResult.h:347
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:249
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:359
int fStatus
minimizer status code
Definition FitResult.h:348
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:352
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:355
std::map< unsigned int, bool > fFixedParams
list of fixed parameters
Definition FitResult.h:357
std::string fMinimType
string indicating type of minimizer
Definition FitResult.h:365
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:225
std::shared_ptr< ROOT::Math::IMultiGenFunction > fObjFunc
! objective function used for fitting
Definition FitResult.h:354
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:235
void NormalizeErrors()
normalize errors using chi2/ndf for chi2 fits
void SetModelFunction(const std::shared_ptr< IModelFunction > &func)
Definition FitResult.h:338
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:344
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:174
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:366
std::map< unsigned int, std::pair< double, double > > fMinosErrors
map contains the two Minos errors
Definition FitResult.h:364
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:209
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.