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 <RooRangeBinning.h>
20#include <RooAbsCategory.h>
21#include <RooAbsLValue.h>
22#include <RooCategory.h>
23#include <RooDataSet.h>
24#include <RooGaussian.h>
25#include <RooDataHist.h>
26#include <RooCustomizer.h>
27#include <RooProdPdf.h>
28#include <RooSimultaneous.h>
29#include <RooSuperCategory.h>
30#include <RooFit/ModelConfig.h>
31#include <RooAbsCollection.h>
32
33#include "JSONIOUtils.h"
34#include "HS3Builder.h"
35#include "JSONReadRecorder.h"
36
37#include <TROOT.h>
38
39#include <algorithm>
40#include <cmath>
41#include <cstring>
42#include <limits>
43#include <iterator>
44#include <fstream>
45#include <functional>
46#include <iostream>
47#include <numeric>
48#include <set>
49#include <sstream>
50#include <stdexcept>
51#include <unordered_map>
52
53/** \class RooJSONFactoryWSTool
54\ingroup roofit_dev_docs_hs3
55
56When using \ref Roofitmain, statistical models can be conveniently handled and
57stored as a RooWorkspace. However, for the sake of interoperability
58with other statistical frameworks, and also ease of manipulation, it
59may be useful to store statistical models in text form.
60
61The RooJSONFactoryWSTool is a helper class to achieve exactly this,
62exporting to and importing from JSON.
63
64In order to import a workspace from a JSON file, you can do
65
66~~~ {.py}
67ws = ROOT.RooWorkspace("ws")
68tool = ROOT.RooJSONFactoryWSTool(ws)
69tool.importJSON("myjson.json")
70~~~
71
72Similarly, in order to export a workspace to a JSON file, you can do
73
74~~~ {.py}
75tool = ROOT.RooJSONFactoryWSTool(ws)
76tool.exportJSON("myjson.json")
77~~~
78
79Analogously, in C++, you can do
80
81~~~ {.cxx}
82#include "RooFitHS3/RooJSONFactoryWSTool.h"
83// ...
84RooWorkspace ws("ws");
85RooJSONFactoryWSTool tool(ws);
86tool.importJSON("myjson.json");
87~~~
88
89and
90
91~~~ {.cxx}
92#include "RooFitHS3/RooJSONFactoryWSTool.h"
93// ...
94RooJSONFactoryWSTool tool(ws);
95tool.exportJSON("myjson.json");
96~~~
97
98For more details, consult the tutorial <a href="rf515__hfJSON_8py.html">rf515_hfJSON</a>.
99
100The RooJSONFactoryWSTool only knows about a limited set of classes for
101import and export. If import or export of a class you're interested in
102fails, you might need to add your own importer or exporter. Please
103consult the relevant section in the \ref roofit_dev_docs to learn how to do that (\ref roofit_dev_docs_hs3).
104
105You can always get a list of all the available importers and exporters by calling the following functions:
106~~~ {.py}
107ROOT.RooFit.JSONIO.printImporters()
108ROOT.RooFit.JSONIO.printExporters()
109~~~
110*/
111
112constexpr auto hs3VersionTag = "0.3";
113
117
118namespace HS3 = RooFit::HS3;
119
120/// What the tool needs to know about the document that it is importing.
122 explicit ToolImportState(HS3Document const &doc) : document{doc}
123 {
124 // Without these indices, every cross-reference resolved during import (e.g. dependencies of a
125 // PiecewiseInterpolation, or factory-expression arguments) would need a linear scan over all sibling objects,
126 // which becomes O(N^2) on workspaces with thousands of entries.
127 for (auto const &function : doc.functions) {
128 functions.emplace(function.name, &function);
129 }
130 for (auto const &distribution : doc.distributions) {
131 distributions.emplace(distribution.name, &distribution);
132 }
133 for (auto const &point : doc.parameterPoints) {
134 if (point.name == "default_values") {
135 defaultValues = &point;
136 for (auto const &p : point.parameters) {
137 defaultValuesByName.emplace(p.name, &p);
138 }
139 break;
140 }
141 }
142 }
143
145 /// The components of combined distributions that have data, and are read as such.
147 std::unordered_map<std::string, HS3::Function const *> functions;
148 std::unordered_map<std::string, HS3::Distribution const *> distributions;
150 std::unordered_map<std::string, HS3::ParameterValue const *> defaultValuesByName;
152 /// The components of array distributions created in this import, by name, with their canonical form (see
153 /// arrayComponentForm()).
154 std::map<std::string, std::string> arrayComponentForms;
155};
156
157/// The document that the tool is exporting.
160 JSONNode *root = nullptr;
161 /// The ranges and binnings of the exported variables, by domain and variable name.
162 std::map<std::string, std::map<std::string, HS3::DomainAxis>> domains;
163 /// The categories that are declared by categorical axes of the "default_domain", by name.
164 std::map<std::string, HS3::CategoricalAxis> categories;
165 /// Names of the objects written so far, to export each object once.
166 std::set<std::string> exportedObjectNames;
167 /// Array distributions to write at the end of the export: their components, and the array of each component.
168 std::map<std::string, std::vector<RooAbsPdf const *>> arrayComponents;
169 std::map<std::string, std::string> arrayOfComponent;
170 /// The name of the top-level object whose export is in progress, and the depth of the export recursion.
171 std::string rootName;
172 int depth = 0;
173 /// The constraint terms of the exported HistFactory channels, as written, and the data sets written for them.
174 std::map<std::string, std::vector<std::string>> constraintTermsOfPdf;
175 std::set<std::string> writtenConstraintData;
176 /// The labels that the constraint terms that are written as components of a combined distribution add to its
177 /// index category, by category. See exportSingleModelConfig().
178 std::map<std::string, std::vector<std::string>> auxiliaryLabels;
179 /// The observable of a constraint term, by the name of the term, see setConstraintObservable().
180 std::map<std::string, std::string> constraintObservables;
181 /// Set by the exporter of an object that is interpreted by the document.
182 std::optional<HistFactoryDist> typedObject;
183 std::vector<DistributionRef> channelConstraints;
184};
185
186std::string const *RooFit::HS3::importedArrayComponentForm(RooJSONFactoryWSTool &tool, std::string const &name)
187{
188 if (!tool._import) {
189 return nullptr;
190 }
191 auto found = tool._import->arrayComponentForms.find(name);
192 return found == tool._import->arrayComponentForms.end() ? nullptr : &found->second;
193}
194
195void RooFit::HS3::recordImportedArrayComponent(RooJSONFactoryWSTool &tool, std::string const &name, std::string form)
196{
197 if (tool._import) {
198 tool._import->arrayComponentForms[name] = std::move(form);
199 }
200}
201
203 std::vector<DistributionRef> channelConstraints)
204{
205 tool._export->typedObject = std::move(dist);
206 tool._export->channelConstraints = std::move(channelConstraints);
207}
208
209namespace {
210
211// Append a name to a list that has every name once.
212void addUnique(std::vector<std::string> &names, std::string const &name)
213{
214 if (std::find(names.begin(), names.end(), name) == names.end()) {
215 names.push_back(name);
216 }
217}
218
219template <class Coll_t>
220std::vector<std::string> namesOf(Coll_t const &objects)
221{
222 std::vector<std::string> names;
223 for (auto const *object : objects) {
224 names.push_back(object->GetName());
225 }
226 return names;
227}
228
229// Whether the states of a category have these labels, in any order.
230bool hasLabels(RooCategory const &cat, std::vector<std::string> const &labels)
231{
232 std::set<std::string> states;
233 for (auto const &state : cat) {
234 states.insert(state.first);
235 }
236 return states == std::set<std::string>(labels.begin(), labels.end());
237}
238
239HS3::Binning toBinning(RooAbsBinning const &binning)
240{
241 if (binning.isUniform()) {
242 return HS3::RegularBinning{binning.numBins()};
243 }
244 HS3::EdgesBinning edges;
245 edges.edges.push_back(binning.binLow(0));
246 for (int i = 0; i < binning.numBins(); ++i) {
247 edges.edges.push_back(binning.binHigh(i));
248 }
249 return edges;
250}
251
252constexpr double inf = std::numeric_limits<double>::infinity();
253constexpr int isInfinite(double x)
254{
255 return (x >= +inf) ? +1 : ((x <= -inf) ? -1 : 0);
256}
257
258// The axis of a domain for a range and binning. Infinite bounds are omitted, and only a bounded range has a binning.
259// A RooRangeBinning is a plain named range without bin structure, fully described by its bounds.
260HS3::DomainAxis toDomainAxis(std::string const &name, RooAbsBinning const &binning)
261{
262 HS3::DomainAxis axis;
263 axis.name = name;
264 if (!isInfinite(binning.lowBound())) {
265 axis.min = binning.lowBound();
266 }
267 if (!isInfinite(binning.highBound())) {
268 axis.max = binning.highBound();
269 }
270 const bool hasBins = binning.numBins() > 0 && !dynamic_cast<RooRangeBinning const *>(&binning);
271 if (axis.min && axis.max && hasBins) {
272 axis.binning = toBinning(binning);
273 }
274 return axis;
275}
276
277// Record the range and binning of a variable in the "default_domain", and its named ranges in the domains of their
278// names.
279void recordDomains(std::map<std::string, std::map<std::string, HS3::DomainAxis>> &domains, RooRealVar const &var)
280{
281 domains[HS3::defaultDomainName][var.GetName()] = toDomainAxis(var.GetName(), var.getBinning());
282 for (auto const &name : var.getBinningNames()) {
283 if (!name.empty()) {
284 domains[name][var.GetName()] = toDomainAxis(var.GetName(), var.getBinning(name.c_str()));
285 }
286 }
287}
288
289// Append a domain with the axes in the order of their names, continuous and categorical ones mixed.
290void appendDomain(std::vector<HS3::Domain> &domains, std::string const &name,
291 std::map<std::string, HS3::DomainAxis> axes,
292 std::map<std::string, HS3::CategoricalAxis> categories = {})
293{
294 std::map<std::string, std::variant<HS3::DomainAxis, HS3::CategoricalAxis>> sorted;
295 for (auto &item : axes) {
296 sorted.emplace(item.first, std::move(item.second));
297 }
298 for (auto &item : categories) {
299 sorted.emplace(item.first, std::move(item.second));
300 }
301 HS3::Domain &domain = domains.emplace_back();
302 domain.name = name;
303 for (auto &item : sorted) {
304 domain.axes.emplace_back(std::move(item.second));
305 }
306}
307
308// Set the binning of a variable, or the binning of one of its named ranges.
309void applyBinning(RooRealVar &var, HS3::Binning const &binning, const char *name = nullptr)
310{
311 if (auto const *edges = std::get_if<HS3::EdgesBinning>(&binning)) {
312 if (edges->edges.empty()) {
313 return;
314 }
315 RooBinning bins(edges->edges.front(), edges->edges.back());
316 for (double edge : edges->edges) {
317 bins.addBoundary(edge);
318 }
319 var.setBinning(bins, name);
320 } else if (int nbins = std::get<HS3::RegularBinning>(binning).nbins) {
321 var.setBins(nbins, name);
322 }
323}
324
325void applyRange(RooRealVar &var, HS3::DomainAxis const &axis)
326{
327 if (axis.min) {
328 if (isInfinite(*axis.min)) {
329 var.removeMin();
330 } else {
331 var.setMin(*axis.min);
332 }
333 }
334 if (axis.max) {
335 if (isInfinite(*axis.max)) {
336 var.removeMax();
337 } else {
338 var.setMax(*axis.max);
339 }
340 }
341 if (axis.binning) {
342 applyBinning(var, *axis.binning);
343 }
344}
345
346// Create the variables of the domains that don't exist yet, and the domains other than the "default_domain" as named
347// ranges.
348void createVariables(RooWorkspace &ws, std::vector<HS3::Domain> const &domains, HS3::DomainRanges const &ranges)
349{
350 auto forEachAxis = [&](auto &&fn) {
351 for (HS3::Domain const &domain : domains) {
352 for (auto const &axis : domain.axes) {
353 if (auto const *continuous = std::get_if<HS3::DomainAxis>(&axis)) {
354 fn(domain.name, *continuous);
355 }
356 }
357 }
358 };
359 // Parameters with a single value are RooConstVars, whichever domain gives the value.
360 forEachAxis([&](std::string const &, HS3::DomainAxis const &axis) {
361 if (axis.fixedValue && !ws.arg(axis.name)) {
362 ws.import(RooConstVar{axis.name.c_str(), axis.name.c_str(), *axis.fixedValue}, RooFit::Silence());
363 }
364 });
365 forEachAxis([&](std::string const &, HS3::DomainAxis const &axis) {
366 if (!axis.fixedValue && ranges.find(axis.name) == &axis && !ws.arg(axis.name)) {
367 RooRealVar var{axis.name.c_str(), axis.name.c_str(), axis.min.value_or(-inf), axis.max.value_or(inf)};
368 if (axis.binning) {
369 applyBinning(var, *axis.binning);
370 }
371 ws.import(var, RooFit::Silence());
372 }
373 });
374 // A categorical axis is a RooCategory with one state per category, in the order of the document and with the
375 // position as index, so that the bins of a RooDataHist follow the order of "categories". An existing RooCategory of
376 // that name must have the same labels. That all domains agree on the categories is checked by the validation.
377 for (HS3::Domain const &domain : domains) {
378 for (auto const &axisVariant : domain.axes) {
379 auto const *axis = std::get_if<HS3::CategoricalAxis>(&axisVariant);
380 if (!axis) {
381 continue;
382 }
383 if (RooAbsArg *existing = ws.arg(axis->name)) {
384 auto *cat = dynamic_cast<RooCategory *>(existing);
385 if (!cat) {
386 RooJSONFactoryWSTool::error("the axis '" + axis->name + "' is categorical, but '" + axis->name +
387 "' already exists and is not a category");
388 }
389 if (!hasLabels(*cat, axis->categories)) {
390 RooJSONFactoryWSTool::error("the categories of the axis '" + axis->name +
391 "' differ from the states of the existing category '" + axis->name + "'");
392 }
393 continue;
394 }
395 RooCategory cat{axis->name.c_str(), axis->name.c_str()};
396 for (std::size_t i = 0; i < axis->categories.size(); ++i) {
397 cat.defineType(axis->categories[i], static_cast<int>(i));
398 }
399 ws.import(cat, RooFit::Silence());
400 }
401 }
402 forEachAxis([&](std::string const &domain, HS3::DomainAxis const &axis) {
403 RooRealVar *var = ws.var(axis.name);
404 if (var && domain != HS3::defaultDomainName) {
405 var->setRange(domain.c_str(), axis.min.value_or(-inf), axis.max.value_or(inf));
406 if (axis.binning) {
407 applyBinning(*var, *axis.binning, domain.c_str());
408 }
409 }
410 });
411}
412
413} // namespace
414
415namespace {
416
417// Ends an import or an export: its state must not survive it, not even if there is an exception. The state of an
418// import refers to the document.
419template <class State_t>
420struct StateScope {
421 std::unique_ptr<State_t> &state;
422 ~StateScope() { state.reset(); }
423};
424
425// Keeps track of the objects that are being imported. Objects that depend on each other would otherwise recurse until
426// the stack overflows.
427class ImportGuard {
428public:
429 ImportGuard(std::vector<std::string> &stack, std::string const &name) : _stack{stack}
430 {
431 if (std::find(_stack.begin(), _stack.end(), name) != _stack.end()) {
432 std::string chain;
433 for (std::string const &ancestor : _stack) {
434 chain += ancestor + " -> ";
435 }
436 RooJSONFactoryWSTool::error("circular dependency in the document: " + chain + name);
437 }
438 _stack.push_back(name);
439 }
440 ~ImportGuard() { _stack.pop_back(); }
441
442private:
443 std::vector<std::string> &_stack;
444};
445
446} // namespace
447
448void RooFit::HS3::report(Diagnostics const &diagnostics, std::string const &object)
449{
450 std::string errors;
451 for (Diagnostic const &diagnostic : diagnostics) {
452 // A path starts with the name of a component, or with the index of an entry if the object is an array.
453 const bool needsDot = !object.empty() && !diagnostic.path.empty() && diagnostic.path.front() != '[';
454 const std::string path = object + (needsDot ? "." : "") + diagnostic.path;
455 const std::string text = path.empty() ? diagnostic.message : path + ": " + diagnostic.message;
456 if (diagnostic.severity == Diagnostic::Severity::Error) {
457 errors += (errors.empty() ? "" : "\n") + text;
458 } else {
459 RooJSONFactoryWSTool::warning("RooFitHS3: " + text);
460 }
461 }
462 if (!errors.empty()) {
464 }
465}
466
467namespace {
468
469// Configure `v` (value, error, binning, constness) from the parameter `p`.
470void configureVariable(HS3::DomainRanges const &ranges, HS3::ParameterValue const &p, RooRealVar &v)
471{
472 if (p.value) {
473 if (auto const *value = std::get_if<double>(&*p.value)) {
474 v.setVal(*value);
475 }
476 }
477 if (HS3::DomainAxis const *range = ranges.find(v.GetName())) {
478 applyRange(v, *range);
479 }
480 if (p.nbins)
481 v.setBins(*p.nbins);
482 if (p.relError)
483 v.setError(v.getVal() * *p.relError);
484 if (p.error)
485 v.setError(*p.error);
486 v.setConstant(p.isConst);
487}
488
489std::string genPrefix(const JSONNode &p, bool trailing_underscore)
490{
491 std::string prefix;
492 if (!p.is_map())
493 return prefix;
494 if (auto node = p.find("namespaces")) {
495 for (const auto &ns : node->children()) {
496 if (!prefix.empty())
497 prefix += "_";
498 prefix += ns.val();
499 }
500 }
501 if (trailing_underscore && !prefix.empty())
502 prefix += "_";
503 return prefix;
504}
505
506// Import string attributes ("dict") and boolean tags ("tags") onto `arg`.
507void importAttributes(RooAbsArg *arg, HS3::Attributes const &attributes)
508{
509 for (auto const &attr : attributes.dict) {
510 arg->setStringAttribute(attr.first.c_str(), attr.second.c_str());
511 }
512 for (auto const &tag : attributes.tags) {
513 arg->setAttribute(tag.c_str());
514 }
515}
516
517// The step widths of the minimization are the errors of the parameters of the ModelConfigs, and of the parameters of
518// the top-level pdfs given the data sets. The observables are no parameters.
519void exportParameterStepWidths(RooWorkspace const &workspace, std::vector<RooAbsPdf *> const &pdfs,
520 std::vector<RooAbsData *> const &data, std::vector<HS3::StepWidth> &out)
521{
522 RooArgSet candidates;
523 RooArgSet excluded;
524 auto addIfPresent = [](RooArgSet &set, RooArgSet const *args) {
525 if (args) {
526 set.add(*args, true);
527 }
528 };
529 for (TObject *obj : workspace.allGenericObjects()) {
530 if (auto const *mc = dynamic_cast<RooFit::ModelConfig const *>(obj)) {
531 addIfPresent(candidates, mc->GetParametersOfInterest());
532 addIfPresent(candidates, mc->GetNuisanceParameters());
533 addIfPresent(excluded, mc->GetObservables());
534 addIfPresent(excluded, mc->GetGlobalObservables());
535 addIfPresent(excluded, mc->GetConditionalObservables());
536 }
537 }
538 for (RooAbsPdf const *pdf : pdfs) {
539 RooArgSet observables;
540 for (RooAbsData const *dataset : data) {
541 std::unique_ptr<RooArgSet> pdfObs{pdf->getObservables(*dataset->get())};
542 observables.add(*pdfObs, true);
543 }
544 if (!observables.empty()) {
545 RooArgSet params;
546 pdf->getParameters(&observables, params);
547 candidates.add(params, true);
548 excluded.add(observables, true);
549 }
550 }
551 candidates.sort();
552 for (RooAbsArg *arg : candidates) {
553 auto *var = dynamic_cast<RooRealVar *>(arg);
554 if (var && var->hasError() && !excluded.find(*arg)) {
555 out.push_back({var->GetName(), var->getError()});
556 }
557 }
558}
559
560void importParameterStepWidths(RooWorkspace &workspace, HS3Document const &doc)
561{
562 for (HS3::StepWidth const &stepWidth : doc.rooFit.stepWidths) {
563 auto *var = dynamic_cast<RooRealVar *>(workspace.arg(stepWidth.name));
564 if (!var) {
565 RooJSONFactoryWSTool::warning("RooFitHS3: skipping parameter_stepwidths entry for unknown or non-real "
566 "variable '" +
567 stepWidth.name + "'.");
568 continue;
569 }
570 var->setError(stepWidth.width);
571 }
572}
573
574// Check that the terms of the likelihoods have distinct variates (see HS3::sharedVariates()) and list the constraints
575// of their HistFactory modifiers (see HS3::unlistedConstraints()). Documents of versions before 0.3, which RooFit
576// wrote with shared variates itself, are read with a warning. Returns the bookkeeping columns, which may be shared.
577std::set<std::string> checkVariates(HS3Document const &doc)
578{
579 const bool isLegacy = doc.metadata.version < HS3::Version{0, 3};
580 std::set<std::string> bookkeepingColumns;
581 for (auto const &[dataset, columns] : HS3::bookkeepingColumns(doc)) {
582 for (std::string const &column : columns) {
584 "RooFitHS3: the axis '" + column + "' of the components of the combined data set '" + dataset +
585 "' is declared as a bookkeeping column without statistical meaning (misc.ROOT_internal."
586 "bookkeeping_columns), so it may be shared by the components, although HS3 requires distinct axes.");
587 bookkeepingColumns.insert(column);
588 }
589 }
590 // The constraints named by HistFactory modifiers, and distinct variates. A document can violate both, e.g. with a
591 // constraint that is listed twice, so all violations are reported together.
592 std::vector<std::string> violations;
593 std::vector<std::string> notes;
594 if (!isLegacy) {
595 for (std::string const &message : HS3::unlistedConstraints(doc, &notes)) {
596 violations.push_back("invalid HS3: " + message +
597 ". The \"constraints\" of a modifier add no term to the likelihood, which has to list "
598 "them.");
599 }
600 }
601 for (std::string const &message : HS3::sharedVariates(doc)) {
602 if (!isLegacy) {
603 violations.push_back(
604 "invalid HS3: " + message +
605 ". The terms of a likelihood and the components of a combined distribution or data set must have distinct "
606 "variates, apart from identical factors within a combined distribution. Distributions that share factors, "
607 "e.g. the models of a combination with common constraint terms, are joined in a combined distribution, "
608 "which the likelihood lists as one term.");
609 continue;
610 }
611 RooJSONFactoryWSTool::warning("RooFitHS3: " + message +
612 ". HS3 0.3 requires distinct variates; the document is read anyway, since it "
613 "declares an older version.");
614 }
615 if (!violations.empty()) {
616 std::string all;
617 for (std::string const &violation : violations) {
618 all += (all.empty() ? "" : "\n") + violation;
619 }
621 }
622 for (std::string const &note : notes) {
623 RooJSONFactoryWSTool::warning("RooFitHS3: " + note + ".");
624 }
625 return bookkeepingColumns;
626}
627
628// Declare the bookkeeping columns of the exported document (see HS3::bookkeepingColumns()): the axes that several
629// components of a combined data set share, and whose variable in the workspace `ws` is used by nothing else, i.e. has
630// no clients and is in no set of a ModelConfig. RooAbsData::split() keeps such a column (e.g. an event number) in
631// every sub-data set.
632void declareBookkeepingColumns(HS3Document &doc, RooWorkspace const &ws)
633{
634 std::vector<RooArgSet const *> modelConfigSets;
635 for (TObject *obj : ws.allGenericObjects()) {
636 if (auto *mc = dynamic_cast<RooFit::ModelConfig *>(obj)) {
637 for (RooArgSet const *set : {mc->GetObservables(), mc->GetParametersOfInterest(), mc->GetNuisanceParameters(),
638 mc->GetGlobalObservables(), mc->GetConditionalObservables()}) {
639 if (set) {
640 modelConfigSets.push_back(set);
641 }
642 }
643 }
644 }
645 auto usedByNothing = [&](std::string const &name) {
646 RooAbsArg const *arg = ws.arg(name.c_str());
647 if (!arg || !arg->clients().empty()) {
648 return false;
649 }
650 return std::none_of(modelConfigSets.begin(), modelConfigSets.end(),
651 [&](RooArgSet const *set) { return set->find(name.c_str()) != nullptr; });
652 };
653 for (auto const &[dataset, axes] : HS3::sharedAxes(doc)) {
654 for (std::string const &axis : axes) {
655 if (usedByNothing(axis)) {
656 doc.rooFit.bookkeepingColumns[dataset].push_back(axis);
657 }
658 }
659 }
660}
661
662// Export the string attributes and tags of `arg` into the ROOT-internal attributes.
663void exportAttributes(const RooAbsArg *arg, std::map<std::string, HS3::Attributes> &attributes)
664{
665 // If this RooConst is a literal number, we don't need to export the attributes.
666 if (isLiteralConstVar(*arg) || dynamic_cast<RooConstVar const *>(arg)) {
667 return;
668 }
669
670 HS3::Attributes *out = nullptr;
671 auto initialize = [&]() {
672 if (!out) {
673 out = &attributes[arg->GetName()];
674 }
675 };
676
677 for (const auto &it : arg->stringAttributes()) {
678 // Skip some RooFit internals
679 if (it.first == "factory_tag" || it.first == "PROD_TERM_TYPE")
680 continue;
681 initialize();
682 out->dict[it.first] = it.second;
683 }
684 for (auto const &attr : arg->attributes()) {
685 // Skip some RooFit internals. The array distribution tag is restored from the type on import.
686 if (attr == "SnapShot_ExtRefClone" || attr == "RooRealConstant_Factory_Object" || attr == arrayDistTag ||
688 continue;
689 initialize();
690 out->tags.push_back(attr);
691 }
692}
693
694} // namespace
695
701
703{
704 return {name, binning.lowBound(), binning.highBound(), toBinning(binning)};
705}
706
708{
709 if (isLiteralConstVar(arg)) {
710 return static_cast<RooConstVar const &>(arg).getVal();
711 }
712 return std::string{arg.GetName()};
713}
714
715namespace {
716
717// The axis of unbinned or point data for a variable. Infinite bounds are left out: the axis is unbounded there.
718HS3::ContinuousAxis toContinuousAxis(RooRealVar const &var)
719{
722 axis.name = var.GetName();
723 if (!RooNumber::isInfinite(var.getMin())) {
724 axis.min = var.getMin();
725 }
726 if (!RooNumber::isInfinite(var.getMax())) {
727 axis.max = var.getMax();
728 }
729 return axis;
730}
731
732// A categorical axis has the labels in the order of the states of the category, which is the order of the bins of a
733// RooDataHist.
734HS3::CategoricalAxis toCategoricalAxis(RooAbsCategory const &cat)
735{
737 axis.name = cat.GetName();
738 for (unsigned int i = 0; i < cat.size(); ++i) {
739 axis.categories.push_back(cat.getOrdinal(i).first);
740 }
741 return axis;
742}
743
744// Binned data over variables that are RooRealVars or RooCategories.
745HS3::BinnedData toBinnedData(RooArgSet const &vars, std::size_t n, double const *contents)
746{
748 for (RooAbsArg const *var : vars) {
749 if (auto const *cat = dynamic_cast<RooCategory const *>(var)) {
751 data.axes.emplace_back(toCategoricalAxis(*cat));
752 } else {
753 data.axes.emplace_back(HS3::toBinnedAxis(static_cast<RooRealVar const &>(*var)));
754 }
755 }
756 data.contents.assign(contents, contents + n);
757 return data;
758}
759
760std::unique_ptr<RooRealVar> createObservable(HS3::BinnedAxis const &axis)
761{
762 auto obs = std::make_unique<RooRealVar>(axis.name.c_str(), axis.name.c_str(), axis.min, axis.max);
763 applyBinning(*obs, axis.binning);
764 return obs;
765}
766
767// Create the variables for the axes of binned data. A categorical axis is one bin per category. HS3 identifies
768// categories by name, so the data may list them in another order than the domain that declares the category.
769// RooDataHist looks up the bin of a category by the order of the states of the category it is given, so the category
770// of the data takes over the states and their order from the category of the workspace. `binOrder` is filled with the
771// position in the document of each bin in RooFit's order (last axis fastest), or left empty if the orders agree.
772RooArgSet createBinnedObservables(std::vector<std::variant<HS3::BinnedAxis, HS3::CategoricalAxis>> const &axes,
773 RooWorkspace const &workspace, std::string const &dataName,
774 std::vector<std::size_t> &binOrder)
775{
776 RooArgSet vars;
777 std::vector<std::vector<std::size_t>> axisPositions;
778 bool reordered = false;
779 for (auto const &axisVariant : axes) {
780 if (auto const *axis = std::get_if<HS3::BinnedAxis>(&axisVariant)) {
781 auto obs = createObservable(*axis);
782 std::vector<std::size_t> positions(obs->numBins());
783 std::iota(positions.begin(), positions.end(), 0);
784 axisPositions.push_back(std::move(positions));
785 vars.addOwned(std::move(obs));
786 continue;
787 }
788 auto const &axis = std::get<HS3::CategoricalAxis>(axisVariant);
789 auto cat = std::make_unique<RooCategory>(axis.name.c_str(), axis.name.c_str());
790 if (RooCategory const *wsCat = workspace.cat(axis.name)) {
791 if (!hasLabels(*wsCat, axis.categories)) {
792 RooJSONFactoryWSTool::error("the categories of the axis '" + axis.name + "' of the dataset '" + dataName +
793 "' differ from those of the category '" + axis.name + "'");
794 }
795 for (unsigned int i = 0; i < wsCat->size(); ++i) {
796 auto const &state = wsCat->getOrdinal(i);
797 cat->defineType(state.first, state.second);
798 }
799 } else {
800 for (std::size_t i = 0; i < axis.categories.size(); ++i) {
801 cat->defineType(axis.categories[i], static_cast<int>(i));
802 }
803 }
804 std::vector<std::size_t> positions(axis.categories.size());
805 for (std::size_t i = 0; i < positions.size(); ++i) {
806 auto found = std::find(axis.categories.begin(), axis.categories.end(), cat->getOrdinal(i).first);
807 positions[i] = std::distance(axis.categories.begin(), found);
808 reordered |= positions[i] != i;
809 }
810 axisPositions.push_back(std::move(positions));
811 vars.addOwned(std::move(cat));
812 }
813 binOrder.clear();
814 if (!reordered) {
815 return vars;
816 }
817 std::size_t total = 1;
818 for (auto const &positions : axisPositions) {
819 total *= positions.size();
820 }
821 binOrder.resize(total);
822 for (std::size_t k = 0; k < total; ++k) {
823 // Decompose RooFit's bin index (last axis fastest) and recompose it with the positions in the document.
824 std::size_t rest = k;
825 std::size_t docIndex = 0;
826 std::size_t stride = 1;
827 for (std::size_t j = axisPositions.size(); j-- > 0;) {
828 const std::size_t nBins = axisPositions[j].size();
829 docIndex += axisPositions[j][rest % nBins] * stride;
830 rest /= nBins;
831 stride *= nBins;
832 }
833 binOrder[k] = docIndex;
834 }
835 return vars;
836}
837
838// The values in RooFit's bin order, from the order of the document (see createBinnedObservables()).
839std::vector<double> permute(std::vector<double> const &values, std::vector<std::size_t> const &order)
840{
841 if (order.empty() || values.size() != order.size()) {
842 return values;
843 }
844 std::vector<double> out(values.size());
845 for (std::size_t k = 0; k < order.size(); ++k) {
846 out[k] = values[order[k]];
847 }
848 return out;
849}
850
851// Make the range of an observable of unbinned data consistent with the "min" and "max" of the axis. Variables that
852// didn't get their range from a domain take it from the axis. If `ranges` is null, all ranges are considered explicit.
853void applyUnbinnedAxisRange(HS3::ContinuousAxis const &axis, std::string const &dataName, RooRealVar &var,
854 HS3::DomainRanges const *ranges)
855{
856 // An absent bound means that the axis is unbounded on that side.
857 const double min = axis.min.value_or(-RooNumber::infinity());
858 const double max = axis.max.value_or(RooNumber::infinity());
859 if (ranges && !ranges->contains(axis.name)) {
860 var.setRange(min, max);
861 } else if (var.getMin() != min || var.getMax() != max) {
862 std::stringstream ss;
863 ss << "RooFitHS3: the range [" << min << ", " << max << "] of the axis '" << axis.name << "' of the dataset '"
864 << dataName << "' differs from the range [" << var.getMin() << ", " << var.getMax() << "] of the variable.";
866 }
867}
868
869std::unique_ptr<RooAbsData> createUnbinnedData(std::string const &name, HS3::UnbinnedData const &input,
870 RooWorkspace &workspace, HS3::DomainRanges const *ranges)
871{
872 RooArgList varlist;
873 for (auto const &axisVariant : input.axes) {
874 auto const *axis = std::get_if<HS3::ContinuousAxis>(&axisVariant);
875 if (!axis) {
876 // The category of a categorical axis is declared by a domain.
877 auto const &catAxis = std::get<HS3::CategoricalAxis>(axisVariant);
878 RooCategory *cat = workspace.cat(catAxis.name);
879 if (!cat) {
880 RooJSONFactoryWSTool::error("The categorical observable \"" + catAxis.name +
881 "\" could not be found in the workspace! Categorical observables are "
882 "declared by a categorical axis in a domain.");
883 }
884 if (!hasLabels(*cat, catAxis.categories)) {
885 RooJSONFactoryWSTool::error("The categories of the axis \"" + catAxis.name +
886 "\" differ from the states of the category \"" + catAxis.name + "\"");
887 }
888 varlist.add(*cat);
889 continue;
890 }
891 RooRealVar *var = workspace.var(axis->name);
892 if (!var) {
893 RooJSONFactoryWSTool::error("The observable \"" + axis->name + "\" could not be found in the workspace!");
894 }
895 varlist.add(*var);
896 applyUnbinnedAxisRange(*axis, name, *var, ranges);
897 }
898 RooArgSet vars(varlist);
899 auto data = std::make_unique<RooDataSet>(name, name, vars, RooFit::WeightVar());
900 const std::size_t nAxes = input.axes.size();
901 for (std::size_t i = 0; i < input.numEntries(); ++i) {
902 for (std::size_t j = 0; j < nAxes; ++j) {
903 const double value = input.entries[i * nAxes + j];
904 if (auto const *catAxis = std::get_if<HS3::CategoricalAxis>(&input.axes[j])) {
905 // The entry of a categorical axis is the position of the label in its "categories".
906 static_cast<RooCategory *>(varlist.at(j))->setLabel(catAxis->categories[static_cast<std::size_t>(value)]);
907 } else {
908 static_cast<RooRealVar *>(varlist.at(j))->setVal(value);
909 }
910 }
911 data->add(vars, input.weights ? (*input.weights)[i] : 1.);
912 }
913 return data;
914}
915
916// Create a RooAbsData (binned or unbinned) from its description.
917std::unique_ptr<RooAbsData> loadData(HS3::Data const &input, RooWorkspace &workspace, HS3::DomainRanges const *ranges)
918{
920
921 // What RooFit can't store is reported, instead of being dropped silently.
922 if (auto const *binned = std::get_if<HS3::BinnedData>(&input.body)) {
923 if (binned->uncertainty && !binned->uncertainty->correlation.empty()) {
924 RooJSONFactoryWSTool::warning("RooFitHS3: the correlations of the uncertainties of the dataset '" +
925 input.name + "' are ignored, because RooDataHist can't store them.");
926 }
927 std::vector<std::size_t> binOrder;
928 RooArgSet vars = createBinnedObservables(binned->axes, workspace, input.name, binOrder);
929 std::vector<double> sigma;
930 if (binned->uncertainty) {
931 sigma = permute(binned->uncertainty->sigma, binOrder);
932 }
933 return HS3::createDataHist(input.name, vars, permute(binned->contents, binOrder),
934 binned->uncertainty ? &sigma : nullptr);
935 }
936 if (auto const *unbinned = std::get_if<HS3::UnbinnedData>(&input.body)) {
937 if (unbinned->hasEntriesUncertainties) {
938 RooJSONFactoryWSTool::warning("RooFitHS3: the \"entries_uncertainties\" of the dataset '" + input.name +
939 "' are ignored, because RooDataSet can't store them.");
940 }
941 return createUnbinnedData(input.name, *unbinned, workspace, ranges);
942 }
943 // Point data is the observation of a single variable. With its axis, it is the same as unbinned data with a single
944 // entry, and becomes a RooDataSet with one entry.
945 auto const &point = std::get<HS3::PointData>(input.body);
946 if (point.uncertainty) {
947 RooJSONFactoryWSTool::warning("RooFitHS3: the \"uncertainty\" of the dataset '" + input.name +
948 "' is ignored: HS3 doesn't define how it enters a likelihood.");
949 }
950 // Without an axis, the value is the one of the single variate of the paired distribution, see
951 // HS3::resolvePointData().
952 if (point.axes.empty()) {
953 RooJSONFactoryWSTool::error("the point data set '" + input.name +
954 "' has no axis, and it is not paired with a distribution that has a single variate");
955 } else if (point.axes.size() != 1) {
956 RooJSONFactoryWSTool::error("the point data set '" + input.name + "' must have exactly one axis");
957 }
959 unbinned.axes.emplace_back(point.axes.front());
960 unbinned.entries.push_back(point.value);
961 return createUnbinnedData(input.name, unbinned, workspace, ranges);
962}
963
964// The version of ROOT that writes the document, with dots only such that it can be read automatically.
965std::string rootVersion()
966{
967 std::string versionName = gROOT->GetVersion();
968 std::replace(versionName.begin(), versionName.end(), '/', '.');
969 return versionName;
970}
971
972// The data set `name` among the loaded ones that are not a component of a combined data set by now, or the data of a
973// constraint term, or nullptr.
974std::unique_ptr<RooAbsData> *findDataset(std::vector<std::unique_ptr<RooAbsData>> &datasets, std::string const &name)
975{
976 auto found = std::find_if(datasets.begin(), datasets.end(), [&](auto &d) { return d && d->GetName() == name; });
977 return found != datasets.end() ? &*found : nullptr;
978}
979
980// A distribution of the document can be a function in RooFit, or it can be skipped.
981void requirePdf(RooAbsArg const *arg, std::string const &what)
982{
983 if (!dynamic_cast<RooAbsPdf const *>(arg)) {
985 (arg ? std::string("a ") + arg->ClassName() + ", not a pdf" : "not imported"));
986 }
987}
988
989// Check that a combined data set paired with a RooSimultaneous in a likelihood has a sub-data set for every component.
990// RooFit has no notion of an unobserved component: a key without sub-data set is a channel without entries, which
991// adds the expected number of events of an extended component to the likelihood. That changes the fit, so it is an
992// error (https://github.com/root-project/root/issues/24004). For a non-extended component it changes nothing, and a
993// sub-data set without component is ignored by RooFit; both are reported as warnings.
994void checkCombinedPairing(RooSimultaneous const &simPdf, std::string const &dataName, HS3::CombinedData const &data)
995{
996 std::vector<RooCategory const *> columns = selectionColumns(simPdf.indexCat());
997 const std::vector<std::string> columnNames = namesOf(columns);
998 std::vector<std::string> dataColumns = data.columns;
999 std::sort(dataColumns.begin(), dataColumns.end());
1000 if (dataColumns != columnNames) {
1001 RooJSONFactoryWSTool::error("the likelihood pairs '" + std::string(simPdf.GetName()) +
1002 "' with the combined data set '" + dataName + "', but their columns differ");
1003 }
1004 // The keys of the data, each as a map from the column to the label.
1005 std::set<std::map<std::string, std::string>> dataKeys;
1006 for (auto const &component : data.components) {
1007 std::map<std::string, std::string> key;
1008 for (std::size_t i = 0; i < data.columns.size(); ++i) {
1009 key[data.columns[i]] = component.key[i];
1010 }
1011 dataKeys.insert(key);
1012 }
1013 auto keyToString = [&](std::map<std::string, std::string> const &key) {
1014 std::vector<std::string> labels;
1015 for (std::string const &column : data.columns) {
1016 labels.push_back(key.at(column));
1017 }
1018 return selectionKeyToString(labels);
1019 };
1020 std::set<std::map<std::string, std::string>> pdfKeys;
1021 for (std::vector<std::string> const &labels : selectionKeys(columns)) {
1022 RooAbsPdf const *component = simPdf.getPdf(selectionLabel(simPdf.indexCat(), columns, labels));
1023 if (!component) {
1024 continue;
1025 }
1026 std::map<std::string, std::string> key;
1027 for (std::size_t i = 0; i < columns.size(); ++i) {
1028 key[columnNames[i]] = labels[i];
1029 }
1030 pdfKeys.insert(key);
1031 if (dataKeys.count(key) > 0) {
1032 continue;
1033 }
1034 if (component->canBeExtended()) {
1036 "the combined data set '" + dataName + "' has no sub-data set for the key " + keyToString(key) +
1037 " of the extended component '" + component->GetName() + "' of '" + simPdf.GetName() +
1038 "'. RooFit cannot leave a component unobserved: it would add the expected number of events of the " +
1039 "component to the likelihood, see https://github.com/root-project/root/issues/24004");
1040 }
1041 RooJSONFactoryWSTool::warning("RooFitHS3: the combined data set '" + dataName +
1042 "' has no sub-data set for the key " + keyToString(key) + " of the component '" +
1043 component->GetName() + "' of '" + simPdf.GetName() +
1044 "', which RooFit treats as present and empty.");
1045 }
1046 for (auto const &key : dataKeys) {
1047 if (pdfKeys.count(key) == 0) {
1048 RooJSONFactoryWSTool::warning("RooFitHS3: the sub-data set for the key " + keyToString(key) +
1049 " of the combined data set '" + dataName + "' is ignored, because '" +
1050 simPdf.GetName() + "' has no component for it.");
1051 }
1052 }
1053}
1054
1055// The observables of the analysis `analysis` if no data set of its likelihood gives them: the list that RooFit writes
1056// in misc.ROOT_internal.ModelConfigs for a ModelConfig without data, or else the variables that HS3 makes
1057// observables. By the standard, all parameters of the distributions of the likelihood are listed in a domain of the
1058// analysis or are constant, so a variate of the distributions of the likelihood (see HS3::variatesOf(), the columns
1059// of a combined distribution are observables as well) that is neither, is an observable. Requiring all three excludes
1060// the parameters, and the observed values of the constraint terms, which are constant parameters.
1061void observablesWithoutData(HS3Document const &doc, HS3::Analysis const &analysis, HS3::Likelihood const &likelihood,
1062 HS3::ModelConfigInfo const *mcInfo, RooWorkspace &workspace, RooArgSet &observables)
1063{
1064 if (mcInfo && mcInfo->observables) {
1065 for (std::string const &name : *mcInfo->observables) {
1066 if (RooAbsArg *arg = workspace.arg(name)) {
1067 observables.add(*arg);
1068 } else {
1069 RooJSONFactoryWSTool::warning("RooFitHS3: the observable '" + name + "' of the analysis '" + analysis.name +
1070 "' (misc.ROOT_internal.ModelConfigs) does not exist");
1071 }
1072 }
1073 return;
1074 }
1075 std::set<std::string> inDomains;
1076 for (auto const &domainRef : analysis.domains) {
1077 if (HS3::Domain const *domain = HS3::findByName(doc.domains, domainRef.name)) {
1078 for (auto const &axis : domain->axes) {
1079 inDomains.insert(HS3::nameOf(axis));
1080 }
1081 }
1082 }
1083 for (auto const &poi : analysis.parametersOfInterest) {
1084 inDomains.insert(poi.name);
1085 }
1086 std::string list;
1087 for (std::string const &variate : HS3::variatesOf(doc, likelihood)) {
1088 RooAbsArg *arg = workspace.arg(variate);
1089 if (!dynamic_cast<RooAbsRealLValue *>(arg) && !dynamic_cast<RooAbsCategoryLValue *>(arg)) {
1090 continue;
1091 }
1092 if (inDomains.count(variate) || arg->isConstant()) {
1093 continue;
1094 }
1095 observables.add(*arg);
1096 list += (list.empty() ? "'" : ", '") + variate + "'";
1097 }
1098 if (!list.empty()) {
1099 oocoutI(nullptr, IO) << "RooFitHS3: no data set of the likelihood of the analysis '" << analysis.name
1100 << "' gives its observables; they are the variates of the likelihood that are neither in a "
1101 "domain of the analysis nor constant: "
1102 << list << std::endl;
1103 }
1104}
1105
1106// Whether the term `term` of a likelihood is a constraint term of the channel `channel` of a model with the channels
1107// `channels`: it has a global observable (a variable that no channel depends on) and another variable that the
1108// channel depends on. An array of constraints is one term.
1109bool isConstraintOfChannel(RooAbsPdf const &term, RooAbsPdf const &channel, RooArgSet const &channels)
1110{
1111 if (&term == &channel || channels.containsInstance(term)) {
1112 return false;
1113 }
1114 RooArgSet leaves;
1115 term.leafNodeServerList(&leaves);
1116 RooArgSet parameters;
1117 bool hasGlobalObservable = false;
1118 for (RooAbsArg *leaf : leaves) {
1119 auto *var = dynamic_cast<RooRealVar *>(leaf);
1120 if (!var) {
1121 continue;
1122 }
1123 // Whether a global observable is constant yet depends on where the document has its value: as a parameter, or
1124 // in the data set of the constraint, which is read later.
1125 if (std::none_of(channels.begin(), channels.end(),
1126 [&](RooAbsArg const *other) { return other->dependsOn(*var); })) {
1127 hasGlobalObservable = true;
1128 } else {
1129 parameters.add(*var);
1130 }
1131 }
1132 return hasGlobalObservable && !parameters.empty() && channel.dependsOn(parameters);
1133}
1134
1135// The other terms of the likelihoods of the document that have the distribution `dist` as a term: their other
1136// distributions that can be constraint terms, and their auxiliary distributions. These are the candidates for
1137// constraint terms of `dist`.
1138std::vector<std::string> otherLikelihoodTerms(HS3Document const &doc, std::string const &dist)
1139{
1140 std::vector<std::string> out;
1141 auto add = [&](std::string const &name) {
1142 if (name != dist) {
1143 addUnique(out, name);
1144 }
1145 };
1146 // A term can be a constraint term of the channels if it is a measurement of one observation: paired with nothing,
1147 // a value given in-line, point data or an unbinned data set of one entry. A combined distribution, or a term paired
1148 // with a data set of several entries (e.g. the model of another document that the likelihood combines with this
1149 // one), is a measurement of its own.
1150 auto canBeConstraint = [&](HS3::LikelihoodTerm const &term) {
1151 if (HS3::find<HS3::CombinedDist>(doc.distributions, term.distribution.name)) {
1152 return false;
1153 }
1154 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1155 if (!dataRef) {
1156 return true;
1157 }
1158 auto data =
1159 std::find_if(doc.data.begin(), doc.data.end(), [&](auto const &d) { return d.name == dataRef->name; });
1160 if (data == doc.data.end() || std::holds_alternative<HS3::PointData>(data->body)) {
1161 return true;
1162 }
1163 auto const *unbinned = std::get_if<HS3::UnbinnedData>(&data->body);
1164 return unbinned && unbinned->numEntries() == 1;
1165 };
1166 for (auto const &likelihood : doc.likelihoods) {
1167 if (std::none_of(likelihood.terms.begin(), likelihood.terms.end(),
1168 [&](auto const &term) { return term.distribution.name == dist; })) {
1169 continue;
1170 }
1171 for (auto const &term : likelihood.terms) {
1172 if (canBeConstraint(term)) {
1173 add(term.distribution.name);
1174 }
1175 }
1176 for (auto const &aux : likelihood.auxDistributions) {
1177 add(aux.name);
1178 }
1179 }
1180 return out;
1181}
1182
1183// In HS3, the constraint terms of a model are terms of the likelihood; in RooFit, as HistFactory builds its models, a
1184// constraint is a factor of every channel whose parameters it constrains, which makes the pdf of the model the
1185// sampling distribution of the auxiliary measurements as well. The export takes the constraints out of the channels
1186// (writeLikelihoodTermsOnce()); this puts them back: a constraint term with a global observable (a constant variable
1187// that the model itself does not depend on) becomes a factor of every channel that is a product and depends on one
1188// of its other parameters. An array of constraints goes to its channels as a whole. The constraints that
1189// found a channel are removed from `constraints`; the others stay external constraints of the ModelConfig, e.g. a
1190// penalty term without an observation, like the regularization of an unfolding, or a constraint of a model whose
1191// channels are not products.
1192void attachConstraintsToChannels(RooAbsPdf &pdf, RooArgSet &constraints)
1193{
1194 RooArgSet channels;
1195 if (auto *simPdf = dynamic_cast<RooSimultaneous *>(&pdf)) {
1196 for (auto const &state : simPdf->indexCat()) {
1197 if (RooAbsPdf *channel = simPdf->getPdf(state.first)) {
1198 channels.add(*channel, /*silent=*/true);
1199 }
1200 }
1201 } else {
1202 channels.add(pdf);
1203 }
1204 RooArgSet attached;
1205 for (auto *constraint : static_range_cast<RooAbsPdf *>(constraints)) {
1206 // Decided for all channels before any is changed: a channel that has the constraint depends on its global
1207 // observable, which then would not look like one anymore.
1208 bool isFactor = false;
1209 std::vector<RooProdPdf *> products;
1210 for (auto *channel : static_range_cast<RooAbsPdf *>(channels)) {
1211 auto *product = dynamic_cast<RooProdPdf *>(channel);
1212 if (!product || channel == constraint) {
1213 continue;
1214 }
1215 if (product->pdfList().find(*constraint)) {
1216 isFactor = true;
1217 } else if (isConstraintOfChannel(*constraint, *channel, channels)) {
1218 products.push_back(product);
1219 }
1220 }
1221 for (RooProdPdf *product : products) {
1222 product->addPdfs(RooArgSet{*constraint});
1223 }
1224 if (isFactor || !products.empty()) {
1225 attached.add(*constraint);
1226 }
1227 }
1228 constraints.remove(attached);
1229}
1230
1231// RooFit has one pdf per ModelConfig: the terms of a likelihood become one RooSimultaneous `<analysis>_simPdf`. Its
1232// channels are the components of the terms that are combined distributions, flattened also where a component is a
1233// combined distribution itself (HS3 #161), and the other terms. Its index has the columns of all combined
1234// distributions, with the label "" in a column that a channel doesn't have (HS3 allows relabelling), and the column
1235// `<analysis>_categoryIndex`, labelled with the names of the terms, if there is a term that is not a combined
1236// distribution or if the channels can't be told apart without it. Several columns are a RooSuperCategory.
1237//
1238// Within a combined distribution, identical factors enter once (union composition). RooFit finds a constraint term
1239// that several channels contain once, but array distributions that are channels of their own would each be evaluated
1240// on their data: the array channels of one component type are merged into one array distribution with the union of
1241// their components, and their data into one entry, if each has a data set of one entry (or no data at all, in a pure
1242// model). The terms of a likelihood are a plain product (HS3): the variates of different terms are distinct, which
1243// the import has checked, so that the flattening adds no union across terms.
1244//
1245// The data sets paired with the terms become one data set `<analysis>_data` with these columns, which replaces them
1246// unless another likelihood or analysis uses them. The columns are added to `observables`. The terms that the new
1247// RooSimultaneous replaces are marked as helpers, which the export only writes if something else uses them.
1248//
1249// Returns nullptr if the likelihood has a single term that needs none of this.
1250RooSimultaneous *flatModelOfLikelihood(HS3Document const &doc, HS3::Analysis const &analysis, RooWorkspace &workspace,
1251 std::vector<HS3::LikelihoodTerm const *> const &terms,
1252 std::vector<std::unique_ptr<RooAbsData>> &datasets, RooArgSet &observables)
1253{
1254 std::string const &analysisName = analysis.name;
1255 struct Channel {
1256 std::size_t term;
1257 std::map<std::string, std::string> labels; // by column
1258 RooAbsPdf *pdf;
1259 };
1260 std::vector<Channel> channels;
1261 std::set<std::string> innerColumns;
1262 bool plainTerm = false;
1263 bool nested = false;
1264 std::function<void(std::size_t, RooAbsPdf *, std::map<std::string, std::string> const &)> collect =
1265 [&](std::size_t term, RooAbsPdf *pdf, std::map<std::string, std::string> const &labels) {
1266 auto *sim = dynamic_cast<RooSimultaneous *>(pdf);
1267 if (!sim) {
1268 channels.push_back({term, labels, pdf});
1269 return;
1270 }
1271 nested |= !labels.empty();
1272 std::vector<RooCategory const *> const columns = selectionColumns(sim->indexCat());
1273 for (RooCategory const *column : columns) {
1274 innerColumns.insert(column->GetName());
1275 }
1276 for (std::vector<std::string> const &key : selectionKeys(columns)) {
1277 if (RooAbsPdf *component = sim->getPdf(selectionLabel(sim->indexCat(), columns, key))) {
1278 std::map<std::string, std::string> inner = labels;
1279 for (std::size_t k = 0; k < columns.size(); ++k) {
1280 if (!inner.emplace(columns[k]->GetName(), key[k]).second) {
1281 RooJSONFactoryWSTool::error("the combined distribution '" + std::string(sim->GetName()) +
1282 "' has the column '" + columns[k]->GetName() +
1283 "', which a combined distribution that contains it has as well");
1284 }
1285 }
1286 collect(term, component, inner);
1287 }
1288 }
1289 };
1290 for (std::size_t i = 0; i < terms.size(); ++i) {
1291 RooAbsPdf *pdf = workspace.pdf(terms[i]->distribution.name);
1292 plainTerm |= !dynamic_cast<RooSimultaneous *>(pdf);
1293 collect(i, pdf, {});
1294 }
1295
1296 // The array channels that are merged, by component type.
1297 auto componentType = [](RooAbsPdf const *pdf) -> std::string {
1298 auto const *array = dynamic_cast<RooProdPdf const *>(pdf);
1299 if (!array || !pdf->getAttribute(arrayDistTag) || array->pdfList().empty()) {
1300 return "";
1301 }
1302 std::string const type = array->pdfList()[0].ClassName();
1303 for (RooAbsArg const *component : array->pdfList()) {
1304 if (type != component->ClassName()) {
1305 return "";
1306 }
1307 }
1308 return type;
1309 };
1310 std::map<std::string, std::vector<std::size_t>> arraysByType;
1311 for (std::size_t c = 0; c < channels.size(); ++c) {
1312 if (std::string const type = componentType(channels[c].pdf); !type.empty()) {
1313 arraysByType[type].push_back(c);
1314 }
1315 }
1316
1317 // The data: every term must be paired with a data set that has the columns of its channels.
1318 std::vector<std::unique_ptr<RooAbsData> *> termData;
1319 for (std::size_t i = 0; i < terms.size(); ++i) {
1320 auto const *dataRef = std::get_if<HS3::DataRef>(&terms[i]->data);
1321 auto found = dataRef ? std::find_if(datasets.begin(), datasets.end(),
1322 [&](auto const &d) { return d && d->GetName() == dataRef->name; })
1323 : datasets.end();
1324 if (found == datasets.end()) {
1325 termData.clear();
1326 break;
1327 }
1328 bool complete = true;
1329 for (Channel const &channel : channels) {
1330 for (auto const &item : channel.labels) {
1331 complete &= channel.term != i || (*found)->get()->find(item.first.c_str()) != nullptr;
1332 }
1333 }
1334 if (!complete) {
1335 termData.clear();
1336 break;
1337 }
1338 termData.push_back(&*found);
1339 }
1340 // The entries of the data of each channel, by the labels of the columns of its term.
1341 auto channelOf = [&](std::size_t term, RooArgSet const &values) -> std::size_t {
1342 for (std::size_t c = 0; c < channels.size(); ++c) {
1343 if (channels[c].term != term) {
1344 continue;
1345 }
1346 bool match = true;
1347 for (auto const &[column, label] : channels[c].labels) {
1348 auto const *cat = dynamic_cast<RooAbsCategory const *>(values.find(column.c_str()));
1349 match &= cat && cat->getCurrentLabel() == label;
1350 }
1351 if (match) {
1352 return c;
1353 }
1354 }
1355 return channels.size();
1356 };
1357 std::vector<int> entries(channels.size(), 0);
1358 for (std::size_t i = 0; i < termData.size(); ++i) {
1359 RooAbsData &data = **termData[i];
1360 for (int entry = 0; entry < data.numEntries(); ++entry) {
1361 std::size_t const c = channelOf(i, *data.get(entry));
1362 if (c < channels.size()) {
1363 ++entries[c];
1364 }
1365 }
1366 }
1367 // The channel that each array channel is merged into, if any.
1368 std::map<std::size_t, std::size_t> mergedInto;
1369 std::map<std::size_t, RooArgList> mergedComponents;
1370 for (auto const &[type, members] : arraysByType) {
1371 std::vector<std::size_t> candidates;
1372 for (std::size_t c : members) {
1373 if (termData.empty() || entries[c] == 1) {
1374 candidates.push_back(c);
1375 }
1376 }
1377 if (candidates.size() < 2) {
1378 continue;
1379 }
1380 RooArgList &components = mergedComponents[candidates.front()];
1381 for (std::size_t c : candidates) {
1382 mergedInto[c] = candidates.front();
1383 // Identical components are one object (see importArrayDist()), which the merged array has once.
1384 for (RooAbsArg *component : static_cast<RooProdPdf *>(channels[c].pdf)->pdfList()) {
1385 if (!components.containsInstance(*component)) {
1386 components.add(*component);
1387 }
1388 }
1389 }
1390 }
1391
1392 if (terms.size() == 1 && !nested && mergedInto.empty()) {
1393 return nullptr;
1394 }
1395
1396 // The column of the terms is needed if the labels of the other columns don't tell the channels apart. A term that
1397 // is not combined has no labels at all; with the column of the terms, an empty label is never the only one of a
1398 // key, which would be the label of a RooSimultaneous over a single RooCategory.
1399 bool unique = !plainTerm;
1400 std::set<std::vector<std::string>> innerKeys;
1401 for (std::size_t c = 0; c < channels.size(); ++c) {
1402 if (mergedInto.count(c) && mergedInto[c] != c) {
1403 continue;
1404 }
1405 std::vector<std::string> key;
1406 for (std::string const &column : innerColumns) {
1407 auto found = channels[c].labels.find(column);
1408 key.push_back(found == channels[c].labels.end() ? "" : found->second);
1409 }
1410 unique = innerKeys.insert(key).second && unique;
1411 }
1412 std::string const termColumn = analysisName + "_categoryIndex";
1413 if (!unique) {
1414 RooCategory outer{termColumn.c_str(), termColumn.c_str()};
1415 for (std::size_t i = 0; i < terms.size(); ++i) {
1416 outer.defineType(terms[i]->distribution.name, static_cast<int>(i));
1417 }
1418 workspace.import(outer, RooFit::Silence());
1419 }
1420
1421 std::vector<RooCategory *> columns;
1422 for (std::string const &column : innerColumns) {
1423 columns.push_back(workspace.cat(column));
1424 }
1425 if (!unique) {
1426 columns.push_back(workspace.cat(termColumn));
1427 }
1428 std::sort(columns.begin(), columns.end(),
1429 [](RooCategory const *l, RooCategory const *r) { return std::strcmp(l->GetName(), r->GetName()) < 0; });
1430 std::vector<RooCategory const *> const constColumns(columns.begin(), columns.end());
1431
1432 // The key of a channel: the name of its term, its labels, and "" for the columns it doesn't have.
1433 auto keyOf = [&](Channel const &channel) {
1434 std::vector<std::string> key;
1435 for (RooCategory *column : columns) {
1436 if (column->GetName() == termColumn) {
1437 key.push_back(terms[channel.term]->distribution.name);
1438 continue;
1439 }
1440 auto found = channel.labels.find(column->GetName());
1441 if (found != channel.labels.end()) {
1442 key.push_back(found->second);
1443 continue;
1444 }
1445 if (!column->hasLabel("")) {
1446 column->defineType("");
1447 }
1448 key.push_back("");
1449 }
1450 return key;
1451 };
1452
1453 std::unique_ptr<RooSuperCategory> superCat;
1454 RooAbsCategoryLValue *indexCat = columns.front();
1455 if (columns.size() > 1) {
1456 RooArgSet inputs;
1457 for (RooCategory *column : columns) {
1458 inputs.add(*column);
1459 }
1460 std::string const indexName = analysisName + "_index";
1461 superCat = std::make_unique<RooSuperCategory>(indexName.c_str(), indexName.c_str(), inputs);
1462 indexCat = superCat.get();
1463 }
1464 std::map<std::string, RooAbsPdf *> pdfMap;
1465 for (std::size_t c = 0; c < channels.size(); ++c) {
1466 RooAbsPdf *pdf = channels[c].pdf;
1467 if (auto found = mergedInto.find(c); found != mergedInto.end()) {
1468 if (found->second != c) {
1469 continue;
1470 }
1471 // The merged array: the union of the components, one object each.
1472 std::string const name = analysisName + "_" + pdf->GetName() + "_merged";
1473 RooProdPdf merged{name.c_str(), name.c_str(), mergedComponents[c]};
1474 merged.setAttribute(arrayDistTag);
1475 workspace.import(merged, RooFit::RecycleConflictNodes(true), RooFit::Silence(true));
1476 pdf = workspace.pdf(name);
1477 }
1478 pdfMap[selectionLabel(*indexCat, constColumns, keyOf(channels[c]))] = pdf;
1479 }
1480 std::string const simPdfName = analysisName + "_simPdf";
1481 RooSimultaneous simPdf{simPdfName.c_str(), simPdfName.c_str(), pdfMap, *indexCat};
1482 workspace.import(simPdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true));
1483 for (RooCategory *column : columns) {
1484 observables.add(*column, /*silent=*/true);
1485 }
1486 // The terms that the RooSimultaneous replaces are written only if something else uses them.
1487 for (HS3::LikelihoodTerm const *term : terms) {
1488 if (auto *sim = dynamic_cast<RooSimultaneous *>(workspace.pdf(term->distribution.name))) {
1489 sim->setAttribute(helperObjectTag);
1490 }
1491 }
1492 auto *result = static_cast<RooSimultaneous *>(workspace.pdf(simPdfName));
1493 if (termData.empty()) {
1494 return result;
1495 }
1496
1497 RooArgSet columnClones; // owns the clones; `vars` also lists the variables of the data sets
1498 for (RooCategory const *column : columns) {
1499 columnClones.addClone(*column);
1500 }
1501 RooArgSet vars{columnClones};
1502 bool weighted = false;
1503 std::string weightName = RooFit::WeightVar().getString(0);
1504 for (auto const *data : termData) {
1505 vars.add(*(*data)->get(), /*silent=*/true);
1506 weighted |= (*data)->isWeighted();
1507 if (auto *ds = dynamic_cast<RooDataSet const *>(data->get()); ds && ds->isWeighted()) {
1508 weightName = ds->weightVar()->GetName();
1509 }
1510 }
1511 std::string const dataName = analysisName + "_data";
1512 std::unique_ptr<RooDataSet> merged;
1513 if (weighted) {
1514 RooRealVar weightVar{weightName.c_str(), weightName.c_str(), 1.0};
1515 vars.add(weightVar);
1516 merged = std::make_unique<RooDataSet>(dataName.c_str(), dataName.c_str(), vars, RooFit::WeightVar(weightVar));
1517 } else {
1518 merged = std::make_unique<RooDataSet>(dataName.c_str(), dataName.c_str(), vars);
1519 }
1520 // The entries of the merged array channels, combined into one per merged array.
1521 std::map<std::size_t, std::unique_ptr<RooArgSet>> mergedEntries;
1522 RooArgSet row;
1523 merged->get()->snapshot(row);
1524 for (std::size_t i = 0; i < terms.size(); ++i) {
1525 RooAbsData &data = **termData[i];
1526 for (int entry = 0; entry < data.numEntries(); ++entry) {
1527 RooArgSet const &values = *data.get(entry);
1528 const double weight = data.weight();
1529 std::size_t const c = channelOf(i, values);
1530 if (auto found = mergedInto.find(c); found != mergedInto.end()) {
1531 std::unique_ptr<RooArgSet> &combined = mergedEntries[found->second];
1532 if (!combined) {
1533 combined = std::make_unique<RooArgSet>();
1534 values.snapshot(*combined);
1535 continue;
1536 }
1537 // Identical factors have the same observed values in all data sets (HS3).
1538 for (RooAbsArg const *value : values) {
1539 auto const *real = dynamic_cast<RooAbsReal const *>(value);
1540 auto const *known = dynamic_cast<RooAbsReal const *>(combined->find(value->GetName()));
1541 if (real && known && !dynamic_cast<RooAbsCategory const *>(value) &&
1542 std::abs(real->getVal() - known->getVal()) > 1e-12 * std::max(1.0, std::abs(known->getVal()))) {
1543 RooJSONFactoryWSTool::error("the observed value of '" + std::string(value->GetName()) +
1544 "' differs between the data sets of the array distributions that " +
1545 "share it in the likelihood of the analysis '" + analysisName + "'");
1546 }
1547 if (!known) {
1548 combined->addClone(*value);
1549 }
1550 }
1551 continue;
1552 }
1553 row.assign(values);
1554 for (RooCategory const *column : columns) {
1555 auto &cat = static_cast<RooCategory &>(row[column->GetName()]);
1556 if (column->GetName() == termColumn) {
1557 cat.setLabel(terms[i]->distribution.name.c_str());
1558 } else if (!values.find(column->GetName())) {
1559 cat.setLabel("");
1560 }
1561 }
1562 merged->add(row, weight);
1563 }
1564 }
1565 for (auto const &[c, values] : mergedEntries) {
1566 row.assign(*values);
1567 std::vector<std::string> const key = keyOf(channels[c]);
1568 for (std::size_t k = 0; k < columns.size(); ++k) {
1569 static_cast<RooCategory &>(row[columns[k]->GetName()]).setLabel(key[k].c_str());
1570 }
1571 merged->add(row, 1.0);
1572 }
1573
1574 // The observables refer to the variables of the data sets of the terms, which are replaced by the merged one.
1575 RooArgSet mergedObservables;
1576 for (RooAbsArg *obs : observables) {
1577 RooAbsArg *inMerged = merged->get()->find(obs->GetName());
1578 mergedObservables.add(inMerged ? *inMerged : *obs, /*silent=*/true);
1579 }
1580 observables.removeAll();
1581 observables.add(mergedObservables);
1582
1583 // The data sets of the terms are replaced, unless something else uses them.
1584 std::size_t analysesOfLikelihood = 0;
1585 for (HS3::Analysis const &other : doc.analyses) {
1586 analysesOfLikelihood += other.likelihood.name == analysis.likelihood.name;
1587 }
1588 for (auto *data : termData) {
1589 std::size_t uses = 0;
1590 for (HS3::Likelihood const &likelihood : doc.likelihoods) {
1591 for (HS3::LikelihoodTerm const &term : likelihood.terms) {
1592 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1593 uses += dataRef && dataRef->name == (*data)->GetName();
1594 }
1595 }
1596 if (uses == 1 && analysesOfLikelihood == 1) {
1597 data->reset();
1598 }
1599 }
1600 datasets.push_back(std::move(merged));
1601 return result;
1602}
1603
1604// Import an analysis (likelihood + domains) as one or more ModelConfig objects into the workspace.
1605void importAnalysis(HS3Document const &doc, HS3::Analysis const &analysis, RooWorkspace &workspace,
1606 std::vector<std::unique_ptr<RooAbsData>> &datasets, std::set<std::string> const &bookkeepingColumns,
1607 std::set<std::string> const &auxiliaryMeasurements)
1608{
1609 std::string const &analysisName = analysis.name;
1610 auto foundInfo = doc.rooFit.modelConfigs.find(analysisName);
1611 HS3::ModelConfigInfo const *mcInfo = foundInfo != doc.rooFit.modelConfigs.end() ? &foundInfo->second : nullptr;
1612
1613 std::string mcname = mcInfo && mcInfo->mcName ? *mcInfo->mcName : analysisName;
1614 if (workspace.obj(mcname))
1615 return;
1616
1617 workspace.import(RooFit::ModelConfig{mcname.c_str(), mcname.c_str()});
1618 auto *mc = static_cast<RooFit::ModelConfig *>(workspace.obj(mcname));
1619 mc->SetWS(workspace);
1620
1621 // The validation has checked that the likelihood exists.
1622 HS3::Likelihood const &likelihood = *HS3::findByName(doc.likelihoods, analysis.likelihood.name);
1623
1624 auto checkPdf = [&](RooAbsArg const *arg, std::string const &name, std::string const &what) {
1625 requirePdf(arg, "the " + what + " '" + name + "' of analysis '" + analysisName + "'");
1626 };
1627
1628 for (auto const &term : likelihood.terms) {
1629 checkPdf(workspace.arg(term.distribution.name), term.distribution.name, "distribution");
1630 }
1631
1632 // The constraint terms of the HistFactory distributions of the likelihood enter through those distributions.
1633 // Listed in "aux_distributions", they are not added again; paired with a data set in "distributions", they are
1634 // not channels, and the data set gives the observed values of their observables.
1635 std::vector<std::unique_ptr<RooArgSet>> trees;
1636 for (auto const &term : likelihood.terms) {
1637 RooAbsPdf *listed = workspace.pdf(term.distribution.name);
1638 trees.push_back(listed ? std::unique_ptr<RooArgSet>{listed->getComponents()} : nullptr);
1639 }
1640 auto isConstraintTermOfOthers = [&](RooAbsArg const &term, std::size_t self) {
1641 auto isPartOf = [&term](RooArgSet const &tree) {
1642 if (tree.find(term.GetName())) {
1643 return true;
1644 }
1645 if (term.getAttribute(arrayDistTag)) {
1646 if (auto const *array = dynamic_cast<RooProdPdf const *>(&term)) {
1647 for (RooAbsArg const *component : array->pdfList()) {
1648 if (tree.find(component->GetName())) {
1649 return true;
1650 }
1651 }
1652 }
1653 }
1654 return false;
1655 };
1656 for (std::size_t i = 0; i < trees.size(); ++i) {
1657 if (i != self && trees[i] && isPartOf(*trees[i])) {
1658 return true;
1659 }
1660 }
1661 return false;
1662 };
1663
1664 // RooFit writes the constraint terms of a model as terms of the likelihood, with config().exportConstraintData
1665 // paired with a data set of one entry. If the document names the pdf of the ModelConfig, and it is a term of the
1666 // likelihood, another term that is not part of it and is paired with such a data set is a constraint term: an
1667 // external constraint of the ModelConfig.
1668 std::string const modelPdfName = mcInfo && mcInfo->pdfName ? *mcInfo->pdfName : "";
1669 std::unique_ptr<RooArgSet> modelTree;
1670 if (RooAbsPdf const *modelPdf = workspace.pdf(modelPdfName);
1671 modelPdf && std::any_of(likelihood.terms.begin(), likelihood.terms.end(),
1672 [&](auto const &term) { return term.distribution.name == modelPdfName; })) {
1673 modelTree.reset(modelPdf->getComponents());
1674 }
1675 // So is a component of a combined distribution that is read as a constraint term (`auxiliaryMeasurements`, see
1676 // readAuxiliaryChannelsAsConstraints()), whatever the document says about the ModelConfig.
1677 auto isConstraintTermOfModel = [&](RooAbsPdf const &listed, HS3::LikelihoodTerm const &term) {
1678 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1679 const bool auxiliary = auxiliaryMeasurements.count(listed.GetName()) > 0;
1680 if (!dataRef || (!auxiliary && (!modelTree || modelTree->find(listed.GetName())))) {
1681 return false;
1682 }
1683 auto const *data = findDataset(datasets, dataRef->name);
1684 return data && (*data)->numEntries() == 1;
1685 };
1686
1687 std::vector<HS3::LikelihoodTerm const *> nllTerms;
1688 RooArgSet constraintObservables;
1689 RooArgSet constraintsWithData;
1690 for (std::size_t i = 0; i < likelihood.terms.size(); ++i) {
1691 auto const &term = likelihood.terms[i];
1692 RooAbsPdf *listed = workspace.pdf(term.distribution.name);
1693 if (listed && !isConstraintTermOfOthers(*listed, i) && isConstraintTermOfModel(*listed, term)) {
1694 constraintsWithData.add(*listed);
1695 } else if (!listed || !isConstraintTermOfOthers(*listed, i)) {
1696 nllTerms.push_back(&term);
1697 continue;
1698 }
1699 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1700 auto *data = dataRef ? findDataset(datasets, dataRef->name) : nullptr;
1701 if (!data) {
1702 continue;
1703 }
1704 if ((*data)->numEntries() != 1) {
1705 throw std::runtime_error("the data set '" + dataRef->name + "' paired with the constraint term '" +
1706 term.distribution.name + "' must have exactly one entry");
1707 }
1708 for (RooAbsArg const *obs : *(*data)->get(0)) {
1709 auto *var = workspace.var(obs->GetName());
1710 auto const *value = dynamic_cast<RooAbsReal const *>(obs);
1711 if (!var || !value) {
1712 RooJSONFactoryWSTool::warning("RooFitHS3: cannot set the observed value of '" +
1713 std::string(obs->GetName()) + "' from the data set '" + dataRef->name +
1714 "': it is not a variable of the workspace");
1715 continue;
1716 }
1717 var->setVal(value->getVal());
1718 var->setConstant(true);
1719 constraintObservables.add(*var);
1720 }
1721 // The values live in the variables now; the data set is not imported.
1722 data->reset();
1723 }
1724 // The constraint terms of HistFactory distributions are listed as auxiliary distributions, but they are part of the
1725 // distributions in RooFit.
1726 std::set<std::string> channelConstraints;
1727 for (auto const &item : doc.rooFit.channelConstraints) {
1728 for (auto const &ref : item.second) {
1729 channelConstraints.insert(ref.name);
1730 }
1731 }
1732 RooArgSet extConstraints;
1733 for (auto const &aux : likelihood.auxDistributions) {
1734 RooAbsArg *extConstraint = workspace.arg(aux.name);
1735 if (!extConstraint) {
1736 continue;
1737 }
1738 checkPdf(extConstraint, aux.name, "auxiliary distribution");
1739 // Only if the constraint really ended up in a distribution of the likelihood.
1740 if (channelConstraints.count(aux.name) &&
1741 std::any_of(nllTerms.begin(), nllTerms.end(), [&](HS3::LikelihoodTerm const *term) {
1742 RooAbsArg const *dist = workspace.arg(term->distribution.name);
1743 return dist && dist->dependsOn(*extConstraint);
1744 })) {
1745 continue;
1746 }
1747 if (isConstraintTermOfOthers(*extConstraint, likelihood.terms.size())) {
1748 continue;
1749 }
1750 extConstraints.add(*extConstraint);
1751 }
1752 RooArgSet observables;
1753 for (HS3::LikelihoodTerm const *term : nllTerms) {
1754 if (auto const *dataRef = std::get_if<HS3::DataRef>(&term->data)) {
1755 auto const *data = findDataset(datasets, dataRef->name);
1756 if (!data) {
1757 throw std::runtime_error("dataset '" + dataRef->name + "' cannot be found!");
1758 }
1759 observables.add(*(*data)->get(), true);
1760 }
1761 }
1762 // Bookkeeping columns of the data sets are no observables of the model.
1763 for (std::string const &column : bookkeepingColumns) {
1764 if (RooAbsArg *arg = observables.find(column.c_str())) {
1765 observables.remove(*arg);
1766 }
1767 }
1768 if (observables.empty()) {
1769 observablesWithoutData(doc, analysis, likelihood, mcInfo, workspace, observables);
1770 }
1771
1772 // A combined distribution paired with a combined data set must have a sub-data set for every component.
1773 for (auto const &term : likelihood.terms) {
1774 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1775 auto *simPdf = dynamic_cast<RooSimultaneous const *>(workspace.pdf(term.distribution.name));
1776 if (!dataRef || !simPdf) {
1777 continue;
1778 }
1779 if (auto const *combined = HS3::find<HS3::CombinedData>(doc.data, dataRef->name)) {
1780 checkCombinedPairing(*simPdf, dataRef->name, *combined);
1781 }
1782 }
1783
1784 // The pdf of the ModelConfig is the one named in the RooFit metadata, e.g. in files of ROOT before HS3 0.3 the
1785 // RooSimultaneous of the channels that the likelihood lists. Otherwise, it is the only term of the likelihood, or
1786 // the union of its terms. Without terms, it is "simPdf".
1787 RooAbsPdf *pdf = mcInfo && mcInfo->pdfName ? workspace.pdf(*mcInfo->pdfName) : nullptr;
1788 if (!pdf && !nllTerms.empty()) {
1789 pdf = flatModelOfLikelihood(doc, analysis, workspace, nllTerms, datasets, observables);
1790 if (!pdf) {
1791 pdf = workspace.pdf(nllTerms.front()->distribution.name);
1792 }
1793 } else if (!pdf) {
1794 pdf = workspace.pdf("simPdf");
1795 }
1796 if (!pdf) {
1797 RooJSONFactoryWSTool::error("the likelihood '" + likelihood.name + "' of analysis '" + analysisName +
1798 "' has no distribution");
1799 }
1800
1801 mc->SetPdf(*pdf);
1802
1803 extConstraints.add(constraintsWithData, /*silent=*/true);
1804 attachConstraintsToChannels(*pdf, extConstraints);
1805 if (!extConstraints.empty())
1806 mc->SetExternalConstraints(extConstraints);
1807
1808 if (analysis.prior) {
1809 if (RooAbsArg *prior = workspace.arg(analysis.prior->name)) {
1810 checkPdf(prior, analysis.prior->name, "prior");
1811 mc->SetPriorPdf(static_cast<RooAbsPdf &>(*prior));
1812 }
1813 }
1814
1815 RooArgSet parametersOfInterest;
1816 for (auto const &poi : analysis.parametersOfInterest) {
1817 RooAbsArg *arg = workspace.arg(poi.name);
1818 if (!arg) {
1819 RooJSONFactoryWSTool::error("the object '" + poi.name + "' in \"parameters_of_interest\" of analysis '" +
1820 analysisName + "' does not exist");
1821 }
1822 if (!dynamic_cast<RooRealVar *>(arg)) {
1823 RooJSONFactoryWSTool::error("the parameter of interest '" + poi.name + "' of analysis '" + analysisName +
1824 "' is a " + arg->ClassName() + ", not a variable" +
1825 (dynamic_cast<RooConstVar *>(arg) ? ", because no domain lists it" : ""));
1826 }
1827 parametersOfInterest.add(*arg);
1828 }
1829
1830 mc->SetParametersOfInterest(parametersOfInterest);
1831 mc->SetObservables(observables);
1832 RooArgSet pars;
1833 pdf->getParameters(&observables, pars);
1834
1835 // Figure out the set parameters that appear in the main measurement:
1836 // getAllConstraints() has the side effect to remove all parameters from
1837 // "mainPars" that are not part of any pdf over observables.
1838 RooArgSet mainPars{pars};
1839 pdf->getAllConstraints(observables, mainPars, /*stripDisconnected*/ true);
1840
1841 // Parameters that only the external constraints depend on are parameters of the likelihood as well, e.g. the
1842 // global observable and the nuisance parameter of a constraint that is not part of the pdf. They are not part of
1843 // the main measurement.
1844 for (RooAbsArg const *extConstraint : extConstraints) {
1845 RooArgSet extPars;
1846 extConstraint->getParameters(&observables, extPars);
1847 pars.add(extPars, /*silent=*/true);
1848 }
1849
1850 RooArgSet domainPars;
1851 for (auto const &domainRef : analysis.domains) {
1852 if (HS3::Domain const *domain = HS3::findByName(doc.domains, domainRef.name)) {
1853 for (auto const &axis : domain->axes) {
1854 if (RooRealVar *wsvar = workspace.var(HS3::nameOf(axis))) {
1855 domainPars.add(*wsvar);
1856 }
1857 }
1858 }
1859 }
1860
1861 RooArgSet nps;
1862 RooArgSet globs;
1863 for (const auto &p : pars) {
1864 if (mc->GetParametersOfInterest()->find(*p))
1865 continue;
1866 if (p->isConstant() && !mainPars.find(*p) && domainPars.find(*p)) {
1867 globs.add(*p);
1868 } else if (domainPars.find(*p)) {
1869 nps.add(*p);
1870 }
1871 }
1872
1873 globs.add(constraintObservables, /*silent=*/true);
1874 mc->SetGlobalObservables(globs);
1875 mc->SetNuisanceParameters(nps);
1876
1877 if (mcInfo && mcInfo->combinedDataName) {
1878 pdf->setStringAttribute("combined_data_name", mcInfo->combinedDataName->c_str());
1879 }
1880
1881 // A missing parameter point was reported by HS3::validate().
1882 RooArgSet const *init = analysis.init ? workspace.getSnapshot(analysis.init->name.c_str()) : nullptr;
1883 if (init) {
1884 const std::string &initName = analysis.init->name;
1885 // ModelConfig::SetSnapshot() saves the snapshot as "<mc name>_<set name>_snapshot". If "init" already follows
1886 // this pattern, which is the case for files written by RooFit, pick the set name such that it is preserved.
1887 std::string setName = initName;
1888 const std::string prefix = mcname + "_";
1889 const std::string suffix = "_snapshot";
1890 if (initName.size() >= prefix.size() + suffix.size() && startsWith(initName, prefix) &&
1891 endsWith(initName, suffix)) {
1892 setName = initName.substr(prefix.size(), initName.size() - prefix.size() - suffix.size());
1893 }
1894 // Take an owning copy: SetSnapshot() might replace the workspace snapshot that `init` points to.
1895 RooArgSet initSet;
1896 init->snapshot(initSet);
1897 initSet.setName(setName.c_str());
1898 mc->SetSnapshot(initSet);
1899 }
1900}
1901
1902// HistFactory modifiers pick the components that constrain their parameters out of an array distribution. By the
1903// standard the whole array enters the likelihood, so the components of a partially used array that nothing uses are
1904// reported.
1905void warnAboutUnusedArrayComponents(RooWorkspace const &ws)
1906{
1907 for (RooAbsArg *arg : ws.allPdfs()) {
1908 auto const *array = dynamic_cast<RooProdPdf const *>(arg);
1909 if (!array || !array->getAttribute(arrayDistTag) || array->hasClients()) {
1910 continue;
1911 }
1912 bool used = false;
1913 std::string unused;
1914 for (RooAbsArg const *component : array->pdfList()) {
1915 bool usedElsewhere = false;
1916 for (RooAbsArg const *client : component->clients()) {
1917 if (client != array) {
1918 usedElsewhere = true;
1919 }
1920 }
1921 if (usedElsewhere) {
1922 used = true;
1923 } else {
1924 unused += (unused.empty() ? "'" : ", '") + std::string(component->GetName()) + "'";
1925 }
1926 }
1927 if (used && !unused.empty()) {
1928 RooJSONFactoryWSTool::warning("RooFitHS3: the components " + unused + " of the array distribution '" +
1929 array->GetName() +
1930 "' are not used by any distribution and are not part of any likelihood");
1931 }
1932 }
1933}
1934
1935void combinePdfs(HS3Document const &doc, RooWorkspace &ws)
1936{
1937 for (auto const &item : doc.rooFit.combinedDistributions) {
1938 std::string const &combinedName = item.first;
1939 HS3::CombinedDistribution const &info = item.second;
1940
1941 RooCategory indexCat{info.indexCat.c_str(), info.indexCat.c_str()};
1942 std::map<std::string, RooAbsPdf *> pdfMap;
1943
1944 for (std::size_t iChannel = 0; iChannel < info.labels.size(); ++iChannel) {
1945 indexCat.defineType(info.labels[iChannel], info.indices[iChannel]);
1946 std::string const &name = info.distributions[iChannel].name;
1947 requirePdf(ws.arg(name),
1948 "the distribution '" + name + "' of the combined distribution '" + combinedName + "'");
1949 pdfMap[info.labels[iChannel]] = ws.pdf(name);
1950 }
1951
1952 RooSimultaneous simPdf{combinedName.c_str(), combinedName.c_str(), pdfMap, indexCat};
1953 ws.import(simPdf, RooFit::RecycleConflictNodes(true), RooFit::Silence(true));
1954 }
1955}
1956
1957void combineDatasets(HS3Document const &doc, std::vector<std::unique_ptr<RooAbsData>> &datasets)
1958{
1959 for (auto const &item : doc.rooFit.combinedDatasets) {
1960 std::string const &combinedName = item.first;
1961 HS3::CombinedDataset const &info = item.second;
1962
1963 // Create the combined dataset for RooFit
1964 std::map<std::string, std::unique_ptr<RooAbsData>> dsMap;
1965 RooCategory indexCat{info.indexCat.c_str(), info.indexCat.c_str()};
1966 RooArgSet allVars{indexCat};
1967 for (std::size_t iChannel = 0; iChannel < info.labels.size(); ++iChannel) {
1968 auto componentName = combinedName + "_" + info.labels[iChannel];
1969 // We move the found channel data out of the "datasets" vector, such that
1970 // the data components don't get imported anymore.
1971 auto *found = findDataset(datasets, componentName);
1972 if (!found) {
1973 RooJSONFactoryWSTool::error("unable to obtain component matching component name '" + componentName + "'");
1974 }
1975 allVars.add(*(*found)->get(), true);
1976 dsMap.insert({info.labels[iChannel], std::move(*found)});
1977 indexCat.defineType(info.labels[iChannel], info.indices[iChannel]);
1978 }
1979
1980 auto combined = std::make_unique<RooDataSet>(combinedName, combinedName, allVars, RooFit::Import(dsMap),
1981 RooFit::Index(indexCat));
1982 datasets.emplace_back(std::move(combined));
1983 }
1984}
1985
1986// The categories of the workspace that are the columns of a combined data set or distribution: they are declared by
1987// categorical axes of the domains, or existed before. The validation has checked the columns and the keys against the
1988// domains, but not against the categories that existed before.
1989template <class Ref_t>
1990std::vector<RooCategory *>
1991columnCategories(RooWorkspace const &workspace, HS3::Combined<Ref_t> const &combined, std::string const &context)
1992{
1993 std::vector<RooCategory *> columns;
1994 for (std::string const &column : combined.columns) {
1995 RooCategory *cat = workspace.cat(column);
1996 if (!cat) {
1997 RooJSONFactoryWSTool::error("the column '" + column + "' of " + context +
1998 " is not declared by a categorical axis of a domain");
1999 }
2000 columns.push_back(cat);
2001 }
2002 for (auto const &component : combined.components) {
2003 for (std::size_t i = 0; i < columns.size(); ++i) {
2004 if (!columns[i]->hasLabel(component.key[i])) {
2005 RooJSONFactoryWSTool::error("the label '" + component.key[i] + "' in position " + std::to_string(i) +
2006 " of a key of " + context + " is not one of the categories of '" +
2007 columns[i]->GetName() + "'");
2008 }
2009 }
2010 }
2011 return columns;
2012}
2013
2014// Build the combined data sets of the document: a RooDataSet with one category column per entry of "columns" and the
2015// variables of all components, filled row by row from the components, which are then no longer imported on their own.
2016// A key without a sub-data set is a state without entries: RooFit has no notion of an absent component. The validation
2017// has checked that the components are data sets of the document.
2018//
2019// A component may itself be a combined data set (HS3 #161), which is then built first. Its columns become columns of
2020// the outer data set, like the RooSimultaneous of a combined distribution with a combined component is flattened: the
2021// rows of the other components have the label "" in them.
2022void assembleCombinedData(HS3Document const &doc, RooWorkspace const &workspace,
2023 std::vector<std::unique_ptr<RooAbsData>> &datasets)
2024{
2025 // The combined data sets in an order in which the components come first.
2026 std::vector<HS3::Data const *> pending;
2027 for (HS3::Data const &input : doc.data) {
2028 if (std::holds_alternative<HS3::CombinedData>(input.body)) {
2029 pending.push_back(&input);
2030 }
2031 }
2032 std::vector<HS3::Data const *> ordered;
2033 std::set<std::string> done;
2034 while (!pending.empty()) {
2035 auto ready = std::find_if(pending.begin(), pending.end(), [&](HS3::Data const *data) {
2036 for (auto const &c : std::get<HS3::CombinedData>(data->body).components) {
2037 if (HS3::find<HS3::CombinedData>(doc.data, c.ref.name) && !done.count(c.ref.name)) {
2038 return false;
2039 }
2040 }
2041 return true;
2042 });
2043 if (ready == pending.end()) {
2044 RooJSONFactoryWSTool::error("the combined data set '" + pending.front()->name +
2045 "' is a component of itself, directly or through other combined data sets");
2046 }
2047 ordered.push_back(*ready);
2048 done.insert((*ready)->name);
2049 pending.erase(ready);
2050 }
2051 for (HS3::Data const *inputPtr : ordered) {
2052 HS3::Data const &input = *inputPtr;
2053 auto const *info = std::get_if<HS3::CombinedData>(&input.body);
2054 std::string const &name = input.name;
2056 std::string const context = "the combined data set '" + name + "'";
2057 std::vector<RooCategory *> columns = columnCategories(workspace, *info, context);
2058
2059 struct Component {
2060 std::vector<std::string> const *key;
2061 std::unique_ptr<RooAbsData> data;
2062 };
2063 std::vector<Component> components;
2064 for (auto const &c : info->components) {
2065 auto *found = findDataset(datasets, c.ref.name);
2066 if (!found) {
2067 RooJSONFactoryWSTool::error("the component '" + c.ref.name + "' of " + context +
2068 " is not a data set of the document, or it is already a component of " +
2069 "another combined data set");
2070 }
2071 components.push_back({&c.key, std::move(*found)});
2072 }
2073
2074 // The variables: the columns first, then those of the components. A weight variable if any component is
2075 // weighted, with errors if any component is binned, like RooDataSet does when importing a map of data sets.
2076 RooArgSet columnClones; // owns the clones; `vars` must not own anything, it also lists the components' variables
2077 for (RooCategory const *column : columns) {
2078 columnClones.addClone(*column);
2079 }
2080 // The columns of components that are combined data sets themselves, with the label "" for the other rows.
2081 for (auto const &c : components) {
2082 for (RooAbsArg const *arg : *c.data->get()) {
2083 if (dynamic_cast<RooCategory const *>(arg) && !columnClones.find(*arg)) {
2084 // The category of the domain has the labels of all components.
2085 RooCategory const *declared = workspace.cat(arg->GetName());
2086 columnClones.addClone(declared ? static_cast<RooAbsArg const &>(*declared) : *arg);
2087 }
2088 }
2089 }
2090 std::vector<RooCategory *> innerColumns;
2091 for (RooAbsArg *arg : columnClones) {
2092 auto *cat = static_cast<RooCategory *>(arg);
2093 if (std::find_if(columns.begin(), columns.end(), [&](RooCategory const *c) {
2094 return std::strcmp(c->GetName(), cat->GetName()) == 0;
2095 }) != columns.end()) {
2096 continue;
2097 }
2098 innerColumns.push_back(cat);
2099 bool everywhere = std::all_of(components.begin(), components.end(),
2100 [&](auto const &c) { return c.data->get()->find(*cat) != nullptr; });
2101 if (!everywhere && !cat->hasLabel("")) {
2102 cat->defineType("");
2103 }
2104 }
2105 RooArgSet vars{columnClones};
2106 bool weighted = false;
2107 bool storeErrors = false;
2108 std::string weightName = RooFit::WeightVar().getString(0);
2109 for (auto const &c : components) {
2110 vars.add(*c.data->get(), /*silent=*/true);
2111 weighted |= c.data->isWeighted();
2112 if (auto *ds = dynamic_cast<RooDataSet const *>(c.data.get()); ds && ds->isWeighted()) {
2113 weightName = ds->weightVar()->GetName();
2114 }
2115 storeErrors |= dynamic_cast<RooDataHist const *>(c.data.get()) != nullptr;
2116 }
2117 std::unique_ptr<RooDataSet> combined;
2118 if (weighted) {
2119 RooRealVar weightVar{weightName.c_str(), weightName.c_str(), 1.0};
2120 vars.add(weightVar);
2121 RooArgSet errorSet{weightVar};
2122 combined = std::make_unique<RooDataSet>(name.c_str(), name.c_str(), vars, RooFit::WeightVar(weightVar),
2123 storeErrors ? RooFit::StoreError(errorSet) : RooCmdArg::none());
2124 } else {
2125 combined = std::make_unique<RooDataSet>(name.c_str(), name.c_str(), vars);
2126 }
2127 for (auto const &c : components) {
2128 for (std::size_t i = 0; i < columns.size(); ++i) {
2129 static_cast<RooCategory &>(vars[columns[i]->GetName()]).setLabel((*c.key)[i].c_str());
2130 }
2131 for (int i = 0; i < c.data->numEntries(); ++i) {
2132 vars.assign(*c.data->get(i));
2133 for (RooCategory *inner : innerColumns) {
2134 if (!c.data->get()->find(*inner)) {
2135 static_cast<RooCategory &>(vars[inner->GetName()]).setLabel("");
2136 }
2137 }
2138 if (weighted) {
2139 combined->add(vars, c.data->weight(), storeErrors ? c.data->weightError(RooAbsData::SumW2) : 0.0);
2140 } else {
2141 combined->add(vars);
2142 }
2143 }
2144 }
2145 datasets.emplace_back(std::move(combined));
2146 }
2147}
2148
2149template <class T>
2150void sortByName(T &coll)
2151{
2152 std::sort(coll.begin(), coll.end(), [](auto &l, auto &r) { return strcmp(l->GetName(), r->GetName()) < 0; });
2153}
2154
2155// Whether no object of the workspace uses `arg`. Only clients that are part of the workspace count: RooFit also
2156// registers evaluation artifacts as clients, like the normalization integral that RooAbsPdf caches after
2157// getVal(normSet), or the integral returned by createIntegral(). These live outside the workspace and are not evidence
2158// that the object is a sub-node of a bigger model (see https://github.com/root-project/root/issues/23221). Helpers that
2159// are not written don't count as users either.
2160bool isTopLevel(RooAbsArg const &arg, RooWorkspace const &ws)
2161{
2162 for (RooAbsArg const *client : arg.clients()) {
2163 if (ws.components().containsInstance(*client) && !isSkippedHelper(*client, ws)) {
2164 return false;
2165 }
2166 }
2167 return true;
2168}
2169
2170// The top-level objects among `args` that are written, sorted by name.
2171template <class Arg_t>
2172std::vector<Arg_t *> topLevelObjects(RooArgSet const &args, RooWorkspace const &ws)
2173{
2174 std::vector<Arg_t *> out;
2175 for (RooAbsArg *arg : args) {
2176 auto *object = dynamic_cast<Arg_t *>(arg);
2177 if (object && isTopLevel(*arg, ws) && !isSkippedHelper(*arg, ws)) {
2178 out.push_back(object);
2179 }
2180 }
2181 sortByName(out);
2182 return out;
2183}
2184
2185} // namespace
2186
2187RooArgSet RooFit::HS3::createObservables(std::vector<BinnedAxis> const &axes)
2188{
2189 RooArgSet vars;
2190 for (BinnedAxis const &axis : axes) {
2191 vars.addOwned(createObservable(axis));
2192 }
2193 return vars;
2194}
2195
2196std::unique_ptr<RooDataHist> RooFit::HS3::createDataHist(std::string const &name, RooArgSet const &vars,
2197 std::vector<double> const &contents,
2198 std::vector<double> const *errors)
2199{
2200 if (errors && errors->size() != contents.size()) {
2201 RooJSONFactoryWSTool::error("inconsistent number of errors and contents in '" + name + "': errors=" +
2202 std::to_string(errors->size()) + ", contents=" + std::to_string(contents.size()));
2203 }
2204 // A continuous variable has the bins of its binning, and a category one bin per state.
2205 std::size_t nBins = 1;
2206 for (RooAbsArg const *var : vars) {
2207 nBins *= std::max(0, dynamic_cast<RooAbsLValue const &>(*var).numBins());
2208 }
2209 if (contents.size() != nBins) {
2210 RooJSONFactoryWSTool::error("inconsistent bin numbers: contents=" + std::to_string(contents.size()) +
2211 ", bins=" + std::to_string(nBins));
2212 }
2213 auto dh = std::make_unique<RooDataHist>(name, name, vars);
2214 // RooDataHist only starts to store squared weights when it sees a positive error, and then initializes them from
2215 // the weights so far. Trigger that before setting any weight, so that errors of zero stay zero.
2216 if (errors && !errors->empty()) {
2217 dh->set(0, 0., 1.);
2218 }
2219 for (std::size_t ibin = 0; ibin < nBins; ++ibin) {
2220 dh->set(ibin, contents[ibin], errors ? (*errors)[ibin] : -1);
2221 }
2222 return dh;
2223}
2224
2225// A combined distribution is a RooSimultaneous. Its index category is the single column, or a RooSuperCategory over the
2226// columns in the order of the document.
2227void RooFit::HS3::buildCombinedDist(RooJSONFactoryWSTool &tool, std::string const &name, CombinedDist const &dist,
2228 std::vector<std::string> const &otherLikelihoodTerms)
2229{
2230 std::vector<RooCategory *> columns = columnCategories(*tool.workspace(), dist, "the combined_dist '" + name + "'");
2231 std::map<std::string, RooAbsPdf *> pdfMap;
2232 for (auto const &component : dist.components) {
2233 pdfMap[selectionLabel(component.key)] = tool.request<RooAbsPdf>(component.ref.name, name);
2234 }
2235
2236 // In RooFit, the constraint terms of a channel are factors of it, which RooFit takes out of the product when it
2237 // builds a likelihood. A channel that is a product gets them when the likelihood is read; the other channels are
2238 // wrapped in a product "<channel>_with_constraints" here, since the components of a RooSimultaneous can't be
2239 // replaced later. The candidates are the other terms of the likelihoods that have this distribution.
2240 std::vector<RooAbsPdf *> terms;
2241 for (std::string const &term : otherLikelihoodTerms) {
2242 if (auto *pdf = tool.tryRequest<RooAbsPdf>(term)) {
2243 terms.push_back(pdf);
2244 }
2245 }
2246 RooArgSet channels;
2247 for (auto const &item : pdfMap) {
2248 channels.add(*item.second, /*silent=*/true);
2249 }
2250 for (auto &item : pdfMap) {
2251 RooAbsPdf &channel = *item.second;
2252 RooArgList factors;
2253 for (RooAbsPdf *term : terms) {
2254 // A combined distribution as a component is flattened by the import of the likelihood (HS3 #161); its
2255 // channels get their constraints there.
2256 if (!dynamic_cast<RooProdPdf *>(&channel) && !dynamic_cast<RooSimultaneous *>(&channel) &&
2257 isConstraintOfChannel(*term, channel, channels)) {
2258 factors.add(*term);
2259 }
2260 }
2261 if (!factors.empty()) {
2262 factors.add(channel);
2263 item.second = &tool.wsEmplace<RooProdPdf>(std::string(channel.GetName()) + "_with_constraints", factors);
2264 }
2265 }
2266
2267 if (columns.size() == 1) {
2268 tool.wsImport(RooSimultaneous{name.c_str(), name.c_str(), pdfMap, *columns.front()});
2269 return;
2270 }
2271 RooArgSet inputs;
2272 for (RooCategory *column : columns) {
2273 inputs.add(*column);
2274 }
2275 std::string const indexName = name + "_index";
2276 RooSuperCategory indexCat{indexName.c_str(), indexName.c_str(), inputs};
2277 tool.wsImport(RooSimultaneous{name.c_str(), name.c_str(), pdfMap, indexCat});
2278}
2279
2280bool isSkippedHelper(RooAbsArg const &arg, RooWorkspace const &ws)
2281{
2282 const bool helper = arg.getAttribute(helperObjectTag);
2283 // An object that nothing in the workspace uses: written, unless it is a helper. A helper that stands for an HS3
2284 // object of its own, an array distribution, is written as that object.
2285 bool hasClients = false;
2286 for (RooAbsArg const *client : arg.clients()) {
2287 if (!ws.components().containsInstance(*client)) {
2288 continue;
2289 }
2290 const bool skipped = isSkippedHelper(*client, ws);
2291 if (!skipped) {
2292 return false;
2293 }
2294 // An array distribution that is not written dissolves into its components, which are then written on their
2295 // own: it is no user of them.
2296 if (!(client->getAttribute(helperObjectTag) && client->getAttribute(arrayDistTag))) {
2297 hasClients = true;
2298 }
2299 }
2300 if (!hasClients && (!helper || (arg.getAttribute(arrayDistTag) && RooJSONFactoryWSTool::config().exportArrayDist))) {
2301 return false;
2302 }
2303 for (TObject const *obj : ws.allGenericObjects()) {
2304 auto const *mc = dynamic_cast<RooFit::ModelConfig const *>(obj);
2305 if (!mc) {
2306 continue;
2307 }
2308 if (mc->GetPdf() == &arg || mc->GetPriorPdf() == &arg ||
2309 (mc->GetExternalConstraints() && mc->GetExternalConstraints()->containsInstance(arg))) {
2310 return false;
2311 }
2312 }
2313 // A helper that only skipped helpers use, or nothing; and, weakly transitive, any other object that only skipped
2314 // helpers use.
2315 return true;
2316}
2317
2319
2321{
2322 if (!_import) {
2323 return false;
2324 }
2325 auto const &componentsWithData = _import->componentsWithData;
2326 // Also as a component of an array distribution, which is the product of its components in RooFit.
2327 return componentsWithData.count(pdf.GetName()) ||
2328 std::any_of(pdf.clients().begin(), pdf.clients().end(), [&](RooAbsArg const *client) {
2329 return client->getAttribute(arrayDistTag) && componentsWithData.count(client->GetName());
2330 });
2331}
2332
2333std::vector<HS3::DistributionRef> const *RooJSONFactoryWSTool::channelConstraints(std::string const &dist) const
2334{
2335 if (!_import) {
2336 return nullptr;
2337 }
2338 auto const &all = _import->document.rooFit.channelConstraints;
2339 auto found = all.find(dist);
2340 return found != all.end() ? &found->second : nullptr;
2341}
2342
2344
2346{
2347 return _import ? _import->document.metadata.version : HS3::Version{};
2348}
2349
2350void RooJSONFactoryWSTool::fillSeq(JSONNode &node, RooAbsCollection const &coll, size_t nMax)
2351{
2352 const size_t old_children = node.num_children();
2353 node.set_seq();
2354 size_t n = 0;
2355 for (RooAbsArg const *arg : coll) {
2356 if (n >= nMax)
2357 break;
2358 writeReference(node.append_child(), *arg);
2359 ++n;
2360 }
2361 if (node.num_children() != old_children + coll.size()) {
2362 error("unable to stream collection " + std::string(coll.GetName()) + " to " + node.key());
2363 }
2364}
2365
2367{
2369 child["name"] << name;
2370 return child;
2371}
2372
2373JSONNode const *RooJSONFactoryWSTool::findNamedChild(JSONNode const &node, std::string const &name)
2374{
2375 if (!node.is_seq())
2376 return nullptr;
2377 for (JSONNode const &child : node.children()) {
2378 if (child["name"].val() == name)
2379 return &child;
2380 }
2381
2382 return nullptr;
2383}
2384
2385/// Whether a string is a valid name: a letter or an underscore, followed by letters, digits or underscores. Only
2386/// characters from the ASCII character set are allowed.
2387bool RooJSONFactoryWSTool::isValidName(const std::string &str)
2388{
2389 return !str.empty() && (std::isalpha(str[0]) || str[0] == '_') &&
2390 std::all_of(str.begin(), str.end(), [](char c) { return std::isalnum(c) || c == '_'; });
2391}
2392
2393bool RooJSONFactoryWSTool::testValidName(const std::string &name, bool forceError)
2394{
2396 std::stringstream ss;
2397 ss << "RooJSONFactoryWSTool() name '" << name << "' is not valid!" << std::endl
2398 << "Sanitize names by setting RooJSONFactoryWSTool::config().allowSanitizeNames = true." << std::endl;
2399 if (RooJSONFactoryWSTool::config().allowExportInvalidNames && !forceError) {
2401 return false;
2402 } else {
2404 }
2405 }
2406 return true;
2407}
2408
2410{
2411 return n["name"].val();
2412}
2413
2414// The specializations of requestImpl() look in the workspace first. If the object is not there, they import what the
2415// document has under that name, and look again.
2416template <>
2417RooRealVar *RooJSONFactoryWSTool::requestImpl<RooRealVar>(const std::string &objname)
2418{
2419 if (_import && !_workspace.var(objname)) {
2420 auto found = _import->defaultValuesByName.find(objname);
2421 if (found != _import->defaultValuesByName.end()) {
2422 importVariable(*found->second);
2423 }
2424 }
2425 return _workspace.var(objname);
2426}
2427
2428template <>
2429RooAbsPdf *RooJSONFactoryWSTool::requestImpl<RooAbsPdf>(const std::string &objname)
2430{
2431 if (_import && !_workspace.pdf(objname)) {
2432 auto found = _import->distributions.find(objname);
2433 if (found != _import->distributions.end()) {
2434 importDistribution(*found->second);
2435 }
2436 }
2437 // HS3 lists some resolution models, which are pdfs in RooFit, as functions.
2438 if (_import && !_workspace.pdf(objname)) {
2439 auto found = _import->functions.find(objname);
2440 if (found != _import->functions.end()) {
2441 importFunction(*found->second->body.node, true);
2442 }
2443 }
2444 return _workspace.pdf(objname);
2445}
2446
2447template <>
2448RooAbsReal *RooJSONFactoryWSTool::requestImpl<RooAbsReal>(const std::string &objname)
2449{
2450 if (RooAbsReal *retval = _workspace.function(objname))
2451 return retval;
2452 if (std::optional<double> number = toNumber(objname))
2453 return &RooFit::RooConst(*number);
2454 if (RooAbsPdf *pdf = requestImpl<RooAbsPdf>(objname))
2455 return pdf;
2456 if (RooRealVar *var = requestImpl<RooRealVar>(objname))
2457 return var;
2458 if (_import && !_workspace.function(objname)) {
2459 auto found = _import->functions.find(objname);
2460 if (found != _import->functions.end()) {
2461 importFunction(*found->second->body.node, true);
2462 }
2463 }
2464 return _workspace.function(objname);
2465}
2466
2467// Export a single variable (RooRealVar or RooConstVar) `v` to the parameter point.
2469{
2470 auto *cv = dynamic_cast<const RooConstVar *>(v);
2471 auto *rrv = dynamic_cast<const RooRealVar *>(v);
2472 if (!cv && !rrv)
2473 return;
2474
2475 // for RooConstVar, if name and value are the same, we don't need to do anything
2476 if (cv && strcmp(cv->GetName(), TString::Format("%g", cv->getVal()).Data()) == 0) {
2477 return;
2478 }
2479
2480 // A named RooConstVar only takes its value: it is written as a domain axis with that single value, not in the
2481 // parameter points.
2482 if (cv) {
2483 HS3::DomainAxis axis;
2484 axis.name = cv->GetName();
2485 axis.fixedValue = cv->getVal();
2486 _export->domains[HS3::defaultDomainName][axis.name] = std::move(axis);
2487 return;
2488 }
2489
2491 var.name = v->GetName();
2492 var.value = rrv->getVal();
2493 var.isConst = rrv->isConstant() || rrv->getMin() >= rrv->getMax();
2494 recordDomains(_export->domains, *rrv);
2495 point.parameters.push_back(std::move(var));
2496}
2497
2498std::string RooJSONFactoryWSTool::exportTransformed(const RooAbsReal *original, const std::string &suffix,
2499 const std::string &formula)
2500{
2501 // A literal constant is spelled as an identifier, which a parameter must not be mistaken for when reading.
2502 if (!isLiteralConstVar(*original) && isLiteralIdentifier(original->GetName())) {
2503 error("cannot write a function of '" + std::string(original->GetName()) +
2504 "': names of the form 'const_<number>' are reserved for functions of literal constants");
2505 }
2506 std::string newname = transformedBaseName(*original) + suffix;
2507 // HS3 0.3 (HS3 PR #154) only allows expressions to refer to parameters, variables and functions.
2508 if (dynamic_cast<RooAbsPdf const *>(original)) {
2509 error("the parameter '" + std::string(original->GetName()) +
2510 "' would have to be written as an expression that refers to a pdf, which HS3 doesn't allow");
2511 }
2512 // Another object that shares the parameter might have exported the helper already.
2513 auto &functions = _export->doc.functions;
2514 if (HS3::findByName(functions, newname)) {
2515 return newname;
2516 }
2517 RooFit::Detail::JSONNode &trafo_node = appendNamedChild((*_export->root)["functions"], newname);
2518 trafo_node["type"] << "generic";
2519 trafo_node["expression"] << TString::Format(formula.c_str(), transformedArgument(*original).c_str()).Data();
2520 functions.push_back({newname, {"generic", nullptr}});
2521 this->setAttribute(newname, "roofit_skip"); // this function should not be imported back in
2522 return newname;
2523}
2524
2525namespace {
2526
2527// Turn an arbitrary string into a valid variable name, but refuse to change the
2528// first character (which would silently rename the object).
2529std::string makeValidNameOrError(std::string const &in)
2530{
2531 if (!std::isalpha(in[0])) {
2532 RooJSONFactoryWSTool::error("refusing to change first character of string '" + in + "' to make a valid name!");
2533 }
2534 std::string out = in;
2535 std::transform(out.begin(), out.end(), out.begin(), [](char c) { return std::isalnum(c) ? c : '_'; });
2536 if (out != in) {
2537 oocoutW(nullptr, ObjectHandling) << "RooFitHS3: changed '" << in << "' to '" << out << "' to become a valid name";
2538 }
2539 return out;
2540}
2541
2542// The labels of a selection key, made valid names and joined by "_". Used in the names of sub-data sets and of
2543// renamed observables. An empty label, for a column that does not apply to a component, stays empty, so that the
2544// position of the other labels still tells the keys apart.
2545std::string selectionKeyName(std::vector<std::string> const &key)
2546{
2547 std::string out;
2548 for (std::size_t i = 0; i < key.size(); ++i) {
2549 out += (i == 0 ? "" : "_") + (key[i].empty() ? std::string{} : makeValidNameOrError(key[i]));
2550 }
2551 return out;
2552}
2553
2554// The RooSimultaneous of the workspace (the first by name) whose columns are `columns`, or nullptr.
2555RooSimultaneous const *findMatchingSimultaneous(RooWorkspace const &workspace, std::vector<std::string> const &columns)
2556{
2557 std::vector<RooSimultaneous const *> candidates;
2558 for (RooAbsArg *arg : workspace.allPdfs()) {
2559 if (auto *candidate = dynamic_cast<RooSimultaneous const *>(arg)) {
2560 candidates.push_back(candidate);
2561 }
2562 }
2563 sortByName(candidates);
2564 for (RooSimultaneous const *candidate : candidates) {
2565 if (namesOf(selectionColumns(candidate->indexCat())) == columns) {
2566 return candidate;
2567 }
2568 }
2569 return nullptr;
2570}
2571
2572} // namespace
2573
2574namespace {
2575
2576// Record an object that was written by an exporter in the document. Its node moves when the array that it is in
2577// grows, so the distributions only get their nodes at the end of the export.
2578void recordGenericObject(HS3Document &doc, bool isPdf, std::string const &name, JSONNode const &elem)
2579{
2580 std::string type = elem.has_child("type") ? elem["type"].val() : "";
2581 if (isPdf) {
2582 doc.distributions.push_back({name, HS3::GenericObject{std::move(type), nullptr}});
2583 } else {
2584 doc.functions.push_back({name, {std::move(type), nullptr}});
2585 }
2586}
2587
2588} // namespace
2589
2590// Export a single object `func` (pdf, function, variable or category) to the output JSON, recording its name in
2591// the exported object names to avoid exporting it twice.
2593{
2594 std::string name = func.GetName();
2595 std::set<std::string> &exportedObjectNames = _export->exportedObjectNames;
2596
2597 if (exportedObjectNames.find(name) != exportedObjectNames.end()) {
2598 // A component of an array distribution is not written under its own name, so an object that refers to it by
2599 // that name would have a dangling reference.
2600 auto const &arrayOfComponent = _export->arrayOfComponent;
2601 if (auto found = arrayOfComponent.find(name); found != arrayOfComponent.end() && found->second != name) {
2602 error("'" + name + "' is written as a component of the array distribution '" + found->second +
2603 "', but another object refers to it by its own name. Set "
2604 "RooJSONFactoryWSTool::config().exportArrayDist = false to write it on its own.");
2605 }
2606 return;
2607 }
2608
2609 exportedObjectNames.insert(name);
2610
2611 // Exporters that group objects per top-level pdf (the HistFactory constraints) ask for the root of the recursion.
2612 if (_export->depth == 0) {
2613 _export->rootName = name;
2614 }
2615 struct DepthGuard {
2616 int &depth;
2617 DepthGuard(int &d) : depth{d} { ++depth; }
2618 ~DepthGuard() { --depth; }
2619 } depthGuard{_export->depth};
2620
2621 if (auto simPdf = dynamic_cast<RooSimultaneous const *>(&func)) {
2622 exportSimultaneous(*simPdf);
2623 return;
2624 } else if (dynamic_cast<RooAbsCategory const *>(&func)) {
2625 // Categories are not objects of the document: the index category of a RooSimultaneous is declared by the
2626 // categorical axes of the domain that its "columns" name.
2627 return;
2628 } else if (dynamic_cast<RooRealVar const *>(&func) || dynamic_cast<RooConstVar const *>(&func)) {
2629 exportVariable(&func, _export->doc.parameterPoints.front());
2630 return;
2631 } else if (config().exportArrayDist && func.getAttribute(arrayDistTag)) {
2632 // An array distribution (HS3 `array_dist`): its components are registered here, and the array is written at
2633 // the end of the export, see exportAsArrayComponent().
2634 auto const *prod = dynamic_cast<RooProdPdf const *>(&func);
2635 if (!prod) {
2636 error("'" + name + "' has the attribute '" + arrayDistTag +
2637 "' of an array distribution, but it is not a RooProdPdf");
2638 }
2639 for (RooAbsPdf *pdf : static_range_cast<RooAbsPdf *>(prod->pdfList())) {
2640 const std::string writtenIn = exportAsArrayComponent(*pdf, name);
2641 if (writtenIn == name) {
2642 continue;
2643 }
2644 // A component of another array distribution: HS3 composes array distributions by union, so a component
2645 // written in several of them is one factor. It is written in this one as well.
2646 if (writtenIn != pdf->GetName() && _export->arrayComponents.count(writtenIn)) {
2647 auto &components = _export->arrayComponents[name];
2648 if (components.empty()) {
2649 _export->exportedObjectNames.insert(name);
2650 }
2651 components.push_back(pdf);
2652 continue;
2653 }
2654 error("cannot write '" + name + "' as an array distribution: its component '" + pdf->GetName() +
2655 "' is already written as '" + writtenIn + "'");
2656 }
2657 return;
2658 }
2659
2660 // HS3 lists some resolution models as functions.
2661 const bool isPdf = dynamic_cast<RooAbsPdf const *>(&func) && !func.InheritsFrom("RooGaussModel") &&
2662 !func.InheritsFrom("RooTruthModel");
2663 auto &collectionNode = (*_export->root)[isPdf ? "distributions" : "functions"];
2664
2665 auto const &exporters = RooFit::JSONIO::exporters();
2666
2667 TClass *cl = func.IsA();
2668
2669 auto &elem = appendNamedChild(collectionNode, name);
2670
2671 auto it = exporters.find(cl);
2672 if (it != exporters.end()) { // check if we have a specific exporter available
2673 for (auto &exp : it->second) {
2674 _serversToExport.clear();
2675 _serversToDelete.clear();
2676 if (!exp->exportObject(this, &func, elem)) {
2677 // The exporter might have messed with the content of the node
2678 // before failing. That's why we clear it and only reset the name.
2679 elem.clear();
2680 elem.set_map();
2681 elem["name"] << name;
2682 continue;
2683 }
2684 // Objects that are interpreted by the document are written here, the others were written by the exporter.
2685 if (_export->typedObject) {
2686 HS3::writeHistFactoryDist(elem, *_export->typedObject);
2687 elem["name"] << name;
2688 _export->doc.distributions.push_back({name, std::move(*_export->typedObject)});
2689 _export->typedObject.reset();
2690 if (!_export->channelConstraints.empty()) {
2691 _export->doc.rooFit.channelConstraints[name] = std::move(_export->channelConstraints);
2692 }
2693 _export->channelConstraints.clear();
2694 } else {
2695 recordGenericObject(_export->doc, isPdf, name, elem);
2696 }
2697 if (exp->autoExportDependants()) {
2698 exportObjects(func.servers());
2699 } else {
2701 }
2702 for (auto &s : _serversToDelete) {
2703 delete s;
2704 }
2705 return;
2706 }
2707 }
2708
2709 std::cerr << "unable to export '" << name << "' of class '" << cl->GetName()
2710 << "': no exporter is registered for this class, or none of them could handle the object. Check "
2711 "https://root.cern/doc/master/group__roofit__dev__docs__hs3.html to see how to write one!\n";
2712}
2713
2715{
2716 return _export->rootName;
2717}
2718
2719std::string RooJSONFactoryWSTool::exportAsArrayComponent(RooAbsPdf const &pdf, std::string const &arrayName)
2720{
2721 const std::string pdfName = pdf.GetName();
2722 auto &arrayOfComponent = _export->arrayOfComponent;
2723 auto &arrayComponents = _export->arrayComponents;
2724 auto &exportedObjectNames = _export->exportedObjectNames;
2725 if (auto it = arrayOfComponent.find(pdfName); it != arrayOfComponent.end()) {
2726 return it->second;
2727 }
2728 // Already written on its own: it is referenced by its name.
2729 if (exportedObjectNames.find(pdfName) != exportedObjectNames.end()) {
2730 return pdfName;
2731 }
2732 if (arrayComponents.find(arrayName) == arrayComponents.end()) {
2733 RooAbsArg const *existing = _workspace.arg(arrayName);
2734 if (existing && !existing->getAttribute(arrayDistTag)) {
2735 error("cannot write the array distribution '" + arrayName +
2736 "': the workspace has another object of that name");
2737 }
2738 exportedObjectNames.insert(arrayName);
2739 }
2740 arrayComponents[arrayName].push_back(&pdf);
2741 arrayOfComponent[pdfName] = arrayName;
2742 exportedObjectNames.insert(pdfName);
2743 return arrayName;
2744}
2745
2746// Write the array distributions registered with exportAsArrayComponent(), in alphabetical order, each followed by the
2747// servers of its components. They are generic objects of the document.
2749{
2750 std::set<std::string> written;
2751 auto &arrayComponents = _export->arrayComponents;
2752 for (;;) {
2753 auto next = std::find_if(arrayComponents.begin(), arrayComponents.end(),
2754 [&](auto const &item) { return written.find(item.first) == written.end(); });
2755 if (next == arrayComponents.end()) {
2756 break;
2757 }
2758 const std::string arrayName = next->first;
2759 written.insert(arrayName);
2760 // Exporting the servers may add to the registry, so the components are copied.
2761 const std::vector<RooAbsPdf const *> components = next->second;
2762 JSONNode &elem = appendNamedChild((*_export->root)["distributions"], arrayName);
2763 writeArrayDist(*this, elem, arrayName, components);
2764 recordGenericObject(_export->doc, true, arrayName, elem);
2765 for (RooAbsPdf const *pdf : components) {
2766 exportObjects(pdf->servers());
2767 }
2768 }
2769}
2770
2771void RooJSONFactoryWSTool::setConstraintObservable(RooAbsPdf const &pdf, std::string const &observable)
2772{
2773 _export->constraintObservables[pdf.GetName()] = observable;
2774}
2775
2776std::string const *RooJSONFactoryWSTool::constraintObservable(std::string const &pdfName) const
2777{
2778 if (!_export) {
2779 return nullptr;
2780 }
2781 auto found = _export->constraintObservables.find(pdfName);
2782 return found == _export->constraintObservables.end() ? nullptr : &found->second;
2783}
2784
2785void RooJSONFactoryWSTool::recordConstraintTerms(std::string const &pdfName, std::vector<std::string> const &terms)
2786{
2787 auto &out = _export->constraintTermsOfPdf[pdfName];
2788 for (auto const &term : terms) {
2789 addUnique(out, term);
2790 }
2791}
2792
2793// Write the data set `dataName` with the observed values of the observables of the constraint term `term` (an
2794// array distribution written in this export, or a single constraint pdf) and return true, or return false if the
2795// observables of the term are not all global observables of the model.
2796bool RooJSONFactoryWSTool::exportConstraintData(std::string const &term, RooArgSet const *globalObservables,
2797 std::string const &dataName)
2798{
2799 std::vector<RooAbsPdf const *> components;
2800 if (auto found = _export->arrayComponents.find(term); found != _export->arrayComponents.end()) {
2801 components = found->second;
2802 } else if (auto const *product = dynamic_cast<RooProdPdf const *>(_workspace.pdf(term))) {
2803 // A product of constraint terms: its factors.
2804 for (RooAbsArg const *factor : product->pdfList()) {
2805 components.push_back(static_cast<RooAbsPdf const *>(factor));
2806 }
2807 } else if (RooAbsPdf *pdf = _workspace.pdf(term)) {
2808 components.push_back(pdf);
2809 }
2810 std::vector<std::string> observables;
2811 for (RooAbsPdf const *pdf : components) {
2812 auto info = arrayComponentInfo(*pdf, constraintObservable(pdf->GetName()));
2813 if (!info || !globalObservables || !globalObservables->find(info->observable.c_str())) {
2814 return false;
2815 }
2816 observables.push_back(info->observable);
2817 }
2818 if (observables.empty()) {
2819 return false;
2820 }
2821 if (!_export->writtenConstraintData.insert(dataName).second) {
2822 return true;
2823 }
2824 if (_workspace.data(dataName)) {
2825 error("cannot write the observed values of the constraint term '" + term + "' as the data set '" + dataName +
2826 "': the workspace has a data set of that name");
2827 }
2829 for (std::string const &name : observables) {
2830 auto const *var = dynamic_cast<RooAbsReal const *>(_workspace.arg(name));
2831 if (!var) {
2832 error("the observable '" + name + "' of the constraint term '" + term + "' is not in the workspace");
2833 }
2834 // A range without a bound leaves the bound out, which means that the axis is unbounded there.
2836 axis.name = name;
2837 if (auto const *rrv = dynamic_cast<RooRealVar const *>(var)) {
2838 axis = toContinuousAxis(*rrv);
2839 }
2840 data.axes.emplace_back(std::move(axis));
2841 data.entries.push_back(var->getVal());
2842 }
2843 // The observed value of a single observable is point data.
2844 if (data.axes.size() == 1) {
2845 HS3::PointData point;
2846 point.value = data.entries.front();
2847 point.axes.push_back(std::get<HS3::ContinuousAxis>(data.axes.front()));
2848 _export->doc.data.push_back({dataName, std::move(point)});
2849 return true;
2850 }
2851 _export->doc.data.push_back({dataName, std::move(data)});
2852 return true;
2853}
2854
2855/**
2856 * @brief Export a RooSimultaneous as a "combined_dist".
2857 *
2858 * The components are selected by a key with one label per column. The columns are the index category of the
2859 * RooSimultaneous or, for a RooSuperCategory index, its input categories, sorted by name. They are declared as
2860 * categorical axes of the default domain. States without a pdf are not written: HS3 does not require a component
2861 * for every key.
2862 */
2864{
2865 RooAbsCategory const &indexCat = simPdf.indexCat();
2866 std::vector<RooCategory const *> columns = selectionColumns(indexCat);
2867
2868 // The distribution takes its place among the distributions here, and is written at the end of the export.
2869 appendNamedChild((*_export->root)["distributions"], simPdf.GetName());
2870 HS3::CombinedDist combined;
2871 for (RooCategory const *column : columns) {
2872 combined.columns.push_back(column->GetName());
2873 recordCategory(*column);
2874 }
2875 // Components with renamed observables replace the original ones (Config::renameCombinedObservables).
2876 auto renamed = _renamedComponents.find(simPdf.GetName());
2877 std::set<RooAbsArg const *> replaced;
2878 std::vector<RooAbsArg const *> replacements;
2879 // In the order of the columns and of their states, which is the order in which the categories are written to
2880 // the domain. This does not depend on the order of the inputs of a RooSuperCategory, so the document is the same
2881 // after a round trip.
2882 for (std::vector<std::string> const &key : selectionKeys(columns)) {
2883 const std::string label = selectionLabel(indexCat, columns, key);
2884 RooAbsPdf const *pdf = simPdf.getPdf(label);
2885 if (!pdf) {
2886 continue;
2887 }
2888 if (renamed != _renamedComponents.end()) {
2889 auto found = renamed->second.find(label);
2890 if (found != renamed->second.end()) {
2891 replaced.insert(pdf);
2892 pdf = found->second;
2893 replacements.push_back(pdf);
2894 }
2895 }
2896 combined.components.push_back({key, {pdf->GetName()}});
2897 }
2898 _export->doc.distributions.push_back({simPdf.GetName(), std::move(combined)});
2899
2900 std::vector<RooAbsArg const *> servers;
2901 for (RooAbsArg const *server : simPdf.servers()) {
2902 if (replaced.count(server) == 0) {
2903 servers.push_back(server);
2904 }
2905 }
2906 servers.insert(servers.end(), replacements.begin(), replacements.end());
2907 exportObjects(servers);
2908}
2909
2910// Declare a category as a categorical axis of the "default_domain". The states are written in their insertion order:
2911// this is the order of the bins of a RooDataHist over the category, and the position becomes the index when the
2912// document is read back.
2914{
2915 HS3::CategoricalAxis axis = toCategoricalAxis(cat);
2916 auto found = _export->categories.find(axis.name);
2917 if (found != _export->categories.end() && found->second.categories != axis.categories) {
2918 RooJSONFactoryWSTool::error("the category '" + axis.name +
2919 "' is written to the domain twice, with different states");
2920 }
2921 _export->categories[axis.name] = std::move(axis);
2922}
2923
2924/// Import the function or distribution `p` into the workspace, with the importers that are registered for its type.
2925/// If `importAllDependants` is false, `p` is a fragment of a document, whose own "functions" and "distributions" are
2926/// imported first.
2927void RooJSONFactoryWSTool::importFunction(const JSONNode &p, bool importAllDependants)
2928{
2929 // To report the components that no importer understands.
2930 const RooFit::Detail::JSONReadRecorder recorder{p};
2931 std::string name(RooJSONFactoryWSTool::name(p));
2932
2933 // If this node if marked to be skipped by RooFit, exit
2934 if (hasAttribute(name, "roofit_skip")) {
2935 return;
2936 }
2937
2938 auto const &importers = RooFit::JSONIO::importers();
2939
2941
2942 if (_workspace.arg(name)) {
2943 return;
2944 }
2945 ImportGuard importGuard{_importStack, name};
2946 if (!p.is_map()) {
2947 RooJSONFactoryWSTool::error("RooJSONFactoryWSTool() function node " + name + " is not a map!");
2948 }
2949 std::string prefix = genPrefix(p, true);
2950 if (!prefix.empty())
2951 name = prefix + name;
2952 if (!p.has_child("type")) {
2953 RooJSONFactoryWSTool::error("RooJSONFactoryWSTool() no type given for function '" + name + "', skipping.");
2954 }
2955
2956 std::string functype(p["type"].val());
2957
2958 // import all dependents if importing a workspace, not for creating new objects
2959 if (!importAllDependants) {
2960 this->importDependants(p);
2961 }
2962
2963 auto it = importers.find(functype);
2964 bool ok = false;
2965 if (it != importers.end()) {
2966 for (auto &imp : it->second) {
2967 ok = imp->importArg(this, p);
2968 if (ok)
2969 break;
2970 }
2971 }
2972 if (!ok) {
2974 "RooJSONFactoryWSTool() no handling for type '" + functype +
2975 "' implemented. Check https://root.cern/doc/master/group__roofit__dev__docs__hs3.html "
2976 "to see how to write an importer for it!");
2977 }
2979 if (!func) {
2980 RooJSONFactoryWSTool::error("something went wrong importing function '" + name + "'.");
2981 }
2982 for (std::string const &component : recorder.unreadComponents()) {
2983 warning("RooFitHS3: " + name + ": unknown component \"" + component + "\" is ignored");
2984 }
2985}
2986
2987// Import a distribution of the document, which is interpreted by the document or by the registered importers.
2989{
2990 if (auto const *generic = std::get_if<HS3::GenericObject>(&distribution.body)) {
2991 this->importFunction(*generic->node, true);
2992 return;
2993 }
2994 std::string const &name = distribution.name;
2995 if (hasAttribute(name, "roofit_skip")) {
2996 return;
2997 }
2999 if (_workspace.arg(name)) {
3000 return;
3001 }
3002 ImportGuard importGuard{_importStack, name};
3003 if (auto const *combined = std::get_if<HS3::CombinedDist>(&distribution.body)) {
3004 HS3::buildCombinedDist(*this, name, *combined, otherLikelihoodTerms(_import->document, name));
3005 return;
3006 }
3007 HS3::buildHistFactoryDist(*this, name, std::get<HS3::HistFactoryDist>(distribution.body));
3008}
3009
3010/// Import a function or distribution that is given as a JSON string, see the overload for a JSONNode.
3011void RooJSONFactoryWSTool::importFunction(const std::string &jsonString, bool importAllDependants)
3012{
3013 this->importFunction((JSONTree::create(jsonString))->rootnode(), importAllDependants);
3014}
3015
3016/// Write the axes and the `n` bin contents of a histogram over the variables `vars`, which are RooRealVars or
3017/// RooCategories, in the order of the variables.
3018void RooJSONFactoryWSTool::exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, JSONNode &output)
3019{
3020 HS3::writeBinnedData(output, toBinnedData(vars, n, contents));
3021}
3022
3023/// Write `n` numbers as an array, each as an integer if it has no fractional part. RooFit doesn't use this function
3024/// itself, but exporters outside of ROOT do.
3025void RooJSONFactoryWSTool::exportArray(std::size_t n, double const *contents, JSONNode &output)
3026{
3027 HS3::writeContents(output, std::vector<double>(contents, contents + n));
3028}
3029
3030// Config::renameCombinedObservables: work out, before anything is exported, the new names of the observables of
3031// every combined data set, and the components of the matching RooSimultaneous with these observables. One
3032// observable per key is named "obs_<key>", several are named "obs_<key>_<observable>". Observables that already
3033// have their new name are left alone, so that a second export of an imported document gives the same result.
3035{
3037 _renamedComponents.clear();
3038 _renamedObjects.clear();
3039 if (!config().renameCombinedObservables) {
3040 return;
3041 }
3042 std::vector<RooAbsData *> datasets;
3043 for (RooAbsData *data : _workspace.allData()) {
3044 datasets.push_back(data);
3045 }
3046 sortByName(datasets);
3047 for (RooAbsData const *data : datasets) {
3048 std::vector<RooCategory const *> columns = selectionColumns(*data->get());
3049 if (columns.empty()) {
3050 continue;
3051 }
3052 RooSimultaneous const *simPdf = findMatchingSimultaneous(_workspace, namesOf(selectionColumns(*data->get())));
3053 for (std::vector<std::string> const &key : selectionKeys(columns)) {
3054 const std::string keyName = selectionKeyName(key);
3055 RooArgSet candidates;
3056 RooAbsPdf const *component = nullptr;
3057 std::string label;
3058 if (simPdf) {
3059 label = selectionLabel(simPdf->indexCat(), columns, key);
3060 component = simPdf->getPdf(label);
3061 if (!component) {
3062 continue;
3063 }
3064 std::unique_ptr<RooArgSet> observables{component->getObservables(*data->get())};
3065 candidates.add(*observables);
3066 } else {
3067 candidates.add(*data->get());
3068 }
3069 std::vector<RooAbsArg *> observables;
3070 for (RooAbsArg *arg : candidates) {
3071 if (!dynamic_cast<RooAbsCategory *>(arg)) {
3072 observables.push_back(arg);
3073 }
3074 }
3075 sortByName(observables);
3076 std::map<std::string, std::string> renames;
3077 for (RooAbsArg const *obs : observables) {
3078 std::string const newName =
3079 "obs_" + keyName + (observables.size() == 1 ? "" : "_" + std::string(obs->GetName()));
3080 if (newName == obs->GetName()) {
3081 continue;
3082 }
3083 if (_workspace.arg(newName.c_str())) {
3084 error("can't rename the observable '" + std::string(obs->GetName()) + "' of the data set '" +
3085 data->GetName() + "' to '" + newName + "': an object of that name already exists");
3086 }
3087 renames[obs->GetName()] = newName;
3088 }
3089 if (renames.empty()) {
3090 continue;
3091 }
3092 _combinedObservableRenames[data->GetName()][keyName] = renames;
3093 if (!simPdf || _renamedComponents[simPdf->GetName()].count(label) > 0) {
3094 continue;
3095 }
3096 // The component with the renamed observables. Nodes that depend on them are cloned with the suffix
3097 // "_<key>", so that nodes shared by several components get one copy per component.
3098 RooCustomizer customizer{*component, keyName.c_str()};
3099 for (auto const &[from, to] : renames) {
3100 RooAbsArg *original = candidates.find(from.c_str());
3101 _renamedObjects.emplace_back(static_cast<RooAbsArg *>(original->clone(to.c_str())));
3102 customizer.replaceArg(*original, *_renamedObjects.back());
3103 }
3104 auto *renamedComponent = static_cast<RooAbsPdf *>(customizer.build());
3105 _renamedObjects.emplace_back(renamedComponent);
3106 _renamedComponents[simPdf->GetName()][label] = renamedComponent;
3107 }
3108 }
3109}
3110
3111/**
3112 * @brief Export a data set with category observables as a "combined" data set.
3113 *
3114 * The categories are the columns, sorted by name, and are declared as categorical axes of the default domain. There
3115 * is one sub-data set per key, i.e. per combination of states, written like any other data set and named after the
3116 * data set and the labels of the key. A key is written also without entries: RooFit treats a channel without entries
3117 * as present and empty. If the workspace has a RooSimultaneous with the same columns, each sub-data set only carries
3118 * the observables of the corresponding component, and keys without entries for which it has no component are left
3119 * out; otherwise, every sub-data set carries all observables.
3120 */
3122{
3123 std::vector<RooCategory const *> columns = selectionColumns(*data.get());
3124 std::string const name = data.GetName();
3125 HS3::CombinedData combined;
3126 for (RooCategory const *column : columns) {
3127 combined.columns.push_back(column->GetName());
3128 recordCategory(*column);
3129 }
3130
3131 // Split the data by the key: by the index category of a matching RooSimultaneous, or by the columns themselves.
3132 RooSimultaneous const *simPdf = findMatchingSimultaneous(_workspace, combined.columns);
3133 std::unique_ptr<RooSuperCategory> superCat;
3134 RooAbsCategory const *indexCat = nullptr;
3135 std::vector<std::unique_ptr<RooAbsData>> parts;
3136 if (simPdf) {
3137 indexCat = &simPdf->indexCat();
3138 parts = data.split(*simPdf, true);
3139 } else if (columns.size() == 1) {
3140 indexCat = columns.front();
3141 parts = data.split(*indexCat, true);
3142 } else {
3143 RooArgSet inputs;
3144 for (RooCategory const *column : columns) {
3145 inputs.add(*column);
3146 }
3147 const std::string superName = name + "_key";
3148 superCat = std::make_unique<RooSuperCategory>(superName.c_str(), superName.c_str(), inputs);
3149 indexCat = superCat.get();
3150 parts = data.split(*indexCat, true);
3151 }
3152
3153 // The combined data set is written before its sub-data sets.
3154 std::vector<RooAbsData *> subDataSets;
3155 for (std::vector<std::string> const &key : selectionKeys(columns)) {
3156 std::string const label = selectionLabel(*indexCat, columns, key);
3157 auto found = std::find_if(parts.begin(), parts.end(), [&](auto &d) { return d->GetName() == label; });
3158 if (found == parts.end() || ((*found)->numEntries() == 0 && simPdf && !simPdf->getPdf(label))) {
3159 continue;
3160 }
3161 const std::string keyName = selectionKeyName(key);
3162 const std::string subName = name + "_" + keyName;
3163 (*found)->SetName(subName.c_str());
3164 // Config::renameCombinedObservables: give the observables of this key their own names.
3165 auto renamesOfData = _combinedObservableRenames.find(name);
3166 if (renamesOfData != _combinedObservableRenames.end()) {
3167 auto renames = renamesOfData->second.find(keyName);
3168 if (renames != renamesOfData->second.end()) {
3169 for (auto const &[from, to] : renames->second) {
3170 (*found)->changeObservableName(from.c_str(), to.c_str());
3171 }
3172 }
3173 }
3174 combined.components.push_back({key, {subName}});
3175 subDataSets.push_back(found->get());
3176 }
3177 _export->doc.data.push_back({name, std::move(combined)});
3178 for (RooAbsData *subData : subDataSets) {
3179 exportData(*subData);
3180 }
3181}
3182
3183// Export a single dataset `data` (binned or unbinned) to the output document.
3185{
3186 for (RooAbsArg const *obs : *data.get()) {
3187 if (dynamic_cast<RooAbsCategory const *>(obs) && !dynamic_cast<RooCategory const *>(obs)) {
3188 error("the data set '" + std::string(data.GetName()) + "' has the categorical observable '" + obs->GetName() +
3189 "', which is not a RooCategory, and can't be written as a combined data set");
3190 }
3191 }
3192
3193 auto write = [&](auto body) { _export->doc.data.push_back({data.GetName(), std::move(body)}); };
3194
3195 // This works around a problem in RooStats/HistFactory that was only fixed
3196 // in ROOT 6.30: until then, the weight variable of the observed dataset,
3197 // called "weightVar", was added to the observables. Therefore, it also got
3198 // added to the Asimov dataset. But the Asimov has its own weight variable,
3199 // called "binWeightAsimov", making "weightVar" an actual observable in the
3200 // Asimov data. But this is only by accident and should be removed.
3201 RooArgSet variables = *data.get();
3202 if (auto weightVar = variables.find("weightVar")) {
3203 variables.remove(*weightVar);
3204 }
3205
3206 // The ranges of the variables are written to the domains. Categories are declared by a categorical axis of the
3207 // default domain.
3208 for (RooAbsArg const *arg : variables) {
3209 if (auto const *cat = dynamic_cast<RooCategory const *>(arg)) {
3210 recordCategory(*cat);
3211 } else {
3212 recordDomains(_export->domains, static_cast<RooRealVar const &>(*arg));
3213 }
3214 }
3215
3216 // this is a regular binned dataset
3217 if (auto dh = dynamic_cast<RooDataHist const *>(&data)) {
3218 return write(toBinnedData(variables, dh->numEntries(), dh->weightArray()));
3219 }
3220
3221 // Check if this actually represents a binned dataset, and then import it
3222 // like a RooDataHist. This happens frequently when people create combined
3223 // RooDataSets from binned data to fit HistFactory models. In this case, it
3224 // doesn't make sense to export them like an unbinned dataset, because the
3225 // coordinates are redundant information with the binning. We only do this
3226 // for 1D data for now. A variable without bins can't be binned data: unbinned data sets leave their axes without
3227 // binning, and would otherwise be written as binned once they have no entries.
3228 if (data.isWeighted() && variables.size() == 1 && dynamic_cast<RooRealVar const *>(variables[0]) &&
3229 static_cast<RooRealVar const &>(*variables[0]).getBins() > 0) {
3230 auto &x = static_cast<RooRealVar const &>(*variables[0]);
3231 std::vector<double> contents;
3232 int i = 0;
3233 for (; i < data.numEntries(); ++i) {
3234 data.get(i);
3235 if (x.getBin() != i)
3236 break;
3237 contents.push_back(data.weight());
3238 }
3239 // Binned data has exactly one entry per bin, in the order of the bins. Further entries, e.g. a second one in
3240 // the last bin, make it unbinned data.
3241 if (i == x.getBins() && data.numEntries() == x.getBins()) {
3242 return write(toBinnedData(variables, contents.size(), contents.data()));
3243 }
3244 }
3245
3246 // A single unweighted entry of a single variable is point data.
3247 if (variables.size() == 1 && data.numEntries() == 1) {
3248 data.get(0);
3249 auto const *var = dynamic_cast<RooRealVar const *>(variables[0]);
3250 if (var && (!data.isWeighted() || data.weight() == 1.)) {
3251 HS3::PointData point;
3252 point.value = var->getVal();
3253 point.axes.push_back(toContinuousAxis(*var));
3254 return write(std::move(point));
3255 }
3256 }
3257
3258 // this really is an unbinned dataset
3259 HS3::UnbinnedData unbinned;
3260 for (RooAbsArg const *arg : variables) {
3261 testValidName(arg->GetName(), false);
3262 if (auto const *cat = dynamic_cast<RooCategory const *>(arg)) {
3263 unbinned.axes.emplace_back(toCategoricalAxis(*cat));
3264 } else {
3265 // HS3 forbids binning information on the axes of unbinned data.
3266 auto const &var = static_cast<RooRealVar const &>(*arg);
3267 unbinned.axes.emplace_back(toContinuousAxis(var));
3268 }
3269 }
3270 std::vector<double> weights;
3271 for (int i = 0; i < data.numEntries(); ++i) {
3272 data.get(i);
3273 // The entries of a categorical axis are the positions of the labels in its "categories".
3274 for (RooAbsArg const *arg : variables) {
3275 if (auto const *cat = dynamic_cast<RooCategory const *>(arg)) {
3276 unbinned.entries.push_back(cat->getCurrentOrdinalNumber());
3277 } else {
3278 unbinned.entries.push_back(static_cast<RooRealVar const *>(arg)->getVal());
3279 }
3280 }
3281 weights.push_back(data.weight());
3282 }
3283 // Weights that are all one are not written.
3284 if (std::any_of(weights.begin(), weights.end(), [](double weight) { return weight != 1.; })) {
3285 unbinned.weights = std::move(weights);
3286 }
3287 write(std::move(unbinned));
3288}
3289
3290/// Create the variables for the "axes" of `topNode`, which are owned by the returned set.
3292{
3293 HS3::Diagnostics diagnostics;
3294 std::vector<HS3::BinnedAxis> axes = HS3::parseBinnedAxes(topNode["axes"], diagnostics);
3295 HS3::report(diagnostics);
3296 return HS3::createObservables(axes);
3297}
3298
3299/// Create a RooDataHist with the name `name` over the variables `vars` from the "contents" of `n`, and its "errors"
3300/// if it has any.
3301std::unique_ptr<RooDataHist>
3302RooJSONFactoryWSTool::readBinnedData(const JSONNode &n, const std::string &name, RooArgSet const &vars)
3303{
3304 if (!n.has_child("contents"))
3305 RooJSONFactoryWSTool::error("no contents given");
3306
3307 JSONNode const &contents = n["contents"];
3308
3309 if (!contents.is_seq())
3310 RooJSONFactoryWSTool::error("contents are not in list form");
3311
3312 std::vector<double> contentVals;
3313 contentVals << contents;
3314
3315 if (!n.has_child("errors")) {
3316 return HS3::createDataHist(name, vars, contentVals, nullptr);
3317 }
3318 if (!n["errors"].is_seq())
3319 RooJSONFactoryWSTool::error("errors are not in list form");
3320 std::vector<double> errorVals;
3321 errorVals << n["errors"];
3322 return HS3::createDataHist(name, vars, contentVals, &errorVals);
3323}
3324
3325// Import a single variable (RooRealVar or RooConstVar) from the parameter `p` into the workspace.
3327{
3329
3330 if (_workspace.arg(p.name))
3331 return;
3332 // A string selects the state of a category, which is done together with the other parameter points.
3333 if (p.value && std::holds_alternative<std::string>(*p.value))
3334 return;
3335 if (!_import->ranges.contains(p.name)) {
3336 // ROOT versions before HS3 0.3 marked named RooConstVars with an attribute.
3337 auto const &attributes = _import->document.rooFit.attributes;
3338 auto found = attributes.find(p.name);
3339 if (found != attributes.end() && found->second.isConstVar) {
3340 if (!p.value) {
3341 RooJSONFactoryWSTool::error("cannot instantiate RooConstVar '" + p.name + "' without \"value\"!");
3342 }
3343 wsEmplace<RooConstVar>(p.name, std::get<double>(*p.value));
3344 return;
3345 }
3346 }
3347 RooRealVar &var = wsEmplace<RooRealVar>(p.name, 1.);
3348 configureVariable(_import->ranges, p, var);
3350}
3351
3352// HS3 requires every parameter to be listed in a domain or constant ("const": true) in the parameter point.
3354{
3355 if (!var.isConstant() && !_import->ranges.contains(var.GetName())) {
3356 warning(std::string("RooFitHS3: the parameter '") + var.GetName() +
3357 "' is not listed in any domain and is not constant: HS3 requires a domain, or \"const\": true. It "
3358 "is read as a free parameter without range.");
3359 }
3360}
3361
3362// Import the objects of a fragment of a document, for which the node `n` plays the role of the document.
3364{
3365 for (const char *section : {"functions", "distributions"}) {
3366 if (auto seq = n.find(section)) {
3367 for (const auto &p : seq->children()) {
3368 this->importFunction(p, true);
3369 }
3370 }
3371 }
3372}
3373
3374// Export a ModelConfig as one analysis for every data set that goes with its pdf, or as one without data.
3376 const std::vector<RooAbsData *> &singleDataSets)
3377{
3378 std::vector<std::string> dataNames;
3379 if (auto simpdf = dynamic_cast<RooSimultaneous const *>(mc.GetPdf())) {
3380 // The combined data sets with the same columns.
3381 const std::vector<std::string> columns = namesOf(selectionColumns(simpdf->indexCat()));
3382 for (HS3::Data const &data : _export->doc.data) {
3383 auto const *combined = std::get_if<HS3::CombinedData>(&data.body);
3384 if (combined && combined->columns == columns) {
3385 dataNames.push_back(data.name);
3386 }
3387 }
3388 } else {
3389 for (RooAbsData const *data : singleDataSets) {
3390 if (mc.GetObservables()->equals(*data->get())) {
3391 dataNames.push_back(data->GetName());
3392 }
3393 }
3394 }
3395 // The analyses are named after the ModelConfig, so that ModelConfigs sharing a pdf and a data set (like an S+B
3396 // and B-only pair) get separate analyses.
3397 for (std::string const &dataName : dataNames) {
3398 exportSingleModelConfig(mc, std::string(mc.GetName()) + "_" + dataName, &dataName);
3399 }
3400 if (dataNames.empty()) {
3401 exportSingleModelConfig(mc, mc.GetName(), nullptr);
3402 }
3403}
3404
3405namespace {
3406
3407// The channels of the pdf of a ModelConfig as they are written: the pdf itself, or the components of a RooSimultaneous,
3408// of which those in `renamed` (by label) replace the original ones (Config::renameCombinedObservables).
3409std::vector<RooAbsPdf const *> channelsOf(RooAbsPdf const &pdf, std::map<std::string, RooAbsPdf const *> const &renamed)
3410{
3411 auto const *simPdf = dynamic_cast<RooSimultaneous const *>(&pdf);
3412 if (!simPdf) {
3413 return {&pdf};
3414 }
3415 std::vector<RooAbsPdf const *> channels;
3416 for (auto const &item : simPdf->indexCat()) {
3417 auto found = renamed.find(item.first);
3418 if (RooAbsPdf const *component = found != renamed.end() ? found->second : simPdf->getPdf(item.first)) {
3419 channels.push_back(component);
3420 }
3421 }
3422 return channels;
3423}
3424
3425// A constraint term of a channel of the pdf of a ModelConfig, see constraintsOfChannels().
3426struct ChannelConstraint {
3427 std::string channel;
3428 RooAbsPdf const *constraint = nullptr;
3429 bool histFactory = false; ///< Whether the channel is written as a histfactory_dist.
3430 /// Whether the channel consists of constraint terms only; `constraint` is then the channel itself.
3431 bool wholeChannel = false;
3432};
3433
3434// The constraint terms of the pdf `pdf` of a ModelConfig with the observables `observables`, which are written as
3435// terms of the likelihood: the constraints that RooFit finds (RooAbsPdf::getAllConstraints()) and that are factors
3436// of a channel, i.e. of `pdf` itself or of a component of the RooSimultaneous `pdf`. In RooFit, constraints are
3437// factors of the channels, and RooFit counts each once, also if several channels share it; in HS3, they are terms
3438// of the likelihood.
3439// - The channels that are written as histfactory_dist (`isHistFactoryChannel`) don't contain their constraints in
3440// the document; their modifiers refer to them. Nested products of their constraint terms are expanded into the
3441// factors, which the HistFactory exporter writes as terms of their own.
3442// - The constraints of a channel that is written as product_dist are taken out of the product by
3443// writeLikelihoodTermsOnce(). This is only done if no other object of the workspace uses the product, so the
3444// constraints of other products are not returned.
3445// Constraints elsewhere, e.g. in a nested product, stay where they are. The channels are taken as they are written,
3446// see channelsOf().
3447std::vector<ChannelConstraint>
3448constraintsOfChannels(RooWorkspace const &ws, RooAbsPdf const &pdf, RooArgSet const &observables,
3449 std::function<bool(std::string const &)> const &isHistFactoryChannel,
3450 std::vector<RooAbsPdf const *> const &channels)
3451{
3452 RooArgSet params;
3453 pdf.getParameters(&observables, params);
3454 std::unique_ptr<RooArgSet> constraints{pdf.getAllConstraints(observables, params, /*stripDisconnected=*/false)};
3455 std::vector<ChannelConstraint> out;
3456 for (RooAbsPdf const *channel : channels) {
3457 auto const *prod = dynamic_cast<RooProdPdf const *>(channel);
3458 if (!prod) {
3459 continue;
3460 }
3461 const bool histFactory = isHistFactoryChannel(prod->GetName());
3462 // A channel that consists of constraint terms only is an auxiliary measurement that is part of the model. It
3463 // is written as that channel, once, and not as constraint terms of the likelihood.
3464 if (!histFactory && !prod->pdfList().empty() &&
3465 std::all_of(prod->pdfList().begin(), prod->pdfList().end(),
3466 [&](RooAbsArg const *factor) { return constraints->find(*factor) != nullptr; })) {
3467 out.push_back({prod->GetName(), prod, false, true});
3468 continue;
3469 }
3470 if (!histFactory) {
3471 // Being a component of a RooSimultaneous, i.e. of a combined distribution, is not a use.
3472 bool usedElsewhere = false;
3473 for (RooAbsArg const *client : prod->clients()) {
3474 if (ws.arg(client->GetName()) == client && !dynamic_cast<RooSimultaneous const *>(client)) {
3475 usedElsewhere = true;
3476 }
3477 }
3478 if (usedElsewhere) {
3479 continue;
3480 }
3481 }
3482 std::function<void(RooAbsPdf const &)> add = [&](RooAbsPdf const &term) {
3483 auto const *nested = dynamic_cast<RooProdPdf const *>(&term);
3484 if (!histFactory || !nested) {
3485 out.push_back({prod->GetName(), &term, histFactory});
3486 return;
3487 }
3488 for (RooAbsArg const *factor : nested->pdfList()) {
3489 add(static_cast<RooAbsPdf const &>(*factor));
3490 }
3491 };
3492 for (RooAbsArg const *factor : prod->pdfList()) {
3493 if (constraints->find(*factor)) {
3494 add(static_cast<RooAbsPdf const &>(*factor));
3495 }
3496 }
3497 }
3498 return out;
3499}
3500
3501} // namespace
3502
3503void RooJSONFactoryWSTool::exportSingleModelConfig(RooFit::ModelConfig const &mc, std::string const &analysisName,
3504 std::string const *dataName)
3505{
3506 HS3Document &doc = _export->doc;
3507 auto pdf = mc.GetPdf();
3508
3509 HS3::Analysis analysis;
3510 analysis.name = analysisName;
3511
3512 // HS3 names must be unique across all top-level components, so the likelihood can't have the analysis name.
3513 HS3::Likelihood likelihood;
3514 likelihood.name = analysisName + "_likelihood";
3515 analysis.likelihood.name = likelihood.name;
3516
3517 if (dataName) {
3518 likelihood.terms.push_back({{pdf->GetName()}, HS3::DataRef{*dataName}});
3519 } else {
3520 // Without data, the likelihood is a pure model, which is written with "data": null.
3521 likelihood.terms.push_back({{pdf->GetName()}, std::monostate{}});
3522 likelihood.pureModel = true;
3523 }
3524
3525 // The additional terms of the likelihood: the external constraints of the ModelConfig, and the constraint terms
3526 // of the channels of the model, which can be the components of a combined distribution (constraintsOfChannels()).
3527 // They are listed in "aux_distributions" with the observed values of their observables as constant parameters, or
3528 // (config().exportConstraintData) in "distributions", each paired with a data set that holds the observed values.
3529 std::vector<RooAbsPdf const *> const channels = channelsOf(*pdf, _renamedComponents[pdf->GetName()]);
3530 // The channels of the model that consist of constraint terms only, see constraintsOfChannels().
3531 std::vector<std::string> auxiliaryChannelsOfModel;
3532 std::vector<std::string> constraintTerms;
3533 if (RooArgSet const *external = mc.GetExternalConstraints()) {
3534 // A component of an array distribution is written as part of the array, which enters the likelihood as a
3535 // whole: the external constraints must contain all of its components.
3536 for (const auto &constr : *external) {
3537 auto array = _export->arrayOfComponent.find(constr->GetName());
3538 if (array == _export->arrayOfComponent.end()) {
3539 addUnique(constraintTerms, constr->GetName());
3540 continue;
3541 }
3542 for (RooAbsPdf const *component : _export->arrayComponents[array->second]) {
3543 if (!external->find(*component)) {
3544 error("cannot write the external constraint '" + std::string(constr->GetName()) + "' of '" +
3545 mc.GetName() + "': it is written as a component of the array distribution '" + array->second +
3546 "', whose component '" + component->GetName() + "' is not an external constraint");
3547 }
3548 }
3549 addUnique(constraintTerms, array->second);
3550 }
3551 }
3552 // The constraint terms that the HistFactory exporter wrote for the channel `channel`, in the order of the document:
3553 // the constraints that the modifiers name, as written (e.g. array distributions), and those that no modifier
3554 // names.
3555 auto writtenByHistFactory = [&](std::string const &channel) {
3556 std::vector<std::string> out;
3557 if (auto found = _export->constraintTermsOfPdf.find(channel); found != _export->constraintTermsOfPdf.end()) {
3558 for (std::string const &term : found->second) {
3559 addUnique(out, term);
3560 }
3561 }
3562 if (auto found = doc.rooFit.channelConstraints.find(channel); found != doc.rooFit.channelConstraints.end()) {
3563 for (auto const &ref : found->second) {
3564 addUnique(out, ref.name);
3565 }
3566 }
3567 return out;
3568 };
3569 RooArgSet const *observables = mc.GetObservables();
3570 if (!observables || observables->empty()) {
3571 // Without observables (e.g. a ModelConfig without data), RooFit can't tell constraints from other pdfs: only the
3572 // constraint terms of the HistFactory channels are listed.
3573 for (RooAbsPdf const *channel : channels) {
3574 for (std::string const &term : writtenByHistFactory(channel->GetName())) {
3575 addUnique(constraintTerms, term);
3576 }
3577 }
3578 } else {
3579 auto isHistFactoryChannel = [&](std::string const &name) {
3580 return _export->constraintTermsOfPdf.count(name) || HS3::find<HS3::HistFactoryDist>(doc.distributions, name);
3581 };
3582 // The constraint terms of the channels as RooFit finds them, under the names under which they are written:
3583 // the array distribution that holds a constraint of a HistFactory channel, or the name of the constraint.
3584 std::map<std::string, std::vector<std::string>> termsOfChannel;
3585 for (ChannelConstraint const &item :
3586 constraintsOfChannels(_workspace, *pdf, *observables, isHistFactoryChannel, channels)) {
3587 if (item.wholeChannel) {
3588 auxiliaryChannelsOfModel.push_back(item.channel);
3589 continue;
3590 }
3591 // A component of an array distribution is never referred to by itself: the array is the term.
3592 std::string term = item.constraint->GetName();
3593 if (auto found = _export->arrayOfComponent.find(term); found != _export->arrayOfComponent.end()) {
3594 term = found->second;
3595 }
3596 addUnique(termsOfChannel[item.channel], term);
3597 }
3598 for (RooAbsPdf const *channelPdf : channels) {
3599 std::string const channel = channelPdf->GetName();
3600 std::vector<std::string> const &found = termsOfChannel[channel];
3601 if (!isHistFactoryChannel(channel)) {
3602 for (std::string const &term : found) {
3603 addUnique(constraintTerms, term);
3604 }
3605 continue;
3606 }
3607 // The constraint terms that the HistFactory exporter wrote must be the ones that RooFit finds, or a
3608 // constraint would be missing from the likelihood, or would be in it without being written. They are listed
3609 // in the order of the document, which doesn't depend on how the workspace was built.
3610 std::vector<std::string> const written = writtenByHistFactory(channel);
3611 std::set<std::string> const writtenSet{written.begin(), written.end()};
3612 std::set<std::string> const foundSet{found.begin(), found.end()};
3613 if (writtenSet != foundSet) {
3614 auto join = [](std::set<std::string> const &names) {
3615 std::string out;
3616 for (std::string const &name : names) {
3617 out += (out.empty() ? "'" : ", '") + name + "'";
3618 }
3619 return out.empty() ? std::string{"none"} : out;
3620 };
3621 error("cannot export the constraint terms of the HistFactory channel '" + channel +
3622 "': the channel writes " + join(writtenSet) + ", but RooFit finds " + join(foundSet));
3623 }
3624 for (std::string const &term : written) {
3625 addUnique(constraintTerms, term);
3626 }
3627 }
3628 }
3629 // An array of constraints with its data set is a measurement like the others: if the model is a combined
3630 // distribution, it is written as a component of it, paired with its data set as a component of the combined data
3631 // set. The combined distribution is then the sampling distribution of all measurements, auxiliary or not. Its
3632 // label is the name of the array. Constraints that are written one by one stay terms of the likelihood: there
3633 // can be hundreds, which is not what an index category is for. So do the constraints of models whose index has
3634 // several columns.
3635 auto const *simPdf = dynamic_cast<RooSimultaneous const *>(pdf);
3636 // Looked up when needed: writing the data set of a constraint term adds to the data sets of the document.
3637 auto findCombinedData = [&]() { return dataName ? HS3::find<HS3::CombinedData>(doc.data, *dataName) : nullptr; };
3638 RooCategory const *indexColumn = nullptr;
3639 if (simPdf && findCombinedData()) {
3640 std::vector<RooCategory const *> columns = selectionColumns(simPdf->indexCat());
3641 if (columns.size() == 1) {
3642 indexColumn = columns.front();
3643 }
3644 }
3645 auto addAuxiliaryChannel = [&](std::string const &term) {
3646 if (indexColumn->hasLabel(term)) {
3647 error("cannot write the constraint term '" + term + "' as a component of the combined distribution '" +
3648 simPdf->GetName() + "': its index category '" + indexColumn->GetName() + "' has a state of that name");
3649 }
3650 addUnique(_export->auxiliaryLabels[indexColumn->GetName()], term);
3651 auto *combinedDist = HS3::find<HS3::CombinedDist>(doc.distributions, simPdf->GetName());
3652 if (!combinedDist) {
3653 error("cannot write the constraint terms of '" + std::string(simPdf->GetName()) +
3654 "' as its components: it was not written as a combined distribution");
3655 }
3656 if (!combinedDist->find({term})) {
3657 combinedDist->components.push_back({{term}, {term}});
3658 doc.rooFit.auxiliaryChannels[simPdf->GetName()].push_back({term});
3659 }
3660 if (HS3::CombinedData *combinedData = findCombinedData(); !combinedData->find({term})) {
3661 combinedData->components.push_back({{term}, HS3::DataRef{*dataName + "_" + term}});
3662 }
3663 };
3664 // A channel of the model that consists of constraint terms is an auxiliary measurement, whose observed values are
3665 // the values of its global observables if the data set has no entries for it. It is written like the arrays
3666 // above: with a data set of the observed values, and marked for RooFit, which can read it as constraint terms.
3667 for (std::string const &channel : auxiliaryChannelsOfModel) {
3668 if (!indexColumn || likelihood.pureModel) {
3669 continue;
3670 }
3671 std::string label;
3672 for (auto const &state : simPdf->indexCat()) {
3673 RooAbsPdf const *component = simPdf->getPdf(state.first);
3674 if (component && channel == component->GetName()) {
3675 label = state.first;
3676 }
3677 }
3678 if (label.empty()) {
3679 continue;
3680 }
3681 auto const *component = findCombinedData()->find({label});
3682 const std::string observed = component ? component->ref.name : *dataName + "_" + label;
3683 // A data set without entries for the channel is replaced by the observed values.
3684 auto written = std::find_if(doc.data.begin(), doc.data.end(), [&](auto const &d) { return d.name == observed; });
3685 if (written == doc.data.end() || written->numEntries() == 0) {
3686 std::optional<HS3::Data> empty;
3687 if (written != doc.data.end()) {
3688 empty = std::move(*written);
3689 doc.data.erase(written);
3690 }
3691 if (exportConstraintData(channel, mc.GetGlobalObservables(), observed)) {
3692 if (HS3::CombinedData *combinedData = findCombinedData(); !combinedData->find({label})) {
3693 combinedData->components.push_back({{label}, HS3::DataRef{observed}});
3694 }
3695 } else {
3696 if (empty) {
3697 doc.data.push_back(std::move(*empty));
3698 }
3699 warning("RooFitHS3: the channel '" + channel + "' of '" + simPdf->GetName() +
3700 "' consists of constraint terms, but has no data, and its observables are not all global "
3701 "observables of the ModelConfig: it is written without an observation.");
3702 continue;
3703 }
3704 }
3705 auto &marked = doc.rooFit.auxiliaryChannels[simPdf->GetName()];
3706 if (!HS3::findByName(marked, channel)) {
3707 marked.push_back({channel});
3708 }
3709 }
3710 for (std::string const &term : constraintTerms) {
3711 // A pure model has no data at all, so the observed values of its constraint terms are not written as data sets
3712 // either: they are the constant parameters of auxiliary distributions.
3713 // A component of a combined data set belongs to that data set alone, and is named after it like the others.
3714 const bool asChannel = indexColumn && _export->arrayComponents.count(term);
3715 const std::string constraintData = asChannel ? *dataName + "_" + term : term + "_data";
3716 if (!likelihood.pureModel && config().exportConstraintData &&
3717 exportConstraintData(term, mc.GetGlobalObservables(), constraintData)) {
3718 if (asChannel) {
3719 addAuxiliaryChannel(term);
3720 } else {
3721 likelihood.terms.push_back({{term}, HS3::DataRef{constraintData}});
3722 }
3723 } else {
3724 likelihood.auxDistributions.push_back({term});
3725 }
3726 }
3727 doc.likelihoods.push_back(std::move(likelihood));
3728
3729 if (RooArgSet const *pois = mc.GetParametersOfInterest()) {
3730 std::vector<std::string> names = namesOf(*pois);
3731 std::sort(names.begin(), names.end());
3732 for (auto const &name : names) {
3733 analysis.parametersOfInterest.push_back({name});
3734 }
3735 }
3736
3737 auto writeProductDomain = [&](const char *suffix, RooArgSet const *args) {
3738 if (!args || args->empty())
3739 return;
3740 HS3::Domain &domain = doc.domains.emplace_back();
3741 domain.name = analysisName + suffix;
3742 analysis.domains.push_back({domain.name});
3743 RooArgList sorted{*args};
3744 sorted.sort();
3745 for (auto *var : static_range_cast<const RooRealVar *>(sorted)) {
3746 domain.axes.emplace_back(toDomainAxis(var->GetName(), var->getBinning()));
3747 }
3748 };
3749
3750 writeProductDomain("_nuisance_parameters", mc.GetNuisanceParameters());
3751 writeProductDomain("_global_observables", mc.GetGlobalObservables());
3752 writeProductDomain("_parameters_of_interest", mc.GetParametersOfInterest());
3753
3754 // The snapshots are exported as parameter points. Reference the one of the ModelConfig as the initial values.
3755 if (_workspace.getSnapshot(mc.GetSnapshotName().c_str())) {
3757 }
3758 // The prior is a top-level pdf of the workspace or a component of one, so it is exported already.
3759 if (RooAbsPdf const *prior = mc.GetPriorPdf()) {
3760 analysis.prior = HS3::DistributionRef{prior->GetName()};
3761 }
3762 doc.analyses.push_back(std::move(analysis));
3763
3764 HS3::ModelConfigInfo &info = doc.rooFit.modelConfigs[analysisName];
3765 info.pdfName = pdf->GetName();
3766 info.mcName = mc.GetName();
3767 // Without a data set, the document doesn't say what the observables are.
3768 if (!dataName && mc.GetObservables() && !mc.GetObservables()->empty()) {
3769 std::vector<std::string> names = namesOf(*mc.GetObservables());
3770 std::sort(names.begin(), names.end());
3771 info.observables = std::move(names);
3772 }
3773}
3774
3775// Export all top-level pdfs, functions, datasets and ModelConfigs of the workspace into `n`.
3777{
3778 _export = std::make_unique<HS3::ToolExportState>();
3779 _export->root = &n;
3780 StateScope<HS3::ToolExportState> exportScope{_export};
3781
3782 HS3Document &doc = _export->doc;
3784 doc.metadata.packages.push_back({"ROOT", rootVersion()});
3785 doc.parameterPoints.push_back({"default_values", {}});
3787
3788 std::vector<RooAbsPdf *> const allpdfs = topLevelObjects<RooAbsPdf>(_workspace.allPdfs(), _workspace);
3789 // A Gaussian constraint is written with its global observable as "x", also if that is its mean in RooFit (see
3790 // setConstraintObservable()). Which one it is must be known before any pdf is written: the pdfs are written in the
3791 // order of their names, and a constraint can come before the model that uses it.
3792 for (TObject *obj : _workspace.allGenericObjects()) {
3793 auto const *mc = dynamic_cast<RooFit::ModelConfig const *>(obj);
3794 RooArgSet const *globs = mc ? mc->GetGlobalObservables() : nullptr;
3795 if (!globs) {
3796 continue;
3797 }
3798 for (RooAbsArg const *arg : _workspace.components()) {
3799 auto const *gauss = dynamic_cast<RooGaussian const *>(arg);
3800 if (gauss && globs->find(gauss->getMean()) && !globs->find(gauss->getX()) &&
3801 !constraintObservable(gauss->GetName())) {
3802 setConstraintObservable(*gauss, gauss->getMean().GetName());
3803 }
3804 }
3805 }
3806 exportObjects(allpdfs);
3807 exportObjects(topLevelObjects<RooAbsReal>(_workspace.allFunctions(), _workspace));
3808
3809 // The array distributions are written after the objects that use them, see exportAsArrayComponent().
3811
3812 for (RooAbsArg *arg : _workspace.components()) {
3813 exportAttributes(arg, doc.rooFit.attributes);
3814 }
3815
3816 std::vector<RooAbsData *> alldata;
3817 for (auto &d : _workspace.allData()) {
3818 alldata.push_back(d);
3819 }
3820 sortByName(alldata);
3821 // Data sets with category observables are combined data sets.
3822 std::vector<RooAbsData *> singleData;
3823 for (auto &d : alldata) {
3824 // Without a matching RooSimultaneous, the categories of a data set are ordinary observables, written as
3825 // categorical axes, unless its observables are renamed per key (Config::renameCombinedObservables).
3826 if (selectionColumns(*d->get()).empty() ||
3828 !findMatchingSimultaneous(_workspace, namesOf(selectionColumns(*d->get()))))) {
3829 singleData.push_back(d);
3830 this->exportData(*d);
3831 } else {
3832 this->exportCombinedData(*d);
3833 }
3834 }
3835
3836 for (TObject *obj : _workspace.allGenericObjects()) {
3837 if (auto mc = dynamic_cast<RooFit::ModelConfig *>(obj)) {
3838 exportModelConfig(*mc, singleData);
3839 }
3840 }
3841
3842 exportParameterStepWidths(_workspace, allpdfs, alldata, doc.rooFit.stepWidths);
3843
3844 for (auto *snsh : static_range_cast<RooArgSet const *>(_workspace.getSnapshots())) {
3845 RooArgSet snapshotSorted;
3846 // We only want to add the variables that actually got exported and skip
3847 // the ones that the pdfs encoded implicitly (like in the case of
3848 // HistFactory).
3849 for (RooAbsArg *arg : *snsh) {
3850 if (std::any_of(allpdfs.begin(), allpdfs.end(), [&](RooAbsPdf *pdf) { return pdf->dependsOn(*arg); })) {
3852 snapshotSorted.add(*arg);
3853 }
3854 }
3855 snapshotSorted.sort();
3856 std::string name(snsh->GetName());
3857 if (name != "default_values") {
3858 doc.parameterPoints.push_back({name, {}});
3859 for (RooAbsArg *arg : snapshotSorted) {
3860 exportVariable(arg, doc.parameterPoints.back());
3861 }
3862 }
3863 }
3864 // The constraint terms that are components of a combined distribution have a label of their own.
3865 for (auto const &item : _export->auxiliaryLabels) {
3866 auto &categories = _export->categories[item.first].categories;
3867 for (std::string const &label : item.second) {
3868 if (std::find(categories.begin(), categories.end(), label) == categories.end()) {
3869 categories.push_back(label);
3870 }
3871 }
3872 }
3873 // The categories are categorical axes of the "default_domain", which must not list them as continuous.
3874 auto &defaultAxes = _export->domains[HS3::defaultDomainName];
3875 for (auto const &item : _export->categories) {
3876 if (defaultAxes.count(item.first)) {
3877 RooJSONFactoryWSTool::error("the variable '" + item.first +
3878 "' is categorical, but the domain already lists it as continuous");
3879 }
3880 }
3881 // The domains of the analyses take precedence.
3882 for (auto &item : _export->domains) {
3883 if (!HS3::findByName(doc.domains, item.first)) {
3884 appendDomain(doc.domains, item.first, std::move(item.second),
3885 item.first == HS3::defaultDomainName ? std::move(_export->categories)
3886 : std::map<std::string, HS3::CategoricalAxis>{});
3887 }
3888 }
3889
3890 // The exporters have written the generic distributions to the JSON tree. Now that the tree has all of them, the
3891 // document refers to their nodes, like a document that was read. The combined distributions are written now, since
3892 // constraint terms can become their components until here, see exportSingleModelConfig().
3893 if (n.has_child("distributions")) {
3894 std::map<std::string, JSONNode *> nodes;
3895 for (JSONNode &node : n["distributions"].children()) {
3896 nodes.emplace(name(node), &node);
3897 }
3898 for (HS3::Distribution &dist : doc.distributions) {
3899 auto found = nodes.find(dist.name);
3900 if (found == nodes.end()) {
3901 continue;
3902 }
3903 if (auto *generic = std::get_if<HS3::GenericObject>(&dist.body)) {
3904 generic->node = found->second;
3905 } else if (auto const *combined = std::get_if<HS3::CombinedDist>(&dist.body)) {
3906 HS3::writeCombinedDist(*found->second, *combined);
3907 }
3908 }
3909 }
3910
3911 // A RooFit model often has a constraint both as a factor of the product of a channel and as a term of the
3912 // likelihood (e.g. a constraint of a HistFactory modifier, an external constraint of the ModelConfig, or any
3913 // constraint of a channel, see constraintsOfChannels()); RooFit counts it once. In HS3 it would enter twice.
3914 for (auto const &[product, factors] : HS3::writeLikelihoodTermsOnce(doc, n)) {
3915 for (std::string const &factor : factors) {
3916 oocoutI(nullptr, IO) << "RooFitHS3: '" << factor << "' is a factor of '" << product
3917 << "' and a term of its likelihood; it is written once, as a term of the likelihood"
3918 << std::endl;
3919 }
3920 }
3921 declareBookkeepingColumns(doc, _workspace);
3922
3923 // The document that RooFit writes has to pass the same checks as the ones that it reads. Until RooFit writes
3924 // documents that follow the current standard, problems are only reported.
3925 HS3::Diagnostics diagnostics;
3926 HS3::ValidateOptions validateOptions;
3927 validateOptions.isExternal = [](std::string const &) { return false; };
3929 HS3::checkDocument(doc, diagnostics, validateOptions);
3930 for (auto &diagnostic : diagnostics) {
3931 diagnostic.severity = HS3::Diagnostic::Severity::Warning;
3932 diagnostic.message = "the exported document is not valid: " + diagnostic.message;
3933 }
3934 HS3::report(diagnostics);
3935 HS3::writeDocument(n, doc);
3936
3937 // Without distinct variates (see HS3::sharedVariates()), the document is only written if explicitly allowed, e.g.
3938 // to rename the variates in the JSON by hand.
3939 if (std::vector<std::string> const shared = HS3::sharedVariates(doc); !shared.empty()) {
3940 if (!config().allowExportSharedVariates) {
3941 std::string text;
3942 for (std::string const &message : shared) {
3943 text += (text.empty() ? "" : "; ") + message;
3944 }
3945 error("cannot export: " + text +
3946 ". HS3 requires the terms of a likelihood and the components of a combined distribution to have "
3947 "distinct variates: give the variates their own names (e.g. 'mass_SR' and 'mass_CR' instead of "
3948 "'mass'; RooJSONFactoryWSTool::config().renameCombinedObservables does this for the observables of "
3949 "combined data sets), or set RooJSONFactoryWSTool::config().allowExportSharedVariates = true to "
3950 "write the document anyway, with a warning, and rename them in the JSON.");
3951 }
3952 for (std::string const &message : shared) {
3953 warning("RooFitHS3: " + message +
3954 ". HS3 requires distinct variates: the document is not valid HS3, and can't be read back before the "
3955 "variates are renamed.");
3956 }
3957 }
3958}
3959
3960/// Import an HS3 document that is given as a JSON string into the workspace. Returns true; errors are exceptions.
3962{
3963 std::stringstream ss(s);
3964 return importJSON(ss);
3965}
3966
3967/// Export the workspace as an HS3 document, and return it as a JSON string.
3969{
3970 std::stringstream ss;
3971 exportJSON(ss);
3972 return ss.str();
3973}
3974
3975/// Export the workspace as an HS3 document, and write it as JSON to the stream. Returns true; errors are exceptions.
3977{
3978 std::unique_ptr<JSONTree> tree = JSONTree::create();
3979 JSONNode &n = tree->rootnode().set_map();
3980 this->exportAllObjects(n);
3981 n.writeJSON(os);
3982 return true;
3983}
3984
3985/// Export the workspace as an HS3 document, and write it to a JSON file. Returns true; errors are exceptions.
3987{
3988 std::ofstream out(filename.c_str());
3989 if (!out.is_open())
3990 RooJSONFactoryWSTool::error("RooJSONFactoryWSTool() invalid output file '" + filename + "'.");
3991 return this->exportJSON(out);
3992}
3993
3994bool RooJSONFactoryWSTool::hasAttribute(const std::string &obj, const std::string &attrib)
3995{
3996 if (!_import)
3997 return false;
3998 auto const &attributes = _import->document.rooFit.attributes;
3999 auto found = attributes.find(obj);
4000 if (found == attributes.end())
4001 return false;
4002 auto const &tags = found->second.tags;
4003 return std::find(tags.begin(), tags.end(), attrib) != tags.end();
4004}
4005void RooJSONFactoryWSTool::setAttribute(const std::string &obj, const std::string &attrib)
4006{
4007 _export->doc.rooFit.attributes[obj].tags.push_back(attrib);
4008}
4009
4010std::string RooJSONFactoryWSTool::getStringAttribute(const std::string &obj, const std::string &attrib)
4011{
4012 if (!_import)
4013 return "";
4014 auto const &attributes = _import->document.rooFit.attributes;
4015 auto found = attributes.find(obj);
4016 if (found == attributes.end())
4017 return "";
4018 auto value = found->second.dict.find(attrib);
4019 return value != found->second.dict.end() ? value->second : "";
4020}
4021void RooJSONFactoryWSTool::setStringAttribute(const std::string &obj, const std::string &attrib,
4022 const std::string &value)
4023{
4024 _export->doc.rooFit.attributes[obj].dict[attrib] = value;
4025}
4026
4027// Import the JSON document rooted at `n` into the workspace.
4029{
4030 HS3::ParseOptions options;
4031 // A user can replace how HistFactory distributions are imported by registering their own importer.
4032 auto const &importers = RooFit::JSONIO::importers();
4033 auto histFactoryImporters = importers.find("histfactory_dist");
4034 options.typedHistFactory = histFactoryImporters != importers.end() && !histFactoryImporters->second.empty() &&
4035 HS3::isBuiltinHistFactoryImporter(*histFactoryImporters->second.front());
4036
4037 HS3::Diagnostics diagnostics;
4038 HS3::upgradeDocument(n, diagnostics, options);
4039 HS3Document parsed = HS3::parseDocument(n, diagnostics, options);
4040 std::optional<RooFit::ValidatedHS3Document> validated;
4041 if (!HS3::hasErrors(diagnostics)) {
4042 HS3::ValidateOptions validateOptions;
4043 validateOptions.strict = !(parsed.metadata.version < HS3::Version{0, 3});
4044 validateOptions.isExternal = [this](std::string const &name) { return _workspace.obj(name) != nullptr; };
4045 validated = HS3::validate(std::move(parsed), diagnostics, validateOptions);
4046 }
4047 HS3::report(diagnostics);
4048 // What HS3 requires of the variates and the constraints is checked on the document as it is, before the components
4049 // that are read as constraint terms are taken out of it.
4050 std::set<std::string> const bookkeepingColumns = checkVariates(validated->doc());
4051 HS3::AuxiliaryConstraints const auxiliary =
4052 HS3::readAuxiliaryChannelsAsConstraints(*validated, config().importConstraintsAsChannels);
4053 for (std::string const &message : auxiliary.warnings) {
4054 warning("RooFitHS3: " + message);
4055 }
4056 for (std::string const &message : HS3::resolvePointData(*validated)) {
4057 error(message);
4058 }
4059 HS3Document const &doc = validated->doc();
4060
4061 StateScope<HS3::ToolImportState> importScope{_import};
4062 _import = std::make_unique<HS3::ToolImportState>(doc);
4063
4064 createVariables(_workspace, _import->document.domains, _import->ranges);
4065
4066 if (_import->defaultValues) {
4067 for (auto const &p : _import->defaultValues->parameters) {
4069 }
4070 }
4071 for (auto const &function : doc.functions) {
4072 this->importFunction(*function.body.node, true);
4073 }
4074 for (auto const &distribution : doc.distributions) {
4075 this->importDistribution(distribution);
4076 }
4077
4078 // This creates the index categories, which the parameter points can refer to.
4079 combinePdfs(doc, _workspace);
4080
4081 for (auto const &point : doc.parameterPoints) {
4082 RooJSONFactoryWSTool::testValidName(point.name, true);
4083
4084 RooArgSet vars;
4085 for (auto const &var : point.parameters) {
4086 std::string const *label = var.value ? std::get_if<std::string>(&*var.value) : nullptr;
4087 if (RooCategory *cat = _workspace.cat(var.name)) {
4088 if (label) {
4089 cat->setLabel(label->c_str());
4090 } else if (var.value) {
4091 cat->setIndex(static_cast<int>(std::get<double>(*var.value)));
4092 }
4093 vars.add(*cat);
4094 continue;
4095 }
4096 if (label) {
4097 warning("RooFitHS3: ignoring the string value of parameter '" + var.name + "' in parameter point '" +
4098 point.name + "', because there is no category with that name.");
4099 continue;
4100 }
4101 RooRealVar *rrv = _workspace.var(var.name);
4102 if (!rrv && !_workspace.arg(var.name)) {
4103 // The parameter is not used by any other component: create it. "const": false is the same as no
4104 // "const" at all.
4105 testValidName(var.name, true);
4106 rrv = &wsEmplace<RooRealVar>(var.name, 1.);
4107 configureVariable(_import->ranges, var, *rrv);
4109 } else if (rrv) {
4110 configureVariable(_import->ranges, var, *rrv);
4111 }
4112 if (rrv) {
4113 vars.add(*rrv);
4114 }
4115 }
4116 _workspace.saveSnapshot(point.name, vars);
4117 }
4118
4119 for (auto const &item : doc.rooFit.attributes) {
4120 if (RooAbsArg *arg = _workspace.arg(item.first))
4121 importAttributes(arg, item.second);
4122 }
4123
4124 // The components of combined data sets are moved out of the "datasets" vector when the combined data set is
4125 // assembled, so they don't get imported on their own. The ROOT-internal form of older files (combineDatasets())
4126 // is handled after the analyses, because their likelihoods refer to the components.
4127 std::vector<std::unique_ptr<RooAbsData>> datasets;
4128 datasets.reserve(doc.data.size());
4129 for (auto const &data : doc.data) {
4130 if (!std::holds_alternative<HS3::CombinedData>(data.body)) {
4131 datasets.push_back(loadData(data, _workspace, &_import->ranges));
4132 }
4133 }
4134 assembleCombinedData(doc, _workspace, datasets);
4135
4136 for (auto const &analysis : doc.analyses) {
4137 importAnalysis(doc, analysis, _workspace, datasets, bookkeepingColumns, auxiliary.terms);
4138 }
4139
4140 combineDatasets(doc, datasets);
4141 // The data sets of the components that are read as constraint terms are not data sets of the workspace: their
4142 // values are in the global observables. Several analyses can share a ModelConfig, of which only the first one
4143 // consumes the data of its constraint terms.
4144 for (auto &d : datasets) {
4145 if (d && auxiliary.data.count(d->GetName())) {
4146 d.reset();
4147 }
4148 }
4149
4150 for (auto const &d : datasets) {
4151 if (d) {
4153 for (auto const &obs : *d->get()) {
4154 if (auto *rrv = dynamic_cast<RooRealVar *>(obs)) {
4155 _workspace.var(rrv->GetName())->setBinning(rrv->getBinning());
4156 }
4157 }
4158 }
4159 }
4160
4161 warnAboutUnusedArrayComponents(_workspace);
4162
4163 if (_workspace.getSnapshot("default_values")) {
4164 _workspace.loadSnapshot("default_values");
4165 }
4166 importParameterStepWidths(_workspace, doc);
4167}
4168
4169/// Import an HS3 document that is read as JSON from the stream into the workspace. Returns true; errors are exceptions.
4171{
4172 std::unique_ptr<JSONTree> tree = JSONTree::create(is);
4173 this->importAllNodes(tree->rootnode());
4174 return true;
4175}
4176
4177/// Import the HS3 document of a JSON file into the workspace. Returns true; errors are exceptions.
4179{
4180 std::ifstream infile(filename.c_str());
4181 if (!infile.is_open())
4182 RooJSONFactoryWSTool::error("RooJSONFactoryWSTool() invalid input file '" + filename + "'.");
4183 return this->importJSON(infile);
4184}
4185
4186void RooJSONFactoryWSTool::importJSONElement(const std::string &name, const std::string &jsonString)
4187{
4188 std::unique_ptr<RooFit::Detail::JSONTree> tree = RooFit::Detail::JSONTree::create(jsonString);
4189 JSONNode &n = tree->rootnode();
4190
4191 // If the objects containts a parameter of interest, import it as a modelConfig
4192 if (n.find("poi")) {
4193
4194 RooStats::ModelConfig modelConfig{"ModelConfig"};
4195 std::string poi = n.find("poi")->val();
4196 std::string pdname = n.find("pdfName")->val();
4197 modelConfig.SetWS(_workspace);
4198 modelConfig.SetPdf(pdname.c_str());
4199 modelConfig.SetParametersOfInterest(_workspace.argSet(poi));
4200 _workspace.import(modelConfig);
4201
4202 return;
4203 }
4204
4205 n["name"] << name;
4206
4207 // Without a type, it must be a variable.
4208 JSONNode const *type = n.find("type");
4209 if (!type) {
4210 this->importVariableElement(n);
4211 } else if (type->val() == "binned" || type->val() == "unbinned") {
4212 HS3::Diagnostics diagnostics;
4213 HS3::Data data = HS3::parseData(n, diagnostics);
4214 HS3::report(diagnostics);
4215 _workspace.import(*loadData(data, _workspace, nullptr), RooFit::Silence());
4216 } else {
4217 this->importFunction(n, false);
4218 }
4219}
4220
4222{
4223 // A variable is given by its "value", by its range "min" and "max", or by both. With only a value, it is constant.
4224 JSONNode const *value = elementNode.find("value");
4225 JSONNode const *min = elementNode.find("min");
4226 JSONNode const *max = elementNode.find("max");
4227 if (!value && !(min && max)) {
4228 throw std::invalid_argument("Invalid Syntax: Please provide either 'value' or 'min' and 'max' or both");
4229 }
4230 HS3::DomainAxis axis;
4231 axis.name = elementNode["name"].val();
4232 HS3::ParameterValue parameter;
4233 parameter.name = axis.name;
4234 if (min && max) {
4235 axis.min = min->val_double();
4236 axis.max = max->val_double();
4237 }
4238 parameter.value = value ? value->val_double() : (*axis.max + *axis.min) / 2;
4239 parameter.isConst = value && !(min && max);
4240 HS3Document doc;
4241 doc.domains.push_back({HS3::defaultDomainName, {std::move(axis)}});
4242 doc.parameterPoints.push_back({"default_values", {parameter}});
4243
4244 StateScope<HS3::ToolImportState> importScope{_import};
4245 _import = std::make_unique<HS3::ToolImportState>(doc);
4246
4247 importVariable(parameter);
4248 if (RooRealVar *rrv = _workspace.var(parameter.name)) {
4249 configureVariable(_import->ranges, parameter, *rrv);
4250 }
4251}
4252
4253/// Write a warning to the RooFit message service, and return its stream.
4254std::ostream &RooJSONFactoryWSTool::warning(std::string const &str)
4255{
4256 return RooMsgService::instance().log(nullptr, RooFit::MsgLevel::WARNING, RooFit::ObjectHandling) << str << std::endl;
4257}
4258
4259/// Write an error to the RooFit message service, and throw it as a std::runtime_error.
4261{
4262 RooMsgService::instance().log(nullptr, RooFit::MsgLevel::ERROR, RooFit::IO) << s << std::endl;
4263 throw std::runtime_error(s);
4264}
4265
4266/// Replace some characters that are common in the names of RooFit objects, but that the HS3 standard doesn't allow in
4267/// names, if config().allowSanitizeNames is set.
4268std::string RooJSONFactoryWSTool::sanitizeName(const std::string str)
4269{
4270 std::string result;
4271 if (RooJSONFactoryWSTool::config().allowSanitizeNames) {
4272 for (char c : str) {
4273 switch (c) {
4274 case '[':
4275 case '|':
4276 case ',':
4277 case '(': result += '_'; break;
4278 case ']':
4279 case ')':
4280 // skip these characters entirely
4281 break;
4282 case '.': result += "_dot_"; break;
4283 case '@': result += "at"; break;
4284 case '-': result += "minus"; break;
4285 case '/': result += "_div_"; break;
4286
4287 default: result += c; break;
4288 }
4289 }
4290 return result;
4291 }
4292 return str;
4293}
4294
4296{
4297 RooWorkspace tmpWS = RooWorkspace();
4298 if (onlyModelConfig) {
4299 for (auto *obj : ws.allGenericObjects()) {
4300 if (auto *mc = dynamic_cast<RooFit::ModelConfig *>(obj)) {
4301 tmpWS.import(*mc->GetPdf(), RooFit::RecycleConflictNodes(true));
4302 }
4303 }
4304
4305 } else {
4306
4307 for (auto *pdf : ws.allPdfs()) {
4308 if (isTopLevel(*pdf, ws)) {
4309 tmpWS.import(*pdf, RooFit::RecycleConflictNodes(true));
4310 }
4311 }
4312
4313 for (auto *func : ws.allFunctions()) {
4314 if (isTopLevel(*func, ws)) {
4315 tmpWS.import(*func, RooFit::RecycleConflictNodes(true));
4316 }
4317 }
4318 }
4319
4320 for (auto *data : ws.allData()) {
4321 tmpWS.import(*data);
4322 }
4323
4324 for (auto *obj : ws.allGenericObjects()) {
4325 tmpWS.import(*obj);
4326 }
4327
4328 for (auto *obj : ws.allResolutionModels()) {
4329 tmpWS.import(*obj);
4330 }
4331
4332 for (auto *snsh : ws.getSnapshots()) {
4333 auto *snshSet = dynamic_cast<RooArgSet *>(snsh);
4334 if (snshSet) {
4335 tmpWS.saveSnapshot(snshSet->GetName(), *snshSet, true);
4336 }
4337 }
4338
4339 return tmpWS;
4340}
4341
4343{
4344 static Config conf;
4345 return conf;
4346}
4347
4348// Sanitize all names in the workspace to be HS3 compliant
4350{
4351 RooWorkspace tmpWS = cleanWS(ws, false);
4352
4353 // Valid names stay as they are.
4354 auto sanitize = [](auto const &objects) {
4355 for (auto *obj : objects) {
4356 obj->SetName(sanitizeName(obj->GetName()).c_str());
4357 }
4358 };
4359 sanitize(tmpWS.allVars());
4360 sanitize(tmpWS.allFunctions());
4361 sanitize(tmpWS.allPdfs());
4362 sanitize(tmpWS.allResolutionModels());
4363 for (auto const &datasets : {tmpWS.allData(), tmpWS.allEmbeddedData()}) {
4364 sanitize(datasets);
4365 for (RooAbsData *data : datasets) {
4366 sanitize(*data->get());
4367 }
4368 }
4369 for (auto *snshObj : tmpWS.getSnapshots()) {
4370 // Snapshots are stored as TObject*, but really they are RooArgSet*
4371 auto *snsh = dynamic_cast<RooArgSet *>(snshObj);
4372 if (!snsh) {
4373 std::cerr << "Warning: found snapshot that is not a RooArgSet, skipping\n";
4374 continue;
4375 }
4376 snsh->setName(sanitizeName(snsh->GetName()).c_str());
4377 sanitize(*snsh);
4378 }
4379 // Generic objects, like the ModelConfigs with their sets
4380 for (auto *obj : tmpWS.allGenericObjects()) {
4381 if (auto *named = dynamic_cast<TNamed *>(obj)) {
4382 named->SetName(sanitizeName(named->GetName()).c_str());
4383 } else if (!isValidName(obj->GetName())) {
4384 std::cerr << "Warning: object " << obj->GetName() << " is not TNamed, cannot rename.\n";
4385 }
4386 if (auto *mc = dynamic_cast<RooFit::ModelConfig *>(obj)) {
4387 sanitize(*mc->GetObservables());
4388 sanitize(*mc->GetParametersOfInterest());
4389 sanitize(*mc->GetNuisanceParameters());
4390 sanitize(*mc->GetGlobalObservables());
4391 }
4392 }
4393 RooWorkspace newWS = cleanWS(tmpWS, false);
4394 newWS.SetName((std::string{ws.GetName()} + "_sanitized").c_str());
4395 return newWS;
4396}
void writeArrayDist(RooJSONFactoryWSTool &tool, JSONNode &elem, std::string const &name, std::vector< RooAbsPdf const * > const &components)
std::optional< ArrayComponentInfo > arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable, RooJSONFactoryWSTool *tool)
std::optional< double > toNumber(const std::string &str)
std::vector< std::vector< std::string > > selectionKeys(std::vector< RooCategory const * > const &columns)
void writeReference(JSONNode &node, RooAbsArg const &arg)
bool isLiteralIdentifier(std::string_view name)
std::string transformedBaseName(RooAbsReal const &param)
std::vector< RooCategory const * > selectionColumns(RooAbsCategory const &indexCat)
std::string transformedArgument(RooAbsReal const &param)
std::string selectionKeyToString(std::vector< std::string > const &key)
bool startsWith(std::string_view str, std::string_view prefix)
bool endsWith(std::string_view str, std::string_view suffix)
std::string selectionLabel(std::vector< std::string > const &key)
bool isLiteralConstVar(RooAbsArg const &arg)
constexpr const char * helperObjectTag
Definition JSONIOUtils.h:45
constexpr const char * arrayDistTag
Definition JSONIOUtils.h:34
std::string message
#define d(i)
Definition RSha256.hxx:102
#define c(i)
Definition RSha256.hxx:101
#define e(i)
Definition RSha256.hxx:103
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
bool isSkippedHelper(RooAbsArg const &arg, RooWorkspace const &ws)
constexpr auto hs3VersionTag
#define oocoutW(o, a)
#define oocoutI(o, a)
static unsigned int total
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 input
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
Option_t Option_t TPoint TPoint const char text
char name[80]
Definition TGX11.cxx:142
#define gROOT
Definition TROOT.h:417
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
TClass * IsA() const override
Definition RooAbsArg.h:674
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:284
virtual TObject * clone(const char *newname=nullptr) const =0
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...
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
RooFit::OwningPtr< RooArgSet > getComponents() const
Create a RooArgSet with all components (branch nodes) of the expression tree headed by this object.
const RefCountList_t & servers() const
List of all servers of this object.
Definition RooAbsArg.h:146
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
const RefCountList_t & clients() const
List of all clients of this object.
Definition RooAbsArg.h:138
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
void leafNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all leaf nodes of the arg tree, starting with ourself as top node.
Abstract base class for RooRealVar binning definitions.
Int_t numBins() const
Return number of bins.
virtual double binLow(Int_t bin) const =0
virtual bool isUniform() const
virtual double highBound() const =0
virtual double lowBound() const =0
virtual double binHigh(Int_t bin) const =0
Abstract base class for objects that represent a discrete value that can be set from the outside,...
A space to attach TBranches.
unsigned int getCurrentOrdinalNumber() const
Return ordinal number of the current state.
bool hasLabel(const std::string &label) const
Check if a state with name label exists.
virtual const char * getCurrentLabel() const
Return label string of current state.
const std::map< std::string, value_type >::value_type & getOrdinal(unsigned int n) const
Return name and index of the nth defined state.
std::size_t size() const
Number of states defined.
const RooCatType * defineType(const char *label)
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 void removeAll()
Remove all arguments from our set, deleting them if we own them.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
const_iterator end() const
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
Storage_t::size_type size() const
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
const_iterator begin() const
void sort(bool reverse=false)
Sort collection using std::sort and name comparison.
virtual bool containsInstance(const RooAbsArg &var) const
Check if this exact instance is in this collection.
void setName(const char *name)
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
Abstract base class for objects that are lvalues, i.e.
virtual Int_t numBins(const char *rangeName=nullptr) const =0
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....
bool canBeExtended() const
If true, PDF can provide extended likelihood term.
Definition RooAbsPdf.h:214
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
virtual Int_t getBins(const char *name=nullptr) const
Get number of bins of currently defined range.
void setConstant(bool value=true)
virtual double getMax(const char *name=nullptr) const
Get maximum of currently defined range.
virtual double getMin(const char *name=nullptr) const
Get minimum of currently defined range.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
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
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition RooArgSet.h:159
bool containsInstance(const RooAbsArg &var) const override
Check if this exact instance is in this collection.
Definition RooArgSet.h:132
Implements a RooAbsBinning in terms of an array of boundary values, posing no constraints on the choi...
Definition RooBinning.h:27
Object to represent discrete states.
Definition RooCategory.h:28
bool setIndex(Int_t index, bool printError=true) override
Set value by specifying the index code of the desired state.
bool defineType(const std::string &label)
Define a state with given name.
bool setLabel(const char *label, bool printError=true) override
Set value by specifying the name of the desired state.
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
const char * getString(Int_t idx) const
Return string stored in slot idx.
Definition RooCmdArg.h:96
Represents a constant real-valued object.
Definition RooConstVar.h:23
RooCustomizer is a factory class to produce clones of a prototype composite PDF object with the same ...
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
Container class to hold unbinned data.
Definition RooDataSet.h:32
std::string val() const
JSONNode const * find(std::string const &key) const
The component at the end of a path of keys, or nullptr if a component on the path doesn't exist.
bool has_child(std::string const &) const
std::string key() const
Records which components of a JSON map are read while it is alive, through any node of the tree.
static std::unique_ptr< JSONTree > create()
An HS3 document. It is move-only, because generic objects refer to the JSON tree of the document.
std::vector< HS3::Analysis > analyses
std::vector< HS3::Data > data
HS3::Metadata metadata
std::vector< HS3::Likelihood > likelihoods
std::vector< HS3::Function > functions
std::vector< HS3::ParameterPoint > parameterPoints
HS3::RooFitInternal rooFit
std::vector< HS3::Domain > domains
std::vector< HS3::Distribution > distributions
Where RooFit takes the ranges of variables from: the "default_domain" if there is one,...
DomainAxis const * find(std::string const &name) const
The axis that defines the range of a variable, or null.
bool contains(std::string const &name) const
Whether any domain has the variable.
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
When using RooFit, statistical models can be conveniently handled and stored as a RooWorkspace.
bool isConstraintReadAsChannel(RooAbsPdf const &pdf) const
Whether the constraint term pdf contributes to the likelihoods of the document that is currently bein...
std::string getStringAttribute(const std::string &obj, const std::string &attrib)
void exportModelConfig(RooStats::ModelConfig const &mc, const std::vector< RooAbsData * > &singleDataSets)
static void fillSeq(RooFit::Detail::JSONNode &node, RooAbsCollection const &coll, size_t nMax=-1)
bool exportConstraintData(std::string const &term, RooArgSet const *globalObservables, std::string const &dataName)
RooJSONFactoryWSTool(RooWorkspace &ws)
void recordConstraintTerms(std::string const &pdfName, std::vector< std::string > const &terms)
T * request(const std::string &objname, const std::string &requestAuthor)
The object objname from the workspace, imported from the document first if needed.
void exportCombinedData(RooAbsData const &data)
Export a data set with category observables as a "combined" data set.
void exportSimultaneous(RooSimultaneous const &simPdf)
Export a RooSimultaneous as a "combined_dist".
void exportData(RooAbsData const &data)
bool hasAttribute(const std::string &obj, const std::string &attrib)
bool importJSON(std::string const &filename)
Import the HS3 document of a JSON file into the workspace. Returns true; errors are exceptions.
std::string const & exportRootName() const
The name of the top-level object whose export is in progress (the root of the current export recursio...
T * tryRequest(const std::string &objname)
Like request(), but returns nullptr if neither the workspace nor the document has the object.
std::map< std::string, std::map< std::string, std::map< std::string, std::string > > > _combinedObservableRenames
Obj_t & wsImport(Obj_t const &obj)
std::vector< std::string > _importStack
static std::unique_ptr< RooDataHist > readBinnedData(const RooFit::Detail::JSONNode &n, const std::string &namecomp, RooArgSet const &vars)
Create a RooDataHist with the name name over the variables vars from the "contents" of n,...
static RooFit::Detail::JSONNode & appendNamedChild(RooFit::Detail::JSONNode &node, std::string const &name)
void importDistribution(RooFit::HS3::Distribution const &distribution)
static void exportArray(std::size_t n, double const *contents, RooFit::Detail::JSONNode &output)
Write n numbers as an array, each as an integer if it has no fractional part.
void recordCategory(RooAbsCategory const &cat)
void exportObjects(T const &args)
static void exportHisto(RooArgSet const &vars, std::size_t n, double const *contents, RooFit::Detail::JSONNode &output)
Write the axes and the n bin contents of a histogram over the variables vars, which are RooRealVars o...
std::vector< RooAbsArg const * > _serversToDelete
std::map< std::string, std::map< std::string, RooAbsPdf const * > > _renamedComponents
std::vector< RooFit::HS3::DistributionRef > const * channelConstraints(std::string const &dist) const
The constraint terms that the document that is currently being imported adds to the HistFactory distr...
std::unique_ptr< RooFit::HS3::ToolExportState > _export
std::string exportJSONtoString()
Export the workspace as an HS3 document, and return it as 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)
static bool isValidName(const std::string &str)
Whether a string is a valid name: a letter or an underscore, followed by letters, digits or underscor...
void importVariable(RooFit::HS3::ParameterValue const &p)
RooFit::HS3::Version hs3Version() const
The HS3 version of the document that is currently being imported.
std::vector< std::unique_ptr< RooAbsArg > > _renamedObjects
void importDependants(const RooFit::Detail::JSONNode &n)
void importJSONElement(const std::string &name, const std::string &jsonString)
static RooWorkspace sanitizeWS(const RooWorkspace &ws)
static void error(const char *s)
Write an error to the RooFit message service, and throw it as a std::runtime_error.
void setConstraintObservable(RooAbsPdf const &pdf, std::string const &observable)
Record that observable is the observable of the constraint term pdf (the side that is not the constra...
void setAttribute(const std::string &obj, const std::string &attrib)
void exportObject(RooAbsArg const &func)
void exportSingleModelConfig(RooStats::ModelConfig const &mc, std::string const &analysisName, std::string const *dataName)
void importFunction(const RooFit::Detail::JSONNode &p, bool importAllDependants)
Import the function or distribution p into the workspace, with the importers that are registered for ...
void importVariableElement(const RooFit::Detail::JSONNode &elementNode)
bool importJSONfromString(const std::string &s)
Import an HS3 document that is given as a JSON string into the workspace. Returns true; errors are ex...
std::unique_ptr< RooFit::HS3::ToolImportState > _import
static bool testValidName(const std::string &name, bool forceError)
void exportVariable(const RooAbsArg *v, RooFit::HS3::ParameterPoint &point)
Obj_t & wsEmplace(RooStringView name, Args_t &&...args)
static std::string sanitizeName(const std::string str)
Replace some characters that are common in the names of RooFit objects, but that the HS3 standard doe...
static std::string name(const RooFit::Detail::JSONNode &n)
void exportAllObjects(RooFit::Detail::JSONNode &n)
bool exportJSON(std::string const &fileName)
Export the workspace as an HS3 document, and write it to a JSON file. Returns true; errors are except...
static RooFit::Detail::JSONNode const * findNamedChild(RooFit::Detail::JSONNode const &node, std::string const &name)
void importAllNodes(RooFit::Detail::JSONNode &n)
std::string exportAsArrayComponent(RooAbsPdf const &pdf, std::string const &arrayName)
void warnIfFreeWithoutDomain(RooRealVar const &var)
std::string const * constraintObservable(std::string const &pdfName) const
void setStringAttribute(const std::string &obj, const std::string &attrib, const std::string &value)
std::vector< RooAbsArg const * > _serversToExport
static std::ostream & warning(const std::string &s)
Write a warning to the RooFit message service, and return its stream.
static RooArgSet readAxes(const RooFit::Detail::JSONNode &node)
Create the variables for the "axes" of topNode, which are owned by the returned set.
static RooMsgService & instance()
Return reference to singleton instance.
std::ostream & log(const RooAbsArg *self, RooFit::MsgLevel level, RooFit::MsgTopic topic, bool forceSkipPrefix=false)
Log error message associated with RooAbsArg object self at given level and topic.
static constexpr double infinity()
Return internal infinity representation.
Definition RooNumber.h:25
static constexpr int isInfinite(double x)
Return true if x is infinite by RooNumber internal specification.
Definition RooNumber.h:27
Efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:35
Binning/range definition that only defines a range but no binning.
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void removeMin(const char *name=nullptr)
Remove lower range limit for binning with given name. Empty name means default range.
void setVal(double value) override
Set value of variable to 'value'.
void setError(double value)
Definition RooRealVar.h:61
void setMin(const char *name, double value, bool shared=true)
Set minimum of name range to given value.
double getError() const
Definition RooRealVar.h:59
void setRange(const char *name, double min, double max, bool shared=true)
Set a fit or plotting range.
void setBins(Int_t nBins, const char *name=nullptr, bool shared=true)
Create a uniform binning under name 'name' for this variable.
bool hasError(bool allowZero=true) const
Definition RooRealVar.h:60
void setBinning(const RooAbsBinning &binning, const char *name=nullptr, bool shared=true)
Add given binning under name 'name' with this variable.
void setMax(const char *name, double value, bool shared=true)
Set maximum of name range to given value.
void removeMax(const char *name=nullptr)
Remove upper range limit for binning with given name. Empty name means default range.
const RooAbsBinning & getBinning(const char *name=nullptr, bool verbose=true, bool createOnTheFly=false, bool shared=true) const override
Return binning definition with name.
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
RooAbsPdf * getPdf(RooStringView catName) const
Return the p.d.f associated with the given index category name.
const RooAbsCategoryLValue & indexCat() const
< A class that holds configuration information for a model using a workspace as a store
Definition ModelConfig.h:34
const std::string & GetSnapshotName() const
get the name of the workspace snapshot saved by SetSnapshot() (empty if there is none)
const RooArgSet * GetGlobalObservables() const
get RooArgSet for global observables (return nullptr if not existing)
const RooArgSet * GetParametersOfInterest() const
get RooArgSet containing the parameter of interest (return nullptr if not existing)
const RooArgSet * GetNuisanceParameters() const
get RooArgSet containing the nuisance parameters (return nullptr if not existing)
void SetWS(RooWorkspace &ws) override
Set a workspace that owns all the necessary components for the analysis.
const RooArgSet * GetObservables() const
get RooArgSet for observables (return nullptr if not existing)
const RooArgSet * GetExternalConstraints() const
get RooArgSet for global observables (return nullptr if not existing)
RooAbsPdf * GetPdf() const
get model PDF (return nullptr if pdf has not been specified or does not exist)
RooAbsPdf * GetPriorPdf() const
get parameters prior pdf (return nullptr if not existing)
Joins several RooAbsCategoryLValue objects into a single category.
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.
RooCategory * cat(RooStringView name) const
Retrieve discrete variable (RooCategory) with given name. A null pointer is returned if not found.
RooArgSet allVars() const
Return set with all variable objects.
RooArgSet argSet(RooStringView nameList) const
Return set of RooAbsArgs matching to given list of names.
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.
RooRealVar * var(RooStringView name) const
Retrieve real-valued variable (RooRealVar) with given name. A null pointer is returned if not found.
RooAbsData * data(RooStringView name) const
Retrieve dataset (binned or unbinned) with given name. A null pointer is returned if not found.
std::list< RooAbsData * > allEmbeddedData() const
Return list of all dataset in the workspace.
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
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:149
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:226
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:548
const char * Data() const
Definition TString.h:385
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2460
RooCmdArg RecycleConflictNodes(bool flag=true)
RooConstVar & RooConst(double val)
RooCmdArg Silence(bool flag=true)
RooCmdArg Index(RooCategory &icat)
RooCmdArg StoreError(const RooArgSet &aset)
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Import(const char *state, TH1 &histo)
const Double_t sigma
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)
double product(DoubleArray factors, std::size_t nFactors)
Definition MathFuncs.h:102
Types that represent an HS3 document.
AuxiliaryConstraints readAuxiliaryChannelsAsConstraints(ValidatedHS3Document &doc, bool asChannels)
RooFit writes an array of constraints with the data set of its observed values as a component of the ...
std::variant< std::string, double > NameOrNumber
A name, or a number for a constant.
std::vector< std::string > unlistedConstraints(HS3Document const &doc, std::vector< std::string > *warnings=nullptr)
In HS3 0.3 (HS3 PR #154, decision on HS3 #156), the "constraints" of a HistFactory modifier add no te...
void checkDocument(HS3Document const &doc, Diagnostics &diagnostics, ValidateOptions const &options={})
The checks of validate(), for a document that is still needed if it doesn't pass them.
auto findByName(Objects_t &objects, std::string const &name) -> decltype(&*objects.begin())
The object with the name name among the objects of a section, e.g. findByName(doc....
Definition HS3Document.h:65
std::map< std::string, std::set< std::string > > writeLikelihoodTermsOnce(HS3Document const &doc, Detail::JSONNode &root)
Writes each term of the likelihoods once: a factor of a product that is a term of the likelihood as w...
std::string const & nameOf(std::variant< Ts... > const &v)
The name of the alternative that a variant holds, e.g. of an axis or of a modifier.
Definition HS3Document.h:58
void buildCombinedDist(RooJSONFactoryWSTool &tool, std::string const &name, CombinedDist const &dist, std::vector< std::string > const &otherLikelihoodTerms={})
Create the RooSimultaneous of a combined distribution in the workspace of the tool.
std::variant< RegularBinning, EdgesBinning > Binning
std::set< std::string > variatesOf(HS3Document const &doc, Likelihood const &likelihood)
The variates of the "distributions" of a likelihood, which it pairs with data, with the columns of it...
std::map< std::string, std::set< std::string > > sharedAxes(HS3Document const &doc)
The axes that several components of a combined data set have, by combined data set.
constexpr char const * defaultDomainName
The domain in which RooFit writes the ranges of all variables. It is a convention of RooFit,...
std::optional< ValidatedHS3Document > validate(HS3Document doc, Diagnostics &diagnostics, ValidateOptions const &options)
Checks what can be checked without knowing how the objects are built: unique names,...
std::set< std::string > componentsWithData(HS3Document const &doc)
The distributions that are components of a combined distribution of a likelihood, with a component of...
void setExportedObject(RooJSONFactoryWSTool &tool, HistFactoryDist dist, std::vector< DistributionRef > channelConstraints)
Called by the exporter of a HistFactory distribution, which is then written by the tool.
void writeDocument(Detail::JSONNode &root, HS3Document const &doc)
Writes everything but the distributions and functions, which are written one by one while they are ex...
void report(Diagnostics const &diagnostics, std::string const &object="")
Forward the warnings to the message service, and throw if there are errors.
void writeContents(Detail::JSONNode &node, std::vector< double > const &values)
Writes an array of numbers, each as an integer if it has no fractional part.
RooArgSet createObservables(std::vector< BinnedAxis > const &axes)
Create the variables for the axes of binned data.
std::string const * importedArrayComponentForm(RooJSONFactoryWSTool &tool, std::string const &name)
The canonical form (see arrayComponentForm()) of the component of an array distribution that this imp...
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
Definition HS3Parser.cxx:92
void recordImportedArrayComponent(RooJSONFactoryWSTool &tool, std::string const &name, std::string form)
Record that this import created the component name of an array distribution, with the canonical form ...
std::map< std::string, std::set< std::string > > bookkeepingColumns(HS3Document const &doc)
The bookkeeping columns by combined data set: the declared ones (RooFitInternal::bookkeepingColumns),...
void writeHistFactoryDist(Detail::JSONNode &node, HistFactoryDist const &dist)
Writes a HistFactory distribution, without its name.
std::vector< std::string > sharedVariates(HS3Document const &doc)
Describes each variate that is shared although it must be distinct: by the terms of a likelihood,...
std::vector< Diagnostic > Diagnostics
NameOrNumber toNameOrNumber(RooAbsArg const &arg)
The name of an object, or the value of a literal constant.
void upgradeDocument(Detail::JSONNode &root, Diagnostics &diagnostics, ParseOptions const &options={})
Rewrites everything that older versions of RooFit wrote in a way that is not part of the standard int...
std::vector< std::string > resolvePointData(ValidatedHS3Document &doc)
A number given in-line in the "data" of a likelihood, or a point data set without axes,...
BinnedAxis toBinnedAxis(RooRealVar const &var)
The axis of binned data for a variable, or for a binning of a variable with the given name.
void writeBinnedData(Detail::JSONNode &node, BinnedData const &data)
Writes the axes, contents and uncertainties of binned data, without its name and type.
std::unique_ptr< RooDataHist > createDataHist(std::string const &name, RooArgSet const &vars, std::vector< double > const &contents, std::vector< double > const *errors)
Create a RooDataHist with the contents and errors. If there are no errors, it doesn't store squared w...
void writeCombinedDist(Detail::JSONNode &node, CombinedDist const &dist)
Writes a combined distribution, without its name.
Data parseData(Detail::JSONNode const &data, Diagnostics &diagnostics)
Reads a data set that doesn't come with a document.
bool isBuiltinHistFactoryImporter(JSONIO::Importer const &importer)
Whether this is the importer that RooFit registers for HistFactory distributions, as opposed to the o...
std::vector< BinnedAxis > parseBinnedAxes(Detail::JSONNode const &axes, Diagnostics &diagnostics)
Reads the axes of binned data that doesn't come with a document.
void buildHistFactoryDist(RooJSONFactoryWSTool &tool, std::string const &name, HistFactoryDist const &dist)
Create the RooFit objects of a HistFactory distribution in the workspace of the tool.
HS3Document parseDocument(Detail::JSONNode const &root, Diagnostics &diagnostics, ParseOptions const &options={})
Reads a document.
ImportMap & importers()
Definition JSONIO.cxx:21
ExportMap & exporters()
Definition JSONIO.cxx:44
@ ObjectHandling
void initialize(typename Architecture_t::Matrix_t &A, EInitialization m)
Definition Functions.h:282
static const char * what
Definition stlLoader.cc:5
std::optional< DistributionRef > prior
std::optional< ParameterPointRef > init
LikelihoodRef likelihood
std::vector< DomainRef > domains
std::vector< ParameterRef > parametersOfInterest
std::vector< std::string > tags
std::map< std::string, std::string > dict
What readAuxiliaryChannelsAsConstraints() changed.
std::set< std::string > data
Their data sets, which hold the observed values of global observables.
std::set< std::string > terms
The components that are no longer components of their combined distribution.
std::vector< std::string > warnings
The axis of binned data.
std::vector< std::string > categories
The data set of a RooSimultaneous as older versions of RooFit wrote it. It is only read.
std::vector< int > indices
std::vector< std::string > labels
A RooSimultaneous as older versions of RooFit wrote it, before HS3 had combined distributions....
std::vector< std::string > labels
std::vector< DistributionRef > distributions
Data sets or distributions that are selected by a key (HS3 #119). The columns are categorical axes of...
CombinedComponent< Ref_t > const * find(std::vector< std::string > const &key) const
The component for a key, or nullptr.
std::vector< CombinedComponent< Ref_t > > components
std::vector< std::string > columns
The axis of point data or unbinned data, which can't have a binning.
std::optional< double > max
std::optional< double > min
std::variant< GenericObject, HistFactoryDist, CombinedDist > body
The axis of a domain.
std::optional< double > min
std::optional< double > max
std::optional< Binning > binning
std::optional< double > fixedValue
std::vector< std::variant< DomainAxis, CategoricalAxis > > axes
std::vector< double > edges
A distribution or function that is not interpreted by the document, but by the importers that are reg...
The data of a likelihood term: a data set, a number given in-line, or none (std::monostate) in a pure...
DistributionRef distribution
std::variant< DataRef, double, std::monostate > data
bool pureModel
Whether "data" is null: the likelihood only groups the distributions of a model without data (e....
std::vector< DistributionRef > auxDistributions
std::vector< LikelihoodTerm > terms
std::string hs3Version
As it was written in the document, empty for fragments of a document.
Version version
The parsed version. Versions that can't be parsed count as the oldest one.
std::vector< Package > packages
std::optional< std::string > pdfName
std::optional< std::vector< std::string > > observables
The observables of the ModelConfig, written if no data set of the likelihood gives them.
std::optional< std::string > mcName
std::optional< std::string > combinedDataName
std::vector< ParameterValue > parameters
std::optional< std::variant< double, std::string > > value
A string selects the state of a category.
Options for upgradeDocument() and parseDocument().
bool typedHistFactory
If false, HistFactory distributions stay generic objects, because a user registered their own importe...
std::vector< ContinuousAxis > axes
A name that says what it refers to, so that for example a DataRef can't be used as a DomainRef.
Definition HS3Document.h:85
std::string name
Definition HS3Document.h:86
std::map< std::string, Attributes > attributes
std::map< std::string, std::vector< DistributionRef > > auxiliaryChannels
The components of a combined distribution that are auxiliary measurements (constraint terms paired wi...
std::map< std::string, std::vector< DistributionRef > > channelConstraints
The constraint terms of HistFactory distributions that no modifier names, by distribution.
std::vector< StepWidth > stepWidths
std::map< std::string, std::vector< std::string > > bookkeepingColumns
Axes that the components of a combined data set share, but that are no variate of any distribution,...
std::map< std::string, ModelConfigInfo > modelConfigs
The document that the tool is exporting.
std::map< std::string, std::string > constraintObservables
The observable of a constraint term, by the name of the term, see setConstraintObservable().
std::string rootName
The name of the top-level object whose export is in progress, and the depth of the export recursion.
std::optional< HistFactoryDist > typedObject
Set by the exporter of an object that is interpreted by the document.
std::map< std::string, std::vector< std::string > > constraintTermsOfPdf
The constraint terms of the exported HistFactory channels, as written, and the data sets written for ...
std::set< std::string > writtenConstraintData
std::map< std::string, HS3::CategoricalAxis > categories
The categories that are declared by categorical axes of the "default_domain", by name.
std::map< std::string, std::map< std::string, HS3::DomainAxis > > domains
The ranges and binnings of the exported variables, by domain and variable name.
std::vector< DistributionRef > channelConstraints
std::set< std::string > exportedObjectNames
Names of the objects written so far, to export each object once.
std::map< std::string, std::vector< RooAbsPdf const * > > arrayComponents
Array distributions to write at the end of the export: their components, and the array of each compon...
std::map< std::string, std::string > arrayOfComponent
std::map< std::string, std::vector< std::string > > auxiliaryLabels
The labels that the constraint terms that are written as components of a combined distribution add to...
What the tool needs to know about the document that it is importing.
ToolImportState(HS3Document const &doc)
std::unordered_map< std::string, HS3::Function const * > functions
std::set< std::string > componentsWithData
The components of combined distributions that have data, and are read as such.
HS3::ParameterPoint const * defaultValues
std::unordered_map< std::string, HS3::ParameterValue const * > defaultValuesByName
std::map< std::string, std::string > arrayComponentForms
The components of array distributions created in this import, by name, with their canonical form (see...
std::unordered_map< std::string, HS3::Distribution const * > distributions
Options for validate().
bool strict
Whether the document has to follow the current standard, or if older conventions of RooFit are tolera...
std::function< bool(std::string const &) isExternal)
Whether a name that is not defined in the document is known in some other way, e.g....
bool renameCombinedObservables
HS3 requires the components of a combined distribution to have distinct variates, e....
TLine l
Definition textangle.C:4