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 const std::string form = RooFit::HS3::arrayComponentForm(componentType, component, defaults);
436 if (ws.arg(pdfName)) {
437 // HS3 composes array distributions by union: an identical component of another array distribution of this
438 // document is the same factor, so the object is shared. A component over the same observable that is not
439 // identical is an error: the two would be different factors that share a variate.
440 std::string const *existing = RooFit::HS3::importedArrayComponentForm(*tool, pdfName);
441 if (!existing) {
442 error("cannot create the component for '" + x + "' as '" + pdfName +
443 "', the workspace already has an object of that name");
444 }
445 if (*existing != form) {
446 error(context + " over '" + x +
447 "' is not identical to the component over the same observable of another array distribution");
448 }
449 pdfs.add(*ws.pdf(pdfName));
450 continue;
451 }
452 JSONNode &node = nodes.append_child().set_map();
453 node["name"] << pdfName;
454 node["type"] << componentType;
455 if (defaults) {
456 for (JSONNode const &field : defaults->children()) {
457 copyValue(node[field.key()], field);
458 }
459 }
460 for (JSONNode const &field : component.children()) {
461 copyValue(node[field.key()], field);
462 }
463 tool->importFunction(node, true);
464 RooAbsPdf *pdf = ws.pdf(pdfName);
465 if (!pdf) {
466 error(context + " did not produce a distribution");
467 }
468 RooFit::HS3::recordImportedArrayComponent(*tool, pdfName, form);
469 pdfs.add(*pdf);
470 }
471
472 // The parameters of a component must not depend on any observable of the array, otherwise the product would not
473 // be normalized.
474 for (std::size_t i = 0; i < observables.size(); ++i) {
475 RooAbsArg const *x = ws.arg(observables[i]);
476 if (!x) {
477 error("the observable '" + observables[i] + "' is not a parameter or function");
478 }
479 for (std::size_t k = 0; k < observables.size(); ++k) {
480 if (k != i && pdfs[i].dependsOn(*ws.arg(observables[k]))) {
481 error("component " + std::to_string(i) + " depends on the observable '" + observables[k] +
482 "' of component " + std::to_string(k));
483 }
484 }
485 for (RooAbsArg const *server : pdfs[i].servers()) {
486 if (server != x && server->dependsOn(*x)) {
487 error("the parameters of component " + std::to_string(i) + " depend on its own observable '" +
488 observables[i] + "'");
489 }
490 }
491 }
492
493 RooProdPdf array{name.c_str(), name.c_str(), pdfs};
494 array.setAttribute(arrayDistTag);
495 // The product only exists to hold the components together.
496 array.setAttribute(helperObjectTag);
497 tool->wsImport(array);
498}
499
500// A "combined_dist" is interpreted by the document. This reads one that doesn't come with a document.
501void importCombinedDist(RooJSONFactoryWSTool *tool, const JSONNode &p)
502{
503 HS3::Diagnostics diagnostics;
504 HS3::Distribution const dist = HS3::parseDistribution(p, diagnostics);
505 if (!HS3::hasErrors(diagnostics)) {
506 HS3::validateCombinedDist(std::get<HS3::CombinedDist>(dist.body), dist.name, diagnostics);
507 }
508 HS3::report(diagnostics, dist.name);
509 HS3::buildCombinedDist(*tool, dist.name, std::get<HS3::CombinedDist>(dist.body));
510}
511
512void importAddPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
513{
514 std::string name(RooJSONFactoryWSTool::name(p));
515 const std::size_t nSummands = p.has_child("summands") ? p["summands"].num_children() : 0;
516 const std::size_t nCoefficients = p.has_child("coefficients") ? p["coefficients"].num_children() : 0;
517 const bool sinceHS3v03 = !(tool->hs3Version() < HS3::Version{0, 3});
518 if (p.has_child("extended")) {
519 // Check the explicit "extended" flag against the number of coefficients, which determines the extended mode of
520 // the RooAddPdf.
521 const bool extended = p["extended"].val_bool();
522 const std::string counts =
523 std::to_string(nCoefficients) + " coefficients for " + std::to_string(nSummands) + " summands";
524 if (extended && nCoefficients > 0 && nCoefficients + 1 == nSummands) {
525 RooJSONFactoryWSTool::error("mixture_dist '" + name + "' is declared as extended, but it has " + counts +
526 ", which defines a non-extended mixture");
527 }
528 if (!extended && nCoefficients == 0 && nSummands > 0) {
529 RooJSONFactoryWSTool::error("mixture_dist '" + name + "' is declared as not extended, but it has " + counts +
530 ", which defines an extended mixture of extended distributions");
531 }
532 if (!extended && nCoefficients == nSummands && nSummands > 0) {
533 // A RooAddPdf with one coefficient per summand can always be extended. The non-extended mixture is the one
534 // with the normalized coefficients c_i / sum(c), of which the last one follows from the others.
535 RooArgList summands = tool->requestArgList<RooAbsPdf>(p, "summands");
536 RooArgList coefficients = tool->requestArgList<RooAbsReal>(p, "coefficients");
537 std::string sum;
538 for (std::size_t i = 0; i < nCoefficients; ++i) {
539 sum += (i == 0 ? "x[" : "+x[") + std::to_string(i) + "]";
540 }
542 for (std::size_t i = 0; i + 1 < nCoefficients; ++i) {
543 fractions.add(tool->wsEmplace<RooFormulaVar>(name + "_fraction_" + std::to_string(i),
544 ("x[" + std::to_string(i) + "]/(" + sum + ")").c_str(),
545 coefficients));
546 }
547 tool->wsEmplace<RooAddPdf>(name, summands, fractions);
548 return;
549 }
550 } else if (nCoefficients == nSummands && nSummands > 0 && sinceHS3v03) {
551 // HS3 0.3 requires the flag. Where it decides about the Poisson term, a document without it is invalid.
552 RooJSONFactoryWSTool::error("mixture_dist '" + name +
553 "' has one coefficient per summand, but no \"extended\" flag, which HS3 "
554 "requires to decide whether the mixture is extended");
555 }
556 if (nSummands > 0 && nCoefficients == 0 && sinceHS3v03) {
557 RooJSONFactoryWSTool::warning("RooFitHS3: mixture_dist '" + name +
558 "' has no coefficients, which HS3 0.3 doesn't define. It is read as the sum of "
559 "its extended summands.");
560 }
561 if (!tool->requestArgList<RooAbsReal>(p, "coefficients").empty()) {
562 tool->wsEmplace<RooAddPdf>(name, tool->requestArgList<RooAbsPdf>(p, "summands"),
563 tool->requestArgList<RooAbsReal>(p, "coefficients"));
564 } else {
565 tool->wsEmplace<RooAddPdf>(name, tool->requestArgList<RooAbsPdf>(p, "summands"));
566 }
567}
568
569void importAddModel(RooJSONFactoryWSTool *tool, const JSONNode &p)
570{
571 std::string name(RooJSONFactoryWSTool::name(p));
572 tool->wsEmplace<RooAddModel>(name, tool->requestArgList<RooAbsPdf>(p, "summands"),
573 tool->requestArgList<RooAbsReal>(p, "coefficients"));
574}
575
576template <bool DivideByBinWidth>
577void importBinWidthFunction(RooJSONFactoryWSTool *tool, const JSONNode &p)
578{
579 std::string name(RooJSONFactoryWSTool::name(p));
580 RooHistFunc *hf = dynamic_cast<RooHistFunc *>(tool->request<RooAbsReal>(p["histogram"].val(), name));
581 if (!hf) {
582 RooJSONFactoryWSTool::error("histogram '" + p["histogram"].val() + "' of '" + name + "' is not a RooHistFunc");
583 }
584 tool->wsEmplace<RooBinWidthFunction>(name, *hf, DivideByBinWidth);
585}
586
587void importBinSamplingPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
588{
589 std::string name(RooJSONFactoryWSTool::name(p));
590
591 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, "pdf");
592 RooRealVar *obs = tool->requestArg<RooRealVar>(p, "observable");
593
594 if (!pdf->dependsOn(*obs)) {
595 RooJSONFactoryWSTool::error(std::string("pdf '") + pdf->GetName() + "' does not depend on observable '" +
596 obs->GetName() + "' as indicated by parent RooBinSamplingPdf '" + name +
597 "', please check!");
598 }
599
600 if (!p.has_child("epsilon")) {
601 RooJSONFactoryWSTool::error("no epsilon given in '" + name + "'");
602 }
603 double epsilon(p["epsilon"].val_double());
604
605 tool->wsEmplace<RooBinSamplingPdf>(name, *obs, *pdf, epsilon);
606}
607
608void importRealSumPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
609{
610 std::string name(RooJSONFactoryWSTool::name(p));
611 RooArgList samples = tool->requestArgList<RooAbsReal>(p, "samples");
612 RooArgList coefs = tool->requestArgList<RooAbsReal>(p, "coefficients");
613 const bool extended = p.has_child("extended") && p["extended"].val_bool();
614 tool->wsEmplace<RooRealSumPdf>(name, samples, coefs, extended);
615}
616
617template <class RooArg_t>
618void importPolynomial(RooJSONFactoryWSTool *tool, const JSONNode &p)
619{
620 std::string name(RooJSONFactoryWSTool::name(p));
621 if (!p.has_child("coefficients")) {
622 RooJSONFactoryWSTool::error("no coefficients given in '" + name + "'");
623 }
624 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
625 RooArgList coefs;
626 int order = 0;
627 int lowestOrder = 0;
628 for (const auto &coef : p["coefficients"].children()) {
629 // As long as the coefficients match the default coefficients in
630 // RooFit, we don't have to instantiate RooFit objects but can
631 // increase the lowestOrder flag.
632 if (order == 0 && (coef.val() == "1.0" || coef.val() == "1")) {
633 ++lowestOrder;
634 } else if (coefs.empty() && (coef.val() == "0.0" || coef.val() == "0")) {
635 ++lowestOrder;
636 } else {
637 coefs.add(*tool->request<RooAbsReal>(coef.val(), name));
638 }
639 ++order;
640 }
641
642 tool->wsEmplace<RooArg_t>(name, *x, coefs, lowestOrder);
643}
644
645// HS3 0.3 distinguishes the discrete "poisson_dist" from the "poisson_continuous_dist" (HS3 #152), which are a
646// RooPoisson without and with noRounding. Before, ROOT wrote both as "poisson_dist" with its own key "integer", where
647// false denotes the continuous form. That key is read for documents before HS3 0.3, without it the discrete form is
648// meant. From HS3 0.3 on, it must not be present.
649template <bool Continuous>
650void importPoisson(RooJSONFactoryWSTool *tool, const JSONNode &p)
651{
652 std::string name(RooJSONFactoryWSTool::name(p));
653 bool noRounding = Continuous;
654 if (p.has_child("integer")) {
655 std::string const type = Continuous ? "poisson_continuous_dist" : "poisson_dist";
656 if (Continuous || !(tool->hs3Version() < HS3::Version{0, 3})) {
658 type + " '" + name +
659 "' has the key \"integer\", which is not part of HS3. The discrete Poisson distribution is "
660 "\"poisson_dist\" and the continuous one is \"poisson_continuous_dist\".");
661 }
662 noRounding = !p["integer"].val_bool();
663 }
664 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
665 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
666 tool->wsEmplace<RooPoisson>(name, *x, *mean, noRounding);
667}
668
669void importDecay(RooJSONFactoryWSTool *tool, const JSONNode &p)
670{
671 std::string name(RooJSONFactoryWSTool::name(p));
672 RooRealVar *t = tool->requestArg<RooRealVar>(p, "t");
673 RooAbsReal *tau = tool->requestArg<RooAbsReal>(p, "tau");
674 // HS3 lists some resolution models as functions.
676 if (!model) {
677 RooJSONFactoryWSTool::error("resolutionModel of '" + name + "' is not a RooResolutionModel");
678 }
679 RooDecay::DecayType decayType = static_cast<RooDecay::DecayType>(p["decayType"].val_int());
680 tool->wsEmplace<RooDecay>(name, *t, *tau, *model, decayType);
681}
682
683void importRealIntegral(RooJSONFactoryWSTool *tool, const JSONNode &p)
684{
685 std::string name(RooJSONFactoryWSTool::name(p));
686 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "integrand");
687 auto vars = tool->requestArgList<RooAbsReal>(p, "variables");
688 RooArgSet normSet;
689 RooArgSet const *normSetPtr = nullptr;
690 if (p.has_child("normalization")) {
691 normSet.add(tool->requestArgSet<RooAbsReal>(p, "normalization"));
692 normSetPtr = &normSet;
693 }
694 JSONNode const *domain = p.find("domain");
695 // todo: at some point, take care of integrator configurations
696 tool->wsEmplace<RooRealIntegral>(name, *func, vars, normSetPtr, static_cast<RooNumIntConfig *>(nullptr),
697 domain ? domain->val().c_str() : nullptr);
698}
699
700void importDerivative(RooJSONFactoryWSTool *tool, const JSONNode &p)
701{
702 std::string name(RooJSONFactoryWSTool::name(p));
703 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "function");
704 RooRealVar *x = tool->requestArg<RooRealVar>(p, "x");
705 Int_t order = p["order"].val_int();
706 double eps = p["eps"].val_double();
707 RooArgSet normSet;
708 if (p.has_child("normalization")) {
709 normSet.add(tool->requestArgSet<RooAbsReal>(p, "normalization"));
710 }
711 tool->wsEmplace<RooDerivative>(name, *func, *x, normSet, order, eps);
712}
713
714void importFFTConvPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
715{
716 std::string name(RooJSONFactoryWSTool::name(p));
717 RooRealVar *convVar = tool->requestArg<RooRealVar>(p, "conv_var");
718 Int_t order = p["ipOrder"].val_int();
719 RooAbsPdf *pdf1 = tool->requestArg<RooAbsPdf>(p, "pdf1");
720 RooAbsPdf *pdf2 = tool->requestArg<RooAbsPdf>(p, "pdf2");
721 if (p.has_child("conv_func")) {
722 RooAbsReal *convFunc = tool->requestArg<RooAbsReal>(p, "conv_func");
723 tool->wsEmplace<RooFFTConvPdf>(name, *convFunc, *convVar, *pdf1, *pdf2, order);
724 } else {
725 tool->wsEmplace<RooFFTConvPdf>(name, *convVar, *pdf1, *pdf2, order);
726 }
727}
728
729void importExtendPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
730{
731 std::string name(RooJSONFactoryWSTool::name(p));
732 // HS3 calls the fields "dist" and "rate". RooFit used to write "pdf" and "norm", which are still accepted.
733 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, p.has_child("pdf") && !p.has_child("dist") ? "pdf" : "dist");
734 RooAbsReal *norm = tool->requestArg<RooAbsReal>(p, p.has_child("norm") && !p.has_child("rate") ? "norm" : "rate");
735 JSONNode const *range = p.find("range");
736 tool->wsEmplace<RooExtendPdf>(name, *pdf, *norm, range ? range->val().c_str() : nullptr);
737}
738
739// HS3 0.3 calls the location parameter of the Landau distribution "mu", since it is neither the mean nor the most
740// probable value. Documents before 0.3 used "mean", which is still read.
741void importLandau(RooJSONFactoryWSTool *tool, const JSONNode &p)
742{
743 const std::string name(RooJSONFactoryWSTool::name(p));
744 const bool legacyKey = !p.has_child("mu") && p.has_child("mean");
745 if (legacyKey && !(tool->hs3Version() < HS3::Version{0, 3})) {
746 RooJSONFactoryWSTool::warning("RooFitHS3: the landau_dist '" + name +
747 "' uses the key \"mean\", which HS3 0.3 renamed to \"mu\".");
748 }
749 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
750 RooAbsReal *mu = tool->requestArg<RooAbsReal>(p, legacyKey ? "mean" : "mu");
751 RooAbsReal *sigma = tool->requestArg<RooAbsReal>(p, "sigma");
752 tool->wsEmplace<RooLandau>(name, *x, *mu, *sigma);
753}
754
755void importLogNormal(RooJSONFactoryWSTool *tool, const JSONNode &p)
756{
757 std::string name(RooJSONFactoryWSTool::name(p));
758 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
759
760 // Same mechanism to undo the parameter transformation as in the
761 // importExponential() function (see comments in that function for more info).
762 const std::string mu = p["mu"].val();
763 const std::string sigma = p["sigma"].val();
764 const bool isStandard = !endsWith(mu, lognormalLogSuffix);
765 RooAbsReal *median = tool->request<RooAbsReal>(isStandard ? mu : transformedOriginal(mu, lognormalLogSuffix), name);
766 RooAbsReal *shape =
767 tool->request<RooAbsReal>(isStandard ? sigma : transformedOriginal(sigma, lognormalLogSuffix), name);
768
769 tool->wsEmplace<RooLognormal>(name, *x, *median, *shape, isStandard);
770}
771
772void importExponential(RooJSONFactoryWSTool *tool, const JSONNode &p)
773{
774 std::string name(RooJSONFactoryWSTool::name(p));
775 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
776
777 // If the parameter name ends with the "_exponential_inverted" suffix,
778 // this means that it was exported from a RooFit object where the
779 // parameter first needed to be transformed on export to match the HS3
780 // specification. But when re-importing such a parameter, we can simply
781 // skip the transformation and use the original RooFit parameter without
782 // the suffix.
783 //
784 // A concrete example: take the following RooFit pdf in the factory language:
785 //
786 // "Exponential::exponential_1(x[0, 10], c[-0.1])"
787 //
788 // It defines en exponential exp(c * x). However, in HS3 the exponential
789 // is defined as exp(-c * x), to RooFit would export these dictionaries
790 // to the JSON:
791 //
792 // {
793 // "name": "exponential_1", // HS3 exponential_dist with transformed parameter
794 // "type": "exponential_dist",
795 // "x": "x",
796 // "c": "c_exponential_inverted"
797 // },
798 // {
799 // "name": "c_exponential_inverted", // transformation function created on-the-fly on export
800 // "type": "generic",
801 // "expression": "-c"
802 // }
803 //
804 // On import, we can directly take the non-transformed parameter, which is
805 // we check for the suffix and optionally remove it from the requested
806 // name next:
807
808 const std::string constParamName = p["c"].val();
809 const bool isInverted = endsWith(constParamName, "_exponential_inverted");
810 RooAbsReal *c = tool->request<RooAbsReal>(
811 isInverted ? transformedOriginal(constParamName, "_exponential_inverted") : constParamName, name);
812
813 tool->wsEmplace<RooExponential>(name, *x, *c, !isInverted);
814}
815
816void importMultiVarGaussian(RooJSONFactoryWSTool *tool, const JSONNode &p)
817{
818 std::string name(RooJSONFactoryWSTool::name(p));
819 const bool hasCov = p.has_child("covariances");
820 const bool hasCorr = p.has_child("correlations") && p.has_child("standard_deviations");
821 if (!hasCov && !hasCorr) {
822 RooJSONFactoryWSTool::error("no covariances or correlations+standard_deviations given in '" + name + "'");
823 }
824 // The covariances are given directly, or as correlations that are scaled with the standard deviations.
825 const std::string key = hasCov ? "covariances" : "correlations";
826 std::vector<double> sigmas;
827 if (hasCov) {
828 sigmas.assign(p[key].num_children(), 1.0);
829 } else {
830 sigmas << p["standard_deviations"];
831 }
832 const std::size_t n = sigmas.size();
833 // The matrix must be square, otherwise the entries would be written out of bounds.
834 if (p[key].num_children() != n) {
835 RooJSONFactoryWSTool::error("\"" + key + "\" in '" + name + "' must have " + std::to_string(n) + " rows");
836 }
837 TMatrixDSym covmat;
838 covmat.ResizeTo(n, n);
839 int i = 0;
840 for (const auto &row : p[key].children()) {
841 if (!row.is_seq() || row.num_children() != n) {
842 RooJSONFactoryWSTool::error("\"" + key + "\" in '" + name + "' must be a square matrix");
843 }
844 int j = 0;
845 for (const auto &val : row.children()) {
846 covmat(i, j) = val.val_double() * sigmas[i] * sigmas[j];
847 ++j;
848 }
849 ++i;
850 }
852 tool->requestArgList<RooAbsReal>(p, "mean"), covmat);
853}
854
855/// Read the binning variables from the "axes" node, ordered like in `varList`.
856RooArgList readBinning(const JSONNode &topNode, const RooArgList &varList)
857{
859 RooArgList vars;
860 for (RooAbsArg *refVar : varList) {
861 if (RooAbsArg *axis = axes.find(*refVar)) {
862 vars.addClone(*axis);
863 }
864 }
865 return vars;
866}
867
868bool importParamHistFunc(RooJSONFactoryWSTool *tool, const JSONNode &p)
869{
870 if (!p.has_child("parameters")) {
871 return false;
872 }
873 std::string name(RooJSONFactoryWSTool::name(p));
874 RooArgList varList = tool->requestArgList<RooRealVar>(p, "variables");
875 const bool hasAxes = p.has_child("axes");
876 if (!hasAxes) {
878 "No axes given in '" + name +
879 "'. Using default binning (uniform; nbins=100). If needed, export the Workspace to JSON with a newer "
880 "Root version that supports custom ParamHistFunc binnings(>=6.38.00).\n");
881 }
882 RooArgList binning = hasAxes ? readBinning(p, varList) : varList;
883 checkParamHistFuncOrderIsDefined(tool->hs3Version(), binning, "the ParamHistFunc '" + name + "'");
884 // The parameters are given in the order of HS3 (last axis fastest); ParamHistFunc expects TH1 order.
885 tool->wsEmplace<ParamHistFunc>(name, binning,
886 toParamHistFuncOrder(tool->requestArgList<RooAbsReal>(p, "parameters"), binning));
887 return true;
888}
889
890void importSpline(RooJSONFactoryWSTool *tool, const JSONNode &p)
891{
892 const std::string name(RooJSONFactoryWSTool::name(p));
893 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
894 if (!p.has_child("x0") || !p.has_child("y0")) {
895 RooJSONFactoryWSTool::error("no x0/y0 given in '" + name + "'");
896 }
897
898 // The optional fields have the defaults of RooSpline.
899 const std::string algo = p.has_child("interpolation") ? p["interpolation"].val() : "poly3";
900 if (algo != "poly3" && algo != "poly5") {
901 RooJSONFactoryWSTool::error("unsupported algo '" + algo + "' for RooSpline in '" + name +
902 "': allowed are 'poly3' and 'poly5'");
903 }
904 const bool logx = p.has_child("logx") && p["logx"].val_bool();
905 const bool logy = p.has_child("logy") && p["logy"].val_bool();
906
907 std::vector<double> x0;
908 std::vector<double> y0;
909 x0 << p["x0"];
910 y0 << p["y0"];
911
912 if (x0.size() != y0.size()) {
913 RooJSONFactoryWSTool::error("x0/y0 size mismatch in '" + name + "': x0 has " + std::to_string(x0.size()) +
914 ", y0 has " + std::to_string(y0.size()));
915 }
916 if (x0.size() < 2) {
917 RooJSONFactoryWSTool::error("need at least 2 knots in '" + name + "'");
918 }
919
920 tool->wsEmplace<::RooSpline>(name.c_str(), *x, x0, y0, algo == "poly5" ? 5 : 3, logx, logy);
921}
922
923void importBernstein(RooJSONFactoryWSTool *tool, const JSONNode &p)
924{
925 std::string name(RooJSONFactoryWSTool::name(p));
926 auto *x = dynamic_cast<RooAbsRealLValue *>(tool->requestArg<RooAbsReal>(p, "x"));
927 if (!x) {
928 RooJSONFactoryWSTool::error("\"x\" of '" + name + "' is not a variable");
929 }
930 tool->wsEmplace<RooBernstein>(name, *x, tool->requestArgList<RooAbsReal>(p, "coefficients"));
931}
932
933void importGaussian(RooJSONFactoryWSTool *tool, const JSONNode &p)
934{
935 std::string name(RooJSONFactoryWSTool::name(p));
936 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
937 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
938 RooAbsReal *sigma = tool->requestArg<RooAbsReal>(p, "sigma");
939 tool->wsEmplace<RooGaussian>(name, *x, *mean, *sigma);
940}
941
942void importUniform(RooJSONFactoryWSTool *tool, const JSONNode &p)
943{
944 std::string name(RooJSONFactoryWSTool::name(p));
945 // A single observable may also be given by its name.
946 if (p.has_child("x") && !p["x"].is_seq()) {
947 tool->wsEmplace<RooUniform>(name, RooArgSet{*tool->requestArg<RooAbsReal>(p, "x")});
948 } else {
949 tool->wsEmplace<RooUniform>(name, tool->requestArgSet<RooAbsReal>(p, "x"));
950 }
951}
952
953namespace CrystalBall {
954
955// The keys of the tails of the double-sided Crystal Ball.
956const std::initializer_list<const char *> tailKeys = {"alpha_L", "n_L", "alpha_R", "n_R"};
957
958bool hasAny(const JSONNode &p, std::initializer_list<const char *> keys)
959{
960 return std::any_of(keys.begin(), keys.end(), [&p](const char *key) { return p.has_child(key); });
961}
962
963bool hasDoubleSidedKeys(const JSONNode &p)
964{
965 return hasAny(p, tailKeys) || hasAny(p, {"sigma_L", "sigma_R"});
966}
967
968// Create a RooCrystalBall with two tails. With `symmetricShorthand`, the tails may also be given as "alpha" and "n"
969// for both sides, as in the "crystalball_dist" of HS3 versions before 0.3.
970void importDoubleSided(RooJSONFactoryWSTool *tool, const JSONNode &p, std::string const &type, bool symmetricShorthand)
971{
972 const std::string name(RooJSONFactoryWSTool::name(p));
973 const std::string context = type + " '" + name + "'";
974
975 const bool asymmetricTails = hasAny(p, tailKeys);
976 const bool symmetricTails = hasAny(p, {"alpha", "n"});
977 if (symmetricTails && !symmetricShorthand) {
978 RooJSONFactoryWSTool::error(context + " must not have \"alpha\" or \"n\", the tails are given by \"alpha_L\", " +
979 "\"n_L\", \"alpha_R\" and \"n_R\"");
980 }
981 if (symmetricTails && asymmetricTails) {
983 " must not combine \"alpha\"/\"n\" with \"alpha_L\"/\"n_L\"/\"alpha_R\"/\"n_R\"");
984 }
985 if (asymmetricTails || !symmetricTails) {
986 for (const char *key : tailKeys) {
987 if (!p.has_child(key)) {
988 RooJSONFactoryWSTool::error(context + " is missing \"" + key +
989 "\": \"alpha_L\", \"n_L\", \"alpha_R\" and \"n_R\" are all required");
990 }
991 }
992 } else if (!p.has_child("alpha") || !p.has_child("n")) {
993 RooJSONFactoryWSTool::error(context + " needs both \"alpha\" and \"n\"");
994 }
995
996 const bool asymmetricWidths = hasAny(p, {"sigma_L", "sigma_R"});
997 if (asymmetricWidths && p.has_child("sigma")) {
998 RooJSONFactoryWSTool::error(context + " must not combine \"sigma\" with \"sigma_L\"/\"sigma_R\"");
999 }
1000 if (asymmetricWidths && !(p.has_child("sigma_L") && p.has_child("sigma_R"))) {
1001 RooJSONFactoryWSTool::error(context + " needs both \"sigma_L\" and \"sigma_R\"");
1002 }
1003 if (!asymmetricWidths && !p.has_child("sigma")) {
1004 RooJSONFactoryWSTool::error(context + " needs either \"sigma\" or both \"sigma_L\" and \"sigma_R\"");
1005 }
1006
1007 RooAbsReal *m = tool->requestArg<RooAbsReal>(p, "m");
1008 RooAbsReal *m0 = tool->requestArg<RooAbsReal>(p, "m0");
1009 RooAbsReal *sigmaL = tool->requestArg<RooAbsReal>(p, asymmetricWidths ? "sigma_L" : "sigma");
1010 RooAbsReal *sigmaR = tool->requestArg<RooAbsReal>(p, asymmetricWidths ? "sigma_R" : "sigma");
1011 RooAbsReal *alphaL = tool->requestArg<RooAbsReal>(p, symmetricTails ? "alpha" : "alpha_L");
1012 RooAbsReal *nL = tool->requestArg<RooAbsReal>(p, symmetricTails ? "n" : "n_L");
1013 RooAbsReal *alphaR = tool->requestArg<RooAbsReal>(p, symmetricTails ? "alpha" : "alpha_R");
1014 RooAbsReal *nR = tool->requestArg<RooAbsReal>(p, symmetricTails ? "n" : "n_R");
1015 tool->wsEmplace<RooCrystalBall>(name, *m, *m0, *sigmaL, *sigmaR, *alphaL, *nL, *alphaR, *nR);
1016}
1017
1018} // namespace CrystalBall
1019
1020// "crystalball_dist" is the single-sided Crystal Ball (RooCBShape). Before HS3 0.3, it was also the double-sided
1021// Crystal Ball, recognizable by the "_L"/"_R" fields. Such documents are still read by this importer, with a
1022// deprecation warning. It declines the single-sided Crystal Ball.
1023bool importLegacyDoubleSidedCrystalBall(RooJSONFactoryWSTool *tool, const JSONNode &p)
1024{
1025 if (!CrystalBall::hasDoubleSidedKeys(p)) {
1026 return false;
1027 }
1028 static bool warned = false;
1029 if (!warned) {
1030 RooJSONFactoryWSTool::warning("RooFitHS3: \"crystalball_dist\" with the fields \"alpha_L\", \"n_L\", "
1031 "\"alpha_R\", \"n_R\", \"sigma_L\" or \"sigma_R\" is deprecated, please use "
1032 "\"crystalball_doublesided_dist\" for the double-sided Crystal Ball.");
1033 warned = true;
1034 }
1035 CrystalBall::importDoubleSided(tool, p, "crystalball_dist", /*symmetricShorthand=*/true);
1036 return true;
1037}
1038
1039void importCrystalBallDoubleSided(RooJSONFactoryWSTool *tool, const JSONNode &p)
1040{
1041 CrystalBall::importDoubleSided(tool, p, "crystalball_doublesided_dist", /*symmetricShorthand=*/false);
1042}
1043
1044///////////////////////////////////////////////////////////////////////////////////////////////////////
1045// specialized exporter implementations
1046///////////////////////////////////////////////////////////////////////////////////////////////////////
1047
1048// A RooCrystalBall with one tail is the single-sided "crystalball_dist" (read back as RooCBShape, which follows the
1049// same convention for the sign of alpha). With two tails, it is a "crystalball_doublesided_dist", whose tails are
1050// always written as "alpha_L"/"n_L"/"alpha_R"/"n_R": there is no shorthand for symmetric tails.
1051void exportCrystalBall(RooJSONFactoryWSTool *, RooCrystalBall const &pdf, JSONNode &elem)
1052{
1053 writeReference(elem["m"], pdf.x());
1054 writeReference(elem["m0"], pdf.x0());
1055 if (!pdf.alphaR() || !pdf.nR()) {
1056 elem["type"] << "crystalball_dist";
1057 writeReference(elem["sigma"], pdf.sigmaL());
1058 writeReference(elem["alpha"], pdf.alphaL());
1059 writeReference(elem["n"], pdf.nL());
1060 return;
1061 }
1062 if (&pdf.sigmaL() == &pdf.sigmaR()) {
1063 writeReference(elem["sigma"], pdf.sigmaL());
1064 } else {
1065 writeReference(elem["sigma_L"], pdf.sigmaL());
1066 writeReference(elem["sigma_R"], pdf.sigmaR());
1067 }
1068 writeReference(elem["alpha_L"], pdf.alphaL());
1069 writeReference(elem["n_L"], pdf.nL());
1070 writeReference(elem["alpha_R"], *pdf.alphaR());
1071 writeReference(elem["n_R"], *pdf.nR());
1072}
1073
1074template <class RooArg_t>
1075void exportAddPdf(RooJSONFactoryWSTool *, RooArg_t const &pdf, JSONNode &elem)
1076{
1077 RooJSONFactoryWSTool::fillSeq(elem["summands"], pdf.pdfList());
1078 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf.coefList());
1079 elem["extended"] << (pdf.extendMode() != RooArg_t::CanNotBeExtended);
1080 // A RooAddModel is written as a mixture_model, which is not part of HS3.
1081 if (pdf.coefList().empty() && std::is_same_v<RooArg_t, RooAddPdf>) {
1082 RooJSONFactoryWSTool::warning("RooFitHS3: the RooAddPdf '" + std::string(pdf.GetName()) +
1083 "' has no coefficients. It is written as a mixture_dist without coefficients, "
1084 "which HS3 0.3 doesn't define, so other implementations might not read it.");
1085 }
1086}
1087
1088void exportRealSumPdf(RooJSONFactoryWSTool *, RooRealSumPdf const &pdf, JSONNode &elem)
1089{
1090 RooJSONFactoryWSTool::fillSeq(elem["samples"], pdf.funcList());
1091 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf.coefList());
1092 elem["extended"] << (pdf.extendMode() != RooAbsPdf::CanNotBeExtended);
1093}
1094
1095template <class RooArg_t>
1096void exportHist(RooJSONFactoryWSTool *tool, RooArg_t const &hf, JSONNode &elem)
1097{
1098 RooDataHist const &dh = hf.dataHist();
1099 // The axes are named after the observables of the function, which are not necessarily the variables of the
1100 // histogram.
1101 auto vars = histogramVariablesNamedAfterObservables(dh, hf.getHistObsList(), hf.variables());
1102 tool->exportHisto(*vars, dh.numEntries(), dh.weightArray(), elem["data"].set_map());
1103}
1104
1105template <class RooArg_t>
1106bool importHist(RooJSONFactoryWSTool *tool, const JSONNode &p)
1107{
1108 std::string name(RooJSONFactoryWSTool::name(p));
1109 if (!p.has_child("data")) {
1110 return false;
1111 }
1112 std::unique_ptr<RooDataHist> dataHist =
1114 tool->wsEmplace<RooArg_t>(name, *dataHist->get(), *dataHist);
1115 return true;
1116}
1117
1118void exportBinSamplingPdf(RooJSONFactoryWSTool *, RooBinSamplingPdf const &pdf, JSONNode &elem)
1119{
1120 elem["pdf"] << pdf.pdf().GetName();
1121 elem["observable"] << pdf.observable().GetName();
1122 elem["epsilon"] << pdf.epsilon();
1123}
1124
1125void exportBinWidthFunction(RooJSONFactoryWSTool *, RooBinWidthFunction const &pdf, JSONNode &elem)
1126{
1127 // It is registered for "binvolume".
1128 if (pdf.divideByBinWidth()) {
1129 elem["type"] << "inverse_binvolume";
1130 }
1131 elem["histogram"] << pdf.histFunc().GetName();
1132}
1133
1134void cleanExpression(TString &expr)
1135{
1136 // Plain substring replacement would also hit longer identifiers that
1137 // share a prefix (e.g. "TMath::Tan" in "TMath::TanH", or "TMath::Pi" in
1138 // "TMath::PiOver2"), corrupting the exported expression. Identifiers
1139 // without a replacement are kept as-is.
1140 replaceIdentifier(expr, "TMath::Exp", "exp");
1141 replaceIdentifier(expr, "TMath::Min", "min");
1142 replaceIdentifier(expr, "TMath::Max", "max");
1143 replaceIdentifier(expr, "TMath::Log", "log");
1144 replaceIdentifier(expr, "TMath::Log10", "log10");
1145 replaceIdentifier(expr, "TMath::Cos", "cos");
1146 replaceIdentifier(expr, "TMath::CosH", "cosh");
1147 replaceIdentifier(expr, "TMath::Sin", "sin");
1148 replaceIdentifier(expr, "TMath::SinH", "sinh");
1149 replaceIdentifier(expr, "TMath::Sqrt", "sqrt");
1150 replaceIdentifier(expr, "TMath::Power", "pow");
1151 replaceIdentifier(expr, "TMath::Erf", "erf");
1152 replaceIdentifier(expr, "TMath::Erfc", "erfc");
1153 replaceIdentifier(expr, "TMath::Floor", "floor");
1154 replaceIdentifier(expr, "TMath::Ceil", "ceil");
1155 replaceIdentifier(expr, "TMath::Abs", "abs");
1156 replaceIdentifier(expr, "TMath::Tan", "tan");
1157 replaceIdentifier(expr, "TMath::TanH", "tanh");
1158 replaceIdentifier(expr, "TMath::ASin", "asin");
1159 replaceIdentifier(expr, "TMath::ACos", "acos");
1160 replaceIdentifier(expr, "TMath::ATan", "atan");
1161 replaceIdentifier(expr, "TMath::ATan2", "atan2");
1162 replaceIdentifier(expr, "TMath::Pi()", "PI");
1163 replaceIdentifier(expr, "TMath::E()", "EULER");
1164}
1165
1166std::optional<std::string> ternariesToIfElse(std::string const &in);
1167
1168// Rewrite one comma-free part of an expression, see ternariesToIfElse().
1169std::optional<std::string> ternaryPartToIfElse(std::string const &in)
1170{
1171 // Find the first '?' that is not enclosed in brackets. A ':' can only follow a '?', and a part has no commas.
1172 const std::size_t question = findTopLevel(in, "?:,");
1173 if (question != std::string::npos && in[question] != '?') {
1174 return std::nullopt;
1175 }
1176
1177 if (question == std::string::npos) {
1178 // No ternary on this level: copy the expression and rewrite the ternaries inside of brackets.
1179 std::string out;
1180 for (std::size_t i = 0; i < in.size(); ++i) {
1181 if (in[i] == ')' || in[i] == ']') {
1182 return std::nullopt;
1183 }
1184 if (in[i] != '(' && in[i] != '[') {
1185 out += in[i];
1186 continue;
1187 }
1188 const std::size_t close = findClosingBracket(in, i);
1189 if (close == std::string::npos) {
1190 return std::nullopt;
1191 }
1192 const std::string inner = in.substr(i + 1, close - i - 1);
1193 const std::optional<std::string> innerOut = ternariesToIfElse(inner);
1194 if (!innerOut) {
1195 return std::nullopt;
1196 }
1197 // Parentheses that only group a ternary are redundant around the ifelse() function call.
1198 const std::string before = trimmed(in.substr(0, i));
1199 const bool isGrouping = in[i] == '(' && (before.empty() || !isIdentifierChar(before.back()));
1200 if (isGrouping && *innerOut != trimmed(inner) && startsWith(*innerOut, "ifelse(") &&
1201 findClosingBracket(*innerOut, std::string("ifelse").size()) == innerOut->size() - 1) {
1202 out += *innerOut;
1203 } else {
1204 out += in[i] + *innerOut + in[close];
1205 }
1206 i = close;
1207 }
1208 return out;
1209 }
1210
1211 // Find the ':' that belongs to this '?': a nested '?' comes with a ':' of its own, which is skipped.
1212 std::size_t colon = question;
1213 for (int nQuestions = 1; nQuestions > 0;) {
1214 colon = findTopLevel(in, "?:", colon + 1);
1215 if (colon == std::string::npos) {
1216 return std::nullopt;
1217 }
1218 nQuestions += in[colon] == '?' ? 1 : -1;
1219 }
1220
1221 const auto condition = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(0, question)));
1222 const auto ifTrue = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(question + 1, colon - question - 1)));
1223 const auto ifFalse = ternaryPartToIfElse(stripEnclosingParentheses(in.substr(colon + 1)));
1224 if (!condition || !ifTrue || !ifFalse || condition->empty() || ifTrue->empty() || ifFalse->empty()) {
1225 return std::nullopt;
1226 }
1227 return "ifelse(" + *condition + "," + *ifTrue + "," + *ifFalse + ")";
1228}
1229
1230// Rewrite the C-style ternaries "c ? a : b" in a TFormula expression into the HS3 conditional "ifelse(c,a,b)". Returns
1231// std::nullopt if this is not safely possible, e.g. because of unbalanced brackets.
1232std::optional<std::string> ternariesToIfElse(std::string const &in)
1233{
1234 std::string out;
1235 bool first = true;
1236 for (std::string const &part : splitTopLevelCommas(in)) {
1237 const std::optional<std::string> partOut = ternaryPartToIfElse(part);
1238 if (!partOut) {
1239 return std::nullopt;
1240 }
1241 out += (first ? "" : ",") + *partOut;
1242 first = false;
1243 }
1244 return out;
1245}
1246
1247// HS3 0.3 (HS3 PR #154) only allows expressions to refer to parameters, variables and functions.
1248void checkExpressionRefersToNoPdf(RooAbsArg const &formula, RooAbsCollection const &dependents)
1249{
1250 for (RooAbsArg const *dependent : dependents) {
1251 if (dynamic_cast<RooAbsPdf const *>(dependent)) {
1252 RooJSONFactoryWSTool::error(std::string("the expression of '") + formula.GetName() + "' refers to the pdf '" +
1253 dependent->GetName() + "', which HS3 doesn't allow");
1254 }
1255 }
1256}
1257
1258template <class RooArg_t>
1259void exportFormulaArg(RooJSONFactoryWSTool *, RooArg_t const &pdf, JSONNode &elem)
1260{
1261 checkExpressionRefersToNoPdf(pdf, pdf.dependents());
1262 TString expression(pdf.expression());
1263 cleanExpression(expression);
1264 // If the tokens follow the "x[#]" convention, the square braces enclosing each number
1265 // ensures that there is a unique mapping between the token and parameter name
1266 // If the tokens follow the "@#" convention, the numbers are not enclosed by braces.
1267 // So there may be tokens with numbers whose lower place value forms a subset string of ones with a higher place
1268 // value, e.g. "@1" is a subset of "@10". So the names of these parameters must be applied descending from the
1269 // highest place value in order to ensure each parameter name is uniquely applied to its token.
1270 for (size_t idx = pdf.nParameters(); idx--;) {
1271 const RooAbsArg *par = pdf.getParameter(idx);
1272 expression.ReplaceAll(("x[" + std::to_string(idx) + "]").c_str(), par->GetName());
1273 expression.ReplaceAll(("@" + std::to_string(idx)).c_str(), par->GetName());
1274 }
1275 if (expression.Contains("?")) {
1276 if (const auto rewritten = ternariesToIfElse(expression.Data())) {
1277 expression = rewritten->c_str();
1278 } else {
1279 RooJSONFactoryWSTool::warning(std::string("RooFitHS3: could not translate the ternary operators in the "
1280 "expression of '") +
1281 pdf.GetName() + "' to ifelse(), exporting the expression unchanged.");
1282 }
1283 }
1284 elem["expression"] << expression.Data();
1285
1286 for (const RooAbsArg *dependent : pdf.dependents()) {
1287 auto const *observable = dynamic_cast<const RooAbsRealLValue *>(dependent);
1288 if (!observable) {
1289 continue;
1290 }
1291 const RooAbsBinning *binning = pdf.getBinning(*observable);
1292 if (!binning) {
1293 continue;
1294 }
1295
1296 HS3::writeAxis(elem["axes"].set_seq().append_child(), HS3::toBinnedAxis(observable->GetName(), *binning));
1297 }
1298}
1299
1300// Write the "x" reference and the coefficient list for polynomial-like
1301// pdfs/funcs, including the implicit defaults below "lowestOrder" so that the
1302// output is self-documenting.
1303template <class RooArg_t>
1304void exportPolynomial(RooJSONFactoryWSTool *, RooArg_t const &pdf, JSONNode &elem)
1305{
1306 elem["x"] << pdf.x().GetName();
1307 auto &coefs = elem["coefficients"].set_seq();
1308 for (int i = 0; i < pdf.lowestOrder(); ++i) {
1309 coefs.append_child() << (i == 0 ? 1.0 : 0.0);
1310 }
1311 for (const auto &coef : pdf.coefList()) {
1312 writeReference(coefs.append_child(), *coef);
1313 }
1314}
1315
1316void exportPoisson(RooJSONFactoryWSTool *, RooPoisson const &pdf, JSONNode &elem)
1317{
1318 // It is registered for "poisson_dist", the discrete Poisson distribution.
1319 if (pdf.getNoRounding()) {
1320 elem["type"] << "poisson_continuous_dist";
1321 }
1322 writeReference(elem["x"], pdf.getX());
1323 writeReference(elem["mean"], pdf.getMean());
1324}
1325
1326// The RooDecay servers are the internal resModel-times-basis convolutions,
1327// which are implementation details that should not leak into the JSON. We
1328// only export the actual dependents (t, tau and the original resolution
1329// model) explicitly.
1330void exportDecay(RooJSONFactoryWSTool *tool, RooDecay const &pdf, JSONNode &elem)
1331{
1332 elem["t"] << pdf.getT().GetName();
1333 writeReference(elem["tau"], pdf.getTau());
1334 elem["resolutionModel"] << pdf.getModel().GetName();
1335 elem["decayType"] << pdf.getDecayType();
1336
1337 tool->queueExport(pdf.getT());
1338 tool->queueExport(pdf.getTau());
1339 tool->queueExport(pdf.getModel());
1340}
1341
1342// A Gaussian constraint whose recorded observable (see RooJSONFactoryWSTool::setConstraintObservable()) is its
1343// mean is written with x and mean swapped, so that the observable is x.
1344void exportGaussian(RooJSONFactoryWSTool *tool, RooGaussian const &gauss, JSONNode &elem)
1345{
1346 std::string const *observable = tool->constraintObservable(gauss.GetName());
1347 const bool swap = observable && *observable == gauss.getMean().GetName() && !isLiteralConstVar(gauss.getMean());
1348 writeReference(elem["x"], swap ? gauss.getMean() : gauss.getX());
1349 writeReference(elem["mean"], swap ? gauss.getX() : gauss.getMean());
1350 writeReference(elem["sigma"], gauss.getSigma());
1351}
1352
1353void exportLogNormal(RooJSONFactoryWSTool *tool, RooLognormal const &pdf, JSONNode &elem)
1354{
1355 writeReference(elem["x"], pdf.getX());
1356
1357 auto &m0 = pdf.getMedian();
1358 auto &k = pdf.getShapeK();
1359
1360 if (pdf.useStandardParametrization()) {
1361 writeReference(elem["mu"], m0);
1362 writeReference(elem["sigma"], k);
1363 } else {
1364 elem["mu"] << lognormalLogName(m0, tool);
1365 elem["sigma"] << lognormalLogName(k, tool);
1366 }
1367}
1368
1369void exportExponential(RooJSONFactoryWSTool *tool, RooExponential const &pdf, JSONNode &elem)
1370{
1371 elem["x"] << pdf.variable().GetName();
1372 auto &c = pdf.coefficient();
1373 if (pdf.negateCoefficient()) {
1374 writeReference(elem["c"], c);
1375 } else {
1376 elem["c"] << tool->exportTransformed(&c, "_exponential_inverted", "-%s");
1377 }
1378}
1379
1380void exportMultiVarGaussian(RooJSONFactoryWSTool *, RooMultiVarGaussian const &pdf, JSONNode &elem)
1381{
1382 RooJSONFactoryWSTool::fillSeq(elem["x"], pdf.xVec());
1383 RooJSONFactoryWSTool::fillSeq(elem["mean"], pdf.muVec());
1384 elem["covariances"].fill_mat(pdf.covarianceMatrix());
1385}
1386
1387void exportTFnBinding(RooJSONFactoryWSTool *, RooTFnBinding const &pdf, JSONNode &elem)
1388{
1389 checkExpressionRefersToNoPdf(pdf, pdf.observables());
1390 checkExpressionRefersToNoPdf(pdf, pdf.parameters());
1391 TString formula(pdf.function().GetExpFormula());
1392 formula.ReplaceAll("x", pdf.observables()[0].GetName());
1393 formula.ReplaceAll("y", pdf.observables()[1].GetName());
1394 formula.ReplaceAll("z", pdf.observables()[2].GetName());
1395 for (size_t i = 0; i < pdf.parameters().size(); ++i) {
1396 TString pname(TString::Format("[%d]", (int)i));
1397 formula.ReplaceAll(pname, pdf.parameters()[i].GetName());
1398 }
1399 elem["expression"] << formula.Data();
1400}
1401
1402void exportDerivative(RooJSONFactoryWSTool *, RooDerivative const &pdf, JSONNode &elem)
1403{
1404 elem["x"] << pdf.getX().GetName();
1405 elem["function"] << pdf.getFunc().GetName();
1406 if (!pdf.getNset().empty()) {
1407 RooJSONFactoryWSTool::fillSeq(elem["normalization"], pdf.getNset());
1408 }
1409 elem["order"] << pdf.order();
1410 elem["eps"] << pdf.eps();
1411}
1412
1413void exportRealIntegral(RooJSONFactoryWSTool *, RooRealIntegral const &integral, JSONNode &elem)
1414{
1415 std::string integrand = integral.integrand().GetName();
1416 elem["integrand"] << integrand;
1417 if (integral.intRange()) {
1418 elem["domain"] << integral.intRange();
1419 }
1420 RooJSONFactoryWSTool::fillSeq(elem["variables"], integral.intVars());
1421 if (RooArgSet const *funcNormSet = integral.funcNormSet()) {
1422 RooJSONFactoryWSTool::fillSeq(elem["normalization"], *funcNormSet);
1423 }
1424}
1425
1426void exportFFTConvPdf(RooJSONFactoryWSTool *, RooFFTConvPdf const &pdf, JSONNode &elem)
1427{
1428 if (auto convFunc = pdf.getPdfConvVar()) {
1429 elem["conv_func"] << convFunc->GetName();
1430 }
1431 elem["conv_var"] << pdf.getConvVar().GetName();
1432 elem["pdf1"] << pdf.getPdf1().GetName();
1433 elem["pdf2"] << pdf.getPdf2().GetName();
1434 elem["ipOrder"] << pdf.getInterpolationOrder();
1435}
1436
1437void exportExtendPdf(RooJSONFactoryWSTool *, RooExtendPdf const &pdf, JSONNode &elem)
1438{
1439 if (auto rangeName = pdf.getRangeName()) {
1440 elem["range"] << rangeName->GetName();
1441 }
1442 elem["dist"] << pdf.pdf().GetName();
1443 writeReference(elem["rate"], pdf.getN());
1444}
1445
1446void exportParamHistFunc(RooJSONFactoryWSTool *, ParamHistFunc const &pdf, JSONNode &elem)
1447{
1448 RooJSONFactoryWSTool::fillSeq(elem["variables"], pdf.dataVars());
1449 // One parameter per bin, in the order of HS3 (last axis fastest), not in ParamHistFunc's internal TH1 order.
1450 auto &paramsNode = elem["parameters"].set_seq();
1451 for (RooAbsReal *param : paramHistFuncParamsInBinOrder(pdf)) {
1452 writeReference(paramsNode.append_child(), *param);
1453 }
1454 auto &observablesNode = elem["axes"].set_seq();
1455 // axes have to be ordered to get consistent bin indices
1456 for (auto *var : static_range_cast<RooRealVar *>(pdf.dataVars())) {
1457 HS3::writeAxis(observablesNode.append_child(), HS3::toBinnedAxis(*var));
1458 }
1459}
1460
1461void exportSpline(RooJSONFactoryWSTool *, RooSpline const &rs, JSONNode &elem)
1462{
1463 elem["x"] << rs.x().GetName();
1464 elem["interpolation"] << (rs.order() == 5 ? "poly5" : "poly3");
1465 elem["logx"] << rs.logx();
1466 elem["logy"] << rs.logy();
1467
1468 // The knots
1469 TSpline const &sp = rs.spline();
1470 auto &x0 = elem["x0"].set_seq();
1471 auto &y0 = elem["y0"].set_seq();
1472 for (int i = 0; i < sp.GetNp(); ++i) {
1473 double xk = 0.0;
1474 double yk = 0.0;
1475 sp.GetKnot(i, xk, yk);
1476 x0.append_child() << xk;
1477 y0.append_child() << yk;
1478 }
1479}
1480
1481void exportBernstein(RooJSONFactoryWSTool *, RooBernstein const &pdf, JSONNode &elem)
1482{
1483 writeReference(elem["x"], pdf.x());
1484 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf.coefList());
1485}
1486
1487void exportLandau(RooJSONFactoryWSTool *, RooLandau const &pdf, JSONNode &elem)
1488{
1489 writeReference(elem["x"], pdf.getX());
1490 writeReference(elem["mu"], pdf.getMean());
1491 writeReference(elem["sigma"], pdf.getSigma());
1492}
1493
1494void exportProduct(RooJSONFactoryWSTool *, RooProduct const &prod, JSONNode &elem)
1495{
1496 RooJSONFactoryWSTool::fillSeq(elem["factors"], prod.realComponents());
1498}
1499
1500void exportUniform(RooJSONFactoryWSTool *, RooUniform const &pdf, JSONNode &elem)
1501{
1503}
1504
1505void importWrapperPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
1506{
1507 std::string name(RooJSONFactoryWSTool::name(p));
1508 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "function");
1509 // ROOT previously exported this key without an underscore.
1510 const char *key = p.has_child("self_normalized") ? "self_normalized" : "selfnormalized";
1511 const bool selfNormalized = p.has_child(key) && p[key].val_bool();
1512 tool->wsEmplace<RooWrapperPdf>(name, *func, selfNormalized);
1513}
1514
1515void exportWrapperPdf(RooJSONFactoryWSTool *, RooWrapperPdf const &pdf, JSONNode &elem)
1516{
1517 // RooWrapperPdf has no accessor for the wrapped function, which is its only proxy.
1518 auto const &funcProxy = dynamic_cast<RooRealProxy const &>(*pdf.getProxy(0));
1519 elem["function"] << funcProxy.absArg()->GetName();
1520 if (pdf.selfNormalized()) {
1521 elem["self_normalized"] << true;
1522 }
1523}
1524
1525///////////////////////////////////////////////////////////////////////////////////////////////////////
1526// instantiate all importers and exporters
1527///////////////////////////////////////////////////////////////////////////////////////////////////////
1528
1529// A class whose constructor takes nothing but objects and lists of objects, each of which it has a getter for, is
1530// read and written field by field. A field describes a constructor argument: its key in the document, and the getter
1531// that gives what is written.
1532
1533// An argument that is one object: requested as a T, and written as a reference to it.
1534template <class T, class Getter_t>
1535struct ObjectField {
1536 const char *key;
1537 Getter_t getter;
1538
1539 T &request(RooJSONFactoryWSTool &tool, const JSONNode &p) const { return *tool.requestArg<T>(p, key); }
1540 template <class RooArg_t>
1541 void write(RooArg_t const &arg, JSONNode &elem) const
1542 {
1543 writeReference(elem[key], (arg.*getter)());
1544 }
1545};
1546
1547// An argument that is a list of objects: requested as a Collection_t of T, and written as a list of references.
1548template <class T, class Collection_t, class Getter_t>
1549struct ListField {
1550 const char *key;
1551 Getter_t getter;
1552
1553 Collection_t request(RooJSONFactoryWSTool &tool, const JSONNode &p) const
1554 {
1555 return tool.requestCollection<T, Collection_t>(p, key);
1556 }
1557 template <class RooArg_t>
1558 void write(RooArg_t const &arg, JSONNode &elem) const
1559 {
1560 RooJSONFactoryWSTool::fillSeq(elem[key], (arg.*getter)());
1561 }
1562};
1563
1564template <class T = RooAbsReal, class Getter_t>
1565ObjectField<T, Getter_t> object(const char *key, Getter_t getter)
1566{
1567 return {key, getter};
1568}
1569
1570template <class T = RooAbsReal, class Collection_t = RooArgList, class Getter_t>
1571ListField<T, Collection_t, Getter_t> list(const char *key, Getter_t getter)
1572{
1573 return {key, getter};
1574}
1575
1576// Register the importer and the exporter of the class RooArg_t, whose constructor takes the name, the title and then
1577// the fields in the given order.
1578template <class RooArg_t, class... Fields_t>
1579void registerFields(const std::string &key, Fields_t... fields)
1580{
1581 auto importFields = [=](RooJSONFactoryWSTool *tool, const JSONNode &p) {
1582 const std::string name = RooJSONFactoryWSTool::name(p);
1583 // The braces guarantee that the fields are requested in their order.
1584 tool->wsImport(RooArg_t{name.c_str(), name.c_str(), fields.request(*tool, p)...});
1585 };
1586 auto exportFields = [=](RooJSONFactoryWSTool *, RooArg_t const &arg, JSONNode &elem) {
1587 (fields.write(arg, elem), ...);
1588 };
1589 registerImporter(key, importFields);
1590 registerExporter<RooArg_t>(key, exportFields);
1591}
1592
1593// A deprecated type key is still read by the importers of its replacement, with a warning the first time.
1594void registerDeprecatedKey(const std::string &key, const std::string &replacement)
1595{
1596 registerImporter(key, [=](RooJSONFactoryWSTool *tool, const JSONNode &p) {
1597 static std::set<std::string> warned;
1598 if (warned.insert(key).second) {
1599 RooJSONFactoryWSTool::warning("RooFitHS3: the type \"" + key + "\" is deprecated, please use \"" +
1600 replacement + "\" instead.");
1601 }
1602 auto const &importers = RooFit::JSONIO::importers().at(replacement);
1603 return std::any_of(importers.begin(), importers.end(),
1604 [&](auto const &importer) { return importer->importArg(tool, p); });
1605 });
1606}
1607
1608// Registers the importers and exporters when the library is loaded.
1609const bool registered = []() {
1610 registerType("bernstein_poly_dist", importBernstein, exportBernstein);
1611 registerType("binsampling_dist", importBinSamplingPdf, exportBinSamplingPdf);
1612 registerType("binvolume", importBinWidthFunction<false>, exportBinWidthFunction);
1613 registerType("crystalball_doublesided_dist", importCrystalBallDoubleSided, exportCrystalBall);
1614 registerType("decay_dist", importDecay, exportDecay, /*autoExportDependants=*/false);
1615 registerType("density_function_dist", importWrapperPdf, exportWrapperPdf);
1616 registerType("derivative", importDerivative, exportDerivative);
1617 registerType("exponential_dist", importExponential, exportExponential);
1618 registerType("fft_convolution_dist", importFFTConvPdf, exportFFTConvPdf);
1619 registerType("gaussian_dist", importGaussian, exportGaussian);
1620 registerType("generic", importFormulaArg<RooFormulaVar>, exportFormulaArg<RooFormulaVar>);
1621 registerType("generic_dist", importFormulaArg<RooGenericPdf>, exportFormulaArg<RooGenericPdf>);
1622 registerType("histogram_dist", importHist<RooHistPdf>, exportHist<RooHistPdf>);
1623 registerType("integral", importRealIntegral, exportRealIntegral);
1624 registerType("landau_dist", importLandau, exportLandau);
1625 registerType("legacy_exp_poly_dist", importPolynomial<RooLegacyExpPoly>, exportPolynomial<RooLegacyExpPoly>);
1626 registerType("lognormal_dist", importLogNormal, exportLogNormal);
1627 registerType("mixture_dist", importAddPdf, exportAddPdf<RooAddPdf>);
1628 registerType("mixture_model", importAddModel, exportAddPdf<RooAddModel>);
1629 registerType("multivariate_normal_dist", importMultiVarGaussian, exportMultiVarGaussian);
1630 registerType("poisson_dist", importPoisson<false>, exportPoisson);
1631 registerType("polynomial", importPolynomial<RooPolyVar>, exportPolynomial<RooPolyVar>);
1632 registerType("polynomial_dist", importPolynomial<RooPolynomial>, exportPolynomial<RooPolynomial>);
1633 registerType("product", importProduct, exportProduct);
1634 registerType("rate_extended_dist", importExtendPdf, exportExtendPdf);
1635 registerType("spline", importSpline, exportSpline);
1636 // A "step" with "data" is a histogram, otherwise it is a ParamHistFunc.
1637 registerType("step", importHist<RooHistFunc>, exportHist<RooHistFunc>);
1638 registerType("step", importParamHistFunc, exportParamHistFunc);
1639 registerType("uniform_dist", importUniform, exportUniform);
1640 registerType("weighted_sum_dist", importRealSumPdf, exportRealSumPdf);
1641
1642 // The classes that are read and written field by field.
1643 registerFields<RooArgusBG>("argus_dist", object("mass", &RooArgusBG::getM), object("resonance", &RooArgusBG::getM0),
1644 object("slope", &RooArgusBG::getC), object("power", &RooArgusBG::getP));
1645 registerFields<RooBifurGauss>("bifurkated_gaussian_dist", object("x", &RooBifurGauss::getX),
1646 object("mean", &RooBifurGauss::getMean), object("sigmaL", &RooBifurGauss::getSigmaL),
1647 object("sigmaR", &RooBifurGauss::getSigmaR));
1648 // A "crystalball_dist" with the fields of two tails is the double-sided Crystal Ball of documents before HS3 0.3.
1649 registerImporter("crystalball_dist", importLegacyDoubleSidedCrystalBall);
1650 registerFields<RooCBShape>("crystalball_dist", object("m", &RooCBShape::getM), object("m0", &RooCBShape::getM0),
1651 object("sigma", &RooCBShape::getSigma), object("alpha", &RooCBShape::getAlpha),
1652 object("n", &RooCBShape::getN));
1653 registerFields<RooChebychev>("chebychev_dist", object("x", &RooChebychev::x),
1654 list("coefficients", &RooChebychev::coefList));
1655 registerFields<RooEffProd>("efficiency_product_pdf_dist", object<RooAbsPdf>("pdf", &RooEffProd::pdf),
1656 object("eff", &RooEffProd::eff));
1657 registerFields<RooGamma>("gamma_dist", object("x", &RooGamma::getX), object("gamma", &RooGamma::getGamma),
1658 object("beta", &RooGamma::getBeta), object("mu", &RooGamma::getMu));
1659 registerFields<RooGaussModel>("gauss_model_function", object<RooRealVar>("x", &RooGaussModel::convVar),
1660 object("mean", &RooGaussModel::getMean), object("sigma", &RooGaussModel::getSigma));
1661 registerFields<RooPowerSum>("power_sum_dist", object("x", &RooPowerSum::base),
1662 list("coefficients", &RooPowerSum::coefList), list("exponents", &RooPowerSum::expList));
1663 registerFields<RooProdPdf>("product_dist", list<RooAbsPdf>("factors", &RooProdPdf::pdfList));
1664 registerFields<RooProjectedPdf>("projected_dist", object<RooAbsPdf>("input_pdf", &RooProjectedPdf::intPdf),
1665 list<RooAbsReal, RooArgSet>("observables", &RooProjectedPdf::intObs));
1666 registerFields<RooAddition>("sum", list("summands", &RooAddition::list));
1667 registerFields<RooTruthModel>("truth_model_function", object<RooRealVar>("x", &RooTruthModel::convVar));
1668 registerFields<RooRealSumFunc>("weighted_sum", list("samples", &RooRealSumFunc::funcList),
1669 list("coefficients", &RooRealSumFunc::coefList));
1670
1671 // A RooTFnBinding is written as a generic formula.
1672 registerExporter<RooTFnBinding>("generic", exportTFnBinding);
1673
1674 // The types that are only read: the ones that RooFit writes in another way, and other names of the types above.
1675 registerImporter("array_dist", importArrayDist);
1676 registerImporter("combined_dist", importCombinedDist);
1677 registerImporter("extend_pdf", importExtendPdf);
1678 registerImporter("generic_function", importFormulaArg<RooFormulaVar>);
1679 registerImporter("histogram", importHist<RooHistFunc>);
1680 registerImporter("inverse_binvolume", importBinWidthFunction<true>);
1681 registerImporter("normal_dist", importGaussian);
1682 registerImporter("poisson_continuous_dist", importPoisson<true>);
1683 registerDeprecatedKey("ARGUS_dist", "argus_dist");
1684 registerDeprecatedKey("binsampling", "binsampling_dist");
1685 registerDeprecatedKey("delta_resolution_model", "truth_model_function");
1686 registerDeprecatedKey("gauss_resolution_model", "gauss_model_function");
1687 registerDeprecatedKey("mixture_resolution_model", "mixture_model");
1688 return true;
1689}();
1690
1691} // namespace
1692
1693std::optional<ArrayComponentInfo>
1694arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable, RooJSONFactoryWSTool *tool)
1695{
1697 RooAbsReal const *x = nullptr;
1698 if (auto const *poisson = dynamic_cast<RooPoisson const *>(&pdf)) {
1699 out.type = poisson->getNoRounding() ? "poisson_continuous_dist" : "poisson_dist";
1700 x = &poisson->getX();
1701 out.fields = {{"mean", HS3::toNameOrNumber(poisson->getMean())}};
1702 } else if (auto const *gauss = dynamic_cast<RooGaussian const *>(&pdf)) {
1703 out.type = "gaussian_dist";
1704 x = &gauss->getX();
1705 RooAbsReal const *mean = &gauss->getMean();
1706 // A Gaussian constraint built by HistFactory has the parameter as x and the global observable as mean. The
1707 // Gaussian is symmetric in the two, so it is written with the observable as x where the observable is known.
1708 if (observable && *observable == mean->GetName() && !isLiteralConstVar(*mean)) {
1709 std::swap(x, mean);
1710 }
1711 out.fields = {{"mean", HS3::toNameOrNumber(*mean)}, {"sigma", HS3::toNameOrNumber(gauss->getSigma())}};
1712 } else if (auto const *lognormal = dynamic_cast<RooLognormal const *>(&pdf)) {
1713 out.type = "lognormal_dist";
1714 x = &lognormal->getX();
1715 if (lognormal->useStandardParametrization()) {
1716 out.fields = {{"mu", HS3::toNameOrNumber(lognormal->getMedian())},
1717 {"sigma", HS3::toNameOrNumber(lognormal->getShapeK())}};
1718 } else {
1719 out.fields = {{"mu", lognormalLogName(lognormal->getMedian(), tool)},
1720 {"sigma", lognormalLogName(lognormal->getShapeK(), tool)}};
1721 }
1722 } else {
1723 return std::nullopt;
1724 }
1725 // The observable of a component must be named: the observables are pairwise distinct and are paired with data.
1726 if (isLiteralConstVar(*x)) {
1727 return std::nullopt;
1728 }
1729 out.observable = x->GetName();
1730 return out;
1731}
1732
1733void writeArrayDist(RooJSONFactoryWSTool &tool, JSONNode &elem, std::string const &name,
1734 std::vector<RooAbsPdf const *> const &components)
1735{
1736 auto error = [&name](std::string const &message) {
1737 RooJSONFactoryWSTool::error("cannot write the array distribution '" + name + "': " + message);
1738 };
1739 if (components.empty()) {
1740 error("it has no components");
1741 }
1742 std::vector<ArrayComponentInfo> comps;
1743 std::set<std::string> observables;
1744 for (RooAbsPdf const *pdf : components) {
1745 auto comp = arrayComponentInfo(*pdf, tool.constraintObservable(pdf->GetName()), &tool);
1746 if (!comp) {
1747 error("'" + std::string(pdf->GetName()) +
1748 "' cannot be a component, only RooPoisson, RooGaussian and RooLognormal over a named observable "
1749 "are supported");
1750 }
1751 if (!comps.empty() && comp->type != comps.front().type) {
1752 error("the components '" + std::string(components.front()->GetName()) + "' (" + comps.front().type +
1753 ") and '" + pdf->GetName() + "' (" + comp->type + ") have different types");
1754 }
1755 if (!observables.insert(comp->observable).second) {
1756 error("two components have the observable '" + comp->observable + "'");
1757 }
1758 comps.push_back(std::move(*comp));
1759 }
1760
1761 elem["type"] << "array_dist";
1762 elem["component_type"] << comps.front().type;
1763
1764 auto write = [](JSONNode &node, HS3::NameOrNumber const &value) {
1765 std::visit([&node](auto const &v) { node << v; }, value);
1766 };
1767
1768 // A field with the same value in every component is written once in "default_parameters".
1769 std::set<std::string> defaultKeys;
1770 if (comps.size() > 1) {
1771 for (std::size_t i = 0; i < comps.front().fields.size(); ++i) {
1772 auto const &field = comps.front().fields[i];
1773 if (std::all_of(comps.begin(), comps.end(),
1774 [&](ArrayComponentInfo const &comp) { return comp.fields[i].second == field.second; })) {
1775 defaultKeys.insert(field.first);
1776 write(elem["default_parameters"].set_map()[field.first], field.second);
1777 }
1778 }
1779 }
1780
1781 JSONNode &seq = elem["components"].set_seq();
1782 for (ArrayComponentInfo const &comp : comps) {
1783 JSONNode &node = seq.append_child().set_map();
1784 node["x"] << comp.observable;
1785 for (auto const &field : comp.fields) {
1786 if (defaultKeys.find(field.first) == defaultKeys.end()) {
1787 write(node[field.first], field.second);
1788 }
1789 }
1790 }
1791}
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::string arrayComponentForm(std::string const &componentType, RooFit::Detail::JSONNode const &component, RooFit::Detail::JSONNode const *defaults)
A canonical form of the component component of an array distribution with the type componentType and ...
std::variant< std::string, double > NameOrNumber
A name, or a number for a constant.
Distribution parseDistribution(Detail::JSONNode const &distribution, Diagnostics &diagnostics)
Reads a distribution that doesn't come with a document.
void buildCombinedDist(RooJSONFactoryWSTool &tool, std::string const &name, CombinedDist const &dist, std::vector< std::string > const &otherLikelihoodTerms={})
Create the RooSimultaneous of a combined distribution in the workspace of the tool.
void report(Diagnostics const &diagnostics, std::string const &object="")
Forward the warnings to the message service, and throw if there are errors.
RooArgSet createObservables(std::vector< BinnedAxis > const &axes)
Create the variables for the axes of binned data.
std::string const * importedArrayComponentForm(RooJSONFactoryWSTool &tool, std::string const &name)
The canonical form (see arrayComponentForm()) of the component of an array distribution that this imp...
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
Definition HS3Parser.cxx:92
void recordImportedArrayComponent(RooJSONFactoryWSTool &tool, std::string const &name, std::string form)
Record that this import created the component name of an array distribution, with the canonical form ...
void writeAxis(Detail::JSONNode &node, BinnedAxis const &axis)
Writes an axis of binned data.
std::vector< Diagnostic > Diagnostics
NameOrNumber toNameOrNumber(RooAbsArg const &arg)
The name of an object, or the value of a literal constant.
BinnedAxis toBinnedAxis(RooRealVar const &var)
The axis of binned data for a variable, or for a binning of a variable with the given name.
std::vector< BinnedAxis > parseBinnedAxes(Detail::JSONNode const &axes, Diagnostics &diagnostics)
Reads the axes of binned data that doesn't come with a document.
void validateCombinedDist(CombinedDist const &dist, std::string const &name, Diagnostics &diagnostics)
ImportMap & importers()
Definition JSONIO.cxx:21
std::vector< std::pair< std::string, RooFit::HS3::NameOrNumber > > fields
Definition JSONIOUtils.h:69
std::string observable
Definition JSONIOUtils.h:68
std::string type
Definition JSONIOUtils.h:67
The axis of binned data.
TMarker m
Definition textangle.C:8
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335