Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
JSONIOUtils.cxx
Go to the documentation of this file.
1#include "JSONIOUtils.h"
2
3#include <RooAbsBinning.h>
4#include <RooAbsLValue.h>
5#include <RooArgList.h>
6#include <RooCategory.h>
7#include <RooConstVar.h>
8#include <RooDataHist.h>
9#include <RooSuperCategory.h>
10#include <RooWorkspace.h>
13
14#include <algorithm>
15#include <cctype>
16#include <cstring>
17#include <set>
18#include <sstream>
19#include <string>
20#include <utility>
21
23
24// Parse the entire string as a number (integer or floating-point). The output is only valid if that succeeds.
25ToNumberOutput toNumber(const std::string &str)
26{
27 // std::from_chars for floating-point types is not portably available on all
28 // platforms ROOT supports, so we rely on the stream extraction.
29 std::istringstream stream(str);
30 ToNumberOutput output;
31 output.valid = (stream >> output.value) && stream.eof();
32 return output;
33}
34
35// True if `arg` is a RooConstVar whose name is a plain number (i.e. a literal constant).
37{
38 bool isRooConstVar = dynamic_cast<RooConstVar const *>(&arg);
39 return isRooConstVar && toNumber(arg.GetName()).valid;
40}
41
42// Write a reference to `arg`: the value if it is a literal constant, and the name otherwise.
43void writeReference(JSONNode &node, RooAbsArg const &arg)
44{
45 if (isLiteralConstVar(arg)) {
46 node << static_cast<RooConstVar const &>(arg).getVal();
47 } else {
48 node << arg.GetName();
49 }
50}
51
52bool startsWith(std::string_view str, std::string_view prefix)
53{
54 return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
55}
56
57bool endsWith(std::string_view str, std::string_view suffix)
58{
59 return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
60}
61
62std::string removeSuffix(std::string_view str, std::string_view suffix)
63{
64 std::string out;
65 out += str;
66 out = out.substr(0, out.length() - suffix.length());
67 return out;
68}
69
70// Writes a regular binning with "min", "max" and "nbins", and an irregular one with its "edges" only, since HS3 0.3
71// forbids "min" and "max" alongside them.
72void writeAxisBinning(JSONNode &node, const RooAbsBinning &binning)
73{
74 if (binning.isUniform()) {
75 node["min"] << binning.lowBound();
76 node["max"] << binning.highBound();
77 node["nbins"] << binning.numBins();
78 return;
79 }
80
81 auto &edges = node["edges"].set_seq();
82 edges.append_child() << binning.binLow(0);
83 for (int i = 0; i < binning.numBins(); ++i) {
84 edges.append_child() << binning.binHigh(i);
85 }
86}
87
88// Parse the leading "MAJOR.MINOR" of an HS3 version string like "0.2", "0.2.9" or "0.3".
89bool parseHS3Version(std::string const &version, int &major, int &minor)
90{
91 std::size_t pos = 0;
92 auto readNumber = [&](int &out) {
93 const std::size_t begin = pos;
94 while (pos < version.size() && std::isdigit(static_cast<unsigned char>(version[pos]))) {
95 ++pos;
96 }
97 // Reject empty and absurdly long numbers, which std::stoi could not represent.
98 if (pos == begin || pos - begin > 9) {
99 return false;
100 }
101 out = std::stoi(version.substr(begin, pos - begin));
102 return true;
103 };
104 if (!readNumber(major) || pos >= version.size() || version[pos] != '.') {
105 return false;
106 }
107 ++pos;
108 return readNumber(minor);
109}
110
111// Whether an HS3 version predates `major.minor`. Versions that can't be parsed count as old. That includes the empty
112// version of objects that are imported without a document.
113bool isHS3VersionBefore(std::string const &version, int major, int minor)
114{
115 int versionMajor = 0;
116 int versionMinor = 0;
117 if (!parseHS3Version(version, versionMajor, versionMinor)) {
118 return true;
119 }
120 return std::make_pair(versionMajor, versionMinor) < std::make_pair(major, minor);
121}
122
123namespace {
124
125std::vector<std::size_t> numBinsPerVariable(RooAbsCollection const &vars)
126{
127 std::vector<std::size_t> nBins;
128 for (RooAbsArg const *var : vars) {
129 nBins.push_back(static_cast<std::size_t>(dynamic_cast<RooAbsLValue const &>(*var).numBins()));
130 }
131 return nBins;
132}
133
134// The position in TH1 order (first variable fastest) of the bin with position `k` in RooDataHist/HS3 order (last
135// variable fastest).
136std::size_t th1Position(std::size_t k, std::vector<std::size_t> const &nBins)
137{
138 std::size_t th1 = 0;
139 std::size_t stride = 1;
140 std::vector<std::size_t> indices(nBins.size());
141 for (std::size_t j = nBins.size(); j-- > 0;) {
142 indices[j] = k % nBins[j];
143 k /= nBins[j];
144 }
145 for (std::size_t j = 0; j < nBins.size(); ++j) {
146 th1 += indices[j] * stride;
147 stride *= nBins[j];
148 }
149 return th1;
150}
151
152} // namespace
153
154std::unique_ptr<RooArgSet>
156{
157 auto out = std::make_unique<RooArgSet>();
158 for (RooAbsArg *var : *dh.get()) {
159 std::string name = var->GetName();
160 for (std::size_t i = 0; i < histObs.size() && i < funcObs.size(); ++i) {
161 if (name == histObs[i]->GetName() && dynamic_cast<RooAbsLValue const *>(funcObs[i])) {
162 name = funcObs[i]->GetName();
163 break;
164 }
165 }
166 out->addOwned(std::unique_ptr<RooAbsArg>{static_cast<RooAbsArg *>(var->clone(name.c_str()))});
167 }
168 return out;
169}
170
171std::vector<RooAbsReal *> paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
172{
173 std::vector<RooAbsReal *> out;
174 for (int k = 0; k < func.numBins(); ++k) {
175 out.push_back(&func.getParameter(k));
176 }
177 return out;
178}
179
180RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, RooAbsCollection const &vars)
181{
182 const std::vector<std::size_t> nBins = numBinsPerVariable(vars);
183 std::vector<RooAbsArg *> th1Order(paramsInBinOrder.size(), nullptr);
184 for (std::size_t k = 0; k < paramsInBinOrder.size(); ++k) {
185 const std::size_t t = th1Position(k, nBins);
186 if (t >= th1Order.size()) {
187 RooJSONFactoryWSTool::error("the number of parameters does not match the number of bins");
188 }
189 th1Order[t] = paramsInBinOrder.at(k);
190 }
191 RooArgList out;
192 for (RooAbsArg *arg : th1Order) {
193 out.add(*arg);
194 }
195 return out;
196}
197
198void checkParamHistFuncOrderIsDefined(std::string const &hs3Version, RooAbsCollection const &vars,
199 std::string const &context)
200{
201 if (vars.size() >= 2 && isHS3VersionBefore(hs3Version, 0, 3)) {
203 " has a multi-dimensional binning. Documents before HS3 0.3 don't define the order "
204 "of its per-bin parameters (RooFit wrote them in TH1 order, while the bin "
205 "contents use the order of HS3 0.3, last axis fastest). Please re-export the "
206 "workspace with a newer ROOT version.");
207 }
208}
209
210namespace {
211
212void sortByName(std::vector<RooCategory const *> &columns)
213{
214 std::sort(columns.begin(), columns.end(),
215 [](RooCategory const *l, RooCategory const *r) { return std::strcmp(l->GetName(), r->GetName()) < 0; });
216}
217
218} // namespace
219
220std::vector<RooCategory const *> selectionColumns(RooAbsCategory const &indexCat)
221{
222 std::vector<RooCategory const *> columns;
223 auto addColumn = [&](RooAbsArg const &arg) {
224 auto *cat = dynamic_cast<RooCategory const *>(&arg);
225 if (!cat) {
226 RooJSONFactoryWSTool::error("the index category '" + std::string(arg.GetName()) + "' is a " + arg.ClassName() +
227 ", but only a RooCategory or a RooSuperCategory of RooCategories " +
228 "can be written as the columns of a combined distribution");
229 }
230 columns.push_back(cat);
231 };
232 if (auto *super = dynamic_cast<RooSuperCategory const *>(&indexCat)) {
233 for (RooAbsArg const *input : super->inputCatList()) {
234 addColumn(*input);
235 }
236 } else {
237 addColumn(indexCat);
238 }
239 sortByName(columns);
240 return columns;
241}
242
243std::vector<RooCategory const *> selectionColumns(RooAbsCollection const &vars)
244{
245 std::vector<RooCategory const *> columns;
246 for (RooAbsArg const *arg : vars) {
247 if (auto *cat = dynamic_cast<RooCategory const *>(arg)) {
248 columns.push_back(cat);
249 }
250 }
251 sortByName(columns);
252 return columns;
253}
254
255std::vector<std::vector<std::string>> selectionKeys(std::vector<RooCategory const *> const &columns)
256{
257 std::vector<std::vector<std::string>> keys{{}};
258 for (RooCategory const *column : columns) {
259 std::vector<std::vector<std::string>> next;
260 for (auto const &key : keys) {
261 for (unsigned int i = 0; i < column->size(); ++i) {
262 next.push_back(key);
263 next.back().push_back(column->getOrdinal(i).first);
264 }
265 }
266 keys = std::move(next);
267 }
268 return keys;
269}
270
271std::string selectionLabel(std::vector<std::string> const &key)
272{
273 if (key.size() == 1) {
274 return key.front();
275 }
276 std::string label = "{";
277 for (std::size_t i = 0; i < key.size(); ++i) {
278 label += (i == 0 ? "" : ";") + key[i];
279 }
280 return label + "}";
281}
282
283std::string selectionKeyToString(std::vector<std::string> const &key)
284{
285 std::string out = "[";
286 for (std::size_t i = 0; i < key.size(); ++i) {
287 out += (i == 0 ? "\"" : ", \"") + key[i] + "\"";
288 }
289 return out + "]";
290}
291
292std::string selectionLabel(RooAbsCategory const &indexCat, std::vector<RooCategory const *> const &columns,
293 std::vector<std::string> const &key)
294{
295 auto *super = dynamic_cast<RooSuperCategory const *>(&indexCat);
296 if (!super) {
297 return key.front();
298 }
299 std::vector<std::string> inInputOrder;
300 for (RooAbsArg const *input : super->inputCatList()) {
301 auto found = std::find_if(columns.begin(), columns.end(),
302 [&](RooCategory const *c) { return std::strcmp(c->GetName(), input->GetName()) == 0; });
303 inInputOrder.push_back(key[found - columns.begin()]);
304 }
305 return selectionLabel(inInputOrder);
306}
307
308std::vector<RooCategory *>
309readSelectionColumns(RooWorkspace const &ws, JSONNode const &node, const char *field, std::string const &context)
310{
311 auto const *list = node.find(field);
312 if (!list || !list->is_seq() || list->num_children() == 0) {
313 RooJSONFactoryWSTool::error("\"" + std::string(field) + "\" of " + context +
314 " must be a non-empty list of names of categorical axes");
315 }
316 std::vector<RooCategory *> columns;
317 for (JSONNode const &child : list->children()) {
318 if (child.is_container() || child.val().empty()) {
319 RooJSONFactoryWSTool::error("\"" + std::string(field) + "\" of " + context +
320 " must be a non-empty list of names of categorical axes");
321 }
322 RooCategory *cat = ws.cat(child.val());
323 if (!cat) {
324 RooJSONFactoryWSTool::error("the column '" + child.val() + "' of " + context +
325 " is not declared by a categorical axis of a domain");
326 }
327 if (std::find(columns.begin(), columns.end(), cat) != columns.end()) {
328 RooJSONFactoryWSTool::error("the column '" + child.val() + "' of " + context + " is listed twice");
329 }
330 columns.push_back(cat);
331 }
332 return columns;
333}
334
335std::vector<std::string>
336readSelectionKey(JSONNode const &component, std::vector<RooCategory *> const &columns, std::string const &context)
337{
338 auto const *keyNode = component.find("key");
339 if (!keyNode || !keyNode->is_seq() || keyNode->num_children() != columns.size()) {
340 RooJSONFactoryWSTool::error("every component of " + context + " must have a \"key\" with " +
341 std::to_string(columns.size()) + " labels, one per column");
342 }
343 std::vector<std::string> key;
344 std::size_t i = 0;
345 for (JSONNode const &label : keyNode->children()) {
346 if (label.is_container() || !columns[i]->hasLabel(label.val())) {
347 RooJSONFactoryWSTool::error("the label '" + (label.is_container() ? std::string("") : label.val()) +
348 "' in position " + std::to_string(i) + " of a key of " + context +
349 " is not one of the categories of '" + columns[i]->GetName() + "'");
350 }
351 key.push_back(label.val());
352 ++i;
353 }
354 return key;
355}
ToNumberOutput 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 isHS3VersionBefore(std::string const &version, int major, int minor)
std::vector< RooCategory const * > selectionColumns(RooAbsCategory const &indexCat)
std::vector< RooAbsReal * > paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, RooAbsCollection const &vars)
std::string selectionKeyToString(std::vector< std::string > const &key)
bool startsWith(std::string_view str, std::string_view prefix)
std::vector< RooCategory * > readSelectionColumns(RooWorkspace const &ws, JSONNode const &node, const char *field, std::string const &context)
bool endsWith(std::string_view str, std::string_view suffix)
std::string selectionLabel(std::vector< std::string > const &key)
std::vector< std::string > readSelectionKey(JSONNode const &component, std::vector< RooCategory * > const &columns, std::string const &context)
bool isLiteralConstVar(RooAbsArg const &arg)
std::string removeSuffix(std::string_view str, std::string_view suffix)
void writeAxisBinning(JSONNode &node, const RooAbsBinning &binning)
std::unique_ptr< RooArgSet > histogramVariablesNamedAfterObservables(RooDataHist const &dh, RooArgSet const &histObs, RooArgSet const &funcObs)
bool parseHS3Version(std::string const &version, int &major, int &minor)
void checkParamHistFuncOrderIsDefined(std::string const &hs3Version, RooAbsCollection const &vars, std::string const &context)
#define c(i)
Definition RSha256.hxx:101
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 r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t child
char name[80]
Definition TGX11.cxx:142
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
Int_t numBins() const
RooAbsReal & getParameter() const
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.
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
A space to attach TBranches.
Abstract container object that can hold multiple RooAbsArg objects.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Storage_t::size_type size() const
Abstract base class for objects that are lvalues, i.e.
virtual Int_t numBins(const char *rangeName=nullptr) const =0
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
Object to represent discrete states.
Definition RooCategory.h:28
Represents a constant real-valued object.
Definition RooConstVar.h:23
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
const RooArgSet * get() const override
Get bin centre of current bin.
Definition RooDataHist.h:82
JSONNode const * find(std::string const &key) const
static void error(const char *s)
Writes an error message to the RooFit message service and throws a runtime_error.
Joins several RooAbsCategoryLValue objects into a single category.
Persistable container for RooFit projects.
RooCategory * cat(RooStringView name) const
Retrieve discrete variable (RooCategory) with given name. A null pointer is returned if not found.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
auto * th1
Definition textalign.C:14
TLine l
Definition textangle.C:4