51#include <unordered_map>
127 for (
auto const &function : doc.
functions) {
128 functions.emplace(function.name, &function);
134 if (point.name ==
"default_values") {
136 for (
auto const &
p : point.parameters) {
147 std::unordered_map<std::string, HS3::Function const *>
functions;
162 std::map<std::string, std::map<std::string, HS3::DomainAxis>>
domains;
191 auto found = tool.
_import->arrayComponentForms.find(
name);
192 return found == tool.
_import->arrayComponentForms.end() ? nullptr : &found->second;
198 tool.
_import->arrayComponentForms[
name] = std::move(form);
203 std::vector<DistributionRef> channelConstraints)
205 tool.
_export->typedObject = std::move(dist);
206 tool.
_export->channelConstraints = std::move(channelConstraints);
212void addUnique(std::vector<std::string> &names, std::string
const &
name)
214 if (std::find(names.begin(), names.end(),
name) == names.end()) {
215 names.push_back(
name);
219template <
class Coll_t>
220std::vector<std::string> namesOf(Coll_t
const &objects)
222 std::vector<std::string> names;
223 for (
auto const *
object : objects) {
224 names.push_back(
object->GetName());
230bool hasLabels(
RooCategory const &cat, std::vector<std::string>
const &labels)
232 std::set<std::string> states;
233 for (
auto const &state : cat) {
234 states.insert(state.first);
236 return states == std::set<std::string>(labels.begin(), labels.end());
246 for (
int i = 0; i < binning.
numBins(); ++i) {
252constexpr double inf = std::numeric_limits<double>::infinity();
253constexpr int isInfinite(
double x)
255 return (
x >= +inf) ? +1 : ((
x <= -inf) ? -1 : 0);
264 if (!isInfinite(binning.
lowBound())) {
271 if (axis.
min && axis.
max && hasBins) {
272 axis.
binning = toBinning(binning);
279void recordDomains(std::map<std::string, std::map<std::string, HS3::DomainAxis>> &domains,
RooRealVar const &var)
282 for (
auto const &
name : var.getBinningNames()) {
290void appendDomain(std::vector<HS3::Domain> &domains, std::string
const &
name,
291 std::map<std::string, HS3::DomainAxis> axes,
292 std::map<std::string, HS3::CategoricalAxis> categories = {})
294 std::map<std::string, std::variant<HS3::DomainAxis, HS3::CategoricalAxis>> sorted;
295 for (
auto &item : axes) {
296 sorted.emplace(item.first, std::move(item.second));
298 for (
auto &item : categories) {
299 sorted.emplace(item.first, std::move(item.second));
303 for (
auto &item : sorted) {
304 domain.
axes.emplace_back(std::move(item.second));
311 if (
auto const *edges = std::get_if<HS3::EdgesBinning>(&binning)) {
312 if (edges->
edges.empty()) {
316 for (
double edge : edges->edges) {
317 bins.addBoundary(edge);
320 }
else if (
int nbins = std::get<HS3::RegularBinning>(binning).nbins) {
328 if (isInfinite(*axis.
min)) {
335 if (isInfinite(*axis.
max)) {
342 applyBinning(var, *axis.
binning);
350 auto forEachAxis = [&](
auto &&fn) {
352 for (
auto const &axis : domain.axes) {
353 if (
auto const *continuous = std::get_if<HS3::DomainAxis>(&axis)) {
354 fn(domain.
name, *continuous);
362 ws.import(RooConstVar{axis.name.c_str(), axis.name.c_str(), *axis.fixedValue},
RooFit::Silence());
367 RooRealVar var{axis.name.c_str(), axis.name.c_str(), axis.min.value_or(-inf), axis.max.value_or(inf)};
369 applyBinning(var, *axis.
binning);
378 for (
auto const &axisVariant : domain.axes) {
379 auto const *axis = std::get_if<HS3::CategoricalAxis>(&axisVariant);
387 "' already exists and is not a category");
389 if (!hasLabels(*cat, axis->categories)) {
391 "' differ from the states of the existing category '" + axis->
name +
"'");
396 for (std::size_t i = 0; i < axis->categories.size(); ++i) {
397 cat.
defineType(axis->categories[i],
static_cast<int>(i));
402 forEachAxis([&](std::string
const &domain,
HS3::DomainAxis const &axis) {
405 var->
setRange(domain.c_str(), axis.
min.value_or(-inf), axis.
max.value_or(inf));
407 applyBinning(*var, *axis.
binning, domain.c_str());
419template <
class State_t>
421 std::unique_ptr<State_t> &state;
422 ~StateScope() { state.reset(); }
429 ImportGuard(std::vector<std::string> &stack, std::string
const &
name) : _stack{stack}
431 if (std::find(_stack.begin(), _stack.end(),
name) != _stack.end()) {
433 for (std::string
const &ancestor : _stack) {
434 chain += ancestor +
" -> ";
438 _stack.push_back(
name);
440 ~ImportGuard() { _stack.pop_back(); }
443 std::vector<std::string> &_stack;
451 for (
Diagnostic const &diagnostic : diagnostics) {
453 const bool needsDot = !
object.empty() && !diagnostic.path.empty() && diagnostic.path.front() !=
'[';
454 const std::string path =
object + (needsDot ?
"." :
"") + diagnostic.path;
455 const std::string
text = path.empty() ? diagnostic.message : path +
": " + diagnostic.message;
456 if (diagnostic.severity == Diagnostic::Severity::Error) {
457 errors += (errors.empty() ?
"" :
"\n") +
text;
462 if (!errors.empty()) {
473 if (
auto const *
value = std::get_if<double>(&*
p.value)) {
478 applyRange(
v, *range);
483 v.setError(
v.getVal() * *
p.relError);
485 v.setError(*
p.error);
486 v.setConstant(
p.isConst);
489std::string genPrefix(
const JSONNode &
p,
bool trailing_underscore)
494 if (
auto node =
p.find(
"namespaces")) {
495 for (
const auto &ns : node->children()) {
501 if (trailing_underscore && !prefix.empty())
509 for (
auto const &
attr : attributes.dict) {
512 for (
auto const &tag : attributes.tags) {
519void exportParameterStepWidths(
RooWorkspace const &workspace, std::vector<RooAbsPdf *>
const &pdfs,
520 std::vector<RooAbsData *>
const &
data, std::vector<HS3::StepWidth> &out)
526 set.
add(*args,
true);
529 for (
TObject *obj : workspace.allGenericObjects()) {
531 addIfPresent(candidates, mc->GetParametersOfInterest());
532 addIfPresent(candidates, mc->GetNuisanceParameters());
533 addIfPresent(excluded, mc->GetObservables());
534 addIfPresent(excluded, mc->GetGlobalObservables());
535 addIfPresent(excluded, mc->GetConditionalObservables());
541 std::unique_ptr<RooArgSet> pdfObs{pdf->getObservables(*dataset->get())};
542 observables.
add(*pdfObs,
true);
544 if (!observables.
empty()) {
546 pdf->getParameters(&observables, params);
547 candidates.
add(params,
true);
548 excluded.
add(observables,
true);
563 auto *var =
dynamic_cast<RooRealVar *
>(workspace.
arg(stepWidth.name));
567 stepWidth.name +
"'.");
577std::set<std::string> checkVariates(
HS3Document const &doc)
582 for (std::string
const &column : columns) {
584 "RooFitHS3: the axis '" + column +
"' of the components of the combined data set '" + dataset +
585 "' is declared as a bookkeeping column without statistical meaning (misc.ROOT_internal."
586 "bookkeeping_columns), so it may be shared by the components, although HS3 requires distinct axes.");
592 std::vector<std::string> violations;
593 std::vector<std::string> notes;
596 violations.push_back(
"invalid HS3: " +
message +
597 ". The \"constraints\" of a modifier add no term to the likelihood, which has to list "
603 violations.push_back(
605 ". The terms of a likelihood and the components of a combined distribution or data set must have distinct "
606 "variates, apart from identical factors within a combined distribution. Distributions that share factors, "
607 "e.g. the models of a combination with common constraint terms, are joined in a combined distribution, "
608 "which the likelihood lists as one term.");
612 ". HS3 0.3 requires distinct variates; the document is read anyway, since it "
613 "declares an older version.");
615 if (!violations.empty()) {
617 for (std::string
const &violation : violations) {
618 all += (all.empty() ?
"" :
"\n") + violation;
622 for (std::string
const ¬e : notes) {
634 std::vector<RooArgSet const *> modelConfigSets;
635 for (
TObject *obj : ws.allGenericObjects()) {
637 for (
RooArgSet const *set : {mc->GetObservables(), mc->GetParametersOfInterest(), mc->GetNuisanceParameters(),
638 mc->GetGlobalObservables(), mc->GetConditionalObservables()}) {
640 modelConfigSets.push_back(set);
645 auto usedByNothing = [&](std::string
const &
name) {
647 if (!arg || !arg->
clients().empty()) {
650 return std::none_of(modelConfigSets.begin(), modelConfigSets.end(),
651 [&](
RooArgSet const *set) { return set->find(name.c_str()) != nullptr; });
654 for (std::string
const &axis : axes) {
655 if (usedByNothing(axis)) {
663void exportAttributes(
const RooAbsArg *arg, std::map<std::string, HS3::Attributes> &attributes)
673 out = &attributes[arg->
GetName()];
677 for (
const auto &it : arg->stringAttributes()) {
679 if (it.first ==
"factory_tag" || it.first ==
"PROD_TERM_TYPE")
682 out->
dict[it.first] = it.second;
684 for (
auto const &
attr : arg->attributes()) {
710 return static_cast<RooConstVar const &
>(arg).getVal();
712 return std::string{arg.
GetName()};
738 for (
unsigned int i = 0; i < cat.
size(); ++i) {
749 if (
auto const *cat =
dynamic_cast<RooCategory const *
>(var)) {
751 data.axes.emplace_back(toCategoricalAxis(*cat));
756 data.contents.assign(contents, contents +
n);
760std::unique_ptr<RooRealVar> createObservable(
HS3::BinnedAxis const &axis)
762 auto obs = std::make_unique<RooRealVar>(axis.
name.c_str(), axis.
name.c_str(), axis.
min, axis.
max);
763 applyBinning(*obs, axis.
binning);
772RooArgSet createBinnedObservables(std::vector<std::variant<HS3::BinnedAxis, HS3::CategoricalAxis>>
const &axes,
773 RooWorkspace const &workspace, std::string
const &dataName,
774 std::vector<std::size_t> &binOrder)
777 std::vector<std::vector<std::size_t>> axisPositions;
778 bool reordered =
false;
779 for (
auto const &axisVariant : axes) {
780 if (
auto const *axis = std::get_if<HS3::BinnedAxis>(&axisVariant)) {
781 auto obs = createObservable(*axis);
782 std::vector<std::size_t> positions(obs->numBins());
783 std::iota(positions.begin(), positions.end(), 0);
784 axisPositions.push_back(std::move(positions));
788 auto const &axis = std::get<HS3::CategoricalAxis>(axisVariant);
789 auto cat = std::make_unique<RooCategory>(axis.
name.c_str(), axis.
name.c_str());
793 "' differ from those of the category '" + axis.
name +
"'");
795 for (
unsigned int i = 0; i < wsCat->size(); ++i) {
796 auto const &state = wsCat->getOrdinal(i);
800 for (std::size_t i = 0; i < axis.
categories.size(); ++i) {
804 std::vector<std::size_t> positions(axis.
categories.size());
805 for (std::size_t i = 0; i < positions.size(); ++i) {
807 positions[i] = std::distance(axis.
categories.begin(), found);
808 reordered |= positions[i] != i;
810 axisPositions.push_back(std::move(positions));
817 std::size_t
total = 1;
818 for (
auto const &positions : axisPositions) {
819 total *= positions.size();
821 binOrder.resize(
total);
822 for (std::size_t k = 0; k <
total; ++k) {
824 std::size_t rest = k;
825 std::size_t docIndex = 0;
826 std::size_t stride = 1;
827 for (std::size_t j = axisPositions.size(); j-- > 0;) {
828 const std::size_t nBins = axisPositions[j].size();
829 docIndex += axisPositions[j][rest % nBins] * stride;
833 binOrder[k] = docIndex;
839std::vector<double> permute(std::vector<double>
const &values, std::vector<std::size_t>
const &order)
841 if (order.empty() || values.size() != order.size()) {
844 std::vector<double> out(values.size());
845 for (std::size_t k = 0; k < order.size(); ++k) {
846 out[k] = values[order[k]];
861 }
else if (var.
getMin() != min || var.
getMax() != max) {
862 std::stringstream ss;
863 ss <<
"RooFitHS3: the range [" << min <<
", " << max <<
"] of the axis '" << axis.
name <<
"' of the dataset '"
864 << dataName <<
"' differs from the range [" << var.
getMin() <<
", " << var.
getMax() <<
"] of the variable.";
873 for (
auto const &axisVariant :
input.axes) {
874 auto const *axis = std::get_if<HS3::ContinuousAxis>(&axisVariant);
877 auto const &catAxis = std::get<HS3::CategoricalAxis>(axisVariant);
881 "\" could not be found in the workspace! Categorical observables are "
882 "declared by a categorical axis in a domain.");
884 if (!hasLabels(*cat, catAxis.categories)) {
886 "\" differ from the states of the category \"" + catAxis.name +
"\"");
896 applyUnbinnedAxisRange(*axis,
name, *var, ranges);
900 const std::size_t nAxes =
input.axes.size();
901 for (std::size_t i = 0; i <
input.numEntries(); ++i) {
902 for (std::size_t j = 0; j < nAxes; ++j) {
903 const double value =
input.entries[i * nAxes + j];
904 if (
auto const *catAxis = std::get_if<HS3::CategoricalAxis>(&
input.axes[j])) {
906 static_cast<RooCategory *
>(varlist.
at(j))->setLabel(catAxis->categories[
static_cast<std::size_t
>(
value)]);
922 if (
auto const *binned = std::get_if<HS3::BinnedData>(&
input.body)) {
923 if (
binned->uncertainty && !
binned->uncertainty->correlation.empty()) {
925 input.name +
"' are ignored, because RooDataHist can't store them.");
927 std::vector<std::size_t> binOrder;
929 std::vector<double>
sigma;
930 if (
binned->uncertainty) {
931 sigma = permute(
binned->uncertainty->sigma, binOrder);
936 if (
auto const *unbinned = std::get_if<HS3::UnbinnedData>(&
input.body)) {
937 if (
unbinned->hasEntriesUncertainties) {
939 "' are ignored, because RooDataSet can't store them.");
941 return createUnbinnedData(
input.name, *unbinned, workspace, ranges);
945 auto const &point = std::get<HS3::PointData>(
input.body);
946 if (point.uncertainty) {
948 "' is ignored: HS3 doesn't define how it enters a likelihood.");
952 if (point.axes.empty()) {
954 "' has no axis, and it is not paired with a distribution that has a single variate");
955 }
else if (point.axes.size() != 1) {
959 unbinned.axes.emplace_back(point.axes.front());
960 unbinned.entries.push_back(point.value);
961 return createUnbinnedData(
input.name, unbinned, workspace, ranges);
965std::string rootVersion()
967 std::string versionName =
gROOT->GetVersion();
968 std::replace(versionName.begin(), versionName.end(),
'/',
'.');
974std::unique_ptr<RooAbsData> *findDataset(std::vector<std::unique_ptr<RooAbsData>> &datasets, std::string
const &
name)
976 auto found = std::find_if(datasets.begin(), datasets.end(), [&](
auto &
d) { return d && d->GetName() == name; });
977 return found != datasets.end() ? &*found :
nullptr;
981void requirePdf(
RooAbsArg const *arg, std::string
const &
what)
983 if (!
dynamic_cast<RooAbsPdf const *
>(arg)) {
985 (arg ? std::string(
"a ") + arg->
ClassName() +
", not a pdf" :
"not imported"));
997 const std::vector<std::string> columnNames = namesOf(columns);
998 std::vector<std::string> dataColumns =
data.columns;
999 std::sort(dataColumns.begin(), dataColumns.end());
1000 if (dataColumns != columnNames) {
1002 "' with the combined data set '" + dataName +
"', but their columns differ");
1005 std::set<std::map<std::string, std::string>> dataKeys;
1006 for (
auto const &component :
data.components) {
1007 std::map<std::string, std::string> key;
1008 for (std::size_t i = 0; i <
data.columns.size(); ++i) {
1009 key[
data.columns[i]] = component.key[i];
1011 dataKeys.insert(key);
1013 auto keyToString = [&](std::map<std::string, std::string>
const &key) {
1014 std::vector<std::string> labels;
1015 for (std::string
const &column :
data.columns) {
1016 labels.push_back(key.at(column));
1020 std::set<std::map<std::string, std::string>> pdfKeys;
1021 for (std::vector<std::string>
const &labels :
selectionKeys(columns)) {
1026 std::map<std::string, std::string> key;
1027 for (std::size_t i = 0; i < columns.size(); ++i) {
1028 key[columnNames[i]] = labels[i];
1030 pdfKeys.insert(key);
1031 if (dataKeys.count(key) > 0) {
1036 "the combined data set '" + dataName +
"' has no sub-data set for the key " + keyToString(key) +
1037 " of the extended component '" + component->
GetName() +
"' of '" + simPdf.
GetName() +
1038 "'. RooFit cannot leave a component unobserved: it would add the expected number of events of the " +
1039 "component to the likelihood, see https://github.com/root-project/root/issues/24004");
1042 "' has no sub-data set for the key " + keyToString(key) +
" of the component '" +
1044 "', which RooFit treats as present and empty.");
1046 for (
auto const &key : dataKeys) {
1047 if (pdfKeys.count(key) == 0) {
1049 " of the combined data set '" + dataName +
"' is ignored, because '" +
1050 simPdf.
GetName() +
"' has no component for it.");
1065 for (std::string
const &
name : *mcInfo->observables) {
1067 observables.
add(*arg);
1070 "' (misc.ROOT_internal.ModelConfigs) does not exist");
1075 std::set<std::string> inDomains;
1076 for (
auto const &domainRef : analysis.domains) {
1078 for (
auto const &axis : domain->axes) {
1083 for (
auto const &poi : analysis.parametersOfInterest) {
1084 inDomains.insert(poi.name);
1087 for (std::string
const &variate :
HS3::
variatesOf(doc, likelihood)) {
1092 if (inDomains.count(variate) || arg->
isConstant()) {
1095 observables.
add(*arg);
1096 list += (list.empty() ?
"'" :
", '") + variate +
"'";
1098 if (!list.empty()) {
1099 oocoutI(
nullptr, IO) <<
"RooFitHS3: no data set of the likelihood of the analysis '" << analysis.
name
1100 <<
"' gives its observables; they are the variates of the likelihood that are neither in a "
1101 "domain of the analysis nor constant: "
1102 << list << std::endl;
1117 bool hasGlobalObservable =
false;
1119 auto *var =
dynamic_cast<RooRealVar *
>(leaf);
1125 if (std::none_of(channels.
begin(), channels.
end(),
1126 [&](
RooAbsArg const *other) { return other->dependsOn(*var); })) {
1127 hasGlobalObservable =
true;
1129 parameters.
add(*var);
1132 return hasGlobalObservable && !parameters.
empty() && channel.
dependsOn(parameters);
1138std::vector<std::string> otherLikelihoodTerms(
HS3Document const &doc, std::string
const &dist)
1140 std::vector<std::string> out;
1141 auto add = [&](std::string
const &
name) {
1143 addUnique(out,
name);
1151 if (HS3::find<HS3::CombinedDist>(doc.
distributions, term.distribution.name)) {
1154 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1159 std::find_if(doc.
data.begin(), doc.
data.end(), [&](
auto const &
d) { return d.name == dataRef->name; });
1160 if (
data == doc.
data.end() || std::holds_alternative<HS3::PointData>(
data->body)) {
1163 auto const *
unbinned = std::get_if<HS3::UnbinnedData>(&
data->body);
1166 for (
auto const &likelihood : doc.likelihoods) {
1167 if (std::none_of(likelihood.
terms.begin(), likelihood.
terms.end(),
1168 [&](
auto const &term) { return term.distribution.name == dist; })) {
1171 for (
auto const &term : likelihood.terms) {
1172 if (canBeConstraint(term)) {
1173 add(term.distribution.name);
1176 for (
auto const &aux : likelihood.auxDistributions) {
1196 for (
auto const &state : simPdf->indexCat()) {
1198 channels.
add(*channel,
true);
1208 bool isFactor =
false;
1209 std::vector<RooProdPdf *> products;
1212 if (!product || channel == constraint) {
1215 if (
product->pdfList().find(*constraint)) {
1217 }
else if (isConstraintOfChannel(*constraint, *channel, channels)) {
1218 products.push_back(product);
1224 if (isFactor || !products.empty()) {
1225 attached.
add(*constraint);
1228 constraints.
remove(attached);
1251 std::vector<HS3::LikelihoodTerm const *>
const &terms,
1252 std::vector<std::unique_ptr<RooAbsData>> &datasets,
RooArgSet &observables)
1254 std::string
const &analysisName = analysis.
name;
1257 std::map<std::string, std::string> labels;
1260 std::vector<Channel> channels;
1261 std::set<std::string> innerColumns;
1262 bool plainTerm =
false;
1263 bool nested =
false;
1264 std::function<void(std::size_t,
RooAbsPdf *, std::map<std::string, std::string>
const &)> collect =
1265 [&](std::size_t term,
RooAbsPdf *pdf, std::map<std::string, std::string>
const &labels) {
1268 channels.push_back({term, labels, pdf});
1271 nested |= !labels.empty();
1272 std::vector<RooCategory const *>
const columns =
selectionColumns(sim->indexCat());
1274 innerColumns.insert(column->GetName());
1276 for (std::vector<std::string>
const &key :
selectionKeys(columns)) {
1278 std::map<std::string, std::string> inner = labels;
1279 for (std::size_t k = 0; k < columns.size(); ++k) {
1280 if (!inner.emplace(columns[k]->GetName(), key[k]).second) {
1282 "' has the column '" + columns[k]->GetName() +
1283 "', which a combined distribution that contains it has as well");
1286 collect(term, component, inner);
1290 for (std::size_t i = 0; i < terms.size(); ++i) {
1291 RooAbsPdf *pdf = workspace.
pdf(terms[i]->distribution.name);
1293 collect(i, pdf, {});
1297 auto componentType = [](
RooAbsPdf const *pdf) -> std::string {
1298 auto const *array =
dynamic_cast<RooProdPdf const *
>(pdf);
1302 std::string
const type = array->pdfList()[0].ClassName();
1303 for (
RooAbsArg const *component : array->pdfList()) {
1310 std::map<std::string, std::vector<std::size_t>> arraysByType;
1311 for (std::size_t
c = 0;
c < channels.size(); ++
c) {
1312 if (std::string
const type = componentType(channels[
c].pdf); !
type.empty()) {
1313 arraysByType[
type].push_back(
c);
1318 std::vector<std::unique_ptr<RooAbsData> *> termData;
1319 for (std::size_t i = 0; i < terms.size(); ++i) {
1320 auto const *dataRef = std::get_if<HS3::DataRef>(&terms[i]->
data);
1321 auto found = dataRef ? std::find_if(datasets.begin(), datasets.end(),
1322 [&](
auto const &
d) { return d && d->GetName() == dataRef->name; })
1324 if (found == datasets.end()) {
1328 bool complete =
true;
1329 for (Channel
const &channel : channels) {
1330 for (
auto const &item : channel.labels) {
1331 complete &= channel.term != i || (*found)->get()->find(item.first.c_str()) !=
nullptr;
1338 termData.push_back(&*found);
1341 auto channelOf = [&](std::size_t term,
RooArgSet const &values) -> std::size_t {
1342 for (std::size_t
c = 0;
c < channels.size(); ++
c) {
1343 if (channels[
c].term != term) {
1347 for (
auto const &[column, label] : channels[
c].labels) {
1348 auto const *cat =
dynamic_cast<RooAbsCategory const *
>(values.find(column.c_str()));
1355 return channels.size();
1357 std::vector<int> entries(channels.size(), 0);
1358 for (std::size_t i = 0; i < termData.size(); ++i) {
1360 for (
int entry = 0; entry <
data.numEntries(); ++entry) {
1361 std::size_t
const c = channelOf(i, *
data.get(entry));
1362 if (
c < channels.size()) {
1368 std::map<std::size_t, std::size_t> mergedInto;
1369 std::map<std::size_t, RooArgList> mergedComponents;
1370 for (
auto const &[
type, members] : arraysByType) {
1371 std::vector<std::size_t> candidates;
1372 for (std::size_t
c : members) {
1373 if (termData.empty() || entries[
c] == 1) {
1374 candidates.push_back(
c);
1377 if (candidates.size() < 2) {
1380 RooArgList &components = mergedComponents[candidates.front()];
1381 for (std::size_t
c : candidates) {
1382 mergedInto[
c] = candidates.front();
1386 components.
add(*component);
1392 if (terms.size() == 1 && !nested && mergedInto.empty()) {
1399 bool unique = !plainTerm;
1400 std::set<std::vector<std::string>> innerKeys;
1401 for (std::size_t
c = 0;
c < channels.size(); ++
c) {
1402 if (mergedInto.count(
c) && mergedInto[
c] !=
c) {
1405 std::vector<std::string> key;
1406 for (std::string
const &column : innerColumns) {
1407 auto found = channels[
c].labels.find(column);
1408 key.push_back(found == channels[
c].labels.end() ?
"" : found->second);
1410 unique = innerKeys.insert(key).second && unique;
1412 std::string
const termColumn = analysisName +
"_categoryIndex";
1414 RooCategory outer{termColumn.c_str(), termColumn.c_str()};
1415 for (std::size_t i = 0; i < terms.size(); ++i) {
1416 outer.defineType(terms[i]->distribution.name,
static_cast<int>(i));
1421 std::vector<RooCategory *> columns;
1422 for (std::string
const &column : innerColumns) {
1423 columns.push_back(workspace.
cat(column));
1426 columns.push_back(workspace.
cat(termColumn));
1428 std::sort(columns.begin(), columns.end(),
1430 std::vector<RooCategory const *>
const constColumns(columns.begin(), columns.end());
1433 auto keyOf = [&](Channel
const &channel) {
1434 std::vector<std::string> key;
1436 if (column->GetName() == termColumn) {
1437 key.push_back(terms[channel.term]->distribution.name);
1440 auto found = channel.labels.find(column->GetName());
1441 if (found != channel.labels.end()) {
1442 key.push_back(found->second);
1445 if (!column->hasLabel(
"")) {
1446 column->defineType(
"");
1453 std::unique_ptr<RooSuperCategory> superCat;
1455 if (columns.size() > 1) {
1458 inputs.
add(*column);
1460 std::string
const indexName = analysisName +
"_index";
1461 superCat = std::make_unique<RooSuperCategory>(indexName.c_str(), indexName.c_str(), inputs);
1462 indexCat = superCat.get();
1464 std::map<std::string, RooAbsPdf *> pdfMap;
1465 for (std::size_t
c = 0;
c < channels.size(); ++
c) {
1467 if (
auto found = mergedInto.find(
c); found != mergedInto.end()) {
1468 if (found->second !=
c) {
1472 std::string
const name = analysisName +
"_" + pdf->
GetName() +
"_merged";
1478 pdfMap[
selectionLabel(*indexCat, constColumns, keyOf(channels[
c]))] = pdf;
1480 std::string
const simPdfName = analysisName +
"_simPdf";
1481 RooSimultaneous simPdf{simPdfName.c_str(), simPdfName.c_str(), pdfMap, *indexCat};
1484 observables.
add(*column,
true);
1488 if (
auto *sim =
dynamic_cast<RooSimultaneous *
>(workspace.
pdf(term->distribution.name))) {
1493 if (termData.empty()) {
1502 bool weighted =
false;
1504 for (
auto const *
data : termData) {
1505 vars.
add(*(*data)->get(),
true);
1506 weighted |= (*data)->isWeighted();
1507 if (
auto *ds =
dynamic_cast<RooDataSet const *
>(
data->get()); ds && ds->isWeighted()) {
1508 weightName = ds->weightVar()->GetName();
1511 std::string
const dataName = analysisName +
"_data";
1512 std::unique_ptr<RooDataSet> merged;
1514 RooRealVar weightVar{weightName.c_str(), weightName.c_str(), 1.0};
1515 vars.
add(weightVar);
1516 merged = std::make_unique<RooDataSet>(dataName.c_str(), dataName.c_str(), vars,
RooFit::WeightVar(weightVar));
1518 merged = std::make_unique<RooDataSet>(dataName.c_str(), dataName.c_str(), vars);
1521 std::map<std::size_t, std::unique_ptr<RooArgSet>> mergedEntries;
1523 merged->get()->snapshot(row);
1524 for (std::size_t i = 0; i < terms.size(); ++i) {
1526 for (
int entry = 0; entry <
data.numEntries(); ++entry) {
1528 const double weight =
data.weight();
1529 std::size_t
const c = channelOf(i, values);
1530 if (
auto found = mergedInto.find(
c); found != mergedInto.end()) {
1531 std::unique_ptr<RooArgSet> &combined = mergedEntries[found->second];
1533 combined = std::make_unique<RooArgSet>();
1540 auto const *known =
dynamic_cast<RooAbsReal const *
>(combined->find(
value->GetName()));
1542 std::abs(real->getVal() - known->getVal()) > 1
e-12 * std::max(1.0, std::abs(known->getVal()))) {
1544 "' differs between the data sets of the array distributions that " +
1545 "share it in the likelihood of the analysis '" + analysisName +
"'");
1548 combined->addClone(*
value);
1555 auto &cat =
static_cast<RooCategory &
>(row[column->GetName()]);
1556 if (column->GetName() == termColumn) {
1557 cat.
setLabel(terms[i]->distribution.name.c_str());
1558 }
else if (!values.
find(column->GetName())) {
1562 merged->add(row, weight);
1565 for (
auto const &[
c, values] : mergedEntries) {
1567 std::vector<std::string>
const key = keyOf(channels[
c]);
1568 for (std::size_t k = 0; k < columns.size(); ++k) {
1569 static_cast<RooCategory &
>(row[columns[k]->GetName()]).setLabel(key[k].c_str());
1571 merged->add(row, 1.0);
1577 RooAbsArg *inMerged = merged->get()->find(obs->GetName());
1578 mergedObservables.
add(inMerged ? *inMerged : *obs, true);
1581 observables.
add(mergedObservables);
1584 std::size_t analysesOfLikelihood = 0;
1586 analysesOfLikelihood += other.likelihood.name == analysis.
likelihood.
name;
1588 for (
auto *
data : termData) {
1589 std::size_t uses = 0;
1592 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1593 uses += dataRef && dataRef->name == (*data)->GetName();
1596 if (uses == 1 && analysesOfLikelihood == 1) {
1600 datasets.push_back(std::move(merged));
1606 std::vector<std::unique_ptr<RooAbsData>> &datasets, std::set<std::string>
const &bookkeepingColumns,
1607 std::set<std::string>
const &auxiliaryMeasurements)
1609 std::string
const &analysisName = analysis.
name;
1613 std::string mcname = mcInfo && mcInfo->
mcName ? *mcInfo->
mcName : analysisName;
1614 if (workspace.
obj(mcname))
1619 mc->
SetWS(workspace);
1624 auto checkPdf = [&](
RooAbsArg const *arg, std::string
const &
name, std::string
const &
what) {
1625 requirePdf(arg,
"the " +
what +
" '" +
name +
"' of analysis '" + analysisName +
"'");
1628 for (
auto const &term : likelihood.terms) {
1629 checkPdf(workspace.
arg(term.distribution.name), term.distribution.name,
"distribution");
1635 std::vector<std::unique_ptr<RooArgSet>> trees;
1636 for (
auto const &term : likelihood.terms) {
1637 RooAbsPdf *listed = workspace.
pdf(term.distribution.name);
1638 trees.push_back(listed ? std::unique_ptr<RooArgSet>{listed->
getComponents()} :
nullptr);
1640 auto isConstraintTermOfOthers = [&](
RooAbsArg const &term, std::size_t self) {
1641 auto isPartOf = [&term](
RooArgSet const &tree) {
1642 if (tree.find(term.
GetName())) {
1646 if (
auto const *array =
dynamic_cast<RooProdPdf const *
>(&term)) {
1647 for (
RooAbsArg const *component : array->pdfList()) {
1648 if (tree.find(component->
GetName())) {
1656 for (std::size_t i = 0; i < trees.size(); ++i) {
1657 if (i != self && trees[i] && isPartOf(*trees[i])) {
1668 std::string
const modelPdfName = mcInfo && mcInfo->
pdfName ? *mcInfo->
pdfName :
"";
1669 std::unique_ptr<RooArgSet> modelTree;
1670 if (
RooAbsPdf const *modelPdf = workspace.
pdf(modelPdfName);
1671 modelPdf && std::any_of(likelihood.
terms.begin(), likelihood.
terms.end(),
1672 [&](
auto const &term) { return term.distribution.name == modelPdfName; })) {
1673 modelTree.reset(modelPdf->getComponents());
1678 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1679 const bool auxiliary = auxiliaryMeasurements.count(listed.
GetName()) > 0;
1680 if (!dataRef || (!auxiliary && (!modelTree || modelTree->find(listed.
GetName())))) {
1683 auto const *
data = findDataset(datasets, dataRef->name);
1684 return data && (*data)->numEntries() == 1;
1687 std::vector<HS3::LikelihoodTerm const *> nllTerms;
1690 for (std::size_t i = 0; i < likelihood.
terms.size(); ++i) {
1691 auto const &term = likelihood.
terms[i];
1692 RooAbsPdf *listed = workspace.
pdf(term.distribution.name);
1693 if (listed && !isConstraintTermOfOthers(*listed, i) && isConstraintTermOfModel(*listed, term)) {
1694 constraintsWithData.
add(*listed);
1695 }
else if (!listed || !isConstraintTermOfOthers(*listed, i)) {
1696 nllTerms.push_back(&term);
1699 auto const *dataRef = std::get_if<HS3::DataRef>(&term.data);
1700 auto *
data = dataRef ? findDataset(datasets, dataRef->name) : nullptr;
1704 if ((*data)->numEntries() != 1) {
1705 throw std::runtime_error(
"the data set '" + dataRef->name +
"' paired with the constraint term '" +
1706 term.distribution.name +
"' must have exactly one entry");
1709 auto *var = workspace.
var(obs->GetName());
1711 if (!var || !
value) {
1713 std::string(obs->GetName()) +
"' from the data set '" + dataRef->name +
1714 "': it is not a variable of the workspace");
1719 constraintObservables.
add(*var);
1726 std::set<std::string> channelConstraints;
1727 for (
auto const &item : doc.rooFit.channelConstraints) {
1728 for (
auto const &ref : item.second) {
1729 channelConstraints.insert(ref.name);
1733 for (
auto const &aux : likelihood.auxDistributions) {
1735 if (!extConstraint) {
1738 checkPdf(extConstraint, aux.name,
"auxiliary distribution");
1740 if (channelConstraints.count(aux.name) &&
1742 RooAbsArg const *dist = workspace.arg(term->distribution.name);
1743 return dist && dist->dependsOn(*extConstraint);
1747 if (isConstraintTermOfOthers(*extConstraint, likelihood.
terms.size())) {
1750 extConstraints.
add(*extConstraint);
1754 if (
auto const *dataRef = std::get_if<HS3::DataRef>(&term->
data)) {
1755 auto const *
data = findDataset(datasets, dataRef->name);
1757 throw std::runtime_error(
"dataset '" + dataRef->name +
"' cannot be found!");
1759 observables.
add(*(*data)->get(),
true);
1765 observables.
remove(*arg);
1768 if (observables.
empty()) {
1769 observablesWithoutData(doc, analysis, likelihood, mcInfo, workspace, observables);
1773 for (
auto const &term : likelihood.terms) {
1774 auto const *dataRef = std::get_if<HS3::DataRef>(&term.
data);
1776 if (!dataRef || !simPdf) {
1779 if (
auto const *combined = HS3::find<HS3::CombinedData>(doc.
data, dataRef->name)) {
1780 checkCombinedPairing(*simPdf, dataRef->name, *combined);
1788 if (!pdf && !nllTerms.empty()) {
1789 pdf = flatModelOfLikelihood(doc, analysis, workspace, nllTerms, datasets, observables);
1791 pdf = workspace.
pdf(nllTerms.front()->distribution.name);
1794 pdf = workspace.
pdf(
"simPdf");
1798 "' has no distribution");
1803 extConstraints.
add(constraintsWithData,
true);
1804 attachConstraintsToChannels(*pdf, extConstraints);
1805 if (!extConstraints.
empty())
1806 mc->SetExternalConstraints(extConstraints);
1808 if (analysis.
prior) {
1810 checkPdf(prior, analysis.
prior->name,
"prior");
1811 mc->SetPriorPdf(
static_cast<RooAbsPdf &
>(*prior));
1816 for (
auto const &poi : analysis.parametersOfInterest) {
1820 analysisName +
"' does not exist");
1824 "' is a " + arg->
ClassName() +
", not a variable" +
1825 (
dynamic_cast<RooConstVar *
>(arg) ?
", because no domain lists it" :
""));
1827 parametersOfInterest.
add(*arg);
1830 mc->SetParametersOfInterest(parametersOfInterest);
1831 mc->SetObservables(observables);
1844 for (
RooAbsArg const *extConstraint : extConstraints) {
1847 pars.
add(extPars,
true);
1851 for (
auto const &domainRef : analysis.domains) {
1853 for (
auto const &axis : domain->axes) {
1855 domainPars.
add(*wsvar);
1863 for (
const auto &
p : pars) {
1864 if (mc->GetParametersOfInterest()->find(*
p))
1866 if (
p->isConstant() && !mainPars.find(*
p) && domainPars.
find(*
p)) {
1868 }
else if (domainPars.
find(*
p)) {
1873 globs.
add(constraintObservables,
true);
1874 mc->SetGlobalObservables(globs);
1875 mc->SetNuisanceParameters(nps);
1884 const std::string &initName = analysis.
init->name;
1887 std::string setName = initName;
1888 const std::string prefix = mcname +
"_";
1889 const std::string suffix =
"_snapshot";
1890 if (initName.size() >= prefix.size() + suffix.size() &&
startsWith(initName, prefix) &&
1892 setName = initName.substr(prefix.size(), initName.size() - prefix.size() - suffix.size());
1897 initSet.
setName(setName.c_str());
1898 mc->SetSnapshot(initSet);
1905void warnAboutUnusedArrayComponents(
RooWorkspace const &ws)
1908 auto const *array =
dynamic_cast<RooProdPdf const *
>(arg);
1909 if (!array || !array->getAttribute(
arrayDistTag) || array->hasClients()) {
1914 for (
RooAbsArg const *component : array->pdfList()) {
1915 bool usedElsewhere =
false;
1916 for (
RooAbsArg const *client : component->clients()) {
1917 if (client != array) {
1918 usedElsewhere =
true;
1921 if (usedElsewhere) {
1924 unused += (unused.empty() ?
"'" :
", '") + std::string(component->
GetName()) +
"'";
1927 if (used && !unused.empty()) {
1930 "' are not used by any distribution and are not part of any likelihood");
1937 for (
auto const &item : doc.rooFit.combinedDistributions) {
1938 std::string
const &combinedName = item.first;
1942 std::map<std::string, RooAbsPdf *> pdfMap;
1944 for (std::size_t iChannel = 0; iChannel < info.
labels.size(); ++iChannel) {
1948 "the distribution '" +
name +
"' of the combined distribution '" + combinedName +
"'");
1952 RooSimultaneous simPdf{combinedName.c_str(), combinedName.c_str(), pdfMap, indexCat};
1957void combineDatasets(
HS3Document const &doc, std::vector<std::unique_ptr<RooAbsData>> &datasets)
1959 for (
auto const &item : doc.rooFit.combinedDatasets) {
1960 std::string
const &combinedName = item.first;
1964 std::map<std::string, std::unique_ptr<RooAbsData>> dsMap;
1967 for (std::size_t iChannel = 0; iChannel < info.
labels.size(); ++iChannel) {
1968 auto componentName = combinedName +
"_" + info.
labels[iChannel];
1971 auto *found = findDataset(datasets, componentName);
1975 allVars.add(*(*found)->get(),
true);
1976 dsMap.insert({info.
labels[iChannel], std::move(*found)});
1980 auto combined = std::make_unique<RooDataSet>(combinedName, combinedName, allVars,
RooFit::Import(dsMap),
1982 datasets.emplace_back(std::move(combined));
1989template <
class Ref_t>
1990std::vector<RooCategory *>
1993 std::vector<RooCategory *> columns;
1994 for (std::string
const &column : combined.columns) {
1998 " is not declared by a categorical axis of a domain");
2000 columns.push_back(cat);
2002 for (
auto const &component : combined.components) {
2003 for (std::size_t i = 0; i < columns.size(); ++i) {
2004 if (!columns[i]->hasLabel(component.key[i])) {
2006 " of a key of " + context +
" is not one of the categories of '" +
2023 std::vector<std::unique_ptr<RooAbsData>> &datasets)
2026 std::vector<HS3::Data const *> pending;
2028 if (std::holds_alternative<HS3::CombinedData>(
input.body)) {
2029 pending.push_back(&
input);
2032 std::vector<HS3::Data const *> ordered;
2033 std::set<std::string> done;
2034 while (!pending.empty()) {
2035 auto ready = std::find_if(pending.begin(), pending.end(), [&](
HS3::Data const *
data) {
2036 for (auto const &c : std::get<HS3::CombinedData>(data->body).components) {
2037 if (HS3::find<HS3::CombinedData>(doc.data, c.ref.name) && !done.count(c.ref.name)) {
2043 if (ready == pending.end()) {
2045 "' is a component of itself, directly or through other combined data sets");
2047 ordered.push_back(*ready);
2048 done.insert((*ready)->name);
2049 pending.erase(ready);
2051 for (
HS3::Data const *inputPtr : ordered) {
2053 auto const *info = std::get_if<HS3::CombinedData>(&
input.body);
2056 std::string
const context =
"the combined data set '" +
name +
"'";
2057 std::vector<RooCategory *> columns = columnCategories(workspace, *info, context);
2060 std::vector<std::string>
const *key;
2061 std::unique_ptr<RooAbsData>
data;
2063 std::vector<Component> components;
2064 for (
auto const &
c : info->components) {
2065 auto *found = findDataset(datasets,
c.ref.name);
2068 " is not a data set of the document, or it is already a component of " +
2069 "another combined data set");
2071 components.push_back({&
c.key, std::move(*found)});
2081 for (
auto const &
c : components) {
2083 if (
dynamic_cast<RooCategory const *
>(arg) && !columnClones.
find(*arg)) {
2086 columnClones.
addClone(declared ?
static_cast<RooAbsArg const &
>(*declared) : *arg);
2090 std::vector<RooCategory *> innerColumns;
2093 if (std::find_if(columns.begin(), columns.end(), [&](
RooCategory const *
c) {
2094 return std::strcmp(c->GetName(), cat->GetName()) == 0;
2095 }) != columns.end()) {
2098 innerColumns.push_back(cat);
2099 bool everywhere = std::all_of(components.begin(), components.end(),
2100 [&](
auto const &
c) { return c.data->get()->find(*cat) != nullptr; });
2101 if (!everywhere && !cat->
hasLabel(
"")) {
2106 bool weighted =
false;
2107 bool storeErrors =
false;
2109 for (
auto const &
c : components) {
2110 vars.
add(*
c.data->get(),
true);
2111 weighted |=
c.data->isWeighted();
2112 if (
auto *ds =
dynamic_cast<RooDataSet const *
>(
c.data.get()); ds && ds->isWeighted()) {
2113 weightName = ds->weightVar()->GetName();
2115 storeErrors |=
dynamic_cast<RooDataHist const *
>(
c.data.get()) !=
nullptr;
2117 std::unique_ptr<RooDataSet> combined;
2119 RooRealVar weightVar{weightName.c_str(), weightName.c_str(), 1.0};
2120 vars.
add(weightVar);
2125 combined = std::make_unique<RooDataSet>(
name.c_str(),
name.c_str(), vars);
2127 for (
auto const &
c : components) {
2128 for (std::size_t i = 0; i < columns.size(); ++i) {
2129 static_cast<RooCategory &
>(vars[columns[i]->GetName()]).setLabel((*
c.key)[i].c_str());
2131 for (
int i = 0; i <
c.data->numEntries(); ++i) {
2134 if (!
c.data->get()->find(*inner)) {
2135 static_cast<RooCategory &
>(vars[inner->GetName()]).setLabel(
"");
2139 combined->add(vars,
c.data->weight(), storeErrors ?
c.data->weightError(
RooAbsData::SumW2) : 0.0);
2141 combined->add(vars);
2145 datasets.emplace_back(std::move(combined));
2150void sortByName(T &coll)
2152 std::sort(coll.begin(), coll.end(), [](
auto &
l,
auto &
r) { return strcmp(l->GetName(), r->GetName()) < 0; });
2162 for (
RooAbsArg const *client : arg.clients()) {
2171template <
class Arg_t>
2174 std::vector<Arg_t *> out;
2176 auto *
object =
dynamic_cast<Arg_t *
>(arg);
2178 out.push_back(
object);
2191 vars.
addOwned(createObservable(axis));
2197 std::vector<double>
const &contents,
2198 std::vector<double>
const *errors)
2200 if (errors && errors->size() != contents.size()) {
2202 std::to_string(errors->size()) +
", contents=" + std::to_string(contents.size()));
2205 std::size_t nBins = 1;
2209 if (contents.size() != nBins) {
2211 ", bins=" + std::to_string(nBins));
2213 auto dh = std::make_unique<RooDataHist>(
name,
name, vars);
2216 if (errors && !errors->empty()) {
2219 for (std::size_t ibin = 0; ibin < nBins; ++ibin) {
2220 dh->set(ibin, contents[ibin], errors ? (*errors)[ibin] : -1);
2228 std::vector<std::string>
const &otherLikelihoodTerms)
2230 std::vector<RooCategory *> columns = columnCategories(*tool.
workspace(), dist,
"the combined_dist '" +
name +
"'");
2231 std::map<std::string, RooAbsPdf *> pdfMap;
2232 for (
auto const &component : dist.components) {
2240 std::vector<RooAbsPdf *> terms;
2241 for (std::string
const &term : otherLikelihoodTerms) {
2243 terms.push_back(pdf);
2247 for (
auto const &item : pdfMap) {
2248 channels.
add(*item.second,
true);
2250 for (
auto &item : pdfMap) {
2257 isConstraintOfChannel(*term, channel, channels)) {
2261 if (!factors.
empty()) {
2262 factors.
add(channel);
2267 if (columns.size() == 1) {
2273 inputs.
add(*column);
2275 std::string
const indexName =
name +
"_index";
2285 bool hasClients =
false;
2308 if (mc->GetPdf() == &arg || mc->GetPriorPdf() == &arg ||
2309 (mc->GetExternalConstraints() && mc->GetExternalConstraints()->containsInstance(arg))) {
2325 auto const &componentsWithData =
_import->componentsWithData;
2327 return componentsWithData.count(pdf.
GetName()) ||
2329 return client->getAttribute(arrayDistTag) && componentsWithData.count(client->GetName());
2338 auto const &all =
_import->document.rooFit.channelConstraints;
2339 auto found = all.find(dist);
2340 return found != all.end() ? &found->second :
nullptr;
2362 error(
"unable to stream collection " + std::string(coll.
GetName()) +
" to " + node.
key());
2389 return !str.empty() && (std::isalpha(str[0]) || str[0] ==
'_') &&
2390 std::all_of(str.begin(), str.end(), [](
char c) {
return std::isalnum(
c) ||
c ==
'_'; });
2396 std::stringstream ss;
2397 ss <<
"RooJSONFactoryWSTool() name '" <<
name <<
"' is not valid!" << std::endl
2398 <<
"Sanitize names by setting RooJSONFactoryWSTool::config().allowSanitizeNames = true." << std::endl;
2411 return n[
"name"].val();
2417RooRealVar *RooJSONFactoryWSTool::requestImpl<RooRealVar>(
const std::string &objname)
2420 auto found =
_import->defaultValuesByName.find(objname);
2421 if (found !=
_import->defaultValuesByName.end()) {
2429RooAbsPdf *RooJSONFactoryWSTool::requestImpl<RooAbsPdf>(
const std::string &objname)
2432 auto found =
_import->distributions.find(objname);
2433 if (found !=
_import->distributions.end()) {
2439 auto found =
_import->functions.find(objname);
2440 if (found !=
_import->functions.end()) {
2448RooAbsReal *RooJSONFactoryWSTool::requestImpl<RooAbsReal>(
const std::string &objname)
2452 if (std::optional<double> number =
toNumber(objname))
2454 if (
RooAbsPdf *pdf = requestImpl<RooAbsPdf>(objname))
2456 if (
RooRealVar *var = requestImpl<RooRealVar>(objname))
2459 auto found =
_import->functions.find(objname);
2460 if (found !=
_import->functions.end()) {
2484 axis.
name = cv->GetName();
2491 var.
name =
v->GetName();
2492 var.
value = rrv->getVal();
2493 var.
isConst = rrv->isConstant() || rrv->getMin() >= rrv->getMax();
2494 recordDomains(
_export->domains, *rrv);
2499 const std::string &formula)
2503 error(
"cannot write a function of '" + std::string(original->
GetName()) +
2504 "': names of the form 'const_<number>' are reserved for functions of literal constants");
2508 if (
dynamic_cast<RooAbsPdf const *
>(original)) {
2509 error(
"the parameter '" + std::string(original->
GetName()) +
2510 "' would have to be written as an expression that refers to a pdf, which HS3 doesn't allow");
2513 auto &functions =
_export->doc.functions;
2518 trafo_node[
"type"] <<
"generic";
2520 functions.push_back({newname, {
"generic",
nullptr}});
2529std::string makeValidNameOrError(std::string
const &in)
2531 if (!std::isalpha(in[0])) {
2534 std::string out = in;
2535 std::transform(out.begin(), out.end(), out.begin(), [](
char c) { return std::isalnum(c) ? c :
'_'; });
2537 oocoutW(
nullptr, ObjectHandling) <<
"RooFitHS3: changed '" << in <<
"' to '" << out <<
"' to become a valid name";
2545std::string selectionKeyName(std::vector<std::string>
const &key)
2548 for (std::size_t i = 0; i < key.size(); ++i) {
2549 out += (i == 0 ?
"" :
"_") + (key[i].empty() ? std::string{} : makeValidNameOrError(key[i]));
2557 std::vector<RooSimultaneous const *> candidates;
2558 for (
RooAbsArg *arg : workspace.allPdfs()) {
2560 candidates.push_back(candidate);
2563 sortByName(candidates);
2595 std::set<std::string> &exportedObjectNames =
_export->exportedObjectNames;
2597 if (exportedObjectNames.find(
name) != exportedObjectNames.end()) {
2600 auto const &arrayOfComponent =
_export->arrayOfComponent;
2601 if (
auto found = arrayOfComponent.find(
name); found != arrayOfComponent.end() && found->second !=
name) {
2602 error(
"'" +
name +
"' is written as a component of the array distribution '" + found->second +
2603 "', but another object refers to it by its own name. Set "
2604 "RooJSONFactoryWSTool::config().exportArrayDist = false to write it on its own.");
2609 exportedObjectNames.insert(
name);
2617 DepthGuard(
int &
d) : depth{
d} { ++depth; }
2618 ~DepthGuard() { --depth; }
2634 auto const *prod =
dynamic_cast<RooProdPdf const *
>(&func);
2637 "' of an array distribution, but it is not a RooProdPdf");
2639 for (
RooAbsPdf *pdf : static_range_cast<RooAbsPdf *>(prod->pdfList())) {
2641 if (writtenIn ==
name) {
2646 if (writtenIn != pdf->
GetName() &&
_export->arrayComponents.count(writtenIn)) {
2647 auto &components =
_export->arrayComponents[
name];
2648 if (components.empty()) {
2651 components.push_back(pdf);
2654 error(
"cannot write '" +
name +
"' as an array distribution: its component '" + pdf->
GetName() +
2655 "' is already written as '" + writtenIn +
"'");
2663 auto &collectionNode = (*
_export->root)[isPdf ?
"distributions" :
"functions"];
2671 auto it = exporters.find(cl);
2672 if (it != exporters.end()) {
2673 for (
auto &exp : it->second) {
2676 if (!exp->exportObject(
this, &func, elem)) {
2681 elem[
"name"] <<
name;
2687 elem[
"name"] <<
name;
2690 if (!
_export->channelConstraints.empty()) {
2691 _export->doc.rooFit.channelConstraints[
name] = std::move(
_export->channelConstraints);
2693 _export->channelConstraints.clear();
2695 recordGenericObject(
_export->doc, isPdf,
name, elem);
2697 if (exp->autoExportDependants()) {
2709 std::cerr <<
"unable to export '" <<
name <<
"' of class '" << cl->
GetName()
2710 <<
"': no exporter is registered for this class, or none of them could handle the object. Check "
2711 "https://root.cern/doc/master/group__roofit__dev__docs__hs3.html to see how to write one!\n";
2721 const std::string pdfName = pdf.
GetName();
2722 auto &arrayOfComponent =
_export->arrayOfComponent;
2723 auto &arrayComponents =
_export->arrayComponents;
2724 auto &exportedObjectNames =
_export->exportedObjectNames;
2725 if (
auto it = arrayOfComponent.find(pdfName); it != arrayOfComponent.end()) {
2729 if (exportedObjectNames.find(pdfName) != exportedObjectNames.end()) {
2732 if (arrayComponents.find(arrayName) == arrayComponents.end()) {
2735 error(
"cannot write the array distribution '" + arrayName +
2736 "': the workspace has another object of that name");
2738 exportedObjectNames.insert(arrayName);
2740 arrayComponents[arrayName].push_back(&pdf);
2741 arrayOfComponent[pdfName] = arrayName;
2742 exportedObjectNames.insert(pdfName);
2750 std::set<std::string> written;
2751 auto &arrayComponents =
_export->arrayComponents;
2753 auto next = std::find_if(arrayComponents.begin(), arrayComponents.end(),
2754 [&](
auto const &item) { return written.find(item.first) == written.end(); });
2755 if (next == arrayComponents.end()) {
2758 const std::string arrayName = next->first;
2759 written.insert(arrayName);
2761 const std::vector<RooAbsPdf const *> components = next->second;
2764 recordGenericObject(
_export->doc,
true, arrayName, elem);
2765 for (
RooAbsPdf const *pdf : components) {
2781 auto found =
_export->constraintObservables.find(pdfName);
2782 return found ==
_export->constraintObservables.end() ? nullptr : &found->second;
2787 auto &out =
_export->constraintTermsOfPdf[pdfName];
2788 for (
auto const &term : terms) {
2789 addUnique(out, term);
2797 std::string
const &dataName)
2799 std::vector<RooAbsPdf const *> components;
2800 if (
auto found =
_export->arrayComponents.find(term); found !=
_export->arrayComponents.end()) {
2801 components = found->second;
2804 for (
RooAbsArg const *factor : product->pdfList()) {
2805 components.push_back(
static_cast<RooAbsPdf const *
>(factor));
2808 components.push_back(pdf);
2810 std::vector<std::string> observables;
2811 for (
RooAbsPdf const *pdf : components) {
2813 if (!info || !globalObservables || !globalObservables->
find(info->observable.c_str())) {
2816 observables.push_back(info->observable);
2818 if (observables.empty()) {
2821 if (!
_export->writtenConstraintData.insert(dataName).second) {
2825 error(
"cannot write the observed values of the constraint term '" + term +
"' as the data set '" + dataName +
2826 "': the workspace has a data set of that name");
2829 for (std::string
const &
name : observables) {
2832 error(
"the observable '" +
name +
"' of the constraint term '" + term +
"' is not in the workspace");
2837 if (
auto const *rrv =
dynamic_cast<RooRealVar const *
>(var)) {
2838 axis = toContinuousAxis(*rrv);
2840 data.axes.emplace_back(std::move(axis));
2844 if (
data.axes.size() == 1) {
2847 point.
axes.push_back(std::get<HS3::ContinuousAxis>(
data.axes.front()));
2848 _export->doc.data.push_back({dataName, std::move(point)});
2851 _export->doc.data.push_back({dataName, std::move(
data)});
2872 combined.
columns.push_back(column->GetName());
2877 std::set<RooAbsArg const *> replaced;
2878 std::vector<RooAbsArg const *> replacements;
2882 for (std::vector<std::string>
const &key :
selectionKeys(columns)) {
2883 const std::string label =
selectionLabel(indexCat, columns, key);
2889 auto found = renamed->second.find(label);
2890 if (found != renamed->second.end()) {
2891 replaced.insert(pdf);
2892 pdf = found->second;
2893 replacements.push_back(pdf);
2898 _export->doc.distributions.push_back({simPdf.
GetName(), std::move(combined)});
2900 std::vector<RooAbsArg const *> servers;
2902 if (replaced.count(server) == 0) {
2903 servers.push_back(server);
2906 servers.insert(servers.end(), replacements.begin(), replacements.end());
2917 if (found !=
_export->categories.end() && found->second.categories != axis.
categories) {
2919 "' is written to the domain twice, with different states");
2949 std::string prefix = genPrefix(
p,
true);
2950 if (!prefix.empty())
2952 if (!
p.has_child(
"type")) {
2956 std::string functype(
p[
"type"].val());
2959 if (!importAllDependants) {
2963 auto it = importers.find(functype);
2965 if (it != importers.end()) {
2966 for (
auto &imp : it->second) {
2967 ok = imp->importArg(
this,
p);
2974 "RooJSONFactoryWSTool() no handling for type '" + functype +
2975 "' implemented. Check https://root.cern/doc/master/group__roofit__dev__docs__hs3.html "
2976 "to see how to write an importer for it!");
2982 for (std::string
const &component : recorder.unreadComponents()) {
2983 warning(
"RooFitHS3: " +
name +
": unknown component \"" + component +
"\" is ignored");
2990 if (
auto const *generic = std::get_if<HS3::GenericObject>(&distribution.
body)) {
2994 std::string
const &
name = distribution.
name;
3003 if (
auto const *combined = std::get_if<HS3::CombinedDist>(&distribution.
body)) {
3013 this->
importFunction((JSONTree::create(jsonString))->rootnode(), importAllDependants);
3039 if (!
config().renameCombinedObservables) {
3042 std::vector<RooAbsData *> datasets;
3044 datasets.push_back(
data);
3046 sortByName(datasets);
3049 if (columns.empty()) {
3053 for (std::vector<std::string>
const &key :
selectionKeys(columns)) {
3054 const std::string keyName = selectionKeyName(key);
3060 component = simPdf->
getPdf(label);
3065 candidates.
add(*observables);
3069 std::vector<RooAbsArg *> observables;
3072 observables.push_back(arg);
3075 sortByName(observables);
3076 std::map<std::string, std::string> renames;
3077 for (
RooAbsArg const *obs : observables) {
3078 std::string
const newName =
3079 "obs_" + keyName + (observables.size() == 1 ?
"" :
"_" + std::string(obs->GetName()));
3080 if (newName == obs->GetName()) {
3084 error(
"can't rename the observable '" + std::string(obs->GetName()) +
"' of the data set '" +
3085 data->GetName() +
"' to '" + newName +
"': an object of that name already exists");
3087 renames[obs->GetName()] = newName;
3089 if (renames.empty()) {
3099 for (
auto const &[from, to] : renames) {
3104 auto *renamedComponent =
static_cast<RooAbsPdf *
>(customizer.build());
3124 std::string
const name =
data.GetName();
3127 combined.
columns.push_back(column->GetName());
3133 std::unique_ptr<RooSuperCategory> superCat;
3135 std::vector<std::unique_ptr<RooAbsData>> parts;
3138 parts =
data.split(*simPdf,
true);
3139 }
else if (columns.size() == 1) {
3140 indexCat = columns.front();
3141 parts =
data.split(*indexCat,
true);
3145 inputs.
add(*column);
3147 const std::string superName =
name +
"_key";
3148 superCat = std::make_unique<RooSuperCategory>(superName.c_str(), superName.c_str(), inputs);
3149 indexCat = superCat.get();
3150 parts =
data.split(*indexCat,
true);
3154 std::vector<RooAbsData *> subDataSets;
3155 for (std::vector<std::string>
const &key :
selectionKeys(columns)) {
3156 std::string
const label =
selectionLabel(*indexCat, columns, key);
3157 auto found = std::find_if(parts.begin(), parts.end(), [&](
auto &
d) { return d->GetName() == label; });
3158 if (found == parts.end() || ((*found)->numEntries() == 0 && simPdf && !simPdf->
getPdf(label))) {
3161 const std::string keyName = selectionKeyName(key);
3162 const std::string subName =
name +
"_" + keyName;
3163 (*found)->SetName(subName.c_str());
3167 auto renames = renamesOfData->second.find(keyName);
3168 if (renames != renamesOfData->second.end()) {
3169 for (
auto const &[from, to] : renames->second) {
3170 (*found)->changeObservableName(from.c_str(), to.c_str());
3174 combined.
components.push_back({key, {subName}});
3175 subDataSets.push_back(found->get());
3177 _export->doc.data.push_back({
name, std::move(combined)});
3188 error(
"the data set '" + std::string(
data.GetName()) +
"' has the categorical observable '" + obs->GetName() +
3189 "', which is not a RooCategory, and can't be written as a combined data set");
3193 auto write = [&](
auto body) {
_export->doc.data.push_back({
data.GetName(), std::move(body)}); };
3202 if (
auto weightVar = variables.find(
"weightVar")) {
3203 variables.remove(*weightVar);
3208 for (
RooAbsArg const *arg : variables) {
3209 if (
auto const *cat =
dynamic_cast<RooCategory const *
>(arg)) {
3218 return write(toBinnedData(variables, dh->numEntries(), dh->weightArray()));
3228 if (
data.isWeighted() && variables.size() == 1 &&
dynamic_cast<RooRealVar const *
>(variables[0]) &&
3230 auto &
x =
static_cast<RooRealVar const &
>(*variables[0]);
3231 std::vector<double> contents;
3233 for (; i <
data.numEntries(); ++i) {
3235 if (
x.getBin() != i)
3237 contents.push_back(
data.weight());
3241 if (i ==
x.getBins() &&
data.numEntries() ==
x.getBins()) {
3242 return write(toBinnedData(variables, contents.size(), contents.data()));
3247 if (variables.size() == 1 &&
data.numEntries() == 1) {
3249 auto const *var =
dynamic_cast<RooRealVar const *
>(variables[0]);
3250 if (var && (!
data.isWeighted() ||
data.weight() == 1.)) {
3253 point.
axes.push_back(toContinuousAxis(*var));
3254 return write(std::move(point));
3260 for (
RooAbsArg const *arg : variables) {
3262 if (
auto const *cat =
dynamic_cast<RooCategory const *
>(arg)) {
3263 unbinned.axes.emplace_back(toCategoricalAxis(*cat));
3266 auto const &var =
static_cast<RooRealVar const &
>(*arg);
3267 unbinned.axes.emplace_back(toContinuousAxis(var));
3270 std::vector<double> weights;
3271 for (
int i = 0; i <
data.numEntries(); ++i) {
3274 for (
RooAbsArg const *arg : variables) {
3275 if (
auto const *cat =
dynamic_cast<RooCategory const *
>(arg)) {
3278 unbinned.entries.push_back(
static_cast<RooRealVar const *
>(arg)->
getVal());
3281 weights.push_back(
data.weight());
3284 if (std::any_of(weights.begin(), weights.end(), [](
double weight) { return weight != 1.; })) {
3285 unbinned.weights = std::move(weights);
3287 write(std::move(unbinned));
3301std::unique_ptr<RooDataHist>
3304 if (!
n.has_child(
"contents"))
3307 JSONNode const &contents =
n[
"contents"];
3312 std::vector<double> contentVals;
3313 contentVals << contents;
3315 if (!
n.has_child(
"errors")) {
3318 if (!
n[
"errors"].is_seq())
3320 std::vector<double> errorVals;
3321 errorVals <<
n[
"errors"];
3333 if (
p.value && std::holds_alternative<std::string>(*
p.value))
3335 if (!
_import->ranges.contains(
p.name)) {
3337 auto const &attributes =
_import->document.rooFit.attributes;
3338 auto found = attributes.find(
p.name);
3339 if (found != attributes.end() && found->second.isConstVar) {
3343 wsEmplace<RooConstVar>(
p.name, std::get<double>(*
p.value));
3347 RooRealVar &var = wsEmplace<RooRealVar>(
p.name, 1.);
3348 configureVariable(
_import->ranges,
p, var);
3356 warning(std::string(
"RooFitHS3: the parameter '") + var.
GetName() +
3357 "' is not listed in any domain and is not constant: HS3 requires a domain, or \"const\": true. It "
3358 "is read as a free parameter without range.");
3365 for (
const char *section : {
"functions",
"distributions"}) {
3366 if (
auto seq =
n.find(section)) {
3367 for (
const auto &
p : seq->children()) {
3376 const std::vector<RooAbsData *> &singleDataSets)
3378 std::vector<std::string> dataNames;
3381 const std::vector<std::string> columns = namesOf(
selectionColumns(simpdf->indexCat()));
3383 auto const *combined = std::get_if<HS3::CombinedData>(&
data.body);
3384 if (combined && combined->columns == columns) {
3385 dataNames.push_back(
data.name);
3391 dataNames.push_back(
data->GetName());
3397 for (std::string
const &dataName : dataNames) {
3400 if (dataNames.empty()) {
3409std::vector<RooAbsPdf const *> channelsOf(
RooAbsPdf const &pdf, std::map<std::string, RooAbsPdf const *>
const &renamed)
3415 std::vector<RooAbsPdf const *> channels;
3416 for (
auto const &item : simPdf->indexCat()) {
3417 auto found = renamed.find(item.first);
3418 if (
RooAbsPdf const *component = found != renamed.end() ? found->second : simPdf->getPdf(item.first)) {
3419 channels.push_back(component);
3426struct ChannelConstraint {
3427 std::string channel;
3429 bool histFactory =
false;
3431 bool wholeChannel =
false;
3447std::vector<ChannelConstraint>
3449 std::function<
bool(std::string
const &)>
const &isHistFactoryChannel,
3450 std::vector<RooAbsPdf const *>
const &channels)
3454 std::unique_ptr<RooArgSet> constraints{pdf.
getAllConstraints(observables, params,
false)};
3455 std::vector<ChannelConstraint> out;
3456 for (
RooAbsPdf const *channel : channels) {
3457 auto const *prod =
dynamic_cast<RooProdPdf const *
>(channel);
3461 const bool histFactory = isHistFactoryChannel(prod->GetName());
3464 if (!histFactory && !prod->pdfList().empty() &&
3465 std::all_of(prod->pdfList().begin(), prod->pdfList().end(),
3466 [&](
RooAbsArg const *factor) { return constraints->find(*factor) != nullptr; })) {
3467 out.push_back({prod->GetName(), prod,
false,
true});
3472 bool usedElsewhere =
false;
3473 for (
RooAbsArg const *client : prod->clients()) {
3474 if (ws.
arg(client->GetName()) == client && !
dynamic_cast<RooSimultaneous const *
>(client)) {
3475 usedElsewhere =
true;
3478 if (usedElsewhere) {
3483 auto const *nested =
dynamic_cast<RooProdPdf const *
>(&term);
3484 if (!histFactory || !nested) {
3485 out.push_back({prod->GetName(), &term, histFactory});
3488 for (
RooAbsArg const *factor : nested->pdfList()) {
3489 add(
static_cast<RooAbsPdf const &
>(*factor));
3492 for (
RooAbsArg const *factor : prod->pdfList()) {
3493 if (constraints->
find(*factor)) {
3494 add(
static_cast<RooAbsPdf const &
>(*factor));
3504 std::string
const *dataName)
3510 analysis.
name = analysisName;
3514 likelihood.
name = analysisName +
"_likelihood";
3521 likelihood.
terms.push_back({{pdf->
GetName()}, std::monostate{}});
3531 std::vector<std::string> auxiliaryChannelsOfModel;
3532 std::vector<std::string> constraintTerms;
3536 for (
const auto &constr : *external) {
3537 auto array =
_export->arrayOfComponent.find(constr->GetName());
3538 if (array ==
_export->arrayOfComponent.end()) {
3539 addUnique(constraintTerms, constr->GetName());
3542 for (
RooAbsPdf const *component :
_export->arrayComponents[array->second]) {
3543 if (!external->find(*component)) {
3544 error(
"cannot write the external constraint '" + std::string(constr->GetName()) +
"' of '" +
3545 mc.
GetName() +
"': it is written as a component of the array distribution '" + array->second +
3546 "', whose component '" + component->
GetName() +
"' is not an external constraint");
3549 addUnique(constraintTerms, array->second);
3555 auto writtenByHistFactory = [&](std::string
const &channel) {
3556 std::vector<std::string> out;
3557 if (
auto found =
_export->constraintTermsOfPdf.find(channel); found !=
_export->constraintTermsOfPdf.end()) {
3558 for (std::string
const &term : found->second) {
3559 addUnique(out, term);
3563 for (
auto const &ref : found->second) {
3564 addUnique(out, ref.name);
3570 if (!observables || observables->
empty()) {
3573 for (
RooAbsPdf const *channel : channels) {
3574 for (std::string
const &term : writtenByHistFactory(channel->
GetName())) {
3575 addUnique(constraintTerms, term);
3579 auto isHistFactoryChannel = [&](std::string
const &
name) {
3584 std::map<std::string, std::vector<std::string>> termsOfChannel;
3585 for (ChannelConstraint
const &item :
3586 constraintsOfChannels(
_workspace, *pdf, *observables, isHistFactoryChannel, channels)) {
3587 if (item.wholeChannel) {
3588 auxiliaryChannelsOfModel.push_back(item.channel);
3592 std::string term = item.constraint->GetName();
3593 if (
auto found =
_export->arrayOfComponent.find(term); found !=
_export->arrayOfComponent.end()) {
3594 term = found->second;
3596 addUnique(termsOfChannel[item.channel], term);
3598 for (
RooAbsPdf const *channelPdf : channels) {
3599 std::string
const channel = channelPdf->
GetName();
3600 std::vector<std::string>
const &found = termsOfChannel[channel];
3601 if (!isHistFactoryChannel(channel)) {
3602 for (std::string
const &term : found) {
3603 addUnique(constraintTerms, term);
3610 std::vector<std::string>
const written = writtenByHistFactory(channel);
3611 std::set<std::string>
const writtenSet{written.begin(), written.end()};
3612 std::set<std::string>
const foundSet{found.begin(), found.end()};
3613 if (writtenSet != foundSet) {
3614 auto join = [](std::set<std::string>
const &names) {
3616 for (std::string
const &
name : names) {
3617 out += (out.empty() ?
"'" :
", '") +
name +
"'";
3619 return out.empty() ? std::string{
"none"} : out;
3621 error(
"cannot export the constraint terms of the HistFactory channel '" + channel +
3622 "': the channel writes " + join(writtenSet) +
", but RooFit finds " + join(foundSet));
3624 for (std::string
const &term : written) {
3625 addUnique(constraintTerms, term);
3637 auto findCombinedData = [&]() {
return dataName ? HS3::find<HS3::CombinedData>(doc.
data, *dataName) :
nullptr; };
3639 if (simPdf && findCombinedData()) {
3641 if (columns.size() == 1) {
3642 indexColumn = columns.front();
3645 auto addAuxiliaryChannel = [&](std::string
const &term) {
3647 error(
"cannot write the constraint term '" + term +
"' as a component of the combined distribution '" +
3648 simPdf->
GetName() +
"': its index category '" + indexColumn->
GetName() +
"' has a state of that name");
3650 addUnique(
_export->auxiliaryLabels[indexColumn->
GetName()], term);
3652 if (!combinedDist) {
3653 error(
"cannot write the constraint terms of '" + std::string(simPdf->
GetName()) +
3654 "' as its components: it was not written as a combined distribution");
3656 if (!combinedDist->find({term})) {
3657 combinedDist->components.push_back({{term}, {term}});
3661 combinedData->components.push_back({{term},
HS3::DataRef{*dataName +
"_" + term}});
3667 for (std::string
const &channel : auxiliaryChannelsOfModel) {
3668 if (!indexColumn || likelihood.
pureModel) {
3672 for (
auto const &state : simPdf->
indexCat()) {
3674 if (component && channel == component->
GetName()) {
3675 label = state.first;
3678 if (label.empty()) {
3681 auto const *component = findCombinedData()->find({label});
3682 const std::string observed = component ? component->ref.name : *dataName +
"_" + label;
3684 auto written = std::find_if(doc.
data.begin(), doc.
data.end(), [&](
auto const &
d) { return d.name == observed; });
3685 if (written == doc.
data.end() || written->numEntries() == 0) {
3686 std::optional<HS3::Data> empty;
3687 if (written != doc.
data.end()) {
3688 empty = std::move(*written);
3689 doc.
data.erase(written);
3693 combinedData->components.push_back({{label},
HS3::DataRef{observed}});
3697 doc.
data.push_back(std::move(*empty));
3699 warning(
"RooFitHS3: the channel '" + channel +
"' of '" + simPdf->
GetName() +
3700 "' consists of constraint terms, but has no data, and its observables are not all global "
3701 "observables of the ModelConfig: it is written without an observation.");
3707 marked.push_back({channel});
3710 for (std::string
const &term : constraintTerms) {
3714 const bool asChannel = indexColumn &&
_export->arrayComponents.count(term);
3715 const std::string constraintData = asChannel ? *dataName +
"_" + term : term +
"_data";
3719 addAuxiliaryChannel(term);
3730 std::vector<std::string> names = namesOf(*pois);
3731 std::sort(names.begin(), names.end());
3732 for (
auto const &
name : names) {
3737 auto writeProductDomain = [&](
const char *suffix,
RooArgSet const *args) {
3738 if (!args || args->
empty())
3741 domain.
name = analysisName + suffix;
3745 for (
auto *var : static_range_cast<const RooRealVar *>(sorted)) {
3762 doc.
analyses.push_back(std::move(analysis));
3770 std::sort(names.begin(), names.end());
3778 _export = std::make_unique<HS3::ToolExportState>();
3780 StateScope<HS3::ToolExportState> exportScope{
_export};
3794 RooArgSet const *globs = mc ? mc->GetGlobalObservables() :
nullptr;
3799 auto const *gauss =
dynamic_cast<RooGaussian const *
>(arg);
3800 if (gauss && globs->
find(gauss->getMean()) && !globs->
find(gauss->getX()) &&
3816 std::vector<RooAbsData *> alldata;
3818 alldata.push_back(
d);
3820 sortByName(alldata);
3822 std::vector<RooAbsData *> singleData;
3823 for (
auto &
d : alldata) {
3829 singleData.push_back(
d);
3850 if (std::any_of(allpdfs.begin(), allpdfs.end(), [&](
RooAbsPdf *pdf) { return pdf->dependsOn(*arg); })) {
3852 snapshotSorted.
add(*arg);
3855 snapshotSorted.
sort();
3856 std::string
name(snsh->GetName());
3857 if (
name !=
"default_values") {
3865 for (
auto const &item :
_export->auxiliaryLabels) {
3866 auto &categories =
_export->categories[item.first].categories;
3867 for (std::string
const &label : item.second) {
3868 if (std::find(categories.begin(), categories.end(), label) == categories.end()) {
3869 categories.push_back(label);
3875 for (
auto const &item :
_export->categories) {
3876 if (defaultAxes.count(item.first)) {
3878 "' is categorical, but the domain already lists it as continuous");
3882 for (
auto &item :
_export->domains) {
3884 appendDomain(doc.
domains, item.first, std::move(item.second),
3886 : std::map<std::string, HS3::CategoricalAxis>{});
3893 if (
n.has_child(
"distributions")) {
3894 std::map<std::string, JSONNode *> nodes;
3895 for (
JSONNode &node :
n[
"distributions"].children()) {
3896 nodes.emplace(
name(node), &node);
3899 auto found = nodes.find(dist.name);
3900 if (found == nodes.end()) {
3903 if (
auto *generic = std::get_if<HS3::GenericObject>(&dist.body)) {
3904 generic->node = found->second;
3905 }
else if (
auto const *combined = std::get_if<HS3::CombinedDist>(&dist.body)) {
3915 for (std::string
const &factor : factors) {
3916 oocoutI(
nullptr, IO) <<
"RooFitHS3: '" << factor <<
"' is a factor of '" << product
3917 <<
"' and a term of its likelihood; it is written once, as a term of the likelihood"
3927 validateOptions.
isExternal = [](std::string
const &) {
return false; };
3930 for (
auto &diagnostic : diagnostics) {
3931 diagnostic.severity = HS3::Diagnostic::Severity::Warning;
3932 diagnostic.message =
"the exported document is not valid: " + diagnostic.message;
3940 if (!
config().allowExportSharedVariates) {
3942 for (std::string
const &
message : shared) {
3946 ". HS3 requires the terms of a likelihood and the components of a combined distribution to have "
3947 "distinct variates: give the variates their own names (e.g. 'mass_SR' and 'mass_CR' instead of "
3948 "'mass'; RooJSONFactoryWSTool::config().renameCombinedObservables does this for the observables of "
3949 "combined data sets), or set RooJSONFactoryWSTool::config().allowExportSharedVariates = true to "
3950 "write the document anyway, with a warning, and rename them in the JSON.");
3952 for (std::string
const &
message : shared) {
3954 ". HS3 requires distinct variates: the document is not valid HS3, and can't be read back before the "
3955 "variates are renamed.");
3963 std::stringstream ss(s);
3970 std::stringstream ss;
3978 std::unique_ptr<JSONTree> tree = JSONTree::create();
3979 JSONNode &
n = tree->rootnode().set_map();
3988 std::ofstream out(
filename.c_str());
3998 auto const &attributes =
_import->document.rooFit.attributes;
3999 auto found = attributes.find(obj);
4000 if (found == attributes.end())
4002 auto const &tags = found->second.tags;
4003 return std::find(tags.begin(), tags.end(), attrib) != tags.end();
4007 _export->doc.rooFit.attributes[obj].tags.push_back(attrib);
4014 auto const &attributes =
_import->document.rooFit.attributes;
4015 auto found = attributes.find(obj);
4016 if (found == attributes.end())
4018 auto value = found->second.dict.find(attrib);
4019 return value != found->second.dict.end() ?
value->second :
"";
4022 const std::string &
value)
4024 _export->doc.rooFit.attributes[obj].dict[attrib] =
value;
4033 auto histFactoryImporters = importers.find(
"histfactory_dist");
4034 options.
typedHistFactory = histFactoryImporters != importers.end() && !histFactoryImporters->second.empty() &&
4040 std::optional<RooFit::ValidatedHS3Document> validated;
4045 validated =
HS3::validate(std::move(parsed), diagnostics, validateOptions);
4050 std::set<std::string>
const bookkeepingColumns = checkVariates(validated->doc());
4061 StateScope<HS3::ToolImportState> importScope{
_import};
4062 _import = std::make_unique<HS3::ToolImportState>(doc);
4067 for (
auto const &
p :
_import->defaultValues->parameters) {
4071 for (
auto const &function : doc.
functions) {
4085 for (
auto const &var : point.parameters) {
4086 std::string
const *label = var.value ? std::get_if<std::string>(&*var.value) :
nullptr;
4090 }
else if (var.value) {
4091 cat->
setIndex(
static_cast<int>(std::get<double>(*var.value)));
4097 warning(
"RooFitHS3: ignoring the string value of parameter '" + var.name +
"' in parameter point '" +
4098 point.name +
"', because there is no category with that name.");
4106 rrv = &wsEmplace<RooRealVar>(var.name, 1.);
4107 configureVariable(
_import->ranges, var, *rrv);
4110 configureVariable(
_import->ranges, var, *rrv);
4121 importAttributes(arg, item.second);
4127 std::vector<std::unique_ptr<RooAbsData>> datasets;
4128 datasets.reserve(doc.
data.size());
4129 for (
auto const &
data : doc.
data) {
4130 if (!std::holds_alternative<HS3::CombinedData>(
data.body)) {
4134 assembleCombinedData(doc,
_workspace, datasets);
4136 for (
auto const &analysis : doc.
analyses) {
4137 importAnalysis(doc, analysis,
_workspace, datasets, bookkeepingColumns, auxiliary.
terms);
4140 combineDatasets(doc, datasets);
4144 for (
auto &
d : datasets) {
4145 if (
d && auxiliary.
data.count(
d->GetName())) {
4150 for (
auto const &
d : datasets) {
4153 for (
auto const &obs : *
d->get()) {
4154 if (
auto *rrv =
dynamic_cast<RooRealVar *
>(obs)) {
4155 _workspace.
var(rrv->GetName())->setBinning(rrv->getBinning());
4172 std::unique_ptr<JSONTree> tree = JSONTree::create(is);
4180 std::ifstream infile(
filename.c_str());
4181 if (!infile.is_open())
4192 if (
n.find(
"poi")) {
4195 std::string poi =
n.find(
"poi")->val();
4196 std::string pdname =
n.find(
"pdfName")->val();
4198 modelConfig.SetPdf(pdname.c_str());
4211 }
else if (
type->val() ==
"binned" ||
type->val() ==
"unbinned") {
4227 if (!
value && !(min && max)) {
4228 throw std::invalid_argument(
"Invalid Syntax: Please provide either 'value' or 'min' and 'max' or both");
4231 axis.
name = elementNode[
"name"].
val();
4235 axis.
min = min->val_double();
4236 axis.
max = max->val_double();
4244 StateScope<HS3::ToolImportState> importScope{
_import};
4245 _import = std::make_unique<HS3::ToolImportState>(doc);
4249 configureVariable(
_import->ranges, parameter, *rrv);
4263 throw std::runtime_error(s);
4272 for (
char c : str) {
4277 case '(':
result +=
'_';
break;
4282 case '.':
result +=
"_dot_";
break;
4283 case '@':
result +=
"at";
break;
4284 case '-':
result +=
"minus";
break;
4285 case '/':
result +=
"_div_";
break;
4298 if (onlyModelConfig) {
4307 for (
auto *pdf : ws.
allPdfs()) {
4308 if (isTopLevel(*pdf, ws)) {
4314 if (isTopLevel(*func, ws)) {
4333 auto *snshSet =
dynamic_cast<RooArgSet *
>(snsh);
4335 tmpWS.
saveSnapshot(snshSet->GetName(), *snshSet,
true);
4354 auto sanitize = [](
auto const &objects) {
4355 for (
auto *obj : objects) {
4366 sanitize(*
data->get());
4371 auto *snsh =
dynamic_cast<RooArgSet *
>(snshObj);
4373 std::cerr <<
"Warning: found snapshot that is not a RooArgSet, skipping\n";
4381 if (
auto *named =
dynamic_cast<TNamed *
>(obj)) {
4382 named->SetName(
sanitizeName(named->GetName()).c_str());
4384 std::cerr <<
"Warning: object " << obj->GetName() <<
" is not TNamed, cannot rename.\n";
4387 sanitize(*mc->GetObservables());
4388 sanitize(*mc->GetParametersOfInterest());
4389 sanitize(*mc->GetNuisanceParameters());
4390 sanitize(*mc->GetGlobalObservables());
4394 newWS.
SetName((std::string{ws.
GetName()} +
"_sanitized").c_str());
void writeArrayDist(RooJSONFactoryWSTool &tool, JSONNode &elem, std::string const &name, std::vector< RooAbsPdf const * > const &components)
std::optional< ArrayComponentInfo > arrayComponentInfo(RooAbsPdf const &pdf, std::string const *observable, RooJSONFactoryWSTool *tool)
std::optional< double > toNumber(const std::string &str)
std::vector< std::vector< std::string > > selectionKeys(std::vector< RooCategory const * > const &columns)
void writeReference(JSONNode &node, RooAbsArg const &arg)
bool isLiteralIdentifier(std::string_view name)
std::string transformedBaseName(RooAbsReal const ¶m)
std::vector< RooCategory const * > selectionColumns(RooAbsCategory const &indexCat)
std::string transformedArgument(RooAbsReal const ¶m)
std::string selectionKeyToString(std::vector< std::string > const &key)
bool startsWith(std::string_view str, std::string_view prefix)
bool endsWith(std::string_view str, std::string_view suffix)
std::string selectionLabel(std::vector< std::string > const &key)
bool isLiteralConstVar(RooAbsArg const &arg)
constexpr const char * helperObjectTag
constexpr const char * arrayDistTag
ROOT::RRangeCast< T, false, Range_t > static_range_cast(Range_t &&coll)
static unsigned int total
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 input
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 filename
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 char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
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 child
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 char Point_t Rectangle_t WindowAttributes_t attr
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
Option_t Option_t TPoint TPoint const char text
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.
TClass * IsA() const override
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
bool isConstant() const
Check if the "Constant" attribute is set.
virtual TObject * clone(const char *newname=nullptr) const =0
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...
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
RooFit::OwningPtr< RooArgSet > getComponents() const
Create a RooArgSet with all components (branch nodes) of the expression tree headed by this object.
const RefCountList_t & servers() const
List of all servers of this object.
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.
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
void leafNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all leaf nodes of the arg tree, starting with ourself as top node.
Abstract base class for RooRealVar binning definitions.
Int_t numBins() const
Return number of bins.
virtual double binLow(Int_t bin) const =0
virtual bool isUniform() const
virtual double highBound() const =0
virtual double lowBound() const =0
virtual double binHigh(Int_t bin) const =0
Abstract base class for objects that represent a discrete value that can be set from the outside,...
A space to attach TBranches.
unsigned int getCurrentOrdinalNumber() const
Return ordinal number of the current state.
bool hasLabel(const std::string &label) const
Check if a state with name label exists.
virtual const char * getCurrentLabel() const
Return label string of current state.
const std::map< std::string, value_type >::value_type & getOrdinal(unsigned int n) const
Return name and index of the nth defined state.
std::size_t size() const
Number of states defined.
const RooCatType * defineType(const char *label)
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 void removeAll()
Remove all arguments from our set, deleting them if we own them.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
const char * GetName() const override
Returns name of object.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
const_iterator end() const
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
Storage_t::size_type size() const
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
virtual RooAbsArg * addClone(const RooAbsArg &var, bool silent=false)
Add a clone of the specified argument to list.
const_iterator begin() const
void sort(bool reverse=false)
Sort collection using std::sort and name comparison.
virtual bool containsInstance(const RooAbsArg &var) const
Check if this exact instance is in this collection.
void setName(const char *name)
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Abstract base class for objects that are lvalues, i.e.
virtual Int_t numBins(const char *rangeName=nullptr) const =0
Abstract interface for all probability density functions.
std::unique_ptr< RooArgSet > getAllConstraints(const RooArgSet &observables, RooArgSet &constrainedParams, bool stripDisconnected=true) const
This helper function finds and collects all constraints terms of all component p.d....
bool canBeExtended() const
If true, PDF can provide extended likelihood term.
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
virtual Int_t getBins(const char *name=nullptr) const
Get number of bins of currently defined range.
void setConstant(bool value=true)
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...
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.
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
bool containsInstance(const RooAbsArg &var) const override
Check if this exact instance is in this collection.
Implements a RooAbsBinning in terms of an array of boundary values, posing no constraints on the choi...
Object to represent discrete states.
bool setIndex(Int_t index, bool printError=true) override
Set value by specifying the index code of the desired state.
bool defineType(const std::string &label)
Define a state with given name.
bool setLabel(const char *label, bool printError=true) override
Set value by specifying the name of the desired state.
Named container for two doubles, two integers two object points and three string pointers that can be...
const char * getString(Int_t idx) const
Return string stored in slot idx.
Represents a constant real-valued object.
RooCustomizer is a factory class to produce clones of a prototype composite PDF object with the same ...
Container class to hold N-dimensional binned data.
Container class to hold unbinned data.
JSONNode & append_child()
size_t num_children() const
JSONNode const * find(std::string const &key) const
The component at the end of a path of keys, or nullptr if a component on the path doesn't exist.
bool has_child(std::string const &) const
Records which components of a JSON map are read while it is alive, through any node of the tree.
static std::unique_ptr< JSONTree > create()
An HS3 document. It is move-only, because generic objects refer to the JSON tree of the document.
std::vector< HS3::Analysis > analyses
std::vector< HS3::Data > data
std::vector< HS3::Likelihood > likelihoods
std::vector< HS3::Function > functions
std::vector< HS3::ParameterPoint > parameterPoints
HS3::RooFitInternal rooFit
std::vector< HS3::Domain > domains
std::vector< HS3::Distribution > distributions
Where RooFit takes the ranges of variables from: the "default_domain" if there is one,...
DomainAxis const * find(std::string const &name) const
The axis that defines the range of a variable, or null.
bool contains(std::string const &name) const
Whether any domain has the variable.
static RooMsgService & instance()
Return reference to singleton instance.
std::ostream & log(const RooAbsArg *self, RooFit::MsgLevel level, RooFit::MsgTopic topic, bool forceSkipPrefix=false)
Log error message associated with RooAbsArg object self at given level and topic.
static constexpr double infinity()
Return internal infinity representation.
static constexpr int isInfinite(double x)
Return true if x is infinite by RooNumber internal specification.
Efficient implementation of a product of PDFs of the form.
Binning/range definition that only defines a range but no binning.
Variable that can be changed from the outside.
void removeMin(const char *name=nullptr)
Remove lower range limit for binning with given name. Empty name means default range.
void setVal(double value) override
Set value of variable to 'value'.
void setError(double value)
void setMin(const char *name, double value, bool shared=true)
Set minimum of name range to given value.
void setRange(const char *name, double min, double max, bool shared=true)
Set a fit or plotting range.
void setBins(Int_t nBins, const char *name=nullptr, bool shared=true)
Create a uniform binning under name 'name' for this variable.
bool hasError(bool allowZero=true) const
void setBinning(const RooAbsBinning &binning, const char *name=nullptr, bool shared=true)
Add given binning under name 'name' with this variable.
void setMax(const char *name, double value, bool shared=true)
Set maximum of name range to given value.
void removeMax(const char *name=nullptr)
Remove upper range limit for binning with given name. Empty name means default range.
const RooAbsBinning & getBinning(const char *name=nullptr, bool verbose=true, bool createOnTheFly=false, bool shared=true) const override
Return binning definition with name.
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
RooAbsPdf * getPdf(RooStringView catName) const
Return the p.d.f associated with the given index category name.
const RooAbsCategoryLValue & indexCat() const
< A class that holds configuration information for a model using a workspace as a store
const std::string & GetSnapshotName() const
get the name of the workspace snapshot saved by SetSnapshot() (empty if there is none)
const RooArgSet * GetGlobalObservables() const
get RooArgSet for global observables (return nullptr if not existing)
const RooArgSet * GetParametersOfInterest() const
get RooArgSet containing the parameter of interest (return nullptr if not existing)
const RooArgSet * GetNuisanceParameters() const
get RooArgSet containing the nuisance parameters (return nullptr if not existing)
void SetWS(RooWorkspace &ws) override
Set a workspace that owns all the necessary components for the analysis.
const RooArgSet * GetObservables() const
get RooArgSet for observables (return nullptr if not existing)
const RooArgSet * GetExternalConstraints() const
get RooArgSet for global observables (return nullptr if not existing)
RooAbsPdf * GetPdf() const
get model PDF (return nullptr if pdf has not been specified or does not exist)
RooAbsPdf * GetPriorPdf() const
get parameters prior pdf (return nullptr if not existing)
Joins several RooAbsCategoryLValue objects into a single category.
Persistable container for RooFit projects.
TObject * obj(RooStringView name) const
Return any type of object (RooAbsArg, RooAbsData or generic object) with given name)
const RooArgSet * getSnapshot(const char *name) const
Return the RooArgSet containing a snapshot of variables contained in the workspace.
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
RooCategory * cat(RooStringView name) const
Retrieve discrete variable (RooCategory) with given name. A null pointer is returned if not found.
RooArgSet allVars() const
Return set with all variable objects.
RooArgSet argSet(RooStringView nameList) const
Return set of RooAbsArgs matching to given list of names.
RooArgSet allResolutionModels() const
Return set with all resolution model objects.
bool saveSnapshot(RooStringView, const char *paramNames)
Save snapshot of values and attributes (including "Constant") of given parameters.
RooArgSet allPdfs() const
Return set with all probability density function objects.
std::list< RooAbsData * > allData() const
Return list of all dataset in the workspace.
RooLinkedList const & getSnapshots() const
std::list< TObject * > allGenericObjects() const
Return list of all generic objects in the workspace.
RooAbsReal * function(RooStringView name) const
Retrieve function (RooAbsReal) with given name. Note that all RooAbsPdfs are also RooAbsReals....
RooAbsArg * arg(RooStringView name) const
Return RooAbsArg with given name. A null pointer is returned if none is found.
const RooArgSet & components() const
RooArgSet allFunctions() const
Return set with all function objects.
RooRealVar * var(RooStringView name) const
Retrieve real-valued variable (RooRealVar) with given name. A null pointer is returned if not found.
RooAbsData * data(RooStringView name) const
Retrieve dataset (binned or unbinned) with given name. A null pointer is returned if not found.
std::list< RooAbsData * > allEmbeddedData() const
Return list of all dataset in the workspace.
bool loadSnapshot(const char *name)
Load the values and attributes of the parameters in the snapshot saved with the given name.
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.
The TNamed class is the base class for all named ROOT classes.
const char * GetName() const override
Returns name of object.
virtual void SetName(const char *name)
Set the name of the TNamed.
Mother of all ROOT objects.
virtual const char * ClassName() const
Returns name of class to which the object belongs.
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
const char * Data() const
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
RooCmdArg RecycleConflictNodes(bool flag=true)
RooConstVar & RooConst(double val)
RooCmdArg Silence(bool flag=true)
RooCmdArg Index(RooCategory &icat)
RooCmdArg StoreError(const RooArgSet &aset)
RooCmdArg WeightVar(const char *name="weight", bool reinterpretAsWeight=false)
RooCmdArg Import(const char *state, TH1 &histo)
CoordSystem::Scalar get(DisplacementVector2D< CoordSystem, Tag > const &p)
double product(DoubleArray factors, std::size_t nFactors)
Types that represent an HS3 document.
AuxiliaryConstraints readAuxiliaryChannelsAsConstraints(ValidatedHS3Document &doc, bool asChannels)
RooFit writes an array of constraints with the data set of its observed values as a component of the ...
std::variant< std::string, double > NameOrNumber
A name, or a number for a constant.
std::vector< std::string > unlistedConstraints(HS3Document const &doc, std::vector< std::string > *warnings=nullptr)
In HS3 0.3 (HS3 PR #154, decision on HS3 #156), the "constraints" of a HistFactory modifier add no te...
void checkDocument(HS3Document const &doc, Diagnostics &diagnostics, ValidateOptions const &options={})
The checks of validate(), for a document that is still needed if it doesn't pass them.
auto findByName(Objects_t &objects, std::string const &name) -> decltype(&*objects.begin())
The object with the name name among the objects of a section, e.g. findByName(doc....
std::map< std::string, std::set< std::string > > writeLikelihoodTermsOnce(HS3Document const &doc, Detail::JSONNode &root)
Writes each term of the likelihoods once: a factor of a product that is a term of the likelihood as w...
std::string const & nameOf(std::variant< Ts... > const &v)
The name of the alternative that a variant holds, e.g. of an axis or of a modifier.
void buildCombinedDist(RooJSONFactoryWSTool &tool, std::string const &name, CombinedDist const &dist, std::vector< std::string > const &otherLikelihoodTerms={})
Create the RooSimultaneous of a combined distribution in the workspace of the tool.
std::variant< RegularBinning, EdgesBinning > Binning
std::set< std::string > variatesOf(HS3Document const &doc, Likelihood const &likelihood)
The variates of the "distributions" of a likelihood, which it pairs with data, with the columns of it...
std::map< std::string, std::set< std::string > > sharedAxes(HS3Document const &doc)
The axes that several components of a combined data set have, by combined data set.
constexpr char const * defaultDomainName
The domain in which RooFit writes the ranges of all variables. It is a convention of RooFit,...
std::optional< ValidatedHS3Document > validate(HS3Document doc, Diagnostics &diagnostics, ValidateOptions const &options)
Checks what can be checked without knowing how the objects are built: unique names,...
std::set< std::string > componentsWithData(HS3Document const &doc)
The distributions that are components of a combined distribution of a likelihood, with a component of...
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.
void writeDocument(Detail::JSONNode &root, HS3Document const &doc)
Writes everything but the distributions and functions, which are written one by one while they are ex...
void report(Diagnostics const &diagnostics, std::string const &object="")
Forward the warnings to the message service, and throw if there are errors.
void writeContents(Detail::JSONNode &node, std::vector< double > const &values)
Writes an array of numbers, each as an integer if it has no fractional part.
RooArgSet createObservables(std::vector< BinnedAxis > const &axes)
Create the variables for the axes of binned data.
std::string const * importedArrayComponentForm(RooJSONFactoryWSTool &tool, std::string const &name)
The canonical form (see arrayComponentForm()) of the component of an array distribution that this imp...
bool hasErrors(Diagnostics const &diagnostics)
Whether there is a diagnostic with error severity.
void recordImportedArrayComponent(RooJSONFactoryWSTool &tool, std::string const &name, std::string form)
Record that this import created the component name of an array distribution, with the canonical form ...
std::map< std::string, std::set< std::string > > bookkeepingColumns(HS3Document const &doc)
The bookkeeping columns by combined data set: the declared ones (RooFitInternal::bookkeepingColumns),...
void writeHistFactoryDist(Detail::JSONNode &node, HistFactoryDist const &dist)
Writes a HistFactory distribution, without its name.
std::vector< std::string > sharedVariates(HS3Document const &doc)
Describes each variate that is shared although it must be distinct: by the terms of a likelihood,...
std::vector< Diagnostic > Diagnostics
NameOrNumber toNameOrNumber(RooAbsArg const &arg)
The name of an object, or the value of a literal constant.
void upgradeDocument(Detail::JSONNode &root, Diagnostics &diagnostics, ParseOptions const &options={})
Rewrites everything that older versions of RooFit wrote in a way that is not part of the standard int...
std::vector< std::string > resolvePointData(ValidatedHS3Document &doc)
A number given in-line in the "data" of a likelihood, or a point data set without axes,...
BinnedAxis toBinnedAxis(RooRealVar const &var)
The axis of binned data for a variable, or for a binning of a variable with the given name.
void writeBinnedData(Detail::JSONNode &node, BinnedData const &data)
Writes the axes, contents and uncertainties of binned data, without its name and type.
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...
void writeCombinedDist(Detail::JSONNode &node, CombinedDist const &dist)
Writes a combined distribution, without its name.
Data parseData(Detail::JSONNode const &data, Diagnostics &diagnostics)
Reads a data set that doesn't come with a document.
bool isBuiltinHistFactoryImporter(JSONIO::Importer const &importer)
Whether this is the importer that RooFit registers for HistFactory distributions, as opposed to the o...
std::vector< BinnedAxis > parseBinnedAxes(Detail::JSONNode const &axes, Diagnostics &diagnostics)
Reads the axes of binned data that doesn't come with a document.
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.
HS3Document parseDocument(Detail::JSONNode const &root, Diagnostics &diagnostics, ParseOptions const &options={})
Reads a document.
void initialize(typename Architecture_t::Matrix_t &A, EInitialization m)
std::optional< DistributionRef > prior
std::optional< ParameterPointRef > init
std::vector< DomainRef > domains
std::vector< ParameterRef > parametersOfInterest
std::vector< std::string > tags
std::map< std::string, std::string > dict
What readAuxiliaryChannelsAsConstraints() changed.
std::set< std::string > data
Their data sets, which hold the observed values of global observables.
std::set< std::string > terms
The components that are no longer components of their combined distribution.
std::vector< std::string > warnings
std::vector< std::string > categories
The data set of a RooSimultaneous as older versions of RooFit wrote it. It is only read.
std::vector< int > indices
std::vector< std::string > labels
A RooSimultaneous as older versions of RooFit wrote it, before HS3 had combined distributions....
std::vector< std::string > labels
std::vector< DistributionRef > distributions
std::vector< int > indices
Data sets or distributions that are selected by a key (HS3 #119). The columns are categorical axes of...
CombinedComponent< Ref_t > const * find(std::vector< std::string > const &key) const
The component for a key, or nullptr.
std::vector< CombinedComponent< Ref_t > > components
std::vector< std::string > columns
The axis of point data or unbinned data, which can't have a binning.
std::optional< double > max
std::optional< double > min
std::variant< GenericObject, HistFactoryDist, CombinedDist > body
std::optional< double > min
std::optional< double > max
std::optional< Binning > binning
std::optional< double > fixedValue
std::vector< std::variant< DomainAxis, CategoricalAxis > > axes
std::vector< double > edges
A distribution or function that is not interpreted by the document, but by the importers that are reg...
The data of a likelihood term: a data set, a number given in-line, or none (std::monostate) in a pure...
DistributionRef distribution
std::variant< DataRef, double, std::monostate > data
bool pureModel
Whether "data" is null: the likelihood only groups the distributions of a model without data (e....
std::vector< DistributionRef > auxDistributions
std::vector< LikelihoodTerm > terms
std::optional< std::string > pdfName
std::optional< std::vector< std::string > > observables
The observables of the ModelConfig, written if no data set of the likelihood gives them.
std::optional< std::string > mcName
std::optional< std::string > combinedDataName
std::vector< ParameterValue > parameters
std::optional< std::variant< double, std::string > > value
A string selects the state of a category.
Options for upgradeDocument() and parseDocument().
bool typedHistFactory
If false, HistFactory distributions stay generic objects, because a user registered their own importe...
std::vector< ContinuousAxis > axes
A name that says what it refers to, so that for example a DataRef can't be used as a DomainRef.
std::map< std::string, Attributes > attributes
std::map< std::string, std::vector< DistributionRef > > auxiliaryChannels
The components of a combined distribution that are auxiliary measurements (constraint terms paired wi...
std::map< std::string, std::vector< DistributionRef > > channelConstraints
The constraint terms of HistFactory distributions that no modifier names, by distribution.
std::vector< StepWidth > stepWidths
std::map< std::string, std::vector< std::string > > bookkeepingColumns
Axes that the components of a combined data set share, but that are no variate of any distribution,...
std::map< std::string, ModelConfigInfo > modelConfigs
bool strict
Whether the document has to follow the current standard, or if older conventions of RooFit are tolera...
std::function< bool(std::string const &) isExternal)
Whether a name that is not defined in the document is known in some other way, e.g....