Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
JSONFactories_RooFitCore.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Carsten D. Burgard, DESY/ATLAS, Dec 2021
5 *
6 * Copyright (c) 2022, CERN
7 *
8 * Redistribution and use in source and binary forms,
9 * with or without modification, are permitted according to the terms
10 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
11 */
12
14
15#include <RooAddPdf.h>
16#include <RooAddModel.h>
17#include <RooArgusBG.h>
18#include <RooBernstein.h>
19#include <RooBifurGauss.h>
20#include <RooBinSamplingPdf.h>
21#include <RooBinWidthFunction.h>
22#include <RooCBShape.h>
23#include <RooChebychev.h>
24#include <RooCrystalBall.h>
25#include <RooDataHist.h>
26#include <RooDecay.h>
27#include <RooDerivative.h>
28#include <RooEffProd.h>
29#include <RooExponential.h>
30#include <RooExtendPdf.h>
31#include <RooFFTConvPdf.h>
33#include <RooFitHS3/JSONIO.h>
34#include <RooFormulaVar.h>
35#include <RooGamma.h>
36#include <RooGaussian.h>
37#include <RooGenericPdf.h>
38#include <RooHistFunc.h>
39#include <RooHistPdf.h>
40#include <RooLandau.h>
41#include <RooLegacyExpPoly.h>
42#include <RooLognormal.h>
43#include <RooMultiVarGaussian.h>
45#include <RooAddition.h>
46#include <RooProduct.h>
47#include <RooProdPdf.h>
48#include <RooPoisson.h>
49#include <RooPolynomial.h>
50#include <RooPolyVar.h>
51#include <RooPowerSum.h>
52#include <RooProjectedPdf.h>
53#include <RooAbsRealLValue.h>
54#include <RooRealSumFunc.h>
55#include <RooRealSumPdf.h>
56#include <RooRealVar.h>
57#include <RooResolutionModel.h>
58#include <RooTFnBinding.h>
59#include <RooTruthModel.h>
60#include <RooGaussModel.h>
61#include <RooWrapperPdf.h>
62#include <RooRealIntegral.h>
63#include <RooSpline.h>
64#include <RooUniform.h>
65#include <TSpline.h>
66
67#include <TF1.h>
68
69#include "HS3Builder.h"
70#include "JSONIOUtils.h"
71
72#include <optional>
73#include <type_traits>
74#include <variant>
75
76#include <algorithm>
77#include <cctype>
78#include <memory>
79#include <initializer_list>
80#include <set>
81#include <string_view>
82#include <vector>
83
85
86namespace HS3 = RooFit::HS3;
87
88///////////////////////////////////////////////////////////////////////////////////////////////////////
89// individually implemented importers
90///////////////////////////////////////////////////////////////////////////////////////////////////////
91
92namespace {
93bool isReservedExpressionIdentifier(const std::string &arg)
94{
95 return arg == "PI" || arg == "EULER" || arg == "TMath";
96}
97
98bool isIdentifierChar(char c)
99{
100 return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
101}
102
103/**
104 * Extracts arguments from a mathematical expression.
105 *
106 * This function takes a string representing a mathematical
107 * expression and extracts the arguments from it. The arguments are
108 * the identifiers: sequences of letters, digits and underscores that
109 * start with a letter. Function calls such as "exp( ... )", identified
110 * as being followed by an opening parenthesis, are not treated as
111 * arguments, and neither are the reserved identifiers.
112 *
113 * @param expr A string representing a mathematical expression.
114 * @return A set of unique strings representing the extracted arguments.
115 */
116std::set<std::string> extractArguments(std::string expr)
117{
118 // Get rid of whitespaces
119 expr.erase(std::remove_if(expr.begin(), expr.end(), [](unsigned char c) { return std::isspace(c); }), expr.end());
120
121 std::set<std::string> arguments;
122 for (std::size_t i = 0; i < expr.size(); ++i) {
123 // A letter starts an identifier, unless it is part of a number in scientific notation, e.g. 2e-5.
124 if (!isalpha(expr[i]) || TFormula::IsScientificNotation(expr, i)) {
125 continue;
126 }
127 const std::size_t start = i;
128 while (i < expr.size() && isIdentifierChar(expr[i])) {
129 ++i;
130 }
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);
135 }
136 }
137 return arguments;
138}
139
140void replaceIdentifier(TString &expr, std::string_view identifier, std::string_view replacement)
141{
142 std::string in(expr.Data());
143 std::string out;
144 out.reserve(in.size());
145
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);
153 pos = end;
154 } else {
155 out.push_back(in[pos]);
156 ++pos;
157 }
158 }
159
160 expr = out.c_str();
161}
162
163std::string trimmed(std::string const &str)
164{
165 const auto begin = str.find_first_not_of(" \t\n");
166 if (begin == std::string::npos) {
167 return "";
168 }
169 return str.substr(begin, str.find_last_not_of(" \t\n") - begin + 1);
170}
171
172// Index of the bracket that closes the one at `open`, or std::string::npos if it is not closed.
173std::size_t findClosingBracket(std::string const &str, std::size_t open)
174{
175 int depth = 0;
176 for (std::size_t i = open; i < str.size(); ++i) {
177 if (str[i] == '(' || str[i] == '[') {
178 ++depth;
179 } else if ((str[i] == ')' || str[i] == ']') && --depth == 0) {
180 return i;
181 }
182 }
183 return std::string::npos;
184}
185
186// Index of the first of the characters `chars` in `str` from `start` on that is not enclosed in brackets, or
187// std::string::npos if there is none. The scope operator "::" is skipped: a ':' is the one of a ternary operator.
188std::size_t findTopLevel(std::string const &str, std::string_view chars, std::size_t start = 0)
189{
190 int depth = 0;
191 for (std::size_t i = start; i < str.size(); ++i) {
192 if (str[i] == '(' || str[i] == '[') {
193 ++depth;
194 } else if (str[i] == ')' || str[i] == ']') {
195 --depth;
196 } else if (str[i] == ':' && i + 1 < str.size() && str[i + 1] == ':') {
197 ++i;
198 } else if (depth == 0 && chars.find(str[i]) != std::string_view::npos) {
199 return i;
200 }
201 }
202 return std::string::npos;
203}
204
205// Split `str` at the commas that are not enclosed in brackets.
206std::vector<std::string> splitTopLevelCommas(std::string const &str)
207{
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));
212 start = comma + 1;
213 }
214 parts.push_back(str.substr(start));
215 return parts;
216}
217
218// Remove parentheses that enclose the whole string, e.g. "((a+b))" becomes "a+b".
219std::string stripEnclosingParentheses(std::string str)
220{
221 str = trimmed(str);
222 while (str.size() >= 2 && str.front() == '(' && findClosingBracket(str, 0) == str.size() - 1) {
223 str = trimmed(str.substr(1, str.size() - 2));
224 }
225 return str;
226}
227
228// Rewrite the HS3 conditional "ifelse(c,a,b)" into the C-style ternary "((c)?(a):(b))" that TFormula understands.
229// Malformed calls are left unchanged, so that TFormula reports them.
230std::string ifElseToTernary(std::string const &expr)
231{
232 static const std::string keyword = "ifelse";
233 std::string out;
234 std::size_t pos = 0;
235 while (pos < expr.size()) {
236 const std::size_t found = expr.find(keyword, pos);
237 if (found == std::string::npos) {
238 break;
239 }
240 const std::size_t open = expr.find_first_not_of(" \t", found + keyword.size());
241 const bool isCall =
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();
249 continue;
250 }
251 out += expr.substr(pos, found - pos);
252 out += "((" + ifElseToTernary(trimmed(args[0])) + ")?(" + ifElseToTernary(trimmed(args[1])) + "):(" +
253 ifElseToTernary(trimmed(args[2])) + "))";
254 pos = close + 1;
255 }
256 return out + expr.substr(pos);
257}
258
259void translateImportedExpression(TString &expr)
260{
261 replaceIdentifier(expr, "PI", "TMath::Pi()");
262 replaceIdentifier(expr, "EULER", "TMath::E()");
263 // The boolean literals, and the exact comparisons, which are the ones of TFormula.
264 replaceIdentifier(expr, "TRUE", "1");
265 replaceIdentifier(expr, "FALSE", "0");
266 expr.ReplaceAll("!==", "!=");
267 expr.ReplaceAll("===", "==");
268 expr = ifElseToTernary(expr.Data()).c_str();
269}
270
271// Give the formula the binnings of its "axes", which are read like the axes of binned data.
272template <class RooArg_t>
273void importFormulaBinnings(RooArg_t &arg, const JSONNode &node)
274{
275 if (!node.has_child("axes")) {
276 return;
277 }
278 const std::string context = "generic formula '" + std::string(arg.GetName()) + "'";
279 HS3::Diagnostics diagnostics;
280 const std::vector<HS3::BinnedAxis> axes = HS3::parseBinnedAxes(node["axes"], diagnostics);
281 HS3::report(diagnostics, std::string(arg.GetName()) + ".axes");
282
283 std::set<std::string> axisNames;
284 for (HS3::BinnedAxis const &axis : axes) {
285 if (!axisNames.insert(axis.name).second) {
286 RooJSONFactoryWSTool::error("duplicate axis '" + axis.name + "' in " + context);
287 }
288 if (!dynamic_cast<RooAbsRealLValue *>(arg.getParameter(axis.name.c_str()))) {
289 RooJSONFactoryWSTool::error("axis '" + axis.name + "' is not a real-valued formula variable of " + context);
290 }
291 auto const *regular = std::get_if<HS3::RegularBinning>(&axis.binning);
292 if (regular && (regular->nbins < 1 || !(axis.min < axis.max))) {
293 RooJSONFactoryWSTool::error("axis '" + axis.name + "' of " + context +
294 " needs a positive \"nbins\" and \"min\" smaller than \"max\"");
295 }
296 }
297 // The formula finds its variable by name, so the variables that are created for the axes can stand in for them.
299 for (auto *var : static_range_cast<RooRealVar *>(vars)) {
300 arg.setBinning(*var, var->getBinning(), /*checkFlatness=*/false);
301 }
302}
303
304template <class RooArg_t>
305void importFormulaArg(RooJSONFactoryWSTool *tool, const JSONNode &p)
306{
307 std::string name(RooJSONFactoryWSTool::name(p));
308 if (!p.has_child("expression")) {
309 RooJSONFactoryWSTool::error("no expression given for '" + name + "'");
310 }
311 TString formula(p["expression"].val());
312 translateImportedExpression(formula);
313 RooArgList dependents;
314 for (const auto &d : extractArguments(formula.Data())) {
315 RooAbsReal *dependent = tool->request<RooAbsReal>(d, name);
316 // HS3 0.3 (HS3 PR #154) only allows expressions to refer to parameters, variables and functions.
317 if (dynamic_cast<RooAbsPdf *>(dependent) && !(tool->hs3Version() < HS3::Version{0, 3})) {
318 RooJSONFactoryWSTool::error("the expression of '" + name + "' refers to the distribution '" + d +
319 "', which is not allowed in HS3");
320 }
321 dependents.add(*dependent);
322 }
323 RooArg_t arg{name.c_str(), formula, dependents};
324 importFormulaBinnings(arg, p);
325 tool->wsImport(arg);
326}
327
328void importProduct(RooJSONFactoryWSTool *tool, const JSONNode &p)
329{
330 std::string name(RooJSONFactoryWSTool::name(p));
331 tool->wsEmplace<RooProduct>(name, tool->requestArgList<RooAbsReal>(p, "factors"));
332}
333
334// RooLognormal has two parametrizations. In the standard one, its parameters are the mean "mu" and the width "sigma" of
335// log(x), like in the lognormal_dist of HS3. In the other one, which is the default of RooFit, they are the median m0
336// of x and the shape parameter k, with mu = log(m0) and sigma = log(k). Such a distribution is written with "mu" and
337// "sigma" naming the functions log(m0) and log(k), which are named after m0 and k with the suffix below. The suffix
338// is also how the parametrization is recognized when reading: the distribution is then created from m0 and k
339// themselves instead of the functions. Only lognormalLogName() and importLogNormal() know this convention, for
340// distributions on their own and for the components of array distributions alike.
341constexpr const char *lognormalLogSuffix = "_lognormal_log";
342
343// What a RooLognormal that is not in the standard parametrization writes as "mu" (for its median) or "sigma" (for its
344// shape parameter): the name of the function log(`param`). The function is written as well if there is a `tool`;
345// without one, only the name is given.
346std::string lognormalLogName(RooAbsReal const &param, RooJSONFactoryWSTool *tool)
347{
348 if (tool) {
349 return tool->exportTransformed(&param, lognormalLogSuffix, "log(%s)");
350 }
351 return transformedBaseName(param) + lognormalLogSuffix;
352}
353
354// Copy the value of a JSON node, keeping numbers and booleans as such.
355void copyValue(JSONNode &target, JSONNode const &source)
356{
357 if (source.is_number()) {
358 target << source.val_double();
359 return;
360 }
361 const std::string value = source.val();
362 if (value == "true" || value == "false") {
363 target << (value == "true");
364 } else {
365 target << value;
366 }
367}
368
369// An HS3 `array_dist` is a product of one-dimensional distributions of one type (`component_type`), each over its own
370// observable `x`. RooFit has no dedicated class for it: every component is imported as an individual pdf of the
371// component type, named after its observable, and a RooProdPdf with the attribute `arrayDistTag` that carries the
372// name of the array holds them together, so that the array can be written back as `array_dist`. HistFactory modifiers
373// that name an array as the constraint of a parameter pick their component out of it (see
374// JSONFactories_HistFactory.cxx).
375void importArrayDist(RooJSONFactoryWSTool *tool, const JSONNode &p)
376{
377 const std::string name = RooJSONFactoryWSTool::name(p);
378 auto error = [&name](std::string const &message) {
379 RooJSONFactoryWSTool::error("array_dist '" + name + "': " + message);
380 };
381
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\"");
386 }
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 "
391 "lognormal_dist");
392 }
393
394 const JSONNode *defaults = p.find("default_parameters");
395 if (defaults) {
396 if (!defaults->is_map()) {
397 error("\"default_parameters\" must be a struct");
398 }
399 if (defaults->has_child("x")) {
400 error("\"x\" must be given per component, not in \"default_parameters\"");
401 }
402 }
403 const JSONNode *components = p.find("components");
404 if (!components || !components->is_seq() || components->num_children() == 0) {
405 error("\"components\" must be a non-empty list");
406 }
407
408 RooWorkspace &ws = *tool->workspace();
409
410 // The components are imported through the importer of the component type, from a node per component that
411 // combines its own fields with the defaults.
413 JSONNode &nodes = tree->rootnode().set_seq();
414 std::vector<std::string> observables;
415 RooArgList pdfs;
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");
420 }
421 const JSONNode *xNode = component.find("x");
422 if (!xNode) {
423 error(context + " has no \"x\"");
424 }
425 if (xNode->is_number() || !xNode->has_val()) {
426 error(context + ": \"x\" must be the name of the observable");
427 }
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");
431 }
432 observables.push_back(x);
433
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");
438 }
439 JSONNode &node = nodes.append_child().set_map();
440 node["name"] << pdfName;
441 node["type"] << componentType;
442 if (defaults) {
443 for (JSONNode const &field : defaults->children()) {
444 copyValue(node[field.key()], field);
445 }
446 }
447 for (JSONNode const &field : component.children()) {
448 copyValue(node[field.key()], field);
449 }
450 tool->importFunction(node, true);
451 RooAbsPdf *pdf = ws.pdf(pdfName);
452 if (!pdf) {
453 error(context + " did not produce a distribution");
454 }
455 pdfs.add(*pdf);
456 }
457
458 // The parameters of a component must not depend on any observable of the array, otherwise the product would not
459 // be normalized.
460 for (std::size_t i = 0; i < observables.size(); ++i) {
461 RooAbsArg const *x = ws.arg(observables[i]);
462 if (!x) {
463 error("the observable '" + observables[i] + "' is not a parameter or function");
464 }
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));
469 }
470 }
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] + "'");
475 }
476 }
477 }
478
479 RooProdPdf array{name.c_str(), name.c_str(), pdfs};
480 array.setAttribute(arrayDistTag);
481 // The product only exists to hold the components together.
482 array.setAttribute(helperObjectTag);
483 tool->wsImport(array);
484}
485
486// A "combined_dist" is interpreted by the document. This reads one that doesn't come with a document.
487void importCombinedDist(RooJSONFactoryWSTool *tool, const JSONNode &p)
488{
489 HS3::Diagnostics diagnostics;
490 HS3::Distribution const dist = HS3::parseDistribution(p, diagnostics);
491 if (!HS3::hasErrors(diagnostics)) {
492 HS3::validateCombinedDist(std::get<HS3::CombinedDist>(dist.body), dist.name, diagnostics);
493 }
494 HS3::report(diagnostics, dist.name);
495 HS3::buildCombinedDist(*tool, dist.name, std::get<HS3::CombinedDist>(dist.body));
496}
497
498void importAddPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
499{
500 std::string name(RooJSONFactoryWSTool::name(p));
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;
503 const bool sinceHS3v03 = !(tool->hs3Version() < HS3::Version{0, 3});
504 if (p.has_child("extended")) {
505 // Check the explicit "extended" flag against the number of coefficients, which determines the extended mode of
506 // the RooAddPdf.
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) {
511 RooJSONFactoryWSTool::error("mixture_dist '" + name + "' is declared as extended, but it has " + counts +
512 ", which defines a non-extended mixture");
513 }
514 if (!extended && nCoefficients == 0 && nSummands > 0) {
515 RooJSONFactoryWSTool::error("mixture_dist '" + name + "' is declared as not extended, but it has " + counts +
516 ", which defines an extended mixture of extended distributions");
517 }
518 if (!extended && nCoefficients == nSummands && nSummands > 0) {
519 // A RooAddPdf with one coefficient per summand can always be extended. The non-extended mixture is the one
520 // with the normalized coefficients c_i / sum(c), of which the last one follows from the others.
521 RooArgList summands = tool->requestArgList<RooAbsPdf>(p, "summands");
522 RooArgList coefficients = tool->requestArgList<RooAbsReal>(p, "coefficients");
523 std::string sum;
524 for (std::size_t i = 0; i < nCoefficients; ++i) {
525 sum += (i == 0 ? "x[" : "+x[") + std::to_string(i) + "]";
526 }
528 for (std::size_t i = 0; i + 1 < nCoefficients; ++i) {
529 fractions.add(tool->wsEmplace<RooFormulaVar>(name + "_fraction_" + std::to_string(i),
530 ("x[" + std::to_string(i) + "]/(" + sum + ")").c_str(),
531 coefficients));
532 }
533 tool->wsEmplace<RooAddPdf>(name, summands, fractions);
534 return;
535 }
536 } else if (nCoefficients == nSummands && nSummands > 0 && sinceHS3v03) {
537 // HS3 0.3 requires the flag. Where it decides about the Poisson term, a document without it is invalid.
538 RooJSONFactoryWSTool::error("mixture_dist '" + name +
539 "' has one coefficient per summand, but no \"extended\" flag, which HS3 "
540 "requires to decide whether the mixture is extended");
541 }
542 if (nSummands > 0 && nCoefficients == 0 && sinceHS3v03) {
543 RooJSONFactoryWSTool::warning("RooFitHS3: mixture_dist '" + name +
544 "' has no coefficients, which HS3 0.3 doesn't define. It is read as the sum of "
545 "its extended summands.");
546 }
547 if (!tool->requestArgList<RooAbsReal>(p, "coefficients").empty()) {
548 tool->wsEmplace<RooAddPdf>(name, tool->requestArgList<RooAbsPdf>(p, "summands"),
549 tool->requestArgList<RooAbsReal>(p, "coefficients"));
550 } else {
551 tool->wsEmplace<RooAddPdf>(name, tool->requestArgList<RooAbsPdf>(p, "summands"));
552 }
553}
554
555void importAddModel(RooJSONFactoryWSTool *tool, const JSONNode &p)
556{
557 std::string name(RooJSONFactoryWSTool::name(p));
558 tool->wsEmplace<RooAddModel>(name, tool->requestArgList<RooAbsPdf>(p, "summands"),
559 tool->requestArgList<RooAbsReal>(p, "coefficients"));
560}
561
562template <bool DivideByBinWidth>
563void importBinWidthFunction(RooJSONFactoryWSTool *tool, const JSONNode &p)
564{
565 std::string name(RooJSONFactoryWSTool::name(p));
566 RooHistFunc *hf = dynamic_cast<RooHistFunc *>(tool->request<RooAbsReal>(p["histogram"].val(), name));
567 if (!hf) {
568 RooJSONFactoryWSTool::error("histogram '" + p["histogram"].val() + "' of '" + name + "' is not a RooHistFunc");
569 }
570 tool->wsEmplace<RooBinWidthFunction>(name, *hf, DivideByBinWidth);
571}
572
573void importBinSamplingPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
574{
575 std::string name(RooJSONFactoryWSTool::name(p));
576
577 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, "pdf");
578 RooRealVar *obs = tool->requestArg<RooRealVar>(p, "observable");
579
580 if (!pdf->dependsOn(*obs)) {
581 RooJSONFactoryWSTool::error(std::string("pdf '") + pdf->GetName() + "' does not depend on observable '" +
582 obs->GetName() + "' as indicated by parent RooBinSamplingPdf '" + name +
583 "', please check!");
584 }
585
586 if (!p.has_child("epsilon")) {
587 RooJSONFactoryWSTool::error("no epsilon given in '" + name + "'");
588 }
589 double epsilon(p["epsilon"].val_double());
590
591 tool->wsEmplace<RooBinSamplingPdf>(name, *obs, *pdf, epsilon);
592}
593
594void importRealSumPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
595{
596 std::string name(RooJSONFactoryWSTool::name(p));
597 RooArgList samples = tool->requestArgList<RooAbsReal>(p, "samples");
598 RooArgList coefs = tool->requestArgList<RooAbsReal>(p, "coefficients");
599 const bool extended = p.has_child("extended") && p["extended"].val_bool();
600 tool->wsEmplace<RooRealSumPdf>(name, samples, coefs, extended);
601}
602
603template <class RooArg_t>
604void importPolynomial(RooJSONFactoryWSTool *tool, const JSONNode &p)
605{
606 std::string name(RooJSONFactoryWSTool::name(p));
607 if (!p.has_child("coefficients")) {
608 RooJSONFactoryWSTool::error("no coefficients given in '" + name + "'");
609 }
610 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
611 RooArgList coefs;
612 int order = 0;
613 int lowestOrder = 0;
614 for (const auto &coef : p["coefficients"].children()) {
615 // As long as the coefficients match the default coefficients in
616 // RooFit, we don't have to instantiate RooFit objects but can
617 // increase the lowestOrder flag.
618 if (order == 0 && (coef.val() == "1.0" || coef.val() == "1")) {
619 ++lowestOrder;
620 } else if (coefs.empty() && (coef.val() == "0.0" || coef.val() == "0")) {
621 ++lowestOrder;
622 } else {
623 coefs.add(*tool->request<RooAbsReal>(coef.val(), name));
624 }
625 ++order;
626 }
627
628 tool->wsEmplace<RooArg_t>(name, *x, coefs, lowestOrder);
629}
630
631// HS3 0.3 distinguishes the discrete "poisson_dist" from the "poisson_continuous_dist" (HS3 #152), which are a
632// RooPoisson without and with noRounding. Before, ROOT wrote both as "poisson_dist" with its own key "integer", where
633// false denotes the continuous form. That key is read for documents before HS3 0.3, without it the discrete form is
634// meant. From HS3 0.3 on, it must not be present.
635template <bool Continuous>
636void importPoisson(RooJSONFactoryWSTool *tool, const JSONNode &p)
637{
638 std::string name(RooJSONFactoryWSTool::name(p));
639 bool noRounding = Continuous;
640 if (p.has_child("integer")) {
641 std::string const type = Continuous ? "poisson_continuous_dist" : "poisson_dist";
642 if (Continuous || !(tool->hs3Version() < HS3::Version{0, 3})) {
644 type + " '" + name +
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\".");
647 }
648 noRounding = !p["integer"].val_bool();
649 }
650 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
651 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
652 tool->wsEmplace<RooPoisson>(name, *x, *mean, noRounding);
653}
654
655void importDecay(RooJSONFactoryWSTool *tool, const JSONNode &p)
656{
657 std::string name(RooJSONFactoryWSTool::name(p));
658 RooRealVar *t = tool->requestArg<RooRealVar>(p, "t");
659 RooAbsReal *tau = tool->requestArg<RooAbsReal>(p, "tau");
660 // HS3 lists some resolution models as functions.
662 if (!model) {
663 RooJSONFactoryWSTool::error("resolutionModel of '" + name + "' is not a RooResolutionModel");
664 }
665 RooDecay::DecayType decayType = static_cast<RooDecay::DecayType>(p["decayType"].val_int());
666 tool->wsEmplace<RooDecay>(name, *t, *tau, *model, decayType);
667}
668
669void importRealIntegral(RooJSONFactoryWSTool *tool, const JSONNode &p)
670{
671 std::string name(RooJSONFactoryWSTool::name(p));
672 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "integrand");
673 auto vars = tool->requestArgList<RooAbsReal>(p, "variables");
674 RooArgSet normSet;
675 RooArgSet const *normSetPtr = nullptr;
676 if (p.has_child("normalization")) {
677 normSet.add(tool->requestArgSet<RooAbsReal>(p, "normalization"));
678 normSetPtr = &normSet;
679 }
680 JSONNode const *domain = p.find("domain");
681 // todo: at some point, take care of integrator configurations
682 tool->wsEmplace<RooRealIntegral>(name, *func, vars, normSetPtr, static_cast<RooNumIntConfig *>(nullptr),
683 domain ? domain->val().c_str() : nullptr);
684}
685
686void importDerivative(RooJSONFactoryWSTool *tool, const JSONNode &p)
687{
688 std::string name(RooJSONFactoryWSTool::name(p));
689 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "function");
690 RooRealVar *x = tool->requestArg<RooRealVar>(p, "x");
691 Int_t order = p["order"].val_int();
692 double eps = p["eps"].val_double();
693 RooArgSet normSet;
694 if (p.has_child("normalization")) {
695 normSet.add(tool->requestArgSet<RooAbsReal>(p, "normalization"));
696 }
697 tool->wsEmplace<RooDerivative>(name, *func, *x, normSet, order, eps);
698}
699
700void importFFTConvPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
701{
702 std::string name(RooJSONFactoryWSTool::name(p));
703 RooRealVar *convVar = tool->requestArg<RooRealVar>(p, "conv_var");
704 Int_t order = p["ipOrder"].val_int();
705 RooAbsPdf *pdf1 = tool->requestArg<RooAbsPdf>(p, "pdf1");
706 RooAbsPdf *pdf2 = tool->requestArg<RooAbsPdf>(p, "pdf2");
707 if (p.has_child("conv_func")) {
708 RooAbsReal *convFunc = tool->requestArg<RooAbsReal>(p, "conv_func");
709 tool->wsEmplace<RooFFTConvPdf>(name, *convFunc, *convVar, *pdf1, *pdf2, order);
710 } else {
711 tool->wsEmplace<RooFFTConvPdf>(name, *convVar, *pdf1, *pdf2, order);
712 }
713}
714
715void importExtendPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
716{
717 std::string name(RooJSONFactoryWSTool::name(p));
718 // HS3 calls the fields "dist" and "rate". RooFit used to write "pdf" and "norm", which are still accepted.
719 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, p.has_child("pdf") && !p.has_child("dist") ? "pdf" : "dist");
720 RooAbsReal *norm = tool->requestArg<RooAbsReal>(p, p.has_child("norm") && !p.has_child("rate") ? "norm" : "rate");
721 JSONNode const *range = p.find("range");
722 tool->wsEmplace<RooExtendPdf>(name, *pdf, *norm, range ? range->val().c_str() : nullptr);
723}
724
725// HS3 0.3 calls the location parameter of the Landau distribution "mu", since it is neither the mean nor the most
726// probable value. Documents before 0.3 used "mean", which is still read.
727void importLandau(RooJSONFactoryWSTool *tool, const JSONNode &p)
728{
729 const std::string name(RooJSONFactoryWSTool::name(p));
730 const bool legacyKey = !p.has_child("mu") && p.has_child("mean");
731 if (legacyKey && !(tool->hs3Version() < HS3::Version{0, 3})) {
732 RooJSONFactoryWSTool::warning("RooFitHS3: the landau_dist '" + name +
733 "' uses the key \"mean\", which HS3 0.3 renamed to \"mu\".");
734 }
735 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
736 RooAbsReal *mu = tool->requestArg<RooAbsReal>(p, legacyKey ? "mean" : "mu");
737 RooAbsReal *sigma = tool->requestArg<RooAbsReal>(p, "sigma");
738 tool->wsEmplace<RooLandau>(name, *x, *mu, *sigma);
739}
740
741void importLogNormal(RooJSONFactoryWSTool *tool, const JSONNode &p)
742{
743 std::string name(RooJSONFactoryWSTool::name(p));
744 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
745
746 // Same mechanism to undo the parameter transformation as in the
747 // importExponential() function (see comments in that function for more info).
748 const std::string mu = p["mu"].val();
749 const std::string sigma = p["sigma"].val();
750 const bool isStandard = !endsWith(mu, lognormalLogSuffix);
751 RooAbsReal *median = tool->request<RooAbsReal>(isStandard ? mu : transformedOriginal(mu, lognormalLogSuffix), name);
752 RooAbsReal *shape =
753 tool->request<RooAbsReal>(isStandard ? sigma : transformedOriginal(sigma, lognormalLogSuffix), name);
754
755 tool->wsEmplace<RooLognormal>(name, *x, *median, *shape, isStandard);
756}
757
758void importExponential(RooJSONFactoryWSTool *tool, const JSONNode &p)
759{
760 std::string name(RooJSONFactoryWSTool::name(p));
761 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
762
763 // If the parameter name ends with the "_exponential_inverted" suffix,
764 // this means that it was exported from a RooFit object where the
765 // parameter first needed to be transformed on export to match the HS3
766 // specification. But when re-importing such a parameter, we can simply
767 // skip the transformation and use the original RooFit parameter without
768 // the suffix.
769 //
770 // A concrete example: take the following RooFit pdf in the factory language:
771 //
772 // "Exponential::exponential_1(x[0, 10], c[-0.1])"
773 //
774 // It defines en exponential exp(c * x). However, in HS3 the exponential
775 // is defined as exp(-c * x), to RooFit would export these dictionaries
776 // to the JSON:
777 //
778 // {
779 // "name": "exponential_1", // HS3 exponential_dist with transformed parameter
780 // "type": "exponential_dist",
781 // "x": "x",
782 // "c": "c_exponential_inverted"
783 // },
784 // {
785 // "name": "c_exponential_inverted", // transformation function created on-the-fly on export
786 // "type": "generic",
787 // "expression": "-c"
788 // }
789 //
790 // On import, we can directly take the non-transformed parameter, which is
791 // we check for the suffix and optionally remove it from the requested
792 // name next:
793
794 const std::string constParamName = p["c"].val();
795 const bool isInverted = endsWith(constParamName, "_exponential_inverted");
796 RooAbsReal *c = tool->request<RooAbsReal>(
797 isInverted ? transformedOriginal(constParamName, "_exponential_inverted") : constParamName, name);
798
799 tool->wsEmplace<RooExponential>(name, *x, *c, !isInverted);
800}
801
802void importMultiVarGaussian(RooJSONFactoryWSTool *tool, const JSONNode &p)
803{
804 std::string name(RooJSONFactoryWSTool::name(p));
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) {
808 RooJSONFactoryWSTool::error("no covariances or correlations+standard_deviations given in '" + name + "'");
809 }
810 // The covariances are given directly, or as correlations that are scaled with the standard deviations.
811 const std::string key = hasCov ? "covariances" : "correlations";
812 std::vector<double> sigmas;
813 if (hasCov) {
814 sigmas.assign(p[key].num_children(), 1.0);
815 } else {
816 sigmas << p["standard_deviations"];
817 }
818 const std::size_t n = sigmas.size();
819 // The matrix must be square, otherwise the entries would be written out of bounds.
820 if (p[key].num_children() != n) {
821 RooJSONFactoryWSTool::error("\"" + key + "\" in '" + name + "' must have " + std::to_string(n) + " rows");
822 }
823 TMatrixDSym covmat;
824 covmat.ResizeTo(n, n);
825 int i = 0;
826 for (const auto &row : p[key].children()) {
827 if (!row.is_seq() || row.num_children() != n) {
828 RooJSONFactoryWSTool::error("\"" + key + "\" in '" + name + "' must be a square matrix");
829 }
830 int j = 0;
831 for (const auto &val : row.children()) {
832 covmat(i, j) = val.val_double() * sigmas[i] * sigmas[j];
833 ++j;
834 }
835 ++i;
836 }
838 tool->requestArgList<RooAbsReal>(p, "mean"), covmat);
839}
840
841/// Read the binning variables from the "axes" node, ordered like in `varList`.
842RooArgList readBinning(const JSONNode &topNode, const RooArgList &varList)
843{
845 RooArgList vars;
846 for (RooAbsArg *refVar : varList) {
847 if (RooAbsArg *axis = axes.find(*refVar)) {
848 vars.addClone(*axis);
849 }
850 }
851 return vars;
852}
853
854bool importParamHistFunc(RooJSONFactoryWSTool *tool, const JSONNode &p)
855{
856 if (!p.has_child("parameters")) {
857 return false;
858 }
859 std::string name(RooJSONFactoryWSTool::name(p));
860 RooArgList varList = tool->requestArgList<RooRealVar>(p, "variables");
861 const bool hasAxes = p.has_child("axes");
862 if (!hasAxes) {
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");
867 }
868 RooArgList binning = hasAxes ? readBinning(p, varList) : varList;
869 checkParamHistFuncOrderIsDefined(tool->hs3Version(), binning, "the ParamHistFunc '" + name + "'");
870 // The parameters are given in the order of HS3 (last axis fastest); ParamHistFunc expects TH1 order.
871 tool->wsEmplace<ParamHistFunc>(name, binning,
872 toParamHistFuncOrder(tool->requestArgList<RooAbsReal>(p, "parameters"), binning));
873 return true;
874}
875
876void importSpline(RooJSONFactoryWSTool *tool, const JSONNode &p)
877{
878 const std::string name(RooJSONFactoryWSTool::name(p));
879 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
880 if (!p.has_child("x0") || !p.has_child("y0")) {
881 RooJSONFactoryWSTool::error("no x0/y0 given in '" + name + "'");
882 }
883
884 // The optional fields have the defaults of RooSpline.
885 const std::string algo = p.has_child("interpolation") ? p["interpolation"].val() : "poly3";
886 if (algo != "poly3" && algo != "poly5") {
887 RooJSONFactoryWSTool::error("unsupported algo '" + algo + "' for RooSpline in '" + name +
888 "': allowed are 'poly3' and 'poly5'");
889 }
890 const bool logx = p.has_child("logx") && p["logx"].val_bool();
891 const bool logy = p.has_child("logy") && p["logy"].val_bool();
892
893 std::vector<double> x0;
894 std::vector<double> y0;
895 x0 << p["x0"];
896 y0 << p["y0"];
897
898 if (x0.size() != y0.size()) {
899 RooJSONFactoryWSTool::error("x0/y0 size mismatch in '" + name + "': x0 has " + std::to_string(x0.size()) +
900 ", y0 has " + std::to_string(y0.size()));
901 }
902 if (x0.size() < 2) {
903 RooJSONFactoryWSTool::error("need at least 2 knots in '" + name + "'");
904 }
905
906 tool->wsEmplace<::RooSpline>(name.c_str(), *x, x0, y0, algo == "poly5" ? 5 : 3, logx, logy);
907}
908
909void importBernstein(RooJSONFactoryWSTool *tool, const JSONNode &p)
910{
911 std::string name(RooJSONFactoryWSTool::name(p));
912 auto *x = dynamic_cast<RooAbsRealLValue *>(tool->requestArg<RooAbsReal>(p, "x"));
913 if (!x) {
914 RooJSONFactoryWSTool::error("\"x\" of '" + name + "' is not a variable");
915 }
916 tool->wsEmplace<RooBernstein>(name, *x, tool->requestArgList<RooAbsReal>(p, "coefficients"));
917}
918
919void importGaussian(RooJSONFactoryWSTool *tool, const JSONNode &p)
920{
921 std::string name(RooJSONFactoryWSTool::name(p));
922 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
923 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
924 RooAbsReal *sigma = tool->requestArg<RooAbsReal>(p, "sigma");
925 tool->wsEmplace<RooGaussian>(name, *x, *mean, *sigma);
926}
927
928void importUniform(RooJSONFactoryWSTool *tool, const JSONNode &p)
929{
930 std::string name(RooJSONFactoryWSTool::name(p));
931 // A single observable may also be given by its name.
932 if (p.has_child("x") && !p["x"].is_seq()) {
933 tool->wsEmplace<RooUniform>(name, RooArgSet{*tool->requestArg<RooAbsReal>(p, "x")});
934 } else {
935 tool->wsEmplace<RooUniform>(name, tool->requestArgSet<RooAbsReal>(p, "x"));
936 }
937}
938
939namespace CrystalBall {
940
941// The keys of the tails of the double-sided Crystal Ball.
942const std::initializer_list<const char *> tailKeys = {"alpha_L", "n_L", "alpha_R", "n_R"};
943
944bool hasAny(const JSONNode &p, std::initializer_list<const char *> keys)
945{
946 return std::any_of(keys.begin(), keys.end(), [&p](const char *key) { return p.has_child(key); });
947}
948
949bool hasDoubleSidedKeys(const JSONNode &p)
950{
951 return hasAny(p, tailKeys) || hasAny(p, {"sigma_L", "sigma_R"});
952}
953
954// Create a RooCrystalBall with two tails. With `symmetricShorthand`, the tails may also be given as "alpha" and "n"
955// for both sides, as in the "crystalball_dist" of HS3 versions before 0.3.
956void importDoubleSided(RooJSONFactoryWSTool *tool, const JSONNode &p, std::string const &type, bool symmetricShorthand)
957{
958 const std::string name(RooJSONFactoryWSTool::name(p));
959 const std::string context = type + " '" + name + "'";
960
961 const bool asymmetricTails = hasAny(p, tailKeys);
962 const bool symmetricTails = hasAny(p, {"alpha", "n"});
963 if (symmetricTails && !symmetricShorthand) {
964 RooJSONFactoryWSTool::error(context + " must not have \"alpha\" or \"n\", the tails are given by \"alpha_L\", " +
965 "\"n_L\", \"alpha_R\" and \"n_R\"");
966 }
967 if (symmetricTails && asymmetricTails) {
969 " must not combine \"alpha\"/\"n\" with \"alpha_L\"/\"n_L\"/\"alpha_R\"/\"n_R\"");
970 }
971 if (asymmetricTails || !symmetricTails) {
972 for (const char *key : tailKeys) {
973 if (!p.has_child(key)) {
974 RooJSONFactoryWSTool::error(context + " is missing \"" + key +
975 "\": \"alpha_L\", \"n_L\", \"alpha_R\" and \"n_R\" are all required");
976 }
977 }
978 } else if (!p.has_child("alpha") || !p.has_child("n")) {
979 RooJSONFactoryWSTool::error(context + " needs both \"alpha\" and \"n\"");
980 }
981
982 const bool asymmetricWidths = hasAny(p, {"sigma_L", "sigma_R"});
983 if (asymmetricWidths && p.has_child("sigma")) {
984 RooJSONFactoryWSTool::error(context + " must not combine \"sigma\" with \"sigma_L\"/\"sigma_R\"");
985 }
986 if (asymmetricWidths && !(p.has_child("sigma_L") && p.has_child("sigma_R"))) {
987 RooJSONFactoryWSTool::error(context + " needs both \"sigma_L\" and \"sigma_R\"");
988 }
989 if (!asymmetricWidths && !p.has_child("sigma")) {
990 RooJSONFactoryWSTool::error(context + " needs either \"sigma\" or both \"sigma_L\" and \"sigma_R\"");
991 }
992
993 RooAbsReal *m = tool->requestArg<RooAbsReal>(p, "m");
994 RooAbsReal *m0 = tool->requestArg<RooAbsReal>(p, "m0");
995 RooAbsReal *sigmaL = tool->requestArg<RooAbsReal>(p, asymmetricWidths ? "sigma_L" : "sigma");
996 RooAbsReal *sigmaR = tool->requestArg<RooAbsReal>(p, asymmetricWidths ? "sigma_R" : "sigma");
997 RooAbsReal *alphaL = tool->requestArg<RooAbsReal>(p, symmetricTails ? "alpha" : "alpha_L");
998 RooAbsReal *nL = tool->requestArg<RooAbsReal>(p, symmetricTails ? "n" : "n_L");
999 RooAbsReal *alphaR = tool->requestArg<RooAbsReal>(p, symmetricTails ? "alpha" : "alpha_R");
1000 RooAbsReal *nR = tool->requestArg<RooAbsReal>(p, symmetricTails ? "n" : "n_R");
1001 tool->wsEmplace<RooCrystalBall>(name, *m, *m0, *sigmaL, *sigmaR, *alphaL, *nL, *alphaR, *nR);
1002}
1003
1004} // namespace CrystalBall
1005
1006// "crystalball_dist" is the single-sided Crystal Ball (RooCBShape). Before HS3 0.3, it was also the double-sided
1007// Crystal Ball, recognizable by the "_L"/"_R" fields. Such documents are still read by this importer, with a
1008// deprecation warning. It declines the single-sided Crystal Ball.
1009bool importLegacyDoubleSidedCrystalBall(RooJSONFactoryWSTool *tool, const JSONNode &p)
1010{
1011 if (!CrystalBall::hasDoubleSidedKeys(p)) {
1012 return false;
1013 }
1014 static bool warned = false;
1015 if (!warned) {
1016 RooJSONFactoryWSTool::warning("RooFitHS3: \"crystalball_dist\" with the fields \"alpha_L\", \"n_L\", "
1017 "\"alpha_R\", \"n_R\", \"sigma_L\" or \"sigma_R\" is deprecated, please use "
1018 "\"crystalball_doublesided_dist\" for the double-sided Crystal Ball.");
1019 warned = true;
1020 }
1021 CrystalBall::importDoubleSided(tool, p, "crystalball_dist", /*symmetricShorthand=*/true);
1022 return true;
1023}
1024
1025void importCrystalBallDoubleSided(RooJSONFactoryWSTool *tool, const JSONNode &p)
1026{
1027 CrystalBall::importDoubleSided(tool, p, "crystalball_doublesided_dist", /*symmetricShorthand=*/false);
1028}
1029
1030///////////////////////////////////////////////////////////////////////////////////////////////////////
1031// specialized exporter implementations
1032///////////////////////////////////////////////////////////////////////////////////////////////////////
1033
1034// A RooCrystalBall with one tail is the single-sided "crystalball_dist" (read back as RooCBShape, which follows the
1035// same convention for the sign of alpha). With two tails, it is a "crystalball_doublesided_dist", whose tails are
1036// always written as "alpha_L"/"n_L"/"alpha_R"/"n_R": there is no shorthand for symmetric tails.
1037void exportCrystalBall(RooJSONFactoryWSTool *, RooCrystalBall const &pdf, JSONNode &elem)
1038{
1039 writeReference(elem["m"], pdf.x());
1040 writeReference(elem["m0"], pdf.x0());
1041 if (!pdf.alphaR() || !pdf.nR()) {
1042 elem["type"] << "crystalball_dist";
1043 writeReference(elem["sigma"], pdf.sigmaL());
1044 writeReference(elem["alpha"], pdf.alphaL());
1045 writeReference(elem["n"], pdf.nL());
1046 return;
1047 }
1048 if (&pdf.sigmaL() == &pdf.sigmaR()) {
1049 writeReference(elem["sigma"], pdf.sigmaL());
1050 } else {
1051 writeReference(elem["sigma_L"], pdf.sigmaL());
1052 writeReference(elem["sigma_R"], pdf.sigmaR());
1053 }
1054 writeReference(elem["alpha_L"], pdf.alphaL());
1055 writeReference(elem["n_L"], pdf.nL());
1056 writeReference(elem["alpha_R"], *pdf.alphaR());
1057 writeReference(elem["n_R"], *pdf.nR());
1058}
1059
1060template <class RooArg_t>
1061void exportAddPdf(RooJSONFactoryWSTool *, RooArg_t const &pdf, JSONNode &elem)
1062{
1063 RooJSONFactoryWSTool::fillSeq(elem["summands"], pdf.pdfList());
1064 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf.coefList());
1065 elem["extended"] << (pdf.extendMode() != RooArg_t::CanNotBeExtended);
1066 // A RooAddModel is written as a mixture_model, which is not part of HS3.
1067 if (pdf.coefList().empty() && std::is_same_v<RooArg_t, RooAddPdf>) {
1068 RooJSONFactoryWSTool::warning("RooFitHS3: the RooAddPdf '" + std::string(pdf.GetName()) +
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.");
1071 }
1072}
1073
1074void exportRealSumPdf(RooJSONFactoryWSTool *, RooRealSumPdf const &pdf, JSONNode &elem)
1075{
1076 RooJSONFactoryWSTool::fillSeq(elem["samples"], pdf.funcList());
1077 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf.coefList());
1078 elem["extended"] << (pdf.extendMode() != RooAbsPdf::CanNotBeExtended);
1079}
1080
1081template <class RooArg_t>
1082void exportHist(RooJSONFactoryWSTool *tool, RooArg_t const &hf, JSONNode &elem)
1083{
1084 RooDataHist const &dh = hf.dataHist();
1085 // The axes are named after the observables of the function, which are not necessarily the variables of the
1086 // histogram.
1087 auto vars = histogramVariablesNamedAfterObservables(dh, hf.getHistObsList(), hf.variables());
1088 tool->exportHisto(*vars, dh.numEntries(), dh.weightArray(), elem["data"].set_map());
1089}
1090
1091template <class RooArg_t>
1092bool importHist(RooJSONFactoryWSTool *tool, const JSONNode &p)
1093{
1094 std::string name(RooJSONFactoryWSTool::name(p));
1095 if (!p.has_child("data")) {
1096 return false;
1097 }
1098 std::unique_ptr<RooDataHist> dataHist =
1100 tool->wsEmplace<RooArg_t>(name, *dataHist->get(), *dataHist);
1101 return true;
1102}
1103
1104void exportBinSamplingPdf(RooJSONFactoryWSTool *, RooBinSamplingPdf const &pdf, JSONNode &elem)
1105{
1106 elem["pdf"] << pdf.pdf().GetName();
1107 elem["observable"] << pdf.observable().GetName();
1108 elem["epsilon"] << pdf.epsilon();
1109}
1110
1111void exportBinWidthFunction(RooJSONFactoryWSTool *, RooBinWidthFunction const &pdf, JSONNode &elem)
1112{
1113 // It is registered for "binvolume".
1114 if (pdf.divideByBinWidth()) {
1115 elem["type"] << "inverse_binvolume";
1116 }
1117 elem["histogram"] << pdf.histFunc().GetName();
1118}
1119
1120void cleanExpression(TString &expr)
1121{
1122 // Plain substring replacement would also hit longer identifiers that
1123 // share a prefix (e.g. "TMath::Tan" in "TMath::TanH", or "TMath::Pi" in
1124 // "TMath::PiOver2"), corrupting the exported expression. Identifiers
1125 // without a replacement are kept as-is.
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");
1150}
1151
1152std::optional<std::string> ternariesToIfElse(std::string const &in);
1153
1154// Rewrite one comma-free part of an expression, see ternariesToIfElse().
1155std::optional<std::string> ternaryPartToIfElse(std::string const &in)
1156{
1157 // Find the first '?' that is not enclosed in brackets. A ':' can only follow a '?', and a part has no commas.
1158 const std::size_t question = findTopLevel(in, "?:,");
1159 if (question != std::string::npos && in[question] != '?') {
1160 return std::nullopt;
1161 }
1162
1163 if (question == std::string::npos) {
1164 // No ternary on this level: copy the expression and rewrite the ternaries inside of brackets.
1165 std::string out;
1166 for (std::size_t i = 0; i < in.size(); ++i) {
1167 if (in[i] == ')' || in[i] == ']') {
1168 return std::nullopt;
1169 }
1170 if (in[i] != '(' && in[i] != '[') {
1171 out += in[i];
1172 continue;
1173 }
1174 const std::size_t close = findClosingBracket(in, i);
1175 if (close == std::string::npos) {
1176 return std::nullopt;
1177 }
1178 const std::string inner = in.substr(i + 1, close - i - 1);
1179 const std::optional<std::string> innerOut = ternariesToIfElse(inner);
1180 if (!innerOut) {
1181 return std::nullopt;
1182 }
1183 // Parentheses that only group a ternary are redundant around the ifelse() function call.
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) {
1188 out += *innerOut;
1189 } else {
1190 out += in[i] + *innerOut + in[close];
1191 }
1192 i = close;
1193 }
1194 return out;
1195 }
1196
1197 // Find the ':' that belongs to this '?': a nested '?' comes with a ':' of its own, which is skipped.
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;
1203 }
1204 nQuestions += in[colon] == '?' ? 1 : -1;
1205 }
1206
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;
1212 }
1213 return "ifelse(" + *condition + "," + *ifTrue + "," + *ifFalse + ")";
1214}
1215
1216// Rewrite the C-style ternaries "c ? a : b" in a TFormula expression into the HS3 conditional "ifelse(c,a,b)". Returns
1217// std::nullopt if this is not safely possible, e.g. because of unbalanced brackets.
1218std::optional<std::string> ternariesToIfElse(std::string const &in)
1219{
1220 std::string out;
1221 bool first = true;
1222 for (std::string const &part : splitTopLevelCommas(in)) {
1223 const std::optional<std::string> partOut = ternaryPartToIfElse(part);
1224 if (!partOut) {
1225 return std::nullopt;
1226 }
1227 out += (first ? "" : ",") + *partOut;
1228 first = false;
1229 }
1230 return out;
1231}
1232
1233// HS3 0.3 (HS3 PR #154) only allows expressions to refer to parameters, variables and functions.
1234void checkExpressionRefersToNoPdf(RooAbsArg const &formula, RooAbsCollection const &dependents)
1235{
1236 for (RooAbsArg const *dependent : dependents) {
1237 if (dynamic_cast<RooAbsPdf const *>(dependent)) {
1238 RooJSONFactoryWSTool::error(std::string("the expression of '") + formula.GetName() + "' refers to the pdf '" +
1239 dependent->GetName() + "', which HS3 doesn't allow");
1240 }
1241 }
1242}
1243
1244template <class RooArg_t>
1245void exportFormulaArg(RooJSONFactoryWSTool *, RooArg_t const &pdf, JSONNode &elem)
1246{
1247 checkExpressionRefersToNoPdf(pdf, pdf.dependents());
1248 TString expression(pdf.expression());
1249 cleanExpression(expression);
1250 // If the tokens follow the "x[#]" convention, the square braces enclosing each number
1251 // ensures that there is a unique mapping between the token and parameter name
1252 // If the tokens follow the "@#" convention, the numbers are not enclosed by braces.
1253 // So there may be tokens with numbers whose lower place value forms a subset string of ones with a higher place
1254 // value, e.g. "@1" is a subset of "@10". So the names of these parameters must be applied descending from the
1255 // highest place value in order to ensure each parameter name is uniquely applied to its token.
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());
1260 }
1261 if (expression.Contains("?")) {
1262 if (const auto rewritten = ternariesToIfElse(expression.Data())) {
1263 expression = rewritten->c_str();
1264 } else {
1265 RooJSONFactoryWSTool::warning(std::string("RooFitHS3: could not translate the ternary operators in the "
1266 "expression of '") +
1267 pdf.GetName() + "' to ifelse(), exporting the expression unchanged.");
1268 }
1269 }
1270 elem["expression"] << expression.Data();
1271
1272 for (const RooAbsArg *dependent : pdf.dependents()) {
1273 auto const *observable = dynamic_cast<const RooAbsRealLValue *>(dependent);
1274 if (!observable) {
1275 continue;
1276 }
1277 const RooAbsBinning *binning = pdf.getBinning(*observable);
1278 if (!binning) {
1279 continue;
1280 }
1281
1282 HS3::writeAxis(elem["axes"].set_seq().append_child(), HS3::toBinnedAxis(observable->GetName(), *binning));
1283 }
1284}
1285
1286// Write the "x" reference and the coefficient list for polynomial-like
1287// pdfs/funcs, including the implicit defaults below "lowestOrder" so that the
1288// output is self-documenting.
1289template <class RooArg_t>
1290void exportPolynomial(RooJSONFactoryWSTool *, RooArg_t const &pdf, JSONNode &elem)
1291{
1292 elem["x"] << pdf.x().GetName();
1293 auto &coefs = elem["coefficients"].set_seq();
1294 for (int i = 0; i < pdf.lowestOrder(); ++i) {
1295 coefs.append_child() << (i == 0 ? 1.0 : 0.0);
1296 }
1297 for (const auto &coef : pdf.coefList()) {
1298 writeReference(coefs.append_child(), *coef);
1299 }
1300}
1301
1302void exportPoisson(RooJSONFactoryWSTool *, RooPoisson const &pdf, JSONNode &elem)
1303{
1304 // It is registered for "poisson_dist", the discrete Poisson distribution.
1305 if (pdf.getNoRounding()) {
1306 elem["type"] << "poisson_continuous_dist";
1307 }
1308 writeReference(elem["x"], pdf.getX());
1309 writeReference(elem["mean"], pdf.getMean());
1310}
1311
1312// The RooDecay servers are the internal resModel-times-basis convolutions,
1313// which are implementation details that should not leak into the JSON. We
1314// only export the actual dependents (t, tau and the original resolution
1315// model) explicitly.
1316void exportDecay(RooJSONFactoryWSTool *tool, RooDecay const &pdf, JSONNode &elem)
1317{
1318 elem["t"] << pdf.getT().GetName();
1319 writeReference(elem["tau"], pdf.getTau());
1320 elem["resolutionModel"] << pdf.getModel().GetName();
1321 elem["decayType"] << pdf.getDecayType();
1322
1323 tool->queueExport(pdf.getT());
1324 tool->queueExport(pdf.getTau());
1325 tool->queueExport(pdf.getModel());
1326}
1327
1328// A Gaussian constraint whose recorded observable (see RooJSONFactoryWSTool::setConstraintObservable()) is its
1329// mean is written with x and mean swapped, so that the observable is x.
1330void exportGaussian(RooJSONFactoryWSTool *tool, RooGaussian const &gauss, JSONNode &elem)
1331{
1332 std::string const *observable = tool->constraintObservable(gauss.GetName());
1333 const bool swap = observable && *observable == gauss.getMean().GetName() && !isLiteralConstVar(gauss.getMean());
1334 writeReference(elem["x"], swap ? gauss.getMean() : gauss.getX());
1335 writeReference(elem["mean"], swap ? gauss.getX() : gauss.getMean());
1336 writeReference(elem["sigma"], gauss.getSigma());
1337}
1338
1339void exportLogNormal(RooJSONFactoryWSTool *tool, RooLognormal const &pdf, JSONNode &elem)
1340{
1341 writeReference(elem["x"], pdf.getX());
1342
1343 auto &m0 = pdf.getMedian();
1344 auto &k = pdf.getShapeK();
1345
1346 if (pdf.useStandardParametrization()) {
1347 writeReference(elem["mu"], m0);
1348 writeReference(elem["sigma"], k);
1349 } else {
1350 elem["mu"] << lognormalLogName(m0, tool);
1351 elem["sigma"] << lognormalLogName(k, tool);
1352 }
1353}
1354
1355void exportExponential(RooJSONFactoryWSTool *tool, RooExponential const &pdf, JSONNode &elem)
1356{
1357 elem["x"] << pdf.variable().GetName();
1358 auto &c = pdf.coefficient();
1359 if (pdf.negateCoefficient()) {
1360 writeReference(elem["c"], c);
1361 } else {
1362 elem["c"] << tool->exportTransformed(&c, "_exponential_inverted", "-%s");
1363 }
1364}
1365
1366void exportMultiVarGaussian(RooJSONFactoryWSTool *, RooMultiVarGaussian const &pdf, JSONNode &elem)
1367{
1368 RooJSONFactoryWSTool::fillSeq(elem["x"], pdf.xVec());
1369 RooJSONFactoryWSTool::fillSeq(elem["mean"], pdf.muVec());
1370 elem["covariances"].fill_mat(pdf.covarianceMatrix());
1371}
1372
1373void exportTFnBinding(RooJSONFactoryWSTool *, RooTFnBinding const &pdf, JSONNode &elem)
1374{
1375 checkExpressionRefersToNoPdf(pdf, pdf.observables());
1376 checkExpressionRefersToNoPdf(pdf, pdf.parameters());
1377 TString formula(pdf.function().GetExpFormula());
1378 formula.ReplaceAll("x", pdf.observables()[0].GetName());
1379 formula.ReplaceAll("y", pdf.observables()[1].GetName());
1380 formula.ReplaceAll("z", pdf.observables()[2].GetName());
1381 for (size_t i = 0; i < pdf.parameters().size(); ++i) {
1382 TString pname(TString::Format("[%d]", (int)i));
1383 formula.ReplaceAll(pname, pdf.parameters()[i].GetName());
1384 }
1385 elem["expression"] << formula.Data();
1386}
1387
1388void exportDerivative(RooJSONFactoryWSTool *, RooDerivative const &pdf, JSONNode &elem)
1389{
1390 elem["x"] << pdf.getX().GetName();
1391 elem["function"] << pdf.getFunc().GetName();
1392 if (!pdf.getNset().empty()) {
1393 RooJSONFactoryWSTool::fillSeq(elem["normalization"], pdf.getNset());
1394 }
1395 elem["order"] << pdf.order();
1396 elem["eps"] << pdf.eps();
1397}
1398
1399void exportRealIntegral(RooJSONFactoryWSTool *, RooRealIntegral const &integral, JSONNode &elem)
1400{
1401 std::string integrand = integral.integrand().GetName();
1402 elem["integrand"] << integrand;
1403 if (integral.intRange()) {
1404 elem["domain"] << integral.intRange();
1405 }
1406 RooJSONFactoryWSTool::fillSeq(elem["variables"], integral.intVars());
1407 if (RooArgSet const *funcNormSet = integral.funcNormSet()) {
1408 RooJSONFactoryWSTool::fillSeq(elem["normalization"], *funcNormSet);
1409 }
1410}
1411
1412void exportFFTConvPdf(RooJSONFactoryWSTool *, RooFFTConvPdf const &pdf, JSONNode &elem)
1413{
1414 if (auto convFunc = pdf.getPdfConvVar()) {
1415 elem["conv_func"] << convFunc->GetName();
1416 }
1417 elem["conv_var"] << pdf.getConvVar().GetName();
1418 elem["pdf1"] << pdf.getPdf1().GetName();
1419 elem["pdf2"] << pdf.getPdf2().GetName();
1420 elem["ipOrder"] << pdf.getInterpolationOrder();
1421}
1422
1423void exportExtendPdf(RooJSONFactoryWSTool *, RooExtendPdf const &pdf, JSONNode &elem)
1424{
1425 if (auto rangeName = pdf.getRangeName()) {
1426 elem["range"] << rangeName->GetName();
1427 }
1428 elem["dist"] << pdf.pdf().GetName();
1429 writeReference(elem["rate"], pdf.getN());
1430}
1431
1432void exportParamHistFunc(RooJSONFactoryWSTool *, ParamHistFunc const &pdf, JSONNode &elem)
1433{
1434 RooJSONFactoryWSTool::fillSeq(elem["variables"], pdf.dataVars());
1435 // One parameter per bin, in the order of HS3 (last axis fastest), not in ParamHistFunc's internal TH1 order.
1436 auto &paramsNode = elem["parameters"].set_seq();
1437 for (RooAbsReal *param : paramHistFuncParamsInBinOrder(pdf)) {
1438 writeReference(paramsNode.append_child(), *param);
1439 }
1440 auto &observablesNode = elem["axes"].set_seq();
1441 // axes have to be ordered to get consistent bin indices
1442 for (auto *var : static_range_cast<RooRealVar *>(pdf.dataVars())) {
1443 HS3::writeAxis(observablesNode.append_child(), HS3::toBinnedAxis(*var));
1444 }
1445}
1446
1447void exportSpline(RooJSONFactoryWSTool *, RooSpline const &rs, JSONNode &elem)
1448{
1449 elem["x"] << rs.x().GetName();
1450 elem["interpolation"] << (rs.order() == 5 ? "poly5" : "poly3");
1451 elem["logx"] << rs.logx();
1452 elem["logy"] << rs.logy();
1453
1454 // The knots
1455 TSpline const &sp = rs.spline();
1456 auto &x0 = elem["x0"].set_seq();
1457 auto &y0 = elem["y0"].set_seq();
1458 for (int i = 0; i < sp.GetNp(); ++i) {
1459 double xk = 0.0;
1460 double yk = 0.0;
1461 sp.GetKnot(i, xk, yk);
1462 x0.append_child() << xk;
1463 y0.append_child() << yk;
1464 }
1465}
1466
1467void exportBernstein(RooJSONFactoryWSTool *, RooBernstein const &pdf, JSONNode &elem)
1468{
1469 writeReference(elem["x"], pdf.x());
1470 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf.coefList());
1471}
1472
1473void exportLandau(RooJSONFactoryWSTool *, RooLandau const &pdf, JSONNode &elem)
1474{
1475 writeReference(elem["x"], pdf.getX());
1476 writeReference(elem["mu"], pdf.getMean());
1477 writeReference(elem["sigma"], pdf.getSigma());
1478}
1479
1480void exportProduct(RooJSONFactoryWSTool *, RooProduct const &prod, JSONNode &elem)
1481{
1482 RooJSONFactoryWSTool::fillSeq(elem["factors"], prod.realComponents());
1484}
1485
1486void exportUniform(RooJSONFactoryWSTool *, RooUniform const &pdf, JSONNode &elem)
1487{
1489}
1490
1491void importWrapperPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
1492{
1493 std::string name(RooJSONFactoryWSTool::name(p));
1494 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "function");
1495 // ROOT previously exported this key without an underscore.
1496 const char *key = p.has_child("self_normalized") ? "self_normalized" : "selfnormalized";
1497 const bool selfNormalized = p.has_child(key) && p[key].val_bool();
1498 tool->wsEmplace<RooWrapperPdf>(name, *func, selfNormalized);
1499}
1500
1501void exportWrapperPdf(RooJSONFactoryWSTool *, RooWrapperPdf const &pdf, JSONNode &elem)
1502{
1503 // RooWrapperPdf has no accessor for the wrapped function, which is its only proxy.
1504 auto const &funcProxy = dynamic_cast<RooRealProxy const &>(*pdf.getProxy(0));
1505 elem["function"] << funcProxy.absArg()->GetName();
1506 if (pdf.selfNormalized()) {
1507 elem["self_normalized"] << true;
1508 }
1509}
1510
1511///////////////////////////////////////////////////////////////////////////////////////////////////////
1512// instantiate all importers and exporters
1513///////////////////////////////////////////////////////////////////////////////////////////////////////
1514
1515// A class whose constructor takes nothing but objects and lists of objects, each of which it has a getter for, is
1516// read and written field by field. A field describes a constructor argument: its key in the document, and the getter
1517// that gives what is written.
1518
1519// An argument that is one object: requested as a T, and written as a reference to it.
1520template <class T, class Getter_t>
1521struct ObjectField {
1522 const char *key;
1523 Getter_t getter;
1524
1525 T &request(RooJSONFactoryWSTool &tool, const JSONNode &p) const { return *tool.requestArg<T>(p, key); }
1526 template <class RooArg_t>
1527 void write(RooArg_t const &arg, JSONNode &elem) const
1528 {
1529 writeReference(elem[key], (arg.*getter)());
1530 }
1531};
1532
1533// An argument that is a list of objects: requested as a Collection_t of T, and written as a list of references.
1534template <class T, class Collection_t, class Getter_t>
1535struct ListField {
1536 const char *key;
1537 Getter_t getter;
1538
1539 Collection_t request(RooJSONFactoryWSTool &tool, const JSONNode &p) const
1540 {
1541 return tool.requestCollection<T, Collection_t>(p, key);
1542 }
1543 template <class RooArg_t>
1544 void write(RooArg_t const &arg, JSONNode &elem) const
1545 {
1546 RooJSONFactoryWSTool::fillSeq(elem[key], (arg.*getter)());
1547 }
1548};
1549
1550template <class T = RooAbsReal, class Getter_t>
1551ObjectField<T, Getter_t> object(const char *key, Getter_t getter)
1552{
1553 return {key, getter};
1554}
1555
1556template <class T = RooAbsReal, class Collection_t = RooArgList, class Getter_t>
1557ListField<T, Collection_t, Getter_t> list(const char *key, Getter_t getter)
1558{
1559 return {key, getter};
1560}
1561
1562// Register the importer and the exporter of the class RooArg_t, whose constructor takes the name, the title and then
1563// the fields in the given order.
1564template <class RooArg_t, class... Fields_t>
1565void registerFields(const std::string &key, Fields_t... fields)
1566{
1567 auto importFields = [=](RooJSONFactoryWSTool *tool, const JSONNode &p) {
1568 const std::string name = RooJSONFactoryWSTool::name(p);
1569 // The braces guarantee that the fields are requested in their order.
1570 tool->wsImport(RooArg_t{name.c_str(), name.c_str(), fields.request(*tool, p)...});
1571 };
1572 auto exportFields = [=](RooJSONFactoryWSTool *, RooArg_t const &arg, JSONNode &elem) {
1573 (fields.write(arg, elem), ...);
1574 };
1575 registerImporter(key, importFields);
1576 registerExporter<RooArg_t>(key, exportFields);
1577}
1578
1579// A deprecated type key is still read by the importers of its replacement, with a warning the first time.
1580void registerDeprecatedKey(const std::string &key, const std::string &replacement)
1581{
1582 registerImporter(key, [=](RooJSONFactoryWSTool *tool, const JSONNode &p) {
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.");
1587 }
1588 auto const &importers = RooFit::JSONIO::importers().at(replacement);
1589 return std::any_of(importers.begin(), importers.end(),
1590 [&](auto const &importer) { return importer->importArg(tool, p); });
1591 });
1592}
1593
1594// Registers the importers and exporters when the library is loaded.
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, /*autoExportDependants=*/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>);
1619 registerType("product", importProduct, exportProduct);
1620 registerType("rate_extended_dist", importExtendPdf, exportExtendPdf);
1621 registerType("spline", importSpline, exportSpline);
1622 // A "step" with "data" is a histogram, otherwise it is a ParamHistFunc.
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);
1627
1628 // The classes that are read and written field by field.
1629 registerFields<RooArgusBG>("argus_dist", object("mass", &RooArgusBG::getM), object("resonance", &RooArgusBG::getM0),
1630 object("slope", &RooArgusBG::getC), object("power", &RooArgusBG::getP));
1631 registerFields<RooBifurGauss>("bifurkated_gaussian_dist", object("x", &RooBifurGauss::getX),
1632 object("mean", &RooBifurGauss::getMean), object("sigmaL", &RooBifurGauss::getSigmaL),
1633 object("sigmaR", &RooBifurGauss::getSigmaR));
1634 // A "crystalball_dist" with the fields of two tails is the double-sided Crystal Ball of documents before HS3 0.3.
1635 registerImporter("crystalball_dist", importLegacyDoubleSidedCrystalBall);
1636 registerFields<RooCBShape>("crystalball_dist", object("m", &RooCBShape::getM), object("m0", &RooCBShape::getM0),
1637 object("sigma", &RooCBShape::getSigma), object("alpha", &RooCBShape::getAlpha),
1638 object("n", &RooCBShape::getN));
1639 registerFields<RooChebychev>("chebychev_dist", object("x", &RooChebychev::x),
1640 list("coefficients", &RooChebychev::coefList));
1641 registerFields<RooEffProd>("efficiency_product_pdf_dist", object<RooAbsPdf>("pdf", &RooEffProd::pdf),
1642 object("eff", &RooEffProd::eff));
1643 registerFields<RooGamma>("gamma_dist", object("x", &RooGamma::getX), object("gamma", &RooGamma::getGamma),
1644 object("beta", &RooGamma::getBeta), object("mu", &RooGamma::getMu));
1645 registerFields<RooGaussModel>("gauss_model_function", object<RooRealVar>("x", &RooGaussModel::convVar),
1646 object("mean", &RooGaussModel::getMean), object("sigma", &RooGaussModel::getSigma));
1647 registerFields<RooPowerSum>("power_sum_dist", object("x", &RooPowerSum::base),
1648 list("coefficients", &RooPowerSum::coefList), list("exponents", &RooPowerSum::expList));
1649 registerFields<RooProdPdf>("product_dist", list<RooAbsPdf>("factors", &RooProdPdf::pdfList));
1650 registerFields<RooProjectedPdf>("projected_dist", object<RooAbsPdf>("input_pdf", &RooProjectedPdf::intPdf),
1651 list<RooAbsReal, RooArgSet>("observables", &RooProjectedPdf::intObs));
1652 registerFields<RooAddition>("sum", list("summands", &RooAddition::list));
1653 registerFields<RooTruthModel>("truth_model_function", object<RooRealVar>("x", &RooTruthModel::convVar));
1654 registerFields<RooRealSumFunc>("weighted_sum", list("samples", &RooRealSumFunc::funcList),
1655 list("coefficients", &RooRealSumFunc::coefList));
1656
1657 // A RooTFnBinding is written as a generic formula.
1658 registerExporter<RooTFnBinding>("generic", exportTFnBinding);
1659
1660 // The types that are only read: the ones that RooFit writes in another way, and other names of the types above.
1661 registerImporter("array_dist", importArrayDist);
1662 registerImporter("combined_dist", importCombinedDist);
1663 registerImporter("extend_pdf", importExtendPdf);
1664 registerImporter("generic_function", importFormulaArg<RooFormulaVar>);
1665 registerImporter("histogram", importHist<RooHistFunc>);
1666 registerImporter("inverse_binvolume", importBinWidthFunction<true>);
1667 registerImporter("normal_dist", importGaussian);
1668 registerImporter("poisson_continuous_dist", importPoisson<true>);
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");
1674 return true;
1675}();
1676
1677} // namespace
1678
1679std::optional<ArrayComponentInfo>
1680arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable, RooJSONFactoryWSTool *tool)
1681{
1683 RooAbsReal const *x = nullptr;
1684 if (auto const *poisson = dynamic_cast<RooPoisson const *>(&pdf)) {
1685 out.type = poisson->getNoRounding() ? "poisson_continuous_dist" : "poisson_dist";
1686 x = &poisson->getX();
1687 out.fields = {{"mean", HS3::toNameOrNumber(poisson->getMean())}};
1688 } else if (auto const *gauss = dynamic_cast<RooGaussian const *>(&pdf)) {
1689 out.type = "gaussian_dist";
1690 x = &gauss->getX();
1691 RooAbsReal const *mean = &gauss->getMean();
1692 // A Gaussian constraint built by HistFactory has the parameter as x and the global observable as mean. The
1693 // Gaussian is symmetric in the two, so it is written with the observable as x where the observable is known.
1694 if (observable && *observable == mean->GetName() && !isLiteralConstVar(*mean)) {
1695 std::swap(x, mean);
1696 }
1697 out.fields = {{"mean", HS3::toNameOrNumber(*mean)}, {"sigma", HS3::toNameOrNumber(gauss->getSigma())}};
1698 } else if (auto const *lognormal = dynamic_cast<RooLognormal const *>(&pdf)) {
1699 out.type = "lognormal_dist";
1700 x = &lognormal->getX();
1701 if (lognormal->useStandardParametrization()) {
1702 out.fields = {{"mu", HS3::toNameOrNumber(lognormal->getMedian())},
1703 {"sigma", HS3::toNameOrNumber(lognormal->getShapeK())}};
1704 } else {
1705 out.fields = {{"mu", lognormalLogName(lognormal->getMedian(), tool)},
1706 {"sigma", lognormalLogName(lognormal->getShapeK(), tool)}};
1707 }
1708 } else {
1709 return std::nullopt;
1710 }
1711 // The observable of a component must be named: the observables are pairwise distinct and are paired with data.
1712 if (isLiteralConstVar(*x)) {
1713 return std::nullopt;
1714 }
1715 out.observable = x->GetName();
1716 return out;
1717}
1718
1719void writeArrayDist(RooJSONFactoryWSTool &tool, JSONNode &elem, std::string const &name,
1720 std::vector<RooAbsPdf const *> const &components)
1721{
1722 auto error = [&name](std::string const &message) {
1723 RooJSONFactoryWSTool::error("cannot write the array distribution '" + name + "': " + message);
1724 };
1725 if (components.empty()) {
1726 error("it has no components");
1727 }
1728 std::vector<ArrayComponentInfo> comps;
1729 std::set<std::string> observables;
1730 for (RooAbsPdf const *pdf : components) {
1731 auto comp = arrayComponentInfo(*pdf, tool.constraintObservable(pdf->GetName()), &tool);
1732 if (!comp) {
1733 error("'" + std::string(pdf->GetName()) +
1734 "' cannot be a component, only RooPoisson, RooGaussian and RooLognormal over a named observable "
1735 "are supported");
1736 }
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");
1740 }
1741 if (!observables.insert(comp->observable).second) {
1742 error("two components have the observable '" + comp->observable + "'");
1743 }
1744 comps.push_back(std::move(*comp));
1745 }
1746
1747 elem["type"] << "array_dist";
1748 elem["component_type"] << comps.front().type;
1749
1750 auto write = [](JSONNode &node, HS3::NameOrNumber const &value) {
1751 std::visit([&node](auto const &v) { node << v; }, value);
1752 };
1753
1754 // A field with the same value in every component is written once in "default_parameters".
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);
1763 }
1764 }
1765 }
1766
1767 JSONNode &seq = elem["components"].set_seq();
1768 for (ArrayComponentInfo const &comp : comps) {
1769 JSONNode &node = seq.append_child().set_map();
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);
1774 }
1775 }
1776 }
1777}
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 &param)
std::vector< RooAbsReal * > paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, 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
Definition JSONIOUtils.h:45
constexpr const char * arrayDistTag
Definition JSONIOUtils.h:34
void registerImporter(const std::string &key, ImportFunc func)
void registerType(const std::string &key, ImportFunc importFunc, ExportFunc< RooArg_t > exportFunc, bool autoExportDependants=true)
std::string message
#define d(i)
Definition RSha256.hxx:102
#define c(i)
Definition RSha256.hxx:101
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
char name[80]
Definition TGX11.cxx:142
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.
Definition RooAbsArg.h:77
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.
Definition RooAbsPdf.h:32
@ CanNotBeExtended
Definition RooAbsPdf.h:208
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...
Definition RooAbsReal.h:63
RooAddModel is an efficient implementation of a sum of PDFs of the form.
Definition RooAddModel.h:26
Efficient implementation of a sum of PDFs of the form.
Definition RooAddPdf.h:32
const RooArgList & list() const
Definition RooAddition.h:42
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
RooAbsReal const & getC() const
Definition RooArgusBG.h:43
RooAbsReal const & getM0() const
Definition RooArgusBG.h:42
RooAbsReal const & getP() const
Definition RooArgusBG.h:44
RooAbsReal const & getM() const
Definition RooArgusBG.h:41
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...
double epsilon() const
const RooAbsPdf & pdf() const
const RooAbsReal & observable() const
Returns the bin width (or volume) given a RooHistFunc.
const RooHistFunc & histFunc() const
RooAbsReal const & getSigma() const
Definition RooCBShape.h:43
RooAbsReal const & getM() const
Definition RooCBShape.h:41
RooAbsReal const & getN() const
Definition RooCBShape.h:45
RooAbsReal const & getM0() const
Definition RooCBShape.h:42
RooAbsReal const & getAlpha() const
Definition RooCBShape.h:44
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.
Definition RooDataHist.h:40
double const * weightArray() const
Single or double sided decay function that can be analytically convolved with any RooResolutionModel ...
Definition RooDecay.h:22
DecayType getDecayType() const
Get the decay type.
Definition RooDecay.h:43
RooAbsReal const & getTau() const
Get the decay constant.
Definition RooDecay.h:40
RooAbsReal const & getT() const
Get the cnvolution variable.
Definition RooDecay.h:37
Represents the first, second, or third order derivative of any RooAbsReal as calculated (numerically)...
double eps() const
RooAbsReal const & getX() const
Int_t order() const
RooArgSet const & getNset() const
RooAbsReal const & getFunc() const
RooAbsReal const & pdf() const
Definition RooEffProd.h:31
RooAbsReal const & eff() const
Definition RooEffProd.h:32
Exponential PDF.
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
std::string val() 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()
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
RooAbsReal const & getX() const
Definition RooGamma.h:34
RooAbsReal const & getGamma() const
Definition RooGamma.h:35
RooAbsReal const & getBeta() const
Definition RooGamma.h:36
RooAbsReal const & getMu() const
Definition RooGamma.h:37
RooAbsReal const & getMean() const
Get the mean parameter.
RooAbsReal const & getSigma() const
Get the sigma parameter.
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
RooAbsReal const & getX() const
Get the x variable.
Definition RooGaussian.h:45
RooAbsReal const & getMean() const
Get the mean parameter.
Definition RooGaussian.h:48
RooAbsReal const & getSigma() const
Get the sigma parameter.
Definition RooGaussian.h:51
A real-valued function sampled from a multidimensional histogram.
Definition RooHistFunc.h:29
When using RooFit, statistical models can be conveniently handled and stored as a RooWorkspace.
static void fillSeq(RooFit::Detail::JSONNode &node, RooAbsCollection const &coll, size_t nMax=-1)
T * requestArg(const RooFit::Detail::JSONNode &node, const std::string &key)
T * request(const std::string &objname, const std::string &requestAuthor)
The object objname from the workspace, imported from the document first if needed.
Coll_t requestCollection(const RooFit::Detail::JSONNode &node, const std::string &seqName)
Obj_t & wsImport(Obj_t const &obj)
static std::unique_ptr< RooDataHist > readBinnedData(const RooFit::Detail::JSONNode &n, const std::string &namecomp, RooArgSet const &vars)
Create a RooDataHist with the name name over the variables vars from the "contents" of n,...
static void exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, RooFit::Detail::JSONNode &output)
Write the axes and the n bin contents of a histogram over the variables vars, which are RooRealVars o...
void queueExport(RooAbsArg const &arg)
RooArgSet requestArgSet(const RooFit::Detail::JSONNode &node, const std::string &seqName)
RooArgList requestArgList(const RooFit::Detail::JSONNode &node, const std::string &seqName)
std::string exportTransformed(const RooAbsReal *original, const std::string &suffix, const std::string &formula)
RooFit::HS3::Version hs3Version() const
The HS3 version of the document that is currently being imported.
static void error(const char *s)
Write an error to the RooFit message service, and throw it as a std::runtime_error.
void importFunction(const RooFit::Detail::JSONNode &p, bool importAllDependants)
Import the function or distribution p into the workspace, with the importers that are registered for ...
Obj_t & wsEmplace(RooStringView name, Args_t &&...args)
static std::string name(const RooFit::Detail::JSONNode &n)
std::string const * constraintObservable(std::string const &pdfName) const
static std::ostream & warning(const std::string &s)
Write a warning to the RooFit message service, and return its stream.
static RooArgSet readAxes(const RooFit::Detail::JSONNode &node)
Create the variables for the "axes" of topNode, which are owned by the returned set.
Landau distribution p.d.f.
Definition RooLandau.h:24
RooAbsReal const & getSigma() const
Definition RooLandau.h:42
RooAbsReal const & getMean() const
Definition RooLandau.h:41
RooAbsReal const & getX() const
Definition RooLandau.h:40
RooFit Lognormal PDF.
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.
Poisson pdf.
Definition RooPoisson.h:18
RooAbsReal const & getX() const
Get the x variable.
Definition RooPoisson.h:44
bool getNoRounding() const
Definition RooPoisson.h:36
RooAbsReal const & getMean() const
Get the mean parameter.
Definition RooPoisson.h:47
RooAbsReal const & base() const
Get the base of the exponentiated terms (aka. x variable).
Definition RooPowerSum.h:29
RooArgList const & coefList() const
Get the list of coefficients.
Definition RooPowerSum.h:32
RooArgList const & expList() const
Get the list of exponents.
Definition RooPowerSum.h:35
Efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:35
const RooArgList & pdfList() const
Definition RooProdPdf.h:70
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
const RooArgList & categoricalComponents() const
Definition RooProduct.h:51
const RooArgList & realComponents() const
Definition RooProduct.h:50
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.
Definition RooRealVar.h:37
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.
Definition RooSpline.h:27
bool logx() const
Definition RooSpline.h:43
RooAbsReal const & x() const
Definition RooSpline.h:40
TSpline const & spline() const
Definition RooSpline.h:42
bool logy() const
Definition RooSpline.h:44
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
Flat p.d.f.
Definition RooUniform.h:24
RooArgList const & observables() const
Definition RooUniform.h:37
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
Definition TF1.h:426
static Bool_t IsScientificNotation(const TString &formula, int ipos)
Definition TFormula.cxx:383
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.
Definition TNamed.h:49
Base class for spline implementation containing the Draw/Paint methods.
Definition TSpline.h:31
virtual void GetKnot(Int_t i, Double_t &x, Double_t &y) const =0
virtual Int_t GetNp() const
Definition TSpline.h:60
Basic string class.
Definition TString.h:137
const char * Data() const
Definition TString.h:385
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:714
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2460
TCanvas * fractions()
Definition fractions.C:1
void swap(RVec< T > &lhs, RVec< T > &rhs)
Definition RVec.hxx:2211
const Double_t sigma
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
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.
Definition HS3Parser.cxx:92
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)
ImportMap & importers()
Definition JSONIO.cxx:21
std::vector< std::pair< std::string, RooFit::HS3::NameOrNumber > > fields
Definition JSONIOUtils.h:66
std::string observable
Definition JSONIOUtils.h:65
std::string type
Definition JSONIOUtils.h:64
The axis of binned data.
TMarker m
Definition textangle.C:8
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335