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";
435 if (ws.
arg(pdfName)) {
436 error(
"cannot create the component for '" +
x +
"' as '" + pdfName +
437 "', the workspace already has an object of that name");
440 node[
"name"] << pdfName;
441 node[
"type"] << componentType;
443 for (
JSONNode const &field : defaults->children()) {
444 copyValue(node[field.key()], field);
447 for (
JSONNode const &field : component.children()) {
448 copyValue(node[field.key()], field);
453 error(context +
" did not produce a distribution");
460 for (std::size_t i = 0; i < observables.size(); ++i) {
463 error(
"the observable '" + observables[i] +
"' is not a parameter or function");
465 for (std::size_t k = 0; k < observables.size(); ++k) {
466 if (k != i && pdfs[i].dependsOn(*ws.
arg(observables[k]))) {
467 error(
"component " + std::to_string(i) +
" depends on the observable '" + observables[k] +
468 "' of component " + std::to_string(k));
471 for (
RooAbsArg const *server : pdfs[i].servers()) {
472 if (server !=
x && server->dependsOn(*
x)) {
473 error(
"the parameters of component " + std::to_string(i) +
" depend on its own observable '" +
474 observables[i] +
"'");
501 const std::size_t nSummands =
p.has_child(
"summands") ?
p[
"summands"].num_children() : 0;
502 const std::size_t nCoefficients =
p.has_child(
"coefficients") ?
p[
"coefficients"].num_children() : 0;
504 if (
p.has_child(
"extended")) {
507 const bool extended =
p[
"extended"].val_bool();
508 const std::string counts =
509 std::to_string(nCoefficients) +
" coefficients for " + std::to_string(nSummands) +
" summands";
510 if (extended && nCoefficients > 0 && nCoefficients + 1 == nSummands) {
512 ", which defines a non-extended mixture");
514 if (!extended && nCoefficients == 0 && nSummands > 0) {
516 ", which defines an extended mixture of extended distributions");
518 if (!extended && nCoefficients == nSummands && nSummands > 0) {
524 for (std::size_t i = 0; i < nCoefficients; ++i) {
525 sum += (i == 0 ?
"x[" :
"+x[") + std::to_string(i) +
"]";
528 for (std::size_t i = 0; i + 1 < nCoefficients; ++i) {
530 (
"x[" + std::to_string(i) +
"]/(" +
sum +
")").c_str(),
536 }
else if (nCoefficients == nSummands && nSummands > 0 && sinceHS3v03) {
539 "' has one coefficient per summand, but no \"extended\" flag, which HS3 "
540 "requires to decide whether the mixture is extended");
542 if (nSummands > 0 && nCoefficients == 0 && sinceHS3v03) {
544 "' has no coefficients, which HS3 0.3 doesn't define. It is read as the sum of "
545 "its extended summands.");
562template <
bool Div
ideByBinW
idth>
582 obs->GetName() +
"' as indicated by parent RooBinSamplingPdf '" +
name +
586 if (!
p.has_child(
"epsilon")) {
589 double epsilon(
p[
"epsilon"].val_double());
599 const bool extended =
p.has_child(
"extended") &&
p[
"extended"].val_bool();
603template <
class RooArg_t>
607 if (!
p.has_child(
"coefficients")) {
614 for (
const auto &coef :
p[
"coefficients"].children()) {
618 if (order == 0 && (coef.val() ==
"1.0" || coef.val() ==
"1")) {
620 }
else if (coefs.empty() && (coef.val() ==
"0.0" || coef.val() ==
"0")) {
635template <
bool Continuous>
639 bool noRounding = Continuous;
640 if (
p.has_child(
"integer")) {
641 std::string
const type = Continuous ?
"poisson_continuous_dist" :
"poisson_dist";
645 "' has the key \"integer\", which is not part of HS3. The discrete Poisson distribution is "
646 "\"poisson_dist\" and the continuous one is \"poisson_continuous_dist\".");
648 noRounding = !
p[
"integer"].val_bool();
676 if (
p.has_child(
"normalization")) {
678 normSetPtr = &normSet;
680 JSONNode const *domain =
p.find(
"domain");
683 domain ? domain->
val().c_str() :
nullptr);
691 Int_t order =
p[
"order"].val_int();
692 double eps =
p[
"eps"].val_double();
694 if (
p.has_child(
"normalization")) {
704 Int_t order =
p[
"ipOrder"].val_int();
707 if (
p.has_child(
"conv_func")) {
730 const bool legacyKey = !
p.has_child(
"mu") &&
p.has_child(
"mean");
733 "' uses the key \"mean\", which HS3 0.3 renamed to \"mu\".");
748 const std::string mu =
p[
"mu"].val();
749 const std::string
sigma =
p[
"sigma"].val();
750 const bool isStandard = !
endsWith(mu, lognormalLogSuffix);
794 const std::string constParamName =
p[
"c"].val();
795 const bool isInverted =
endsWith(constParamName,
"_exponential_inverted");
805 const bool hasCov =
p.has_child(
"covariances");
806 const bool hasCorr =
p.has_child(
"correlations") &&
p.has_child(
"standard_deviations");
807 if (!hasCov && !hasCorr) {
811 const std::string key = hasCov ?
"covariances" :
"correlations";
812 std::vector<double> sigmas;
814 sigmas.assign(
p[key].num_children(), 1.0);
816 sigmas <<
p[
"standard_deviations"];
818 const std::size_t
n = sigmas.size();
820 if (
p[key].num_children() !=
n) {
826 for (
const auto &row :
p[key].children()) {
827 if (!row.is_seq() || row.num_children() !=
n) {
831 for (
const auto &val : row.children()) {
832 covmat(i, j) = val.val_double() * sigmas[i] * sigmas[j];
856 if (!
p.has_child(
"parameters")) {
861 const bool hasAxes =
p.has_child(
"axes");
864 "No axes given in '" +
name +
865 "'. Using default binning (uniform; nbins=100). If needed, export the Workspace to JSON with a newer "
866 "Root version that supports custom ParamHistFunc binnings(>=6.38.00).\n");
868 RooArgList binning = hasAxes ? readBinning(
p, varList) : varList;
880 if (!
p.has_child(
"x0") || !
p.has_child(
"y0")) {
885 const std::string algo =
p.has_child(
"interpolation") ?
p[
"interpolation"].val() :
"poly3";
886 if (algo !=
"poly3" && algo !=
"poly5") {
888 "': allowed are 'poly3' and 'poly5'");
890 const bool logx =
p.has_child(
"logx") &&
p[
"logx"].val_bool();
891 const bool logy =
p.has_child(
"logy") &&
p[
"logy"].val_bool();
893 std::vector<double> x0;
894 std::vector<double> y0;
898 if (x0.size() != y0.size()) {
900 ", y0 has " + std::to_string(y0.size()));
932 if (
p.has_child(
"x") && !
p[
"x"].is_seq()) {
942const std::initializer_list<const char *> tailKeys = {
"alpha_L",
"n_L",
"alpha_R",
"n_R"};
944bool hasAny(
const JSONNode &
p, std::initializer_list<const char *> keys)
946 return std::any_of(keys.begin(), keys.end(), [&
p](
const char *key) { return p.has_child(key); });
949bool hasDoubleSidedKeys(
const JSONNode &
p)
951 return hasAny(
p, tailKeys) || hasAny(
p, {
"sigma_L",
"sigma_R"});
959 const std::string context =
type +
" '" +
name +
"'";
961 const bool asymmetricTails = hasAny(
p, tailKeys);
962 const bool symmetricTails = hasAny(
p, {
"alpha",
"n"});
963 if (symmetricTails && !symmetricShorthand) {
965 "\"n_L\", \"alpha_R\" and \"n_R\"");
967 if (symmetricTails && asymmetricTails) {
969 " must not combine \"alpha\"/\"n\" with \"alpha_L\"/\"n_L\"/\"alpha_R\"/\"n_R\"");
971 if (asymmetricTails || !symmetricTails) {
972 for (
const char *key : tailKeys) {
973 if (!
p.has_child(key)) {
975 "\": \"alpha_L\", \"n_L\", \"alpha_R\" and \"n_R\" are all required");
978 }
else if (!
p.has_child(
"alpha") || !
p.has_child(
"n")) {
982 const bool asymmetricWidths = hasAny(
p, {
"sigma_L",
"sigma_R"});
983 if (asymmetricWidths &&
p.has_child(
"sigma")) {
986 if (asymmetricWidths && !(
p.has_child(
"sigma_L") &&
p.has_child(
"sigma_R"))) {
989 if (!asymmetricWidths && !
p.has_child(
"sigma")) {
1011 if (!CrystalBall::hasDoubleSidedKeys(
p)) {
1014 static bool warned =
false;
1017 "\"alpha_R\", \"n_R\", \"sigma_L\" or \"sigma_R\" is deprecated, please use "
1018 "\"crystalball_doublesided_dist\" for the double-sided Crystal Ball.");
1021 CrystalBall::importDoubleSided(tool,
p,
"crystalball_dist",
true);
1027 CrystalBall::importDoubleSided(tool,
p,
"crystalball_doublesided_dist",
false);
1042 elem[
"type"] <<
"crystalball_dist";
1060template <
class RooArg_t>
1065 elem[
"extended"] << (pdf.extendMode() != RooArg_t::CanNotBeExtended);
1067 if (pdf.coefList().empty() && std::is_same_v<RooArg_t, RooAddPdf>) {
1069 "' has no coefficients. It is written as a mixture_dist without coefficients, "
1070 "which HS3 0.3 doesn't define, so other implementations might not read it.");
1081template <
class RooArg_t>
1091template <
class RooArg_t>
1095 if (!
p.has_child(
"data")) {
1098 std::unique_ptr<RooDataHist> dataHist =
1100 tool->
wsEmplace<RooArg_t>(
name, *dataHist->get(), *dataHist);
1108 elem[
"epsilon"] << pdf.
epsilon();
1115 elem[
"type"] <<
"inverse_binvolume";
1120void cleanExpression(
TString &expr)
1126 replaceIdentifier(expr,
"TMath::Exp",
"exp");
1127 replaceIdentifier(expr,
"TMath::Min",
"min");
1128 replaceIdentifier(expr,
"TMath::Max",
"max");
1129 replaceIdentifier(expr,
"TMath::Log",
"log");
1130 replaceIdentifier(expr,
"TMath::Log10",
"log10");
1131 replaceIdentifier(expr,
"TMath::Cos",
"cos");
1132 replaceIdentifier(expr,
"TMath::CosH",
"cosh");
1133 replaceIdentifier(expr,
"TMath::Sin",
"sin");
1134 replaceIdentifier(expr,
"TMath::SinH",
"sinh");
1135 replaceIdentifier(expr,
"TMath::Sqrt",
"sqrt");
1136 replaceIdentifier(expr,
"TMath::Power",
"pow");
1137 replaceIdentifier(expr,
"TMath::Erf",
"erf");
1138 replaceIdentifier(expr,
"TMath::Erfc",
"erfc");
1139 replaceIdentifier(expr,
"TMath::Floor",
"floor");
1140 replaceIdentifier(expr,
"TMath::Ceil",
"ceil");
1141 replaceIdentifier(expr,
"TMath::Abs",
"abs");
1142 replaceIdentifier(expr,
"TMath::Tan",
"tan");
1143 replaceIdentifier(expr,
"TMath::TanH",
"tanh");
1144 replaceIdentifier(expr,
"TMath::ASin",
"asin");
1145 replaceIdentifier(expr,
"TMath::ACos",
"acos");
1146 replaceIdentifier(expr,
"TMath::ATan",
"atan");
1147 replaceIdentifier(expr,
"TMath::ATan2",
"atan2");
1148 replaceIdentifier(expr,
"TMath::Pi()",
"PI");
1149 replaceIdentifier(expr,
"TMath::E()",
"EULER");
1152std::optional<std::string> ternariesToIfElse(std::string
const &in);
1155std::optional<std::string> ternaryPartToIfElse(std::string
const &in)
1158 const std::size_t question = findTopLevel(in,
"?:,");
1159 if (question != std::string::npos && in[question] !=
'?') {
1160 return std::nullopt;
1163 if (question == std::string::npos) {
1166 for (std::size_t i = 0; i < in.size(); ++i) {
1167 if (in[i] ==
')' || in[i] ==
']') {
1168 return std::nullopt;
1170 if (in[i] !=
'(' && in[i] !=
'[') {
1174 const std::size_t
close = findClosingBracket(in, i);
1175 if (close == std::string::npos) {
1176 return std::nullopt;
1178 const std::string inner = in.substr(i + 1, close - i - 1);
1179 const std::optional<std::string> innerOut = ternariesToIfElse(inner);
1181 return std::nullopt;
1184 const std::string before = trimmed(in.substr(0, i));
1185 const bool isGrouping = in[i] ==
'(' && (before.empty() || !isIdentifierChar(before.back()));
1186 if (isGrouping && *innerOut != trimmed(inner) &&
startsWith(*innerOut,
"ifelse(") &&
1187 findClosingBracket(*innerOut, std::string(
"ifelse").
size()) == innerOut->size() - 1) {
1190 out += in[i] + *innerOut + in[
close];
1198 std::size_t colon = question;
1199 for (
int nQuestions = 1; nQuestions > 0;) {
1200 colon = findTopLevel(in,
"?:", colon + 1);
1201 if (colon == std::string::npos) {
1202 return std::nullopt;
1204 nQuestions += in[colon] ==
'?' ? 1 : -1;
1207 const auto condition = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(0, question)));
1208 const auto ifTrue = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(question + 1, colon - question - 1)));
1209 const auto ifFalse = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(colon + 1)));
1210 if (!condition || !ifTrue || !ifFalse || condition->empty() || ifTrue->empty() || ifFalse->empty()) {
1211 return std::nullopt;
1213 return "ifelse(" + *condition +
"," + *ifTrue +
"," + *ifFalse +
")";
1218std::optional<std::string> ternariesToIfElse(std::string
const &in)
1222 for (std::string
const &part : splitTopLevelCommas(in)) {
1223 const std::optional<std::string> partOut = ternaryPartToIfElse(part);
1225 return std::nullopt;
1227 out += (first ?
"" :
",") + *partOut;
1236 for (
RooAbsArg const *dependent : dependents) {
1237 if (
dynamic_cast<RooAbsPdf const *
>(dependent)) {
1239 dependent->
GetName() +
"', which HS3 doesn't allow");
1244template <
class RooArg_t>
1247 checkExpressionRefersToNoPdf(pdf, pdf.dependents());
1248 TString expression(pdf.expression());
1249 cleanExpression(expression);
1256 for (
size_t idx = pdf.nParameters(); idx--;) {
1257 const RooAbsArg *par = pdf.getParameter(idx);
1258 expression.ReplaceAll((
"x[" + std::to_string(idx) +
"]").c_str(), par->
GetName());
1259 expression.ReplaceAll((
"@" + std::to_string(idx)).c_str(), par->
GetName());
1261 if (expression.Contains(
"?")) {
1262 if (
const auto rewritten = ternariesToIfElse(expression.Data())) {
1263 expression = rewritten->c_str();
1266 "expression of '") +
1267 pdf.GetName() +
"' to ifelse(), exporting the expression unchanged.");
1270 elem[
"expression"] << expression.Data();
1272 for (
const RooAbsArg *dependent : pdf.dependents()) {
1273 auto const *observable =
dynamic_cast<const RooAbsRealLValue *
>(dependent);
1289template <
class RooArg_t>
1292 elem[
"x"] << pdf.x().GetName();
1293 auto &coefs = elem[
"coefficients"].
set_seq();
1294 for (
int i = 0; i < pdf.lowestOrder(); ++i) {
1297 for (
const auto &coef : pdf.coefList()) {
1306 elem[
"type"] <<
"poisson_continuous_dist";
1350 elem[
"mu"] << lognormalLogName(m0, tool);
1351 elem[
"sigma"] << lognormalLogName(k, tool);
1375 checkExpressionRefersToNoPdf(pdf, pdf.
observables());
1376 checkExpressionRefersToNoPdf(pdf, pdf.
parameters());
1385 elem[
"expression"] << formula.Data();
1395 elem[
"order"] << pdf.
order();
1396 elem[
"eps"] << pdf.
eps();
1402 elem[
"integrand"] << integrand;
1404 elem[
"domain"] << integral.
intRange();
1415 elem[
"conv_func"] << convFunc->GetName();
1426 elem[
"range"] << rangeName->GetName();
1436 auto ¶msNode = elem[
"parameters"].
set_seq();
1440 auto &observablesNode = elem[
"axes"].
set_seq();
1450 elem[
"interpolation"] << (rs.
order() == 5 ?
"poly5" :
"poly3");
1451 elem[
"logx"] << rs.
logx();
1452 elem[
"logy"] << rs.
logy();
1456 auto &x0 = elem[
"x0"].
set_seq();
1457 auto &y0 = elem[
"y0"].
set_seq();
1458 for (
int i = 0; i < sp.
GetNp(); ++i) {
1462 x0.append_child() << xk;
1463 y0.append_child() << yk;
1496 const char *key =
p.has_child(
"self_normalized") ?
"self_normalized" :
"selfnormalized";
1497 const bool selfNormalized =
p.has_child(key) &&
p[key].val_bool();
1505 elem[
"function"] << funcProxy.absArg()->GetName();
1507 elem[
"self_normalized"] <<
true;
1520template <
class T,
class Getter_t>
1526 template <
class RooArg_t>
1527 void write(RooArg_t
const &arg,
JSONNode &elem)
const
1534template <
class T,
class Collection_t,
class Getter_t>
1543 template <
class RooArg_t>
1544 void write(RooArg_t
const &arg,
JSONNode &elem)
const
1550template <
class T = RooAbsReal,
class Getter_t>
1551ObjectField<T, Getter_t>
object(
const char *key, Getter_t getter)
1553 return {key, getter};
1556template <
class T = RooAbsReal,
class Collection_t = RooArgList,
class Getter_t>
1557ListField<T, Collection_t, Getter_t> list(
const char *key, Getter_t getter)
1559 return {key, getter};
1564template <
class RooArg_t,
class... Fields_t>
1565void registerFields(
const std::string &key, Fields_t... fields)
1570 tool->
wsImport(RooArg_t{
name.c_str(),
name.c_str(), fields.request(*tool,
p)...});
1573 (fields.write(arg, elem), ...);
1576 registerExporter<RooArg_t>(key, exportFields);
1580void registerDeprecatedKey(
const std::string &key,
const std::string &replacement)
1583 static std::set<std::string> warned;
1584 if (warned.insert(key).second) {
1585 RooJSONFactoryWSTool::warning(
"RooFitHS3: the type \"" + key +
"\" is deprecated, please use \"" +
1586 replacement +
"\" instead.");
1590 [&](
auto const &importer) { return importer->importArg(tool, p); });
1595const bool registered = []() {
1596 registerType(
"bernstein_poly_dist", importBernstein, exportBernstein);
1597 registerType(
"binsampling_dist", importBinSamplingPdf, exportBinSamplingPdf);
1598 registerType(
"binvolume", importBinWidthFunction<false>, exportBinWidthFunction);
1599 registerType(
"crystalball_doublesided_dist", importCrystalBallDoubleSided, exportCrystalBall);
1600 registerType(
"decay_dist", importDecay, exportDecay,
false);
1601 registerType(
"density_function_dist", importWrapperPdf, exportWrapperPdf);
1602 registerType(
"derivative", importDerivative, exportDerivative);
1603 registerType(
"exponential_dist", importExponential, exportExponential);
1604 registerType(
"fft_convolution_dist", importFFTConvPdf, exportFFTConvPdf);
1605 registerType(
"gaussian_dist", importGaussian, exportGaussian);
1606 registerType(
"generic", importFormulaArg<RooFormulaVar>, exportFormulaArg<RooFormulaVar>);
1607 registerType(
"generic_dist", importFormulaArg<RooGenericPdf>, exportFormulaArg<RooGenericPdf>);
1608 registerType(
"histogram_dist", importHist<RooHistPdf>, exportHist<RooHistPdf>);
1609 registerType(
"integral", importRealIntegral, exportRealIntegral);
1610 registerType(
"landau_dist", importLandau, exportLandau);
1611 registerType(
"legacy_exp_poly_dist", importPolynomial<RooLegacyExpPoly>, exportPolynomial<RooLegacyExpPoly>);
1612 registerType(
"lognormal_dist", importLogNormal, exportLogNormal);
1613 registerType(
"mixture_dist", importAddPdf, exportAddPdf<RooAddPdf>);
1614 registerType(
"mixture_model", importAddModel, exportAddPdf<RooAddModel>);
1615 registerType(
"multivariate_normal_dist", importMultiVarGaussian, exportMultiVarGaussian);
1616 registerType(
"poisson_dist", importPoisson<false>, exportPoisson);
1617 registerType(
"polynomial", importPolynomial<RooPolyVar>, exportPolynomial<RooPolyVar>);
1618 registerType(
"polynomial_dist", importPolynomial<RooPolynomial>, exportPolynomial<RooPolynomial>);
1620 registerType(
"rate_extended_dist", importExtendPdf, exportExtendPdf);
1623 registerType(
"step", importHist<RooHistFunc>, exportHist<RooHistFunc>);
1624 registerType(
"step", importParamHistFunc, exportParamHistFunc);
1625 registerType(
"uniform_dist", importUniform, exportUniform);
1626 registerType(
"weighted_sum_dist", importRealSumPdf, exportRealSumPdf);
1631 registerFields<RooBifurGauss>(
"bifurkated_gaussian_dist",
object(
"x", &
RooBifurGauss::getX),
1639 registerFields<RooChebychev>(
"chebychev_dist",
object(
"x", &
RooChebychev::x),
1649 registerFields<RooProdPdf>(
"product_dist", list<RooAbsPdf>(
"factors", &
RooProdPdf::pdfList));
1658 registerExporter<RooTFnBinding>(
"generic", exportTFnBinding);
1669 registerDeprecatedKey(
"ARGUS_dist",
"argus_dist");
1670 registerDeprecatedKey(
"binsampling",
"binsampling_dist");
1671 registerDeprecatedKey(
"delta_resolution_model",
"truth_model_function");
1672 registerDeprecatedKey(
"gauss_resolution_model",
"gauss_model_function");
1673 registerDeprecatedKey(
"mixture_resolution_model",
"mixture_model");
1679std::optional<ArrayComponentInfo>
1684 if (
auto const *poisson =
dynamic_cast<RooPoisson const *
>(&pdf)) {
1685 out.
type = poisson->getNoRounding() ?
"poisson_continuous_dist" :
"poisson_dist";
1686 x = &poisson->getX();
1688 }
else if (
auto const *gauss =
dynamic_cast<RooGaussian const *
>(&pdf)) {
1689 out.
type =
"gaussian_dist";
1698 }
else if (
auto const *lognormal =
dynamic_cast<RooLognormal const *
>(&pdf)) {
1699 out.
type =
"lognormal_dist";
1700 x = &lognormal->getX();
1701 if (lognormal->useStandardParametrization()) {
1705 out.
fields = {{
"mu", lognormalLogName(lognormal->getMedian(), tool)},
1706 {
"sigma", lognormalLogName(lognormal->getShapeK(), tool)}};
1709 return std::nullopt;
1713 return std::nullopt;
1720 std::vector<RooAbsPdf const *>
const &components)
1722 auto error = [&
name](std::string
const &
message) {
1725 if (components.empty()) {
1726 error(
"it has no components");
1728 std::vector<ArrayComponentInfo> comps;
1729 std::set<std::string> observables;
1730 for (
RooAbsPdf const *pdf : components) {
1733 error(
"'" + std::string(pdf->
GetName()) +
1734 "' cannot be a component, only RooPoisson, RooGaussian and RooLognormal over a named observable "
1737 if (!comps.empty() && comp->type != comps.front().type) {
1738 error(
"the components '" + std::string(components.front()->GetName()) +
"' (" + comps.front().type +
1739 ") and '" + pdf->
GetName() +
"' (" + comp->type +
") have different types");
1741 if (!observables.insert(comp->observable).second) {
1742 error(
"two components have the observable '" + comp->observable +
"'");
1744 comps.push_back(std::move(*comp));
1747 elem[
"type"] <<
"array_dist";
1748 elem[
"component_type"] << comps.front().type;
1751 std::visit([&node](
auto const &
v) { node <<
v; },
value);
1755 std::set<std::string> defaultKeys;
1756 if (comps.size() > 1) {
1757 for (std::size_t i = 0; i < comps.front().fields.size(); ++i) {
1758 auto const &field = comps.front().fields[i];
1759 if (std::all_of(comps.begin(), comps.end(),
1760 [&](
ArrayComponentInfo const &comp) { return comp.fields[i].second == field.second; })) {
1761 defaultKeys.insert(field.first);
1762 write(elem[
"default_parameters"].set_map()[field.first], field.second);
1770 node[
"x"] << comp.observable;
1771 for (
auto const &field : comp.fields) {
1772 if (defaultKeys.find(field.first) == defaultKeys.end()) {
1773 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::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.
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
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)