ROOT  6.06/04
Reference Guide
TFormula.cxx
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 
12 #if __cplusplus >= 201103L
13 #define ROOT_CPLUSPLUS11 1
14 #endif
15 
16 #include "TROOT.h"
17 #include "TClass.h"
18 #include "TMethod.h"
19 #include "TMath.h"
20 #include "TF1.h"
21 #include "TMethodCall.h"
22 #include <TBenchmark.h>
23 #include "TError.h"
24 #include "TInterpreter.h"
25 #include "TFormula.h"
26 #include <cassert>
27 #include <iostream>
28 #include <unordered_map>
29 #include <functional>
30 
31 using namespace std;
32 
33 // #define __STDC_LIMIT_MACROS
34 // #define __STDC_CONSTANT_MACROS
35 
36 // #include "cling/Interpreter/Interpreter.h"
37 // #include "cling/Interpreter/Value.h"
38 // #include "cling/Interpreter/StoredValueRef.h"
39 
40 
41 #ifdef WIN32
42 #pragma optimize("",off)
43 #endif
44 #include "v5/TFormula.h"
45 
47 /** \class TFormula TFormula.h "inc/TFormula.h"
48  \ingroup Hist
49 The F O R M U L A class
50 
51 <p>This is a new version of the TFormula class based on Cling.
52 This class is not 100% backward compatible with the old TFOrmula class, which is still available in ROOT as
53 <code>ROOT::v5::TFormula</code>. Some of the TFormula member funtions available in version 5, such as
54 <code>Analyze</code> and <code>AnalyzeFunction</code> are not available in the new TFormula.
55 On the other hand formula expressions which were valid in version 5 are still valid in TFormula version 6</p>
56 
57 <p>This class has been implemented during Google Summer of Code 2013 by Maciej Zimnoch.</p>
58 
59 <h3>Example of valid expressions:</h3>
60 
61 <ul>
62 <li><code>sin(x)/x</code></li>
63 <li><code>[0]*sin(x) + [1]*exp(-[2]*x)</code></li>
64 <li><code>x + y**2</code></li>
65 <li><code>x^2 + y^2</code></li>
66 <li><code>[0]*pow([1],4)</code></li>
67 <li><code>2*pi*sqrt(x/y)</code></li>
68 <li><code>gaus(0)*expo(3) + ypol3(5)*x</code></li>
69 <li><code>gausn(0)*expo(3) + ypol3(5)*x</code></li>
70 </ul>
71 
72 <p>In the last example above:</p>
73 
74 <ul>
75 <li><code>gaus(0)</code> is a substitute for <code>[0]*exp(-0.5*((x-[1])/[2])**2)</code>
76  and (0) means start numbering parameters at 0</li>
77 <li><code>gausn(0)</code> is a substitute for <code>[0]*exp(-0.5*((x-[1])/[2])**2)/(sqrt(2*pi)*[2]))</code>
78  and (0) means start numbering parameters at 0</li>
79 <li><code>expo(3)</code> is a substitute for <code>exp([3]+[4]*x</code></li>
80 <li><code>pol3(5)</code> is a substitute for <code>par[5]+par[6]*x+par[7]*x**2+par[8]*x**3</code>
81  (<code>PolN</code> stands for Polynomial of degree N)</li>
82 </ul>
83 
84 <p><code>TMath</code> functions can be part of the expression, eg:</p>
85 
86 <ul>
87 <li><code>TMath::Landau(x)*sin(x)</code></li>
88 <li><code>TMath::Erf(x)</code></li>
89 </ul>
90 
91 <p>Formula may contain constans, eg:</p>
92 
93 <ul>
94 <li><code>sqrt2</code></li>
95 <li><code>e</code></li>
96 <li><code>pi</code></li>
97 <li><code>ln10</code></li>
98 <li><code>infinity</code></li>
99 </ul>
100 
101 <p>and more.</p>
102 
103 <p>Comparisons operators are also supported <code>(&amp;&amp;, ||, ==, &lt;=, &gt;=, !)</code></p>
104 
105 <p>Examples:</p>
106 
107 <pre><code> `sin(x*(x&lt;0.5 || x&gt;1))`
108 </code></pre>
109 
110 <p>If the result of a comparison is TRUE, the result is 1, otherwise 0.</p>
111 
112 <p>Already predefined names can be given. For example, if the formula</p>
113 
114 <pre><code> `TFormula old("old",sin(x*(x&lt;0.5 || x&gt;1)))`
115 </code></pre>
116 
117 <p>one can assign a name to the formula. By default the name of the object = title = formula itself.</p>
118 
119 <pre><code> `TFormula new("new","x*old")`
120 </code></pre>
121 
122 <p>is equivalent to:</p>
123 
124 <pre><code> `TFormula new("new","x*sin(x*(x&lt;0.5 || x&gt;1))")`
125 </code></pre>
126 
127 <p>The class supports unlimited numer of variables and parameters.
128  By default the names which can be used for the variables are <code>x,y,z,t</code> or
129  <code>x[0],x[1],x[2],x[3],....x[N]</code> for N-dimensionals formula.</p>
130 
131 <p>This class is not anymore the base class for the function classes <code>TF1</code>, but it has now
132 adata member of TF1 which can be access via <code>TF1::GetFormula</code>. </p>
133 
134 
135 \class TFormulaFunction
136  Helper class for TFormula
137 \class TFormulaVariable
138  Another helper class for TFormula
139 \class TFormulaParamOrder
140  Functor defining the parameter order
141 
142 */
143 
144 // prefix used for function name passed to Cling
145 static const TString gNamePrefix = "TFormula__";
146 
147 // static map of function pointers and expressions
148 //static std::unordered_map<std::string, TInterpreter::CallFuncIFacePtr_t::Generic_t> gClingFunctions = std::unordered_map<TString, TInterpreter::CallFuncIFacePtr_t::Generic_t>();
149 static std::unordered_map<std::string, void *> gClingFunctions = std::unordered_map<std::string, void * >();
150 
151 Bool_t TFormula::IsOperator(const char c)
152 {
153  // operator ":" must be handled separatly
154  char ops[] = { '+','^', '-','/','*','<','>','|','&','!','=','?'};
155  Int_t opsLen = sizeof(ops)/sizeof(char);
156  for(Int_t i = 0; i < opsLen; ++i)
157  if(ops[i] == c)
158  return true;
159  return false;
160 }
161 
163 {
164  char brackets[] = { ')','(','{','}'};
165  Int_t bracketsLen = sizeof(brackets)/sizeof(char);
166  for(Int_t i = 0; i < bracketsLen; ++i)
167  if(brackets[i] == c)
168  return true;
169  return false;
170 }
171 
173 {
174  return !IsBracket(c) && !IsOperator(c) && c != ',' && c != ' ';
175 }
176 
178 {
179  return name == "x" || name == "z" || name == "y" || name == "t";
180 }
181 
182 
184 {
185  // check if the character at position i is part of a scientific notation
186  if ( (formula[i] == 'e' || formula[i] == 'E') && (i > 0 && i < formula.Length()-1) ) {
187  // handle cases: 2e+3 2e-3 2e3 and 2.e+3
188  if ( (isdigit(formula[i-1]) || formula[i-1] == '.') && ( isdigit(formula[i+1]) || formula[i+1] == '+' || formula[i+1] == '-' ) )
189  return true;
190  }
191  return false;
192 }
193 
194 Bool_t TFormula::IsHexadecimal(const TString & formula, int i)
195 {
196  // check if the character at position i is part of a scientific notation
197  if ( (formula[i] == 'x' || formula[i] == 'X') && (i > 0 && i < formula.Length()-1) && formula[i-1] == '0') {
198  if (isdigit(formula[i+1]) )
199  return true;
200  static char hex_values[12] = { 'a','A', 'b','B','c','C','d','D','e','E','f','F'};
201  for (int jjj = 0; jjj < 12; ++jjj) {
202  if (formula[i+1] == hex_values[jjj])
203  return true;
204  }
205  }
206  // else
207  // return false;
208  // // handle cases: 2e+3 2e-3 2e3 and 2.e+3
209  // if ( (isdigit(formula[i-1]) || formula[i-1] == '.') && ( isdigit(formula[i+1]) || formula[i+1] == '+' || formula[i+1] == '-' ) )
210  // return true;
211  // }
212  return false;
213 }
214 
215 bool TFormulaParamOrder::operator() (const TString& a, const TString& b) const {
216  // implement comparison used to set parameter orders in TFormula
217  // want p2 to be before p10
218 
219  // strip first character in case you have (p0, p1, pN)
220  if ( a[0] == 'p' && a.Length() > 1) {
221  if ( b[0] == 'p' && b.Length() > 1) {
222  // strip first character
223  TString lhs = a(1,a.Length()-1);
224  TString rhs = b(1,b.Length()-1);
225  if (lhs.IsDigit() && rhs.IsDigit() )
226  return (lhs.Atoi() < rhs.Atoi() );
227  }
228  else {
229  return true; // assume a(a numeric name) is always before b (an alphanumeric name)
230  }
231  }
232  else {
233  if ( b[0] == 'p' && b.Length() > 1)
234  // now b is numeric and a is not so return false
235  return false;
236 
237  // case both names are numeric
238  if (a.IsDigit() && b.IsDigit() )
239  return (a.Atoi() < b.Atoi() );
240 
241  }
242 
243  return a < b;
244 }
245 
247 {
248  fName = "";
249  fTitle = "";
250  fClingInput = "";
251  fReadyToExecute = false;
252  fClingInitialized = false;
253  fAllParametersSetted = false;
254  fMethod = 0;
255  fNdim = 0;
256  fNpar = 0;
257  fNumber = 0;
258  fClingName = "";
259  fFormula = "";
260  fLambdaPtr = nullptr;
261 }
262 
263 ////////////////////////////////////////////////////////////////////////////////
264 
265 static bool IsReservedName(const char* name){
266  if (strlen(name)!=1) return false;
267  for (auto const & specialName : {"x","y","z","t"}){
268  if (strcmp(name,specialName)==0) return true;
269  }
270  return false;
271 }
272 
273 
275 {
276 
277  // N.B. a memory leak may happen if user set bit after constructing the object,
278  // Setting of bit should be done only internally
279  if (!TestBit(TFormula::kNotGlobal) && gROOT ) {
281  gROOT->GetListOfFunctions()->Remove(this);
282  }
283 
284  if(fMethod)
285  {
286  fMethod->Delete();
287  }
288  int nLinParts = fLinearParts.size();
289  if (nLinParts > 0) {
290  for (int i = 0; i < nLinParts; ++i) delete fLinearParts[i];
291  }
292 }
293 
294 TFormula::TFormula(const char *name, const char *formula, bool addToGlobList) :
295  TNamed(name,formula),
296  fClingInput(formula),fFormula(formula)
297 {
298  fReadyToExecute = false;
299  fClingInitialized = false;
300  fMethod = 0;
301  fNdim = 0;
302  fNpar = 0;
303  fNumber = 0;
304  fLambdaPtr = nullptr;
305 
306  FillDefaults();
307 
308 
309  if (addToGlobList && gROOT) {
310  TFormula *old = 0;
312  old = dynamic_cast<TFormula*> ( gROOT->GetListOfFunctions()->FindObject(name) );
313  if (old)
314  gROOT->GetListOfFunctions()->Remove(old);
315  if (IsReservedName(name))
316  Error("TFormula","The name %s is reserved as a TFormula variable name.\n",name);
317  else
318  gROOT->GetListOfFunctions()->Add(this);
319  }
320  SetBit(kNotGlobal,!addToGlobList);
321 
322  //fName = gNamePrefix + name; // is this needed
323 
324  // do not process null formulas.
325  if (!fFormula.IsNull() ) {
327 
329  }
330 
331 }
332 
333 /// constructor from a full compileable C++ expression
334 TFormula::TFormula(const char *name, const char *formula, int ndim, int npar, bool addToGlobList) :
335  TNamed(name,formula),
336  fClingInput(formula),fFormula(formula)
337 {
338  fReadyToExecute = false;
339  fClingInitialized = false;
340  fNpar = 0;
341  fLambdaPtr = nullptr;
342 
343 
344  fNdim = ndim;
345  for (int i = 0; i < npar; ++i) {
346  DoAddParameter(TString::Format("p%d",i), 0, false);
347  }
348  fAllParametersSetted = true;
349  assert (fNpar == npar);
350 
351  bool ret = InitLambdaExpression(formula);
352 
353  if (ret) {
354 
356 
357  fReadyToExecute = true;
358 
359  if (addToGlobList && gROOT) {
360  TFormula *old = 0;
362  old = dynamic_cast<TFormula*> ( gROOT->GetListOfFunctions()->FindObject(name) );
363  if (old)
364  gROOT->GetListOfFunctions()->Remove(old);
365  if (IsReservedName(name))
366  Error("TFormula","The name %s is reserved as a TFormula variable name.\n",name);
367  else
368  gROOT->GetListOfFunctions()->Add(this);
369  }
370  SetBit(kNotGlobal,!addToGlobList);
371  }
372  else
373  Error("TFormula","Syntax error in building the lambda expression %s", formula );
374 }
375 
376 
377 TFormula::TFormula(const TFormula &formula) :
378  TNamed(formula.GetName(),formula.GetTitle())
379 {
380  fReadyToExecute = false;
381  fClingInitialized = false;
382  fMethod = 0;
383  fNdim = formula.GetNdim();
384  fNpar = formula.GetNpar();
385  fNumber = formula.GetNumber();
386  fFormula = formula.GetExpFormula(); // returns fFormula in case of Lambda's
387  fLambdaPtr = nullptr;
388 
389  // case of function based on a C++ expression (lambda's) which is ready to be compiled
390  if (formula.fLambdaPtr && formula.TestBit(TFormula::kLambda)) {
391 
393  fParams = formula.fParams;
396 
397  bool ret = InitLambdaExpression(fFormula);
398 
399  if (ret) {
401  fReadyToExecute = true;
402  }
403  else
404  Error("TFormula","Syntax error in building the lambda expression %s", fFormula.Data() );
405 
406  }
407  else {
408 
409  FillDefaults();
410 
413  }
414 
415 
416  if (!TestBit(TFormula::kNotGlobal) && gROOT ) {
418  TFormula *old = (TFormula*)gROOT->GetListOfFunctions()->FindObject(formula.GetName());
419  if (old)
420  gROOT->GetListOfFunctions()->Remove(old);
421 
422  if (IsReservedName(formula.GetName())) {
423  Error("TFormula","The name %s is reserved as a TFormula variable name.\n",formula.GetName());
424  } else
425  gROOT->GetListOfFunctions()->Add(this);
426  }
427 
428 }
429 
431 {
432  //*-*
433  //*-* = Operator
434  //*-*
435 
436  if (this != &rhs) {
437  rhs.Copy(*this);
438  }
439  return *this;
440 }
441 
442 Bool_t TFormula::InitLambdaExpression(const char * formula) {
443 
444  std::string lambdaExpression = formula;
445 
446  // check if formula exist already in the map
447  {
449 
450  auto funcit = gClingFunctions.find(lambdaExpression);
451  if (funcit != gClingFunctions.end() ) {
452  fLambdaPtr = funcit->second;
453  fClingInitialized = true;
454  return true;
455  }
456  }
457 
458  // set the cling name using hash of the static formulae map
459  auto hasher = gClingFunctions.hash_function();
460  TString lambdaName = TString::Format("lambda__id%zu",(unsigned long) hasher(lambdaExpression) );
461 
462  //lambdaExpression = TString::Format("[&](double * x, double *){ return %s ;}",formula);
463  //TString lambdaName = TString::Format("mylambda_%s",GetName() );
464  TString lineExpr = TString::Format("std::function<double(double*,double*)> %s = %s ;",lambdaName.Data(), lambdaExpression.c_str() );
465  gInterpreter->ProcessLine(lineExpr);
466  fLambdaPtr = (void*) gInterpreter->ProcessLine(TString(lambdaName)+TString(";")); // add ; to avoid printing
467  if (fLambdaPtr != nullptr) {
469  gClingFunctions.insert ( std::make_pair ( lambdaExpression, fLambdaPtr) );
470  fClingInitialized = true;
471  return true;
472  }
473  fClingInitialized = false;
474  return false;
475 }
476 
477 
478 
479 Int_t TFormula::Compile(const char *expression)
480 {
481  // Compile the given expression with Cling
482  // backward compatibility method to be used in combination with the empty constructor
483  // if no expression is given , the current stored formula (retrieved with GetExpFormula()) or the title is used.
484  // return 0 if the formula compilation is successfull
485 
486 
487  TString formula = expression;
488  if (formula.IsNull() ) {
489  formula = fFormula;
490  if (formula.IsNull() ) formula = GetTitle();
491  }
492 
493  if (formula.IsNull() ) return -1;
494 
495  // do not re-process if it was done before
496  if (IsValid() && formula == fFormula ) return 0;
497 
498  // clear if a formula was already existing
499  if (!fFormula.IsNull() ) Clear();
500 
501  fFormula = formula;
502 
503  if (TestBit(TFormula::kLambda) ) {
504  bool ret = InitLambdaExpression(fFormula);
505  return (ret) ? 0 : 1;
506  }
507 
508  if (fVars.empty() ) FillDefaults();
509  // prepare the formula for Cling
510  //printf("compile: processing formula %s\n",fFormula.Data() );
512  // pass formula in CLing
513  bool ret = PrepareFormula(fFormula);
514 
515  return (ret) ? 0 : 1;
516 }
517 
518 void TFormula::Copy(TObject &obj) const
519 {
520  TNamed::Copy(obj);
521  // need to copy also cling parameters
522  TFormula & fnew = dynamic_cast<TFormula&>(obj);
523 
526 
527  fnew.fFuncs = fFuncs;
528  fnew.fVars = fVars;
529  fnew.fParams = fParams;
530  fnew.fConsts = fConsts;
532  fnew.fFormula = fFormula;
533  fnew.fNdim = fNdim;
534  fnew.fNpar = fNpar;
535  fnew.fNumber = fNumber;
537  // copy Linear parts (it is a vector of TFormula pointers) needs to be copied one by one
538  // looping at all the elements
539  // delete first previous elements
540  int nLinParts = fnew.fLinearParts.size();
541  if (nLinParts > 0) {
542  for (int i = 0; i < nLinParts; ++i) delete fnew.fLinearParts[i];
543  fnew.fLinearParts.clear();
544  }
545  // old size that needs to be copied
546  nLinParts = fLinearParts.size();
547  if (nLinParts > 0) {
548  fnew.fLinearParts.reserve(nLinParts);
549  for (int i = 0; i < nLinParts; ++i) {
550  TFormula * linearNew = new TFormula();
551  TFormula * linearOld = (TFormula*) fLinearParts[i];
552  if (linearOld) {
553  linearOld->Copy(*linearNew);
554  fnew.fLinearParts.push_back(linearNew);
555  }
556  else
557  Warning("Copy","Function %s - expr %s has a dummy linear part %d",GetName(),GetExpFormula().Data(),i);
558  }
559  }
560 
561  fnew.fClingInput = fClingInput;
565  fnew.fClingName = fClingName;
566 
567  // case of function based on a C++ expression (lambda's) which is ready to be compiled
569 
570  bool ret = fnew.InitLambdaExpression(fnew.fFormula);
571  if (ret) {
573  fnew.fReadyToExecute = true;
574  }
575  else {
576  Error("TFormula","Syntax error in building the lambda expression %s", fFormula.Data() );
577  fnew.fReadyToExecute = false;
578  }
579  }
580  else if (fMethod) {
581  if (fnew.fMethod) delete fnew.fMethod;
582  // use copy-constructor of TMethodCall
583  TMethodCall *m = new TMethodCall(*fMethod);
584  fnew.fMethod = m;
585  }
586 
587  fnew.fFuncPtr = fFuncPtr;
588 
589 }
590 
592 {
593  // clear the formula setting expression to empty and reset the variables and parameters containers
594  fNdim = 0;
595  fNpar = 0;
596  fNumber = 0;
597  fFormula = "";
598  fClingName = "";
599 
600 
601  if(fMethod) fMethod->Delete();
602  fMethod = nullptr;
603 
604  fClingVariables.clear();
605  fClingParameters.clear();
606  fReadyToExecute = false;
607  fClingInitialized = false;
608  fAllParametersSetted = false;
609  fFuncs.clear();
610  fVars.clear();
611  fParams.clear();
612  fConsts.clear();
613  fFunctionsShortcuts.clear();
614 
615  // delete linear parts
616  int nLinParts = fLinearParts.size();
617  if (nLinParts > 0) {
618  for (int i = 0; i < nLinParts; ++i) delete fLinearParts[i];
619  }
620  fLinearParts.clear();
621 
622 }
624 {
625  //*-*
626  //*-* Sets TMethodCall to function inside Cling environment
627  //*-* TFormula uses it to execute function.
628  //*-* After call, TFormula should be ready to evaluate formula.
629  //*-*
630  if(!fMethod)
631  {
632  fMethod = new TMethodCall();
633 
634  Bool_t hasParameters = (fNpar > 0);
635  Bool_t hasVariables = (fNdim > 0);
636  TString prototypeArguments = "";
637  if(hasVariables)
638  {
639  prototypeArguments.Append("Double_t*");
640  }
641  if(hasVariables && hasParameters)
642  {
643  prototypeArguments.Append(",");
644  }
645  if(hasParameters)
646  {
647  prototypeArguments.Append("Double_t*");
648  }
649  // init method call using real function name (cling name) which is defined in ProcessFormula
650  fMethod->InitWithPrototype(fClingName,prototypeArguments);
651  if(!fMethod->IsValid())
652  {
653  Error("Eval","Can't find %s function prototype with arguments %s",fClingName.Data(),prototypeArguments.Data());
654  return false;
655  }
656 
657  // not needed anymore since we use the function pointer
658  // if(hasParameters)
659  // {
660  // Long_t args[2];
661  // args[0] = (Long_t)fClingVariables.data();
662  // args[1] = (Long_t)fClingParameters.data();
663  // fMethod->SetParamPtrs(args,2);
664  // }
665  // else
666  // {
667  // Long_t args[1];
668  // args[0] = (Long_t)fClingVariables.data();
669  // fMethod->SetParamPtrs(args,1);
670  // }
671 
672  CallFunc_t * callfunc = fMethod->GetCallFunc();
674  fFuncPtr = faceptr.fGeneric;
675  }
676  return true;
677 }
678 
680 {
681  //*-*
682  //*-* Inputs formula, transfered to C++ code into Cling
683  //*-*
685  {
688  }
689 }
691 {
692  //*-*
693  //*-* Fill structures with default variables, constants and function shortcuts
694  //*-*
695 //#ifdef ROOT_CPLUSPLUS11
696 
697  const TString defvars[] = { "x","y","z","t"};
698  const pair<TString,Double_t> defconsts[] = { {"pi",TMath::Pi()}, {"sqrt2",TMath::Sqrt2()},
699  {"infinity",TMath::Infinity()}, {"e",TMath::E()}, {"ln10",TMath::Ln10()},
700  {"loge",TMath::LogE()}, {"c",TMath::C()}, {"g",TMath::G()},
701  {"h",TMath::H()}, {"k",TMath::K()},{"sigma",TMath::Sigma()},
702  {"r",TMath::R()}, {"eg",TMath::EulerGamma()},{"true",1},{"false",0} };
703  // const pair<TString,Double_t> defconsts[] = { {"pi",TMath::Pi()}, {"sqrt2",TMath::Sqrt2()},
704  // {"infinity",TMath::Infinity()}, {"ln10",TMath::Ln10()},
705  // {"loge",TMath::LogE()}, {"true",1},{"false",0} };
706  const pair<TString,TString> funShortcuts[] =
707  { {"sin","TMath::Sin" },
708  {"cos","TMath::Cos" }, {"exp","TMath::Exp"}, {"log","TMath::Log"}, {"log10","TMath::Log10"},
709  {"tan","TMath::Tan"}, {"sinh","TMath::SinH"}, {"cosh","TMath::CosH"},
710  {"tanh","TMath::TanH"}, {"asin","TMath::ASin"}, {"acos","TMath::ACos"},
711  {"atan","TMath::ATan"}, {"atan2","TMath::ATan2"}, {"sqrt","TMath::Sqrt"},
712  {"ceil","TMath::Ceil"}, {"floor","TMath::Floor"}, {"pow","TMath::Power"},
713  {"binomial","TMath::Binomial"},{"abs","TMath::Abs"},
714  {"min","TMath::Min"},{"max","TMath::Max"},{"sign","TMath::Sign" },
715  {"sq","TMath::Sq"}
716  };
717 
718  std::vector<TString> defvars2(10);
719  for (int i = 0; i < 9; ++i)
720  defvars2[i] = TString::Format("x[%d]",i);
721 
722  for(auto var : defvars)
723  {
724  int pos = fVars.size();
725  fVars[var] = TFormulaVariable(var,0,pos);
726  fClingVariables.push_back(0);
727  }
728  // add also the variables definesd like x[0],x[1],x[2],...
729  // support up to x[9] - if needed extend that to higher value
730  // const int maxdim = 10;
731  // for (int i = 0; i < maxdim; ++i) {
732  // TString xvar = TString::Format("x[%d]",i);
733  // fVars[xvar] = TFormulaVariable(xvar,0,i);
734  // fClingVariables.push_back(0);
735  // }
736 
737  for(auto con : defconsts)
738  {
739  fConsts[con.first] = con.second;
740  }
741  for(auto fun : funShortcuts)
742  {
743  fFunctionsShortcuts[fun.first] = fun.second;
744  }
745 
746 /*** - old code tu support C++03
747 #else
748 
749  TString defvarsNames[] = {"x","y","z","t"};
750  Int_t defvarsLength = sizeof(defvarsNames)/sizeof(TString);
751 
752  TString defconstsNames[] = {"pi","sqrt2","infinity","e","ln10","loge","c","g","h","k","sigma","r","eg","true","false"};
753  Double_t defconstsValues[] = {TMath::Pi(),TMath::Sqrt2(),TMath::Infinity(),TMath::E(),TMath::Ln10(),TMath::LogE(),
754  TMath::C(),TMath::G(),TMath::H(),TMath::K(),TMath::Sigma(),TMath::R(),TMath::EulerGamma(), 1, 0};
755  Int_t defconstsLength = sizeof(defconstsNames)/sizeof(TString);
756 
757  TString funShortcutsNames[] = {"sin","cos","exp","log","tan","sinh","cosh","tanh","asin","acos","atan","atan2","sqrt",
758  "ceil","floor","pow","binomial","abs"};
759  TString funShortcutsExtendedNames[] = {"TMath::Sin","TMath::Cos","TMath::Exp","TMath::Log","TMath::Tan","TMath::SinH",
760  "TMath::CosH","TMath::TanH","TMath::ASin","TMath::ACos","TMath::ATan","TMath::ATan2",
761  "TMath::Sqrt","TMath::Ceil","TMath::Floor","TMath::Power","TMath::Binomial","TMath::Abs"};
762  Int_t funShortcutsLength = sizeof(funShortcutsNames)/sizeof(TString);
763 
764  for(Int_t i = 0; i < defvarsLength; ++i)
765  {
766  TString var = defvarsNames[i];
767  Double_t value = 0;
768  unsigned int pos = fVars.size();
769  fVars[var] = TFormulaVariable(var,value,pos);
770  fClingVariables.push_back(value);
771  }
772 
773  for(Int_t i = 0; i < defconstsLength; ++i)
774  {
775  fConsts[defconstsNames[i]] = defconstsValues[i];
776  }
777  for(Int_t i = 0; i < funShortcutsLength; ++i)
778  {
779  pair<TString,TString> fun(funShortcutsNames[i],funShortcutsExtendedNames[i]);
780  fFunctionsShortcuts[fun.first] = fun.second;
781  }
782 
783 #endif
784 ***/
785 
786 }
787 
789 {
790  //*-*
791  //*-* Handling polN
792  //*-* If before 'pol' exist any name, this name will be treated as variable used in polynomial
793  //*-* eg.
794  //*-* varpol2(5) will be replaced with: [5] + [6]*var + [7]*var^2
795  //*-* Empty name is treated like variable x.
796  //*-*
797  Int_t polPos = formula.Index("pol");
798  while(polPos != kNPOS)
799  {
800 
801  Bool_t defaultVariable = false;
802  TString variable;
803  Int_t openingBracketPos = formula.Index('(',polPos);
804  Bool_t defaultCounter = openingBracketPos == kNPOS;
805  Bool_t defaultDegree = true;
806  Int_t degree,counter;
807  TString sdegree;
808  if(!defaultCounter)
809  {
810  // veryfy first of opening parenthesis belongs to pol expression
811  // character between 'pol' and '(' must all be digits
812  sdegree = formula(polPos + 3,openingBracketPos - polPos - 3);
813  if (!sdegree.IsDigit() ) defaultCounter = true;
814  }
815  if (!defaultCounter) {
816  degree = sdegree.Atoi();
817  counter = TString(formula(openingBracketPos+1,formula.Index(')',polPos) - openingBracketPos)).Atoi();
818  }
819  else
820  {
821  Int_t temp = polPos+3;
822  while(temp < formula.Length() && isdigit(formula[temp]))
823  {
824  defaultDegree = false;
825  temp++;
826  }
827  degree = TString(formula(polPos+3,temp - polPos - 3)).Atoi();
828  counter = 0;
829  }
830 
831  TString replacement = TString::Format("[%d]",counter);
832  if(polPos - 1 < 0 || !IsFunctionNameChar(formula[polPos-1]) || formula[polPos-1] == ':' )
833  {
834  variable = "x";
835  defaultVariable = true;
836  }
837  else
838  {
839  Int_t tmp = polPos - 1;
840  while(tmp >= 0 && IsFunctionNameChar(formula[tmp]) && formula[tmp] != ':')
841  {
842  tmp--;
843  }
844  variable = formula(tmp + 1, polPos - (tmp+1));
845  }
846  Int_t param = counter + 1;
847  Int_t tmp = 1;
848  while(tmp <= degree)
849  {
850  replacement.Append(TString::Format("+[%d]*%s^%d",param,variable.Data(),tmp));
851  param++;
852  tmp++;
853  }
855  if(defaultCounter && !defaultDegree)
856  {
857  pattern = TString::Format("%spol%d",(defaultVariable ? "" : variable.Data()),degree);
858  }
859  else if(defaultCounter && defaultDegree)
860  {
861  pattern = TString::Format("%spol",(defaultVariable ? "" : variable.Data()));
862  }
863  else
864  {
865  pattern = TString::Format("%spol%d(%d)",(defaultVariable ? "" : variable.Data()),degree,counter);
866  }
867 
868  if (!formula.Contains(pattern)) {
869  Error("HandlePolN","Error handling polynomial function - expression is %s - trying to replace %s with %s ", formula.Data(), pattern.Data(), replacement.Data() );
870  break;
871  }
872  if (formula == pattern) {
873  // case of single polynomial
874  SetBit(kLinear,1);
875  fNumber = 300 + degree;
876  }
877  formula.ReplaceAll(pattern,replacement);
878  polPos = formula.Index("pol");
879  }
880 }
882 {
883  //*-*
884  //*-* Handling parametrized functions
885  //*-* Function can be normalized, and have different variable then x.
886  //*-* Variables should be placed in brackets after function name.
887  //*-* No brackets are treated like [x].
888  //*-* Normalized function has char 'n' after name, eg.
889  //*-* gausn[var](0) will be replaced with [0]*exp(-0.5*((var-[1])/[2])^2)/(sqrt(2*pi)*[2])
890  //*-*
891  //*-* Adding function is easy, just follow these rules:
892  //*-* - Key for function map is pair of name and dimension of function
893  //*-* - value of key is a pair function body and normalized function body
894  //*-* - {Vn} is a place where variable appear, n represents n-th variable from variable list.
895  //*-* Count starts from 0.
896  //*-* - [num] stands for parameter number.
897  //*-* If user pass to function argument 5, num will stand for (5 + num) parameter.
898  //*-*
899 
900  map< pair<TString,Int_t> ,pair<TString,TString> > functions;
901  functions.insert(make_pair(make_pair("gaus",1),make_pair("[0]*exp(-0.5*(({V0}-[1])/[2])*(({V0}-[1])/[2]))","[0]*exp(-0.5*(({V0}-[1])/[2])*(({V0}-[1])/[2]))/(sqrt(2*pi)*[2])")));
902  functions.insert(make_pair(make_pair("landau",1),make_pair("[0]*TMath::Landau({V0},[1],[2],false)","[0]*TMath::Landau({V0},[1],[2],true)")));
903  functions.insert(make_pair(make_pair("expo",1),make_pair("exp([0]+[1]*{V0})","")));
904  functions.insert(make_pair(make_pair("crystalball",1),make_pair("[0]*ROOT::Math::crystalball_function({V0},[3],[4],[2],[1])","[0]*ROOT::Math::crystalball_pdf({V0},[3],[4],[2],[1])")));
905  functions.insert(make_pair(make_pair("breitwigner",1),make_pair("[0]*ROOT::Math::breitwigner_pdf({V0},[2],[1])","[0]*ROOT::Math::breitwigner_pdf({V0},[2],[4],[1])")));
906  // chebyshev polynomial
907  functions.insert(make_pair(make_pair("cheb0" ,1),make_pair("ROOT::Math::Chebyshev0({V0},[0])","")));
908  functions.insert(make_pair(make_pair("cheb1" ,1),make_pair("ROOT::Math::Chebyshev1({V0},[0],[1])","")));
909  functions.insert(make_pair(make_pair("cheb2" ,1),make_pair("ROOT::Math::Chebyshev2({V0},[0],[1],[2])","")));
910  functions.insert(make_pair(make_pair("cheb3" ,1),make_pair("ROOT::Math::Chebyshev3({V0},[0],[1],[2],[3])","")));
911  functions.insert(make_pair(make_pair("cheb4" ,1),make_pair("ROOT::Math::Chebyshev4({V0},[0],[1],[2],[3],[4])","")));
912  functions.insert(make_pair(make_pair("cheb5" ,1),make_pair("ROOT::Math::Chebyshev5({V0},[0],[1],[2],[3],[4],[5])","")));
913  functions.insert(make_pair(make_pair("cheb6" ,1),make_pair("ROOT::Math::Chebyshev6({V0},[0],[1],[2],[3],[4],[5],[6])","")));
914  functions.insert(make_pair(make_pair("cheb7" ,1),make_pair("ROOT::Math::Chebyshev7({V0},[0],[1],[2],[3],[4],[5],[6],[7])","")));
915  functions.insert(make_pair(make_pair("cheb8" ,1),make_pair("ROOT::Math::Chebyshev8({V0},[0],[1],[2],[3],[4],[5],[6],[7],[8])","")));
916  functions.insert(make_pair(make_pair("cheb9" ,1),make_pair("ROOT::Math::Chebyshev9({V0},[0],[1],[2],[3],[4],[5],[6],[7],[8],[9])","")));
917  functions.insert(make_pair(make_pair("cheb10",1),make_pair("ROOT::Math::Chebyshev10({V0},[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10])","")));
918  // 2-dimensional functions
919  functions.insert(make_pair(make_pair("gaus",2),make_pair("[0]*exp(-0.5*(({V0}-[1])/[2])^2 - 0.5*(({V1}-[3])/[4])^2)","")));
920  functions.insert(make_pair(make_pair("landau",2),make_pair("[0]*TMath::Landau({V0},[1],[2],false)*TMath::Landau({V1},[3],[4],false)","")));
921  functions.insert(make_pair(make_pair("expo",2),make_pair("exp([0]+[1]*{V0})","exp([0]+[1]*{V0}+[2]*{V1})")));
922 
923  map<TString,Int_t> functionsNumbers;
924  functionsNumbers["gaus"] = 100;
925  functionsNumbers["landau"] = 400;
926  functionsNumbers["expo"] = 200;
927  functionsNumbers["crystalball"] = 500;
928 
929  // replace old names xygaus -> gaus[x,y]
930  formula.ReplaceAll("xygaus","gaus[x,y]");
931  formula.ReplaceAll("xylandau","landau[x,y]");
932  formula.ReplaceAll("xyexpo","expo[x,y]");
933 
934  for(map<pair<TString,Int_t>,pair<TString,TString> >::iterator it = functions.begin(); it != functions.end(); ++it)
935  {
936 
937  TString funName = it->first.first;
938  Int_t funPos = formula.Index(funName);
939 
940 
941 
942  //std::cout << formula << " ---- " << funName << " " << funPos << std::endl;
943  while(funPos != kNPOS)
944  {
945 
946  // should also check that function is not something else (e.g. exponential - parse the expo)
947  Int_t lastFunPos = funPos + funName.Length();
948 
949  // check that first and last character is not alphanumeric
950  Int_t iposBefore = funPos - 1;
951  //std::cout << "looping on funpos is " << funPos << " formula is " << formula << std::endl;
952  if (iposBefore >= 0) {
953  assert( iposBefore < formula.Length() );
954  if (isalpha(formula[iposBefore] ) ) {
955  //std::cout << "previous character for function " << funName << " is -" << formula[iposBefore] << "- skip " << std::endl;
956  break;
957  }
958  }
959 
960  Bool_t isNormalized = false;
961  if (lastFunPos < formula.Length() ) {
962  // check if function is normalized by looking at "n" character after function name (e.g. gausn)
963  isNormalized = (formula[lastFunPos] == 'n');
964  if (isNormalized) lastFunPos += 1;
965  if (lastFunPos < formula.Length() ) {
966  // check if also last character is not alphanumeric or a digit
967  if (isalnum(formula[lastFunPos] ) ) break;
968  if (formula[lastFunPos] != '[' && formula[lastFunPos] != '(' && ! IsOperator(formula[lastFunPos] ) ) {
969  funPos = formula.Index(funName,lastFunPos);
970  continue;
971  }
972  }
973  }
974 
975  if(isNormalized)
976  {
977  SetBit(kNormalized,1);
978  }
979  std::vector<TString> variables;
980  Int_t dim = 0;
981  TString varList = "";
982  Bool_t defaultVariable = false;
983 
984  // check if function has specified the [...] e.g. gaus[x,y]
985  Int_t openingBracketPos = funPos + funName.Length() + (isNormalized ? 1 : 0);
986  Int_t closingBracketPos = kNPOS;
987  if(openingBracketPos > formula.Length() || formula[openingBracketPos] != '[')
988  {
989  dim = 1;
990  variables.resize(dim);
991  variables[0] = "x";
992  defaultVariable = true;
993  }
994  else
995  {
996  // in case of [..] found, assume they specify all the variables. Use it to get function dimension
997  closingBracketPos = formula.Index(']',openingBracketPos);
998  varList = formula(openingBracketPos+1,closingBracketPos - openingBracketPos - 1);
999  dim = varList.CountChar(',') + 1;
1000  variables.resize(dim);
1001  Int_t Nvar = 0;
1002  TString varName = "";
1003  for(Int_t i = 0 ; i < varList.Length(); ++i)
1004  {
1005  if(IsFunctionNameChar(varList[i]))
1006  {
1007  varName.Append(varList[i]);
1008  }
1009  if(varList[i] == ',')
1010  {
1011  variables[Nvar] = varName;
1012  varName = "";
1013  Nvar++;
1014  }
1015  }
1016  if(varName != "") // we will miss last variable
1017  {
1018  variables[Nvar] = varName;
1019  }
1020  }
1021  // chech if dimension obtained from [...] is compatible with existing pre-defined functions
1022  if(dim != it->first.second)
1023  {
1024  pair<TString,Int_t> key = make_pair(funName,dim);
1025  if(functions.find(key) == functions.end())
1026  {
1027  Error("PreProcessFormula","%d dimension function %s is not defined as parametrized function.",dim,funName.Data());
1028  return;
1029  }
1030  break;
1031  }
1032  // look now for the (..) brackets to get the parameter counter (e.g. gaus(0) + gaus(3) )
1033  // need to start for a position
1034  Int_t openingParenthesisPos = (closingBracketPos == kNPOS) ? openingBracketPos : closingBracketPos + 1;
1035  bool defaultCounter = (openingParenthesisPos > formula.Length() || formula[openingParenthesisPos] != '(');
1036 
1037  //Int_t openingParenthesisPos = formula.Index('(',funPos);
1038  //Bool_t defaultCounter = (openingParenthesisPos == kNPOS);
1039  Int_t counter;
1040  if(defaultCounter)
1041  {
1042  counter = 0;
1043  }
1044  else
1045  {
1046  counter = TString(formula(openingParenthesisPos+1,formula.Index(')',funPos) - openingParenthesisPos -1)).Atoi();
1047  }
1048  //std::cout << "openingParenthesisPos " << openingParenthesisPos << " counter is " << counter << std::endl;
1049 
1050  TString body = (isNormalized ? it->second.second : it->second.first);
1051  if(isNormalized && body == "")
1052  {
1053  Error("PreprocessFormula","%d dimension function %s has no normalized form.",it->first.second,funName.Data());
1054  break;
1055  }
1056  for(int i = 0 ; i < body.Length() ; ++i)
1057  {
1058  if(body[i] == '{')
1059  {
1060  // replace {Vn} with variable names
1061  i += 2; // skip '{' and 'V'
1062  Int_t num = TString(body(i,body.Index('}',i) - i)).Atoi();
1063  TString variable = variables[num];
1064  TString pattern = TString::Format("{V%d}",num);
1065  i -= 2; // restore original position
1066  body.Replace(i, pattern.Length(),variable,variable.Length());
1067  i += variable.Length()-1; // update i to reflect change in body string
1068  }
1069  else if(body[i] == '[')
1070  {
1071  // update parameter counters in case of many functions (e.g. gaus(0)+gaus(3) )
1072  Int_t tmp = i;
1073  while(tmp < body.Length() && body[tmp] != ']')
1074  {
1075  tmp++;
1076  }
1077  Int_t num = TString(body(i+1,tmp - 1 - i)).Atoi();
1078  num += counter;
1079  TString replacement = TString::Format("%d",num);
1080 
1081  body.Replace(i+1,tmp - 1 - i,replacement,replacement.Length());
1082  i += replacement.Length() + 1;
1083  }
1084  }
1085  TString pattern;
1086  if(defaultCounter && defaultVariable)
1087  {
1088  pattern = TString::Format("%s%s",
1089  funName.Data(),
1090  (isNormalized ? "n" : ""));
1091  }
1092  if(!defaultCounter && defaultVariable)
1093  {
1094  pattern = TString::Format("%s%s(%d)",
1095  funName.Data(),
1096  (isNormalized ? "n" : ""),
1097  counter);
1098  }
1099  if(defaultCounter && !defaultVariable)
1100  {
1101  pattern = TString::Format("%s%s[%s]",
1102  funName.Data(),
1103  (isNormalized ? "n":""),
1104  varList.Data());
1105  }
1106  if(!defaultCounter && !defaultVariable)
1107  {
1108  pattern = TString::Format("%s%s[%s](%d)",
1109  funName.Data(),
1110  (isNormalized ? "n" : ""),
1111  varList.Data(),
1112  counter);
1113  }
1114  TString replacement = body;
1115 
1116  // set the number (only in case a function exists without anything else
1117  if (fNumber == 0 && formula.Length() <= (pattern.Length()-funPos) +1 ) { // leave 1 extra
1118  fNumber = functionsNumbers[funName] + 10*(dim-1);
1119  }
1120 
1121  formula.Replace(funPos,pattern.Length(),replacement,replacement.Length());
1122 
1123  funPos = formula.Index(funName);
1124  }
1125  //std::cout << " formula is now " << formula << std::endl;
1126  }
1127 
1128 }
1130 {
1131  //*-*
1132  //*-* Handling exponentiation
1133  //*-* Can handle multiple carets, eg.
1134  //*-* 2^3^4 will be treated like 2^(3^4)
1135  //*-*
1136  Int_t caretPos = formula.Last('^');
1137  while(caretPos != kNPOS)
1138  {
1139 
1140  TString right,left;
1141  Int_t temp = caretPos;
1142  temp--;
1143  // get the expression in ( ) which has the operator^ applied
1144  if(formula[temp] == ')')
1145  {
1146  Int_t depth = 1;
1147  temp--;
1148  while(depth != 0 && temp > 0)
1149  {
1150  if(formula[temp] == ')')
1151  depth++;
1152  if(formula[temp] == '(')
1153  depth--;
1154  temp--;
1155  }
1156  if (depth == 0) temp++;
1157  }
1158  // this in case of someting like sin(x+2)^2
1159  do {
1160  temp--; // go down one
1161  // handle scientific notation cases (1.e-2 ^ 3 )
1162  if (temp>=2 && IsScientificNotation(formula, temp-1) ) temp-=3;
1163  }
1164  while(temp >= 0 && !IsOperator(formula[temp]) && !IsBracket(formula[temp]) );
1165 
1166  assert(temp+1 >= 0);
1167  Int_t leftPos = temp+1;
1168  left = formula(leftPos, caretPos - leftPos);
1169  //std::cout << "left to replace is " << left << std::endl;
1170 
1171  // look now at the expression after the ^ operator
1172  temp = caretPos;
1173  temp++;
1174  if (temp >= formula.Length() ) {
1175  Error("HandleExponentiation","Invalid position of operator ^");
1176  return;
1177  }
1178  if(formula[temp] == '(')
1179  {
1180  Int_t depth = 1;
1181  temp++;
1182  while(depth != 0 && temp < formula.Length())
1183  {
1184  if(formula[temp] == ')')
1185  depth--;
1186  if(formula[temp] == '(')
1187  depth++;
1188  temp++;
1189  }
1190  temp--;
1191  }
1192  else {
1193  // handle case first character is operator - or + continue
1194  if (formula[temp] == '-' || formula[temp] == '+' ) temp++;
1195  // handle cases x^-2 or x^+2
1196  // need to handle also cases x^sin(x+y)
1197  Int_t depth = 0;
1198  // stop right expression if is an operator or if is a ")" from a zero depth
1199  while(temp < formula.Length() && ( (depth > 0) || !IsOperator(formula[temp]) ) )
1200  {
1201  temp++;
1202  // handle scientific notation cases (1.e-2 ^ 3 )
1203  if (temp>=2 && IsScientificNotation(formula, temp) ) temp+=2;
1204  // for internal parenthesis
1205  if (temp < formula.Length() && formula[temp] == '(') depth++;
1206  if (temp < formula.Length() && formula[temp] == ')') {
1207  if (depth > 0)
1208  depth--;
1209  else
1210  break; // case of end of a previously started expression e.g. sin(x^2)
1211  }
1212  }
1213  }
1214  right = formula(caretPos + 1, (temp - 1) - caretPos );
1215  //std::cout << "right to replace is " << right << std::endl;
1216 
1217  TString pattern = TString::Format("%s^%s",left.Data(),right.Data());
1218  TString replacement = TString::Format("pow(%s,%s)",left.Data(),right.Data());
1219 
1220  //std::cout << "pattern : " << pattern << std::endl;
1221  //std::cout << "replacement : " << replacement << std::endl;
1222  formula.Replace(leftPos,pattern.Length(),replacement,replacement.Length());
1223 
1224  caretPos = formula.Last('^');
1225  }
1226 }
1227 
1228 // handle linear functions defined with the operator ++
1230 {
1231  // Handle Linear functions identified with "@" operator
1232  Int_t linPos = formula.Index("@");
1233  if (linPos == kNPOS ) return; // function is not linear
1234  Int_t NofLinParts = formula.CountChar((int)'@');
1235  assert(NofLinParts > 0);
1236  fLinearParts.reserve(NofLinParts + 1);
1237  Int_t Nlinear = 0;
1238  bool first = true;
1239  while(linPos != kNPOS)
1240  {
1241  SetBit(kLinear,1);
1242  // analyze left part only the first time
1243  Int_t temp = 0;
1244  TString left;
1245  if (first) {
1246  temp = linPos - 1;
1247  while(temp >= 0 && formula[temp] != '@')
1248  {
1249  temp--;
1250  }
1251  left = formula(temp+1,linPos - (temp +1));
1252  }
1253  temp = linPos + 1;
1254  while(temp < formula.Length() && formula[temp] != '@')
1255  {
1256  temp++;
1257  }
1258  TString right = formula(linPos+1,temp - (linPos+1));
1259 
1260  TString pattern = (first) ? TString::Format("%s@%s",left.Data(),right.Data()) : TString::Format("@%s",right.Data());
1261  TString replacement = (first) ? TString::Format("([%d]*(%s))+([%d]*(%s))",Nlinear,left.Data(),Nlinear+1,right.Data()) : TString::Format("+([%d]*(%s))",Nlinear,right.Data());
1262  Nlinear += (first) ? 2 : 1;
1263 
1264  formula.ReplaceAll(pattern,replacement);
1265  if (first) {
1266  TFormula *lin1 = new TFormula("__linear1",left,false);
1267  fLinearParts.push_back(lin1);
1268  }
1269  TFormula *lin2 = new TFormula("__linear2",right,false);
1270  fLinearParts.push_back(lin2);
1271 
1272  linPos = formula.Index("@");
1273  first = false;
1274  }
1275 }
1276 
1278 {
1279  //*-*
1280  //*-* Preprocessing of formula
1281  //*-* Replace all ** by ^, and removes spaces.
1282  //*-* Handle also parametrized functions like polN,gaus,expo,landau
1283  //*-* and exponentiation.
1284  //*-* Similar functionality should be added here.
1285  //*-*
1286  formula.ReplaceAll("**","^");
1287  formula.ReplaceAll("++","@"); // for linear functions
1288  formula.ReplaceAll(" ","");
1289  HandlePolN(formula);
1290  HandleParametrizedFunctions(formula);
1291  HandleExponentiation(formula);
1292  // "++" wil be dealt with Handle Linear
1293  HandleLinear(formula);
1294  // special case for "--" and "++"
1295  // ("++" needs to be written with whitespace that is removed before but then we re-add it again
1296  formula.ReplaceAll("--","- -");
1297  formula.ReplaceAll("++","+ +");
1298 }
1300 {
1301  // prepare the formula to be executed
1302  // normally is called with fFormula
1303 
1304  fFuncs.clear();
1305  fReadyToExecute = false;
1306  ExtractFunctors(formula);
1307 
1308  // update the expression with the new formula
1309  fFormula = formula;
1310  // save formula to parse variable and parameters for Cling
1311  fClingInput = formula;
1312  // replace all { and }
1313  fFormula.ReplaceAll("{","");
1314  fFormula.ReplaceAll("}","");
1315 
1316  //std::cout << "functors are extracted formula is " << std::endl;
1317  //std::cout << fFormula << std::endl << std::endl;
1318 
1319  fFuncs.sort();
1320  fFuncs.unique();
1321 
1322  // use inputFormula for Cling
1324 
1325  // for pre-defined functions (need after processing)
1326  if (fNumber != 0) SetPredefinedParamNames();
1327 
1329 }
1331 {
1332  //*-*
1333  //*-* Extracts functors from formula, and put them in fFuncs.
1334  //*-* Simple grammar:
1335  //*-* <function> := name(arg1,arg2...)
1336  //*-* <variable> := name
1337  //*-* <parameter> := [number]
1338  //*-* <name> := String containing lower and upper letters, numbers, underscores
1339  //*-* <number> := Integer number
1340  //*-* Operators are omitted.
1341  //*-*
1342  TString name = "";
1343  TString body = "";
1344  //printf("formula is : %s \n",formula.Data() );
1345  for(Int_t i = 0 ; i < formula.Length(); ++i )
1346  {
1347 
1348  //std::cout << "loop on character : " << i << " " << formula[i] << std::endl;
1349  // case of parameters
1350  if(formula[i] == '[')
1351  {
1352  Int_t tmp = i;
1353  i++;
1354  TString param = "";
1355  while(formula[i] != ']' && i < formula.Length())
1356  {
1357  param.Append(formula[i++]);
1358  }
1359  i++;
1360  //rename parameter name XX to pXX
1361  if (param.IsDigit() ) param.Insert(0,'p');
1362  // handle whitespace characters in parname
1363  param.ReplaceAll("\\s"," ");
1364  DoAddParameter(param,0,false);
1365  TString replacement = TString::Format("{[%s]}",param.Data());
1366  formula.Replace(tmp,i - tmp, replacement,replacement.Length());
1367  fFuncs.push_back(TFormulaFunction(param));
1368  //printf("found parameter %s \n",param.Data() );
1369  continue;
1370  }
1371  // case of strings
1372  if (formula[i] == '\"') {
1373  // look for next instance of "\"
1374  do {
1375  i++;
1376  } while(formula[i] != '\"');
1377  }
1378  // case of e or E for numbers in exponential notaton (e.g. 2.2e-3)
1379  if (IsScientificNotation(formula, i) )
1380  continue;
1381  // case of x for hexadecimal numbers
1382  if (IsHexadecimal(formula, i) ) {
1383  // find position of operator
1384  // do not check cases if character is not only a to f, but accept anything
1385  while ( !IsOperator(formula[i]) && i < formula.Length() ) {
1386  i++;
1387  }
1388  continue;
1389  }
1390 
1391 
1392  //std::cout << "investigating character : " << i << " " << formula[i] << " of formula " << formula << std::endl;
1393  // look for variable and function names. They start in C++ with alphanumeric characters
1394  if(isalpha(formula[i]) && !IsOperator(formula[i])) // not really needed to check if operator (if isalpha is not an operator)
1395  {
1396  //std::cout << "character : " << i << " " << formula[i] << " is not an operator and is alpha " << std::endl;
1397 
1398  while( IsFunctionNameChar(formula[i]) && i < formula.Length())
1399  {
1400  // need special case for separting operator ":" from scope operator "::"
1401  if (formula[i] == ':' && ( (i+1) < formula.Length() ) ) {
1402  if ( formula[i+1] == ':' ) {
1403  // case of :: (scopeOperator)
1404  name.Append("::");
1405  i+=2;
1406  continue;
1407  }
1408  else
1409  break;
1410  }
1411 
1412  name.Append(formula[i++]);
1413  }
1414  //printf(" build a name %s \n",name.Data() );
1415  if(formula[i] == '(')
1416  {
1417  i++;
1418  if(formula[i] == ')')
1419  {
1420  fFuncs.push_back(TFormulaFunction(name,body,0));
1421  name = body = "";
1422  continue;
1423  }
1424  Int_t depth = 1;
1425  Int_t args = 1; // we will miss first argument
1426  while(depth != 0 && i < formula.Length())
1427  {
1428  switch(formula[i])
1429  {
1430  case '(': depth++; break;
1431  case ')': depth--; break;
1432  case ',': if(depth == 1) args++; break;
1433  }
1434  if(depth != 0) // we don't want last ')' inside body
1435  {
1436  body.Append(formula[i++]);
1437  }
1438  }
1439  Int_t originalBodyLen = body.Length();
1440  ExtractFunctors(body);
1441  formula.Replace(i-originalBodyLen,originalBodyLen,body,body.Length());
1442  i += body.Length() - originalBodyLen;
1443  fFuncs.push_back(TFormulaFunction(name,body,args));
1444  }
1445  else
1446  {
1447 
1448  //std::cout << "check if character : " << i << " " << formula[i] << " from name " << name << " is a function " << std::endl;
1449 
1450  // check if function is provided by gROOT
1451  TObject *obj = 0;
1452  {
1454  obj = gROOT->GetListOfFunctions()->FindObject(name);
1455  }
1456  TFormula * f = dynamic_cast<TFormula*> (obj);
1457  if (!f) {
1458  // maybe object is a TF1
1459  TF1 * f1 = dynamic_cast<TF1*> (obj);
1460  if (f1) f = f1->GetFormula();
1461  }
1462  if (f) {
1463  TString replacementFormula = f->GetExpFormula();
1464  // analyze expression string
1465  //std::cout << "formula to replace for " << f->GetName() << " is " << replacementFormula << std::endl;
1466  PreProcessFormula(replacementFormula);
1467  // we need to define different parameters if we use the unnamed default parameters ([0])
1468  // I need to replace all the terms in the functor for backward compatibility of the case
1469  // f1("[0]*x") f2("[0]*x") f1+f2 - it is weird but it is better to support
1470  //std::cout << "current number of parameter is " << fNpar << std::endl;
1471  int nparOffset = 0;
1472  //if (fParams.find("0") != fParams.end() ) {
1473  // do in any case if parameters are existing
1474  std::vector<TString> newNames;
1475  if (fNpar > 0) {
1476  nparOffset = fNpar;
1477  newNames.resize(f->GetNpar() );
1478  // start from higher number to avoid overlap
1479  for (int jpar = f->GetNpar()-1; jpar >= 0; --jpar ) {
1480  // parameters name have a "p" added in front
1481  TString pj = TString(f->GetParName(jpar));
1482  if ( pj[0] == 'p' && TString(pj(1,pj.Length())).IsDigit() ) {
1483  TString oldName = TString::Format("[%s]",f->GetParName(jpar));
1484  TString newName = TString::Format("[p%d]",nparOffset+jpar);
1485  //std::cout << "replace - parameter " << f->GetParName(jpar) << " with " << newName << std::endl;
1486  replacementFormula.ReplaceAll(oldName,newName);
1487  newNames[jpar] = newName;
1488  }
1489  else
1490  newNames[jpar] = f->GetParName(jpar);
1491  }
1492  //std::cout << "after replacing params " << replacementFormula << std::endl;
1493  }
1494  ExtractFunctors(replacementFormula);
1495  //std::cout << "after re-extracting functors " << replacementFormula << std::endl;
1496 
1497  // set parameter value from replacement formula
1498  for (int jpar = 0; jpar < f->GetNpar(); ++jpar) {
1499  if (nparOffset> 0) {
1500  // parameter have an offset- so take this into accound
1501  assert((int) newNames.size() == f->GetNpar() );
1502  SetParameter(newNames[jpar], f->GetParameter(jpar) );
1503  }
1504  else
1505  // names are the same between current formula and replaced one
1506  SetParameter(f->GetParName(jpar), f->GetParameter(jpar) );
1507  }
1508  // need to add parenthesis at begin end end of replacementFormula
1509  replacementFormula.Insert(0,'(');
1510  replacementFormula.Insert(replacementFormula.Length(),')');
1511  formula.Replace(i-name.Length(),name.Length(), replacementFormula, replacementFormula.Length());
1512  // move forward the index i of the main loop
1513  i += replacementFormula.Length()-name.Length();
1514 
1515  // we have extracted all the functor for "fname"
1516  //std::cout << " i = " << i << " f[i] = " << formula[i] << " - " << formula << std::endl;
1517  name = "";
1518 
1519  continue;
1520  }
1521 
1522  // add now functor in
1523  TString replacement = TString::Format("{%s}",name.Data());
1524  formula.Replace(i-name.Length(),name.Length(),replacement,replacement.Length());
1525  i += 2;
1526  fFuncs.push_back(TFormulaFunction(name));
1527  }
1528  }
1529  name = body = "";
1530 
1531  }
1532 }
1534 {
1535  //*-*
1536  //*-* Iterates through funtors in fFuncs and performs the appropriate action.
1537  //*-* If functor has 0 arguments (has only name) can be:
1538  //*-* - variable
1539  //*-* * will be replaced with x[num], where x is an array containing value of this variable under num.
1540  //*-* - pre-defined formula
1541  //*-* * will be replaced with formulas body
1542  //*-* - constant
1543  //*-* * will be replaced with constant value
1544  //*-* - parameter
1545  //*-* * will be replaced with p[num], where p is an array containing value of this parameter under num.
1546  //*-* If has arguments it can be :
1547  //*-* - function shortcut, eg. sin
1548  //*-* * will be replaced with fullname of function, eg. sin -> TMath::Sin
1549  //*-* - function from cling environment, eg. TMath::BreitWigner(x,y,z)
1550  //*-* * first check if function exists, and has same number of arguments, then accept it and set as found.
1551  //*-* If all functors after iteration are matched with corresponding action,
1552  //*-* it inputs C++ code of formula into cling, and sets flag that formula is ready to evaluate.
1553  //*-*
1554 
1555  // std::cout << "Begin: formula is " << formula << " list of functors " << fFuncs.size() << std::endl;
1556 
1557  for(list<TFormulaFunction>::iterator funcsIt = fFuncs.begin(); funcsIt != fFuncs.end(); ++funcsIt)
1558  {
1559  TFormulaFunction & fun = *funcsIt;
1560 
1561  //std::cout << "fun is " << fun.GetName() << std::endl;
1562 
1563  if(fun.fFound)
1564  continue;
1565  if(fun.IsFuncCall())
1566  {
1567  map<TString,TString>::iterator it = fFunctionsShortcuts.find(fun.GetName());
1568  if(it != fFunctionsShortcuts.end())
1569  {
1570  TString shortcut = it->first;
1571  TString full = it->second;
1572  //std::cout << " functor " << fun.GetName() << " found - replace " << shortcut << " with " << full << " in " << formula << std::endl;
1573  // replace all functors
1574  Ssiz_t index = formula.Index(shortcut,0);
1575  while ( index != kNPOS) {
1576  // check that function is not in a namespace and is not in other characters
1577  //std::cout << "analyzing " << shortcut << " in " << formula << std::endl;
1578  Ssiz_t i2 = index + shortcut.Length();
1579  if ( (index > 0) && (isalpha( formula[index-1] ) || formula[index-1] == ':' )) {
1580  index = formula.Index(shortcut,i2);
1581  continue;
1582  }
1583  if (i2 < formula.Length() && formula[i2] != '(') {
1584  index = formula.Index(shortcut,i2);
1585  continue;
1586  }
1587  // now replace the string
1588  formula.Replace(index, shortcut.Length(), full);
1589  Ssiz_t inext = index + full.Length();
1590  index = formula.Index(shortcut,inext);
1591  fun.fFound = true;
1592  }
1593  }
1594  if(fun.fName.Contains("::")) // add support for nested namespaces
1595  {
1596  // look for last occurence of "::"
1597  std::string name(fun.fName);
1598  size_t index = name.rfind("::");
1599  assert(index != std::string::npos);
1600  TString className = fun.fName(0,fun.fName(0,index).Length());
1601  TString functionName = fun.fName(index + 2, fun.fName.Length());
1602 
1603  Bool_t silent = true;
1604  TClass *tclass = TClass::GetClass(className,silent);
1605  // std::cout << "looking for class " << className << std::endl;
1606  const TList *methodList = tclass->GetListOfAllPublicMethods();
1607  TIter next(methodList);
1608  TMethod *p;
1609  while ((p = (TMethod*) next()))
1610  {
1611  if (strcmp(p->GetName(),functionName.Data()) == 0 &&
1612  (fun.GetNargs() <= p->GetNargs() && fun.GetNargs() >= p->GetNargs() - p->GetNargsOpt() ) )
1613  {
1614  fun.fFound = true;
1615  break;
1616  }
1617  }
1618  }
1619  if(!fun.fFound)
1620  {
1621  // try to look into all the global functions in gROOT
1622  TFunction* f;
1623  {
1625  f = (TFunction*) gROOT->GetListOfGlobalFunctions(true)->FindObject(fun.fName);
1626  }
1627  // if found a function with matching arguments
1628  if (f && fun.GetNargs() <= f->GetNargs() && fun.GetNargs() >= f->GetNargs() - f->GetNargsOpt() )
1629  {
1630  fun.fFound = true;
1631  }
1632  }
1633 
1634  if(!fun.fFound)
1635  {
1636  // ignore not found functions
1637  if (gDebug)
1638  Info("TFormula","Could not find %s function with %d argument(s)",fun.GetName(),fun.GetNargs());
1639  fun.fFound = false;
1640  }
1641  }
1642  else
1643  {
1644  TFormula* old = 0;
1645  {
1647  old = (TFormula*)gROOT->GetListOfFunctions()->FindObject(gNamePrefix + fun.fName);
1648  }
1649  if(old)
1650  {
1651  // we should not go here (this analysis is done before in ExtractFunctors)
1652  assert(false);
1653  fun.fFound = true;
1654  TString pattern = TString::Format("{%s}",fun.GetName());
1655  TString replacement = old->GetExpFormula();
1656  PreProcessFormula(replacement);
1657  ExtractFunctors(replacement);
1658  formula.ReplaceAll(pattern,replacement);
1659  continue;
1660  }
1661  // looking for default variables defined in fVars
1662 
1663  map<TString,TFormulaVariable>::iterator varsIt = fVars.find(fun.GetName());
1664  if(varsIt!= fVars.end())
1665  {
1666 
1667  TString name = (*varsIt).second.GetName();
1668  Double_t value = (*varsIt).second.fValue;
1669 
1670 
1671  AddVariable(name,value); // this set the cling variable
1672  if(!fVars[name].fFound)
1673  {
1674 
1675 
1676  fVars[name].fFound = true;
1677  int varDim = (*varsIt).second.fArrayPos; // variable dimenions (0 for x, 1 for y, 2, for z)
1678  if (varDim >= fNdim) {
1679  fNdim = varDim+1;
1680 
1681  // we need to be sure that all other variables are added with position less
1682  for ( auto &v : fVars) {
1683  if (v.second.fArrayPos < varDim && !v.second.fFound ) {
1684  AddVariable(v.first, v.second.fValue);
1685  v.second.fFound = true;
1686  }
1687  }
1688  }
1689  }
1690  // remove the "{.. }" added around the variable
1691  TString pattern = TString::Format("{%s}",name.Data());
1692  TString replacement = TString::Format("x[%d]",(*varsIt).second.fArrayPos);
1693  formula.ReplaceAll(pattern,replacement);
1694 
1695  //std::cout << "Found an observable for " << fun.GetName() << std::endl;
1696 
1697  fun.fFound = true;
1698  continue;
1699  }
1700  // check for observables defined as x[0],x[1],....
1701  // maybe could use a regular expression here
1702  // only in case match with defined variables is not successfull
1703  TString funname = fun.GetName();
1704  if (funname.Contains("x[") && funname.Contains("]") ) {
1705  TString sdigit = funname(2,funname.Index("]") );
1706  int digit = sdigit.Atoi();
1707  if (digit >= fNdim) {
1708  fNdim = digit+1;
1709  // we need to add the variables in fVars all of them before x[n]
1710  for (int j = 0; j < fNdim; ++j) {
1711  TString vname = TString::Format("x[%d]",j);
1712  if (fVars.find(vname) == fVars.end() ) {
1713  fVars[vname] = TFormulaVariable(vname,0,j);
1714  fVars[vname].fFound = true;
1715  AddVariable(vname,0.);
1716  }
1717  }
1718  }
1719  //std::cout << "Found matching observable for " << funname << std::endl;
1720  fun.fFound = true;
1721  // remove the "{.. }" added around the variable
1722  TString pattern = TString::Format("{%s}",funname.Data());
1723  formula.ReplaceAll(pattern,funname);
1724  continue;
1725  }
1726  //}
1727 
1728  auto paramsIt = fParams.find(fun.GetName());
1729  if(paramsIt != fParams.end())
1730  {
1731  //TString name = (*paramsIt).second.GetName();
1732  TString pattern = TString::Format("{[%s]}",fun.GetName());
1733  //std::cout << "pattern is " << pattern << std::endl;
1734  if(formula.Index(pattern) != kNPOS)
1735  {
1736  //TString replacement = TString::Format("p[%d]",(*paramsIt).second.fArrayPos);
1737  TString replacement = TString::Format("p[%d]",(*paramsIt).second);
1738  //std::cout << "replace pattern " << pattern << " with " << replacement << std::endl;
1739  formula.ReplaceAll(pattern,replacement);
1740 
1741  }
1742  fun.fFound = true;
1743  continue;
1744  }
1745  else {
1746  //std::cout << "functor " << fun.GetName() << " is not a parameter " << std::endl;
1747  }
1748 
1749  // looking for constants (needs to be done after looking at the parameters)
1750  map<TString,Double_t>::iterator constIt = fConsts.find(fun.GetName());
1751  if(constIt != fConsts.end())
1752  {
1753  TString pattern = TString::Format("{%s}",fun.GetName());
1754  TString value = TString::Format("%lf",(*constIt).second);
1755  formula.ReplaceAll(pattern,value);
1756  fun.fFound = true;
1757  //std::cout << "constant with name " << fun.GetName() << " is found " << std::endl;
1758  continue;
1759  }
1760 
1761 
1762  fun.fFound = false;
1763  }
1764  }
1765  //std::cout << "End: formula is " << formula << std::endl;
1766 
1767  // ignore case of functors have been matched - try to pass it to Cling
1768  if(!fReadyToExecute)
1769  {
1770  fReadyToExecute = true;
1771  Bool_t hasVariables = (fNdim > 0);
1772  Bool_t hasParameters = (fNpar > 0);
1773  if(!hasParameters)
1774  {
1775  fAllParametersSetted = true;
1776  }
1777  // assume a function without variables is always 1-dimensional
1778  if (hasParameters && ! hasVariables) {
1779  fNdim = 1;
1780  AddVariable("x",0);
1781  hasVariables = true;
1782  }
1783  Bool_t hasBoth = hasVariables && hasParameters;
1784  Bool_t inputIntoCling = (formula.Length() > 0);
1785  if (inputIntoCling) {
1786 
1787  // save copy of inputFormula in a std::strig for the unordered map
1788  // and also formula is same as FClingInput typically and it will be modified
1789  std::string inputFormula = std::string(formula);
1790 
1791 
1792  // valid input formula - try to put into Cling
1793  TString argumentsPrototype =
1794  TString::Format("%s%s%s",(hasVariables ? "Double_t *x" : ""), (hasBoth ? "," : ""),
1795  (hasParameters ? "Double_t *p" : ""));
1796 
1797 
1798  // set the name for Cling using the hash_function
1800 
1801  // check if formula exist already in the map
1803 
1804  auto funcit = gClingFunctions.find(inputFormula);
1805 
1806  if (funcit != gClingFunctions.end() ) {
1808  fClingInitialized = true;
1809  inputIntoCling = false;
1810  }
1811 
1812  // set the cling name using hash of the static formulae map
1813  auto hasher = gClingFunctions.hash_function();
1814  fClingName = TString::Format("%s__id%zu",gNamePrefix.Data(),(unsigned long) hasher(inputFormula) );
1815 
1816  fClingInput = TString::Format("Double_t %s(%s){ return %s ; }", fClingName.Data(),argumentsPrototype.Data(),inputFormula.c_str());
1817 
1818  // this is not needed (maybe can be re-added in case of recompilation of identical expressions
1819  // // check in case of a change if need to re-initialize
1820  // if (fClingInitialized) {
1821  // if (oldClingInput == fClingInput)
1822  // inputIntoCling = false;
1823  // else
1824  // fClingInitialized = false;
1825  // }
1826 
1827 
1828  if(inputIntoCling) {
1830  if (fClingInitialized) {
1831  // if Cling has been succesfully initialized
1832  // dave function ptr in the static map
1834  gClingFunctions.insert ( std::make_pair ( inputFormula, (void*) fFuncPtr) );
1835  }
1836 
1837  }
1838  else {
1839  fAllParametersSetted = true;
1840  fClingInitialized = true;
1841  }
1842  }
1843  }
1844 
1845 
1846  // IN case of a Cling Error check components wich are not found in Cling
1847  // check that all formula components arematched otherwise emit an error
1848  if (!fClingInitialized) {
1849  Bool_t allFunctorsMatched = true;
1850  for(list<TFormulaFunction>::iterator it = fFuncs.begin(); it != fFuncs.end(); it++)
1851  {
1852  if(!it->fFound)
1853  {
1854  allFunctorsMatched = false;
1855  if (it->GetNargs() == 0)
1856  Error("ProcessFormula","\"%s\" has not been matched in the formula expression",it->GetName() );
1857  else
1858  Error("ProcessFormula","Could not find %s function with %d argument(s)",it->GetName(),it->GetNargs());
1859  }
1860  }
1861  if (!allFunctorsMatched) {
1862  Error("ProcessFormula","Formula \"%s\" is invalid !", GetExpFormula().Data() );
1863  fReadyToExecute = false;
1864  }
1865  }
1866 
1867  // clean up un-used default variables in case formula is valid
1869  auto itvar = fVars.begin();
1870  do
1871  {
1872  if ( ! itvar->second.fFound ) {
1873  //std::cout << "Erase variable " << itvar->first << std::endl;
1874  itvar = fVars.erase(itvar);
1875  }
1876  else
1877  itvar++;
1878  }
1879  while( itvar != fVars.end() );
1880  }
1881 
1882 }
1884 
1885  // set parameter names only in case of pre-defined functions
1886  if (fNumber == 0) return;
1887 
1888  if (fNumber == 100) { // Gaussian
1889  SetParName(0,"Constant");
1890  SetParName(1,"Mean");
1891  SetParName(2,"Sigma");
1892  return;
1893  }
1894  if (fNumber == 110) {
1895  SetParName(0,"Constant");
1896  SetParName(1,"MeanX");
1897  SetParName(2,"SigmaX");
1898  SetParName(3,"MeanY");
1899  SetParName(4,"SigmaY");
1900  return;
1901  }
1902  if (fNumber == 200) { // exponential
1903  SetParName(0,"Constant");
1904  SetParName(1,"Slope");
1905  return;
1906  }
1907  if (fNumber == 400) { // landau
1908  SetParName(0,"Constant");
1909  SetParName(1,"MPV");
1910  SetParName(2,"Sigma");
1911  return;
1912  }
1913  if (fNumber == 500) { // crystal-ball
1914  SetParName(0,"Constant");
1915  SetParName(1,"Mean");
1916  SetParName(2,"Sigma");
1917  SetParName(3,"Alpha");
1918  SetParName(4,"N");
1919  return;
1920  }
1921  if (fNumber == 600) { // breit-wigner
1922  SetParName(0,"Constant");
1923  SetParName(1,"Mean");
1924  SetParName(2,"Gamma");
1925  return;
1926  }
1927  // if formula is a polynomial (or chebyshev), set parameter names
1928  // not needed anymore (p0 is assigned by default)
1929  // if (fNumber == (300+fNpar-1) ) {
1930  // for (int i = 0; i < fNpar; i++) SetParName(i,TString::Format("p%d",i));
1931  // return;
1932  // }
1933 
1934  // // general case if parameters are digits (XX) change to pXX
1935  // auto paramMap = fParams; // need to copy the map because SetParName is going to modify it
1936  // for ( auto & p : paramMap) {
1937  // if (p.first.IsDigit() )
1938  // SetParName(p.second,TString::Format("p%s",p.first.Data()));
1939  // }
1940 
1941  return;
1942 }
1944 {
1945  // Return linear part.
1946 
1947  if (!fLinearParts.empty()) {
1948  int n = fLinearParts.size();
1949  if (i < 0 || i >= n ) {
1950  Error("GetLinearPart","Formula %s has only %d linear parts - requested %d",GetName(),n,i);
1951  return nullptr;
1952  }
1953  return fLinearParts[i];
1954  }
1955  return nullptr;
1956 }
1958 {
1959  //*-*
1960  //*-* Adds variable to known variables, and reprocess formula.
1961  //*-*
1962 
1963  if(fVars.find(name) != fVars.end() )
1964  {
1965  TFormulaVariable & var = fVars[name];
1966  var.fValue = value;
1967 
1968  // If the position is not defined in the Cling vectors, make space for it
1969  // but normally is variable is defined in fVars a slot should be also present in fClingVariables
1970  if(var.fArrayPos < 0)
1971  {
1972  var.fArrayPos = fVars.size();
1973  }
1974  if(var.fArrayPos >= (int)fClingVariables.size())
1975  {
1976  fClingVariables.resize(var.fArrayPos+1);
1977  }
1979  }
1980  else
1981  {
1982  TFormulaVariable var(name,value,fVars.size());
1983  fVars[name] = var;
1984  fClingVariables.push_back(value);
1985  if (!fFormula.IsNull() ) {
1986  //printf("process formula again - %s \n",fClingInput.Data() );
1988  }
1989  }
1990 
1991 }
1992 void TFormula::AddVariables(const TString *vars, const Int_t size)
1993 {
1994  //*-*
1995  //*-* Adds multiple variables.
1996  //*-* First argument is an array of pairs<TString,Double>, where
1997  //*-* first argument is name of variable,
1998  //*-* second argument represents value.
1999  //*-* size - number of variables passed in first argument
2000  //*-*
2001 
2002  Bool_t anyNewVar = false;
2003  for(Int_t i = 0 ; i < size; ++i)
2004  {
2005 
2006  const TString & vname = vars[i];
2007 
2008  TFormulaVariable &var = fVars[vname];
2009  if(var.fArrayPos < 0)
2010  {
2011 
2012  var.fName = vname;
2013  var.fArrayPos = fVars.size();
2014  anyNewVar = true;
2015  var.fValue = 0;
2016  if(var.fArrayPos >= (int)fClingVariables.capacity())
2017  {
2018  Int_t multiplier = 2;
2019  if(fFuncs.size() > 100)
2020  {
2021  multiplier = TMath::Floor(TMath::Log10(fFuncs.size()) * 10);
2022  }
2023  fClingVariables.reserve(multiplier * fClingVariables.capacity());
2024  }
2025  fClingVariables.push_back(0.0);
2026  }
2027  // else
2028  // {
2029  // var.fValue = v.second;
2030  // fClingVariables[var.fArrayPos] = v.second;
2031  // }
2032  }
2033  if(anyNewVar && !fFormula.IsNull())
2034  {
2036  }
2037 
2038 }
2039 
2040 void TFormula::SetName(const char* name)
2041 {
2042  // Set the name of the formula. We need to allow the list of function to
2043  // properly handle the hashes.
2044  if (IsReservedName(name)) {
2045  Error("SetName","The name \'%s\' is reserved as a TFormula variable name.\n"
2046  "\tThis function will not be renamed.",name);
2047  } else {
2048  // Here we need to remove and re-add to keep the hashes consistent with
2049  // the underlying names.
2050  auto listOfFunctions = gROOT->GetListOfFunctions();
2051  TObject* thisAsFunctionInList = nullptr;
2053  if (listOfFunctions){
2054  thisAsFunctionInList = listOfFunctions->FindObject(this);
2055  if (thisAsFunctionInList) listOfFunctions->Remove(thisAsFunctionInList);
2056  }
2057  TNamed::SetName(name);
2058  if (thisAsFunctionInList) listOfFunctions->Add(thisAsFunctionInList);
2059  }
2060 }
2061 
2062 void TFormula::SetVariables(const pair<TString,Double_t> *vars, const Int_t size)
2063 {
2064  //*-*
2065  //*-* Sets multiple variables.
2066  //*-* First argument is an array of pairs<TString,Double>, where
2067  //*-* first argument is name of variable,
2068  //*-* second argument represents value.
2069  //*-* size - number of variables passed in first argument
2070  //*-*
2071  for(Int_t i = 0; i < size; ++i)
2072  {
2073  pair<TString,Double_t> v = vars[i];
2074  if(fVars.find(v.first) != fVars.end())
2075  {
2076  fVars[v.first].fValue = v.second;
2077  fClingVariables[fVars[v.first].fArrayPos] = v.second;
2078  }
2079  else
2080  {
2081  Error("SetVariables","Variable %s is not defined.",v.first.Data());
2082  }
2083  }
2084 }
2085 
2087 {
2088  //*-*
2089  //*-* Returns variable value.
2090  //*-*
2091  TString sname(name);
2092  if(fVars.find(sname) == fVars.end())
2093  {
2094  Error("GetVariable","Variable %s is not defined.",sname.Data());
2095  return -1;
2096  }
2097  return fVars.find(sname)->second.fValue;
2098 }
2100 {
2101  //*-*
2102  //*-* Returns variable number (positon in array) given its name
2103  //*-*
2104  TString sname(name);
2105  if(fVars.find(sname) == fVars.end())
2106  {
2107  Error("GetVarNumber","Variable %s is not defined.",sname.Data());
2108  return -1;
2109  }
2110  return fVars.find(sname)->second.fArrayPos;
2111 }
2112 
2114 {
2115  //*-*
2116  //*-* Returns variable name given its position in the array
2117  //*-*
2118 
2119  if (ivar < 0 || ivar >= fNdim) return "";
2120 
2121  // need to loop on the map to find corresponding variable
2122  for ( auto & v : fVars) {
2123  if (v.second.fArrayPos == ivar) return v.first;
2124  }
2125  Error("GetVarName","Variable with index %d not found !!",ivar);
2126  //return TString::Format("x%d",ivar);
2127  return TString();
2128 }
2129 
2131 {
2132  //*-*
2133  //*-* Sets variable value.
2134  //*-*
2135  if(fVars.find(name) == fVars.end())
2136  {
2137  Error("SetVariable","Variable %s is not defined.",name.Data());
2138  return;
2139  }
2140  fVars[name].fValue = value;
2141  fClingVariables[fVars[name].fArrayPos] = value;
2142 }
2143 
2145 {
2146  //*-*
2147  //*-* Adds parameter to known parameters.
2148  //*-* User should use SetParameter, because parameters are added during initialization part,
2149  //*-* and after that adding new will be pointless.
2150  //*-*
2151 
2152  //std::cout << "adding parameter " << name << std::endl;
2153 
2154  // if parameter is already defined in fParams - just set the new value
2155  if(fParams.find(name) != fParams.end() )
2156  {
2157  int ipos = fParams[name];
2158  //TFormulaVariable & par = fParams[name];
2159  //par.fValue = value;
2160  if (ipos < 0)
2161  {
2162  ipos = fParams.size();
2163  fParams[name] = ipos;
2164  }
2165 //
2166  if(ipos >= (int)fClingParameters.size())
2167  {
2168  if(ipos >= (int)fClingParameters.capacity())
2169  fClingParameters.reserve( TMath::Max(int(fParams.size()), ipos+1));
2170  fClingParameters.insert(fClingParameters.end(),ipos+1-fClingParameters.size(),0.0);
2171  }
2172  fClingParameters[ipos] = value;
2173  }
2174  else
2175  {
2176  // new parameter defined
2177  fNpar++;
2178  //TFormulaVariable(name,value,fParams.size());
2179  int pos = fParams.size();
2180  //fParams.insert(std::make_pair<TString,TFormulaVariable>(name,TFormulaVariable(name,value,pos)));
2181  auto ret = fParams.insert(std::make_pair(name,pos));
2182  // map returns a std::pair<iterator, bool>
2183  // use map the order for defult position of parameters in the vector
2184  // (i.e use the alphabetic order)
2185  if (ret.second) {
2186  // a new element is inserted
2187  if (ret.first == fParams.begin() )
2188  pos = 0;
2189  else {
2190  auto previous = (ret.first);
2191  --previous;
2192  pos = previous->second + 1;
2193  }
2194 
2195 
2196  if (pos < (int)fClingParameters.size() )
2197  fClingParameters.insert(fClingParameters.begin()+pos,value);
2198  else {
2199  // this should not happen
2200  if (pos > (int)fClingParameters.size() )
2201  Warning("inserting parameter %s at pos %d when vector size is %d \n",name.Data(),pos,(int)fClingParameters.size() );
2202 
2203  if(pos >= (int)fClingParameters.capacity())
2204  fClingParameters.reserve( TMath::Max(int(fParams.size()), pos+1));
2205  fClingParameters.insert(fClingParameters.end(),pos+1-fClingParameters.size(),0.0);
2206  fClingParameters[pos] = value;
2207  }
2208 
2209  // need to adjust all other positions
2210  for ( auto it = ret.first; it != fParams.end(); ++it ) {
2211  it->second = pos;
2212  pos++;
2213  }
2214  // for (auto & p : fParams)
2215  // std::cout << "Parameter " << p.first << " position " << p.second << std::endl;
2216  // printf("inserted parameters size params %d size cling %d \n",fParams.size(), fClingParameters.size() );
2217  }
2218  if (processFormula) {
2219  // replace first in input parameter name with [name]
2220  fClingInput.ReplaceAll(name,TString::Format("[%s]",name.Data() ) );
2222  }
2223  }
2224 
2225 }
2226 Int_t TFormula::GetParNumber(const char * name) const {
2227  // return parameter index given a name (return -1 for not existing parameters)
2228  // non need to print an error
2229  auto it = fParams.find(name);
2230  if(it == fParams.end())
2231  {
2232  return -1;
2233  }
2234  return it->second;
2235 
2236 }
2237 
2239 {
2240  //*-*
2241  //*-* Returns parameter value given by string.
2242  //*-*
2243  int i = GetParNumber(name);
2244  if (i == -1) {
2245  Error("GetParameter","Parameter %s is not defined.",name);
2246  return TMath::QuietNaN();
2247  }
2248 
2249  return GetParameter( GetParNumber(name) );
2250 }
2252 {
2253  //*-*
2254  //*-* Return parameter value given by integer.
2255  //*-*
2256  //*-*
2257  //TString name = TString::Format("%d",param);
2258  if(param >=0 && param < (int) fClingParameters.size())
2259  return fClingParameters[param];
2260  Error("GetParameter","wrong index used - use GetParameter(name)");
2261  return TMath::QuietNaN();
2262 }
2263 const char * TFormula::GetParName(Int_t ipar) const
2264 {
2265  //*-*
2266  //*-* Return parameter name given by integer.
2267  //*-*
2268  if (ipar < 0 || ipar >= fNpar) return "";
2269 
2270  // need to loop on the map to find corresponding parameter
2271  for ( auto & p : fParams) {
2272  if (p.second == ipar) return p.first.Data();
2273  }
2274  Error("GetParName","Parameter with index %d not found !!",ipar);
2275  //return TString::Format("p%d",ipar);
2276  return TString();
2277 }
2279 {
2280  if(!fClingParameters.empty())
2281  return const_cast<Double_t*>(&fClingParameters[0]);
2282  return 0;
2283 }
2284 
2286 {
2287  for(Int_t i = 0; i < fNpar; ++i)
2288  {
2289  if (Int_t(fClingParameters.size()) > i)
2290  params[i] = fClingParameters[i];
2291  else
2292  params[i] = -1;
2293  }
2294 }
2295 
2297 {
2298  //*-*
2299  //*-* Sets parameter value.
2300  //*-*
2301 
2302  SetParameter( GetParNumber(name), value);
2303 
2304  // do we need this ???
2305 #ifdef OLDPARAMS
2306  if(fParams.find(name) == fParams.end())
2307  {
2308  Error("SetParameter","Parameter %s is not defined.",name.Data());
2309  return;
2310  }
2311  fParams[name].fValue = value;
2312  fParams[name].fFound = true;
2313  fClingParameters[fParams[name].fArrayPos] = value;
2314  fAllParametersSetted = true;
2315  for(map<TString,TFormulaVariable>::iterator it = fParams.begin(); it != fParams.end(); it++)
2316  {
2317  if(!it->second.fFound)
2318  {
2319  fAllParametersSetted = false;
2320  break;
2321  }
2322  }
2323 #endif
2324 }
2325 #ifdef OLDPARAMS
2326 void TFormula::SetParameters(const pair<TString,Double_t> *params,const Int_t size)
2327 {
2328  //*-*
2329  //*-* Set multiple parameters.
2330  //*-* First argument is an array of pairs<TString,Double>, where
2331  //*-* first argument is name of parameter,
2332  //*-* second argument represents value.
2333  //*-* size - number of params passed in first argument
2334  //*-*
2335  for(Int_t i = 0 ; i < size ; ++i)
2336  {
2337  pair<TString,Double_t> p = params[i];
2338  if(fParams.find(p.first) == fParams.end())
2339  {
2340  Error("SetParameters","Parameter %s is not defined",p.first.Data());
2341  continue;
2342  }
2343  fParams[p.first].fValue = p.second;
2344  fParams[p.first].fFound = true;
2345  fClingParameters[fParams[p.first].fArrayPos] = p.second;
2346  }
2347  fAllParametersSetted = true;
2348  for(map<TString,TFormulaVariable>::iterator it = fParams.begin(); it != fParams.end(); it++)
2349  {
2350  if(!it->second.fFound)
2351  {
2352  fAllParametersSetted = false;
2353  break;
2354  }
2355  }
2356 }
2357 #endif
2358 
2359 void TFormula::DoSetParameters(const Double_t *params, Int_t size)
2360 {
2361  if(!params || size < 0 || size > fNpar) return;
2362  // reset vector of cling parameters
2363  if (size != (int) fClingParameters.size() ) {
2364  Warning("SetParameters","size is not same of cling parameter size %d - %d",size,int(fClingParameters.size()) );
2365  for(Int_t i = 0; i < size; ++i)
2366  {
2367  TString name = TString::Format("%d",i);
2368  SetParameter(name,params[i]);
2369  }
2370  return;
2371  }
2372  fAllParametersSetted = true;
2373  std::copy(params, params+size, fClingParameters.begin() );
2374 }
2375 
2377 {
2378  // set a vector of parameters value
2379  // Order in the vector is by default the aphabetic order given to the parameters
2380  // apart if the users has defined explicitly the parameter names
2381  DoSetParameters(params,fNpar);
2382 }
2384  Double_t p5,Double_t p6,Double_t p7,Double_t p8,
2385  Double_t p9,Double_t p10)
2386 {
2387  // Set a list of parameters.
2388  // The order is by default the aphabetic order given to the parameters
2389  // apart if the users has defined explicitly the parameter names
2390  if(fNpar >= 1) SetParameter(0,p0);
2391  if(fNpar >= 2) SetParameter(1,p1);
2392  if(fNpar >= 3) SetParameter(2,p2);
2393  if(fNpar >= 4) SetParameter(3,p3);
2394  if(fNpar >= 5) SetParameter(4,p4);
2395  if(fNpar >= 6) SetParameter(5,p5);
2396  if(fNpar >= 7) SetParameter(6,p6);
2397  if(fNpar >= 8) SetParameter(7,p7);
2398  if(fNpar >= 9) SetParameter(8,p8);
2399  if(fNpar >= 10) SetParameter(9,p9);
2400  if(fNpar >= 11) SetParameter(10,p10);
2401 }
2403 {
2404  // Set a parameter given a parameter index
2405  // The parameter index is by default the aphabetic order given to the parameters
2406  // apart if the users has defined explicitly the parameter names
2407  if (param < 0 || param >= fNpar) return;
2408  assert(int(fClingParameters.size()) == fNpar);
2409  fClingParameters[param] = value;
2410  // TString name = TString::Format("%d",param);
2411  // SetParameter(name,value);
2412 }
2413 void TFormula::SetParNames(const char *name0,const char *name1,const char *name2,const char *name3,
2414  const char *name4, const char *name5,const char *name6,const char *name7,
2415  const char *name8,const char *name9,const char *name10)
2416 {
2417  if(fNpar >= 1) SetParName(0,name0);
2418  if(fNpar >= 2) SetParName(1,name1);
2419  if(fNpar >= 3) SetParName(2,name2);
2420  if(fNpar >= 4) SetParName(3,name3);
2421  if(fNpar >= 5) SetParName(4,name4);
2422  if(fNpar >= 6) SetParName(5,name5);
2423  if(fNpar >= 7) SetParName(6,name6);
2424  if(fNpar >= 8) SetParName(7,name7);
2425  if(fNpar >= 9) SetParName(8,name8);
2426  if(fNpar >= 10) SetParName(9,name9);
2427  if(fNpar >= 11) SetParName(10,name10);
2428 }
2429 void TFormula::SetParName(Int_t ipar, const char * name)
2430 {
2431 
2432  if (ipar < 0 || ipar > fNpar) {
2433  Error("SetParName","Wrong Parameter index %d ",ipar);
2434  return;
2435  }
2436  TString oldName;
2437  // find parameter with given index
2438  for ( auto &it : fParams) {
2439  if (it.second == ipar) {
2440  oldName = it.first;
2441  fParams.erase(oldName);
2442  fParams.insert(std::make_pair(name, ipar) );
2443  break;
2444  }
2445  }
2446  if (oldName.IsNull() ) {
2447  Error("SetParName","Parameter %d is not existing.",ipar);
2448  return;
2449  }
2450 
2451  //replace also parameter name in formula expression
2452  ReplaceParamName(fFormula, oldName, name);
2453 
2454 }
2455 
2456 void TFormula::ReplaceParamName(TString & formula, const TString & oldName, const TString & name){
2457  // replace in Formula expression the parameter name
2458  if (!formula.IsNull() ) {
2459  bool found = false;
2460  for(list<TFormulaFunction>::iterator it = fFuncs.begin(); it != fFuncs.end(); ++it)
2461  {
2462  if(oldName == it->GetName())
2463  {
2464  found = true;
2465  it->fName = name;
2466  break;
2467  }
2468  }
2469  if(!found)
2470  {
2471  Error("SetParName","Parameter %s is not defined.",oldName.Data());
2472  return;
2473  }
2474  // change whitespace to \\s avoid problems in parsing
2475  TString newName = name;
2476  newName.ReplaceAll(" ","\\s");
2477  TString pattern = TString::Format("[%s]",oldName.Data());
2478  TString replacement = TString::Format("[%s]",newName.Data());
2479  formula.ReplaceAll(pattern,replacement);
2480  }
2481 
2482 }
2483 
2484 Double_t TFormula::EvalPar(const Double_t *x,const Double_t *params) const
2485 {
2486 
2487  return DoEval(x, params);
2488 }
2490 {
2491  //*-*
2492  //*-* Sets first 4 variables (e.g. x, y, z, t) and evaluate formula.
2493  //*-*
2494  double xxx[4] = {x,y,z,t};
2495  return DoEval(xxx);
2496 }
2498 {
2499  //*-*
2500  //*-* Sets first 3 variables (e.g. x, y, z) and evaluate formula.
2501  //*-*
2502  double xxx[3] = {x,y,z};
2503  return DoEval(xxx);
2504 }
2506 {
2507  //*-*
2508  //*-* Sets first 2 variables (e.g. x and y) and evaluate formula.
2509  //*-*
2510  double xxx[2] = {x,y};
2511  return DoEval(xxx);
2512 }
2514 {
2515  //*-*
2516  //*-* Sets first variable (e.g. x) and evaluate formula.
2517  //*-*
2518  //double xxx[1] = {x};
2519  double * xxx = &x;
2520  return DoEval(xxx);
2521 }
2522 Double_t TFormula::DoEval(const double * x, const double * params) const
2523 {
2524  //*-*
2525  //*-* Evaluate formula.
2526  //*-* If formula is not ready to execute(missing parameters/variables),
2527  //*-* print these which are not known.
2528  //*-* If parameter has default value, and has not been setted, appropriate warning is shown.
2529  //*-*
2530 
2531  if(!fReadyToExecute)
2532  {
2533  Error("Eval","Formula is invalid and not ready to execute ");
2534  for(auto it = fFuncs.begin(); it != fFuncs.end(); ++it)
2535  {
2536  TFormulaFunction fun = *it;
2537  if(!fun.fFound)
2538  {
2539  printf("%s is unknown.\n",fun.GetName());
2540  }
2541  }
2542  return TMath::QuietNaN();
2543  }
2544  if (fLambdaPtr && TestBit(TFormula::kLambda)) {// case of lambda functions
2545  std::function<double(double *, double *)> & fptr = * ( (std::function<double(double *, double *)> *) fLambdaPtr);
2546  assert(x);
2547  //double * v = (x) ? const_cast<double*>(x) : const_cast<double*>(fClingVariables.data());
2548  double * v = const_cast<double*>(x);
2549  double * p = (params) ? const_cast<double*>(params) : const_cast<double*>(fClingParameters.data());
2550  return fptr(v, p);
2551  }
2552  // this is needed when reading from a file
2553  if (!fClingInitialized) {
2554  Error("Eval","Formula is invalid or not properly initialized - try calling TFormula::Compile");
2555  return TMath::QuietNaN();
2556 #ifdef EVAL_IS_NOT_CONST
2557  // need to replace in cling the name of the pointer of this object
2558  TString oldClingName = fClingName;
2560  fClingInput.ReplaceAll(oldClingName, fClingName);
2562 #endif
2563  }
2564 
2565  Double_t result = 0;
2566  void* args[2];
2567  double * vars = (x) ? const_cast<double*>(x) : const_cast<double*>(fClingVariables.data());
2568  args[0] = &vars;
2569  if (fNpar <= 0)
2570  (*fFuncPtr)(0, 1, args, &result);
2571  else {
2572  double * pars = (params) ? const_cast<double*>(params) : const_cast<double*>(fClingParameters.data());
2573  args[1] = &pars;
2574  (*fFuncPtr)(0, 2, args, &result);
2575  }
2576  return result;
2577 }
2578 
2579 ////////////////////////////////////////////////////////////////////////////////
2580 /// return the expression formula
2581 /// If option = "P" replace the parameter names with their values
2582 /// If option = "CLING" return the actual expression used to build the function passed to cling
2583 /// If option = "CLINGP" replace in the CLING expression the parameter with their values
2584 
2586 {
2587  TString opt(option);
2588  if (opt.IsNull() || TestBit(TFormula::kLambda) ) return fFormula;
2589  opt.ToUpper();
2590 
2591  // if (opt.Contains("N") ) {
2592  // TString formula = fFormula;
2593  // ReplaceParName(formula, ....)
2594  // }
2595 
2596  if (opt.Contains("CLING") ) {
2597  std::string clingFunc = fClingInput.Data();
2598  std::size_t found = clingFunc.find("return");
2599  std::size_t found2 = clingFunc.rfind(";");
2600  if (found == std::string::npos || found2 == std::string::npos) {
2601  Error("GetExpFormula","Invalid Cling expression - return default formula expression");
2602  return fFormula;
2603  }
2604  TString clingFormula = fClingInput(found+7,found2-found-7);
2605  // to be implemented
2606  if (!opt.Contains("P")) return clingFormula;
2607  // replace all "p[" with "[parname"
2608  int i = 0;
2609  while (i < clingFormula.Length()-2 ) {
2610  // look for p[number
2611  if (clingFormula[i] == 'p' && clingFormula[i+1] == '[' && isdigit(clingFormula[i+2]) ) {
2612  int j = i+3;
2613  while ( isdigit(clingFormula[j]) ) { j++;}
2614  if (clingFormula[j] != ']') {
2615  Error("GetExpFormula","Parameters not found - invalid expression - return default cling formula");
2616  return clingFormula;
2617  }
2618  TString parNumbName = clingFormula(i+2,j-i-2);
2619  int parNumber = parNumbName.Atoi();
2620  assert(parNumber < fNpar);
2621  TString replacement = TString::Format("%f",GetParameter(parNumber));
2622  clingFormula.Replace(i,j-i+1, replacement );
2623  i += replacement.Length();
2624  }
2625  i++;
2626  }
2627  return clingFormula;
2628  }
2629  if (opt.Contains("P") ) {
2630  // replace parameter names with their values
2631  TString expFormula = fFormula;
2632  int i = 0;
2633  while (i < expFormula.Length()-2 ) {
2634  // look for [parName]
2635  if (expFormula[i] == '[') {
2636  int j = i+1;
2637  while ( expFormula[j] != ']' ) { j++;}
2638  if (expFormula[j] != ']') {
2639  Error("GetExpFormula","Parameter names not found - invalid expression - return default formula");
2640  return expFormula;
2641  }
2642  TString parName = expFormula(i+1,j-i-1);
2643  TString replacement = TString::Format("%g",GetParameter(parName));
2644  expFormula.Replace(i,j-i+1, replacement );
2645  i += replacement.Length();
2646  }
2647  i++;
2648  }
2649  return expFormula;
2650  }
2651  Warning("GetExpFormula","Invalid option - return defult formula expression");
2652  return fFormula;
2653 }
2654 ////////////////////////////////////////////////////////////////////////////////
2655 /// print the formula and its attributes
2656 
2657 void TFormula::Print(Option_t *option) const
2658 {
2659  printf(" %20s : %s Ndim= %d, Npar= %d, Number= %d \n",GetName(),GetTitle(), fNdim,fNpar,fNumber);
2660  printf(" Formula expression: \n");
2661  printf("\t%s \n",fFormula.Data() );
2662  TString opt(option);
2663  opt.ToUpper();
2664  // do an evaluation as a cross-check
2665  //if (fReadyToExecute) Eval();
2666 
2667  if (opt.Contains("V") ) {
2668  if (fNdim > 0 && !TestBit(TFormula::kLambda)) {
2669  printf("List of Variables: \n");
2670  assert(int(fClingVariables.size()) >= fNdim);
2671  for ( int ivar = 0; ivar < fNdim ; ++ivar) {
2672  printf("Var%4d %20s = %10f \n",ivar,GetVarName(ivar).Data(), fClingVariables[ivar]);
2673  }
2674  }
2675  if (fNpar > 0) {
2676  printf("List of Parameters: \n");
2677  if ( int(fClingParameters.size()) < fNpar)
2678  Error("Print","Number of stored parameters in vector %lu in map %lu is different than fNpar %d",fClingParameters.size(), fParams.size(), fNpar);
2679  assert(int(fClingParameters.size()) >= fNpar);
2680  // print with order passed to Cling function
2681  for ( int ipar = 0; ipar < fNpar ; ++ipar) {
2682  printf("Par%4d %20s = %10f \n",ipar,GetParName(ipar), fClingParameters[ipar] );
2683  }
2684  }
2685  printf("Expression passed to Cling:\n");
2686  printf("\t%s\n",fClingInput.Data() );
2687  }
2688  if(!fReadyToExecute)
2689  {
2690  Warning("Print","Formula is not ready to execute. Missing parameters/variables");
2691  for(list<TFormulaFunction>::const_iterator it = fFuncs.begin(); it != fFuncs.end(); ++it)
2692  {
2693  TFormulaFunction fun = *it;
2694  if(!fun.fFound)
2695  {
2696  printf("%s is unknown.\n",fun.GetName());
2697  }
2698  }
2699  }
2701  {
2702  // we can skip this
2703  // Info("Print","Not all parameters are setted.");
2704  // for(map<TString,TFormulaVariable>::const_iterator it = fParams.begin(); it != fParams.end(); ++it)
2705  // {
2706  // pair<TString,TFormulaVariable> param = *it;
2707  // if(!param.second.fFound)
2708  // {
2709  // printf("%s has default value %lf\n",param.first.Data(),param.second.GetInitialValue());
2710  // }
2711  // }
2712 
2713  }
2714 
2715 
2716 }
2717 ////////////////////////////////////////////////////////////////////////////////
2718 /// Stream a class object.
2719 
2720 void TFormula::Streamer(TBuffer &b)
2721 {
2722  if (b.IsReading() ) {
2723  UInt_t R__s, R__c;
2724  Version_t v = b.ReadVersion(&R__s, &R__c);
2725  //std::cout << "version " << v << std::endl;
2726  if (v <= 8 && v > 3 && v != 6) {
2727  // old TFormula class
2728  ROOT::v5::TFormula * fold = new ROOT::v5::TFormula();
2729  // read old TFormula class
2730  fold->Streamer(b, v, R__s, R__c, TFormula::Class());
2731  //std::cout << "read old tformula class " << std::endl;
2732  TFormula fnew(fold->GetName(), fold->GetExpFormula() );
2733 
2734  *this = fnew;
2735 
2736 // printf("copying content in a new TFormula \n");
2737  SetParameters(fold->GetParameters() );
2738  if (!fReadyToExecute ) {
2739  Error("Streamer","Old formula read from file is NOT valid");
2740  Print("v");
2741  }
2742  delete fold;
2743  return;
2744  }
2745  else if (v > 8) {
2746  // new TFormula class
2747  b.ReadClassBuffer(TFormula::Class(), this, v, R__s, R__c);
2748 
2749  //std::cout << "reading npar = " << GetNpar() << std::endl;
2750 
2751  // initialize the formula
2752  // need to set size of fClingVariables which is transient
2753  //fClingVariables.resize(fNdim);
2754 
2755  // case of formula contains only parameters
2756  if (fFormula.IsNull() ) return;
2757 
2758 
2759  // store parameter values, names and order
2760  std::vector<double> parValues = fClingParameters;
2761  auto paramMap = fParams;
2762  fNpar = fParams.size();
2763 
2764  if (!TestBit(TFormula::kLambda) ) {
2765 
2766  //std::cout << "Streamer::Reading preprocess the formula " << fFormula << " ndim = " << fNdim << " npar = " << fNpar << std::endl;
2767  // for ( auto &p : fParams)
2768  // std::cout << "parameter " << p.first << " index " << p.second << std::endl;
2769 
2770  fClingParameters.clear(); // need to be reset before re-initializing it
2771 
2772  FillDefaults();
2773 
2774 
2776 
2777  //std::cout << "Streamer::after pre-process the formula " << fFormula << " ndim = " << fNdim << " npar = " << fNpar << std::endl;
2778 
2780 
2781  //std::cout << "Streamer::after prepared " << fClingInput << " ndim = " << fNdim << " npar = " << fNpar << std::endl;
2782 
2783 
2784  // restore parameter values
2785  if (fNpar != (int) parValues.size() ) {
2786  Error("Streamer","number of parameters computed (%d) is not same as the stored parameters (%d)",fNpar,int(parValues.size()) );
2787  Print("v");
2788  }
2789  }
2790  else {
2791  // case of lamda expressions
2792  bool ret = InitLambdaExpression(fFormula);
2793  if (ret) {
2794  fReadyToExecute = true;
2795  fClingInitialized = true;
2796  }
2797  }
2798  assert(fNpar == (int) parValues.size() );
2799  std::copy( parValues.begin(), parValues.end(), fClingParameters.begin() );
2800  // restore parameter names and order
2801  if (fParams.size() != paramMap.size() ) {
2802  Warning("Streamer","number of parameters list found (%lu) is not same as the stored one (%lu) - use re-created list",fParams.size(),paramMap.size()) ;
2803  //Print("v");
2804  }
2805  else
2806  //assert(fParams.size() == paramMap.size() );
2807  fParams = paramMap;
2808 
2809  // input formula into Cling
2810  // need to replace in cling the name of the pointer of this object
2811  // TString oldClingName = fClingName;
2812  // fClingName.Replace(fClingName.Index("_0x")+1,fClingName.Length(), TString::Format("%p",this) );
2813  // fClingInput.ReplaceAll(oldClingName, fClingName);
2814  // InputFormulaIntoCling();
2815 
2816 
2817 
2818  if (!TestBit(kNotGlobal)) {
2820  gROOT->GetListOfFunctions()->Add(this);
2821  }
2822  if (!fReadyToExecute ) {
2823  Error("Streamer","Formula read from file is NOT ready to execute");
2824  Print("v");
2825  }
2826  //std::cout << "reading 2 npar = " << GetNpar() << std::endl;
2827 
2828  return;
2829  }
2830  else {
2831  Error("Streamer","Reading version %d is not supported",v);
2832  return;
2833  }
2834  }
2835  else {
2836  // case of writing
2838  //std::cout << "writing npar = " << GetNpar() << std::endl;
2839  }
2840 }
Bool_t IsFuncCall() const
Definition: TFormula.h:43
virtual void Clear(Option_t *option="")
Set name and title to empty strings ("").
Definition: TFormula.cxx:591
static Bool_t IsBracket(const char c)
Definition: TFormula.cxx:162
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:52
Ssiz_t Last(char c) const
Find last occurrence of a character c.
Definition: TString.cxx:864
void Streamer(TBuffer &b, const TClass *onfile_class)
Stream a class object.
void HandleExponentiation(TString &formula)
Definition: TFormula.cxx:1129
std::map< TString, Double_t > fConsts
Definition: TFormula.h:121
virtual Int_t WriteClassBuffer(const TClass *cl, void *pointer)=0
Double_t G()
Definition: TMath.h:68
virtual CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *) const
Definition: TInterpreter.h:275
Int_t fNpar
Definition: TFormula.h:125
Double_t Floor(Double_t x)
Definition: TMath.h:473
virtual TFormula * GetFormula()
Definition: TF1.h:332
Double_t H()
Definition: TMath.h:81
std::vector< TObject * > fLinearParts
Definition: TFormula.h:127
static double p3(double t, double a, double b, double c, double d)
Double_t Eval(Double_t x) const
Definition: TFormula.cxx:2513
Bool_t IsReading() const
Definition: TBuffer.h:81
short Version_t
Definition: RtypesCore.h:61
Int_t GetVarNumber(const char *name) const
Definition: TFormula.cxx:2099
Ssiz_t Length() const
Definition: TString.h:390
void variables(TString fin="TMVA.root", TString dirName="InputVariables_Id", TString title="TMVA Input Variables", Bool_t isRegression=kFALSE, Bool_t useTMVAStyle=kTRUE)
Definition: variables.cxx:10
static const TString gNamePrefix
Definition: TFormula.cxx:145
void AddVariables(const TString *vars, const Int_t size)
Definition: TFormula.cxx:1992
TMethodCall * fMethod
Definition: TFormula.h:101
const char Option_t
Definition: RtypesCore.h:62
void DoSetParameters(const Double_t *p, Int_t size)
Definition: TFormula.cxx:2359
void HandleLinear(TString &formula)
Definition: TFormula.cxx:1229
void HandlePolN(TString &formula)
Definition: TFormula.cxx:788
Double_t QuietNaN()
Definition: TMath.h:635
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:635
#define assert(cond)
Definition: unittest.h:542
TString fName
Definition: TFormula.h:35
Int_t GetNargs() const
Number of function arguments.
Definition: TFunction.cxx:164
void SetParameters(const Double_t *params)
Definition: TFormula.cxx:2376
virtual void SetName(const char *name)
Change (i.e.
Definition: TNamed.cxx:128
Double_t Sqrt2()
Definition: TMath.h:51
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:892
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")
Definition: TFormula.cxx:2413
void SetVariables(const std::pair< TString, Double_t > *vars, const Int_t size)
Definition: TFormula.cxx:2062
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1101
Buffer base class used for serializing objects.
Definition: TBuffer.h:40
CallFunc_t * GetCallFunc() const
Definition: TMethodCall.h:97
Helper class for TFormula.
Definition: TFormula.h:32
#define gROOT
Definition: TROOT.h:352
Basic string class.
Definition: TString.h:137
void AddVariable(const TString &name, Double_t value=0)
Definition: TFormula.cxx:1957
void InputFormulaIntoCling()
pointer to the lambda function
Definition: TFormula.cxx:679
void DoAddParameter(const TString &name, Double_t value, bool processFormula)
Definition: TFormula.cxx:2144
int Int_t
Definition: RtypesCore.h:41
virtual void Copy(TObject &f1) const
Copy this to obj.
Definition: TFormula.cxx:518
bool Bool_t
Definition: RtypesCore.h:59
TArc * a
Definition: textangle.C:12
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:63
const TList * GetListOfAllPublicMethods(Bool_t load=kTRUE)
Returns a list of all public methods of this class and its base classes.
Definition: TClass.cxx:3611
Bool_t fFound
Definition: TFormula.h:38
Bool_t fAllParametersSetted
transient to force re-initialization
Definition: TFormula.h:100
#define gInterpreter
Definition: TInterpreter.h:502
Double_t EulerGamma()
Definition: TMath.h:122
Int_t GetParNumber(const char *name) const
Definition: TFormula.cxx:2226
STL namespace.
const TObject * GetLinearPart(Int_t i) const
Definition: TFormula.cxx:1943
TString & Insert(Ssiz_t pos, const char *s)
Definition: TString.h:592
void SetPredefinedParamNames()
Definition: TFormula.cxx:1883
void Print(Option_t *option="") const
print the formula and its attributes
Definition: TFormula.cxx:2657
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:732
Bool_t PrepareFormula(TString &formula)
Definition: TFormula.cxx:1299
TString & Replace(Ssiz_t pos, Ssiz_t n, const char *s)
Definition: TString.h:625
const char * Data() const
Definition: TString.h:349
void ReplaceParamName(TString &formula, const TString &oldname, const TString &name)
Definition: TFormula.cxx:2456
virtual ~TFormula()
Definition: TFormula.cxx:274
Double_t x[n]
Definition: legend1.C:17
Double_t EvalPar(const Double_t *x, const Double_t *params=0) const
Definition: TFormula.cxx:2484
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString...
Definition: TString.cxx:2334
Double_t C()
Definition: TMath.h:63
Double_t R()
Definition: TMath.h:109
void Class()
Definition: Class.C:29
Int_t fArrayPos
Definition: TFormula.h:70
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:33
Double_t Ln10()
Definition: TMath.h:57
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:83
void SetParameter(const char *name, Double_t value)
Definition: TFormula.cxx:2296
TString GetVarName(Int_t ivar) const
Definition: TFormula.cxx:2113
Double_t Log10(Double_t x)
Definition: TMath.h:529
virtual Bool_t Declare(const char *code)=0
static double p2(double t, double a, double b, double c)
void(* Generic_t)(void *, int, void **, void *)
Definition: TInterpreter.h:77
TInterpreter::CallFuncIFacePtr_t::Generic_t fFuncPtr
unique name passed to Cling to define the function ( double clingName(double*x, double*p) ) ...
Definition: TFormula.h:104
static Bool_t IsScientificNotation(const TString &formula, int ipos)
Definition: TFormula.cxx:183
TFormula & operator=(const TFormula &rhs)
Definition: TFormula.cxx:430
static bool IsReservedName(const char *name)
Definition: TFormula.cxx:265
TString & Append(const char *cs)
Definition: TString.h:492
std::vector< std::vector< double > > Data
static const std::string pattern("pattern")
TString GetExpFormula(Option_t *option="") const
return the expression formula If option = "P" replace the parameter names with their values If option...
Definition: TFormula.cxx:2585
Int_t Atoi() const
Return integer value of string.
Definition: TString.cxx:1964
Double_t fValue
Definition: TFormula.h:69
void * fLambdaPtr
function pointer
Definition: TFormula.h:105
Method or function calling interface.
Definition: TMethodCall.h:41
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:918
Int_t GetNdim() const
Definition: TFormula.h:177
void SetParName(Int_t ipar, const char *name)
Definition: TFormula.cxx:2429
static std::unordered_map< std::string, void * > gClingFunctions
Definition: TFormula.cxx:149
Double_t Infinity()
Definition: TMath.h:648
A doubly linked list.
Definition: TList.h:47
Double_t Sigma()
Definition: TMath.h:100
Int_t fNdim
Definition: TFormula.h:124
Int_t GetNargsOpt() const
Number of function optional (default) arguments.
Definition: TFunction.cxx:174
virtual void Delete(Option_t *option="")
Delete this object.
Definition: TObject.cxx:228
static Bool_t IsHexadecimal(const TString &formula, int ipos)
Definition: TFormula.cxx:194
std::vector< Double_t > fClingParameters
cached variables
Definition: TFormula.h:97
Int_t GetNpar() const
Definition: TFormula.h:178
void FillDefaults()
Definition: TFormula.cxx:690
void HandleParametrizedFunctions(TString &formula)
Definition: TFormula.cxx:881
SVector< double, 2 > v
Definition: Dict.h:5
static Bool_t IsOperator(const char c)
Definition: TFormula.cxx:151
void SetName(const char *name)
Change (i.e.
Definition: TFormula.cxx:2040
The F O R M U L A class.
Definition: TFormula.h:89
unsigned int UInt_t
Definition: RtypesCore.h:42
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:173
TMarker * m
Definition: textangle.C:8
static Bool_t IsDefaultVariableName(const TString &name)
Definition: TFormula.cxx:177
Double_t K()
Definition: TMath.h:95
Double_t E()
Definition: TMath.h:54
bool operator()(const TString &a, const TString &b) const
Definition: TFormula.cxx:215
static Bool_t IsFunctionNameChar(const char c)
Definition: TFormula.cxx:172
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
The ROOT global object gROOT contains a list of all defined classes.
Definition: TClass.h:81
const std::string sname
Definition: testIO.cxx:45
static double p1(double t, double a, double b)
Int_t CountChar(Int_t c) const
Return number of times character c occurs in the string.
Definition: TString.cxx:443
Double_t DoEval(const Double_t *x, const Double_t *p=nullptr) const
Definition: TFormula.cxx:2522
Bool_t IsNull() const
Definition: TString.h:387
Double_t GetVariable(const char *name) const
Definition: TFormula.cxx:2086
Bool_t PrepareEvalMethod()
Definition: TFormula.cxx:623
TString fFormula
Definition: TFormula.h:123
void InitWithPrototype(TClass *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
Initialize the method invocation environment.
#define R__LOCKGUARD2(mutex)
TString fClingName
pointer to methocall
Definition: TFormula.h:102
Double_t Pi()
Definition: TMath.h:44
std::vector< Double_t > fClingVariables
input function passed to Cling
Definition: TFormula.h:96
virtual Int_t ReadClassBuffer(const TClass *cl, void *pointer, const TClass *onfile_class=0)=0
int Ssiz_t
Definition: RtypesCore.h:63
virtual Double_t * GetParameters() const
Definition: TFormula.h:249
std::map< TString, TString > fFunctionsShortcuts
Definition: TFormula.h:122
#define ClassImp(name)
Definition: Rtypes.h:279
double f(double x)
Double_t * GetParameters() const
Definition: TFormula.cxx:2278
double Double_t
Definition: RtypesCore.h:55
Int_t GetNumber() const
Definition: TFormula.h:179
Double_t y[n]
Definition: legend1.C:17
Int_t fNumber
Definition: TFormula.h:126
Int_t Compile(const char *expression="")
Definition: TFormula.cxx:479
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Definition: TClass.cxx:2871
Int_t GetNargs() const
Definition: TFormula.h:42
#define name(a, b)
Definition: linkTestLib0.cpp:5
void SetVariable(const TString &name, Double_t value)
Definition: TFormula.cxx:2130
const char * GetParName(Int_t ipar) const
Definition: TFormula.cxx:2263
Mother of all ROOT objects.
Definition: TObject.h:58
Bool_t InitLambdaExpression(const char *formula)
Definition: TFormula.cxx:442
TString fName
Definition: TFormula.h:68
Global functions class (global functions are obtained from CINT).
Definition: TFunction.h:30
Bool_t IsDigit() const
Returns true if all characters in string are digits (0-9) or white spaces, i.e.
Definition: TString.cxx:1806
Bool_t IsValid() const
Definition: TFormula.h:189
const Ssiz_t kNPOS
Definition: Rtypes.h:115
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:202
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
1-Dim function class
Definition: TF1.h:149
void ProcessFormula(TString &formula)
Definition: TFormula.cxx:1533
Each ROOT class (see TClass) has a linked list of methods.
Definition: TMethod.h:40
TF1 * f1
Definition: legend1.C:11
R__EXTERN Int_t gDebug
Definition: Rtypes.h:128
double result[121]
Bool_t fReadyToExecute
Definition: TFormula.h:98
R__EXTERN TInterpreter * gCling
Definition: TInterpreter.h:504
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:582
void ExtractFunctors(TString &formula)
Definition: TFormula.cxx:1330
TString fClingInput
Definition: TFormula.h:95
virtual TString GetExpFormula(Option_t *option="") const
Reconstruct the formula expression from the internal TFormula member variables.
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition: TObject.cxx:379
float value
Definition: math.cpp:443
std::map< TString, TFormulaVariable > fVars
Definition: TFormula.h:119
const Int_t n
Definition: legend1.C:16
Bool_t fClingInitialized
trasient to force initialization
Definition: TFormula.h:99
std::map< TString, Int_t, TFormulaParamOrder > fParams
list of variable names
Definition: TFormula.h:120
Double_t GetParameter(const char *name) const
Definition: TFormula.cxx:2238
Bool_t IsValid() const
Return true if the method call has been properly initialized and is usable.
std::list< TFormulaFunction > fFuncs
Definition: TFormula.h:118
Another helper class for TFormula.
Definition: TFormula.h:65
Double_t LogE()
Definition: TMath.h:60
virtual Version_t ReadVersion(UInt_t *start=0, UInt_t *bcnt=0, const TClass *cl=0)=0
void PreProcessFormula(TString &formula)
Definition: TFormula.cxx:1277
const char * GetName() const
Definition: TFormula.h:40
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:904