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