Logo ROOT   6.10/09
Reference Guide
Fitter.h
Go to the documentation of this file.
1 // @(#)root/mathcore:$Id$
2 // Author: L. Moneta Wed Aug 30 11:05:19 2006
3 
4 /**********************************************************************
5  * *
6  * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
7  * *
8  * *
9  **********************************************************************/
10 
11 // Header file for class Fitter
12 
13 #ifndef ROOT_Fit_Fitter
14 #define ROOT_Fit_Fitter
15 
16 /**
17 @defgroup Fit Fitting and Parameter Estimation
18 
19 Classes used for fitting (regression analysis) and estimation of parameter values given a data sample.
20 
21 @ingroup MathCore
22 
23 */
24 
25 #include "Fit/BinData.h"
26 #include "Fit/UnBinData.h"
27 #include "Fit/FitConfig.h"
28 #include "Fit/FitResult.h"
29 #include "Math/IParamFunctionfwd.h"
30 #include <memory>
31 
32 
33 namespace ROOT {
34 
35 
36  namespace Math {
37  class Minimizer;
38 
39  // should maybe put this in a FitMethodFunctionfwd file
40  template<class FunctionType> class BasicFitMethodFunction;
41 
42  // define the normal and gradient function
45 
46  }
47 
48  /**
49  Namespace for the fitting classes
50  @ingroup Fit
51  */
52 
53  namespace Fit {
54 
55 /**
56  @defgroup FitMain User Fitting classes
57 
58  Main Classes used for fitting a given data set
59  @ingroup Fit
60 */
61 
62 
63 //___________________________________________________________________________________
64 /**
65  Fitter class, entry point for performing all type of fits.
66  Fits are performed using the generic ROOT::Fit::Fitter::Fit method.
67  The inputs are the data points and a model function (using a ROOT::Math::IParamFunction)
68  The result of the fit is returned and kept internally in the ROOT::Fit::FitResult class.
69  The configuration of the fit (parameters, options, etc...) are specified in the
70  ROOT::Math::FitConfig class.
71  After fitting the config of the fit will be modified to have the new values the resulting
72  parameter of the fit with step sizes equal to the errors. FitConfig can be preserved with
73  initial parameters by calling FitConfig.SetUpdateAfterFit(false);
74 
75  @ingroup FitMain
76 */
77 class Fitter {
78 
79 public:
80 
85 
88 
89 
90  /**
91  Default constructor
92  */
93  Fitter ();
94 
95  /**
96  Constructor from a result
97  */
98  Fitter (const std::shared_ptr<FitResult> & result);
99 
100 
101  /**
102  Destructor
103  */
104  ~Fitter ();
105 
106 private:
107 
108  /**
109  Copy constructor (disabled, class is not copyable)
110  */
111  Fitter(const Fitter &);
112 
113  /**
114  Assignment operator (disabled, class is not copyable)
115  */
116  Fitter & operator = (const Fitter & rhs);
117 
118 
119 public:
120 
121  /**
122  fit a data set using any generic model function
123  If data set is binned a least square fit is performed
124  If data set is unbinned a maximum likelihood fit (not extended) is done
125  Pre-requisite on the function:
126  it must implement the 1D or multidimensional parametric function interface
127  */
128  template < class Data , class Function>
129  bool Fit( const Data & data, const Function & func ) {
130  SetFunction(func);
131  return Fit(data);
132  }
133 
134  /**
135  Fit a binned data set using a least square fit (default method)
136  */
137  bool Fit(const BinData & data) {
138  SetData(data);
139  return DoLeastSquareFit();
140  }
141  bool Fit(const std::shared_ptr<BinData> & data) {
142  SetData(data);
143  return DoLeastSquareFit();
144  }
145 
146  /**
147  Fit a binned data set using a least square fit
148  */
149  bool LeastSquareFit(const BinData & data) {
150  return Fit(data);
151  }
152 
153  /**
154  fit an unbinned data set using loglikelihood method
155  */
156  bool Fit(const UnBinData & data, bool extended = false) {
157  SetData(data);
158  return DoUnbinnedLikelihoodFit(extended);
159  }
160 
161  /**
162  Binned Likelihood fit. Default is extended
163  */
164  bool LikelihoodFit(const BinData & data, bool extended = true) {
165  SetData(data);
166  return DoBinnedLikelihoodFit(extended);
167  }
168  bool LikelihoodFit(const std::shared_ptr<BinData> & data, bool extended = true) {
169  SetData(data);
170  return DoBinnedLikelihoodFit(extended);
171  }
172  /**
173  Unbinned Likelihood fit. Default is not extended
174  */
175  bool LikelihoodFit(const UnBinData & data, bool extended = false) {
176  SetData(data);
177  return DoUnbinnedLikelihoodFit(extended);
178  }
179  bool LikelihoodFit(const std::shared_ptr<UnBinData> & data, bool extended = false) {
180  SetData(data);
181  return DoUnbinnedLikelihoodFit(extended);
182  }
183 
184 
185  /**
186  fit a data set using any generic model function
187  Pre-requisite on the function:
188  */
189  template < class Data , class Function>
190  bool LikelihoodFit( const Data & data, const Function & func, bool extended) {
191  SetFunction(func);
192  return LikelihoodFit(data, extended);
193  }
194 
195  /**
196  do a linear fit on a set of bin-data
197  */
198  bool LinearFit(const BinData & data) {
199  SetData(data);
200  return DoLinearFit();
201  }
202  bool LinearFit(const std::shared_ptr<BinData> & data) {
203  SetData(data);
204  return DoLinearFit();
205  }
206 
207 
208  /**
209  Fit using the a generic FCN function as a C++ callable object implementing
210  double () (const double *)
211  Note that the function dimension (i.e. the number of parameter) is needed in this case
212  For the options see documentation for following methods FitFCN(IMultiGenFunction & fcn,..)
213  */
214  template <class Function>
215  bool FitFCN(unsigned int npar, Function & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false);
216 
217  /**
218  Set a generic FCN function as a C++ callable object implementing
219  double () (const double *)
220  Note that the function dimension (i.e. the number of parameter) is needed in this case
221  For the options see documentation for following methods FitFCN(IMultiGenFunction & fcn,..)
222  */
223  template <class Function>
224  bool SetFCN(unsigned int npar, Function & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false);
225 
226  /**
227  Fit using the given FCN function represented by a multi-dimensional function interface
228  (ROOT::Math::IMultiGenFunction).
229  Give optionally the initial arameter values, data size to have the fit Ndf correctly
230  set in the FitResult and flag specifying if it is a chi2 fit.
231  Note that if the parameters values are not given (params=0) the
232  current parameter settings are used. The parameter settings can be created before
233  by using the FitConfig::SetParamsSetting. If they have not been created they are created
234  automatically when the params pointer is not zero.
235  Note that passing a params != 0 will set the parameter settings to the new value AND also the
236  step sizes to some pre-defined value (stepsize = 0.3 * abs(parameter_value) )
237  */
238  bool FitFCN(const ROOT::Math::IMultiGenFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool
239  chi2fit = false);
240 
241  /**
242  Fit using a FitMethodFunction interface. Same as method above, but now extra information
243  can be taken from the function class
244  */
245  bool FitFCN(const ROOT::Math::FitMethodFunction & fcn, const double * params = 0);
246 
247  /**
248  Set the FCN function represented by a multi-dimensional function interface
249  (ROOT::Math::IMultiGenFunction) and optionally the initial parameters
250  See also note above for the initial parameters for FitFCN
251  */
252  bool SetFCN(const ROOT::Math::IMultiGenFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false);
253 
254  /**
255  Set the objective function (FCN) using a FitMethodFunction interface.
256  Same as method above, but now extra information can be taken from the function class
257  */
258  bool SetFCN(const ROOT::Math::FitMethodFunction & fcn, const double * params = 0);
259 
260  /**
261  Fit using the given FCN function representing a multi-dimensional gradient function
262  interface (ROOT::Math::IMultiGradFunction). In this case the minimizer will use the
263  gradient information provided by the function.
264  For the options same consideration as in the previous method
265  */
266  bool FitFCN(const ROOT::Math::IMultiGradFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false);
267 
268  /**
269  Fit using a FitMethodGradFunction interface. Same as method above, but now extra information
270  can be taken from the function class
271  */
272  bool FitFCN(const ROOT::Math::FitMethodGradFunction & fcn, const double * params = 0);
273 
274  /**
275  Set the FCN function represented by a multi-dimensional gradient function interface
276  (ROOT::Math::IMultiGenFunction) and optionally the initial parameters
277  See also note above for the initial parameters for FitFCN
278  */
279  bool SetFCN(const ROOT::Math::IMultiGradFunction & fcn, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false);
280 
281  /**
282  Set the objective function (FCN) using a FitMethodGradFunction interface.
283  Same as method above, but now extra information can be taken from the function class
284  */
285  bool SetFCN(const ROOT::Math::FitMethodGradFunction & fcn, const double * params = 0);
286 
287 
288  /**
289  fit using user provided FCN with Minuit-like interface
290  If npar = 0 it is assumed that the parameters are specified in the parameter settings created before
291  For the options same consideration as in the previous method
292  */
293  typedef void (* MinuitFCN_t )(int &npar, double *gin, double &f, double *u, int flag);
294  bool FitFCN( MinuitFCN_t fcn, int npar = 0, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false);
295 
296  /**
297  set objective function using user provided FCN with Minuit-like interface
298  If npar = 0 it is assumed that the parameters are specified in the parameter settings created before
299  For the options same consideration as in the previous method
300  */
301  bool SetFCN( MinuitFCN_t fcn, int npar = 0, const double * params = 0, unsigned int dataSize = 0, bool chi2fit = false);
302 
303  /**
304  Perform a fit with the previously set FCN function. Require SetFCN before
305  */
306  bool FitFCN();
307 
308  /**
309  Perform a simple FCN evaluation. FitResult will be modified and contain the value of the FCN
310  */
311  bool EvalFCN();
312 
313 
314 
315  /**
316  Set the fitted function (model function) from a parametric function interface
317  */
318  void SetFunction(const IModelFunction & func, bool useGradient = false);
319  /**
320  Set the fitted function from a parametric 1D function interface
321  */
322  void SetFunction(const IModel1DFunction & func, bool useGradient = false);
323 
324  /**
325  Set the fitted function (model function) from a parametric gradient function interface
326  */
327  void SetFunction(const IGradModelFunction & func, bool useGradient = true);
328  /**
329  Set the fitted function from 1D gradient parametric function interface
330  */
331  void SetFunction(const IGradModel1DFunction & func, bool useGradient = true);
332 
333 
334  /**
335  get fit result
336  */
337  const FitResult & Result() const {
338  assert( fResult.get() );
339  return *fResult;
340  }
341 
342 
343  /**
344  perform an error analysis on the result using the Hessian
345  Errors are obtaied from the inverse of the Hessian matrix
346  To be called only after fitting and when a minimizer supporting the Hessian calculations is used
347  otherwise an error (false) is returned.
348  A new FitResult with the Hessian result will be produced
349  */
350  bool CalculateHessErrors();
351 
352  /**
353  perform an error analysis on the result using MINOS
354  To be called only after fitting and when a minimizer supporting MINOS is used
355  otherwise an error (false) is returned.
356  The result will be appended in the fit result class
357  Optionally a vector of parameter indeces can be passed for selecting
358  the parameters to analyse using FitConfig::SetMinosErrors
359  */
360  bool CalculateMinosErrors();
361 
362  /**
363  access to the fit configuration (const method)
364  */
365  const FitConfig & Config() const { return fConfig; }
366 
367  /**
368  access to the configuration (non const method)
369  */
370  FitConfig & Config() { return fConfig; }
371 
372  /**
373  query if fit is binned. In cse of false teh fit can be unbinned
374  or is not defined (like in case of fitting through a ::FitFCN)
375  */
376  bool IsBinFit() const { return fBinFit; }
377 
378  /**
379  return pointer to last used minimizer
380  (is NULL in case fit is not yet done)
381  This pointer is guranteed to be valid as far as the fitter class is valid and a new fit is not redone.
382  To be used only after fitting.
383  The pointer should not be stored and will be invalided after performing a new fitting.
384  In this case a new instance of ROOT::Math::Minimizer will be re-created and can be
385  obtained calling again GetMinimizer()
386  */
387  ROOT::Math::Minimizer * GetMinimizer() const { return fMinimizer.get(); }
388 
389  /**
390  return pointer to last used objective function
391  (is NULL in case fit is not yet done)
392  This pointer will be valid as far as the fitter class
393  has not been deleted. To be used after the fitting.
394  The pointer should not be stored and will be invalided after performing a new fitting.
395  In this case a new instance of the function pointer will be re-created and can be
396  obtained calling again GetFCN()
397  */
398  ROOT::Math::IMultiGenFunction * GetFCN() const { return fObjFunction.get(); }
399 
400 
401  /**
402  apply correction in the error matrix for the weights for likelihood fits
403  This method can be called only after a fit. The
404  passed function (loglw2) is a log-likelihood function impelemented using the
405  sum of weight squared
406  When using FitConfig.SetWeightCorrection() this correction is applied
407  automatically when doing a likelihood fit (binned or unbinned)
408  */
409  bool ApplyWeightCorrection(const ROOT::Math::IMultiGenFunction & loglw2, bool minimizeW2L=false);
410 
411 
412 protected:
413 
414 
415  /// least square fit
416  bool DoLeastSquareFit();
417  /// binned likelihood fit
418  bool DoBinnedLikelihoodFit( bool extended = true);
419  /// un-binned likelihood fit
420  bool DoUnbinnedLikelihoodFit( bool extended = false);
421  /// linear least square fit
422  bool DoLinearFit();
423 
424  // initialize the minimizer
425  bool DoInitMinimizer();
426  /// do minimization
427  bool DoMinimization(const BaseFunc & f, const ROOT::Math::IMultiGenFunction * chifunc = 0);
428  // do minimization after having set obj function
429  bool DoMinimization(const ROOT::Math::IMultiGenFunction * chifunc = 0);
430  // update config after fit
431  void DoUpdateFitConfig();
432  // get function calls from the FCN
433  int GetNCallsFromFCN();
434 
435 
436  //set data for the fit
437  void SetData(const FitData & data) {
438  fData = std::shared_ptr<FitData>(const_cast<FitData*>(&data),DummyDeleter<FitData>());
439  }
440  // set data and function without cloning them
441  void SetFunctionAndData(const IModelFunction & func, const FitData & data) {
442  SetData(data);
443  fFunc = std::shared_ptr<IModelFunction>(const_cast<IModelFunction*>(&func),DummyDeleter<IModelFunction>());
444  }
445 
446  //set data for the fit using a shared ptr
447  template <class Data>
448  void SetData(const std::shared_ptr<Data> & data) {
449  fData = std::static_pointer_cast<Data>(data);
450  }
451 
452  /// look at the user provided FCN and get data and model function is
453  /// they derive from ROOT::Fit FCN classes
454  void ExamineFCN();
455 
456 
457  /// internal functions to get data set and model function from FCN
458  /// useful for fits done with customized FCN classes
459  template <class ObjFuncType>
460  bool GetDataFromFCN();
461 
462 
463 private:
464 
465  bool fUseGradient; // flag to indicate if using gradient or not
466 
467  bool fBinFit; // flag to indicate if fit is binned
468  // in case of false the fit is unbinned or undefined)
469  // flag it is used to compute chi2 for binned likelihood fit
470 
471  int fFitType; // type of fit (0 undefined, 1 least square, 2 likelihood)
472 
473  int fDataSize; // size of data sets (need for Fumili or LM fitters)
474 
475  FitConfig fConfig; // fitter configuration (options and parameter settings)
476 
477  std::shared_ptr<IModelFunction> fFunc; //! copy of the fitted function containing on output the fit result
478 
479  std::shared_ptr<ROOT::Fit::FitResult> fResult; //! pointer to the object containing the result of the fit
480 
481  std::shared_ptr<ROOT::Math::Minimizer> fMinimizer; //! pointer to used minimizer
482 
483  std::shared_ptr<ROOT::Fit::FitData> fData; //! pointer to the fit data (binned or unbinned data)
484 
485  std::shared_ptr<ROOT::Math::IMultiGenFunction> fObjFunction; //! pointer to used objective function
486 
487 };
488 
489 
490 // internal functions to get data set and model function from FCN
491 // useful for fits done with customized FCN classes
492 template <class ObjFuncType>
493 bool Fitter::GetDataFromFCN() {
494  ObjFuncType * objfunc = dynamic_cast<ObjFuncType*>(fObjFunction.get() );
495  if (objfunc) {
496  fFunc = objfunc->ModelFunctionPtr();
497  fData = objfunc->DataPtr();
498  return true;
499  }
500  else {
501  return false;
502  }
503 }
504 
505 
506  } // end namespace Fit
507 
508 } // end namespace ROOT
509 
510 // implementation of inline methods
511 
512 
513 #ifndef __CINT__
514 
515 #include "Math/WrappedFunction.h"
516 
517 template<class Function>
518 bool ROOT::Fit::Fitter::FitFCN(unsigned int npar, Function & f, const double * par, unsigned int datasize,bool chi2fit) {
520  return FitFCN(wf,par,datasize,chi2fit);
521 }
522 template<class Function>
523 bool ROOT::Fit::Fitter::SetFCN(unsigned int npar, Function & f, const double * par, unsigned int datasize,bool chi2fit) {
525  return SetFCN(wf,par,datasize,chi2fit);
526 }
527 
528 
529 
530 
531 #endif // endif __CINT__
532 
533 #endif /* ROOT_Fit_Fitter */
ROOT::Math::IParamFunction IModel1DFunction
Definition: Fitter.h:83
Interface (abstract class) for multi-dimensional functions providing a gradient calculation.
Definition: IFunction.h:330
double par[1]
Definition: unuranDistr.cxx:38
Namespace for new ROOT classes and functions.
Definition: StringConv.hxx:21
FitConfig & Config()
access to the configuration (non const method)
Definition: Fitter.h:370
bool Fit(const std::shared_ptr< BinData > &data)
Definition: Fitter.h:141
bool LikelihoodFit(const UnBinData &data, bool extended=false)
Unbinned Likelihood fit.
Definition: Fitter.h:175
Base class for all the fit data types: Stores the coordinates and the DataOptions.
Definition: FitData.h:65
void SetData(const FitData &data)
Definition: Fitter.h:437
ROOT::Math::IMultiGenFunction BaseFunc
Definition: Fitter.h:86
std::shared_ptr< IModelFunction > fFunc
Definition: Fitter.h:477
Class describing the unbinned data sets (just x coordinates values) of any dimensions.
Definition: UnBinData.h:42
Interface (abstract class) for parametric gradient multi-dimensional functions providing in addition ...
bool Fit(const UnBinData &data, bool extended=false)
fit an unbinned data set using loglikelihood method
Definition: Fitter.h:156
bool LikelihoodFit(const std::shared_ptr< UnBinData > &data, bool extended=false)
Definition: Fitter.h:179
std::shared_ptr< ROOT::Fit::FitResult > fResult
copy of the fitted function containing on output the fit result
Definition: Fitter.h:479
bool LeastSquareFit(const BinData &data)
Fit a binned data set using a least square fit.
Definition: Fitter.h:149
const FitResult & Result() const
get fit result
Definition: Fitter.h:337
ROOT::Math::IParamMultiGradFunction IGradModelFunction
Definition: Fitter.h:82
Abstract Minimizer class, defining the interface for the various minimizer (like Minuit2, Minuit, GSL, etc..) Plug-in&#39;s exist in ROOT to be able to instantiate the derived classes like ROOT::Math::GSLMinimizer or ROOT::Math::Minuit2Minimizer via the plug-in manager.
Definition: Minimizer.h:78
ROOT::Math::IParamGradFunction IGradModel1DFunction
Definition: Fitter.h:84
std::vector< std::vector< double > > Data
bool LinearFit(const BinData &data)
do a linear fit on a set of bin-data
Definition: Fitter.h:198
const FitConfig & Config() const
access to the fit configuration (const method)
Definition: Fitter.h:365
Documentation for the abstract class IBaseFunctionMultiDim.
Definition: IFunction.h:62
std::shared_ptr< ROOT::Fit::FitData > fData
pointer to used minimizer
Definition: Fitter.h:483
bool Fit(const Data &data, const Function &func)
fit a data set using any generic model function If data set is binned a least square fit is performed...
Definition: Fitter.h:129
FitConfig fConfig
Definition: Fitter.h:475
Double_t(* Function)(Double_t)
Definition: Functor.C:4
bool IsBinFit() const
query if fit is binned.
Definition: Fitter.h:376
RooCmdArg Minimizer(const char *type, const char *alg=0)
Fitter class, entry point for performing all type of fits.
Definition: Fitter.h:77
bool Fit(const BinData &data)
Fit a binned data set using a least square fit (default method)
Definition: Fitter.h:137
ROOT::Math::IMultiGenFunction * GetFCN() const
return pointer to last used objective function (is NULL in case fit is not yet done) This pointer wil...
Definition: Fitter.h:398
bool FitFCN()
Perform a fit with the previously set FCN function.
Definition: Fitter.cxx:290
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:53
std::shared_ptr< ROOT::Math::Minimizer > fMinimizer
pointer to the object containing the result of the fit
Definition: Fitter.h:481
bool LikelihoodFit(const BinData &data, bool extended=true)
Binned Likelihood fit.
Definition: Fitter.h:164
Interface (abstract class) for parametric one-dimensional gradient functions providing in addition to...
IParamFunction interface (abstract class) describing multi-dimensional parameteric functions It is a ...
bool LikelihoodFit(const std::shared_ptr< BinData > &data, bool extended=true)
Definition: Fitter.h:168
class containg the result of the fit and all the related information (fitted parameter values...
Definition: FitResult.h:48
double f(double x)
Specialized IParamFunction interface (abstract class) for one-dimensional parametric functions It is ...
FitMethodFunction class Interface for objective functions (like chi2 and likelihood used in the fit) ...
Definition: Fitter.h:40
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 func(double *x, double *p)
Definition: stressTF1.cxx:213
ROOT::Math::IMultiGradFunction BaseGradFunc
Definition: Fitter.h:87
std::shared_ptr< ROOT::Math::IMultiGenFunction > fObjFunction
pointer to the fit data (binned or unbinned data)
Definition: Fitter.h:485
Template class to wrap any C++ callable object implementing operator() (const double * x) in a multi-...
bool useGradient
Namespace for new Math classes and functions.
Binding & operator=(OUT(*fun)(void))
bool fUseGradient
Definition: Fitter.h:465
BasicFitMethodFunction< ROOT::Math::IMultiGradFunction > FitMethodGradFunction
Definition: Fitter.h:44
typedef void((*Func_t)())
void SetFunctionAndData(const IModelFunction &func, const FitData &data)
Definition: Fitter.h:441
bool SetFCN(unsigned int npar, Function &fcn, const double *params=0, unsigned int dataSize=0, bool chi2fit=false)
Set a generic FCN function as a C++ callable object implementing double () (const double *) Note that...
Definition: Fitter.h:523
ROOT::Math::Minimizer * GetMinimizer() const
return pointer to last used minimizer (is NULL in case fit is not yet done) This pointer is guranteed...
Definition: Fitter.h:387
bool LikelihoodFit(const Data &data, const Function &func, bool extended)
fit a data set using any generic model function Pre-requisite on the function:
Definition: Fitter.h:190
double result[121]
bool LinearFit(const std::shared_ptr< BinData > &data)
Definition: Fitter.h:202
void SetData(const std::shared_ptr< Data > &data)
Definition: Fitter.h:448
ROOT::Math::IParamMultiFunction IModelFunction
Definition: Fitter.h:81
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition: FitConfig.h:45
BasicFitMethodFunction< ROOT::Math::IMultiGenFunction > FitMethodFunction
Definition: Fitter.h:40