Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
JSONIOUtils.cxx
Go to the documentation of this file.
1#include "JSONIOUtils.h"
2
3#include <RooAbsLValue.h>
4#include <RooArgList.h>
5#include <RooCategory.h>
6#include <RooConstVar.h>
7#include <RooDataHist.h>
8#include <RooSuperCategory.h>
9#include <RooWorkspace.h>
12
13#include <algorithm>
14#include <cctype>
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <set>
19#include <sstream>
20#include <string>
21#include <utility>
22
24
25std::optional<double> 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 double value = 0.0;
31 return (stream >> value) && stream.eof() ? std::optional<double>{value} : std::nullopt;
32}
33
34// True if `arg` is a RooConstVar whose name is a plain number (i.e. a literal constant).
36{
37 return dynamic_cast<RooConstVar const *>(&arg) && toNumber(arg.GetName());
38}
39
40// Write a reference to `arg`: the value if it is a literal constant, and the name otherwise.
41void writeReference(JSONNode &node, RooAbsArg const &arg)
42{
43 if (isLiteralConstVar(arg)) {
44 node << static_cast<RooConstVar const &>(arg).getVal();
45 } else {
46 node << arg.GetName();
47 }
48}
49
50bool startsWith(std::string_view str, std::string_view prefix)
51{
52 return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix);
53}
54
55bool endsWith(std::string_view str, std::string_view suffix)
56{
57 return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix);
58}
59
60std::string removeSuffix(std::string_view str, std::string_view suffix)
61{
62 std::string out;
63 out += str;
64 out = out.substr(0, out.length() - suffix.length());
65 return out;
66}
67
68namespace {
69
70constexpr std::string_view literalPrefix = "const_";
71
72// The shortest decimal representation of a value that is read back as the same value.
73std::string shortestNumber(double value)
74{
75 char buffer[32];
76 for (int precision = 1; precision <= 17; ++precision) {
77 std::snprintf(buffer, sizeof(buffer), "%.*g", precision, value);
78 if (std::strtod(buffer, nullptr) == value) {
79 break;
80 }
81 }
82 return buffer;
83}
84
85// The number that the identifier of a literal constant spells, or an empty string if `name` is no such identifier.
86std::string numberOfLiteralIdentifier(std::string_view name)
87{
88 if (!startsWith(name, literalPrefix) || name.size() == literalPrefix.size()) {
89 return "";
90 }
91 std::string number;
92 for (char c : name.substr(literalPrefix.size())) {
93 if (c == 'p') {
94 number += '.';
95 } else if (c == 'm') {
96 number += '-';
97 } else if (std::isdigit(static_cast<unsigned char>(c)) || c == 'e') {
98 number += c;
99 } else {
100 return "";
101 }
102 }
103 char *end = nullptr;
104 std::strtod(number.c_str(), &end);
105 return end == number.c_str() + number.size() ? number : "";
106}
107
108} // namespace
109
110std::string transformedArgument(RooAbsReal const &param)
111{
112 if (!isLiteralConstVar(param)) {
113 return param.GetName();
114 }
115 // In parentheses if negative, such that "-%s" doesn't become "--1".
116 const std::string number = shortestNumber(param.getVal());
117 return number[0] == '-' ? "(" + number + ")" : number;
118}
119
120std::string transformedBaseName(RooAbsReal const &param)
121{
122 if (!isLiteralConstVar(param)) {
123 return param.GetName();
124 }
125 std::string out{literalPrefix};
126 for (char c : shortestNumber(param.getVal())) {
127 if (c == '.') {
128 out += 'p';
129 } else if (c == '-') {
130 out += 'm';
131 } else if (c != '+') {
132 out += c;
133 }
134 }
135 return out;
136}
137
138bool isLiteralIdentifier(std::string_view name)
139{
140 return !numberOfLiteralIdentifier(name).empty();
141}
142
143std::string transformedOriginal(std::string_view name, std::string_view suffix)
144{
145 const std::string base = removeSuffix(name, suffix);
146 const std::string number = numberOfLiteralIdentifier(base);
147 return number.empty() ? base : number;
148}
149
150namespace {
151
152std::vector<std::size_t> numBinsPerVariable(RooAbsCollection const &vars)
153{
154 std::vector<std::size_t> nBins;
155 for (RooAbsArg const *var : vars) {
156 nBins.push_back(static_cast<std::size_t>(dynamic_cast<RooAbsLValue const &>(*var).numBins()));
157 }
158 return nBins;
159}
160
161// The position in TH1 order (first variable fastest) of the bin with position `k` in RooDataHist/HS3 order (last
162// variable fastest).
163std::size_t th1Position(std::size_t k, std::vector<std::size_t> const &nBins)
164{
165 std::size_t th1 = 0;
166 std::size_t stride = 1;
167 std::vector<std::size_t> indices(nBins.size());
168 for (std::size_t j = nBins.size(); j-- > 0;) {
169 indices[j] = k % nBins[j];
170 k /= nBins[j];
171 }
172 for (std::size_t j = 0; j < nBins.size(); ++j) {
173 th1 += indices[j] * stride;
174 stride *= nBins[j];
175 }
176 return th1;
177}
178
179} // namespace
180
181std::unique_ptr<RooArgSet>
183{
184 auto out = std::make_unique<RooArgSet>();
185 for (RooAbsArg *var : *dh.get()) {
186 std::string name = var->GetName();
187 for (std::size_t i = 0; i < histObs.size() && i < funcObs.size(); ++i) {
188 if (name == histObs[i]->GetName() && dynamic_cast<RooAbsLValue const *>(funcObs[i])) {
189 name = funcObs[i]->GetName();
190 break;
191 }
192 }
193 out->addOwned(std::unique_ptr<RooAbsArg>{static_cast<RooAbsArg *>(var->clone(name.c_str()))});
194 }
195 return out;
196}
197
198std::vector<RooAbsReal *> paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
199{
200 std::vector<RooAbsReal *> out;
201 for (int k = 0; k < func.numBins(); ++k) {
202 out.push_back(&func.getParameter(k));
203 }
204 return out;
205}
206
207RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, RooAbsCollection const &vars)
208{
209 const std::vector<std::size_t> nBins = numBinsPerVariable(vars);
210 std::vector<RooAbsArg *> th1Order(paramsInBinOrder.size(), nullptr);
211 for (std::size_t k = 0; k < paramsInBinOrder.size(); ++k) {
212 const std::size_t t = th1Position(k, nBins);
213 if (t >= th1Order.size()) {
214 RooJSONFactoryWSTool::error("the number of parameters does not match the number of bins");
215 }
216 th1Order[t] = paramsInBinOrder.at(k);
217 }
218 RooArgList out;
219 for (RooAbsArg *arg : th1Order) {
220 out.add(*arg);
221 }
222 return out;
223}
224
226 std::string const &context)
227{
228 if (vars.size() >= 2 && version < RooFit::HS3::Version{0, 3}) {
230 " has a multi-dimensional binning. Documents before HS3 0.3 don't define the order "
231 "of its per-bin parameters (RooFit wrote them in TH1 order, while the bin "
232 "contents use the order of HS3 0.3, last axis fastest). Please re-export the "
233 "workspace with a newer ROOT version.");
234 }
235}
236
237namespace {
238
239void sortByName(std::vector<RooCategory const *> &columns)
240{
241 std::sort(columns.begin(), columns.end(),
242 [](RooCategory const *l, RooCategory const *r) { return std::strcmp(l->GetName(), r->GetName()) < 0; });
243}
244
245} // namespace
246
247std::vector<RooCategory const *> selectionColumns(RooAbsCategory const &indexCat)
248{
249 std::vector<RooCategory const *> columns;
250 auto addColumn = [&](RooAbsArg const &arg) {
251 auto *cat = dynamic_cast<RooCategory const *>(&arg);
252 if (!cat) {
253 RooJSONFactoryWSTool::error("the index category '" + std::string(arg.GetName()) + "' is a " + arg.ClassName() +
254 ", but only a RooCategory or a RooSuperCategory of RooCategories " +
255 "can be written as the columns of a combined distribution");
256 }
257 columns.push_back(cat);
258 };
259 if (auto *super = dynamic_cast<RooSuperCategory const *>(&indexCat)) {
260 for (RooAbsArg const *input : super->inputCatList()) {
261 addColumn(*input);
262 }
263 } else {
264 addColumn(indexCat);
265 }
266 sortByName(columns);
267 return columns;
268}
269
270std::vector<RooCategory const *> selectionColumns(RooAbsCollection const &vars)
271{
272 std::vector<RooCategory const *> columns;
273 for (RooAbsArg const *arg : vars) {
274 if (auto *cat = dynamic_cast<RooCategory const *>(arg)) {
275 columns.push_back(cat);
276 }
277 }
278 sortByName(columns);
279 return columns;
280}
281
282std::vector<std::vector<std::string>> selectionKeys(std::vector<RooCategory const *> const &columns)
283{
284 std::vector<std::vector<std::string>> keys{{}};
285 for (RooCategory const *column : columns) {
286 std::vector<std::vector<std::string>> next;
287 for (auto const &key : keys) {
288 for (unsigned int i = 0; i < column->size(); ++i) {
289 next.push_back(key);
290 next.back().push_back(column->getOrdinal(i).first);
291 }
292 }
293 keys = std::move(next);
294 }
295 return keys;
296}
297
298std::string selectionLabel(std::vector<std::string> const &key)
299{
300 if (key.size() == 1) {
301 return key.front();
302 }
303 std::string label = "{";
304 for (std::size_t i = 0; i < key.size(); ++i) {
305 label += (i == 0 ? "" : ";") + key[i];
306 }
307 return label + "}";
308}
309
310std::string selectionKeyToString(std::vector<std::string> const &key)
311{
312 std::string out = "[";
313 for (std::size_t i = 0; i < key.size(); ++i) {
314 out += (i == 0 ? "\"" : ", \"") + key[i] + "\"";
315 }
316 return out + "]";
317}
318
319std::string selectionLabel(RooAbsCategory const &indexCat, std::vector<RooCategory const *> const &columns,
320 std::vector<std::string> const &key)
321{
322 auto *super = dynamic_cast<RooSuperCategory const *>(&indexCat);
323 if (!super) {
324 return key.front();
325 }
326 std::vector<std::string> inInputOrder;
327 for (RooAbsArg const *input : super->inputCatList()) {
328 auto found = std::find_if(columns.begin(), columns.end(),
329 [&](RooCategory const *c) { return std::strcmp(c->GetName(), input->GetName()) == 0; });
330 inInputOrder.push_back(key[found - columns.begin()]);
331 }
332 return selectionLabel(inInputOrder);
333}
std::optional< double > toNumber(const std::string &str)
void checkParamHistFuncOrderIsDefined(RooFit::HS3::Version const &version, RooAbsCollection const &vars, std::string const &context)
std::vector< std::vector< std::string > > selectionKeys(std::vector< RooCategory const * > const &columns)
void writeReference(JSONNode &node, RooAbsArg const &arg)
std::string transformedOriginal(std::string_view name, std::string_view suffix)
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)
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)
bool endsWith(std::string_view str, std::string_view suffix)
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)
#define c(i)
Definition RSha256.hxx:101
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
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 value
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
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
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
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
static void error(const char *s)
Write an error to the RooFit message service, and throw it as a std::runtime_error.
Joins several RooAbsCategoryLValue objects into a single category.
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