Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooJSONFactoryWSTool.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
13#include <RooFitHS3/JSONIO.h>
15
16#include <RooConstVar.h>
17#include <RooRealVar.h>
18#include <RooBinning.h>
19#include <RooAbsCategory.h>
20#include <RooRealProxy.h>
21#include <RooListProxy.h>
22#include <RooAbsProxy.h>
23#include <RooCategory.h>
24#include <RooDataSet.h>
25#include <RooDataHist.h>
26#include <RooSimultaneous.h>
27#include <RooFormulaVar.h>
28#include <RooFit/ModelConfig.h>
29
30#include "JSONIOUtils.h"
31#include "Domains.h"
32
33#include "RooFitImplHelpers.h"
34
35#include <TROOT.h>
36
37#include <algorithm>
38#include <fstream>
39#include <iostream>
40#include <stack>
41#include <stdexcept>
42
43/** \class RooJSONFactoryWSTool
44\ingroup roofit
45
46When using \ref Roofitmain, statistical models can be conveniently handled and
47stored as a RooWorkspace. However, for the sake of interoperability
48with other statistical frameworks, and also ease of manipulation, it
49may be useful to store statistical models in text form.
50
51The RooJSONFactoryWSTool is a helper class to achieve exactly this,
52exporting to and importing from JSON and YML.
53
54In order to import a workspace from a JSON file, you can do
55
56~~~ {.py}
57ws = ROOT.RooWorkspace("ws")
58tool = ROOT.RooJSONFactoryWSTool(ws)
59tool.importJSON("myjson.json")
60~~~
61
62Similarly, in order to export a workspace to a JSON file, you can do
63
64~~~ {.py}
65tool = ROOT.RooJSONFactoryWSTool(ws)
66tool.exportJSON("myjson.json")
67~~~
68
69For more details, consult the tutorial <a href="rf515__hfJSON_8py.html">rf515_hfJSON</a>.
70
71In order to import and export YML files, `ROOT` needs to be compiled
72with the external dependency <a
73href="https://github.com/biojppm/rapidyaml">RapidYAML</a>, which needs
74to be installed on your system when building `ROOT`.
75
76The RooJSONFactoryWSTool only knows about a limited set of classes for
77import and export. If import or export of a class you're interested in
78fails, you might need to add your own importer or exporter. Please
79consult the relevant section in the \ref roofit_dev_docs to learn how to do that (\ref roofit_dev_docs_hs3).
80
81You can always get a list of all the available importers and exporters by calling the following functions:
82~~~ {.py}
83ROOT.RooFit.JSONIO.printImporters()
84ROOT.RooFit.JSONIO.printExporters()
85ROOT.RooFit.JSONIO.printFactoryExpressions()
86ROOT.RooFit.JSONIO.printExportKeys()
87~~~
88
89Alternatively, you can generate a LaTeX version of the available importers and exporters by calling
90~~~ {.py}
91tool = ROOT.RooJSONFactoryWSTool(ws)
92tool.writedoc("hs3.tex")
93~~~
94*/
95
96constexpr auto hs3VersionTag = "0.2";
97
100
101namespace {
102
103/**
104 * @brief Check if the number of components in CombinedData matches the number of categories in the RooSimultaneous PDF.
105 *
106 * This function checks whether the number of components in the provided CombinedData 'data' matches the number of
107 * categories in the provided RooSimultaneous PDF 'pdf'.
108 *
109 * @param data The reference to the CombinedData to be checked.
110 * @param pdf The pointer to the RooSimultaneous PDF for comparison.
111 * @return bool Returns true if the number of components in 'data' matches the number of categories in 'pdf'; otherwise,
112 * returns false.
113 */
114bool matches(const RooJSONFactoryWSTool::CombinedData &data, const RooSimultaneous *pdf)
115{
116 return data.components.size() == pdf->indexCat().size();
117}
118
119/**
120 * @struct Var
121 * @brief Structure to store variable information.
122 *
123 * This structure represents variable information such as the number of bins, minimum and maximum values,
124 * and a vector of binning edges for a variable.
125 */
126struct Var {
127 int nbins; // Number of bins
128 double min; // Minimum value
129 double max; // Maximum value
130 std::vector<double> edges; // Vector of edges
131
132 /**
133 * @brief Constructor for Var.
134 * @param n Number of bins.
135 */
136 Var(int n) : nbins(n), min(0), max(n) {}
137
138 /**
139 * @brief Constructor for Var from JSONNode.
140 * @param val JSONNode containing variable information.
141 */
142 Var(const JSONNode &val);
143};
144
145/**
146 * @brief Check if a string represents a valid number.
147 *
148 * This function checks whether the provided string 'str' represents a valid number.
149 * The function returns true if the entire string can be parsed as a number (integer or floating-point); otherwise, it
150 * returns false.
151 *
152 * @param str The string to be checked.
153 * @return bool Returns true if the string 'str' represents a valid number; otherwise, returns false.
154 */
155bool isNumber(const std::string &str)
156{
157 bool first = true;
158 for (char const &c : str) {
159 if (std::isdigit(c) == 0 && c != '.' && !(first && (c == '-' || c == '+')))
160 return false;
161 first = false;
162 }
163 return true;
164}
165
166/**
167 * @brief Check if a string is a valid name.
168 *
169 * A valid name should start with a letter or an underscore, followed by letters, digits, or underscores.
170 * Only characters from the ASCII character set are allowed.
171 *
172 * @param str The string to be checked.
173 * @return bool Returns true if the string is a valid name; otherwise, returns false.
174 */
175bool isValidName(const std::string &str)
176{
177 // Check if the string is empty or starts with a non-letter/non-underscore character
178 if (str.empty() || !(std::isalpha(str[0]) || str[0] == '_')) {
179 return false;
180 }
181
182 // Check the remaining characters in the string
183 for (char c : str) {
184 // Allow letters, digits, and underscore
185 if (!(std::isalnum(c) || c == '_')) {
186 return false;
187 }
188 }
189
190 // If all characters are valid, the string is a valid name
191 return true;
192}
193
194/**
195 * @brief Configure a RooRealVar based on information from a JSONNode.
196 *
197 * This function configures the provided RooRealVar 'v' based on the information provided in the JSONNode 'p'.
198 * The JSONNode 'p' contains information about various properties of the RooRealVar, such as its value, error, number of
199 * bins, etc. The function reads these properties from the JSONNode and sets the corresponding properties of the
200 * RooRealVar accordingly.
201 *
202 * @param domains The reference to the RooFit::JSONIO::Detail::Domains containing domain information for variables (not
203 * used in this function).
204 * @param p The JSONNode containing information about the properties of the RooRealVar 'v'.
205 * @param v The reference to the RooRealVar to be configured.
206 * @return void
207 */
208void configureVariable(RooFit::JSONIO::Detail::Domains &domains, const JSONNode &p, RooRealVar &v)
209{
210 if (!p.has_child("name")) {
211 RooJSONFactoryWSTool::error("cannot instantiate variable without \"name\"!");
212 }
213 if (auto n = p.find("value"))
214 v.setVal(n->val_double());
215 domains.writeVariable(v);
216 if (auto n = p.find("nbins"))
217 v.setBins(n->val_int());
218 if (auto n = p.find("relErr"))
219 v.setError(v.getVal() * n->val_double());
220 if (auto n = p.find("err"))
221 v.setError(n->val_double());
222 if (auto n = p.find("const")) {
223 v.setConstant(n->val_bool());
224 } else {
225 v.setConstant(false);
226 }
227}
228
229JSONNode const *getVariablesNode(JSONNode const &rootNode)
230{
231 auto paramPointsNode = rootNode.find("parameter_points");
232 if (!paramPointsNode)
233 return nullptr;
234 auto out = RooJSONFactoryWSTool::findNamedChild(*paramPointsNode, "default_values");
235 if (out == nullptr)
236 return nullptr;
237 return &((*out)["parameters"]);
238}
239
240Var::Var(const JSONNode &val)
241{
242 if (val.find("edges")) {
243 for (auto const &child : val.children()) {
244 this->edges.push_back(child.val_double());
245 }
246 this->nbins = this->edges.size();
247 this->min = this->edges[0];
248 this->max = this->edges[this->nbins - 1];
249 } else {
250 if (!val.find("nbins")) {
251 this->nbins = 1;
252 } else {
253 this->nbins = val["nbins"].val_int();
254 }
255 if (!val.find("min")) {
256 this->min = 0;
257 } else {
258 this->min = val["min"].val_double();
259 }
260 if (!val.find("max")) {
261 this->max = 1;
262 } else {
263 this->max = val["max"].val_double();
264 }
265 }
266}
267
268std::string genPrefix(const JSONNode &p, bool trailing_underscore)
269{
270 std::string prefix;
271 if (!p.is_map())
272 return prefix;
273 if (auto node = p.find("namespaces")) {
274 for (const auto &ns : node->children()) {
275 if (!prefix.empty())
276 prefix += "_";
277 prefix += ns.val();
278 }
279 }
280 if (trailing_underscore && !prefix.empty())
281 prefix += "_";
282 return prefix;
283}
284
285// helpers for serializing / deserializing binned datasets
286void genIndicesHelper(std::vector<std::vector<int>> &combinations, std::vector<int> &curr_comb,
287 const std::vector<int> &vars_numbins, size_t curridx)
288{
289 if (curridx == vars_numbins.size()) {
290 // we have filled a combination. Copy it.
291 combinations.emplace_back(curr_comb);
292 } else {
293 for (int i = 0; i < vars_numbins[curridx]; ++i) {
294 curr_comb[curridx] = i;
295 ::genIndicesHelper(combinations, curr_comb, vars_numbins, curridx + 1);
296 }
297 }
298}
299
300/**
301 * @brief Import attributes from a JSONNode into a RooAbsArg.
302 *
303 * This function imports attributes, represented by the provided JSONNode 'node', into the provided RooAbsArg 'arg'.
304 * The attributes are read from the JSONNode and applied to the RooAbsArg.
305 *
306 * @param arg The pointer to the RooAbsArg to which the attributes will be imported.
307 * @param node The JSONNode containing information about the attributes to be imported.
308 * @return void
309 */
310void importAttributes(RooAbsArg *arg, JSONNode const &node)
311{
312 if (auto seq = node.find("dict")) {
313 for (const auto &attr : seq->children()) {
314 arg->setStringAttribute(attr.key().c_str(), attr.val().c_str());
315 }
316 }
317 if (auto seq = node.find("tags")) {
318 for (const auto &attr : seq->children()) {
319 arg->setAttribute(attr.val().c_str());
320 }
321 }
322}
323
324// RooWSFactoryTool expression handling
325std::string generate(const RooFit::JSONIO::ImportExpression &ex, const JSONNode &p, RooJSONFactoryWSTool *tool)
326{
327 std::stringstream expression;
328 std::string classname(ex.tclass->GetName());
329 size_t colon = classname.find_last_of(':');
330 expression << (colon < classname.size() ? classname.substr(colon + 1) : classname);
331 bool first = true;
332 const auto &name = RooJSONFactoryWSTool::name(p);
333 for (auto k : ex.arguments) {
334 expression << (first ? "::" + name + "(" : ",");
335 first = false;
336 if (k == "true" || k == "false") {
337 expression << (k == "true" ? "1" : "0");
338 } else if (!p.has_child(k)) {
339 std::stringstream errMsg;
340 errMsg << "node '" << name << "' is missing key '" << k << "'";
341 RooJSONFactoryWSTool::error(errMsg.str());
342 } else if (p[k].is_seq()) {
343 bool firstInner = true;
344 for (RooAbsArg *arg : tool->requestArgList<RooAbsReal>(p, k)) {
345 expression << (firstInner ? "{" : ",") << arg->GetName();
346 firstInner = false;
347 }
348 expression << "}";
349 } else {
350 tool->requestArg<RooAbsReal>(p, p[k].key());
351 expression << p[k].val();
352 }
353 }
354 expression << ")";
355 return expression.str();
356}
357
358/**
359 * @brief Generate bin indices for a set of RooRealVars.
360 *
361 * This function generates all possible combinations of bin indices for the provided RooArgSet 'vars' containing
362 * RooRealVars. Each bin index represents a possible bin selection for the corresponding RooRealVar. The bin indices are
363 * stored in a vector of vectors, where each inner vector represents a combination of bin indices for all RooRealVars.
364 *
365 * @param vars The RooArgSet containing the RooRealVars for which bin indices will be generated.
366 * @return std::vector<std::vector<int>> A vector of vectors containing all possible combinations of bin indices.
367 */
368std::vector<std::vector<int>> generateBinIndices(const RooArgSet &vars)
369{
370 std::vector<std::vector<int>> combinations;
371 std::vector<int> vars_numbins;
372 vars_numbins.reserve(vars.size());
373 for (const auto *absv : static_range_cast<RooRealVar *>(vars)) {
374 vars_numbins.push_back(absv->getBins());
375 }
376 std::vector<int> curr_comb(vars.size());
377 ::genIndicesHelper(combinations, curr_comb, vars_numbins, 0);
378 return combinations;
379}
380
381template <typename... Keys_t>
382JSONNode const *findRooFitInternal(JSONNode const &node, Keys_t const &...keys)
383{
384 return node.find("misc", "ROOT_internal", keys...);
385}
386
387/**
388 * @brief Check if a RooAbsArg is a literal constant variable.
389 *
390 * This function checks whether the provided RooAbsArg 'arg' is a literal constant variable.
391 * A literal constant variable is a RooConstVar with a numeric value as a name.
392 *
393 * @param arg The reference to the RooAbsArg to be checked.
394 * @return bool Returns true if 'arg' is a literal constant variable; otherwise, returns false.
395 */
396bool isLiteralConstVar(RooAbsArg const &arg)
397{
398 bool isRooConstVar = dynamic_cast<RooConstVar const *>(&arg);
399 return isRooConstVar && isNumber(arg.GetName());
400}
401
402/**
403 * @brief Export attributes of a RooAbsArg to a JSONNode.
404 *
405 * This function exports the attributes of the provided RooAbsArg 'arg' to the JSONNode 'rootnode'.
406 *
407 * @param arg The pointer to the RooAbsArg from which attributes will be exported.
408 * @param rootnode The JSONNode to which the attributes will be exported.
409 * @return void
410 */
411void exportAttributes(const RooAbsArg *arg, JSONNode &rootnode)
412{
413 // If this RooConst is a literal number, we don't need to export the attributes.
414 if (isLiteralConstVar(*arg)) {
415 return;
416 }
417
418 JSONNode *node = nullptr;
419
420 auto initializeNode = [&]() {
421 if (node)
422 return;
423
424 node = &RooJSONFactoryWSTool::getRooFitInternal(rootnode, "attributes").set_map()[arg->GetName()].set_map();
425 };
426
427 // We have to remember if the variable was a constant RooRealVar or a
428 // RooConstVar in RooFit to reconstruct the workspace correctly. The HS3
429 // standard does not make this distinction.
430 bool isRooConstVar = dynamic_cast<RooConstVar const *>(arg);
431 if (isRooConstVar) {
432 initializeNode();
433 (*node)["is_const_var"] << 1;
434 }
435
436 // export all string attributes of an object
437 if (!arg->stringAttributes().empty()) {
438 for (const auto &it : arg->stringAttributes()) {
439 // Skip some RooFit internals
440 if (it.first == "factory_tag" || it.first == "PROD_TERM_TYPE")
441 continue;
442 initializeNode();
443 (*node)["dict"].set_map()[it.first] << it.second;
444 }
445 }
446 if (!arg->attributes().empty()) {
447 for (auto const &attr : arg->attributes()) {
448 // Skip some RooFit internals
449 if (attr == "SnapShot_ExtRefClone" || attr == "RooRealConstant_Factory_Object")
450 continue;
451 initializeNode();
452 (*node)["tags"].set_seq().append_child() << attr;
453 }
454 }
455}
456
457/**
458 * @brief Create several observables in the workspace.
459 *
460 * This function obtains a list of observables from the provided
461 * RooWorkspace 'ws' based on their names given in the 'axes" field of
462 * the JSONNode 'node'. The observables are added to the RooArgSet
463 * 'out'.
464 *
465 * @param ws The RooWorkspace in which the observables will be created.
466 * @param node The JSONNode containing information about the observables to be created.
467 * @param out The RooArgSet to which the created observables will be added.
468 * @return void
469 */
470void getObservables(RooWorkspace const &ws, const JSONNode &node, RooArgSet &out)
471{
472 std::map<std::string, Var> vars;
473 for (const auto &p : node["axes"].children()) {
474 vars.emplace(RooJSONFactoryWSTool::name(p), Var(p));
475 }
476
477 for (auto v : vars) {
478 std::string name(v.first);
479 if (ws.var(name)) {
480 out.add(*ws.var(name));
481 } else {
482 std::stringstream errMsg;
483 errMsg << "The observable \"" << name << "\" could not be found in the workspace!";
484 RooJSONFactoryWSTool::error(errMsg.str());
485 }
486 }
487}
488
489/**
490 * @brief Import data from the JSONNode into the workspace.
491 *
492 * This function imports data, represented by the provided JSONNode 'p', into the workspace represented by the provided
493 * RooWorkspace. The data information is read from the JSONNode and added to the workspace.
494 *
495 * @param p The JSONNode representing the data to be imported.
496 * @param workspace The RooWorkspace to which the data will be imported.
497 * @return std::unique_ptr<RooAbsData> A unique pointer to the RooAbsData object representing the imported data.
498 * The caller is responsible for managing the memory of the returned object.
499 */
500std::unique_ptr<RooAbsData> loadData(const JSONNode &p, RooWorkspace &workspace)
501{
502 std::string name(RooJSONFactoryWSTool::name(p));
503
504 if (!::isValidName(name)) {
505 std::stringstream ss;
506 ss << "RooJSONFactoryWSTool() data name '" << name << "' is not valid!" << std::endl;
508 }
509
510 std::string const &type = p["type"].val();
511 if (type == "binned") {
512 // binned
514 } else if (type == "unbinned") {
515 // unbinned
516 RooArgSet vars;
517 getObservables(workspace, p, vars);
518 RooArgList varlist(vars);
519 auto data = std::make_unique<RooDataSet>(name, name, vars, RooFit::WeightVar());
520 auto &coords = p["entries"];
521 auto &weights = p["weights"];
522 if (coords.num_children() != weights.num_children()) {
523 RooJSONFactoryWSTool::error("inconsistent number of entries and weights!");
524 }
525 if (!coords.is_seq()) {
526 RooJSONFactoryWSTool::error("key 'entries' is not a list!");
527 }
528 std::vector<double> weightVals;
529 for (auto const &weight : weights.children()) {
530 weightVals.push_back(weight.val_double());
531 }
532 std::size_t i = 0;
533 for (auto const &point : coords.children()) {
534 if (!point.is_seq()) {
535 std::stringstream errMsg;
536 errMsg << "coordinate point '" << i << "' is not a list!";
537 RooJSONFactoryWSTool::error(errMsg.str());
538 }
539 if (point.num_children() != varlist.size()) {
540 RooJSONFactoryWSTool::error("inconsistent number of entries and observables!");
541 }
542 std::size_t j = 0;
543 for (auto const &pointj : point.children()) {
544 auto *v = static_cast<RooRealVar *>(varlist.at(j));
545 v->setVal(pointj.val_double());
546 ++j;
547 }
548 data->add(vars, weightVals[i]);
549 ++i;
550 }
551 return data;
552 }
553
554 std::stringstream ss;
555 ss << "RooJSONFactoryWSTool() failed to create dataset " << name << std::endl;
557 return nullptr;
558}
559
560/**
561 * @brief Import an analysis from the JSONNode into the workspace.
562 *
563 * This function imports an analysis, represented by the provided JSONNodes 'analysisNode' and 'likelihoodsNode',
564 * into the workspace represented by the provided RooWorkspace. The analysis information is read from the JSONNodes
565 * and added to the workspace as one or more RooStats::ModelConfig objects.
566 *
567 * @param rootnode The root JSONNode representing the entire JSON file.
568 * @param analysisNode The JSONNode representing the analysis to be imported.
569 * @param likelihoodsNode The JSONNode containing information about likelihoods associated with the analysis.
570 * @param workspace The RooWorkspace to which the analysis will be imported.
571 * @param datasets A vector of unique pointers to RooAbsData objects representing the data associated with the analysis.
572 * @return void
573 */
574void importAnalysis(const JSONNode &rootnode, const JSONNode &analysisNode, const JSONNode &likelihoodsNode,
575 RooWorkspace &workspace, const std::vector<std::unique_ptr<RooAbsData>> &datasets)
576{
577 // if this is a toplevel pdf, also create a modelConfig for it
578 std::string const &analysisName = RooJSONFactoryWSTool::name(analysisNode);
579 JSONNode const *mcAuxNode = findRooFitInternal(rootnode, "ModelConfigs", analysisName);
580
581 JSONNode const *mcNameNode = mcAuxNode ? mcAuxNode->find("mcName") : nullptr;
582 std::string mcname = mcNameNode ? mcNameNode->val() : analysisName;
583 if (workspace.obj(mcname))
584 return;
585
586 workspace.import(RooStats::ModelConfig{mcname.c_str(), mcname.c_str()});
587 auto *mc = static_cast<RooStats::ModelConfig *>(workspace.obj(mcname));
588 mc->SetWS(workspace);
589
590 std::vector<std::string> nllDistNames;
591 std::vector<std::string> nllDataNames;
592
593 auto *nllNode = RooJSONFactoryWSTool::findNamedChild(likelihoodsNode, analysisNode["likelihood"].val());
594 if (!nllNode) {
595 throw std::runtime_error("likelihood node not found!");
596 }
597 for (auto &nameNode : (*nllNode)["distributions"].children()) {
598 nllDistNames.push_back(nameNode.val());
599 }
600 RooArgSet extConstraints;
601 for (auto &nameNode : (*nllNode)["aux_distributions"].children()) {
602 RooAbsArg *extConstraint = workspace.arg(nameNode.val());
603 if (extConstraint) {
604 extConstraints.add(*extConstraint);
605 }
606 }
607 RooArgSet observables;
608 for (auto &nameNode : (*nllNode)["data"].children()) {
609 nllDataNames.push_back(nameNode.val());
610 for (const auto &d : datasets) {
611 if (d->GetName() == nameNode.val()) {
612 observables.add(*d->get());
613 }
614 }
615 }
616
617 JSONNode const *pdfNameNode = mcAuxNode ? mcAuxNode->find("pdfName") : nullptr;
618 std::string const pdfName = pdfNameNode ? pdfNameNode->val() : "simPdf";
619
620 RooAbsPdf *pdf = static_cast<RooSimultaneous *>(workspace.pdf(pdfName));
621
622 if (!pdf) {
623 // if there is no simultaneous pdf, we can check whether there is only one pdf in the list
624 if (nllDistNames.size() == 1) {
625 // if so, we can use that one to populate the ModelConfig
626 pdf = workspace.pdf(nllDistNames[0]);
627 } else {
628 // otherwise, we have no choice but to build a simPdf by hand
629 std::string simPdfName = analysisName + "_simPdf";
630 std::string indexCatName = analysisName + "_categoryIndex";
631 RooCategory indexCat{indexCatName.c_str(), indexCatName.c_str()};
632 std::map<std::string, RooAbsPdf *> pdfMap;
633 for (std::size_t i = 0; i < nllDistNames.size(); ++i) {
634 indexCat.defineType(nllDistNames[i], i);
635 pdfMap[nllDistNames[i]] = workspace.pdf(nllDistNames[i]);
636 }
637 RooSimultaneous simPdf{simPdfName.c_str(), simPdfName.c_str(), pdfMap, indexCat};
638 workspace.import(simPdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true));
639 pdf = static_cast<RooSimultaneous *>(workspace.pdf(simPdfName));
640 }
641 }
642
643 mc->SetPdf(*pdf);
644
645 if (!extConstraints.empty())
646 mc->SetExternalConstraints(extConstraints);
647
648 auto readArgSet = [&](std::string const &name) {
649 RooArgSet out;
650 for (auto const &child : analysisNode[name].children()) {
651 out.add(*workspace.arg(child.val()));
652 }
653 return out;
654 };
655
656 mc->SetParametersOfInterest(readArgSet("parameters_of_interest"));
657 mc->SetObservables(observables);
658 RooArgSet pars;
659 pdf->getParameters(&observables, pars);
660
661 // Figure out the set parameters that appear in the main measurement:
662 // getAllConstraints() has the side effect to remove all parameters from
663 // "mainPars" that are not part of any pdf over observables.
664 RooArgSet mainPars{pars};
665 pdf->getAllConstraints(observables, mainPars, /*stripDisconnected*/ true);
666
667 RooArgSet nps;
668 RooArgSet globs;
669 for (const auto &p : pars) {
670 if (mc->GetParametersOfInterest()->find(*p))
671 continue;
672 if (p->isConstant() && !mainPars.find(*p)) {
673 globs.add(*p);
674 } else {
675 nps.add(*p);
676 }
677 }
678 mc->SetGlobalObservables(globs);
679 mc->SetNuisanceParameters(nps);
680
681 if (mcAuxNode) {
682 if (auto found = mcAuxNode->find("combined_data_name")) {
683 pdf->setStringAttribute("combined_data_name", found->val().c_str());
684 }
685 }
686}
687
688void combinePdfs(const JSONNode &rootnode, RooWorkspace &ws)
689{
690 auto *combinedPdfInfoNode = findRooFitInternal(rootnode, "combined_distributions");
691
692 // If there is no info on combining pdfs
693 if (combinedPdfInfoNode == nullptr) {
694 return;
695 }
696
697 for (auto &info : combinedPdfInfoNode->children()) {
698
699 // parse the information
700 std::string combinedName = info.key();
701 std::string indexCatName = info["index_cat"].val();
702 std::vector<std::string> labels;
703 std::vector<int> indices;
704 std::vector<std::string> pdfNames;
705 for (auto &n : info["indices"].children()) {
706 indices.push_back(n.val_int());
707 }
708 for (auto &n : info["labels"].children()) {
709 labels.push_back(n.val());
710 }
711 for (auto &n : info["distributions"].children()) {
712 pdfNames.push_back(n.val());
713 }
714
715 RooCategory indexCat{indexCatName.c_str(), indexCatName.c_str()};
716 std::map<std::string, RooAbsPdf *> pdfMap;
717
718 for (std::size_t iChannel = 0; iChannel < labels.size(); ++iChannel) {
719 indexCat.defineType(labels[iChannel], indices[iChannel]);
720 pdfMap[labels[iChannel]] = ws.pdf(pdfNames[iChannel]);
721 }
722
723 RooSimultaneous simPdf{combinedName.c_str(), combinedName.c_str(), pdfMap, indexCat};
724 ws.import(simPdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true));
725 }
726}
727
728void combineDatasets(const JSONNode &rootnode, std::vector<std::unique_ptr<RooAbsData>> &datasets)
729{
730 auto *combinedDataInfoNode = findRooFitInternal(rootnode, "combined_datasets");
731
732 // If there is no info on combining datasets
733 if (combinedDataInfoNode == nullptr) {
734 return;
735 }
736
737 for (auto &info : combinedDataInfoNode->children()) {
738
739 // parse the information
740 std::string combinedName = info.key();
741 std::string indexCatName = info["index_cat"].val();
742 std::vector<std::string> labels;
743 std::vector<int> indices;
744 for (auto &n : info["indices"].children()) {
745 indices.push_back(n.val_int());
746 }
747 for (auto &n : info["labels"].children()) {
748 labels.push_back(n.val());
749 }
750 if (indices.size() != labels.size()) {
751 RooJSONFactoryWSTool::error("mismatch in number of indices and labels!");
752 }
753
754 // Create the combined dataset for RooFit
755 std::map<std::string, std::unique_ptr<RooAbsData>> dsMap;
756 RooCategory indexCat{indexCatName.c_str(), indexCatName.c_str()};
757 RooArgSet allVars{indexCat};
758 for (std::size_t iChannel = 0; iChannel < labels.size(); ++iChannel) {
759 auto componentName = combinedName + "_" + labels[iChannel];
760 // We move the found channel data out of the "datasets" vector, such that
761 // the data components don't get imported anymore.
762 std::unique_ptr<RooAbsData> &component = *std::find_if(
763 datasets.begin(), datasets.end(), [&](auto &d) { return d && d->GetName() == componentName; });
764 if (!component)
765 RooJSONFactoryWSTool::error("unable to obtain component matching component name '" + componentName + "'");
766 allVars.add(*component->get());
767 dsMap.insert({labels[iChannel], std::move(component)});
768 indexCat.defineType(labels[iChannel], indices[iChannel]);
769 }
770
771 auto combined = std::make_unique<RooDataSet>(combinedName, combinedName, allVars, RooFit::Import(dsMap),
772 RooFit::Index(indexCat));
773 datasets.emplace_back(std::move(combined));
774 }
775}
776
777template <class T>
778void sortByName(T &coll)
779{
780 std::sort(coll.begin(), coll.end(), [](auto &l, auto &r) { return strcmp(l->GetName(), r->GetName()) < 0; });
781}
782
783} // namespace
784
786
788
789void RooJSONFactoryWSTool::fillSeq(JSONNode &node, RooAbsCollection const &coll, size_t nMax)
790{
791 const size_t old_children = node.num_children();
792 node.set_seq();
793 size_t n = 0;
794 for (RooAbsArg const *arg : coll) {
795 if (n >= nMax)
796 break;
797 if (isLiteralConstVar(*arg)) {
798 node.append_child() << static_cast<RooConstVar const *>(arg)->getVal();
799 } else {
800 node.append_child() << arg->GetName();
801 }
802 ++n;
803 }
804 if (node.num_children() != old_children + coll.size()) {
805 error("unable to stream collection " + std::string(coll.GetName()) + " to " + node.key());
806 }
807}
808
810{
812 return node.set_map()[name].set_map();
813 }
815 child["name"] << name;
816 return child;
817}
818
819JSONNode const *RooJSONFactoryWSTool::findNamedChild(JSONNode const &node, std::string const &name)
820{
822 if (!node.is_map())
823 return nullptr;
824 return node.find(name);
825 }
826 if (!node.is_seq())
827 return nullptr;
828 for (JSONNode const &child : node.children()) {
829 if (child["name"].val() == name)
830 return &child;
831 }
832
833 return nullptr;
834}
835
837{
838 return useListsInsteadOfDicts ? n["name"].val() : n.key();
839}
840
842{
843 return appendNamedChild(rootNode["parameter_points"], "default_values")["parameters"];
844}
845
846template <>
847RooRealVar *RooJSONFactoryWSTool::requestImpl<RooRealVar>(const std::string &objname)
848{
849 if (RooRealVar *retval = _workspace.var(objname))
850 return retval;
851 if (JSONNode const *vars = getVariablesNode(*_rootnodeInput)) {
852 if (auto node = vars->find(objname)) {
853 this->importVariable(*node);
854 if (RooRealVar *retval = _workspace.var(objname))
855 return retval;
856 }
857 }
858 return nullptr;
859}
860
861template <>
862RooAbsPdf *RooJSONFactoryWSTool::requestImpl<RooAbsPdf>(const std::string &objname)
863{
864 if (RooAbsPdf *retval = _workspace.pdf(objname))
865 return retval;
866 if (auto distributionsNode = _rootnodeInput->find("distributions")) {
867 if (auto child = findNamedChild(*distributionsNode, objname)) {
868 this->importFunction(*child, true);
869 if (RooAbsPdf *retval = _workspace.pdf(objname))
870 return retval;
871 }
872 }
873 return nullptr;
874}
875
876template <>
877RooAbsReal *RooJSONFactoryWSTool::requestImpl<RooAbsReal>(const std::string &objname)
878{
879 if (RooAbsReal *retval = _workspace.function(objname))
880 return retval;
881 if (isNumber(objname))
882 return &RooFit::RooConst(std::stod(objname));
883 if (RooAbsPdf *pdf = requestImpl<RooAbsPdf>(objname))
884 return pdf;
885 if (RooRealVar *var = requestImpl<RooRealVar>(objname))
886 return var;
887 if (auto functionNode = _rootnodeInput->find("functions")) {
888 if (auto child = findNamedChild(*functionNode, objname)) {
889 this->importFunction(*child, true);
890 if (RooAbsReal *retval = _workspace.function(objname))
891 return retval;
892 }
893 }
894 return nullptr;
895}
896
897/**
898 * @brief Export a variable from the workspace to a JSONNode.
899 *
900 * This function exports a variable, represented by the provided RooAbsArg pointer 'v', from the workspace to a
901 * JSONNode. The variable's information is added to the JSONNode as key-value pairs.
902 *
903 * @param v The pointer to the RooAbsArg representing the variable to be exported.
904 * @param node The JSONNode to which the variable will be exported.
905 * @return void
906 */
908{
909 auto *cv = dynamic_cast<const RooConstVar *>(v);
910 auto *rrv = dynamic_cast<const RooRealVar *>(v);
911 if (!cv && !rrv)
912 return;
913
914 // for RooConstVar, if name and value are the same, we don't need to do anything
915 if (cv && strcmp(cv->GetName(), TString::Format("%g", cv->getVal()).Data()) == 0) {
916 return;
917 }
918
919 // this variable was already exported
920 if (findNamedChild(node, v->GetName())) {
921 return;
922 }
923
924 JSONNode &var = appendNamedChild(node, v->GetName());
925
926 if (cv) {
927 var["value"] << cv->getVal();
928 var["const"] << true;
929 } else if (rrv) {
930 var["value"] << rrv->getVal();
931 if (rrv->isConstant()) {
932 var["const"] << rrv->isConstant();
933 }
934 if (rrv->getBins() != 100) {
935 var["nbins"] << rrv->getBins();
936 }
937 _domains->readVariable(*rrv);
938 }
939}
940
941/**
942 * @brief Export variables from the workspace to a JSONNode.
943 *
944 * This function exports variables, represented by the provided RooArgSet, from the workspace to a JSONNode.
945 * The variables' information is added to the JSONNode as key-value pairs.
946 *
947 * @param allElems The RooArgSet representing the variables to be exported.
948 * @param n The JSONNode to which the variables will be exported.
949 * @return void
950 */
952{
953 // export a list of RooRealVar objects
954 for (RooAbsArg *arg : allElems) {
955 exportVariable(arg, n);
956 }
957}
958
959RooAbsReal *RooJSONFactoryWSTool::importTransformed(const std::string &name, const std::string &tag,
960 const std::string &operation_name, const std::string &formula)
961{
962 RooAbsReal *transformed = nullptr;
963 const std::string tagname = "autogen_transform_" + tag;
964 if (this->hasAttribute(name, tagname)) {
965 const std::string &original = this->getStringAttribute(name, tagname + "_original");
966 transformed = this->workspace()->function(original);
967 if (transformed)
968 return transformed;
969 }
970 const std::string newname = name + "_" + tag + "_" + operation_name;
971 transformed = this->workspace()->function(newname);
972 if (!transformed) {
973 auto *original = this->workspace()->arg(name);
974 if (!original) {
975 error("unable to import transformed of '" + name + "', original not present.");
976 }
977 RooArgSet components{*original};
978 const std::string &expression = TString::Format(formula.c_str(), name.c_str()).Data();
979 transformed = &wsEmplace<RooFormulaVar>(newname, expression.c_str(), components);
980 transformed->setAttribute(tagname.c_str());
981 }
982 return transformed;
983}
984
985std::string RooJSONFactoryWSTool::exportTransformed(const RooAbsReal *original, const std::string &tag,
986 const std::string &operation_name, const std::string &formula)
987{
988 const std::string tagname = "autogen_transform_" + tag;
989 if (original->getAttribute(tagname.c_str())) {
990 if (const RooFormulaVar *trafo = dynamic_cast<const RooFormulaVar *>(original)) {
991 return trafo->dependents().first()->GetName();
992 }
993 }
994
995 std::string newname = std::string(original->GetName()) + "_" + tag + "_" + operation_name;
996 auto &trafo_node = this->createAdHoc("functions", newname);
997 trafo_node["type"] << "generic_function";
998 trafo_node["expression"] << TString::Format(formula.c_str(), original->GetName()).Data();
999 this->setAttribute(newname, tagname);
1000 this->setStringAttribute(newname, tagname + "_original", original->GetName());
1001 return newname;
1002}
1003
1004RooFit::Detail::JSONNode &RooJSONFactoryWSTool::createAdHoc(const std::string &toplevel, const std::string &name)
1005{
1006 auto &collectionNode = (*_rootnodeOutput)[toplevel];
1007 return appendNamedChild(collectionNode, name);
1008}
1009
1010/**
1011 * @brief Export an object from the workspace to a JSONNode.
1012 *
1013 * This function exports an object, represented by the provided RooAbsArg, from the workspace to a JSONNode.
1014 * The object's information is added to the JSONNode as key-value pairs.
1015 *
1016 * @param func The RooAbsArg representing the object to be exported.
1017 * @param exportedObjectNames A set of strings containing names of previously exported objects to avoid duplicates.
1018 * This set is updated with the name of the newly exported object.
1019 * @return void
1020 */
1021void RooJSONFactoryWSTool::exportObject(RooAbsArg const &func, std::set<std::string> &exportedObjectNames)
1022{
1023 const std::string name = func.GetName();
1024
1025 // if this element was already exported, skip
1026 if (exportedObjectNames.find(name) != exportedObjectNames.end())
1027 return;
1028
1029 exportedObjectNames.insert(name);
1030
1031 if (auto simPdf = dynamic_cast<RooSimultaneous const *>(&func)) {
1032 // RooSimultaneous is not used in the HS3 standard, we only export the
1033 // dependents and some ROOT internal information.
1034 for (RooAbsArg *s : func.servers()) {
1035 this->exportObject(*s, exportedObjectNames);
1036 }
1037
1038 std::vector<std::string> channelNames;
1039 for (auto const &item : simPdf->indexCat()) {
1040 channelNames.push_back(item.first);
1041 }
1042
1043 auto &infoNode = getRooFitInternal(*_rootnodeOutput, "combined_distributions").set_map();
1044 auto &child = infoNode[simPdf->GetName()].set_map();
1045 child["index_cat"] << simPdf->indexCat().GetName();
1046 exportCategory(simPdf->indexCat(), child);
1047 child["distributions"].set_seq();
1048 for (auto const &item : simPdf->indexCat()) {
1049 child["distributions"].append_child() << simPdf->getPdf(item.first.c_str())->GetName();
1050 }
1051
1052 return;
1053 } else if (dynamic_cast<RooAbsCategory const *>(&func)) {
1054 // categories are created by the respective RooSimultaneous, so we're skipping the export here
1055 return;
1056 } else if (dynamic_cast<RooRealVar const *>(&func) || dynamic_cast<RooConstVar const *>(&func)) {
1057 exportVariable(&func, *_varsNode);
1058 return;
1059 }
1060
1061 auto &collectionNode = (*_rootnodeOutput)[dynamic_cast<RooAbsPdf const *>(&func) ? "distributions" : "functions"];
1062
1063 auto const &exporters = RooFit::JSONIO::exporters();
1064 auto const &exportKeys = RooFit::JSONIO::exportKeys();
1065
1066 TClass *cl = func.IsA();
1067
1068 auto &elem = appendNamedChild(collectionNode, name);
1069
1070 auto it = exporters.find(cl);
1071 if (it != exporters.end()) { // check if we have a specific exporter available
1072 for (auto &exp : it->second) {
1073 _serversToExport.clear();
1074 if (!exp->exportObject(this, &func, elem)) {
1075 // The exporter might have messed with the content of the node
1076 // before failing. That's why we clear it and only reset the name.
1077 elem.clear();
1078 elem.set_map();
1080 elem["name"] << name;
1081 }
1082 continue;
1083 }
1084 if (exp->autoExportDependants()) {
1085 for (RooAbsArg *s : func.servers()) {
1086 this->exportObject(*s, exportedObjectNames);
1087 }
1088 } else {
1089 for (RooAbsArg const *s : _serversToExport) {
1090 this->exportObject(*s, exportedObjectNames);
1091 }
1092 }
1093 return;
1094 }
1095 }
1096
1097 // generic export using the factory expressions
1098 const auto &dict = exportKeys.find(cl);
1099 if (dict == exportKeys.end()) {
1100 std::cerr << "unable to export class '" << cl->GetName() << "' - no export keys available!\n"
1101 << "there are several possible reasons for this:\n"
1102 << " 1. " << cl->GetName() << " is a custom class that you or some package you are using added.\n"
1103 << " 2. " << cl->GetName()
1104 << " is a ROOT class that nobody ever bothered to write a serialization definition for.\n"
1105 << " 3. something is wrong with your setup, e.g. you might have called "
1106 "RooFit::JSONIO::clearExportKeys() and/or never successfully read a file defining these "
1107 "keys with RooFit::JSONIO::loadExportKeys(filename)\n"
1108 << "either way, please make sure that:\n"
1109 << " 3: you are reading a file with export keys - call RooFit::JSONIO::printExportKeys() to "
1110 "see what is available\n"
1111 << " 2 & 1: you might need to write a serialization definition yourself. check "
1112 "https://github.com/root-project/root/blob/master/roofit/hs3/README.md to "
1113 "see how to do this!\n";
1114 return;
1115 }
1116
1117 elem["type"] << dict->second.type;
1118
1119 size_t nprox = func.numProxies();
1120
1121 for (size_t i = 0; i < nprox; ++i) {
1122 RooAbsProxy *p = func.getProxy(i);
1123
1124 // some proxies start with a "!". This is a magic symbol that we don't want to stream
1125 std::string pname(p->name());
1126 if (pname[0] == '!')
1127 pname.erase(0, 1);
1128
1129 auto k = dict->second.proxies.find(pname);
1130 if (k == dict->second.proxies.end()) {
1131 std::cerr << "failed to find key matching proxy '" << pname << "' for type '" << dict->second.type
1132 << "', encountered in '" << func.GetName() << "', skipping" << std::endl;
1133 return;
1134 }
1135
1136 // empty string is interpreted as an instruction to ignore this value
1137 if (k->second.empty())
1138 continue;
1139
1140 if (auto l = dynamic_cast<RooListProxy *>(p)) {
1141 fillSeq(elem[k->second], *l);
1142 }
1143 if (auto r = dynamic_cast<RooArgProxy *>(p)) {
1144 if (isLiteralConstVar(*r->absArg())) {
1145 elem[k->second] << static_cast<RooConstVar *>(r->absArg())->getVal();
1146 } else {
1147 elem[k->second] << r->absArg()->GetName();
1148 }
1149 }
1150 }
1151
1152 // export all the servers of a given RooAbsArg
1153 for (RooAbsArg *s : func.servers()) {
1154 this->exportObject(*s, exportedObjectNames);
1155 }
1156}
1157
1158/**
1159 * @brief Import a function from the JSONNode into the workspace.
1160 *
1161 * This function imports a function from the given JSONNode into the workspace.
1162 * The function's information is read from the JSONNode and added to the workspace.
1163 *
1164 * @param p The JSONNode representing the function to be imported.
1165 * @param importAllDependants A boolean flag indicating whether to import all dependants (servers) of the function.
1166 * @return void
1167 */
1168void RooJSONFactoryWSTool::importFunction(const JSONNode &p, bool importAllDependants)
1169{
1170 auto const &importers = RooFit::JSONIO::importers();
1171 auto const &factoryExpressions = RooFit::JSONIO::importExpressions();
1172
1173 // some preparations: what type of function are we dealing with here?
1174 std::string name(RooJSONFactoryWSTool::name(p));
1175 if (!::isValidName(name)) {
1176 std::stringstream ss;
1177 ss << "RooJSONFactoryWSTool() function name '" << name << "' is not valid!" << std::endl;
1179 }
1180
1181 // if the RooAbsArg already exists, we don't need to do anything
1182 if (_workspace.arg(name)) {
1183 return;
1184 }
1185 // if the key we found is not a map, it's an error
1186 if (!p.is_map()) {
1187 std::stringstream ss;
1188 ss << "RooJSONFactoryWSTool() function node " + name + " is not a map!";
1190 return;
1191 }
1192 std::string prefix = genPrefix(p, true);
1193 if (!prefix.empty())
1194 name = prefix + name;
1195 if (!p.has_child("type")) {
1196 std::stringstream ss;
1197 ss << "RooJSONFactoryWSTool() no type given for function '" << name << "', skipping." << std::endl;
1199 return;
1200 }
1201
1202 std::string functype(p["type"].val());
1203
1204 // import all dependents if importing a workspace, not for creating new objects
1205 if (!importAllDependants) {
1206 this->importDependants(p);
1207 }
1208
1209 // check for specific implementations
1210 auto it = importers.find(functype);
1211 bool ok = false;
1212 if (it != importers.end()) {
1213 for (auto &imp : it->second) {
1214 ok = imp->importArg(this, p);
1215 if (ok)
1216 break;
1217 }
1218 }
1219 if (!ok) { // generic import using the factory expressions
1220 auto expr = factoryExpressions.find(functype);
1221 if (expr != factoryExpressions.end()) {
1222 std::string expression = ::generate(expr->second, p, this);
1223 if (!_workspace.factory(expression)) {
1224 std::stringstream ss;
1225 ss << "RooJSONFactoryWSTool() failed to create " << expr->second.tclass->GetName() << " '" << name
1226 << "', skipping. expression was\n"
1227 << expression << std::endl;
1229 }
1230 } else {
1231 std::stringstream ss;
1232 ss << "RooJSONFactoryWSTool() no handling for type '" << functype << "' implemented, skipping."
1233 << "\n"
1234 << "there are several possible reasons for this:\n"
1235 << " 1. " << functype << " is a custom type that is not available in RooFit.\n"
1236 << " 2. " << functype
1237 << " is a ROOT class that nobody ever bothered to write a deserialization definition for.\n"
1238 << " 3. something is wrong with your setup, e.g. you might have called "
1239 "RooFit::JSONIO::clearFactoryExpressions() and/or never successfully read a file defining "
1240 "these expressions with RooFit::JSONIO::loadFactoryExpressions(filename)\n"
1241 << "either way, please make sure that:\n"
1242 << " 3: you are reading a file with factory expressions - call "
1243 "RooFit::JSONIO::printFactoryExpressions() "
1244 "to see what is available\n"
1245 << " 2 & 1: you might need to write a deserialization definition yourself. check "
1246 "https://github.com/root-project/root/blob/master/roofit/hs3/README.md to see "
1247 "how to do this!"
1248 << std::endl;
1250 return;
1251 }
1252 }
1254 if (!func) {
1255 std::stringstream err;
1256 err << "something went wrong importing function '" << name << "'.";
1257 RooJSONFactoryWSTool::error(err.str());
1258 }
1259}
1260
1261/**
1262 * @brief Import a function from a JSON string into the workspace.
1263 *
1264 * This function imports a function from the provided JSON string into the workspace.
1265 * The function's information is read from the JSON string and added to the workspace.
1266 *
1267 * @param jsonString The JSON string containing the function information.
1268 * @param importAllDependants A boolean flag indicating whether to import all dependants (servers) of the function.
1269 * @return void
1270 */
1271void RooJSONFactoryWSTool::importFunction(const std::string &jsonString, bool importAllDependants)
1272{
1273 this->importFunction((JSONTree::create(jsonString))->rootnode(), importAllDependants);
1274}
1275
1276/**
1277 * @brief Export histogram data to a JSONNode.
1278 *
1279 * This function exports histogram data, represented by the provided variables and contents, to a JSONNode.
1280 * The histogram's axes information and bin contents are added as key-value pairs to the JSONNode.
1281 *
1282 * @param vars The RooArgSet representing the variables associated with the histogram.
1283 * @param n The number of bins in the histogram.
1284 * @param contents A pointer to the array containing the bin contents of the histogram.
1285 * @param output The JSONNode to which the histogram data will be exported.
1286 * @return void
1287 */
1288void RooJSONFactoryWSTool::exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, JSONNode &output)
1289{
1290 auto &observablesNode = output["axes"].set_seq();
1291 // axes have to be ordered to get consistent bin indices
1292 for (auto *var : static_range_cast<RooRealVar *>(vars)) {
1293 JSONNode &obsNode = observablesNode.append_child().set_map();
1294 obsNode["name"] << var->GetName();
1295 if (var->getBinning().isUniform()) {
1296 obsNode["min"] << var->getMin();
1297 obsNode["max"] << var->getMax();
1298 obsNode["nbins"] << var->getBins();
1299 } else {
1300 auto &edges = obsNode["edges"];
1301 edges.set_seq();
1302 double val = var->getBinning().binLow(0);
1303 edges.append_child() << val;
1304 for (int i = 0; i < var->getBinning().numBins(); ++i) {
1305 val = var->getBinning().binHigh(i);
1306 edges.append_child() << val;
1307 }
1308 }
1309 }
1310
1311 return exportArray(n, contents, output["contents"]);
1312}
1313
1314/**
1315 * @brief Export an array of doubles to a JSONNode.
1316 *
1317 * This function exports an array of doubles, represented by the provided size and contents,
1318 * to a JSONNode. The array elements are added to the JSONNode as a sequence of values.
1319 *
1320 * @param n The size of the array.
1321 * @param contents A pointer to the array containing the double values.
1322 * @param output The JSONNode to which the array will be exported.
1323 * @return void
1324 */
1325void RooJSONFactoryWSTool::exportArray(std::size_t n, double const *contents, JSONNode &output)
1326{
1327 output.set_seq();
1328 for (std::size_t i = 0; i < n; ++i) {
1329 double w = contents[i];
1330 // To make sure there are no unnecessary floating points in the JSON
1331 if (int(w) == w) {
1332 output.append_child() << int(w);
1333 } else {
1334 output.append_child() << w;
1335 }
1336 }
1337}
1338
1339/**
1340 * @brief Export a RooAbsCategory object to a JSONNode.
1341 *
1342 * This function exports a RooAbsCategory object, represented by the provided categories and indices,
1343 * to a JSONNode. The category labels and corresponding indices are added to the JSONNode as key-value pairs.
1344 *
1345 * @param cat The RooAbsCategory object to be exported.
1346 * @param node The JSONNode to which the category data will be exported.
1347 * @return void
1348 */
1350{
1351 auto &labels = node["labels"].set_seq();
1352 auto &indices = node["indices"].set_seq();
1353
1354 for (auto const &item : cat) {
1355 std::string label;
1356 if (std::isalpha(item.first[0])) {
1357 label = RooFit::Detail::makeValidVarName(item.first);
1358 if (label != item.first) {
1359 oocoutW(nullptr, IO) << "RooFitHS3: changed '" << item.first << "' to '" << label
1360 << "' to become a valid name";
1361 }
1362 } else {
1363 RooJSONFactoryWSTool::error("refusing to change first character of string '" + item.first +
1364 "' to make a valid name!");
1365 label = item.first;
1366 }
1367 labels.append_child() << label;
1368 indices.append_child() << item.second;
1369 }
1370}
1371
1372/**
1373 * @brief Export combined data from the workspace to a custom struct.
1374 *
1375 * This function exports combined data from the workspace, represented by the provided RooAbsData object,
1376 * to a CombinedData struct. The struct contains information such as variables, categories,
1377 * and bin contents of the combined data.
1378 *
1379 * @param data The RooAbsData object representing the combined data to be exported.
1380 * @return CombinedData A custom struct containing the exported combined data.
1381 */
1383{
1384 // find category observables
1385 RooAbsCategory *cat = nullptr;
1386 for (RooAbsArg *obs : *data.get()) {
1387 if (dynamic_cast<RooAbsCategory *>(obs)) {
1388 if (cat) {
1389 RooJSONFactoryWSTool::error("dataset '" + std::string(data.GetName()) +
1390 " has several category observables!");
1391 }
1392 cat = static_cast<RooAbsCategory *>(obs);
1393 }
1394 }
1395
1396 // prepare return value
1398
1399 if (!cat)
1400 return datamap;
1401 // this is a combined dataset
1402
1403 datamap.name = data.GetName();
1404
1405 // Write information necessary to reconstruct the combined dataset upon import
1406 auto &child = getRooFitInternal(*_rootnodeOutput, "combined_datasets").set_map()[data.GetName()].set_map();
1407 child["index_cat"] << cat->GetName();
1408 exportCategory(*cat, child);
1409
1410 // Find a RooSimultaneous model that would fit to this dataset
1411 RooSimultaneous const *simPdf = nullptr;
1412 auto *combinedPdfInfoNode = findRooFitInternal(*_rootnodeOutput, "combined_distributions");
1413 if (combinedPdfInfoNode) {
1414 for (auto &info : combinedPdfInfoNode->children()) {
1415 if (info["index_cat"].val() == cat->GetName()) {
1416 simPdf = static_cast<RooSimultaneous const *>(_workspace.pdf(info.key()));
1417 }
1418 }
1419 }
1420
1421 // If there is an associated simultaneous pdf for the index category, we
1422 // use the RooAbsData::split() overload that takes the RooSimultaneous.
1423 // Like this, the observables that are not relevant for a given channel
1424 // are automatically split from the component datasets.
1425 std::unique_ptr<TList> dataList{simPdf ? data.split(*simPdf, true) : data.split(*cat, true)};
1426
1427 for (RooAbsData *absData : static_range_cast<RooAbsData *>(*dataList)) {
1428 std::string catName(absData->GetName());
1429 std::string dataName;
1430 if (std::isalpha(catName[0])) {
1431 dataName = RooFit::Detail::makeValidVarName(catName);
1432 if (dataName != catName) {
1433 oocoutW(nullptr, IO) << "RooFitHS3: changed '" << catName << "' to '" << dataName
1434 << "' to become a valid name";
1435 }
1436 } else {
1437 RooJSONFactoryWSTool::error("refusing to change first character of string '" + catName +
1438 "' to make a valid name!");
1439 dataName = catName;
1440 }
1441 absData->SetName((std::string(data.GetName()) + "_" + dataName).c_str());
1442 datamap.components[catName] = absData->GetName();
1443 this->exportData(*absData);
1444 }
1445 return datamap;
1446}
1447
1448/**
1449 * @brief Export data from the workspace to a JSONNode.
1450 *
1451 * This function exports data represented by the provided RooAbsData object,
1452 * to a JSONNode. The data's information is added as key-value pairs to the JSONNode.
1453 *
1454 * @param data The RooAbsData object representing the data to be exported.
1455 * @return void
1456 */
1458{
1459 // find category observables
1460 RooAbsCategory *cat = nullptr;
1461 for (RooAbsArg *obs : *data.get()) {
1462 if (dynamic_cast<RooAbsCategory *>(obs)) {
1463 if (cat) {
1464 RooJSONFactoryWSTool::error("dataset '" + std::string(data.GetName()) +
1465 " has several category observables!");
1466 }
1467 cat = static_cast<RooAbsCategory *>(obs);
1468 }
1469 }
1470
1471 if (cat)
1472 return;
1473
1474 JSONNode &output = appendNamedChild((*_rootnodeOutput)["data"], data.GetName());
1475
1476 // this is a binned dataset
1477 if (auto dh = dynamic_cast<RooDataHist const *>(&data)) {
1478 output["type"] << "binned";
1479 return exportHisto(*dh->get(), dh->numEntries(), dh->weightArray(), output);
1480 }
1481
1482 // this is a regular unbinned dataset
1483
1484 // This works around a problem in RooStats/HistFactory that was only fixed
1485 // in ROOT 6.30: until then, the weight variable of the observed dataset,
1486 // called "weightVar", was added to the observables. Therefore, it also got
1487 // added to the Asimov dataset. But the Asimov has its own weight variable,
1488 // called "binWeightAsimov", making "weightVar" an actual observable in the
1489 // Asimov data. But this is only by accident and should be removed.
1490 RooArgSet variables = *data.get();
1491 if (auto weightVar = variables.find("weightVar")) {
1492 variables.remove(*weightVar);
1493 }
1494
1495 // Check if this actually represents a binned dataset, and then import it
1496 // like a RooDataHist. This happens frequently when people create combined
1497 // RooDataSets from binned data to fit HistFactory models. In this case, it
1498 // doesn't make sense to export them like an unbinned dataset, because the
1499 // coordinates are redundant information with the binning. We only do this
1500 // for 1D data for now.
1501 if (data.isWeighted() && variables.size() == 1) {
1502 bool isBinnedData = false;
1503 auto &x = static_cast<RooRealVar const &>(*variables[0]);
1504 std::vector<double> contents;
1505 int i = 0;
1506 for (; i < data.numEntries(); ++i) {
1507 data.get(i);
1508 if (x.getBin() != i)
1509 break;
1510 contents.push_back(data.weight());
1511 }
1512 if (i == x.getBins())
1513 isBinnedData = true;
1514 if (isBinnedData) {
1515 output["type"] << "binned";
1516 return exportHisto(variables, data.numEntries(), contents.data(), output);
1517 }
1518 }
1519
1520 output["type"] << "unbinned";
1521
1522 for (RooAbsArg *arg : variables) {
1523 exportVariable(arg, output["axes"]);
1524 }
1525 auto &coords = output["entries"].set_seq();
1526 auto *weights = data.isWeighted() ? &output["weights"].set_seq() : nullptr;
1527 for (int i = 0; i < data.numEntries(); ++i) {
1528 data.get(i);
1529 coords.append_child().fill_seq(variables, [](auto x) { return static_cast<RooRealVar *>(x)->getVal(); });
1530 if (weights)
1531 weights->append_child() << data.weight();
1532 }
1533}
1534
1535/**
1536 * @brief Read axes from the JSONNode and create a RooArgSet representing them.
1537 *
1538 * This function reads axes information from the given JSONNode and
1539 * creates a RooArgSet with variables representing these axes.
1540 *
1541 * @param topNode The JSONNode containing the axes information to be read.
1542 * @return RooArgSet A RooArgSet containing the variables created from the JSONNode.
1543 */
1545{
1546 RooArgSet vars;
1547
1548 for (JSONNode const &node : topNode["axes"].children()) {
1549 if (node.has_child("edges")) {
1550 std::vector<double> edges;
1551 for (auto const &bound : node["edges"].children()) {
1552 edges.push_back(bound.val_double());
1553 }
1554 auto obs = std::make_unique<RooRealVar>(node["name"].val().c_str(), node["name"].val().c_str(), edges[0],
1555 edges[edges.size() - 1]);
1556 RooBinning bins(obs->getMin(), obs->getMax());
1557 for (auto b : edges) {
1558 bins.addBoundary(b);
1559 }
1560 obs->setBinning(bins);
1561 vars.addOwned(std::move(obs));
1562 } else {
1563 auto obs = std::make_unique<RooRealVar>(node["name"].val().c_str(), node["name"].val().c_str(),
1564 node["min"].val_double(), node["max"].val_double());
1565 obs->setBins(node["nbins"].val_int());
1566 vars.addOwned(std::move(obs));
1567 }
1568 }
1569
1570 return vars;
1571}
1572
1573/**
1574 * @brief Read binned data from the JSONNode and create a RooDataHist object.
1575 *
1576 * This function reads binned data from the given JSONNode and creates a RooDataHist object.
1577 * The binned data is associated with the specified name and variables (RooArgSet) in the workspace.
1578 *
1579 * @param n The JSONNode representing the binned data to be read.
1580 * @param name The name to be associated with the created RooDataHist object.
1581 * @param vars The RooArgSet representing the variables associated with the binned data.
1582 * @return std::unique_ptr<RooDataHist> A unique pointer to the created RooDataHist object.
1583 */
1584std::unique_ptr<RooDataHist>
1585RooJSONFactoryWSTool::readBinnedData(const JSONNode &n, const std::string &name, RooArgSet const &vars)
1586{
1587 if (!n.has_child("contents"))
1588 RooJSONFactoryWSTool::error("no contents given");
1589
1590 JSONNode const &contents = n["contents"];
1591
1592 if (!contents.is_seq())
1593 RooJSONFactoryWSTool::error("contents are not in list form");
1594
1595 JSONNode const *errors = nullptr;
1596 if (n.has_child("errors")) {
1597 errors = &n["errors"];
1598 if (!errors->is_seq())
1599 RooJSONFactoryWSTool::error("errors are not in list form");
1600 }
1601
1602 auto bins = generateBinIndices(vars);
1603 if (contents.num_children() != bins.size()) {
1604 std::stringstream errMsg;
1605 errMsg << "inconsistent bin numbers: contents=" << contents.num_children() << ", bins=" << bins.size();
1606 RooJSONFactoryWSTool::error(errMsg.str());
1607 }
1608 auto dh = std::make_unique<RooDataHist>(name, name, vars);
1609 std::vector<double> contentVals;
1610 contentVals.reserve(contents.num_children());
1611 for (auto const &cont : contents.children()) {
1612 contentVals.push_back(cont.val_double());
1613 }
1614 std::vector<double> errorVals;
1615 if (errors) {
1616 errorVals.reserve(errors->num_children());
1617 for (auto const &err : errors->children()) {
1618 errorVals.push_back(err.val_double());
1619 }
1620 }
1621 for (size_t ibin = 0; ibin < bins.size(); ++ibin) {
1622 const double err = errors ? errorVals[ibin] : -1;
1623 dh->set(ibin, contentVals[ibin], err);
1624 }
1625 return dh;
1626}
1627
1628/**
1629 * @brief Import a variable from the JSONNode into the workspace.
1630 *
1631 * This function imports a variable from the given JSONNode into the workspace.
1632 * The variable's information is read from the JSONNode and added to the workspace.
1633 *
1634 * @param p The JSONNode representing the variable to be imported.
1635 * @return void
1636 */
1638{
1639 // import a RooRealVar object
1640 std::string name(RooJSONFactoryWSTool::name(p));
1641
1642 if (!::isValidName(name)) {
1643 std::stringstream ss;
1644 ss << "RooJSONFactoryWSTool() variable name '" << name << "' is not valid!" << std::endl;
1646 }
1647
1648 if (_workspace.var(name))
1649 return;
1650 if (!p.is_map()) {
1651 std::stringstream ss;
1652 ss << "RooJSONFactoryWSTool() node '" << name << "' is not a map, skipping.";
1653 oocoutE(nullptr, InputArguments) << ss.str() << std::endl;
1654 return;
1655 }
1656 if (_attributesNode) {
1657 if (auto *attrNode = _attributesNode->find(name)) {
1658 // We should not create RooRealVar objects for RooConstVars!
1659 if (attrNode->has_child("is_const_var") && (*attrNode)["is_const_var"].val_int() == 1) {
1660 wsEmplace<RooConstVar>(name, p["value"].val_double());
1661 return;
1662 }
1663 }
1664 }
1665 configureVariable(*_domains, p, wsEmplace<RooRealVar>(name, 1.));
1666}
1667
1668/**
1669 * @brief Import all dependants (servers) of a node into the workspace.
1670 *
1671 * This function imports all the dependants (servers) of the given JSONNode into the workspace.
1672 * The dependants' information is read from the JSONNode and added to the workspace.
1673 *
1674 * @param n The JSONNode representing the node whose dependants are to be imported.
1675 * @return void
1676 */
1678{
1679 // import all the dependants of an object
1680 if (JSONNode const *varsNode = getVariablesNode(n)) {
1681 for (const auto &p : varsNode->children()) {
1683 }
1684 }
1685 if (auto seq = n.find("functions")) {
1686 for (const auto &p : seq->children()) {
1687 this->importFunction(p, true);
1688 }
1689 }
1690 if (auto seq = n.find("distributions")) {
1691 for (const auto &p : seq->children()) {
1692 this->importFunction(p, true);
1693 }
1694 }
1695}
1696
1698 const std::vector<CombinedData> &combDataSets)
1699{
1700 auto pdf = dynamic_cast<RooSimultaneous const *>(mc.GetPdf());
1701 if (pdf == nullptr) {
1702 warning("RooFitHS3 only supports ModelConfigs with RooSimultaneous! Skipping ModelConfig.");
1703 return;
1704 }
1705
1706 for (std::size_t i = 0; i < std::max(combDataSets.size(), std::size_t(1)); ++i) {
1707 const bool hasdata = i < combDataSets.size();
1708 if (hasdata && !matches(combDataSets.at(i), pdf))
1709 continue;
1710
1711 std::string analysisName(pdf->GetName());
1712 if (hasdata)
1713 analysisName += "_" + combDataSets[i].name;
1714
1715 exportSingleModelConfig(rootnode, mc, analysisName, hasdata ? &combDataSets[i].components : nullptr);
1716 }
1717}
1718
1720 std::string const &analysisName,
1721 std::map<std::string, std::string> const *dataComponents)
1722{
1723 auto pdf = static_cast<RooSimultaneous const *>(mc.GetPdf());
1724
1725 JSONNode &analysisNode = appendNamedChild(rootnode["analyses"], analysisName);
1726
1727 analysisNode["domains"].set_seq().append_child() << "default_domain";
1728
1729 analysisNode["likelihood"] << analysisName;
1730
1731 auto &nllNode = appendNamedChild(rootnode["likelihoods"], analysisName);
1732 nllNode["distributions"].set_seq();
1733 nllNode["data"].set_seq();
1734
1735 if (dataComponents) {
1736 for (auto const &item : pdf->indexCat()) {
1737 const auto &dataComp = dataComponents->find(item.first);
1738 nllNode["distributions"].append_child() << pdf->getPdf(item.first)->GetName();
1739 nllNode["data"].append_child() << dataComp->second;
1740 }
1741 }
1742
1743 if (mc.GetExternalConstraints()) {
1744 auto &extConstrNode = nllNode["aux_distributions"];
1745 extConstrNode.set_seq();
1746 for (const auto &constr : *mc.GetExternalConstraints()) {
1747 extConstrNode.append_child() << constr->GetName();
1748 }
1749 }
1750
1751 auto writeList = [&](const char *name, RooArgSet const *args) {
1752 if (!args)
1753 return;
1754
1755 std::vector<std::string> names;
1756 names.reserve(args->size());
1757 for (RooAbsArg const *arg : *args)
1758 names.push_back(arg->GetName());
1759 std::sort(names.begin(), names.end());
1760 analysisNode[name].fill_seq(names);
1761 };
1762
1763 writeList("parameters_of_interest", mc.GetParametersOfInterest());
1764
1765 auto &modelConfigAux = getRooFitInternal(rootnode, "ModelConfigs", analysisName);
1766 modelConfigAux.set_map();
1767 modelConfigAux["pdfName"] << pdf->GetName();
1768 modelConfigAux["mcName"] << mc.GetName();
1769}
1770
1771/**
1772 * @brief Export all objects in the workspace to a JSONNode.
1773 *
1774 * This function exports all the objects in the workspace to the provided JSONNode.
1775 * The objects' information is added as key-value pairs to the JSONNode.
1776 *
1777 * @param n The JSONNode to which the objects will be exported.
1778 * @return void
1779 */
1781{
1782 _domains = std::make_unique<RooFit::JSONIO::Detail::Domains>();
1784 _rootnodeOutput = &n;
1785
1786 // export all toplevel pdfs
1787 std::vector<RooAbsPdf *> allpdfs;
1788 for (auto &arg : _workspace.allPdfs()) {
1789 if (!arg->hasClients()) {
1790 if (auto *pdf = dynamic_cast<RooAbsPdf *>(arg)) {
1791 allpdfs.push_back(pdf);
1792 }
1793 }
1794 }
1795 sortByName(allpdfs);
1796 std::set<std::string> exportedObjectNames;
1797 for (RooAbsPdf *p : allpdfs) {
1798 this->exportObject(*p, exportedObjectNames);
1799 }
1800
1801 // export attributes of all objects
1802 for (RooAbsArg *arg : _workspace.components()) {
1803 exportAttributes(arg, n);
1804 }
1805
1806 // export all datasets
1807 std::vector<RooAbsData *> alldata;
1808 for (auto &d : _workspace.allData()) {
1809 alldata.push_back(d);
1810 }
1811 sortByName(alldata);
1812 // first, take care of combined datasets
1813 std::vector<RooJSONFactoryWSTool::CombinedData> combData;
1814 for (auto &d : alldata) {
1815 auto data = this->exportCombinedData(*d);
1816 if (!data.components.empty())
1817 combData.push_back(data);
1818 }
1819 // next, take care of regular datasets
1820 for (auto &d : alldata) {
1821 this->exportData(*d);
1822 }
1823
1824 // export all ModelConfig objects and attached Pdfs
1825 for (TObject *obj : _workspace.allGenericObjects()) {
1826 if (auto mc = dynamic_cast<RooStats::ModelConfig *>(obj)) {
1827 exportModelConfig(n, *mc, combData);
1828 }
1829 }
1830
1831 for (auto *snsh : static_range_cast<RooArgSet const *>(_workspace.getSnapshots())) {
1832 RooArgSet snapshotSorted;
1833 // We only want to add the variables that actually got exported and skip
1834 // the ones that the pdfs encoded implicitly (like in the case of
1835 // HistFactory).
1836 for (RooAbsArg *arg : *snsh) {
1837 if (exportedObjectNames.find(arg->GetName()) != exportedObjectNames.end()) {
1838 bool do_export = false;
1839 for (const auto &pdf : allpdfs) {
1840 if (pdf->dependsOn(*arg)) {
1841 do_export = true;
1842 }
1843 }
1844 if (do_export && !::isValidName(arg->GetName())) {
1845 std::stringstream ss;
1846 ss << "RooJSONFactoryWSTool() variable '" << arg->GetName() << "' has an invalid name!" << std::endl;
1848 }
1849 if (do_export)
1850 snapshotSorted.add(*arg);
1851 }
1852 }
1853 snapshotSorted.sort();
1854 std::string name(snsh->GetName());
1855 if (name != "default_values") {
1856 this->exportVariables(snapshotSorted, appendNamedChild(n["parameter_points"], name)["parameters"]);
1857 }
1858 }
1859 _varsNode = nullptr;
1860 _domains->writeJSON(n["domains"]);
1861 _domains.reset();
1862 _rootnodeOutput = nullptr;
1863}
1864
1865/**
1866 * @brief Import the workspace from a JSON string.
1867 *
1868 * @param s The JSON string containing the workspace data.
1869 * @return bool Returns true on successful import, false otherwise.
1870 */
1872{
1873 std::stringstream ss(s);
1874 return importJSON(ss);
1875}
1876
1877/**
1878 * @brief Import the workspace from a YML string.
1879 *
1880 * @param s The YML string containing the workspace data.
1881 * @return bool Returns true on successful import, false otherwise.
1882 */
1884{
1885 std::stringstream ss(s);
1886 return importYML(ss);
1887}
1888
1889/**
1890 * @brief Export the workspace to a JSON string.
1891 *
1892 * @return std::string The JSON string representing the exported workspace.
1893 */
1895{
1896 std::stringstream ss;
1897 exportJSON(ss);
1898 return ss.str();
1899}
1900
1901/**
1902 * @brief Export the workspace to a YML string.
1903 *
1904 * @return std::string The YML string representing the exported workspace.
1905 */
1907{
1908 std::stringstream ss;
1909 exportYML(ss);
1910 return ss.str();
1911}
1912
1913/**
1914 * @brief Create a new JSON tree with version information.
1915 *
1916 * @return std::unique_ptr<JSONTree> A unique pointer to the created JSON tree.
1917 */
1919{
1920 std::unique_ptr<JSONTree> tree = JSONTree::create();
1921 JSONNode &n = tree->rootnode();
1922 n.set_map();
1923 auto &metadata = n["metadata"].set_map();
1924
1925 // add the mandatory hs3 version number
1926 metadata["hs3_version"] << hs3VersionTag;
1927
1928 // Add information about the ROOT version that was used to generate this file
1929 auto &rootInfo = appendNamedChild(metadata["packages"], "ROOT");
1930 std::string versionName = gROOT->GetVersion();
1931 // We want to consistently use dots such that the version name can be easily
1932 // digested automatically.
1933 std::replace(versionName.begin(), versionName.end(), '/', '.');
1934 rootInfo["version"] << versionName;
1935
1936 return tree;
1937}
1938
1939/**
1940 * @brief Export the workspace to JSON format and write to the output stream.
1941 *
1942 * @param os The output stream to write the JSON data to.
1943 * @return bool Returns true on successful export, false otherwise.
1944 */
1946{
1947 std::unique_ptr<JSONTree> tree = createNewJSONTree();
1948 JSONNode &n = tree->rootnode();
1949 this->exportAllObjects(n);
1950 n.writeJSON(os);
1951 return true;
1952}
1953
1954/**
1955 * @brief Export the workspace to JSON format and write to the specified file.
1956 *
1957 * @param filename The name of the JSON file to create and write the data to.
1958 * @return bool Returns true on successful export, false otherwise.
1959 */
1961{
1962 std::ofstream out(filename.c_str());
1963 if (!out.is_open()) {
1964 std::stringstream ss;
1965 ss << "RooJSONFactoryWSTool() invalid output file '" << filename << "'." << std::endl;
1967 return false;
1968 }
1969 return this->exportJSON(out);
1970}
1971
1972/**
1973 * @brief Export the workspace to YML format and write to the output stream.
1974 *
1975 * @param os The output stream to write the YML data to.
1976 * @return bool Returns true on successful export, false otherwise.
1977 */
1979{
1980 std::unique_ptr<JSONTree> tree = createNewJSONTree();
1981 JSONNode &n = tree->rootnode();
1982 this->exportAllObjects(n);
1983 n.writeYML(os);
1984 return true;
1985}
1986
1987/**
1988 * @brief Export the workspace to YML format and write to the specified file.
1989 *
1990 * @param filename The name of the YML file to create and write the data to.
1991 * @return bool Returns true on successful export, false otherwise.
1992 */
1994{
1995 std::ofstream out(filename.c_str());
1996 if (!out.is_open()) {
1997 std::stringstream ss;
1998 ss << "RooJSONFactoryWSTool() invalid output file '" << filename << "'." << std::endl;
2000 return false;
2001 }
2002 return this->exportYML(out);
2003}
2004
2005bool RooJSONFactoryWSTool::hasAttribute(const std::string &obj, const std::string &attrib)
2006{
2007 if (!_attributesNode)
2008 return false;
2009 if (auto attrNode = _attributesNode->find(obj)) {
2010 if (auto seq = attrNode->find("tags")) {
2011 for (auto &a : seq->children()) {
2012 if (a.val() == attrib)
2013 return true;
2014 }
2015 }
2016 }
2017 return false;
2018}
2019void RooJSONFactoryWSTool::setAttribute(const std::string &obj, const std::string &attrib)
2020{
2021 auto node = &RooJSONFactoryWSTool::getRooFitInternal(*_rootnodeOutput, "attributes").set_map()[obj].set_map();
2022 auto &tags = (*node)["tags"];
2023 tags.set_seq();
2024 tags.append_child() << attrib;
2025}
2026
2027std::string RooJSONFactoryWSTool::getStringAttribute(const std::string &obj, const std::string &attrib)
2028{
2029 if (!_attributesNode)
2030 return "";
2031 if (auto attrNode = _attributesNode->find(obj)) {
2032 if (auto dict = attrNode->find("dict")) {
2033 if (auto *a = dict->find(attrib)) {
2034 return a->val();
2035 }
2036 }
2037 }
2038 return "";
2039}
2040void RooJSONFactoryWSTool::setStringAttribute(const std::string &obj, const std::string &attrib,
2041 const std::string &value)
2042{
2043 auto node = &RooJSONFactoryWSTool::getRooFitInternal(*_rootnodeOutput, "attributes").set_map()[obj].set_map();
2044 auto &dict = (*node)["dict"];
2045 dict.set_map();
2046 dict[attrib] << value;
2047}
2048
2049/**
2050 * @brief Imports all nodes of the JSON data and adds them to the workspace.
2051 *
2052 * @param n The JSONNode representing the root node of the JSON data.
2053 * @return void
2054 */
2056{
2057 // Per HS3 standard, the hs3_version in the metadata is required. So we
2058 // error out if it is missing. TODO: now we are only checking if the
2059 // hs3_version tag exists, but in the future when the HS3 specification
2060 // versions are actually frozen, we should also check if the hs3_version is
2061 // one that RooFit can actually read.
2062 auto metadata = n.find("metadata");
2063 if (!metadata || !metadata->find("hs3_version")) {
2064 std::stringstream ss;
2065 ss << "The HS3 version is missing in the JSON!\n"
2066 << "Please include the HS3 version in the metadata field, e.g.:\n"
2067 << " \"metadata\" :\n"
2068 << " {\n"
2069 << " \"hs3_version\" : \"" << hs3VersionTag << "\"\n"
2070 << " }";
2071 error(ss.str());
2072 }
2073
2074 _domains = std::make_unique<RooFit::JSONIO::Detail::Domains>();
2075 if (auto domains = n.find("domains")) {
2076 _domains->readJSON(*domains);
2077 }
2078 _domains->populate(_workspace);
2079
2080 _rootnodeInput = &n;
2081
2082 _attributesNode = findRooFitInternal(*_rootnodeInput, "attributes");
2083
2084 this->importDependants(n);
2085
2086 if (auto paramPointsNode = n.find("parameter_points")) {
2087 for (const auto &snsh : paramPointsNode->children()) {
2088 std::string name = RooJSONFactoryWSTool::name(snsh);
2089
2090 if (!::isValidName(name)) {
2091 std::stringstream ss;
2092 ss << "RooJSONFactoryWSTool() node name '" << name << "' is not valid!" << std::endl;
2094 }
2095
2096 RooArgSet vars;
2097 for (const auto &var : snsh["parameters"].children()) {
2099 configureVariable(*_domains, var, *rrv);
2100 vars.add(*rrv);
2101 }
2102 }
2104 }
2105 }
2106
2107 combinePdfs(*_rootnodeInput, _workspace);
2108
2109 // Import attributes
2110 if (_attributesNode) {
2111 for (const auto &elem : _attributesNode->children()) {
2112 if (RooAbsArg *arg = _workspace.arg(elem.key()))
2113 importAttributes(arg, elem);
2114 }
2115 }
2116
2117 _attributesNode = nullptr;
2118
2119 // We delay the import of the data to after combineDatasets(), because it
2120 // might be that some datasets are merged to combined datasets there. In
2121 // that case, we will remove the components from the "datasets" vector so they
2122 // don't get imported.
2123 std::vector<std::unique_ptr<RooAbsData>> datasets;
2124 if (auto dataNode = n.find("data")) {
2125 for (const auto &p : dataNode->children()) {
2126 datasets.push_back(loadData(p, _workspace));
2127 }
2128 }
2129
2130 // Now, read in analyses and likelihoods if there are any
2131
2132 if (auto analysesNode = n.find("analyses")) {
2133 for (JSONNode const &analysisNode : analysesNode->children()) {
2134 importAnalysis(*_rootnodeInput, analysisNode, n["likelihoods"], _workspace, datasets);
2135 }
2136 }
2137
2138 combineDatasets(*_rootnodeInput, datasets);
2139
2140 for (auto const &d : datasets) {
2141 if (d)
2143 }
2144
2145 _rootnodeInput = nullptr;
2146 _domains.reset();
2147}
2148
2149/**
2150 * @brief Imports a JSON file from the given input stream to the workspace.
2151 *
2152 * @param is The input stream containing the JSON data.
2153 * @return bool Returns true on successful import, false otherwise.
2154 */
2156{
2157 // import a JSON file to the workspace
2158 std::unique_ptr<JSONTree> tree = JSONTree::create(is);
2159 this->importAllNodes(tree->rootnode());
2160 return true;
2161}
2162
2163/**
2164 * @brief Imports a JSON file from the given filename to the workspace.
2165 *
2166 * @param filename The name of the JSON file to import.
2167 * @return bool Returns true on successful import, false otherwise.
2168 */
2170{
2171 // import a JSON file to the workspace
2172 std::ifstream infile(filename.c_str());
2173 if (!infile.is_open()) {
2174 std::stringstream ss;
2175 ss << "RooJSONFactoryWSTool() invalid input file '" << filename << "'." << std::endl;
2177 return false;
2178 }
2179 return this->importJSON(infile);
2180}
2181
2182/**
2183 * @brief Imports a YML file from the given input stream to the workspace.
2184 *
2185 * @param is The input stream containing the YML data.
2186 * @return bool Returns true on successful import, false otherwise.
2187 */
2189{
2190 // import a YML file to the workspace
2191 std::unique_ptr<JSONTree> tree = JSONTree::create(is);
2192 this->importAllNodes(tree->rootnode());
2193 return true;
2194}
2195
2196/**
2197 * @brief Imports a YML file from the given filename to the workspace.
2198 *
2199 * @param filename The name of the YML file to import.
2200 * @return bool Returns true on successful import, false otherwise.
2201 */
2203{
2204 // import a YML file to the workspace
2205 std::ifstream infile(filename.c_str());
2206 if (!infile.is_open()) {
2207 std::stringstream ss;
2208 ss << "RooJSONFactoryWSTool() invalid input file '" << filename << "'." << std::endl;
2210 return false;
2211 }
2212 return this->importYML(infile);
2213}
2214
2215void RooJSONFactoryWSTool::importJSONElement(const std::string &name, const std::string &jsonString)
2216{
2217 std::unique_ptr<RooFit::Detail::JSONTree> tree = RooFit::Detail::JSONTree::create(jsonString);
2218 JSONNode &n = tree->rootnode();
2219 n["name"] << name;
2220
2221 bool isVariable = true;
2222 if (n.find("type")) {
2223 isVariable = false;
2224 }
2225
2226 if (isVariable) {
2227 this->importVariableElement(n);
2228 } else {
2229 this->importFunction(n, false);
2230 }
2231}
2232
2234{
2235 std::unique_ptr<RooFit::Detail::JSONTree> tree = varJSONString(elementNode);
2236 JSONNode &n = tree->rootnode();
2237 _domains = std::make_unique<RooFit::JSONIO::Detail::Domains>();
2238 if (auto domains = n.find("domains"))
2239 _domains->readJSON(*domains);
2240
2241 _rootnodeInput = &n;
2242 _attributesNode = findRooFitInternal(*_rootnodeInput, "attributes");
2243
2244 JSONNode const *varsNode = getVariablesNode(n);
2245 const auto &p = varsNode->child(0);
2247
2248 auto paramPointsNode = n.find("parameter_points");
2249 const auto &snsh = paramPointsNode->child(0);
2250 std::string name = RooJSONFactoryWSTool::name(snsh);
2251 RooArgSet vars;
2252 const auto &var = snsh["parameters"].child(0);
2254 configureVariable(*_domains, var, *rrv);
2255 vars.add(*rrv);
2256 }
2257
2258 // Import attributes
2259 if (_attributesNode) {
2260 for (const auto &elem : _attributesNode->children()) {
2261 if (RooAbsArg *arg = _workspace.arg(elem.key()))
2262 importAttributes(arg, elem);
2263 }
2264 }
2265
2266 _attributesNode = nullptr;
2267 _rootnodeInput = nullptr;
2268 _domains.reset();
2269}
2270
2271/**
2272 * @brief Writes a warning message to the RooFit message service.
2273 *
2274 * @param str The warning message to be logged.
2275 * @return std::ostream& A reference to the output stream.
2276 */
2277std::ostream &RooJSONFactoryWSTool::warning(std::string const &str)
2278{
2279 return RooMsgService::instance().log(nullptr, RooFit::MsgLevel::ERROR, RooFit::IO) << str << std::endl;
2280}
2281
2282/**
2283 * @brief Writes an error message to the RooFit message service and throws a runtime_error.
2284 *
2285 * @param s The error message to be logged and thrown.
2286 * @return void
2287 */
2289{
2290 RooMsgService::instance().log(nullptr, RooFit::MsgLevel::ERROR, RooFit::IO) << s << std::endl;
2291 throw std::runtime_error(s);
2292}
std::unique_ptr< RooFit::Detail::JSONTree > varJSONString(const JSONNode &treeRoot)
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
constexpr auto hs3VersionTag
#define oocoutW(o, a)
#define oocoutE(o, a)
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 filename
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
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 r
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 child
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 attr
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:110
#define gROOT
Definition TROOT.h:406
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
TIterator Use servers() and begin()
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
const std::set< std::string > & attributes() const
Definition RooAbsArg.h:339
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
const std::map< std::string, std::string > & stringAttributes() const
Definition RooAbsArg.h:347
Int_t numProxies() const
Return the number of registered proxies.
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
RooAbsProxy * getProxy(Int_t index) const
Return the nth proxy from the proxy list.
A space to attach TBranches.
std::size_t size() const
Number of states defined.
Abstract container object that can hold multiple RooAbsArg objects.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Storage_t::size_type size() const
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
void sort(bool reverse=false)
Sort collection using std::sort and name comparison.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:57
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
RooArgSet * getAllConstraints(const RooArgSet &observables, RooArgSet &constrainedParams, bool stripDisconnected=true, bool removeConstraintsFromPdf=false) const
This helper function finds and collects all constraints terms of all component p.d....
Abstract interface for proxy classes.
Definition RooAbsProxy.h:37
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
Abstract interface for RooAbsArg proxy classes.
Definition RooArgProxy.h:24
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:55
Implements a RooAbsBinning in terms of an array of boundary values, posing no constraints on the choi...
Definition RooBinning.h:27
bool addBoundary(double boundary)
Add bin boundary at given value.
Object to represent discrete states.
Definition RooCategory.h:28
bool defineType(const std::string &label)
Define a state with given name.
Represents a constant real-valued object.
Definition RooConstVar.h:23
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:39
virtual std::string val() const =0
void fill_seq(Collection const &coll)
virtual JSONNode & set_map()=0
virtual JSONNode & append_child()=0
virtual children_view children()
virtual size_t num_children() const =0
virtual JSONNode & child(size_t pos)=0
virtual JSONNode & set_seq()=0
virtual void writeJSON(std::ostream &os) const =0
virtual bool is_seq() const =0
virtual bool is_map() const =0
virtual std::string key() const =0
virtual double val_double() const
JSONNode const * find(std::string const &key) const
virtual int val_int() const
static std::unique_ptr< JSONTree > create()
void writeVariable(RooRealVar &) const
Definition Domains.cxx:43
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
When using RooFit, statistical models can be conveniently handled and stored as a RooWorkspace.
void importFunction(const RooFit::Detail::JSONNode &n, bool importAllDependants)
Import a function from the JSONNode into the workspace.
static constexpr bool useListsInsteadOfDicts
std::string getStringAttribute(const std::string &obj, const std::string &attrib)
bool importYML(std::string const &filename)
Imports a YML file from the given filename to the workspace.
static void fillSeq(RooFit::Detail::JSONNode &node, RooAbsCollection const &coll, size_t nMax=-1)
void exportCategory(RooAbsCategory const &cat, RooFit::Detail::JSONNode &node)
Export a RooAbsCategory object to a JSONNode.
T * requestArg(const RooFit::Detail::JSONNode &node, const std::string &key)
RooJSONFactoryWSTool(RooWorkspace &ws)
void importVariable(const RooFit::Detail::JSONNode &n)
Import a variable from the JSONNode into the workspace.
void exportData(RooAbsData const &data)
Export data from the workspace to a JSONNode.
bool hasAttribute(const std::string &obj, const std::string &attrib)
void exportVariables(const RooArgSet &allElems, RooFit::Detail::JSONNode &n)
Export variables from the workspace to a JSONNode.
bool importJSON(std::string const &filename)
Imports a JSON file from the given filename to the workspace.
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 RooFit::Detail::JSONNode & appendNamedChild(RooFit::Detail::JSONNode &node, std::string const &name)
RooAbsReal * importTransformed(const std::string &name, const std::string &tag, const std::string &operation_name, const std::string &formula)
std::string exportYMLtoString()
Export the workspace to a YML string.
static RooFit::Detail::JSONNode & getRooFitInternal(RooFit::Detail::JSONNode &node, Keys_t const &...keys)
static void exportArray(std::size_t n, double const *contents, RooFit::Detail::JSONNode &output)
Export an array of doubles to a JSONNode.
bool importYMLfromString(const std::string &s)
Import the workspace from a YML string.
RooFit::Detail::JSONNode * _rootnodeOutput
static void exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, RooFit::Detail::JSONNode &output)
Export histogram data to a JSONNode.
void exportSingleModelConfig(RooFit::Detail::JSONNode &rootnode, RooStats::ModelConfig const &mc, std::string const &analysisName, std::map< std::string, std::string > const *dataComponents)
static std::unique_ptr< RooFit::Detail::JSONTree > createNewJSONTree()
Create a new JSON tree with version information.
void exportVariable(const RooAbsArg *v, RooFit::Detail::JSONNode &n)
Export a variable from the workspace to a JSONNode.
const RooFit::Detail::JSONNode * _rootnodeInput
RooJSONFactoryWSTool::CombinedData exportCombinedData(RooAbsData const &data)
Export combined data from the workspace to a custom struct.
std::string exportJSONtoString()
Export the workspace to a JSON string.
RooArgList requestArgList(const RooFit::Detail::JSONNode &node, const std::string &seqName)
const RooFit::Detail::JSONNode * _attributesNode
void importDependants(const RooFit::Detail::JSONNode &n)
Import all dependants (servers) of a node into the workspace.
void importJSONElement(const std::string &name, const std::string &jsonString)
static void error(const char *s)
Writes an error message to the RooFit message service and throws a runtime_error.
void exportModelConfig(RooFit::Detail::JSONNode &rootnode, RooStats::ModelConfig const &mc, const std::vector< RooJSONFactoryWSTool::CombinedData > &d)
void setAttribute(const std::string &obj, const std::string &attrib)
bool exportYML(std::string const &fileName)
Export the workspace to YML format and write to the specified file.
std::string exportTransformed(const RooAbsReal *original, const std::string &tag, const std::string &operation_name, const std::string &formula)
bool importJSONfromString(const std::string &s)
Import the workspace from a JSON string.
RooFit::Detail::JSONNode * _varsNode
void exportObject(RooAbsArg const &func, std::set< std::string > &exportedObjectNames)
Export an object from the workspace to a JSONNode.
static RooFit::Detail::JSONNode & makeVariablesNode(RooFit::Detail::JSONNode &rootNode)
void importAllNodes(const RooFit::Detail::JSONNode &n)
Imports all nodes of the JSON data and adds them to the workspace.
static std::string name(const RooFit::Detail::JSONNode &n)
void exportAllObjects(RooFit::Detail::JSONNode &n)
Export all objects in the workspace to a JSONNode.
bool exportJSON(std::string const &fileName)
Export the workspace to JSON format and write to the specified file.
static RooFit::Detail::JSONNode const * findNamedChild(RooFit::Detail::JSONNode const &node, std::string const &name)
void setStringAttribute(const std::string &obj, const std::string &attrib, const std::string &value)
std::vector< RooAbsArg const * > _serversToExport
std::unique_ptr< RooFit::JSONIO::Detail::Domains > _domains
RooFit::Detail::JSONNode & createAdHoc(const std::string &toplevel, const std::string &name)
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.
void importVariableElement(const RooFit::Detail::JSONNode &n)
std::ostream & log(const RooAbsArg *self, RooFit::MsgLevel level, RooFit::MsgTopic facility, bool forceSkipPrefix=false)
Log error message associated with RooAbsArg object self at given level and topic.
static RooMsgService & instance()
Return reference to singleton instance.
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setVal(double value) override
Set value of variable to 'value'.
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
const RooAbsCategoryLValue & indexCat() const
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
Definition ModelConfig.h:35
const RooArgSet * GetParametersOfInterest() const
get RooArgSet containing the parameter of interest (return nullptr if not existing)
void SetWS(RooWorkspace &ws) override
Set a workspace that owns all the necessary components for the analysis.
const RooArgSet * GetExternalConstraints() const
get RooArgSet for global observables (return nullptr if not existing)
RooAbsPdf * GetPdf() const
get model PDF (return nullptr if pdf has not been specified or does not exist)
Persistable container for RooFit projects.
TObject * obj(RooStringView name) const
Return any type of object (RooAbsArg, RooAbsData or generic object) with given name)
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
bool saveSnapshot(RooStringView, const char *paramNames)
Save snapshot of values and attributes (including "Constant") of given parameters.
RooArgSet allPdfs() const
Return set with all probability density function objects.
std::list< RooAbsData * > allData() const
Return list of all dataset in the workspace.
RooLinkedList const & getSnapshots() const
std::list< TObject * > allGenericObjects() const
Return list of all generic objects in the workspace.
RooAbsReal * function(RooStringView name) const
Retrieve function (RooAbsReal) with given name. Note that all RooAbsPdfs are also RooAbsReals....
RooAbsArg * arg(RooStringView name) const
Return RooAbsArg with given name. A null pointer is returned if none is found.
bool import(const RooAbsArg &arg, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}, const RooCmdArg &arg9={})
Import a RooAbsArg object, e.g.
const RooArgSet & components() const
RooFactoryWSTool & factory()
Return instance to factory tool.
RooRealVar * var(RooStringView name) const
Retrieve real-valued variable (RooRealVar) with given name. A null pointer is returned if not found.
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:81
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
TClass * IsA() const override
Definition TNamed.h:58
Mother of all ROOT objects.
Definition TObject.h:41
const char * Data() const
Definition TString.h:376
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:2378
RooCmdArg RecycleConflictNodes(bool flag=true)
RooConstVar & RooConst(double val)
RooCmdArg Silence(bool flag=true)
RooCmdArg Index(RooCategory &icat)
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Import(const char *state, TH1 &histo)
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
Double_t ex[n]
Definition legend1.C:17
std::string makeValidVarName(std::string const &in)
ImportMap & importers()
Definition JSONIO.cxx:42
ExportMap & exporters()
Definition JSONIO.cxx:48
ImportExpressionMap & importExpressions()
Definition JSONIO.cxx:54
ExportKeysMap & exportKeys()
Definition JSONIO.cxx:61
std::map< std::string, std::string > components
TLine l
Definition textangle.C:4
static void output()