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