Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HS3Upgrade.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// Everything that older versions of RooFit wrote in a way that is not part of the HS3 standard is translated here into
14// the form that the parser understands. The rewrites go by the shape of the JSON: the same version number was written
15// by ROOT releases with different conventions. Only what a missing component means depends on the version.
16
17#include "HS3Schema.h"
18
19#include <functional>
20#include <set>
21#include <string>
22
24
25namespace RooFit {
26namespace HS3 {
27namespace {
28
29// The version that the standard requires the interpolation of modifiers from on.
30constexpr Version explicitInterpolationVersion{0, 3, 0};
31// Before this version, normsys and histosys modifiers without constraint had an implicit Gaussian constraint.
32constexpr Version explicitConstraintVersion{0, 2, 0};
33// From this version on, the gamma parameters of modifiers are free unless "constraints" names their constraint terms,
34// "shapesys" is deprecated, and a sample without "errors" has no statistical uncertainty.
35constexpr Version namedConstraintVersion{0, 3, 0};
36
37using IsDistribution = std::function<bool(std::string const &)>;
38
39bool isScalar(JSONNode const &node)
40{
41 return !node.is_container() && !node.is_null();
42}
43
44// Calls fn(element, cursor, index) for each struct in the array `key` of `parent`, if there is one. What is skipped is
45// reported by the parser.
46template <class Fn>
47void forEachStruct(JSONNode &parent, const char *key, Cursor const &parentCursor, Fn &&fn)
48{
49 if (!parent.is_map() || !parent.has_child(key) || !parent[key].is_seq()) {
50 return;
51 }
52 Cursor array{parent[key], parentCursor, key};
53 std::size_t index = 0;
54 for (JSONNode &element : parent[key].children()) {
55 if (element.is_map()) {
56 fn(element, Cursor{element, array, index}, index);
57 }
58 ++index;
59 }
60}
61
62bool isConstraintType(std::string const &value)
63{
64 return value == "Gauss" || value == "Poisson" || value == "LogNormal";
65}
66
67// Older versions of RooFit spelled "LogNormal" differently.
68std::string canonicalConstraintType(std::string const &value)
69{
70 return value == "Lognormal" ? "LogNormal" : value;
71}
72
73// The "constraints" of the standard take precedence over the keys that older documents used.
74bool eraseLegacyConstraints(JSONNode &mod)
75{
76 if (!mod.has_child("constraints")) {
77 return false;
78 }
79 mod.erase("constraint");
80 mod.erase("constraint_name");
81 mod.erase("constraint_type");
82 return true;
83}
84
85// Write a legacy constraint of a normsys, histosys or normfactor modifier as "constraint" if it is a type, or
86// "constraint_name" if it refers to a distribution.
87void upgradeConstraint(JSONNode &mod, IsDistribution const &isDistribution)
88{
89 if (eraseLegacyConstraints(mod)) {
90 return;
91 }
92 if (mod.has_child("constraint_name")) {
93 mod.erase("constraint");
94 mod.erase("constraint_type");
95 return;
96 }
97 if (mod.has_child("constraint")) {
98 mod.erase("constraint_type");
99 JSONNode &constraint = mod["constraint"];
100 if (!isScalar(constraint)) {
101 return; // reported by the parser
102 }
103 const std::string value = constraint.val();
104 // In older documents, the "constraint" can be the name of a distribution, which has priority.
105 if (isDistribution(value)) {
106 mod["constraint_name"] << value;
107 mod.erase("constraint");
108 } else {
109 constraint << canonicalConstraintType(value);
110 }
111 return;
112 }
113 if (mod.has_child("constraint_type")) {
114 JSONNode &constraintType = mod["constraint_type"];
115 if (isScalar(constraintType)) {
116 mod["constraint"] << canonicalConstraintType(constraintType.val());
117 }
118 mod.erase("constraint_type");
119 }
120}
121
122// The constraint of the gamma parameters of a shapesys modifier. In contrast to the other modifiers, it is not possible
123// to name a distribution in this way, and "constraint_type" has priority.
124void upgradeGammaConstraint(JSONNode &mod)
125{
126 if (eraseLegacyConstraints(mod)) {
127 return;
128 }
129 if (mod.has_child("constraint_type")) {
130 JSONNode &constraintType = mod["constraint_type"];
131 if (isScalar(constraintType)) {
132 mod["constraint"] << canonicalConstraintType(constraintType.val());
133 }
134 mod.erase("constraint_type");
135 } else if (mod.has_child("constraint") && isScalar(mod["constraint"])) {
136 mod["constraint"] << canonicalConstraintType(mod["constraint"].val());
137 }
138}
139
140// An integer code that was used before the structured interpolations.
141void upgradeInterpolationCode(JSONNode &mod, InterpolationClass interpolationClass, Cursor const &c)
142{
143 if (!mod.has_child("interpolation") || mod["interpolation"].is_map()) {
144 return;
145 }
146 JSONNode &node = mod["interpolation"];
147 if (auto interpolation = readInterpolationCode(Cursor{node, c, "interpolation"}, interpolationClass)) {
148 node.set_null();
149 writeInterpolation(node, *interpolation);
150 }
151}
152
153struct ChannelState {
154 std::string channelName;
157 bool warnedShapeSys = false;
158};
159
160// Whether "constraints" leaves the single parameter of a modifier unconstrained.
161bool isExplicitlyUnconstrained(JSONNode const &constraints)
162{
163 return constraints.is_seq() && constraints.num_children() == 1 && constraints.child(0).is_null();
164}
165
166void upgradeModifier(JSONNode &mod, std::size_t index, std::string const &sampleName, Version const &version,
167 bool hasDefaultInterpolation, IsDistribution const &isDistribution, ChannelState &state,
168 Cursor const &c)
169{
170 if (!mod.has_child("type") || !isScalar(mod["type"])) {
171 return; // reported by the parser
172 }
173 const std::string type = mod["type"].val();
174 const bool hasSingleParameter = type == "normfactor" || type == "normsys" || type == "histosys";
175
176 // The "parameters" of the standard take precedence over the "parameter" of older documents.
177 std::string parameter;
178 if (hasSingleParameter && mod.has_child("parameters")) {
179 mod.erase("parameter");
180 JSONNode const &parameters = mod["parameters"];
181 if (parameters.is_seq() && parameters.num_children() == 1 && isScalar(parameters.child(0))) {
182 parameter = parameters.child(0).val();
183 }
184 } else if (mod.has_child("parameter") && isScalar(mod["parameter"])) {
185 parameter = mod["parameter"].val();
186 }
187
188 // The name of a modifier is not part of the standard. RooFit names objects after it, so a generated name must be
189 // unique, unlike the name of a parameter, which is shared on purpose.
190 if (!mod.has_child("name")) {
191 mod["name"] << (!parameter.empty() ? parameter
192 : state.channelName + "_" + sampleName + "_syst_" + std::to_string(index));
193 // Older documents gave the function of a custom modifier in "parameter". It is the name now, so it is not left
194 // for the parser to report as ignored.
195 if (type == "custom" && !parameter.empty()) {
196 mod.erase("parameter");
197 }
198 }
199 const std::string name = isScalar(mod["name"]) ? mod["name"].val() : "";
200
201 if (hasSingleParameter && !mod.has_child("parameter") && !mod.has_child("parameters")) {
202 parameter = type == "normfactor" ? name : "alpha_" + name;
203 mod["parameter"] << parameter;
204 }
205
206 if (type == "normfactor") {
207 upgradeConstraint(mod, isDistribution);
208 } else if (type == "normsys" || type == "histosys") {
209 upgradeConstraint(mod, isDistribution);
210 const bool constrained = mod.has_child("constraint") || mod.has_child("constraint_name") ||
211 (mod.has_child("constraints") && !isExplicitlyUnconstrained(mod["constraints"]));
212 if (!constrained) {
213 if (version < explicitConstraintVersion) {
214 mod.erase("constraints");
215 mod["constraint"] << "Gauss";
216 } else if (!state.warnedUnconstrained) {
217 c.warning("modifier '" + name + "' of sample '" + sampleName + "' has no constraint, so its parameter '" +
218 parameter +
219 "' is unconstrained. Older RooFit versions implied a unit Gaussian. Other modifiers of this "
220 "channel are not reported.");
221 state.warnedUnconstrained = true;
222 }
223 }
224 // Before structured interpolations were introduced, both modifier classes used the integer code 4 as their
225 // implicit default. The meaning of the code is class-dependent. HS3 forbids implementation-specific defaults.
226 if (!mod.has_child("interpolation") && !hasDefaultInterpolation && version < explicitInterpolationVersion) {
227 if (!state.warnedInterpolation) {
228 c.warning("interpolation for " + type + " modifier '" + name + "' in sample '" + sampleName +
229 "' of channel '" + state.channelName +
230 "' is not given, and the channel has no \"default_interpolation\". Using the implicit default "
231 "of older RooFit versions (code 4), which is deprecated.");
232 state.warnedInterpolation = true;
233 }
234 mod["interpolation"] << 4;
235 }
236 const auto interpolationClass = type == "normsys" ? InterpolationClass::Flexible : InterpolationClass::Piecewise;
237 upgradeInterpolationCode(mod, interpolationClass, c);
238 } else if (type == "shapesys" || type == "shapefactor") {
239 if (type == "shapesys" && !(version < namedConstraintVersion) && !state.warnedShapeSys) {
240 c.warning("the modifier type \"shapesys\" is deprecated, please use \"shapefactor\" instead.");
241 state.warnedShapeSys = true;
242 }
243 upgradeGammaConstraint(mod);
244 if (!mod.has_child("constraint") && !mod.has_child("constraints")) {
245 if (version < namedConstraintVersion) {
246 // Without any information about the constraint, older versions created Gaussian constraints.
247 mod["constraint"] << "Gauss";
248 } else if (mod.has_child("data") && mod["data"].is_map() && mod["data"].has_child("vals")) {
249 if (mod["data"]["vals"].is_seq() && mod["data"]["vals"].num_children() > 0) {
250 c.warning("the \"data.vals\" of modifier '" + name + "' of sample '" + sampleName +
251 "' are ignored, because it names no constraints, so its parameters are free");
252 }
253 mod["data"].erase("vals");
254 }
255 }
256 } else if (type == "staterror") {
257 if (eraseLegacyConstraints(mod)) {
258 return;
259 }
260 // ROOT 6.38 and 6.40.00 wrote "constraint_type".
261 if (mod.has_child("constraint_type")) {
262 if (!mod.has_child("constraint") && isScalar(mod["constraint_type"])) {
263 mod["constraint"] << mod["constraint_type"].val();
264 }
265 mod.erase("constraint_type");
266 }
267 }
268}
269
270void upgradeHistFactory(JSONNode &dist, Version const &version, IsDistribution const &isDistribution, Cursor const &c)
271{
272 ChannelState state;
273 if (dist.has_child("name") && isScalar(dist["name"])) {
274 state.channelName = dist["name"].val();
275 if (state.channelName.rfind("model_", 0) == 0) {
276 state.channelName.erase(0, 6);
277 }
278 }
279
280 // Before HS3 0.3, the gamma parameters of the staterror modifiers had Poisson constraints unless the document said
281 // otherwise, and samples without "errors" had Poisson uncertainties. From HS3 0.3 on, RooFit only creates
282 // constraints if its channel-level settings give their type.
283 const bool legacyStatError = version < namedConstraintVersion;
284 if (legacyStatError && !dist.has_child("staterror")) {
285 dist["staterror"].set_map();
286 }
287 if (dist.has_child("staterror") && dist["staterror"].is_map()) {
288 JSONNode &config = dist["staterror"];
289 upgradeGammaConstraint(config);
290 if (legacyStatError) {
291 if (!config.has_child("constraint") && !config.has_child("constraints")) {
292 config["constraint"] << "Poisson";
293 }
294 config["implied_poisson_errors"] << true;
295 }
296 }
297
298 const bool hasDefaultInterpolation = dist.has_child("default_interpolation");
299 forEachStruct(dist, "samples", c, [&](JSONNode &sample, Cursor const &sampleCursor, std::size_t) {
300 const std::string sampleName = sample.has_child("name") && isScalar(sample["name"]) ? sample["name"].val() : "";
301 forEachStruct(sample, "modifiers", sampleCursor, [&](JSONNode &mod, Cursor const &modCursor, std::size_t index) {
302 upgradeModifier(mod, index, sampleName, version, hasDefaultInterpolation, isDistribution, state, modCursor);
303 });
304 });
305}
306
307// Older versions of RooFit wrote the binning of the observables also for unbinned data, which the standard forbids.
308// The edges were written without "min" and "max".
309void upgradeUnbinnedAxis(JSONNode &axis)
310{
311 if (axis.has_child("edges") && axis["edges"].is_seq() && axis["edges"].num_children() > 0) {
312 JSONNode &edges = axis["edges"];
313 JSONNode const &first = edges.child(0);
314 JSONNode const &last = edges.child(edges.num_children() - 1);
315 if (!axis.has_child("min") && first.is_number()) {
316 axis["min"] << first.val_double();
317 }
318 if (!axis.has_child("max") && last.is_number()) {
319 axis["max"] << last.val_double();
320 }
321 }
322 axis.erase("edges");
323 axis.erase("nbins");
324}
325
326void upgradeData(JSONNode &root, Version const &version, Cursor const &rootCursor)
327{
328 if (!(version < explicitInterpolationVersion)) {
329 return;
330 }
331 forEachStruct(root, "data", rootCursor, [](JSONNode &data, Cursor const &dataCursor, std::size_t) {
332 if (data.has_child("type") && isScalar(data["type"]) && data["type"].val() == "unbinned") {
333 forEachStruct(data, "axes", dataCursor,
334 [](JSONNode &axis, Cursor const &, std::size_t) { upgradeUnbinnedAxis(axis); });
335 }
336 });
337}
338
339// HS3 0.3 forbids "min" and "max" alongside "edges" (HS3 #126), which documents before 0.3 had. Where they agree with
340// the edges, which the parser checks, they are only redundant, so they give a warning.
341void warnBoundsWithEdges(JSONNode &root, Version const &version, Cursor const &rootCursor)
342{
343 if (version < Version{0, 3, 0}) {
344 return;
345 }
346 for (const char *section : {"domains", "data", "distributions"}) {
347 forEachStruct(root, section, rootCursor, [](JSONNode &object, Cursor const &objectCursor, std::size_t) {
348 forEachStruct(object, "axes", objectCursor, [](JSONNode &axis, Cursor const &axisCursor, std::size_t) {
349 if (axis.has_child("edges") && (axis.has_child("min") || axis.has_child("max"))) {
350 axisCursor.warning("\"min\" and \"max\" must not be given alongside \"edges\" from HS3 0.3 on, the "
351 "edges give the range");
352 }
353 });
354 });
355 }
356}
357
358Version documentVersion(JSONNode const &root)
359{
360 Version version;
361 if (JSONNode const *versionNode = root.find("metadata", "hs3_version")) {
362 if (isScalar(*versionNode)) {
363 parseVersion(versionNode->val(), version);
364 }
365 }
366 return version;
367}
368
369} // namespace
370
371void upgradeDocument(JSONNode &root, Diagnostics &diagnostics, ParseOptions const &options)
372{
373 if (!root.is_map()) {
374 return;
375 }
376 const Version version = documentVersion(root);
377 Cursor rootCursor{root, diagnostics};
378 warnBoundsWithEdges(root, version, rootCursor);
379 upgradeData(root, version, rootCursor);
380 if (!options.typedHistFactory) {
381 return;
382 }
383
384 std::set<std::string> distributionNames;
385 forEachStruct(root, "distributions", rootCursor, [&](JSONNode &dist, Cursor const &, std::size_t) {
386 if (dist.has_child("name") && isScalar(dist["name"])) {
387 distributionNames.insert(dist["name"].val());
388 }
389 });
390 // The version from which on "constraint" is only a type of the standard.
391 const bool constraintCanBeName = version < explicitInterpolationVersion;
392 IsDistribution isDistribution = [&](std::string const &name) {
393 return constraintCanBeName && distributionNames.count(name) > 0;
394 };
395
396 forEachStruct(root, "distributions", rootCursor, [&](JSONNode &dist, Cursor const &distCursor, std::size_t) {
397 if (dist.has_child("type") && isScalar(dist["type"]) && dist["type"].val() == "histfactory_dist") {
398 upgradeHistFactory(dist, version, isDistribution, distCursor);
399 }
400 });
401}
402
403void upgradeHistFactoryDist(JSONNode &distribution, Version const &version, Diagnostics &diagnostics)
404{
405 IsDistribution isDistribution = [](std::string const &name) {
406 return !isConstraintType(name) && name != "Lognormal" && name != "Const";
407 };
408 upgradeHistFactory(distribution, version, isDistribution, Cursor{distribution, diagnostics});
409}
410
411} // namespace HS3
412} // namespace RooFit
bool warnedInterpolation
bool warnedShapeSys
std::string channelName
bool warnedUnconstrained
#define c(i)
Definition RSha256.hxx:101
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 index
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 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
XID Cursor
Definition TGX11.h:36
void erase(std::string const &key)
Remove a child of a map, if it exists.
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
JSONNode & child(size_t pos)
A position in the JSON tree.
Definition HS3Schema.h:31
double dist(Rotation3D const &r1, Rotation3D const &r2)
Types that represent an HS3 document.
void upgradeHistFactoryDist(Detail::JSONNode &distribution, Version const &version, Diagnostics &diagnostics)
Same as upgradeDocument(), but for a single HistFactory distribution that doesn't come with a documen...
std::optional< Interpolation > readInterpolationCode(Cursor const &c, InterpolationClass interpolationClass)
Reads an integer interpolation code, as older versions of RooFit wrote them.
std::vector< Diagnostic > Diagnostics
void writeInterpolation(Detail::JSONNode &node, Interpolation const &interpolation)
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...
bool parseVersion(std::string const &version, Version &out)
Reads the leading "MAJOR.MINOR" and the optional ".PATCH" of an HS3 version string.
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
Options for upgradeDocument() and parseDocument().
bool typedHistFactory
If false, HistFactory distributions stay generic objects, because a user registered their own importe...