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