Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TFormula.h
Go to the documentation of this file.
1// @(#)root/hist:$Id$
2// Author: Maciej Zimnoch 30/09/2013
3
4/*************************************************************************
5 * Copyright (C) 1995-2013, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11#ifndef ROOT_TFormula
12#define ROOT_TFormula
13
14
15#include "TNamed.h"
16#include "TBits.h"
17#include "TInterpreter.h"
18#include <cassert>
19#include <vector>
20#include <list>
21#include <map>
22#include <string>
23#include <atomic>
24#include <Math/Types.h>
25
26class TMethodCall;
27
28
30{
31public:
37 const char * GetName() const { return fName.Data(); }
38 const char * GetBody() const { return fBody.Data(); }
39 Int_t GetNargs() const { return fNargs;}
40 Bool_t IsFuncCall() const { return fFuncCall;}
42 TFormulaFunction(const TString &name, const TString &body, int numArgs)
43 : fName(name),fBody(body),fNargs(numArgs),fFound(false),fFuncCall(true) {}
45 : fName(name),fBody(""),fNargs(0),fFound(false),fFuncCall(false){}
46 Bool_t operator<(const TFormulaFunction &rhv) const
47 {
48 // order by length - first the longer ones to avoid replacing wrong functions
49 if ( fName.Length() < rhv.fName.Length() )
50 return true;
51 else if ( fName.Length() > rhv.fName.Length() )
52 return false;
53 // case of equal length
54 return fName < rhv.fName && fBody < rhv.fBody;
55 }
56 Bool_t operator==(const TFormulaFunction &rhv) const
57 {
58 return fName == rhv.fName && fBody == rhv.fBody && fNargs == rhv.fNargs;
59 }
60};
61
63{
64public:
69 const char * GetName() const { return fName.Data(); }
70 Double_t GetInitialValue() const { return fValue; }
71 Int_t GetArrayPos() const { return fArrayPos; }
72 TFormulaVariable():fName(""),fValue(-1),fArrayPos(-1),fFound(false){}
73 TFormulaVariable(const TString &name, Double_t value, Int_t pos)
74 : fName(name), fValue(value), fArrayPos(pos),fFound(false) {}
75 Bool_t operator<(const TFormulaVariable &rhv) const
76 {
77 return fName < rhv.fName;
78 }
79};
80
81struct TFormulaParamOrder {
82 bool operator() (const TString& a, const TString& b) const;
83};
84
85
86class TFormula : public TNamed
87{
88private:
89
90 // All data members are transient apart from the string defining the formula and the parameter values
91
92 TString fClingInput; //! input function passed to Cling
93 std::vector<Double_t> fClingVariables; //! cached variables
94 std::vector<Double_t> fClingParameters; // parameter values
95 Bool_t fReadyToExecute; //! trasient to force initialization
96 std::atomic<Bool_t> fClingInitialized; //! transient to force re-initialization
97 Bool_t fAllParametersSetted; // flag to control if all parameters are setted
98 Bool_t fLazyInitialization = kFALSE; //! transient flag to control lazy initialization (needed for reading from files)
99 std::unique_ptr<TMethodCall> fMethod; //! pointer to methodcall
100 std::unique_ptr<TMethodCall> fGradMethod; //! pointer to a methodcall
101 TString fClingName; //! unique name passed to Cling to define the function ( double clingName(double*x, double*p) )
102 std::string fSavedInputFormula; //! unique name used to defined the function and used in the global map (need to be saved in case of lazy initialization)
103
105 std::string fGradGenerationInput; //! input query to clad to generate a gradient
106 CallFuncSignature fFuncPtr = nullptr; //! function pointer, owned by the JIT.
107 CallFuncSignature fGradFuncPtr = nullptr; //! function pointer, owned by the JIT.
108 void * fLambdaPtr = nullptr; //! pointer to the lambda function
109 static bool fIsCladRuntimeIncluded;
110
113 void FillDefaults();
114 void HandlePolN(TString &formula);
116 void HandleParamRanges(TString &formula);
117 void HandleFunctionArguments(TString &formula);
118 void HandleExponentiation(TString &formula);
119 void HandleLinear(TString &formula);
120 Bool_t InitLambdaExpression(const char * formula);
122 void ReplaceAllNames(TString &formula, std::map<TString, TString> &substitutions);
123 void FillParametrizedFunctions(std::map<std::pair<TString, Int_t>, std::pair<TString, TString>> &functions);
126 std::string GetGradientFuncName() const {
127 assert(fClingName.Length() && "TFormula is not initialized yet!");
128 return std::string(fClingName.Data()) + "_grad";
129 }
130 bool HasGradientGenerationFailed() const {
131 return !fGradMethod && !fGradGenerationInput.empty();
132 }
133
134protected:
135
136 std::list<TFormulaFunction> fFuncs; //!
137 std::map<TString,TFormulaVariable> fVars; //! list of variable names
138 std::map<TString,Int_t,TFormulaParamOrder> fParams; //|| list of parameter names
139 std::map<TString,Double_t> fConsts; //!
140 std::map<TString,TString> fFunctionsShortcuts; //!
141 TString fFormula; // string representing the formula expression
142 Int_t fNdim; // Dimension - needed for lambda expressions
143 Int_t fNpar; //! Number of parameter (transient since we save the vector)
144 Int_t fNumber; //!
145 std::vector<TObject*> fLinearParts; // vector of linear functions
146 Bool_t fVectorized = false; // whether we should use vectorized or regular variables
147 // (we default to false since a lot of functions still cannot be expressed in vectorized form)
148
149 static Bool_t IsOperator(const char c);
150 static Bool_t IsBracket(const char c);
151 static Bool_t IsFunctionNameChar(const char c);
152 static Bool_t IsScientificNotation(const TString & formula, int ipos);
153 static Bool_t IsHexadecimal(const TString & formula, int ipos);
154 static Bool_t IsAParameterName(const TString & formula, int ipos);
155 void ExtractFunctors(TString &formula);
156 void PreProcessFormula(TString &formula);
157 void ProcessFormula(TString &formula);
158 Bool_t PrepareFormula(TString &formula);
159 void ReplaceParamName(TString &formula, const TString & oldname, const TString & name);
160 void DoAddParameter(const TString &name, Double_t value, bool processFormula);
161 void DoSetParameters(const Double_t * p, Int_t size);
163
164 Double_t DoEval(const Double_t * x, const Double_t * p = nullptr) const;
165#ifdef R__HAS_VECCORE
166 ROOT::Double_v DoEvalVec(const ROOT::Double_v *x, const Double_t *p = nullptr) const;
167#endif
168
169public:
170
171 enum EStatusBits {
172 kNotGlobal = BIT(10), // don't store in gROOT->GetListOfFunction (it should be protected)
173 kNormalized = BIT(14), // set to true if the TFormula (ex gausn) is normalized
174 kLinear = BIT(16), //set to true if the TFormula is for linear fitting
175 kLambda = BIT(17) // set to true if TFormula has been build with a lambda
176 };
177 using GradientStorage = std::vector<Double_t>;
178
179 TFormula();
180 virtual ~TFormula();
181 TFormula& operator=(const TFormula &rhs);
182 TFormula(const char *name, const char * formula = "", bool addToGlobList = true, bool vectorize = false);
183 TFormula(const char *name, const char * formula, int ndim, int npar, bool addToGlobList = true);
184 TFormula(const TFormula &formula);
185 // TFormula(const char *name, Int_t nparams, Int_t ndims);
186
187 void AddParameter(const TString &name, Double_t value = 0) { DoAddParameter(name,value,true); }
188 void AddVariable(const TString &name, Double_t value = 0);
189 void AddVariables(const TString *vars, const Int_t size);
190 Int_t Compile(const char *expression="");
191 virtual void Copy(TObject &f1) const;
192 virtual void Clear(Option_t * option="");
193 Double_t Eval(Double_t x) const;
197 Double_t EvalPar(const Double_t *x, const Double_t *params=0) const;
198
199 /// Generate gradient computation routine with respect to the parameters.
200 /// \returns true if a gradient was generated and GradientPar can be called.
201 bool GenerateGradientPar();
202
203 /// Compute the gradient employing automatic differentiation.
204 ///
205 /// \param[in] x - The given variables, if nullptr the already stored
206 /// variables are used.
207 /// \param[out] result - The result of the computation wrt each direction.
208 void GradientPar(const Double_t *x, TFormula::GradientStorage& result);
209
210 void GradientPar(const Double_t *x, Double_t *result);
211
212 // query if TFormula provides gradient computation using AD (CLAD)
213 bool HasGeneratedGradient() const {
214 return fGradMethod != nullptr;
215 }
216
217 // template <class T>
218 // T Eval(T x, T y = 0, T z = 0, T t = 0) const;
219 template <class T>
220 T EvalPar(const T *x, const Double_t *params = 0) const {
221 return EvalParVec(x, params);
222 }
223#ifdef R__HAS_VECCORE
224 ROOT::Double_v EvalParVec(const ROOT::Double_v *x, const Double_t *params = 0) const;
225#endif
226 TString GetExpFormula(Option_t *option="") const;
228 const TObject *GetLinearPart(Int_t i) const;
229 Int_t GetNdim() const {return fNdim;}
230 Int_t GetNpar() const {return fNpar;}
231 Int_t GetNumber() const { return fNumber; }
232 const char * GetParName(Int_t ipar) const;
233 Int_t GetParNumber(const char * name) const;
234 Double_t GetParameter(const char * name) const;
235 Double_t GetParameter(Int_t param) const;
236 Double_t* GetParameters() const;
237 void GetParameters(Double_t *params) const;
238 Double_t GetVariable(const char *name) const;
239 Int_t GetVarNumber(const char *name) const;
240 TString GetVarName(Int_t ivar) const;
241 Bool_t IsValid() const { return fReadyToExecute && fClingInitialized; }
242 Bool_t IsVectorized() const { return fVectorized; }
243 Bool_t IsLinear() const { return TestBit(kLinear); }
244 void Print(Option_t *option = "") const;
245 void SetName(const char* name);
246 void SetParameter(const char* name, Double_t value);
247 void SetParameter(Int_t param, Double_t value);
248 void SetParameters(const Double_t *params);
249 //void SetParameters(const pair<TString,Double_t> *params, const Int_t size);
250 void SetParameters(Double_t p0,Double_t p1,Double_t p2=0,Double_t p3=0,Double_t p4=0,
251 Double_t p5=0,Double_t p6=0,Double_t p7=0,Double_t p8=0,
252 Double_t p9=0,Double_t p10=0); // *MENU*
253 void SetParName(Int_t ipar, const char *name);
254 void SetParNames(const char *name0="p0",const char *name1="p1",const char
255 *name2="p2",const char *name3="p3",const char
256 *name4="p4", const char *name5="p5",const char *name6="p6",const char *name7="p7",const char
257 *name8="p8",const char *name9="p9",const char *name10="p10"); // *MENU*
258 void SetVariable(const TString &name, Double_t value);
259 void SetVariables(const std::pair<TString,Double_t> *vars, const Int_t size);
260 void SetVectorized(Bool_t vectorized);
261
263};
264#endif
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
int Int_t
Definition RtypesCore.h:45
const Bool_t kFALSE
Definition RtypesCore.h:92
bool Bool_t
Definition RtypesCore.h:63
double Double_t
Definition RtypesCore.h:59
const char Option_t
Definition RtypesCore.h:66
#define ClassDef(name, id)
Definition Rtypes.h:325
#define BIT(n)
Definition Rtypes.h:85
char name[80]
Definition TGX11.cxx:110
Helper class for TFormula.
Definition TFormula.h:30
const char * GetName() const
Definition TFormula.h:37
const char * GetBody() const
Definition TFormula.h:38
Int_t GetNargs() const
Definition TFormula.h:39
TString fName
Definition TFormula.h:32
TString fBody
Definition TFormula.h:33
Bool_t operator<(const TFormulaFunction &rhv) const
Definition TFormula.h:46
Bool_t fFuncCall
Definition TFormula.h:36
Bool_t IsFuncCall() const
Definition TFormula.h:40
Bool_t operator==(const TFormulaFunction &rhv) const
Definition TFormula.h:56
Another helper class for TFormula.
Definition TFormula.h:63
TString fName
Definition TFormula.h:65
Bool_t operator<(const TFormulaVariable &rhv) const
Definition TFormula.h:75
const char * GetName() const
Definition TFormula.h:69
Int_t GetArrayPos() const
Definition TFormula.h:71
Double_t GetInitialValue() const
Definition TFormula.h:70
Double_t fValue
Definition TFormula.h:66
The Formula class.
Definition TFormula.h:87
Double_t GetParameter(const char *name) const
Returns parameter value given by string.
Bool_t PrepareFormula(TString &formula)
prepare the formula to be executed normally is called with fFormula
std::atomic< Bool_t > fClingInitialized
trasient to force initialization
Definition TFormula.h:96
void FillDefaults()
Fill structures with default variables, constants and function shortcuts.
Definition TFormula.cxx:849
const TObject * GetLinearPart(Int_t i) const
Return linear part.
Bool_t IsLinear() const
Definition TFormula.h:243
void InputFormulaIntoCling()
Inputs formula, transfered to C++ code into Cling.
Definition TFormula.cxx:823
virtual ~TFormula()
Definition TFormula.cxx:413
void DoAddParameter(const TString &name, Double_t value, bool processFormula)
Adds parameter to known parameters.
bool HasGeneratedGradient() const
Definition TFormula.h:213
void HandleLinear(TString &formula)
Handle linear functions defined with the operator ++.
TString fClingName
pointer to a methodcall
Definition TFormula.h:101
TString GetVarName(Int_t ivar) const
Returns variable name given its position in the array.
void SetVariable(const TString &name, Double_t value)
Sets variable value.
std::vector< Double_t > GradientStorage
Definition TFormula.h:177
Int_t GetParNumber(const char *name) const
Return parameter index given a name (return -1 for not existing parameters) non need to print an erro...
void DoSetParameters(const Double_t *p, Int_t size)
TString GetGradientFormula() const
Double_t Eval(Double_t x) const
Sets first variable (e.g. x) and evaluate formula.
void HandleParametrizedFunctions(TString &formula)
Handling parametrized functions Function can be normalized, and have different variable then x.
TInterpreter::CallFuncIFacePtr_t::Generic_t CallFuncSignature
unique name used to defined the function and used in the global map (need to be saved in case of lazy...
Definition TFormula.h:104
Double_t * GetParameters() const
void SetParName(Int_t ipar, const char *name)
std::string fGradGenerationInput
Definition TFormula.h:105
Double_t EvalPar(const Double_t *x, const Double_t *params=0) const
static Bool_t IsAParameterName(const TString &formula, int ipos)
Definition TFormula.cxx:302
bool HasGradientGenerationFailed() const
Definition TFormula.h:130
void ReplaceParamName(TString &formula, const TString &oldname, const TString &name)
Replace in Formula expression the parameter name.
void SetPredefinedParamNames()
Set parameter names only in case of pre-defined functions.
std::map< TString, Double_t > fConsts
Definition TFormula.h:139
std::map< TString, TString > fFunctionsShortcuts
Definition TFormula.h:140
void HandleParamRanges(TString &formula)
Handling parameter ranges, in the form of [1..5].
std::vector< TObject * > fLinearParts
Definition TFormula.h:145
static Bool_t IsBracket(const char c)
Definition TFormula.cxx:243
Bool_t fVectorized
Definition TFormula.h:146
TString fClingInput
Definition TFormula.h:92
Bool_t PrepareEvalMethod()
Sets TMethodCall to function inside Cling environment.
Definition TFormula.cxx:808
Int_t fNumber
Number of parameter (transient since we save the vector)
Definition TFormula.h:144
std::string GetGradientFuncName() const
Definition TFormula.h:126
static bool fIsCladRuntimeIncluded
pointer to the lambda function
Definition TFormula.h:109
Double_t GetVariable(const char *name) const
Returns variable value.
std::list< TFormulaFunction > fFuncs
Definition TFormula.h:136
Bool_t fAllParametersSetted
transient to force re-initialization
Definition TFormula.h:97
void ProcessFormula(TString &formula)
Iterates through functors in fFuncs and performs the appropriate action.
static Bool_t IsOperator(const char c)
Definition TFormula.cxx:235
void SetVectorized(Bool_t vectorized)
void FillVecFunctionsShurtCuts()
Fill the shortcuts for vectorized functions We will replace for example sin with vecCore::Mat::Sin.
Definition TFormula.cxx:917
const char * GetParName(Int_t ipar) const
Return parameter name given by integer.
std::map< TString, TFormulaVariable > fVars
Definition TFormula.h:137
CallFuncSignature fFuncPtr
input query to clad to generate a gradient
Definition TFormula.h:106
void HandlePolN(TString &formula)
Handling polN If before 'pol' exist any name, this name will be treated as variable used in polynomia...
Definition TFormula.cxx:949
static Bool_t IsHexadecimal(const TString &formula, int ipos)
Definition TFormula.cxx:279
void ExtractFunctors(TString &formula)
Extracts functors from formula, and put them in fFuncs.
Int_t GetNumber() const
Definition TFormula.h:231
Bool_t InitLambdaExpression(const char *formula)
Definition TFormula.cxx:554
void SetParameters(const Double_t *params)
Set a vector of parameters value.
void AddParameter(const TString &name, Double_t value=0)
Definition TFormula.h:187
void Print(Option_t *option="") const
Print the formula and its attributes.
std::string fSavedInputFormula
unique name passed to Cling to define the function ( double clingName(double*x, double*p) )
Definition TFormula.h:102
void GradientPar(const Double_t *x, TFormula::GradientStorage &result)
Compute the gradient employing automatic differentiation.
void SetName(const char *name)
Set the name of the formula.
Bool_t IsValid() const
Definition TFormula.h:241
void ReplaceAllNames(TString &formula, std::map< TString, TString > &substitutions)
Definition TFormula.cxx:354
static Bool_t IsDefaultVariableName(const TString &name)
Definition TFormula.cxx:261
Int_t GetNpar() const
Definition TFormula.h:230
void FillParametrizedFunctions(std::map< std::pair< TString, Int_t >, std::pair< TString, TString > > &functions)
Fill map with parametrized functions.
void SetParNames(const char *name0="p0", const char *name1="p1", const char *name2="p2", const char *name3="p3", const char *name4="p4", const char *name5="p5", const char *name6="p6", const char *name7="p7", const char *name8="p8", const char *name9="p9", const char *name10="p10")
void AddVariables(const TString *vars, const Int_t size)
Adds multiple variables.
Int_t GetVarNumber(const char *name) const
Returns variable number (positon in array) given its name.
std::vector< Double_t > fClingVariables
input function passed to Cling
Definition TFormula.h:93
std::unique_ptr< TMethodCall > fMethod
transient flag to control lazy initialization (needed for reading from files)
Definition TFormula.h:99
TString fFormula
Definition TFormula.h:141
static Bool_t IsScientificNotation(const TString &formula, int ipos)
Definition TFormula.cxx:267
CallFuncSignature fGradFuncPtr
function pointer, owned by the JIT.
Definition TFormula.h:107
std::vector< Double_t > fClingParameters
cached variables
Definition TFormula.h:94
void SetParameter(const char *name, Double_t value)
Sets parameter value.
std::unique_ptr< TMethodCall > fGradMethod
pointer to methodcall
Definition TFormula.h:100
void PreProcessFormula(TString &formula)
Preprocessing of formula Replace all ** by ^, and removes spaces.
TString GetExpFormula(Option_t *option="") const
Return the expression formula.
Int_t fNdim
Definition TFormula.h:142
void SetVariables(const std::pair< TString, Double_t > *vars, const Int_t size)
Sets multiple variables.
void ReInitializeEvalMethod()
Re-initialize eval method.
@ kNotGlobal
Definition TFormula.h:172
@ kNormalized
Definition TFormula.h:173
void * fLambdaPtr
function pointer, owned by the JIT.
Definition TFormula.h:108
TFormula & operator=(const TFormula &rhs)
= operator.
Definition TFormula.cxx:544
Int_t Compile(const char *expression="")
Compile the given expression with Cling backward compatibility method to be used in combination with ...
Definition TFormula.cxx:599
Int_t fNpar
Definition TFormula.h:143
void HandleFunctionArguments(TString &formula)
Handling user functions (and parametrized functions) to take variables and optionally parameters as a...
std::map< TString, Int_t, TFormulaParamOrder > fParams
list of variable names
Definition TFormula.h:138
Bool_t IsVectorized() const
Definition TFormula.h:242
void AddVariable(const TString &name, Double_t value=0)
Adds variable to known variables, and reprocess formula.
Bool_t fLazyInitialization
Definition TFormula.h:98
Int_t GetNdim() const
Definition TFormula.h:229
virtual void Clear(Option_t *option="")
Clear the formula setting expression to empty and reset the variables and parameters containers.
Definition TFormula.cxx:716
void HandleExponentiation(TString &formula)
Handling exponentiation Can handle multiple carets, eg.
static Bool_t IsFunctionNameChar(const char c)
Definition TFormula.cxx:255
virtual void Copy(TObject &f1) const
Copy this to obj.
Definition TFormula.cxx:633
Double_t DoEval(const Double_t *x, const Double_t *p=nullptr) const
Evaluate formula.
Bool_t fReadyToExecute
Definition TFormula.h:95
bool GenerateGradientPar()
Generate gradient computation routine with respect to the parameters.
Method or function calling interface.
Definition TMethodCall.h:37
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
Mother of all ROOT objects.
Definition TObject.h:37
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:187
Basic string class.
Definition TString.h:136
Ssiz_t Length() const
Definition TString.h:410
const char * Data() const
Definition TString.h:369
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
TF1 * f1
Definition legend1.C:11
double T(double x)
Double_t Double_v
Definition Types.h:51
Functor defining the parameter order.
Definition TFormula.h:81
bool operator()(const TString &a, const TString &b) const
Definition TFormula.cxx:324
void(* Generic_t)(void *, int, void **, void *)