Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
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, bool binFit = true, 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 /// query if parameter i has the Minos error
192 bool HasMinosError(unsigned int i) const;
193
194 /// lower Minos error. If Minos has not run for parameter i return the parabolic error
195 double LowerError(unsigned int i) const;
196
197 /// upper Minos error. If Minos has not run for parameter i return the parabolic error
198 double UpperError(unsigned int i) const;
199
200 /// parameter global correlation coefficient
201 double GlobalCC(unsigned int i) const {
202 return (i < fGlobalCC.size() ) ? fGlobalCC[i] : -1;
203 }
204
205
206 /// retrieve covariance matrix element
207 double CovMatrix (unsigned int i, unsigned int j) const {
208 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
209 if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits
210 if ( j < i )
211 return fCovMatrix[j + i* (i+1) / 2];
212 else
213 return fCovMatrix[i + j* (j+1) / 2];
214 }
215
216 /// retrieve correlation elements
217 double Correlation(unsigned int i, unsigned int j ) const {
218 if ( i >= fErrors.size() || j >= fErrors.size() ) return 0;
219 if (fCovMatrix.size() == 0) return 0; // no matrix is available in case of non-valid fits
220 double tmp = CovMatrix(i,i)*CovMatrix(j,j);
221 return ( tmp > 0) ? CovMatrix(i,j)/ std::sqrt(tmp) : 0;
222 }
223
224 /// fill covariance matrix elements using a generic matrix class implementing operator(i,j)
225 /// the matrix must be previously allocates with right size (npar * npar)
226 template<class Matrix>
227 void GetCovarianceMatrix(Matrix & mat) const {
228 unsigned int npar = fErrors.size();
229 if (fCovMatrix.size() != npar*(npar+1)/2 ) return; // do nothing
230 for (unsigned int i = 0; i< npar; ++i) {
231 for (unsigned int j = 0; j<=i; ++j) {
232 mat(i,j) = fCovMatrix[j + i*(i+1)/2 ];
233 if (i != j) mat(j,i) = mat(i,j);
234 }
235 }
236 }
237
238 /// fill a correlation matrix elements using a generic symmetric matrix class implementing operator(i,j)
239 /// the matrix must be previously allocates with right size (npar * npar)
240 template<class Matrix>
241 void GetCorrelationMatrix(Matrix & mat) const {
242 unsigned int npar = fErrors.size();
243 if (fCovMatrix.size() != npar*(npar+1)/2) return; // do nothing
244 for (unsigned int i = 0; i< npar; ++i) {
245 for (unsigned int j = 0; j<=i; ++j) {
246 double tmp = fCovMatrix[i * (i +3)/2 ] * fCovMatrix[ j * (j+3)/2 ];
247 mat(i,j) = (tmp > 0) ? fCovMatrix[j + i*(i+1)/2 ] / std::sqrt(tmp) : 0;
248 if (i != j) mat(j,i) = mat(i,j);
249 }
250 }
251 }
252
253 /**
254 get confidence intervals for an array of n points x.
255 stride1 indicates the stride in the coordinate space while stride2 the stride in dimension space.
256 For 1-dim points : stride1=1, stride2=1
257 for multi-dim points arranged as (x0,x1,...,xN,y0,....yN) stride1=1 stride2=n
258 for multi-dim points arranged as (x0,y0,..,x1,y1,...,xN,yN,..) stride1=ndim, stride2=1
259
260 the confidence interval are returned in the array ci
261 cl is the desired confidence interval value
262 norm is a flag to control if the intervals need to be normalized to the chi2/ndf value
263 The intervals can be corrected optionally using the chi2/ndf value of the fit if a chi2 fit is performed.
264 This has changed since ROOT 6.14, before the interval were corrected by default.
265 */
266 void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl=0.95, bool norm = false ) const;
267
268 /**
269 evaluate confidence interval for the point specified in the passed data sets
270 the confidence interval are returned in the array ci
271 cl is the desired confidence interval value.
272 This method is maintained for backward compatibility and will be deprecated
273 */
274 void GetConfidenceIntervals(const BinData & data, double * ci, double cl=0.95, bool norm = false ) const;
275
276 /**
277 evaluate confidence interval for the data set used in the last fit
278 the confidence interval are returned as a vector of data points
279 */
280 std::vector<double> GetConfidenceIntervals(double cl=0.95, bool norm = false ) const;
281
282 /**
283 scan likelihood value of parameter and fill the given graph.
284 */
285 bool Scan(unsigned int ipar, unsigned int &npoints, double *pntsx, double *pntsy, double xmin = 0, double xmax = 0);
286
287 /**
288 create contour of two parameters around the minimum
289 pass as option confidence level: default is a value of 0.683
290 */
291 bool Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *pntsx, double *pntsy, double confLevel = 0.683);
292
293 /// get index for parameter name (return -1 if not found)
294 int Index(const std::string & name) const;
295
296 ///normalize errors using chi2/ndf for chi2 fits
297 void NormalizeErrors();
298
299 /// flag to check if errors are normalized
300 bool NormalizedErrors() const { return fNormalized; }
301
302 /// print the result and optionally covariance matrix and correlations
303 void Print(std::ostream & os, bool covmat = false) const;
304
305 ///print error matrix and correlations
306 void PrintCovMatrix(std::ostream & os) const;
307
308 /// query if a parameter is bound
309 bool IsParameterBound(unsigned int ipar) const;
310
311 /// query if a parameter is fixed
312 bool IsParameterFixed(unsigned int ipar) const;
313
314 /// retrieve parameter bounds - return false if parameter is not bound
315 bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const;
316
317
318 /// get name of parameter (deprecated)
319 std::string GetParameterName(unsigned int ipar) const {
320 return ParName(ipar);
321 }
322
323
324protected:
325
326
327 /// Return pointer non const pointer to model (fit) function with fitted parameter values.
328 /// used by Fitter class
329 std::shared_ptr<IModelFunction> ModelFunction() { return fFitFunc; }
330 void SetModelFunction(const std::shared_ptr<IModelFunction> & func) { fFitFunc = func; }
331
332 friend class Fitter;
333
334
335 bool fValid; ///< flag for indicating valid fit
336 bool fNormalized; ///< flag for indicating is errors are normalized
337 unsigned int fNFree; ///< number of fit free parameters (total parameters are in size of parameter vector)
338 unsigned int fNdf; ///< number of degree of freedom
339 unsigned int fNCalls; ///< number of function calls
340 int fStatus; ///< minimizer status code
341 int fCovStatus; ///< covariance matrix status code
342 double fVal; ///< minimum function value
343 double fEdm; ///< expected distance from minimum
344 double fChi2; ///< fit chi2 value (different than fval in case of chi2 fits)
345 std::shared_ptr<ROOT::Math::Minimizer> fMinimizer; ///<! minimizer object used for fitting
346 std::shared_ptr<ROOT::Math::IMultiGenFunction> fObjFunc; ///<! objective function used for fitting
347 std::shared_ptr<IModelFunction> fFitFunc; ///<! model function resulting from the fit.
348 std::shared_ptr<FitData> fFitData; ///<! data set used in the fit
349 std::map<unsigned int, bool> fFixedParams; ///< list of fixed parameters
350 std::map<unsigned int, unsigned int> fBoundParams; ///< list of limited parameters
351 std::vector<std::pair<double,double> > fParamBounds; ///< parameter bounds
352 std::vector<double> fParams; ///< parameter values. Size is total number of parameters
353 std::vector<double> fErrors; ///< errors
354 std::vector<double> fCovMatrix; ///< covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
355 std::vector<double> fGlobalCC; ///< global Correlation coefficient
356 std::map<unsigned int, std::pair<double,double> > fMinosErrors; ///< map contains the two Minos errors
357 std::string fMinimType; ///< string indicating type of minimizer
358 std::vector<std::string> fParNames; ///< parameter names (only with FCN only fits, when fFitFunc=0)
359
360};
361
362
363 } // end namespace Fit
364
365} // end namespace ROOT
366
367
368
369
370
371#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:355
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=nullptr, unsigned int ncalls=0)
Fill the fit result from a Minimizer instance after fitting Run also Minos if requested from the conf...
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:337
std::map< unsigned int, unsigned int > fBoundParams
list of limited parameters
Definition FitResult.h:350
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
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:342
double fEdm
expected distance from minimum
Definition FitResult.h:343
std::vector< double > fErrors
errors
Definition FitResult.h:353
bool NormalizedErrors() const
flag to check if errors are normalized
Definition FitResult.h:300
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:345
bool fValid
flag for indicating valid fit
Definition FitResult.h:335
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
unsigned int fNdf
number of degree of freedom
Definition FitResult.h:338
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:207
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:341
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:348
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:319
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:352
std::vector< double > fCovMatrix
covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
Definition FitResult.h:354
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:329
void PrintCovMatrix(std::ostream &os) const
print error matrix and correlations
unsigned int fNCalls
number of function calls
Definition FitResult.h:339
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:241
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:351
int fStatus
minimizer status code
Definition FitResult.h:340
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:344
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:347
std::map< unsigned int, bool > fFixedParams
list of fixed parameters
Definition FitResult.h:349
std::string fMinimType
string indicating type of minimizer
Definition FitResult.h:357
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:217
std::shared_ptr< ROOT::Math::IMultiGenFunction > fObjFunc
! objective function used for fitting
Definition FitResult.h:346
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:227
void NormalizeErrors()
normalize errors using chi2/ndf for chi2 fits
void SetModelFunction(const std::shared_ptr< IModelFunction > &func)
Definition FitResult.h:330
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:336
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:358
std::map< unsigned int, std::pair< double, double > > fMinosErrors
map contains the two Minos errors
Definition FitResult.h:356
const IModelFunction * FittedFunction() const
fitting quantities
Definition FitResult.h:139
double GlobalCC(unsigned int i) const
parameter global correlation coefficient
Definition FitResult.h:201
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=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.