79#include <initializer_list>
93bool isReservedExpressionIdentifier(
const std::string &arg)
95 return arg ==
"PI" || arg ==
"EULER" || arg ==
"TMath";
98bool isIdentifierChar(
char c)
100 return std::isalnum(
static_cast<unsigned char>(
c)) ||
c ==
'_';
116std::set<std::string> extractArguments(std::string expr)
119 expr.erase(std::remove_if(expr.begin(), expr.end(), [](
unsigned char c) { return std::isspace(c); }), expr.end());
121 std::set<std::string> arguments;
122 for (std::size_t i = 0; i < expr.size(); ++i) {
127 const std::size_t start = i;
128 while (i < expr.size() && isIdentifierChar(expr[i])) {
131 const std::string arg = expr.substr(start, i - start);
132 const bool isFunctionCall = i < expr.size() && expr[i] ==
'(';
133 if (!isFunctionCall && !isReservedExpressionIdentifier(arg)) {
134 arguments.insert(arg);
140void replaceIdentifier(
TString &expr, std::string_view identifier, std::string_view replacement)
142 std::string in(expr.
Data());
144 out.reserve(in.size());
146 for (std::size_t pos = 0; pos < in.size();) {
147 const bool matches = in.compare(pos, identifier.size(), identifier) == 0;
148 const bool beforeIdentifier = pos > 0 && isIdentifierChar(in[pos - 1]);
149 const std::size_t end = pos + identifier.size();
150 const bool afterIdentifier = end < in.size() && isIdentifierChar(in[end]);
151 if (matches && !beforeIdentifier && !afterIdentifier) {
152 out.append(replacement);
155 out.push_back(in[pos]);
163std::string trimmed(std::string
const &str)
165 const auto begin = str.find_first_not_of(
" \t\n");
166 if (begin == std::string::npos) {
169 return str.substr(begin, str.find_last_not_of(
" \t\n") - begin + 1);
173std::size_t findClosingBracket(std::string
const &str, std::size_t open)
176 for (std::size_t i = open; i < str.size(); ++i) {
177 if (str[i] ==
'(' || str[i] ==
'[') {
179 }
else if ((str[i] ==
')' || str[i] ==
']') && --depth == 0) {
183 return std::string::npos;
188std::size_t findTopLevel(std::string
const &str, std::string_view chars, std::size_t start = 0)
191 for (std::size_t i = start; i < str.size(); ++i) {
192 if (str[i] ==
'(' || str[i] ==
'[') {
194 }
else if (str[i] ==
')' || str[i] ==
']') {
196 }
else if (str[i] ==
':' && i + 1 < str.size() && str[i + 1] ==
':') {
198 }
else if (depth == 0 && chars.find(str[i]) != std::string_view::npos) {
202 return std::string::npos;
206std::vector<std::string> splitTopLevelCommas(std::string
const &str)
208 std::vector<std::string> parts;
209 std::size_t start = 0;
210 for (std::size_t comma = findTopLevel(str,
","); comma != std::string::npos; comma = findTopLevel(str,
",", start)) {
211 parts.push_back(str.substr(start, comma - start));
214 parts.push_back(str.substr(start));
219std::string stripEnclosingParentheses(std::string str)
222 while (str.size() >= 2 && str.front() ==
'(' && findClosingBracket(str, 0) == str.size() - 1) {
223 str = trimmed(str.substr(1, str.size() - 2));
230std::string ifElseToTernary(std::string
const &expr)
232 static const std::string keyword =
"ifelse";
235 while (pos < expr.size()) {
236 const std::size_t found = expr.find(keyword, pos);
237 if (found == std::string::npos) {
240 const std::size_t
open = expr.find_first_not_of(
" \t", found + keyword.size());
242 (found == 0 || !isIdentifierChar(expr[found - 1])) && open != std::string::npos && expr[open] ==
'(';
243 const std::size_t
close = isCall ? findClosingBracket(expr, open) : std::string::npos;
244 const auto args =
close != std::string::npos ? splitTopLevelCommas(expr.substr(open + 1, close - open - 1))
245 : std::vector<std::string>{};
246 if (args.size() != 3) {
247 out += expr.substr(pos, found + keyword.size() - pos);
248 pos = found + keyword.size();
251 out += expr.substr(pos, found - pos);
252 out +=
"((" + ifElseToTernary(trimmed(args[0])) +
")?(" + ifElseToTernary(trimmed(args[1])) +
"):(" +
253 ifElseToTernary(trimmed(args[2])) +
"))";
256 return out + expr.substr(pos);
259void translateImportedExpression(
TString &expr)
261 replaceIdentifier(expr,
"PI",
"TMath::Pi()");
262 replaceIdentifier(expr,
"EULER",
"TMath::E()");
264 replaceIdentifier(expr,
"TRUE",
"1");
265 replaceIdentifier(expr,
"FALSE",
"0");
268 expr = ifElseToTernary(expr.
Data()).c_str();
272template <
class RooArg_t>
273void importFormulaBinnings(RooArg_t &arg,
const JSONNode &node)
278 const std::string context =
"generic formula '" + std::string(arg.GetName()) +
"'";
281 HS3::report(diagnostics, std::string(arg.GetName()) +
".axes");
283 std::set<std::string> axisNames;
285 if (!axisNames.insert(axis.name).second) {
288 if (!
dynamic_cast<RooAbsRealLValue *
>(arg.getParameter(axis.name.c_str()))) {
291 auto const *regular = std::get_if<HS3::RegularBinning>(&axis.binning);
292 if (regular && (regular->nbins < 1 || !(axis.min < axis.max))) {
294 " needs a positive \"nbins\" and \"min\" smaller than \"max\"");
300 arg.setBinning(*var, var->getBinning(),
false);
304template <
class RooArg_t>
308 if (!
p.has_child(
"expression")) {
311 TString formula(
p[
"expression"].val());
312 translateImportedExpression(formula);
314 for (
const auto &
d : extractArguments(formula.Data())) {
319 "', which is not allowed in HS3");
321 dependents.
add(*dependent);
323 RooArg_t arg{
name.c_str(), formula, dependents};
324 importFormulaBinnings(arg,
p);
341constexpr const char *lognormalLogSuffix =
"_lognormal_log";
361 const std::string
value = source.
val();
382 static const std::set<std::string> supportedComponentTypes{
"poisson_dist",
"poisson_continuous_dist",
383 "gaussian_dist",
"normal_dist",
"lognormal_dist"};
384 if (!
p.has_child(
"component_type")) {
385 error(
"missing \"component_type\"");
387 const std::string componentType =
p[
"component_type"].val();
388 if (supportedComponentTypes.find(componentType) == supportedComponentTypes.end()) {
389 error(
"the component_type '" + componentType +
390 "' is not supported, supported are poisson_dist, poisson_continuous_dist, gaussian_dist and "
394 const JSONNode *defaults =
p.find(
"default_parameters");
396 if (!defaults->
is_map()) {
397 error(
"\"default_parameters\" must be a struct");
400 error(
"\"x\" must be given per component, not in \"default_parameters\"");
403 const JSONNode *components =
p.find(
"components");
405 error(
"\"components\" must be a non-empty list");
414 std::vector<std::string> observables;
416 for (
JSONNode const &component : components->children()) {
417 const std::string context =
"component " + std::to_string(observables.size());
418 if (!component.is_map()) {
419 error(context +
" must be a struct");
423 error(context +
" has no \"x\"");
426 error(context +
": \"x\" must be the name of the observable");
428 const std::string
x = xNode->
val();
429 if (std::find(observables.begin(), observables.end(),
x) != observables.end()) {
430 error(
"the observable '" +
x +
"' is used by two components");
432 observables.push_back(
x);
434 const std::string pdfName =
x +
"_constraint";
436 if (ws.
arg(pdfName)) {
442 error(
"cannot create the component for '" +
x +
"' as '" + pdfName +
443 "', the workspace already has an object of that name");
445 if (*existing != form) {
446 error(context +
" over '" +
x +
447 "' is not identical to the component over the same observable of another array distribution");
449 pdfs.
add(*ws.
pdf(pdfName));
453 node[
"name"] << pdfName;
454 node[
"type"] << componentType;
456 for (
JSONNode const &field : defaults->children()) {
457 copyValue(node[field.key()], field);
460 for (
JSONNode const &field : component.children()) {
461 copyValue(node[field.key()], field);
466 error(context +
" did not produce a distribution");
474 for (std::size_t i = 0; i < observables.size(); ++i) {
477 error(
"the observable '" + observables[i] +
"' is not a parameter or function");
479 for (std::size_t k = 0; k < observables.size(); ++k) {
480 if (k != i && pdfs[i].dependsOn(*ws.
arg(observables[k]))) {
481 error(
"component " + std::to_string(i) +
" depends on the observable '" + observables[k] +
482 "' of component " + std::to_string(k));
485 for (
RooAbsArg const *server : pdfs[i].servers()) {
486 if (server !=
x && server->dependsOn(*
x)) {
487 error(
"the parameters of component " + std::to_string(i) +
" depend on its own observable '" +
488 observables[i] +
"'");
515 const std::size_t nSummands =
p.has_child(
"summands") ?
p[
"summands"].num_children() : 0;
516 const std::size_t nCoefficients =
p.has_child(
"coefficients") ?
p[
"coefficients"].num_children() : 0;
518 if (
p.has_child(
"extended")) {
521 const bool extended =
p[
"extended"].val_bool();
522 const std::string counts =
523 std::to_string(nCoefficients) +
" coefficients for " + std::to_string(nSummands) +
" summands";
524 if (extended && nCoefficients > 0 && nCoefficients + 1 == nSummands) {
526 ", which defines a non-extended mixture");
528 if (!extended && nCoefficients == 0 && nSummands > 0) {
530 ", which defines an extended mixture of extended distributions");
532 if (!extended && nCoefficients == nSummands && nSummands > 0) {
538 for (std::size_t i = 0; i < nCoefficients; ++i) {
539 sum += (i == 0 ?
"x[" :
"+x[") + std::to_string(i) +
"]";
542 for (std::size_t i = 0; i + 1 < nCoefficients; ++i) {
544 (
"x[" + std::to_string(i) +
"]/(" +
sum +
")").c_str(),
550 }
else if (nCoefficients == nSummands && nSummands > 0 && sinceHS3v03) {
553 "' has one coefficient per summand, but no \"extended\" flag, which HS3 "
554 "requires to decide whether the mixture is extended");
556 if (nSummands > 0 && nCoefficients == 0 && sinceHS3v03) {
558 "' has no coefficients, which HS3 0.3 doesn't define. It is read as the sum of "
559 "its extended summands.");
576template <
bool Div
ideByBinW
idth>
596 obs->GetName() +
"' as indicated by parent RooBinSamplingPdf '" +
name +
600 if (!
p.has_child(
"epsilon")) {
603 double epsilon(
p[
"epsilon"].val_double());
613 const bool extended =
p.has_child(
"extended") &&
p[
"extended"].val_bool();
617template <
class RooArg_t>
621 if (!
p.has_child(
"coefficients")) {
628 for (
const auto &coef :
p[
"coefficients"].children()) {
632 if (order == 0 && (coef.val() ==
"1.0" || coef.val() ==
"1")) {
634 }
else if (coefs.empty() && (coef.val() ==
"0.0" || coef.val() ==
"0")) {
649template <
bool Continuous>
653 bool noRounding = Continuous;
654 if (
p.has_child(
"integer")) {
655 std::string
const type = Continuous ?
"poisson_continuous_dist" :
"poisson_dist";
659 "' has the key \"integer\", which is not part of HS3. The discrete Poisson distribution is "
660 "\"poisson_dist\" and the continuous one is \"poisson_continuous_dist\".");
662 noRounding = !
p[
"integer"].val_bool();
690 if (
p.has_child(
"normalization")) {
692 normSetPtr = &normSet;
694 JSONNode const *domain =
p.find(
"domain");
697 domain ? domain->
val().c_str() :
nullptr);
705 Int_t order =
p[
"order"].val_int();
706 double eps =
p[
"eps"].val_double();
708 if (
p.has_child(
"normalization")) {
718 Int_t order =
p[
"ipOrder"].val_int();
721 if (
p.has_child(
"conv_func")) {
744 const bool legacyKey = !
p.has_child(
"mu") &&
p.has_child(
"mean");
747 "' uses the key \"mean\", which HS3 0.3 renamed to \"mu\".");
762 const std::string mu =
p[
"mu"].val();
763 const std::string
sigma =
p[
"sigma"].val();
764 const bool isStandard = !
endsWith(mu, lognormalLogSuffix);
808 const std::string constParamName =
p[
"c"].val();
809 const bool isInverted =
endsWith(constParamName,
"_exponential_inverted");
819 const bool hasCov =
p.has_child(
"covariances");
820 const bool hasCorr =
p.has_child(
"correlations") &&
p.has_child(
"standard_deviations");
821 if (!hasCov && !hasCorr) {
825 const std::string key = hasCov ?
"covariances" :
"correlations";
826 std::vector<double> sigmas;
828 sigmas.assign(
p[key].num_children(), 1.0);
830 sigmas <<
p[
"standard_deviations"];
832 const std::size_t
n = sigmas.size();
834 if (
p[key].num_children() !=
n) {
840 for (
const auto &row :
p[key].children()) {
841 if (!row.is_seq() || row.num_children() !=
n) {
845 for (
const auto &val : row.children()) {
846 covmat(i, j) = val.val_double() * sigmas[i] * sigmas[j];
870 if (!
p.has_child(
"parameters")) {
875 const bool hasAxes =
p.has_child(
"axes");
878 "No axes given in '" +
name +
879 "'. Using default binning (uniform; nbins=100). If needed, export the Workspace to JSON with a newer "
880 "Root version that supports custom ParamHistFunc binnings(>=6.38.00).\n");
882 RooArgList binning = hasAxes ? readBinning(
p, varList) : varList;
894 if (!
p.has_child(
"x0") || !
p.has_child(
"y0")) {
899 const std::string algo =
p.has_child(
"interpolation") ?
p[
"interpolation"].val() :
"poly3";
900 if (algo !=
"poly3" && algo !=
"poly5") {
902 "': allowed are 'poly3' and 'poly5'");
904 const bool logx =
p.has_child(
"logx") &&
p[
"logx"].val_bool();
905 const bool logy =
p.has_child(
"logy") &&
p[
"logy"].val_bool();
907 std::vector<double> x0;
908 std::vector<double> y0;
912 if (x0.size() != y0.size()) {
914 ", y0 has " + std::to_string(y0.size()));
946 if (
p.has_child(
"x") && !
p[
"x"].is_seq()) {
956const std::initializer_list<const char *> tailKeys = {
"alpha_L",
"n_L",
"alpha_R",
"n_R"};
958bool hasAny(
const JSONNode &
p, std::initializer_list<const char *> keys)
960 return std::any_of(keys.begin(), keys.end(), [&
p](
const char *key) { return p.has_child(key); });
963bool hasDoubleSidedKeys(
const JSONNode &
p)
965 return hasAny(
p, tailKeys) || hasAny(
p, {
"sigma_L",
"sigma_R"});
973 const std::string context =
type +
" '" +
name +
"'";
975 const bool asymmetricTails = hasAny(
p, tailKeys);
976 const bool symmetricTails = hasAny(
p, {
"alpha",
"n"});
977 if (symmetricTails && !symmetricShorthand) {
979 "\"n_L\", \"alpha_R\" and \"n_R\"");
981 if (symmetricTails && asymmetricTails) {
983 " must not combine \"alpha\"/\"n\" with \"alpha_L\"/\"n_L\"/\"alpha_R\"/\"n_R\"");
985 if (asymmetricTails || !symmetricTails) {
986 for (
const char *key : tailKeys) {
987 if (!
p.has_child(key)) {
989 "\": \"alpha_L\", \"n_L\", \"alpha_R\" and \"n_R\" are all required");
992 }
else if (!
p.has_child(
"alpha") || !
p.has_child(
"n")) {
996 const bool asymmetricWidths = hasAny(
p, {
"sigma_L",
"sigma_R"});
997 if (asymmetricWidths &&
p.has_child(
"sigma")) {
1000 if (asymmetricWidths && !(
p.has_child(
"sigma_L") &&
p.has_child(
"sigma_R"))) {
1003 if (!asymmetricWidths && !
p.has_child(
"sigma")) {
1025 if (!CrystalBall::hasDoubleSidedKeys(
p)) {
1028 static bool warned =
false;
1031 "\"alpha_R\", \"n_R\", \"sigma_L\" or \"sigma_R\" is deprecated, please use "
1032 "\"crystalball_doublesided_dist\" for the double-sided Crystal Ball.");
1035 CrystalBall::importDoubleSided(tool,
p,
"crystalball_dist",
true);
1041 CrystalBall::importDoubleSided(tool,
p,
"crystalball_doublesided_dist",
false);
1056 elem[
"type"] <<
"crystalball_dist";
1074template <
class RooArg_t>
1079 elem[
"extended"] << (pdf.extendMode() != RooArg_t::CanNotBeExtended);
1081 if (pdf.coefList().empty() && std::is_same_v<RooArg_t, RooAddPdf>) {
1083 "' has no coefficients. It is written as a mixture_dist without coefficients, "
1084 "which HS3 0.3 doesn't define, so other implementations might not read it.");
1095template <
class RooArg_t>
1105template <
class RooArg_t>
1109 if (!
p.has_child(
"data")) {
1112 std::unique_ptr<RooDataHist> dataHist =
1114 tool->
wsEmplace<RooArg_t>(
name, *dataHist->get(), *dataHist);
1122 elem[
"epsilon"] << pdf.
epsilon();
1129 elem[
"type"] <<
"inverse_binvolume";
1134void cleanExpression(
TString &expr)
1140 replaceIdentifier(expr,
"TMath::Exp",
"exp");
1141 replaceIdentifier(expr,
"TMath::Min",
"min");
1142 replaceIdentifier(expr,
"TMath::Max",
"max");
1143 replaceIdentifier(expr,
"TMath::Log",
"log");
1144 replaceIdentifier(expr,
"TMath::Log10",
"log10");
1145 replaceIdentifier(expr,
"TMath::Cos",
"cos");
1146 replaceIdentifier(expr,
"TMath::CosH",
"cosh");
1147 replaceIdentifier(expr,
"TMath::Sin",
"sin");
1148 replaceIdentifier(expr,
"TMath::SinH",
"sinh");
1149 replaceIdentifier(expr,
"TMath::Sqrt",
"sqrt");
1150 replaceIdentifier(expr,
"TMath::Power",
"pow");
1151 replaceIdentifier(expr,
"TMath::Erf",
"erf");
1152 replaceIdentifier(expr,
"TMath::Erfc",
"erfc");
1153 replaceIdentifier(expr,
"TMath::Floor",
"floor");
1154 replaceIdentifier(expr,
"TMath::Ceil",
"ceil");
1155 replaceIdentifier(expr,
"TMath::Abs",
"abs");
1156 replaceIdentifier(expr,
"TMath::Tan",
"tan");
1157 replaceIdentifier(expr,
"TMath::TanH",
"tanh");
1158 replaceIdentifier(expr,
"TMath::ASin",
"asin");
1159 replaceIdentifier(expr,
"TMath::ACos",
"acos");
1160 replaceIdentifier(expr,
"TMath::ATan",
"atan");
1161 replaceIdentifier(expr,
"TMath::ATan2",
"atan2");
1162 replaceIdentifier(expr,
"TMath::Pi()",
"PI");
1163 replaceIdentifier(expr,
"TMath::E()",
"EULER");
1166std::optional<std::string> ternariesToIfElse(std::string
const &in);
1169std::optional<std::string> ternaryPartToIfElse(std::string
const &in)
1172 const std::size_t question = findTopLevel(in,
"?:,");
1173 if (question != std::string::npos && in[question] !=
'?') {
1174 return std::nullopt;
1177 if (question == std::string::npos) {
1180 for (std::size_t i = 0; i < in.size(); ++i) {
1181 if (in[i] ==
')' || in[i] ==
']') {
1182 return std::nullopt;
1184 if (in[i] !=
'(' && in[i] !=
'[') {
1188 const std::size_t
close = findClosingBracket(in, i);
1189 if (close == std::string::npos) {
1190 return std::nullopt;
1192 const std::string inner = in.substr(i + 1, close - i - 1);
1193 const std::optional<std::string> innerOut = ternariesToIfElse(inner);
1195 return std::nullopt;
1198 const std::string before = trimmed(in.substr(0, i));
1199 const bool isGrouping = in[i] ==
'(' && (before.empty() || !isIdentifierChar(before.back()));
1200 if (isGrouping && *innerOut != trimmed(inner) &&
startsWith(*innerOut,
"ifelse(") &&
1201 findClosingBracket(*innerOut, std::string(
"ifelse").
size()) == innerOut->size() - 1) {
1204 out += in[i] + *innerOut + in[
close];
1212 std::size_t colon = question;
1213 for (
int nQuestions = 1; nQuestions > 0;) {
1214 colon = findTopLevel(in,
"?:", colon + 1);
1215 if (colon == std::string::npos) {
1216 return std::nullopt;
1218 nQuestions += in[colon] ==
'?' ? 1 : -1;
1221 const auto condition = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(0, question)));
1222 const auto ifTrue = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(question + 1, colon - question - 1)));
1223 const auto ifFalse = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(colon + 1)));
1224 if (!condition || !ifTrue || !ifFalse || condition->empty() || ifTrue->empty() || ifFalse->empty()) {
1225 return std::nullopt;
1227 return "ifelse(" + *condition +
"," + *ifTrue +
"," + *ifFalse +
")";
1232std::optional<std::string> ternariesToIfElse(std::string
const &in)
1236 for (std::string
const &part : splitTopLevelCommas(in)) {
1237 const std::optional<std::string> partOut = ternaryPartToIfElse(part);
1239 return std::nullopt;
1241 out += (first ?
"" :
",") + *partOut;
1250 for (
RooAbsArg const *dependent : dependents) {
1251 if (
dynamic_cast<RooAbsPdf const *
>(dependent)) {
1253 dependent->
GetName() +
"', which HS3 doesn't allow");
1258template <
class RooArg_t>
1261 checkExpressionRefersToNoPdf(pdf, pdf.dependents());
1262 TString expression(pdf.expression());
1263 cleanExpression(expression);
1270 for (
size_t idx = pdf.nParameters(); idx--;) {
1271 const RooAbsArg *par = pdf.getParameter(idx);
1272 expression.ReplaceAll((
"x[" + std::to_string(idx) +
"]").c_str(), par->
GetName());
1273 expression.ReplaceAll((
"@" + std::to_string(idx)).c_str(), par->
GetName());
1275 if (expression.Contains(
"?")) {
1276 if (
const auto rewritten = ternariesToIfElse(expression.Data())) {
1277 expression = rewritten->c_str();
1280 "expression of '") +
1281 pdf.GetName() +
"' to ifelse(), exporting the expression unchanged.");
1284 elem[
"expression"] << expression.Data();
1286 for (
const RooAbsArg *dependent : pdf.dependents()) {
1287 auto const *observable =
dynamic_cast<const RooAbsRealLValue *
>(dependent);
1303template <
class RooArg_t>
1306 elem[
"x"] << pdf.x().GetName();
1307 auto &coefs = elem[
"coefficients"].
set_seq();
1308 for (
int i = 0; i < pdf.lowestOrder(); ++i) {
1311 for (
const auto &coef : pdf.coefList()) {
1320 elem[
"type"] <<
"poisson_continuous_dist";
1364 elem[
"mu"] << lognormalLogName(m0, tool);
1365 elem[
"sigma"] << lognormalLogName(k, tool);
1389 checkExpressionRefersToNoPdf(pdf, pdf.
observables());
1390 checkExpressionRefersToNoPdf(pdf, pdf.
parameters());
1399 elem[
"expression"] << formula.Data();
1409 elem[
"order"] << pdf.
order();
1410 elem[
"eps"] << pdf.
eps();
1416 elem[
"integrand"] << integrand;
1418 elem[
"domain"] << integral.
intRange();
1429 elem[
"conv_func"] << convFunc->GetName();
1440 elem[
"range"] << rangeName->GetName();
1450 auto ¶msNode = elem[
"parameters"].
set_seq();
1454 auto &observablesNode = elem[
"axes"].
set_seq();
1464 elem[
"interpolation"] << (rs.
order() == 5 ?
"poly5" :
"poly3");
1465 elem[
"logx"] << rs.
logx();
1466 elem[
"logy"] << rs.
logy();
1470 auto &x0 = elem[
"x0"].
set_seq();
1471 auto &y0 = elem[
"y0"].
set_seq();
1472 for (
int i = 0; i < sp.
GetNp(); ++i) {
1476 x0.append_child() << xk;
1477 y0.append_child() << yk;
1510 const char *key =
p.has_child(
"self_normalized") ?
"self_normalized" :
"selfnormalized";
1511 const bool selfNormalized =
p.has_child(key) &&
p[key].val_bool();
1519 elem[
"function"] << funcProxy.absArg()->GetName();
1521 elem[
"self_normalized"] <<
true;
1534template <
class T,
class Getter_t>
1540 template <
class RooArg_t>
1541 void write(RooArg_t
const &arg,
JSONNode &elem)
const
1548template <
class T,
class Collection_t,
class Getter_t>
1557 template <
class RooArg_t>
1558 void write(RooArg_t
const &arg,
JSONNode &elem)
const
1564template <
class T = RooAbsReal,
class Getter_t>
1565ObjectField<T, Getter_t>
object(
const char *key, Getter_t getter)
1567 return {key, getter};
1570template <
class T = RooAbsReal,
class Collection_t = RooArgList,
class Getter_t>
1571ListField<T, Collection_t, Getter_t> list(
const char *key, Getter_t getter)
1573 return {key, getter};
1578template <
class RooArg_t,
class... Fields_t>
1579void registerFields(
const std::string &key, Fields_t... fields)
1584 tool->
wsImport(RooArg_t{
name.c_str(),
name.c_str(), fields.request(*tool,
p)...});
1587 (fields.write(arg, elem), ...);
1590 registerExporter<RooArg_t>(key, exportFields);
1594void registerDeprecatedKey(
const std::string &key,
const std::string &replacement)
1597 static std::set<std::string> warned;
1598 if (warned.insert(key).second) {
1599 RooJSONFactoryWSTool::warning(
"RooFitHS3: the type \"" + key +
"\" is deprecated, please use \"" +
1600 replacement +
"\" instead.");
1604 [&](
auto const &importer) { return importer->importArg(tool, p); });
1609const bool registered = []() {
1610 registerType(
"bernstein_poly_dist", importBernstein, exportBernstein);
1611 registerType(
"binsampling_dist", importBinSamplingPdf, exportBinSamplingPdf);
1612 registerType(
"binvolume", importBinWidthFunction<false>, exportBinWidthFunction);
1613 registerType(
"crystalball_doublesided_dist", importCrystalBallDoubleSided, exportCrystalBall);
1614 registerType(
"decay_dist", importDecay, exportDecay,
false);
1615 registerType(
"density_function_dist", importWrapperPdf, exportWrapperPdf);
1616 registerType(
"derivative", importDerivative, exportDerivative);
1617 registerType(
"exponential_dist", importExponential, exportExponential);
1618 registerType(
"fft_convolution_dist", importFFTConvPdf, exportFFTConvPdf);
1619 registerType(
"gaussian_dist", importGaussian, exportGaussian);
1620 registerType(
"generic", importFormulaArg<RooFormulaVar>, exportFormulaArg<RooFormulaVar>);
1621 registerType(
"generic_dist", importFormulaArg<RooGenericPdf>, exportFormulaArg<RooGenericPdf>);
1622 registerType(
"histogram_dist", importHist<RooHistPdf>, exportHist<RooHistPdf>);
1623 registerType(
"integral", importRealIntegral, exportRealIntegral);
1624 registerType(
"landau_dist", importLandau, exportLandau);
1625 registerType(
"legacy_exp_poly_dist", importPolynomial<RooLegacyExpPoly>, exportPolynomial<RooLegacyExpPoly>);
1626 registerType(
"lognormal_dist", importLogNormal, exportLogNormal);
1627 registerType(
"mixture_dist", importAddPdf, exportAddPdf<RooAddPdf>);
1628 registerType(
"mixture_model", importAddModel, exportAddPdf<RooAddModel>);
1629 registerType(
"multivariate_normal_dist", importMultiVarGaussian, exportMultiVarGaussian);
1630 registerType(
"poisson_dist", importPoisson<false>, exportPoisson);
1631 registerType(
"polynomial", importPolynomial<RooPolyVar>, exportPolynomial<RooPolyVar>);
1632 registerType(
"polynomial_dist", importPolynomial<RooPolynomial>, exportPolynomial<RooPolynomial>);
1634 registerType(
"rate_extended_dist", importExtendPdf, exportExtendPdf);
1637 registerType(
"step", importHist<RooHistFunc>, exportHist<RooHistFunc>);
1638 registerType(
"step", importParamHistFunc, exportParamHistFunc);
1639 registerType(
"uniform_dist", importUniform, exportUniform);
1640 registerType(
"weighted_sum_dist", importRealSumPdf, exportRealSumPdf);
1645 registerFields<RooBifurGauss>(
"bifurkated_gaussian_dist",
object(
"x", &
RooBifurGauss::getX),
1653 registerFields<RooChebychev>(
"chebychev_dist",
object(
"x", &
RooChebychev::x),
1663 registerFields<RooProdPdf>(
"product_dist", list<RooAbsPdf>(
"factors", &
RooProdPdf::pdfList));
1672 registerExporter<RooTFnBinding>(
"generic", exportTFnBinding);
1683 registerDeprecatedKey(
"ARGUS_dist",
"argus_dist");
1684 registerDeprecatedKey(
"binsampling",
"binsampling_dist");
1685 registerDeprecatedKey(
"delta_resolution_model",
"truth_model_function");
1686 registerDeprecatedKey(
"gauss_resolution_model",
"gauss_model_function");
1687 registerDeprecatedKey(
"mixture_resolution_model",
"mixture_model");
1693std::optional<ArrayComponentInfo>
1698 if (
auto const *poisson =
dynamic_cast<RooPoisson const *
>(&pdf)) {
1699 out.
type = poisson->getNoRounding() ?
"poisson_continuous_dist" :
"poisson_dist";
1700 x = &poisson->getX();
1702 }
else if (
auto const *gauss =
dynamic_cast<RooGaussian const *
>(&pdf)) {
1703 out.
type =
"gaussian_dist";
1712 }
else if (
auto const *lognormal =
dynamic_cast<RooLognormal const *
>(&pdf)) {
1713 out.
type =
"lognormal_dist";
1714 x = &lognormal->getX();
1715 if (lognormal->useStandardParametrization()) {
1719 out.
fields = {{
"mu", lognormalLogName(lognormal->getMedian(), tool)},
1720 {
"sigma", lognormalLogName(lognormal->getShapeK(), tool)}};
1723 return std::nullopt;
1727 return std::nullopt;
1734 std::vector<RooAbsPdf const *>
const &components)
1736 auto error = [&
name](std::string
const &
message) {
1739 if (components.empty()) {
1740 error(
"it has no components");
1742 std::vector<ArrayComponentInfo> comps;
1743 std::set<std::string> observables;
1744 for (
RooAbsPdf const *pdf : components) {
1747 error(
"'" + std::string(pdf->
GetName()) +
1748 "' cannot be a component, only RooPoisson, RooGaussian and RooLognormal over a named observable "
1751 if (!comps.empty() && comp->type != comps.front().type) {
1752 error(
"the components '" + std::string(components.front()->GetName()) +
"' (" + comps.front().type +
1753 ") and '" + pdf->
GetName() +
"' (" + comp->type +
") have different types");
1755 if (!observables.insert(comp->observable).second) {
1756 error(
"two components have the observable '" + comp->observable +
"'");
1758 comps.push_back(std::move(*comp));
1761 elem[
"type"] <<
"array_dist";
1762 elem[
"component_type"] << comps.front().type;
1765 std::visit([&node](
auto const &
v) { node <<
v; },
value);
1769 std::set<std::string> defaultKeys;
1770 if (comps.size() > 1) {
1771 for (std::size_t i = 0; i < comps.front().fields.size(); ++i) {
1772 auto const &field = comps.front().fields[i];
1773 if (std::all_of(comps.begin(), comps.end(),
1774 [&](
ArrayComponentInfo const &comp) { return comp.fields[i].second == field.second; })) {
1775 defaultKeys.insert(field.first);
1776 write(elem[
"default_parameters"].set_map()[field.first], field.second);
1784 node[
"x"] << comp.observable;
1785 for (
auto const &field : comp.fields) {
1786 if (defaultKeys.find(field.first) == defaultKeys.end()) {
1787 write(node[field.first], field.second);
void writeArrayDist(RooJSONFactoryWSTool &tool, JSONNode &elem, std::string const &name, std::vector< RooAbsPdf const * > const &components)
std::optional< ArrayComponentInfo > arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable, RooJSONFactoryWSTool *tool)
void checkParamHistFuncOrderIsDefined(RooFit::HS3::Version const &version, RooAbsCollection const &vars, std::string const &context)
void writeReference(JSONNode &node, RooAbsArg const &arg)
std::string transformedOriginal(std::string_view name, std::string_view suffix)
std::string transformedBaseName(RooAbsReal const ¶m)
std::vector< RooAbsReal * > paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
RooArgList toParamHistFuncOrder(RooArgList const ¶msInBinOrder, RooAbsCollection const &vars)
bool startsWith(std::string_view str, std::string_view prefix)
bool endsWith(std::string_view str, std::string_view suffix)
bool isLiteralConstVar(RooAbsArg const &arg)
std::unique_ptr< RooArgSet > histogramVariablesNamedAfterObservables(RooDataHist const &dh, RooArgSet const &histObs, RooArgSet const &funcObs)
constexpr const char * helperObjectTag
constexpr const char * arrayDistTag
void registerImporter(const std::string &key, ImportFunc func)
void registerType(const std::string &key, ImportFunc importFunc, ExportFunc< RooArg_t > exportFunc, bool autoExportDependants=true)
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t target
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
const RooArgList & dataVars() const
RooAbsReal const & getModel() const
Get the resolution model.
Common abstract base class for objects that represent a value and a "shape" in RooFit.
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
RooAbsProxy * getProxy(Int_t index) const
Return the nth proxy from the proxy list.
Abstract base class for RooRealVar binning definitions.
Int_t getInterpolationOrder() const
Abstract container object that can hold multiple RooAbsArg objects.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
RooAbsArg * find(const char *name) const
Find object with given name in list.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract interface for all probability density functions.
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
Abstract base class for objects that represent a real value and implements functionality common to al...
RooAddModel is an efficient implementation of a sum of PDFs of the form.
Efficient implementation of a sum of PDFs of the form.
const RooArgList & list() const
RooArgList is a container object that can hold multiple RooAbsArg objects.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
RooAbsReal const & getC() const
RooAbsReal const & getM0() const
RooAbsReal const & getP() const
RooAbsReal const & getM() const
Bernstein basis polynomials are positive-definite in the range [0,1].
RooAbsRealLValue const & x() const
RooArgList const & coefList() const
RooAbsReal const & getSigmaL() const
Get the left sigma parameter.
RooAbsReal const & getSigmaR() const
Get the right sigma parameter.
RooAbsReal const & getX() const
Get the x variable.
RooAbsReal const & getMean() const
Get the mean parameter.
The RooBinSamplingPdf is supposed to be used as an adapter between a continuous PDF and a binned dist...
const RooAbsPdf & pdf() const
const RooAbsReal & observable() const
Returns the bin width (or volume) given a RooHistFunc.
bool divideByBinWidth() const
const RooHistFunc & histFunc() const
RooAbsReal const & getSigma() const
RooAbsReal const & getM() const
RooAbsReal const & getN() const
RooAbsReal const & getM0() const
RooAbsReal const & getAlpha() const
RooAbsReal const & x() const
RooArgList const & coefList() const
PDF implementing the generalized Asymmetrical Double-Sided Crystall Ball line shape.
RooAbsReal const * nR() const
RooAbsReal const * alphaR() const
RooAbsReal const & sigmaR() const
RooAbsReal const & nL() const
RooAbsReal const & x0() const
RooAbsReal const & x() const
RooAbsReal const & sigmaL() const
RooAbsReal const & alphaL() const
Container class to hold N-dimensional binned data.
double const * weightArray() const
Single or double sided decay function that can be analytically convolved with any RooResolutionModel ...
DecayType getDecayType() const
Get the decay type.
RooAbsReal const & getTau() const
Get the decay constant.
RooAbsReal const & getT() const
Get the cnvolution variable.
Represents the first, second, or third order derivative of any RooAbsReal as calculated (numerically)...
RooAbsReal const & getX() const
RooArgSet const & getNset() const
RooAbsReal const & getFunc() const
RooAbsReal const & pdf() const
RooAbsReal const & eff() const
bool negateCoefficient() const
RooAbsReal const & coefficient() const
Get the coefficient "c".
RooAbsReal const & variable() const
Get the x variable.
RooExtendPdf is a wrapper around an existing PDF that adds a parameteric extended likelihood term to ...
TNamed const * getRangeName() const
RooAbsPdf const & pdf() const
RooAbsReal const & getN() const
PDF for the numerical (FFT) convolution of two PDFs.
RooAbsReal const * getPdfConvVar() const
RooAbsReal const & getConvVar() const
RooAbsReal const & getPdf2() const
RooAbsReal const & getPdf1() const
double val_double() const
JSONNode & append_child()
size_t num_children() const
void fill_mat(Matrix const &mat)
JSONNode const * find(std::string const &key) const
The component at the end of a path of keys, or nullptr if a component on the path doesn't exist.
bool has_child(std::string const &) const
static std::unique_ptr< JSONTree > create()
RooAbsReal const & getX() const
RooAbsReal const & getGamma() const
RooAbsReal const & getBeta() const
RooAbsReal const & getMu() const
RooAbsReal const & getMean() const
Get the mean parameter.
RooAbsReal const & getSigma() const
Get the sigma parameter.
RooAbsReal const & getX() const
Get the x variable.
RooAbsReal const & getMean() const
Get the mean parameter.
RooAbsReal const & getSigma() const
Get the sigma parameter.
A real-valued function sampled from a multidimensional histogram.
Landau distribution p.d.f.
RooAbsReal const & getSigma() const
RooAbsReal const & getMean() const
RooAbsReal const & getX() const
bool useStandardParametrization() const
RooAbsReal const & getMedian() const
Get the median parameter.
RooAbsReal const & getShapeK() const
Get the shape parameter.
RooAbsReal const & getX() const
Get the x variable.
Multivariate Gaussian p.d.f.
const TMatrixDSym & covarianceMatrix() const
const RooArgList & xVec() const
const RooArgList & muVec() const
Holds the configuration parameters of the various numeric integrators used by RooRealIntegral.
RooAbsReal const & getX() const
Get the x variable.
bool getNoRounding() const
RooAbsReal const & getMean() const
Get the mean parameter.
RooAbsReal const & base() const
Get the base of the exponentiated terms (aka. x variable).
RooArgList const & coefList() const
Get the list of coefficients.
RooArgList const & expList() const
Get the list of exponents.
Efficient implementation of a product of PDFs of the form.
const RooArgList & pdfList() const
Represents the product of a given set of RooAbsReal objects.
const RooArgList & categoricalComponents() const
const RooArgList & realComponents() const
RooAbsReal const & intPdf() const
RooArgSet const & intObs() const
Performs hybrid numerical/analytical integrals of RooAbsReal objects.
RooArgSet const * funcNormSet() const
RooArgSet intVars() const
const RooAbsReal & integrand() const
const char * intRange() const
const RooArgList & coefList() const
const RooArgList & funcList() const
Implements a PDF constructed from a sum of functions:
const RooArgList & funcList() const
ExtendMode extendMode() const override
Returns ability of PDF to provide extended likelihood terms.
const RooArgList & coefList() const
Variable that can be changed from the outside.
RooResolutionModel is the base class for PDFs that represent a resolution model that can be convolute...
RooAbsRealLValue & convVar() const
Return the convolution variable of the resolution model.
A RooFit class for creating spline functions.
RooAbsReal const & x() const
TSpline const & spline() const
int order() const
Return the order of the spline.
Use TF1, TF2, TF3 functions as RooFit objects.
const TF1 & function() const
const RooArgList & parameters() const
const RooArgList & observables() const
Persistable container for RooFit projects.
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
RooAbsArg * arg(RooStringView name) const
Return RooAbsArg with given name. A null pointer is returned if none is found.
The RooWrapperPdf is a class that can be used to convert a function into a PDF.
bool selfNormalized() const override
Shows if a PDF is self-normalized, which means that no attempt is made to add a normalization term.
virtual TString GetExpFormula(Option_t *option="") const
TMatrixTBase< Element > & ResizeTo(Int_t nrows, Int_t ncols, Int_t=-1) override
Set size of the matrix to nrows x ncols New dynamic elements are created, the overlapping part of the...
const char * GetName() const override
Returns name of object.
Base class for spline implementation containing the Draw/Paint methods.
virtual void GetKnot(Int_t i, Double_t &x, Double_t &y) const =0
virtual Int_t GetNp() const
const char * Data() const
TString & ReplaceAll(const TString &s1, const TString &s2)
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
void swap(RVec< T > &lhs, RVec< T > &rhs)
double dist(Rotation3D const &r1, Rotation3D const &r2)
Types that represent an HS3 document.
std::string arrayComponentForm(std::string const &componentType, RooFit::Detail::JSONNode const &component, RooFit::Detail::JSONNode const *defaults)
A canonical form of the component component of an array distribution with the type componentType and ...
std::variant< std::string, double > NameOrNumber
A name, or a number for a constant.
Distribution parseDistribution(Detail::JSONNode const &distribution, Diagnostics &diagnostics)
Reads a distribution that doesn't come with a document.
void buildCombinedDist(RooJSONFactoryWSTool &tool, std::string const &name, CombinedDist const &dist, std::vector< std::string > const &otherLikelihoodTerms={})
Create the RooSimultaneous of a combined distribution in the workspace of the tool.
void report(Diagnostics const &diagnostics, std::string const &object="")
Forward the warnings to the message service, and throw if there are errors.
RooArgSet createObservables(std::vector< BinnedAxis > const &axes)
Create the variables for the axes of binned data.
std::string const * importedArrayComponentForm(RooJSONFactoryWSTool &tool, std::string const &name)
The canonical form (see arrayComponentForm()) of the component of an array distribution that this imp...
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
void recordImportedArrayComponent(RooJSONFactoryWSTool &tool, std::string const &name, std::string form)
Record that this import created the component name of an array distribution, with the canonical form ...
void writeAxis(Detail::JSONNode &node, BinnedAxis const &axis)
Writes an axis of binned data.
std::vector< Diagnostic > Diagnostics
NameOrNumber toNameOrNumber(RooAbsArg const &arg)
The name of an object, or the value of a literal constant.
BinnedAxis toBinnedAxis(RooRealVar const &var)
The axis of binned data for a variable, or for a binning of a variable with the given name.
std::vector< BinnedAxis > parseBinnedAxes(Detail::JSONNode const &axes, Diagnostics &diagnostics)
Reads the axes of binned data that doesn't come with a document.
void validateCombinedDist(CombinedDist const &dist, std::string const &name, Diagnostics &diagnostics)
std::vector< std::pair< std::string, RooFit::HS3::NameOrNumber > > fields
static uint64_t sum(uint64_t i)