Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HS3Writer.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Jonas Rembser, CERN, Nov 2026
5 *
6 * Copyright (c) 2026, 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// Writes the typed representation of HS3 documents, with the keys that HS3Parser.cxx reads.
14
15#include "HS3Document.h"
16
18
19#include <algorithm>
20#include <cmath>
21
23
24namespace RooFit {
25namespace HS3 {
26namespace {
27
28// The counterparts of the readValue() functions of the parser, for the values that are written in one way only.
29template <class T>
30void writeValue(JSONNode &node, T const &value)
31{
32 node << value;
33}
34
35template <class Tag>
36void writeValue(JSONNode &node, Ref<Tag> const &ref)
37{
38 node << ref.name;
39}
40
41void writeValue(JSONNode &node, NameOrNumber const &value)
42{
43 std::visit([&](auto const &v) { node << v; }, value);
44}
45
46template <class T>
47void writeValue(JSONNode &node, std::vector<T> const &values)
48{
49 node.set_seq();
50 for (auto const &value : values) {
51 writeValue(node.append_child(), value);
52 }
53}
54
55// A component that is left out if it has no value.
56template <class T>
57void writeOptional(JSONNode &node, const char *key, std::optional<T> const &value)
58{
59 if (value) {
60 writeValue(node[key], *value);
61 }
62}
63
64// Writes a number, as an integer if it has no fractional part.
65void writeNumber(JSONNode &node, double value)
66{
67 if (static_cast<int>(value) == value) {
68 node << static_cast<int>(value);
69 } else {
70 node << value;
71 }
72}
73
74JSONNode &appendNamed(JSONNode &array, std::string const &name)
75{
77 child["name"] << name;
78 return child;
79}
80
81void writeBinning(JSONNode &node, Binning const &binning)
82{
83 if (auto const *edges = std::get_if<EdgesBinning>(&binning)) {
84 node["edges"].fill_seq(edges->edges);
85 } else {
86 node["nbins"] << std::get<RegularBinning>(binning).nbins;
87 }
88}
89
90// An infinite or missing bound of a continuous data axis is omitted, which means that the range is unbounded. JSON null
91// is not defined for bounds.
92void writeAxis(JSONNode &node, ContinuousAxis const &axis)
93{
94 node.set_map();
95 node["name"] << axis.name;
96 if (axis.min && !std::isinf(*axis.min)) {
97 node["min"] << *axis.min;
98 }
99 if (axis.max && !std::isinf(*axis.max)) {
100 node["max"] << *axis.max;
101 }
102}
103
104void writeAxis(JSONNode &node, CategoricalAxis const &axis)
105{
106 node.set_map();
107 node["name"] << axis.name;
108 node["categories"].fill_seq(axis.categories);
109}
110
111// An infinite or missing bound of a domain axis is omitted, which means that the range is unbounded.
112void writeAxis(JSONNode &node, DomainAxis const &axis)
113{
114 node.set_map();
115 node["name"] << axis.name;
116 if (axis.fixedValue) {
117 node["value"] << *axis.fixedValue;
118 return;
119 }
120 // HS3 0.3 forbids "min" and "max" alongside "edges", which give the range. They are only written if they differ from
121 // the edges, which would otherwise be lost.
122 auto const *edges = axis.binning ? std::get_if<EdgesBinning>(&*axis.binning) : nullptr;
123 const bool rangeFromEdges = edges && !edges->edges.empty() && axis.min && axis.max &&
124 *axis.min == edges->edges.front() && *axis.max == edges->edges.back();
125 if (!rangeFromEdges && axis.min && !std::isinf(*axis.min)) {
126 node["min"] << *axis.min;
127 }
128 if (!rangeFromEdges && axis.max && !std::isinf(*axis.max)) {
129 node["max"] << *axis.max;
130 }
131 if (axis.binning) {
132 writeBinning(node, *axis.binning);
133 }
134}
135
136template <class... Axes>
137void writeAxes(JSONNode &node, std::vector<std::variant<Axes...>> const &axes)
138{
139 node.set_seq();
140 for (auto const &axis : axes) {
141 std::visit([&](auto const &a) { writeAxis(node.append_child(), a); }, axis);
142 }
143}
144
145template <class Axis>
146void writeAxes(JSONNode &node, std::vector<Axis> const &axes)
147{
148 node.set_seq();
149 for (auto const &axis : axes) {
150 writeAxis(node.append_child(), axis);
151 }
152}
153
154// The parameter of a modifier with a single parameter, and the name of its constraint distribution. A constraint type
155// is written in the form of older documents.
156void writeParameter(JSONNode &mod, ParameterRef const &parameter, Constraint const &constraint)
157{
158 mod["parameters"].set_seq().append_child() << parameter.name;
159 std::visit(
160 overloaded{[](Unconstrained) {}, [&](ConstraintType type) { mod["constraint"] << toString(type); },
161 [&](ConstraintPdf const &pdf) { mod["constraints"].set_seq().append_child() << pdf.pdf.name; }},
162 constraint);
163}
164
165void writeGammaConstraint(JSONNode &node, GammaConstraint const &constraint, const char *typeKey)
166{
167 std::visit(overloaded{[](Unconstrained) {}, [&](ConstraintType type) { node[typeKey] << toString(type); },
168 [&](ConstantGammas) { node[typeKey] << "Const"; },
169 [&](GammaConstraintPdfs const &pdfs) {
170 JSONNode &names = node["constraints"].set_seq();
171 for (auto const &pdf : pdfs.pdfs) {
172 if (pdf) {
173 names.append_child() << pdf->name;
174 } else {
175 names.append_child().set_null();
176 }
177 }
178 }},
179 constraint);
180}
181
182void writeModifier(JSONNode &mod, Modifier const &modifier)
183{
184 mod.set_map();
185 mod["name"] << nameOf(modifier);
186 mod["type"] << typeOf(modifier);
187 std::visit(overloaded{
188 [&](NormFactor const &m) { writeParameter(mod, m.parameter, m.constraint); },
189 [&](NormSys const &m) {
190 writeParameter(mod, m.parameter, m.constraint);
191 if (m.interpolation) {
192 writeInterpolation(mod["interpolation"], *m.interpolation);
193 }
194 JSONNode &data = mod["data"].set_map();
195 data["lo"] << m.lo;
196 data["hi"] << m.hi;
197 },
198 [&](HistoSys const &m) {
199 writeParameter(mod, m.parameter, m.constraint);
200 if (m.interpolation) {
201 writeInterpolation(mod["interpolation"], *m.interpolation);
202 }
203 JSONNode &data = mod["data"].set_map();
204 writeContents(data["lo"].set_map()["contents"], m.lo.contents);
205 writeContents(data["hi"].set_map()["contents"], m.hi.contents);
206 },
207 [&](ShapeSys const &m) {
208 writeValue(mod["parameters"], m.parameters);
209 writeGammaConstraint(mod, m.constraint, "constraint");
210 // The values are only used by the constraint types of older documents.
211 if (!m.vals.empty()) {
212 mod["data"].set_map()["vals"].fill_seq(m.vals);
213 }
214 },
215 [&](StatError const &m) {
216 writeValue(mod["parameters"], m.parameters);
217 writeGammaConstraint(mod, m.constraint, "constraint");
218 },
219 [](CustomModifier const &) {},
220 },
221 modifier);
222}
223
224// The columns and the components of a combined data set or distribution, which name what they select in `refKey`.
225template <class Ref_t>
226void writeCombined(JSONNode &node, Combined<Ref_t> const &combined, const char *refKey)
227{
228 node["columns"].fill_seq(combined.columns);
229 JSONNode &components = node["components"].set_seq();
230 for (auto const &component : combined.components) {
231 JSONNode &out = components.append_child().set_map();
232 out["key"].fill_seq(component.key);
233 out[refKey] << component.ref.name;
234 }
235}
236
237void writeParameterPoint(JSONNode &points, ParameterPoint const &point)
238{
239 JSONNode &parameters = appendNamed(points, point.name)["parameters"].set_seq();
240 for (auto const &p : point.parameters) {
241 JSONNode &node = appendNamed(parameters, p.name);
242 if (p.value) {
243 std::visit([&](auto const &value) { node["value"] << value; }, *p.value);
244 }
245 if (p.isConst) {
246 node["const"] << true;
247 }
248 }
249}
250
251void writeData(JSONNode &dataArray, Data const &data)
252{
253 JSONNode &node = appendNamed(dataArray, data.name);
254 std::visit(overloaded{
255 [&](BinnedData const &d) {
256 node["type"] << "binned";
257 writeBinnedData(node, d);
258 },
259 [&](UnbinnedData const &d) {
260 node["type"] << "unbinned";
261 writeAxes(node["axes"], d.axes);
262 JSONNode &entries = node["entries"].set_seq();
263 const std::size_t nAxes = d.axes.size();
264 for (std::size_t i = 0; i < d.numEntries(); ++i) {
265 JSONNode &row = entries.append_child().set_seq();
266 for (std::size_t j = 0; j < nAxes; ++j) {
267 const double value = d.entries[i * nAxes + j];
268 if (auto const *category = std::get_if<CategoricalAxis>(&d.axes[j])) {
269 row.append_child() << category->categories[static_cast<std::size_t>(value)];
270 } else {
271 row.append_child() << value;
272 }
273 }
274 }
275 writeOptional(node, "weights", d.weights);
276 },
277 [&](CombinedData const &d) {
278 node["type"] << "combined";
279 writeCombined(node, d, "dataset");
280 },
281 [&](PointData const &d) {
282 node["type"] << "point";
283 node["value"] << d.value;
284 writeOptional(node, "uncertainty", d.uncertainty);
285 if (!d.axes.empty()) {
286 writeAxes(node["axes"], d.axes);
287 }
288 },
289 },
290 data.body);
291}
292
293void writeLikelihood(JSONNode &likelihoods, Likelihood const &likelihood)
294{
295 JSONNode &node = appendNamed(likelihoods, likelihood.name);
296 JSONNode &distributions = node["distributions"].set_seq();
297 if (likelihood.pureModel) {
298 for (auto const &term : likelihood.terms) {
299 distributions.append_child() << term.distribution.name;
300 }
301 node["data"].set_null();
302 } else {
303 JSONNode &data = node["data"].set_seq();
304 for (auto const &term : likelihood.terms) {
305 distributions.append_child() << term.distribution.name;
306 std::visit(overloaded{[&](DataRef const &ref) { data.append_child() << ref.name; },
307 [&](double value) { writeNumber(data.append_child(), value); },
308 [&](std::monostate) { data.append_child().set_null(); }},
309 term.data);
310 }
311 }
312 if (!likelihood.auxDistributions.empty()) {
313 writeValue(node["aux_distributions"], likelihood.auxDistributions);
314 }
315}
316
317void writeAnalysis(JSONNode &analyses, Analysis const &analysis)
318{
319 JSONNode &node = appendNamed(analyses, analysis.name);
320 writeValue(node["domains"], analysis.domains);
321 node["likelihood"] << analysis.likelihood.name;
322 if (!analysis.parametersOfInterest.empty()) {
323 writeValue(node["parameters_of_interest"], analysis.parametersOfInterest);
324 }
325 writeOptional(node, "init", analysis.init);
326 writeOptional(node, "prior", analysis.prior);
327}
328
329void writeValue(JSONNode &node, Attributes const &attributes)
330{
331 node.set_map();
332 if (!attributes.dict.empty()) {
333 JSONNode &dict = node["dict"].set_map();
334 for (auto const &entry : attributes.dict) {
335 dict[entry.first] << entry.second;
336 }
337 }
338 if (!attributes.tags.empty()) {
339 node["tags"].fill_seq(attributes.tags);
340 }
341}
342
343void writeValue(JSONNode &node, ModelConfigInfo const &info)
344{
345 node.set_map();
346 writeOptional(node, "mcName", info.mcName);
347 writeOptional(node, "pdfName", info.pdfName);
348 writeOptional(node, "observables", info.observables);
349}
350
351// A component of "misc.ROOT_internal" with one value per name, which is left out if there are no values.
352template <class T>
353void writeInternal(JSONNode &root, const char *key, std::map<std::string, T> const &values)
354{
355 if (values.empty()) {
356 return;
357 }
358 JSONNode &node = root.get("misc", "ROOT_internal")[key].set_map();
359 for (auto const &item : values) {
360 writeValue(node[item.first], item.second);
361 }
362}
363
364void writeRooFitInternal(JSONNode &root, RooFitInternal const &internal)
365{
366 writeInternal(root, "attributes", internal.attributes);
367 writeInternal(root, "ModelConfigs", internal.modelConfigs);
368 writeInternal(root, "histfactory_constraints", internal.channelConstraints);
369 writeInternal(root, "auxiliary_channels", internal.auxiliaryChannels);
370 writeInternal(root, "bookkeeping_columns", internal.bookkeepingColumns);
371 if (!internal.stepWidths.empty()) {
372 JSONNode &stepWidths = root.get("misc", "minimization")["parameter_stepwidths"].set_seq();
373 for (auto const &stepWidth : internal.stepWidths) {
374 appendNamed(stepWidths, stepWidth.name)["step_width"] << stepWidth.width;
375 }
376 }
377}
378
379} // namespace
380
381void writeContents(JSONNode &node, std::vector<double> const &values)
382{
383 node.set_seq();
384 for (double value : values) {
385 writeNumber(node.append_child(), value);
386 }
387}
388
389void writeInterpolation(JSONNode &node, Interpolation const &interpolation)
390{
391 node.set_map();
392 node["type"] << toString(interpolation.type);
393 node["in"] << toString(interpolation.in);
394 if (interpolation.out) {
395 node["out"] << toString(*interpolation.out);
396 } else {
397 node["out"].set_null();
398 }
399}
400
401namespace {
402
403template <class Function_t>
404void writeInterpolated(JSONNode &node, Function_t const &function, char const *type)
405{
406 node["type"] << type;
407 auto const &interpolations = function.interpolations;
408 const bool allEqual = std::all_of(interpolations.begin(), interpolations.end(),
409 [&](Interpolation const &i) { return i == interpolations.front(); });
410 JSONNode &interpolationsNode = node["interpolations"].set_seq();
411 for (std::size_t i = 0; i < (allEqual ? std::min<std::size_t>(interpolations.size(), 1) : interpolations.size());
412 ++i) {
413 writeInterpolation(interpolationsNode.append_child(), interpolations[i]);
414 }
415 writeValue(node["vars"], function.parameters);
416 node["nom"] << function.nominal;
417 writeValue(node["high"], function.high);
418 writeValue(node["low"], function.low);
419}
420
421} // namespace
422
423void writeAxis(JSONNode &node, BinnedAxis const &axis)
424{
425 node.set_map();
426 node["name"] << axis.name;
427 // The range of an irregular binning is given by its "edges": HS3 0.3 forbids "min" and "max" alongside them.
428 if (!std::holds_alternative<EdgesBinning>(axis.binning)) {
429 node["min"] << axis.min;
430 node["max"] << axis.max;
431 }
432 writeBinning(node, axis.binning);
433}
434
436{
437 writeAxes(node["axes"], data.axes);
438 writeContents(node["contents"], data.contents);
439 if (data.uncertainty) {
440 JSONNode &uncertainty = node["uncertainty"].set_map();
441 uncertainty["type"] << "gaussian_uncertainty";
442 uncertainty["sigma"].fill_seq(data.uncertainty->sigma);
443 }
444}
445
447{
448 writeInterpolated(node, function, "interpolation");
449 node["positiveDefinite"] << function.positiveDefinite;
450}
451
453{
454 writeInterpolated(node, function, "interpolation0d");
455}
456
458{
459 node.set_map();
460 node["type"] << "histfactory_dist";
461 if (!std::holds_alternative<Unconstrained>(dist.statError.constraint)) {
462 writeGammaConstraint(node["staterror"].set_map(), dist.statError.constraint, "constraint_type");
463 }
464 if (dist.defaultInterpolation) {
465 writeInterpolation(node["default_interpolation"], *dist.defaultInterpolation);
466 }
467 writeAxes(node["axes"], dist.axes);
468 JSONNode &samples = node["samples"].set_seq();
469 for (auto const &sample : dist.samples) {
470 JSONNode &s = appendNamed(samples, sample.name);
471 JSONNode &modifiers = s["modifiers"].set_seq();
472 for (auto const &modifier : sample.modifiers) {
473 writeModifier(modifiers.append_child(), modifier);
474 }
475 JSONNode &data = s["data"].set_map();
476 writeContents(data["contents"], sample.contents);
477 if (sample.errors) {
478 writeContents(data["errors"], *sample.errors);
479 }
480 }
481}
482
484{
485 node["type"] << "combined_dist";
486 writeCombined(node, dist, "dist");
487}
488
489void writeDocument(JSONNode &root, HS3Document const &doc)
490{
491 root.set_map();
492 JSONNode &metadata = root["metadata"].set_map();
493 metadata["hs3_version"] << doc.metadata.hs3Version;
494 for (auto const &package : doc.metadata.packages) {
495 appendNamed(metadata["packages"], package.name)["version"] << package.version;
496 }
497
498 for (auto const &point : doc.parameterPoints) {
499 writeParameterPoint(root["parameter_points"], point);
500 }
501 for (auto const &domain : doc.domains) {
502 JSONNode &node = appendNamed(root["domains"], domain.name);
503 node["type"] << "product_domain";
504 writeAxes(node["axes"], domain.axes);
505 }
506 for (auto const &data : doc.data) {
507 writeData(root["data"], data);
508 }
509 for (auto const &likelihood : doc.likelihoods) {
510 writeLikelihood(root["likelihoods"], likelihood);
511 }
512 for (auto const &analysis : doc.analyses) {
513 writeAnalysis(root["analyses"], analysis);
514 }
515 writeRooFitInternal(root, doc.rooFit);
516}
517
518} // namespace HS3
519} // namespace RooFit
#define d(i)
Definition RSha256.hxx:102
#define a(i)
Definition RSha256.hxx:99
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t 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 modifier
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t points
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:142
JSONNode & get(std::string const &key)
The component at the end of a path of keys. The nodes on the path become maps.
void fill_seq(Collection const &coll)
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::ParameterPoint > parameterPoints
HS3::RooFitInternal rooFit
std::vector< HS3::Domain > domains
Types that represent an HS3 document.
std::variant< std::string, double > NameOrNumber
A name, or a number for a constant.
void writeInterpolatedFunction(Detail::JSONNode &node, InterpolatedFunction const &function)
Writes the functions "interpolation" and "interpolation0d", with a single interpolation if they are a...
std::variant< NormFactor, NormSys, HistoSys, ShapeSys, StatError, CustomModifier > Modifier
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
Combined< DataRef > CombinedData
std::variant< RegularBinning, EdgesBinning > Binning
ConstraintType
The constraint types that older documents named, for which RooFit creates the constraint terms.
Ref< struct DataTag > DataRef
Definition HS3Document.h:90
char const * toString(InterpolationType type)
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...
char const * typeOf(Modifier const &modifier)
The type of a modifier, as the standard names it.
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.
void writeInterpolatedNumber(Detail::JSONNode &node, InterpolatedNumber const &function)
void writeHistFactoryDist(Detail::JSONNode &node, HistFactoryDist const &dist)
Writes a HistFactory distribution, without its name.
Ref< struct ParameterTag > ParameterRef
Definition HS3Document.h:94
void writeAxis(Detail::JSONNode &node, BinnedAxis const &axis)
Writes an axis of binned data.
void writeInterpolation(Detail::JSONNode &node, Interpolation const &interpolation)
std::variant< Unconstrained, ConstraintType, ConstantGammas, GammaConstraintPdfs > GammaConstraint
void writeBinnedData(Detail::JSONNode &node, BinnedData const &data)
Writes the axes, contents and uncertainties of binned data, without its name and type.
overloaded(Ts...) -> overloaded< Ts... >
std::variant< Unconstrained, ConstraintType, ConstraintPdf > Constraint
void writeCombinedDist(Detail::JSONNode &node, CombinedDist const &dist)
Writes a combined distribution, without its name.
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
The axis of binned data.
Data sets or distributions that are selected by a key (HS3 #119). The columns are categorical axes of...
The function "interpolation" of RooFit, implemented by PiecewiseInterpolation: a nominal function plu...
The function "interpolation0d" of RooFit, implemented by FlexibleInterpVar: a nominal value plus the ...
How a modifier of a HistFactory distribution interpolates and extrapolates its effect.
InterpolationType type
InterpolationFunction in
std::optional< InterpolationFunction > out
If not set, the function inside the bounds is used outside as well.
std::string hs3Version
As it was written in the document, empty for fragments of a document.
std::vector< Package > packages
TMarker m
Definition textangle.C:8