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