Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
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
39template<class Func>
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/// \class TLinearMinimizer
56/// \note See ROOT::Minuit2 for a newer version of this class.
57///
58/// TLinearMinimizer, simple class implementing the ROOT::Math::Minimizer
59/// interface usingTLinearFitter. This class uses TLinearFitter to find directly
60/// (by solving a system of linear equations) the minimum of a least-square
61/// function which has a linear dependence in the fit parameters. This class is
62/// not used directly, but via the ROOT::Fitter class, when calling the
63/// LinearFit method. It is instantiates using the plug-in manager
64/// (plug-in name is "Linear").
65////////////////////////////////////////////////////////////////////////////////
66
67
68
70 fRobust(false),
71 fDim(0),
72 fNFree(0),
73 fMinVal(0),
74 fObjFunc(nullptr),
75 fFitter(nullptr)
76{
77 // Default constructor implementation.
78 // type is not used - needed for consistency with other minimizer plug-ins
79}
80
82 fRobust(false),
83 fDim(0),
84 fNFree(0),
85 fMinVal(0),
86 fObjFunc(nullptr),
87 fFitter(nullptr)
88{
89 // constructor passing a type of algorithm, (supported now robust via LTS regression)
90
91 // select type from the string
92 std::string algoname(type);
93 std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int(*)(int)) tolower );
94
95 if (algoname.find("robust") != std::string::npos) fRobust = true;
96
97}
98
100{
101 // Destructor implementation.
102 if (fFitter) delete fFitter;
103}
104
106 // Set the function to be minimized. The function must be a Chi2 gradient function
107 // When performing a linear fit we need the basis functions, which are the partial derivatives with respect to the parameters of the model function.
108
109 if(!objfunc.HasGradient()) {
110 // Set function to be minimized. Flag an error since only support Gradient objective functions
111 Error("TLinearMinimizer::SetFunction(IMultiGenFunction)","Wrong type of function used for Linear fitter");
112 }
113
115 const Chi2Func * chi2func = dynamic_cast<const Chi2Func *>(&objfunc);
116 if (chi2func ==nullptr) {
117 Error("TLinearMinimizer::SetFunction(IMultiGenFunction)","Wrong type of function used for Linear fitter");
118 return;
119 }
121
122 // need to get the gradient parametric model function
124 const ModelFunc * modfunc = dynamic_cast<const ModelFunc*>( &(chi2func->ModelFunction()) );
125 assert(modfunc != nullptr);
126
127 fDim = chi2func->NDim(); // number of parameters
128 fNFree = fDim; // in case of no fixed parameters
129 // get the basis functions (derivatives of the modelfunc)
131 flist.SetOwner(kFALSE); // we do not want to own the list - it will be owned by the TLinearFitter class
132 for (unsigned int i = 0; i < fDim; ++i) {
133 // t.b.f: should not create TF1 classes
134 // when creating TF1 (if another function with same name exists it is
135 // deleted since it is added in function list in gROOT
136 // fix the problem using meaniful names (difficult to re-produce)
138 TUUID u;
139 std::string fname = "_LinearMinimimizer_BasisFunction_" +
140 std::string(u.AsString() );
142 flist.Add(f);
143 }
144
145 // create TLinearFitter (do it now because only now now the coordinate dimensions)
146 if (fFitter) delete fFitter; // reset by deleting previous copy
147 fFitter = new TLinearFitter( static_cast<const ModelFunc::BaseFunc&>(*modfunc).NDim() );
148
149 fFitter->StoreData(fRobust); // need a copy of data in case of robust fitting
150
152
153 // get the fitter data
154 const ROOT::Fit::BinData & data = chi2func->Data();
155 // add the data but not store them
156 std::vector<double> xc(data.NDim());
157 for (unsigned int i = 0; i < data.Size(); ++i) {
158 double y = 0;
159 const double * x1 = data.GetPoint(i,y);
160 double ey = 1;
161 if (! data.Opt().fErrors1) {
162 ey = data.Error(i);
163 }
164 // in case of bin volume- scale the data according to the bin volume
165 double binVolume = 1.;
166 double * x = nullptr;
167 if (data.Opt().fBinVolume) {
168 // compute the bin volume
169 const double * x2 = data.BinUpEdge(i);
170 for (unsigned int j = 0; j < data.NDim(); ++j) {
171 binVolume *= (x2[j]-x1[j]);
172 // we are always using bin centers
173 xc[j] = 0.5 * (x2[j]+ x1[j]);
174 }
175 if (data.Opt().fNormBinVolume) binVolume /= data.RefVolume();
176 // we cannot scale f so we scale the points
177 y /= binVolume;
178 ey /= binVolume;
179 x = xc.data();
180 } else {
181 x = const_cast<double*>(x1);
182 }
183 //std::cout << "adding point " << i << " x " << x[0] << " y " << y << " e " << ey << std::endl;
184 fFitter->AddPoint( x , y, ey);
185 }
186
187}
188
189bool TLinearMinimizer::SetFixedVariable(unsigned int ivar, const std::string & /* name */ , double val) {
190 // set a fixed variable.
191 if (!fFitter) return false;
193 return true;
194}
195
197 // find directly the minimum of the chi2 function
198 // solving the linear equation. Use TVirtualFitter::Eval.
199
200 if (fFitter == nullptr || fObjFunc == nullptr) return false;
201
203
204 int iret = 0;
205 if (!fRobust)
206 iret = fFitter->Eval();
207 else {
208 // robust fitting - get h parameter using tolerance (t.b. improved)
209 double h = Tolerance();
210 if (PrintLevel() > 0)
211 std::cout << "TLinearMinimizer: Robust fitting with h = " << h << std::endl;
213 }
214 fStatus = iret;
215
216 if (iret != 0) {
217 Warning("Minimize","TLinearFitter failed in finding the solution");
218 return false;
219 }
220
221
222 // get parameter values
223 fParams.resize( fDim);
224 // no error available for robust fitting
225 if (!fRobust) fErrors.resize( fDim);
226 for (unsigned int i = 0; i < fDim; ++i) {
227 fParams[i] = fFitter->GetParameter( i);
228 if (!fRobust) fErrors[i] = fFitter->GetParError( i );
229 }
230 fCovar.resize(fDim*fDim);
231 double * cov = fFitter->GetCovarianceMatrix();
232
233 if (!fRobust && cov) std::copy(cov,cov+fDim*fDim,fCovar.begin() );
234
235 // calculate chi2 value
236
237 fMinVal = (*fObjFunc)(&fParams.front());
238
239 return true;
240
241}
242
243
244// } // end namespace Fit
245
246// } // end namespace ROOT
247
#define f(i)
Definition RSha256.hxx:104
#define h(i)
Definition RSha256.hxx:106
constexpr Bool_t kFALSE
Definition RtypesCore.h:108
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:208
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:252
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char x2
Option_t Option_t TPoint TPoint const char x1
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition BinData.h:52
Chi2FCN class for binned fits using the least square methods.
Definition Chi2FCN.h:46
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:63
Interface (abstract class) for parametric gradient multi-dimensional functions providing in addition ...
double Tolerance() const
Absolute tolerance.
Definition Minimizer.h:317
int fStatus
status of minimizer
Definition Minimizer.h:388
int PrintLevel() const
Set print level.
Definition Minimizer.h:308
Param Functor class for Multidimensional functions.
const_iterator begin() const
const_iterator end() const
1-Dim function class
Definition TF1.h:182
Int_t GetNumberFreeParameters() const override
virtual Int_t Eval()
Perform the fit and evaluate the parameters Returns 0 if the fit is ok, 1 if there are errors.
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 EvalRobust(Double_t h=-1)
Finds the parameters of the fitted function in case data contains outliers.
Double_t GetParError(Int_t ipar) const override
Returns the error of parameter #ipar
void FixParameter(Int_t ipar) override
Fixes paramter #ipar at its current value.
virtual void AddPoint(Double_t *x, Double_t y, Double_t e=1)
Adds 1 point to the fitter.
Double_t * GetCovarianceMatrix() const override
Returns covariance matrix.
Double_t GetParameter(Int_t ipar) const override
virtual void StoreData(Bool_t store)
void SetFunction(const ROOT::Math::IMultiGenFunction &func) override
set the fit model function
TLinearFitter * fFitter
~TLinearMinimizer() override
Destructor (no operations)
bool fRobust
return reference to the objective function virtual const ROOT::Math::IGenFunction & Function() const;
const ROOT::Math::IMultiGradFunction * fObjFunc
bool Minimize() override
method to perform the minimization
std::vector< double > fParams
TLinearMinimizer(int type=0)
Default constructor.
std::vector< double > fCovar
std::vector< double > fErrors
bool SetFixedVariable(unsigned int, const std::string &, double) override
set fixed variable (override if minimizer supports them )
An array of TObjects.
Definition TObjArray.h:31
This class defines a UUID (Universally Unique IDentifier), also known as GUIDs (Globally Unique IDent...
Definition TUUID.h:42
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
Double_t ey[n]
Definition legend1.C:17
double operator()(double *x, double *)
BasisFunction(const Func &f, int k)
unsigned int fKPar
const Func * fFunc