Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
JSONFactories_HistFactory.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Carsten D. Burgard, DESY/ATLAS, Dec 2021
5 *
6 * Copyright (c) 2022, 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
14#include <RooFitHS3/JSONIO.h>
16
21#include <RooConstVar.h>
22#include <RooRealVar.h>
23#include <RooDataHist.h>
24#include <RooHistFunc.h>
25#include <RooRealSumPdf.h>
26#include <RooBinWidthFunction.h>
27#include <RooProdPdf.h>
28#include <RooPoisson.h>
29#include <RooFormulaVar.h>
30#include <RooLognormal.h>
31#include <RooGaussian.h>
32#include <RooProduct.h>
33#include <RooWorkspace.h>
34#include <RooFitImplHelpers.h>
35#include <RooFit/ModelConfig.h>
36
37#include <algorithm>
38#include <cctype>
39#include <cmath>
40#include <iterator>
41#include <limits>
42#include <map>
43#include <optional>
44#include <regex>
45#include <set>
46#include <sstream>
47#include <variant>
48
49#include "HS3Builder.h"
50#include "JSONIOUtils.h"
51
56
57namespace HS3 = RooFit::HS3;
58
59using namespace RooStats::HistFactory;
60using namespace RooStats::HistFactory::Detail;
62
63namespace {
64
65double round_prec(double d, int nSig)
66{
67 if (d == 0.0)
68 return 0.0;
69 int ndigits = std::floor(std::log10(std::abs(d))) + 1 - nSig;
70 double sf = std::pow(10, ndigits);
71 if (std::abs(d / sf) < 2)
72 ndigits--;
73 return sf * std::round(d / sf);
74}
75
76// An interpolation as it is written in the document, for messages.
77std::string interpolationString(const Interpolation &interpolation)
78{
80 HS3::writeInterpolation(tree->rootnode(), interpolation);
81 std::stringstream ss;
82 tree->rootnode().writeJSON(ss);
83 return ss.str();
84}
85
86const char *interpolationClassName(InterpolationClass interpolationClass)
87{
88 return interpolationClass == InterpolationClass::Piecewise ? "PiecewiseInterpolation" : "FlexibleInterpVar";
89}
90
91Interpolation interpolationFromCode(int code, InterpolationClass interpolationClass, const std::string &context)
92{
93 if (auto interpolation = HS3::interpolationFromCode(code, interpolationClass)) {
94 return *interpolation;
95 }
96 RooJSONFactoryWSTool::error(context + " has unsupported " + interpolationClassName(interpolationClass) + " code " +
97 std::to_string(code));
98}
99
100int codeFromInterpolation(const Interpolation &interpolation, InterpolationClass interpolationClass,
101 const std::string &context)
102{
103 if (auto code = HS3::codeFromInterpolation(interpolation, interpolationClass)) {
104 return *code;
105 }
106 RooJSONFactoryWSTool::error(context + " " + interpolationString(interpolation) + " cannot be represented by " +
107 interpolationClassName(interpolationClass));
108}
109
110// The interpolations of the parameters of a PiecewiseInterpolation or FlexibleInterpVar.
111std::vector<Interpolation>
112toInterpolations(std::vector<int> const &codes, InterpolationClass interpolationClass, std::string const &context)
113{
114 std::vector<Interpolation> out;
115 out.reserve(codes.size());
116 for (std::size_t i = 0; i < codes.size(); ++i) {
117 out.push_back(
118 interpolationFromCode(codes[i], interpolationClass, context + " at parameter index " + std::to_string(i)));
119 }
120 return out;
121}
122
123std::vector<int> toCodes(std::vector<Interpolation> const &interpolations, InterpolationClass interpolationClass,
124 std::string const &context)
125{
126 std::vector<int> out;
127 out.reserve(interpolations.size());
128 for (std::size_t i = 0; i < interpolations.size(); ++i) {
129 out.push_back(codeFromInterpolation(interpolations[i], interpolationClass,
130 context + " component 'interpolations' at index " + std::to_string(i)));
131 }
132 return out;
133}
134
135void erasePrefix(std::string &str, std::string_view prefix)
136{
137 if (startsWith(str, prefix)) {
138 str.erase(0, prefix.size());
139 }
140}
141
142bool eraseSuffix(std::string &str, std::string_view suffix)
143{
144 if (endsWith(str, suffix)) {
145 str.erase(str.size() - suffix.size());
146 return true;
147 } else {
148 return false;
149 }
150}
151
152template <class Coll>
153void sortByName(Coll &coll)
154{
155 std::sort(coll.begin(), coll.end(), [](auto &l, auto &r) { return l.name < r.name; });
156}
157
158// Whether any of the gamma parameters names a constraint. Otherwise, they are all free, and nothing is written.
159bool anyNamed(HS3::GammaConstraintPdfs const &constraints)
160{
161 return std::any_of(constraints.pdfs.begin(), constraints.pdfs.end(),
162 [](auto const &pdf) { return pdf.has_value(); });
163}
164
165template <class T>
166T *findClient(RooAbsArg *gamma)
167{
168 for (const auto &client : gamma->clients()) {
169 if (auto casted = dynamic_cast<T *>(client)) {
170 return casted;
171 }
172 if (T *found = findClient<T>(client)) {
173 return found;
174 }
175 }
176 return nullptr;
177}
178
179template <class T>
180T *findAmong(RooAbsArg *g, std::vector<RooAbsPdf *> const &pdfs)
181{
182 for (RooAbsPdf *pdf : pdfs) {
183 if (auto casted = dynamic_cast<T *>(pdf); casted && casted->dependsOn(*g)) {
184 return casted;
185 }
186 }
187 return nullptr;
188}
189
190// Find the constraint of the parameter `g`: preferably among the constraint terms `channelConstraints` of the channel
191// (the other factors of its product), otherwise among the clients of `g`. Looking at the channel first avoids taking
192// another pdf that depends on the parameter, e.g. in another channel, for its constraint.
193RooAbsPdf *findConstraint(RooAbsArg *g, std::vector<RooAbsPdf *> const &channelConstraints)
194{
195 if (!g)
196 return nullptr;
197 if (auto *constraint = findAmong<RooPoisson>(g, channelConstraints))
198 return constraint;
199 if (auto *constraint = findAmong<RooGaussian>(g, channelConstraints))
200 return constraint;
201 if (auto *constraint = findAmong<RooLognormal>(g, channelConstraints))
202 return constraint;
203 if (auto *constraint = findClient<RooPoisson>(g))
204 return constraint;
205 if (auto *constraint = findClient<RooGaussian>(g))
206 return constraint;
207 return findClient<RooLognormal>(g);
208}
209
210RooRealVar &createNominal(RooWorkspace &ws, std::string const &parname, double val)
211{
212 RooRealVar &nom = getOrCreate<RooRealVar>(ws, "nom_" + parname, val, -10, 10);
213 nom.setConstant(true);
214 return nom;
215}
216
217/// Get the conventional name of the constraint pdf for a constrained
218/// parameter.
219std::string constraintName(std::string const &paramName)
220{
221 return paramName + "Constraint";
222}
223
224// The component of the array distribution `array` that constrains `param`: the one that depends on it.
225RooAbsPdf &arrayComponentFor(RooProdPdf const &array, RooAbsArg const &param, std::string const &context)
226{
227 std::vector<RooAbsPdf *> matches;
228 for (RooAbsPdf *pdf : static_range_cast<RooAbsPdf *>(array.pdfList())) {
229 if (pdf->dependsOn(param)) {
230 matches.push_back(pdf);
231 }
232 }
233 if (matches.size() == 1) {
234 return *matches.front();
235 }
236 const std::string what = "the array distribution '" + std::string(array.GetName()) +
237 "' named as the constraint of '" + param.GetName() + "' (" + context + ") has ";
238 if (matches.empty()) {
239 RooJSONFactoryWSTool::error(what + "no component that depends on this parameter");
240 }
241 RooJSONFactoryWSTool::error(what + std::to_string(matches.size()) +
242 " components that depend on this parameter, but a parameter can only be constrained "
243 "by one component");
244}
245
246// Find the constraint distribution `constraintName` of the parameter `param`. If the name resolves to an array
247// distribution, the component that depends on the parameter is returned: that is the term that enters the likelihood
248// for this parameter, and the whole array enters once through the components of all of its parameters.
249RooAbsPdf &findNamedConstraint(RooJSONFactoryWSTool &tool, std::string const &constraintName, RooAbsArg const &param,
250 std::string const &context)
251{
252 RooAbsPdf *constraint = tool.tryRequest<RooAbsPdf>(constraintName);
253 if (!constraint) {
254 RooJSONFactoryWSTool::error("unable to find the constraint '" + constraintName + "' of " + context);
255 }
256 auto const *array = dynamic_cast<RooProdPdf const *>(constraint);
257 return array && array->getAttribute(arrayDistTag) ? arrayComponentFor(*array, param, context) : *constraint;
258}
259
260// The parameter of a modifier, which is created if the document doesn't define it. It's a variable, or a constant if
261// the document doesn't give it a domain.
262RooAbsReal &getOrCreateParameter(RooJSONFactoryWSTool &tool, std::string const &name, double val, double min,
263 double max, std::string const &modifier)
264{
265 RooWorkspace &ws = *tool.workspace();
266 TObject *existing = ws.obj(name);
267 if (!existing) {
268 return getOrCreate<RooRealVar>(ws, name, val, min, max);
269 }
270 if (dynamic_cast<RooRealVar *>(existing) || dynamic_cast<RooConstVar *>(existing)) {
271 return *static_cast<RooAbsReal *>(existing);
272 }
273 RooJSONFactoryWSTool::error("the parameter '" + name + "' of the modifier '" + modifier +
274 "' is neither a variable nor a constant");
275}
276
277void setErrorIfVariable(RooAbsReal &param, double error)
278{
279 if (auto *var = dynamic_cast<RooRealVar *>(&param)) {
280 var->setError(error);
281 }
282}
283
284// All constraints of parameters that control a whole sample are created here. Following the HS3 standard, the nominal
285// value is defined by the type of the modifier, and the standard deviation is one.
286void addConstraint(RooJSONFactoryWSTool &tool, HS3::Constraint const &constraint, RooAbsReal &param, double nominal,
287 const char *modifierType, std::string const &modifier, std::string const &sample,
288 RooArgSet &constraints)
289{
290 RooWorkspace &ws = *tool.workspace();
291 std::visit(HS3::overloaded{
292 [](HS3::Unconstrained) {},
294 // The validation only lets a Gaussian constraint through.
295 RooRealVar &nom = createNominal(ws, param.GetName(), nominal);
296 setErrorIfVariable(param, 1.0);
297 const std::string name = constraintName(param.GetName());
298 RooAbsPdf *pdf = ws.pdf(name);
299 constraints.add(pdf ? *pdf : tool.wsEmplace<RooGaussian>(name, param, nom, 1.));
300 },
301 [&](HS3::ConstraintPdf const &constraintPdf) {
302 RooAbsPdf &pdf = findNamedConstraint(tool, constraintPdf.pdf.name, param,
303 std::string("the ") + modifierType + " modifier '" + modifier +
304 "' of sample '" + sample + "'");
305 if (auto gauss = dynamic_cast<RooGaussian *>(&pdf)) {
306 setErrorIfVariable(param, gauss->getSigma().getVal());
307 }
308 constraints.add(pdf);
309 },
310 },
311 constraint);
312}
313
314// The constraint of the parameter of a normsys or histosys modifier, whose nominal value is zero. Before HS3 named the
315// constraint distributions in "constraints", RooFit created the global observable "nom_<parameter>", which the
316// constraint distribution of older documents may use without defining it.
317void addSysConstraint(RooJSONFactoryWSTool &tool, HS3::Constraint const &constraint, RooAbsReal &param,
318 const char *modifierType, std::string const &modifier, std::string const &sample,
319 RooArgSet &constraints)
320{
321 auto const *pdf = std::get_if<HS3::ConstraintPdf>(&constraint);
322 if (pdf && pdf->legacyName) {
323 createNominal(*tool.workspace(), param.GetName(), 0.0);
324 }
325 addConstraint(tool, constraint, param, 0.0, modifierType, modifier, sample, constraints);
326}
327
328// The tau of a Poisson constraint of a gamma whose mean is the product gamma * tau, like in HistFactory, or
329// std::nullopt if the constraint has another form.
330std::optional<double> findPoissonTau(RooPoisson const &constraint, RooAbsArg const &gamma)
331{
332 auto const *mean = dynamic_cast<RooProduct const *>(&constraint.getMean());
333 if (!mean) {
334 return std::nullopt;
335 }
336
337 // The tau is the constant factor. In imported workspaces, it can also be a variable that is named like it.
338 for (RooAbsArg *arg : mean->servers()) {
339 auto const *tau = dynamic_cast<RooAbsReal const *>(arg);
340 if (tau && arg != &gamma && (tau->isConstant() || endsWith(tau->GetName(), "_tau"))) {
341 return tau->getVal();
342 }
343 }
344 return std::nullopt;
345}
346
347// The relative uncertainty that the constraint distribution of a gamma encodes, if it has one of the forms of
348// HistFactory: the sigma of a Gaussian, or 1/sqrt(tau) for a Poisson distribution with mean gamma * tau. The nominal
349// value of a gamma is 1, so the sigma of a Gaussian is relative to it. It is not divided by the mean, which is the
350// gamma itself in the Gaussians that HistFactory creates.
351std::optional<double> gammaRelUncertainty(RooAbsPdf const &constraint, RooAbsArg const &gamma)
352{
353 if (auto gauss = dynamic_cast<RooGaussian const *>(&constraint)) {
354 return gauss->getSigma().getVal();
355 }
356 if (auto poisson = dynamic_cast<RooPoisson const *>(&constraint)) {
357 if (auto tau = findPoissonTau(*poisson, gamma)) {
358 return 1. / std::sqrt(*tau);
359 }
360 }
361 return std::nullopt;
362}
363
364// Configure the gammas that have a constraint distribution like HistFactory does from their relative uncertainties,
365// see configureConstrainedGammas(). The relative uncertainty of a gamma is the one in `relSigmas` if it is positive,
366// and otherwise the one that its constraint distribution encodes, see gammaRelUncertainty(). Without `relSigmas`, the
367// latter is only the initial error of the gamma. The unconstrained gammas are free, and left as they are. So are the
368// gammas that are functions defined elsewhere in the document, since only variables can be configured.
369void configureGammasWithConstraints(RooArgList const &gammas, std::vector<double> const &relSigmas,
370 std::vector<RooAbsPdf *> const &constraintPdfs, double minSigma)
371{
372 RooArgList constrainedGammas;
373 std::vector<double> constrainedSigmas;
374 for (std::size_t i = 0; i < gammas.size(); ++i) {
375 auto *gamma = dynamic_cast<RooRealVar *>(&gammas[i]);
376 if (!constraintPdfs[i] || !gamma) {
377 continue;
378 }
379 std::optional<double> relSigma = !relSigmas.empty() && relSigmas[i] > 0.
380 ? std::make_optional(relSigmas[i])
381 : gammaRelUncertainty(*constraintPdfs[i], *gamma);
382 // Without any known uncertainty, the gamma is left to its constraint distribution.
383 if (!relSigma) {
384 continue;
385 }
386 if (relSigmas.empty()) {
387 gamma->setError(*relSigma);
388 } else {
389 constrainedGammas.add(*gamma);
390 constrainedSigmas.push_back(*relSigma);
391 }
392 }
393 configureConstrainedGammas(constrainedGammas, constrainedSigmas, minSigma);
394}
395
396// Create the ParamHistFunc of the gamma parameters, together with their constraints. With a constraint type, RooFit
397// creates the constraints of the gammas from their relative uncertainties `vals`, like HistFactory.
398ParamHistFunc &createPHF(RooJSONFactoryWSTool &tool, std::string const &phfname, std::string const &sysname,
399 std::vector<HS3::ParameterRef> const &parnames, std::vector<double> const &vals,
400 HS3::GammaConstraint const &constraint, RooArgSet &constraints, RooArgSet const &observables,
401 double gammaMax, double minSigma, std::size_t nBins, std::string const &context,
402 bool configureGammas = true)
403{
404 RooWorkspace &ws = *tool.workspace();
405
406 // The validation made sure that there is a value, parameter and constraint for each bin, if they are given.
407 RooArgList gammas;
408 for (std::size_t i = 0; i < nBins; ++i) {
409 const std::string name = parnames.empty() ? "gamma_" + sysname + "_bin_" + std::to_string(i) : parnames[i].name;
410 auto *existing = dynamic_cast<RooAbsReal *>(ws.obj(name));
411 gammas.add(existing ? *existing : getOrCreate<RooRealVar>(ws, name, 1., defaultGammaMin, gammaMax));
412 }
413
414 // The gammas and `vals` are given in the order of HS3 (last axis fastest), which is also the order in which they
415 // are paired below. ParamHistFunc expects its parameters in TH1 order.
416 checkParamHistFuncOrderIsDefined(tool.hs3Version(), observables, "the modifier '" + sysname + "'");
417 RooArgList gammasInTH1Order = toParamHistFuncOrder(gammas, observables);
418
419 // Shape modifiers of the same name in a channel share the function, so they need the same parameters.
420 if (RooAbsArg *existing = ws.arg(phfname.c_str())) {
421 auto *existingPHF = dynamic_cast<ParamHistFunc *>(existing);
422 if (!existingPHF || existingPHF->paramList().size() != gammasInTH1Order.size() ||
423 !existingPHF->paramList().hasSameLayout(gammasInTH1Order)) {
424 RooJSONFactoryWSTool::error("the modifier '" + sysname + "' has other parameters than another modifier " +
425 "of this name in the channel");
426 }
427 }
428 auto &phf = tool.wsEmplace<ParamHistFunc>(phfname, observables, gammasInTH1Order);
429
430 auto addGammaConstraints = [&](Constraint::Type type) {
431 for (auto const &term : createGammaConstraints(gammas, vals, minSigma, type).constraints) {
432 constraints.add(tool.wsImport(*term));
433 }
434 };
435
436 if (auto const *pdfs = std::get_if<HS3::GammaConstraintPdfs>(&constraint)) {
437 // The constraints are resolved per gamma (in bin order, like "constraints"), which also picks the right
438 // component out of an array distribution. Unconstrained gammas get a nullptr.
439 std::vector<RooAbsPdf *> constraintPdfs;
440 for (std::size_t i = 0; i < pdfs->pdfs.size(); ++i) {
441 auto const &pdfName = pdfs->pdfs[i];
442 RooAbsPdf *pdf = pdfName ? &findNamedConstraint(tool, pdfName->name, gammas[i], context) : nullptr;
443 if (pdf) {
444 constraints.add(*pdf);
445 }
446 constraintPdfs.push_back(pdf);
447 }
448 // Without `configureGammas`, nothing is derived from `vals`: the gammas keep their range and constness, and
449 // only get the initial error that their constraint distribution encodes.
450 configureGammasWithConstraints(gammas, configureGammas ? vals : std::vector<double>{}, constraintPdfs, minSigma);
451 }
452
453 if (vals.empty()) {
454 return phf;
455 }
456
457 std::visit(HS3::overloaded{
458 // Free gammas are left as they are, and the ones with named constraints are configured above.
459 [](HS3::Unconstrained) {},
460 [](HS3::GammaConstraintPdfs const &) {},
462 // Only the gammas that are variables can be set constant; the others can be functions.
463 for (RooAbsArg *gamma : gammas) {
464 if (auto *var = dynamic_cast<RooRealVar *>(gamma)) {
465 var->setConstant(true);
466 }
467 }
468 },
470 switch (type) {
471 case HS3::ConstraintType::Gauss: addGammaConstraints(Constraint::Gaussian); break;
472 case HS3::ConstraintType::Poisson: addGammaConstraints(Constraint::Poisson); break;
473 case HS3::ConstraintType::LogNormal:
474 RooJSONFactoryWSTool::error(std::string("unsupported constraint '") + toString(type) +
475 "' for the gamma parameters of '" + sysname +
476 "', supported are \"Poisson\" and \"Gauss\"");
477 }
478 },
479 },
480 constraint);
481
482 return phf;
483}
484
485// The relative uncertainty that the constraint distribution of a gamma encodes, see gammaRelUncertainty(). Constraints
486// of another form raise an error.
487double constraintRelError(RooAbsPdf const &constraint, RooAbsArg const &gamma)
488{
489 if (auto relSigma = gammaRelUncertainty(constraint, gamma)) {
490 return *relSigma;
491 }
492 RooJSONFactoryWSTool::error("unsupported constraint '" + std::string(constraint.GetName()) + "' of '" +
493 gamma.GetName() +
494 "': only RooGaussian and RooPoisson with mean gamma * tau are supported for the "
495 "relative uncertainties of gammas");
496}
497
498struct ChannelContext {
501 RooArgSet const &observables;
502 std::string fprefix;
503 std::string channelName;
504 RooAbsArg const *mcStatObject;
505 RooArgSet &constraints;
506};
507
508void buildSample(ChannelContext const &ctx, HS3::Sample const &sample)
509{
510 RooJSONFactoryWSTool &tool = ctx.tool;
511 RooWorkspace &ws = *tool.workspace();
512
513 std::string const &sampleName = sample.name;
514 std::string prefixedName = ctx.fprefix + "_" + sampleName;
515
516 // The objects of a sample are not shared, so an existing object of the same name is a name clash.
517 auto newName = [&](std::string name) {
518 if (ws.arg(name.c_str())) {
519 RooJSONFactoryWSTool::error("the object '" + name + "' for sample '" + sampleName + "' of channel '" +
520 ctx.channelName + "' has the name of an existing object");
521 }
522 return name;
523 };
524
525 auto dataHist = HS3::createDataHist(prefixedName + "_dataHist", ctx.observables, sample.contents,
526 sample.errors ? &*sample.errors : nullptr);
527 auto &hf = tool.wsEmplace<RooHistFunc>(newName("hist_" + prefixedName), ctx.observables, *dataHist);
528 hf.SetTitle(sampleName.c_str());
529
530 // What the modifiers contribute: the factors of the shape and of the normalization of the sample.
531 RooArgList shapeElems;
532 RooArgList normElems;
533 // The arguments of the FlexibleInterpVar for the normsys modifiers.
534 RooArgList overallNps;
535 std::vector<double> overallLow;
536 std::vector<double> overallHigh;
537 std::vector<int> overallInterp;
538 // The arguments of the PiecewiseInterpolation for the histosys modifiers.
539 RooArgList histNps;
540 RooArgList histoLo;
541 RooArgList histoHi;
542 std::vector<int> histoInterp;
543 std::map<std::string, int> histoSysCount;
544
545 shapeElems.add(tool.wsEmplace<RooBinWidthFunction>(newName(prefixedName + "_binWidth"), hf, true));
546
547 const bool hasStatError = std::any_of(sample.modifiers.begin(), sample.modifiers.end(),
548 [](auto const &m) { return std::holds_alternative<HS3::StatError>(m); });
549 if (hasStatError) {
550 shapeElems.add(*ctx.mcStatObject);
551 }
552
553 // The validation made sure that the channel has a "default_interpolation" if a modifier doesn't give its own.
554 auto interpolationCode = [&](std::optional<Interpolation> const &interpolation,
555 InterpolationClass interpolationClass, const char *type, std::string const &name) {
556 return codeFromInterpolation(interpolation ? *interpolation : ctx.dist.defaultInterpolation.value(),
557 interpolationClass,
558 std::string("interpolation for ") + type + " modifier '" + name + "' in sample '" +
559 sampleName + "' of channel '" + ctx.channelName + "'");
560 };
561
562 for (HS3::Modifier const &modifier : sample.modifiers) {
563 std::visit(
565 [](HS3::StatError const &) {}, // built once for the channel, in buildHistFactoryDist()
566 [&](HS3::NormFactor const &mod) {
567 RooAbsReal &param = getOrCreateParameter(tool, mod.parameter.name, 1., -3, 5, mod.name);
568 // Norm factors get an initial zero error like in HistoToWorkspaceFactoryFast, unless an error was
569 // already set, e.g. by the constraint of another occurrence of this parameter.
570 if (auto *var = dynamic_cast<RooRealVar *>(&param); var && !var->hasError()) {
571 var->setError(0.0);
572 }
573 normElems.add(param);
574 addConstraint(tool, mod.constraint, param, 1.0, "normfactor", mod.name, sampleName, ctx.constraints);
575 },
576 [&](HS3::NormSys const &mod) {
577 RooAbsReal &param = getOrCreateParameter(tool, mod.parameter.name, 0., -5, 5, mod.name);
578 overallNps.add(param);
579 const int interp =
580 interpolationCode(mod.interpolation, InterpolationClass::Flexible, "normsys", mod.name);
581 // FlexibleInterpVar code 4 interpolates in log-space, so variations <= 0 would give NaN, which
582 // propagates through the model and makes its evaluation fail. As a hack, they are cut off.
583 auto cutOff = [&](double variation) {
584 return interp == 4 && variation <= 0 ? std::numeric_limits<double>::epsilon() : variation;
585 };
586 overallLow.push_back(cutOff(mod.lo));
587 overallHigh.push_back(cutOff(mod.hi));
588 overallInterp.push_back(interp);
589
590 addSysConstraint(tool, mod.constraint, param, "normsys", mod.name, sampleName, ctx.constraints);
591 },
592 [&](HS3::HistoSys const &mod) {
593 RooAbsReal &param = getOrCreateParameter(tool, mod.parameter.name, 0., -5, 5, mod.name);
594 histNps.add(param);
595 // Documents before HS3 0.3 can have several histosys modifiers of the same name in a sample (see the
596 // validation). Their histograms are told apart by a counter.
597 const int count = ++histoSysCount[mod.name];
598 const std::string objName = count == 1 ? mod.name : mod.name + "_" + std::to_string(count);
599 auto addVariation = [&](RooArgList &list, HS3::HistoSysVariation const &variation, const char *suffix) {
600 const std::string name = newName(objName + suffix + prefixedName);
601 list.add(
602 tool.wsEmplace<RooHistFunc>(name, ctx.observables,
603 HS3::createDataHist(name, ctx.observables, variation.contents,
604 variation.errors ? &*variation.errors : nullptr)));
605 };
606 addVariation(histoLo, mod.lo, "Low_");
607 addVariation(histoHi, mod.hi, "High_");
608 histoInterp.push_back(
609 interpolationCode(mod.interpolation, InterpolationClass::Piecewise, "histosys", mod.name));
610 addSysConstraint(tool, mod.constraint, param, "histosys", mod.name, sampleName, ctx.constraints);
611 },
612 [&](HS3::ShapeSys const &mod) {
613 const bool constrained = std::visit(
614 HS3::overloaded{[](HS3::Unconstrained) { return false; }, [](HS3::ConstantGammas) { return false; },
615 [&](HS3::ConstraintType) { return !mod.vals.empty(); },
616 [](HS3::GammaConstraintPdfs const &constraints) { return anyNamed(constraints); }},
617 mod.constraint);
618 // Follow the naming of HistFactory: "<channel>_<name>_ShapeSys" for constrained and
619 // "<channel>_<name>_shapeFactor" for free parameters.
620 const std::string funcName =
621 ctx.channelName + "_" + mod.name + (constrained ? "_ShapeSys" : "_shapeFactor");
622 shapeElems.add(createPHF(tool, funcName, mod.name, mod.parameters, mod.vals, mod.constraint,
623 ctx.constraints, ctx.observables, defaultShapeSysGammaMax, minShapeUncertainty,
624 sample.contents.size(),
625 "the shapesys modifier '" + mod.name + "' of sample '" + sampleName + "'"));
626 },
627 [&](HS3::CustomModifier const &mod) {
628 // The function can come later in the document.
629 RooAbsReal *obj = tool.request<RooAbsReal>(mod.name, ctx.channelName);
630 if (obj->dependsOn(ctx.observables)) {
631 shapeElems.add(*obj);
632 } else {
633 normElems.add(*obj);
634 }
635 },
636 },
637 modifier);
638 }
639
640 if (!overallNps.empty()) {
641 std::string interpName = newName(sampleName + "_" + ctx.channelName + "_epsilon");
642 normElems.add(tool.wsEmplace<RooStats::HistFactory::FlexibleInterpVar>(interpName, overallNps, 1., overallLow,
643 overallHigh, overallInterp));
644 }
645 if (!histNps.empty()) {
646 auto &v = tool.wsEmplace<PiecewiseInterpolation>(newName("histoSys_" + prefixedName), hf, histoLo, histoHi,
647 histNps, histoInterp);
649 shapeElems.add(v);
650 } else {
651 shapeElems.add(hf);
652 }
653
654 tool.wsEmplace<RooProduct>(newName(prefixedName + "_shapes"), shapeElems);
655 if (!normElems.empty()) {
656 tool.wsEmplace<RooProduct>(newName(prefixedName + "_scaleFactors"), normElems);
657 } else {
658 ws.factory("RooConstVar::" + newName(prefixedName + "_scaleFactors") + "(1.)");
659 }
660}
661
662// The constraint of the gamma parameters of the staterror modifiers. Without one, the gamma parameters are free.
663HS3::GammaConstraint statErrorConstraint(HS3::HistFactoryDist const &dist)
664{
665 // The constraint distributions named by a staterror modifier take precedence over a constraint type, and a type
666 // given on a staterror modifier over the channel-level setting.
667 HS3::GammaConstraint const *modifierConstraint = nullptr;
668 for (auto const &sample : dist.samples) {
669 for (auto const &modifier : sample.modifiers) {
670 auto const *statError = std::get_if<HS3::StatError>(&modifier);
671 if (!statError) {
672 continue;
673 }
674 if (std::holds_alternative<HS3::GammaConstraintPdfs>(statError->constraint)) {
675 return statError->constraint;
676 }
677 if (!modifierConstraint && !std::holds_alternative<HS3::Unconstrained>(statError->constraint)) {
678 modifierConstraint = &statError->constraint;
679 }
680 }
681 }
682 return modifierConstraint ? *modifierConstraint : dist.statError.constraint;
683}
684
685// This is only used for HistFactory distributions that the document doesn't interpret, e.g. because they don't come
686// with a document.
687class HistFactoryImporter : public RooFit::JSONIO::Importer {
688public:
689 bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &node) const override
690 {
691 std::string name = RooJSONFactoryWSTool::name(node);
692 if (!node.has_child("samples")) {
693 RooJSONFactoryWSTool::error("no samples in '" + name + "', skipping.");
694 }
695 // The upgrade rewrites the JSON, so it has to work on a copy.
696 std::stringstream ss;
697 node.writeJSON(ss);
698 std::unique_ptr<RooFit::Detail::JSONTree> tree = RooFit::Detail::JSONTree::create(ss.str());
699
700 HS3::Diagnostics diagnostics;
701 HS3::upgradeHistFactoryDist(tree->rootnode(), tool->hs3Version(), diagnostics);
702 HS3::HistFactoryDist dist = HS3::parseHistFactoryDist(tree->rootnode(), diagnostics);
703 if (!HS3::hasErrors(diagnostics)) {
704 HS3::validateHistFactoryDist(dist, name, diagnostics);
705 }
706 HS3::report(diagnostics);
707 HS3::buildHistFactoryDist(*tool, name, dist);
708 return true;
709 }
710};
711
712void exportFlexibleInterpVar(RooJSONFactoryWSTool *, RooStats::HistFactory::FlexibleInterpVar const &fip,
713 JSONNode &elem)
714{
715 const std::string context = "FlexibleInterpVar '" + std::string{fip.GetName()} + "'";
716 const std::size_t nParameters = fip.variables().size();
717 if (fip.low().size() != nParameters || fip.high().size() != nParameters ||
718 fip.interpolationCodes().size() != nParameters) {
719 RooJSONFactoryWSTool::error(context + " has non-matching parameter, variation, and interpolation lengths");
720 }
722 for (RooAbsArg const *var : fip.variables()) {
723 out.parameters.push_back(var->GetName());
724 }
725 out.nominal = fip.nominal();
726 out.high = fip.high();
727 out.low = fip.low();
728 out.interpolations = toInterpolations(fip.interpolationCodes(), InterpolationClass::Flexible, context);
730}
731
732void exportPiecewiseInterpolation(RooJSONFactoryWSTool *, PiecewiseInterpolation const &pip, JSONNode &elem)
733{
734 const std::string context = "PiecewiseInterpolation '" + std::string{pip.GetName()} + "'";
735 const std::size_t nParameters = pip.paramList().size();
736 if (pip.lowList().size() != nParameters || pip.highList().size() != nParameters ||
737 pip.interpolationCodes().size() != nParameters) {
738 RooJSONFactoryWSTool::error(context + " has non-matching parameter, variation, and interpolation lengths");
739 }
741 out.nominal = pip.nominalHist()->GetName();
742 for (std::size_t i = 0; i < nParameters; ++i) {
743 out.parameters.push_back(HS3::toNameOrNumber(pip.paramList()[i]));
744 out.high.push_back(HS3::toNameOrNumber(pip.highList()[i]));
745 out.low.push_back(HS3::toNameOrNumber(pip.lowList()[i]));
746 }
747 out.interpolations = toInterpolations(pip.interpolationCodes(), InterpolationClass::Piecewise, context);
750}
751
752void importPiecewiseInterpolation(RooJSONFactoryWSTool *tool, const JSONNode &p)
753{
754 std::string name(RooJSONFactoryWSTool::name(p));
755 HS3::Diagnostics diagnostics;
757 HS3::report(diagnostics, name);
758
759 auto request = [&](std::vector<HS3::NameOrNumber> const &refs) {
760 RooArgList out;
761 for (auto const &ref : refs) {
762 auto const *value = std::get_if<double>(&ref);
763 out.add(value ? RooFit::RooConst(*value) : *tool->request<RooAbsReal>(std::get<std::string>(ref), name));
764 }
765 return out;
766 };
767 RooArgList vars{request(in.parameters)};
768 RooArgList low{request(in.low)};
769 RooArgList high{request(in.high)};
770 auto &pip = tool->wsEmplace<PiecewiseInterpolation>(
771 name, *tool->request<RooAbsReal>(in.nominal, name), low, high, vars,
772 toCodes(in.interpolations, InterpolationClass::Piecewise, "PiecewiseInterpolation '" + name + "'"));
774}
775
776void importFlexibleInterpVar(RooJSONFactoryWSTool *tool, const JSONNode &p)
777{
778 std::string name(RooJSONFactoryWSTool::name(p));
779 HS3::Diagnostics diagnostics;
781 HS3::report(diagnostics, name);
782
783 RooArgList vars;
784 for (std::string const &var : in.parameters) {
785 vars.add(*tool->request<RooAbsReal>(var, name));
786 }
788 name, vars, in.nominal, in.low, in.high,
789 toCodes(in.interpolations, InterpolationClass::Flexible, "FlexibleInterpVar '" + name + "'"));
790}
791
792std::string stripOuterParens(const std::string &s)
793{
794 size_t start = 0;
795 size_t end = s.size();
796
797 // Whether the parenthesis at `start` is only closed by the one at `end - 1`.
798 auto enclosesAll = [&]() {
799 int depth = 0;
800 for (size_t i = start; i < end - 1; ++i) {
801 if (s[i] == '(') {
802 ++depth;
803 } else if (s[i] == ')') {
804 --depth;
805 }
806 if (depth == 0) {
807 return false;
808 }
809 }
810 return true;
811 };
812 while (start < end && s[start] == '(' && s[end - 1] == ')' && enclosesAll()) {
813 ++start;
814 --end;
815 }
816 return s.substr(start, end - start);
817}
818
819/// Whether the `+` or `-` at position `i` of `expr` is a binary operator, i.e. not a sign and not part of the exponent
820/// of a number like `1e-5`.
821bool isBinaryOperator(const std::string &expr, std::size_t i)
822{
823 std::size_t j = i;
824 while (j > 0 && std::isspace(static_cast<unsigned char>(expr[j - 1]))) {
825 --j;
826 }
827 if (j == 0) {
828 return false;
829 }
830 const char prev = expr[j - 1];
831 if (prev == 'e' || prev == 'E') {
832 // An exponent if the "e" directly follows the digits of a number, which don't start a name.
833 std::size_t k = j - 1;
834 while (k > 0 && (std::isdigit(static_cast<unsigned char>(expr[k - 1])) || expr[k - 1] == '.')) {
835 --k;
836 }
837 const bool startsName = k > 0 && (std::isalpha(static_cast<unsigned char>(expr[k - 1])) || expr[k - 1] == '_');
838 if (k < j - 1 && !startsName && i == j) {
839 return false;
840 }
841 }
842 return std::isalnum(static_cast<unsigned char>(prev)) || prev == '_' || prev == '.' || prev == ')' || prev == ']';
843}
844
845std::vector<std::string> splitTopLevelProduct(const std::string &expr)
846{
847 std::vector<std::string> parts;
848 int depth = 0;
849 size_t start = 0;
850
851 for (size_t i = 0; i < expr.size(); ++i) {
852 char c = expr[i];
853 if (c == '(') {
854 ++depth;
855 } else if (c == ')') {
856 --depth;
857 } else if ((c == '+' || c == '-') && depth == 0 && isBinaryOperator(expr, i)) {
858 return {}; // A sum or difference at the top level is not a product, e.g. "1 + 0.2 * k"
859 } else if (c == '*' && depth == 0) {
860 parts.push_back(stripOuterParens(expr.substr(start, i - start)));
861 start = i + 1;
862 }
863 }
864
865 if (parts.empty()) {
866 return {}; // Not a top-level product
867 }
868
869 parts.push_back(stripOuterParens(expr.substr(start)));
870 return parts;
871}
872
873// Expand the nested products of the constraint terms of a channel into their factors, which are the constraint terms
874// that the modifier parameters are looked up in, see findConstraint().
875void collectConstraintTerms(RooAbsPdf *pdf, std::vector<RooAbsPdf *> &terms)
876{
877 if (auto prod = dynamic_cast<RooProdPdf *>(pdf)) {
878 for (auto *factor : static_range_cast<RooAbsPdf *>(prod->pdfList())) {
879 collectConstraintTerms(factor, terms);
880 }
881 } else {
882 terms.push_back(pdf);
883 }
884}
885
886// A normsys that is written as the formula "1 +- a * b", where one of a and b is a constrained parameter.
887struct FormulaNormSys {
888 RooAbsReal *param;
889 RooAbsPdf *constraint;
890 double variation;
891};
892
893std::optional<FormulaNormSys> parseOverallModifierFormula(const std::string &s, RooFormulaVar *formula,
894 std::vector<RooAbsPdf *> const &channelConstraints)
895{
896 static const std::regex pattern(
897 R"(^\s*1(?:\.0)?\s*([\+\-])\s*([a-zA-Z_][a-zA-Z0-9_]*|[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)\s*\*\s*([a-zA-Z_][a-zA-Z0-9_]*|[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)\s*$)");
898
899 std::smatch match;
900 if (!std::regex_match(s, match, pattern)) {
901 return std::nullopt;
902 }
903 // The factors a and b are parameters of the formula or numbers. A recognized formula has exactly one constrained
904 // parameter, and the value of the other factor is the variation.
905 auto *a = static_cast<RooAbsReal *>(formula->getParameter(match[2].str().c_str()));
906 auto *b = static_cast<RooAbsReal *>(formula->getParameter(match[4].str().c_str()));
907 RooAbsPdf *constraintA = findConstraint(dynamic_cast<RooRealVar *>(a), channelConstraints);
908 RooAbsPdf *constraintB = findConstraint(dynamic_cast<RooRealVar *>(b), channelConstraints);
909 if (!constraintA == !constraintB) {
910 return std::nullopt;
911 }
912 RooAbsReal *other = constraintA ? b : a;
913 const double sign = match[1].str() == "-" ? -1.0 : 1.0;
914 const double variation = sign * (other ? other->getVal() : toDouble(match[constraintA ? 4 : 2].str()));
915 return FormulaNormSys{constraintA ? a : b, constraintA ? constraintA : constraintB, variation};
916}
917
918void collectElements(RooArgList &elems, RooAbsArg *arg)
919{
920 if (auto prod = dynamic_cast<RooProduct *>(arg)) {
921 for (const auto &e : prod->components()) {
922 collectElements(elems, e);
923 }
924 } else {
925 elems.add(*arg);
926 }
927}
928
929bool allRooRealVar(const RooAbsCollection &list)
930{
931 return std::all_of(list.begin(), list.end(), [](RooAbsArg *arg) { return dynamic_cast<RooRealVar *>(arg); });
932}
933
934std::vector<double> contents(RooDataHist const &dataHist)
935{
936 return {dataHist.weightArray(), dataHist.weightArray() + dataHist.numEntries()};
937}
938
939// A channel as it is exported, and what the exporter needs to know about its RooFit objects.
940struct ExportedChannel {
941 std::string name;
943 /// Whether a formula among the factors of a sample was written as several modifiers, see readChannel().
944 bool decomposedFormulas = false;
945 // The variables of the first histogram, named after the observables of the channel.
946 std::unique_ptr<RooArgSet> observables;
947 std::size_t nBins = 0;
948 /// The pdfs that the modifiers name as constraints, by name.
949 std::map<std::string, RooAbsPdf const *> constraints;
950 std::vector<RooAbsReal *> customModifiers;
951 /// Parts of formulas that are exported as custom modifiers. They are created for the export.
952 std::vector<std::unique_ptr<RooAbsReal>> temporaries;
953 // To reconstruct the statistical uncertainties, by bin.
954 std::map<std::size_t, double> totYield;
955 std::map<std::size_t, double> totYield2;
956 std::map<std::size_t, double> relErrors;
957 // Constant inverse bin widths of HistFactory before ROOT 6.26, which histfactory_dist implies.
958 std::set<RooAbsArg const *> legacyBinWidthFactors;
959};
960
961/// The volume of the first bin and the average bin volume of every histogram among the nodes of a channel. HistFactory
962/// before ROOT 6.26 took the inverse bin width as the number of bins over the range of each observable.
963std::vector<double> binVolumes(RooArgSet const &channelNodes)
964{
965 std::vector<double> out;
966 for (RooAbsArg *node : channelNodes) {
967 auto *hf = dynamic_cast<RooHistFunc const *>(node);
968 if (!hf || hf->dataHist().numEntries() == 0) {
969 continue;
970 }
971 out.push_back(hf->dataHist().binVolume(0));
972 double average = 1.;
973 for (RooAbsArg *obs : *hf->dataHist().get()) {
974 if (auto *real = dynamic_cast<RooRealVar const *>(obs)) {
975 average *= (real->getMax() - real->getMin()) / real->numBins();
976 }
977 }
978 out.push_back(average);
979 }
980 return out;
981}
982
983/// Whether a constant factor of a sample is the inverse bin width that HistFactory before ROOT 6.26 multiplied the
984/// samples with (a constant `RooRealVar` `binWidth_<observables>_<i>` in the coefficients of the `RooRealSumPdf`).
985/// `histfactory_dist` implies this factor, so it is not written as a modifier. It is identified by its structure, not
986/// by its name: a constant that is not floating in any snapshot, used only by the sum or the products of the channel
987/// (among the objects of the workspace), with the inverse of the volume of the first bin, or of the average bin volume,
988/// of one of the histograms of the channel as value.
989bool isLegacyBinWidthFactor(RooAbsArg const &factor, RooRealSumPdf const &sumpdf, RooArgSet const &channelNodes,
990 std::vector<double> const &volumes, RooWorkspace const &ws)
991{
992 if (!RooJSONFactoryWSTool::config().identifyLegacyBinWidthFactors) {
993 return false;
994 }
995 auto const *var = dynamic_cast<RooRealVar const *>(&factor);
996 if (!dynamic_cast<RooConstVar const *>(&factor) && !(var && var->isConstant())) {
997 return false;
998 }
999 if (var) {
1000 for (auto *snapshot : static_range_cast<RooArgSet const *>(ws.getSnapshots())) {
1001 auto const *inSnapshot = dynamic_cast<RooRealVar const *>(snapshot->find(*var));
1002 if (inSnapshot && !inSnapshot->isConstant()) {
1003 return false;
1004 }
1005 }
1006 }
1007 // A channel whose observables are renamed (RooJSONFactoryWSTool::Config::renameCombinedObservables) is a clone
1008 // made by RooCustomizer, which marks the cloned nodes with "ORIGNAME:<original>". The factor doesn't depend on the
1009 // observables, so it is not cloned: the original sum and products of the channel are still its clients.
1010 auto isOriginalOfChannelNode = [&](RooAbsArg const &client) {
1011 const std::string attribute = std::string{"ORIGNAME:"} + client.GetName();
1012 return std::any_of(channelNodes.begin(), channelNodes.end(),
1013 [&](RooAbsArg const *node) { return node->getAttribute(attribute.c_str()); });
1014 };
1015 for (RooAbsArg const *client : factor.clients()) {
1016 const bool isChannelProduct = dynamic_cast<RooProduct const *>(client) && channelNodes.find(*client) == client;
1017 if (client == &sumpdf || isChannelProduct || isOriginalOfChannelNode(*client)) {
1018 continue;
1019 }
1020 // Objects outside the workspace are no part of the model, e.g. the computation graph of a likelihood that was
1021 // created from the model before the export.
1022 if (ws.arg(client->GetName()) != client) {
1023 continue;
1024 }
1025 return false;
1026 }
1027 // The value was stored with 7 significant digits.
1028 const double value = static_cast<RooAbsReal const &>(factor).getVal();
1029 return std::any_of(volumes.begin(), volumes.end(),
1030 [&](double volume) { return volume > 0. && std::abs(value * volume - 1.) < 1e-6; });
1031}
1032
1033/// Whether a ParamHistFunc has the structure of the one of a HistFactory ShapeSys or ShapeFactor: it is defined over
1034/// the observables of the channel, with one parameter per bin of the channel. The import recreates such a function from
1035/// a shapefactor modifier. Its name doesn't matter.
1036bool isShapeModifierFunction(ParamHistFunc const &phf, ExportedChannel const &channel)
1037{
1038 return channel.observables && phf.paramList().size() == channel.nBins &&
1039 static_cast<std::size_t>(phf.numBins()) == channel.nBins && phf.dataVars().equals(*channel.observables);
1040}
1041
1042// Read the channel from the RooRealSumPdf. With `decomposeFormulas`, a RooFormulaVar among the factors of a sample
1043// that is a product is written as one modifier per factor; otherwise, like any other function, as one custom modifier.
1044ExportedChannel readChannel(RooJSONFactoryWSTool *tool, const std::string &pdfname, const RooRealSumPdf *sumpdf,
1045 std::vector<RooAbsPdf *> const &channelConstraints, bool decomposeFormulas = true)
1046{
1047 ExportedChannel channel;
1048
1049 RooWorkspace const &ws = *tool->workspace();
1050
1051 channel.name = pdfname;
1052 erasePrefix(channel.name, "model_");
1053 eraseSuffix(channel.name, "_model");
1054
1055 RooArgSet channelNodes;
1056 sumpdf->treeNodeServerList(&channelNodes);
1057 const std::vector<double> volumes = binVolumes(channelNodes);
1058
1059 // The modifiers name only the constraint terms of the channel. A pdf of a parameter that is not, like an external
1060 // constraint or a prior, stays where it is.
1061 auto constraintTerm = [&](RooAbsPdf const *pdf) -> std::optional<HS3::DistributionRef> {
1062 if (std::find(channelConstraints.begin(), channelConstraints.end(), pdf) == channelConstraints.end()) {
1063 return std::nullopt;
1064 }
1065 channel.constraints.emplace(pdf->GetName(), pdf);
1066 return HS3::DistributionRef{pdf->GetName()};
1067 };
1068 auto constraint = [&](RooAbsPdf const *pdf) -> HS3::Constraint {
1069 auto ref = constraintTerm(pdf);
1071 };
1072
1073 for (size_t sampleidx = 0; sampleidx < sumpdf->funcList().size(); ++sampleidx) {
1074 PiecewiseInterpolation *pip = nullptr;
1075 std::vector<ParamHistFunc *> phfs;
1076
1077 const auto func = sumpdf->funcList().at(sampleidx);
1078 HS3::Sample sample;
1079 sample.name = func->GetName();
1080 erasePrefix(sample.name, "L_x_");
1081 eraseSuffix(sample.name, "_shapes");
1082 eraseSuffix(sample.name, "_" + channel.name);
1083 erasePrefix(sample.name, pdfname + "_");
1084
1085 // The modifiers by type, which are written in this order.
1086 std::vector<HS3::NormFactor> normFactors;
1087 std::vector<HS3::NormSys> normSys;
1088 std::vector<HS3::HistoSys> histoSys;
1089 std::vector<HS3::ShapeSys> shapeSys;
1090 std::vector<HS3::CustomModifier> custom;
1091 std::vector<HS3::CustomModifier> temporaries;
1092 std::optional<HS3::StatError> statError;
1093
1094 auto addNormSys = [&](RooAbsReal &param, double hi, double lo, HS3::Interpolation interpolation,
1095 RooAbsPdf const *pdf) {
1096 std::string sysname(param.GetName());
1097 erasePrefix(sysname, "alpha_");
1098 normSys.push_back({sysname, {param.GetName()}, hi, lo, constraint(pdf), interpolation});
1099 };
1100
1101 auto updateObservables = [&](RooHistFunc const &histFunc) {
1102 RooDataHist const &dataHist = histFunc.dataHist();
1103 // The axes are named after the observables of the RooHistFunc, which are not necessarily the variables of
1104 // its histogram (e.g. after a RooCustomizer replaced them).
1105 auto varsPtr =
1106 histogramVariablesNamedAfterObservables(dataHist, histFunc.getHistObsList(), histFunc.variables());
1107 if (channel.observables == nullptr) {
1108 channel.observables = std::move(varsPtr);
1109 channel.nBins = dataHist.numEntries();
1110 } else {
1111 // The bin contents of all samples are written in the order of the axes of the channel (the last axis
1112 // varies fastest), which is the order of the observables of the first histogram.
1113 if (varsPtr->size() != channel.observables->size() || !varsPtr->hasSameLayout(*channel.observables)) {
1114 RooJSONFactoryWSTool::error("the histograms of channel '" + channel.name +
1115 "' don't have their observables in the same order, so their bin "
1116 "contents can't be written along the same axes");
1117 }
1118 }
1119 if (sample.contents.empty()) {
1120 sample.contents = contents(dataHist);
1121 }
1122 };
1123 auto processElements = [&](const auto &elements, auto &&self) -> void {
1124 for (RooAbsArg *e : elements) {
1125 if (auto *binWidth = dynamic_cast<RooBinWidthFunction *>(e); binWidth && binWidth->divideByBinWidth()) {
1126 // The division by the bin width is implied by histfactory_dist.
1127 } else if (isLegacyBinWidthFactor(*e, *sumpdf, channelNodes, volumes, ws)) {
1128 // Before ROOT 6.26, HistFactory multiplied the samples with a constant inverse bin width instead.
1129 channel.legacyBinWidthFactors.insert(e);
1130 if (!TString(e->GetName()).Contains("binWidth")) {
1131 oocoutW(nullptr, ObjectHandling)
1132 << "RooFitHS3: the constant factor '" << e->GetName() << "' of sample '" << sample.name
1133 << "' in channel '" << channel.name
1134 << "' is used like the inverse bin width of HistFactory before ROOT 6.26 (its value is the "
1135 "inverse bin volume), so it is not written: histfactory_dist implies it. Set "
1136 "RooJSONFactoryWSTool::config().identifyLegacyBinWidthFactors = false to write such factors "
1137 "as normfactors."
1138 << std::endl;
1139 }
1140 } else if (auto constVar = dynamic_cast<RooConstVar *>(e)) {
1141 if (constVar->getVal() != 1.) {
1142 normFactors.push_back({constVar->GetName(), {constVar->GetName()}, HS3::Unconstrained{}});
1143 }
1144 } else if (auto par = dynamic_cast<RooRealVar *>(e)) {
1145 // The constraint is found among the clients of the parameter, whichever of x and mean of a Gaussian it
1146 // is.
1147 normFactors.push_back(
1148 {par->GetName(), {par->GetName()}, constraint(findConstraint(par, channelConstraints))});
1149 } else if (auto hf = dynamic_cast<const RooHistFunc *>(e)) {
1150 updateObservables(*hf);
1151 } else if (ParamHistFunc *phf = dynamic_cast<ParamHistFunc *>(e); phf && allRooRealVar(phf->paramList())) {
1152 phfs.push_back(phf);
1153 } else if (auto fip = dynamic_cast<RooStats::HistFactory::FlexibleInterpVar *>(e)) {
1154 // some (modified) histfactory models have several instances of FlexibleInterpVar
1155 // we collect and merge them. A function input, like the ones of Measurement::AddGammaSyst() and
1156 // AddLogNormSyst(), is not a parameter: its variation is a custom modifier, and its constraint a
1157 // constraint term of the channel.
1158 auto isFunction = [](RooAbsArg *v) { return !dynamic_cast<RooRealVar *>(v) && !v->isConstant(); };
1159 RooArgList const &inputs = fip->variables();
1160 if (!inputs.empty() && std::all_of(inputs.begin(), inputs.end(), isFunction)) {
1161 custom.push_back({fip->GetName()});
1162 channel.customModifiers.push_back(fip);
1163 continue;
1164 }
1165 for (size_t i = 0; i < inputs.size(); ++i) {
1166 RooAbsReal *var = static_cast<RooAbsReal *>(inputs.at(i));
1167 if (isFunction(var)) {
1168 custom.push_back({std::string(fip->GetName()) + "_" + var->GetName()});
1169 channel.temporaries.push_back(std::make_unique<RooStats::HistFactory::FlexibleInterpVar>(
1170 custom.back().name.c_str(), "", RooArgList{*var}, 1., std::vector<double>{fip->low()[i]},
1171 std::vector<double>{fip->high()[i]}, std::vector<int>{fip->interpolationCodes()[i]}));
1172 continue;
1173 }
1174 std::string sysname(var->GetName());
1175 erasePrefix(sysname, "alpha_");
1176 const std::string context = "normsys modifier '" + sysname + "' in sample '" + sample.name +
1177 "' of channel '" + channel.name + "'";
1178 // A parameter without constraint is unconstrained.
1179 addNormSys(*var, fip->high()[i], fip->low()[i],
1180 interpolationFromCode(fip->interpolationCodes()[i], InterpolationClass::Flexible, context),
1181 findConstraint(var, channelConstraints));
1182 }
1183 } else if (!pip && (pip = dynamic_cast<PiecewiseInterpolation *>(e))) {
1184 // nothing to do here, already assigned
1185 } else if (RooFormulaVar *formula = dynamic_cast<RooFormulaVar *>(e)) {
1186 // people do a lot of fancy stuff with RooFormulaVar, like including NormSys via explicit formulae.
1187 // let's try to decompose it into building blocks
1188 TString expression(formula->expression());
1189 for (size_t i = formula->nParameters(); i--;) {
1190 const RooAbsArg *p = formula->getParameter(i);
1191 expression.ReplaceAll(("x[" + std::to_string(i) + "]").c_str(), p->GetName());
1192 expression.ReplaceAll(("@" + std::to_string(i)).c_str(), p->GetName());
1193 }
1194 std::vector<std::string> components;
1195 if (decomposeFormulas) {
1196 components = splitTopLevelProduct(expression.Data());
1197 }
1198 channel.decomposedFormulas |= !components.empty();
1199 if (components.empty()) {
1200 // it's not a product, let's just treat it as an unknown element
1201 custom.push_back({formula->GetName()});
1202 channel.customModifiers.push_back(formula);
1203 } else {
1204 // it is a product, we can try to handle the elements separately
1205 std::vector<RooAbsArg *> realComponents;
1206 int idx = 0;
1207 for (auto &comp : components) {
1208 if (auto *part = formula->getParameter(comp.c_str())) {
1209 // a trivial element of a product, which we can treat as its own modifier
1210 realComponents.push_back(part);
1211 } else if (auto sys = parseOverallModifierFormula(comp, formula, channelConstraints)) {
1212 // An attempt at explicitly encoding an overallSys. Preserve the legacy export behaviour for
1213 // recognized explicit formulae.
1214 addNormSys(*sys->param, 1.0 + sys->variation, 1.0 - sys->variation,
1215 multiplicativePiecewiseExponential, sys->constraint);
1216 } else {
1217 // this is something non-trivial, let's deal with it separately
1218 std::string name = std::string(formula->GetName()) + "_part" + std::to_string(idx++);
1219 temporaries.push_back({name});
1220 channel.temporaries.push_back(std::make_unique<RooFormulaVar>(
1221 name.c_str(), name.c_str(), comp.c_str(), formula->dependents()));
1222 }
1223 }
1224 self(realComponents, self);
1225 }
1226 } else if (auto real = dynamic_cast<RooAbsReal *>(e)) {
1227 custom.push_back({real->GetName()});
1228 channel.customModifiers.push_back(real);
1229 }
1230 }
1231 };
1232
1233 RooArgList elems;
1234 collectElements(elems, func);
1235 collectElements(elems, sumpdf->coefList().at(sampleidx));
1236 processElements(elems, processElements);
1237
1238 if (pip) {
1239 // see if we can get the observables
1240 if (auto nh = dynamic_cast<RooHistFunc const *>(pip->nominalHist())) {
1241 updateObservables(*nh);
1242 }
1243 for (size_t i = 0; i < pip->paramList().size(); ++i) {
1244 auto lo = dynamic_cast<RooHistFunc *>(pip->lowList().at(i));
1245 auto hi = dynamic_cast<RooHistFunc *>(pip->highList().at(i));
1246 if (!lo || !hi) {
1247 continue;
1248 }
1249 RooAbsReal *var = static_cast<RooAbsReal *>(pip->paramList().at(i));
1250 std::string sysname(var->GetName());
1251 erasePrefix(sysname, "alpha_");
1252 // A parameter without constraint is unconstrained.
1253 const auto *pdf = findConstraint(var, channelConstraints);
1254 if (!pdf && !var->isConstant() && !dynamic_cast<RooRealVar *>(var)) {
1255 RooJSONFactoryWSTool::error("cannot find constraint for " + std::string(var->GetName()) +
1256 ": functions are not supported as parameters of histosys modifiers");
1257 }
1258 const std::string context =
1259 "histosys modifier '" + sysname + "' in sample '" + sample.name + "' of channel '" + channel.name + "'";
1260 histoSys.push_back(
1261 {sysname,
1262 {var->GetName()},
1263 {contents(hi->dataHist()), std::nullopt},
1264 {contents(lo->dataHist()), std::nullopt},
1265 constraint(pdf),
1266 interpolationFromCode(pip->interpolationCodes()[i], InterpolationClass::Piecewise, context)});
1267 }
1268 }
1269
1270 for (ParamHistFunc *phf : phfs) {
1271 if (startsWith(phf->GetName(), "mc_stat_")) { // MC stat uncertainty
1272 statError.emplace();
1273 statError->name = "staterror";
1275 // In the order of the bins (last axis fastest), like the contents of the samples.
1277 const std::size_t bin = statError->parameters.size();
1278 statError->parameters.push_back({g->GetName()});
1279 RooAbsPdf *pdf = findConstraint(g, channelConstraints);
1280 pdfs.pdfs.push_back(constraintTerm(pdf));
1281 channel.totYield[bin] += sample.contents[bin];
1282 channel.totYield2[bin] += sample.contents[bin] * sample.contents[bin];
1283 if (pdf) {
1284 channel.relErrors[bin] = constraintRelError(*pdf, *g);
1285 }
1286 }
1287 if (anyNamed(pdfs)) {
1288 statError->constraint = std::move(pdfs);
1289 }
1290 } else { // ShapeSys or ShapeFactor
1291 // Other ParamHistFuncs can't be written as shapefactors: the import would recreate the function over the
1292 // observables and bins of the channel. Over other variables, they are written as custom modifiers, which
1293 // refer to the function by name. Over the observables of the channel with another binning, they can't be
1294 // written at all, since the observables can only have one binning on import.
1295 if (!isShapeModifierFunction(*phf, channel)) {
1296 if (channel.observables && phf->dataVars().overlaps(*channel.observables)) {
1297 RooJSONFactoryWSTool::error("cannot write the ParamHistFunc '" + std::string(phf->GetName()) +
1298 "': it has another binning of the observables of channel '" +
1299 channel.name + "'");
1300 }
1301 custom.push_back({phf->GetName()});
1302 channel.customModifiers.push_back(phf);
1303 continue;
1304 }
1305 HS3::ShapeSys &sys = shapeSys.emplace_back();
1306 sys.name = phf->GetName();
1307 erasePrefix(sys.name, channel.name + "_");
1308 for (std::string_view suffix : {"_ShapeSys", "_shapeSys", "_ShapeFactor", "_shapeFactor"}) {
1309 if (eraseSuffix(sys.name, suffix))
1310 break;
1311 }
1312
1313 // Both are written as "shapefactor": the constrained parameters name their constraint distribution in
1314 // "constraints", the others are free.
1317 sys.parameters.push_back({g->GetName()});
1318 RooAbsPdf *pdf = findConstraint(g, channelConstraints);
1319 if (!pdf)
1320 pdf = ws.pdf(constraintName(g->GetName()));
1321 pdfs.pdfs.push_back(constraintTerm(pdf));
1322 }
1323 if (anyNamed(pdfs)) {
1324 sys.constraint = std::move(pdfs);
1325 }
1326 }
1327 }
1328
1329 sortByName(normFactors);
1330 sortByName(normSys);
1331 sortByName(histoSys);
1332 sortByName(shapeSys);
1333 auto append = [&](auto &modifiers) {
1334 sample.modifiers.insert(sample.modifiers.end(), std::make_move_iterator(modifiers.begin()),
1335 std::make_move_iterator(modifiers.end()));
1336 };
1337 append(normFactors);
1338 append(normSys);
1339 append(histoSys);
1340 append(shapeSys);
1341 append(custom);
1342 append(temporaries);
1343 if (statError) {
1344 sample.modifiers.push_back(std::move(*statError));
1345 }
1346
1347 channel.dist.samples.push_back(std::move(sample));
1348 }
1349
1350 sortByName(channel.dist.samples);
1351 return channel;
1352}
1353
1354// Whether the distribution of the channel passes the checks of a HistFactory distribution, with its duplicate
1355// modifiers combined like for the export.
1356bool isValidChannel(ExportedChannel const &channel, std::string const &pdfname)
1357{
1358 if (!channel.observables) {
1359 return true; // nothing was read that could be checked
1360 }
1361 HS3::HistFactoryDist dist = channel.dist;
1362 HS3::Diagnostics diagnostics;
1363 HS3::mergeDuplicateModifiers(dist, channel.name, diagnostics);
1364 for (auto *obs : static_range_cast<RooRealVar *>(*channel.observables)) {
1365 dist.axes.push_back(HS3::toBinnedAxis(*obs));
1366 }
1367 HS3::validateHistFactoryDist(dist, pdfname, diagnostics);
1368 return !HS3::hasErrors(diagnostics);
1369}
1370
1371// The statistical uncertainties of the samples are reconstructed from the constraints of the gamma parameters, with
1372// the (arbitrary) convention that all samples have the same relative uncertainty.
1373void configureStatError(ExportedChannel &channel)
1374{
1375 for (HS3::Sample &sample : channel.dist.samples) {
1376 if (std::none_of(sample.modifiers.begin(), sample.modifiers.end(),
1377 [](auto const &m) { return std::holds_alternative<HS3::StatError>(m); })) {
1378 continue;
1379 }
1380 std::vector<double> errors(sample.contents.size());
1381 for (auto const &bin : channel.relErrors) {
1382 const std::size_t i = bin.first;
1383 // this reconstruction is inherently imprecise, so we truncate it at some decimal places to make sure that
1384 // we don't carry around too many useless digits
1385 errors[i] =
1386 round_prec(bin.second * channel.totYield[i] / std::sqrt(channel.totYield2[i]) * sample.contents[i], 7);
1387 }
1388 sample.errors = std::move(errors);
1389 }
1390}
1391
1392// The RooRealSumPdf of a product of exactly one RooRealSumPdf and other pdfs, or null for anything else. Such a product
1393// has the form that the HistFactory exporter writes as a histfactory_dist with its constraint terms.
1394RooRealSumPdf const *channelSum(RooAbsArg const &pdf)
1395{
1396 auto const *prod = dynamic_cast<RooProdPdf const *>(&pdf);
1397 if (!prod) {
1398 return nullptr;
1399 }
1400 RooRealSumPdf const *sum = nullptr;
1401 for (RooAbsArg const *factor : prod->pdfList()) {
1402 if (auto const *factorSum = dynamic_cast<RooRealSumPdf const *>(factor)) {
1403 if (sum) {
1404 return nullptr;
1405 }
1406 sum = factorSum;
1407 }
1408 }
1409 return sum;
1410}
1411
1412// Whether the constraint `constraint` can be written as an array component: every object of the workspace that uses
1413// it is a HistFactory channel, which refers to it through its modifiers, or an array distribution. Any other user,
1414// e.g. an ordinary product or a ModelConfig that has it as an external constraint, refers to the constraint by its
1415// own name, which an array component doesn't have. The decision only depends on the workspace, not on the order in
1416// which the export visits the objects.
1417bool usedOnlyByHistFactoryChannels(RooJSONFactoryWSTool &tool, RooAbsPdf const &constraint)
1418{
1419 // A component of an array distribution stays in it (see exportConstraint()); a ModelConfig refers to it through
1420 // the array.
1421 const bool inArray = std::any_of(constraint.clients().begin(), constraint.clients().end(),
1422 [](RooAbsArg const *client) { return client->getAttribute(arrayDistTag); });
1423 if (!inArray) {
1424 for (TObject const *obj : tool.workspace()->allGenericObjects()) {
1425 auto const *mc = dynamic_cast<RooFit::ModelConfig const *>(obj);
1426 if (mc && mc->GetExternalConstraints() && mc->GetExternalConstraints()->find(constraint.GetName())) {
1427 return false;
1428 }
1429 }
1430 }
1431 for (RooAbsArg const *client : constraint.clients()) {
1432 if (tool.workspace()->arg(client->GetName()) != client || isSkippedHelper(*client, *tool.workspace())) {
1433 continue; // not part of what is exported
1434 }
1435 if (!client->getAttribute(arrayDistTag) && !channelSum(*client)) {
1436 return false;
1437 }
1438 }
1439 return true;
1440}
1441
1442// Register the constraint `constraint` of a modifier parameter for the export and return the name under which it is
1443// written. Constraints are collected into one array distribution per type and top-level pdf (or, if the constraint
1444// already belongs to an array distribution, that one), unless the arrays are switched off, the constraint cannot be
1445// a component, or it is used by objects other than HistFactory channels. In those cases it is written on its own.
1446std::string exportConstraint(RooJSONFactoryWSTool &tool, RooAbsPdf const &constraint)
1447{
1448 if (RooJSONFactoryWSTool::config().exportArrayDist && usedOnlyByHistFactoryChannels(tool, constraint)) {
1449 if (auto info = arrayComponentInfo(constraint)) {
1450 std::string arrayName;
1451 // An array that is written: one that only skipped helpers use is not (see isSkippedHelper()).
1452 for (RooAbsArg const *client : constraint.clients()) {
1453 if (client->getAttribute(arrayDistTag) && !isSkippedHelper(*client, *tool.workspace())) {
1454 arrayName = client->GetName();
1455 break;
1456 }
1457 }
1458 if (arrayName.empty()) {
1459 // "poisson_continuous_dist" -> "<root>_poisson_continuous_constraints"
1460 arrayName = tool.exportRootName() + "_" + removeSuffix(info->type, "_dist") + "_constraints";
1461 }
1462 return tool.exportAsArrayComponent(constraint, arrayName);
1463 }
1464 }
1465 tool.queueExport(constraint);
1466 return constraint.GetName();
1467}
1468
1469// Export the constraints that the modifiers name, in the order in which the modifiers are written, and replace their
1470// names by the names under which they are written: an array distribution that holds them, or their own name. Returns
1471// these terms, for the likelihoods of the models that contain this channel.
1472std::vector<std::string> exportNamedConstraints(RooJSONFactoryWSTool &tool, ExportedChannel &channel)
1473{
1474 std::map<std::string, std::string> writtenAs;
1475 std::vector<std::string> terms;
1476 RooWorkspace &ws = *tool.workspace();
1477 auto rename = [&](std::string &name, std::string const &paramName) {
1478 auto found = writtenAs.find(name);
1479 if (found == writtenAs.end()) {
1480 RooAbsPdf const &constraint = *channel.constraints.at(name);
1481 // HistFactory builds the Gaussian constraints with the parameter as x and the global observable as mean.
1482 // The observable is the side that does not depend on the parameter; recording it makes the Gaussian be
1483 // written with the observable as x.
1484 RooAbsArg const *param = ws.arg(paramName);
1485 if (auto const *gauss = dynamic_cast<RooGaussian const *>(&constraint); gauss && param) {
1486 RooAbsReal const &observable = gauss->getX().dependsOn(*param) ? gauss->getMean() : gauss->getX();
1487 if (!isLiteralConstVar(observable)) {
1488 tool.setConstraintObservable(constraint, observable.GetName());
1489 }
1490 }
1491 found = writtenAs.emplace(name, exportConstraint(tool, constraint)).first;
1492 if (std::find(terms.begin(), terms.end(), found->second) == terms.end()) {
1493 terms.push_back(found->second);
1494 }
1495 }
1496 name = found->second;
1497 };
1498 auto renameConstraint = [&](HS3::Constraint &constraint, HS3::ParameterRef const &param) {
1499 if (auto *pdf = std::get_if<HS3::ConstraintPdf>(&constraint)) {
1500 rename(pdf->pdf.name, param.name);
1501 }
1502 };
1503 auto renameGammas = [&](HS3::GammaConstraint &constraint, std::vector<HS3::ParameterRef> const &params) {
1504 if (auto *pdfs = std::get_if<HS3::GammaConstraintPdfs>(&constraint)) {
1505 for (std::size_t i = 0; i < pdfs->pdfs.size(); ++i) {
1506 if (auto &pdf = pdfs->pdfs[i]) {
1507 rename(pdf->name, params[i].name);
1508 }
1509 }
1510 }
1511 };
1512 for (HS3::Sample &sample : channel.dist.samples) {
1513 for (HS3::Modifier &modifier : sample.modifiers) {
1514 std::visit(HS3::overloaded{[&](HS3::NormFactor &m) { renameConstraint(m.constraint, m.parameter); },
1515 [&](HS3::NormSys &m) { renameConstraint(m.constraint, m.parameter); },
1516 [&](HS3::HistoSys &m) { renameConstraint(m.constraint, m.parameter); },
1517 [&](HS3::ShapeSys &m) { renameGammas(m.constraint, m.parameters); },
1518 [&](HS3::StatError &m) { renameGammas(m.constraint, m.parameters); },
1519 [](HS3::CustomModifier &) {}},
1520 modifier);
1521 }
1522 }
1523 return terms;
1524}
1525
1526bool tryExportHistFactory(RooJSONFactoryWSTool *tool, const std::string &pdfname, const RooRealSumPdf *sumpdf,
1527 std::vector<RooAbsPdf *> constraints)
1528{
1529 // some preliminary checks
1530 if (!sumpdf) {
1531 return false;
1532 }
1533
1534 for (RooAbsArg *sample : sumpdf->funcList()) {
1535 if (!dynamic_cast<RooProduct *>(sample) && !dynamic_cast<RooRealSumPdf *>(sample)) {
1536 return false;
1537 }
1538 }
1539
1540 ExportedChannel channel = readChannel(tool, pdfname, sumpdf, constraints);
1541 // Writing a formula as several modifiers must not be what makes the channel invalid, e.g. because a parameter that
1542 // occurs twice in the formula becomes two normfactors of the same name. If it is, the formulas are written as
1543 // custom modifiers instead.
1544 if (channel.decomposedFormulas && !isValidChannel(channel, pdfname)) {
1545 ExportedChannel plain = readChannel(tool, pdfname, sumpdf, constraints, /*decomposeFormulas=*/false);
1546 if (isValidChannel(plain, pdfname)) {
1547 channel = std::move(plain);
1548 }
1549 }
1550 HS3::HistFactoryDist &dist = channel.dist;
1551
1552 // sanity checks
1553 if (dist.samples.empty())
1554 return false;
1555 for (auto &sample : dist.samples) {
1556 if (sample.contents.empty()) {
1557 return false;
1558 }
1559 }
1560
1561 HS3::Diagnostics diagnostics;
1562 HS3::mergeDuplicateModifiers(dist, channel.name, diagnostics);
1563 HS3::report(diagnostics);
1564 configureStatError(channel);
1566
1567 for (auto *obs : static_range_cast<RooRealVar *>(*channel.observables)) {
1568 dist.axes.push_back(HS3::toBinnedAxis(*obs));
1569 }
1570
1571 tool->recordConstraintTerms(pdfname, exportNamedConstraints(*tool, channel));
1572
1573 for (RooAbsReal *modifier : channel.customModifiers) {
1574 tool->queueExport(*modifier);
1575 }
1576 for (auto &modifier : channel.temporaries) {
1577 tool->queueExportTemporary(modifier.release());
1578 }
1579
1580 // Export all model parameters
1581 RooArgSet parameters;
1582 sumpdf->getParameters(channel.observables.get(), parameters);
1583 for (RooAbsArg *param : parameters) {
1584 // This should exclude the global observables. The legacy inverse bin widths are not written at all.
1585 if (!startsWith(param->GetName(), "nom_") && !channel.legacyBinWidthFactors.count(param)) {
1586 tool->queueExport(*param);
1587 }
1588 }
1589
1590 // All other constraint terms of the channel are written separately.
1591 std::vector<HS3::DistributionRef> channelConstraintNames;
1592 for (RooAbsPdf const *pdf : constraints) {
1593 if (!channel.constraints.count(pdf->GetName())) {
1594 tool->queueExport(*pdf);
1595 channelConstraintNames.push_back({pdf->GetName()});
1596 }
1597 }
1598
1599 HS3::setExportedObject(*tool, std::move(dist), std::move(channelConstraintNames));
1600 return true;
1601}
1602
1603// Writes a RooRealSumPdf, or the product of one with its constraint terms, as a histfactory_dist.
1604class HistFactoryStreamer : public RooFit::JSONIO::Exporter {
1605public:
1606 bool autoExportDependants() const override { return false; }
1607 std::string const &key() const override
1608 {
1609 static const std::string keystring = "histfactory_dist";
1610 return keystring;
1611 }
1612 bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *p, JSONNode &) const override
1613 {
1614 auto const *sumpdf = dynamic_cast<RooRealSumPdf const *>(p);
1615 std::vector<RooAbsPdf *> constraints;
1616 if (auto const *prodpdf = dynamic_cast<RooProdPdf const *>(p)) {
1617 sumpdf = channelSum(*prodpdf);
1618 for (auto *pdf : static_range_cast<RooAbsPdf *>(prodpdf->pdfList())) {
1619 if (pdf != sumpdf) {
1620 // The constraint terms can also be grouped in nested products.
1621 collectConstraintTerms(pdf, constraints);
1622 }
1623 }
1624 }
1625 return tryExportHistFactory(tool, p->GetName(), sumpdf, constraints);
1626 }
1627};
1628
1629// Registers the importers and exporters when the library is loaded.
1630const bool registered = []() {
1631 registerType("interpolation", importPiecewiseInterpolation, exportPiecewiseInterpolation);
1632 registerType("interpolation0d", importFlexibleInterpVar, exportFlexibleInterpVar);
1633 RooFit::JSONIO::registerImporter<HistFactoryImporter>("histfactory_dist", true);
1634 RooFit::JSONIO::registerExporter<HistFactoryStreamer>(RooProdPdf::Class(), true);
1635 RooFit::JSONIO::registerExporter<HistFactoryStreamer>(RooRealSumPdf::Class(), true);
1636 return true;
1637}();
1638
1639} // namespace
1640
1642{
1643 RooArgSet observables = createObservables(dist.axes);
1644
1645 // The yields and their variances by bin, summed over the samples with a staterror modifier.
1646 std::vector<double> sumW;
1647 std::vector<double> sumW2;
1648 std::vector<ParameterRef> gammaParnames;
1649 for (auto const &sample : dist.samples) {
1650 auto found = std::find_if(sample.modifiers.begin(), sample.modifiers.end(),
1651 [](auto const &m) { return std::holds_alternative<StatError>(m); });
1652 if (found == sample.modifiers.end()) {
1653 continue;
1654 }
1655 sumW.resize(sample.contents.size());
1656 sumW2.resize(sample.contents.size());
1657 for (std::size_t i = 0; i < sample.contents.size(); ++i) {
1658 sumW[i] += sample.contents[i];
1659 // A sample without "errors" contributes no statistical uncertainty, unless Poisson uncertainties are implied.
1660 if (sample.errors) {
1661 sumW2[i] += (*sample.errors)[i] * (*sample.errors)[i];
1662 } else if (dist.statError.impliedPoissonErrors) {
1663 sumW2[i] += sample.contents[i];
1664 }
1665 }
1666 if (gammaParnames.empty()) {
1667 gammaParnames = std::get<StatError>(*found).parameters;
1668 }
1669 }
1670
1671 std::string channelName = name;
1672 erasePrefix(channelName, "model_");
1673
1674 RooAbsArg *mcStatObject = nullptr;
1675 RooArgSet constraints;
1676 if (!sumW.empty()) {
1677 // The relative uncertainties. The gammas of bins without a positive yield are set constant later.
1678 std::vector<double> errs(sumW.size());
1679 for (std::size_t i = 0; i < sumW.size(); ++i) {
1680 errs[i] = sumW[i] > 0. ? std::sqrt(sumW2[i]) / sumW[i] : 0.;
1681 }
1682
1683 // In HS3 0.3 (HS3 PR #154, decision on HS3 #156), the named constraints of a staterror are authoritative: the
1684 // range, the constness and the step width of the gammas come from the document, and nothing is derived from
1685 // the errors of the samples. Older documents relied on RooFit configuring the gammas from them.
1686 const bool configureGammas = tool.hs3Version() < HS3::Version{0, 3};
1687 mcStatObject = &createPHF(tool, "mc_stat_" + channelName, "stat_" + channelName, gammaParnames, errs,
1688 statErrorConstraint(dist), constraints, observables, defaultStatErrorGammaMax,
1689 dist.statError.relThreshold, errs.size(),
1690 "the staterror modifier of channel '" + name + "'", configureGammas);
1691 }
1692
1693 ChannelContext ctx{tool, dist, observables, name, channelName, mcStatObject, constraints};
1694
1696 RooArgList coefs;
1697 for (HS3::Sample const &sample : dist.samples) {
1698 buildSample(ctx, sample);
1699 funcs.add(*tool.request<RooAbsReal>(name + "_" + sample.name + "_shapes", name));
1700 coefs.add(*tool.request<RooAbsReal>(name + "_" + sample.name + "_scaleFactors", name));
1701 }
1702
1703 if (auto const *channelConstraints = tool.channelConstraints(name)) {
1704 for (auto const &ref : *channelConstraints) {
1705 constraints.add(*tool.request<RooAbsPdf>(ref.name, name));
1706 }
1707 }
1708
1709 // A constraint that is a measurement of its own, as a component of a combined distribution with data, contributes
1710 // there, and is not multiplied into the channel.
1711 {
1712 RooArgSet ownMeasurements;
1713 for (auto *constraint : static_range_cast<RooAbsPdf *>(constraints)) {
1714 if (tool.isConstraintReadAsChannel(*constraint)) {
1715 ownMeasurements.add(*constraint);
1716 }
1717 }
1718 constraints.remove(ownMeasurements);
1719 }
1720
1721 // With constraints, the channel is the product of the sum of the samples and the constraints.
1722 auto &sum = tool.wsEmplace<RooRealSumPdf>(constraints.empty() ? name : channelName + "_model", funcs, coefs, true);
1723 sum.SetTitle(name.c_str());
1724 // A histfactory_dist is a product of Poisson distributions of the bin counts. RooFit's binned likelihood
1725 // computes exactly that (it differs from the event-wise likelihood only by a constant), and binned generation
1726 // generates bin counts, so both are enabled, as HistFactory does by default.
1727 sum.setAttribute("BinnedLikelihood");
1728 sum.setAttribute("GenerateBinned");
1729 if (!constraints.empty()) {
1730 tool.wsEmplace<RooProdPdf>(name, constraints, RooFit::Conditional(sum, observables));
1731 }
1732}
1733
1735{
1736 return dynamic_cast<HistFactoryImporter const *>(&importer) != nullptr;
1737}
std::string channelName
std::optional< ArrayComponentInfo > arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable, RooJSONFactoryWSTool *tool)
void checkParamHistFuncOrderIsDefined(RooFit::HS3::Version const &version, RooAbsCollection const &vars, std::string const &context)
std::vector< RooAbsReal * > paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
RooArgList toParamHistFuncOrder(RooArgList const &paramsInBinOrder, RooAbsCollection const &vars)
bool startsWith(std::string_view str, std::string_view prefix)
bool endsWith(std::string_view str, std::string_view suffix)
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)
bool isSkippedHelper(RooAbsArg const &arg, RooWorkspace const &ws)
constexpr const char * arrayDistTag
Definition JSONIOUtils.h:34
void registerType(const std::string &key, ImportFunc importFunc, ExportFunc< RooArg_t > exportFunc, bool autoExportDependants=true)
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define g(i)
Definition RSha256.hxx:105
#define a(i)
Definition RSha256.hxx:99
#define e(i)
Definition RSha256.hxx:103
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
double toDouble(const char *s)
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define oocoutW(o, a)
winID h TVirtualViewer3D TVirtualGLPainter p
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
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void funcs
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 type
char name[80]
Definition TGX11.cxx:142
#define hi
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
const RooArgList & paramList() const
Int_t numBins() const
const RooArgList & dataVars() const
The PiecewiseInterpolation is a class that can morph distributions into each other,...
const RooArgList & highList() const
const RooAbsReal * nominalHist() const
Return pointer to the nominal hist function.
const RooArgList & lowList() const
void setPositiveDefinite(bool flag=true)
const RooArgList & paramList() const
const std::vector< int > & interpolationCodes() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
void treeNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool doBranch=true, bool doLeaf=true, bool valueOnly=false, bool recurseFundamental=false) const
Fill supplied list with nodes of the arg tree, following all server links, starting with ourself as t...
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:284
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
const RefCountList_t & clients() const
List of all clients of this object.
Definition RooAbsArg.h:138
Abstract container object that can hold multiple RooAbsArg objects.
bool equals(const RooAbsCollection &otherColl) const
Check if this and other collection have identically-named contents.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
bool overlaps(Iterator_t otherCollBegin, Iterator_t otherCollEnd) const
const_iterator end() const
Storage_t::size_type size() const
const_iterator begin() const
RooAbsArg * find(const char *name) const
Find object with given name in list.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
void setConstant(bool value=true)
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
Returns the bin width (or volume) given a RooHistFunc.
Represents a constant real-valued object.
Definition RooConstVar.h:23
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
double const * weightArray() const
void writeJSON(std::ostream &os) const
bool has_child(std::string const &) const
static std::unique_ptr< JSONTree > create()
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
RooAbsArg * getParameter(const char *name) const
Return pointer to parameter with given name.
const char * expression() const
const RooArgList & dependents() const
size_t nParameters() const
Return the number of parameters.
Plain Gaussian p.d.f.
Definition RooGaussian.h:24
A real-valued function sampled from a multidimensional histogram.
Definition RooHistFunc.h:29
When using RooFit, statistical models can be conveniently handled and stored as a RooWorkspace.
bool isConstraintReadAsChannel(RooAbsPdf const &pdf) const
Whether the constraint term pdf contributes to the likelihoods of the document that is currently bein...
void recordConstraintTerms(std::string const &pdfName, std::vector< std::string > const &terms)
T * request(const std::string &objname, const std::string &requestAuthor)
The object objname from the workspace, imported from the document first if needed.
std::string const & exportRootName() const
The name of the top-level object whose export is in progress (the root of the current export recursio...
T * tryRequest(const std::string &objname)
Like request(), but returns nullptr if neither the workspace nor the document has the object.
Obj_t & wsImport(Obj_t const &obj)
void queueExportTemporary(RooAbsArg *arg)
void queueExport(RooAbsArg const &arg)
std::vector< RooFit::HS3::DistributionRef > const * channelConstraints(std::string const &dist) const
The constraint terms that the document that is currently being imported adds to the HistFactory distr...
RooFit::HS3::Version hs3Version() const
The HS3 version of the document that is currently being imported.
static void error(const char *s)
Write an error to the RooFit message service, and throw it as a std::runtime_error.
void setConstraintObservable(RooAbsPdf const &pdf, std::string const &observable)
Record that observable is the observable of the constraint term pdf (the side that is not the constra...
Obj_t & wsEmplace(RooStringView name, Args_t &&...args)
static std::string name(const RooFit::Detail::JSONNode &n)
std::string exportAsArrayComponent(RooAbsPdf const &pdf, std::string const &arrayName)
Poisson pdf.
Definition RooPoisson.h:18
RooAbsReal const & getMean() const
Get the mean parameter.
Definition RooPoisson.h:47
Efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:35
static TClass * Class()
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
Implements a PDF constructed from a sum of functions:
const RooArgList & funcList() const
static TClass * Class()
const RooArgList & coefList() const
Variable that can be changed from the outside.
Definition RooRealVar.h:37
bool hasError(bool allowZero=true) const
Definition RooRealVar.h:60
const std::vector< int > & interpolationCodes() const
const RooListProxy & variables() const
const std::vector< double > & high() const
const std::vector< double > & low() const
< A class that holds configuration information for a model using a workspace as a store
Definition ModelConfig.h:34
Persistable container for RooFit projects.
TObject * obj(RooStringView name) const
Return any type of object (RooAbsArg, RooAbsData or generic object) with given name)
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
RooAbsArg * arg(RooStringView name) const
Return RooAbsArg with given name. A null pointer is returned if none is found.
RooFactoryWSTool & factory()
Return instance to factory tool.
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:173
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
Basic string class.
Definition TString.h:137
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:642
RooCmdArg Conditional(const RooArgSet &pdfSet, const RooArgSet &depSet, bool depsAreCond=false)
RooConstVar & RooConst(double val)
double gamma(double x)
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)
double dist(Rotation3D const &r1, Rotation3D const &r2)
Types that represent an HS3 document.
HistFactoryDist parseHistFactoryDist(Detail::JSONNode const &distribution, Diagnostics &diagnostics)
Reads a HistFactory distribution that doesn't come with a 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 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
InterpolationClass
The RooFit classes that implement the interpolations, which encode them with integer codes.
void mergeDuplicateModifiers(HistFactoryDist &dist, std::string const &channel, Diagnostics &diagnostics)
Combines the modifiers of a sample that have the same type and name, which HistFactory models can hav...
ConstraintType
The constraint types that older documents named, for which RooFit creates the constraint terms.
std::optional< Interpolation > interpolationFromCode(int code, InterpolationClass interpolationClass)
The interpolation for an integer code, or nothing if the class doesn't support the code.
Definition HS3Parser.cxx:62
void factorOutDefaultInterpolation(HistFactoryDist &dist)
Makes the most common interpolation of the modifiers the "default_interpolation", which they then don...
void setExportedObject(RooJSONFactoryWSTool &tool, HistFactoryDist dist, std::vector< DistributionRef > channelConstraints)
Called by the exporter of a HistFactory distribution, which is then written by the tool.
char const * toString(InterpolationType type)
InterpolatedNumber parseInterpolatedNumber(Detail::JSONNode const &node, Diagnostics &diagnostics)
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...
void report(Diagnostics const &diagnostics, std::string const &object="")
Forward the warnings to the message service, and throw if there are errors.
InterpolatedFunction parseInterpolatedFunction(Detail::JSONNode const &node, Diagnostics &diagnostics)
Reads the functions "interpolation" and "interpolation0d", which don't come with a document.
RooArgSet createObservables(std::vector< BinnedAxis > const &axes)
Create the variables for the axes of binned data.
std::optional< int > codeFromInterpolation(Interpolation const &interpolation, InterpolationClass interpolationClass)
The integer code of an interpolation, or nothing if the class can't represent the interpolation.
Definition HS3Parser.cxx:81
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
Definition HS3Parser.cxx:92
void writeInterpolatedNumber(Detail::JSONNode &node, InterpolatedNumber const &function)
constexpr Interpolation multiplicativePiecewiseExponential
std::vector< Diagnostic > Diagnostics
void writeInterpolation(Detail::JSONNode &node, Interpolation const &interpolation)
NameOrNumber toNameOrNumber(RooAbsArg const &arg)
The name of an object, or the value of a literal constant.
std::variant< Unconstrained, ConstraintType, ConstantGammas, GammaConstraintPdfs > GammaConstraint
BinnedAxis toBinnedAxis(RooRealVar const &var)
The axis of binned data for a variable, or for a binning of a variable with the given name.
std::unique_ptr< RooDataHist > createDataHist(std::string const &name, RooArgSet const &vars, std::vector< double > const &contents, std::vector< double > const *errors)
Create a RooDataHist with the contents and errors. If there are no errors, it doesn't store squared w...
std::variant< Unconstrained, ConstraintType, ConstraintPdf > Constraint
bool isBuiltinHistFactoryImporter(JSONIO::Importer const &importer)
Whether this is the importer that RooFit registers for HistFactory distributions, as opposed to the o...
void buildHistFactoryDist(RooJSONFactoryWSTool &tool, std::string const &name, HistFactoryDist const &dist)
Create the RooFit objects of a HistFactory distribution in the workspace of the tool.
void configureConstrainedGammas(RooArgList const &gammas, std::span< const double > relSigmas, double minSigma)
Configure constrained gamma parameters for fitting.
Arg_t & getOrCreate(RooWorkspace &ws, std::string const &name, Params_t &&...params)
CreateGammaConstraintsOutput createGammaConstraints(RooArgList const &paramSet, std::span< const double > relSigmas, double minSigma, Constraint::Type type)
void variables(TString dataset, TString fin="TMVA.root", TString dirName="InputVariables_Id", TString title="TMVA Input Variables", Bool_t isRegression=kFALSE, Bool_t useTMVAStyle=kTRUE)
static const char * what
Definition stlLoader.cc:5
The gamma parameters are constant, which is a RooFit extension.
The constraint term is a distribution of the document, named in "constraints".
Multiplies the sample with a function of the document.
Every gamma parameter has its own constraint term, or none, as named in "constraints".
std::vector< std::optional< DistributionRef > > pdfs
std::vector< Sample > samples
The function "interpolation" of RooFit, implemented by PiecewiseInterpolation: a nominal function plu...
std::vector< Interpolation > interpolations
One per parameter.
std::vector< NameOrNumber > parameters
std::vector< NameOrNumber > low
std::vector< NameOrNumber > high
The function "interpolation0d" of RooFit, implemented by FlexibleInterpVar: a nominal value plus the ...
std::vector< double > high
std::vector< double > low
std::vector< std::string > parameters
std::vector< Interpolation > interpolations
One per parameter.
How a modifier of a HistFactory distribution interpolates and extrapolates its effect.
std::vector< double > contents
std::optional< std::vector< double > > errors
std::vector< Modifier > modifiers
Scales each bin by its own parameter. The modifier type "shapesys" is a deprecated alias of "shapefac...
Scales each bin by a parameter, that is constrained by the statistical uncertainty of all samples tha...
The parameter of the modifier is not constrained.
Combines lambdas into one visitor for std::visit(). The compiler complains about the alternatives wit...
Definition HS3Document.h:50
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335