65double round_prec(
double d,
int nSig)
69 int ndigits = std::floor(std::log10(std::abs(
d))) + 1 - nSig;
70 double sf = std::pow(10, ndigits);
71 if (std::abs(
d / sf) < 2)
73 return sf * std::round(
d / sf);
77std::string interpolationString(
const Interpolation &interpolation)
82 tree->rootnode().writeJSON(ss);
86const char *interpolationClassName(InterpolationClass interpolationClass)
88 return interpolationClass == InterpolationClass::Piecewise ?
"PiecewiseInterpolation" :
"FlexibleInterpVar";
94 return *interpolation;
97 std::to_string(code));
101 const std::string &context)
107 interpolationClassName(interpolationClass));
111std::vector<Interpolation>
112toInterpolations(std::vector<int>
const &codes, InterpolationClass interpolationClass, std::string
const &context)
114 std::vector<Interpolation> out;
115 out.reserve(codes.size());
116 for (std::size_t i = 0; i < codes.size(); ++i) {
118 interpolationFromCode(codes[i], interpolationClass, context +
" at parameter index " + std::to_string(i)));
123std::vector<int> toCodes(std::vector<Interpolation>
const &interpolations, InterpolationClass interpolationClass,
124 std::string
const &context)
126 std::vector<int> out;
127 out.reserve(interpolations.size());
128 for (std::size_t i = 0; i < interpolations.size(); ++i) {
130 context +
" component 'interpolations' at index " + std::to_string(i)));
135void erasePrefix(std::string &str, std::string_view prefix)
138 str.erase(0, prefix.size());
142bool eraseSuffix(std::string &str, std::string_view suffix)
145 str.erase(str.size() - suffix.size());
153void sortByName(Coll &coll)
155 std::sort(coll.begin(), coll.end(), [](
auto &
l,
auto &
r) { return l.name < r.name; });
161 return std::any_of(constraints.
pdfs.begin(), constraints.
pdfs.end(),
162 [](
auto const &pdf) { return pdf.has_value(); });
168 for (
const auto &client :
gamma->clients()) {
169 if (
auto casted =
dynamic_cast<T *
>(client)) {
172 if (T *found = findClient<T>(client)) {
180T *findAmong(
RooAbsArg *
g, std::vector<RooAbsPdf *>
const &pdfs)
183 if (
auto casted =
dynamic_cast<T *
>(pdf); casted && casted->dependsOn(*
g)) {
197 if (
auto *constraint = findAmong<RooPoisson>(
g, channelConstraints))
199 if (
auto *constraint = findAmong<RooGaussian>(
g, channelConstraints))
201 if (
auto *constraint = findAmong<RooLognormal>(
g, channelConstraints))
203 if (
auto *constraint = findClient<RooPoisson>(
g))
205 if (
auto *constraint = findClient<RooGaussian>(
g))
207 return findClient<RooLognormal>(
g);
212 RooRealVar &nom = getOrCreate<RooRealVar>(ws,
"nom_" + parname, val, -10, 10);
219std::string constraintName(std::string
const ¶mName)
221 return paramName +
"Constraint";
227 std::vector<RooAbsPdf *> matches;
229 if (pdf->dependsOn(param)) {
230 matches.push_back(pdf);
233 if (matches.size() == 1) {
234 return *matches.front();
236 const std::string
what =
"the array distribution '" + std::string(array.
GetName()) +
237 "' named as the constraint of '" + param.
GetName() +
"' (" + context +
") has ";
238 if (matches.empty()) {
242 " components that depend on this parameter, but a parameter can only be constrained "
250 std::string
const &context)
256 auto const *array =
dynamic_cast<RooProdPdf const *
>(constraint);
263 double max, std::string
const &
modifier)
268 return getOrCreate<RooRealVar>(ws,
name, val, min, max);
274 "' is neither a variable nor a constant");
277void setErrorIfVariable(
RooAbsReal ¶m,
double error)
279 if (
auto *var =
dynamic_cast<RooRealVar *
>(¶m)) {
280 var->setError(error);
287 const char *modifierType, std::string
const &
modifier, std::string
const &sample,
296 setErrorIfVariable(param, 1.0);
297 const std::string
name = constraintName(param.
GetName());
302 RooAbsPdf &pdf = findNamedConstraint(tool, constraintPdf.pdf.name, param,
303 std::string(
"the ") + modifierType +
" modifier '" +
modifier +
304 "' of sample '" + sample +
"'");
305 if (
auto gauss =
dynamic_cast<RooGaussian *
>(&pdf)) {
306 setErrorIfVariable(param, gauss->getSigma().getVal());
308 constraints.
add(pdf);
318 const char *modifierType, std::string
const &
modifier, std::string
const &sample,
321 auto const *pdf = std::get_if<HS3::ConstraintPdf>(&constraint);
322 if (pdf && pdf->legacyName) {
325 addConstraint(tool, constraint, param, 0.0, modifierType,
modifier, sample, constraints);
339 auto const *tau =
dynamic_cast<RooAbsReal const *
>(arg);
340 if (tau && arg != &gamma && (tau->isConstant() ||
endsWith(tau->GetName(),
"_tau"))) {
351std::optional<double> gammaRelUncertainty(
RooAbsPdf const &constraint,
RooAbsArg const &gamma)
353 if (
auto gauss =
dynamic_cast<RooGaussian const *
>(&constraint)) {
354 return gauss->getSigma().getVal();
356 if (
auto poisson =
dynamic_cast<RooPoisson const *
>(&constraint)) {
357 if (
auto tau = findPoissonTau(*poisson, gamma)) {
358 return 1. / std::sqrt(*tau);
369void configureGammasWithConstraints(
RooArgList const &gammas, std::vector<double>
const &relSigmas,
370 std::vector<RooAbsPdf *>
const &constraintPdfs,
double minSigma)
373 std::vector<double> constrainedSigmas;
374 for (std::size_t i = 0; i < gammas.
size(); ++i) {
376 if (!constraintPdfs[i] || !gamma) {
379 std::optional<double> relSigma = !relSigmas.empty() && relSigmas[i] > 0.
380 ? std::make_optional(relSigmas[i])
381 : gammaRelUncertainty(*constraintPdfs[i], *
gamma);
386 if (relSigmas.empty()) {
387 gamma->setError(*relSigma);
389 constrainedGammas.
add(*gamma);
390 constrainedSigmas.push_back(*relSigma);
399 std::vector<HS3::ParameterRef>
const &parnames, std::vector<double>
const &vals,
401 double gammaMax,
double minSigma, std::size_t nBins, std::string
const &context,
402 bool configureGammas =
true)
408 for (std::size_t i = 0; i < nBins; ++i) {
409 const std::string
name = parnames.empty() ?
"gamma_" + sysname +
"_bin_" + std::to_string(i) : parnames[i].
name;
422 if (!existingPHF || existingPHF->paramList().size() != gammasInTH1Order.
size() ||
423 !existingPHF->paramList().hasSameLayout(gammasInTH1Order)) {
425 "of this name in the channel");
436 if (
auto const *pdfs = std::get_if<HS3::GammaConstraintPdfs>(&constraint)) {
439 std::vector<RooAbsPdf *> constraintPdfs;
440 for (std::size_t i = 0; i < pdfs->pdfs.size(); ++i) {
441 auto const &pdfName = pdfs->pdfs[i];
442 RooAbsPdf *pdf = pdfName ? &findNamedConstraint(tool, pdfName->name, gammas[i], context) : nullptr;
444 constraints.
add(*pdf);
446 constraintPdfs.push_back(pdf);
450 configureGammasWithConstraints(gammas, configureGammas ? vals : std::vector<
double>{}, constraintPdfs, minSigma);
464 if (
auto *var =
dynamic_cast<RooRealVar *
>(gamma)) {
465 var->setConstant(
true);
473 case HS3::ConstraintType::LogNormal:
475 "' for the gamma parameters of '" + sysname +
476 "', supported are \"Poisson\" and \"Gauss\"");
489 if (
auto relSigma = gammaRelUncertainty(constraint, gamma)) {
494 "': only RooGaussian and RooPoisson with mean gamma * tau are supported for the "
495 "relative uncertainties of gammas");
498struct ChannelContext {
508void buildSample(ChannelContext
const &ctx,
HS3::Sample const &sample)
513 std::string
const &sampleName = sample.
name;
514 std::string prefixedName = ctx.fprefix +
"_" + sampleName;
517 auto newName = [&](std::string
name) {
520 ctx.channelName +
"' has the name of an existing object");
527 auto &hf = tool.
wsEmplace<
RooHistFunc>(newName(
"hist_" + prefixedName), ctx.observables, *dataHist);
535 std::vector<double> overallLow;
536 std::vector<double> overallHigh;
537 std::vector<int> overallInterp;
542 std::vector<int> histoInterp;
543 std::map<std::string, int> histoSysCount;
547 const bool hasStatError = std::any_of(sample.
modifiers.begin(), sample.
modifiers.end(),
548 [](
auto const &
m) { return std::holds_alternative<HS3::StatError>(m); });
550 shapeElems.
add(*ctx.mcStatObject);
554 auto interpolationCode = [&](std::optional<Interpolation>
const &interpolation,
555 InterpolationClass interpolationClass,
const char *
type, std::string
const &
name) {
558 std::string(
"interpolation for ") +
type +
" modifier '" +
name +
"' in sample '" +
559 sampleName +
"' of channel '" + ctx.
channelName +
"'");
567 RooAbsReal ¶m = getOrCreateParameter(tool, mod.parameter.name, 1., -3, 5, mod.name);
573 normElems.
add(param);
574 addConstraint(tool, mod.constraint, param, 1.0,
"normfactor", mod.name, sampleName, ctx.constraints);
577 RooAbsReal ¶m = getOrCreateParameter(tool, mod.parameter.name, 0., -5, 5, mod.name);
578 overallNps.
add(param);
580 interpolationCode(mod.interpolation, InterpolationClass::Flexible,
"normsys", mod.name);
583 auto cutOff = [&](
double variation) {
584 return interp == 4 && variation <= 0 ? std::numeric_limits<double>::epsilon() : variation;
586 overallLow.push_back(cutOff(mod.lo));
587 overallHigh.push_back(cutOff(mod.hi));
588 overallInterp.push_back(interp);
590 addSysConstraint(tool, mod.constraint, param,
"normsys", mod.name, sampleName, ctx.constraints);
593 RooAbsReal ¶m = getOrCreateParameter(tool, mod.parameter.name, 0., -5, 5, mod.name);
597 const int count = ++histoSysCount[mod.name];
598 const std::string objName = count == 1 ? mod.name : mod.name +
"_" + std::to_string(count);
600 const std::string
name = newName(objName + suffix + prefixedName);
604 variation.errors ? &*variation.errors : nullptr)));
606 addVariation(histoLo, mod.lo,
"Low_");
607 addVariation(histoHi, mod.hi,
"High_");
608 histoInterp.push_back(
609 interpolationCode(mod.interpolation, InterpolationClass::Piecewise,
"histosys", mod.name));
610 addSysConstraint(tool, mod.constraint, param,
"histosys", mod.name, sampleName, ctx.constraints);
613 const bool constrained = std::visit(
620 const std::string funcName =
621 ctx.channelName +
"_" + mod.name + (constrained ?
"_ShapeSys" :
"_shapeFactor");
622 shapeElems.
add(createPHF(tool, funcName, mod.name, mod.parameters, mod.vals, mod.constraint,
625 "the shapesys modifier '" + mod.name +
"' of sample '" + sampleName +
"'"));
631 shapeElems.
add(*obj);
640 if (!overallNps.
empty()) {
641 std::string interpName = newName(sampleName +
"_" + ctx.channelName +
"_epsilon");
643 overallHigh, overallInterp));
645 if (!histNps.
empty()) {
647 histNps, histoInterp);
655 if (!normElems.
empty()) {
658 ws.
factory(
"RooConstVar::" + newName(prefixedName +
"_scaleFactors") +
"(1.)");
668 for (
auto const &sample :
dist.samples) {
669 for (
auto const &
modifier : sample.modifiers) {
670 auto const *statError = std::get_if<HS3::StatError>(&
modifier);
674 if (std::holds_alternative<HS3::GammaConstraintPdfs>(statError->constraint)) {
675 return statError->constraint;
677 if (!modifierConstraint && !std::holds_alternative<HS3::Unconstrained>(statError->constraint)) {
678 modifierConstraint = &statError->constraint;
682 return modifierConstraint ? *modifierConstraint :
dist.statError.constraint;
696 std::stringstream ss;
715 const std::string context =
"FlexibleInterpVar '" + std::string{fip.
GetName()} +
"'";
717 if (fip.
low().size() != nParameters || fip.
high().size() != nParameters ||
734 const std::string context =
"PiecewiseInterpolation '" + std::string{pip.
GetName()} +
"'";
742 for (std::size_t i = 0; i < nParameters; ++i) {
759 auto request = [&](std::vector<HS3::NameOrNumber>
const &refs) {
761 for (
auto const &ref : refs) {
762 auto const *
value = std::get_if<double>(&ref);
772 toCodes(in.
interpolations, InterpolationClass::Piecewise,
"PiecewiseInterpolation '" +
name +
"'"));
784 for (std::string
const &var : in.parameters) {
789 toCodes(in.
interpolations, InterpolationClass::Flexible,
"FlexibleInterpVar '" +
name +
"'"));
792std::string stripOuterParens(
const std::string &s)
795 size_t end = s.size();
798 auto enclosesAll = [&]() {
800 for (
size_t i = start; i < end - 1; ++i) {
803 }
else if (s[i] ==
')') {
812 while (start < end && s[start] ==
'(' && s[end - 1] ==
')' && enclosesAll()) {
816 return s.substr(start, end - start);
821bool isBinaryOperator(
const std::string &expr, std::size_t i)
824 while (j > 0 && std::isspace(
static_cast<unsigned char>(expr[j - 1]))) {
830 const char prev = expr[j - 1];
831 if (prev ==
'e' || prev ==
'E') {
833 std::size_t k = j - 1;
834 while (k > 0 && (std::isdigit(
static_cast<unsigned char>(expr[k - 1])) || expr[k - 1] ==
'.')) {
837 const bool startsName = k > 0 && (std::isalpha(
static_cast<unsigned char>(expr[k - 1])) || expr[k - 1] ==
'_');
838 if (k < j - 1 && !startsName && i == j) {
842 return std::isalnum(
static_cast<unsigned char>(prev)) || prev ==
'_' || prev ==
'.' || prev ==
')' || prev ==
']';
845std::vector<std::string> splitTopLevelProduct(
const std::string &expr)
847 std::vector<std::string> parts;
851 for (
size_t i = 0; i < expr.size(); ++i) {
855 }
else if (
c ==
')') {
857 }
else if ((
c ==
'+' ||
c ==
'-') && depth == 0 && isBinaryOperator(expr, i)) {
859 }
else if (
c ==
'*' && depth == 0) {
860 parts.push_back(stripOuterParens(expr.substr(start, i - start)));
869 parts.push_back(stripOuterParens(expr.substr(start)));
875void collectConstraintTerms(
RooAbsPdf *pdf, std::vector<RooAbsPdf *> &terms)
877 if (
auto prod =
dynamic_cast<RooProdPdf *
>(pdf)) {
879 collectConstraintTerms(factor, terms);
882 terms.push_back(pdf);
887struct FormulaNormSys {
893std::optional<FormulaNormSys> parseOverallModifierFormula(
const std::string &s,
RooFormulaVar *formula,
894 std::vector<RooAbsPdf *>
const &channelConstraints)
896 static const std::regex pattern(
897 R
"(^\s*1(?:\.0)?\s*([\+\-])\s*([a-zA-Z_][a-zA-Z0-9_]*|[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)\s*\*\s*([a-zA-Z_][a-zA-Z0-9_]*|[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?)\s*$)");
900 if (!std::regex_match(s, match, pattern)) {
909 if (!constraintA == !constraintB) {
913 const double sign = match[1].str() ==
"-" ? -1.0 : 1.0;
914 const double variation = sign * (other ? other->
getVal() :
toDouble(match[constraintA ? 4 : 2].str()));
915 return FormulaNormSys{constraintA ?
a :
b, constraintA ? constraintA : constraintB, variation};
920 if (
auto prod =
dynamic_cast<RooProduct *
>(arg)) {
921 for (
const auto &
e : prod->components()) {
922 collectElements(elems,
e);
931 return std::all_of(list.begin(), list.end(), [](
RooAbsArg *arg) { return dynamic_cast<RooRealVar *>(arg); });
934std::vector<double> contents(
RooDataHist const &dataHist)
940struct ExportedChannel {
944 bool decomposedFormulas =
false;
946 std::unique_ptr<RooArgSet> observables;
947 std::size_t nBins = 0;
949 std::map<std::string, RooAbsPdf const *> constraints;
950 std::vector<RooAbsReal *> customModifiers;
952 std::vector<std::unique_ptr<RooAbsReal>> temporaries;
954 std::map<std::size_t, double> totYield;
955 std::map<std::size_t, double> totYield2;
956 std::map<std::size_t, double> relErrors;
958 std::set<RooAbsArg const *> legacyBinWidthFactors;
963std::vector<double> binVolumes(
RooArgSet const &channelNodes)
965 std::vector<double> out;
967 auto *hf =
dynamic_cast<RooHistFunc const *
>(node);
968 if (!hf || hf->dataHist().numEntries() == 0) {
971 out.push_back(hf->dataHist().binVolume(0));
974 if (
auto *real =
dynamic_cast<RooRealVar const *
>(obs)) {
975 average *= (real->getMax() - real->getMin()) / real->numBins();
978 out.push_back(average);
990 std::vector<double>
const &volumes,
RooWorkspace const &ws)
995 auto const *var =
dynamic_cast<RooRealVar const *
>(&factor);
996 if (!
dynamic_cast<RooConstVar const *
>(&factor) && !(var && var->isConstant())) {
1001 auto const *inSnapshot =
dynamic_cast<RooRealVar const *
>(snapshot->find(*var));
1002 if (inSnapshot && !inSnapshot->isConstant()) {
1010 auto isOriginalOfChannelNode = [&](
RooAbsArg const &client) {
1011 const std::string attribute = std::string{
"ORIGNAME:"} + client.
GetName();
1012 return std::any_of(channelNodes.
begin(), channelNodes.
end(),
1013 [&](
RooAbsArg const *node) { return node->getAttribute(attribute.c_str()); });
1015 for (
RooAbsArg const *client : factor.clients()) {
1016 const bool isChannelProduct =
dynamic_cast<RooProduct const *
>(client) && channelNodes.
find(*client) == client;
1017 if (client == &sumpdf || isChannelProduct || isOriginalOfChannelNode(*client)) {
1022 if (ws.
arg(client->GetName()) != client) {
1028 const double value =
static_cast<RooAbsReal const &
>(factor).getVal();
1029 return std::any_of(volumes.begin(), volumes.end(),
1030 [&](
double volume) { return volume > 0. && std::abs(value * volume - 1.) < 1e-6; });
1036bool isShapeModifierFunction(
ParamHistFunc const &phf, ExportedChannel
const &channel)
1038 return channel.observables && phf.
paramList().
size() == channel.nBins &&
1039 static_cast<std::size_t
>(phf.
numBins()) == channel.nBins && phf.
dataVars().
equals(*channel.observables);
1045 std::vector<RooAbsPdf *>
const &channelConstraints,
bool decomposeFormulas =
true)
1047 ExportedChannel channel;
1051 channel.name = pdfname;
1052 erasePrefix(channel.name,
"model_");
1053 eraseSuffix(channel.name,
"_model");
1057 const std::vector<double> volumes = binVolumes(channelNodes);
1061 auto constraintTerm = [&](
RooAbsPdf const *pdf) -> std::optional<HS3::DistributionRef> {
1062 if (std::find(channelConstraints.begin(), channelConstraints.end(), pdf) == channelConstraints.end()) {
1063 return std::nullopt;
1065 channel.constraints.emplace(pdf->
GetName(), pdf);
1069 auto ref = constraintTerm(pdf);
1073 for (
size_t sampleidx = 0; sampleidx < sumpdf->
funcList().
size(); ++sampleidx) {
1075 std::vector<ParamHistFunc *> phfs;
1077 const auto func = sumpdf->
funcList().
at(sampleidx);
1079 sample.
name = func->GetName();
1080 erasePrefix(sample.
name,
"L_x_");
1081 eraseSuffix(sample.
name,
"_shapes");
1082 eraseSuffix(sample.
name,
"_" + channel.name);
1083 erasePrefix(sample.
name, pdfname +
"_");
1086 std::vector<HS3::NormFactor> normFactors;
1087 std::vector<HS3::NormSys> normSys;
1088 std::vector<HS3::HistoSys> histoSys;
1089 std::vector<HS3::ShapeSys> shapeSys;
1090 std::vector<HS3::CustomModifier> custom;
1091 std::vector<HS3::CustomModifier> temporaries;
1092 std::optional<HS3::StatError> statError;
1096 std::string sysname(param.
GetName());
1097 erasePrefix(sysname,
"alpha_");
1098 normSys.push_back({sysname, {param.
GetName()},
hi, lo, constraint(pdf), interpolation});
1101 auto updateObservables = [&](
RooHistFunc const &histFunc) {
1102 RooDataHist const &dataHist = histFunc.dataHist();
1107 if (channel.observables ==
nullptr) {
1108 channel.observables = std::move(varsPtr);
1113 if (varsPtr->size() != channel.observables->size() || !varsPtr->hasSameLayout(*channel.observables)) {
1115 "' don't have their observables in the same order, so their bin "
1116 "contents can't be written along the same axes");
1120 sample.
contents = contents(dataHist);
1123 auto processElements = [&](
const auto &elements,
auto &&self) ->
void {
1127 }
else if (isLegacyBinWidthFactor(*
e, *sumpdf, channelNodes, volumes, ws)) {
1129 channel.legacyBinWidthFactors.insert(
e);
1131 oocoutW(
nullptr, ObjectHandling)
1132 <<
"RooFitHS3: the constant factor '" <<
e->GetName() <<
"' of sample '" << sample.
name
1133 <<
"' in channel '" << channel.name
1134 <<
"' is used like the inverse bin width of HistFactory before ROOT 6.26 (its value is the "
1135 "inverse bin volume), so it is not written: histfactory_dist implies it. Set "
1136 "RooJSONFactoryWSTool::config().identifyLegacyBinWidthFactors = false to write such factors "
1140 }
else if (
auto constVar =
dynamic_cast<RooConstVar *
>(
e)) {
1141 if (constVar->getVal() != 1.) {
1142 normFactors.push_back({constVar->GetName(), {constVar->GetName()},
HS3::Unconstrained{}});
1144 }
else if (
auto par =
dynamic_cast<RooRealVar *
>(
e)) {
1147 normFactors.push_back(
1148 {par->GetName(), {par->GetName()}, constraint(findConstraint(par, channelConstraints))});
1149 }
else if (
auto hf =
dynamic_cast<const RooHistFunc *
>(
e)) {
1150 updateObservables(*hf);
1152 phfs.push_back(phf);
1160 if (!inputs.
empty() && std::all_of(inputs.
begin(), inputs.
end(), isFunction)) {
1161 custom.push_back({fip->
GetName()});
1162 channel.customModifiers.push_back(fip);
1165 for (
size_t i = 0; i < inputs.
size(); ++i) {
1167 if (isFunction(var)) {
1168 custom.push_back({std::string(fip->
GetName()) +
"_" + var->
GetName()});
1169 channel.temporaries.push_back(std::make_unique<RooStats::HistFactory::FlexibleInterpVar>(
1170 custom.back().name.c_str(),
"",
RooArgList{*var}, 1., std::vector<double>{fip->low()[i]},
1171 std::vector<double>{fip->high()[i]}, std::vector<int>{fip->interpolationCodes()[i]}));
1174 std::string sysname(var->
GetName());
1175 erasePrefix(sysname,
"alpha_");
1176 const std::string context =
"normsys modifier '" + sysname +
"' in sample '" + sample.
name +
1177 "' of channel '" + channel.name +
"'";
1179 addNormSys(*var, fip->
high()[i], fip->
low()[i],
1181 findConstraint(var, channelConstraints));
1191 expression.ReplaceAll((
"x[" + std::to_string(i) +
"]").c_str(),
p->
GetName());
1192 expression.ReplaceAll((
"@" + std::to_string(i)).c_str(),
p->
GetName());
1194 std::vector<std::string> components;
1195 if (decomposeFormulas) {
1196 components = splitTopLevelProduct(expression.Data());
1198 channel.decomposedFormulas |= !components.empty();
1199 if (components.empty()) {
1201 custom.push_back({formula->
GetName()});
1202 channel.customModifiers.push_back(formula);
1205 std::vector<RooAbsArg *> realComponents;
1207 for (
auto &comp : components) {
1208 if (
auto *part = formula->
getParameter(comp.c_str())) {
1210 realComponents.push_back(part);
1211 }
else if (
auto sys = parseOverallModifierFormula(comp, formula, channelConstraints)) {
1214 addNormSys(*sys->param, 1.0 + sys->variation, 1.0 - sys->variation,
1215 multiplicativePiecewiseExponential, sys->constraint);
1218 std::string
name = std::string(formula->
GetName()) +
"_part" + std::to_string(idx++);
1219 temporaries.push_back({
name});
1220 channel.temporaries.push_back(std::make_unique<RooFormulaVar>(
1224 self(realComponents, self);
1226 }
else if (
auto real =
dynamic_cast<RooAbsReal *
>(
e)) {
1227 custom.push_back({real->GetName()});
1228 channel.customModifiers.push_back(real);
1234 collectElements(elems, func);
1235 collectElements(elems, sumpdf->
coefList().
at(sampleidx));
1236 processElements(elems, processElements);
1241 updateObservables(*nh);
1250 std::string sysname(var->
GetName());
1251 erasePrefix(sysname,
"alpha_");
1253 const auto *pdf = findConstraint(var, channelConstraints);
1256 ": functions are not supported as parameters of histosys modifiers");
1258 const std::string context =
1259 "histosys modifier '" + sysname +
"' in sample '" + sample.
name +
"' of channel '" + channel.name +
"'";
1263 {contents(
hi->dataHist()), std::nullopt},
1264 {contents(lo->dataHist()), std::nullopt},
1272 statError.emplace();
1273 statError->name =
"staterror";
1277 const std::size_t bin = statError->parameters.size();
1278 statError->parameters.push_back({
g->GetName()});
1279 RooAbsPdf *pdf = findConstraint(
g, channelConstraints);
1280 pdfs.
pdfs.push_back(constraintTerm(pdf));
1281 channel.totYield[bin] += sample.
contents[bin];
1284 channel.relErrors[bin] = constraintRelError(*pdf, *
g);
1287 if (anyNamed(pdfs)) {
1288 statError->constraint = std::move(pdfs);
1295 if (!isShapeModifierFunction(*phf, channel)) {
1296 if (channel.observables && phf->
dataVars().
overlaps(*channel.observables)) {
1298 "': it has another binning of the observables of channel '" +
1299 channel.name +
"'");
1301 custom.push_back({phf->
GetName()});
1302 channel.customModifiers.push_back(phf);
1307 erasePrefix(sys.name, channel.name +
"_");
1308 for (std::string_view suffix : {
"_ShapeSys",
"_shapeSys",
"_ShapeFactor",
"_shapeFactor"}) {
1309 if (eraseSuffix(sys.name, suffix))
1317 sys.parameters.push_back({
g->GetName()});
1318 RooAbsPdf *pdf = findConstraint(
g, channelConstraints);
1320 pdf = ws.
pdf(constraintName(
g->GetName()));
1321 pdfs.
pdfs.push_back(constraintTerm(pdf));
1323 if (anyNamed(pdfs)) {
1324 sys.constraint = std::move(pdfs);
1329 sortByName(normFactors);
1330 sortByName(normSys);
1331 sortByName(histoSys);
1332 sortByName(shapeSys);
1333 auto append = [&](
auto &modifiers) {
1334 sample.
modifiers.insert(sample.
modifiers.end(), std::make_move_iterator(modifiers.begin()),
1335 std::make_move_iterator(modifiers.end()));
1337 append(normFactors);
1342 append(temporaries);
1344 sample.
modifiers.push_back(std::move(*statError));
1347 channel.dist.
samples.push_back(std::move(sample));
1350 sortByName(channel.dist.
samples);
1356bool isValidChannel(ExportedChannel
const &channel, std::string
const &pdfname)
1358 if (!channel.observables) {
1373void configureStatError(ExportedChannel &channel)
1377 [](
auto const &
m) { return std::holds_alternative<HS3::StatError>(m); })) {
1380 std::vector<double> errors(sample.
contents.size());
1381 for (
auto const &bin : channel.relErrors) {
1382 const std::size_t i = bin.first;
1386 round_prec(bin.second * channel.totYield[i] / std::sqrt(channel.totYield2[i]) * sample.
contents[i], 7);
1388 sample.
errors = std::move(errors);
1396 auto const *prod =
dynamic_cast<RooProdPdf const *
>(&pdf);
1401 for (
RooAbsArg const *factor : prod->pdfList()) {
1402 if (
auto const *factorSum =
dynamic_cast<RooRealSumPdf const *
>(factor)) {
1421 const bool inArray = std::any_of(constraint.
clients().begin(), constraint.
clients().end(),
1422 [](
RooAbsArg const *client) { return client->getAttribute(arrayDistTag); });
1424 for (
TObject const *obj : tool.workspace()->allGenericObjects()) {
1426 if (mc && mc->GetExternalConstraints() && mc->GetExternalConstraints()->find(constraint.
GetName())) {
1431 for (
RooAbsArg const *client : constraint.clients()) {
1435 if (!client->getAttribute(
arrayDistTag) && !channelSum(*client)) {
1450 std::string arrayName;
1452 for (
RooAbsArg const *client : constraint.clients()) {
1454 arrayName = client->GetName();
1458 if (arrayName.empty()) {
1472std::vector<std::string> exportNamedConstraints(
RooJSONFactoryWSTool &tool, ExportedChannel &channel)
1474 std::map<std::string, std::string> writtenAs;
1475 std::vector<std::string> terms;
1477 auto rename = [&](std::string &
name, std::string
const ¶mName) {
1478 auto found = writtenAs.find(
name);
1479 if (found == writtenAs.end()) {
1480 RooAbsPdf const &constraint = *channel.constraints.at(
name);
1485 if (
auto const *gauss =
dynamic_cast<RooGaussian const *
>(&constraint); gauss && param) {
1486 RooAbsReal const &observable = gauss->getX().
dependsOn(*param) ? gauss->getMean() : gauss->getX();
1491 found = writtenAs.emplace(
name, exportConstraint(tool, constraint)).first;
1492 if (std::find(terms.begin(), terms.end(), found->second) == terms.end()) {
1493 terms.push_back(found->second);
1496 name = found->second;
1499 if (
auto *pdf = std::get_if<HS3::ConstraintPdf>(&constraint)) {
1500 rename(pdf->pdf.name, param.name);
1503 auto renameGammas = [&](
HS3::GammaConstraint &constraint, std::vector<HS3::ParameterRef>
const ¶ms) {
1504 if (
auto *pdfs = std::get_if<HS3::GammaConstraintPdfs>(&constraint)) {
1505 for (std::size_t i = 0; i < pdfs->
pdfs.size(); ++i) {
1506 if (
auto &pdf = pdfs->
pdfs[i]) {
1507 rename(pdf->name, params[i].name);
1515 [&](
HS3::NormSys &
m) { renameConstraint(
m.constraint,
m.parameter); },
1527 std::vector<RooAbsPdf *> constraints)
1534 for (
RooAbsArg *sample : sumpdf->funcList()) {
1540 ExportedChannel channel = readChannel(tool, pdfname, sumpdf, constraints);
1544 if (channel.decomposedFormulas && !isValidChannel(channel, pdfname)) {
1545 ExportedChannel plain = readChannel(tool, pdfname, sumpdf, constraints,
false);
1546 if (isValidChannel(plain, pdfname)) {
1547 channel = std::move(plain);
1553 if (
dist.samples.empty())
1555 for (
auto &sample :
dist.samples) {
1564 configureStatError(channel);
1576 for (
auto &
modifier : channel.temporaries) {
1582 sumpdf->
getParameters(channel.observables.get(), parameters);
1585 if (!
startsWith(param->
GetName(),
"nom_") && !channel.legacyBinWidthFactors.count(param)) {
1591 std::vector<HS3::DistributionRef> channelConstraintNames;
1592 for (
RooAbsPdf const *pdf : constraints) {
1593 if (!channel.constraints.count(pdf->
GetName())) {
1595 channelConstraintNames.push_back({pdf->
GetName()});
1606 bool autoExportDependants()
const override {
return false; }
1607 std::string
const &key()
const override
1609 static const std::string keystring =
"histfactory_dist";
1615 std::vector<RooAbsPdf *> constraints;
1616 if (
auto const *prodpdf =
dynamic_cast<RooProdPdf const *
>(
p)) {
1617 sumpdf = channelSum(*prodpdf);
1619 if (pdf != sumpdf) {
1621 collectConstraintTerms(pdf, constraints);
1625 return tryExportHistFactory(tool,
p->
GetName(), sumpdf, constraints);
1630const bool registered = []() {
1631 registerType(
"interpolation", importPiecewiseInterpolation, exportPiecewiseInterpolation);
1632 registerType(
"interpolation0d", importFlexibleInterpVar, exportFlexibleInterpVar);
1633 RooFit::JSONIO::registerImporter<HistFactoryImporter>(
"histfactory_dist",
true);
1634 RooFit::JSONIO::registerExporter<HistFactoryStreamer>(
RooProdPdf::Class(),
true);
1646 std::vector<double> sumW;
1647 std::vector<double> sumW2;
1648 std::vector<ParameterRef> gammaParnames;
1649 for (
auto const &sample : dist.samples) {
1651 [](
auto const &
m) { return std::holds_alternative<StatError>(m); });
1655 sumW.resize(sample.
contents.size());
1656 sumW2.resize(sample.
contents.size());
1657 for (std::size_t i = 0; i < sample.
contents.size(); ++i) {
1662 }
else if (dist.statError.impliedPoissonErrors) {
1666 if (gammaParnames.empty()) {
1667 gammaParnames = std::get<StatError>(*found).parameters;
1676 if (!sumW.empty()) {
1678 std::vector<double> errs(sumW.size());
1679 for (std::size_t i = 0; i < sumW.size(); ++i) {
1680 errs[i] = sumW[i] > 0. ? std::sqrt(sumW2[i]) / sumW[i] : 0.;
1689 dist.statError.relThreshold, errs.size(),
1690 "the staterror modifier of channel '" +
name +
"'", configureGammas);
1693 ChannelContext ctx{tool, dist, observables,
name,
channelName, mcStatObject, constraints};
1698 buildSample(ctx, sample);
1704 for (
auto const &ref : *channelConstraints) {
1713 for (
auto *constraint : static_range_cast<RooAbsPdf *>(constraints)) {
1715 ownMeasurements.
add(*constraint);
1718 constraints.
remove(ownMeasurements);
1727 sum.setAttribute(
"BinnedLikelihood");
1728 sum.setAttribute(
"GenerateBinned");
1729 if (!constraints.
empty()) {
1736 return dynamic_cast<HistFactoryImporter
const *
>(&importer) !=
nullptr;
std::optional< ArrayComponentInfo > arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable, RooJSONFactoryWSTool *tool)
void checkParamHistFuncOrderIsDefined(RooFit::HS3::Version const &version, RooAbsCollection const &vars, std::string const &context)
std::vector< RooAbsReal * > paramHistFuncParamsInBinOrder(ParamHistFunc const &func)
RooArgList toParamHistFuncOrder(RooArgList const ¶msInBinOrder, RooAbsCollection const &vars)
bool startsWith(std::string_view str, std::string_view prefix)
bool endsWith(std::string_view str, std::string_view suffix)
bool isLiteralConstVar(RooAbsArg const &arg)
std::string removeSuffix(std::string_view str, std::string_view suffix)
std::unique_ptr< RooArgSet > histogramVariablesNamedAfterObservables(RooDataHist const &dh, RooArgSet const &histObs, RooArgSet const &funcObs)
bool isSkippedHelper(RooAbsArg const &arg, RooWorkspace const &ws)
constexpr const char * arrayDistTag
void registerType(const std::string &key, ImportFunc importFunc, ExportFunc< RooArg_t > exportFunc, bool autoExportDependants=true)
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
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t r
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void funcs
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t modifier
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
A class which maps the current values of a RooRealVar (or a set of RooRealVars) to one of a number of...
const RooArgList & paramList() const
const RooArgList & dataVars() const
The PiecewiseInterpolation is a class that can morph distributions into each other,...
const RooArgList & highList() const
const RooAbsReal * nominalHist() const
Return pointer to the nominal hist function.
bool positiveDefinite() const
const RooArgList & lowList() const
void setPositiveDefinite(bool flag=true)
const RooArgList & paramList() const
const std::vector< int > & interpolationCodes() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
void treeNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool doBranch=true, bool doLeaf=true, bool valueOnly=false, bool recurseFundamental=false) const
Fill supplied list with nodes of the arg tree, following all server links, starting with ourself as t...
bool isConstant() const
Check if the "Constant" attribute is set.
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
const RefCountList_t & clients() const
List of all clients of this object.
Abstract container object that can hold multiple RooAbsArg objects.
bool equals(const RooAbsCollection &otherColl) const
Check if this and other collection have identically-named contents.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
bool overlaps(Iterator_t otherCollBegin, Iterator_t otherCollEnd) const
const_iterator end() const
Storage_t::size_type size() const
const_iterator begin() const
RooAbsArg * find(const char *name) const
Find object with given name in list.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract interface for all probability density functions.
void setConstant(bool value=true)
Abstract base class for objects that represent a real value and implements functionality common to al...
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
RooArgList is a container object that can hold multiple RooAbsArg objects.
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Returns the bin width (or volume) given a RooHistFunc.
bool divideByBinWidth() const
Represents a constant real-valued object.
Container class to hold N-dimensional binned data.
double const * weightArray() const
void writeJSON(std::ostream &os) const
bool has_child(std::string const &) const
static std::unique_ptr< JSONTree > create()
A real-valued function sampled from a multidimensional histogram.
RooAbsReal const & getMean() const
Get the mean parameter.
Efficient implementation of a product of PDFs of the form.
Represents the product of a given set of RooAbsReal objects.
Implements a PDF constructed from a sum of functions:
const RooArgList & funcList() const
const RooArgList & coefList() const
Variable that can be changed from the outside.
bool hasError(bool allowZero=true) const
const std::vector< int > & interpolationCodes() const
const RooListProxy & variables() const
const std::vector< double > & high() const
const std::vector< double > & low() const
< A class that holds configuration information for a model using a workspace as a store
Persistable container for RooFit projects.
TObject * obj(RooStringView name) const
Return any type of object (RooAbsArg, RooAbsData or generic object) with given name)
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
RooAbsArg * arg(RooStringView name) const
Return RooAbsArg with given name. A null pointer is returned if none is found.
RooFactoryWSTool & factory()
Return instance to factory tool.
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
const char * GetName() const override
Returns name of object.
Mother of all ROOT objects.
virtual const char * GetName() const
Returns name of object.
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
RooCmdArg Conditional(const RooArgSet &pdfSet, const RooArgSet &depSet, bool depsAreCond=false)
RooConstVar & RooConst(double val)
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)
double dist(Rotation3D const &r1, Rotation3D const &r2)
Types that represent an HS3 document.
HistFactoryDist parseHistFactoryDist(Detail::JSONNode const &distribution, Diagnostics &diagnostics)
Reads a HistFactory distribution that doesn't come with a document.
void validateHistFactoryDist(HistFactoryDist const &dist, std::string const &name, Diagnostics &diagnostics)
Same as validate(), but for a single HistFactory or combined distribution that doesn't come with a do...
void writeInterpolatedFunction(Detail::JSONNode &node, InterpolatedFunction const &function)
Writes the functions "interpolation" and "interpolation0d", with a single interpolation if they are a...
std::variant< NormFactor, NormSys, HistoSys, ShapeSys, StatError, CustomModifier > Modifier
InterpolationClass
The RooFit classes that implement the interpolations, which encode them with integer codes.
void mergeDuplicateModifiers(HistFactoryDist &dist, std::string const &channel, Diagnostics &diagnostics)
Combines the modifiers of a sample that have the same type and name, which HistFactory models can hav...
ConstraintType
The constraint types that older documents named, for which RooFit creates the constraint terms.
std::optional< Interpolation > interpolationFromCode(int code, InterpolationClass interpolationClass)
The interpolation for an integer code, or nothing if the class doesn't support the code.
void factorOutDefaultInterpolation(HistFactoryDist &dist)
Makes the most common interpolation of the modifiers the "default_interpolation", which they then don...
void setExportedObject(RooJSONFactoryWSTool &tool, HistFactoryDist dist, std::vector< DistributionRef > channelConstraints)
Called by the exporter of a HistFactory distribution, which is then written by the tool.
char const * toString(InterpolationType type)
InterpolatedNumber parseInterpolatedNumber(Detail::JSONNode const &node, Diagnostics &diagnostics)
void upgradeHistFactoryDist(Detail::JSONNode &distribution, Version const &version, Diagnostics &diagnostics)
Same as upgradeDocument(), but for a single HistFactory distribution that doesn't come with a documen...
void report(Diagnostics const &diagnostics, std::string const &object="")
Forward the warnings to the message service, and throw if there are errors.
InterpolatedFunction parseInterpolatedFunction(Detail::JSONNode const &node, Diagnostics &diagnostics)
Reads the functions "interpolation" and "interpolation0d", which don't come with a document.
RooArgSet createObservables(std::vector< BinnedAxis > const &axes)
Create the variables for the axes of binned data.
std::optional< int > codeFromInterpolation(Interpolation const &interpolation, InterpolationClass interpolationClass)
The integer code of an interpolation, or nothing if the class can't represent the interpolation.
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
void writeInterpolatedNumber(Detail::JSONNode &node, InterpolatedNumber const &function)
constexpr Interpolation multiplicativePiecewiseExponential
std::vector< Diagnostic > Diagnostics
void writeInterpolation(Detail::JSONNode &node, Interpolation const &interpolation)
NameOrNumber toNameOrNumber(RooAbsArg const &arg)
The name of an object, or the value of a literal constant.
std::variant< Unconstrained, ConstraintType, ConstantGammas, GammaConstraintPdfs > GammaConstraint
BinnedAxis toBinnedAxis(RooRealVar const &var)
The axis of binned data for a variable, or for a binning of a variable with the given name.
std::unique_ptr< RooDataHist > createDataHist(std::string const &name, RooArgSet const &vars, std::vector< double > const &contents, std::vector< double > const *errors)
Create a RooDataHist with the contents and errors. If there are no errors, it doesn't store squared w...
std::variant< Unconstrained, ConstraintType, ConstraintPdf > Constraint
bool isBuiltinHistFactoryImporter(JSONIO::Importer const &importer)
Whether this is the importer that RooFit registers for HistFactory distributions, as opposed to the o...
void buildHistFactoryDist(RooJSONFactoryWSTool &tool, std::string const &name, HistFactoryDist const &dist)
Create the RooFit objects of a HistFactory distribution in the workspace of the tool.
constexpr double defaultShapeSysGammaMax
constexpr double minShapeUncertainty
constexpr double defaultStatErrorGammaMax
constexpr double defaultGammaMin
void configureConstrainedGammas(RooArgList const &gammas, std::span< const double > relSigmas, double minSigma)
Configure constrained gamma parameters for fitting.
Arg_t & getOrCreate(RooWorkspace &ws, std::string const &name, Params_t &&...params)
CreateGammaConstraintsOutput createGammaConstraints(RooArgList const ¶mSet, std::span< const double > relSigmas, double minSigma, Constraint::Type type)
void variables(TString dataset, TString fin="TMVA.root", TString dirName="InputVariables_Id", TString title="TMVA Input Variables", Bool_t isRegression=kFALSE, Bool_t useTMVAStyle=kTRUE)
The gamma parameters are constant, which is a RooFit extension.
The constraint term is a distribution of the document, named in "constraints".
Multiplies the sample with a function of the document.
Every gamma parameter has its own constraint term, or none, as named in "constraints".
std::vector< std::optional< DistributionRef > > pdfs
std::vector< Sample > samples
The function "interpolation" of RooFit, implemented by PiecewiseInterpolation: a nominal function plu...
std::vector< Interpolation > interpolations
One per parameter.
std::vector< NameOrNumber > parameters
std::vector< NameOrNumber > low
std::vector< NameOrNumber > high
The function "interpolation0d" of RooFit, implemented by FlexibleInterpVar: a nominal value plus the ...
std::vector< double > high
std::vector< double > low
std::vector< std::string > parameters
std::vector< Interpolation > interpolations
One per parameter.
How a modifier of a HistFactory distribution interpolates and extrapolates its effect.
std::vector< double > contents
std::optional< std::vector< double > > errors
std::vector< Modifier > modifiers
Scales each bin by its own parameter. The modifier type "shapesys" is a deprecated alias of "shapefac...
Scales each bin by a parameter, that is constrained by the statistical uncertainty of all samples tha...
The parameter of the modifier is not constrained.
Combines lambdas into one visitor for std::visit(). The compiler complains about the alternatives wit...
static uint64_t sum(uint64_t i)