73 template <
class FitObject>
76 template <
class FitObject>
79 template <
class FitObject>
89 Error(
"Fit",
"function may not be null pointer");
93 Error(
"Fit",
"function is zombie");
99 Error(
"Fit",
"function %s has illegal number of parameters = %d",
f1->
GetName(), npar);
105 Error(
"Fit",
"function %s dimension, %d, is greater than fit object dimension, %d",
110 Error(
"Fit",
"function %s dimension, %d, is smaller than fit object dimension -1, %d",
122 Double_t fxmin, fymin, fzmin, fxmax, fymax, fzmax;
123 f1.
GetRange(fxmin, fymin, fzmin, fxmax, fymax, fzmax);
132template<
class FitObject>
139 printf(
"fit function %s\n",
f1->
GetName() );
145 if (iret != 0)
return iret;
151 if (fitOption.
Integral)
Info(
"Fit",
"Ignore Integral option. Model function dimension is less than the data object dimension");
152 if (fitOption.
Like)
Info(
"Fit",
"Ignore Likelihood option. Model function dimension is less than the data object dimension");
160 if (special==299+npar) linear =
kTRUE;
166 std::shared_ptr<TFitResult> tfr(
new TFitResult() );
168 std::shared_ptr<ROOT::Fit::Fitter> fitter(
new ROOT::Fit::Fitter(std::static_pointer_cast<ROOT::Fit::FitResult>(tfr) ) );
181 if (fitOption.
PChi2 == 1) {
183 }
else if (fitOption.
PChi2 == 2) {
194 printf(
"use range \n" );
199 printf(
"range size %d\n", range.
Size(0) );
202 printf(
" range in x = [%f,%f] \n",
x1,
x2);
209 if (fitdata->Size() == 0 ) {
210 Warning(
"Fit",
"Fit data is empty ");
215 printf(
"HFit:: data size is %d \n",fitdata->Size());
216 for (
unsigned int i = 0; i < fitdata->Size(); ++i) {
217 if (fitdata->NDim() == 1) printf(
" x[%d] = %f - value = %f \n", i,*(fitdata->Coords(i)),fitdata->Value(i) );
227 if (special != 0 && !fitOption.
Bound && !linear) {
237 else if (special == 299 + npar)
244 if ( (linear || fitOption.
Gradient) )
246#ifdef R__HAS_STD_EXPERIMENTAL_SIMD
258 if (
int(fitdata->NDim()) == hdim -1 ) fitConfig.
SetNormErrors(
true);
266 for (
int i = 0; i < npar; ++i) {
272 if (plow*pup != 0 && plow >= pup) {
275 else if (plow < pup ) {
290 double step = 0.1 * (pup - plow);
292 if ( parSettings.
Value() < pup && pup - parSettings.
Value() < 2 * step )
293 step = (pup - parSettings.
Value() ) / 2;
294 else if ( parSettings.
Value() > plow && parSettings.
Value() - plow < 2 * step )
295 step = (parSettings.
Value() - plow ) / 2;
324 std::string
type =
"Robust";
350 if (fitOption.
Like) printf(
"do likelihood fit...\n");
351 if (linear) printf(
"do linear fit...\n");
352 printf(
"do now fit...\n");
367 if (fitOption.
User && userFcn)
368 fitok = fitter->FitFCN( userFcn );
369 else if (fitOption.
Like) {
371 bool weight = ((fitOption.
Like & 2) == 2);
373 bool extended = ((fitOption.
Like & 4 ) != 4 );
377 fitok = fitter->LikelihoodFit(fitdata, extended, fitOption.
ExecPolicy);
380 fitok = fitter->Fit(fitdata, fitOption.
ExecPolicy);
382 if ( !fitok && !fitOption.
Quiet )
383 Warning(
"Fit",
"Abnormal termination of minimization.");
389 iret = fitResult.
Status();
413 if (!fitOption.
Quiet) {
415 if (fitter->GetMinimizer() && fitConfig.
MinimizerType() ==
"Minuit" &&
417 fitter->GetMinimizer()->PrintResults();
422 fitResult.
Print(std::cout);
436 bcfitter->
SetFCN(userFcn);
458 tfr->SetTitle(title);
473 if (range.
Size(0) == 0) {
484 if (range.
Size(1) == 0) {
495 if (range.
Size(2) == 0) {
506 std::cout <<
"xmin,xmax" <<
xmin <<
" " <<
xmax << std::endl;
525 else if (range.
Size(0) == 0) {
527 double xmin = std::numeric_limits<double>::infinity();
528 double xmax = -std::numeric_limits<double>::infinity();
531 while ( (
g = (
TGraph*) next() ) ) {
532 double x1 = 0,
x2 = 0,
y1 = 0,
y2 = 0;
547 if (range.
Size(0) == 0) {
548 double xmin =
gr->GetXmin();
549 double xmax =
gr->GetXmax();
552 if (range.
Size(1) == 0) {
553 double ymin =
gr->GetYmin();
554 double ymax =
gr->GetYmax();
565 for (
int i = 0; i < ndim; ++i ) {
566 if ( range.
Size(i) == 0 ) {
573template<
class FitObject>
579 std::cout <<
"draw and store fit function " <<
f1->
GetName() << std::endl;
591 std::cout <<
"draw and store fit function " <<
f1->
GetName()
592 <<
" Range in x = [ " <<
xmin <<
" , " <<
xmax <<
" ]" << std::endl;
596 if (funcList ==
nullptr){
597 Error(
"StoreAndDrawFitFunction",
"Function list has not been created - cannot store the fitted function");
605 bool reuseOldFunction =
false;
606 if (delOldFunction) {
609 while ((obj = next())) {
616 reuseOldFunction =
true;
622 TF1 *fnew1 =
nullptr;
623 TF2 *fnew2 =
nullptr;
624 TF3 *fnew3 =
nullptr;
628 if (!reuseOldFunction) {
632 funcList->
Add(fnew1);
642 }
else if (ndim < 3) {
643 if (!reuseOldFunction) {
647 funcList->
Add(fnew2);
650 fnew2 =
dynamic_cast<TF2*
>(
f1);
659 if (!reuseOldFunction) {
663 funcList->
Add(fnew3);
666 fnew3 =
dynamic_cast<TF3*
>(
f1);
677 if (drawFunction && ndim < 3 && h1->InheritsFrom(
TH1::Class() ) ) {
680 if (!
gPad || (
gPad &&
gPad->GetListOfPrimitives()->FindObject(
h1) ==
nullptr ) )
696 if (
option ==
nullptr)
return;
715 if (
type == EFitObjectType::kHistogram) {
748 if (fitOption.
Like == 1) {
752 if (fitOption.
Like == 2) fitOption.
Like = 6;
753 else fitOption.
Like = 4;
758 Warning(
"Fit",
"Cannot use P or X option in combination of L. Ignore the chi2 option and perform a likelihood fit");
762 else if (
type == EFitObjectType::kGraph) {
769 constexpr auto length = std::char_traits<char>::length;
771 int start = opt.
Index(
"H=0.");
772 int numpos = start +
length(
"H=0.");
775 while( (numpos+numlen<
len) && isdigit(opt[numpos+numlen]) ) numlen++;
776 TString num = opt(numpos,numlen);
778 h = atof(num.
Data());
792 Warning(
"FitOptionsMake",
"Cannot use User (U) fit option when running in multi-thread mode. The option is ignored");
820 Info(
"CheckGraphFitOptions",
"L (Log Likelihood fit) is an invalid option when fitting a graph. It is ignored");
824 Info(
"CheckGraphFitOptions",
"I (use function integral) is an invalid option when fitting a graph. It is ignored");
836 std::shared_ptr<ROOT::Fit::UnBinData> fitdata(
data);
839 printf(
"tree data size is %d \n",fitdata->Size());
840 for (
unsigned int i = 0; i < fitdata->Size(); ++i) {
841 if (fitdata->NDim() == 1) printf(
" x[%d] = %f \n", i,*(fitdata->Coords(i) ) );
844 if (fitdata->Size() == 0 ) {
845 Warning(
"Fit",
"Fit data is empty ");
850 std::shared_ptr<TFitResult> tfr(
new TFitResult() );
856 unsigned int dim = fitdata->NDim();
862 assert ( (
int) dim == fitfunc->
GetNdim() );
871 for (
int i = 0; i < npar; ++i) {
876 if (plow*pup != 0 && plow >= pup) {
879 else if (plow < pup ) {
894 double step = 0.1 * (pup - plow);
896 if ( parSettings.
Value() < pup && pup - parSettings.
Value() < 2 * step )
897 step = (pup - parSettings.
Value() ) / 2;
898 else if ( parSettings.
Value() > plow && parSettings.
Value() - plow < 2 * step )
899 step = (parSettings.
Value() - plow ) / 2;
921 if ( (fitOption.
Like & 2) == 2)
924 bool extended = (fitOption.
Like & 1) == 1;
927 fitok = fitter->LikelihoodFit(fitdata, extended, fitOption.
ExecPolicy);
928 if ( !fitok && !fitOption.
Quiet )
929 Warning(
"UnBinFit",
"Abnormal termination of minimization.");
933 int iret = fitResult.
Status();
957 if (lastFitter)
delete lastFitter;
962 else if (!fitOption.
Quiet) fitResult.
Print(std::cout);
973 tfr->SetTitle(title);
988 Warning(
"HFit::FitObject",
"A weighted likelihood fit is requested but histogram is not weighted - do a standard Likelihood fit");
1046template<
class FitObject>
1062 if (
data.Size() == 0 ) {
1063 Warning(
"Chisquare",
"data set is empty - return -1");
const Bool_t kIterBackward
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
void Info(const char *location, const char *msgfmt,...)
Use this function for informational messages.
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
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 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 length
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 UChar_t len
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 y2
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
Option_t Option_t TPoint TPoint const char y1
R__EXTERN TVirtualMutex * gROOTMutex
R__EXTERN TVirtualMutex * gGlobalMutex
#define R__LOCKGUARD(mutex)
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Chi2FCN class for binned fits using the least square methods.
class describing the range in the coordinates it supports multiple range in a coordinate.
void AddRange(unsigned int icoord, double xmin, double xmax)
add a range [xmin,xmax] for the new coordinate icoord Adding a range does not delete existing one,...
unsigned int Size(unsigned int icoord=0) const
return range size for coordinate icoord (starts from zero) Size == 0 indicates no range is present [-...
void GetRange(unsigned int irange, unsigned int icoord, double &xmin, double &xmax) const
get the i-th range for given coordinate.
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
void SetMinimizer(const char *type, const char *algo=nullptr)
set minimizer type and algorithm
void SetMinosErrors(bool on=true)
set Minos errors computation to be performed after fitting
void SetNormErrors(bool on=true)
set the option to normalize the error on the result according to chi2/ndf
bool NormalizeErrors() const
flag to check if resulting errors are be normalized according to chi2/ndf
void SetMinimizerOptions(const ROOT::Math::MinimizerOptions &minopt)
set all the minimizer options using class ROOT::Math::MinimizerOptions
void SetWeightCorrection(bool on=true)
apply the weight correction for error matrix computation
void SetParabErrors(bool on=true)
set parabolic errors
const std::string & MinimizerType() const
return type of minimizer package
const ParameterSettings & ParSettings(unsigned int i) const
get the parameter settings for the i-th parameter (const method)
ROOT::Math::MinimizerOptions & MinimizerOptions()
access to the minimizer control parameter (non const method)
class containing the result of the fit and all the related information (fitted parameter values,...
bool IsEmpty() const
True if a fit result does not exist (even invalid) with parameter values.
const std::vector< double > & Errors() const
parameter errors (return st::vector)
const std::vector< double > & Parameters() const
parameter values (return std::vector)
unsigned int Ndf() const
Number of degree of freedom.
double Chi2() const
Return the Chi2 value after fitting In case of unbinned fits (or not defined one, see the documentati...
void Print(std::ostream &os, bool covmat=false) const
print the result and optionally covariance matrix and correlations
void PrintCovMatrix(std::ostream &os) const
print error matrix and correlations
int Status() const
minimizer status code
Fitter class, entry point for performing all type of fits.
Class, describing value, limits and step size of the parameters Provides functionality also to set/re...
void SetStepSize(double err)
set the step size
void SetLimits(double low, double up)
set a double side limit, if low == up the parameter is fixed if low > up the limits are removed The c...
double Value() const
return parameter value
void SetUpperLimit(double up)
set a single upper limit
void Fix()
fix the parameter
void SetLowerLimit(double low)
set a single lower limit
class evaluating the log likelihood for binned Poisson likelihood fits it is template to distinguish ...
Class describing the un-binned data sets (just x coordinates values) of any dimensions.
IParamFunction interface (abstract class) describing multi-dimensional parametric functions It is a d...
void SetPrintLevel(int level)
set print level
void SetTolerance(double tol)
set the tolerance
Class to Wrap a ROOT Function class (like TF1) in a IParamMultiFunction interface of multi-dimensions...
Class to manage histogram axis.
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Int_t GetLast() const
Return last bin on the axis i.e.
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Int_t GetFirst() const
Return first bin on the axis i.e.
Backward compatible implementation of TVirtualFitter.
virtual void SetMethodCall(TMethodCall *m)
For using interpreted function passed by the user.
void SetFCN(void(*fcn)(Int_t &, Double_t *, Double_t &f, Double_t *, Int_t)) override
Override setFCN to use the Adapter to Minuit2 FCN interface To set the address of the minimization fu...
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
virtual Int_t GetNumber() const
virtual void GetParLimits(Int_t ipar, Double_t &parmin, Double_t &parmax) const
Return limits for parameter ipar.
virtual void SetNDF(Int_t ndf)
Set the number of degrees of freedom ndf should be the number of points used in a fit - the number of...
virtual Double_t GetParError(Int_t ipar) const
Return value of parameter number ipar.
virtual void SetChisquare(Double_t chi2)
virtual void SetRange(Double_t xmin, Double_t xmax)
Initialize the upper and lower bounds to draw the function.
virtual Int_t GetNpar() const
virtual void SetParErrors(const Double_t *errors)
Set errors for all active parameters when calling this function, the array errors must have at least ...
virtual void SetParent(TObject *p=nullptr)
virtual Double_t * GetParameters() const
void Copy(TObject &f1) const override
Copy this F1 to a new F1.
virtual void SetNumberFitPoints(Int_t npfits)
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
virtual Bool_t IsLinear() const
virtual void SetParameters(const Double_t *params)
virtual void Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax)
Save values of function in array fSave.
TClass * IsA() const override
virtual Int_t GetNdim() const
virtual Bool_t AddToGlobalList(Bool_t on=kTRUE)
Add to global list of functions (gROOT->GetListOfFunctions() ) return previous status (true if the fu...
A 2-Dim function with parameters.
void Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax) override
Save values of function in array fSave.
void SetRange(Double_t xmin, Double_t xmax) override
Initialize the upper and lower bounds to draw the function.
TF3 defines a 3D Function with Parameters.
void Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax) override
Save values of function in array fSave.
void SetRange(Double_t xmin, Double_t xmax) override
Initialize the upper and lower bounds to draw the function.
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
Extends the ROOT::Fit::Result class with a TNamed inheritance providing easy possibility for I/O.
Graphics object made of three arrays X, Y and Z with the same number of points each.
A TGraph is an object made of two arrays X and Y with npoints each.
virtual TH1F * GetHistogram() const
Returns a pointer to the histogram used to draw the axis Takes into account the two following cases.
TH1 is the base class of all histogram classes in ROOT.
virtual Int_t GetDimension() const
void Draw(Option_t *option="") override
Draw this histogram with options.
TList * GetListOfFunctions() const
virtual Int_t GetSumw2N() const
Multidimensional histogram base.
void Add(TObject *obj) override
TObject * Remove(TObject *obj) override
Remove object from the list.
A TMultiGraph is a collection of TGraph (or derived) objects.
TList * GetListOfGraphs() const
TH1F * GetHistogram()
Returns a pointer to the histogram used to draw the axis.
const char * GetName() const override
Returns name of object.
const char * GetTitle() const override
Returns title of object.
Mother of all ROOT objects.
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
R__ALWAYS_INLINE Bool_t IsZombie() const
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
const char * Data() const
TString & ReplaceAll(const TString &s1, const TString &s2)
void ToUpper()
Change string to upper case.
TString & Remove(Ssiz_t pos)
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Abstract Base Class for Fitting.
virtual void SetFitOption(Foption_t option)
virtual void SetObjectFit(TObject *obj)
TMethodCall * GetMethodCall() const
void(* FCNFunc_t)(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag)
virtual void SetUserFunc(TObject *userfunc)
static TVirtualFitter * GetFitter()
static: return the current Fitter
static void SetFitter(TVirtualFitter *fitter, Int_t maxpar=25)
Static function to set an alternative fitter.
void GetDrawingRange(TH1 *h1, ROOT::Fit::DataRange &range)
void GetFunctionRange(const TF1 &f1, ROOT::Fit::DataRange &range)
int CheckFitFunction(const TF1 *f1, int hdim)
TFitResultPtr Fit(FitObject *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
void FitOptionsMake(const char *option, Foption_t &fitOption)
void CheckGraphFitOptions(Foption_t &fitOption)
void StoreAndDrawFitFunction(FitObject *h1, TF1 *f1, const ROOT::Fit::DataRange &range, bool, bool, const char *goption)
double ComputeChi2(const FitObject &h1, TF1 &f1, bool useRange, ROOT::Fit::EChisquareType type, bool useIntegral=false)
int GetDimension(const TH1 *h1)
void InitPolynom(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for a polynomial function given the fit data Set the parameters to an unwei...
TFitResultPtr FitObject(TH1 *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
fitting function for a TH1 (called from TH1::Fit)
double Chisquare(const TH1 &h1, TF1 &f1, bool useRange, EChisquareType type, bool useIntegral=false)
compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation)
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
void Init2DGaus(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for 2D gaussian function given the fit data Set the sigma limits for zero t...
TFitResultPtr UnBinFit(ROOT::Fit::UnBinData *data, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption)
fit an unbin data set (from tree or from histogram buffer) using a TF1 pointer and fit options.
void FillData(BinData &dv, const TH1 *hist, TF1 *func=nullptr)
fill the data vector from a TH1.
void InitExpo(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for an exponential function given the fit data Set the constant and slope a...
void InitGaus(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for gaussian function given the fit data Set the sigma limits for zero top ...
std::string ToString(const T &val)
Utility function for conversion to strings.
Bool_t IsImplicitMTEnabled()
Returns true if the implicit multi-threading in ROOT is enabled.
Int_t Finite(Double_t x)
Check if it is finite with a mask in order to be consistent in presence of fast math.
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Returns x raised to the power y.
ROOT::EExecutionPolicy ExecPolicy
DataOptions : simple structure holding the options on how the data are filled.
bool fErrors1
use all errors equal to 1, i.e. fit without errors (default is false)
bool fNormBinVolume
normalize data by a normalized the bin volume (bin volume divided by a reference value)
bool fUseRange
use the function range when creating the fit data (default is false)
bool fUseEmpty
use empty bins (default is false) with a fixed error of 1
bool fIntegral
use integral of bin content instead of bin center (default is false)
bool fExpErrors
use expected errors from the function and not from the data
bool fBinVolume
normalize data by the bin volume (it is used in the Poisson likelihood fits)
bool fCoordErrors
use errors on the x coordinates when available (default is true)