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 <RooBinning.h>
21#include <RooBinSamplingPdf.h>
22#include <RooBinWidthFunction.h>
23#include <RooCBShape.h>
24#include <RooChebychev.h>
25#include <RooConstVar.h>
26#include <RooCrystalBall.h>
27#include <RooDataHist.h>
28#include <RooDecay.h>
29#include <RooDerivative.h>
30#include <RooEffProd.h>
31#include <RooExponential.h>
32#include <RooExtendPdf.h>
33#include <RooFFTConvPdf.h>
35#include <RooFitHS3/JSONIO.h>
36#include <RooFormulaVar.h>
37#include <RooGamma.h>
38#include <RooGaussian.h>
39#include <RooGenericPdf.h>
40#include <RooHistFunc.h>
41#include <RooHistPdf.h>
42#include <RooLandau.h>
43#include <RooLegacyExpPoly.h>
44#include <RooLognormal.h>
45#include <RooMultiVarGaussian.h>
47#include <RooAddition.h>
48#include <RooProduct.h>
49#include <RooProdPdf.h>
50#include <RooPoisson.h>
51#include <RooPolynomial.h>
52#include <RooPolyVar.h>
53#include <RooPowerSum.h>
54#include <RooProjectedPdf.h>
55#include <RooAbsRealLValue.h>
56#include <RooRealSumFunc.h>
57#include <RooRealSumPdf.h>
58#include <RooRealVar.h>
59#include <RooResolutionModel.h>
60#include <RooTFnBinding.h>
61#include <RooTruthModel.h>
62#include <RooGaussModel.h>
63#include <RooWrapperPdf.h>
64#include <RooRealIntegral.h>
65#include <RooSpline.h>
66#include <RooUniform.h>
67#include <RooUniformBinning.h>
68#include <TSpline.h>
69
70#include <TF1.h>
71
72#include <RooCategory.h>
73#include <RooSimultaneous.h>
74#include <RooSuperCategory.h>
75#include "JSONIOUtils.h"
76
77#include <optional>
78#include <type_traits>
79#include <variant>
80
81#include "static_execute.h"
82
83#include <algorithm>
84#include <cctype>
85#include <cmath>
86#include <limits>
87#include <memory>
88#include <initializer_list>
89#include <set>
90#include <sstream>
91#include <string_view>
92#include <vector>
93
95
96///////////////////////////////////////////////////////////////////////////////////////////////////////
97// individually implemented importers
98///////////////////////////////////////////////////////////////////////////////////////////////////////
99
100namespace {
101bool isReservedExpressionIdentifier(const std::string &arg)
102{
103 return arg == "PI" || arg == "EULER" || arg == "TMath";
104}
105
106/**
107 * Extracts arguments from a mathematical expression.
108 *
109 * This function takes a string representing a mathematical
110 * expression and extracts the arguments from it. The arguments are
111 * defined as sequences of characters that do not contain digits,
112 * spaces, or parentheses, and that start with a letter. Function
113 * calls such as "exp( ... )", identified as being followed by an
114 * opening parenthesis, are not treated as arguments. The extracted
115 * arguments are returned as a vector of strings.
116 *
117 * @param expr A string representing a mathematical expression.
118 * @return A set of unique strings representing the extracted arguments.
119 */
120std::set<std::string> extractArguments(std::string expr)
121{
122 // Get rid of whitespaces
123 expr.erase(std::remove_if(expr.begin(), expr.end(), [](unsigned char c) { return std::isspace(c); }), expr.end());
124
125 std::set<std::string> arguments;
126 size_t startidx = expr.size();
127 for (size_t i = 0; i < expr.size(); ++i) {
128 if (startidx >= expr.size()) {
129 if (isalpha(expr[i])) {
130 startidx = i;
131 // check this character is not part of scientific notation, e.g. 2e-5
132 if (TFormula::IsScientificNotation(expr, i)) {
133 // if it is, we ignore this character
134 startidx = expr.size();
135 }
136 }
137 } else {
138 if (!isdigit(expr[i]) && !isalpha(expr[i]) && expr[i] != '_') {
139 if (expr[i] == '(') {
140 startidx = expr.size();
141 continue;
142 }
143 std::string arg(expr.substr(startidx, i - startidx));
144 startidx = expr.size();
145 if (!isReservedExpressionIdentifier(arg)) {
146 arguments.insert(arg);
147 }
148 }
149 }
150 }
151 if (startidx < expr.size()) {
152 std::string arg(expr.substr(startidx));
153 if (!isReservedExpressionIdentifier(arg)) {
154 arguments.insert(arg);
155 }
156 }
157 return arguments;
158}
159
160void replaceIdentifier(TString &expr, std::string_view identifier, std::string_view replacement)
161{
162 std::string in(expr.Data());
163 std::string out;
164 out.reserve(in.size());
165
166 for (std::size_t pos = 0; pos < in.size();) {
167 const bool matches = in.compare(pos, identifier.size(), identifier) == 0;
168 const bool beforeIdentifier =
169 pos > 0 && (std::isalnum(static_cast<unsigned char>(in[pos - 1])) || in[pos - 1] == '_');
170 const std::size_t end = pos + identifier.size();
171 const bool afterIdentifier =
172 end < in.size() && (std::isalnum(static_cast<unsigned char>(in[end])) || in[end] == '_');
173 if (matches && !beforeIdentifier && !afterIdentifier) {
174 out.append(replacement);
175 pos = end;
176 } else {
177 out.push_back(in[pos]);
178 ++pos;
179 }
180 }
181
182 expr = out.c_str();
183}
184
185bool isIdentifierChar(char c)
186{
187 return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
188}
189
190std::string trimmed(std::string const &str)
191{
192 const auto begin = str.find_first_not_of(" \t\n");
193 if (begin == std::string::npos) {
194 return "";
195 }
196 return str.substr(begin, str.find_last_not_of(" \t\n") - begin + 1);
197}
198
199// Index of the bracket that closes the one at `open`, or std::string::npos if it is not closed.
200std::size_t findClosingBracket(std::string const &str, std::size_t open)
201{
202 int depth = 0;
203 for (std::size_t i = open; i < str.size(); ++i) {
204 if (str[i] == '(' || str[i] == '[') {
205 ++depth;
206 } else if ((str[i] == ')' || str[i] == ']') && --depth == 0) {
207 return i;
208 }
209 }
210 return std::string::npos;
211}
212
213// Split `str` at the commas that are not enclosed in brackets.
214std::vector<std::string> splitTopLevelCommas(std::string const &str)
215{
216 std::vector<std::string> parts;
217 int depth = 0;
218 std::size_t start = 0;
219 for (std::size_t i = 0; i < str.size(); ++i) {
220 if (str[i] == '(' || str[i] == '[') {
221 ++depth;
222 } else if (str[i] == ')' || str[i] == ']') {
223 --depth;
224 } else if (str[i] == ',' && depth == 0) {
225 parts.push_back(str.substr(start, i - start));
226 start = i + 1;
227 }
228 }
229 parts.push_back(str.substr(start));
230 return parts;
231}
232
233// Remove parentheses that enclose the whole string, e.g. "((a+b))" becomes "a+b".
234std::string stripEnclosingParentheses(std::string str)
235{
236 str = trimmed(str);
237 while (str.size() >= 2 && str.front() == '(' && findClosingBracket(str, 0) == str.size() - 1) {
238 str = trimmed(str.substr(1, str.size() - 2));
239 }
240 return str;
241}
242
243// Rewrite the HS3 conditional "ifelse(c,a,b)" into the C-style ternary "((c)?(a):(b))" that TFormula understands.
244// Malformed calls are left unchanged, so that TFormula reports them.
245std::string ifElseToTernary(std::string const &expr)
246{
247 static const std::string keyword = "ifelse";
248 std::string out;
249 std::size_t pos = 0;
250 while (pos < expr.size()) {
251 const std::size_t found = expr.find(keyword, pos);
252 if (found == std::string::npos) {
253 break;
254 }
255 const std::size_t open = expr.find_first_not_of(" \t", found + keyword.size());
256 const bool isCall =
257 (found == 0 || !isIdentifierChar(expr[found - 1])) && open != std::string::npos && expr[open] == '(';
258 const std::size_t close = isCall ? findClosingBracket(expr, open) : std::string::npos;
259 const auto args = close != std::string::npos ? splitTopLevelCommas(expr.substr(open + 1, close - open - 1))
260 : std::vector<std::string>{};
261 if (args.size() != 3) {
262 out += expr.substr(pos, found + keyword.size() - pos);
263 pos = found + keyword.size();
264 continue;
265 }
266 out += expr.substr(pos, found - pos);
267 out += "((" + ifElseToTernary(trimmed(args[0])) + ")?(" + ifElseToTernary(trimmed(args[1])) + "):(" +
268 ifElseToTernary(trimmed(args[2])) + "))";
269 pos = close + 1;
270 }
271 return out + expr.substr(pos);
272}
273
274void translateImportedExpression(TString &expr)
275{
276 replaceIdentifier(expr, "PI", "TMath::Pi()");
277 replaceIdentifier(expr, "EULER", "TMath::E()");
278 if (std::string(expr.Data()).find("ifelse") != std::string::npos) {
279 expr = ifElseToTernary(expr.Data()).c_str();
280 }
281}
282
283int readPositiveInteger(const JSONNode &node, const std::string &context)
284{
285 // Read through val_double() so an integer encoded as a JSON float (e.g. 1e6,
286 // whose textual form is "1e+06") is accepted like elsewhere in HS3, while
287 // fractional, non-finite, out-of-range or non-numeric values are rejected.
288 const double value = node.is_number() ? node.val_double() : std::numeric_limits<double>::quiet_NaN();
289 if (!std::isfinite(value) || value < 1.0 || value != std::floor(value) ||
290 value > static_cast<double>(std::numeric_limits<int>::max())) {
291 RooJSONFactoryWSTool::error("\"nbins\" in " + context + " must be a positive integer");
292 }
293 return static_cast<int>(value);
294}
295
296std::unique_ptr<RooAbsBinning>
297readFormulaAxisBinning(const JSONNode &axis, const std::string &axisName, const std::string &formulaName)
298{
299 const std::string context = "axis '" + axisName + "' of generic formula '" + formulaName + "'";
300 const bool hasEdges = axis.has_child("edges");
301 const bool hasMin = axis.has_child("min");
302 const bool hasMax = axis.has_child("max");
303 const bool hasNBins = axis.has_child("nbins");
304
305 if (hasEdges && hasNBins) {
306 RooJSONFactoryWSTool::error(context + " must use either \"edges\" or \"nbins\"");
307 }
308
309 if (hasEdges) {
310 const JSONNode &edgesNode = axis["edges"];
311 if (!edgesNode.is_seq()) {
312 RooJSONFactoryWSTool::error("\"edges\" in " + context + " must be a sequence");
313 }
314
315 std::vector<double> edges;
316 edges.reserve(edgesNode.num_children());
317 for (const JSONNode &edgeNode : edgesNode.children()) {
318 if (!edgeNode.is_number()) {
319 RooJSONFactoryWSTool::error("\"edges\" in " + context + " must contain only finite values");
320 }
321 const double edge = edgeNode.val_double();
322 if (!std::isfinite(edge)) {
323 RooJSONFactoryWSTool::error("\"edges\" in " + context + " must contain only finite values");
324 }
325 if (!edges.empty() && edge <= edges.back()) {
326 RooJSONFactoryWSTool::error("\"edges\" in " + context + " must be strictly increasing");
327 }
328 edges.push_back(edge);
329 }
330 if (edges.size() < 2) {
331 RooJSONFactoryWSTool::error("\"edges\" in " + context + " must contain at least two values");
332 }
333 // The HS3 standard requires "min" and "max" also for irregular binnings, which older versions of RooFit didn't
334 // write.
335 if ((hasMin && (!axis["min"].is_number() || axis["min"].val_double() != edges.front())) ||
336 (hasMax && (!axis["max"].is_number() || axis["max"].val_double() != edges.back()))) {
337 RooJSONFactoryWSTool::error("\"min\" and \"max\" in " + context + " must agree with the \"edges\"");
338 }
339 return std::make_unique<RooBinning>(static_cast<int>(edges.size() - 1), edges.data());
340 }
341
342 if (!hasMin || !hasMax || !hasNBins) {
343 RooJSONFactoryWSTool::error(context + " must define \"min\", \"max\", and \"nbins\"");
344 }
345
346 if (!axis["min"].is_number() || !axis["max"].is_number()) {
347 RooJSONFactoryWSTool::error("\"min\" and \"max\" in " + context + " must be finite and increasing");
348 }
349 const double min = axis["min"].val_double();
350 const double max = axis["max"].val_double();
351 if (!std::isfinite(min) || !std::isfinite(max) || max <= min) {
352 RooJSONFactoryWSTool::error("\"min\" and \"max\" in " + context + " must be finite and increasing");
353 }
354 return std::make_unique<RooUniformBinning>(min, max, readPositiveInteger(axis["nbins"], context));
355}
356
357template <class RooArg_t>
358void importFormulaBinnings(RooArg_t &arg, const JSONNode &node)
359{
360 if (!node.has_child("axes")) {
361 return;
362 }
363
364 const JSONNode &axes = node["axes"];
365 if (!axes.is_seq()) {
366 RooJSONFactoryWSTool::error("\"axes\" in generic formula '" + std::string(arg.GetName()) +
367 "' must be a sequence");
368 }
369
370 std::set<std::string> axisNames;
371 for (const JSONNode &axis : axes.children()) {
372 if (!axis.is_map() || !axis.has_child("name")) {
373 RooJSONFactoryWSTool::error("each axis in generic formula '" + std::string(arg.GetName()) +
374 "' must be a map with a \"name\"");
375 }
376 const std::string axisName = axis["name"].val();
377 if (!axisNames.insert(axisName).second) {
378 RooJSONFactoryWSTool::error("duplicate axis '" + axisName + "' in generic formula '" + arg.GetName() + "'");
379 }
380
381 auto *observable = dynamic_cast<RooAbsRealLValue *>(arg.getParameter(axisName.c_str()));
382 if (!observable) {
384 "axis '" + axisName + "' is not a real-valued formula variable of generic formula '" + arg.GetName() + "'");
385 }
386
387 std::unique_ptr<RooAbsBinning> binning = readFormulaAxisBinning(axis, axisName, arg.GetName());
388 arg.setBinning(*observable, *binning, /*checkFlatness=*/false);
389 }
390}
391
392template <class RooArg_t>
393bool importFormulaArg(RooJSONFactoryWSTool *tool, const JSONNode &p)
394{
395 std::string name(RooJSONFactoryWSTool::name(p));
396 if (!p.has_child("expression")) {
397 RooJSONFactoryWSTool::error("no expression given for '" + name + "'");
398 }
399 TString formula(p["expression"].val());
400 translateImportedExpression(formula);
401 RooArgList dependents;
402 for (const auto &d : extractArguments(formula.Data())) {
403 dependents.add(*tool->request<RooAbsReal>(d, name));
404 }
405 RooArg_t arg{name.c_str(), formula, dependents};
406 importFormulaBinnings(arg, p);
407 tool->wsImport(arg);
408 return true;
409}
410
411bool importProduct(RooJSONFactoryWSTool *tool, const JSONNode &p)
412{
413 std::string name(RooJSONFactoryWSTool::name(p));
414 tool->wsEmplace<RooProduct>(name, tool->requestArgList<RooAbsReal>(p, "factors"));
415 return true;
416}
417
418bool importProdPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
419{
420 std::string name(RooJSONFactoryWSTool::name(p));
421 tool->wsEmplace<RooProdPdf>(name, tool->requestArgList<RooAbsPdf>(p, "factors"));
422 return true;
423}
424
425// The name of the pdf that represents the component of an array distribution over the observable `observable`.
426std::string arrayComponentName(std::string const &observable)
427{
428 return observable + "_constraint";
429}
430
431// Copy the value of a JSON node, keeping numbers and booleans as such.
432void copyValue(JSONNode &target, JSONNode const &source)
433{
434 if (source.is_number()) {
435 target << source.val_double();
436 return;
437 }
438 const std::string value = source.val();
439 if (value == "true" || value == "false") {
440 target << (value == "true");
441 } else {
442 target << value;
443 }
444}
445
446// An HS3 `array_dist` is a product of one-dimensional distributions of one type (`component_type`), each over its own
447// observable `x`. RooFit has no dedicated class for it: every component is imported as an individual pdf of the
448// component type, named after its observable, and a RooProdPdf with the attribute `arrayDistTag` that carries the
449// name of the array holds them together, so that the array can be written back as `array_dist`. HistFactory modifiers
450// that name an array as the constraint of a parameter pick their component out of it (see
451// JSONFactories_HistFactory.cxx).
452bool importArrayDist(RooJSONFactoryWSTool *tool, const JSONNode &p)
453{
454 const std::string name = RooJSONFactoryWSTool::name(p);
455 auto error = [&name](std::string const &message) {
456 RooJSONFactoryWSTool::error("array_dist '" + name + "': " + message);
457 };
458
459 static const std::set<std::string> supportedComponentTypes{"poisson_dist", "poisson_continuous_dist",
460 "gaussian_dist", "normal_dist", "lognormal_dist"};
461 if (!p.has_child("component_type")) {
462 error("missing \"component_type\"");
463 }
464 const std::string componentType = p["component_type"].val();
465 if (supportedComponentTypes.find(componentType) == supportedComponentTypes.end()) {
466 error("the component_type '" + componentType +
467 "' is not supported, supported are poisson_dist, poisson_continuous_dist, gaussian_dist and "
468 "lognormal_dist");
469 }
470
471 const JSONNode *defaults = p.find("default_parameters");
472 if (defaults) {
473 if (!defaults->is_map()) {
474 error("\"default_parameters\" must be a struct");
475 }
476 if (defaults->has_child("x")) {
477 error("\"x\" must be given per component, not in \"default_parameters\"");
478 }
479 }
480 const JSONNode *components = p.find("components");
481 if (!components || !components->is_seq() || components->num_children() == 0) {
482 error("\"components\" must be a non-empty list");
483 }
484
485 RooWorkspace &ws = *tool->workspace();
486
487 // The components are imported through the importer of the component type, from a node per component that
488 // combines its own fields with the defaults.
490 JSONNode &nodes = tree->rootnode().set_seq();
491 std::vector<std::string> observables;
492 RooArgList pdfs;
493 for (JSONNode const &component : components->children()) {
494 const std::string context = "component " + std::to_string(observables.size());
495 if (!component.is_map()) {
496 error(context + " must be a struct");
497 }
498 const JSONNode *xNode = component.find("x");
499 if (!xNode) {
500 error(context + " has no \"x\"");
501 }
502 if (xNode->is_number() || !xNode->has_val()) {
503 error(context + ": \"x\" must be the name of the observable");
504 }
505 const std::string x = xNode->val();
506 if (std::find(observables.begin(), observables.end(), x) != observables.end()) {
507 error("the observable '" + x + "' is used by two components");
508 }
509 observables.push_back(x);
510
511 const std::string pdfName = arrayComponentName(x);
512 if (ws.arg(pdfName)) {
513 error("cannot create the component for '" + x + "' as '" + pdfName +
514 "', the workspace already has an object of that name");
515 }
516 JSONNode &node = nodes.append_child().set_map();
517 node["name"] << pdfName;
518 node["type"] << componentType;
519 if (defaults) {
520 for (JSONNode const &field : defaults->children()) {
521 copyValue(node[field.key()], field);
522 }
523 }
524 for (JSONNode const &field : component.children()) {
525 copyValue(node[field.key()], field);
526 }
527 tool->importFunction(node, true);
528 RooAbsPdf *pdf = ws.pdf(pdfName);
529 if (!pdf) {
530 error(context + " did not produce a distribution");
531 }
532 pdfs.add(*pdf);
533 }
534
535 // The parameters of a component must not depend on any observable of the array, otherwise the product would not
536 // be normalized.
537 for (std::size_t i = 0; i < observables.size(); ++i) {
538 RooAbsArg const *x = ws.arg(observables[i]);
539 if (!x) {
540 error("the observable '" + observables[i] + "' is not a parameter or function");
541 }
542 for (std::size_t k = 0; k < observables.size(); ++k) {
543 if (k != i && pdfs[i].dependsOn(*ws.arg(observables[k]))) {
544 error("component " + std::to_string(i) + " depends on the observable '" + observables[k] +
545 "' of component " + std::to_string(k));
546 }
547 }
548 for (RooAbsArg const *server : pdfs[i].servers()) {
549 if (server != x && server->dependsOn(*x)) {
550 error("the parameters of component " + std::to_string(i) + " depend on its own observable '" +
551 observables[i] + "'");
552 }
553 }
554 }
555
556 RooProdPdf array{name.c_str(), name.c_str(), pdfs};
557 array.setAttribute(arrayDistTag);
558 tool->wsImport(array);
559 return true;
560}
561
562// One field of a component of an array distribution: a name or a number.
563using ArrayFieldValue = std::variant<std::string, double>;
564
565struct ArrayComponent {
566 std::string type;
567 std::string x;
568 std::vector<std::pair<std::string, ArrayFieldValue>> fields;
569};
570
571ArrayFieldValue nameOrNumber(RooAbsReal const &arg)
572{
573 if (isLiteralConstVar(arg)) {
574 return static_cast<RooConstVar const &>(arg).getVal();
575 }
576 return std::string{arg.GetName()};
577}
578
579// The type, observable and fields of `pdf` as a component of an array distribution, with the fields of the standalone
580// exporters, or std::nullopt if `pdf` cannot be a component. A Gaussian whose mean is the recorded `observable` is
581// written with x and mean swapped.
582std::optional<ArrayComponent> arrayComponentOf(RooAbsPdf const &pdf, std::string const *observable = nullptr)
583{
584 ArrayComponent out;
585 RooAbsReal const *x = nullptr;
586 if (auto const *poisson = dynamic_cast<RooPoisson const *>(&pdf)) {
587 out.type = poisson->getNoRounding() ? "poisson_continuous_dist" : "poisson_dist";
588 x = &poisson->getX();
589 out.fields = {{"mean", nameOrNumber(poisson->getMean())}};
590 } else if (auto const *gauss = dynamic_cast<RooGaussian const *>(&pdf)) {
591 out.type = "gaussian_dist";
592 x = &gauss->getX();
593 RooAbsReal const *mean = &gauss->getMean();
594 // A Gaussian constraint built by HistFactory has the parameter as x and the global observable as mean. The
595 // Gaussian is symmetric in the two, so it is written with the observable as x where the observable is known.
596 if (observable && *observable == mean->GetName() && !isLiteralConstVar(*mean)) {
597 std::swap(x, mean);
598 }
599 out.fields = {{"mean", nameOrNumber(*mean)}, {"sigma", nameOrNumber(gauss->getSigma())}};
600 } else if (auto const *lognormal = dynamic_cast<RooLognormal const *>(&pdf)) {
601 if (!lognormal->useStandardParametrization()) {
602 return std::nullopt;
603 }
604 out.type = "lognormal_dist";
605 x = &lognormal->getX();
606 out.fields = {{"mu", nameOrNumber(lognormal->getMedian())}, {"sigma", nameOrNumber(lognormal->getShapeK())}};
607 } else {
608 return std::nullopt;
609 }
610 // The observable of a component must be named: the observables are pairwise distinct and are paired with data.
611 if (isLiteralConstVar(*x)) {
612 return std::nullopt;
613 }
614 out.x = x->GetName();
615 return out;
616}
617
618bool importAddition(RooJSONFactoryWSTool *tool, const JSONNode &p)
619{
620 std::string name(RooJSONFactoryWSTool::name(p));
621 tool->wsEmplace<RooAddition>(name, tool->requestArgList<RooAbsReal>(p, "summands"));
622 return true;
623}
624
625// A "combined_dist" is a RooSimultaneous. Its index category is the single column, or a RooSuperCategory over the
626// columns in the order of the document; the columns are categories declared by categorical axes of the domains.
627bool importCombinedDist(RooJSONFactoryWSTool *tool, const JSONNode &p)
628{
629 std::string const name(RooJSONFactoryWSTool::name(p));
630 std::string const context = "the combined_dist '" + name + "'";
631 // Whether a combined distribution is extended follows from its components; HS3 forbids declaring it.
632 if (p.has_child("extended")) {
633 RooJSONFactoryWSTool::error(context + " must not have \"extended\": whether it is extended follows from its " +
634 "components");
635 }
636 std::vector<RooCategory *> columns = readSelectionColumns(*tool->workspace(), p, "columns", context);
637
638 auto const *componentsNode = p.find("components");
639 if (!componentsNode || !componentsNode->is_seq() || componentsNode->num_children() == 0) {
640 RooJSONFactoryWSTool::error("\"components\" of " + context + " must be a non-empty list");
641 }
642 std::map<std::string, RooAbsPdf *> pdfMap;
643 for (JSONNode const &component : componentsNode->children()) {
644 if (!component.is_map() || !component.has_child("dist")) {
645 RooJSONFactoryWSTool::error("every component of " + context + " must have a \"key\" and a \"dist\"");
646 }
647 std::vector<std::string> const key = readSelectionKey(component, columns, context);
648 std::string const label = selectionLabel(key);
649 if (pdfMap.find(label) != pdfMap.end()) {
650 RooJSONFactoryWSTool::error("the key " + selectionKeyToString(key) + " is used by two components of " +
651 context);
652 }
653 pdfMap[label] = tool->request<RooAbsPdf>(component["dist"].val(), name);
654 }
655
656 if (columns.size() == 1) {
657 tool->wsImport(RooSimultaneous{name.c_str(), name.c_str(), pdfMap, *columns.front()});
658 return true;
659 }
660 RooArgSet inputs;
661 for (RooCategory *column : columns) {
662 inputs.add(*column);
663 }
664 std::string const indexName = name + "_index";
665 RooSuperCategory indexCat{indexName.c_str(), indexName.c_str(), inputs};
666 tool->wsImport(RooSimultaneous{name.c_str(), name.c_str(), pdfMap, indexCat});
667 return true;
668}
669
670bool importAddPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
671{
672 std::string name(RooJSONFactoryWSTool::name(p));
673 if (p.has_child("extended")) {
674 // Check the explicit "extended" flag against the number of coefficients, which determines the extended mode of
675 // the RooAddPdf.
676 const bool extended = p["extended"].val_bool();
677 const std::size_t nSummands = p.has_child("summands") ? p["summands"].num_children() : 0;
678 const std::size_t nCoefficients = p.has_child("coefficients") ? p["coefficients"].num_children() : 0;
679 const std::string counts =
680 std::to_string(nCoefficients) + " coefficients for " + std::to_string(nSummands) + " summands";
681 if (extended && nCoefficients > 0 && nCoefficients + 1 == nSummands) {
682 RooJSONFactoryWSTool::error("mixture_dist '" + name + "' is declared as extended, but it has " + counts +
683 ", which defines a non-extended mixture");
684 }
685 if (!extended && nCoefficients == 0 && nSummands > 0) {
686 RooJSONFactoryWSTool::error("mixture_dist '" + name + "' is declared as not extended, but it has " + counts +
687 ", which defines an extended mixture of extended distributions");
688 }
689 if (!extended && nCoefficients == nSummands) {
690 RooJSONFactoryWSTool::warning("RooFitHS3: mixture_dist '" + name + "' is declared as not extended, but " +
691 "RooFit can use it as extended because it has one coefficient per summand. " +
692 "Don't use the extended likelihood term when fitting it.");
693 }
694 }
695 if (!tool->requestArgList<RooAbsReal>(p, "coefficients").empty()) {
696 tool->wsEmplace<RooAddPdf>(name, tool->requestArgList<RooAbsPdf>(p, "summands"),
697 tool->requestArgList<RooAbsReal>(p, "coefficients"));
698 return true;
699 }
700 tool->wsEmplace<RooAddPdf>(name, tool->requestArgList<RooAbsPdf>(p, "summands"));
701 return true;
702}
703
704bool importAddModel(RooJSONFactoryWSTool *tool, const JSONNode &p)
705{
706 std::string name(RooJSONFactoryWSTool::name(p));
707 tool->wsEmplace<RooAddModel>(name, tool->requestArgList<RooAbsPdf>(p, "summands"),
708 tool->requestArgList<RooAbsReal>(p, "coefficients"));
709 return true;
710}
711
712template <bool DivideByBinWidth>
713bool importBinWidthFunction(RooJSONFactoryWSTool *tool, const JSONNode &p)
714{
715 std::string name(RooJSONFactoryWSTool::name(p));
716 RooHistFunc *hf = dynamic_cast<RooHistFunc *>(tool->request<RooAbsReal>(p["histogram"].val(), name));
717 if (!hf) {
718 RooJSONFactoryWSTool::error("histogram '" + p["histogram"].val() + "' of '" + name + "' is not a RooHistFunc");
719 }
720 tool->wsEmplace<RooBinWidthFunction>(name, *hf, DivideByBinWidth);
721 return true;
722}
723
724bool importBinSamplingPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
725{
726 std::string name(RooJSONFactoryWSTool::name(p));
727
728 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, "pdf");
729 RooRealVar *obs = tool->requestArg<RooRealVar>(p, "observable");
730
731 if (!pdf->dependsOn(*obs)) {
732 RooJSONFactoryWSTool::error(std::string("pdf '") + pdf->GetName() + "' does not depend on observable '" +
733 obs->GetName() + "' as indicated by parent RooBinSamplingPdf '" + name +
734 "', please check!");
735 }
736
737 if (!p.has_child("epsilon")) {
738 RooJSONFactoryWSTool::error("no epsilon given in '" + name + "'");
739 }
740 double epsilon(p["epsilon"].val_double());
741
742 tool->wsEmplace<RooBinSamplingPdf>(name, *obs, *pdf, epsilon);
743
744 return true;
745}
746
747template <class RooArg_t>
748bool importRealSum(RooJSONFactoryWSTool *tool, const JSONNode &p)
749{
750 std::string name(RooJSONFactoryWSTool::name(p));
751 RooArgList samples = tool->requestArgList<RooAbsReal>(p, "samples");
752 RooArgList coefs = tool->requestArgList<RooAbsReal>(p, "coefficients");
753 if constexpr (std::is_same_v<RooArg_t, RooRealSumPdf>) {
754 const bool extended = p.has_child("extended") && p["extended"].val_bool();
755 tool->wsEmplace<RooRealSumPdf>(name, samples, coefs, extended);
756 } else {
757 tool->wsEmplace<RooArg_t>(name, samples, coefs);
758 }
759 return true;
760}
761
762template <class RooArg_t>
763bool importPolynomial(RooJSONFactoryWSTool *tool, const JSONNode &p)
764{
765 std::string name(RooJSONFactoryWSTool::name(p));
766 if (!p.has_child("coefficients")) {
767 RooJSONFactoryWSTool::error("no coefficients given in '" + name + "'");
768 }
769 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
770 RooArgList coefs;
771 int order = 0;
772 int lowestOrder = 0;
773 for (const auto &coef : p["coefficients"].children()) {
774 // As long as the coefficients match the default coefficients in
775 // RooFit, we don't have to instantiate RooFit objects but can
776 // increase the lowestOrder flag.
777 if (order == 0 && (coef.val() == "1.0" || coef.val() == "1")) {
778 ++lowestOrder;
779 } else if (coefs.empty() && (coef.val() == "0.0" || coef.val() == "0")) {
780 ++lowestOrder;
781 } else {
782 coefs.add(*tool->request<RooAbsReal>(coef.val(), name));
783 }
784 ++order;
785 }
786
787 tool->wsEmplace<RooArg_t>(name, *x, coefs, lowestOrder);
788 return true;
789}
790
791// HS3 0.3 distinguishes the discrete "poisson_dist" from the "poisson_continuous_dist" (HS3 #152), which are a
792// RooPoisson without and with noRounding. Before, ROOT wrote both as "poisson_dist" with its own key "integer", where
793// false denotes the continuous form. That key is read for documents before HS3 0.3, without it the discrete form is
794// meant. From HS3 0.3 on, it must not be present.
795template <bool Continuous>
796bool importPoisson(RooJSONFactoryWSTool *tool, const JSONNode &p)
797{
798 std::string name(RooJSONFactoryWSTool::name(p));
799 bool noRounding = Continuous;
800 if (p.has_child("integer")) {
801 std::string const type = Continuous ? "poisson_continuous_dist" : "poisson_dist";
802 if (Continuous || !isHS3VersionBefore(tool->hs3VersionInput(), 0, 3)) {
804 type + " '" + name +
805 "' has the key \"integer\", which is not part of HS3. The discrete Poisson distribution is "
806 "\"poisson_dist\" and the continuous one is \"poisson_continuous_dist\".");
807 }
808 noRounding = !p["integer"].val_bool();
809 }
810 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
811 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
812 tool->wsEmplace<RooPoisson>(name, *x, *mean, noRounding);
813 return true;
814}
815
816bool importDecay(RooJSONFactoryWSTool *tool, const JSONNode &p)
817{
818 std::string name(RooJSONFactoryWSTool::name(p));
819 RooRealVar *t = tool->requestArg<RooRealVar>(p, "t");
820 RooAbsReal *tau = tool->requestArg<RooAbsReal>(p, "tau");
821 // HS3 lists some resolution models as functions.
823 if (!model) {
824 RooJSONFactoryWSTool::error("resolutionModel of '" + name + "' is not a RooResolutionModel");
825 }
826 RooDecay::DecayType decayType = static_cast<RooDecay::DecayType>(p["decayType"].val_int());
827 tool->wsEmplace<RooDecay>(name, *t, *tau, *model, decayType);
828 return true;
829}
830
831bool importTruthModel(RooJSONFactoryWSTool *tool, const JSONNode &p)
832{
833 std::string name(RooJSONFactoryWSTool::name(p));
834 RooRealVar *x = tool->requestArg<RooRealVar>(p, "x");
835 tool->wsEmplace<RooTruthModel>(name, *x);
836 return true;
837}
838
839bool importGaussModel(RooJSONFactoryWSTool *tool, const JSONNode &p)
840{
841 std::string name(RooJSONFactoryWSTool::name(p));
842 RooRealVar *x = tool->requestArg<RooRealVar>(p, "x");
843 RooRealVar *mean = tool->requestArg<RooRealVar>(p, "mean");
844 RooRealVar *sigma = tool->requestArg<RooRealVar>(p, "sigma");
845 tool->wsEmplace<RooGaussModel>(name, *x, *mean, *sigma);
846 return true;
847}
848
849bool importRealIntegral(RooJSONFactoryWSTool *tool, const JSONNode &p)
850{
851 std::string name(RooJSONFactoryWSTool::name(p));
852 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "integrand");
853 auto vars = tool->requestArgList<RooAbsReal>(p, "variables");
854 RooArgSet normSet;
855 RooArgSet const *normSetPtr = nullptr;
856 if (p.has_child("normalization")) {
857 normSet.add(tool->requestArgSet<RooAbsReal>(p, "normalization"));
858 normSetPtr = &normSet;
859 }
860 std::string domain;
861 bool hasDomain = p.has_child("domain");
862 if (hasDomain) {
863 domain = p["domain"].val();
864 }
865 // todo: at some point, take care of integrator configurations
866 tool->wsEmplace<RooRealIntegral>(name, *func, vars, normSetPtr, static_cast<RooNumIntConfig *>(nullptr),
867 hasDomain ? domain.c_str() : nullptr);
868 return true;
869}
870
871bool importDerivative(RooJSONFactoryWSTool *tool, const JSONNode &p)
872{
873 std::string name(RooJSONFactoryWSTool::name(p));
874 RooAbsReal *func = tool->requestArg<RooAbsReal>(p, "function");
875 RooRealVar *x = tool->requestArg<RooRealVar>(p, "x");
876 Int_t order = p["order"].val_int();
877 double eps = p["eps"].val_double();
878 if (p.has_child("normalization")) {
879 RooArgSet normSet;
880 normSet.add(tool->requestArgSet<RooAbsReal>(p, "normalization"));
881 tool->wsEmplace<RooDerivative>(name, *func, *x, normSet, order, eps);
882 return true;
883 }
884 tool->wsEmplace<RooDerivative>(name, *func, *x, order, eps);
885 return true;
886}
887
888bool importFFTConvPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
889{
890 std::string name(RooJSONFactoryWSTool::name(p));
891 RooRealVar *convVar = tool->requestArg<RooRealVar>(p, "conv_var");
892 Int_t order = p["ipOrder"].val_int();
893 RooAbsPdf *pdf1 = tool->requestArg<RooAbsPdf>(p, "pdf1");
894 RooAbsPdf *pdf2 = tool->requestArg<RooAbsPdf>(p, "pdf2");
895 if (p.has_child("conv_func")) {
896 RooAbsReal *convFunc = tool->requestArg<RooAbsReal>(p, "conv_func");
897 tool->wsEmplace<RooFFTConvPdf>(name, *convFunc, *convVar, *pdf1, *pdf2, order);
898 return true;
899 }
900 tool->wsEmplace<RooFFTConvPdf>(name, *convVar, *pdf1, *pdf2, order);
901 return true;
902}
903
904bool importExtendPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
905{
906 std::string name(RooJSONFactoryWSTool::name(p));
907 // HS3 calls the fields "dist" and "rate". RooFit used to write "pdf" and "norm", which are still accepted.
908 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, p.has_child("pdf") && !p.has_child("dist") ? "pdf" : "dist");
909 RooAbsReal *norm = tool->requestArg<RooAbsReal>(p, p.has_child("norm") && !p.has_child("rate") ? "norm" : "rate");
910 if (p.has_child("range")) {
911 std::string rangeName = p["range"].val();
912 tool->wsEmplace<RooExtendPdf>(name, *pdf, *norm, rangeName.c_str());
913 return true;
914 }
915 tool->wsEmplace<RooExtendPdf>(name, *pdf, *norm);
916 return true;
917}
918
919bool importLogNormal(RooJSONFactoryWSTool *tool, const JSONNode &p)
920{
921 std::string name(RooJSONFactoryWSTool::name(p));
922 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
923
924 // Same mechanism to undo the parameter transformation as in the
925 // importExponential() function (see comments in that function for more info).
926 const std::string muName = p["mu"].val();
927 const std::string sigmaName = p["sigma"].val();
928 const bool isTransformed = endsWith(muName, "_lognormal_log");
929 const std::string suffixToRemove = isTransformed ? "_lognormal_log" : "";
930 RooAbsReal *mu = tool->request<RooAbsReal>(removeSuffix(muName, suffixToRemove), name);
931 RooAbsReal *sigma = tool->request<RooAbsReal>(removeSuffix(sigmaName, suffixToRemove), name);
932
933 tool->wsEmplace<RooLognormal>(name, *x, *mu, *sigma, !isTransformed);
934
935 return true;
936}
937
938bool importExponential(RooJSONFactoryWSTool *tool, const JSONNode &p)
939{
940 std::string name(RooJSONFactoryWSTool::name(p));
941 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
942
943 // If the parameter name ends with the "_exponential_inverted" suffix,
944 // this means that it was exported from a RooFit object where the
945 // parameter first needed to be transformed on export to match the HS3
946 // specification. But when re-importing such a parameter, we can simply
947 // skip the transformation and use the original RooFit parameter without
948 // the suffix.
949 //
950 // A concrete example: take the following RooFit pdf in the factory language:
951 //
952 // "Exponential::exponential_1(x[0, 10], c[-0.1])"
953 //
954 // It defines en exponential exp(c * x). However, in HS3 the exponential
955 // is defined as exp(-c * x), to RooFit would export these dictionaries
956 // to the JSON:
957 //
958 // {
959 // "name": "exponential_1", // HS3 exponential_dist with transformed parameter
960 // "type": "exponential_dist",
961 // "x": "x",
962 // "c": "c_exponential_inverted"
963 // },
964 // {
965 // "name": "c_exponential_inverted", // transformation function created on-the-fly on export
966 // "type": "generic",
967 // "expression": "-c"
968 // }
969 //
970 // On import, we can directly take the non-transformed parameter, which is
971 // we check for the suffix and optionally remove it from the requested
972 // name next:
973
974 const std::string constParamName = p["c"].val();
975 const bool isInverted = endsWith(constParamName, "_exponential_inverted");
976 const std::string suffixToRemove = isInverted ? "_exponential_inverted" : "";
977 RooAbsReal *c = tool->request<RooAbsReal>(removeSuffix(constParamName, suffixToRemove), name);
978
979 tool->wsEmplace<RooExponential>(name, *x, *c, !isInverted);
980
981 return true;
982}
983
984bool importMultiVarGaussian(RooJSONFactoryWSTool *tool, const JSONNode &p)
985{
986 std::string name(RooJSONFactoryWSTool::name(p));
987 bool has_cov = p.has_child("covariances");
988 bool has_corr = p.has_child("correlations") && p.has_child("standard_deviations");
989 if (!has_cov && !has_corr) {
990 RooJSONFactoryWSTool::error("no covariances or correlations+standard_deviations given in '" + name + "'");
991 }
992
993 TMatrixDSym covmat;
994
995 // The matrix must be square, otherwise the entries would be written out of bounds.
996 auto checkSquare = [&](const char *key, std::size_t n) {
997 if (p[key].num_children() != n) {
998 RooJSONFactoryWSTool::error("\"" + std::string(key) + "\" in '" + name + "' must have " + std::to_string(n) +
999 " rows");
1000 }
1001 for (const auto &row : p[key].children()) {
1002 if (!row.is_seq() || row.num_children() != n) {
1003 RooJSONFactoryWSTool::error("\"" + std::string(key) + "\" in '" + name + "' must be a square matrix");
1004 }
1005 }
1006 };
1007
1008 if (has_cov) {
1009 int n = p["covariances"].num_children();
1010 checkSquare("covariances", n);
1011 int i = 0;
1012 covmat.ResizeTo(n, n);
1013 for (const auto &row : p["covariances"].children()) {
1014 int j = 0;
1015 for (const auto &val : row.children()) {
1016 covmat(i, j) = val.val_double();
1017 ++j;
1018 }
1019 ++i;
1020 }
1021 } else {
1022 std::vector<double> variances;
1023 variances << p["standard_deviations"];
1024 checkSquare("correlations", variances.size());
1025 covmat.ResizeTo(variances.size(), variances.size());
1026 int i = 0;
1027 for (const auto &row : p["correlations"].children()) {
1028 int j = 0;
1029 for (const auto &val : row.children()) {
1030 covmat(i, j) = val.val_double() * variances[i] * variances[j];
1031 ++j;
1032 }
1033 ++i;
1034 }
1035 }
1037 tool->requestArgList<RooAbsReal>(p, "mean"), covmat);
1038 return true;
1039}
1040
1041/// Read the binning variables from the "axes" node, ordered like in `varList`.
1042RooArgList readBinning(const JSONNode &topNode, const RooArgList &varList)
1043{
1045 RooArgList vars;
1046 for (RooAbsArg *refVar : varList) {
1047 if (RooAbsArg *axis = axes.find(*refVar)) {
1048 vars.addClone(*axis);
1049 }
1050 }
1051 return vars;
1052}
1053
1054bool importParamHistFunc(RooJSONFactoryWSTool *tool, const JSONNode &p)
1055{
1056 if (!p.has_child("parameters")) {
1057 return false;
1058 }
1059 std::string name(RooJSONFactoryWSTool::name(p));
1060 RooArgList varList = tool->requestArgList<RooRealVar>(p, "variables");
1061 if (!p.has_child("axes")) {
1062 std::stringstream ss;
1063 ss << "No axes given in '" << name << "'"
1064 << ". Using default binning (uniform; nbins=100). If needed, export the Workspace to JSON with a newer "
1065 << "Root version that supports custom ParamHistFunc binnings(>=6.38.00)." << std::endl;
1067 checkParamHistFuncOrderIsDefined(tool->hs3VersionInput(), varList, "the ParamHistFunc '" + name + "'");
1068 tool->wsEmplace<ParamHistFunc>(name, varList,
1069 toParamHistFuncOrder(tool->requestArgList<RooAbsReal>(p, "parameters"), varList));
1070 return true;
1071 }
1072 RooArgList binning = readBinning(p, varList);
1073 checkParamHistFuncOrderIsDefined(tool->hs3VersionInput(), binning, "the ParamHistFunc '" + name + "'");
1074 // The parameters are given in the order of HS3 (last axis fastest); ParamHistFunc expects TH1 order.
1075 tool->wsEmplace<ParamHistFunc>(name, binning,
1076 toParamHistFuncOrder(tool->requestArgList<RooAbsReal>(p, "parameters"), binning));
1077 return true;
1078}
1079
1080bool importSpline(RooJSONFactoryWSTool *tool, const JSONNode &p)
1081{
1082 const std::string name(RooJSONFactoryWSTool::name(p));
1083
1084 // Mandatory fields
1085 if (!p.has_child("x")) {
1086 RooJSONFactoryWSTool::error("no x given in '" + name + "'");
1087 }
1088 if (!p.has_child("x0") || !p.has_child("y0")) {
1089 RooJSONFactoryWSTool::error("no x0/y0 given in '" + name + "'");
1090 }
1091
1092 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
1093
1094 // Optional fields (defaults follow RooSpline ctor defaults)
1095 std::string algo = p.has_child("interpolation") ? p["interpolation"].val() : "poly3";
1096 int order = 0;
1097 if (algo == "poly3") {
1098 order = 3;
1099 } else if (algo == "poly5") {
1100 order = 5;
1101 } else {
1102 RooJSONFactoryWSTool::error("unsupported algo '" + algo + "' for RooSpline in '" + name +
1103 "': allowed are 'poly3' and 'poly5'");
1104 }
1105 const bool logx = p.has_child("logx") ? p["logx"].val_bool() : false;
1106 const bool logy = p.has_child("logy") ? p["logy"].val_bool() : false;
1107
1108 // Read knots
1109 std::vector<double> x0;
1110 std::vector<double> y0;
1111 x0 << p["x0"];
1112 y0 << p["y0"];
1113
1114 if (x0.size() != y0.size()) {
1115 RooJSONFactoryWSTool::error("x0/y0 size mismatch in '" + name + "': x0 has " + std::to_string(x0.size()) +
1116 ", y0 has " + std::to_string(y0.size()));
1117 }
1118 if (x0.size() < 2) {
1119 RooJSONFactoryWSTool::error("need at least 2 knots in '" + name + "'");
1120 }
1121
1122 // Construct RooSpline(name,title, x, x0, y0, order, logx, logy)
1123 tool->wsEmplace<::RooSpline>(name.c_str(), *x, std::span<const double>(x0.data(), x0.size()),
1124 std::span<const double>(y0.data(), y0.size()), order, logx, logy);
1125
1126 return true;
1127}
1128
1129bool importArgus(RooJSONFactoryWSTool *tool, const JSONNode &p)
1130{
1131 std::string name(RooJSONFactoryWSTool::name(p));
1132 RooAbsReal *mass = tool->requestArg<RooAbsReal>(p, "mass");
1133 RooAbsReal *resonance = tool->requestArg<RooAbsReal>(p, "resonance");
1134 RooAbsReal *slope = tool->requestArg<RooAbsReal>(p, "slope");
1135 RooAbsReal *power = tool->requestArg<RooAbsReal>(p, "power");
1136 tool->wsEmplace<RooArgusBG>(name, *mass, *resonance, *slope, *power);
1137 return true;
1138}
1139
1140bool importBernstein(RooJSONFactoryWSTool *tool, const JSONNode &p)
1141{
1142 std::string name(RooJSONFactoryWSTool::name(p));
1143 auto *x = dynamic_cast<RooAbsRealLValue *>(tool->requestArg<RooAbsReal>(p, "x"));
1144 if (!x) {
1145 RooJSONFactoryWSTool::error("\"x\" of '" + name + "' is not a variable");
1146 }
1147 tool->wsEmplace<RooBernstein>(name, *x, tool->requestArgList<RooAbsReal>(p, "coefficients"));
1148 return true;
1149}
1150
1151bool importBifurGauss(RooJSONFactoryWSTool *tool, const JSONNode &p)
1152{
1153 std::string name(RooJSONFactoryWSTool::name(p));
1154 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
1155 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
1156 RooAbsReal *sigmaL = tool->requestArg<RooAbsReal>(p, "sigmaL");
1157 RooAbsReal *sigmaR = tool->requestArg<RooAbsReal>(p, "sigmaR");
1158 tool->wsEmplace<RooBifurGauss>(name, *x, *mean, *sigmaL, *sigmaR);
1159 return true;
1160}
1161
1162bool importChebychev(RooJSONFactoryWSTool *tool, const JSONNode &p)
1163{
1164 std::string name(RooJSONFactoryWSTool::name(p));
1165 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
1166 tool->wsEmplace<RooChebychev>(name, *x, tool->requestArgList<RooAbsReal>(p, "coefficients"));
1167 return true;
1168}
1169
1170bool importEffProd(RooJSONFactoryWSTool *tool, const JSONNode &p)
1171{
1172 std::string name(RooJSONFactoryWSTool::name(p));
1173 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, "pdf");
1174 RooAbsReal *eff = tool->requestArg<RooAbsReal>(p, "eff");
1175 tool->wsEmplace<RooEffProd>(name, *pdf, *eff);
1176 return true;
1177}
1178
1179bool importGamma(RooJSONFactoryWSTool *tool, const JSONNode &p)
1180{
1181 std::string name(RooJSONFactoryWSTool::name(p));
1182 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
1183 RooAbsReal *gamma = tool->requestArg<RooAbsReal>(p, "gamma");
1184 RooAbsReal *beta = tool->requestArg<RooAbsReal>(p, "beta");
1185 RooAbsReal *mu = tool->requestArg<RooAbsReal>(p, "mu");
1186 tool->wsEmplace<RooGamma>(name, *x, *gamma, *beta, *mu);
1187 return true;
1188}
1189
1190bool importGaussian(RooJSONFactoryWSTool *tool, const JSONNode &p)
1191{
1192 std::string name(RooJSONFactoryWSTool::name(p));
1193 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
1194 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
1195 RooAbsReal *sigma = tool->requestArg<RooAbsReal>(p, "sigma");
1196 tool->wsEmplace<RooGaussian>(name, *x, *mean, *sigma);
1197 return true;
1198}
1199
1200bool importLandau(RooJSONFactoryWSTool *tool, const JSONNode &p)
1201{
1202 std::string name(RooJSONFactoryWSTool::name(p));
1203 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
1204 RooAbsReal *mean = tool->requestArg<RooAbsReal>(p, "mean");
1205 RooAbsReal *sigma = tool->requestArg<RooAbsReal>(p, "sigma");
1206 tool->wsEmplace<RooLandau>(name, *x, *mean, *sigma);
1207 return true;
1208}
1209
1210bool importPowerSum(RooJSONFactoryWSTool *tool, const JSONNode &p)
1211{
1212 std::string name(RooJSONFactoryWSTool::name(p));
1213 RooAbsReal *x = tool->requestArg<RooAbsReal>(p, "x");
1214 RooArgList coefs = tool->requestArgList<RooAbsReal>(p, "coefficients");
1215 RooArgList exps = tool->requestArgList<RooAbsReal>(p, "exponents");
1216 tool->wsEmplace<RooPowerSum>(name, *x, coefs, exps);
1217 return true;
1218}
1219
1220bool importProjectedPdf(RooJSONFactoryWSTool *tool, const JSONNode &p)
1221{
1222 std::string name(RooJSONFactoryWSTool::name(p));
1223 RooAbsPdf *pdf = tool->requestArg<RooAbsPdf>(p, "input_pdf");
1224 tool->wsEmplace<RooProjectedPdf>(name, *pdf, tool->requestArgSet<RooAbsReal>(p, "observables"));
1225 return true;
1226}
1227
1228bool importUniform(RooJSONFactoryWSTool *tool, const JSONNode &p)
1229{
1230 std::string name(RooJSONFactoryWSTool::name(p));
1231 // A single observable may also be given by its name.
1232 if (p.has_child("x") && !p["x"].is_seq()) {
1233 tool->wsEmplace<RooUniform>(name, RooArgSet{*tool->requestArg<RooAbsReal>(p, "x")});
1234 return true;
1235 }
1236 tool->wsEmplace<RooUniform>(name, tool->requestArgSet<RooAbsReal>(p, "x"));
1237 return true;
1238}
1239
1240// Importer that is registered with top priority for a deprecated type key. It warns once, and then lets the importers
1241// that are registered for the deprecated key do the actual work.
1242class DeprecatedKeyImporter : public RooFit::JSONIO::Importer {
1243public:
1244 DeprecatedKeyImporter(std::string key, std::string replacement)
1245 : _key{std::move(key)}, _replacement{std::move(replacement)}
1246 {
1247 }
1248 bool importArg(RooJSONFactoryWSTool *, const JSONNode &) const override
1249 {
1250 if (!_warned) {
1251 RooJSONFactoryWSTool::warning("RooFitHS3: the type \"" + _key + "\" is deprecated, please use \"" +
1252 _replacement + "\" instead.");
1253 _warned = true;
1254 }
1255 return false;
1256 }
1257
1258private:
1259 const std::string _key;
1260 const std::string _replacement;
1261 mutable bool _warned = false;
1262};
1263
1264namespace CrystalBall {
1265
1266// The keys of the tails of the double-sided Crystal Ball.
1267const std::initializer_list<const char *> tailKeys = {"alpha_L", "n_L", "alpha_R", "n_R"};
1268
1269bool hasAny(const JSONNode &p, std::initializer_list<const char *> keys)
1270{
1271 for (const char *key : keys) {
1272 if (p.has_child(key)) {
1273 return true;
1274 }
1275 }
1276 return false;
1277}
1278
1279bool hasDoubleSidedKeys(const JSONNode &p)
1280{
1281 return hasAny(p, tailKeys) || hasAny(p, {"sigma_L", "sigma_R"});
1282}
1283
1284// Create a RooCrystalBall with two tails. With `symmetricShorthand`, the tails may also be given as "alpha" and "n"
1285// for both sides, as in the "crystalball_dist" of HS3 versions before 0.3.
1286void importDoubleSided(RooJSONFactoryWSTool *tool, const JSONNode &p, std::string const &type, bool symmetricShorthand)
1287{
1288 const std::string name(RooJSONFactoryWSTool::name(p));
1289 const std::string context = type + " '" + name + "'";
1290
1291 const bool asymmetricTails = hasAny(p, tailKeys);
1292 const bool symmetricTails = hasAny(p, {"alpha", "n"});
1293 if (symmetricTails && !symmetricShorthand) {
1294 RooJSONFactoryWSTool::error(context + " must not have \"alpha\" or \"n\", the tails are given by \"alpha_L\", " +
1295 "\"n_L\", \"alpha_R\" and \"n_R\"");
1296 }
1297 if (symmetricTails && asymmetricTails) {
1299 " must not combine \"alpha\"/\"n\" with \"alpha_L\"/\"n_L\"/\"alpha_R\"/\"n_R\"");
1300 }
1301 if (asymmetricTails || !symmetricTails) {
1302 for (const char *key : tailKeys) {
1303 if (!p.has_child(key)) {
1304 RooJSONFactoryWSTool::error(context + " is missing \"" + key +
1305 "\": \"alpha_L\", \"n_L\", \"alpha_R\" and \"n_R\" are all required");
1306 }
1307 }
1308 } else if (!p.has_child("alpha") || !p.has_child("n")) {
1309 RooJSONFactoryWSTool::error(context + " needs both \"alpha\" and \"n\"");
1310 }
1311
1312 const bool asymmetricWidths = hasAny(p, {"sigma_L", "sigma_R"});
1313 if (asymmetricWidths && p.has_child("sigma")) {
1314 RooJSONFactoryWSTool::error(context + " must not combine \"sigma\" with \"sigma_L\"/\"sigma_R\"");
1315 }
1316 if (asymmetricWidths && !(p.has_child("sigma_L") && p.has_child("sigma_R"))) {
1317 RooJSONFactoryWSTool::error(context + " needs both \"sigma_L\" and \"sigma_R\"");
1318 }
1319 if (!asymmetricWidths && !p.has_child("sigma")) {
1320 RooJSONFactoryWSTool::error(context + " needs either \"sigma\" or both \"sigma_L\" and \"sigma_R\"");
1321 }
1322
1323 RooAbsReal *m = tool->requestArg<RooAbsReal>(p, "m");
1324 RooAbsReal *m0 = tool->requestArg<RooAbsReal>(p, "m0");
1325 RooAbsReal *sigmaL = tool->requestArg<RooAbsReal>(p, asymmetricWidths ? "sigma_L" : "sigma");
1326 RooAbsReal *sigmaR = tool->requestArg<RooAbsReal>(p, asymmetricWidths ? "sigma_R" : "sigma");
1327 RooAbsReal *alphaL = tool->requestArg<RooAbsReal>(p, symmetricTails ? "alpha" : "alpha_L");
1328 RooAbsReal *nL = tool->requestArg<RooAbsReal>(p, symmetricTails ? "n" : "n_L");
1329 RooAbsReal *alphaR = tool->requestArg<RooAbsReal>(p, symmetricTails ? "alpha" : "alpha_R");
1330 RooAbsReal *nR = tool->requestArg<RooAbsReal>(p, symmetricTails ? "n" : "n_R");
1331 tool->wsEmplace<RooCrystalBall>(name, *m, *m0, *sigmaL, *sigmaR, *alphaL, *nL, *alphaR, *nR);
1332}
1333
1334} // namespace CrystalBall
1335
1336// "crystalball_dist" is the single-sided Crystal Ball (RooCBShape). Before HS3 0.3, it was also the double-sided
1337// Crystal Ball, recognizable by the "_L"/"_R" fields. Such documents are still read, with a deprecation warning.
1338class CrystalBallImporter : public RooFit::JSONIO::Importer {
1339public:
1340 bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override
1341 {
1342 if (!CrystalBall::hasDoubleSidedKeys(p)) {
1343 std::string name(RooJSONFactoryWSTool::name(p));
1344 RooAbsReal *m = tool->requestArg<RooAbsReal>(p, "m");
1345 RooAbsReal *m0 = tool->requestArg<RooAbsReal>(p, "m0");
1346 RooAbsReal *sigma = tool->requestArg<RooAbsReal>(p, "sigma");
1347 RooAbsReal *alpha = tool->requestArg<RooAbsReal>(p, "alpha");
1348 RooAbsReal *n = tool->requestArg<RooAbsReal>(p, "n");
1349 tool->wsEmplace<RooCBShape>(name, *m, *m0, *sigma, *alpha, *n);
1350 return true;
1351 }
1352 if (!_warned) {
1353 RooJSONFactoryWSTool::warning("RooFitHS3: \"crystalball_dist\" with the fields \"alpha_L\", \"n_L\", "
1354 "\"alpha_R\", \"n_R\", \"sigma_L\" or \"sigma_R\" is deprecated, please use "
1355 "\"crystalball_doublesided_dist\" for the double-sided Crystal Ball.");
1356 _warned = true;
1357 }
1358 CrystalBall::importDoubleSided(tool, p, "crystalball_dist", /*symmetricShorthand=*/true);
1359 return true;
1360 }
1361
1362private:
1363 mutable bool _warned = false;
1364};
1365
1366bool importCrystalBallDoubleSided(RooJSONFactoryWSTool *tool, const JSONNode &p)
1367{
1368 CrystalBall::importDoubleSided(tool, p, "crystalball_doublesided_dist", /*symmetricShorthand=*/false);
1369 return true;
1370}
1371
1372///////////////////////////////////////////////////////////////////////////////////////////////////////
1373// specialized exporter implementations
1374///////////////////////////////////////////////////////////////////////////////////////////////////////
1375
1376// A RooCrystalBall with one tail is the single-sided "crystalball_dist" (read back as RooCBShape, which follows the
1377// same convention for the sign of alpha). With two tails, it is a "crystalball_doublesided_dist", whose tails are
1378// always written as "alpha_L"/"n_L"/"alpha_R"/"n_R": there is no shorthand for symmetric tails.
1379bool exportCrystalBall(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1380{
1381 auto const *pdf = static_cast<const RooCrystalBall *>(func);
1382 writeReference(elem["m"], pdf->x());
1383 writeReference(elem["m0"], pdf->x0());
1384 if (!pdf->alphaR() || !pdf->nR()) {
1385 elem["type"] << "crystalball_dist";
1386 writeReference(elem["sigma"], pdf->sigmaL());
1387 writeReference(elem["alpha"], pdf->alphaL());
1388 writeReference(elem["n"], pdf->nL());
1389 return true;
1390 }
1391 elem["type"] << key;
1392 if (&pdf->sigmaL() == &pdf->sigmaR()) {
1393 writeReference(elem["sigma"], pdf->sigmaL());
1394 } else {
1395 writeReference(elem["sigma_L"], pdf->sigmaL());
1396 writeReference(elem["sigma_R"], pdf->sigmaR());
1397 }
1398 writeReference(elem["alpha_L"], pdf->alphaL());
1399 writeReference(elem["n_L"], pdf->nL());
1400 writeReference(elem["alpha_R"], *pdf->alphaR());
1401 writeReference(elem["n_R"], *pdf->nR());
1402 return true;
1403}
1404
1405template <class RooArg_t>
1406bool exportAddPdf(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1407{
1408 const RooArg_t *pdf = static_cast<const RooArg_t *>(func);
1409 elem["type"] << key;
1410 RooJSONFactoryWSTool::fillSeq(elem["summands"], pdf->pdfList());
1411 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList());
1412 elem["extended"] << (pdf->extendMode() != RooArg_t::CanNotBeExtended);
1413 return true;
1414}
1415
1416template <class RooArg_t>
1417bool exportRealSum(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1418{
1419 auto const *pdf = static_cast<const RooArg_t *>(func);
1420 elem["type"] << key;
1421 RooJSONFactoryWSTool::fillSeq(elem["samples"], pdf->funcList());
1422 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList());
1423 if constexpr (std::is_same_v<RooArg_t, RooRealSumPdf>) {
1424 elem["extended"] << (pdf->extendMode() != RooAbsPdf::CanNotBeExtended);
1425 }
1426 return true;
1427}
1428
1429template <class RooArg_t>
1430bool exportHist(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1431{
1432 const RooArg_t *hf = static_cast<const RooArg_t *>(func);
1433 elem["type"] << key;
1434 RooDataHist const &dh = hf->dataHist();
1435 // The axes are named after the observables of the function, which are not necessarily the variables of the
1436 // histogram.
1437 auto vars = histogramVariablesNamedAfterObservables(dh, hf->getHistObsList(), hf->variables());
1438 tool->exportHisto(*vars, dh.numEntries(), dh.weightArray(), elem["data"].set_map());
1439 return true;
1440}
1441
1442template <class RooArg_t>
1443bool importHist(RooJSONFactoryWSTool *tool, const JSONNode &p)
1444{
1445 std::string name(RooJSONFactoryWSTool::name(p));
1446 if (!p.has_child("data")) {
1447 return false;
1448 }
1449 std::unique_ptr<RooDataHist> dataHist =
1451 tool->wsEmplace<RooArg_t>(name, *dataHist->get(), *dataHist);
1452 return true;
1453}
1454
1455bool exportBinSamplingPdf(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1456{
1457 const RooBinSamplingPdf *pdf = static_cast<const RooBinSamplingPdf *>(func);
1458 elem["type"] << key;
1459 elem["pdf"] << pdf->pdf().GetName();
1460 elem["observable"] << pdf->observable().GetName();
1461 elem["epsilon"] << pdf->epsilon();
1462 return true;
1463}
1464
1465bool exportBinWidthFunction(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &)
1466{
1467 const RooBinWidthFunction *pdf = static_cast<const RooBinWidthFunction *>(func);
1468 elem["type"] << (pdf->divideByBinWidth() ? "inverse_binvolume" : "binvolume");
1469 elem["histogram"] << pdf->histFunc().GetName();
1470 return true;
1471}
1472
1473void cleanExpression(TString &expr)
1474{
1475 // Plain substring replacement would also hit longer identifiers that
1476 // share a prefix (e.g. "TMath::Tan" in "TMath::TanH", or "TMath::Pi" in
1477 // "TMath::PiOver2"), corrupting the exported expression. Identifiers
1478 // without a replacement are kept as-is.
1479 replaceIdentifier(expr, "TMath::Exp", "exp");
1480 replaceIdentifier(expr, "TMath::Min", "min");
1481 replaceIdentifier(expr, "TMath::Max", "max");
1482 replaceIdentifier(expr, "TMath::Log", "log");
1483 replaceIdentifier(expr, "TMath::Log10", "log10");
1484 replaceIdentifier(expr, "TMath::Cos", "cos");
1485 replaceIdentifier(expr, "TMath::CosH", "cosh");
1486 replaceIdentifier(expr, "TMath::Sin", "sin");
1487 replaceIdentifier(expr, "TMath::SinH", "sinh");
1488 replaceIdentifier(expr, "TMath::Sqrt", "sqrt");
1489 replaceIdentifier(expr, "TMath::Power", "pow");
1490 replaceIdentifier(expr, "TMath::Erf", "erf");
1491 replaceIdentifier(expr, "TMath::Erfc", "erfc");
1492 replaceIdentifier(expr, "TMath::Floor", "floor");
1493 replaceIdentifier(expr, "TMath::Ceil", "ceil");
1494 replaceIdentifier(expr, "TMath::Abs", "abs");
1495 replaceIdentifier(expr, "TMath::Tan", "tan");
1496 replaceIdentifier(expr, "TMath::TanH", "tanh");
1497 replaceIdentifier(expr, "TMath::ASin", "asin");
1498 replaceIdentifier(expr, "TMath::ACos", "acos");
1499 replaceIdentifier(expr, "TMath::ATan", "atan");
1500 replaceIdentifier(expr, "TMath::ATan2", "atan2");
1501 replaceIdentifier(expr, "TMath::Pi()", "PI");
1502 replaceIdentifier(expr, "TMath::E()", "EULER");
1503}
1504
1505bool ternariesToIfElse(std::string const &in, std::string &out);
1506
1507// Rewrite one comma-free part of an expression, see ternariesToIfElse().
1508bool ternaryPartToIfElse(std::string const &in, std::string &out)
1509{
1510 // Find the first '?' that is not enclosed in brackets. A ':' that is not part of "::" can only follow a '?'.
1511 std::size_t question = std::string::npos;
1512 int depth = 0;
1513 for (std::size_t i = 0; i < in.size() && question == std::string::npos; ++i) {
1514 const char c = in[i];
1515 if (c == '(' || c == '[') {
1516 ++depth;
1517 } else if (c == ')' || c == ']') {
1518 --depth;
1519 } else if (c == ':' && i + 1 < in.size() && in[i + 1] == ':') {
1520 ++i;
1521 } else if (depth == 0 && c == ':') {
1522 return false;
1523 } else if (depth == 0 && c == '?') {
1524 question = i;
1525 } else if (depth == 0 && c == ',') {
1526 return false;
1527 }
1528 }
1529
1530 if (question == std::string::npos) {
1531 // No ternary on this level: copy the expression and rewrite the ternaries inside of brackets.
1532 out.clear();
1533 for (std::size_t i = 0; i < in.size(); ++i) {
1534 if (in[i] == ')' || in[i] == ']') {
1535 return false;
1536 }
1537 if (in[i] != '(' && in[i] != '[') {
1538 out += in[i];
1539 continue;
1540 }
1541 const std::size_t close = findClosingBracket(in, i);
1542 if (close == std::string::npos) {
1543 return false;
1544 }
1545 const std::string inner = in.substr(i + 1, close - i - 1);
1546 std::string innerOut;
1547 if (!ternariesToIfElse(inner, innerOut)) {
1548 return false;
1549 }
1550 // Parentheses that only group a ternary are redundant around the ifelse() function call.
1551 const std::string before = trimmed(in.substr(0, i));
1552 const bool isGrouping = in[i] == '(' && (before.empty() || !isIdentifierChar(before.back()));
1553 if (isGrouping && innerOut != trimmed(inner) && startsWith(innerOut, "ifelse(") &&
1554 findClosingBracket(innerOut, std::string("ifelse").size()) == innerOut.size() - 1) {
1555 out += innerOut;
1556 } else {
1557 out += in[i] + innerOut + in[close];
1558 }
1559 i = close;
1560 }
1561 return true;
1562 }
1563
1564 // Find the ':' that belongs to this '?', taking nested ternaries into account.
1565 std::size_t colon = std::string::npos;
1566 int nested = 0;
1567 depth = 0;
1568 for (std::size_t i = question + 1; i < in.size() && colon == std::string::npos; ++i) {
1569 const char c = in[i];
1570 if (c == '(' || c == '[') {
1571 ++depth;
1572 } else if (c == ')' || c == ']') {
1573 --depth;
1574 } else if (c == ':' && i + 1 < in.size() && in[i + 1] == ':') {
1575 ++i;
1576 } else if (depth == 0 && c == '?') {
1577 ++nested;
1578 } else if (depth == 0 && c == ':') {
1579 if (nested == 0) {
1580 colon = i;
1581 } else {
1582 --nested;
1583 }
1584 }
1585 }
1586 if (colon == std::string::npos) {
1587 return false;
1588 }
1589
1590 std::string condition;
1591 std::string ifTrue;
1592 std::string ifFalse;
1593 if (!ternaryPartToIfElse(stripEnclosingParentheses(in.substr(0, question)), condition) ||
1594 !ternaryPartToIfElse(stripEnclosingParentheses(in.substr(question + 1, colon - question - 1)), ifTrue) ||
1595 !ternaryPartToIfElse(stripEnclosingParentheses(in.substr(colon + 1)), ifFalse)) {
1596 return false;
1597 }
1598 if (condition.empty() || ifTrue.empty() || ifFalse.empty()) {
1599 return false;
1600 }
1601 out = "ifelse(" + condition + "," + ifTrue + "," + ifFalse + ")";
1602 return true;
1603}
1604
1605// Rewrite the C-style ternaries "c ? a : b" in a TFormula expression into the HS3 conditional "ifelse(c,a,b)". Returns
1606// false if this is not safely possible, e.g. because of unbalanced brackets.
1607bool ternariesToIfElse(std::string const &in, std::string &out)
1608{
1609 out.clear();
1610 bool first = true;
1611 for (std::string const &part : splitTopLevelCommas(in)) {
1612 std::string partOut;
1613 if (!ternaryPartToIfElse(part, partOut)) {
1614 return false;
1615 }
1616 out += (first ? "" : ",") + partOut;
1617 first = false;
1618 }
1619 return true;
1620}
1621
1622template <class RooArg_t>
1623bool exportFormulaArg(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1624{
1625 const RooArg_t *pdf = static_cast<const RooArg_t *>(func);
1626 elem["type"] << key;
1627 TString expression(pdf->expression());
1628 cleanExpression(expression);
1629 // If the tokens follow the "x[#]" convention, the square braces enclosing each number
1630 // ensures that there is a unique mapping between the token and parameter name
1631 // If the tokens follow the "@#" convention, the numbers are not enclosed by braces.
1632 // So there may be tokens with numbers whose lower place value forms a subset string of ones with a higher place
1633 // value, e.g. "@1" is a subset of "@10". So the names of these parameters must be applied descending from the
1634 // highest place value in order to ensure each parameter name is uniquely applied to its token.
1635 for (size_t idx = pdf->nParameters(); idx--;) {
1636 const RooAbsArg *par = pdf->getParameter(idx);
1637 expression.ReplaceAll(("x[" + std::to_string(idx) + "]").c_str(), par->GetName());
1638 expression.ReplaceAll(("@" + std::to_string(idx)).c_str(), par->GetName());
1639 }
1640 if (expression.Contains("?")) {
1641 std::string rewritten;
1642 if (ternariesToIfElse(expression.Data(), rewritten)) {
1643 expression = rewritten.c_str();
1644 } else {
1645 RooJSONFactoryWSTool::warning(std::string("RooFitHS3: could not translate the ternary operators in the "
1646 "expression of '") +
1647 func->GetName() + "' to ifelse(), exporting the expression unchanged.");
1648 }
1649 }
1650 elem["expression"] << expression.Data();
1651
1652 for (const RooAbsArg *dependent : pdf->dependents()) {
1653 auto const *observable = dynamic_cast<const RooAbsRealLValue *>(dependent);
1654 if (!observable) {
1655 continue;
1656 }
1657 const RooAbsBinning *binning = pdf->getBinning(*observable);
1658 if (!binning) {
1659 continue;
1660 }
1661
1662 auto &axes = elem["axes"];
1663 if (!axes.is_seq()) {
1664 axes.set_seq();
1665 }
1666 auto &axis = axes.append_child().set_map();
1667 axis["name"] << observable->GetName();
1668 writeAxisBinning(axis, *binning);
1669 }
1670 return true;
1671}
1672
1673// Write the "x" reference and the coefficient list for polynomial-like
1674// pdfs/funcs, including the implicit defaults below "lowestOrder" so that the
1675// output is self-documenting.
1676template <class RooArg_t>
1677bool exportPolynomial(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1678{
1679 auto const *pdf = static_cast<const RooArg_t *>(func);
1680 elem["type"] << key;
1681 elem["x"] << pdf->x().GetName();
1682 auto &coefs = elem["coefficients"].set_seq();
1683 for (int i = 0; i < pdf->lowestOrder(); ++i) {
1684 coefs.append_child() << (i == 0 ? 1.0 : 0.0);
1685 }
1686 for (const auto &coef : pdf->coefList()) {
1687 coefs.append_child() << coef->GetName();
1688 }
1689 return true;
1690}
1691
1692bool exportPoisson(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1693{
1694 auto *pdf = static_cast<const RooPoisson *>(func);
1695 elem["type"] << (pdf->getNoRounding() ? "poisson_continuous_dist" : key);
1696 elem["x"] << pdf->getX().GetName();
1697 elem["mean"] << pdf->getMean().GetName();
1698 return true;
1699}
1700
1701// The RooDecay servers are the internal resModel-times-basis convolutions,
1702// which are implementation details that should not leak into the JSON. We
1703// only export the actual dependents (t, tau and the original resolution
1704// model) explicitly.
1705bool exportDecay(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1706{
1707 auto *pdf = static_cast<const RooDecay *>(func);
1708 elem["type"] << key;
1709 elem["t"] << pdf->getT().GetName();
1710 elem["tau"] << pdf->getTau().GetName();
1711 elem["resolutionModel"] << pdf->getModel().GetName();
1712 elem["decayType"] << pdf->getDecayType();
1713
1714 tool->queueExport(pdf->getT());
1715 tool->queueExport(pdf->getTau());
1716 tool->queueExport(pdf->getModel());
1717
1718 return true;
1719}
1720
1721bool exportTruthModel(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1722{
1723 auto *pdf = static_cast<const RooTruthModel *>(func);
1724 elem["type"] << key;
1725 elem["x"] << pdf->convVar().GetName();
1726
1727 return true;
1728}
1729
1730bool exportGaussModel(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1731{
1732 auto *pdf = static_cast<const RooGaussModel *>(func);
1733 elem["type"] << key;
1734 elem["x"] << pdf->convVar().GetName();
1735 elem["mean"] << pdf->getMean().GetName();
1736 elem["sigma"] << pdf->getSigma().GetName();
1737 return true;
1738}
1739
1740// A Gaussian constraint whose recorded observable (see RooJSONFactoryWSTool::setConstraintObservable()) is its
1741// mean is written with x and mean swapped, so that the observable is x.
1742bool exportGaussian(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1743{
1744 auto const *gauss = static_cast<RooGaussian const *>(func);
1745 std::string const *observable = tool->constraintObservable(gauss->GetName());
1746 const bool swap = observable && *observable == gauss->getMean().GetName() && !isLiteralConstVar(gauss->getMean());
1747 elem["type"] << key;
1748 writeReference(elem["x"], swap ? gauss->getMean() : gauss->getX());
1749 writeReference(elem["mean"], swap ? gauss->getX() : gauss->getMean());
1750 writeReference(elem["sigma"], gauss->getSigma());
1751 return true;
1752}
1753
1754bool exportLogNormal(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1755{
1756 auto *pdf = static_cast<const RooLognormal *>(func);
1757
1758 elem["type"] << key;
1759 elem["x"] << pdf->getX().GetName();
1760
1761 auto &m0 = pdf->getMedian();
1762 auto &k = pdf->getShapeK();
1763
1764 if (pdf->useStandardParametrization()) {
1765 elem["mu"] << m0.GetName();
1766 elem["sigma"] << k.GetName();
1767 } else {
1768 elem["mu"] << tool->exportTransformed(&m0, "_lognormal_log", "log(%s)");
1769 elem["sigma"] << tool->exportTransformed(&k, "_lognormal_log", "log(%s)");
1770 }
1771
1772 return true;
1773}
1774
1775bool exportExponential(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1776{
1777 auto *pdf = static_cast<const RooExponential *>(func);
1778 elem["type"] << key;
1779 elem["x"] << pdf->variable().GetName();
1780 auto &c = pdf->coefficient();
1781 if (pdf->negateCoefficient()) {
1782 elem["c"] << c.GetName();
1783 } else {
1784 elem["c"] << tool->exportTransformed(&c, "_exponential_inverted", "-%s");
1785 }
1786
1787 return true;
1788}
1789
1790bool exportMultiVarGaussian(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1791{
1792 auto *pdf = static_cast<const RooMultiVarGaussian *>(func);
1793 elem["type"] << key;
1794 RooJSONFactoryWSTool::fillSeq(elem["x"], pdf->xVec());
1795 RooJSONFactoryWSTool::fillSeq(elem["mean"], pdf->muVec());
1796 elem["covariances"].fill_mat(pdf->covarianceMatrix());
1797 return true;
1798}
1799
1800bool exportTFnBinding(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1801{
1802 auto *pdf = static_cast<const RooTFnBinding *>(func);
1803 elem["type"] << key;
1804
1805 TString formula(pdf->function().GetExpFormula());
1806 formula.ReplaceAll("x", pdf->observables()[0].GetName());
1807 formula.ReplaceAll("y", pdf->observables()[1].GetName());
1808 formula.ReplaceAll("z", pdf->observables()[2].GetName());
1809 for (size_t i = 0; i < pdf->parameters().size(); ++i) {
1810 TString pname(TString::Format("[%d]", (int)i));
1811 formula.ReplaceAll(pname, pdf->parameters()[i].GetName());
1812 }
1813 elem["expression"] << formula.Data();
1814 return true;
1815}
1816
1817bool exportDerivative(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1818{
1819 auto *pdf = static_cast<const RooDerivative *>(func);
1820 elem["type"] << key;
1821 elem["x"] << pdf->getX().GetName();
1822 elem["function"] << pdf->getFunc().GetName();
1823 if (!pdf->getNset().empty()) {
1824 RooJSONFactoryWSTool::fillSeq(elem["normalization"], pdf->getNset());
1825 }
1826 elem["order"] << pdf->order();
1827 elem["eps"] << pdf->eps();
1828 return true;
1829}
1830
1831bool exportRealIntegral(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1832{
1833 auto *integral = static_cast<const RooRealIntegral *>(func);
1834 elem["type"] << key;
1835 std::string integrand = integral->integrand().GetName();
1836 elem["integrand"] << integrand;
1837 if (integral->intRange()) {
1838 elem["domain"] << integral->intRange();
1839 }
1840 RooJSONFactoryWSTool::fillSeq(elem["variables"], integral->intVars());
1841 if (RooArgSet const *funcNormSet = integral->funcNormSet()) {
1842 RooJSONFactoryWSTool::fillSeq(elem["normalization"], *funcNormSet);
1843 }
1844 return true;
1845}
1846
1847bool exportFFTConvPdf(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1848{
1849 auto *pdf = static_cast<const RooFFTConvPdf *>(func);
1850 elem["type"] << key;
1851 if (auto convFunc = pdf->getPdfConvVar()) {
1852 elem["conv_func"] << convFunc->GetName();
1853 }
1854 elem["conv_var"] << pdf->getConvVar().GetName();
1855 elem["pdf1"] << pdf->getPdf1().GetName();
1856 elem["pdf2"] << pdf->getPdf2().GetName();
1857 elem["ipOrder"] << pdf->getInterpolationOrder();
1858 return true;
1859}
1860
1861bool exportExtendPdf(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1862{
1863 auto *pdf = static_cast<const RooExtendPdf *>(func);
1864 elem["type"] << key;
1865 if (auto rangeName = pdf->getRangeName()) {
1866 elem["range"] << rangeName->GetName();
1867 }
1868 elem["dist"] << pdf->pdf().GetName();
1869 elem["rate"] << pdf->getN().GetName();
1870 return true;
1871}
1872
1873bool exportParamHistFunc(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1874{
1875 auto *pdf = static_cast<const ParamHistFunc *>(func);
1876 elem["type"] << key;
1877 RooJSONFactoryWSTool::fillSeq(elem["variables"], pdf->dataVars());
1878 // One parameter per bin, in the order of HS3 (last axis fastest), not in ParamHistFunc's internal TH1 order.
1879 auto &paramsNode = elem["parameters"].set_seq();
1880 for (RooAbsReal *param : paramHistFuncParamsInBinOrder(*pdf)) {
1881 paramsNode.append_child() << param->GetName();
1882 }
1883 auto &observablesNode = elem["axes"].set_seq();
1884 // axes have to be ordered to get consistent bin indices
1885 for (auto *var : static_range_cast<RooRealVar *>(pdf->dataVars())) {
1886 RooJSONFactoryWSTool::exportAxis(observablesNode.append_child().set_map(), *var);
1887 }
1888 return true;
1889}
1890
1891bool exportSpline(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1892{
1893 auto const *rs = static_cast<RooSpline const *>(func);
1894
1895 elem["type"] << key;
1896
1897 // Independent variable
1898 elem["x"] << rs->x().GetName();
1899
1900 // Spline configuration
1901 // Canonical algo for RooSpline
1902 elem["interpolation"] << (rs->order() == 5 ? "poly5" : "poly3");
1903 elem["logx"] << rs->logx();
1904 elem["logy"] << rs->logy();
1905
1906 // Serialize knots as primitive arrays
1907 TSpline const &sp = rs->spline();
1908 auto &x0 = elem["x0"].set_seq();
1909 auto &y0 = elem["y0"].set_seq();
1910
1911 const int np = sp.GetNp();
1912 for (int i = 0; i < np; ++i) {
1913 double xk = 0.0;
1914 double yk = 0.0;
1915 sp.GetKnot(i, xk, yk);
1916 x0.append_child() << xk;
1917 y0.append_child() << yk;
1918 }
1919
1920 return true;
1921}
1922
1923bool exportAddition(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1924{
1925 elem["type"] << key;
1926 RooJSONFactoryWSTool::fillSeq(elem["summands"], static_cast<const RooAddition *>(func)->list());
1927 return true;
1928}
1929
1930bool exportArgus(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1931{
1932 auto *pdf = static_cast<const RooArgusBG *>(func);
1933 elem["type"] << key;
1934 writeReference(elem["mass"], pdf->getM());
1935 writeReference(elem["resonance"], pdf->getM0());
1936 writeReference(elem["slope"], pdf->getC());
1937 writeReference(elem["power"], pdf->getP());
1938 return true;
1939}
1940
1941bool exportBernstein(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1942{
1943 auto *pdf = static_cast<const RooBernstein *>(func);
1944 elem["type"] << key;
1945 writeReference(elem["x"], pdf->x());
1946 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList());
1947 return true;
1948}
1949
1950bool exportBifurGauss(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1951{
1952 auto *pdf = static_cast<const RooBifurGauss *>(func);
1953 elem["type"] << key;
1954 writeReference(elem["x"], pdf->getX());
1955 writeReference(elem["mean"], pdf->getMean());
1956 writeReference(elem["sigmaL"], pdf->getSigmaL());
1957 writeReference(elem["sigmaR"], pdf->getSigmaR());
1958 return true;
1959}
1960
1961bool exportCBShape(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1962{
1963 auto *pdf = static_cast<const RooCBShape *>(func);
1964 elem["type"] << key;
1965 writeReference(elem["m"], pdf->getM());
1966 writeReference(elem["m0"], pdf->getM0());
1967 writeReference(elem["sigma"], pdf->getSigma());
1968 writeReference(elem["alpha"], pdf->getAlpha());
1969 writeReference(elem["n"], pdf->getN());
1970 return true;
1971}
1972
1973bool exportChebychev(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1974{
1975 auto *pdf = static_cast<const RooChebychev *>(func);
1976 elem["type"] << key;
1977 writeReference(elem["x"], pdf->x());
1978 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList());
1979 return true;
1980}
1981
1982bool exportEffProd(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1983{
1984 auto *pdf = static_cast<const RooEffProd *>(func);
1985 elem["type"] << key;
1986 writeReference(elem["pdf"], pdf->pdf());
1987 writeReference(elem["eff"], pdf->eff());
1988 return true;
1989}
1990
1991bool exportGamma(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
1992{
1993 auto *pdf = static_cast<const RooGamma *>(func);
1994 elem["type"] << key;
1995 writeReference(elem["x"], pdf->getX());
1996 writeReference(elem["gamma"], pdf->getGamma());
1997 writeReference(elem["beta"], pdf->getBeta());
1998 writeReference(elem["mu"], pdf->getMu());
1999 return true;
2000}
2001
2002bool exportLandau(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
2003{
2004 auto *pdf = static_cast<const RooLandau *>(func);
2005 elem["type"] << key;
2006 writeReference(elem["x"], pdf->getX());
2007 writeReference(elem["mean"], pdf->getMean());
2008 writeReference(elem["sigma"], pdf->getSigma());
2009 return true;
2010}
2011
2012bool exportPowerSum(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
2013{
2014 auto *pdf = static_cast<const RooPowerSum *>(func);
2015 elem["type"] << key;
2016 writeReference(elem["x"], pdf->base());
2017 RooJSONFactoryWSTool::fillSeq(elem["coefficients"], pdf->coefList());
2018 RooJSONFactoryWSTool::fillSeq(elem["exponents"], pdf->expList());
2019 return true;
2020}
2021
2022bool exportProdPdf(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
2023{
2024 elem["type"] << key;
2025 RooJSONFactoryWSTool::fillSeq(elem["factors"], static_cast<const RooProdPdf *>(func)->pdfList());
2026 return true;
2027}
2028
2029bool exportProduct(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
2030{
2031 auto *prod = static_cast<const RooProduct *>(func);
2032 elem["type"] << key;
2033 RooJSONFactoryWSTool::fillSeq(elem["factors"], prod->realComponents());
2034 RooJSONFactoryWSTool::fillSeq(elem["factors"], prod->categoricalComponents());
2035 return true;
2036}
2037
2038bool exportProjectedPdf(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
2039{
2040 auto *pdf = static_cast<const RooProjectedPdf *>(func);
2041 elem["type"] << key;
2042 writeReference(elem["input_pdf"], pdf->intPdf());
2043 RooJSONFactoryWSTool::fillSeq(elem["observables"], pdf->intObs());
2044 return true;
2045}
2046
2047bool exportUniform(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem, std::string const &key)
2048{
2049 elem["type"] << key;
2050 RooJSONFactoryWSTool::fillSeq(elem["x"], static_cast<const RooUniform *>(func)->observables());
2051 return true;
2052}
2053
2054bool importWrapperPdf(RooJSONFactoryWSTool *tool, const JSONNode &node)
2055{
2056 if (node["type"].val() != "density_function_dist")
2057 return false;
2058
2059 auto name = RooJSONFactoryWSTool::name(node);
2060 auto *func = tool->requestArg<RooAbsReal>(node, "function");
2061
2062 bool selfNormalized = false;
2063
2064 auto sn = node.find("self_normalized");
2065 // ROOT previously exported this key without an underscore.
2066 if (!sn)
2067 sn = node.find("selfnormalized");
2068 if (sn)
2069 selfNormalized = sn->val_bool();
2070
2071 tool->wsEmplace<RooWrapperPdf>(name, *func, selfNormalized);
2072 return true;
2073}
2074
2075bool exportWrapperPdf(RooJSONFactoryWSTool *, const RooAbsArg *arg, JSONNode &node, std::string const &key)
2076{
2077 auto const *pdf = dynamic_cast<RooWrapperPdf const *>(arg);
2078 if (!pdf)
2079 return false;
2080
2081 node["type"] << key;
2082
2083 // Proxy name in RooWrapperPdf is "_func" / "func" depending on accessor/proxy export.
2084 // Prefer a public accessor if one exists; otherwise inspect proxies as below.
2085 auto const *funcProxy = dynamic_cast<RooRealProxy const *>(pdf->getProxy(0));
2086 if (!funcProxy || !funcProxy->absArg())
2087 return false;
2088
2089 node["function"] << funcProxy->absArg()->GetName();
2090 if (pdf->selfNormalized())
2091 node["self_normalized"] << true;
2092
2093 return true;
2094}
2095
2096///////////////////////////////////////////////////////////////////////////////////////////////////////
2097// instantiate all importers and exporters
2098///////////////////////////////////////////////////////////////////////////////////////////////////////
2099
2100// Adapters that wrap the plain import/export functions above into the
2101// RooFit::JSONIO::Importer/Exporter interface. The exporter also owns the HS3
2102// type key, which is passed at registration time.
2103template <auto Func>
2104class FuncImporter : public RooFit::JSONIO::Importer {
2105public:
2106 bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override { return Func(tool, p); }
2107};
2108
2109template <auto Func>
2110class FuncExporter : public RooFit::JSONIO::Exporter {
2111public:
2112 FuncExporter(std::string key, bool autoExportDependants)
2113 : _key{std::move(key)}, _autoExportDependants{autoExportDependants}
2114 {
2115 }
2116 std::string const &key() const override { return _key; }
2117 bool autoExportDependants() const override { return _autoExportDependants; }
2118 bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *func, JSONNode &elem) const override
2119 {
2120 return Func(tool, func, elem, _key);
2121 }
2122
2123private:
2124 const std::string _key;
2125 const bool _autoExportDependants;
2126};
2127
2128template <auto Func>
2129void registerImporter(const std::string &key, bool topPriority = true)
2130{
2131 RooFit::JSONIO::registerImporter(key, std::make_unique<FuncImporter<Func>>(), topPriority);
2132}
2133
2134template <auto Func>
2135void registerExporter(TClass const *cl, std::string key, bool topPriority = true, bool autoExportDependants = true)
2136{
2137 RooFit::JSONIO::registerExporter(cl, std::make_unique<FuncExporter<Func>>(std::move(key), autoExportDependants),
2138 topPriority);
2139}
2140
2141STATIC_EXECUTE([]() {
2142 registerImporter<importWrapperPdf>("density_function_dist");
2143 registerImporter<importExtendPdf>("rate_extended_dist");
2144 RooFit::JSONIO::registerImporter("crystalball_dist", std::make_unique<CrystalBallImporter>());
2145 registerImporter<importCrystalBallDoubleSided>("crystalball_doublesided_dist");
2146 RooFit::JSONIO::registerImporter("ARGUS_dist", std::make_unique<DeprecatedKeyImporter>("ARGUS_dist", "argus_dist"));
2148 std::make_unique<DeprecatedKeyImporter>("binsampling", "binsampling_dist"));
2150 "mixture_resolution_model", std::make_unique<DeprecatedKeyImporter>("mixture_resolution_model", "mixture_model"));
2151 RooFit::JSONIO::registerImporter("delta_resolution_model", std::make_unique<DeprecatedKeyImporter>(
2152 "delta_resolution_model", "truth_model_function"));
2153 RooFit::JSONIO::registerImporter("gauss_resolution_model", std::make_unique<DeprecatedKeyImporter>(
2154 "gauss_resolution_model", "gauss_model_function"));
2155 registerImporter<importArgus>("argus_dist", false);
2156 registerImporter<importArgus>("ARGUS_dist", false);
2157 registerImporter<importBernstein>("bernstein_poly_dist", false);
2158 registerImporter<importBifurGauss>("bifurkated_gaussian_dist", false);
2159 registerImporter<importChebychev>("chebychev_dist", false);
2160 registerImporter<importEffProd>("efficiency_product_pdf_dist", false);
2161 registerImporter<importGamma>("gamma_dist", false);
2162 registerImporter<importGaussian>("gaussian_dist", false);
2163 registerImporter<importGaussian>("normal_dist", false);
2164 registerImporter<importLandau>("landau_dist", false);
2165 registerImporter<importPowerSum>("power_sum_dist", false);
2166 registerImporter<importProjectedPdf>("projected_dist", false);
2167 registerImporter<importUniform>("uniform_dist", false);
2168 registerImporter<importProduct>("product", false);
2169 registerImporter<importProdPdf>("product_dist", false);
2170 registerImporter<importArrayDist>("array_dist", false);
2171 registerImporter<importAddition>("sum", false);
2172 registerImporter<importAddPdf>("mixture_dist", false);
2173 registerImporter<importAddModel>("mixture_model", false);
2174 registerImporter<importCombinedDist>("combined_dist", false);
2175 registerImporter<importAddModel>("mixture_resolution_model", false);
2176 registerImporter<importBinSamplingPdf>("binsampling_dist", false);
2177 registerImporter<importBinSamplingPdf>("binsampling", false);
2178 registerImporter<importBinWidthFunction<false>>("binvolume", false);
2179 registerImporter<importBinWidthFunction<true>>("inverse_binvolume", false);
2180 registerImporter<importPolynomial<RooLegacyExpPoly>>("legacy_exp_poly_dist", false);
2181 registerImporter<importExponential>("exponential_dist", false);
2182 registerImporter<importFormulaArg<RooFormulaVar>>("generic", false);
2183 registerImporter<importFormulaArg<RooFormulaVar>>("generic_function", false);
2184 registerImporter<importFormulaArg<RooGenericPdf>>("generic_dist", false);
2185 registerImporter<importHist<RooHistFunc>>("histogram", false);
2186 registerImporter<importHist<RooHistFunc>>("step", false);
2187 registerImporter<importHist<RooHistPdf>>("histogram_dist", false);
2188 registerImporter<importLogNormal>("lognormal_dist", false);
2189 registerImporter<importMultiVarGaussian>("multivariate_normal_dist", false);
2190 registerImporter<importPoisson<false>>("poisson_dist", false);
2191 registerImporter<importPoisson<true>>("poisson_continuous_dist", false);
2192 registerImporter<importDecay>("decay_dist", false);
2193 registerImporter<importTruthModel>("truth_model_function", false);
2194 registerImporter<importTruthModel>("delta_resolution_model", false);
2195 registerImporter<importGaussModel>("gauss_model_function", false);
2196 registerImporter<importGaussModel>("gauss_resolution_model", false);
2197 registerImporter<importPolynomial<RooPolynomial>>("polynomial_dist", false);
2198 registerImporter<importPolynomial<RooPolyVar>>("polynomial", false);
2199 registerImporter<importRealSum<RooRealSumPdf>>("weighted_sum_dist", false);
2200 registerImporter<importRealSum<RooRealSumFunc>>("weighted_sum", false);
2201 registerImporter<importRealIntegral>("integral", false);
2202 registerImporter<importDerivative>("derivative", false);
2203 registerImporter<importFFTConvPdf>("fft_convolution_dist", false);
2204 registerImporter<importExtendPdf>("extend_pdf", false);
2205 registerImporter<importParamHistFunc>("step", false);
2206 registerImporter<importSpline>("spline", false);
2207
2208 registerExporter<exportWrapperPdf>(RooWrapperPdf::Class(), "density_function_dist");
2209 registerExporter<exportAddPdf<RooAddPdf>>(RooAddPdf::Class(), "mixture_dist", false);
2210 registerExporter<exportAddPdf<RooAddModel>>(RooAddModel::Class(), "mixture_model", false);
2211 registerExporter<exportBinSamplingPdf>(RooBinSamplingPdf::Class(), "binsampling_dist", false);
2212 registerExporter<exportCrystalBall>(RooCrystalBall::Class(), "crystalball_doublesided_dist", false);
2213 registerExporter<exportBinWidthFunction>(RooBinWidthFunction::Class(), "binvolume", false);
2214 registerExporter<exportPolynomial<RooLegacyExpPoly>>(RooLegacyExpPoly::Class(), "legacy_exp_poly_dist", false);
2215 registerExporter<exportExponential>(RooExponential::Class(), "exponential_dist", false);
2216 registerExporter<exportFormulaArg<RooFormulaVar>>(RooFormulaVar::Class(), "generic", false);
2217 registerExporter<exportFormulaArg<RooGenericPdf>>(RooGenericPdf::Class(), "generic_dist", false);
2218 registerExporter<exportHist<RooHistFunc>>(RooHistFunc::Class(), "step", false);
2219 registerExporter<exportHist<RooHistPdf>>(RooHistPdf::Class(), "histogram_dist", false);
2220 registerExporter<exportLogNormal>(RooLognormal::Class(), "lognormal_dist", false);
2221 registerExporter<exportGaussian>(RooGaussian::Class(), "gaussian_dist", true);
2222 registerExporter<exportMultiVarGaussian>(RooMultiVarGaussian::Class(), "multivariate_normal_dist", false);
2223 registerExporter<exportPoisson>(RooPoisson::Class(), "poisson_dist", false);
2224 registerExporter<exportDecay>(RooDecay::Class(), "decay_dist", false, /*autoExportDependants=*/false);
2225 registerExporter<exportTruthModel>(RooTruthModel::Class(), "truth_model_function", false);
2226 registerExporter<exportGaussModel>(RooGaussModel::Class(), "gauss_model_function", false);
2227 registerExporter<exportPolynomial<RooPolynomial>>(RooPolynomial::Class(), "polynomial_dist", false);
2228 registerExporter<exportPolynomial<RooPolyVar>>(RooPolyVar::Class(), "polynomial", false);
2229 registerExporter<exportRealSum<RooRealSumFunc>>(RooRealSumFunc::Class(), "weighted_sum", false);
2230 registerExporter<exportRealSum<RooRealSumPdf>>(RooRealSumPdf::Class(), "weighted_sum_dist", false);
2231 registerExporter<exportTFnBinding>(RooTFnBinding::Class(), "generic", false);
2232 registerExporter<exportRealIntegral>(RooRealIntegral::Class(), "integral", false);
2233 registerExporter<exportDerivative>(RooDerivative::Class(), "derivative", false);
2234 registerExporter<exportFFTConvPdf>(RooFFTConvPdf::Class(), "fft_convolution_dist", false);
2235 registerExporter<exportExtendPdf>(RooExtendPdf::Class(), "rate_extended_dist", false);
2236 registerExporter<exportParamHistFunc>(ParamHistFunc::Class(), "step", false);
2237 registerExporter<exportSpline>(RooSpline::Class(), "spline", false);
2238 registerExporter<exportAddition>(RooAddition::Class(), "sum", false);
2239 registerExporter<exportArgus>(RooArgusBG::Class(), "argus_dist", false);
2240 registerExporter<exportBernstein>(RooBernstein::Class(), "bernstein_poly_dist", false);
2241 registerExporter<exportBifurGauss>(RooBifurGauss::Class(), "bifurkated_gaussian_dist", false);
2242 registerExporter<exportCBShape>(RooCBShape::Class(), "crystalball_dist", false);
2243 registerExporter<exportChebychev>(RooChebychev::Class(), "chebychev_dist", false);
2244 registerExporter<exportEffProd>(RooEffProd::Class(), "efficiency_product_pdf_dist", false);
2245 registerExporter<exportGamma>(RooGamma::Class(), "gamma_dist", false);
2246 registerExporter<exportLandau>(RooLandau::Class(), "landau_dist", false);
2247 registerExporter<exportPowerSum>(RooPowerSum::Class(), "power_sum_dist", false);
2248 registerExporter<exportProdPdf>(RooProdPdf::Class(), "product_dist", false);
2249 registerExporter<exportProduct>(RooProduct::Class(), "product", false);
2250 registerExporter<exportProjectedPdf>(RooProjectedPdf::Class(), "projected_dist", false);
2251 registerExporter<exportUniform>(RooUniform::Class(), "uniform_dist", false);
2252});
2253
2254} // namespace
2255
2256std::optional<ArrayComponentInfo> arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable)
2257{
2258 auto component = arrayComponentOf(pdf, observable);
2259 if (!component) {
2260 return std::nullopt;
2261 }
2262 return ArrayComponentInfo{component->type, component->x};
2263}
2264
2265void writeArrayDist(JSONNode &elem, std::string const &name, std::vector<RooAbsPdf const *> const &components,
2266 std::map<std::string, std::string> const &observableOf)
2267{
2268 auto error = [&name](std::string const &message) {
2269 RooJSONFactoryWSTool::error("cannot write the array distribution '" + name + "': " + message);
2270 };
2271 if (components.empty()) {
2272 error("it has no components");
2273 }
2274 std::vector<ArrayComponent> comps;
2275 std::set<std::string> observables;
2276 for (RooAbsPdf const *pdf : components) {
2277 auto recorded = observableOf.find(pdf->GetName());
2278 auto comp = arrayComponentOf(*pdf, recorded != observableOf.end() ? &recorded->second : nullptr);
2279 if (!comp) {
2280 error("'" + std::string(pdf->GetName()) +
2281 "' cannot be a component, only RooPoisson, RooGaussian and RooLognormal (standard parametrization) "
2282 "over a named observable are supported");
2283 }
2284 if (!comps.empty() && comp->type != comps.front().type) {
2285 error("the components '" + std::string(components.front()->GetName()) + "' (" + comps.front().type +
2286 ") and '" + pdf->GetName() + "' (" + comp->type + ") have different types");
2287 }
2288 if (!observables.insert(comp->x).second) {
2289 error("two components have the observable '" + comp->x + "'");
2290 }
2291 comps.push_back(std::move(*comp));
2292 }
2293
2294 elem["type"] << "array_dist";
2295 elem["component_type"] << comps.front().type;
2296
2297 auto write = [](JSONNode &node, ArrayFieldValue const &value) {
2298 std::visit([&node](auto const &v) { node << v; }, value);
2299 };
2300
2301 // A field with the same value in every component is written once in "default_parameters".
2302 std::set<std::string> defaultKeys;
2303 if (comps.size() > 1) {
2304 for (std::size_t i = 0; i < comps.front().fields.size(); ++i) {
2305 auto const &field = comps.front().fields[i];
2306 if (std::all_of(comps.begin(), comps.end(),
2307 [&](ArrayComponent const &comp) { return comp.fields[i].second == field.second; })) {
2308 defaultKeys.insert(field.first);
2309 }
2310 }
2311 }
2312 if (!defaultKeys.empty()) {
2313 JSONNode &defaults = elem["default_parameters"].set_map();
2314 for (auto const &field : comps.front().fields) {
2315 if (defaultKeys.find(field.first) != defaultKeys.end()) {
2316 write(defaults[field.first], field.second);
2317 }
2318 }
2319 }
2320
2321 JSONNode &seq = elem["components"].set_seq();
2322 for (ArrayComponent const &comp : comps) {
2323 JSONNode &node = seq.append_child().set_map();
2324 node["x"] << comp.x;
2325 for (auto const &field : comp.fields) {
2326 if (defaultKeys.find(field.first) == defaultKeys.end()) {
2327 write(node[field.first], field.second);
2328 }
2329 }
2330 }
2331}
void writeArrayDist(JSONNode &elem, std::string const &name, std::vector< RooAbsPdf const * > const &components, std::map< std::string, std::string > const &observableOf)
std::optional< ArrayComponentInfo > arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable)
void writeReference(JSONNode &node, RooAbsArg const &arg)
bool isHS3VersionBefore(std::string const &version, int major, int minor)
std::vector< RooAbsReal * > paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, RooAbsCollection const &vars)
std::string selectionKeyToString(std::vector< std::string > const &key)
bool startsWith(std::string_view str, std::string_view prefix)
std::vector< RooCategory * > readSelectionColumns(RooWorkspace const &ws, JSONNode const &node, const char *field, std::string const &context)
bool endsWith(std::string_view str, std::string_view suffix)
std::string selectionLabel(std::vector< std::string > const &key)
std::vector< std::string > readSelectionKey(JSONNode const &component, std::vector< RooCategory * > const &columns, std::string const &context)
bool isLiteralConstVar(RooAbsArg const &arg)
std::string removeSuffix(std::string_view str, std::string_view suffix)
void writeAxisBinning(JSONNode &node, const RooAbsBinning &binning)
std::unique_ptr< RooArgSet > histogramVariablesNamedAfterObservables(RooDataHist const &dh, RooArgSet const &histObs, RooArgSet const &funcObs)
void checkParamHistFuncOrderIsDefined(std::string const &hs3Version, RooAbsCollection const &vars, std::string const &context)
constexpr const char * arrayDistTag
Definition JSONIOUtils.h:23
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 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 np
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...
static TClass * Class()
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.
Abstract base class for RooRealVar binning definitions.
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
static TClass * Class()
Efficient implementation of a sum of PDFs of the form.
Definition RooAddPdf.h:32
static TClass * Class()
Calculates the sum of a set of RooAbsReal terms, or when constructed with two sets,...
Definition RooAddition.h:27
static TClass * Class()
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
RooArgusBG is a RooAbsPdf implementation describing the ARGUS background shape.
Definition RooArgusBG.h:22
static TClass * Class()
Bernstein basis polynomials are positive-definite in the range [0,1].
static TClass * Class()
Bifurcated Gaussian p.d.f with different widths on left and right side of maximum value.
static TClass * Class()
The RooBinSamplingPdf is supposed to be used as an adapter between a continuous PDF and a binned dist...
static TClass * Class()
double epsilon() const
const RooAbsPdf & pdf() const
const RooAbsReal & observable() const
Returns the bin width (or volume) given a RooHistFunc.
const RooHistFunc & histFunc() const
static TClass * Class()
PDF implementing the Crystal Ball line shape.
Definition RooCBShape.h:24
static TClass * Class()
Object to represent discrete states.
Definition RooCategory.h:28
Chebychev polynomial p.d.f.
static TClass * Class()
Represents a constant real-valued object.
Definition RooConstVar.h:23
PDF implementing the generalized Asymmetrical Double-Sided Crystall Ball line shape.
static TClass * Class()
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
static TClass * Class()
Represents the first, second, or third order derivative of any RooAbsReal as calculated (numerically)...
static TClass * Class()
The class RooEffProd implements the product of a PDF with an efficiency function.
Definition RooEffProd.h:19
static TClass * Class()
Exponential PDF.
static TClass * Class()
RooExtendPdf is a wrapper around an existing PDF that adds a parameteric extended likelihood term to ...
static TClass * Class()
PDF for the numerical (FFT) convolution of two PDFs.
static TClass * Class()
std::string val() const
void fill_mat(Matrix const &mat)
JSONNode const * find(std::string const &key) const
bool has_child(std::string const &) const
static std::unique_ptr< JSONTree > create()
static TClass * Class()
Implementation of the Gamma PDF for RooFit/RooStats.
Definition RooGamma.h:20
static TClass * Class()
Class RooGaussModel implements a RooResolutionModel that models a Gaussian distribution.
static TClass * Class()
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
static TClass * Class()
static TClass * Class()
A real-valued function sampled from a multidimensional histogram.
Definition RooHistFunc.h:29
static TClass * Class()
static TClass * Class()
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.
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)
Read binned data from the JSONNode and create a RooDataHist object.
static void exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, RooFit::Detail::JSONNode &output)
Export histogram data to a JSONNode.
void queueExport(RooAbsArg const &arg)
std::string const & hs3VersionInput() const
The "hs3_version" of the document that is currently being imported, or an empty string outside of an ...
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)
static void exportAxis(RooFit::Detail::JSONNode &obsNode, RooRealVar const &var)
static void error(const char *s)
Writes an error message to the RooFit message service and throws a runtime_error.
void importFunction(const RooFit::Detail::JSONNode &p, bool importAllDependants)
Import a function from the JSONNode into the workspace.
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)
Writes a warning message to the RooFit message service.
static RooArgSet readAxes(const RooFit::Detail::JSONNode &node)
Read axes from the JSONNode and create a RooArgSet representing them.
Landau distribution p.d.f.
Definition RooLandau.h:24
static TClass * Class()
static TClass * Class()
RooFit Lognormal PDF.
static TClass * Class()
Multivariate Gaussian p.d.f.
static TClass * Class()
Holds the configuration parameters of the various numeric integrators used by RooRealIntegral.
Poisson pdf.
Definition RooPoisson.h:18
static TClass * Class()
static TClass * Class()
static TClass * Class()
RooPowerSum implements a power law PDF of the form.
Definition RooPowerSum.h:20
static TClass * Class()
Efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:35
static TClass * Class()
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
static TClass * Class()
A RooAbsPdf implementation that represent a projection of a given input p.d.f and the object returned...
static TClass * Class()
Performs hybrid numerical/analytical integrals of RooAbsReal objects.
static TClass * Class()
static TClass * Class()
Implements a PDF constructed from a sum of functions:
static TClass * Class()
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...
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
A RooFit class for creating spline functions.
Definition RooSpline.h:27
static TClass * Class()
Joins several RooAbsCategoryLValue objects into a single category.
Use TF1, TF2, TF3 functions as RooFit objects.
static TClass * Class()
Implements a RooResolution model that corresponds to a delta function.
static TClass * Class()
Flat p.d.f.
Definition RooUniform.h:24
static TClass * Class()
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.
static TClass * Class()
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
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
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
double beta(double x, double y)
Calculates the beta function.
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 gamma(double x)
double poisson(double x, double par)
Definition MathFuncs.h:240
static bool registerImporter(const std::string &key, bool topPriority=true)
Definition JSONIO.h:73
bool registerImporter(const std::string &key, std::unique_ptr< const Importer > f, bool topPriority=true)
Definition JSONIO.cxx:72
static bool registerExporter(const TClass *key, bool topPriority=true)
Definition JSONIO.h:78
bool registerExporter(const TClass *key, std::unique_ptr< const Exporter > f, bool topPriority=true)
Definition JSONIO.cxx:79
#define STATIC_EXECUTE(MY_FUNC)
std::string type
Definition JSONIOUtils.h:45
TMarker m
Definition textangle.C:8