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
36#include <regex>
37
38#include "static_execute.h"
39#include "JSONIOUtils.h"
40
42
43using namespace RooStats::HistFactory;
44using namespace RooStats::HistFactory::Detail;
46
47namespace {
48
49double round_prec(double d, int nSig)
50{
51 if (d == 0.0)
52 return 0.0;
53 int ndigits = std::floor(std::log10(std::abs(d))) + 1 - nSig;
54 double sf = std::pow(10, ndigits);
55 if (std::abs(d / sf) < 2)
56 ndigits--;
57 return sf * std::round(d / sf);
58}
59
60// To avoid repeating the same string literals that can potentially get out of
61// sync.
62namespace Literals {
63constexpr auto staterror = "staterror";
64}
65
66void erasePrefix(std::string &str, std::string_view prefix)
67{
68 if (startsWith(str, prefix)) {
69 str.erase(0, prefix.size());
70 }
71}
72
73bool eraseSuffix(std::string &str, std::string_view suffix)
74{
75 if (endsWith(str, suffix)) {
76 str.erase(str.size() - suffix.size());
77 return true;
78 } else {
79 return false;
80 }
81}
82
83template <class Coll>
84void sortByName(Coll &coll)
85{
86 std::sort(coll.begin(), coll.end(), [](auto &l, auto &r) { return l.name < r.name; });
87}
88
89template <class T>
90T *findClient(RooAbsArg *gamma)
91{
92 for (const auto &client : gamma->clients()) {
93 if (auto casted = dynamic_cast<T *>(client)) {
94 return casted;
95 } else {
96 T *c = findClient<T>(client);
97 if (c)
98 return c;
99 }
100 }
101 return nullptr;
102}
103
105{
106 if (!g)
107 return nullptr;
109 if (constraint_p)
110 return constraint_p;
112 if (constraint_g)
113 return constraint_g;
115 if (constraint_l)
116 return constraint_l;
117 return nullptr;
118}
119
120inline std::string defaultGammaName(std::string const &sysname, std::size_t i)
121{
122 return "gamma_" + sysname + "_bin_" + std::to_string(i);
123}
124
125/// Export the names of the gamma parameters to the modifier struct if the
126/// names don't match the default gamma parameter names, which is gamma_<sysname>_bin_<i>
127void optionallyExportGammaParameters(JSONNode &mod, std::string const &sysname, std::vector<RooAbsReal *> const &params,
128 bool forceExport = true)
129{
130 std::vector<std::string> paramNames;
131 bool needExport = forceExport;
132 for (std::size_t i = 0; i < params.size(); ++i) {
133 std::string name(params[i]->GetName());
134 paramNames.push_back(name);
135 if (name != defaultGammaName(sysname, i)) {
136 needExport = true;
137 }
138 }
139 if (needExport) {
140 mod["parameters"].fill_seq(paramNames);
141 }
142}
143
144RooRealVar &createNominal(RooWorkspace &ws, std::string const &parname, double val, double min, double max)
145{
146 RooRealVar &nom = getOrCreate<RooRealVar>(ws, "nom_" + parname, val, min, max);
147 nom.setConstant(true);
148 return nom;
149}
150
151/// Get the conventional name of the constraint pdf for a constrained
152/// parameter.
153std::string constraintName(std::string const &paramName)
154{
155 return paramName + "Constraint";
156}
157
158bool isLegacyConstraintType(std::string const &value)
159{
160 return value == "Gauss" || value == "Poisson" || value == "Const" || value == "Lognormal";
161}
162
163RooAbsPdf *findNamedConstraint(RooJSONFactoryWSTool &tool, std::string const &constraintName, std::string const &sample)
164{
165 if (auto *constraint = tool.workspace()->pdf(constraintName)) {
166 return constraint;
167 }
168
169 try {
170 return tool.request<RooAbsPdf>(constraintName, sample);
172 if (err.child() != constraintName) {
173 throw;
174 }
175 }
176
177 return nullptr;
178}
179
181 std::string const &constraintType)
182{
183 if (constraintType == "Gauss") {
184 param.setError(1.0);
185 return getOrCreate<RooGaussian>(*tool.workspace(), constraintName(param.GetName()), param,
186 *tool.workspace()->var(std::string("nom_") + param.GetName()), 1.);
187 }
188
189 RooJSONFactoryWSTool::error("legacy constraint value '" + constraintType + "' for modifier '" +
191 "' is a known constraint type, but it cannot be resolved in this context");
192}
193
194ParamHistFunc &createPHF(const std::string &phfname, std::string const &sysname,
195 const std::vector<std::string> &parnames, const std::vector<double> &vals,
196 RooJSONFactoryWSTool &tool, RooAbsCollection &constraints, const RooArgSet &observables,
197 const std::string &constraintType, double gammaMin, double gammaMax, double minSigma,
198 bool createConstraints = true)
199{
200 RooWorkspace &ws = *tool.workspace();
201
202 size_t n = std::max(vals.size(), parnames.size());
204 for (std::size_t i = 0; i < n; ++i) {
205 const std::string name = parnames.empty() ? defaultGammaName(sysname, i) : parnames[i];
206 auto *e = dynamic_cast<RooAbsReal *>(ws.obj(name.c_str()));
207 if (e)
208 gammas.add(*e);
209 else
211 }
212
213 auto &phf = tool.wsEmplace<ParamHistFunc>(phfname, observables, gammas);
214
215 if (vals.size() > 0) {
216 if (!createConstraints) {
218 } else if (constraintType != "Const") {
220 gammas, vals, minSigma, constraintType == "Poisson" ? Constraint::Poisson : Constraint::Gaussian);
221 for (auto const &term : constraintsInfo.constraints) {
223 constraints.add(*ws.pdf(term->GetName()));
224 }
225 } else {
226 for (auto *gamma : static_range_cast<RooRealVar *>(gammas)) {
227 gamma->setConstant(true);
228 }
229 }
230 }
231
232 return phf;
233}
234
235bool hasStaterror(const JSONNode &comp)
236{
237 if (!comp.has_child("modifiers"))
238 return false;
239 for (const auto &mod : comp["modifiers"].children()) {
240 if (mod["type"].val() == ::Literals::staterror)
241 return true;
242 }
243 return false;
244}
245
246const JSONNode &findStaterror(const JSONNode &comp)
247{
248 if (comp.has_child("modifiers")) {
249 for (const auto &mod : comp["modifiers"].children()) {
250 if (mod["type"].val() == ::Literals::staterror)
251 return mod;
252 }
253 }
254 RooJSONFactoryWSTool::error("sample '" + RooJSONFactoryWSTool::name(comp) + "' does not have a " +
255 ::Literals::staterror + " modifier!");
256}
257
258RooAbsPdf &
259getOrCreateConstraint(RooJSONFactoryWSTool &tool, const JSONNode &mod, RooRealVar &param, const std::string &sample)
260{
261 JSONNode const *constrName = mod.find("constraint_name");
262 if (constrName) {
263 auto constraint_name = constrName->val();
264 auto constraint = findNamedConstraint(tool, constraint_name, sample);
265 if (!constraint) {
266 RooJSONFactoryWSTool::error("unable to find definition of of constraint '" + constraint_name +
267 "' for modifier '" + RooJSONFactoryWSTool::name(mod) + "'");
268 }
269 if (auto gauss = dynamic_cast<RooGaussian *const>(constraint)) {
270 param.setError(gauss->getSigma().getVal());
271 }
272 return *constraint;
273 }
274
275 if (auto constr = mod.find("constraint")) {
276 std::string constraintValue = constr->val();
277 if (auto *constraint = findNamedConstraint(tool, constraintValue, sample)) {
278 if (auto gauss = dynamic_cast<RooGaussian *const>(constraint)) {
279 param.setError(gauss->getSigma().getVal());
280 }
281 return *constraint;
282 }
283
286 }
287
288 RooJSONFactoryWSTool::error("unable to resolve constraint value '" + constraintValue + "' for modifier '" +
290 "': this looks like a legacy workspace where the 'constraint' field is neither a "
291 "constraint pdf name nor a supported legacy constraint type");
292 }
293
294 std::string constraint_type = "Gauss";
295 if (auto constrType = mod.find("constraint_type")) {
297 }
300 }
301 RooJSONFactoryWSTool::error("unknown or invalid constraint for modifier '" + RooJSONFactoryWSTool::name(mod) + "'");
302}
303double poissonTau(RooPoisson const &constraint, RooAbsArg const &gamma)
304{
305 auto const *mean = dynamic_cast<RooProduct const *>(&constraint.getMean());
306 if (!mean) {
307 RooJSONFactoryWSTool::error("Poisson gamma constraint mean is not a RooProduct: " +
308 std::string(constraint.GetName()));
309 }
310
311 for (RooAbsArg *arg : mean->servers()) {
312 if (arg == &gamma) {
313 continue;
314 }
315
316 if (auto const *tau = dynamic_cast<RooConstVar const *>(arg)) {
317 return tau->getVal();
318 }
319
320 // Imported workspaces can sometimes represent
321 // constants as constant RooRealVars.
322 if (auto const *real = dynamic_cast<RooAbsReal const *>(arg)) {
323 if (real->isConstant() || endsWith(std::string(real->GetName()), "_tau")) {
324 return real->getVal();
325 }
326 }
327 }
328
329 RooJSONFactoryWSTool::error("Could not find tau component in Poisson gamma constraint mean: " +
330 std::string(constraint.GetName()));
331 return std::numeric_limits<double>::quiet_NaN();
332}
333
335 RooAbsArg const *mcStatObject, const std::string &fprefix, const JSONNode &p,
336 RooArgSet &constraints)
337{
338 RooWorkspace &ws = *tool.workspace();
339
341 std::string prefixedName = fprefix + "_" + sampleName;
342
343 std::string channelName = fprefix;
344 erasePrefix(channelName, "model_");
345
346 if (!p.has_child("data")) {
347 RooJSONFactoryWSTool::error("sample '" + sampleName + "' does not define a 'data' key");
348 }
349
350 auto &hf = tool.wsEmplace<RooHistFunc>("hist_" + prefixedName, varlist, dh);
351 hf.SetTitle(RooJSONFactoryWSTool::name(p).c_str());
352
355
356 shapeElems.add(tool.wsEmplace<RooBinWidthFunction>(prefixedName + "_binWidth", hf, true));
357
358 if (hasStaterror(p)) {
360 }
361
362 if (p.has_child("modifiers")) {
364 std::vector<double> overall_low;
365 std::vector<double> overall_high;
366 std::vector<int> overall_interp;
367
371
372 int idx = 0;
373 for (const auto &mod : p["modifiers"].children()) {
374 std::string const &modtype = mod["type"].val();
375 std::string const &sysname =
376 mod.has_child("name")
377 ? mod["name"].val()
378 : (mod.has_child("parameter") ? mod["parameter"].val() : "syst_" + std::to_string(idx));
379 ++idx;
380 if (modtype == "staterror") {
381 // this is dealt with at a different place, ignore it for now
382 } else if (modtype == "normfactor") {
384 constrParam.setError(0.0);
386 if (mod.has_child("constraint") || mod.has_child("constraint_name") || mod.has_child("constraint_type")) {
387 // for norm factors, constraints are optional
389 }
390 } else if (modtype == "normsys") {
391 auto *parameter = mod.find("parameter");
392 std::string parname(parameter ? parameter->val() : "alpha_" + sysname);
393 createNominal(ws, parname, 0.0, -10, 10);
394 auto &par = getOrCreate<RooRealVar>(ws, parname, 0., -5, 5);
395 overall_nps.add(par);
396 auto &data = mod["data"];
397 int interp = 4;
398 if (mod.has_child("interpolation")) {
399 interp = mod["interpolation"].val_int();
400 }
401 double low = data["lo"].val_double();
402 double high = data["hi"].val_double();
403
404 // the below contains a a hack to cut off variations that go below 0
405 // this is needed because with interpolation code 4, which is the default, interpolation is done in
406 // log-space. hence, values <= 0 result in NaN which propagate throughout the model and cause evaluations to
407 // fail if you know a nicer way to solve this, please go ahead and fix the lines below
408 if (interp == 4 && low <= 0)
409 low = std::numeric_limits<double>::epsilon();
410 if (interp == 4 && high <= 0)
411 high = std::numeric_limits<double>::epsilon();
412
413 overall_low.push_back(low);
414 overall_high.push_back(high);
415 overall_interp.push_back(interp);
416
417 constraints.add(getOrCreateConstraint(tool, mod, par, sampleName));
418 } else if (modtype == "histosys") {
419 auto *parameter = mod.find("parameter");
420 std::string parname(parameter ? parameter->val() : "alpha_" + sysname);
421 createNominal(ws, parname, 0.0, -10, 10);
422 auto &par = getOrCreate<RooRealVar>(ws, parname, 0., -5, 5);
423 histNps.add(par);
424 auto &data = mod["data"];
425 histoLo.add(tool.wsEmplace<RooHistFunc>(
426 sysname + "Low_" + prefixedName, varlist,
428 histoHi.add(tool.wsEmplace<RooHistFunc>(
429 sysname + "High_" + prefixedName, varlist,
430 RooJSONFactoryWSTool::readBinnedData(data["hi"], sysname + "High_" + prefixedName, varlist)));
431 constraints.add(getOrCreateConstraint(tool, mod, par, sampleName));
432 } else if (modtype == "shapesys" || modtype == "shapefactor") {
433 std::string funcName = channelName + "_" + sysname + "_ShapeSys";
434 // funcName should be "<channel_name>_<sysname>_ShapeSys"
435 std::vector<double> vals;
436 if (mod["data"].has_child("vals")) {
437 for (const auto &v : mod["data"]["vals"].children()) {
438 vals.push_back(v.val_double());
439 }
440 }
441 std::vector<std::string> parnames;
442 for (const auto &v : mod["parameters"].children()) {
443 parnames.push_back(v.val());
444 }
445 if (vals.empty() && parnames.empty()) {
446 RooJSONFactoryWSTool::error("unable to instantiate shapesys '" + sysname +
447 "' with neither values nor parameters!");
448 }
449 std::string constraint = "unknown";
450 std::vector<RooAbsPdf *> constraintPdfs;
451 bool const hasConstraintList = mod.has_child("constraints");
452 if (hasConstraintList) {
453 for (const auto &v : mod["constraints"].children()) {
454 if (v.is_null()) {
455 constraintPdfs.push_back(nullptr);
456 } else {
457 std::string constraintName = v.val();
459 if (!constraintPdf) {
460 RooJSONFactoryWSTool::error("unable to find definition of constraint '" + constraintName +
461 "' for modifier '" + RooJSONFactoryWSTool::name(mod) + "'");
462 }
463 constraintPdfs.push_back(constraintPdf);
464 }
465 }
466 std::size_t const nGammas = std::max(vals.size(), parnames.size());
467 if (constraintPdfs.size() != nGammas) {
468 std::stringstream ss;
469 ss << "modifier '" << RooJSONFactoryWSTool::name(mod) << "' has " << constraintPdfs.size()
470 << " constraints, but " << nGammas << " parameters";
472 }
473 } else if (mod.has_child("constraint_type")) {
474 constraint = mod["constraint_type"].val();
475 } else if (mod.has_child("constraint")) {
476 std::string constraintValue = mod["constraint"].val();
478 constraint = constraintValue;
479 } else {
480 RooJSONFactoryWSTool::error("unable to resolve constraint value '" + constraintValue +
481 "' for modifier '" + RooJSONFactoryWSTool::name(mod) +
482 "': this looks like a legacy workspace where the 'constraint' field is "
483 "not a supported legacy constraint type");
484 }
485 }
486 shapeElems.add(createPHF(funcName, sysname, parnames, vals, tool, constraints, varlist, constraint,
488 /*createConstraints=*/!hasConstraintList));
489 for (auto *constraintPdf : constraintPdfs) {
490 if (constraintPdf) {
491 constraints.add(*constraintPdf);
492 }
493 }
494 } else if (modtype == "custom") {
495 RooAbsReal *obj = ws.function(sysname);
496 if (!obj) {
497 RooJSONFactoryWSTool::error("unable to find custom modifier '" + sysname + "'");
498 }
499 if (obj->dependsOn(varlist)) {
500 shapeElems.add(*obj);
501 } else {
502 normElems.add(*obj);
503 }
504 } else {
505 RooJSONFactoryWSTool::error("modifier '" + sysname + "' of unknown type '" + modtype + "'");
506 }
507 }
508
509 std::string interpName = sampleName + "_" + channelName + "_epsilon";
510 if (!overall_nps.empty()) {
513 normElems.add(v);
514 }
515 if (!histNps.empty()) {
516 auto &v = tool.wsEmplace<PiecewiseInterpolation>("histoSys_" + prefixedName, hf, histoLo, histoHi, histNps);
518 v.setAllInterpCodes(4); // default interpCode for HistFactory
519 shapeElems.add(v);
520 } else {
521 shapeElems.add(hf);
522 }
523 }
524
525 tool.wsEmplace<RooProduct>(prefixedName + "_shapes", shapeElems);
526 if (!normElems.empty()) {
527 tool.wsEmplace<RooProduct>(prefixedName + "_scaleFactors", normElems);
528 } else {
529 ws.factory("RooConstVar::" + prefixedName + "_scaleFactors(1.)");
530 }
531
532 return true;
533}
534
535class HistFactoryImporter : public RooFit::JSONIO::Importer {
536public:
537 bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override
538 {
539 std::string name = RooJSONFactoryWSTool::name(p);
540 if (!p.has_child("samples")) {
541 RooJSONFactoryWSTool::error("no samples in '" + name + "', skipping.");
542 }
543 double statErrThresh = 0;
544 std::string statErrType = "Poisson";
545 if (p.has_child(::Literals::staterror)) {
546 auto &staterr = p[::Literals::staterror];
547 if (staterr.has_child("relThreshold"))
548 statErrThresh = staterr["relThreshold"].val_double();
549 if (staterr.has_child("constraint_type"))
550 statErrType = staterr["constraint_type"].val();
551 }
552 std::vector<double> sumW;
553 std::vector<double> sumW2;
554 std::vector<std::string> gammaParnames;
556
557 std::string fprefix = name;
558
559 std::vector<std::unique_ptr<RooDataHist>> data;
560 for (const auto &comp : p["samples"].children()) {
561 std::unique_ptr<RooDataHist> dh = RooJSONFactoryWSTool::readBinnedData(
562 comp["data"], fprefix + "_" + RooJSONFactoryWSTool::name(comp) + "_dataHist", observables);
563 size_t nbins = dh->numEntries();
564
565 if (hasStaterror(comp)) {
566 if (sumW.empty()) {
567 sumW.resize(nbins);
568 sumW2.resize(nbins);
569 }
570 for (size_t i = 0; i < nbins; ++i) {
571 sumW[i] += dh->weight(i);
572 sumW2[i] += dh->weightSquared(i);
573 }
574 if (gammaParnames.empty()) {
575 if (auto staterrorParams = findStaterror(comp).find("parameters")) {
576 for (const auto &v : staterrorParams->children()) {
577 gammaParnames.push_back(v.val());
578 }
579 }
580 }
581 }
582 data.emplace_back(std::move(dh));
583 }
584
585 RooAbsArg *mcStatObject = nullptr;
586 RooArgSet constraints;
587 if (!sumW.empty()) {
588 std::string channelName = name;
589 erasePrefix(channelName, "model_");
590
591 std::vector<double> errs(sumW.size());
592 for (size_t i = 0; i < sumW.size(); ++i) {
593 if (sumW[i] == 0.) {
594 errs[i] = 0.;
595 continue;
596 }
597 errs[i] = std::sqrt(sumW2[i]) / sumW[i];
598 // avoid negative sigma. This NP will be set constant anyway later
599 errs[i] = std::max(errs[i], 0.);
600 }
601
603 &createPHF("mc_stat_" + channelName, "stat_" + channelName, gammaParnames, errs, *tool, constraints,
605 }
606
607 int idx = 0;
609 RooArgList coefs;
610 for (const auto &comp : p["samples"].children()) {
611 importHistSample(*tool, *data[idx], observables, mcStatObject, fprefix, comp, constraints);
612 ++idx;
613
614 std::string const &compName = RooJSONFactoryWSTool::name(comp);
615 funcs.add(*tool->request<RooAbsReal>(fprefix + "_" + compName + "_shapes", name));
616 coefs.add(*tool->request<RooAbsReal>(fprefix + "_" + compName + "_scaleFactors", name));
617 }
618
619 if (constraints.empty()) {
620 tool->wsEmplace<RooRealSumPdf>(name, funcs, coefs, true);
621 } else {
622 std::string sumName = name + "_model";
623 erasePrefix(sumName, "model_");
624 auto &sum = tool->wsEmplace<RooRealSumPdf>(sumName, funcs, coefs, true);
625 sum.SetTitle(name.c_str());
626 tool->wsEmplace<RooProdPdf>(name, constraints, RooFit::Conditional(sum, observables));
627 }
628 return true;
629 }
630};
631
632class FlexibleInterpVarStreamer : public RooFit::JSONIO::Exporter {
633public:
634 std::string const &key() const override
635 {
636 static const std::string keystring = "interpolation0d";
637 return keystring;
638 }
639 bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override
640 {
641 auto fip = static_cast<const RooStats::HistFactory::FlexibleInterpVar *>(func);
642 elem["type"] << key();
643 elem["interpolationCodes"].fill_seq(fip->interpolationCodes());
644 RooJSONFactoryWSTool::fillSeq(elem["vars"], fip->variables());
645 elem["nom"] << fip->nominal();
646 elem["high"].fill_seq(fip->high(), fip->variables().size());
647 elem["low"].fill_seq(fip->low(), fip->variables().size());
648 return true;
649 }
650};
651
652class PiecewiseInterpolationStreamer : public RooFit::JSONIO::Exporter {
653public:
654 std::string const &key() const override
655 {
656 static const std::string keystring = "interpolation";
657 return keystring;
658 }
659 bool exportObject(RooJSONFactoryWSTool *, const RooAbsArg *func, JSONNode &elem) const override
660 {
661 const PiecewiseInterpolation *pip = static_cast<const PiecewiseInterpolation *>(func);
662 elem["type"] << key();
663 elem["interpolationCodes"].fill_seq(pip->interpolationCodes());
664 elem["positiveDefinite"] << pip->positiveDefinite();
665 RooJSONFactoryWSTool::fillSeq(elem["vars"], pip->paramList());
666 elem["nom"] << pip->nominalHist()->GetName();
667 RooJSONFactoryWSTool::fillSeq(elem["high"], pip->highList(), pip->paramList().size());
668 RooJSONFactoryWSTool::fillSeq(elem["low"], pip->lowList(), pip->paramList().size());
669 return true;
670 }
671};
672
673class PiecewiseInterpolationFactory : public RooFit::JSONIO::Importer {
674public:
675 bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override
676 {
677 std::string name(RooJSONFactoryWSTool::name(p));
678
679 RooArgList vars{tool->requestArgList<RooAbsReal>(p, "vars")};
680
681 auto &pip = tool->wsEmplace<PiecewiseInterpolation>(name, *tool->requestArg<RooAbsReal>(p, "nom"),
682 tool->requestArgList<RooAbsReal>(p, "low"),
683 tool->requestArgList<RooAbsReal>(p, "high"), vars);
684
685 pip.setPositiveDefinite(p["positiveDefinite"].val_bool());
686
687 if (p.has_child("interpolationCodes")) {
688 std::size_t i = 0;
689 for (auto const &node : p["interpolationCodes"].children()) {
690 pip.setInterpCode(*static_cast<RooAbsReal *>(vars.at(i)), node.val_int(), true);
691 ++i;
692 }
693 }
694
695 return true;
696 }
697};
698
699class FlexibleInterpVarFactory : public RooFit::JSONIO::Importer {
700public:
701 bool importArg(RooJSONFactoryWSTool *tool, const JSONNode &p) const override
702 {
703 std::string name(RooJSONFactoryWSTool::name(p));
704 if (!p.has_child("high")) {
705 RooJSONFactoryWSTool::error("no high variations of '" + name + "'");
706 }
707 if (!p.has_child("low")) {
708 RooJSONFactoryWSTool::error("no low variations of '" + name + "'");
709 }
710 if (!p.has_child("nom")) {
711 RooJSONFactoryWSTool::error("no nominal variation of '" + name + "'");
712 }
713
714 double nom(p["nom"].val_double());
715
716 RooArgList vars{tool->requestArgList<RooRealVar>(p, "vars")};
717
718 std::vector<double> high;
719 high << p["high"];
720
721 std::vector<double> low;
722 low << p["low"];
723
724 if (vars.size() != low.size() || vars.size() != high.size()) {
725 RooJSONFactoryWSTool::error("FlexibleInterpVar '" + name +
726 "' has non-matching lengths of 'vars', 'high' and 'low'!");
727 }
728
729 auto &fip = tool->wsEmplace<RooStats::HistFactory::FlexibleInterpVar>(name, vars, nom, low, high);
730
731 if (p.has_child("interpolationCodes")) {
732 size_t i = 0;
733 for (auto const &node : p["interpolationCodes"].children()) {
734 fip.setInterpCode(*static_cast<RooAbsReal *>(vars.at(i)), node.val_int());
735 ++i;
736 }
737 }
738
739 return true;
740 }
741};
742
743struct NormFactor {
744 std::string name;
745 RooAbsReal const *param = nullptr;
746 RooAbsPdf const *constraint = nullptr;
747 NormFactor(RooAbsReal const &par, const RooAbsPdf *constr = nullptr)
748 : name{par.GetName()}, param{&par}, constraint{constr}
749 {
750 }
751};
752
753struct NormSys {
754 std::string name = "";
755 RooAbsReal const *param = nullptr;
756 double low = 1.;
757 double high = 1.;
758 int interpolationCode = 4;
759 RooAbsPdf const *constraint = nullptr;
760 NormSys() {};
761 NormSys(const std::string &n, RooAbsReal *const p, double h, double l, int i, const RooAbsPdf *c)
762 : name(n), param(p), low(l), high(h), interpolationCode(i), constraint(c)
763 {
764 }
765};
766
767struct HistoSys {
768 std::string name;
769 RooAbsReal const *param = nullptr;
770 std::vector<double> low;
771 std::vector<double> high;
772 RooAbsPdf const *constraint = nullptr;
773 HistoSys(const std::string &n, RooAbsReal *const p, RooHistFunc *l, RooHistFunc *h, const RooAbsPdf *c)
774 : name(n), param(p), constraint(c)
775 {
776 low.assign(l->dataHist().weightArray(), l->dataHist().weightArray() + l->dataHist().numEntries());
777 high.assign(h->dataHist().weightArray(), h->dataHist().weightArray() + h->dataHist().numEntries());
778 }
779};
780struct ShapeSys {
781 std::string name;
782 std::vector<double> constraints;
783 std::vector<RooAbsPdf const *> constraintPdfs;
784 std::vector<RooAbsReal *> parameters;
785 ShapeSys(const std::string &n) : name{n} {}
786};
787
788struct GenericElement {
789 std::string name;
790 RooAbsReal *function = nullptr;
791 GenericElement(RooAbsReal *e) : name(e->GetName()), function(e) {};
792};
793
794std::string stripOuterParens(const std::string &s)
795{
796 size_t start = 0;
797 size_t end = s.size();
798
799 while (start < end && s[start] == '(' && s[end - 1] == ')') {
800 int depth = 0;
801 bool balanced = true;
802 for (size_t i = start; i < end - 1; ++i) {
803 if (s[i] == '(')
804 ++depth;
805 else if (s[i] == ')')
806 --depth;
807 if (depth == 0 && i < end - 1) {
808 balanced = false;
809 break;
810 }
811 }
812 if (balanced) {
813 ++start;
814 --end;
815 } else {
816 break;
817 }
818 }
819 return s.substr(start, end - start);
820}
821
822std::vector<std::string> splitTopLevelProduct(const std::string &expr)
823{
824 std::vector<std::string> parts;
825 int depth = 0;
826 size_t start = 0;
827 bool foundTopLevelStar = false;
828
829 for (size_t i = 0; i < expr.size(); ++i) {
830 char c = expr[i];
831 if (c == '(') {
832 ++depth;
833 } else if (c == ')') {
834 --depth;
835 } else if (c == '*' && depth == 0) {
836 foundTopLevelStar = true;
837 std::string sub = expr.substr(start, i - start);
838 parts.push_back(stripOuterParens(sub));
839 start = i + 1;
840 }
841 }
842
843 if (!foundTopLevelStar) {
844 return {}; // Not a top-level product
845 }
846
847 std::string sub = expr.substr(start);
848 parts.push_back(stripOuterParens(sub));
849 return parts;
850}
851
852NormSys parseOverallModifierFormula(const std::string &s, RooFormulaVar *formula)
853{
854 static const std::regex pattern(
855 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*$)");
856
857 NormSys sys;
858 double sign = 1.0;
859
860 std::smatch match;
861 if (std::regex_match(s, match, pattern)) {
862 if (match[1].str() == "-") {
863 sign = -1.0;
864 }
865
866 std::string token2 = match[2].str();
867 std::string token3 = match[4].str();
868
869 RooAbsReal *p2 = static_cast<RooAbsReal *>(formula->getParameter(token2.c_str()));
870 RooAbsReal *p3 = static_cast<RooAbsReal *>(formula->getParameter(token3.c_str()));
871 RooRealVar *v2 = dynamic_cast<RooRealVar *>(p2);
872 RooRealVar *v3 = dynamic_cast<RooRealVar *>(p3);
873
874 auto *constr2 = findConstraint(v2);
875 auto *constr3 = findConstraint(v3);
876
877 if (constr2 && !p3) {
878 sys.name = p2->GetName();
879 sys.param = p2;
880 sys.high = sign * toDouble(token3);
881 sys.low = -sign * toDouble(token3);
882 } else if (!p2 && constr3) {
883 sys.name = p3->GetName();
884 sys.param = p3;
885 sys.high = sign * toDouble(token2);
886 sys.low = -sign * toDouble(token2);
887 } else if (constr2 && p3 && !constr3) {
888 sys.name = v2->GetName();
889 sys.param = v2;
890 sys.high = sign * p3->getVal();
891 sys.low = -sign * p3->getVal();
892 } else if (p2 && !constr2 && constr3) {
893 sys.name = v3->GetName();
894 sys.param = v3;
895 sys.high = sign * p2->getVal();
896 sys.low = -sign * p2->getVal();
897 }
898
899 // interpolation code 1 means linear, which is what we have here
900 sys.interpolationCode = 1;
901
902 erasePrefix(sys.name, "alpha_");
903 }
904 return sys;
905}
906
907void collectElements(RooArgSet &elems, RooAbsArg *arg)
908{
909 if (auto prod = dynamic_cast<RooProduct *>(arg)) {
910 for (const auto &e : prod->components()) {
911 collectElements(elems, e);
912 }
913 } else {
914 elems.add(*arg);
915 }
916}
917
918bool allRooRealVar(const RooAbsCollection &list)
919{
920 for (auto *var : list) {
921 if (!dynamic_cast<RooRealVar *>(var)) {
922 return false;
923 }
924 }
925 return true;
926}
927
928struct Sample {
929 std::string name;
930 std::vector<double> hist;
931 std::vector<double> histError;
932 std::vector<NormFactor> normfactors;
933 std::vector<NormSys> normsys;
934 std::vector<HistoSys> histosys;
935 std::vector<ShapeSys> shapesys;
936 std::vector<GenericElement> tmpElements;
937 std::vector<GenericElement> otherElements;
938 bool useBarlowBeestonLight = false;
939 std::vector<RooAbsReal *> staterrorParameters;
940 Sample(const std::string &n) : name{n} {}
941};
942
943void addNormFactor(RooRealVar const *par, Sample &sample, RooWorkspace *ws)
944{
945 std::string parname = par->GetName();
946 bool isConstrained = false;
947 for (RooAbsArg const *pdf : ws->allPdfs()) {
948 if (auto gauss = dynamic_cast<RooGaussian const *>(pdf)) {
949 if (parname == gauss->getX().GetName()) {
950 sample.normfactors.emplace_back(*par, gauss);
951 isConstrained = true;
952 }
953 }
954 }
955 if (!isConstrained)
956 sample.normfactors.emplace_back(*par);
957}
958
959namespace {
960
961bool verbose = false;
962
963}
964
965struct Channel {
966 std::string name;
967 std::vector<Sample> samples;
968 std::map<int, double> tot_yield;
969 std::map<int, double> tot_yield2;
970 std::map<int, double> rel_errors;
971 RooArgSet const *varSet = nullptr;
972 long unsigned int nBins = 0;
973};
974
976{
977 Channel channel;
978
979 RooWorkspace *ws = tool->workspace();
980
981 channel.name = pdfname;
982 erasePrefix(channel.name, "model_");
983 eraseSuffix(channel.name, "_model");
984
985 for (size_t sampleidx = 0; sampleidx < sumpdf->funcList().size(); ++sampleidx) {
986 PiecewiseInterpolation *pip = nullptr;
987 std::vector<ParamHistFunc *> phfs;
988
989 const auto func = sumpdf->funcList().at(sampleidx);
990 Sample sample(func->GetName());
991 erasePrefix(sample.name, "L_x_");
992 eraseSuffix(sample.name, "_shapes");
993 eraseSuffix(sample.name, "_" + channel.name);
994 erasePrefix(sample.name, pdfname + "_");
995
996 auto updateObservables = [&](RooDataHist const &dataHist) {
997 if (channel.varSet == nullptr) {
998 channel.varSet = dataHist.get();
999 channel.nBins = dataHist.numEntries();
1000 }
1001 if (sample.hist.empty()) {
1002 auto *w = dataHist.weightArray();
1003 sample.hist.assign(w, w + dataHist.numEntries());
1004 }
1005 };
1006 auto processElements = [&](const auto &elements, auto &&self) -> void {
1007 for (RooAbsArg *e : elements) {
1008 if (TString(e->GetName()).Contains("binWidth")) {
1009 // The bin width modifiers are handled separately. We can't just
1010 // check for the RooBinWidthFunction type here, because prior to
1011 // ROOT 6.26, the multiplication with the inverse bin width was
1012 // done in a different way (like a normfactor with a RooRealVar,
1013 // but it was stored in the dataset).
1014 // Fortunately, the name was similar, so we can match the modifier
1015 // name.
1016 } else if (auto constVar = dynamic_cast<RooConstVar *>(e)) {
1017 if (constVar->getVal() != 1.) {
1018 sample.normfactors.emplace_back(*constVar);
1019 }
1020 } else if (auto par = dynamic_cast<RooRealVar *>(e)) {
1021 addNormFactor(par, sample, ws);
1022 } else if (auto hf = dynamic_cast<const RooHistFunc *>(e)) {
1023 updateObservables(hf->dataHist());
1024 } else if (ParamHistFunc *phf = dynamic_cast<ParamHistFunc *>(e); phf && allRooRealVar(phf->paramList())) {
1025 phfs.push_back(phf);
1026 } else if (auto fip = dynamic_cast<RooStats::HistFactory::FlexibleInterpVar *>(e)) {
1027 // some (modified) histfactory models have several instances of FlexibleInterpVar
1028 // we collect and merge them
1029 for (size_t i = 0; i < fip->variables().size(); ++i) {
1030 RooAbsReal *var = static_cast<RooAbsReal *>(fip->variables().at(i));
1031 std::string sysname(var->GetName());
1032 erasePrefix(sysname, "alpha_");
1033 const auto *constraint = findConstraint(var);
1034 if (!constraint && !var->isConstant()) {
1035 RooJSONFactoryWSTool::error("cannot find constraint for " + std::string(var->GetName()));
1036 } else {
1037 sample.normsys.emplace_back(sysname, var, fip->high()[i], fip->low()[i],
1038 fip->interpolationCodes()[i], constraint);
1039 }
1040 }
1041 } else if (!pip && (pip = dynamic_cast<PiecewiseInterpolation *>(e))) {
1042 // nothing to do here, already assigned
1043 } else if (RooFormulaVar *formula = dynamic_cast<RooFormulaVar *>(e)) {
1044 // people do a lot of fancy stuff with RooFormulaVar, like including NormSys via explicit formulae.
1045 // let's try to decompose it into building blocks
1046 TString expression(formula->expression());
1047 for (size_t i = formula->nParameters(); i--;) {
1048 const RooAbsArg *p = formula->getParameter(i);
1049 expression.ReplaceAll(("x[" + std::to_string(i) + "]").c_str(), p->GetName());
1050 expression.ReplaceAll(("@" + std::to_string(i)).c_str(), p->GetName());
1051 }
1052 auto components = splitTopLevelProduct(expression.Data());
1053 if (components.size() == 0) {
1054 // it's not a product, let's just treat it as an unknown element
1055 sample.otherElements.push_back(formula);
1056 } else {
1057 // it is a prododuct, we can try to handle the elements separately
1058 std::vector<RooAbsArg *> realComponents;
1059 int idx = 0;
1060 for (auto &comp : components) {
1061 // check if this is a trivial element of a product, we can treat it as its own modifier
1062 auto *part = formula->getParameter(comp.c_str());
1063 if (part) {
1064 realComponents.push_back(part);
1065 continue;
1066 }
1067 // check if this is an attempt at explicitly encoding an overallSys
1068 auto normsys = parseOverallModifierFormula(comp, formula);
1069 if (normsys.param) {
1070 sample.normsys.emplace_back(std::move(normsys));
1071 continue;
1072 }
1073
1074 // this is something non-trivial, let's deal with it separately
1075 std::string name = std::string(formula->GetName()) + "_part" + std::to_string(idx);
1076 ++idx;
1077 auto *var = new RooFormulaVar(name.c_str(), name.c_str(), comp.c_str(), formula->dependents());
1078 sample.tmpElements.push_back({var});
1079 }
1080 self(realComponents, self);
1081 }
1082 } else if (auto real = dynamic_cast<RooAbsReal *>(e)) {
1083 sample.otherElements.push_back(real);
1084 }
1085 }
1086 };
1087
1088 RooArgSet elems;
1089 collectElements(elems, func);
1090 collectElements(elems, sumpdf->coefList().at(sampleidx));
1092
1093 // see if we can get the observables
1094 if (pip) {
1095 if (auto nh = dynamic_cast<RooHistFunc const *>(pip->nominalHist())) {
1096 updateObservables(nh->dataHist());
1097 }
1098 }
1099
1100 // sort and configure norms
1101 sortByName(sample.normfactors);
1102 sortByName(sample.normsys);
1103
1104 // sort and configure the histosys
1105 if (pip) {
1106 for (size_t i = 0; i < pip->paramList().size(); ++i) {
1107 RooAbsReal *var = static_cast<RooAbsReal *>(pip->paramList().at(i));
1108 std::string sysname(var->GetName());
1109 erasePrefix(sysname, "alpha_");
1110 if (auto lo = dynamic_cast<RooHistFunc *>(pip->lowList().at(i))) {
1111 if (auto hi = dynamic_cast<RooHistFunc *>(pip->highList().at(i))) {
1112 const auto *constraint = findConstraint(var);
1113 if (!constraint && !var->isConstant()) {
1114 RooJSONFactoryWSTool::error("cannot find constraint for " + std::string(var->GetName()));
1115 } else {
1116 sample.histosys.emplace_back(sysname, var, lo, hi, constraint);
1117 }
1118 }
1119 }
1120 }
1121 sortByName(sample.histosys);
1122 }
1123
1124 for (ParamHistFunc *phf : phfs) {
1125 if (startsWith(std::string(phf->GetName()), "mc_stat_")) { // MC stat uncertainty
1126 int idx = 0;
1127 for (const auto &g : phf->paramList()) {
1128 sample.staterrorParameters.push_back(static_cast<RooRealVar *>(g));
1129 ++idx;
1130 RooAbsPdf *constraint = findConstraint(g);
1131 if (channel.tot_yield.find(idx) == channel.tot_yield.end()) {
1132 channel.tot_yield[idx] = 0;
1133 channel.tot_yield2[idx] = 0;
1134 }
1135 channel.tot_yield[idx] += sample.hist[idx - 1];
1136 channel.tot_yield2[idx] += (sample.hist[idx - 1] * sample.hist[idx - 1]);
1137 if (constraint) {
1138 if (RooPoisson *constraint_p = dynamic_cast<RooPoisson *>(constraint)) {
1139 double erel = 1. / std::sqrt(poissonTau(*constraint_p, *g));
1140 channel.rel_errors[idx] = erel;
1141 } else if (RooGaussian *constraint_g = dynamic_cast<RooGaussian *>(constraint)) {
1142 double erel = constraint_g->getSigma().getVal() / constraint_g->getMean().getVal();
1143 channel.rel_errors[idx] = erel;
1144 } else {
1146 "currently, only RooPoisson and RooGaussian are supported as constraint types");
1147 }
1148 }
1149 }
1150 sample.useBarlowBeestonLight = true;
1151 } else { // other ShapeSys
1152 ShapeSys sys(phf->GetName());
1153 erasePrefix(sys.name, channel.name + "_");
1154 bool isshapesys = eraseSuffix(sys.name, "_ShapeSys") || eraseSuffix(sys.name, "_shapeSys");
1155 bool isshapefactor = eraseSuffix(sys.name, "_ShapeFactor") || eraseSuffix(sys.name, "_shapeFactor");
1156
1157 for (const auto &g : phf->paramList()) {
1158 sys.parameters.push_back(static_cast<RooRealVar *>(g));
1159 RooAbsPdf *constraint = nullptr;
1160 if (isshapesys) {
1161 constraint = findConstraint(g);
1162 if (!constraint)
1163 constraint = ws->pdf(constraintName(g->GetName()));
1164 if (!constraint && !g->isConstant()) {
1165 RooJSONFactoryWSTool::error("cannot find constraint for " + std::string(g->GetName()));
1166 }
1167 } else if (!isshapefactor) {
1168 RooJSONFactoryWSTool::error("unknown type of shapesys " + std::string(phf->GetName()));
1169 }
1170 if (!constraint) {
1171 sys.constraints.push_back(0.0);
1172 sys.constraintPdfs.push_back(nullptr);
1173 } else if (auto constraint_p = dynamic_cast<RooPoisson *>(constraint)) {
1174 sys.constraints.push_back(1. / std::sqrt(poissonTau(*constraint_p, *g)));
1175 sys.constraintPdfs.push_back(constraint_p);
1176 } else if (auto constraint_g = dynamic_cast<RooGaussian *>(constraint)) {
1177 sys.constraints.push_back(constraint_g->getSigma().getVal() / constraint_g->getMean().getVal());
1178 sys.constraintPdfs.push_back(constraint_g);
1179 } else {
1181 "currently, only RooPoisson and RooGaussian are supported as constraint types");
1182 }
1183 }
1184 sample.shapesys.emplace_back(std::move(sys));
1185 }
1186 }
1187 sortByName(sample.shapesys);
1188
1189 // add the sample
1190 channel.samples.emplace_back(std::move(sample));
1191 }
1192
1193 sortByName(channel.samples);
1194 return channel;
1195}
1196
1197void configureStatError(Channel &channel)
1198{
1199 for (auto &sample : channel.samples) {
1200 if (sample.useBarlowBeestonLight) {
1201 sample.histError.resize(sample.hist.size());
1202 for (auto bin : channel.rel_errors) {
1203 // reverse engineering the correct partial error
1204 // the (arbitrary) convention used here is that all samples should have the same relative error
1205 const int i = bin.first;
1206 const double relerr_tot = bin.second;
1207 const double count = sample.hist[i - 1];
1208 // this reconstruction is inherently imprecise, so we truncate it at some decimal places to make sure that
1209 // we don't carry around too many useless digits
1210 sample.histError[i - 1] =
1211 round_prec(relerr_tot * channel.tot_yield[i] / std::sqrt(channel.tot_yield2[i]) * count, 7);
1212 }
1213 }
1214 }
1215}
1216
1218{
1219 // Write the constraint reference for any modifier that supports an
1220 // external Gaussian/Poisson/etc. constraint.
1221 auto writeConstraint = [](JSONNode &mod, auto const &sys) {
1222 if (sys.constraint) {
1223 mod["constraint"] << sys.constraint->GetName();
1224 }
1225 };
1226
1227 bool observablesWritten = false;
1228 for (const auto &sample : channel.samples) {
1229
1230 elem["type"] << "histfactory_dist";
1231
1232 auto &s = RooJSONFactoryWSTool::appendNamedChild(elem["samples"], sample.name);
1233
1234 auto &modifiers = s["modifiers"];
1235 modifiers.set_seq();
1236
1237 for (const auto &nf : sample.normfactors) {
1238 auto &mod = modifiers.append_child();
1239 mod.set_map();
1240 mod["name"] << nf.name;
1241 mod["parameter"] << nf.param->GetName();
1242 mod["type"] << "normfactor";
1243 if (nf.constraint) {
1244 mod["constraint"] << nf.constraint->GetName();
1245 tool->queueExport(*nf.constraint);
1246 }
1247 }
1248
1249 for (const auto &sys : sample.normsys) {
1250 auto &mod = modifiers.append_child();
1251 mod.set_map();
1252 mod["name"] << sys.name;
1253 mod["type"] << "normsys";
1254 mod["parameter"] << sys.param->GetName();
1255 if (sys.interpolationCode != 4) {
1256 mod["interpolation"] << sys.interpolationCode;
1257 }
1258 writeConstraint(mod, sys);
1259 auto &data = mod["data"].set_map();
1260 data["lo"] << sys.low;
1261 data["hi"] << sys.high;
1262 }
1263
1264 for (const auto &sys : sample.histosys) {
1265 auto &mod = modifiers.append_child();
1266 mod.set_map();
1267 mod["name"] << sys.name;
1268 mod["type"] << "histosys";
1269 mod["parameter"] << sys.param->GetName();
1270 writeConstraint(mod, sys);
1271 auto &data = mod["data"].set_map();
1272 if (channel.nBins != sys.low.size() || channel.nBins != sys.high.size()) {
1273 std::stringstream ss;
1274 ss << "inconsistent binning: " << channel.nBins << " bins expected, but " << sys.low.size() << "/"
1275 << sys.high.size() << " found in nominal histogram errors!";
1276 RooJSONFactoryWSTool::error(ss.str().c_str());
1277 }
1278 RooJSONFactoryWSTool::exportArray(channel.nBins, sys.low.data(), data["lo"].set_map()["contents"]);
1279 RooJSONFactoryWSTool::exportArray(channel.nBins, sys.high.data(), data["hi"].set_map()["contents"]);
1280 }
1281
1282 for (const auto &sys : sample.shapesys) {
1283 auto &mod = modifiers.append_child();
1284 mod.set_map();
1285 mod["name"] << sys.name;
1286 mod["type"] << "shapesys";
1287 optionallyExportGammaParameters(mod, sys.name, sys.parameters);
1288 if (std::any_of(sys.constraintPdfs.begin(), sys.constraintPdfs.end(),
1289 [](auto *pdf) { return pdf != nullptr; })) {
1290 auto &constraintNames = mod["constraints"].set_seq();
1291 for (auto *constraint : sys.constraintPdfs) {
1292 if (constraint) {
1293 constraintNames.append_child() << constraint->GetName();
1294 } else {
1295 constraintNames.append_child().set_null();
1296 }
1297 }
1298 }
1299 mod["data"].set_map()["vals"].fill_seq(sys.constraints);
1300 }
1301
1302 for (const auto &other : sample.otherElements) {
1303 auto &mod = modifiers.append_child();
1304 mod.set_map();
1305 mod["name"] << other.name;
1306 mod["type"] << "custom";
1307 }
1308 for (const auto &other : sample.tmpElements) {
1309 auto &mod = modifiers.append_child();
1310 mod.set_map();
1311 mod["name"] << other.name;
1312 mod["type"] << "custom";
1313 }
1314
1315 if (sample.useBarlowBeestonLight) {
1316 auto &mod = modifiers.append_child();
1317 mod.set_map();
1318 mod["name"] << ::Literals::staterror;
1319 mod["type"] << ::Literals::staterror;
1320 optionallyExportGammaParameters(mod, "stat_" + channel.name, sample.staterrorParameters);
1321 }
1322
1323 if (!observablesWritten) {
1324 auto &output = elem["axes"].set_seq();
1325 for (auto *obs : static_range_cast<RooRealVar *>(*channel.varSet)) {
1326 RooJSONFactoryWSTool::exportAxis(output.append_child().set_map(), *obs);
1327 }
1328 observablesWritten = true;
1329 }
1330 auto &dataNode = s["data"].set_map();
1331 if (channel.nBins != sample.hist.size()) {
1332 std::stringstream ss;
1333 ss << "inconsistent binning: " << channel.nBins << " bins expected, but " << sample.hist.size()
1334 << " found in nominal histogram!";
1335 RooJSONFactoryWSTool::error(ss.str().c_str());
1336 }
1337 RooJSONFactoryWSTool::exportArray(channel.nBins, sample.hist.data(), dataNode["contents"]);
1338 if (!sample.histError.empty()) {
1339 if (channel.nBins != sample.histError.size()) {
1340 std::stringstream ss;
1341 ss << "inconsistent binning: " << channel.nBins << " bins expected, but " << sample.histError.size()
1342 << " found in nominal histogram errors!";
1343 RooJSONFactoryWSTool::error(ss.str().c_str());
1344 }
1345 RooJSONFactoryWSTool::exportArray(channel.nBins, sample.histError.data(), dataNode["errors"]);
1346 }
1347 }
1348
1349 return true;
1350}
1351
1352std::vector<RooAbsPdf *> findLostConstraints(const Channel &channel, const std::vector<RooAbsPdf *> &constraints)
1353{
1354 // collect all the vars that are used by the model
1355 std::set<const RooAbsReal *> vars;
1356 for (const auto &sample : channel.samples) {
1357 for (const auto &nf : sample.normfactors) {
1358 vars.insert(nf.param);
1359 }
1360 for (const auto &sys : sample.normsys) {
1361 vars.insert(sys.param);
1362 }
1363
1364 for (const auto &sys : sample.histosys) {
1365 vars.insert(sys.param);
1366 }
1367 for (const auto &sys : sample.shapesys) {
1368 for (const auto &par : sys.parameters) {
1369 vars.insert(par);
1370 }
1371 }
1372 if (sample.useBarlowBeestonLight) {
1373 for (const auto &par : sample.staterrorParameters) {
1374 vars.insert(par);
1375 }
1376 }
1377 }
1378
1379 // check if there is any constraint present that is unrelated to these vars
1380 std::vector<RooAbsPdf *> lostConstraints;
1381 for (auto *pdf : constraints) {
1382 bool related = false;
1383 for (const auto *var : vars) {
1384 if (pdf->dependsOn(*var)) {
1385 related = true;
1386 }
1387 }
1388 if (!related) {
1389 lostConstraints.push_back(pdf);
1390 }
1391 }
1392 // return the constraints that would be "lost" when exporting the model
1393 return lostConstraints;
1394}
1395
1397 std::vector<RooAbsPdf *> constraints, JSONNode &elem)
1398{
1399 // some preliminary checks
1400 if (!sumpdf) {
1401 if (verbose) {
1402 std::cout << pdfname << " is not a sumpdf" << std::endl;
1403 }
1404 return false;
1405 }
1406
1407 for (RooAbsArg *sample : sumpdf->funcList()) {
1408 if (!dynamic_cast<RooProduct *>(sample) && !dynamic_cast<RooRealSumPdf *>(sample)) {
1409 if (verbose)
1410 std::cout << "sample " << sample->GetName() << " is no RooProduct or RooRealSumPdf in " << pdfname
1411 << std::endl;
1412 return false;
1413 }
1414 }
1415
1416 auto channel = readChannel(tool, pdfname, sumpdf);
1417
1418 // sanity checks
1419 if (channel.samples.size() == 0)
1420 return false;
1421 for (auto &sample : channel.samples) {
1422 if (sample.hist.empty()) {
1423 return false;
1424 }
1425 }
1426
1427 // stat error handling
1428 configureStatError(channel);
1429
1430 auto lostConstraints = findLostConstraints(channel, constraints);
1431 // Export all the lost constraints
1432 for (const auto *constraint : lostConstraints) {
1434 "losing constraint term '" + std::string(constraint->GetName()) +
1435 "', implicit constraints are not supported by HS3 yet! The term will appear in the HS3 file, but will not be "
1436 "picked up when creating a likelihood from it! You will have to add it manually as an external constraint.");
1437 tool->queueExport(*constraint);
1438 }
1439
1440 // Export all the regular modifiers
1441 for (const auto &sample : channel.samples) {
1442 for (auto &modifier : sample.normfactors) {
1443 if (modifier.constraint) {
1444 tool->queueExport(*modifier.constraint);
1445 }
1446 }
1447 for (auto &modifier : sample.normsys) {
1448 if (modifier.constraint) {
1449 tool->queueExport(*modifier.constraint);
1450 }
1451 }
1452 for (auto &modifier : sample.histosys) {
1453 if (modifier.constraint) {
1454 tool->queueExport(*modifier.constraint);
1455 }
1456 }
1457 for (auto &modifier : sample.shapesys) {
1458 for (auto *constraint : modifier.constraintPdfs) {
1459 if (constraint) {
1460 tool->queueExport(*constraint);
1461 }
1462 }
1463 }
1464 }
1465
1466 // Export all the custom modifiers
1467 for (const auto &sample : channel.samples) {
1468 for (auto &modifier : sample.otherElements) {
1469 tool->queueExport(*modifier.function);
1470 }
1471 for (auto &modifier : sample.tmpElements) {
1472 tool->queueExportTemporary(modifier.function);
1473 }
1474 }
1475
1476 // Export all model parameters
1477 RooArgSet parameters;
1478 sumpdf->getParameters(channel.varSet, parameters);
1479 for (RooAbsArg *param : parameters) {
1480 // This should exclude the global observables
1481 if (!startsWith(std::string{param->GetName()}, "nom_")) {
1482 tool->queueExport(*param);
1483 }
1484 }
1485
1486 return exportChannel(tool, channel, elem);
1487}
1488
1489class HistFactoryStreamer_ProdPdf : public RooFit::JSONIO::Exporter {
1490public:
1491 bool autoExportDependants() const override { return false; }
1493 {
1494 std::vector<RooAbsPdf *> constraints;
1495 RooRealSumPdf *sumpdf = nullptr;
1496 for (auto *pdf : static_range_cast<RooAbsPdf *>(prodpdf->pdfList())) {
1497 auto thispdf = dynamic_cast<RooRealSumPdf *>(pdf);
1498 if (thispdf) {
1499 if (!sumpdf)
1500 sumpdf = thispdf;
1501 else
1502 return false;
1503 } else {
1504 constraints.push_back(pdf);
1505 }
1506 }
1507 if (!sumpdf)
1508 return false;
1509
1510 bool ok = tryExportHistFactory(tool, prodpdf->GetName(), sumpdf, constraints, elem);
1511 return ok;
1512 }
1513 std::string const &key() const override
1514 {
1515 static const std::string keystring = "histfactory_dist";
1516 return keystring;
1517 }
1518 bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *p, JSONNode &elem) const override
1519 {
1520 return tryExport(tool, static_cast<const RooProdPdf *>(p), elem);
1521 }
1522};
1523
1524class HistFactoryStreamer_SumPdf : public RooFit::JSONIO::Exporter {
1525public:
1526 bool autoExportDependants() const override { return false; }
1528 {
1529 std::vector<RooAbsPdf *> constraints;
1530 return tryExportHistFactory(tool, sumpdf->GetName(), sumpdf, constraints, elem);
1531 }
1532 std::string const &key() const override
1533 {
1534 static const std::string keystring = "histfactory_dist";
1535 return keystring;
1536 }
1537 bool exportObject(RooJSONFactoryWSTool *tool, const RooAbsArg *p, JSONNode &elem) const override
1538 {
1539 return tryExport(tool, static_cast<const RooRealSumPdf *>(p), elem);
1540 }
1541};
1542
1543STATIC_EXECUTE([]() {
1544 using namespace RooFit::JSONIO;
1545
1546 registerImporter<HistFactoryImporter>("histfactory_dist", true);
1548 registerImporter<FlexibleInterpVarFactory>("interpolation0d", true);
1553});
1554
1555} // namespace
bool startsWith(std::string_view str, std::string_view prefix)
bool endsWith(std::string_view str, std::string_view suffix)
#define d(i)
Definition RSha256.hxx:102
#define c(i)
Definition RSha256.hxx:101
#define g(i)
Definition RSha256.hxx:105
#define h(i)
Definition RSha256.hxx:106
#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
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void 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
char name[80]
Definition TGX11.cxx:148
#define hi
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
The PiecewiseInterpolation is a class that can morph distributions into each other,...
static TClass * Class()
void setPositiveDefinite(bool flag=true)
const_iterator begin() const
const_iterator end() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:76
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.
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:283
Abstract container object that can hold multiple RooAbsArg objects.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
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
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:31
When using RooFit, statistical models can be conveniently handled and stored as a RooWorkspace.
static void fillSeq(RooFit::Detail::JSONNode &node, RooAbsCollection const &coll, size_t nMax=-1)
static std::unique_ptr< RooDataHist > readBinnedData(const RooFit::Detail::JSONNode &n, const std::string &namecomp, RooArgSet const &vars)
Read binned data from the JSONNode and create a RooDataHist object.
static RooFit::Detail::JSONNode & appendNamedChild(RooFit::Detail::JSONNode &node, std::string const &name)
static void exportArray(std::size_t n, double const *contents, RooFit::Detail::JSONNode &output)
Export an array of doubles to a JSONNode.
static void exportAxis(RooFit::Detail::JSONNode &obsNode, RooRealVar const &var)
Export the name and binning of a RooRealVar to a JSONNode.
static void error(const char *s)
Writes an error message to the RooFit message service and throws a runtime_error.
static std::string name(const RooFit::Detail::JSONNode &n)
static std::ostream & warning(const std::string &s)
Writes a warning message to the RooFit message service.
static RooArgSet readAxes(const RooFit::Detail::JSONNode &node)
Read axes from the JSONNode and create a RooArgSet representing them.
RooFit Lognormal PDF.
Poisson pdf.
Definition RooPoisson.h:19
RooAbsReal const & getMean() const
Get the mean parameter.
Definition RooPoisson.h:48
Efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:36
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:
static TClass * Class()
Variable that can be changed from the outside.
Definition RooRealVar.h:37
void setError(double value)
Definition RooRealVar.h:61
This class encapsulates all information for the statistical interpretation of one experiment.
Configuration for a constrained, coherent shape variation of affected samples.
Configuration for an un- constrained overall systematic to scale sample normalisations.
Definition Measurement.h:60
Constrained bin-by-bin variation of affected histogram.
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.
RooAbsReal * function(RooStringView name) const
Retrieve function (RooAbsReal) with given name. Note that all RooAbsPdfs are also RooAbsReals....
RooFactoryWSTool & factory()
Return instance to factory tool.
bool import(const RooAbsArg &arg, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}, const RooCmdArg &arg9={})
Import a RooAbsArg object, e.g.
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
Basic string class.
Definition TString.h:138
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:643
RooCmdArg RecycleConflictNodes(bool flag=true)
RooCmdArg Conditional(const RooArgSet &pdfSet, const RooArgSet &depSet, bool depsAreCond=false)
const Int_t n
Definition legend1.C:16
double gamma(double x)
void configureConstrainedGammas(RooArgList const &gammas, std::span< const double > relSigmas, double minSigma)
Configure constrained gamma parameters for fitting.
CreateGammaConstraintsOutput createGammaConstraints(RooArgList const &paramList, std::span< const double > relSigmas, double minSigma, Constraint::Type type)
#define STATIC_EXECUTE(MY_FUNC)
TLine l
Definition textangle.C:4
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2338