Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
JSONIOUtils.h
Go to the documentation of this file.
1#ifndef JSONIOUtils_h
2#define JSONIOUtils_h
3
4#include <map>
5#include <memory>
6#include <optional>
7#include <string>
8#include <string_view>
9#include <type_traits>
10#include <utility>
11#include <vector>
13#include <RooFitHS3/JSONIO.h>
14
15#include "HS3Document.h"
16
17class RooAbsArg;
18class RooAbsBinning;
19class RooAbsCategory;
21class RooAbsPdf;
22class RooAbsReal;
23class RooArgList;
24class RooArgSet;
25class RooCategory;
26class RooDataHist;
28class RooWorkspace;
29class ParamHistFunc;
30
31// A RooProdPdf with this attribute represents an HS3 `array_dist`: a product of one-dimensional distributions of one
32// type, each over its own observable. The factors are the components, imported as individual pdfs named after their
33// observable.
34inline constexpr const char *arrayDistTag = "hs3_array_dist";
35
36// An object with this attribute is a helper: RooFit created it to represent something of an HS3 document that it has
37// no class for, e.g. the RooProdPdf that holds the components of an array distribution together, or the parts of a
38// composite structure that stands for one HS3 object. A helper is not a statement of the user about the model, so:
39// - it is only written if another object that is written refers to it by name, or if the HS3 object that it stands
40// for is written (see isSkippedHelper()), but not just because it is in the workspace;
41// - a helper that is not written is ignored wherever the export looks at the users of an object, e.g. to decide
42// whether the object is a top-level object or whether a constraint can be a component of an array.
43// The attribute is set by the importers and is not written to the document. Objects created by users don't have it
44// and are always written.
45inline constexpr const char *helperObjectTag = "hs3_helper";
46
47// True if `arg` is a RooConstVar whose name is a plain number (i.e. a literal constant).
48bool isLiteralConstVar(RooAbsArg const &arg);
49
50// Whether the export of the workspace `ws` does not write `arg`: a helper (see helperObjectTag) that nothing written
51// refers to, i.e. it has no clients in the workspace other than helpers that are skipped themselves and no ModelConfig
52// names it; a helper that stands for an HS3 object of its own (an array distribution) and that nothing in the
53// workspace uses is written as that object. The property is weakly transitive: any other object whose clients in the
54// workspace are all skipped, and that no ModelConfig names, is skipped as well, so that what only a skipped helper
55// uses is not written either. An array distribution that is skipped dissolves into its components, which are written
56// on their own: it doesn't count as a user of them. Such an object is treated as if it were not in the workspace.
57bool isSkippedHelper(RooAbsArg const &arg, RooWorkspace const &ws);
58
59// The HS3 type, the observable and the other fields of `pdf` as a component of an array distribution (RooPoisson,
60// RooGaussian or RooLognormal, over a named observable), or std::nullopt if `pdf` cannot be a component. The fields
61// are the ones of the exporter of its class.
62// If `observable` names the mean of a RooGaussian, the Gaussian is written with x and mean swapped (see
63// RooJSONFactoryWSTool::setConstraintObservable()). The functions that a field names, e.g. for a RooLognormal that is
64// not in the standard parametrization, are only written if there is a `tool`; without one, this only describes the
65// component.
67 std::string type;
68 std::string observable;
69 std::vector<std::pair<std::string, RooFit::HS3::NameOrNumber>> fields;
70};
71std::optional<ArrayComponentInfo>
72arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable = nullptr, RooJSONFactoryWSTool *tool = nullptr);
73
74// Write the array distribution `name` with the given components into `elem`. The `tool` knows the observables that
75// are recorded for the components, and writes the functions that they need besides, e.g. for a RooLognormal that is
76// not in the standard parametrization.
77void writeArrayDist(RooJSONFactoryWSTool &tool, RooFit::Detail::JSONNode &elem, std::string const &name,
78 std::vector<RooAbsPdf const *> const &components);
79
80// The number that a string spells as a whole, if it does.
81std::optional<double> toNumber(const std::string &str);
83bool startsWith(std::string_view str, std::string_view prefix);
84bool endsWith(std::string_view str, std::string_view suffix);
85std::string removeSuffix(std::string_view str, std::string_view suffix);
86
87// Some RooFit classes are parametrized differently than their HS3 distribution, e.g. RooLognormal by default. They
88// are written with a function of the parameter (RooJSONFactoryWSTool::exportTransformed()), which is named after the
89// parameter with a suffix that says what the function is. A literal constant has no name that could be part of an
90// identifier ("1.2", "-3", "1e-05"), so its value is spelled as one: "const_1p2", "const_m3", "const_1em05".
91//
92// What a transformed function is named after: the name of the parameter, or the identifier for the value of a
93// literal constant.
94std::string transformedBaseName(RooAbsReal const &param);
95// What a transformed function is a function of: the name of the parameter, or the value of a literal constant with
96// as many digits as it takes to read it back unchanged (in parentheses if it is negative).
97std::string transformedArgument(RooAbsReal const &param);
98// The inverse: what to create the RooFit object from, given the name of a transformed function with this suffix. This
99// is the name of the parameter, or the value of a literal constant as a string.
100std::string transformedOriginal(std::string_view name, std::string_view suffix);
101// Whether a name is the identifier for the value of a literal constant.
102bool isLiteralIdentifier(std::string_view name);
103
104// A RooHistFunc or RooHistPdf is evaluated with its own observables (`funcObs`), which are mapped by position onto
105// the variables of its histogram (`histObs`) and need not have the same names, e.g. after a RooCustomizer replaced
106// them. The variables of the histogram `dh`, in the order of the histogram, each named after the observable that is
107// mapped onto it, so that the axes are written with the names of the observables. A variable onto which no variable
108// or category is mapped keeps its name.
109std::unique_ptr<RooArgSet>
110histogramVariablesNamedAfterObservables(RooDataHist const &dh, RooArgSet const &histObs, RooArgSet const &funcObs);
111
112// ParamHistFunc orders its parameters like the bins of a TH1 (first variable fastest), while HS3 lays out per-bin
113// arrays with the last axis varying fastest, like RooDataHist. These helpers convert at the HS3 boundary.
114std::vector<RooAbsReal *> paramHistFuncParamsInBinOrder(ParamHistFunc const &func);
115RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, RooAbsCollection const &vars);
116// Documents before HS3 0.3 wrote the parameters of multi-dimensional ParamHistFuncs in TH1 order. No such documents
117// are known; they are rejected instead of being guessed.
119 std::string const &context);
120
121// Selection keys (HS3 "combined" data sets and "combined_dist"): a key is one label per column, and the columns are
122// categories declared by categorical axes of the domains. In RooFit, the columns are the index category of a
123// RooSimultaneous (a RooCategory), or the input categories of a RooSuperCategory index, or the category observables
124// of a combined data set. They are sorted by name, so that a distribution and a data set agree on the order of the
125// columns without looking at each other.
126std::vector<RooCategory const *> selectionColumns(RooAbsCategory const &indexCat);
127std::vector<RooCategory const *> selectionColumns(RooAbsCollection const &vars);
128// All keys of the columns, in the order of the columns and of their states, with the first column varying slowest.
129std::vector<std::vector<std::string>> selectionKeys(std::vector<RooCategory const *> const &columns);
130// The state label of a RooCategory (one column) or of a RooSuperCategory over the columns in that order.
131std::string selectionLabel(std::vector<std::string> const &key);
132// The state label of `indexCat` for a key with the labels in the order of `columns`: the label itself for a
133// RooCategory, or "{a;b}" with the labels in the order of the inputs for a RooSuperCategory.
134std::string selectionLabel(RooAbsCategory const &indexCat, std::vector<RooCategory const *> const &columns,
135 std::vector<std::string> const &key);
136// A key as written in the document, for messages: ["a", "b"].
137std::string selectionKeyToString(std::vector<std::string> const &key);
138
139// Adapters that wrap plain import and export functions into the RooFit::JSONIO::Importer and Exporter interface, for
140// the importers and exporters that RooFit registers itself.
141
142// An import function that returns nothing always reads the object. One that returns a bool can decline by returning
143// false, so that the next importer of the type key is tried.
144template <class ImportFunc>
146public:
147 explicit FuncImporter(ImportFunc func) : _func{func} {}
148 bool importArg(RooJSONFactoryWSTool *tool, const RooFit::Detail::JSONNode &p) const override
149 {
150 if constexpr (std::is_void_v<decltype(_func(tool, p))>) {
151 _func(tool, p);
152 return true;
153 } else {
154 return _func(tool, p);
155 }
156 }
157
158private:
159 const ImportFunc _func;
160};
161
162template <class RooArg_t>
163using ExportFunc = void (*)(RooJSONFactoryWSTool *, RooArg_t const &, RooFit::Detail::JSONNode &);
164
165// The exporter of the class RooArg_t writes the HS3 type key that the export function is registered with. A function
166// overwrites it if the type depends on the object.
167template <class RooArg_t, class Func>
169public:
170 FuncExporter(Func func, std::string key, bool autoExportDependants)
172 {
173 }
174 std::string const &key() const override { return _key; }
175 bool autoExportDependants() const override { return _autoExportDependants; }
176 bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *arg, RooFit::Detail::JSONNode &elem) const override
177 {
178 elem["type"] << _key;
179 _func(tool, static_cast<RooArg_t const &>(*arg), elem);
180 return true;
181 }
182
183private:
184 const Func _func;
185 const std::string _key;
187};
188
189// The importers of a type key and the exporters of a class are tried in the order of their registration.
190template <class ImportFunc>
191void registerImporter(const std::string &key, ImportFunc func)
192{
193 RooFit::JSONIO::registerImporter(key, std::make_unique<FuncImporter<ImportFunc>>(func), false);
194}
195
196template <class RooArg_t, class Func>
197void registerExporter(std::string key, Func func, bool autoExportDependants = true)
198{
200 RooArg_t::Class(), std::make_unique<FuncExporter<RooArg_t, Func>>(func, std::move(key), autoExportDependants),
201 false);
202}
203
204// A class that is read and written with the same type key.
205template <class ImportFunc, class RooArg_t>
206void registerType(const std::string &key, ImportFunc importFunc, ExportFunc<RooArg_t> exportFunc,
207 bool autoExportDependants = true)
208{
209 registerImporter(key, importFunc);
210 registerExporter<RooArg_t>(key, exportFunc, autoExportDependants);
211}
212
213#endif
std::optional< double > toNumber(const std::string &str)
void checkParamHistFuncOrderIsDefined(RooFit::HS3::Version const &version, RooAbsCollection const &vars, std::string const &context)
void writeArrayDist(RooJSONFactoryWSTool &tool, RooFit::Detail::JSONNode &elem, std::string const &name, std::vector< RooAbsPdf const * > const &components)
constexpr const char * helperObjectTag
Definition JSONIOUtils.h:45
bool isSkippedHelper(RooAbsArg const &arg, RooWorkspace const &ws)
std::vector< std::vector< std::string > > selectionKeys(std::vector< RooCategory const * > const &columns)
std::string transformedOriginal(std::string_view name, std::string_view suffix)
void registerExporter(std::string key, Func func, bool autoExportDependants=true)
bool isLiteralIdentifier(std::string_view name)
std::string transformedBaseName(RooAbsReal const &param)
std::vector< RooCategory const * > selectionColumns(RooAbsCategory const &indexCat)
std::vector< RooAbsReal * > paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
std::string transformedArgument(RooAbsReal const &param)
void(*)(RooJSONFactoryWSTool *, RooArg_t const &, RooFit::Detail::JSONNode &) ExportFunc
RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, RooAbsCollection const &vars)
std::string selectionKeyToString(std::vector< std::string > const &key)
constexpr const char * arrayDistTag
Definition JSONIOUtils.h:34
bool startsWith(std::string_view str, std::string_view prefix)
bool endsWith(std::string_view str, std::string_view suffix)
std::optional< ArrayComponentInfo > arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable=nullptr, RooJSONFactoryWSTool *tool=nullptr)
std::string selectionLabel(std::vector< std::string > const &key)
bool isLiteralConstVar(RooAbsArg const &arg)
std::string removeSuffix(std::string_view str, std::string_view suffix)
std::unique_ptr< RooArgSet > histogramVariablesNamedAfterObservables(RooDataHist const &dh, RooArgSet const &histObs, RooArgSet const &funcObs)
void writeReference(RooFit::Detail::JSONNode &node, RooAbsArg const &arg)
void registerImporter(const std::string &key, ImportFunc func)
void registerType(const std::string &key, ImportFunc importFunc, ExportFunc< RooArg_t > exportFunc, bool autoExportDependants=true)
winID h TVirtualViewer3D TVirtualGLPainter p
char name[80]
Definition TGX11.cxx:142
const std::string _key
const Func _func
bool autoExportDependants() const override
bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *arg, RooFit::Detail::JSONNode &elem) const override
FuncExporter(Func func, std::string key, bool autoExportDependants)
std::string const & key() const override
const bool _autoExportDependants
FuncImporter(ImportFunc func)
const ImportFunc _func
bool importArg(RooJSONFactoryWSTool *tool, const RooFit::Detail::JSONNode &p) const override
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
Abstract base class for RooRealVar binning definitions.
A space to attach TBranches.
Abstract container object that can hold multiple RooAbsArg objects.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
Object to represent discrete states.
Definition RooCategory.h:28
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
When using RooFit, statistical models can be conveniently handled and stored as a RooWorkspace.
Persistable container for RooFit projects.
static bool registerImporter(const std::string &key, bool topPriority=true)
Definition JSONIO.h:73
static bool registerExporter(const TClass *key, bool topPriority=true)
Definition JSONIO.h:78
std::vector< std::pair< std::string, RooFit::HS3::NameOrNumber > > fields
Definition JSONIOUtils.h:69
std::string observable
Definition JSONIOUtils.h:68
std::string type
Definition JSONIOUtils.h:67