Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooSimultaneous.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * *
9 * Copyright (c) 2000-2005, Regents of the University of California *
10 * and Stanford University. All rights reserved. *
11 * *
12 * Redistribution and use in source and binary forms, *
13 * with or without modification, are permitted according to the terms *
14 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15 *****************************************************************************/
16
17/**
18\file RooSimultaneous.cxx
19\class RooSimultaneous
20\ingroup Roofitcore
21
22Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
23The class takes an index category, which is used as a selector
24for PDFs, and a list of PDFs, each associated
25with a state of the index category. RooSimultaneous always returns
26the value of the PDF that is associated with the current value
27of the index category.
28
29Extended likelihood fitting is supported if all components support
30extended likelihood mode. If the index category is among the normalization
31variables, the expected number of events by a RooSimultaneous is the sum over
32all components. Otherwise, it is that of the component p.d.f. selected by the
33index category. For a RooSuperCategory index, it counts as being among the
34normalization variables if all of its input categories are.
35
36The index category can be accessed using indexCategory().
37
38###Generating events
39When generating events from a RooSimultaneous, the index category has to be added to
40the dataset. Further, the PDF needs to know the relative probabilities of each category, i.e.,
41how many events are in which category. This can be achieved in two ways:
42- Generating with proto data that have category entries: An event from the same category as
43in the proto data is created for each event in the proto data.
44See RooAbsPdf::generate(const RooArgSet&,const RooDataSet&,Int_t,bool,bool,bool) const.
45- No proto data: A category is chosen randomly.
46\note This requires that the PDFs building the simultaneous are extended. In this way,
47the relative probability of each category can be calculated from the number of events
48in each category.
49
50###Switch mode
51If the index category is not an observable, but a parameter, the RooSimultaneous
52acts as a "switch" that evaluates to the component selected by the current index
53state, like a RooMultiPdf. Its expected number of events is then the one of the
54selected component.
55
56###Nesting simultaneous PDFs
57RooSimultaneous components are currently flattened into a RooSimultaneous over a
58RooSuperCategory of all index categories. This is deprecated: from ROOT 6.44,
59they are kept as they are and only supported if their index category is a
60parameter (switch mode). To combine channels, use one RooSimultaneous over a
61RooCategory with one state per channel.
62**/
63
64#include "RooSimultaneous.h"
65
66#include "Roo1DTable.h"
68#include "RooAbsData.h"
69#include "RooAddPdf.h"
70#include "RooArgSet.h"
71#include "RooBinSamplingPdf.h"
72#include "RooCategory.h"
73#include "RooCmdConfig.h"
75#include "RooDataHist.h"
76#include "RooDataSet.h"
77#include "RooFormulaVar.h"
78#include "RooGlobalFunc.h"
79#include "RooMsgService.h"
80#include "RooNameReg.h"
81#include "RooPlot.h"
82#include "RooRandom.h"
83#include "RooRealVar.h"
84#include "RooSimGenContext.h"
86#include "RooSuperCategory.h"
87
88#include "RooFitImplHelpers.h"
89
90#include <ROOT/StringUtils.hxx>
91
92#include <algorithm>
93#include <iostream>
94#include <map>
95
96namespace {
97
98std::map<std::string, RooAbsPdf *> createPdfMap(const RooArgList &inPdfList, RooAbsCategoryLValue &inIndexCat)
99{
100 std::map<std::string, RooAbsPdf *> pdfMap;
101 auto indexCatIt = inIndexCat.begin();
102 for (unsigned int i = 0; i < inPdfList.size(); ++i) {
103 auto pdf = static_cast<RooAbsPdf *>(&inPdfList[i]);
104 const auto &nameIdx = (*indexCatIt++);
105 pdfMap[nameIdx.first] = pdf;
106 }
107 return pdfMap;
108}
109
110void replaceOrAdd(RooLinkedList &lst, TObject &obj)
111{
112 TObject *old = lst.FindObject(obj.GetName());
113 if (old) {
114 lst.Replace(old, &obj);
115 } else {
116 lst.Add(&obj);
117 }
118}
119
120} // namespace
121
123
124void RooSimultaneous::InitializationOutput::addPdf(const RooAbsPdf &pdf, std::string const &catLabel)
125{
126 finalPdfs.push_back(&pdf);
127 finalCatLabels.emplace_back(catLabel);
128}
129
130using std::string;
131
132
133
134
135////////////////////////////////////////////////////////////////////////////////
136/// Constructor with index category. PDFs associated with indexCat
137/// states can be added after construction with the addPdf() function.
138///
139/// RooSimultaneous can function without having a PDF associated
140/// with every single state. The normalization in such cases is taken
141/// from the number of registered PDFs, but getVal() will assert if
142/// when called for an unregistered index state.
143
144RooSimultaneous::RooSimultaneous(const char *name, const char *title,
145 RooAbsCategoryLValue& inIndexCat) :
146 RooSimultaneous{name, title, std::map<std::string, RooAbsPdf*>{}, inIndexCat}
147{
148}
149
150
151////////////////////////////////////////////////////////////////////////////////
152/// Constructor from index category and full list of PDFs.
153/// In this constructor form, a PDF must be supplied for each indexCat state
154/// to avoid ambiguities. The PDFs are associated with the states of the
155/// index category as they appear when iterating through the category states
156/// with RooAbsCategory::begin() and RooAbsCategory::end(). This usually means
157/// they are associated by ascending index numbers.
158///
159/// PDFs may not overlap (i.e. share any variables) with the index category (function)
160
161RooSimultaneous::RooSimultaneous(const char *name, const char *title,
162 const RooArgList& inPdfList, RooAbsCategoryLValue& inIndexCat) :
163 RooSimultaneous{name, title, createPdfMap(inPdfList, inIndexCat), inIndexCat}
164{
165 if (inPdfList.size() != inIndexCat.size()) {
166 std::stringstream errMsg;
167 errMsg << "RooSimultaneous::ctor(" << GetName()
168 << " ERROR: Number PDF list entries must match number of index category states, no PDFs added";
169 coutE(InputArguments) << errMsg.str() << std::endl;
170 throw std::invalid_argument(errMsg.str());
171 }
172}
173
174
175////////////////////////////////////////////////////////////////////////////////
176
177RooSimultaneous::RooSimultaneous(const char *name, const char *title, std::map<string, RooAbsPdf *> pdfMap,
178 RooAbsCategoryLValue &inIndexCat)
179 : RooSimultaneous(name, title, std::move(*initialize(name ? name : "", inIndexCat, pdfMap)))
180{
181}
182
183/// For internal use in RooFit.
184RooSimultaneous::RooSimultaneous(const char *name, const char *title,
186 RooAbsCategoryLValue &inIndexCat)
187 : RooSimultaneous(name, title, RooFit::Detail::flatMapToStdMap(pdfMap), inIndexCat)
188{
189}
190
192 : RooAbsPdf(name, title),
193 _plotCoefNormSet("!plotCoefNormSet", "plotCoefNormSet", this, false, false),
194 _partIntMgr(this, 10),
195 _indexCat("indexCat", "Index category", this, *initInfo.indexCat)
196{
197 for (std::size_t i = 0; i < initInfo.finalPdfs.size(); ++i) {
198 addPdf(*initInfo.finalPdfs[i], initInfo.finalCatLabels[i].c_str());
199 }
200
201 // Take ownership of eventual super category
202 if (initInfo.superIndex) {
203 addOwnedComponents(std::move(initInfo.superIndex));
204 }
205}
206
207/// \cond ROOFIT_INTERNAL
208
209// This class cannot be locally defined in initialize as it cannot be
210// used as a template argument in that case
211namespace RooSimultaneousAux {
212 struct CompInfo {
213 RooAbsPdf* pdf ;
214 RooSimultaneous* simPdf ;
215 const RooAbsCategoryLValue* subIndex ;
216 std::unique_ptr<RooArgSet> subIndexComps;
217 } ;
218}
219
220/// \endcond
221
222std::unique_ptr<RooSimultaneous::InitializationOutput>
224 std::map<std::string, RooAbsPdf *> const& pdfMap)
225
226{
227 auto out = std::make_unique<RooSimultaneous::InitializationOutput>();
228 out->indexCat = &inIndexCat;
229
230 // First see if there are any RooSimultaneous input components
231 bool simComps(false) ;
232 for (auto const& item : pdfMap) {
233 if (dynamic_cast<RooSimultaneous*>(item.second)) {
234 simComps = true ;
235 break ;
236 }
237 }
238
239 // If there are no simultaneous component p.d.f. do simple processing through addPdf()
240 if (!simComps) {
241 for (auto const& item : pdfMap) {
242 out->addPdf(*item.second,item.first);
243 }
244 return out;
245 }
246
247 std::string msgPrefix = "RooSimultaneous::initialize(" + name + ") ";
248
249 std::string nestedNames;
250 std::size_t nNested = 0;
251 for (auto const &item : pdfMap) {
252 if (dynamic_cast<RooSimultaneous *>(item.second)) {
253 nestedNames += (nNested++ ? ", \"" : "\"") + std::string(item.second->GetName()) + "\"";
254 }
255 }
256 oocoutW(nullptr, InputArguments)
257 << msgPrefix << (nNested > 1 ? "the components " : "the component ") << nestedNames
258 << (nNested > 1 ? " are RooSimultaneous themselves and get" : " is a RooSimultaneous itself and gets")
259 << " flattened into a\nRooSimultaneous over a RooSuperCategory. This is deprecated: from ROOT 6.44, nested "
260 "RooSimultaneous are only\nsupported if their index category is a parameter (switch mode), and until then the "
261 "flattening breaks such\nswitches. To combine channels, use one RooSimultaneous over a RooCategory with one "
262 "state per channel."
263 << std::endl;
264
265 // Replicating a component to several states of the flattened index category
266 // silently changes the model (GitHub issue #23342).
267 auto warnReplication = [&](RooAbsPdf const &pdf, std::string const &label, RooArgSet const &repliCats,
268 std::size_t nReplicas) {
269 oocoutW(nullptr, InputArguments)
270 << msgPrefix << "\"" << pdf.GetName() << "\" (state \"" << label << "\") doesn't depend on " << repliCats
271 << " and is copied into " << nReplicas << " states; if it is extended, its expected events are counted "
272 << nReplicas << " times (GitHub issue #23342)." << std::endl;
273 };
274
275 RooArgSet allAuxCats ;
276 std::map<string,RooSimultaneousAux::CompInfo> compMap ;
277 for (auto const& item : pdfMap) {
278 RooSimultaneousAux::CompInfo ci ;
279 ci.pdf = item.second ;
280 RooSimultaneous* simComp = dynamic_cast<RooSimultaneous*>(item.second) ;
281 if (simComp) {
282 ci.simPdf = simComp ;
283 ci.subIndex = &simComp->indexCat() ;
284 ci.subIndexComps = simComp->indexCat().isFundamental()
285 ? std::make_unique<RooArgSet>(simComp->indexCat())
286 : std::unique_ptr<RooArgSet>(simComp->indexCat().getVariables());
287 allAuxCats.add(*ci.subIndexComps,true) ;
288 } else {
289 ci.simPdf = nullptr;
290 ci.subIndex = nullptr;
291 }
292 compMap[item.first] = std::move(ci);
293 }
294
295 // Construct the 'superIndex' from the nominal index category and all auxiliary components
296 RooArgSet allCats(inIndexCat) ;
297 allCats.add(allAuxCats) ;
298 std::string siname = name + "_index";
299 out->superIndex = std::make_unique<RooSuperCategory>(siname.c_str(),siname.c_str(),allCats) ;
300 auto *superIndex = out->superIndex.get();
301 out->indexCat = superIndex;
302
303 // Now process each of original pdf/state map entries
304 for (auto const& citem : compMap) {
305
306 RooArgSet repliCats(allAuxCats) ;
307 if (citem.second.subIndexComps) {
308 repliCats.remove(*citem.second.subIndexComps) ;
309 }
310 inIndexCat.setLabel(citem.first.c_str()) ;
311
312 if (!citem.second.simPdf) {
313
314 // Entry is a plain p.d.f. assign it to every state permutation of the repliCats set
315 RooSuperCategory repliSuperCat("tmp","tmp",repliCats) ;
316 if (repliSuperCat.size() > 1) {
317 warnReplication(*citem.second.pdf, citem.first, repliCats, repliSuperCat.size());
318 }
319
320 // Iterator over all states of repliSuperCat
321 for (const auto& nameIdx : repliSuperCat) {
322 // Set value
323 repliSuperCat.setLabel(nameIdx.first) ;
324 // Retrieve corresponding label of superIndex
325 string superLabel = superIndex->getCurrentLabel() ;
326 out->addPdf(*citem.second.pdf,superLabel);
327 oocxcoutD(static_cast<RooAbsArg*>(nullptr), InputArguments) << msgPrefix
328 << "assigning pdf " << citem.second.pdf->GetName() << " to super label " << superLabel << std::endl ;
329 }
330 } else {
331
332 // Entry is a simultaneous p.d.f
333
334 if (repliCats.empty()) {
335
336 // Case 1 -- No replication of components of RooSim component are required
337
338 for (const auto& type : *citem.second.subIndex) {
339 const_cast<RooAbsCategoryLValue*>(citem.second.subIndex)->setLabel(type.first.c_str());
340 string superLabel = superIndex->getCurrentLabel() ;
341 RooAbsPdf* compPdf = citem.second.simPdf->getPdf(type.first);
342 if (compPdf) {
343 out->addPdf(*compPdf,superLabel);
344 oocxcoutD(static_cast<RooAbsArg*>(nullptr), InputArguments) << msgPrefix
345 << "assigning pdf " << compPdf->GetName() << "(member of " << citem.second.pdf->GetName()
346 << ") to super label " << superLabel << std::endl ;
347 } else {
348 oocoutW(nullptr, InputArguments) << msgPrefix << "WARNING: No p.d.f. associated with label "
349 << type.second << " for component RooSimultaneous p.d.f " << citem.second.pdf->GetName()
350 << "which is associated with master index label " << citem.first << std::endl ;
351 }
352 }
353
354 } else {
355
356 // Case 2 -- Replication of components of RooSim component are required
357
358 // Make replication supercat
359 RooSuperCategory repliSuperCat("tmp","tmp",repliCats) ;
360 if (repliSuperCat.size() > 1) {
361 warnReplication(*citem.second.pdf, citem.first, repliCats, repliSuperCat.size());
362 }
363
364 for (const auto& stype : *citem.second.subIndex) {
365 const_cast<RooAbsCategoryLValue*>(citem.second.subIndex)->setLabel(stype.first.c_str());
366
367 for (const auto& nameIdx : repliSuperCat) {
368 repliSuperCat.setLabel(nameIdx.first) ;
369 const string superLabel = superIndex->getCurrentLabel() ;
370 RooAbsPdf* compPdf = citem.second.simPdf->getPdf(stype.first);
371 if (compPdf) {
372 out->addPdf(*compPdf,superLabel);
373 oocxcoutD(static_cast<RooAbsArg*>(nullptr), InputArguments) << msgPrefix
374 << "assigning pdf " << compPdf->GetName() << "(member of " << citem.second.pdf->GetName()
375 << ") to super label " << superLabel << std::endl ;
376 } else {
377 oocoutW(nullptr, InputArguments) << msgPrefix << "WARNING: No p.d.f. associated with label "
378 << stype.second << " for component RooSimultaneous p.d.f " << citem.second.pdf->GetName()
379 << "which is associated with master index label " << citem.first << std::endl ;
380 }
381 }
382 }
383 }
384 }
385 }
386
387 return out;
388}
389
390
391////////////////////////////////////////////////////////////////////////////////
392/// Copy constructor
393
395 RooAbsPdf(other,name),
396 _plotCoefNormSet("!plotCoefNormSet",this,other._plotCoefNormSet),
397 _plotCoefNormRange(other._plotCoefNormRange),
398 _partIntMgr(other._partIntMgr,this),
399 _indexCat("indexCat",this,other._indexCat),
400 _numPdf(other._numPdf)
401{
402 // Copy proxy list
403 for(auto* proxy : static_range_cast<RooRealProxy*>(other._pdfProxyList)) {
404 _pdfProxyList.Add(new RooRealProxy(proxy->GetName(),this,*proxy)) ;
405 }
406}
407
408
409
410////////////////////////////////////////////////////////////////////////////////
411/// Destructor
412
417
418
419
420////////////////////////////////////////////////////////////////////////////////
421/// Return the p.d.f associated with the given index category name
422
424{
425 RooRealProxy* proxy = static_cast<RooRealProxy*>(_pdfProxyList.FindObject(catName.c_str()));
426 return proxy ? static_cast<RooAbsPdf*>(proxy->absArg()) : nullptr;
427}
428
429
430
431////////////////////////////////////////////////////////////////////////////////
432/// Associate given PDF with index category state label 'catLabel'.
433/// The name state must be already defined in the index category.
434///
435/// RooSimultaneous can function without having a PDF associated
436/// with every single state. The normalization in such cases is taken
437/// from the number of registered PDFs, but getVal() will fail if
438/// called for an unregistered index state.
439///
440/// PDFs may not overlap (i.e. share any variables) with the index category (function).
441/// \param[in] pdf PDF to be added.
442/// \param[in] catLabel Name of the category state to be associated to the PDF.
443/// \return `true` in case of failure.
444
445bool RooSimultaneous::addPdf(const RooAbsPdf& pdf, const char* catLabel)
446{
447 // PDFs cannot overlap with the index category
448 if (pdf.dependsOn(_indexCat.arg())) {
449 coutE(InputArguments) << "RooSimultaneous::addPdf(" << GetName() << "): PDF '" << pdf.GetName()
450 << "' overlaps with index category '" << _indexCat.arg().GetName() << "'."<< std::endl ;
451 return true ;
452 }
453
454 // Each index state can only have one PDF associated with it
455 if (_pdfProxyList.FindObject(catLabel)) {
456 coutE(InputArguments) << "RooSimultaneous::addPdf(" << GetName() << "): index state '"
457 << catLabel << "' has already an associated PDF." << std::endl ;
458 return true ;
459 }
460
461 const RooSimultaneous* simPdf = dynamic_cast<const RooSimultaneous*>(&pdf) ;
462 if (simPdf) {
463
464 coutE(InputArguments) << "RooSimultaneous::addPdf(" << GetName()
465 << ") ERROR: you cannot add a RooSimultaneous component to a RooSimultaneous using addPdf()."
466 << " Use the constructor with RooArgList if input p.d.f.s or the map<string,RooAbsPdf&> instead." << std::endl ;
467 return true ;
468
469 } else {
470
471 // Create a proxy named after the associated index state
472 TObject* proxy = new RooRealProxy(catLabel,catLabel,this,const_cast<RooAbsPdf&>(pdf));
473 _pdfProxyList.Add(proxy) ;
474 _numPdf += 1 ;
475 }
476
477 return false ;
478}
479
480////////////////////////////////////////////////////////////////////////////////
481/// Examine the pdf components and check if one of them can be extended or must be extended.
482/// It is enough to have one component that can be extended or must be extended to return the flag in
483/// the total simultaneous pdf.
484
486{
487 bool anyCanExtend = false;
488
489 for (auto *proxy : static_range_cast<RooRealProxy *>(_pdfProxyList)) {
490 auto &pdf = static_cast<RooAbsPdf const&>(proxy->arg());
491 if (pdf.mustBeExtended())
492 return MustBeExtended;
493 anyCanExtend |= pdf.canBeExtended();
494 }
495 return anyCanExtend ? CanBeExtended : CanNotBeExtended;
496}
497
498////////////////////////////////////////////////////////////////////////////////
499/// Return the current value:
500/// the value of the PDF associated with the current index category state
501
503{
504 // Retrieve the proxy by index name
506 if(!proxy) {
507 return 0;
508 }
509
510 double nEvtTot = 1.0;
511 double nEvtCat = 1.0;
512
513 // Relative yield weight only if normalized over the index states. In
514 // "switch mode", the value is the one of the selected component.
516
517 nEvtTot = 0;
518 nEvtCat = 0;
519
520 for (auto *proxy2 : static_range_cast<RooRealProxy *>(_pdfProxyList)) {
521 auto &pdf2 = static_cast<RooAbsPdf const &>(proxy2->arg());
522 if(!pdf2.canBeExtended()) {
523 // If one of the pdfs can't be expected, reset the normalization
524 // factor to one and break out of the loop.
525 nEvtTot = 1.0;
526 nEvtCat = 1.0;
527 break;
528 }
529 const double nEvt = pdf2.expectedEvents(_normSet);
530 nEvtTot += nEvt;
531 if (proxy == proxy2) {
532 // Matching by proxy by pointer rather than pdfs, because it's
533 // possible to have the same pdf used in different states.
534 nEvtCat += nEvt;
535 }
536 }
537 }
538 double catFrac = nEvtCat / nEvtTot;
539
540 // Return the selected PDF value, normalized by the relative number of
541 // expected events if applicable.
542 return *proxy * catFrac;
543}
544
545////////////////////////////////////////////////////////////////////////////////
546/// Return the number of expected events: If the index is in nset,
547/// then return the sum of the expected events of all components,
548/// otherwise return the number of expected events of the PDF
549/// associated with the current index category state
550
552{
553 if (indexCatIsInNormSet(nset)) {
554
555 double sum(0) ;
556
557 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdfProxyList)) {
558 sum += (static_cast<RooAbsPdf*>(proxy->absArg()))->expectedEvents(nset) ;
559 }
560
561 return sum ;
562
563 } else {
564
565 // Retrieve the proxy by index name
567
568 //assert(proxy!=0) ;
569 if (proxy==nullptr) return 0 ;
570
571 // Return the selected PDF value, normalized by the number of index states
572 return (static_cast<RooAbsPdf*>(proxy->absArg()))->expectedEvents(nset);
573 }
574}
575
576
577
578////////////////////////////////////////////////////////////////////////////////
579/// Expected events function for the new evaluation backends: the sum over all
580/// components, or the selected component in "switch mode" (see expectedEvents()).
581
582std::unique_ptr<RooAbsReal> RooSimultaneous::createExpectedEventsFunc(const RooArgSet *nset) const
583{
584 const std::string name = std::string(GetName()) + "_expectedEvents";
585
586 // One function per distinct component, because the same pdf can be used in
587 // several states. Components that can't be extended contribute zero, like
588 // in expectedEvents().
589 RooArgList formulaArgs;
590 RooArgSet ownedFuncs;
591 std::map<RooAbsPdf const *, std::string> funcRefs;
592 bool failed = false;
593 auto ref = [&](RooAbsPdf const &pdf) -> std::string {
594 if (!pdf.canBeExtended()) {
595 return "0.0";
596 }
597 auto found = funcRefs.find(&pdf);
598 if (found != funcRefs.end()) {
599 return found->second;
600 }
601 std::unique_ptr<RooAbsReal> func = pdf.createExpectedEventsFunc(nset);
602 if (!func) {
603 failed = true;
604 return "0.0";
605 }
606 // Different components can have the same name
607 func->SetName((std::string(func->GetName()) + "_" + std::to_string(funcRefs.size())).c_str());
608 std::string const funcRef = "x[" + std::to_string(formulaArgs.size()) + "]";
609 formulaArgs.add(*func);
610 ownedFuncs.addOwned(std::move(func));
611 return funcRefs[&pdf] = funcRef;
612 };
613
614 std::string formula;
615 if (indexCatIsInNormSet(nset)) {
616 for (auto *proxy : static_range_cast<RooRealProxy *>(_pdfProxyList)) {
617 formula += (formula.empty() ? "" : " + ") + ref(static_cast<RooAbsPdf const &>(proxy->arg()));
618 }
619 if (formula.empty()) {
620 formula = "0.0";
621 }
622 } else {
623 // Nested ternary expression that selects the component matching the
624 // index state, keyed on the state index numbers.
625 formulaArgs.add(_indexCat.arg());
626 std::size_t numStates = 0;
627 for (auto const &nameIdx : _indexCat.arg()) {
628 auto *proxy = static_cast<RooRealProxy *>(_pdfProxyList.FindObject(nameIdx.first.c_str()));
629 if (!proxy) {
630 continue;
631 }
632 formula += "x[0] == " + std::to_string(nameIdx.second) + " ? " +
633 ref(static_cast<RooAbsPdf const &>(proxy->arg())) + " : (";
634 ++numStates;
635 }
636 formula += "0.0" + std::string(numStates, ')');
637 }
638
639 // Like the default implementation, return nullptr if a component can't
640 // create the function.
641 if (failed) {
642 return nullptr;
643 }
644
645 auto out = std::make_unique<RooFormulaVar>(name.c_str(), name.c_str(), formula.c_str(), formulaArgs);
646 out->addOwnedComponents(std::move(ownedFuncs));
647 return out;
648}
649
650////////////////////////////////////////////////////////////////////////////////
651/// Forward determination of analytical integration capabilities to component p.d.f.s
652/// A unique code is assigned to the combined integration capabilities of all associated
653/// p.d.f.s
654
656 const RooArgSet* normSet, const char* rangeName) const
657{
658 // Declare that we can analytically integrate all requested observables
659 analVars.add(allVars) ;
660
661 // Retrieve (or create) the required partial integral list
662 Int_t code ;
663
664 // Check if this configuration was created before
665 CacheElem* cache = static_cast<CacheElem*>(_partIntMgr.getObj(normSet,&analVars,nullptr,RooNameReg::ptr(rangeName))) ;
666 if (cache) {
667 code = _partIntMgr.lastIndex() ;
668 return code+1 ;
669 }
670 cache = new CacheElem ;
671
672 // Create the partial integral set for this request
673 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdfProxyList)) {
674 cache->_partIntList.addOwned(std::unique_ptr<RooAbsReal>{proxy->arg().createIntegral(analVars,normSet,nullptr,rangeName)});
675 }
676
677 // Store the partial integral list and return the assigned code ;
678 code = _partIntMgr.setObj(normSet,&analVars,cache,RooNameReg::ptr(rangeName)) ;
679
680 return code+1 ;
681}
682
683
684
685////////////////////////////////////////////////////////////////////////////////
686/// Return analytical integration defined by given code
687
688double RooSimultaneous::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* /*rangeName*/) const
689{
690 // No integration scenario
691 if (code==0) {
692 return getVal(normSet) ;
693 }
694
695 // Partial integration scenarios, rangeName already encoded in 'code'
696 CacheElem* cache = static_cast<CacheElem*>(_partIntMgr.getObjByIndex(code-1)) ;
697
699 Int_t idx = _pdfProxyList.IndexOf(proxy) ;
700 return (static_cast<RooAbsReal*>(cache->_partIntList.at(idx)))->getVal(normSet) ;
701}
702
703
704
705
706
707
708////////////////////////////////////////////////////////////////////////////////
709/// Back-end for plotOn() implementation on RooSimultaneous which
710/// needs special handling because a RooSimultaneous PDF cannot
711/// project out its index category via integration. plotOn() will
712/// abort if this is requested without providing a projection dataset.
713
715{
716 // Sanity checks
717 if (plotSanityChecks(frame)) return frame ;
718
719 // Special case: if an asymmetry is requested with respect to our index
720 // category, we cannot reroute the plotting to the component pdfs. The
721 // component pdfs don't depend on the index category, so the asymmetry engine
722 // in the base class would not be able to split them by index state. Instead,
723 // we delegate directly to the base class implementation, which constructs the
724 // asymmetry from the two index-state component pdfs (see the overridden
725 // createAsymmetryComponent() and GitHub issue #14255).
726 if (auto *asymCmd = static_cast<RooCmdArg *>(cmdList.FindObject("Asymmetry"))) {
727 auto *asymCat = dynamic_cast<RooAbsCategory const *>(asymCmd->getObject(0));
728 if (asymCat && asymCat == &_indexCat.arg()) {
729
730 RooLinkedList cmdList2(cmdList);
731
732 // The base-class asymmetry-plotting engine averages the projection over
733 // the projection dataset. This is not supported for the composite data
734 // stores that back datasets with a category index, so we flatten such a
735 // projection dataset into a plain (vector-backed) copy first. Both the
736 // copy and the replacement command must outlive the plotOn() call below,
737 // because the command list only stores pointers to them.
738 std::unique_ptr<RooAbsData> flatProjData;
739 RooCmdArg newProjWData;
740 if (auto *projWData = static_cast<RooCmdArg *>(cmdList2.FindObject("ProjData"))) {
741 auto *projData = dynamic_cast<RooDataSet const *>(projWData->getObject(1));
742 if (projData && dynamic_cast<RooCompositeDataStore const *>(projData->store())) {
743 flatProjData = std::make_unique<RooDataSet>(projData->GetName(), projData->GetTitle(), *projData->get(),
744 RooFit::Import(*const_cast<RooDataSet *>(projData)));
745 const RooArgSet *projDataSet = projWData->getSet(0);
746 newProjWData = projDataSet ? RooFit::ProjWData(*projDataSet, *flatProjData)
747 : RooFit::ProjWData(*flatProjData);
748 replaceOrAdd(cmdList2, newProjWData);
749 }
750 }
751
752 return RooAbsReal::plotOn(frame, cmdList2);
753 }
754 }
755
756 // Extract projection configuration from command list
757 RooCmdConfig pc("RooSimultaneous::plotOn(" + std::string(GetName()) + ")");
758 pc.defineString("sliceCatState","SliceCat",0,"",true) ;
759 pc.defineDouble("scaleFactor","Normalization",0,1.0) ;
760 pc.defineInt("scaleType","Normalization",0,RooAbsPdf::Relative) ;
761 pc.defineObject("sliceCatList","SliceCat",0,nullptr,true) ;
762 // This dummy is needed for plotOn to recognize the "SliceCatMany" command.
763 // It is not used directly, but the "SliceCat" commands are nested in it.
764 // Removing this dummy definition results in "ERROR: unrecognized command: SliceCatMany".
765 pc.defineObject("dummy1","SliceCatMany",0) ;
766 pc.defineSet("projSet","Project",0) ;
767 pc.defineSet("sliceSet","SliceVars",0) ;
768 pc.defineSet("projDataSet","ProjData",0) ;
769 pc.defineObject("projData","ProjData",1) ;
770 pc.defineMutex("Project","SliceVars") ;
771 pc.allowUndefined() ; // there may be commands we don't handle here
772
773 // Process and check varargs
774 pc.process(cmdList) ;
775 if (!pc.ok(true)) {
776 return frame ;
777 }
778
779 RooAbsData* projData = static_cast<RooAbsData*>(pc.getObject("projData")) ;
780 const RooArgSet* projDataSet = pc.getSet("projDataSet");
781 const RooArgSet* sliceSetTmp = pc.getSet("sliceSet") ;
782 std::unique_ptr<RooArgSet> sliceSet( sliceSetTmp ? (static_cast<RooArgSet*>(sliceSetTmp->Clone())) : nullptr );
783 const RooArgSet* projSet = pc.getSet("projSet") ;
784 double scaleFactor = pc.getDouble("scaleFactor") ;
785 ScaleType stype = (ScaleType) pc.getInt("scaleType") ;
786
787
788 // Look for category slice arguments and add them to the master slice list if found
789 const char* sliceCatState = pc.getString("sliceCatState",nullptr,true) ;
790 const RooLinkedList& sliceCatList = pc.getObjectList("sliceCatList") ;
791 if (sliceCatState) {
792
793 // Make the master slice set if it doesnt exist
794 if (!sliceSet) {
795 sliceSet = std::make_unique<RooArgSet>();
796 }
797
798 // Prepare comma separated label list for parsing
799 auto catTokens = ROOT::Split(sliceCatState, ",");
800
801 // Loop over all categories provided by (multiple) Slice() arguments
802 unsigned int tokenIndex = 0;
803 for(auto * scat : static_range_cast<RooCategory*>(sliceCatList)) {
804 const char* slabel = tokenIndex >= catTokens.size() ? nullptr : catTokens[tokenIndex++].c_str();
805
806 if (slabel) {
807 // Set the slice position to the value indicated by slabel
808 scat->setLabel(slabel) ;
809 // Add the slice category to the master slice set
810 sliceSet->add(*scat,false) ;
811 }
812 }
813 }
814
815 // Check if we have a projection dataset
816 if (!projData) {
817 coutE(InputArguments) << "RooSimultaneous::plotOn(" << GetName() << ") ERROR: must have a projection dataset for index category" << std::endl ;
818 return frame ;
819 }
820
821 // Make list of variables to be projected
822 RooArgSet projectedVars ;
823 if (sliceSet) {
824 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
825
826 // Take out the sliced variables
827 for (const auto sliceArg : *sliceSet) {
828 RooAbsArg* arg = projectedVars.find(sliceArg->GetName()) ;
829 if (arg) {
830 projectedVars.remove(*arg) ;
831 } else {
832 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") slice variable "
833 << sliceArg->GetName() << " was not projected anyway" << std::endl ;
834 }
835 }
836 } else if (projSet) {
837 makeProjectionSet(frame->getPlotVar(),projSet,projectedVars,false) ;
838 } else {
839 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
840 }
841
842 bool projIndex(false) ;
843
844 if (!_indexCat.arg().isDerived()) {
845 // *** Error checking for a fundamental index category ***
846 //cout << "RooSim::plotOn: index is fundamental" << std::endl ;
847
848 // Check that the provided projection dataset contains our index variable
849 if (!projData->get()->find(_indexCat.arg().GetName())) {
850 coutE(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") ERROR: Projection over index category "
851 << "requested, but projection data set doesn't contain index category" << std::endl ;
852 return frame ;
853 }
854
855 if (projectedVars.find(_indexCat.arg().GetName())) {
856 projIndex=true ;
857 }
858
859 } else {
860 // *** Error checking for a composite index category ***
861
862 // Determine if any servers of the index category are in the projectedVars
863 RooArgSet projIdxServers ;
864 bool anyServers(false) ;
865 for (const auto server : flattenedCatList()) {
866 if (projectedVars.find(server->GetName())) {
867 anyServers=true ;
868 projIdxServers.add(*server) ;
869 }
870 }
871
872 // Check that the projection dataset contains all the
873 // index category components we're projecting over
874
875 // Determine if all projected servers of the index category are in the projection dataset
876 bool allServers(true) ;
877 std::string missing;
878 for (const auto server : projIdxServers) {
879 if (!projData->get()->find(server->GetName())) {
880 allServers=false ;
881 missing = server->GetName();
882 }
883 }
884
885 if (!allServers) {
886 coutE(Plotting) << "RooSimultaneous::plotOn(" << GetName()
887 << ") ERROR: Projection dataset doesn't contain complete set of index categories to do projection."
888 << "\n\tcategory " << missing << " is missing." << std::endl ;
889 return frame ;
890 }
891
892 if (anyServers) {
893 projIndex = true ;
894 }
895 }
896
897 // Calculate relative weight fractions of components
898 std::unique_ptr<Roo1DTable> wTable( projData->table(_indexCat.arg()) );
899
900 // Clone the index category to be able to cycle through the category states for plotting without
901 // affecting the category state of our instance
902 RooArgSet idxCloneSet;
903 RooArgSet(*_indexCat).snapshot(idxCloneSet, true);
904 auto idxCatClone = static_cast<RooAbsCategoryLValue*>(idxCloneSet.find(_indexCat->GetName()) );
905 assert(idxCatClone);
906
907 // Make list of category columns to exclude from projection data
908 std::unique_ptr<RooArgSet> idxCompSliceSet( idxCatClone->getObservables(frame->getNormVars()) );
909
910 // If we don't project over the index, just do the regular plotOn
911 if (!projIndex) {
912
913 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
914 << " represents a slice in the index category (" << _indexCat.arg().GetName() << ")" << std::endl ;
915
916 // Reduce projData: take out fitCat (component) columns and entries that don't match selected slice
917 // Construct cut string to only select projection data event that match the current slice
918
919 // Make cut string to exclude rows from projection data
920 if (sliceSet) {
921 for (auto *idxComp : static_range_cast<RooCategory *>(*idxCompSliceSet)) {
922 if (auto* slicedComponent = static_cast<const RooAbsCategory*>(sliceSet->find(*idxComp))) {
923 idxComp->setIndex(slicedComponent->getCurrentIndex(), false);
924 }
925 }
926 }
927 std::string cutString = RooFit::Detail::makeSliceCutString(*idxCompSliceSet);
928
929 // Make temporary projData without RooSim index category components
930 RooArgSet projDataVars(*projData->get()) ;
931 projDataVars.remove(*idxCompSliceSet,true,true) ;
932
933 std::unique_ptr<RooAbsData>
934 projDataTmp(projData->reduce(RooFit::SelectVars(projDataVars), RooFit::Cut(cutString.c_str())));
935
936 // Override normalization and projection dataset
937 RooCmdArg tmp1 =
938 RooFit::Normalization(scaleFactor * wTable->get(idxCatClone->getCurrentLabel()), RooAbsReal::NumEvent);
939 RooCmdArg tmp2 = RooFit::ProjWData(*projDataSet,*projDataTmp) ;
940
941 // WVE -- do not adjust normalization for asymmetry plots
942 RooLinkedList cmdList2(cmdList) ;
943 if (!cmdList.find("Asymmetry")) {
944 replaceOrAdd(cmdList2, tmp1);
945 }
946 replaceOrAdd(cmdList2, tmp2);
947
948 // Plot single component
949 RooPlot* retFrame = getPdf(idxCatClone->getCurrentLabel())->plotOn(frame,cmdList2);
950 return retFrame ;
951 }
952
953 // If we project over the index, plot using a temporary RooAddPdf
954 // using the weights from the data as coefficients
955
956 // Build the list of indexCat components that are sliced
957 idxCompSliceSet->remove(projectedVars,true,true) ;
958
959 // Make a new expression that is the weighted sum of requested components
960 RooArgList pdfCompList ;
961 RooArgList wgtCompList ;
962//RooAbsPdf* pdf ;
963 double sumWeight(0) ;
964 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdfProxyList)) {
965
966 idxCatClone->setLabel(proxy->name()) ;
967
968 // Determine if this component is the current slice (if we slice)
969 bool skip(false) ;
970 for (const auto idxSliceCompArg : *idxCompSliceSet) {
971 const auto idxSliceComp = static_cast<RooAbsCategory*>(idxSliceCompArg);
972 RooAbsCategory* idxComp = static_cast<RooAbsCategory*>(idxCloneSet.find(idxSliceComp->GetName())) ;
973 if (idxComp->getCurrentIndex()!=idxSliceComp->getCurrentIndex()) {
974 skip=true ;
975 break ;
976 }
977 }
978 if (skip) continue ;
979
980 // Instantiate a RRV holding this pdfs weight
981 wgtCompList.addOwned(std::make_unique<RooRealVar>(proxy->name(),"coef",wTable->get(proxy->name())));
982 sumWeight += wTable->getFrac(proxy->name()) ;
983
984 // Add the PDF to list list
985 pdfCompList.add(proxy->arg()) ;
986 }
987
988 TString plotVarName(GetName()) ;
989 RooAddPdf plotVar{plotVarName,"weighted sum of RS components",pdfCompList,wgtCompList};
990
991 // Fix appropriate coefficient normalization in plot function
992 if (!_plotCoefNormSet.empty()) {
993 plotVar.fixAddCoefNormalization(_plotCoefNormSet) ;
994 }
995
996 std::unique_ptr<RooAbsData> projDataTmp;
997 RooArgSet projSetTmp ;
998 if (projData) {
999
1000 // Construct cut string to only select projection data event that match the current slice
1001 std::string cutString = RooFit::Detail::makeSliceCutString(*idxCompSliceSet);
1002
1003 // Make temporary projData without RooSim index category components
1004 RooArgSet projDataVars(*projData->get()) ;
1005 RooArgSet idxCatServers;
1006 _indexCat.arg().getObservables(frame->getNormVars(), idxCatServers) ;
1007
1008 projDataVars.remove(idxCatServers,true,true) ;
1009
1010 projDataTmp = std::unique_ptr<RooAbsData>{projData->reduce(RooFit::SelectVars(projDataVars), RooFit::Cut(cutString.c_str()))};
1011
1012
1013
1014 if (projSet) {
1015 projSetTmp.add(*projSet) ;
1016 projSetTmp.remove(idxCatServers,true,true);
1017 }
1018 }
1019
1020
1021 if (_indexCat.arg().isDerived() && !idxCompSliceSet->empty()) {
1022 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
1023 << " represents a slice in index category components " << *idxCompSliceSet << std::endl ;
1024
1025 RooArgSet idxCompProjSet;
1026 _indexCat.arg().getObservables(frame->getNormVars(), idxCompProjSet) ;
1027 idxCompProjSet.remove(*idxCompSliceSet,true,true) ;
1028 if (!idxCompProjSet.empty()) {
1029 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
1030 << " averages with data index category components " << idxCompProjSet << std::endl ;
1031 }
1032 } else {
1033 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
1034 << " averages with data index category (" << _indexCat.arg().GetName() << ")" << std::endl ;
1035 }
1036
1037
1038 // Override normalization and projection dataset
1039 RooLinkedList cmdList2(cmdList) ;
1040
1041 RooCmdArg tmp1 = RooFit::Normalization(scaleFactor*sumWeight,stype) ;
1042 RooCmdArg tmp2 = RooFit::ProjWData(*projDataSet,*projDataTmp) ;
1043 // WVE -- do not adjust normalization for asymmetry plots
1044 if (!cmdList.find("Asymmetry")) {
1045 replaceOrAdd(cmdList2, tmp1);
1046 }
1047 replaceOrAdd(cmdList2, tmp2);
1048
1049 RooPlot* frame2 ;
1050 if (!projSetTmp.empty()) {
1051 // Plot temporary function
1052 RooCmdArg tmp3 = RooFit::Project(projSetTmp) ;
1053 replaceOrAdd(cmdList2, tmp3);
1054 frame2 = plotVar.plotOn(frame,cmdList2) ;
1055 } else {
1056 // Plot temporary function
1057 frame2 = plotVar.plotOn(frame,cmdList2) ;
1058 }
1059
1060 return frame2 ;
1061}
1062
1063
1064////////////////////////////////////////////////////////////////////////////////
1065/// Build the component function of an asymmetry plot (see
1066/// RooAbsReal::plotAsymOn()) for a fixed state of the asymmetry category.
1067///
1068/// When the asymmetry is requested in our own index category, the component for
1069/// a given index state is simply the corresponding pdf. We return a clone of
1070/// that pdf directly instead of a RooSimultaneous with a pinned index, because
1071/// a RooSimultaneous compiles its per-category observables with a category
1072/// prefix. That prefix makes it incompatible with the vectorized evaluation
1073/// backend that averages the asymmetry over the projection data, and would
1074/// otherwise silently yield a flat (zero) asymmetry (see issue #14255). For any
1075/// other asymmetry category we fall back to the generic implementation.
1076
1077std::unique_ptr<RooAbsReal>
1079{
1080 if (&asymCat == &_indexCat.arg()) {
1081 const std::string &label = _indexCat.arg().lookupName(asymCatState.getCurrentIndex());
1082 if (RooAbsPdf *pdf = getPdf(label)) {
1083 return RooHelpers::cloneTreeWithSameParameters(static_cast<RooAbsReal const &>(*pdf));
1084 }
1085 }
1086 return RooAbsReal::createAsymmetryComponent(asymCat, asymCatState);
1087}
1088
1089
1090////////////////////////////////////////////////////////////////////////////////
1091/// Interface function used by test statistics to freeze choice of observables
1092/// for interpretation of fraction coefficients. Needed here because a RooSimultaneous
1093/// works like a RooAddPdf when plotted
1094
1095void RooSimultaneous::selectNormalization(const RooArgSet* normSet, bool /*force*/)
1096{
1098 if (normSet) {
1099 // The index category must not be stored in the set: it is meaningless for
1100 // the coefficient normalization, since it is never an observable of the
1101 // component pdfs (RooAddPdf::selectNormalization() would filter it out
1102 // again anyway). Worse, it is already registered as a value server via
1103 // the index category proxy, and registering the same server a second
1104 // time through this non-propagating set proxy corrupts the reference
1105 // counts of the server's client lists when the set is cleared again.
1106 RooArgSet filteredNormSet{*normSet};
1107 filteredNormSet.remove(_indexCat.arg(), true, true);
1108 _plotCoefNormSet.add(filteredNormSet);
1109 }
1110}
1111
1112
1113////////////////////////////////////////////////////////////////////////////////
1114/// Interface function used by test statistics to freeze choice of range
1115/// for interpretation of fraction coefficients. Needed here because a RooSimultaneous
1116/// works like a RooAddPdf when plotted
1117
1118void RooSimultaneous::selectNormalizationRange(const char* normRange2, bool /*force*/)
1119{
1120 _plotCoefNormRange = RooNameReg::ptr(normRange2) ;
1121}
1122
1123
1124
1125
1126////////////////////////////////////////////////////////////////////////////////
1127
1129 const RooArgSet* auxProto, bool verbose, bool autoBinned, const char* binnedTag) const
1130{
1131 const char* idxCatName = _indexCat.arg().GetName() ;
1132
1133 if (vars.find(idxCatName) && prototype==nullptr
1134 && (auxProto==nullptr || auxProto->empty())
1135 && (autoBinned || (binnedTag && strlen(binnedTag)))) {
1136
1137 // Return special generator config that can also do binned generation for selected states
1138 return new RooSimSplitGenContext(*this,vars,verbose,autoBinned,binnedTag) ;
1139
1140 } else {
1141
1142 // Return regular generator config ;
1143 return genContext(vars,prototype,auxProto,verbose) ;
1144 }
1145}
1146
1147
1148
1149////////////////////////////////////////////////////////////////////////////////
1150/// Return specialized generator context for simultaneous p.d.f.s
1151
1153 const RooArgSet* auxProto, bool verbose) const
1154{
1155 RooArgSet allVars{vars};
1156 if(prototype) allVars.add(*prototype->get());
1157
1158 RooArgSet catsAmongAllVars;
1159 allVars.selectCommon(flattenedCatList(), catsAmongAllVars);
1160
1161 // Not generating index cat: we better error out because it's not clear what
1162 // the user expects here. Does the user want to generate according to the
1163 // currently-selected pdf? Or does the user want to generate global
1164 // observable values according to the union of all category pdfs?
1165 // Print an error and tell the user what to do to explicitly.
1166 if(catsAmongAllVars.empty()) {
1167 coutE(InputArguments) << "RooSimultaneous::generateSimGlobal(" << GetName()
1168 << ") asking to generate without the index category!\n"
1169 << "It's not clear what to do. you probably want to either:\n"
1170 << "\n"
1171 << " 1. Generate according to the currently-selected pdf.\n"
1172 << " Please do this explicitly with:\n"
1173 << " simpdf->getPdf(simpdf->indexCat().getCurrentLabel())->generate(vars, ...)\n"
1174 << "\n"
1175 << " 1. Generate global observable values according to the union of all component pdfs.\n"
1176 << " For this, please use simpdf->generateSimGlobal(vars, ...)\n"
1177 << std::endl;
1178 return nullptr;
1179 }
1180
1181 RooArgSet catsAmongProtoVars;
1182 if(prototype) {
1183 prototype->get()->selectCommon(flattenedCatList(), catsAmongProtoVars);
1184
1185 if(!catsAmongProtoVars.empty() && catsAmongProtoVars.size() != flattenedCatList().size()) {
1186 // Abort if we have only part of the servers
1187 coutE(Plotting) << "RooSimultaneous::genContext: ERROR: prototype must include either all "
1188 << " components of the RooSimultaneous index category or none " << std::endl;
1189 return nullptr;
1190 }
1191 }
1192
1193 return new RooSimGenContext(*this,vars,prototype,auxProto,verbose) ;
1194}
1195
1196
1197
1198
1199////////////////////////////////////////////////////////////////////////////////
1200
1202 const RooArgSet* nset,
1203 double scaleFactor,
1204 bool correctForBinVolume,
1205 bool showProgress) const
1206{
1207 if (RooAbsReal::fillDataHist (hist, nset, scaleFactor,
1208 correctForBinVolume, showProgress) == nullptr)
1209 return nullptr;
1210
1211 const double sum = hist->sumEntries();
1212 if (sum != 0) {
1213 for (int i=0 ; i<hist->numEntries() ; i++) {
1214 hist->set(i, hist->weight(i) / sum, 0.);
1215 }
1216 }
1217
1218 return hist;
1219}
1220
1221
1222
1223
1224////////////////////////////////////////////////////////////////////////////////
1225/// Special generator interface for generation of 'global observables' -- for RooStats tools.
1226///
1227/// \note Why one can't just use RooAbsPdf::generate()? That's because when
1228/// using the regular generate() method, a specific component pdf is selected
1229/// for each generated entry according to the index category value. However,
1230/// global observable values are independent of the current index category,
1231/// which can best be illustrated with the case where a global observable
1232/// corresponds to a nuisance parameter that is relevant for multiple channels.
1233/// So the interpretation of what is an entry in the generated dataset is very
1234/// different, hence the separate function.
1235
1237{
1238 // Generating the index category together with the global observables doesn't make any sense.
1239 RooArgSet catsAmongAllVars;
1240 whatVars.selectCommon(flattenedCatList(), catsAmongAllVars);
1241 if(!catsAmongAllVars.empty()) {
1242 coutE(InputArguments) << "RooSimultaneous::generateSimGlobal(" << GetName()
1243 << ") asking to generate global obserables at the same time as the index category!\n"
1244 << "This doesn't make any sense: global observables are generally not related to a specific channel.\n"
1245 << std::endl;
1246 return nullptr;
1247 }
1248
1249 // Make set with clone of variables (placeholder for output)
1250 RooArgSet globClone;
1251 whatVars.snapshot(globClone);
1252
1253 auto data = std::make_unique<RooDataSet>("gensimglobal","gensimglobal",whatVars);
1254
1255 for (Int_t i=0 ; i<nEvents ; i++) {
1256 for (const auto& nameIdx : indexCat()) {
1257
1258 // Get pdf associated with state from simpdf
1259 RooAbsPdf* pdftmp = getPdf(nameIdx.first);
1260
1261 RooArgSet globtmp;
1262 pdftmp->getObservables(&whatVars, globtmp) ;
1263
1264 // If there are any, generate only global variables defined by the pdf
1265 // associated with this state and transfer values to output placeholder.
1266 if (!globtmp.empty()) {
1267 globClone.assign(*std::unique_ptr<RooDataSet>{pdftmp->generate(globtmp,1)}->get(0)) ;
1268 }
1269 }
1270 data->add(globClone) ;
1271 }
1272
1273 return RooFit::makeOwningPtr(std::move(data));
1274}
1275
1276
1277/// Wraps the components of this RooSimultaneous in RooBinSamplingPdfs.
1278/// \param[in] data The dataset to be used in the eventual fit, used to figure
1279/// out the observables and whether the dataset is binned.
1280/// \param[in] precision Precision argument for all created RooBinSamplingPdfs.
1282
1283 if (precision < 0.) return;
1284
1285 RooArgSet newSamplingPdfs;
1286
1287 for (auto const &item : this->indexCat()) {
1288
1289 auto const &catName = item.first;
1290 auto &pdf = *this->getPdf(catName);
1291
1292 if (auto newSamplingPdf = RooBinSamplingPdf::create(pdf, data, precision)) {
1293 // Set the "ORIGNAME" attribute the indicate to
1294 // RooAbsArg::redirectServers() which pdf should be replaced by this
1295 // RooBinSamplingPdf in the RooSimultaneous.
1296 newSamplingPdf->setAttribute(
1297 (std::string("ORIGNAME:") + pdf.GetName()).c_str());
1298 newSamplingPdfs.addOwned(std::move(newSamplingPdf));
1299 }
1300 }
1301
1302 this->redirectServers(newSamplingPdfs, false, true);
1303 this->addOwnedComponents(std::move(newSamplingPdfs));
1304}
1305
1306
1307/// Wraps the components of this RooSimultaneous in RooBinSamplingPdfs, with a
1308/// different precision parameter for each component.
1309/// \param[in] data The dataset to be used in the eventual fit, used to figure
1310/// out the observables and whether the dataset is binned.
1311/// \param[in] precisions The map that gives the precision argument for each
1312/// component in the RooSimultaneous. The keys are the pdf names. If
1313/// there is no value for a given component, it will not use the bin
1314/// integration. Otherwise, the value has the same meaning than in
1315/// the IntegrateBins() command argument for RooAbsPdf::fitTo().
1316/// \param[in] useCategoryNames If this flag is set, the category names will be
1317/// used to look up the precision in the precisions map instead of
1318/// the pdf names.
1320 std::map<std::string, double> const& precisions,
1321 bool useCategoryNames /*=false*/) {
1322
1323 constexpr double defaultPrecision = -1.;
1324
1325 RooArgSet newSamplingPdfs;
1326
1327 for (auto const &item : this->indexCat()) {
1328
1329 auto const &catName = item.first;
1330 auto &pdf = *this->getPdf(catName);
1331 std::string pdfName = pdf.GetName();
1332
1333 auto found = precisions.find(useCategoryNames ? catName : pdfName);
1334 const double precision =
1335 found != precisions.end() ? found->second : defaultPrecision;
1336 if (precision < 0.)
1337 continue;
1338
1339 if (auto newSamplingPdf = RooBinSamplingPdf::create(pdf, data, precision)) {
1340 // Set the "ORIGNAME" attribute the indicate to
1341 // RooAbsArg::redirectServers() which pdf should be replaced by this
1342 // RooBinSamplingPdf in the RooSimultaneous.
1343 newSamplingPdf->setAttribute(
1344 (std::string("ORIGNAME:") + pdf.GetName()).c_str());
1345 newSamplingPdfs.addOwned(std::move(newSamplingPdf));
1346 }
1347 }
1348
1349 this->redirectServers(newSamplingPdfs, false, true);
1350 this->addOwnedComponents(std::move(newSamplingPdfs));
1351}
1352
1353/// Internal utility function to get a list of all category components for this
1354/// RooSimultaneous. The output contains only the index category if it is a
1355/// RooCategory, or the list of all category components if it is a
1356/// RooSuperCategory.
1358{
1359 // Note that the index category of a RooSimultaneous can only be of type
1360 // RooCategory or RooSuperCategory, because these are the only classes that
1361 // inherit from RooAbsCategoryLValue.
1362 if (auto superCat = dynamic_cast<RooSuperCategory const*>(&_indexCat.arg())) {
1363 return superCat->inputCatList();
1364 }
1365
1366 if(!_indexCatSet) {
1367 _indexCatSet = std::make_unique<RooArgSet>(_indexCat.arg());
1368 }
1369 return *_indexCatSet;
1370}
1371
1372////////////////////////////////////////////////////////////////////////////////
1373/// Check if the index category is in the normalization set `nset`, matching by
1374/// name. For a RooSuperCategory index, it's enough if all its input categories
1375/// are in `nset`, which is the case for the variables of a dataset.
1377{
1378 if (!nset) {
1379 return false;
1380 }
1381 if (nset->contains(_indexCat.arg())) {
1382 return true;
1383 }
1384 RooArgSet const &cats = flattenedCatList();
1385 return std::all_of(cats.begin(), cats.end(), [&](RooAbsArg const *cat) { return nset->contains(*cat); });
1386}
1387
1388////////////////////////////////////////////////////////////////////////////////
1389/// Check if the index category is among the variables `vars`, matching by
1390/// name. For a RooSuperCategory index, any of its input categories counts.
1391///
1392/// If the index category is not among the observables of a fit, this
1393/// RooSimultaneous does not split the data into channels: it acts as a
1394/// "switch" that evaluates to the component selected by the current index
1395/// state, analogous to RooMultiPdf. Fitting infrastructure uses this check to
1396/// decide between the two modes.
1398{
1399 RooArgSet catsAmongVars;
1400 vars.selectCommon(flattenedCatList(), catsAmongVars);
1401 return !catsAmongVars.empty();
1402}
1403
1404namespace {
1405
1406void markObs(RooAbsArg *arg, std::string const &prefix, RooArgSet const &normSet)
1407{
1408 for (RooAbsArg *server : arg->servers()) {
1409 if (server->isFundamental() && normSet.find(*server)) {
1410 markObs(server, prefix, normSet);
1411 server->setAttribute("__obs__");
1412 } else if (!server->isFundamental()) {
1413 markObs(server, prefix, normSet);
1414 }
1415 }
1416}
1417
1418void prefixArgs(RooAbsArg *arg, std::string const &prefix, RooArgSet const &normSet)
1419{
1420 if (!arg->getStringAttribute("__prefix__")) {
1421 arg->SetName((prefix + arg->GetName()).c_str());
1422 arg->setStringAttribute("__prefix__", prefix.c_str());
1423 }
1424 for (RooAbsArg *server : arg->servers()) {
1425 if (server->isFundamental() && normSet.find(*server)) {
1426 prefixArgs(server, prefix, normSet);
1427 } else if (!server->isFundamental()) {
1428 prefixArgs(server, prefix, normSet);
1429 }
1430 }
1431}
1432
1433} // namespace
1434
1435std::unique_ptr<RooAbsArg>
1437{
1438 if (!indexCatIsObservable(normSet)) {
1439 // The index category is not an observable here: the RooSimultaneous
1440 // acts as a plain "switch" that evaluates to the component selected by
1441 // the current index state, analogous to RooMultiPdf. The channel
1442 // observables are then the same as the ones of this pdf, so the
1443 // channel-splitting compilation below (which renames the per-channel
1444 // observables so they can be filled from split datasets) must not be
1445 // used. Compile like an ordinary self-normalized pdf instead.
1446 return RooAbsPdf::compileForNormSet(normSet, ctx);
1447 }
1448
1449 std::unique_ptr<RooSimultaneous> newSimPdf{static_cast<RooSimultaneous *>(this->Clone())};
1450
1451 const char *rangeName = this->getStringAttribute("RangeName");
1452 bool splitRange = this->getAttribute("SplitRange");
1453
1454 RooArgSet newPdfs;
1455 std::vector<std::string> catNames;
1456
1457 for (auto *proxy : static_range_cast<RooRealProxy *>(newSimPdf->_pdfProxyList)) {
1458 catNames.emplace_back(proxy->GetName());
1459 std::string const &catName = catNames.back();
1460 const std::string prefix = "_" + catName + "_";
1461
1462 const std::string origname = proxy->arg().GetName();
1463
1464 auto pdfClone = RooHelpers::cloneTreeWithSameParameters(static_cast<RooAbsPdf const &>(proxy->arg()), &normSet);
1465
1466 markObs(pdfClone.get(), prefix, normSet);
1467
1468 std::unique_ptr<RooArgSet> pdfNormSet{
1469 std::unique_ptr<RooArgSet>(pdfClone->getVariables())->selectByAttrib("__obs__", true)};
1470 std::unique_ptr<RooArgSet> condVarSet{
1471 std::unique_ptr<RooArgSet>(pdfClone->getVariables())->selectByAttrib("__conditional__", true)};
1472
1473 pdfNormSet->remove(*condVarSet, true, true);
1474
1475 if (rangeName) {
1476 pdfClone->setNormRange(RooHelpers::getRangeNameForSimComponent(rangeName, splitRange, catName).c_str());
1477 }
1478
1479 RooFit::Detail::CompileContext pdfContext{*pdfNormSet};
1480 pdfContext.setLikelihoodMode(ctx.likelihoodMode());
1481 auto *pdfFinal = pdfContext.compile(*pdfClone, *newSimPdf, *pdfNormSet);
1482
1483 // The observables of the compiled computation graph are clones of the
1484 // ones in `pdfNormSet`, and only the clones are prefixed below. That's
1485 // why we have to translate the normalization set to the compiled args
1486 // before using it any further.
1487 RooArgSet compiledPdfNormSet = pdfContext.mapToCompiled(*pdfNormSet);
1488
1489 // We can only prefix the observables after everything related the
1490 // compiling of the compute graph for the normalization set is done. This
1491 // is because of a subtlety in conditional RooProdPdfs, which stores the
1492 // normalization sets for the individual pdfs in RooArgSets that are
1493 // disconnected from the computation graph, so we have no control over
1494 // them. An alternative would be to use recursive server re-direction,
1495 // but this has more performance overhead.
1496 prefixArgs(pdfFinal, prefix, normSet);
1497
1498 // This has to be done with the observables of the compiled graph, which
1499 // are prefixed at this point. Otherwise, the RooAddPdf components don't
1500 // find their coefficient normalization observables and silently keep the
1501 // default "automatic" interpretation of the coefficients, which results
1502 // in wrong yields in ranged fits (GitHub issue #23444).
1503 pdfFinal->fixAddCoefNormalization(compiledPdfNormSet, false);
1504
1505 pdfClone->SetName((std::string("_") + pdfClone->GetName()).c_str());
1506 pdfFinal->addOwnedComponents(std::move(pdfClone));
1507
1508 pdfFinal->setAttribute(("ORIGNAME:" + origname).c_str());
1509 newPdfs.add(*pdfFinal);
1510
1511 // We will remove the old pdf server because we will fill the new ones by
1512 // hand via the creation of new proxies.
1513 newSimPdf->removeServer(const_cast<RooAbsReal &>(proxy->arg()), true);
1514 }
1515
1516 // Replace pdfs with compiled pdfs. Don't use RooAbsArg::redirectServers()
1517 // here, because it doesn't support replacing two servers with the same name
1518 // (it can happen in a RooSimultaneous that two pdfs have the same name).
1519
1520 // First delete old proxies (we have already removed the servers before).
1521 newSimPdf->_pdfProxyList.Delete();
1522
1523 // Recreate the _pdfProxyList with the compiled pdfs
1524 for (std::size_t i = 0; i < newPdfs.size(); ++i) {
1525 const char *label = catNames[i].c_str();
1526 newSimPdf->_pdfProxyList.Add(
1527 new RooRealProxy(label, label, newSimPdf.get(), *static_cast<RooAbsReal *>(newPdfs[i])));
1528 }
1529
1530 ctx.compileServers(*newSimPdf, normSet); // to trigger compiling also the index category
1531
1532 return newSimPdf;
1533}
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define coutI(a)
#define oocoutW(o, a)
#define oocxcoutD(o, a)
#define coutE(a)
RooTemplateProxy< RooAbsReal > RooRealProxy
Compatibility typedef replacing the old RooRealProxy class.
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 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
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
bool dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr, bool valueOnly=false) const
Test whether we depend on (ie, are served by) any object in the specified collection.
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
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.
void SetName(const char *name) override
Set the name of the TNamed.
bool addOwnedComponents(const RooAbsCollection &comps)
Take ownership of the contents of 'comps'.
const Text_t * getStringAttribute(const Text_t *key) const
Get string attribute mapped under key 'key'.
bool redirectServers(const RooAbsCollection &newServerList, bool mustReplaceAll=false, bool nameChange=false, bool isRecursionStep=false)
Replace all direct servers of this object with the new servers in newServerList.
virtual bool isDerived() const
Does value or shape of this arg depend on any other arg?
Definition RooAbsArg.h:98
bool getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
RooFit::OwningPtr< RooArgSet > getVariables(bool stripDisconnected=true) const
Return RooArgSet with all variables (tree leaf nodes of expression tree)
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:89
virtual bool isFundamental() const
Is this object a fundamental type that can be added to a dataset? Fundamental-type subclasses overrid...
Definition RooAbsArg.h:176
Abstract base class for objects that represent a discrete value that can be set from the outside,...
virtual bool setLabel(const char *label, bool printError=true)=0
Change category state by specifying a state name.
A space to attach TBranches.
virtual value_type getCurrentIndex() const
Return index number of current state.
virtual const char * getCurrentLabel() const
Return label string of current state.
const std::string & lookupName(value_type index) const
Get the name corresponding to the given index.
std::map< std::string, value_type >::const_iterator begin() const
Iterator for category state names. Points to pairs of index and name.
std::size_t size() const
Number of states defined.
bool contains(const char *name) const
Check if collection contains an argument with a specific name.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
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
RooAbsArg * first() const
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
const_iterator begin() const
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
virtual const RooArgSet * get() const
Definition RooAbsData.h:99
virtual Roo1DTable * table(const RooArgSet &catSet, const char *cuts="", const char *opts="") const
Construct table for product of categories in catSet.
RooFit::OwningPtr< RooAbsData > reduce(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
Create a reduced copy of this dataset.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract base class for generator contexts of RooAbsPdf objects.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
std::unique_ptr< RooAbsArg > compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const override
RooArgSet const * _normSet
! Normalization set with for above integral
Definition RooAbsPdf.h:314
RooPlot * plotOn(RooPlot *frame, 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={}, const RooCmdArg &arg10={}) const override
Helper calling plotOn(RooPlot*, RooLinkedList&) const.
Definition RooAbsPdf.h:116
bool canBeExtended() const
If true, PDF can provide extended likelihood term.
Definition RooAbsPdf.h:214
@ CanBeExtended
Definition RooAbsPdf.h:208
@ MustBeExtended
Definition RooAbsPdf.h:208
@ CanNotBeExtended
Definition RooAbsPdf.h:208
RooFit::OwningPtr< RooDataSet > generate(const RooArgSet &whatVars, Int_t nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={})
See RooAbsPdf::generate(const RooArgSet&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,...
Definition RooAbsPdf.h:49
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
RooDataHist * fillDataHist(RooDataHist *hist, const RooArgSet *nset, double scaleFactor, bool correctForBinVolume=false, bool showProgress=false) const
Fill a RooDataHist with values sampled from this function at the bin centers.
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
bool plotSanityChecks(RooPlot *frame) const
Utility function for plotOn(), perform general sanity check on frame to ensure safe plotting operatio...
virtual std::unique_ptr< RooAbsReal > createAsymmetryComponent(const RooAbsCategoryLValue &asymCat, const RooAbsCategoryLValue &asymCatState) const
Build the component function of an asymmetry plot (see plotAsymOn()) that corresponds to a fixed stat...
virtual RooPlot * plotOn(RooPlot *frame, 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={}, const RooCmdArg &arg10={}) const
Plot (project) PDF on specified frame.
void makeProjectionSet(const RooAbsArg *plotVar, const RooArgSet *allVars, RooArgSet &projectedVars, bool silent) const
Utility function for plotOn() that constructs the set of observables to project when plotting ourselv...
Efficient implementation of a sum of PDFs of the form.
Definition RooAddPdf.h:32
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition RooArgSet.h:159
RooArgSet * selectCommon(const RooAbsCollection &refColl) const
Use RooAbsCollection::selecCommon(), but return as RooArgSet.
Definition RooArgSet.h:154
static std::unique_ptr< RooAbsPdf > create(RooAbsPdf &pdf, RooAbsData const &data, double precision)
Creates a wrapping RooBinSamplingPdf if appropriate.
Int_t setObj(const RooArgSet *nset, T *obj, const TNamed *isetRangeName=nullptr)
Setter function without integration set.
T * getObjByIndex(Int_t index) const
Retrieve payload object by slot index.
Int_t lastIndex() const
Return index of slot used in last get or set operation.
T * getObj(const RooArgSet *nset, Int_t *sterileIndex=nullptr, const TNamed *isetRangeName=nullptr)
Getter function without integration set.
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
Configurable parser for RooCmdArg named arguments.
void defineMutex(const char *head, Args_t &&... tail)
Define arguments where any pair is mutually exclusive.
bool process(const RooCmdArg &arg)
Process given RooCmdArg.
double getDouble(const char *name, double defaultValue=0.0) const
Return double property registered with name 'name'.
bool defineDouble(const char *name, const char *argName, int doubleNum, double defValue=0.0)
Define double property name 'name' mapped to double in slot 'doubleNum' in RooCmdArg with name argNam...
RooArgSet * getSet(const char *name, RooArgSet *set=nullptr) const
Return RooArgSet property registered with name 'name'.
bool defineSet(const char *name, const char *argName, int setNum, const RooArgSet *set=nullptr)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
bool ok(bool verbose) const
Return true of parsing was successful.
bool defineObject(const char *name, const char *argName, int setNum, const TObject *obj=nullptr, bool isArray=false)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
const char * getString(const char *name, const char *defaultValue="", bool convEmptyToNull=false) const
Return string property registered with name 'name'.
bool defineString(const char *name, const char *argName, int stringNum, const char *defValue="", bool appendMode=false)
Define double property name 'name' mapped to double in slot 'stringNum' in RooCmdArg with name argNam...
const RooLinkedList & getObjectList(const char *name) const
Return list of objects registered with name 'name'.
bool defineInt(const char *name, const char *argName, int intNum, int defValue=0)
Define integer property name 'name' mapped to integer in slot 'intNum' in RooCmdArg with name argName...
void allowUndefined(bool flag=true)
If flag is true the processing of unrecognized RooCmdArgs is not considered an error.
int getInt(const char *name, int defaultValue=0) const
Return integer property registered with name 'name'.
TObject * getObject(const char *name, TObject *obj=nullptr) const
Return TObject property registered with name 'name'.
void removeAll() override
Remove all argument inset using remove(const RooAbsArg&).
bool add(const RooAbsArg &var, bool valueServer, bool shapeServer, bool silent)
Overloaded RooCollection_t::add() method insert object into set and registers object as server to own...
Combines several disjunct datasets into one.
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
double weight(std::size_t i) const
Return weight of i-th bin.
void set(std::size_t binNumber, double weight, double wgtErr)
Set bin content of bin that was last loaded with get(std::size_t).
double sumEntries() const override
Sum the weights of all bins.
Container class to hold unbinned data.
Definition RooDataSet.h:32
const RooArgSet * get(Int_t index) const override
Return RooArgSet with coordinates of event 'index'.
void compileServers(RooAbsArg &arg, RooArgSet const &normSet)
Collection class for internal use, storing a collection of RooAbsArg pointers in a doubly linked list...
bool Replace(const TObject *oldArg, const TObject *newArg)
Replace object 'oldArg' in collection with new object 'newArg'.
TObject * find(const char *name) const
Return pointer to object with given name in collection.
virtual void Add(TObject *arg)
TObject * FindObject(const char *name) const override
Return pointer to object with given name.
static const TNamed * ptr(const char *stringPtr)
Return a unique TNamed pointer for given C++ string.
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
const RooArgSet * getNormVars() const
Definition RooPlot.h:146
RooAbsRealLValue * getPlotVar() const
Definition RooPlot.h:137
Facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
void selectNormalization(const RooArgSet *depSet=nullptr, bool force=false) override
Interface function used by test statistics to freeze choice of observables for interpretation of frac...
double evaluate() const override
Return the current value: the value of the PDF associated with the current index category state.
Int_t _numPdf
Number of registered PDFs.
void selectNormalizationRange(const char *rangeName=nullptr, bool force=false) override
Interface function used by test statistics to freeze choice of range for interpretation of fraction c...
TList _pdfProxyList
List of PDF proxies (named after applicable category state)
std::unique_ptr< RooAbsReal > createAsymmetryComponent(const RooAbsCategoryLValue &asymCat, const RooAbsCategoryLValue &asymCatState) const override
Build the component function of an asymmetry plot (see RooAbsReal::plotAsymOn()) for a fixed state of...
bool indexCatIsInNormSet(RooArgSet const *nset) const
Check if the index category is in the normalization set nset, matching by name.
std::unique_ptr< RooAbsReal > createExpectedEventsFunc(const RooArgSet *nset) const override
Expected events function for the new evaluation backends: the sum over all components,...
RooObjCacheManager _partIntMgr
! Component normalization manager
~RooSimultaneous() override
Destructor.
RooFit::OwningPtr< RooDataSet > generateSimGlobal(const RooArgSet &whatVars, Int_t nEvents) override
Special generator interface for generation of 'global observables' – for RooStats tools.
RooArgSet const & flattenedCatList() const
Internal utility function to get a list of all category components for this RooSimultaneous.
RooPlot * plotOn(RooPlot *frame, 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={}, const RooCmdArg &arg10={}) const override
ExtendMode extendMode() const override
Examine the pdf components and check if one of them can be extended or must be extended.
RooCategoryProxy _indexCat
Index category.
double analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=nullptr) const override
Return analytical integration defined by given code.
Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &numVars, const RooArgSet *normSet, const char *rangeName=nullptr) const override
Forward determination of analytical integration capabilities to component p.d.f.s A unique code is as...
double expectedEvents(const RooArgSet *nset) const override
Return the number of expected events: If the index is in nset, then return the sum of the expected ev...
friend class RooSimGenContext
RooAbsGenContext * autoGenContext(const RooArgSet &vars, const RooDataSet *prototype=nullptr, const RooArgSet *auxProto=nullptr, bool verbose=false, bool autoBinned=true, const char *binnedTag="") const override
RooAbsPdf * getPdf(RooStringView catName) const
Return the p.d.f associated with the given index category name.
std::unique_ptr< RooAbsArg > compileForNormSet(RooArgSet const &normSet, RooFit::Detail::CompileContext &ctx) const override
static std::unique_ptr< RooSimultaneous::InitializationOutput > initialize(std::string const &name, RooAbsCategoryLValue &inIndexCat, std::map< std::string, RooAbsPdf * > const &pdfMap)
void wrapPdfsInBinSamplingPdfs(RooAbsData const &data, double precision)
Wraps the components of this RooSimultaneous in RooBinSamplingPdfs.
bool indexCatIsObservable(RooArgSet const &vars) const
Check if the index category is among the variables vars, matching by name.
const TNamed * _plotCoefNormRange
RooAbsGenContext * genContext(const RooArgSet &vars, const RooDataSet *prototype=nullptr, const RooArgSet *auxProto=nullptr, bool verbose=false) const override
Return specialized generator context for simultaneous p.d.f.s.
std::unique_ptr< RooArgSet > _indexCatSet
! Index category wrapped in a RooArgSet if needed internally
bool addPdf(const RooAbsPdf &pdf, const char *catLabel)
Associate given PDF with index category state label 'catLabel'.
RooSetProxy _plotCoefNormSet
const RooAbsCategoryLValue & indexCat() const
friend class RooSimSplitGenContext
virtual RooDataHist * fillDataHist(RooDataHist *hist, const RooArgSet *nset, double scaleFactor, bool correctForBinVolume=false, bool showProgress=false) const
The RooStringView is a wrapper around a C-style string that can also be constructed from a std::strin...
const char * c_str() const
Joins several RooAbsCategoryLValue objects into a single category.
bool setLabel(const char *label, bool printError=true) override
Set the value of the super category by specifying the state name.
const char * label() const
Get the label of the current category state. This function only makes sense for category proxies.
const T & arg() const
Return reference to object held in proxy.
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void Add(TObject *obj) override
Definition TList.h:81
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:600
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
virtual Int_t IndexOf(const TObject *obj) const
Return index of object in collection.
Basic string class.
Definition TString.h:137
RooCmdArg SelectVars(const RooArgSet &vars)
RooCmdArg Import(const char *state, TH1 &histo)
RooCmdArg ProjWData(const RooAbsData &projData, bool binData=false)
RooCmdArg Project(const RooArgSet &projSet)
RooCmdArg Normalization(double scaleFactor)
RooCmdArg Cut(const char *cutSpec)
std::vector< std::string > Split(std::string_view str, std::string_view delims, bool skipEmpty=false)
Splits a string at each character in delims.
std::string makeSliceCutString(RooArgSet const &sliceDataSet)
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
Definition Config.h:35
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
Definition Config.h:40
std::unique_ptr< T > cloneTreeWithSameParameters(T const &arg, RooArgSet const *observables=nullptr)
Clone RooAbsArg object and reattach to original parameters.
std::string getRangeNameForSimComponent(std::string const &rangeName, bool splitRange, std::string const &catName)
Internal struct used for initialization.
std::vector< RooAbsPdf const * > finalPdfs
std::vector< std::string > finalCatLabels
void addPdf(const RooAbsPdf &pdf, std::string const &catLabel)
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335