Back to home page

EIC code displayed by LXR

 
 

    


Warning, file /include/root/TF1.h was not indexed or was modified since last indexation (in which case cross-reference links may be missing, inaccurate or erroneous).

0001 // @(#)root/hist:$Id$
0002 // Author: Rene Brun   18/08/95
0003 
0004 /*************************************************************************
0005  * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
0006  * All rights reserved.                                                  *
0007  *                                                                       *
0008  * For the licensing terms see $ROOTSYS/LICENSE.                         *
0009  * For the list of contributors see $ROOTSYS/README/CREDITS.             *
0010  *************************************************************************/
0011 // ---------------------------------- F1.h
0012 
0013 #ifndef ROOT_TF1
0014 #define ROOT_TF1
0015 
0016 //////////////////////////////////////////////////////////////////////////
0017 //                                                                      //
0018 // TF1                                                                  //
0019 //                                                                      //
0020 // The Parametric 1-D function                                          //
0021 //                                                                      //
0022 //////////////////////////////////////////////////////////////////////////
0023 
0024 #include "RConfigure.h"
0025 #include <functional>
0026 #include <cassert>
0027 #include <memory>
0028 #include <string>
0029 #include <vector>
0030 #include "TFormula.h"
0031 #include "TMethodCall.h"
0032 #include "TAttLine.h"
0033 #include "TAttFill.h"
0034 #include "TAttMarker.h"
0035 #include "TF1AbsComposition.h"
0036 #include "TMath.h"
0037 #include "TMatrixDSymfwd.h"
0038 #include "Math/Types.h"
0039 #include "Math/ParamFunctor.h"
0040 
0041 #include <string>
0042 
0043 class TF1;
0044 class TH1;
0045 class TAxis;
0046 class TRandom;
0047 
0048 namespace ROOT {
0049    namespace Fit {
0050       class FitResult;
0051    }
0052 }
0053 
0054 class TF1Parameters {
0055 public:
0056    TF1Parameters() {} // needed for the I/O
0057    TF1Parameters(Int_t npar) :
0058       fParameters(std::vector<Double_t>(npar)),
0059       fParNames(std::vector<std::string>(npar))
0060    {
0061       for (int i = 0; i < npar; ++i) {
0062          fParNames[i] = std::string(TString::Format("p%d", i).Data());
0063       }
0064    }
0065    // copy constructor
0066    TF1Parameters(const TF1Parameters &rhs) :
0067       fParameters(rhs.fParameters),
0068       fParNames(rhs.fParNames)
0069    {}
0070    // assignment
0071    TF1Parameters &operator=(const TF1Parameters &rhs)
0072    {
0073       if (&rhs == this) return *this;
0074       fParameters = rhs.fParameters;
0075       fParNames = rhs.fParNames;
0076       return *this;
0077    }
0078    virtual ~TF1Parameters() {}
0079 
0080    // getter methods
0081    Double_t GetParameter(Int_t iparam) const
0082    {
0083       return (CheckIndex(iparam)) ? fParameters[iparam] : 0;
0084    }
0085    Double_t GetParameter(const char *name) const
0086    {
0087       return GetParameter(GetParNumber(name));
0088    }
0089    const Double_t *GetParameters() const
0090    {
0091       return fParameters.data();
0092    }
0093    const std::vector<double> &ParamsVec() const
0094    {
0095       return fParameters;
0096    }
0097 
0098    Int_t GetParNumber(const char *name) const;
0099 
0100    const char *GetParName(Int_t iparam) const
0101    {
0102       return (CheckIndex(iparam)) ? fParNames[iparam].c_str() : "";
0103    }
0104 
0105 
0106    // setter methods
0107    void   SetParameter(Int_t iparam, Double_t value)
0108    {
0109       if (!CheckIndex(iparam)) return;
0110       fParameters[iparam] = value;
0111    }
0112    void  SetParameters(const Double_t *params)
0113    {
0114       std::copy(params, params + fParameters.size(), fParameters.begin());
0115    }
0116    template <typename... Args>
0117    void   SetParameters(Double_t arg1, Args &&... args);
0118 
0119    void   SetParameter(const char *name, Double_t value)
0120    {
0121       SetParameter(GetParNumber(name), value);
0122    }
0123    void   SetParName(Int_t iparam, const char *name)
0124    {
0125       if (!CheckIndex(iparam)) return;
0126       fParNames[iparam] = std::string(name);
0127    }
0128    template <typename... Args>
0129    void   SetParNames(Args &&... args);
0130 
0131    ClassDef(TF1Parameters, 1)  // The Parameters of a parameteric function
0132 private:
0133 
0134    bool CheckIndex(Int_t i) const
0135    {
0136       return (i >= 0 && i < int(fParameters.size()));
0137    }
0138 
0139    std::vector<Double_t> fParameters;    // parameter values
0140    std::vector<std::string> fParNames;   // parameter names
0141 };
0142 
0143 /// Set parameter values.
0144 /// NaN values will be skipped, meaning that the corresponding parameters will not be changed.
0145 template <typename... Args>
0146 void TF1Parameters::SetParameters(Double_t arg1, Args &&...args)
0147 {
0148    int i = 0;
0149    for (double val : {arg1, static_cast<Double_t>(args)...}) {
0150       if(!TMath::IsNaN(val)) SetParameter(i++, val);
0151    }
0152 }
0153 
0154 /// Set parameter names.
0155 /// Empty strings will be skipped, meaning that the corresponding name will not be changed.
0156 template <typename... Args>
0157 void TF1Parameters::SetParNames(Args &&...args)
0158 {
0159    int i = 0;
0160    for (auto name : {static_cast<std::string const&>(args)...}) {
0161       if(!name.empty()) SetParName(i++, name.c_str());
0162    }
0163 }
0164 
0165 namespace ROOT {
0166    namespace Internal {
0167       /// %Internal class used by TF1 for defining
0168       /// template specialization for different TF1 constructors
0169       template<class Func>
0170       struct TF1Builder {
0171          static void Build(TF1 *f, Func func);
0172       };
0173 
0174       template<class Func>
0175       struct TF1Builder<Func *> {
0176          static void Build(TF1 *f, Func *func);
0177       };
0178    }
0179 }
0180 
0181 
0182 class TF1 : public TNamed, public TAttLine, public TAttFill, public TAttMarker {
0183 
0184    template<class Func>
0185    friend struct ROOT::Internal::TF1Builder;
0186 
0187 public:
0188    /// Add to list behavior
0189    enum class EAddToList {
0190       kDefault,
0191       kAdd,
0192       kNo
0193    };
0194 
0195 
0196    struct TF1FunctorPointer {
0197       virtual  ~TF1FunctorPointer() {}
0198       virtual  TF1FunctorPointer * Clone() const = 0;
0199    };
0200 
0201 protected:
0202 
0203    enum EFType {
0204       kFormula = 0,      ///< Formula functions which can be stored,
0205       kPtrScalarFreeFcn, ///< Pointer to scalar free function,
0206       kInterpreted,      ///< Interpreted functions constructed by name,
0207       kTemplVec,         ///< Vectorized free functions or TemplScalar functors evaluating on vectorized parameters,
0208       kTemplScalar,      ///< TemplScalar functors evaluating on scalar parameters
0209       kCompositionFcn
0210    }; // formula based on composition class (e.g. NSUM, CONV)
0211 
0212    Double_t    fXmin{-1111};                        ///<  Lower bounds for the range
0213    Double_t    fXmax{-1111};                        ///<  Upper bounds for the range
0214    Int_t       fNpar{};                             ///<  Number of parameters
0215    Int_t       fNdim{};                             ///<  Function dimension
0216    Int_t       fNpx{100};                           ///<  Number of points used for the graphical representation
0217    EFType      fType{EFType::kTemplScalar};
0218    Int_t       fNpfits{};                           ///<  Number of points used in the fit
0219    Int_t       fNDF{};                              ///<  Number of degrees of freedom in the fit
0220    Double_t    fChisquare{};                        ///<  Function fit chisquare
0221    Double_t    fMinimum{-1111};                     ///<  Minimum value for plotting
0222    Double_t    fMaximum{-1111};                     ///<  Maximum value for plotting
0223    std::vector<Double_t>    fParErrors;             ///<  Array of errors of the fNpar parameters
0224    std::vector<Double_t>    fParMin;                ///<  Array of lower limits of the fNpar parameters
0225    std::vector<Double_t>    fParMax;                ///<  Array of upper limits of the fNpar parameters
0226    std::vector<Double_t>    fSave;                  ///<  Array of fNsave function values
0227    std::vector<Double_t>    fIntegral;              ///<! Integral of function binned on fNpx bins
0228    std::vector<Double_t>    fAlpha;                 ///<! Array alpha. for each bin in x the deconvolution r of fIntegral
0229    std::vector<Double_t>    fBeta;                  ///<! Array beta.  is approximated by x = alpha +beta*r *gamma*r**2
0230    std::vector<Double_t>    fGamma;                 ///<! Array gamma.
0231    TObject     *fParent{nullptr};                   ///<! Parent object hooking this function (if one)
0232    TH1         *fHistogram{nullptr};                ///<! Pointer to histogram used for visualisation
0233    std::unique_ptr<TMethodCall> fMethodCall;        ///<! Pointer to MethodCall in case of interpreted function
0234    Bool_t      fNormalized{false};                  ///<  Normalization option (false by default)
0235    Double_t    fNormIntegral{};                     ///<  Integral of the function before being normalized
0236    std::unique_ptr<TF1FunctorPointer>  fFunctor;    ///<! Functor object to wrap any C++ callable object
0237    std::unique_ptr<TFormula>   fFormula;            ///<  Pointer to TFormula in case when user define formula
0238    std::unique_ptr<TF1Parameters> fParams;          ///<  Pointer to Function parameters object (exists only for not-formula functions)
0239    std::unique_ptr<TF1AbsComposition> fComposition; ///<  Pointer to composition (NSUM or CONV)
0240 
0241    /// General constructor for TF1. Most of the other constructors delegate on it
0242    TF1(EFType functionType, const char *name, Double_t xmin, Double_t xmax, Int_t npar, Int_t ndim, EAddToList addToGlobList, TF1Parameters *params = nullptr, TF1FunctorPointer * functor = nullptr):
0243       TNamed(name, name), TAttLine(), TAttFill(), TAttMarker(), fXmin(xmin), fXmax(xmax), fNpar(npar), fNdim(ndim),
0244       fType(functionType), fParErrors(npar), fParMin(npar), fParMax(npar)
0245    {
0246       fParams.reset(params);
0247       fFunctor.reset(functor);
0248       DoInitialize(addToGlobList);
0249    }
0250 
0251 private:
0252    // NSUM parsing helper functions
0253    void DefineNSUMTerm(TObjArray *newFuncs, TObjArray *coeffNames,
0254                TString &fullFormula,
0255                TString &formula, int termStart, int termEnd,
0256                Double_t xmin, Double_t xmax);
0257    int TermCoeffLength(TString &term);
0258 
0259 protected:
0260 
0261    template <class T>
0262    struct TF1FunctorPointerImpl: TF1FunctorPointer {
0263       TF1FunctorPointerImpl(const ROOT::Math::ParamFunctorTempl<T> &func): fImpl(func) {};
0264       TF1FunctorPointerImpl(const std::function<T(const T *f, const Double_t *param)> &func) : fImpl(func){};
0265       ~TF1FunctorPointerImpl() override {}
0266        TF1FunctorPointer * Clone() const override { return new TF1FunctorPointerImpl<T>(fImpl); }
0267       ROOT::Math::ParamFunctorTempl<T> fImpl;
0268    };
0269 
0270 
0271 
0272 
0273    static std::atomic<Bool_t> fgAbsValue;  //use absolute value of function when computing integral
0274    static Bool_t fgRejectPoint;  //True if point must be rejected in a fit
0275    static std::atomic<Bool_t> fgAddToGlobList; //True if we want to register the function in the global list
0276    static TF1   *fgCurrent;   //pointer to current function being processed
0277 
0278 
0279    //void CreateFromFunctor(const char *name, Int_t npar, Int_t ndim = 1);
0280    void DoInitialize(EAddToList addToGlobList);
0281 
0282    void IntegrateForNormalization();
0283    // tabulate the cumulative function integral at  fNpx points. Used by GetRandom
0284    Bool_t ComputeCdfTable(Option_t * opt);
0285 
0286    virtual Double_t GetMinMaxNDim(Double_t *x , Bool_t findmax, Double_t epsilon = 0, Int_t maxiter = 0) const;
0287    virtual void GetRange(Double_t *xmin, Double_t *xmax) const;
0288    virtual TH1 *DoCreateHistogram(Double_t xmin, Double_t xmax, Bool_t recreate = kFALSE);
0289 
0290    TString ProvideSaveName(Option_t *option);
0291 
0292 public:
0293 
0294    // TF1 status bits
0295    enum EStatusBits {
0296       kNotGlobal   = BIT(10),  // don't register in global list of functions
0297       kNotDraw     = BIT(9)  // don't draw the function when in a TH1
0298    };
0299 
0300    TF1();
0301    TF1(const char *name, const char *formula, Double_t xmin = 0, Double_t xmax = 1, EAddToList addToGlobList = EAddToList::kDefault, bool vectorize = false);
0302    TF1(const char *name, const char *formula, Double_t xmin, Double_t xmax, Option_t * option);  // same as above but using a string for option
0303    TF1(const char *name, Double_t xmin, Double_t xmax, Int_t npar, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault);
0304    TF1(const char *name, Double_t (*fcn)(Double_t *, Double_t *), Double_t xmin = 0, Double_t xmax = 1, Int_t npar = 0, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault);
0305    TF1(const char *name, Double_t (*fcn)(const Double_t *, const Double_t *), Double_t xmin = 0, Double_t xmax = 1, Int_t npar = 0, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault);
0306 
0307    template <class T>
0308    TF1(const char *name, std::function<T(const T *data, const Double_t *param)> &fcn, Double_t xmin = 0, Double_t xmax = 1, Int_t npar = 0, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault):
0309       TF1(EFType::kTemplScalar, name, xmin, xmax, npar, ndim, addToGlobList, new TF1Parameters(npar), new TF1FunctorPointerImpl<T>(fcn))
0310    {
0311       fType = std::is_same<T, double>::value ? TF1::EFType::kTemplScalar : TF1::EFType::kTemplVec;
0312    }
0313 
0314    ////////////////////////////////////////////////////////////////////////////////
0315    /// Constructor using a pointer to function.
0316    ///
0317    /// \param[in] name object name
0318    /// \param[in] fcn pointer to function
0319    /// \param[in] xmin,xmax x axis limits
0320    /// \param[in] npar is the number of free parameters used by the function
0321    /// \param[in] ndim number of dimensions
0322    /// \param[in] addToGlobList boolean marking if it should be added to global list
0323    ///
0324    /// This constructor creates a function of type C when invoked
0325    /// with the normal C++ compiler.
0326    ///
0327    ///
0328    /// \warning A function created with this constructor cannot be Cloned
0329 
0330 
0331    template <class T>
0332    TF1(const char *name, T(*fcn)(const T *, const Double_t *), Double_t xmin = 0, Double_t xmax = 1, Int_t npar = 0, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault):
0333       TF1(EFType::kTemplVec, name, xmin, xmax, npar, ndim, addToGlobList, new TF1Parameters(npar), new TF1FunctorPointerImpl<T>(fcn))
0334    {}
0335 
0336    // Constructors using functors (compiled mode only)
0337    TF1(const char *name, ROOT::Math::ParamFunctor f, Double_t xmin = 0, Double_t xmax = 1, Int_t npar = 0, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault);
0338 
0339    /// Template constructors from any  C++ callable object,  defining  the operator() (double * , double *)
0340    /// and returning a double.
0341    /// The class name is not needed when using compile code, while it is required when using
0342    /// interpreted code via the specialized constructor with void *.
0343    /// An instance of the C++ function class or its pointer can both be used. The former is recommended when using
0344    /// C++ compiled code, but if CINT-compatibility is needed, then a pointer to the function class must be used.
0345    /// xmin and xmax specify the plotting range,  npar is the number of parameters.
0346    /// See the tutorial math/exampleFunctor.C for an example of using this constructor
0347    template <typename Func>
0348    TF1(const char *name, Func f, Double_t xmin, Double_t xmax, Int_t npar, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault) :
0349       TF1(EFType::kTemplScalar, name, xmin, xmax, npar, ndim, addToGlobList)
0350    {
0351       //actual fType set in TF1Builder
0352       ROOT::Internal::TF1Builder<Func>::Build(this, f);
0353    }
0354 
0355    /// Template constructors from a pointer to any C++ class of type PtrObj with a specific member function of type
0356    /// MemFn.
0357    /// The member function must have the signature of  (double * , double *) and returning a double.
0358    /// The class name and the method name are not needed when using compile code
0359    /// (the member function pointer is used in this case), while they are required when using interpreted
0360    /// code via the specialized constructor with void *.
0361    /// xmin and xmax specify the plotting range,  npar is the number of parameters.
0362    /// See the tutorial math/exampleFunctor.C for an example of using this constructor
0363    template <class PtrObj, typename MemFn>
0364    TF1(const char *name, const  PtrObj &p, MemFn memFn, Double_t xmin, Double_t xmax, Int_t npar, Int_t ndim = 1, EAddToList addToGlobList = EAddToList::kDefault) :
0365       TF1(EFType::kTemplScalar, name, xmin, xmax, npar, ndim, addToGlobList, new TF1Parameters(npar), new TF1FunctorPointerImpl<double>(ROOT::Math::ParamFunctor(p, memFn)))
0366    {}
0367 
0368    TF1(const TF1 &f1);
0369    TF1 &operator=(const TF1 &rhs);
0370      ~TF1() override;
0371    virtual void     AddParameter(const TString &name, Double_t value)
0372    {
0373       if (fFormula) fFormula->AddParameter(name, value);
0374    }
0375    // virtual void     AddParameters(const pair<TString,Double_t> *pairs, Int_t size) { fFormula->AddParameters(pairs,size); }
0376    // virtual void     AddVariable(const TString &name, Double_t value = 0) { if (fFormula) fFormula->AddVariable(name,value); }
0377    // virtual void     AddVariables(const TString *vars, Int_t size) { if (fFormula) fFormula->AddVariables(vars,size); }
0378    virtual Bool_t   AddToGlobalList(Bool_t on = kTRUE);
0379    static  Bool_t   DefaultAddToGlobalList(Bool_t on = kTRUE);
0380    void     Browse(TBrowser *b) override;
0381    void     Copy(TObject &f1) const override;
0382    TObject         *Clone(const char *newname = nullptr) const override;
0383    virtual Double_t Derivative(Double_t x, Double_t *params = nullptr, Double_t epsilon = 0.001) const;
0384    virtual Double_t Derivative2(Double_t x, Double_t *params = nullptr, Double_t epsilon = 0.001) const;
0385    virtual Double_t Derivative3(Double_t x, Double_t *params = nullptr, Double_t epsilon = 0.001) const;
0386    static  Double_t DerivativeError();
0387    Int_t    DistancetoPrimitive(Int_t px, Int_t py) override;
0388    void     Draw(Option_t *option = "") override;
0389    virtual TF1     *DrawCopy(Option_t *option = "") const;
0390    virtual TObject *DrawDerivative(Option_t *option = "al"); // *MENU*
0391    virtual TObject *DrawIntegral(Option_t *option = "al"); // *MENU*
0392    virtual void     DrawF1(Double_t xmin, Double_t xmax, Option_t *option = "");
0393    virtual Double_t Eval(Double_t x, Double_t y = 0, Double_t z = 0, Double_t t = 0) const;
0394    //template <class T> T Eval(T x, T y = 0, T z = 0, T t = 0) const;
0395    virtual Double_t EvalPar(const Double_t *x, const Double_t *params = nullptr);
0396    template <class T> T EvalPar(const T *x, const Double_t *params = nullptr);
0397    virtual Double_t operator()(Double_t x, Double_t y = 0, Double_t z = 0, Double_t t = 0) const;
0398    template <class T> T operator()(const T *x, const Double_t *params = nullptr);
0399    Double_t EvalUncertainty(Double_t x, const TMatrixDSym *covMatrix = nullptr) const;
0400    void     ExecuteEvent(Int_t event, Int_t px, Int_t py) override;
0401    virtual void     FixParameter(Int_t ipar, Double_t value);
0402    /// Return true if function has data in fSave buffer
0403    Bool_t HasSave() const { return !fSave.empty(); }
0404    bool IsVectorized()
0405    {
0406       return (fType == EFType::kTemplVec) || (fType == EFType::kFormula && fFormula && fFormula->IsVectorized());
0407    }
0408    /// Return the Chisquare after fitting. See ROOT::Fit::FitResult::Chi2()
0409    Double_t     GetChisquare() const
0410    {
0411       return fChisquare;
0412    }
0413    virtual TH1     *GetHistogram() const;
0414    virtual TH1     *CreateHistogram()
0415    {
0416       return DoCreateHistogram(fXmin, fXmax);
0417    }
0418    virtual TFormula *GetFormula()
0419    {
0420       return fFormula.get();
0421    }
0422    virtual const TFormula *GetFormula() const
0423    {
0424       return fFormula.get();
0425    }
0426    virtual TString  GetExpFormula(Option_t *option = "") const
0427    {
0428       return (fFormula) ? fFormula->GetExpFormula(option) : TString();
0429    }
0430    virtual const TObject *GetLinearPart(Int_t i) const
0431    {
0432       return (fFormula) ? fFormula->GetLinearPart(i) : nullptr;
0433    }
0434    virtual Double_t GetMaximum(Double_t xmin = 0, Double_t xmax = 0, Double_t epsilon = 1.E-10, Int_t maxiter = 100, Bool_t logx = false) const;
0435    virtual Double_t GetMinimum(Double_t xmin = 0, Double_t xmax = 0, Double_t epsilon = 1.E-10, Int_t maxiter = 100, Bool_t logx = false) const;
0436    virtual Double_t GetMaximumX(Double_t xmin = 0, Double_t xmax = 0, Double_t epsilon = 1.E-10, Int_t maxiter = 100, Bool_t logx = false) const;
0437    virtual Double_t GetMinimumX(Double_t xmin = 0, Double_t xmax = 0, Double_t epsilon = 1.E-10, Int_t maxiter = 100, Bool_t logx = false) const;
0438    virtual Double_t GetMaximumStored() const
0439    {
0440       return fMaximum;
0441    }
0442    virtual Double_t GetMinimumStored() const
0443    {
0444       return fMinimum;
0445    }
0446    virtual Int_t    GetNpar() const
0447    {
0448       return fNpar;
0449    }
0450    virtual Int_t    GetNdim() const
0451    {
0452       return fNdim;
0453    }
0454    virtual Int_t    GetNDF() const;
0455    virtual Int_t    GetNpx() const
0456    {
0457       return fNpx;
0458    }
0459    TMethodCall    *GetMethodCall() const
0460    {
0461       return fMethodCall.get();
0462    }
0463    virtual Int_t    GetNumber() const
0464    {
0465       return (fFormula) ? fFormula->GetNumber() : 0;
0466    }
0467    virtual Int_t    GetNumberFreeParameters() const;
0468    virtual Int_t    GetNumberFitPoints() const
0469    {
0470       return fNpfits;
0471    }
0472    char    *GetObjectInfo(Int_t px, Int_t py) const override;
0473    TObject    *GetParent() const
0474    {
0475       return fParent;
0476    }
0477    virtual Double_t GetParameter(Int_t ipar) const
0478    {
0479       return (fFormula) ? fFormula->GetParameter(ipar) : fParams->GetParameter(ipar);
0480    }
0481    virtual Double_t GetParameter(const TString &name)  const
0482    {
0483       return (fFormula) ? fFormula->GetParameter(name) : fParams->GetParameter(name);
0484    }
0485    virtual Double_t *GetParameters() const
0486    {
0487       return (fFormula) ? fFormula->GetParameters() : const_cast<Double_t *>(fParams->GetParameters());
0488    }
0489    virtual void     GetParameters(Double_t *params)
0490    {
0491       if (fFormula) fFormula->GetParameters(params);
0492       else std::copy(fParams->ParamsVec().begin(), fParams->ParamsVec().end(), params);
0493    }
0494    virtual const char *GetParName(Int_t ipar) const
0495    {
0496       return (fFormula) ? fFormula->GetParName(ipar) : fParams->GetParName(ipar);
0497    }
0498    virtual Int_t    GetParNumber(const char *name) const
0499    {
0500       return (fFormula) ? fFormula->GetParNumber(name) : fParams->GetParNumber(name);
0501    }
0502    virtual Double_t GetParError(Int_t ipar) const;
0503    virtual Double_t GetParError(const char *name) const
0504    {
0505       return GetParError(GetParNumber(name));
0506    }
0507    virtual const Double_t *GetParErrors() const
0508    {
0509       return fParErrors.data();
0510    }
0511    virtual void     GetParLimits(Int_t ipar, Double_t &parmin, Double_t &parmax) const;
0512    virtual Double_t GetProb() const;
0513    virtual Int_t    GetQuantiles(Int_t n, Double_t *xp, const Double_t *p);
0514    virtual Double_t GetRandom(TRandom * rng = nullptr, Option_t * opt = nullptr);
0515    virtual Double_t GetRandom(Double_t xmin, Double_t xmax, TRandom * rng = nullptr, Option_t * opt = nullptr);
0516    virtual void     GetRange(Double_t &xmin, Double_t &xmax) const;
0517    virtual void     GetRange(Double_t &xmin, Double_t &ymin, Double_t &xmax, Double_t &ymax) const;
0518    virtual void     GetRange(Double_t &xmin, Double_t &ymin, Double_t &zmin, Double_t &xmax, Double_t &ymax, Double_t &zmax) const;
0519    virtual Double_t GetSave(const Double_t *x);
0520    virtual Double_t GetX(Double_t y, Double_t xmin = 0, Double_t xmax = 0, Double_t epsilon = 1.E-10, Int_t maxiter = 100, Bool_t logx = false) const;
0521    virtual Double_t GetXmin() const
0522    {
0523       return fXmin;
0524    }
0525    virtual Double_t GetXmax() const
0526    {
0527       return fXmax;
0528    }
0529    TAxis           *GetXaxis() const ;
0530    TAxis           *GetYaxis() const ;
0531    TAxis           *GetZaxis() const ;
0532    virtual Double_t GetVariable(const TString &name)
0533    {
0534       return (fFormula) ? fFormula->GetVariable(name) : 0;
0535    }
0536    virtual Double_t GradientPar(Int_t ipar, const Double_t *x, Double_t eps = 0.01) const;
0537    template <class T>
0538    T GradientPar(Int_t ipar, const T *x, Double_t eps = 0.01) const;
0539    template <class T>
0540    T GradientParTempl(Int_t ipar, const T *x, Double_t eps = 0.01) const;
0541 
0542    virtual void     GradientPar(const Double_t *x, Double_t *grad, Double_t eps = 0.01) const;
0543    template <class T>
0544    void GradientPar(const T *x, T *grad, Double_t eps = 0.01) const;
0545    template <class T>
0546    void GradientParTempl(const T *x, T *grad, Double_t eps = 0.01) const;
0547 
0548    virtual void     InitArgs(const Double_t *x, const Double_t *params);
0549    static  void     InitStandardFunctions();
0550    virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel = 1.e-12);
0551    virtual Double_t IntegralOneDim(Double_t a, Double_t b, Double_t epsrel, Double_t epsabs, Double_t &err);
0552    virtual Double_t IntegralError(Double_t a, Double_t b, const Double_t *params = nullptr, const Double_t *covmat = nullptr, Double_t epsilon = 1.E-2);
0553    virtual Double_t IntegralError(Int_t n, const Double_t *a, const Double_t *b, const Double_t *params = nullptr, const Double_t *covmat = nullptr, Double_t epsilon = 1.E-2);
0554    // virtual Double_t IntegralFast(const TGraph *g, Double_t a, Double_t b, Double_t *params = nullptr);
0555    virtual Double_t IntegralFast(Int_t num, Double_t *x, Double_t *w, Double_t a, Double_t b, Double_t *params = nullptr, Double_t epsilon = 1e-12);
0556    virtual Double_t IntegralMultiple(Int_t n, const Double_t *a, const Double_t *b, Int_t maxpts, Double_t epsrel, Double_t epsabs , Double_t &relerr, Int_t &nfnevl, Int_t &ifail);
0557    virtual Double_t IntegralMultiple(Int_t n, const Double_t *a, const Double_t *b, Int_t /*minpts*/, Int_t maxpts, Double_t epsrel, Double_t &relerr, Int_t &nfnevl, Int_t &ifail)
0558    {
0559       return  IntegralMultiple(n, a, b, maxpts, epsrel, epsrel, relerr, nfnevl, ifail);
0560    }
0561    virtual Double_t IntegralMultiple(Int_t n, const Double_t *a, const Double_t *b, Double_t epsrel, Double_t &relerr);
0562    virtual Bool_t   IsEvalNormalized() const
0563    {
0564       return fNormalized;
0565    }
0566    /// return kTRUE if the point is inside the function range
0567    virtual Bool_t   IsInside(const Double_t *x) const
0568    {
0569       return !((x[0] < fXmin) || (x[0] > fXmax));
0570    }
0571    virtual Bool_t   IsLinear() const
0572    {
0573       return (fFormula) ? fFormula->IsLinear() : false;
0574    }
0575    virtual Bool_t   IsValid() const;
0576    void     Print(Option_t *option = "") const override;
0577    void     Paint(Option_t *option = "") override;
0578    virtual void     ReleaseParameter(Int_t ipar);
0579    virtual void     Save(Double_t xmin, Double_t xmax, Double_t ymin, Double_t ymax, Double_t zmin, Double_t zmax);
0580    void     SavePrimitive(std::ostream &out, Option_t *option = "") override;
0581    virtual void     SetChisquare(Double_t chi2)
0582    {
0583       fChisquare = chi2;
0584    }
0585    virtual void     SetFitResult(const ROOT::Fit::FitResult &result, const Int_t *indpar = nullptr);
0586    template <class PtrObj, typename MemFn>
0587    void SetFunction(PtrObj &p, MemFn memFn);
0588    template <typename Func>
0589    void SetFunction(Func f);
0590    virtual void     SetMaximum(Double_t maximum = -1111); // *MENU*
0591    virtual void     SetMinimum(Double_t minimum = -1111); // *MENU*
0592    virtual void     SetNDF(Int_t ndf);
0593    virtual void     SetNumberFitPoints(Int_t npfits)
0594    {
0595       fNpfits = npfits;
0596    }
0597    virtual void     SetNormalized(Bool_t flag)
0598    {
0599       fNormalized = flag;
0600       Update();
0601    }
0602    inline void SetNdim(Int_t ndim)
0603    {
0604       fNdim = ndim;
0605       Update();
0606    }
0607    virtual void     SetNpx(Int_t npx = 100); // *MENU*
0608    virtual void     SetParameter(Int_t param, Double_t value)
0609    {
0610       (fFormula) ? fFormula->SetParameter(param, value) : fParams->SetParameter(param, value);
0611       Update();
0612    }
0613    virtual void     SetParameter(const TString &name, Double_t value)
0614    {
0615       (fFormula) ? fFormula->SetParameter(name, value) : fParams->SetParameter(name, value);
0616       Update();
0617    }
0618    virtual void     SetParameters(const Double_t *params)
0619    {
0620       (fFormula) ? fFormula->SetParameters(params) : fParams->SetParameters(params);
0621       Update();
0622    }
0623    /// Set parameter values.
0624    /// NaN values will be skipped, meaning that the corresponding parameters will not be changed.
0625    virtual void SetParameters(double p0, double p1 = TMath::QuietNaN(), double p2 = TMath::QuietNaN(),
0626                               double p3 = TMath::QuietNaN(), double p4 = TMath::QuietNaN(), double p5 = TMath::QuietNaN(),
0627                               double p6 = TMath::QuietNaN(), double p7 = TMath::QuietNaN(), double p8 = TMath::QuietNaN(),
0628                               double p9 = TMath::QuietNaN(), double p10 = TMath::QuietNaN())
0629    {
0630       // Note: this is not made a variadic template method because it would
0631       // presumably break the context menu in the TBrowser. Also, probably this
0632       // method should not be virtual, because if the user wants to change
0633       // parameter setting behavior, the SetParameter() method can be
0634       // overridden.
0635       if (fFormula) fFormula->SetParameters(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
0636       else          fParams->SetParameters(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10);
0637       Update();
0638    } // *MENU*
0639    virtual void     SetParName(Int_t ipar, const char *name);
0640    virtual void     SetParNames(const char *name0 = "", const char *name1 = "", const char *name2 = "",
0641                                 const char *name3 = "", const char *name4 = "", const char *name5 = "",
0642                                 const char *name6 = "", const char *name7 = "", const char *name8 = "",
0643                                 const char *name9 = "", const char *name10 = ""); // *MENU*
0644    virtual void     SetParError(Int_t ipar, Double_t error);
0645    virtual void     SetParErrors(const Double_t *errors);
0646    virtual void     SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax);
0647    virtual void     SetParent(TObject *p = nullptr)
0648    {
0649       fParent = p;
0650    }
0651    virtual void     SetRange(Double_t xmin, Double_t xmax); // *MENU*
0652    virtual void     SetRange(Double_t xmin, Double_t ymin,  Double_t xmax, Double_t ymax);
0653    virtual void     SetRange(Double_t xmin, Double_t ymin, Double_t zmin,  Double_t xmax, Double_t ymax, Double_t zmax);
0654    virtual void     SetSavedPoint(Int_t point, Double_t value);
0655    void     SetTitle(const char *title = "") override; // *MENU*
0656    virtual void     SetVectorized(Bool_t vectorized)
0657    {
0658       if (fType == EFType::kFormula && fFormula)
0659          fFormula->SetVectorized(vectorized);
0660       else
0661          Warning("SetVectorized", "Can only set vectorized flag on formula-based TF1");
0662    }
0663    virtual void     Update();
0664 
0665    static  TF1     *GetCurrent();
0666    static  void     AbsValue(Bool_t reject = kTRUE);
0667    static  void     RejectPoint(Bool_t reject = kTRUE);
0668    static  Bool_t   RejectedPoint();
0669    static  void     SetCurrent(TF1 *f1);
0670 
0671    //Moments
0672    virtual Double_t Moment(Double_t n, Double_t a, Double_t b, const Double_t *params = nullptr, Double_t epsilon = 0.000001);
0673    virtual Double_t CentralMoment(Double_t n, Double_t a, Double_t b, const Double_t *params = nullptr, Double_t epsilon = 0.000001);
0674    virtual Double_t Mean(Double_t a, Double_t b, const Double_t *params = nullptr, Double_t epsilon = 0.000001)
0675    {
0676       return Moment(1, a, b, params, epsilon);
0677    }
0678    virtual Double_t Variance(Double_t a, Double_t b, const Double_t *params = nullptr, Double_t epsilon = 0.000001)
0679    {
0680       return CentralMoment(2, a, b, params, epsilon);
0681    }
0682 
0683    //some useful static utility functions to compute sampling points for Integral
0684    //static  void     CalcGaussLegendreSamplingPoints(TGraph *g, Double_t eps=3.0e-11);
0685    //static  TGraph  *CalcGaussLegendreSamplingPoints(Int_t num=21, Double_t eps=3.0e-11);
0686    static  void     CalcGaussLegendreSamplingPoints(Int_t num, Double_t *x, Double_t *w, Double_t eps = 3.0e-11);
0687 
0688 private:
0689    template <class T>
0690    T EvalParTempl(const T *data, const Double_t *params = nullptr);
0691 
0692    double EvalParVec(const Double_t *data, const Double_t *params);
0693 
0694    ClassDefOverride(TF1, 12) // The Parametric 1-D function
0695 };
0696 
0697 namespace ROOT {
0698    namespace Internal {
0699 
0700       template<class Func>
0701       void TF1Builder<Func>::Build(TF1 *f, Func func)
0702       {
0703          // check if vector interface is supported by Func
0704 #ifdef R__HAS_STD_EXPERIMENTAL_SIMD
0705          if constexpr(std::is_invocable_r_v<Double_v, Func, Double_v*, double *>) {
0706             f->fType = TF1::EFType::kTemplVec;
0707             f->fFunctor.reset(new TF1::TF1FunctorPointerImpl(ROOT::Math::ParamFunctorTempl<Double_v>(func)));
0708          } else
0709 #endif
0710          {
0711             f->fType = TF1::EFType::kTemplScalar;
0712             f->fFunctor.reset(new TF1::TF1FunctorPointerImpl(ROOT::Math::ParamFunctorTempl<double>(func)));
0713          }
0714 
0715          f->fParams = std::make_unique<TF1Parameters>(f->fNpar);
0716       }
0717 
0718       template<class Func>
0719       void TF1Builder<Func *>::Build(TF1 *f, Func *func)
0720       {
0721          // check if vector interface is supported by Func
0722 #ifdef R__HAS_STD_EXPERIMENTAL_SIMD
0723          if constexpr(std::is_invocable_r_v<Double_v, Func, Double_v*, double *>) {
0724             f->fType = TF1::EFType::kTemplVec;
0725             f->fFunctor.reset(new TF1::TF1FunctorPointerImpl(ROOT::Math::ParamFunctorTempl<Double_v>(func)));
0726          } else
0727 #endif
0728          {
0729             f->fType = TF1::EFType::kTemplScalar;
0730             f->fFunctor.reset(new TF1::TF1FunctorPointerImpl(ROOT::Math::ParamFunctorTempl<double>(func)));
0731          }
0732 
0733          f->fParams = std::make_unique<TF1Parameters>(f->fNpar);
0734       }
0735 
0736       /// TF1 building from a string
0737       /// used to build a TFormula based on a lambda function
0738       template<>
0739       struct TF1Builder<const char *> {
0740          static void Build(TF1 *f, const char *formula)
0741          {
0742             f->fType = TF1::EFType::kFormula;
0743             f->fFormula = std::make_unique<TFormula>("tf1lambda", formula, f->fNdim, f->fNpar, false);
0744             TString formulaExpression(formula);
0745             Ssiz_t first = formulaExpression.Index("return") + 7;
0746             Ssiz_t last  = formulaExpression.Last(';');
0747             TString title = formulaExpression(first, last - first);
0748             f->SetTitle(title);
0749          }
0750       };
0751 
0752       inline void
0753       EvalParMultiDim(TF1 *func, Double_t *out, const Double_t *x, std::size_t size, std::size_t rows, Double_t *params)
0754       {
0755          for (size_t i = 0; i < rows; i++) {
0756             out[i] = func->EvalPar(x + i * size, params);
0757          }
0758       }
0759    }
0760 }
0761 
0762 inline Double_t TF1::operator()(Double_t x, Double_t y, Double_t z, Double_t t) const
0763 {
0764    return Eval(x, y, z, t);
0765 }
0766 
0767 template <class T>
0768 inline T TF1::operator()(const T *x, const Double_t *params)
0769 {
0770    return EvalPar(x, params);
0771 }
0772 
0773 ////////////////////////////////////////////////////////////////////////////////
0774 ///   EvalPar for vectorized
0775 template <class T>
0776 T TF1::EvalPar(const T *x, const Double_t *params)
0777 {
0778   if (fType == EFType::kTemplVec || fType == EFType::kTemplScalar) {
0779      return EvalParTempl(x, params);
0780   } else if (fType == EFType::kFormula) {
0781      return fFormula->EvalPar(x, params);
0782   } else
0783      return TF1::EvalPar((double *)x, params);
0784 }
0785 
0786 ////////////////////////////////////////////////////////////////////////////////
0787 ///   Eval for vectorized functions
0788 // template <class T>
0789 // T TF1::Eval(T x, T y, T z, T t) const
0790 // {
0791 //    if (fType == EFType::kFormula)
0792 //       return fFormula->Eval(x, y, z, t);
0793 
0794 //    T xx[] = {x, y, z, t};
0795 //    Double_t *pp = (Double_t *)fParams->GetParameters();
0796 //    return ((TF1 *)this)->EvalPar(xx, pp);
0797 // }
0798 
0799 // Internal to TF1. Evaluates Templated interfaces
0800 template <class T>
0801 inline T TF1::EvalParTempl(const T *data, const Double_t *params)
0802 {
0803    assert(fType == EFType::kTemplScalar || fType == EFType::kTemplVec);
0804    if (!params) params = (Double_t *)fParams->GetParameters();
0805    if (fFunctor)
0806       return ((TF1FunctorPointerImpl<T> *)fFunctor.get())->fImpl(data, params);
0807 
0808    // this should throw an error
0809    // we nned to implement a vectorized GetSave(x)
0810    return TMath::SignalingNaN();
0811 }
0812 
0813 inline void TF1::SetRange(Double_t xmin, Double_t,  Double_t xmax, Double_t)
0814 {
0815    TF1::SetRange(xmin, xmax);
0816 }
0817 inline void TF1::SetRange(Double_t xmin, Double_t, Double_t,  Double_t xmax, Double_t, Double_t)
0818 {
0819    TF1::SetRange(xmin, xmax);
0820 }
0821 
0822 template <typename Func>
0823 void TF1::SetFunction(Func f)
0824 {
0825    // set function from a generic C++ callable object
0826    fType = EFType::kPtrScalarFreeFcn;
0827    fFunctor = std::make_unique<TF1::TF1FunctorPointerImpl<double>>(ROOT::Math::ParamFunctor(f));
0828 }
0829 template <class PtrObj, typename MemFn>
0830 void TF1::SetFunction(PtrObj &p, MemFn memFn)
0831 {
0832    // set from a pointer to a member function
0833    fType = EFType::kPtrScalarFreeFcn;
0834    fFunctor = std::make_unique<TF1::TF1FunctorPointerImpl<double>>(ROOT::Math::ParamFunctor(p, memFn));
0835 }
0836 
0837 template <class T>
0838 inline T TF1::GradientPar(Int_t ipar, const T *x, Double_t eps) const
0839 {
0840    if (fType == EFType::kTemplVec || fType == EFType::kTemplScalar) {
0841       return GradientParTempl<T>(ipar, x, eps);
0842    } else
0843       return GradientParTempl<Double_t>(ipar, (const Double_t *)x, eps);
0844 }
0845 
0846 template <class T>
0847 inline T TF1::GradientParTempl(Int_t ipar, const T *x, Double_t eps) const
0848 {
0849    if (GetNpar() == 0)
0850       return 0;
0851 
0852    if (eps < 1e-10 || eps > 1) {
0853       Warning("Derivative", "parameter esp=%g out of allowed range[1e-10,1], reset to 0.01", eps);
0854       eps = 0.01;
0855    }
0856    Double_t h;
0857    TF1 *func = (TF1 *)this;
0858    Double_t *parameters = GetParameters();
0859 
0860    // Copy parameters for thread safety
0861    std::vector<Double_t> parametersCopy(parameters, parameters + GetNpar());
0862    parameters = parametersCopy.data();
0863 
0864    Double_t al, bl, h2;
0865    T f1, f2, g1, g2, d0, d2;
0866 
0867    ((TF1 *)this)->GetParLimits(ipar, al, bl);
0868    if (al * bl != 0 && al >= bl) {
0869       // this parameter is fixed
0870       return 0;
0871    }
0872 
0873    // check if error has been computer (is not zero)
0874    if (func->GetParError(ipar) != 0)
0875       h = eps * func->GetParError(ipar);
0876    else
0877       h = eps;
0878 
0879    // save original parameters
0880    Double_t par0 = parameters[ipar];
0881 
0882    parameters[ipar] = par0 + h;
0883    f1 = func->EvalPar(x, parameters);
0884    parameters[ipar] = par0 - h;
0885    f2 = func->EvalPar(x, parameters);
0886    parameters[ipar] = par0 + h / 2;
0887    g1 = func->EvalPar(x, parameters);
0888    parameters[ipar] = par0 - h / 2;
0889    g2 = func->EvalPar(x, parameters);
0890 
0891    // compute the central differences
0892    h2 = 1 / (2. * h);
0893    d0 = f1 - f2;
0894    d2 = 2 * (g1 - g2);
0895 
0896    T grad = h2 * (4 * d2 - d0) / 3.;
0897 
0898    // restore original value
0899    parameters[ipar] = par0;
0900 
0901    return grad;
0902 }
0903 
0904 template <class T>
0905 inline void TF1::GradientPar(const T *x, T *grad, Double_t eps) const
0906 {
0907    if (fType == EFType::kTemplVec || fType == EFType::kTemplScalar) {
0908       GradientParTempl<T>(x, grad, eps);
0909    } else
0910       GradientParTempl<Double_t>((const Double_t *)x, (Double_t *)grad, eps);
0911 }
0912 
0913 template <class T>
0914 inline void TF1::GradientParTempl(const T *x, T *grad, Double_t eps) const
0915 {
0916    if (eps < 1e-10 || eps > 1) {
0917       Warning("Derivative", "parameter esp=%g out of allowed range[1e-10,1], reset to 0.01", eps);
0918       eps = 0.01;
0919    }
0920 
0921    for (Int_t ipar = 0; ipar < GetNpar(); ipar++) {
0922       grad[ipar] = GradientParTempl<T>(ipar, x, eps);
0923    }
0924 }
0925 
0926 #endif