27#include <unordered_map>
33#pragma optimize("",off)
212static std::unordered_map<std::string, void *>
gClingFunctions = std::unordered_map<std::string, void * >();
219 for (
int i = 0; i < nobjects; ++i) {
220 if (fromv5[i] && target[i]) {
237 const static std::set<char> ops {
'+',
'^',
'-',
'/',
'*',
'<',
'>',
'|',
'&',
'!',
'=',
'?',
'%'};
238 return ops.end() != ops.find(
c);
245 char brackets[] = {
')',
'(',
'{',
'}'};
246 Int_t bracketsLen =
sizeof(brackets)/
sizeof(
char);
247 for(
Int_t i = 0; i < bracketsLen; ++i)
269 if ( (formula[i] ==
'e' || formula[i] ==
'E') && (i > 0 && i < formula.
Length()-1) ) {
271 if ( (isdigit(formula[i-1]) || formula[i-1] ==
'.') && ( isdigit(formula[i+1]) || formula[i+1] ==
'+' || formula[i+1] ==
'-' ) )
281 if ( (formula[i] ==
'x' || formula[i] ==
'X') && (i > 0 && i < formula.
Length()-1) && formula[i-1] ==
'0') {
282 if (isdigit(formula[i+1]) )
284 static char hex_values[12] = {
'a',
'A',
'b',
'B',
'c',
'C',
'd',
'D',
'e',
'E',
'f',
'F'};
285 for (
int jjj = 0; jjj < 12; ++jjj) {
286 if (formula[i+1] == hex_values[jjj])
303 Bool_t foundOpenParenthesis =
false;
304 if (pos == 0 || pos == formula.
Length()-1)
return false;
305 for (
int i = pos-1; i >=0; i--) {
306 if (formula[i] ==
']' )
return false;
307 if (formula[i] ==
'[' ) {
308 foundOpenParenthesis =
true;
312 if (!foundOpenParenthesis )
return false;
315 for (
int i = pos+1; i < formula.
Length(); i++) {
316 if (formula[i] ==
']' )
return true;
329 TRegexp numericPattern(
"p?[0-9]+");
332 int patternStart = numericPattern.
Index(
a, &len);
333 bool aNumeric = (patternStart == 0 && len ==
a.Length());
335 patternStart = numericPattern.
Index(
b, &len);
336 bool bNumeric = (patternStart == 0 && len ==
b.Length());
338 if (aNumeric && !bNumeric)
340 else if (!aNumeric && bNumeric)
342 else if (!aNumeric && !bNumeric)
345 int aInt = (
a[0] ==
'p') ?
TString(
a(1,
a.Length())).
Atoi() :
a.Atoi();
346 int bInt = (
b[0] ==
'p') ?
TString(
b(1,
b.Length())).
Atoi() :
b.Atoi();
357 for (
int i = 0; i < formula.
Length(); i++) {
360 if (isalpha(formula[i]) || formula[i] ==
'{' || formula[i] ==
'[') {
364 || (formula[i] ==
'{' && formula[j] ==
'}'));
372 if (substitutions.find(
name) != substitutions.end()) {
376 }
else if (isalpha(formula[i])) {
379 i +=
name.Length() - 1;
405 if (strlen(
name)!=1)
return false;
406 for (
auto const & specialName : {
"x",
"y",
"z",
"t"}){
407 if (strcmp(
name,specialName)==0)
return true;
420 gROOT->GetListOfFunctions()->Remove(
this);
428 for (
int i = 0; i < nLinParts; ++i)
delete fLinearParts[i];
435 fClingInput(formula),fFormula(formula)
446#ifndef R__HAS_VECCORE
453 if (addToGlobList &&
gROOT) {
458 gROOT->GetListOfFunctions()->Remove(old);
460 Error(
"TFormula",
"The name %s is reserved as a TFormula variable name.\n",
name);
462 gROOT->GetListOfFunctions()->Add(
this);
482 fClingInput(formula),fFormula(formula)
495 for (
int i = 0; i < npar; ++i) {
499 assert (
fNpar == npar);
509 if (addToGlobList &&
gROOT) {
514 gROOT->GetListOfFunctions()->Remove(old);
516 Error(
"TFormula",
"The name %s is reserved as a TFormula variable name.\n",
name);
518 gROOT->GetListOfFunctions()->Add(
this);
523 Error(
"TFormula",
"Syntax error in building the lambda expression %s", formula );
528 TNamed(formula.
GetName(),formula.GetTitle()), fMethod(nullptr)
536 gROOT->GetListOfFunctions()->Remove(old);
539 Error(
"TFormula",
"The name %s is reserved as a TFormula variable name.\n",formula.
GetName());
541 gROOT->GetListOfFunctions()->Add(
this);
561 std::string lambdaExpression = formula;
585 TString lineExpr =
TString::Format(
"std::function<double(double*,double*)> %s = %s ;",lambdaName.
Data(), lambdaExpression.c_str() );
612 if (formula.
IsNull() )
return -1;
624 return (ret) ? 0 : 1;
634 return (ret) ? 0 : 1;
663 for (
int i = 0; i < nLinParts; ++i)
delete fnew.
fLinearParts[i];
670 for (
int i = 0; i < nLinParts; ++i) {
674 linearOld->
Copy(*linearNew);
699 Error(
"TFormula",
"Syntax error in building the lambda expression %s",
fFormula.
Data() );
752 for (
int i = 0; i < nLinParts; ++i)
delete fLinearParts[i];
759static std::unique_ptr<TMethodCall>
761 bool IsVectorized,
bool IsGradient =
false) {
762 std::unique_ptr<TMethodCall> Method = std::unique_ptr<TMethodCall>(
new TMethodCall());
764 TString prototypeArguments =
"";
765 if (HasVariables || HasParameters) {
767 prototypeArguments.
Append(
"ROOT::Double_v*");
769 prototypeArguments.
Append(
"Double_t*");
771 auto AddDoublePtrParam = [&prototypeArguments] () {
772 prototypeArguments.
Append(
",");
773 prototypeArguments.
Append(
"Double_t*");
784 Method->InitWithPrototype(FuncName, prototypeArguments);
785 if (!Method->IsValid()) {
786 Error(
"prepareMethod",
787 "Can't compile function %s prototype with arguments %s", FuncName,
788 prototypeArguments.
Data());
797 if (!Method)
return nullptr;
801 Error(
"prepareFuncPtr",
"Callfunc retuned from Cling is not valid");
808 Error(
"prepareFuncPtr",
"Compiled function pointer is null");
845 TString triggerAutoparsing =
"namespace ROOT_TFormula_triggerAutoParse {\n"; triggerAutoparsing +=
fClingInput +
"\n}";
864 const TString defvars[] = {
"x",
"y",
"z",
"t"};
865 const pair<TString, Double_t> defconsts[] = {{
"pi",
TMath::Pi()},
883 const pair<TString,TString> funShortcuts[] =
884 { {
"sin",
"TMath::Sin" },
885 {
"cos",
"TMath::Cos" }, {
"exp",
"TMath::Exp"}, {
"log",
"TMath::Log"}, {
"log10",
"TMath::Log10"},
886 {
"tan",
"TMath::Tan"}, {
"sinh",
"TMath::SinH"}, {
"cosh",
"TMath::CosH"},
887 {
"tanh",
"TMath::TanH"}, {
"asin",
"TMath::ASin"}, {
"acos",
"TMath::ACos"},
888 {
"atan",
"TMath::ATan"}, {
"atan2",
"TMath::ATan2"}, {
"sqrt",
"TMath::Sqrt"},
889 {
"ceil",
"TMath::Ceil"}, {
"floor",
"TMath::Floor"}, {
"pow",
"TMath::Power"},
890 {
"binomial",
"TMath::Binomial"},{
"abs",
"TMath::Abs"},
891 {
"min",
"TMath::Min"},{
"max",
"TMath::Max"},{
"sign",
"TMath::Sign" },
895 std::vector<TString> defvars2(10);
896 for (
int i = 0; i < 9; ++i)
899 for (
const auto &var : defvars) {
900 int pos =
fVars.size();
913 for (
auto con : defconsts) {
914 fConsts[con.first] = con.second;
919 for (
auto fun : funShortcuts) {
932 const pair<TString,TString> vecFunShortcuts[] =
933 { {
"sin",
"vecCore::math::Sin" },
934 {
"cos",
"vecCore::math::Cos" }, {
"exp",
"vecCore::math::Exp"}, {
"log",
"vecCore::math::Log"}, {
"log10",
"vecCore::math::Log10"},
935 {
"tan",
"vecCore::math::Tan"},
937 {
"asin",
"vecCore::math::ASin"},
938 {
"acos",
"TMath::Pi()/2-vecCore::math::ASin"},
939 {
"atan",
"vecCore::math::ATan"},
940 {
"atan2",
"vecCore::math::ATan2"}, {
"sqrt",
"vecCore::math::Sqrt"},
941 {
"ceil",
"vecCore::math::Ceil"}, {
"floor",
"vecCore::math::Floor"}, {
"pow",
"vecCore::math::Pow"},
942 {
"cbrt",
"vecCore::math::Cbrt"},{
"abs",
"vecCore::math::Abs"},
943 {
"min",
"vecCore::math::Min"},{
"max",
"vecCore::math::Max"},{
"sign",
"vecCore::math::Sign" }
947 for (
auto fun : vecFunShortcuts) {
967 Bool_t defaultVariable =
false;
969 Int_t openingBracketPos = formula.
Index(
'(', polPos);
970 Bool_t defaultCounter = openingBracketPos ==
kNPOS;
971 Bool_t defaultDegree =
true;
974 if (!defaultCounter) {
977 sdegree = formula(polPos + 3, openingBracketPos - polPos - 3);
979 defaultCounter =
true;
981 if (!defaultCounter) {
983 counter =
TString(formula(openingBracketPos + 1, formula.
Index(
')', polPos) - openingBracketPos)).
Atoi();
985 Int_t temp = polPos + 3;
986 while (temp < formula.
Length() && isdigit(formula[temp])) {
987 defaultDegree =
false;
995 if (polPos - 1 < 0 || !
IsFunctionNameChar(formula[polPos - 1]) || formula[polPos - 1] ==
':') {
997 defaultVariable =
true;
999 Int_t tmp = polPos - 1;
1003 variable = formula(tmp + 1, polPos - (tmp + 1));
1005 Int_t param = counter + 1;
1017 replacement.
Insert(0,
'(');
1021 if (defaultCounter && !defaultDegree) {
1023 }
else if (defaultCounter && defaultDegree) {
1030 Error(
"HandlePolN",
"Error handling polynomial function - expression is %s - trying to replace %s with %s ",
1034 if (formula == pattern) {
1040 polPos = formula.
Index(
"pol");
1066 map< pair<TString,Int_t> ,pair<TString,TString> > functions;
1069 map<TString,Int_t> functionsNumbers;
1070 functionsNumbers[
"gaus"] = 100;
1071 functionsNumbers[
"bigaus"] = 102;
1072 functionsNumbers[
"landau"] = 400;
1073 functionsNumbers[
"expo"] = 200;
1074 functionsNumbers[
"crystalball"] = 500;
1085 formula.
ReplaceAll(
"xylandau",
"landau[x,y]");
1088 const char * defaultVariableNames[] = {
"x",
"y",
"z"};
1090 for (map<pair<TString, Int_t>, pair<TString, TString>>::iterator it = functions.begin(); it != functions.end();
1093 TString funName = it->first.first;
1094 Int_t funDim = it->first.second;
1104 Int_t iposBefore = funPos - 1;
1107 if (iposBefore >= 0) {
1108 assert(iposBefore < formula.
Length());
1109 if (isalpha(formula[iposBefore])) {
1112 funPos = formula.
Index(funName, lastFunPos);
1117 Bool_t isNormalized =
false;
1118 if (lastFunPos < formula.
Length()) {
1120 isNormalized = (formula[lastFunPos] ==
'n');
1123 if (lastFunPos < formula.
Length()) {
1124 char c = formula[lastFunPos];
1127 if (isalnum(
c) || (!
IsOperator(
c) &&
c !=
'(' &&
c !=
')' &&
c !=
'[' &&
c !=
']')) {
1129 funPos = formula.
Index(funName, lastFunPos);
1141 Bool_t defaultVariables =
false;
1144 Int_t openingBracketPos = funPos + funName.
Length() + (isNormalized ? 1 : 0);
1146 if (openingBracketPos > formula.
Length() || formula[openingBracketPos] !=
'[') {
1149 for (
Int_t idim = 0; idim < dim; ++idim)
1150 variables[idim] = defaultVariableNames[idim];
1151 defaultVariables =
true;
1154 closingBracketPos = formula.
Index(
']', openingBracketPos);
1155 varList = formula(openingBracketPos + 1, closingBracketPos - openingBracketPos - 1);
1162 varName.
Append(varList[i]);
1164 if (varList[i] ==
',') {
1177 if (dim != funDim) {
1178 pair<TString, Int_t> key = make_pair(funName, dim);
1179 if (functions.find(key) == functions.end()) {
1180 Error(
"PreProcessFormula",
"Dimension of function %s is detected to be of dimension %d and is not "
1181 "compatible with existing pre-defined function which has dim %d",
1182 funName.
Data(), dim, funDim);
1186 funPos = formula.
Index(funName, lastFunPos);
1191 Int_t openingParenthesisPos = (closingBracketPos ==
kNPOS) ? openingBracketPos : closingBracketPos + 1;
1192 bool defaultCounter = (openingParenthesisPos > formula.
Length() || formula[openingParenthesisPos] !=
'(');
1197 if (defaultCounter) {
1203 TRegexp counterPattern(
"([0-9]+)");
1205 if (counterPattern.
Index(formula, &len, openingParenthesisPos) == -1) {
1206 funPos = formula.
Index(funName, funPos + 1);
1210 TString(formula(openingParenthesisPos + 1, formula.
Index(
')', funPos) - openingParenthesisPos - 1))
1216 TString body = (isNormalized ? it->second.second : it->second.first);
1217 if (isNormalized && body ==
"") {
1218 Error(
"PreprocessFormula",
"%d dimension function %s has no normalized form.", it->first.second,
1222 for (
int i = 0; i < body.
Length(); ++i) {
1223 if (body[i] ==
'{') {
1231 i += variable.
Length() - 1;
1232 }
else if (body[i] ==
'[') {
1235 while (tmp < body.
Length() && body[tmp] !=
']') {
1242 body.
Replace(i + 1, tmp - 1 - i, replacement, replacement.
Length());
1243 i += replacement.
Length() + 1;
1247 if (defaultCounter && defaultVariables) {
1250 if (!defaultCounter && defaultVariables) {
1251 pattern =
TString::Format(
"%s%s(%d)", funName.
Data(), (isNormalized ?
"n" :
""), counter);
1253 if (defaultCounter && !defaultVariables) {
1256 if (!defaultCounter && !defaultVariables) {
1264 fNumber = functionsNumbers[funName] + 10 * (dim - 1);
1271 funPos = formula.
Index(funName);
1281 TRegexp rangePattern(
"\\[[0-9]+\\.\\.[0-9]+\\]");
1284 while ((matchIdx = rangePattern.
Index(formula, &len, matchIdx)) != -1) {
1285 int startIdx = matchIdx + 1;
1286 int endIdx = formula.
Index(
"..", startIdx) + 2;
1290 if (endCnt <= startCnt)
1291 Error(
"HandleParamRanges",
"End parameter (%d) <= start parameter (%d) in parameter range", endCnt, startCnt);
1294 for (
int cnt = startCnt;
cnt < endCnt;
cnt++)
1299 formula.
Replace(matchIdx, formula.
Index(
"]", matchIdx) + 1 - matchIdx, newString);
1301 matchIdx += newString.
Length();
1315 std::map<std::pair<TString, Int_t>, std::pair<TString, TString>> parFunctions;
1323 if (formula[i] ==
'[') {
1324 while (formula[i] !=
']')
1329 if (formula[i] ==
'\"') {
1332 while (formula[i] !=
'\"');
1346 if (isalpha(formula[i]) && !
IsOperator(formula[i])) {
1359 std::vector<int> argSeparators;
1360 argSeparators.push_back(j);
1362 for (k = j + 1; depth >= 1 && k < formula.
Length(); k++) {
1363 if (formula[k] ==
',' && depth == 1) {
1365 argSeparators.push_back(k);
1366 }
else if (formula[k] ==
'(')
1368 else if (formula[k] ==
')')
1371 argSeparators.push_back(k - 1);
1377 obj =
gROOT->GetListOfFunctions()->FindObject(
name);
1382 TF1 *
f1 =
dynamic_cast<TF1 *
>(obj);
1390 bool nameRecognized = (
f !=
nullptr);
1397 ndim =
f->GetNdim();
1398 npar =
f->GetNpar();
1399 replacementFormula =
f->GetExpFormula();
1403 for (
auto keyval : parFunctions) {
1405 pair<TString, Int_t> name_ndim = keyval.first;
1407 pair<TString, TString> formulaPair = keyval.second;
1410 if (
name == name_ndim.first)
1411 replacementFormula = formulaPair.first;
1412 else if (
name == name_ndim.first +
"n" && formulaPair.second !=
"")
1413 replacementFormula = formulaPair.second;
1418 ndim = name_ndim.second;
1423 while ((idx = replacementFormula.
Index(
'[', idx)) !=
kNPOS) {
1424 npar = max(npar, 1 +
TString(replacementFormula(idx + 1, replacementFormula.
Length())).
Atoi());
1425 idx = replacementFormula.
Index(
']', idx);
1427 Error(
"HandleFunctionArguments",
"Square brackets not matching in formula %s",
1428 (
const char *)replacementFormula);
1435 if (nArguments == ndim + npar || nArguments == npar || nArguments == ndim) {
1436 nameRecognized =
true;
1441 if (nameRecognized && ndim > 4)
1442 Error(
"HandleFunctionArguments",
"Number of dimensions %d greater than 4. Cannot parse formula.", ndim);
1445 if (nameRecognized && j < formula.
Length() && formula[j] ==
'(') {
1450 map<TString, TString> argSubstitutions;
1452 const char *defaultVariableNames[] = {
"x",
"y",
"z",
"t"};
1455 bool canReplace =
false;
1456 if (nArguments == ndim + npar) {
1458 for (
int argNr = 0; argNr < nArguments; argNr++) {
1462 TString(formula(argSeparators[argNr] + 1, argSeparators[argNr + 1] - argSeparators[argNr] - 1));
1469 argSubstitutions[oldName] = newName;
1472 argSubstitutions[defaultVariableNames[argNr]] = newName;
1475 int parNr = argNr - ndim;
1478 argSubstitutions[oldName] = newName;
1481 if (
f && oldName == newName)
1487 }
else if (nArguments == npar) {
1492 bool varsImplicit =
true;
1493 for (
int argNr = 0; argNr < nArguments && varsImplicit; argNr++) {
1494 int openIdx = argSeparators[argNr] + 1;
1495 int closeIdx = argSeparators[argNr + 1] - 1;
1498 if (formula[openIdx] !=
'[' || formula[closeIdx] !=
']' || closeIdx <= openIdx + 1)
1499 varsImplicit =
false;
1502 for (
int idx = openIdx + 1; idx < closeIdx && varsImplicit; idx++)
1504 varsImplicit =
false;
1507 Warning(
"HandleFunctionArguments",
1508 "Argument %d is not a parameter. Cannot assume variables are implicit.", argNr);
1515 for (
int dim = 0; dim < ndim; dim++) {
1516 argSubstitutions[
TString::Format(
"{V%d}", dim)] = defaultVariableNames[dim];
1520 for (
int argNr = 0; argNr < nArguments; argNr++) {
1524 TString(formula(argSeparators[argNr] + 1, argSeparators[argNr + 1] - argSeparators[argNr] - 1));
1528 argSubstitutions[oldName] = newName;
1531 if (
f && oldName == newName)
1538 if (!canReplace && nArguments == ndim) {
1542 for (
int argNr = 0; argNr < nArguments; argNr++) {
1545 TString(formula(argSeparators[argNr] + 1, argSeparators[argNr + 1] - argSeparators[argNr] - 1));
1549 argSubstitutions[oldName] = newName;
1552 argSubstitutions[defaultVariableNames[argNr]] = newName;
1557 for (
int parNr = 0; parNr < npar; parNr++)
1571 formula.
Replace(i, k - i, replacementFormula);
1572 i += replacementFormula.
Length() - 1;
1575 Warning(
"HandleFunctionArguments",
"Unable to make replacement. Number of parameters doesn't work : "
1576 "%d arguments, %d dimensions, %d parameters",
1577 nArguments, ndim, npar);
1600 Int_t temp = caretPos;
1603 if (formula[temp] ==
')') {
1606 while (depth != 0 && temp > 0) {
1607 if (formula[temp] ==
')')
1609 if (formula[temp] ==
'(')
1624 assert(temp + 1 >= 0);
1625 Int_t leftPos = temp + 1;
1626 left = formula(leftPos, caretPos - leftPos);
1632 if (temp >= formula.
Length()) {
1633 Error(
"HandleExponentiation",
"Invalid position of operator ^");
1636 if (formula[temp] ==
'(') {
1639 while (depth != 0 && temp < formula.
Length()) {
1640 if (formula[temp] ==
')')
1642 if (formula[temp] ==
'(')
1649 if (formula[temp] ==
'-' || formula[temp] ==
'+')
1655 while (temp < formula.
Length() && ((depth > 0) || !
IsOperator(formula[temp]))) {
1661 if (temp < formula.
Length() && formula[temp] ==
'(')
1663 if (temp < formula.
Length() && formula[temp] ==
')') {
1671 right = formula(caretPos + 1, (temp - 1) - caretPos);
1681 caretPos = formula.
Last(
'^');
1692 if (linPos ==
kNPOS )
return;
1694 assert(nofLinParts > 0);
1705 while (temp >= 0 && formula[temp] !=
'@') {
1708 left = formula(temp + 1, linPos - (temp + 1));
1711 while (temp < formula.
Length() && formula[temp] !=
'@') {
1714 TString right = formula(linPos + 1, temp - (linPos + 1));
1721 Nlinear += (
first) ? 2 : 1;
1731 linPos = formula.
Index(
"@");
1815 if (formula[i] ==
'[') {
1819 while (i < formula.
Length() && formula[i] !=
']') {
1820 param.
Append(formula[i++]);
1825 int paramIndex = -1;
1827 paramIndex = param.
Atoi();
1831 for (
int idx = 0; idx <= paramIndex; ++idx) {
1851 formula.
Replace(tmp, i - tmp, replacement, replacement.
Length());
1855 int deltai = replacement.
Length() - (i-tmp);
1861 if (formula[i] ==
'\"') {
1865 }
while (formula[i] !=
'\"');
1883 if (isalpha(formula[i]) &&
1891 if (formula[i] ==
':' && ((i + 1) < formula.
Length())) {
1892 if (formula[i + 1] ==
':') {
1901 name.Append(formula[i++]);
1904 if (formula[i] ==
'(') {
1906 if (formula[i] ==
')') {
1913 while (depth != 0 && i < formula.
Length()) {
1914 switch (formula[i]) {
1915 case '(': depth++;
break;
1916 case ')': depth--;
break;
1924 body.
Append(formula[i++]);
1929 formula.
Replace(i - originalBodyLen, originalBodyLen, body, body.
Length());
1930 i += body.
Length() - originalBodyLen;
1943 obj =
gROOT->GetListOfFunctions()->FindObject(
name);
1948 TF1 *
f1 =
dynamic_cast<TF1 *
>(obj);
1958 TString replacementFormula =
f->GetExpFormula();
1971 std::vector<TString> newNames;
1974 newNames.resize(
f->GetNpar());
1976 for (
int jpar =
f->GetNpar() - 1; jpar >= 0; --jpar) {
1984 replacementFormula.
ReplaceAll(oldName, newName);
1985 newNames[jpar] = newName;
1987 newNames[jpar] =
f->GetParName(jpar);
1995 for (
int jpar = 0; jpar <
f->GetNpar(); ++jpar) {
1996 if (nparOffset > 0) {
1998 assert((
int)newNames.size() ==
f->GetNpar());
2005 replacementFormula.
Insert(0,
'(');
2006 replacementFormula.
Insert(replacementFormula.
Length(),
')');
2009 i += replacementFormula.
Length() -
name.Length();
2053 for (list<TFormulaFunction>::iterator funcsIt =
fFuncs.begin(); funcsIt !=
fFuncs.end(); ++funcsIt) {
2070 while (index !=
kNPOS) {
2074 if ((index > 0) && (isalpha(formula[index - 1]) || formula[index - 1] ==
':')) {
2075 index = formula.
Index(shortcut, i2);
2078 if (i2 < formula.
Length() && formula[i2] !=
'(') {
2079 index = formula.
Index(shortcut, i2);
2085 index = formula.
Index(shortcut, inext);
2092#ifdef TFORMULA_CHECK_FUNCTIONS
2098 size_t index =
name.rfind(
"::");
2099 assert(index != std::string::npos);
2107 TIter next(methodList);
2109 while ((p = (
TMethod *)next())) {
2110 if (strcmp(p->
GetName(), functionName.
Data()) == 0 &&
2125 if (
f && fun.
GetNargs() <=
f->GetNargs() && fun.
GetNargs() >=
f->GetNargs() -
f->GetNargsOpt()) {
2133 Info(
"TFormula",
"Could not find %s function with %d argument(s)", fun.
GetName(), fun.
GetNargs());
2156 map<TString, TFormulaVariable>::iterator varsIt =
fVars.find(fun.
GetName());
2157 if (varsIt !=
fVars.end()) {
2160 Double_t value = (*varsIt).second.fValue;
2166 int varDim = (*varsIt).second.fArrayPos;
2167 if (varDim >=
fNdim) {
2172 if (
v.second.fArrayPos < varDim && !
v.second.fFound) {
2174 v.second.fFound =
true;
2195 int digit = sdigit.
Atoi();
2196 if (digit >=
fNdim) {
2199 for (
int j = 0; j <
fNdim; ++j) {
2203 fVars[vname].fFound =
true;
2218 if (paramsIt !=
fParams.end()) {
2235 map<TString, Double_t>::iterator constIt =
fConsts.find(fun.
GetName());
2236 if (constIt !=
fConsts.end()) {
2255 if (!hasParameters) {
2269 if (inputIntoCling) {
2272 std::string inputFormula(formula.
Data());
2276 std::string inputFormulaVecFlag = inputFormula;
2278 inputFormulaVecFlag +=
" (vectorized)";
2283 TString argumentsPrototype =
TString::Format(
"%s%s%s", ( (hasVariables || hasParameters) ? (argType +
" *x").Data() :
""),
2284 (hasParameters ?
"," :
""), (hasParameters ?
"Double_t *p" :
""));
2301 inputIntoCling =
false;
2311 argumentsPrototype.
Data(), inputFormula.c_str());
2330 if (inputIntoCling) {
2356 for (list<TFormulaFunction>::iterator it =
fFuncs.begin(); it !=
fFuncs.end(); ++it) {
2358 if (!it->fFound && !it->IsFuncCall()) {
2360 if (it->GetNargs() == 0)
2361 Error(
"ProcessFormula",
"\"%s\" has not been matched in the formula expression", it->GetName());
2363 Error(
"ProcessFormula",
"Could not find %s function with %d argument(s)", it->GetName(), it->GetNargs());
2374 auto itvar =
fVars.begin();
2377 if (!itvar->second.fFound) {
2379 itvar =
fVars.erase(itvar);
2382 }
while (itvar !=
fVars.end());
2393 make_pair(make_pair(
"gaus", 1), make_pair(
"[0]*exp(-0.5*(({V0}-[1])/[2])*(({V0}-[1])/[2]))",
2394 "[0]*exp(-0.5*(({V0}-[1])/[2])*(({V0}-[1])/[2]))/(sqrt(2*pi)*[2])")));
2395 functions.insert(make_pair(make_pair(
"landau", 1), make_pair(
"[0]*TMath::Landau({V0},[1],[2],false)",
2396 "[0]*TMath::Landau({V0},[1],[2],true)")));
2397 functions.insert(make_pair(make_pair(
"expo", 1), make_pair(
"exp([0]+[1]*{V0})",
"")));
2399 make_pair(make_pair(
"crystalball", 1), make_pair(
"[0]*ROOT::Math::crystalball_function({V0},[3],[4],[2],[1])",
2400 "[0]*ROOT::Math::crystalball_pdf({V0},[3],[4],[2],[1])")));
2402 make_pair(make_pair(
"breitwigner", 1), make_pair(
"[0]*ROOT::Math::breitwigner_pdf({V0},[2],[1])",
2403 "[0]*ROOT::Math::breitwigner_pdf({V0},[2],[4],[1])")));
2405 functions.insert(make_pair(make_pair(
"cheb0", 1), make_pair(
"ROOT::Math::Chebyshev0({V0},[0])",
"")));
2406 functions.insert(make_pair(make_pair(
"cheb1", 1), make_pair(
"ROOT::Math::Chebyshev1({V0},[0],[1])",
"")));
2407 functions.insert(make_pair(make_pair(
"cheb2", 1), make_pair(
"ROOT::Math::Chebyshev2({V0},[0],[1],[2])",
"")));
2408 functions.insert(make_pair(make_pair(
"cheb3", 1), make_pair(
"ROOT::Math::Chebyshev3({V0},[0],[1],[2],[3])",
"")));
2410 make_pair(make_pair(
"cheb4", 1), make_pair(
"ROOT::Math::Chebyshev4({V0},[0],[1],[2],[3],[4])",
"")));
2412 make_pair(make_pair(
"cheb5", 1), make_pair(
"ROOT::Math::Chebyshev5({V0},[0],[1],[2],[3],[4],[5])",
"")));
2414 make_pair(make_pair(
"cheb6", 1), make_pair(
"ROOT::Math::Chebyshev6({V0},[0],[1],[2],[3],[4],[5],[6])",
"")));
2416 make_pair(make_pair(
"cheb7", 1), make_pair(
"ROOT::Math::Chebyshev7({V0},[0],[1],[2],[3],[4],[5],[6],[7])",
"")));
2417 functions.insert(make_pair(make_pair(
"cheb8", 1),
2418 make_pair(
"ROOT::Math::Chebyshev8({V0},[0],[1],[2],[3],[4],[5],[6],[7],[8])",
"")));
2419 functions.insert(make_pair(make_pair(
"cheb9", 1),
2420 make_pair(
"ROOT::Math::Chebyshev9({V0},[0],[1],[2],[3],[4],[5],[6],[7],[8],[9])",
"")));
2422 make_pair(make_pair(
"cheb10", 1),
2423 make_pair(
"ROOT::Math::Chebyshev10({V0},[0],[1],[2],[3],[4],[5],[6],[7],[8],[9],[10])",
"")));
2426 make_pair(make_pair(
"gaus", 2), make_pair(
"[0]*exp(-0.5*(({V0}-[1])/[2])^2 - 0.5*(({V1}-[3])/[4])^2)",
"")));
2428 make_pair(make_pair(
"landau", 2),
2429 make_pair(
"[0]*TMath::Landau({V0},[1],[2],false)*TMath::Landau({V1},[3],[4],false)",
"")));
2430 functions.insert(make_pair(make_pair(
"expo", 2), make_pair(
"exp([0]+[1]*{V0})",
"exp([0]+[1]*{V0}+[2]*{V1})")));
2433 make_pair(make_pair(
"gaus", 3), make_pair(
"[0]*exp(-0.5*(({V0}-[1])/[2])^2 - 0.5*(({V1}-[3])/[4])^2 - 0.5*(({V2}-[5])/[6])^2)",
"")));
2436 make_pair(make_pair(
"bigaus", 2), make_pair(
"[0]*ROOT::Math::bigaussian_pdf({V0},{V1},[2],[4],[5],[1],[3])",
2437 "[0]*ROOT::Math::bigaussian_pdf({V0},{V1},[2],[4],[5],[1],[3])")));
2529 if (i < 0 || i >=
n ) {
2530 Error(
"GetLinearPart",
"Formula %s has only %d linear parts - requested %d",
GetName(),
n,i);
2576 Bool_t anyNewVar =
false;
2577 for (
Int_t i = 0; i < size; ++i) {
2579 const TString &vname = vars[i];
2589 Int_t multiplier = 2;
2590 if (
fFuncs.size() > 100) {
2615 Error(
"SetName",
"The name \'%s\' is reserved as a TFormula variable name.\n"
2616 "\tThis function will not be renamed.",
2621 auto listOfFunctions =
gROOT->GetListOfFunctions();
2622 TObject* thisAsFunctionInList =
nullptr;
2624 if (listOfFunctions){
2625 thisAsFunctionInList = listOfFunctions->
FindObject(
this);
2626 if (thisAsFunctionInList) listOfFunctions->Remove(thisAsFunctionInList);
2629 if (thisAsFunctionInList) listOfFunctions->Add(thisAsFunctionInList);
2643 for(
Int_t i = 0; i < size; ++i)
2647 fVars[
v.first].fValue =
v.second;
2650 Error(
"SetVariables",
"Variable %s is not defined.",
v.first.Data());
2661 if (
fVars.end() == nameIt) {
2662 Error(
"GetVariable",
"Variable %s is not defined.",
name);
2665 return nameIt->second.fValue;
2674 if (
fVars.end() == nameIt) {
2675 Error(
"GetVarNumber",
"Variable %s is not defined.",
name);
2678 return nameIt->second.fArrayPos;
2686 if (ivar < 0 || ivar >=
fNdim)
return "";
2689 for (
auto &
v :
fVars) {
2690 if (
v.second.fArrayPos == ivar)
return v.first;
2692 Error(
"GetVarName",
"Variable with index %d not found !!",ivar);
2703 Error(
"SetVariable",
"Variable %s is not defined.",
name.Data());
2742 auto ret =
fParams.insert(std::make_pair(
name, pos));
2748 if (ret.first ==
fParams.begin())
2751 auto previous = (ret.first);
2753 pos = previous->second + 1;
2761 Warning(
"inserting parameter %s at pos %d when vector size is %d \n",
name.Data(), pos,
2771 for (
auto it = ret.first; it !=
fParams.end(); ++it) {
2781 if (processFormula) {
2809 Error(
"GetParameter",
"Parameter %s is not defined.",
name);
2824 Error(
"GetParameter",
"wrong index used - use GetParameter(name)");
2833 if (ipar < 0 || ipar >=
fNpar)
return "";
2837 if (p.second == ipar)
return p.first.Data();
2839 Error(
"GetParName",
"Parameter with index %d not found !!",ipar);
2872 Error(
"SetParameter",
"Parameter %s is not defined.",
name.Data());
2879 for (map<TString, TFormulaVariable>::iterator it =
fParams.begin(); it !=
fParams.end(); ++it) {
2880 if (!it->second.fFound) {
2899 for(
Int_t i = 0 ; i < size ; ++i)
2901 pair<TString, Double_t> p = params[i];
2903 Error(
"SetParameters",
"Parameter %s is not defined", p.first.Data());
2906 fParams[p.first].fValue = p.second;
2907 fParams[p.first].fFound =
true;
2911 for (map<TString, TFormulaVariable>::iterator it =
fParams.begin(); it !=
fParams.end(); ++it) {
2912 if (!it->second.fFound) {
2923 if(!params || size < 0 || size >
fNpar)
return;
2926 Warning(
"SetParameters",
"size is not same of cling parameter size %d - %d",size,
int(
fClingParameters.size()) );
2927 for (
Int_t i = 0; i < size; ++i) {
2975 if (param < 0 || param >=
fNpar)
return;
2984 const char *name4,
const char *name5,
const char *name6,
const char *name7,
2985 const char *name8,
const char *name9,
const char *name10)
3015 if (ipar < 0 || ipar >
fNpar) {
3016 Error(
"SetParName",
"Wrong Parameter index %d ",ipar);
3022 if (it.second == ipar) {
3030 Error(
"SetParName",
"Parameter %d is not existing.",ipar);
3043 if (!formula.
IsNull() ) {
3045 for(list<TFormulaFunction>::iterator it =
fFuncs.begin(); it !=
fFuncs.end(); ++it)
3047 if (oldName == it->GetName()) {
3054 Error(
"SetParName",
"Parameter %s is not defined.", oldName.
Data());
3070#ifdef R__HAS_VECCORE
3072 Info(
"SetVectorized",
"Cannot vectorized a function of zero dimension");
3077 Error(
"SetVectorized",
"Cannot set vectorized to %d -- Formula is missing", vectorized);
3097 Warning(
"SetVectorized",
"Cannot set vectorized -- try building with option -Dbuiltin_veccore=On");
3107#ifdef R__HAS_VECCORE
3111 return vecCore::Get( ret, 0 );
3118 Info(
"EvalPar",
"Function is vectorized - converting Double_t into ROOT::Double_v and back");
3121 const int maxDim = 4;
3122 std::array<ROOT::Double_v, maxDim> xvec;
3123 for (
int i = 0; i <
fNdim; i++)
3127 return vecCore::Get(ans, 0);
3130 std::vector<ROOT::Double_v> xvec(
fNdim);
3131 for (
int i = 0; i <
fNdim; i++)
3135 return vecCore::Get(ans, 0);
3140 Error(
"EvalPar",
"Formula is vectorized (even though VECCORE is disabled!)");
3162 gInterpreter->Declare(
"#include <Math/CladDerivator.h>\n#pragma clad OFF");
3173 "#pragma clad ON\n" +
3174 "void " + GradReqFuncName +
"() {\n" +
3175 "clad::gradient(" + std::string(
fClingName.
Data()) +
");\n }\n" +
3186 GradFuncName.c_str(),
3200 Error(
"GradientPar",
"Could not initialize the formula!");
3205 Error(
"GradientPar",
"Could not generate a gradient for the formula %s!",
3210 if ((
int)result.size() <
fNpar) {
3212 "The size of gradient result is %zu but %d is required. Resizing.",
3213 result.size(),
fNpar);
3214 result.resize(
fNpar);
3236 (*fGradFuncPtr)(0, 2, args,
nullptr);
3248 (*fGradFuncPtr)(0, 3, args,
nullptr);
3253#ifdef R__HAS_VECCORE
3263 return DoEvalVec(
x, params);
3266 return DoEval(
nullptr, params);
3271 Info(
"EvalPar",
"Function is not vectorized - converting ROOT::Double_v into Double_t and back");
3273 const int vecSize = vecCore::VectorSize<ROOT::Double_v>();
3274 std::vector<Double_t> xscalars(vecSize*
fNdim);
3276 for (
int i = 0; i < vecSize; i++)
3277 for (
int j = 0; j <
fNdim; j++)
3278 xscalars[i*
fNdim+j] = vecCore::Get(
x[j],i);
3281 for (
int i = 0; i < vecSize; i++)
3282 vecCore::Set(answers, i,
DoEval(&xscalars[i*
fNdim], params));
3293 double xxx[4] = {
x,
y,z,t};
3302 double xxx[3] = {
x,
y,z};
3311 double xxx[2] = {
x,
y};
3334 Error(
"Eval",
"Formula is invalid and not ready to execute ");
3335 for (
auto it =
fFuncs.begin(); it !=
fFuncs.end(); ++it) {
3338 printf(
"%s is unknown.\n", fun.
GetName());
3348 auto thisFormula =
const_cast<TFormula*
>(
this);
3352 Error(
"DoEval",
"Formula has error and it is not properly initialized ");
3360 double *
v =
const_cast<double*
>(
x);
3361 double * p = (params) ?
const_cast<double*
>(params) :
const_cast<double*
>(
fClingParameters.data());
3368 double * vars = (
x) ?
const_cast<double*
>(
x) :
const_cast<double*
>(
fClingVariables.data());
3371 (*fFuncPtr)(0, 1, args, &result);
3373 double *pars = (params) ?
const_cast<double *
>(params) :
const_cast<double *
>(
fClingParameters.data());
3375 (*fFuncPtr)(0, 2, args, &result);
3382#ifdef R__HAS_VECCORE
3386 Error(
"Eval",
"Formula is invalid and not ready to execute ");
3387 for (
auto it =
fFuncs.begin(); it !=
fFuncs.end(); ++it) {
3390 printf(
"%s is unknown.\n", fun.
GetName());
3400 auto thisFormula =
const_cast<TFormula*
>(
this);
3410 (*fFuncPtr)(0, 1, args, &result);
3412 double *pars = (params) ?
const_cast<double *
>(params) :
const_cast<double *
>(
fClingParameters.data());
3414 (*fFuncPtr)(0, 2, args, &result);
3431 Info(
"ReInitializeEvalMethod",
"compile now lambda expression function using Cling");
3440 if (!
fLazyInitialization)
Warning(
"ReInitializeEvalMethod",
"Formula is NOT properly initialized - try calling again TFormula::PrepareEvalMethod");
3499 std::size_t found = clingFunc.find(
"return");
3500 std::size_t found2 = clingFunc.rfind(
";");
3501 if (found == std::string::npos || found2 == std::string::npos) {
3502 Error(
"GetExpFormula",
"Invalid Cling expression - return default formula expression");
3507 if (!opt.
Contains(
"P"))
return clingFormula;
3510 while (i < clingFormula.
Length()-2 ) {
3512 if (clingFormula[i] ==
'p' && clingFormula[i+1] ==
'[' && isdigit(clingFormula[i+2]) ) {
3514 while ( isdigit(clingFormula[j]) ) { j++;}
3515 if (clingFormula[j] !=
']') {
3516 Error(
"GetExpFormula",
"Parameters not found - invalid expression - return default cling formula");
3517 return clingFormula;
3519 TString parNumbName = clingFormula(i+2,j-i-2);
3520 int parNumber = parNumbName.
Atoi();
3521 assert(parNumber <
fNpar);
3523 clingFormula.
Replace(i,j-i+1, replacement );
3524 i += replacement.
Length();
3528 return clingFormula;
3534 while (i < expFormula.
Length()-2 ) {
3536 if (expFormula[i] ==
'[') {
3538 while ( expFormula[j] !=
']' ) { j++;}
3539 if (expFormula[j] !=
']') {
3540 Error(
"GetExpFormula",
"Parameter names not found - invalid expression - return default formula");
3543 TString parName = expFormula(i+1,j-i-1);
3545 expFormula.
Replace(i,j-i+1, replacement );
3546 i += replacement.
Length();
3552 Warning(
"GetExpFormula",
"Invalid option - return default formula expression");
3557 std::unique_ptr<TInterpreterValue>
v =
gInterpreter->MakeInterpreterValue();
3559 return v->ToString();
3568 printf(
" Formula expression: \n");
3577 printf(
"List of Variables: \n");
3579 for (
int ivar = 0; ivar <
fNdim ; ++ivar) {
3584 printf(
"List of Parameters: \n");
3589 for (
int ipar = 0; ipar <
fNpar ; ++ipar) {
3593 printf(
"Expression passed to Cling:\n");
3596 printf(
"Generated Gradient:\n");
3603 Warning(
"Print",
"Formula is not ready to execute. Missing parameters/variables");
3604 for (list<TFormulaFunction>::const_iterator it =
fFuncs.begin(); it !=
fFuncs.end(); ++it) {
3607 printf(
"%s is unknown.\n", fun.
GetName());
3630 if (
b.IsReading() ) {
3634 if (v <= 8 && v > 3 &&
v != 6) {
3647 Error(
"Streamer",
"Old formula read from file is NOT valid");
3700 if (
fNpar != (
int) parValues.size() ) {
3701 Error(
"Streamer",
"number of parameters computed (%d) is not same as the stored parameters (%d)",
fNpar,
int(parValues.size()) );
3704 if (
v > 11 &&
fNdim != ndim) {
3705 Error(
"Streamer",
"number of dimension computed (%d) is not same as the stored value (%d)",
fNdim, ndim );
3720 assert(
fNpar == (
int) parValues.size() );
3723 if (
fParams.size() != paramMap.size() ) {
3724 Warning(
"Streamer",
"number of parameters list found (%zu) is not same as the stored one (%zu) - use re-created list",
fParams.size(),paramMap.size()) ;
3740 gROOT->GetListOfFunctions()->Add(
this);
3743 Error(
"Streamer",
"Formula read from file is NOT ready to execute");
3751 Error(
"Streamer",
"Reading version %d is not supported",
v);
void Error(const char *location, const char *msgfmt,...)
void GetParameters(TFitEditor::FuncParams_t &pars, TF1 *func)
Stores the parameters of the given function into pars.
R__EXTERN TInterpreter * gCling
R__EXTERN TVirtualMutex * gROOTMutex
typedef void((*Func_t)())
#define R__LOCKGUARD(mutex)
Buffer base class used for serializing objects.
TClass instances represent classes, structs and namespaces in the ROOT type system.
const TList * GetListOfAllPublicMethods(Bool_t load=kTRUE)
Returns a list of all public methods of this class and its base classes.
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.
virtual TFormula * GetFormula()
Global functions class (global functions are obtained from CINT).
Int_t GetNargsOpt() const
Number of function optional (default) arguments.
Int_t GetNargs() const
Number of function arguments.
virtual Bool_t Declare(const char *code)=0
virtual Bool_t CallFunc_IsValid(CallFunc_t *) const
virtual Long_t ProcessLine(const char *line, EErrorCode *error=0)=0
virtual CallFuncIFacePtr_t CallFunc_IFacePtr(CallFunc_t *) const
Method or function calling interface.
CallFunc_t * GetCallFunc() const
Each ROOT class (see TClass) has a linked list of methods.
The TNamed class is the base class for all named ROOT classes.
virtual void Copy(TObject &named) const
Copy this to obj.
virtual void SetName(const char *name)
Set the name of the TNamed.
virtual const char * GetTitle() const
Returns title of object.
virtual const char * GetName() const
Returns name of object.
Mother of all ROOT objects.
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
virtual void Delete(Option_t *option="")
Delete this object.
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Regular expression class.
Ssiz_t Index(const TString &str, Ssiz_t *len, Ssiz_t start=0) const
Find the first occurrence of the regexp in string and return the position, or -1 if there is no match...
TString & Insert(Ssiz_t pos, const char *s)
Int_t Atoi() const
Return integer value of string.
TString & Replace(Ssiz_t pos, Ssiz_t n, const char *s)
const char * Data() const
Bool_t IsDigit() const
Returns true if all characters in string are digits (0-9) or white spaces, i.e.
TString & ReplaceAll(const TString &s1, const TString &s2)
Ssiz_t Last(char c) const
Find last occurrence of a character c.
void ToUpper()
Change string to upper case.
Int_t CountChar(Int_t c) const
Return number of times character c occurs in the string.
TString & Append(const char *cs)
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
std::string GetName(const std::string &scope_name)
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
static constexpr double degree
void variables(TString dataset, TString fin="TMVA.root", TString dirName="InputVariables_Id", TString title="TMVA Input Variables", Bool_t isRegression=kFALSE, Bool_t useTMVAStyle=kTRUE)
constexpr Double_t G()
Gravitational constant in: .
constexpr Double_t C()
Velocity of light in .
Short_t Max(Short_t a, Short_t b)
Double_t QuietNaN()
Returns a quiet NaN as defined by IEEE 754
Double_t Floor(Double_t x)
constexpr Double_t K()
Boltzmann's constant in .
constexpr Double_t Sqrt2()
constexpr Double_t E()
Base of natural log:
constexpr Double_t Sigma()
Stefan-Boltzmann constant in .
constexpr Double_t H()
Planck's constant in .
constexpr Double_t LogE()
Base-10 log of e (to convert ln to log)
constexpr Double_t Ln10()
Natural log of 10 (to convert log to ln)
constexpr Double_t EulerGamma()
Euler-Mascheroni Constant.
constexpr Double_t R()
Universal gas constant ( ) in
Double_t Log10(Double_t x)
Double_t Infinity()
Returns an infinity as defined by the IEEE standard.
void(* Generic_t)(void *, int, void **, void *)