ROOT  6.07/01
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
TLinearMinimizer.cxx
Go to the documentation of this file.
1 // @(#)root/minuit:$Id$
2 // Author: L. Moneta Wed Oct 25 16:28:55 2006
3 
4 /**********************************************************************
5  * *
6  * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
7  * *
8  * *
9  **********************************************************************/
10 
11 // Implementation file for class TLinearMinimizer
12 
13 #include "TLinearMinimizer.h"
14 #include "Math/IParamFunction.h"
15 #include "TF1.h"
16 #include "TUUID.h"
17 #include "TROOT.h"
18 #include "Fit/BasicFCN.h"
19 #include "Fit/BinData.h"
20 #include "Fit/Chi2FCN.h"
21 
22 #include "TLinearFitter.h"
23 #include "TVirtualMutex.h"
24 
25 #include <iostream>
26 #include <cassert>
27 #include <algorithm>
28 #include <functional>
29 
30 
31 
32 // namespace ROOT {
33 
34 // namespace Fit {
35 
36 
37 // structure used for creating the TF1 representing the basis functions
38 // they are the derivatives w.r.t the parameters of the model function
39 template<class Func>
40 struct BasisFunction {
41  BasisFunction(const Func & f, int k) :
42  fKPar(k),
43  fFunc(&f)
44  {}
45 
46  double operator() ( double * x, double *) {
47  return fFunc->ParameterDerivative(x,fKPar);
48  }
49 
50  unsigned int fKPar; // param component
51  const Func * fFunc;
52 };
53 
54 
55 //______________________________________________________________________________
56 //
57 // TLinearMinimizer, simple class implementing the ROOT::Math::Minimizer interface using
58 // TLinearFitter.
59 // This class uses TLinearFitter to find directly (by solving a system of linear equations)
60 // the minimum of a
61 // least-square function which has a linear dependence in the fit parameters.
62 // This class is not used directly, but via the ROOT::Fitter class, when calling the
63 // LinearFit method. It is instantiates using the plug-in manager (plug-in name is "Linear")
64 //
65 //__________________________________________________________________________________________
66 
67 
69 
70 
72  fRobust(false),
73  fDim(0),
74  fNFree(0),
75  fMinVal(0),
76  fObjFunc(0),
77  fFitter(0)
78 {
79  // Default constructor implementation.
80  // type is not used - needed for consistency with other minimizer plug-ins
81 }
82 
84  fRobust(false),
85  fDim(0),
86  fNFree(0),
87  fMinVal(0),
88  fObjFunc(0),
89  fFitter(0)
90 {
91  // constructor passing a type of algorithm, (supported now robust via LTS regression)
92 
93  // select type from the string
94  std::string algoname(type);
95  std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) tolower );
96 
97  if (algoname.find("robust") != std::string::npos) fRobust = true;
98 
99 }
100 
102 {
103  // Destructor implementation.
104  if (fFitter) delete fFitter;
105 }
106 
108  Minimizer()
109 {
110  // Implementation of copy constructor.
111 }
112 
114 {
115  // Implementation of assignment operator.
116  if (this == &rhs) return *this; // time saving self-test
117  return *this;
118 }
119 
120 
122  // Set function to be minimized. Flag an error since only support Gradient objective functions
123 
124  Error("TLinearMinimizer::SetFunction(IMultiGenFunction)","Wrong type of function used for Linear fitter");
125 }
126 
127 
129  // Set the function to be minimized. The function must be a Chi2 gradient function
130  // When performing a linear fit we need the basis functions, which are the partial derivatives with respect to the parameters of the model function.
131 
133  const Chi2Func * chi2func = dynamic_cast<const Chi2Func *>(&objfunc);
134  if (chi2func ==0) {
135  Error("TLinearMinimizer::SetFunction(IMultiGradFunction)","Wrong type of function used for Linear fitter");
136  return;
137  }
138  fObjFunc = chi2func;
139 
140  // need to get the gradient parametric model function
141  typedef ROOT::Math::IParamMultiGradFunction ModelFunc;
142  const ModelFunc * modfunc = dynamic_cast<const ModelFunc*>( &(chi2func->ModelFunction()) );
143  assert(modfunc != 0);
144 
145  fDim = chi2func->NDim(); // number of parameters
146  fNFree = fDim;
147  // get the basis functions (derivatives of the modelfunc)
148  TObjArray flist;
149  for (unsigned int i = 0; i < fDim; ++i) {
150  // t.b.f: should not create TF1 classes
151  // when creating TF1 (if onother function with same name exists it is
152  // deleted since it is added in function list in gROOT
153  // fix the problem using meaniful names (difficult to re-produce)
154  BasisFunction<ModelFunc > bf(*modfunc,i);
155  TUUID u;
156  std::string fname = "_LinearMinimimizer_BasisFunction_" +
157  std::string(u.AsString() );
158  TF1 * f = new TF1(fname.c_str(),ROOT::Math::ParamFunctor(bf));
159  flist.Add(f);
160  // remove this functions from gROOT
162  gROOT->GetListOfFunctions()->Remove(f);
163 
164  }
165 
166  // create TLinearFitter (do it now because olny now now the coordinate dimensions)
167  if (fFitter) delete fFitter; // reset by deleting previous copy
168  fFitter = new TLinearFitter( static_cast<const ModelFunc::BaseFunc&>(*modfunc).NDim() );
169 
170  fFitter->StoreData(fRobust); // need a copy of data in case of robust fitting
171 
172  fFitter->SetBasisFunctions(&flist);
173 
174  // get the fitter data
175  const ROOT::Fit::BinData & data = chi2func->Data();
176  // add the data but not store them
177  for (unsigned int i = 0; i < data.Size(); ++i) {
178  double y = 0;
179  const double * x = data.GetPoint(i,y);
180  double ey = 1;
181  if (! data.Opt().fErrors1) {
182  ey = data.Error(i);
183  }
184  // interface should take a double *
185  fFitter->AddPoint( const_cast<double *>(x) , y, ey);
186  }
187 
188 }
189 
190 bool TLinearMinimizer::SetFixedVariable(unsigned int ivar, const std::string & /* name */ , double val) {
191  // set a fixed variable.
192  if (!fFitter) return false;
193  fFitter->FixParameter(ivar, val);
194  return true;
195 }
196 
198  // find directly the minimum of the chi2 function
199  // solving the linear equation. Use TVirtualFitter::Eval.
200 
201  if (fFitter == 0 || fObjFunc == 0) return false;
202 
203  int iret = 0;
204  if (!fRobust)
205  iret = fFitter->Eval();
206  else {
207  // robust fitting - get h parameter using tolerance (t.b. improved)
208  double h = Tolerance();
209  if (PrintLevel() > 0)
210  std::cout << "TLinearMinimizer: Robust fitting with h = " << h << std::endl;
211  iret = fFitter->EvalRobust(h);
212  }
213  fStatus = iret;
214 
215  if (iret != 0) {
216  Warning("Minimize","TLinearFitter failed in finding the solution");
217  return false;
218  }
219 
220 
221  // get parameter values
222  fParams.resize( fDim);
223  // no error available for robust fitting
224  if (!fRobust) fErrors.resize( fDim);
225  for (unsigned int i = 0; i < fDim; ++i) {
226  fParams[i] = fFitter->GetParameter( i);
227  if (!fRobust) fErrors[i] = fFitter->GetParError( i );
228  }
229  fCovar.resize(fDim*fDim);
230  double * cov = fFitter->GetCovarianceMatrix();
231 
232  if (!fRobust && cov) std::copy(cov,cov+fDim*fDim,fCovar.begin() );
233 
234  // calculate chi2 value
235 
236  fMinVal = (*fObjFunc)(&fParams.front());
237 
238  return true;
239 
240 }
241 
242 
243 // } // end namespace Fit
244 
245 // } // end namespace ROOT
246 
virtual void StoreData(Bool_t store)
Interface (abstract class) for multi-dimensional functions providing a gradient calculation.
Definition: IFunction.h:322
std::vector< double > fErrors
An array of TObjects.
Definition: TObjArray.h:39
virtual void FixParameter(Int_t ipar)
Fixes paramter #ipar at its current value.
The Linear Fitter - For fitting functions that are LINEAR IN PARAMETERS.
std::vector< double > fParams
#define assert(cond)
Definition: unittest.h:542
TH1 * h
Definition: legend2.C:5
#define gROOT
Definition: TROOT.h:344
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:63
double Tolerance() const
absolute tolerance
Definition: Minimizer.h:428
TLinearFitter * fFitter
ClassImp(TIterator) Bool_t TIterator return false
Compare two iterator objects.
Definition: TIterator.cxx:21
unsigned int fNFree
TLinearMinimizer class: minimizer implementation based on TMinuit.
TFile * f
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition: TUUID.h:44
unsigned int Size() const
return number of fit points
Definition: BinData.h:447
Double_t x[n]
Definition: legend1.C:17
TLinearMinimizer & operator=(const TLinearMinimizer &rhs)
Assignment operator.
std::vector< double > fCovar
UChar_t mod R__LOCKGUARD2(gSrvAuthenticateMutex)
virtual void SetFunction(const ROOT::Math::IMultiGenFunction &func)
set the fit model function
void Error(const char *location, const char *msgfmt,...)
Chi2FCN class for binnned fits using the least square methods.
Definition: Chi2FCN.h:68
IParamFunction interface (abstract class) describing multi-dimensional parameteric functions It is a ...
RooCmdArg Minimizer(const char *type, const char *alg=0)
const ROOT::Math::IMultiGradFunction * fObjFunc
virtual Int_t EvalRobust(Double_t h=-1)
Finds the parameters of the fitted function in case data contains outliers.
const char * AsString() const
Return UUID as string. Copy string immediately since it will be reused.
Definition: TUUID.cxx:536
int PrintLevel() const
minimizer configuration parameters
Definition: Minimizer.h:419
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:61
void Warning(const char *location, const char *msgfmt,...)
virtual Double_t GetParameter(Int_t ipar) const
virtual void SetBasisFunctions(TObjArray *functions)
set the basis functions in case the fitting function is not set directly The TLinearFitter will manag...
virtual Int_t Eval()
Perform the fit and evaluate the parameters Returns 0 if the fit is ok, 1 if there are errors...
TLinearMinimizer(int type=0)
Default constructor.
TRObject operator()(const T1 &t1) const
Interface (abstract class) for parametric gradient multi-dimensional functions providing in addition ...
int type
Definition: TGX11.cxx:120
Double_t y[n]
Definition: legend1.C:17
Double_t ey[n]
Definition: legend1.C:17
virtual bool Minimize()
method to perform the minimization
double Error(unsigned int ipoint) const
return error on the value for the given fit point Safe (but slower) method returning correctly the er...
Definition: BinData.h:249
bool fRobust
return reference to the objective function virtual const ROOT::Math::IGenFunction & Function() const;...
1-Dim function class
Definition: TF1.h:149
Param Functor class for Multidimensional functions.
Definition: ParamFunctor.h:209
const DataOptions & Opt() const
access to options
Definition: DataVector.h:97
virtual Double_t GetParError(Int_t ipar) const
Returns the error of parameter #ipar.
void Add(TObject *obj)
Definition: TObjArray.h:75
const double * GetPoint(unsigned int ipoint, double &value) const
retrieve at the same time a pointer to the coordinate data and the fit value More efficient than call...
Definition: BinData.h:304
virtual ~TLinearMinimizer()
Destructor (no operations)
Documentation for the abstract class IBaseFunctionMultiDim.
Definition: IFunction.h:63
ClassImp(TLinearMinimizer) TLinearMinimizer
virtual bool SetFixedVariable(unsigned int, const std::string &, double)
set fixed variable (override if minimizer supports them )
virtual Double_t * GetCovarianceMatrix() const
Returns covariance matrix.
virtual void AddPoint(Double_t *x, Double_t y, Double_t e=1)
Adds 1 point to the fitter.