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