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 only supported if their index category is a
58parameter (switch mode); otherwise, creating the likelihood fails. To combine
59channels, use one RooSimultaneous over a RooCategory with one state per channel,
60or over a RooSuperCategory if the channels span the full product of several
61categories. RooSimultaneous objects flattened by ROOT 6.42 or earlier and read
62from files still work.
63**/
64
65#include "RooSimultaneous.h"
66
67#include "Roo1DTable.h"
69#include "RooAbsData.h"
70#include "RooAddPdf.h"
71#include "RooArgSet.h"
72#include "RooBinSamplingPdf.h"
73#include "RooCategory.h"
74#include "RooCmdConfig.h"
76#include "RooDataHist.h"
77#include "RooDataSet.h"
78#include "RooFormulaVar.h"
79#include "RooGlobalFunc.h"
80#include "RooMsgService.h"
81#include "RooNameReg.h"
82#include "RooPlot.h"
83#include "RooRandom.h"
84#include "RooRealVar.h"
85#include "RooSimGenContext.h"
87#include "RooSuperCategory.h"
88
89#include "RooFitImplHelpers.h"
90
91#include <ROOT/StringUtils.hxx>
92
93#include <algorithm>
94#include <iostream>
95#include <map>
96
97namespace {
98
99std::map<std::string, RooAbsPdf *> createPdfMap(const RooArgList &inPdfList, RooAbsCategoryLValue &inIndexCat)
100{
101 std::map<std::string, RooAbsPdf *> pdfMap;
102 auto indexCatIt = inIndexCat.begin();
103 for (unsigned int i = 0; i < inPdfList.size(); ++i) {
104 auto pdf = static_cast<RooAbsPdf *>(&inPdfList[i]);
105 const auto &nameIdx = (*indexCatIt++);
106 pdfMap[nameIdx.first] = pdf;
107 }
108 return pdfMap;
109}
110
111void replaceOrAdd(RooLinkedList &lst, TObject &obj)
112{
113 TObject *old = lst.FindObject(obj.GetName());
114 if (old) {
115 lst.Replace(old, &obj);
116 } else {
117 lst.Add(&obj);
118 }
119}
120
121} // namespace
122
123using std::string;
124
125
126
127
128////////////////////////////////////////////////////////////////////////////////
129/// Constructor with index category. PDFs associated with indexCat
130/// states can be added after construction with the addPdf() function.
131///
132/// RooSimultaneous can function without having a PDF associated
133/// with every single state. The normalization in such cases is taken
134/// from the number of registered PDFs, but getVal() will assert if
135/// when called for an unregistered index state.
136
137RooSimultaneous::RooSimultaneous(const char *name, const char *title,
138 RooAbsCategoryLValue& inIndexCat) :
139 RooSimultaneous{name, title, std::map<std::string, RooAbsPdf*>{}, inIndexCat}
140{
141}
142
143
144////////////////////////////////////////////////////////////////////////////////
145/// Constructor from index category and full list of PDFs.
146/// In this constructor form, a PDF must be supplied for each indexCat state
147/// to avoid ambiguities. The PDFs are associated with the states of the
148/// index category as they appear when iterating through the category states
149/// with RooAbsCategory::begin() and RooAbsCategory::end(). This usually means
150/// they are associated by ascending index numbers.
151///
152/// PDFs may not overlap (i.e. share any variables) with the index category (function)
153
154RooSimultaneous::RooSimultaneous(const char *name, const char *title,
155 const RooArgList& inPdfList, RooAbsCategoryLValue& inIndexCat) :
156 RooSimultaneous{name, title, createPdfMap(inPdfList, inIndexCat), inIndexCat}
157{
158 if (inPdfList.size() != inIndexCat.size()) {
159 std::stringstream errMsg;
160 errMsg << "RooSimultaneous::ctor(" << GetName()
161 << " ERROR: Number PDF list entries must match number of index category states, no PDFs added";
162 coutE(InputArguments) << errMsg.str() << std::endl;
163 throw std::invalid_argument(errMsg.str());
164 }
165}
166
167
168////////////////////////////////////////////////////////////////////////////////
169
170RooSimultaneous::RooSimultaneous(const char *name, const char *title, std::map<string, RooAbsPdf *> pdfMap,
171 RooAbsCategoryLValue &inIndexCat)
172 : RooAbsPdf(name, title),
173 _plotCoefNormSet("!plotCoefNormSet", "plotCoefNormSet", this, false, false),
174 _partIntMgr(this, 10),
175 _indexCat("indexCat", "Index category", this, inIndexCat)
176{
177 for (auto const &item : pdfMap) {
178 addPdf(*item.second, item.first.c_str());
179 }
180}
181
182/// For internal use in RooFit.
183RooSimultaneous::RooSimultaneous(const char *name, const char *title,
185 RooAbsCategoryLValue &inIndexCat)
186 : RooSimultaneous(name, title, RooFit::Detail::flatMapToStdMap(pdfMap), inIndexCat)
187{
188}
189
190////////////////////////////////////////////////////////////////////////////////
191/// Copy constructor
192
194 RooAbsPdf(other,name),
195 _plotCoefNormSet("!plotCoefNormSet",this,other._plotCoefNormSet),
196 _plotCoefNormRange(other._plotCoefNormRange),
197 _partIntMgr(other._partIntMgr,this),
198 _indexCat("indexCat",this,other._indexCat),
199 _numPdf(other._numPdf)
200{
201 // Copy proxy list
202 for(auto* proxy : static_range_cast<RooRealProxy*>(other._pdfProxyList)) {
203 _pdfProxyList.Add(new RooRealProxy(proxy->GetName(),this,*proxy)) ;
204 }
205}
206
207
208
209////////////////////////////////////////////////////////////////////////////////
210/// Destructor
211
216
217
218
219////////////////////////////////////////////////////////////////////////////////
220/// Return the p.d.f associated with the given index category name
221
223{
224 RooRealProxy* proxy = static_cast<RooRealProxy*>(_pdfProxyList.FindObject(catName.c_str()));
225 return proxy ? static_cast<RooAbsPdf*>(proxy->absArg()) : nullptr;
226}
227
228
229
230////////////////////////////////////////////////////////////////////////////////
231/// Associate given PDF with index category state label 'catLabel'.
232/// The name state must be already defined in the index category.
233///
234/// RooSimultaneous can function without having a PDF associated
235/// with every single state. The normalization in such cases is taken
236/// from the number of registered PDFs, but getVal() will fail if
237/// called for an unregistered index state.
238///
239/// PDFs may not overlap (i.e. share any variables) with the index category (function).
240/// \param[in] pdf PDF to be added.
241/// \param[in] catLabel Name of the category state to be associated to the PDF.
242/// \return `true` in case of failure.
243
244bool RooSimultaneous::addPdf(const RooAbsPdf& pdf, const char* catLabel)
245{
246 // PDFs cannot overlap with the index category
247 if (pdf.dependsOn(_indexCat.arg())) {
248 coutE(InputArguments) << "RooSimultaneous::addPdf(" << GetName() << "): PDF '" << pdf.GetName()
249 << "' overlaps with index category '" << _indexCat.arg().GetName() << "'."<< std::endl ;
250 return true ;
251 }
252
253 // Each index state can only have one PDF associated with it
254 if (_pdfProxyList.FindObject(catLabel)) {
255 coutE(InputArguments) << "RooSimultaneous::addPdf(" << GetName() << "): index state '"
256 << catLabel << "' has already an associated PDF." << std::endl ;
257 return true ;
258 }
259
260 // Create a proxy named after the associated index state
261 TObject* proxy = new RooRealProxy(catLabel,catLabel,this,const_cast<RooAbsPdf&>(pdf));
262 _pdfProxyList.Add(proxy) ;
263 _numPdf += 1 ;
264
265 return false ;
266}
267
268////////////////////////////////////////////////////////////////////////////////
269/// Examine the pdf components and check if one of them can be extended or must be extended.
270/// It is enough to have one component that can be extended or must be extended to return the flag in
271/// the total simultaneous pdf.
272
274{
275 bool anyCanExtend = false;
276
277 for (auto *proxy : static_range_cast<RooRealProxy *>(_pdfProxyList)) {
278 auto &pdf = static_cast<RooAbsPdf const&>(proxy->arg());
279 if (pdf.mustBeExtended())
280 return MustBeExtended;
281 anyCanExtend |= pdf.canBeExtended();
282 }
283 return anyCanExtend ? CanBeExtended : CanNotBeExtended;
284}
285
286////////////////////////////////////////////////////////////////////////////////
287/// Return the current value:
288/// the value of the PDF associated with the current index category state
289
291{
292 // Retrieve the proxy by index name
294 if(!proxy) {
295 return 0;
296 }
297
298 double nEvtTot = 1.0;
299 double nEvtCat = 1.0;
300
301 // Relative yield weight only if normalized over the index states. In
302 // "switch mode", the value is the one of the selected component.
304
305 nEvtTot = 0;
306 nEvtCat = 0;
307
308 for (auto *proxy2 : static_range_cast<RooRealProxy *>(_pdfProxyList)) {
309 auto &pdf2 = static_cast<RooAbsPdf const &>(proxy2->arg());
310 if(!pdf2.canBeExtended()) {
311 // If one of the pdfs can't be expected, reset the normalization
312 // factor to one and break out of the loop.
313 nEvtTot = 1.0;
314 nEvtCat = 1.0;
315 break;
316 }
317 const double nEvt = pdf2.expectedEvents(_normSet);
318 nEvtTot += nEvt;
319 if (proxy == proxy2) {
320 // Matching by proxy by pointer rather than pdfs, because it's
321 // possible to have the same pdf used in different states.
322 nEvtCat += nEvt;
323 }
324 }
325 }
326 double catFrac = nEvtCat / nEvtTot;
327
328 // Return the selected PDF value, normalized by the relative number of
329 // expected events if applicable.
330 return *proxy * catFrac;
331}
332
333////////////////////////////////////////////////////////////////////////////////
334/// Return the number of expected events: If the index is in nset,
335/// then return the sum of the expected events of all components,
336/// otherwise return the number of expected events of the PDF
337/// associated with the current index category state
338
340{
341 if (indexCatIsInNormSet(nset)) {
342
343 double sum(0) ;
344
345 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdfProxyList)) {
346 sum += (static_cast<RooAbsPdf*>(proxy->absArg()))->expectedEvents(nset) ;
347 }
348
349 return sum ;
350
351 } else {
352
353 // Retrieve the proxy by index name
355
356 //assert(proxy!=0) ;
357 if (proxy==nullptr) return 0 ;
358
359 // Return the selected PDF value, normalized by the number of index states
360 return (static_cast<RooAbsPdf*>(proxy->absArg()))->expectedEvents(nset);
361 }
362}
363
364
365
366////////////////////////////////////////////////////////////////////////////////
367/// Expected events function for the new evaluation backends: the sum over all
368/// components, or the selected component in "switch mode" (see expectedEvents()).
369
370std::unique_ptr<RooAbsReal> RooSimultaneous::createExpectedEventsFunc(const RooArgSet *nset) const
371{
372 const std::string name = std::string(GetName()) + "_expectedEvents";
373
374 // One function per distinct component, because the same pdf can be used in
375 // several states. Components that can't be extended contribute zero, like
376 // in expectedEvents().
377 RooArgList formulaArgs;
378 RooArgSet ownedFuncs;
379 std::map<RooAbsPdf const *, std::string> funcRefs;
380 bool failed = false;
381 auto ref = [&](RooAbsPdf const &pdf) -> std::string {
382 if (!pdf.canBeExtended()) {
383 return "0.0";
384 }
385 auto found = funcRefs.find(&pdf);
386 if (found != funcRefs.end()) {
387 return found->second;
388 }
389 std::unique_ptr<RooAbsReal> func = pdf.createExpectedEventsFunc(nset);
390 if (!func) {
391 failed = true;
392 return "0.0";
393 }
394 // Different components can have the same name
395 func->SetName((std::string(func->GetName()) + "_" + std::to_string(funcRefs.size())).c_str());
396 std::string const funcRef = "x[" + std::to_string(formulaArgs.size()) + "]";
397 formulaArgs.add(*func);
398 ownedFuncs.addOwned(std::move(func));
399 return funcRefs[&pdf] = funcRef;
400 };
401
402 std::string formula;
403 if (indexCatIsInNormSet(nset)) {
404 for (auto *proxy : static_range_cast<RooRealProxy *>(_pdfProxyList)) {
405 formula += (formula.empty() ? "" : " + ") + ref(static_cast<RooAbsPdf const &>(proxy->arg()));
406 }
407 if (formula.empty()) {
408 formula = "0.0";
409 }
410 } else {
411 // Nested ternary expression that selects the component matching the
412 // index state, keyed on the state index numbers.
413 formulaArgs.add(_indexCat.arg());
414 std::size_t numStates = 0;
415 for (auto const &nameIdx : _indexCat.arg()) {
416 auto *proxy = static_cast<RooRealProxy *>(_pdfProxyList.FindObject(nameIdx.first.c_str()));
417 if (!proxy) {
418 continue;
419 }
420 formula += "x[0] == " + std::to_string(nameIdx.second) + " ? " +
421 ref(static_cast<RooAbsPdf const &>(proxy->arg())) + " : (";
422 ++numStates;
423 }
424 formula += "0.0" + std::string(numStates, ')');
425 }
426
427 // Like the default implementation, return nullptr if a component can't
428 // create the function.
429 if (failed) {
430 return nullptr;
431 }
432
433 auto out = std::make_unique<RooFormulaVar>(name.c_str(), name.c_str(), formula.c_str(), formulaArgs);
434 out->addOwnedComponents(std::move(ownedFuncs));
435 return out;
436}
437
438////////////////////////////////////////////////////////////////////////////////
439/// Forward determination of analytical integration capabilities to component p.d.f.s
440/// A unique code is assigned to the combined integration capabilities of all associated
441/// p.d.f.s
442
444 const RooArgSet* normSet, const char* rangeName) const
445{
446 // Declare that we can analytically integrate all requested observables
447 analVars.add(allVars) ;
448
449 // Retrieve (or create) the required partial integral list
450 Int_t code ;
451
452 // Check if this configuration was created before
453 CacheElem* cache = static_cast<CacheElem*>(_partIntMgr.getObj(normSet,&analVars,nullptr,RooNameReg::ptr(rangeName))) ;
454 if (cache) {
455 code = _partIntMgr.lastIndex() ;
456 return code+1 ;
457 }
458 cache = new CacheElem ;
459
460 // Create the partial integral set for this request
461 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdfProxyList)) {
462 cache->_partIntList.addOwned(std::unique_ptr<RooAbsReal>{proxy->arg().createIntegral(analVars,normSet,nullptr,rangeName)});
463 }
464
465 // Store the partial integral list and return the assigned code ;
466 code = _partIntMgr.setObj(normSet,&analVars,cache,RooNameReg::ptr(rangeName)) ;
467
468 return code+1 ;
469}
470
471
472
473////////////////////////////////////////////////////////////////////////////////
474/// Return analytical integration defined by given code
475
476double RooSimultaneous::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* /*rangeName*/) const
477{
478 // No integration scenario
479 if (code==0) {
480 return getVal(normSet) ;
481 }
482
483 // Partial integration scenarios, rangeName already encoded in 'code'
484 CacheElem* cache = static_cast<CacheElem*>(_partIntMgr.getObjByIndex(code-1)) ;
485
487 Int_t idx = _pdfProxyList.IndexOf(proxy) ;
488 return (static_cast<RooAbsReal*>(cache->_partIntList.at(idx)))->getVal(normSet) ;
489}
490
491
492
493
494
495
496////////////////////////////////////////////////////////////////////////////////
497/// Back-end for plotOn() implementation on RooSimultaneous which
498/// needs special handling because a RooSimultaneous PDF cannot
499/// project out its index category via integration. plotOn() will
500/// abort if this is requested without providing a projection dataset.
501
503{
504 // Sanity checks
505 if (plotSanityChecks(frame)) return frame ;
506
507 // Special case: if an asymmetry is requested with respect to our index
508 // category, we cannot reroute the plotting to the component pdfs. The
509 // component pdfs don't depend on the index category, so the asymmetry engine
510 // in the base class would not be able to split them by index state. Instead,
511 // we delegate directly to the base class implementation, which constructs the
512 // asymmetry from the two index-state component pdfs (see the overridden
513 // createAsymmetryComponent() and GitHub issue #14255).
514 if (auto *asymCmd = static_cast<RooCmdArg *>(cmdList.FindObject("Asymmetry"))) {
515 auto *asymCat = dynamic_cast<RooAbsCategory const *>(asymCmd->getObject(0));
516 if (asymCat && asymCat == &_indexCat.arg()) {
517
518 RooLinkedList cmdList2(cmdList);
519
520 // The base-class asymmetry-plotting engine averages the projection over
521 // the projection dataset. This is not supported for the composite data
522 // stores that back datasets with a category index, so we flatten such a
523 // projection dataset into a plain (vector-backed) copy first. Both the
524 // copy and the replacement command must outlive the plotOn() call below,
525 // because the command list only stores pointers to them.
526 std::unique_ptr<RooAbsData> flatProjData;
527 RooCmdArg newProjWData;
528 if (auto *projWData = static_cast<RooCmdArg *>(cmdList2.FindObject("ProjData"))) {
529 auto *projData = dynamic_cast<RooDataSet const *>(projWData->getObject(1));
530 if (projData && dynamic_cast<RooCompositeDataStore const *>(projData->store())) {
531 flatProjData = std::make_unique<RooDataSet>(projData->GetName(), projData->GetTitle(), *projData->get(),
532 RooFit::Import(*const_cast<RooDataSet *>(projData)));
533 const RooArgSet *projDataSet = projWData->getSet(0);
534 newProjWData = projDataSet ? RooFit::ProjWData(*projDataSet, *flatProjData)
535 : RooFit::ProjWData(*flatProjData);
536 replaceOrAdd(cmdList2, newProjWData);
537 }
538 }
539
540 return RooAbsReal::plotOn(frame, cmdList2);
541 }
542 }
543
544 // In switch mode, i.e., if the index category is neither in the projection
545 // data nor an observable of the frame, plot the selected component. This is
546 // the case for a nested RooSimultaneous when plotting a slice of the outer one.
547 if (auto *projWData = static_cast<RooCmdArg *>(cmdList.FindObject("ProjData"))) {
548 auto *projData = static_cast<RooAbsData const *>(projWData->getObject(1));
549 const RooArgSet *normVars = frame->getNormVars();
550 if (projData && !indexCatIsObservable(*projData->get()) && !(normVars && indexCatIsObservable(*normVars))) {
551 if (RooAbsPdf *pdf = getPdf(_indexCat.label())) {
552 return pdf->plotOn(frame, cmdList);
553 }
554 }
555 }
556
557 // Extract projection configuration from command list
558 RooCmdConfig pc("RooSimultaneous::plotOn(" + std::string(GetName()) + ")");
559 pc.defineString("sliceCatState","SliceCat",0,"",true) ;
560 pc.defineDouble("scaleFactor","Normalization",0,1.0) ;
561 pc.defineInt("scaleType","Normalization",0,RooAbsPdf::Relative) ;
562 pc.defineObject("sliceCatList","SliceCat",0,nullptr,true) ;
563 // This dummy is needed for plotOn to recognize the "SliceCatMany" command.
564 // It is not used directly, but the "SliceCat" commands are nested in it.
565 // Removing this dummy definition results in "ERROR: unrecognized command: SliceCatMany".
566 pc.defineObject("dummy1","SliceCatMany",0) ;
567 pc.defineSet("projSet","Project",0) ;
568 pc.defineSet("sliceSet","SliceVars",0) ;
569 pc.defineSet("projDataSet","ProjData",0) ;
570 pc.defineObject("projData","ProjData",1) ;
571 pc.defineMutex("Project","SliceVars") ;
572 pc.allowUndefined() ; // there may be commands we don't handle here
573
574 // Process and check varargs
575 pc.process(cmdList) ;
576 if (!pc.ok(true)) {
577 return frame ;
578 }
579
580 RooAbsData* projData = static_cast<RooAbsData*>(pc.getObject("projData")) ;
581 const RooArgSet* projDataSet = pc.getSet("projDataSet");
582 const RooArgSet* sliceSetTmp = pc.getSet("sliceSet") ;
583 std::unique_ptr<RooArgSet> sliceSet( sliceSetTmp ? (static_cast<RooArgSet*>(sliceSetTmp->Clone())) : nullptr );
584 const RooArgSet* projSet = pc.getSet("projSet") ;
585 double scaleFactor = pc.getDouble("scaleFactor") ;
586 ScaleType stype = (ScaleType) pc.getInt("scaleType") ;
587
588
589 // Look for category slice arguments and add them to the master slice list if found
590 const char* sliceCatState = pc.getString("sliceCatState",nullptr,true) ;
591 const RooLinkedList& sliceCatList = pc.getObjectList("sliceCatList") ;
592 if (sliceCatState) {
593
594 // Make the master slice set if it doesnt exist
595 if (!sliceSet) {
596 sliceSet = std::make_unique<RooArgSet>();
597 }
598
599 // Prepare comma separated label list for parsing
600 auto catTokens = ROOT::Split(sliceCatState, ",");
601
602 // Loop over all categories provided by (multiple) Slice() arguments
603 unsigned int tokenIndex = 0;
604 for(auto * scat : static_range_cast<RooCategory*>(sliceCatList)) {
605 const char* slabel = tokenIndex >= catTokens.size() ? nullptr : catTokens[tokenIndex++].c_str();
606
607 if (slabel) {
608 // Set the slice position to the value indicated by slabel
609 scat->setLabel(slabel) ;
610 // Add the slice category to the master slice set
611 sliceSet->add(*scat,false) ;
612 }
613 }
614 }
615
616 // Check if we have a projection dataset
617 if (!projData) {
618 coutE(InputArguments) << "RooSimultaneous::plotOn(" << GetName() << ") ERROR: must have a projection dataset for index category" << std::endl ;
619 return frame ;
620 }
621
622 // Make list of variables to be projected
623 RooArgSet projectedVars ;
624 if (sliceSet) {
625 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
626
627 // Take out the sliced variables
628 for (const auto sliceArg : *sliceSet) {
629 RooAbsArg* arg = projectedVars.find(sliceArg->GetName()) ;
630 if (arg) {
631 projectedVars.remove(*arg) ;
632 } else {
633 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") slice variable "
634 << sliceArg->GetName() << " was not projected anyway" << std::endl ;
635 }
636 }
637 } else if (projSet) {
638 makeProjectionSet(frame->getPlotVar(),projSet,projectedVars,false) ;
639 } else {
640 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
641 }
642
643 bool projIndex(false) ;
644
645 if (!_indexCat.arg().isDerived()) {
646 // *** Error checking for a fundamental index category ***
647 //cout << "RooSim::plotOn: index is fundamental" << std::endl ;
648
649 // Check that the provided projection dataset contains our index variable
650 if (!projData->get()->find(_indexCat.arg().GetName())) {
651 coutE(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") ERROR: Projection over index category "
652 << "requested, but projection data set doesn't contain index category" << std::endl ;
653 return frame ;
654 }
655
656 if (projectedVars.find(_indexCat.arg().GetName())) {
657 projIndex=true ;
658 }
659
660 } else {
661 // *** Error checking for a composite index category ***
662
663 // Determine if any servers of the index category are in the projectedVars
664 RooArgSet projIdxServers ;
665 bool anyServers(false) ;
666 for (const auto server : flattenedCatList()) {
667 if (projectedVars.find(server->GetName())) {
668 anyServers=true ;
669 projIdxServers.add(*server) ;
670 }
671 }
672
673 // Check that the projection dataset contains all the
674 // index category components we're projecting over
675
676 // Determine if all projected servers of the index category are in the projection dataset
677 bool allServers(true) ;
678 std::string missing;
679 for (const auto server : projIdxServers) {
680 if (!projData->get()->find(server->GetName())) {
681 allServers=false ;
682 missing = server->GetName();
683 }
684 }
685
686 if (!allServers) {
687 coutE(Plotting) << "RooSimultaneous::plotOn(" << GetName()
688 << ") ERROR: Projection dataset doesn't contain complete set of index categories to do projection."
689 << "\n\tcategory " << missing << " is missing." << std::endl ;
690 return frame ;
691 }
692
693 if (anyServers) {
694 projIndex = true ;
695 }
696 }
697
698 // Calculate relative weight fractions of components
699 std::unique_ptr<Roo1DTable> wTable( projData->table(_indexCat.arg()) );
700
701 // Clone the index category to be able to cycle through the category states for plotting without
702 // affecting the category state of our instance
703 RooArgSet idxCloneSet;
704 RooArgSet(*_indexCat).snapshot(idxCloneSet, true);
705 auto idxCatClone = static_cast<RooAbsCategoryLValue*>(idxCloneSet.find(_indexCat->GetName()) );
706 assert(idxCatClone);
707
708 // Make list of category columns to exclude from projection data
709 std::unique_ptr<RooArgSet> idxCompSliceSet( idxCatClone->getObservables(frame->getNormVars()) );
710
711 // If we don't project over the index, just do the regular plotOn
712 if (!projIndex) {
713
714 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
715 << " represents a slice in the index category (" << _indexCat.arg().GetName() << ")" << std::endl ;
716
717 // Reduce projData: take out fitCat (component) columns and entries that don't match selected slice
718 // Construct cut string to only select projection data event that match the current slice
719
720 // Make cut string to exclude rows from projection data
721 if (sliceSet) {
722 for (auto *idxComp : static_range_cast<RooCategory *>(*idxCompSliceSet)) {
723 if (auto* slicedComponent = static_cast<const RooAbsCategory*>(sliceSet->find(*idxComp))) {
724 idxComp->setIndex(slicedComponent->getCurrentIndex(), false);
725 }
726 }
727 }
728 std::string cutString = RooFit::Detail::makeSliceCutString(*idxCompSliceSet);
729
730 // Make temporary projData without RooSim index category components
731 RooArgSet projDataVars(*projData->get()) ;
732 projDataVars.remove(*idxCompSliceSet,true,true) ;
733
734 std::unique_ptr<RooAbsData>
735 projDataTmp(projData->reduce(RooFit::SelectVars(projDataVars), RooFit::Cut(cutString.c_str())));
736
737 // Override normalization and projection dataset
738 RooCmdArg tmp1 =
739 RooFit::Normalization(scaleFactor * wTable->get(idxCatClone->getCurrentLabel()), RooAbsReal::NumEvent);
740 RooCmdArg tmp2 = RooFit::ProjWData(*projDataSet,*projDataTmp) ;
741
742 // WVE -- do not adjust normalization for asymmetry plots
743 RooLinkedList cmdList2(cmdList) ;
744 if (!cmdList.find("Asymmetry")) {
745 replaceOrAdd(cmdList2, tmp1);
746 }
747 replaceOrAdd(cmdList2, tmp2);
748
749 // Plot single component
750 RooPlot* retFrame = getPdf(idxCatClone->getCurrentLabel())->plotOn(frame,cmdList2);
751 return retFrame ;
752 }
753
754 // If we project over the index, plot using a temporary RooAddPdf
755 // using the weights from the data as coefficients
756
757 // Build the list of indexCat components that are sliced
758 idxCompSliceSet->remove(projectedVars,true,true) ;
759
760 // Make a new expression that is the weighted sum of requested components
761 RooArgList pdfCompList ;
762 RooArgList wgtCompList ;
763//RooAbsPdf* pdf ;
764 double sumWeight(0) ;
765 for(auto * proxy : static_range_cast<RooRealProxy*>(_pdfProxyList)) {
766
767 idxCatClone->setLabel(proxy->name()) ;
768
769 // Determine if this component is the current slice (if we slice)
770 bool skip(false) ;
771 for (const auto idxSliceCompArg : *idxCompSliceSet) {
772 const auto idxSliceComp = static_cast<RooAbsCategory*>(idxSliceCompArg);
773 RooAbsCategory* idxComp = static_cast<RooAbsCategory*>(idxCloneSet.find(idxSliceComp->GetName())) ;
774 if (idxComp->getCurrentIndex()!=idxSliceComp->getCurrentIndex()) {
775 skip=true ;
776 break ;
777 }
778 }
779 if (skip) continue ;
780
781 // Instantiate a RRV holding this pdfs weight
782 wgtCompList.addOwned(std::make_unique<RooRealVar>(proxy->name(),"coef",wTable->get(proxy->name())));
783 sumWeight += wTable->getFrac(proxy->name()) ;
784
785 // Add the PDF to list list
786 pdfCompList.add(proxy->arg()) ;
787 }
788
789 TString plotVarName(GetName()) ;
790 RooAddPdf plotVar{plotVarName,"weighted sum of RS components",pdfCompList,wgtCompList};
791
792 // Fix appropriate coefficient normalization in plot function
793 if (!_plotCoefNormSet.empty()) {
794 plotVar.fixAddCoefNormalization(_plotCoefNormSet) ;
795 }
796
797 std::unique_ptr<RooAbsData> projDataTmp;
798 RooArgSet projSetTmp ;
799 if (projData) {
800
801 // Construct cut string to only select projection data event that match the current slice
802 std::string cutString = RooFit::Detail::makeSliceCutString(*idxCompSliceSet);
803
804 // Make temporary projData without RooSim index category components
805 RooArgSet projDataVars(*projData->get()) ;
806 RooArgSet idxCatServers;
807 _indexCat.arg().getObservables(frame->getNormVars(), idxCatServers) ;
808
809 projDataVars.remove(idxCatServers,true,true) ;
810
811 projDataTmp = std::unique_ptr<RooAbsData>{projData->reduce(RooFit::SelectVars(projDataVars), RooFit::Cut(cutString.c_str()))};
812
813
814
815 if (projSet) {
816 projSetTmp.add(*projSet) ;
817 projSetTmp.remove(idxCatServers,true,true);
818 }
819 }
820
821
822 if (_indexCat.arg().isDerived() && !idxCompSliceSet->empty()) {
823 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
824 << " represents a slice in index category components " << *idxCompSliceSet << std::endl ;
825
826 RooArgSet idxCompProjSet;
827 _indexCat.arg().getObservables(frame->getNormVars(), idxCompProjSet) ;
828 idxCompProjSet.remove(*idxCompSliceSet,true,true) ;
829 if (!idxCompProjSet.empty()) {
830 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
831 << " averages with data index category components " << idxCompProjSet << std::endl ;
832 }
833 } else {
834 coutI(Plotting) << "RooSimultaneous::plotOn(" << GetName() << ") plot on " << frame->getPlotVar()->GetName()
835 << " averages with data index category (" << _indexCat.arg().GetName() << ")" << std::endl ;
836 }
837
838
839 // Override normalization and projection dataset
840 RooLinkedList cmdList2(cmdList) ;
841
842 RooCmdArg tmp1 = RooFit::Normalization(scaleFactor*sumWeight,stype) ;
843 RooCmdArg tmp2 = RooFit::ProjWData(*projDataSet,*projDataTmp) ;
844 // WVE -- do not adjust normalization for asymmetry plots
845 if (!cmdList.find("Asymmetry")) {
846 replaceOrAdd(cmdList2, tmp1);
847 }
848 replaceOrAdd(cmdList2, tmp2);
849
850 RooPlot* frame2 ;
851 if (!projSetTmp.empty()) {
852 // Plot temporary function
853 RooCmdArg tmp3 = RooFit::Project(projSetTmp) ;
854 replaceOrAdd(cmdList2, tmp3);
855 frame2 = plotVar.plotOn(frame,cmdList2) ;
856 } else {
857 // Plot temporary function
858 frame2 = plotVar.plotOn(frame,cmdList2) ;
859 }
860
861 return frame2 ;
862}
863
864
865////////////////////////////////////////////////////////////////////////////////
866/// Build the component function of an asymmetry plot (see
867/// RooAbsReal::plotAsymOn()) for a fixed state of the asymmetry category.
868///
869/// When the asymmetry is requested in our own index category, the component for
870/// a given index state is simply the corresponding pdf. We return a clone of
871/// that pdf directly instead of a RooSimultaneous with a pinned index, because
872/// a RooSimultaneous compiles its per-category observables with a category
873/// prefix. That prefix makes it incompatible with the vectorized evaluation
874/// backend that averages the asymmetry over the projection data, and would
875/// otherwise silently yield a flat (zero) asymmetry (see issue #14255). For any
876/// other asymmetry category we fall back to the generic implementation.
877
878std::unique_ptr<RooAbsReal>
880{
881 if (&asymCat == &_indexCat.arg()) {
882 const std::string &label = _indexCat.arg().lookupName(asymCatState.getCurrentIndex());
883 if (RooAbsPdf *pdf = getPdf(label)) {
884 return RooHelpers::cloneTreeWithSameParameters(static_cast<RooAbsReal const &>(*pdf));
885 }
886 }
887 return RooAbsReal::createAsymmetryComponent(asymCat, asymCatState);
888}
889
890
891////////////////////////////////////////////////////////////////////////////////
892/// Interface function used by test statistics to freeze choice of observables
893/// for interpretation of fraction coefficients. Needed here because a RooSimultaneous
894/// works like a RooAddPdf when plotted
895
896void RooSimultaneous::selectNormalization(const RooArgSet* normSet, bool /*force*/)
897{
899 if (normSet) {
900 // The index category must not be stored in the set: it is meaningless for
901 // the coefficient normalization, since it is never an observable of the
902 // component pdfs (RooAddPdf::selectNormalization() would filter it out
903 // again anyway). Worse, it is already registered as a value server via
904 // the index category proxy, and registering the same server a second
905 // time through this non-propagating set proxy corrupts the reference
906 // counts of the server's client lists when the set is cleared again.
907 RooArgSet filteredNormSet{*normSet};
908 filteredNormSet.remove(_indexCat.arg(), true, true);
909 _plotCoefNormSet.add(filteredNormSet);
910 }
911}
912
913
914////////////////////////////////////////////////////////////////////////////////
915/// Interface function used by test statistics to freeze choice of range
916/// for interpretation of fraction coefficients. Needed here because a RooSimultaneous
917/// works like a RooAddPdf when plotted
918
919void RooSimultaneous::selectNormalizationRange(const char *rangeName, bool /*force*/)
920{
922}
923
924
925
926
927////////////////////////////////////////////////////////////////////////////////
928
930 const RooArgSet* auxProto, bool verbose, bool autoBinned, const char* binnedTag) const
931{
932 const char* idxCatName = _indexCat.arg().GetName() ;
933
934 if (vars.find(idxCatName) && prototype==nullptr
935 && (auxProto==nullptr || auxProto->empty())
936 && (autoBinned || (binnedTag && strlen(binnedTag)))) {
937
938 // Return special generator config that can also do binned generation for selected states
939 return new RooSimSplitGenContext(*this,vars,verbose,autoBinned,binnedTag) ;
940
941 } else {
942
943 // Return regular generator config ;
944 return genContext(vars,prototype,auxProto,verbose) ;
945 }
946}
947
948
949
950////////////////////////////////////////////////////////////////////////////////
951/// Return specialized generator context for simultaneous p.d.f.s
952
954 const RooArgSet* auxProto, bool verbose) const
955{
956 RooArgSet allVars{vars};
957 if(prototype) allVars.add(*prototype->get());
958
959 RooArgSet catsAmongAllVars;
960 allVars.selectCommon(flattenedCatList(), catsAmongAllVars);
961
962 // Not generating index cat: we better error out because it's not clear what
963 // the user expects here. Does the user want to generate according to the
964 // currently-selected pdf? Or does the user want to generate global
965 // observable values according to the union of all category pdfs?
966 // Print an error and tell the user what to do to explicitly.
967 if(catsAmongAllVars.empty()) {
968 coutE(InputArguments) << "RooSimultaneous::generateSimGlobal(" << GetName()
969 << ") asking to generate without the index category!\n"
970 << "It's not clear what to do. you probably want to either:\n"
971 << "\n"
972 << " 1. Generate according to the currently-selected pdf.\n"
973 << " Please do this explicitly with:\n"
974 << " simpdf->getPdf(simpdf->indexCat().getCurrentLabel())->generate(vars, ...)\n"
975 << "\n"
976 << " 1. Generate global observable values according to the union of all component pdfs.\n"
977 << " For this, please use simpdf->generateSimGlobal(vars, ...)\n"
978 << std::endl;
979 return nullptr;
980 }
981
982 RooArgSet catsAmongProtoVars;
983 if(prototype) {
984 prototype->get()->selectCommon(flattenedCatList(), catsAmongProtoVars);
985
986 if(!catsAmongProtoVars.empty() && catsAmongProtoVars.size() != flattenedCatList().size()) {
987 // Abort if we have only part of the servers
988 coutE(Plotting) << "RooSimultaneous::genContext: ERROR: prototype must include either all "
989 << " components of the RooSimultaneous index category or none " << std::endl;
990 return nullptr;
991 }
992 }
993
994 return new RooSimGenContext(*this,vars,prototype,auxProto,verbose) ;
995}
996
997
998
999
1000////////////////////////////////////////////////////////////////////////////////
1001
1003 const RooArgSet* nset,
1004 double scaleFactor,
1005 bool correctForBinVolume,
1006 bool showProgress) const
1007{
1008 if (RooAbsReal::fillDataHist (hist, nset, scaleFactor,
1009 correctForBinVolume, showProgress) == nullptr)
1010 return nullptr;
1011
1012 const double sum = hist->sumEntries();
1013 if (sum != 0) {
1014 for (int i=0 ; i<hist->numEntries() ; i++) {
1015 hist->set(i, hist->weight(i) / sum, 0.);
1016 }
1017 }
1018
1019 return hist;
1020}
1021
1022
1023
1024
1025////////////////////////////////////////////////////////////////////////////////
1026/// Special generator interface for generation of 'global observables' -- for RooStats tools.
1027///
1028/// \note Why one can't just use RooAbsPdf::generate()? That's because when
1029/// using the regular generate() method, a specific component pdf is selected
1030/// for each generated entry according to the index category value. However,
1031/// global observable values are independent of the current index category,
1032/// which can best be illustrated with the case where a global observable
1033/// corresponds to a nuisance parameter that is relevant for multiple channels.
1034/// So the interpretation of what is an entry in the generated dataset is very
1035/// different, hence the separate function.
1036
1038{
1039 // Generating the index category together with the global observables doesn't make any sense.
1040 RooArgSet catsAmongAllVars;
1041 whatVars.selectCommon(flattenedCatList(), catsAmongAllVars);
1042 if(!catsAmongAllVars.empty()) {
1043 coutE(InputArguments) << "RooSimultaneous::generateSimGlobal(" << GetName()
1044 << ") asking to generate global obserables at the same time as the index category!\n"
1045 << "This doesn't make any sense: global observables are generally not related to a specific channel.\n"
1046 << std::endl;
1047 return nullptr;
1048 }
1049
1050 // Make set with clone of variables (placeholder for output)
1051 RooArgSet globClone;
1052 whatVars.snapshot(globClone);
1053
1054 auto data = std::make_unique<RooDataSet>("gensimglobal","gensimglobal",whatVars);
1055
1056 for (Int_t i=0 ; i<nEvents ; i++) {
1057 for (const auto& nameIdx : indexCat()) {
1058
1059 // Get pdf associated with state from simpdf
1060 RooAbsPdf* pdftmp = getPdf(nameIdx.first);
1061
1062 RooArgSet globtmp;
1063 pdftmp->getObservables(&whatVars, globtmp) ;
1064
1065 // If there are any, generate only global variables defined by the pdf
1066 // associated with this state and transfer values to output placeholder.
1067 if (!globtmp.empty()) {
1068 globClone.assign(*std::unique_ptr<RooDataSet>{pdftmp->generate(globtmp,1)}->get(0)) ;
1069 }
1070 }
1071 data->add(globClone) ;
1072 }
1073
1074 return RooFit::makeOwningPtr(std::move(data));
1075}
1076
1077
1078/// Wraps the components of this RooSimultaneous in RooBinSamplingPdfs.
1079/// \param[in] data The dataset to be used in the eventual fit, used to figure
1080/// out the observables and whether the dataset is binned.
1081/// \param[in] precision Precision argument for all created RooBinSamplingPdfs.
1083
1084 if (precision < 0.) return;
1085
1086 RooArgSet newSamplingPdfs;
1087
1088 for (auto const &item : this->indexCat()) {
1089
1090 auto const &catName = item.first;
1091 auto &pdf = *this->getPdf(catName);
1092
1093 if (auto newSamplingPdf = RooBinSamplingPdf::create(pdf, data, precision)) {
1094 // Set the "ORIGNAME" attribute the indicate to
1095 // RooAbsArg::redirectServers() which pdf should be replaced by this
1096 // RooBinSamplingPdf in the RooSimultaneous.
1097 newSamplingPdf->setAttribute(
1098 (std::string("ORIGNAME:") + pdf.GetName()).c_str());
1099 newSamplingPdfs.addOwned(std::move(newSamplingPdf));
1100 }
1101 }
1102
1103 this->redirectServers(newSamplingPdfs, false, true);
1104 this->addOwnedComponents(std::move(newSamplingPdfs));
1105}
1106
1107
1108/// Wraps the components of this RooSimultaneous in RooBinSamplingPdfs, with a
1109/// different precision parameter for each component.
1110/// \param[in] data The dataset to be used in the eventual fit, used to figure
1111/// out the observables and whether the dataset is binned.
1112/// \param[in] precisions The map that gives the precision argument for each
1113/// component in the RooSimultaneous. The keys are the pdf names. If
1114/// there is no value for a given component, it will not use the bin
1115/// integration. Otherwise, the value has the same meaning than in
1116/// the IntegrateBins() command argument for RooAbsPdf::fitTo().
1117/// \param[in] useCategoryNames If this flag is set, the category names will be
1118/// used to look up the precision in the precisions map instead of
1119/// the pdf names.
1121 std::map<std::string, double> const& precisions,
1122 bool useCategoryNames /*=false*/) {
1123
1124 constexpr double defaultPrecision = -1.;
1125
1126 RooArgSet newSamplingPdfs;
1127
1128 for (auto const &item : this->indexCat()) {
1129
1130 auto const &catName = item.first;
1131 auto &pdf = *this->getPdf(catName);
1132 std::string pdfName = pdf.GetName();
1133
1134 auto found = precisions.find(useCategoryNames ? catName : pdfName);
1135 const double precision =
1136 found != precisions.end() ? found->second : defaultPrecision;
1137 if (precision < 0.)
1138 continue;
1139
1140 if (auto newSamplingPdf = RooBinSamplingPdf::create(pdf, data, precision)) {
1141 // Set the "ORIGNAME" attribute the indicate to
1142 // RooAbsArg::redirectServers() which pdf should be replaced by this
1143 // RooBinSamplingPdf in the RooSimultaneous.
1144 newSamplingPdf->setAttribute(
1145 (std::string("ORIGNAME:") + pdf.GetName()).c_str());
1146 newSamplingPdfs.addOwned(std::move(newSamplingPdf));
1147 }
1148 }
1149
1150 this->redirectServers(newSamplingPdfs, false, true);
1151 this->addOwnedComponents(std::move(newSamplingPdfs));
1152}
1153
1154/// Internal utility function to get a list of all category components for this
1155/// RooSimultaneous. The output contains only the index category if it is a
1156/// RooCategory, or the list of all category components if it is a
1157/// RooSuperCategory.
1159{
1160 // Note that the index category of a RooSimultaneous can only be of type
1161 // RooCategory or RooSuperCategory, because these are the only classes that
1162 // inherit from RooAbsCategoryLValue.
1163 if (auto superCat = dynamic_cast<RooSuperCategory const*>(&_indexCat.arg())) {
1164 return superCat->inputCatList();
1165 }
1166
1167 if(!_indexCatSet) {
1168 _indexCatSet = std::make_unique<RooArgSet>(_indexCat.arg());
1169 }
1170 return *_indexCatSet;
1171}
1172
1173////////////////////////////////////////////////////////////////////////////////
1174/// For the generator contexts: a component that is a RooSimultaneous whose
1175/// index category is not among the generated variables `vars` is in switch
1176/// mode, so its selected component is generated instead. Returns nullptr if
1177/// the selected state has no pdf.
1179{
1180 while (auto *sim = dynamic_cast<RooSimultaneous *>(pdf)) {
1181 if (sim->indexCatIsObservable(vars)) {
1182 break;
1183 }
1184 pdf = sim->getPdf(sim->indexCat().getCurrentLabel());
1185 }
1186 return pdf;
1187}
1188
1189////////////////////////////////////////////////////////////////////////////////
1190/// Check if the index category is in the normalization set `nset`, matching by
1191/// name. For a RooSuperCategory index, it's enough if all its input categories
1192/// are in `nset`, which is the case for the variables of a dataset.
1194{
1195 if (!nset) {
1196 return false;
1197 }
1198 if (nset->contains(_indexCat.arg())) {
1199 return true;
1200 }
1201 RooArgSet const &cats = flattenedCatList();
1202 return std::all_of(cats.begin(), cats.end(), [&](RooAbsArg const *cat) { return nset->contains(*cat); });
1203}
1204
1205////////////////////////////////////////////////////////////////////////////////
1206/// Check if the index category is among the variables `vars`, matching by
1207/// name. For a RooSuperCategory index, any of its input categories counts.
1208///
1209/// If the index category is not among the observables of a fit, this
1210/// RooSimultaneous does not split the data into channels: it acts as a
1211/// "switch" that evaluates to the component selected by the current index
1212/// state, analogous to RooMultiPdf. Fitting infrastructure uses this check to
1213/// decide between the two modes.
1215{
1216 RooArgSet catsAmongVars;
1217 vars.selectCommon(flattenedCatList(), catsAmongVars);
1218 return !catsAmongVars.empty();
1219}
1220
1221namespace {
1222
1223void markObs(RooAbsArg *arg, std::string const &prefix, RooArgSet const &normSet)
1224{
1225 for (RooAbsArg *server : arg->servers()) {
1226 if (server->isFundamental() && normSet.find(*server)) {
1227 markObs(server, prefix, normSet);
1228 server->setAttribute("__obs__");
1229 } else if (!server->isFundamental()) {
1230 markObs(server, prefix, normSet);
1231 }
1232 }
1233}
1234
1235void prefixArgs(RooAbsArg *arg, std::string const &prefix, RooArgSet const &normSet)
1236{
1237 if (!arg->getStringAttribute("__prefix__")) {
1238 arg->SetName((prefix + arg->GetName()).c_str());
1239 arg->setStringAttribute("__prefix__", prefix.c_str());
1240 }
1241 for (RooAbsArg *server : arg->servers()) {
1242 if (server->isFundamental() && normSet.find(*server)) {
1243 prefixArgs(server, prefix, normSet);
1244 } else if (!server->isFundamental()) {
1245 prefixArgs(server, prefix, normSet);
1246 }
1247 }
1248}
1249
1250} // namespace
1251
1252std::unique_ptr<RooAbsArg>
1254{
1255 if (!indexCatIsObservable(normSet)) {
1256 // The index category is not an observable here: the RooSimultaneous
1257 // acts as a plain "switch" that evaluates to the component selected by
1258 // the current index state, analogous to RooMultiPdf. The channel
1259 // observables are then the same as the ones of this pdf, so the
1260 // channel-splitting compilation below (which renames the per-channel
1261 // observables so they can be filled from split datasets) must not be
1262 // used. Compile like an ordinary self-normalized pdf instead.
1263 return RooAbsPdf::compileForNormSet(normSet, ctx);
1264 }
1265
1266 std::unique_ptr<RooSimultaneous> newSimPdf{static_cast<RooSimultaneous *>(this->Clone())};
1267
1268 const char *rangeName = this->getStringAttribute("RangeName");
1269 bool splitRange = this->getAttribute("SplitRange");
1270
1271 RooArgSet newPdfs;
1272 std::vector<std::string> catNames;
1273
1274 for (auto *proxy : static_range_cast<RooRealProxy *>(newSimPdf->_pdfProxyList)) {
1275 catNames.emplace_back(proxy->GetName());
1276 std::string const &catName = catNames.back();
1277 const std::string prefix = "_" + catName + "_";
1278
1279 const std::string origname = proxy->arg().GetName();
1280
1281 auto pdfClone = RooHelpers::cloneTreeWithSameParameters(static_cast<RooAbsPdf const &>(proxy->arg()), &normSet);
1282
1283 markObs(pdfClone.get(), prefix, normSet);
1284
1285 std::unique_ptr<RooArgSet> pdfNormSet{
1286 std::unique_ptr<RooArgSet>(pdfClone->getVariables())->selectByAttrib("__obs__", true)};
1287 std::unique_ptr<RooArgSet> condVarSet{
1288 std::unique_ptr<RooArgSet>(pdfClone->getVariables())->selectByAttrib("__conditional__", true)};
1289
1290 pdfNormSet->remove(*condVarSet, true, true);
1291
1292 if (rangeName) {
1293 pdfClone->setNormRange(RooHelpers::getRangeNameForSimComponent(rangeName, splitRange, catName).c_str());
1294 }
1295
1296 RooFit::Detail::CompileContext pdfContext{*pdfNormSet};
1297 pdfContext.setLikelihoodMode(ctx.likelihoodMode());
1298 auto *pdfFinal = pdfContext.compile(*pdfClone, *newSimPdf, *pdfNormSet);
1299
1300 // The observables of the compiled computation graph are clones of the
1301 // ones in `pdfNormSet`, and only the clones are prefixed below. That's
1302 // why we have to translate the normalization set to the compiled args
1303 // before using it any further.
1304 RooArgSet compiledPdfNormSet = pdfContext.mapToCompiled(*pdfNormSet);
1305
1306 // We can only prefix the observables after everything related the
1307 // compiling of the compute graph for the normalization set is done. This
1308 // is because of a subtlety in conditional RooProdPdfs, which stores the
1309 // normalization sets for the individual pdfs in RooArgSets that are
1310 // disconnected from the computation graph, so we have no control over
1311 // them. An alternative would be to use recursive server re-direction,
1312 // but this has more performance overhead.
1313 prefixArgs(pdfFinal, prefix, normSet);
1314
1315 // This has to be done with the observables of the compiled graph, which
1316 // are prefixed at this point. Otherwise, the RooAddPdf components don't
1317 // find their coefficient normalization observables and silently keep the
1318 // default "automatic" interpretation of the coefficients, which results
1319 // in wrong yields in ranged fits (GitHub issue #23444).
1320 pdfFinal->fixAddCoefNormalization(compiledPdfNormSet, false);
1321
1322 pdfClone->SetName((std::string("_") + pdfClone->GetName()).c_str());
1323 pdfFinal->addOwnedComponents(std::move(pdfClone));
1324
1325 pdfFinal->setAttribute(("ORIGNAME:" + origname).c_str());
1326 newPdfs.add(*pdfFinal);
1327
1328 // We will remove the old pdf server because we will fill the new ones by
1329 // hand via the creation of new proxies.
1330 newSimPdf->removeServer(const_cast<RooAbsReal &>(proxy->arg()), true);
1331 }
1332
1333 // Replace pdfs with compiled pdfs. Don't use RooAbsArg::redirectServers()
1334 // here, because it doesn't support replacing two servers with the same name
1335 // (it can happen in a RooSimultaneous that two pdfs have the same name).
1336
1337 // First delete old proxies (we have already removed the servers before).
1338 newSimPdf->_pdfProxyList.Delete();
1339
1340 // Recreate the _pdfProxyList with the compiled pdfs
1341 for (std::size_t i = 0; i < newPdfs.size(); ++i) {
1342 const char *label = catNames[i].c_str();
1343 newSimPdf->_pdfProxyList.Add(
1344 new RooRealProxy(label, label, newSimPdf.get(), *static_cast<RooAbsReal *>(newPdfs[i])));
1345 }
1346
1347 ctx.compileServers(*newSimPdf, normSet); // to trigger compiling also the index category
1348
1349 return newSimPdf;
1350}
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define coutI(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
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.
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:89
Abstract base class for objects that represent a discrete value that can be set from the outside,...
A space to attach TBranches.
virtual value_type getCurrentIndex() const
Return index number 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
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...
RooDataHist * fillDataHist(RooDataHist *hist, const RooArgSet *normSet, double scaleFactor, bool correctForBinSize=false, bool showProgress=false) const
Fill a RooDataHist with values sampled from this function at the bin centers.
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.
bool defineSet(const char *name, const char *argName, int setNum, const RooArgSet *defVal=nullptr)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
double getDouble(const char *name, double defVal=0.0) const
Return double property registered with name 'name'.
void defineMutex(const char *head, Args_t &&... tail)
Define arguments where any pair is mutually exclusive.
bool process(const RooCmdArg &arg)
Process given RooCmdArg.
int getInt(const char *name, int defVal=0) const
Return integer property registered with name 'name'.
RooArgSet * getSet(const char *name, RooArgSet *defVal=nullptr) const
Return RooArgSet 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...
bool ok(bool verbose) const
Return true of parsing was successful.
TObject * getObject(const char *name, TObject *defVal=nullptr) const
Return TObject 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'.
const char * getString(const char *name, const char *defVal="", bool convEmptyToNull=false) const
Return string property 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.
bool defineObject(const char *name, const char *argName, int setNum, const TObject *defVal=nullptr, bool isArray=false)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
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 TObject pointers in a vector.
bool Replace(const TObject *oldArg, const TObject *newArg)
Replace object 'oldArg' in collection with new object 'newArg'.
virtual void Add(TObject *arg)
Insert object into collection.
TObject * find(const char *name) const
Return pointer to object with given name in collection.
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.
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.
void selectNormalization(const RooArgSet *normSet=nullptr, bool force=false) override
Interface function used by test statistics to freeze choice of observables for interpretation of frac...
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.
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
void wrapPdfsInBinSamplingPdfs(RooAbsData const &data, double precision)
Wraps the components of this RooSimultaneous in RooBinSamplingPdfs.
static RooAbsPdf * resolveSwitchMode(RooAbsPdf *pdf, RooArgSet const &vars)
For the generator contexts: a component that is a RooSimultaneous whose index category is not among t...
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
Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, 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...
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.
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)
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335