Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HS3Validate.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#include "HS3Document.h"
14
15#include <algorithm>
16#include <cmath>
17#include <limits>
18#include <map>
19#include <optional>
20#include <set>
21#include <string>
22#include <vector>
23
24namespace RooFit {
25namespace HS3 {
26namespace {
27
28std::string at(const char *section, std::size_t index, std::string const &name)
29{
30 return std::string(section) + "[" + std::to_string(index) + "](" + name + ")";
31}
32
33class Validator {
34public:
35 Validator(HS3Document const &doc, Diagnostics &diagnostics, ValidateOptions const &options)
36 : _doc{doc}, _diagnostics{diagnostics}, _options{options}
37 {
38 }
39
40 void run()
41 {
42 collectNames();
43 checkFixedAxes();
44 checkCategoricalAxes();
45 checkLikelihoods();
46 checkAnalyses();
47 checkData();
48 checkCombinedData();
49 for (std::size_t i = 0; i < _doc.distributions.size(); ++i) {
50 auto const &dist = _doc.distributions[i];
51 if (auto const *histFactory = std::get_if<HistFactoryDist>(&dist.body)) {
52 checkHistFactory(*histFactory, dist.name, at("distributions", i, dist.name));
53 } else if (auto const *combined = std::get_if<CombinedDist>(&dist.body)) {
54 checkCombined(*combined, at("distributions", i, dist.name), "the combined_dist '" + dist.name + "'");
55 }
56 }
57 for (auto const &item : _doc.rooFit.combinedDistributions) {
58 for (auto const &ref : item.second.distributions) {
59 requireDistribution(ref.name, "misc.ROOT_internal.combined_distributions." + item.first, "distribution");
60 }
61 }
62 for (auto const &item : _doc.rooFit.auxiliaryChannels) {
63 requireDistribution(item.first, "misc.ROOT_internal.auxiliary_channels", "distribution");
64 for (auto const &ref : item.second) {
65 requireDistribution(ref.name, "misc.ROOT_internal.auxiliary_channels." + item.first, "component");
66 }
67 }
68 for (auto const &item : _doc.rooFit.channelConstraints) {
69 requireDistribution(item.first, "misc.ROOT_internal.histfactory_constraints", "distribution");
70 for (auto const &ref : item.second) {
71 requireDistribution(ref.name, "misc.ROOT_internal.histfactory_constraints." + item.first, "constraint");
72 }
73 }
74 }
75
76 void error(std::string const &path, std::string const &message)
77 {
79 }
80
81 void warning(std::string const &path, std::string const &message)
82 {
84 }
85
86 // An error in documents that follow the current standard, which older versions of RooFit didn't care about.
87 void strictError(std::string const &path, std::string const &message)
88 {
89 _diagnostics.push_back(
91 }
92
93 void checkHistFactory(HistFactoryDist const &dist, std::string const &name, std::string const &path);
94 template <class Ref_t>
95 void checkCombined(Combined<Ref_t> const &combined, std::string const &path, std::string const &context);
96
97private:
98 bool isExternal(std::string const &name) const { return _options.isExternal && _options.isExternal(name); }
99
100 char const *sectionOf(std::string const &name) const
101 {
102 auto found = _sections.find(name);
103 return found != _sections.end() ? found->second.front() : nullptr;
104 }
105
106 bool isDefinedIn(std::string const &name, char const *section) const
107 {
108 auto found = _sections.find(name);
109 if (found == _sections.end()) {
110 return false;
111 }
112 return std::any_of(found->second.begin(), found->second.end(),
113 [&](char const *s) { return std::string(s) == section; });
114 }
115
116 void requireDistribution(std::string const &name, std::string const &path, std::string const &what)
117 {
118 // RooFit refers to a RooSimultaneous by name, like the likelihood of a ModelConfig without data does.
119 if (!isDefinedIn(name, "distributions") && !_doc.rooFit.combinedDistributions.count(name) && !isExternal(name)) {
120 error(path, "the " + what + " '" + name + "' does not exist");
121 }
122 }
123
124 void addParameter(std::string const &name) { _parameters.insert(name); }
125
126 // The number of bins of an axis, after reporting an invalid binning.
127 std::size_t checkAxis(BinnedAxis const &axis, std::string const &path);
128 std::size_t checkAxis(CategoricalAxis const &axis, std::string const &path);
129 template <class... Axis>
130 std::size_t checkAxis(std::variant<Axis...> const &axis, std::string const &path)
131 {
132 return std::visit([&](auto const &a) { return checkAxis(a, path); }, axis);
133 }
134 // The number of bins of all axes, or nothing if it can't be stored.
135 template <class Axes>
136 std::optional<std::size_t> numBins(Axes const &axes, std::string const &path);
137
138 void collectNames();
139 void checkFixedAxes();
140 void checkCategoricalAxes();
141 void checkLikelihoods();
142 void checkAnalyses();
143 void checkNormalizationRanges(Analysis const &analysis, std::string const &path);
144 void checkData();
145 void checkCombinedData();
146
147 HS3Document const &_doc;
149 ValidateOptions const &_options;
150 std::map<std::string, std::vector<char const *>> _sections; ///< The sections where a name is defined.
151 std::set<std::string> _parameters;
152 std::map<std::string, std::vector<std::string> const *> _categories; ///< Of the categorical axes of the domains.
153};
154
155// The names that the HS3 expression language reserves for itself: its literals and functions (HS3 0.3, "Identifiers").
156static bool isReservedName(std::string const &name)
157{
158 static const std::set<std::string> reserved{"PI", "EULER", "TRUE", "FALSE", "ifelse", "exp", "log",
159 "sqrt", "abs", "floor", "ceil", "pow", "min", "max",
160 "sin", "cos", "tan", "asin", "acos", "atan", "erf"};
161 return reserved.count(name) > 0;
162}
163
164// HS3 requires the names of all objects to be unique within a document, including the parameters. RooFit writes such
165// documents, e.g. for a range and a pdf of one name, so only ambiguous clashes in current documents are errors.
166void Validator::collectNames()
167{
168 auto check = [&](char const *section, std::string const &name) {
169 auto &sections = _sections[name];
170 sections.push_back(section);
171 if (sections.size() == 1) {
172 return;
173 }
174 std::string const firstSection = sections.front();
175 // RooFit used to give analyses and likelihoods the name of the pdf or the analysis. Accept this for backwards
176 // compatibility: analyses are not referenced by name, and likelihoods only from analyses, so there is no
177 // ambiguity.
178 auto isLegacyNamed = [](std::string const &s) { return s == "likelihoods" || s == "analyses"; };
179 // Within one section, and between distributions and functions (both can be referenced by name), a clash is
180 // ambiguous. Other clashes are produced by RooFit itself (a range, snapshot or data set named like a pdf).
181 auto isReferable = [](std::string const &s) { return s == "distributions" || s == "functions"; };
182 const bool ambiguous = firstSection == section || (isReferable(firstSection) && isReferable(section));
183 if (!_options.strict || !ambiguous || isLegacyNamed(firstSection) || isLegacyNamed(section)) {
184 warning("", "the name '" + name + "' is used in \"" + firstSection + "\" and in \"" + section +
185 "\", which is not allowed by the HS3 standard.");
186 return;
187 }
188 error("", "duplicate name '" + name + "': it is defined in \"" + firstSection + "\" and in \"" + section +
189 "\", but names must be unique within the document");
190 };
191 auto checkSection = [&](char const *section, auto const &objects) {
192 for (auto const &object : objects) {
193 check(section, object.name);
194 }
195 };
196 checkSection("distributions", _doc.distributions);
197 checkSection("functions", _doc.functions);
198 checkSection("data", _doc.data);
199 checkSection("domains", _doc.domains);
200 checkSection("parameter_points", _doc.parameterPoints);
201 checkSection("likelihoods", _doc.likelihoods);
202 checkSection("analyses", _doc.analyses);
203
204 // The parameters are the axes of the domains, the entries of the parameter points, and the parameters of
205 // HistFactory modifiers, which are created on the fly.
206 for (auto const &domain : _doc.domains) {
207 for (auto const &axis : domain.axes) {
208 addParameter(nameOf(axis));
209 }
210 }
211 for (auto const &point : _doc.parameterPoints) {
212 for (auto const &parameter : point.parameters) {
213 addParameter(parameter.name);
214 }
215 }
216 for (auto const &item : _doc.rooFit.combinedDistributions) {
217 addParameter(item.second.indexCat);
218 }
219 for (auto const &dist : _doc.distributions) {
220 auto const *histFactory = std::get_if<HistFactoryDist>(&dist.body);
221 if (!histFactory) {
222 continue;
223 }
224 for (auto const &sample : histFactory->samples) {
225 for (auto const &modifier : sample.modifiers) {
226 std::visit(overloaded{[&](NormFactor const &m) { addParameter(m.parameter.name); },
227 [&](NormSys const &m) { addParameter(m.parameter.name); },
228 [&](HistoSys const &m) { addParameter(m.parameter.name); },
229 [&](ShapeSys const &m) {
230 for (auto const &p : m.parameters) {
231 addParameter(p.name);
232 }
233 },
234 [&](StatError const &m) {
235 for (auto const &p : m.parameters) {
236 addParameter(p.name);
237 }
238 },
239 [](CustomModifier const &) {}},
240 modifier);
241 }
242 }
243 }
244 // Objects that expressions can refer to must not carry the reserved names of the expression language.
245 auto checkNotReserved = [&](char const *what, std::string const &name) {
246 if (isReservedName(name)) {
247 strictError("", "the " + std::string(what) + " '" + name +
248 "' has a name that the HS3 expression language reserves for itself");
249 }
250 };
251 for (auto const &dist : _doc.distributions) {
252 checkNotReserved("distribution", dist.name);
253 }
254 for (auto const &func : _doc.functions) {
255 checkNotReserved("function", func.name);
256 }
257 for (std::string const &parameter : _parameters) {
258 checkNotReserved("parameter", parameter);
259 }
260 for (std::string const &parameter : _parameters) {
261 if (char const *section = sectionOf(parameter)) {
262 strictError("", "the name '" + parameter + "' is used in \"" + section +
263 "\" and for a parameter, which is not allowed by the HS3 standard.");
264 }
265 }
266}
267
268// A fixed axis says that the parameter only takes a single value. No other domain can give it a range or another
269// value, and no parameter point another value.
270void Validator::checkFixedAxes()
271{
272 struct FixedAxis {
273 double value = 0.0;
274 std::string const *domain = nullptr;
275 };
276 std::map<std::string, FixedAxis> fixedAxes;
277 auto forEachAxis = [&](auto &&fn) {
278 for (std::size_t i = 0; i < _doc.domains.size(); ++i) {
279 for (auto const &axis : _doc.domains[i].axes) {
280 // A categorical axis is passed as null.
281 fn(i, nameOf(axis), std::get_if<DomainAxis>(&axis));
282 }
283 }
284 };
285 forEachAxis([&](std::size_t i, std::string const &, DomainAxis const *continuous) {
286 if (!continuous || !continuous->fixedValue) {
287 return;
288 }
289 DomainAxis const &axis = *continuous;
290 Domain const &domain = _doc.domains[i];
291 if (!std::isfinite(*axis.fixedValue)) {
292 error(at("domains", i, domain.name),
293 "the single value of the parameter '" + axis.name + "' is not finite, which JSON can't represent");
294 }
295 auto inserted = fixedAxes.insert({axis.name, FixedAxis{*axis.fixedValue, &domain.name}});
296 if (!inserted.second && inserted.first->second.value != *axis.fixedValue) {
297 error(at("domains", i, domain.name),
298 "the parameter '" + axis.name + "' has different single values in the domains '" +
299 *inserted.first->second.domain + "' and '" + domain.name + "'");
300 }
301 });
302 if (fixedAxes.empty()) {
303 return;
304 }
305 forEachAxis([&](std::size_t i, std::string const &name, DomainAxis const *continuous) {
306 auto found = fixedAxes.find(name);
307 if (found != fixedAxes.end() && !(continuous && continuous->fixedValue)) {
308 Domain const &domain = _doc.domains[i];
309 error(at("domains", i, domain.name),
310 "the parameter '" + name + "' has the single value " + std::to_string(found->second.value) +
311 " in the domain '" + *found->second.domain + "', but " + (continuous ? "a range" : "categories") +
312 " in the domain '" + domain.name + "'");
313 }
314 });
315 for (std::size_t i = 0; i < _doc.parameterPoints.size(); ++i) {
316 ParameterPoint const &point = _doc.parameterPoints[i];
317 for (ParameterValue const &parameter : point.parameters) {
318 auto found = fixedAxes.find(parameter.name);
319 double const *value = parameter.value ? std::get_if<double>(&*parameter.value) : nullptr;
320 if (value && found != fixedAxes.end() && *value != found->second.value) {
321 error(at("parameter_points", i, point.name),
322 "the parameter point '" + point.name + "' gives the parameter '" + parameter.name + "' the value " +
323 std::to_string(*value) + ", but its domain only has the value " +
324 std::to_string(found->second.value));
325 }
326 }
327 }
328}
329
330// A categorical axis (HS3 #108) declares a category. All domains that list it must give it the same categories, and
331// none may list it as continuous.
332void Validator::checkCategoricalAxes()
333{
334 struct Declaration {
335 std::vector<std::string> const *categories = nullptr;
336 std::string const *domain = nullptr;
337 };
338 std::map<std::string, Declaration> categorical;
339 for (std::size_t i = 0; i < _doc.domains.size(); ++i) {
340 Domain const &domain = _doc.domains[i];
341 for (auto const &axis : domain.axes) {
342 auto const *cat = std::get_if<CategoricalAxis>(&axis);
343 if (!cat) {
344 continue;
345 }
346 _categories.emplace(cat->name, &cat->categories);
347 auto inserted = categorical.insert({cat->name, Declaration{&cat->categories, &domain.name}});
348 if (!inserted.second && *inserted.first->second.categories != cat->categories) {
349 error(at("domains", i, domain.name), "the categorical axis '" + cat->name + "' is listed in the domains '" +
350 *inserted.first->second.domain + "' and '" + domain.name +
351 "' with different categories");
352 }
353 }
354 }
355 for (std::size_t i = 0; i < _doc.domains.size(); ++i) {
356 Domain const &domain = _doc.domains[i];
357 for (auto const &axis : domain.axes) {
358 auto const *continuous = std::get_if<DomainAxis>(&axis);
359 if (!continuous || continuous->fixedValue) {
360 continue; // fixed axes are checked by checkFixedAxes()
361 }
362 auto found = categorical.find(continuous->name);
363 if (found != categorical.end()) {
364 error(at("domains", i, domain.name),
365 "the axis '" + continuous->name + "' is listed in a domain as categorical and as continuous");
366 }
367 }
368 }
369}
370
371// The columns of a combined data set or distribution are categorical axes of the domains, or categories that exist
372// already, and the keys consist of their categories.
373template <class Ref_t>
374void Validator::checkCombined(Combined<Ref_t> const &combined, std::string const &path, std::string const &context)
375{
376 std::vector<std::vector<std::string> const *> columnCategories;
377 std::set<std::string> columns;
378 for (std::string const &column : combined.columns) {
379 auto found = _categories.find(column);
380 if (found == _categories.end() && !isExternal(column)) {
381 error(path,
382 "the column '" + column + "' of " + context + " is not declared by a categorical axis of a domain");
383 return;
384 }
385 if (!columns.insert(column).second) {
386 error(path, "the column '" + column + "' of " + context + " is listed twice");
387 return;
388 }
389 columnCategories.push_back(found != _categories.end() ? found->second : nullptr);
390 }
391 std::set<std::vector<std::string>> keys;
392 for (auto const &component : combined.components) {
393 for (std::size_t k = 0; k < component.key.size(); ++k) {
394 auto const *categories = columnCategories[k];
395 if (categories && std::find(categories->begin(), categories->end(), component.key[k]) == categories->end()) {
396 error(path, "the label '" + component.key[k] + "' in position " + std::to_string(k) + " of a key of " +
397 context + " is not one of the categories of '" + combined.columns[k] + "'");
398 }
399 }
400 if (!keys.insert(component.key).second) {
401 std::string key = "[";
402 for (std::size_t k = 0; k < component.key.size(); ++k) {
403 key += (k == 0 ? "\"" : ", \"") + component.key[k] + "\"";
404 }
405 error(path, "the key " + key + "] is used by two components of " + context);
406 }
407 }
408}
409
410// Every sub-data set of a combined data set is a data set of the document that belongs to one combined data set. A
411// component may itself be a combined data set, paired with a component that is a combined distribution.
412void Validator::checkCombinedData()
413{
414 std::set<std::string> usedComponents;
415 for (std::size_t i = 0; i < _doc.data.size(); ++i) {
416 auto const *combined = std::get_if<CombinedData>(&_doc.data[i].body);
417 if (!combined) {
418 continue;
419 }
420 std::string const path = at("data", i, _doc.data[i].name);
421 std::string const context = "the combined data set '" + _doc.data[i].name + "'";
422 checkCombined(*combined, path, context);
423 for (auto const &component : combined->components) {
424 std::string const &name = component.ref.name;
425 if (!isDefinedIn(name, "data") || name == _doc.data[i].name || !usedComponents.insert(name).second) {
426 error(path, "the component '" + name + "' of " + context +
427 " is not a data set of the document, or it is already a component of another combined "
428 "data set");
429 }
430 }
431 }
432}
433
434void Validator::checkLikelihoods()
435{
436 for (std::size_t i = 0; i < _doc.likelihoods.size(); ++i) {
437 auto const &likelihood = _doc.likelihoods[i];
438 const std::string path = at("likelihoods", i, likelihood.name);
439 for (auto const &term : likelihood.terms) {
440 requireDistribution(term.distribution.name, path + ".distributions", "distribution");
441 if (auto const *data = std::get_if<DataRef>(&term.data)) {
442 if (!isDefinedIn(data->name, "data")) {
443 error(path + ".data", "dataset '" + data->name + "' cannot be found!");
444 }
445 }
446 }
447 for (auto const &aux : likelihood.auxDistributions) {
448 if (!isDefinedIn(aux.name, "distributions") && !isExternal(aux.name)) {
449 strictError(path + ".aux_distributions", "the distribution '" + aux.name + "' does not exist");
450 }
451 }
452 }
453}
454
455void Validator::checkAnalyses()
456{
457 for (std::size_t i = 0; i < _doc.analyses.size(); ++i) {
458 auto const &analysis = _doc.analyses[i];
459 const std::string path = at("analyses", i, analysis.name);
460 if (!isDefinedIn(analysis.likelihood.name, "likelihoods")) {
461 error(path + ".likelihood", "likelihood node not found!");
462 }
463 for (auto const &poi : analysis.parametersOfInterest) {
464 if (char const *section = sectionOf(poi.name)) {
465 error(path, "the parameter of interest '" + poi.name + "' of analysis '" + analysis.name +
466 "' is defined in \"" + section + "\", but it must be a parameter");
467 } else if (!_parameters.count(poi.name) && !isExternal(poi.name)) {
468 error(path, "the object '" + poi.name + "' in \"parameters_of_interest\" of analysis '" + analysis.name +
469 "' does not exist");
470 }
471 }
472 for (auto const &domain : analysis.domains) {
473 if (!isDefinedIn(domain.name, "domains")) {
474 strictError(path + ".domains", "the domain '" + domain.name + "' does not exist");
475 }
476 }
477 if (analysis.init && !isDefinedIn(analysis.init->name, "parameter_points")) {
478 warning(path, "the parameter point '" + analysis.init->name + "' used as \"init\" of analysis '" +
479 analysis.name + "' does not exist.");
480 }
481 if (analysis.prior && !isDefinedIn(analysis.prior->name, "distributions") && !isExternal(analysis.prior->name)) {
482 strictError(path + ".prior", "the distribution '" + analysis.prior->name + "' does not exist");
483 }
484 checkNormalizationRanges(analysis, path);
485 }
486}
487
488// A variate is normalized over the axis of the paired data set, or else over its axis in the domains of the analysis.
489// If both exist, they must give the same range, where an absent bound is equal only to an absent bound (HS3 0.3).
490void Validator::checkNormalizationRanges(Analysis const &analysis, std::string const &path)
491{
492 using Range = std::pair<std::optional<double>, std::optional<double>>;
493 auto bound = [](std::optional<double> value) { return value && !std::isinf(*value) ? value : std::nullopt; };
494 auto format = [](Range const &range) {
495 auto one = [](std::optional<double> value) { return value ? std::to_string(*value) : std::string("none"); };
496 return "[" + one(range.first) + ", " + one(range.second) + "]";
497 };
498
499 std::map<std::string, Range> domainRanges;
500 for (auto const &ref : analysis.domains) {
501 for (auto const &domain : _doc.domains) {
502 if (domain.name != ref.name) {
503 continue;
504 }
505 for (auto const &axisVariant : domain.axes) {
506 auto const *axis = std::get_if<DomainAxis>(&axisVariant);
507 if (!axis || axis->fixedValue) {
508 continue; // a fixed axis gives no range
509 }
510 domainRanges[axis->name] = {bound(axis->min), bound(axis->max)};
511 }
512 }
513 }
514 if (domainRanges.empty()) {
515 return;
516 }
517
518 auto check = [&](std::string const &dataName, std::string const &axisName, Range const &dataRange) {
519 auto found = domainRanges.find(axisName);
520 if (found != domainRanges.end() && found->second != dataRange) {
521 strictError(path, "the axis '" + axisName + "' of the data set '" + dataName + "' has the range " +
522 format(dataRange) + ", but the domains of the analysis '" + analysis.name +
523 "' give it the range " + format(found->second));
524 }
525 };
526 std::function<void(std::string const &)> checkData = [&](std::string const &dataName) {
527 for (auto const &data : _doc.data) {
528 if (data.name != dataName) {
529 continue;
530 }
531 // Continuous and binned axes have a range, categorical axes don't.
532 auto checkAxis = [&](auto const &a) { check(data.name, a.name, {bound(a.min), bound(a.max)}); };
533 auto checkAxes = [&](auto const &axes) {
534 for (auto const &axis : axes) {
535 std::visit(overloaded{[](CategoricalAxis const &) {}, checkAxis}, axis);
536 }
537 };
538 std::visit(overloaded{[&](PointData const &d) { std::for_each(d.axes.begin(), d.axes.end(), checkAxis); },
539 [&](UnbinnedData const &d) { checkAxes(d.axes); },
540 [&](BinnedData const &d) { checkAxes(d.axes); },
541 [&](CombinedData const &d) {
542 for (auto const &component : d.components) {
543 checkData(component.ref.name);
544 }
545 }},
546 data.body);
547 }
548 };
549 for (auto const &likelihood : _doc.likelihoods) {
550 if (likelihood.name != analysis.likelihood.name) {
551 continue;
552 }
553 for (auto const &term : likelihood.terms) {
554 if (auto const *data = std::get_if<DataRef>(&term.data)) {
555 checkData(data->name);
556 }
557 }
558 }
559}
560
561std::size_t Validator::checkAxis(BinnedAxis const &axis, std::string const &path)
562{
563 // Unlike continuous axes, binned axes always have finite bounds.
564 if (std::isinf(axis.min) || std::isinf(axis.max)) {
565 error(path, "the binned axis '" + axis.name + "' needs finite bounds");
566 }
567 if (auto const *regular = std::get_if<RegularBinning>(&axis.binning)) {
568 if (regular->nbins <= 0) {
569 error(path, "the axis '" + axis.name + "' needs a positive number of bins");
570 return 0;
571 }
572 if (!(axis.min < axis.max)) {
573 error(path, "the axis '" + axis.name + "' needs \"min\" smaller than \"max\"");
574 }
575 return regular->nbins;
576 }
577 auto const &edges = std::get<EdgesBinning>(axis.binning).edges;
578 return edges.empty() ? 0 : edges.size() - 1;
579}
580
581std::size_t Validator::checkAxis(CategoricalAxis const &axis, std::string const &path)
582{
583 if (axis.categories.empty()) {
584 error(path, "the axis '" + axis.name + "' needs at least one category");
585 }
586 return axis.categories.size();
587}
588
589template <class Axes>
590std::optional<std::size_t> Validator::numBins(Axes const &axes, std::string const &path)
591{
592 std::size_t nBins = 1;
593 bool valid = true;
594 for (std::size_t i = 0; i < axes.size(); ++i) {
595 const std::size_t n = checkAxis(axes[i], path + ".axes[" + std::to_string(i) + "]");
596 if (n == 0) {
597 valid = false; // reported already
598 } else if (nBins > std::numeric_limits<std::size_t>::max() / n) {
599 error(path + ".axes", "the axes have more bins than can be stored");
600 return std::nullopt;
601 }
602 nBins *= n;
603 }
604 return valid ? std::optional<std::size_t>{nBins} : std::nullopt;
605}
606
607void Validator::checkData()
608{
609 for (std::size_t i = 0; i < _doc.data.size(); ++i) {
610 auto const &data = _doc.data[i];
611 const std::string path = at("data", i, data.name);
612 // A fixed axis is only allowed in domains (HS3 0.3). Older versions of RooFit wrote the constant observables of
613 // data sets like this.
614 auto checkNotFixed = [&](ContinuousAxis const &axis) {
615 if (axis.hasFixedValue) {
616 strictError(path, "the axis '" + axis.name + "' of a data set must not have a fixed \"value\"");
617 }
618 };
619 if (auto const *point = std::get_if<PointData>(&data.body)) {
620 for (auto const &axis : point->axes) {
621 checkNotFixed(axis);
622 }
623 } else if (auto const *unbinned = std::get_if<UnbinnedData>(&data.body)) {
624 for (auto const &axis : unbinned->axes) {
625 if (auto const *continuous = std::get_if<ContinuousAxis>(&axis)) {
626 checkNotFixed(*continuous);
627 }
628 }
629 }
630 auto const *binned = std::get_if<BinnedData>(&data.body);
631 if (!binned) {
632 continue;
633 }
634 std::optional<std::size_t> nBinsOrNone = numBins(binned->axes, path);
635 if (!nBinsOrNone) {
636 continue;
637 }
638 const std::size_t nBins = *nBinsOrNone;
639 if (binned->contents.size() != nBins) {
640 error(path, "inconsistent bin numbers: contents=" + std::to_string(binned->contents.size()) +
641 ", bins=" + std::to_string(nBins));
642 }
643 if (binned->uncertainty) {
644 auto const &sigma = binned->uncertainty->sigma;
645 if (sigma.size() != binned->contents.size()) {
646 error(path, "inconsistent number of errors and contents in '" + data.name +
647 "': errors=" + std::to_string(sigma.size()) +
648 ", contents=" + std::to_string(binned->contents.size()));
649 }
650 auto const &correlation = binned->uncertainty->correlation;
651 if (!correlation.empty()) {
652 bool square = correlation.size() == binned->contents.size();
653 for (auto const &row : correlation) {
654 square = square && row.size() == binned->contents.size();
655 }
656 if (!square) {
657 error(path + ".uncertainty.correlation", "must be a square matrix of the size of \"contents\"");
658 }
659 }
660 }
661 }
662}
663
664void Validator::checkHistFactory(HistFactoryDist const &dist, std::string const &name, std::string const &path)
665{
666 if (dist.axes.empty()) {
667 error(path + ".axes", "a HistFactory distribution needs at least one axis");
668 return;
669 }
670 std::optional<std::size_t> nBinsOrNone = numBins(dist.axes, path);
671 if (!nBinsOrNone) {
672 return;
673 }
674 const std::size_t nBins = *nBinsOrNone;
675
676 std::string channelName = name;
677 if (channelName.rfind("model_", 0) == 0) {
678 channelName.erase(0, 6);
679 }
680
681 auto checkSize = [&](std::string const &where, std::size_t size, char const *what) {
682 if (size != nBins) {
683 error(where, std::string(what) + " has " + std::to_string(size) + " entries, but the channel has " +
684 std::to_string(nBins) + " bins");
685 }
686 };
687
688 // Two modifiers with the same parameter must have the same constraint.
689 std::map<std::string, std::pair<Constraint, std::string>> constraintOfParameter;
690 auto checkCorrelated = [&](std::string const &where, std::string const &parameter, Constraint const &constraint) {
691 auto inserted = constraintOfParameter.emplace(parameter, std::make_pair(constraint, where));
692 if (inserted.second) {
693 return;
694 }
695 if (!(inserted.first->second.first == constraint)) {
696 warning(where, "the parameter '" + parameter + "' has a different constraint than in " +
697 inserted.first->second.second +
698 ", but modifiers with the same parameter must share the constraint");
699 }
700 };
701
702 // The constraint distributions of the gamma parameters of shape modifiers.
703 auto checkGammaConstraint = [&](std::string const &where, GammaConstraint const &constraint) {
704 auto const *pdfs = std::get_if<GammaConstraintPdfs>(&constraint);
705 if (!pdfs) {
706 return;
707 }
708 checkSize(where + ".constraints", pdfs->pdfs.size(), "\"constraints\"");
709 for (auto const &pdf : pdfs->pdfs) {
710 if (pdf) {
711 requireDistribution(pdf->name, where + ".constraints", "constraint");
712 }
713 }
714 };
715
716 auto checkParameter = [&](std::string const &where, std::string const &parameter, std::string const &modifier) {
717 if (char const *section = sectionOf(parameter)) {
718 error(where, "the parameter '" + parameter + "' of the modifier '" + modifier + "' is defined in \"" +
719 section + "\", but it must be a parameter");
720 }
721 };
722
723 checkGammaConstraint(path + ".staterror", dist.statError.constraint);
724
725 // The staterror modifiers of all samples share the gamma parameters, so the ones that name constraints must name
726 // the same.
727 GammaConstraintPdfs const *statErrorConstraints = nullptr;
728 auto checkStatErrorConstraints = [&](std::string const &where, GammaConstraint const &constraint) {
729 auto const *pdfs = std::get_if<GammaConstraintPdfs>(&constraint);
730 if (!pdfs) {
731 return;
732 }
733 if (!statErrorConstraints) {
734 statErrorConstraints = pdfs;
735 return;
736 }
737 auto const &first = statErrorConstraints->pdfs;
738 const bool same = std::equal(first.begin(), first.end(), pdfs->pdfs.begin(), pdfs->pdfs.end(),
739 [](auto const &l, auto const &r) { return l && r ? l->name == r->name : !l && !r; });
740 if (!same) {
741 error(where,
742 "the staterror modifiers of the samples of channel '" + channelName + "' name different constraints");
743 }
744 };
745
746 std::set<std::string> sampleNames;
747 for (std::size_t iSample = 0; iSample < dist.samples.size(); ++iSample) {
748 auto const &sample = dist.samples[iSample];
749 const std::string samplePath = path + ".samples[" + std::to_string(iSample) + "](" + sample.name + ")";
750 if (!sampleNames.insert(sample.name).second) {
751 error(samplePath, "the name of the sample is not unique in the channel");
752 }
753 checkSize(samplePath + ".data.contents", sample.contents.size(), "\"contents\"");
754 // These modifiers create objects that are named after them. Older versions of RooFit wrote a parameter that
755 // interpolates a sample more than once as several histosys modifiers of the same name, which are still read.
756 std::set<std::string> objectNames;
757 auto checkUniqueName = [&](std::string const &where, char const *type, std::string const &modifierName,
758 bool allowedBeforeHS3v03 = false) {
759 if (!objectNames.insert(std::string(type) + " " + modifierName).second) {
760 const std::string message =
761 std::string("there is another ") + type + " modifier named '" + modifierName + "' in the sample";
762 if (allowedBeforeHS3v03) {
763 strictError(where, message);
764 } else {
765 error(where, message);
766 }
767 }
768 };
769 if (sample.errors && sample.errors->size() != sample.contents.size()) {
770 error(samplePath + ".data", "inconsistent number of errors and contents in '" + sample.name +
771 "': errors=" + std::to_string(sample.errors->size()) +
772 ", contents=" + std::to_string(sample.contents.size()));
773 }
774 for (std::size_t iModifier = 0; iModifier < sample.modifiers.size(); ++iModifier) {
775 Modifier const &modifier = sample.modifiers[iModifier];
776 const std::string modifierPath =
777 samplePath + ".modifiers[" + std::to_string(iModifier) + "](" + nameOf(modifier) + ")";
778 auto checkInterpolation = [&](std::optional<Interpolation> const &interpolation, char const *type,
779 std::string const &modifierName) {
780 if (!interpolation && !dist.defaultInterpolation) {
781 error(modifierPath, std::string("interpolation for ") + type + " modifier '" + modifierName +
782 "' in sample '" + sample.name + "' of channel '" + channelName +
783 "' is not given, and the channel has no \"default_interpolation\"");
784 }
785 };
786 // The modifiers with a single parameter, which can have a constraint. Of the constraint types of older
787 // documents, RooFit only creates the Gaussian for them.
788 auto checkSingleParameter = [&](auto const &m) {
789 checkParameter(modifierPath, m.parameter.name, m.name);
790 if (auto const *pdf = std::get_if<ConstraintPdf>(&m.constraint)) {
791 requireDistribution(pdf->pdf.name, modifierPath, "constraint");
792 } else if (auto const *type = std::get_if<ConstraintType>(&m.constraint);
793 type && *type != ConstraintType::Gauss) {
794 error(modifierPath, std::string("legacy constraint value '") + toString(*type) + "' for modifier '" +
795 m.name +
796 "' is a known constraint type, but it cannot be resolved in this context");
797 }
798 checkCorrelated(modifierPath, m.parameter.name, m.constraint);
799 };
800 std::visit(overloaded{
801 [&](NormFactor const &m) { checkSingleParameter(m); },
802 [&](NormSys const &m) {
803 checkSingleParameter(m);
804 checkInterpolation(m.interpolation, "normsys", m.name);
805 },
806 [&](HistoSys const &m) {
807 checkUniqueName(modifierPath, "histosys", m.name, true);
808 checkSingleParameter(m);
809 checkInterpolation(m.interpolation, "histosys", m.name);
810 checkSize(modifierPath + ".data.hi.contents", m.hi.contents.size(), "\"contents\"");
811 checkSize(modifierPath + ".data.lo.contents", m.lo.contents.size(), "\"contents\"");
812 },
813 [&](ShapeSys const &m) {
814 checkUniqueName(modifierPath, "shapesys", m.name);
815 if (!m.vals.empty()) {
816 checkSize(modifierPath + ".data.vals", m.vals.size(), "\"vals\"");
817 }
818 if (!m.parameters.empty()) {
819 checkSize(modifierPath + ".parameters", m.parameters.size(), "\"parameters\"");
820 }
821 for (auto const &p : m.parameters) {
822 checkParameter(modifierPath, p.name, m.name);
823 }
824 checkGammaConstraint(modifierPath, m.constraint);
825 },
826 [&](StatError const &m) {
827 if (!m.parameters.empty()) {
828 checkSize(modifierPath + ".parameters", m.parameters.size(), "\"parameters\"");
829 }
830 checkGammaConstraint(modifierPath, m.constraint);
831 checkStatErrorConstraints(modifierPath, m.constraint);
832 // A lognormal constraint makes no sense for gamma parameters.
833 if (auto const *type = std::get_if<ConstraintType>(&m.constraint);
834 type && *type == ConstraintType::LogNormal) {
835 error(modifierPath, std::string("unsupported constraint '") + toString(*type) +
836 "' of the staterror modifier in channel '" + name +
837 "', supported are \"Poisson\" and \"Gauss\"");
838 }
839 },
840 [&](CustomModifier const &m) {
841 if (!isDefinedIn(m.name, "functions") && !isDefinedIn(m.name, "distributions") &&
842 !isExternal(m.name)) {
843 error(modifierPath, "unable to find custom modifier '" + m.name + "'");
844 }
845 },
846 },
847 modifier);
848 }
849 }
850}
851
852} // namespace
853
854void checkDocument(HS3Document const &doc, Diagnostics &diagnostics, ValidateOptions const &options)
855{
856 Validator{doc, diagnostics, options}.run();
857}
858
859std::optional<ValidatedHS3Document> validate(HS3Document doc, Diagnostics &diagnostics, ValidateOptions const &options)
860{
861 checkDocument(doc, diagnostics, options);
862 if (hasErrors(diagnostics)) {
863 return std::nullopt;
864 }
865 return ValidatedHS3Document{std::move(doc)};
866}
867
868void validateHistFactoryDist(HistFactoryDist const &dist, std::string const &name, Diagnostics &diagnostics)
869{
870 // Without a document, all names are resolved later in the workspace.
871 HS3Document empty;
872 ValidateOptions options;
873 options.isExternal = [](std::string const &) { return true; };
874 Validator{empty, diagnostics, options}.checkHistFactory(dist, name, "");
875}
876
877void validateCombinedDist(CombinedDist const &dist, std::string const &name, Diagnostics &diagnostics)
878{
879 // Without a document, the columns are categories of the workspace, whose labels are checked when it is built.
880 HS3Document empty;
881 ValidateOptions options;
882 options.isExternal = [](std::string const &) { return true; };
883 Validator{empty, diagnostics, options}.checkCombined(dist, "", "the combined_dist '" + name + "'");
884}
885
886} // namespace HS3
887} // namespace RooFit
std::string channelName
ValidateOptions const & _options
Diagnostics & _diagnostics
std::map< std::string, std::vector< char const * > > _sections
The sections where a name is defined.
std::map< std::string, std::vector< std::string > const * > _categories
Of the categorical axes of the domains.
HS3Document const & _doc
std::set< std::string > _parameters
std::string message
#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 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 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 modifier
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 format
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
An HS3 document. It is move-only, because generic objects refer to the JSON tree of the document.
A document that passed validate().
const Double_t sigma
const Int_t n
Definition legend1.C:16
double dist(Rotation3D const &r1, Rotation3D const &r2)
Types that represent an HS3 document.
void validateHistFactoryDist(HistFactoryDist const &dist, std::string const &name, Diagnostics &diagnostics)
Same as validate(), but for a single HistFactory or combined distribution that doesn't come with a do...
void checkDocument(HS3Document const &doc, Diagnostics &diagnostics, ValidateOptions const &options={})
The checks of validate(), for a document that is still needed if it doesn't pass them.
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::optional< ValidatedHS3Document > validate(HS3Document doc, Diagnostics &diagnostics, ValidateOptions const &options)
Checks what can be checked without knowing how the objects are built: unique names,...
char const * toString(InterpolationType type)
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
Definition HS3Parser.cxx:92
std::vector< Diagnostic > Diagnostics
std::variant< Unconstrained, ConstraintType, ConstantGammas, GammaConstraintPdfs > GammaConstraint
std::variant< Unconstrained, ConstraintType, ConstraintPdf > Constraint
void validateCombinedDist(CombinedDist const &dist, std::string const &name, Diagnostics &diagnostics)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
static const char * what
Definition stlLoader.cc:5
Data sets or distributions that are selected by a key (HS3 #119). The columns are categorical axes of...
Options for validate().
std::function< bool(std::string const &) isExternal)
Whether a name that is not defined in the document is known in some other way, e.g....
Ta Range(0, 0, 1, 1)
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4