Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsOptTestStatistic.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 RooAbsOptTestStatistic.cxx
19\class RooAbsOptTestStatistic
20\ingroup Roofitcore
21
22RooAbsOptTestStatistic is the abstract base class for test
23statistics objects that evaluate a function or PDF at each point of a given
24dataset. This class provides generic optimizations, such as
25caching and precalculation of constant terms that can be made for
26all such quantities.
27
28Implementations should define evaluatePartition(), which calculates the
29value of a (sub)range of the dataset and optionally combinedValue(),
30which combines the values calculated for each partition. If combinedValue()
31is not overloaded, the default implementation will add the partition results
32to obtain the combined result.
33
34Support for calculation in partitions is needed to allow multi-core
35parallelized calculation of test statistics.
36**/
37
38#include "RooFit.h"
39
40#include "Riostream.h"
41#include "TClass.h"
42#include <string.h>
43
44
46#include "RooMsgService.h"
47#include "RooAbsPdf.h"
48#include "RooAbsData.h"
49#include "RooDataHist.h"
50#include "RooArgSet.h"
51#include "RooRealVar.h"
52#include "RooErrorHandler.h"
53#include "RooGlobalFunc.h"
54#include "RooBinning.h"
55#include "RooAbsDataStore.h"
56#include "RooCategory.h"
57#include "RooDataSet.h"
58#include "RooProdPdf.h"
59#include "RooAddPdf.h"
60#include "RooProduct.h"
61#include "RooRealSumPdf.h"
62#include "RooTrace.h"
63#include "RooVectorDataStore.h"
64#include "RooBinSamplingPdf.h"
65
66using namespace std;
67
69;
70
71
72////////////////////////////////////////////////////////////////////////////////
73/// Default Constructor
74
76{
77 // Initialize all non-persisted data members
78
79 _funcObsSet = 0 ;
80 _funcCloneSet = 0 ;
81 _funcClone = 0 ;
82
83 _normSet = 0 ;
84 _projDeps = 0 ;
85
86 _origFunc = 0 ;
87 _origData = 0 ;
88
89 _ownData = kTRUE ;
90 _sealed = kFALSE ;
92}
93
94
95
96////////////////////////////////////////////////////////////////////////////////
97/// Create a test statistic, and optimise its calculation.
98/// \param[in] name Name of the instance.
99/// \param[in] title Title (for e.g. plotting).
100/// \param[in] real Function to evaluate.
101/// \param[in] indata Dataset for which to compute test statistic.
102/// \param[in] projDeps A set of projected observables.
103/// \param[in] rangeName If not null, only events in the dataset inside the range will be used in the test
104/// statistic calculation.
105/// \param[in] addCoefRangeName If not null, all RooAddPdf components of `real` will be
106/// instructed to fix their fraction definitions to the given named range.
107/// \param[in] nCPU If > 1, the test statistic calculation will be parallelised over multiple processes. By default, the data
108/// is split with 'bulk' partitioning (each process calculates a contiguous block of fraction 1/nCPU
109/// of the data). For binned data, this approach may be suboptimal as the number of bins with >0 entries
110/// in each processing block may vary greatly; thereby distributing the workload rather unevenly.
111/// \param[in] interleave Strategy how to distribute events among workers. If an interleave partitioning strategy is used where each partition
112/// i takes all bins for which (ibin % ncpu == i), an even distribution of work is more likely.
113/// \param[in] splitCutRange If true, a different rangeName constructed as `rangeName_{catName}` will be used
114/// as range definition for each index state of a RooSimultaneous.
115/// \param[in] cloneInputData Not used. Data is always cloned.
116/// \param[in] integrateOverBinsPrecision If > 0, PDF in binned fits are integrated over the bins. This sets the precision. If = 0,
117/// only unbinned PDFs fit to RooDataHist are integrated. If < 0, PDFs are never integrated.
119 RooAbsData& indata, const RooArgSet& projDeps,
121 RooAbsTestStatistic(name,title,real,indata,projDeps,cfg),
122 _projDeps(0),
123 _sealed(kFALSE),
124 _optimized(kFALSE),
125 _integrateBinsPrecision(cfg.integrateOverBinsPrecision)
126{
127 // Don't do a thing in master mode
128
129 if (operMode()!=Slave) {
130 _funcObsSet = 0 ;
131 _funcCloneSet = 0 ;
132 _funcClone = 0 ;
133 _normSet = 0 ;
134 _projDeps = 0 ;
135 _origFunc = 0 ;
136 _origData = 0 ;
137 _ownData = kFALSE ;
138 _sealed = kFALSE ;
139 return ;
140 }
141
142 _origFunc = 0 ; //other._origFunc ;
143 _origData = 0 ; // other._origData ;
144
145 initSlave(real, indata, projDeps, _rangeName.c_str(), _addCoefRangeName.c_str()) ;
146}
147
148////////////////////////////////////////////////////////////////////////////////
149/// Copy constructor
150
152 RooAbsTestStatistic(other,name), _sealed(other._sealed), _sealNotice(other._sealNotice), _optimized(kFALSE),
153 _integrateBinsPrecision(other._integrateBinsPrecision)
154{
155 // Don't do a thing in master mode
156 if (operMode()!=Slave) {
157
158 _funcObsSet = 0 ;
159 _funcCloneSet = 0 ;
160 _funcClone = 0 ;
161 _normSet = other._normSet ? ((RooArgSet*) other._normSet->snapshot()) : 0 ;
162 _projDeps = 0 ;
163 _origFunc = 0 ;
164 _origData = 0 ;
165 _ownData = kFALSE ;
166 return ;
167 }
168
169 _origFunc = 0 ; //other._origFunc ;
170 _origData = 0 ; // other._origData ;
171 _projDeps = 0 ;
172
173 initSlave(*other._funcClone,*other._dataClone,other._projDeps?*other._projDeps:RooArgSet(),other._rangeName.c_str(),other._addCoefRangeName.c_str()) ;
174}
175
176
177
178////////////////////////////////////////////////////////////////////////////////
179
180void RooAbsOptTestStatistic::initSlave(RooAbsReal& real, RooAbsData& indata, const RooArgSet& projDeps, const char* rangeName,
181 const char* addCoefRangeName) {
182 // ******************************************************************
183 // *** PART 1 *** Clone incoming pdf, attach to each other *
184 // ******************************************************************
185
186 // Clone FUNC
187 _funcClone = static_cast<RooAbsReal*>(real.cloneTree());
188 _funcCloneSet = 0 ;
189
190 // Attach FUNC to data set
192
193 if (_funcClone->getAttribute("BinnedLikelihood")) {
194 _funcClone->setAttribute("BinnedLikelihoodActive") ;
195 }
196
197 // Reattach FUNC to original parameters
198 RooArgSet* origParams = (RooArgSet*) real.getParameters(indata) ;
200
201 // Mark all projected dependents as such
202 if (projDeps.getSize()>0) {
203 RooArgSet *projDataDeps = (RooArgSet*) _funcObsSet->selectCommon(projDeps) ;
204 projDataDeps->setAttribAll("projectedDependent") ;
205 delete projDataDeps ;
206 }
207
208 // If PDF is a RooProdPdf (with possible constraint terms)
209 // analyze pdf for actual parameters (i.e those in unconnected constraint terms should be
210 // ignored as here so that the test statistic will not be recalculated if those
211 // are changed
212 RooProdPdf* pdfWithCons = dynamic_cast<RooProdPdf*>(_funcClone) ;
213 if (pdfWithCons) {
214
215 RooArgSet* connPars = pdfWithCons->getConnectedParameters(*indata.get()) ;
216 // Add connected parameters as servers
218 _paramSet.add(*connPars) ;
219 delete connPars ;
220
221 } else {
222 // Add parameters as servers
223 _paramSet.add(*origParams) ;
224 }
225
226
227 delete origParams ;
228
229 // Store normalization set
230 _normSet = (RooArgSet*) indata.get()->snapshot(kFALSE) ;
231
232 // Expand list of observables with any observables used in parameterized ranges.
233 // This NEEDS to be a counting loop since we are inserting during the loop.
234 for (std::size_t i = 0; i < _funcObsSet->size(); ++i) {
235 auto realDepRLV = dynamic_cast<const RooAbsRealLValue*>((*_funcObsSet)[i]);
236 if (realDepRLV && realDepRLV->isDerived()) {
237 RooArgSet tmp2;
238 realDepRLV->leafNodeServerList(&tmp2, 0, kTRUE);
239 _funcObsSet->add(tmp2,kTRUE);
240 }
241 }
242
243
244
245 // ******************************************************************
246 // *** PART 2 *** Clone and adjust incoming data, attach to PDF *
247 // ******************************************************************
248
249 // Check if the fit ranges of the dependents in the data and in the FUNC are consistent
250 const RooArgSet* dataDepSet = indata.get() ;
251 for (const auto arg : *_funcObsSet) {
252
253 // Check that both dataset and function argument are of type RooRealVar
254 RooRealVar* realReal = dynamic_cast<RooRealVar*>(arg) ;
255 if (!realReal) continue ;
256 RooRealVar* datReal = dynamic_cast<RooRealVar*>(dataDepSet->find(realReal->GetName())) ;
257 if (!datReal) continue ;
258
259 // Check that range of observables in pdf is equal or contained in range of observables in data
260
261 if (!realReal->getBinning().lowBoundFunc() && realReal->getMin()<(datReal->getMin()-1e-6)) {
262 coutE(InputArguments) << "RooAbsOptTestStatistic: ERROR minimum of FUNC observable " << arg->GetName()
263 << "(" << realReal->getMin() << ") is smaller than that of "
264 << arg->GetName() << " in the dataset (" << datReal->getMin() << ")" << endl ;
266 return ;
267 }
268
269 if (!realReal->getBinning().highBoundFunc() && realReal->getMax()>(datReal->getMax()+1e-6)) {
270 coutE(InputArguments) << "RooAbsOptTestStatistic: ERROR maximum of FUNC observable " << arg->GetName()
271 << " is larger than that of " << arg->GetName() << " in the dataset" << endl ;
273 return ;
274 }
275 }
276
277 // Copy data and strip entries lost by adjusted fit range, _dataClone ranges will be copied from realDepSet ranges
278 if (rangeName && strlen(rangeName)) {
280 // cout << "RooAbsOptTestStatistic: reducing dataset to fit in range named " << rangeName << " resulting dataset has " << _dataClone->sumEntries() << " events" << endl ;
281 } else {
282 _dataClone = (RooAbsData*) indata.Clone() ;
283 }
284 _ownData = kTRUE ;
285
286
287 // ******************************************************************
288 // *** PART 3 *** Make adjustments for fit ranges, if specified *
289 // ******************************************************************
290
291 std::unique_ptr<RooArgSet> origObsSet( real.getObservables(indata) );
292 RooArgSet* dataObsSet = (RooArgSet*) _dataClone->get() ;
293 if (rangeName && strlen(rangeName)) {
294 cxcoutI(Fitting) << "RooAbsOptTestStatistic::ctor(" << GetName() << ") constructing test statistic for sub-range named " << rangeName << endl ;
295
296 bool observablesKnowRange = false;
297 // Adjust FUNC normalization ranges to requested fitRange, store original ranges for RooAddPdf coefficient interpretation
298 for (const auto arg : *_funcObsSet) {
299
300 RooRealVar* realObs = dynamic_cast<RooRealVar*>(arg) ;
301 if (realObs) {
302
303 auto transferRangeAndBinning = [&](RooRealVar & toVar, const char* toName, const char* fromName) {
304 toVar.setRange(toName, realObs->getMin(fromName),realObs->getMax(fromName));
305 // If the realObs also has a binning with a name matching the
306 // rangeName, it will be set as the default binning. If `fromName` is
307 // a nullptr to signify taking the default binning from `realObs`,
308 // don't check if it exists as there is always a default binning.
309 if(!fromName || realObs->hasBinning(fromName)) {
310 toVar.setBinning(realObs->getBinning(fromName), toName);
311 }
312 };
313
314 observablesKnowRange |= realObs->hasRange(rangeName);
315
316 // If no explicit range is given for RooAddPdf coefficients, create explicit named range equivalent to original observables range
317 if (!(addCoefRangeName && strlen(addCoefRangeName))) {
318 transferRangeAndBinning(*realObs, Form("NormalizationRangeFor%s",rangeName), nullptr);
319 }
320
321 // Adjust range of function observable to those of given named range
322 transferRangeAndBinning(*realObs, nullptr, rangeName);
323
324 // Adjust range of data observable to those of given named range
325 RooRealVar* dataObs = (RooRealVar*) dataObsSet->find(realObs->GetName()) ;
326 transferRangeAndBinning(*dataObs, nullptr, rangeName);
327
328 // Keep track of list of fit ranges in string attribute fit range of original p.d.f.
329 if (!_splitRange) {
330 const std::string fitRangeName = std::string("fit_") + GetName();
331 const char* origAttrib = real.getStringAttribute("fitrange") ;
332 std::string newAttr = origAttrib ? origAttrib : "";
333
334 if (newAttr.find(fitRangeName) == std::string::npos) {
335 newAttr += (newAttr.empty() ? "" : ",") + fitRangeName;
336 }
337 real.setStringAttribute("fitrange", newAttr.c_str());
338 RooRealVar* origObs = (RooRealVar*) origObsSet->find(arg->GetName()) ;
339 if (origObs) {
340 transferRangeAndBinning(*origObs, fitRangeName.c_str(), rangeName);
341 }
342 }
343 }
344 }
345
346 if (!observablesKnowRange)
347 coutW(Fitting) << "None of the fit observables seem to know the range '" << rangeName << "'. This means that the full range will be used." << std::endl;
348 }
349
350
351 // ******************************************************************
352 // *** PART 3.2 *** Binned fits *
353 // ******************************************************************
354
355 // If dataset is binned, activate caching of bins that are invalid because the're outside the
356 // updated range definition (WVE need to add virtual interface here)
357 RooDataHist* tmph = dynamic_cast<RooDataHist*>(_dataClone) ;
358 if (tmph) {
359 tmph->cacheValidEntries() ;
360 }
361
363
364
365 // Fix RooAddPdf coefficients to original normalization range
366 if (rangeName && strlen(rangeName)) {
367
368 // WVE Remove projected dependents from normalization
370
371 if (addCoefRangeName && strlen(addCoefRangeName)) {
372 cxcoutI(Fitting) << "RooAbsOptTestStatistic::ctor(" << GetName()
373 << ") fixing interpretation of coefficients of any RooAddPdf component to range " << addCoefRangeName << endl ;
374 _funcClone->fixAddCoefRange(addCoefRangeName,kFALSE) ;
375 } else {
376 cxcoutI(Fitting) << "RooAbsOptTestStatistic::ctor(" << GetName()
377 << ") fixing interpretation of coefficients of any RooAddPdf to full domain of observables " << endl ;
378 _funcClone->fixAddCoefRange(Form("NormalizationRangeFor%s",rangeName),kFALSE) ;
379 }
380 }
381
382
383 // This is deferred from part 2 - but must happen after part 3 - otherwise invalid bins cannot be properly marked in cacheValidEntries
386
387
388
389
390 // *********************************************************************
391 // *** PART 4 *** Adjust normalization range for projected observables *
392 // *********************************************************************
393
394 // Remove projected dependents from normalization set
395 if (projDeps.getSize()>0) {
396
397 _projDeps = (RooArgSet*) projDeps.snapshot(kFALSE) ;
398
399 //RooArgSet* tobedel = (RooArgSet*) _normSet->selectCommon(*_projDeps) ;
401
402 // Mark all projected dependents as such
404 projDataDeps->setAttribAll("projectedDependent") ;
405 delete projDataDeps ;
406 }
407
408
409 coutI(Optimization) << "RooAbsOptTestStatistic::ctor(" << GetName() << ") optimizing internal clone of p.d.f for likelihood evaluation."
410 << "Lazy evaluation and associated change tracking will disabled for all nodes that depend on observables" << endl ;
411
412
413 // *********************************************************************
414 // *** PART 4 *** Finalization and activation of optimization *
415 // *********************************************************************
416
417 // Redirect pointers of base class to clone
418 _func = _funcClone ;
419 _data = _dataClone ;
420
422
424
425 // It would be unusual if the global observables are used in the likelihood
426 // outside of the constraint terms, but if they are we have to be consistent
427 // and also redirect them to the snapshots in the dataset if appropriate.
430 }
431
432}
433
434
435////////////////////////////////////////////////////////////////////////////////
436/// Destructor
437
439{
440 if (operMode()==Slave) {
441 delete _funcClone ;
442 delete _funcObsSet ;
443 if (_projDeps) {
444 delete _projDeps ;
445 }
446 if (_ownData) {
447 delete _dataClone ;
448 }
449 }
450 delete _normSet ;
451}
452
453
454
455////////////////////////////////////////////////////////////////////////////////
456/// Method to combined test statistic results calculated into partitions into
457/// the global result. This default implementation adds the partition return
458/// values
459
461{
462 // Default implementation returns sum of components
463 Double_t sum(0), carry(0);
464 for (Int_t i = 0; i < n; ++i) {
465 Double_t y = array[i]->getValV();
466 carry += reinterpret_cast<RooAbsOptTestStatistic*>(array[i])->getCarry();
467 y -= carry;
468 const Double_t t = sum + y;
469 carry = (t - sum) - y;
470 sum = t;
471 }
472 _evalCarry = carry;
473 return sum ;
474}
475
476
477
478////////////////////////////////////////////////////////////////////////////////
479/// Catch server redirect calls and forward to internal clone of function
480
481Bool_t RooAbsOptTestStatistic::redirectServersHook(const RooAbsCollection& newServerList, Bool_t mustReplaceAll, Bool_t nameChange, Bool_t isRecursive)
482{
483 RooAbsTestStatistic::redirectServersHook(newServerList,mustReplaceAll,nameChange,isRecursive) ;
484 if (operMode()!=Slave) return kFALSE ;
485 Bool_t ret = _funcClone->recursiveRedirectServers(newServerList,kFALSE,nameChange) ;
486 return ret ;
487}
488
489
490
491////////////////////////////////////////////////////////////////////////////////
492/// Catch print hook function and forward to function clone
493
495{
497 if (operMode()!=Slave) return ;
498 TString indent2(indent) ;
499 indent2 += "opt >>" ;
500 _funcClone->printCompactTree(os,indent2.Data()) ;
501 os << indent2 << " dataset clone = " << _dataClone << " first obs = " << _dataClone->get()->first() << endl ;
502}
503
504
505
506////////////////////////////////////////////////////////////////////////////////
507/// Driver function to propagate constant term optimizations in test statistic.
508/// If code Activate is sent, constant term optimization will be executed.
509/// If code Deactivate is sent, any existing constant term optimizations will
510/// be abandoned. If codes ConfigChange or ValueChange are sent, any existing
511/// constant term optimizations will be redone.
512
514{
515 // cout << "ROATS::constOpt(" << GetName() << ") funcClone structure dump BEFORE const-opt" << endl ;
516 // _funcClone->Print("t") ;
517
518 RooAbsTestStatistic::constOptimizeTestStatistic(opcode,doAlsoTrackingOpt);
519 if (operMode()!=Slave) return ;
520
521 if (_dataClone->hasFilledCache() && _dataClone->store()->cacheOwner()!=this) {
522 if (opcode==Activate) {
523 cxcoutW(Optimization) << "RooAbsOptTestStatistic::constOptimize(" << GetName()
524 << ") dataset cache is owned by another object, no constant term optimization can be applied" << endl ;
525 }
526 return ;
527 }
528
529 if (!allowFunctionCache()) {
530 if (opcode==Activate) {
531 cxcoutI(Optimization) << "RooAbsOptTestStatistic::constOptimize(" << GetName()
532 << ") function caching prohibited by test statistic, no constant term optimization is applied" << endl ;
533 }
534 return ;
535 }
536
537 if (_dataClone->hasFilledCache() && opcode==Activate) {
538 opcode=ValueChange ;
539 }
540
541 switch(opcode) {
542 case Activate:
543 cxcoutI(Optimization) << "RooAbsOptTestStatistic::constOptimize(" << GetName()
544 << ") optimizing evaluation of test statistic by finding all nodes in p.d.f that depend exclusively"
545 << " on observables and constant parameters and precalculating their values" << endl ;
546 optimizeConstantTerms(kTRUE,doAlsoTrackingOpt) ;
547 break ;
548
549 case DeActivate:
550 cxcoutI(Optimization) << "RooAbsOptTestStatistic::constOptimize(" << GetName()
551 << ") deactivating optimization of constant terms in test statistic" << endl ;
553 break ;
554
555 case ConfigChange:
556 cxcoutI(Optimization) << "RooAbsOptTestStatistic::constOptimize(" << GetName()
557 << ") one ore more parameter were changed from constant to floating or vice versa, "
558 << "re-evaluating constant term optimization" << endl ;
560 optimizeConstantTerms(kTRUE,doAlsoTrackingOpt) ;
561 break ;
562
563 case ValueChange:
564 cxcoutI(Optimization) << "RooAbsOptTestStatistic::constOptimize(" << GetName()
565 << ") the value of one ore more constant parameter were changed re-evaluating constant term optimization" << endl ;
566 // Request a forcible cache update of all cached nodes
568
569 break ;
570 }
571
572// cout << "ROATS::constOpt(" << GetName() << ") funcClone structure dump AFTER const-opt" << endl ;
573// _funcClone->Print("t") ;
574}
575
576
577
578////////////////////////////////////////////////////////////////////////////////
579/// This method changes the value caching logic for all nodes that depends on any of the observables
580/// as defined by the given dataset. When evaluating a test statistic constructed from the RooAbsReal
581/// with a dataset the observables are guaranteed to change with every call, thus there is no point
582/// in tracking these changes which result in a net overhead. Thus for observable-dependent nodes,
583/// the evaluation mechanism is changed from being dependent on a 'valueDirty' flag to guaranteed evaluation.
584/// On the dataset side, the observables objects are modified to no longer send valueDirty messages
585/// to their client
586
588{
589// cout << "RooAbsOptTestStatistic::optimizeCaching(" << GetName() << "," << this << ")" << endl ;
590
591 // Trigger create of all object caches now in nodes that have deferred object creation
592 // so that cache contents can be processed immediately
594
595 // Set value caching mode for all nodes that depend on any of the observables to ADirty
597
598 // Disable propagation of dirty state flags for observables
600
601 // Disable reading of observables that are not used
603}
604
605
606
607////////////////////////////////////////////////////////////////////////////////
608/// Driver function to activate global constant term optimization.
609/// If activated, constant terms are found and cached with the dataset.
610/// The operation mode of cached nodes is set to AClean meaning that
611/// their getVal() call will never result in an evaluate call.
612/// Finally the branches in the dataset that correspond to observables
613/// that are exclusively used in constant terms are disabled as
614/// they serve no more purpose
615
617{
618 if(activate) {
619
620 if (_optimized) {
621 return ;
622 }
623
624 // Trigger create of all object caches now in nodes that have deferred object creation
625 // so that cache contents can be processed immediately
627
628
629 // WVE - Patch to allow customization of optimization level per component pdf
630 if (_funcClone->getAttribute("NoOptimizeLevel1")) {
631 coutI(Minimization) << " Optimization customization: Level-1 constant-term optimization prohibited by attribute NoOptimizeLevel1 set on top-level pdf "
632 << _funcClone->IsA()->GetName() << "::" << _funcClone->GetName() << endl ;
633 return ;
634 }
635 if (_funcClone->getAttribute("NoOptimizeLevel2")) {
636 coutI(Minimization) << " Optimization customization: Level-2 constant-term optimization prohibited by attribute NoOptimizeLevel2 set on top-level pdf "
637 << _funcClone->IsA()->GetName() << "::" << _funcClone->GetName() << endl ;
638 applyTrackingOpt=kFALSE ;
639 }
640
641 // Apply tracking optimization here. Default strategy is to track components
642 // of RooAddPdfs and RooRealSumPdfs. If these components are a RooProdPdf
643 // or a RooProduct respectively, track the components of these products instead
644 // of the product term
645 RooArgSet trackNodes ;
646
647
648 // Add safety check here - applyTrackingOpt will only be applied if present
649 // dataset is constructed in terms of a RooVectorDataStore
650 if (applyTrackingOpt) {
651 if (!dynamic_cast<RooVectorDataStore*>(_dataClone->store())) {
652 coutW(Optimization) << "RooAbsOptTestStatistic::optimizeConstantTerms(" << GetName()
653 << ") WARNING Cache-and-track optimization (Optimize level 2) is only available for datasets"
654 << " implement in terms of RooVectorDataStore - ignoring this option for current dataset" << endl ;
655 applyTrackingOpt = kFALSE ;
656 }
657 }
658
659 if (applyTrackingOpt) {
660 RooArgSet branches ;
661 _funcClone->branchNodeServerList(&branches) ;
662 for (auto arg : branches) {
663 arg->setCacheAndTrackHints(trackNodes);
664 }
665 // Do not set CacheAndTrack on constant expressions
666 RooArgSet* constNodes = (RooArgSet*) trackNodes.selectByAttrib("Constant",kTRUE) ;
667 trackNodes.remove(*constNodes) ;
668 delete constNodes ;
669
670 // Set CacheAndTrack flag on all remaining nodes
671 trackNodes.setAttribAll("CacheAndTrack",kTRUE) ;
672 }
673
674 // Find all nodes that depend exclusively on constant parameters
676
678
679 // Cache constant nodes with dataset - also cache entries corresponding to zero-weights in data when using BinnedLikelihood
680 _dataClone->cacheArgs(this,_cachedNodes,_normSet,!_funcClone->getAttribute("BinnedLikelihood")) ;
681
682 // Put all cached nodes in AClean value caching mode so that their evaluate() is never called
683 for (auto cacheArg : _cachedNodes) {
684 cacheArg->setOperMode(RooAbsArg::AClean) ;
685 }
686
687 RooArgSet* constNodes = (RooArgSet*) _cachedNodes.selectByAttrib("ConstantExpressionCached",kTRUE) ;
688 RooArgSet actualTrackNodes(_cachedNodes) ;
689 actualTrackNodes.remove(*constNodes) ;
690 if (constNodes->getSize()>0) {
691 if (constNodes->getSize()<20) {
692 coutI(Minimization) << " The following expressions have been identified as constant and will be precalculated and cached: " << *constNodes << endl ;
693 } else {
694 coutI(Minimization) << " A total of " << constNodes->getSize() << " expressions have been identified as constant and will be precalculated and cached." << endl ;
695 }
696 }
697 if (actualTrackNodes.getSize()>0) {
698 if (actualTrackNodes.getSize()<20) {
699 coutI(Minimization) << " The following expressions will be evaluated in cache-and-track mode: " << actualTrackNodes << endl ;
700 } else {
701 coutI(Minimization) << " A total of " << constNodes->getSize() << " expressions will be evaluated in cache-and-track-mode." << endl ;
702 }
703 }
704 delete constNodes ;
705
706 // Disable reading of observables that are no longer used
708
709 _optimized = kTRUE ;
710
711 } else {
712
713 // Delete the cache
715
716 // Reactivate all tree branches
718
719 // Reset all nodes to ADirty
721
722 // Disable propagation of dirty state flags for observables
724
726
727
729 }
730}
731
732
733
734////////////////////////////////////////////////////////////////////////////////
735/// Change dataset that is used to given one. If cloneData is kTRUE, a clone of
736/// in the input dataset is made. If the test statistic was constructed with
737/// a range specification on the data, the cloneData argument is ignored and
738/// the data is always cloned.
740{
741
742 if (operMode()==SimMaster) {
743 //cout << "ROATS::setDataSlave() ERROR this is SimMaster _funcClone = " << _funcClone << endl ;
744 return kFALSE ;
745 }
746
747 //cout << "ROATS::setDataSlave() new dataset size = " << indata.numEntries() << endl ;
748 //indata.Print("v") ;
749
750
751 // If the current dataset is owned, transfer the ownership to unique pointer
752 // that will get out of scope at the end of this function. We can't delete it
753 // right now, because there might be global observables in the model that
754 // first need to be redirected to the new dataset with a later call to
755 // RooAbsArg::recursiveRedirectServers.
756 std::unique_ptr<RooAbsData> oldOwnedData;
757 if (_ownData) {
758 oldOwnedData.reset(_dataClone);
759 _dataClone = nullptr ;
760 }
761
762 if (!cloneData && _rangeName.size()>0) {
763 coutW(InputArguments) << "RooAbsOptTestStatistic::setData(" << GetName() << ") WARNING: test statistic was constructed with range selection on data, "
764 << "ignoring request to _not_ clone the input dataset" << endl ;
765 cloneData = kTRUE ;
766 }
767
768 if (cloneData) {
769 // Cloning input dataset
770 if (_rangeName.size()==0) {
771 _dataClone = (RooAbsData*) indata.reduce(*indata.get()) ;
772 } else {
774 }
775 _ownData = kTRUE ;
776
777 } else {
778
779 // Taking input dataset
780 _dataClone = &indata ;
781 _ownData = ownNewData ;
782
783 }
784
785 // Attach function clone to dataset
788 _data = _dataClone ;
789
790 // ReCache constant nodes with dataset
791 if (_cachedNodes.getSize()>0) {
793 }
794
795 // Adjust internal event count
796 setEventCount(indata.numEntries()) ;
797
798 setValueDirty() ;
799
800 // It would be unusual if the global observables are used in the likelihood
801 // outside of the constraint terms, but if they are we have to be consistent
802 // and also redirect them to the snapshots in the dataset if appropriate.
805 }
806
807 return kTRUE ;
808}
809
810
811
812
813////////////////////////////////////////////////////////////////////////////////
814
816{
817 if (_sealed) {
818 Bool_t notice = (sealNotice() && strlen(sealNotice())) ;
819 coutW(ObjectHandling) << "RooAbsOptTestStatistic::data(" << GetName()
820 << ") WARNING: object sealed by creator - access to data is not permitted: "
821 << (notice?sealNotice():"<no user notice>") << endl ;
822 static RooDataSet dummy ("dummy","dummy",RooArgSet()) ;
823 return dummy ;
824 }
825 return *_dataClone ;
826}
827
828
829////////////////////////////////////////////////////////////////////////////////
830
832{
833 if (_sealed) {
834 Bool_t notice = (sealNotice() && strlen(sealNotice())) ;
835 coutW(ObjectHandling) << "RooAbsOptTestStatistic::data(" << GetName()
836 << ") WARNING: object sealed by creator - access to data is not permitted: "
837 << (notice?sealNotice():"<no user notice>") << endl ;
838 static RooDataSet dummy ("dummy","dummy",RooArgSet()) ;
839 return dummy ;
840 }
841 return *_dataClone ;
842}
843
844
845////////////////////////////////////////////////////////////////////////////////
846/// Inspect PDF to find out if we are doing a binned fit to a 1-dimensional unbinned PDF.
847/// If this is the case, enable finer sampling of bins by wrapping PDF into a RooBinSamplingPdf.
848/// The member _integrateBinsPrecision decides how we act:
849/// - < 0: Don't do anything.
850/// - = 0: Only enable feature if fitting unbinned PDF to RooDataHist.
851/// - > 0: Enable as requested.
853
854 auto& pdf = static_cast<RooAbsPdf&>(*_funcClone);
857 _funcClone = newPdf.release();
858 }
859
860}
#define e(i)
Definition RSha256.hxx:103
#define coutI(a)
#define cxcoutI(a)
#define coutW(a)
#define cxcoutW(a)
#define coutE(a)
const Bool_t kFALSE
Definition RtypesCore.h:101
const Bool_t kTRUE
Definition RtypesCore.h:100
#define ClassImp(name)
Definition Rtypes.h:364
static void indent(ostringstream &buf, int indent_level)
char name[80]
Definition TGX11.cxx:110
char * Form(const char *fmt,...)
virtual RooAbsArg * cloneTree(const char *newname=0) const
Clone tree expression of objects.
RooArgSet * getObservables(const RooArgSet &set, Bool_t valueOnly=kTRUE) const
Given a set of possible observables, return the observables that this PDF depends on.
Definition RooAbsArg.h:309
void printCompactTree(const char *indent="", const char *fileName=0, const char *namePat=0, RooAbsArg *client=0)
Print tree structure of expression tree on stdout, or to file if filename is specified.
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
Bool_t findConstantNodes(const RooArgSet &observables, RooArgSet &cacheList)
Find branch nodes with all-constant parameters, and add them to the list of nodes that can be cached ...
friend class RooArgSet
Definition RooAbsArg.h:642
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'.
void setAttribute(const Text_t *name, Bool_t value=kTRUE)
Set (default) or clear a named boolean attribute of this object.
void setValueDirty()
Mark the element dirty. This forces a re-evaluation when a value is requested.
Definition RooAbsArg.h:505
virtual void optimizeCacheMode(const RooArgSet &observables)
Activate cache mode optimization with given definition of observables.
Bool_t getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
RooArgSet * getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
void branchNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=0, Bool_t recurseNonDerived=kFALSE) const
Fill supplied list with all branch nodes of the arg tree starting with ourself as top node.
Bool_t recursiveRedirectServers(const RooAbsCollection &newServerList, Bool_t mustReplaceAll=kFALSE, Bool_t nameChange=kFALSE, Bool_t recurseInNewSet=kTRUE)
Recursively replace all servers with the new servers in newSet.
virtual RooAbsReal * highBoundFunc() const
Return pointer to RooAbsReal parameterized upper bound, if any.
virtual RooAbsReal * lowBoundFunc() const
Return pointer to RooAbsReal parameterized lower bound, if any.
RooAbsCollection is an abstract container object that can hold multiple RooAbsArg objects.
virtual void removeAll()
Remove all arguments from our set, deleting them if we own them.
Int_t getSize() const
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
Storage_t::size_type size() const
RooAbsArg * first() const
void setAttribAll(const Text_t *name, Bool_t value=kTRUE)
Set given attribute in each element of the collection by calling each elements setAttribute() functio...
bool selectCommon(const RooAbsCollection &refColl, RooAbsCollection &outColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
RooAbsCollection * selectByAttrib(const char *name, Bool_t value) const
Create a subset of the current collection, consisting only of those elements with the specified attri...
virtual Bool_t remove(const RooAbsArg &var, Bool_t silent=kFALSE, Bool_t matchByNameOnly=kFALSE)
Remove the specified argument from our list.
RooAbsArg * find(const char *name) const
Find object with given name in list.
virtual const RooAbsArg * cacheOwner()=0
virtual void forceCacheUpdate()
RooAbsData is the common abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:82
virtual const RooArgSet * get() const
Definition RooAbsData.h:128
RooAbsDataStore * store()
Definition RooAbsData.h:104
virtual void optimizeReadingWithCaching(RooAbsArg &arg, const RooArgSet &cacheList, const RooArgSet &keepObsList)
Prepare dataset for use with cached constant terms listed in 'cacheList' of expression 'arg'.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
RooArgSet const * getGlobalObservables() const
Returns snapshot of global observables stored in this data.
Definition RooAbsData.h:315
virtual void resetCache()
Internal method – Remove cached function values.
Bool_t hasFilledCache() const
RooAbsData * reduce(const RooCmdArg &arg1, const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg())
Create a reduced copy of this dataset.
virtual void cacheArgs(const RooAbsArg *owner, RooArgSet &varSet, const RooArgSet *nset=0, Bool_t skipZeroWeights=kFALSE)
Internal method – Cache given set of functions with data.
void attachBuffers(const RooArgSet &extObs)
virtual void setArgStatus(const RooArgSet &set, Bool_t active)
void setDirtyProp(Bool_t flag)
Control propagation of dirty flags from observables in dataset.
RooAbsOptTestStatistic is the abstract base class for test statistics objects that evaluate a functio...
virtual ~RooAbsOptTestStatistic()
Destructor.
RooAbsReal * _origFunc
List of nodes that are cached as constant expressions.
void optimizeCaching()
This method changes the value caching logic for all nodes that depends on any of the observables as d...
const char * sealNotice() const
void optimizeConstantTerms(Bool_t, Bool_t=kTRUE)
Driver function to activate global constant term optimization.
void setUpBinSampling()
Inspect PDF to find out if we are doing a binned fit to a 1-dimensional unbinned PDF.
virtual Bool_t allowFunctionCache()
virtual Bool_t redirectServersHook(const RooAbsCollection &newServerList, Bool_t mustReplaceAll, Bool_t nameChange, Bool_t isRecursive)
Catch server redirect calls and forward to internal clone of function.
virtual void printCompactTreeHook(std::ostream &os, const char *indent="")
Catch print hook function and forward to function clone.
void initSlave(RooAbsReal &real, RooAbsData &indata, const RooArgSet &projDeps, const char *rangeName, const char *addCoefRangeName)
virtual Double_t combinedValue(RooAbsReal **gofArray, Int_t nVal) const
Method to combined test statistic results calculated into partitions into the global result.
virtual RooArgSet requiredExtraObservables() const
RooAbsOptTestStatistic()
Default Constructor.
Bool_t setDataSlave(RooAbsData &data, Bool_t cloneData=kTRUE, Bool_t ownNewDataAnyway=kFALSE)
Change dataset that is used to given one.
void constOptimizeTestStatistic(ConstOpCode opcode, Bool_t doAlsoTrackingOpt=kTRUE)
Driver function to propagate constant term optimizations in test statistic.
RooAbsRealLValue is the common abstract base class for objects that represent a real value that may a...
virtual Double_t getMax(const char *name=0) const
Get maximum of currently defined range.
virtual Bool_t hasRange(const char *name) const
Check if variable has a binning with given name.
virtual Double_t getMin(const char *name=0) const
Get miniminum of currently defined range.
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition RooAbsReal.h:64
virtual void fixAddCoefRange(const char *rangeName=0, Bool_t force=kTRUE)
Fix the interpretation of the coefficient of any RooAddPdf component in the expression tree headed by...
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:94
virtual Double_t getValV(const RooArgSet *normalisationSet=nullptr) const
Return value of object.
virtual void fixAddCoefNormalization(const RooArgSet &addNormSet=RooArgSet(), Bool_t force=kTRUE)
Fix the interpretation of the coefficient of any RooAddPdf component in the expression tree headed by...
RooAbsTestStatistic is the abstract base class for all test statistics.
GOFOpMode operMode() const
virtual void constOptimizeTestStatistic(ConstOpCode opcode, Bool_t doAlsoTrackingOpt=kTRUE)
Forward constant term optimization management calls to component test statistics.
virtual Bool_t redirectServersHook(const RooAbsCollection &newServerList, Bool_t mustReplaceAll, Bool_t nameChange, Bool_t isRecursive)
Forward server redirect calls to component test statistics.
void setEventCount(Int_t nEvents)
virtual Double_t getCarry() const
Double_t _evalCarry
Offset as KahanSum to avoid loss of precision.
const bool _takeGlobalObservablesFromData
virtual void printCompactTreeHook(std::ostream &os, const char *indent="")
Add extra information on component test statistics when printing itself as part of a tree structure.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:35
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition RooArgSet.h:158
static std::unique_ptr< RooAbsPdf > create(RooAbsPdf &pdf, RooAbsData const &data, double precision)
Creates a wrapping RooBinSamplingPdf if appropriate.
The RooDataHist is a container class to hold N-dimensional binned data.
Definition RooDataHist.h:45
void cacheValidEntries()
Compute which bins of the dataset are part of the currently set fit range.
RooDataSet is a container class to hold unbinned data.
Definition RooDataSet.h:36
static void softAbort()
RooProdPdf is an efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:33
RooArgSet * getConnectedParameters(const RooArgSet &observables) const
Return all parameter constraint p.d.f.s on parameters listed in constrainedParams.
RooRealVar represents a variable that can be changed from the outside.
Definition RooRealVar.h:39
Bool_t hasBinning(const char *name) const
Returns true if variable has a binning named 'name'.
void setRange(const char *name, Double_t min, Double_t max)
Set a fit or plotting range.
const RooAbsBinning & getBinning(const char *name=0, Bool_t verbose=kTRUE, Bool_t createOnTheFly=kFALSE) const
Return binning definition with name.
void setBinning(const RooAbsBinning &binning, const char *name=0)
Add given binning under name 'name' with this variable.
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE) override
Overloaded RooArgSet::add() method inserts 'var' into set and registers 'var' as server to owner with...
virtual void removeAll() override
Remove all argument inset using remove(const RooAbsArg&).
RooVectorDataStore uses std::vectors to store data columns.
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition TNamed.cxx:74
virtual const char * GetName() const
Returns name of object.
Definition TNamed.h:47
Basic string class.
Definition TString.h:136
const char * Data() const
Definition TString.h:369
RooCmdArg SelectVars(const RooArgSet &vars)
RooCmdArg CutRange(const char *rangeName)
Double_t y[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2345