Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HS3Variates.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Carsten D. Burgard, DESY/ATLAS, Nov 2026
5 * Jonas Rembser, CERN, Nov 2026
6 *
7 * Copyright (c) 2026, CERN
8 *
9 * Redistribution and use in source and binary forms,
10 * with or without modification, are permitted according to the terms
11 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
12 */
13
14// HS3 requires the terms of a likelihood, and the components of a combined distribution or data set, to have distinct
15// variates: a variate in two of them is one quantity modelled twice (e.g. a constraint that is a term of the likelihood
16// and a factor of a channel), or two quantities with one name (e.g. the observable "mass" of two channels, which need
17// their own names, "mass_SR" and "mass_CR"). All cases are checked with the same function, sharedVariates(), on the
18// document, when it is exported and when it is imported. The generic distributions are read as far as the standard
19// says what they consist of, through the nodes that the document refers to.
20//
21// This file also has what else follows from which distribution is paired with which data: how often a constraint
22// contributes to a likelihood, and how a document is changed so that RooFit can read its auxiliary measurements and
23// its point data.
24
25#include "HS3Document.h"
26
28
29#include <algorithm>
30#include <functional>
31#include <cstdio>
32#include <iterator>
33#include <map>
34#include <set>
35#include <sstream>
36#include <string>
37#include <utility>
38#include <variant>
39#include <vector>
40
42
43namespace RooFit {
44namespace HS3 {
45namespace {
46
47// Append a name to a list that has every name once.
48void addUnique(std::vector<std::string> &names, std::string const &name)
49{
50 if (std::find(names.begin(), names.end(), name) == names.end()) {
51 names.push_back(name);
52 }
53}
54
55bool isName(JSONNode const &node)
56{
57 return !node.is_container() && !node.is_null() && !node.is_number();
58}
59
60// Add the names in `node` (one name or a list) to `out`.
61void addNames(JSONNode const &node, std::set<std::string> &out)
62{
63 if (node.is_seq()) {
64 for (JSONNode const &child : node.children()) {
65 addNames(child, out);
66 }
67 } else if (isName(node)) {
68 out.insert(node.val());
69 }
70}
71
72// The names in the list `key` of a generic distribution. The entries of the list are the names, or components that
73// give the name as `field`.
74std::vector<std::string> namesIn(JSONNode const &node, const char *key, const char *field = nullptr)
75{
76 std::vector<std::string> out;
77 if (JSONNode const *list = node.find(key)) {
78 for (JSONNode const &entry : list->children()) {
79 JSONNode const *name = field ? entry.find(field) : &entry;
80 if (name && isName(*name)) {
81 out.push_back(name->val());
82 }
83 }
84 }
85 return out;
86}
87
88// The constraint terms that the modifiers of a HistFactory distribution name in "constraints". The "constraint_name"
89// of older documents is not counted: it predates the requirement of distinct variates.
90std::vector<std::string> namedConstraints(HistFactoryDist const &dist)
91{
92 std::vector<std::string> out;
93 auto add = overloaded{[&](ConstraintPdf const &constraint) {
94 if (!constraint.legacyName) {
95 out.push_back(constraint.pdf.name);
96 }
97 },
98 [&](GammaConstraintPdfs const &constraints) {
99 for (auto const &pdf : constraints.pdfs) {
100 if (pdf) {
101 out.push_back(pdf->name);
102 }
103 }
104 },
105 [](auto const &) {}};
106 for (Sample const &sample : dist.samples) {
107 for (Modifier const &modifier : sample.modifiers) {
108 std::visit(overloaded{[](CustomModifier const &) {}, [&](auto const &m) { std::visit(add, m.constraint); }},
109 modifier);
110 }
111 }
112 return out;
113}
114
115// The same for a HistFactory distribution that the document doesn't interpret, because a user registered their own
116// importer or exporter for it.
117std::vector<std::string> namedConstraints(JSONNode const &dist)
118{
119 std::vector<std::string> out;
120 if (JSONNode const *samples = dist.find("samples")) {
121 for (JSONNode const &sample : samples->children()) {
122 if (JSONNode const *modifiers = sample.find("modifiers")) {
123 for (JSONNode const &modifier : modifiers->children()) {
124 for (std::string const &constraint : namesIn(modifier, "constraints")) {
125 out.push_back(constraint);
126 }
127 }
128 }
129 }
130 }
131 return out;
132}
133
134// The names of the components of a combined distribution.
135std::vector<std::string> componentsOf(CombinedDist const &dist)
136{
137 std::vector<std::string> out;
138 for (auto const &component : dist.components) {
139 out.push_back(component.ref.name);
140 }
141 return out;
142}
143
144// The node of a distribution that the document doesn't interpret, if it has one and, optionally, the type `type`.
145JSONNode const *genericNode(Distribution const &dist, const char *type = nullptr)
146{
147 auto const *generic = std::get_if<GenericObject>(&dist.body);
148 return generic && (!type || generic->type == type) ? generic->node : nullptr;
149}
150
151// The distributions of a document by name, and what they say about the variates. The document must outlive this
152// object.
153class Distributions {
154public:
155 explicit Distributions(HS3Document const &doc) : _doc{doc}
156 {
157 for (Distribution const &dist : doc.distributions) {
158 _byName.emplace(dist.name, &dist);
159 }
160 }
161
162 // The distribution `name` if the document represents it as a `Body_t`, or nullptr.
163 template <class Body_t>
164 Body_t const *find(std::string const &name) const
165 {
166 auto found = _byName.find(name);
167 return found != _byName.end() ? std::get_if<Body_t>(&found->second->body) : nullptr;
168 }
169
170 // The node of the generic distribution `name` if it has the type `type`, or nullptr.
171 JSONNode const *nodeOf(std::string const &name, const char *type) const
172 {
173 auto found = _byName.find(name);
174 return found != _byName.end() ? genericNode(*found->second, type) : nullptr;
175 }
176
177 // Add the variates of the distribution `name` to `out`: the "x" of a fundamental distribution (a name or a list)
178 // and the axes of a distribution with axes (e.g. histfactory_dist), through products, mixtures and combined
179 // distributions, and the "x" of the components of an array distribution. The constraint terms named by a
180 // histfactory_dist are terms of their own, see likelihoodTerms(). Distributions in `visited` are skipped.
181 void addVariates(std::string const &name, std::set<std::string> &out, std::set<std::string> &visited) const
182 {
183 if (!visited.insert(name).second) {
184 return;
185 }
186 if (auto const *histFactory = find<HistFactoryDist>(name)) {
187 for (BinnedAxis const &axis : histFactory->axes) {
188 out.insert(axis.name);
189 }
190 }
191 auto addVariatesOf = [&](std::vector<std::string> const &parts) {
192 for (std::string const &part : parts) {
193 addVariates(part, out, visited);
194 }
195 };
196 if (auto const *combined = find<CombinedDist>(name)) {
197 addVariatesOf(componentsOf(*combined));
198 }
199 auto const *generic = find<GenericObject>(name);
200 if (!generic || !generic->node) {
201 return;
202 }
203 JSONNode const &node = *generic->node;
204 if (generic->type == "product_dist") {
205 addVariatesOf(namesIn(node, "factors"));
206 } else if (generic->type == "mixture_dist") {
207 addVariatesOf(namesIn(node, "summands"));
208 } else if (generic->type == "array_dist") {
209 if (JSONNode const *components = node.find("components")) {
210 for (JSONNode const &component : components->children()) {
211 if (JSONNode const *x = component.find("x")) {
212 addNames(*x, out);
213 }
214 }
215 }
216 } else {
217 if (JSONNode const *x = node.find("x")) {
218 addNames(*x, out);
219 }
220 for (std::string const &axis : namesIn(node, "axes", "name")) {
221 out.insert(axis);
222 }
223 }
224 }
225
226 // The terms of a likelihood, each once: its distributions (the components of a combined distribution, or of a
227 // RooSimultaneous written to ROOT_internal by older versions, are terms of their own), its "aux_distributions",
228 // and the constraint terms named by the modifiers of its histfactory_dist terms.
229 std::vector<std::string> likelihoodTerms(Likelihood const &likelihood) const
230 {
231 std::vector<std::string> terms;
232 auto add = [&](std::string const &name) {
233 auto legacy = _doc.rooFit.combinedDistributions.find(name);
234 if (auto const *combined = find<CombinedDist>(name)) {
235 for (std::string const &component : componentsOf(*combined)) {
236 addUnique(terms, component);
237 }
238 } else if (!_byName.count(name) && legacy != _doc.rooFit.combinedDistributions.end()) {
239 for (DistributionRef const &component : legacy->second.distributions) {
240 addUnique(terms, component.name);
241 }
242 } else {
243 addUnique(terms, name);
244 }
245 };
246 for (LikelihoodTerm const &term : likelihood.terms) {
247 add(term.distribution.name);
248 }
249 for (DistributionRef const &aux : likelihood.auxDistributions) {
250 add(aux.name);
251 }
252 // The list grows by the constraint terms while it is read.
253 for (std::size_t i = 0; i < terms.size(); ++i) {
254 std::vector<std::string> constraints;
255 if (auto const *histFactory = find<HistFactoryDist>(terms[i])) {
256 constraints = namedConstraints(*histFactory);
257 } else if (JSONNode const *generic = nodeOf(terms[i], "histfactory_dist")) {
258 constraints = namedConstraints(*generic);
259 }
260 for (std::string const &constraint : constraints) {
261 addUnique(terms, constraint);
262 }
263 }
264 return terms;
265 }
266
267private:
268 HS3Document const &_doc;
269 std::map<std::string, Distribution const *> _byName;
270};
271
272// The parts (terms or components) of something that must have distinct variates, with their variates.
273using PartVariates = std::vector<std::pair<std::string, std::set<std::string>>>;
274
275// Append a message for each variate that several of `parts` share. `what` names the parts and `context` the whole,
276// e.g. "terms" of "the likelihood 'lh'".
277void addShared(PartVariates const &parts, std::string const &what, std::string const &context,
278 std::vector<std::string> &messages)
279{
280 std::map<std::string, std::vector<std::string>> partsOfVariate;
281 std::vector<std::string> order;
282 for (auto const &[part, variates] : parts) {
283 for (std::string const &variate : variates) {
284 auto &list = partsOfVariate[variate];
285 if (list.empty()) {
286 order.push_back(variate);
287 }
288 addUnique(list, part);
289 }
290 }
291 for (std::string const &variate : order) {
292 auto const &list = partsOfVariate[variate];
293 if (list.size() < 2) {
294 continue;
295 }
296 std::string names;
297 for (std::size_t i = 0; i < list.size(); ++i) {
298 names += (i == 0 ? "'" : (i + 1 == list.size() ? "' and '" : "', '")) + list[i];
299 }
300 messages.push_back("the variate '" + variate + "' is shared by the " + what + " " + names + "' of " + context);
301 }
302}
303
304// The axes of the components of a combined data set, by component. A component that is a combined data set itself has
305// the axes of all of its components.
306PartVariates componentAxes(HS3Document const &doc, CombinedData const &combined)
307{
308 PartVariates parts;
309 for (auto const &component : combined.components) {
310 std::set<std::string> axes;
311 if (Data const *found = findByName(doc.data, component.ref.name)) {
312 std::visit(overloaded{[&](CombinedData const &inner) {
313 for (auto const &[name, innerAxes] : componentAxes(doc, inner)) {
314 axes.insert(innerAxes.begin(), innerAxes.end());
315 }
316 },
317 [&](PointData const &data) {
318 for (ContinuousAxis const &axis : data.axes) {
319 axes.insert(axis.name);
320 }
321 },
322 [&](auto const &data) {
323 for (auto const &axis : data.axes) {
324 axes.insert(nameOf(axis));
325 }
326 }},
327 found->body);
328 }
329 parts.emplace_back(component.ref.name, axes);
330 }
331 return parts;
332}
333
334// The number of entries of the data set `name` of the document (see Data::numEntries()). Without such a data set, the
335// document is not valid, which is reported elsewhere: one is assumed.
336int numDataEntries(HS3Document const &doc, std::string const &name)
337{
338 Data const *data = findByName(doc.data, name);
339 return data ? static_cast<int>(data->numEntries()) : 1;
340}
341
342} // namespace
343
344std::set<std::string> variatesOf(HS3Document const &doc, Likelihood const &likelihood)
345{
346 Distributions distributions{doc};
347 std::set<std::string> variates;
348 std::set<std::string> visited;
349 for (LikelihoodTerm const &term : likelihood.terms) {
350 distributions.addVariates(term.distribution.name, variates, visited);
351 if (auto const *combined = distributions.find<CombinedDist>(term.distribution.name)) {
352 variates.insert(combined->columns.begin(), combined->columns.end());
353 }
354 }
355 return variates;
356}
357
358std::set<std::string> variatesOf(HS3Document const &doc, std::string const &distribution)
359{
360 std::set<std::string> variates;
361 std::set<std::string> visited;
362 Distributions{doc}.addVariates(distribution, variates, visited);
363 return variates;
364}
365
366std::map<std::string, std::set<std::string>> sharedAxes(HS3Document const &doc)
367{
368 std::map<std::string, std::set<std::string>> out;
369 for (Data const &data : doc.data) {
370 if (auto const *combined = std::get_if<CombinedData>(&data.body)) {
371 std::map<std::string, int> counts;
372 for (auto const &[component, axes] : componentAxes(doc, *combined)) {
373 for (std::string const &axis : axes) {
374 if (++counts[axis] == 2) {
375 out[data.name].insert(axis);
376 }
377 }
378 }
379 }
380 }
381 return out;
382}
383
384std::map<std::string, std::set<std::string>> bookkeepingColumns(HS3Document const &doc)
385{
386 std::map<std::string, std::set<std::string>> out;
387 if (doc.rooFit.bookkeepingColumns.empty()) {
388 return out;
389 }
390 Distributions distributions{doc};
391 std::set<std::string> variates;
392 std::set<std::string> visited;
393 for (Distribution const &dist : doc.distributions) {
394 distributions.addVariates(dist.name, variates, visited);
395 }
396 for (auto const &[dataset, columns] : doc.rooFit.bookkeepingColumns) {
397 for (std::string const &column : columns) {
398 if (!variates.count(column)) {
399 out[dataset].insert(column);
400 }
401 }
402 }
403 return out;
404}
405
406std::vector<std::string> unlistedConstraints(HS3Document const &doc, std::vector<std::string> *warnings)
407{
408 Distributions distributions{doc};
409 std::vector<std::string> messages;
410 for (Likelihood const &likelihood : doc.likelihoods) {
411 std::map<std::string, int> contributions;
412 // The combined distributions in which a distribution is a component without data.
413 std::map<std::string, std::set<std::string>> withoutData;
414 std::set<std::string> named;
415 // The products that are being expanded, since a document that was not imported yet can have circular ones.
416 std::set<std::string> expanding;
417 // `combined` is the combined distribution whose component without data the distribution is reached through.
418 std::function<void(std::string const &, int, std::string const &)> contribute =
419 [&](std::string const &name, int entries, std::string const &combined) {
420 contributions[name] += entries;
421 if (entries == 0) {
422 withoutData[name].insert(combined);
423 }
424 if (auto const *histFactory = distributions.find<HistFactoryDist>(name)) {
425 for (std::string const &constraint : namedConstraints(*histFactory)) {
426 named.insert(constraint);
427 }
428 } else if (JSONNode const *generic = distributions.nodeOf(name, "histfactory_dist")) {
429 for (std::string const &constraint : namedConstraints(*generic)) {
430 named.insert(constraint);
431 }
432 } else if (JSONNode const *product = distributions.nodeOf(name, "product_dist");
433 product && expanding.insert(name).second) {
434 for (std::string const &factor : namesIn(*product, "factors")) {
435 contribute(factor, entries, combined);
436 }
437 expanding.erase(name);
438 }
439 };
440 // The components of a combined distribution, each with the entries of the component of the paired combined data
441 // set that has the same key. Without paired data (a pure model), every component contributes once.
442 // A component that is a combined distribution itself (HS3 #161) contributes its own components, with the
443 // component of the data set that is paired with it.
444 std::function<void(std::string const &, CombinedDist const &, Data const *)> contributeCombined =
445 [&](std::string const &distName, CombinedDist const &dist, Data const *data) {
446 auto const *combinedData = data ? std::get_if<CombinedData>(&data->body) : nullptr;
447 for (auto const &component : dist.components) {
448 int entries = 1;
449 Data const *componentData = nullptr;
450 if (combinedData) {
451 auto const *dataComponent = combinedData->find(component.key);
452 entries = dataComponent ? numDataEntries(doc, dataComponent->ref.name) : 0;
453 componentData = dataComponent ? findByName(doc.data, dataComponent->ref.name) : nullptr;
454 if (!dataComponent && warnings) {
455 warnings->push_back("the component '" + component.ref.name + "' of the combined distribution '" +
456 distName + "' has no component in the data set '" + data->name +
457 "' that the likelihood '" + likelihood.name +
458 "' pairs it with, so it does not contribute to the likelihood");
459 }
460 }
461 if (auto const *nested = distributions.find<CombinedDist>(component.ref.name)) {
462 contributions[component.ref.name] += entries;
463 if (entries > 0) {
464 contributeCombined(component.ref.name, *nested, componentData);
465 }
466 continue;
467 }
468 contribute(component.ref.name, entries, distName);
469 }
470 };
471 for (LikelihoodTerm const &term : likelihood.terms) {
472 // The paired data: a data set, a value given in-line, or nothing (a pure model).
473 auto const *dataRef = std::get_if<DataRef>(&term.data);
474 Data const *data = dataRef ? findByName(doc.data, dataRef->name) : nullptr;
475 std::string const &name = term.distribution.name;
476 if (auto const *combined = distributions.find<CombinedDist>(name)) {
477 ++contributions[name];
478 contributeCombined(name, *combined, data);
479 } else {
480 contribute(name, data ? numDataEntries(doc, data->name) : 1, "");
481 }
482 }
483 for (DistributionRef const &aux : likelihood.auxDistributions) {
484 contribute(aux.name, 1, "");
485 }
486 for (std::string const &constraint : named) {
487 const int n = contributions[constraint];
488 auto const &regions = withoutData[constraint];
489 std::string inRegions;
490 for (std::string const &region : regions) {
491 inRegions += (inRegions.empty() ? "'" : ", '") + region + "'";
492 }
493 if (n != 1) {
494 messages.push_back("the constraint '" + constraint +
495 "' named by a modifier of a HistFactory channel contributes " + std::to_string(n) +
496 " times to the likelihood '" + likelihood.name +
497 "', but it must contribute exactly once" +
498 (n == 0 && !regions.empty() ? " (it is a component of the combined distribution " +
499 inRegions + " without data, which is no observation)"
500 : ""));
501 } else if (!regions.empty() && warnings) {
502 warnings->push_back("the constraint '" + constraint + "' is a term of the likelihood '" + likelihood.name +
503 "' and also a component of the combined distribution " + inRegions +
504 " without data. It contributes once, as the term");
505 }
506 }
507 }
508 return messages;
509}
510
511std::set<std::string> componentsWithData(HS3Document const &doc)
512{
513 Distributions distributions{doc};
514 std::set<std::string> out;
515 // The components of the combined distribution `distName` that the combined data set `combinedData` has entries
516 // for, also those of a component that is a combined distribution itself (HS3 #161).
517 std::function<void(std::string const &, CombinedData const *)> collect = [&](std::string const &distName,
518 CombinedData const *combinedData) {
519 auto const *dist = distributions.find<CombinedDist>(distName);
520 if (!dist || !combinedData) {
521 return;
522 }
523 for (auto const &component : dist->components) {
524 auto const *dataComponent = combinedData->find(component.key);
525 if (dataComponent && numDataEntries(doc, dataComponent->ref.name) > 0) {
526 out.insert(component.ref.name);
527 collect(component.ref.name, find<CombinedData>(doc.data, dataComponent->ref.name));
528 }
529 }
530 };
531 for (Likelihood const &likelihood : doc.likelihoods) {
532 for (LikelihoodTerm const &term : likelihood.terms) {
533 auto const *dataRef = std::get_if<DataRef>(&term.data);
534 collect(term.distribution.name, dataRef ? find<CombinedData>(doc.data, dataRef->name) : nullptr);
535 }
536 }
537 return out;
538}
539
540std::string arrayComponentForm(std::string const &componentType, JSONNode const &component, JSONNode const *defaults)
541{
542 // A value in canonical form: numbers as the double they represent (two literals are identical if they are the same
543 // number), names as they are, anything else as written.
544 auto canonical = [](JSONNode const &value) {
545 if (value.is_number()) {
546 char buffer[32];
547 std::snprintf(buffer, sizeof(buffer), "%.17g", value.val_double());
548 return std::string{"#"} + buffer;
549 }
550 if (value.has_val()) {
551 return "$" + value.val();
552 }
553 std::stringstream ss;
554 value.writeJSON(ss);
555 return ss.str();
556 };
557 std::map<std::string, std::string> fields;
558 if (defaults) {
559 for (auto const &field : defaults->children()) {
560 fields[field.key()] = canonical(field);
561 }
562 }
563 for (auto const &field : component.children()) {
564 fields[field.key()] = canonical(field);
565 }
566 std::string form = componentType;
567 for (auto const &[key, value] : fields) {
568 form += ";" + key + "=" + value;
569 }
570 return form;
571}
572
573std::vector<std::string> sharedVariates(HS3Document const &doc)
574{
575 Distributions distributions{doc};
576 std::vector<std::string> messages;
577 // The parts of a distribution, with their variates, as union composition (HS3) defines them: the components of a
578 // combined distribution, recursively, and the components of an array distribution are parts of their own; any other
579 // distribution is one part. Identical parts (the same distribution, or array components with the same canonical
580 // form, see arrayComponentForm()) are one part, named after the first of them ("<array>[<x>]" for an array
581 // component); the variates of such parts are added to `identical`. `reached` gets every distribution on the way.
582 // A combined distribution that is paired with the combined data set `data` has a factor only for the components with
583 // a component of the data set that has entries (HS3); without paired data, every component counts.
584 std::function<void(std::string const &, Data const *, PartVariates &, std::map<std::string, std::string> &,
585 std::set<std::string> &, std::set<std::string> &)>
586 addUnionParts = [&](std::string const &name, Data const *data, PartVariates &parts,
587 std::map<std::string, std::string> &nameOfForm, std::set<std::string> &identical,
588 std::set<std::string> &reached) {
589 reached.insert(name);
590 auto addPart = [&](std::string const &part, std::set<std::string> const &variates) {
591 auto found = std::find_if(parts.begin(), parts.end(), [&](auto const &p) { return p.first == part; });
592 if (found != parts.end()) {
593 identical.insert(variates.begin(), variates.end());
594 return;
595 }
596 parts.emplace_back(part, variates);
597 };
598 if (auto const *combined = distributions.find<CombinedDist>(name)) {
599 auto const *combinedData = data ? std::get_if<CombinedData>(&data->body) : nullptr;
600 for (auto const &component : combined->components) {
601 Data const *componentData = nullptr;
602 if (combinedData) {
603 auto const *dataComponent = combinedData->find(component.key);
604 componentData = dataComponent ? findByName(doc.data, dataComponent->ref.name) : nullptr;
605 if (!componentData || numDataEntries(doc, componentData->name) == 0) {
606 continue;
607 }
608 }
609 addUnionParts(component.ref.name, componentData, parts, nameOfForm, identical, reached);
610 }
611 return;
612 }
613 JSONNode const *array = distributions.nodeOf(name, "array_dist");
614 JSONNode const *components = array ? array->find("components") : nullptr;
615 if (!components) {
616 std::set<std::string> variates;
617 std::set<std::string> visited;
618 distributions.addVariates(name, variates, visited);
619 addPart(name, variates);
620 return;
621 }
622 std::string const componentType = array->has_child("component_type") ? (*array)["component_type"].val() : "";
623 JSONNode const *defaults = array->find("default_parameters");
624 for (JSONNode const &component : components->children()) {
625 std::set<std::string> x;
626 if (JSONNode const *xNode = component.find("x")) {
627 addNames(*xNode, x);
628 }
629 std::string const form = arrayComponentForm(componentType, component, defaults);
630 auto found = nameOfForm.find(form);
631 if (found == nameOfForm.end()) {
632 found = nameOfForm.emplace(form, name + "[" + (x.empty() ? "" : *x.begin()) + "]").first;
633 }
634 addPart(found->second, x);
635 }
636 };
637 // The variates of identical factors of a combined distribution, by name: they may occur in several sub-data sets of
638 // the paired combined data set.
639 std::map<std::string, std::set<std::string>> identicalOfCombined;
640 auto unionOf = [&](std::string const &name, Data const *data, std::set<std::string> &reached) {
641 PartVariates parts;
642 std::map<std::string, std::string> nameOfForm;
643 std::set<std::string> identical;
644 addUnionParts(name, data, parts, nameOfForm, identical, reached);
645 if (distributions.find<CombinedDist>(name)) {
646 identicalOfCombined[name] = identical;
647 }
648 return parts;
649 };
650 std::set<std::string> inLikelihoods;
651 for (Likelihood const &likelihood : doc.likelihoods) {
652 // The likelihood is the plain product of its terms (HS3): union composition applies within a term, not across
653 // terms, so that a variate of two terms is shared, also by identical factors. Each part is named after its term.
654 PartVariates parts;
655 std::set<std::string> reached;
656 std::vector<std::string> named;
657 auto addTerm = [&](std::string const &term, Data const *data) {
658 inLikelihoods.insert(term);
659 std::set<std::string> reachedByTerm;
660 PartVariates termParts = unionOf(term, data, reachedByTerm);
661 // The same distribution as a part of another term is a factor of its own as well.
662 for (auto &part : termParts) {
663 bool again = std::any_of(parts.begin(), parts.end(), [&](auto const &p) { return p.first == part.first; });
664 parts.emplace_back(again ? part.first + "' (again in the term '" + term : part.first, part.second);
665 }
666 reached.insert(reachedByTerm.begin(), reachedByTerm.end());
667 };
668 for (LikelihoodTerm const &term : likelihood.terms) {
669 auto const *dataRef = std::get_if<DataRef>(&term.data);
670 addTerm(term.distribution.name, dataRef ? findByName(doc.data, dataRef->name) : nullptr);
671 }
672 for (DistributionRef const &aux : likelihood.auxDistributions) {
673 addTerm(aux.name, nullptr);
674 }
675 // The constraint terms named by the HistFactory channels that no term reaches are terms of their own: RooFit adds
676 // them itself for documents before HS3 0.3.
677 for (std::string const &term : distributions.likelihoodTerms(likelihood)) {
678 if (!reached.count(term) && !inLikelihoods.count(term)) {
679 addTerm(term, nullptr);
680 }
681 }
682 addShared(parts, "terms", "the likelihood '" + likelihood.name + "'", messages);
683 }
684 for (Distribution const &dist : doc.distributions) {
685 if (std::holds_alternative<CombinedDist>(dist.body) && !inLikelihoods.count(dist.name)) {
686 std::set<std::string> reached;
687 addShared(unionOf(dist.name, nullptr, reached), "components", "the combined_dist '" + dist.name + "'",
688 messages);
689 }
690 }
691 // The axes of the components of every combined data set, also of those that a likelihood lists. The axes for the
692 // variates of identical factors of the combined distribution that a likelihood pairs it with may occur in several
693 // components.
694 std::map<std::string, std::set<std::string>> exempt = bookkeepingColumns(doc);
695 for (Likelihood const &likelihood : doc.likelihoods) {
696 for (LikelihoodTerm const &term : likelihood.terms) {
697 auto const *dataRef = std::get_if<DataRef>(&term.data);
698 auto identical = identicalOfCombined.find(term.distribution.name);
699 if (dataRef && identical != identicalOfCombined.end()) {
700 exempt[dataRef->name].insert(identical->second.begin(), identical->second.end());
701 }
702 }
703 }
704 for (Data const &data : doc.data) {
705 auto const *combined = std::get_if<CombinedData>(&data.body);
706 if (!combined) {
707 continue;
708 }
709 PartVariates parts = componentAxes(doc, *combined);
710 if (auto found = exempt.find(data.name); found != exempt.end()) {
711 for (auto &part : parts) {
712 for (std::string const &column : found->second) {
713 part.second.erase(column);
714 }
715 }
716 }
717 addShared(parts, "components", "the combined data set '" + data.name + "'", messages);
718 }
719 return messages;
720}
721
723{
724 HS3Document &doc = validated._doc;
726 // The components that are taken out of their combined distribution, by combined distribution, with their labels.
727 std::map<std::string, std::map<std::string, std::string>> dropped;
728 std::set<std::string> labels;
729
730 // Components without data that are also terms with data. A data set can only be a component of one combined data
731 // set, so that the data of a term gets a copy for every further one. The copies are added to the document after
732 // the loop, which keeps pointers into the data sets.
733 std::vector<Data> copies;
734 auto hasEntries = [&](std::string const &name) {
735 Data const *data = findByName(doc.data, name);
736 data = data ? data : findByName(copies, name);
737 return data && data->numEntries() > 0;
738 };
739 std::set<std::string> dataOfComponents;
740 for (Likelihood &likelihood : doc.likelihoods) {
741 std::set<std::string> termsToRemove;
742 for (LikelihoodTerm const &term : likelihood.terms) {
743 auto const *combinedDist = find<CombinedDist>(doc.distributions, term.distribution.name);
744 auto const *dataRef = std::get_if<DataRef>(&term.data);
745 auto *combined = dataRef ? find<CombinedData>(doc.data, dataRef->name) : nullptr;
746 if (!combinedDist || !combined) {
747 continue;
748 }
749 for (auto const &component : combinedDist->components) {
750 if (component.key.size() != 1) {
751 continue;
752 }
753 std::string const &label = component.key.front();
754 std::string const &dist = component.ref.name;
755 auto ownTerm =
756 std::find_if(likelihood.terms.begin(), likelihood.terms.end(), [&](LikelihoodTerm const &other) {
757 return other.distribution.name == dist && std::holds_alternative<DataRef>(other.data);
758 });
759 if (ownTerm == likelihood.terms.end()) {
760 continue;
761 }
762 auto dataComponent = std::find_if(combined->components.begin(), combined->components.end(),
763 [&](auto const &c) { return c.key == component.key; });
764 if (dataComponent != combined->components.end() && hasEntries(dataComponent->ref.name)) {
765 continue; // two contributions, which is not for RooFit to resolve
766 }
767 out.warnings.push_back("the distribution '" + dist + "' is a component of '" + term.distribution.name +
768 "' without data and a term of the likelihood '" + likelihood.name +
769 "' with data. It is read as " +
770 (asChannels ? "the component, with the data of the term." : "the term only."));
771 if (asChannels) {
772 DataRef termData = std::get<DataRef>(ownTerm->data);
773 if (!dataOfComponents.insert(termData.name).second) {
774 Data const *original = findByName(doc.data, termData.name);
775 const std::string copyName = dataRef->name + "_" + label;
776 if (original && !findByName(doc.data, copyName) && !findByName(copies, copyName)) {
777 copies.push_back(*original);
778 copies.back().name = copyName;
779 termData.name = copyName;
780 }
781 }
782 if (dataComponent != combined->components.end()) {
783 dataComponent->ref = termData;
784 } else {
785 combined->components.push_back({{label}, termData});
786 }
787 termsToRemove.insert(dist);
788 } else {
789 dropped[term.distribution.name][dist] = label;
790 labels.insert(label);
791 }
792 }
793 }
794 likelihood.terms.erase(
795 std::remove_if(likelihood.terms.begin(), likelihood.terms.end(),
796 [&](LikelihoodTerm const &term) { return termsToRemove.count(term.distribution.name) > 0; }),
797 likelihood.terms.end());
798 }
799 doc.data.insert(doc.data.end(), copies.begin(), copies.end());
800 if (asChannels) {
801 return out;
802 }
803
804 for (auto const &item : doc.rooFit.auxiliaryChannels) {
805 auto const *combinedDist = find<CombinedDist>(doc.distributions, item.first);
806 for (auto const &ref : item.second) {
807 std::string label = ref.name;
808 if (combinedDist) {
809 for (auto const &component : combinedDist->components) {
810 if (component.ref.name == ref.name && component.key.size() == 1) {
811 label = component.key.front();
812 }
813 }
814 }
815 dropped[item.first][ref.name] = label;
816 labels.insert(label);
817 }
818 }
819 auto isLabel = [&](std::vector<std::string> const &key) { return key.size() == 1 && labels.count(key.front()); };
820 for (Likelihood &likelihood : doc.likelihoods) {
821 std::vector<LikelihoodTerm> added;
822 for (LikelihoodTerm const &term : likelihood.terms) {
823 auto found = dropped.find(term.distribution.name);
824 if (found == dropped.end()) {
825 continue;
826 }
827 auto const *dataRef = std::get_if<DataRef>(&term.data);
828 auto const *combined = dataRef ? find<CombinedData>(doc.data, dataRef->name) : nullptr;
829 for (auto const &item : found->second) {
830 std::string const &dist = item.first;
831 std::string const &label = item.second;
832 if (std::any_of(likelihood.terms.begin(), likelihood.terms.end(),
833 [&](auto const &other) { return other.distribution.name == dist; })) {
834 continue; // a term of its own already
835 }
836 if (auto const *component = combined ? combined->find({label}) : nullptr) {
837 added.push_back({{dist}, component->ref});
838 } else if (std::none_of(likelihood.auxDistributions.begin(), likelihood.auxDistributions.end(),
839 [&](auto const &ref) { return ref.name == dist; })) {
840 // Without data, the observed values are the values of the constant observables.
841 likelihood.auxDistributions.push_back({dist});
842 }
843 }
844 }
845 likelihood.terms.insert(likelihood.terms.end(), added.begin(), added.end());
846 }
847 for (Data &data : doc.data) {
848 if (auto *combined = std::get_if<CombinedData>(&data.body)) {
849 auto &components = combined->components;
850 for (auto const &component : components) {
851 // Not the data sets without entries: they hold no values, and stay data sets of the workspace.
852 if (isLabel(component.key) && hasEntries(component.ref.name)) {
853 out.data.insert(component.ref.name);
854 }
855 }
856 components.erase(std::remove_if(components.begin(), components.end(),
857 [&](auto const &component) { return isLabel(component.key); }),
858 components.end());
859 }
860 }
861 for (Domain &domain : doc.domains) {
862 for (auto &axis : domain.axes) {
863 if (auto *categorical = std::get_if<CategoricalAxis>(&axis)) {
864 auto &categories = categorical->categories;
865 categories.erase(std::remove_if(categories.begin(), categories.end(),
866 [&](std::string const &label) { return labels.count(label) > 0; }),
867 categories.end());
868 }
869 }
870 }
871 for (auto const &droppedFrom : dropped) {
872 std::map<std::string, std::string> const &components = droppedFrom.second;
873 for (auto const &item : components) {
874 out.terms.insert(item.first);
875 }
876 if (auto *combinedDist = find<CombinedDist>(doc.distributions, droppedFrom.first)) {
877 auto &all = combinedDist->components;
878 all.erase(std::remove_if(all.begin(), all.end(),
879 [&](auto const &component) { return components.count(component.ref.name) > 0; }),
880 all.end());
881 }
882 }
883 return out;
884}
885
886std::vector<std::string> resolvePointData(ValidatedHS3Document &validated)
887{
888 HS3Document &doc = validated._doc;
889 std::vector<std::string> errors;
890 auto soleVariateOf = [&](std::string const &distribution, std::string const &what) {
891 std::set<std::string> const variates = variatesOf(doc, distribution);
892 if (variates.size() == 1) {
893 return *variates.begin();
894 }
895 errors.push_back("the variate of the distribution '" + distribution + "', which " + what +
896 " is paired with, can't be determined, since it doesn't have a single variate");
897 return std::string{};
898 };
899 std::vector<Data> inlineData;
900 std::map<std::string, std::string> variateOfPointData; // of the point data sets without axes
901 for (Likelihood &likelihood : doc.likelihoods) {
902 for (LikelihoodTerm &term : likelihood.terms) {
903 std::string const &distribution = term.distribution.name;
904 if (auto const *value = std::get_if<double>(&term.data)) {
905 // Older versions of RooFit wrote "data": [0], with the number 0 as the only entry, for a ModelConfig
906 // without data. In this exact form, it is no observation in documents before 0.3 (HS3 PR #154). RooFit
907 // now writes "data": null.
908 if (*value == 0. && likelihood.terms.size() == 1 && doc.metadata.version < Version{0, 3}) {
909 term.data = std::monostate{};
910 continue;
911 }
912 std::string name = distribution + "_data";
913 for (std::size_t k = 1; findByName(doc.data, name) || findByName(inlineData, name); ++k) {
914 name = distribution + "_data_" + std::to_string(k);
915 }
916 PointData point;
917 point.value = *value;
918 point.axes.push_back(
919 {soleVariateOf(distribution, "the number in the \"data\" of the likelihood '" + likelihood.name + "'"),
920 std::nullopt, std::nullopt});
921 inlineData.push_back({name, std::move(point)});
922 term.data = DataRef{name};
923 continue;
924 }
925 auto const *ref = std::get_if<DataRef>(&term.data);
926 auto const *point = ref ? find<PointData>(doc.data, ref->name) : nullptr;
927 if (!point) {
928 continue;
929 }
930 if (!point->axes.empty()) {
931 // The axis of point data is named like the variate of the paired distribution.
932 std::set<std::string> const variates = variatesOf(doc, distribution);
933 if (variates.size() == 1 && point->axes.front().name != *variates.begin()) {
934 errors.push_back("the axis '" + point->axes.front().name + "' of the point data set '" + ref->name +
935 "' is not the variate '" + *variates.begin() + "' of the distribution '" +
936 distribution + "' it is paired with");
937 }
938 continue;
939 }
940 std::string const variate = soleVariateOf(distribution, "the point data set '" + ref->name + "'");
941 auto inserted = variateOfPointData.emplace(ref->name, variate);
942 if (!inserted.second && inserted.first->second != variate) {
943 errors.push_back("the point data set '" + ref->name +
944 "' without axes is paired with distributions of different variates, '" +
945 inserted.first->second + "' and '" + variate + "'");
946 }
947 }
948 }
949 for (auto const &[name, variate] : variateOfPointData) {
950 find<PointData>(doc.data, name)->axes.push_back({variate, std::nullopt, std::nullopt});
951 }
952 doc.data.insert(doc.data.end(), std::make_move_iterator(inlineData.begin()),
953 std::make_move_iterator(inlineData.end()));
954 return errors;
955}
956
957std::map<std::string, std::set<std::string>> writeLikelihoodTermsOnce(HS3Document const &doc, JSONNode &root)
958{
959 std::map<std::string, std::set<std::string>> removed;
960 if (!root.has_child("distributions")) {
961 return removed;
962 }
963 Distributions distributions{doc};
964 // The products that are terms, with the factors that are terms wherever the product is one.
965 std::map<std::string, std::set<std::string>> removable;
966 for (Likelihood const &likelihood : doc.likelihoods) {
967 std::vector<std::string> const terms = distributions.likelihoodTerms(likelihood);
968 for (std::string const &term : terms) {
969 JSONNode const *product = distributions.nodeOf(term, "product_dist");
970 if (!product) {
971 continue;
972 }
973 std::set<std::string> factorsThatAreTerms;
974 for (std::string const &factor : namesIn(*product, "factors")) {
975 if (factor != term && std::find(terms.begin(), terms.end(), factor) != terms.end()) {
976 factorsThatAreTerms.insert(factor);
977 }
978 }
979 auto found = removable.find(term);
980 if (found == removable.end()) {
981 removable[term] = factorsThatAreTerms;
982 } else {
983 std::set<std::string> both;
984 std::set_intersection(found->second.begin(), found->second.end(), factorsThatAreTerms.begin(),
985 factorsThatAreTerms.end(), std::inserter(both, both.begin()));
986 found->second = both;
987 }
988 }
989 }
990 // Products that another distribution uses are left alone.
991 for (Distribution const &dist : doc.distributions) {
992 if (JSONNode const *node = genericNode(dist)) {
993 for (const char *key : {"factors", "summands"}) {
994 for (std::string const &part : namesIn(*node, key)) {
995 removable.erase(part);
996 }
997 }
998 }
999 }
1000 for (JSONNode &dist : root["distributions"].children()) {
1001 auto found = removable.find(dist["name"].val());
1002 if (found == removable.end() || found->second.empty()) {
1003 continue;
1004 }
1005 std::vector<std::string> keep;
1006 for (JSONNode const &factor : dist["factors"].children()) {
1007 if (!found->second.count(factor.val())) {
1008 keep.push_back(factor.val());
1009 }
1010 }
1011 if (!keep.empty()) {
1012 dist["factors"].clear();
1013 dist["factors"].fill_seq(keep);
1014 removed.insert(*found);
1015 }
1016 }
1017 return removed;
1018}
1019
1020} // namespace HS3
1021} // namespace RooFit
HS3Document const & _doc
std::map< std::string, Distribution const * > _byName
#define c(i)
Definition RSha256.hxx:101
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t 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 modifier
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
char name[80]
Definition TGX11.cxx:142
std::string val() 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
An HS3 document. It is move-only, because generic objects refer to the JSON tree of the document.
std::vector< HS3::Data > data
HS3::Metadata metadata
std::vector< HS3::Likelihood > likelihoods
HS3::RooFitInternal rooFit
std::vector< HS3::Domain > domains
std::vector< HS3::Distribution > distributions
A document that passed validate().
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
double dist(Rotation3D const &r1, Rotation3D const &r2)
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::string arrayComponentForm(std::string const &componentType, RooFit::Detail::JSONNode const &component, RooFit::Detail::JSONNode const *defaults)
A canonical form of the component component of an array distribution with the type componentType and ...
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...
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....
Definition HS3Document.h:65
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::variant< NormFactor, NormSys, HistoSys, ShapeSys, StatError, CustomModifier > Modifier
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.
Definition HS3Document.h:58
Combined< DataRef > CombinedData
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.
std::set< std::string > componentsWithData(HS3Document const &doc)
The distributions that are components of a combined distribution of a likelihood, with a component of...
Ref< struct DistributionTag > DistributionRef
std::map< std::string, std::set< std::string > > bookkeepingColumns(HS3Document const &doc)
The bookkeeping columns by combined data set: the declared ones (RooFitInternal::bookkeepingColumns),...
auto find(Objects_t &objects, std::string const &name) -> decltype(std::get_if< Body_t >(&objects.begin() ->body))
The body of the object name if it is a Body_t, e.g. find<CombinedData>(doc.data, "obsData"),...
Definition HS3Document.h:77
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< std::string > resolvePointData(ValidatedHS3Document &doc)
A number given in-line in the "data" of a likelihood, or a point data set without axes,...
overloaded(Ts...) -> overloaded< Ts... >
Combined< DistributionRef > CombinedDist
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
static const char * what
Definition stlLoader.cc:5
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
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::string name
The data of a likelihood term: a data set, a number given in-line, or none (std::monostate) in a pure...
std::vector< LikelihoodTerm > terms
Version version
The parsed version. Versions that can't be parsed count as the oldest one.
std::vector< ContinuousAxis > axes
std::string name
Definition HS3Document.h:86
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< std::string > > bookkeepingColumns
Axes that the components of a combined data set share, but that are no variate of any distribution,...
TMarker m
Definition textangle.C:8