Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsReal.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
19/** \class RooAbsReal
20
21 Abstract base class for objects that represent a
22 real value and implements functionality common to all real-valued objects
23 such as the ability to plot them, to construct integrals of them, the
24 ability to advertise (partial) analytical integrals etc.
25
26 Implementation of RooAbsReal may be derived, thus no interface
27 is provided to modify the contents.
28
29 \ingroup Roofitcore
30*/
31
32#include "RooAbsReal.h"
33
34#include "FitHelpers.h"
36#include "RooAbsData.h"
37#include "RooAddPdf.h"
38#include "RooAddition.h"
39#include "RooArgList.h"
40#include "RooArgSet.h"
41#include "RooBinning.h"
42#include "RooBrentRootFinder.h"
43#include "RooCachedReal.h"
44#include "RooCategory.h"
45#include "RooCmdConfig.h"
46#include "RooConstVar.h"
47#include "RooCurve.h"
48#include "RooCustomizer.h"
49#include "RooDataHist.h"
50#include "RooDataSet.h"
51#include "RooDerivative.h"
52#include "RooFirstMoment.h"
54#include "RooFit/Evaluator.h"
55#include "RooFitResult.h"
56#include "RooFormulaVar.h"
57#include "RooFunctor.h"
58#include "RooGlobalFunc.h"
59#include "RooFitImplHelpers.h"
60#include "RooHist.h"
61#include "RooMoment.h"
62#include "RooMsgService.h"
63#include "RooNumIntConfig.h"
64#include "RooNumRunningInt.h"
65#include "RooParamBinning.h"
66#include "RooPlot.h"
67#include "RooProduct.h"
68#include "RooProfileLL.h"
69#include "RooRealBinding.h"
70#include "RooRealIntegral.h"
71#include "RooRealVar.h"
72#include "RooSecondMoment.h"
73#include "RooVectorDataStore.h"
74#include "TreeReadBuffer.h"
75#include "ValueChecking.h"
76
77#include "ROOT/StringUtils.hxx"
78#include "Compression.h"
79#include "Math/IFunction.h"
80#include "TMath.h"
81#include "TTree.h"
82#include "TH1.h"
83#include "TH2.h"
84#include "TH3.h"
85#include "TBranch.h"
86#include "TLeaf.h"
87#include "TAttLine.h"
88#include "TF1.h"
89#include "TF2.h"
90#include "TF3.h"
91#include "TMatrixD.h"
92#include "TVector.h"
93#include "strlcpy.h"
94#ifndef NDEBUG
95#include <TSystem.h> // To print stack traces when caching errors are detected
96#endif
97
98#include <iomanip>
99#include <iostream>
100#include <limits>
101#include <mutex>
102#include <set>
103#include <sstream>
104#include <sys/types.h>
105
106namespace {
107
108// Internal helper RooAbsFunc that evaluates the scaled data-weighted average of
109// given RooAbsReal as a function of a single variable using the RooFit::Evaluator.
110class ScaledDataWeightedAverage : public RooAbsFunc {
111public:
112 ScaledDataWeightedAverage(RooAbsReal const &arg, RooAbsData const &data, double scaleFactor, RooAbsRealLValue &var)
113 : RooAbsFunc{1}, _var{var}, _dataWeights{data.getWeightBatch(0, data.numEntries())}, _scaleFactor{scaleFactor}
114 {
115 _arg = RooFit::Detail::compileForNormSet(arg, *data.get());
116 _arg->recursiveRedirectServers(RooArgList{var});
117 _evaluator = std::make_unique<RooFit::Evaluator>(*_arg);
118 std::stack<std::vector<double>>{}.swap(_vectorBuffers);
119 auto dataSpans = RooFit::BatchModeDataHelpers::getDataSpans(data, "", nullptr, /*skipZeroWeights=*/false,
120 /*takeGlobalObservablesFromData=*/true,
121 _vectorBuffers);
122 for (auto const& item : dataSpans) {
123 _evaluator->setInput(item.first->GetName(), item.second, false);
124 }
125 }
126
127 double operator()(const double xvector[]) const override
128 {
129 double oldVal = _var.getVal();
130 _var.setVal(xvector[0]);
131
132 double out = 0.0;
133 std::span<const double> pdfValues = _evaluator->run();
134 if (_dataWeights.empty()) {
135 out = std::accumulate(pdfValues.begin(), pdfValues.end(), 0.0) / pdfValues.size();
136 } else {
137 double weightsSum = 0.0;
138 for (std::size_t i = 0; i < pdfValues.size(); ++i) {
139 out += pdfValues[i] * _dataWeights[i];
140 weightsSum += _dataWeights[i];
141 }
142 out /= weightsSum;
143 }
144 out *= _scaleFactor;
145
146 _var.setVal(oldVal);
147 return out;
148 }
149 double getMinLimit(UInt_t /*dimension*/) const override { return _var.getMin(); }
150 double getMaxLimit(UInt_t /*dimension*/) const override { return _var.getMax(); }
151
152private:
153 RooAbsRealLValue &_var;
154 std::unique_ptr<RooAbsReal> _arg;
155 std::span<const double> _dataWeights;
156 double _scaleFactor;
157 std::unique_ptr<RooFit::Evaluator> _evaluator;
158 std::stack<std::vector<double>> _vectorBuffers;
159};
160
161struct EvalErrorData {
162 using ErrorList = std::map<const RooAbsArg *, std::pair<std::string, std::list<RooAbsReal::EvalError>>>;
164 int count = 0;
165 ErrorList errorList;
166};
167
168EvalErrorData &evalErrorData()
169{
170 static EvalErrorData data;
171 return data;
172}
173
174} // namespace
175
177{
178 return evalErrorData().errorList.size();
179}
180
181EvalErrorData::ErrorList::iterator RooAbsReal::evalErrorIter()
182{
183 return evalErrorData().errorList.begin();
184}
185
186
189
192
193
194////////////////////////////////////////////////////////////////////////////////
195/// coverity[UNINIT_CTOR]
196/// Default constructor
197
199
200
201////////////////////////////////////////////////////////////////////////////////
202/// Constructor with unit label
203
204RooAbsReal::RooAbsReal(const char *name, const char *title, const char *unit) : RooAbsReal{name, title, 0.0, 0.0, unit}
205{
206}
207
208
209////////////////////////////////////////////////////////////////////////////////
210/// Constructor with plot range and unit label
211
212RooAbsReal::RooAbsReal(const char *name, const char *title, double inMinVal,
213 double inMaxVal, const char *unit) :
214 RooAbsArg(name,title), _plotMin(inMinVal), _plotMax(inMaxVal), _unit(unit)
215{
216 setValueDirty() ;
217 setShapeDirty() ;
218}
219
220
221////////////////////////////////////////////////////////////////////////////////
222/// Copy constructor
224 RooAbsArg(other,name), _plotMin(other._plotMin), _plotMax(other._plotMax),
225 _plotBins(other._plotBins), _value(other._value), _unit(other._unit), _label(other._label),
226 _forceNumInt(other._forceNumInt), _selectComp(other._selectComp)
227{
228 if (other._specIntegratorConfig) {
229 _specIntegratorConfig = std::make_unique<RooNumIntConfig>(*other._specIntegratorConfig) ;
230 }
231}
232
233
234////////////////////////////////////////////////////////////////////////////////
235/// Destructor
236
238{
239 if (_treeReadBuffer) {
240 delete _treeReadBuffer;
241 }
242 _treeReadBuffer = nullptr;
243}
244
245
246////////////////////////////////////////////////////////////////////////////////
247/// Equality operator comparing to a double
248
250{
251 return (getVal()==value) ;
252}
253
254
255
256////////////////////////////////////////////////////////////////////////////////
257/// Equality operator when comparing to another RooAbsArg.
258/// Only functional when the other arg is a RooAbsReal
259
261{
262 const RooAbsReal* otherReal = dynamic_cast<const RooAbsReal*>(&other) ;
263 return otherReal ? operator==(otherReal->getVal()) : false ;
264}
265
266
267////////////////////////////////////////////////////////////////////////////////
268
270{
271 if (!assumeSameType) {
272 const RooAbsReal* otherReal = dynamic_cast<const RooAbsReal*>(&other) ;
273 return otherReal ? operator==(otherReal->getVal()) : false ;
274 } else {
275 return getVal() == static_cast<const RooAbsReal&>(other).getVal();
276 }
277}
278
279
280////////////////////////////////////////////////////////////////////////////////
281/// Return this variable's title string. If appendUnit is true and
282/// this variable has units, also append a string " (<unit>)".
283
285{
286 if(appendUnit && 0 != strlen(getUnit())) {
287 return std::string{GetTitle()} + " (" + getUnit() + ")";
288 }
289 return GetTitle();
290}
291
292
293
294////////////////////////////////////////////////////////////////////////////////
295/// Return value of object. If the cache is clean, return the
296/// cached value, otherwise recalculate on the fly and refill
297/// the cache
298
299double RooAbsReal::getValV(const RooArgSet* nset) const
300{
301 if (nset && nset->uniqueId().value() != _lastNormSetId) {
302 const_cast<RooAbsReal*>(this)->setProxyNormSet(nset);
303 _lastNormSetId = nset->uniqueId().value();
304 }
305
306 if (isValueDirtyAndClear()) {
307 _value = traceEval(nullptr) ;
308 // clearValueDirty() ;
309 }
310
311 return hideOffset() ? _value + offset() : _value;
312}
313
314
315////////////////////////////////////////////////////////////////////////////////
316/// Calculate current value of object, with error tracing wrapper
317
318double RooAbsReal::traceEval(const RooArgSet* /*nset*/) const
319{
320 double value = evaluate() ;
321
322 if (TMath::IsNaN(value)) {
323 logEvalError("function value is NAN") ;
324 }
325
326 //cxcoutD(Tracing) << "RooAbsReal::getValF(" << GetName() << ") operMode = " << _operMode << " recalculated, new value = " << value << std::endl ;
327
328 //Standard tracing code goes here
329 if (!isValidReal(value)) {
330 coutW(Tracing) << "RooAbsReal::traceEval(" << GetName()
331 << "): validation failed: " << value << std::endl ;
332 }
333
334 //Call optional subclass tracing code
335 // traceEvalHook(value) ;
336
337 return value ;
338}
339
340
341
342////////////////////////////////////////////////////////////////////////////////
343/// Variant of getAnalyticalIntegral that is also passed the normalization set
344/// that should be applied to the integrand of which the integral is requested.
345/// For certain operator p.d.f it is useful to overload this function rather
346/// than analyticalIntegralWN() as the additional normalization information
347/// may be useful in determining a more efficient decomposition of the
348/// requested integral.
349
355
356
357
358////////////////////////////////////////////////////////////////////////////////
359/// Interface function getAnalyticalIntergral advertises the
360/// analytical integrals that are supported. 'integSet'
361/// is the set of dependents for which integration is requested. The
362/// function should copy the subset of dependents it can analytically
363/// integrate to anaIntSet and return a unique identification code for
364/// this integration configuration. If no integration can be
365/// performed, zero should be returned.
366
367Int_t RooAbsReal::getAnalyticalIntegral(RooArgSet& /*integSet*/, RooArgSet& /*anaIntSet*/, const char* /*rangeName*/) const
368{
369 return 0 ;
370}
371
372
373
374////////////////////////////////////////////////////////////////////////////////
375/// Implements the actual analytical integral(s) advertised by
376/// getAnalyticalIntegral. This functions will only be called with
377/// codes returned by getAnalyticalIntegral, except code zero.
378
379double RooAbsReal::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName) const
380{
381// std::cout << "RooAbsReal::analyticalIntegralWN(" << GetName() << ") code = " << code << " normSet = " << (normSet?*normSet:RooArgSet()) << std::endl ;
382 if (code==0) return getVal(normSet) ;
383 return analyticalIntegral(code,rangeName) ;
384}
385
386
387
388////////////////////////////////////////////////////////////////////////////////
389/// Implements the actual analytical integral(s) advertised by
390/// getAnalyticalIntegral. This functions will only be called with
391/// codes returned by getAnalyticalIntegral, except code zero.
392
393double RooAbsReal::analyticalIntegral(Int_t code, const char* /*rangeName*/) const
394{
395 // By default no analytical integrals are implemented
396 coutF(Eval) << "RooAbsReal::analyticalIntegral(" << GetName() << ") code " << code << " not implemented" << std::endl ;
397 return 0 ;
398}
399
400
401
402////////////////////////////////////////////////////////////////////////////////
403/// Get the label associated with the variable
404
405const char *RooAbsReal::getPlotLabel() const
406{
407 return _label.IsNull() ? fName.Data() : _label.Data();
408}
409
410
411
412////////////////////////////////////////////////////////////////////////////////
413/// Set the label associated with this variable
414
415void RooAbsReal::setPlotLabel(const char *label)
416{
417 _label= label;
418}
419
420
421
422////////////////////////////////////////////////////////////////////////////////
423///Read object contents from stream (dummy for now)
424
425bool RooAbsReal::readFromStream(std::istream& /*is*/, bool /*compact*/, bool /*verbose*/)
426{
427 return false ;
428}
429
430
431
432////////////////////////////////////////////////////////////////////////////////
433///Write object contents to stream (dummy for now)
434
435void RooAbsReal::writeToStream(std::ostream& /*os*/, bool /*compact*/) const
436{
437}
438
439
440
441////////////////////////////////////////////////////////////////////////////////
442/// Print object value
443
444void RooAbsReal::printValue(std::ostream& os) const
445{
446 os << getVal() ;
447}
448
449
450
451////////////////////////////////////////////////////////////////////////////////
452/// Structure printing
453
454void RooAbsReal::printMultiline(std::ostream& os, Int_t contents, bool verbose, TString indent) const
455{
456 RooAbsArg::printMultiline(os,contents,verbose,indent) ;
457 os << indent << "--- RooAbsReal ---" << std::endl;
458 TString unit(_unit);
459 if(!unit.IsNull()) unit.Prepend(' ');
460 //os << indent << " Value = " << getVal() << unit << std::endl;
461 os << std::endl << indent << " Plot label is \"" << getPlotLabel() << "\"" << "\n";
462}
463
464
465////////////////////////////////////////////////////////////////////////////////
466/// Create a RooProfileLL object that eliminates all nuisance parameters in the
467/// present function. The nuisance parameters are defined as all parameters
468/// of the function except the stated paramsOfInterest
469
471{
472 // Construct name of profile object
473 auto name = std::string(GetName()) + "_Profile[";
474 bool first = true;
475 for (auto const& arg : paramsOfInterest) {
476 if (first) {
477 first = false ;
478 } else {
479 name.append(",") ;
480 }
481 name.append(arg->GetName()) ;
482 }
483 name.append("]") ;
484
485 // Create and return profile object
486 auto out = std::make_unique<RooProfileLL>(name.c_str(),(std::string("Profile of ") + GetTitle()).c_str(),*this,paramsOfInterest);
487 return RooFit::makeOwningPtr<RooAbsReal>(std::move(out));
488}
489
490
491
492
493
494
495////////////////////////////////////////////////////////////////////////////////
496/// Create an object that represents the integral of the function over one or more observables listed in `iset`.
497/// The actual integration calculation is only performed when the returned object is evaluated. The name
498/// of the integral object is automatically constructed from the name of the input function, the variables
499/// it integrates and the range integrates over.
500///
501/// \note The integral over a PDF is usually not normalised (*i.e.*, it is usually not
502/// 1 when integrating the PDF over the full range). In fact, this integral is used *to compute*
503/// the normalisation of each PDF. See the [rf110 tutorial](group__tutorial__roofit.html)
504/// for details on PDF normalisation.
505///
506/// The following named arguments are accepted
507/// | | Effect on integral creation
508/// |--|-------------------------------
509/// | `NormSet(const RooArgSet&)` | Specify normalization set, mostly useful when working with PDFs
510/// | `NumIntConfig(const RooNumIntConfig&)` | Use given configuration for any numeric integration, if necessary
511/// | `Range(const char* name)` | Integrate only over given range. Multiple ranges may be specified by passing multiple Range() arguments
512
514 const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5,
515 const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const
516{
517 // Define configuration for this method
518 RooCmdConfig pc("RooAbsReal::createIntegral(" + std::string(GetName()) + ")");
519 pc.defineString("rangeName","RangeWithName",0,"",true) ;
520 pc.defineSet("normSet","NormSet",0,nullptr) ;
521 pc.defineObject("numIntConfig","NumIntConfig",0,nullptr) ;
522
523 // Process & check varargs
525 if (!pc.ok(true)) {
526 return nullptr;
527 }
528
529 // Extract values from named arguments
530 const char* rangeName = pc.getString("rangeName",nullptr,true) ;
531 const RooArgSet* nset = pc.getSet("normSet",nullptr);
532 const RooNumIntConfig* cfg = static_cast<const RooNumIntConfig*>(pc.getObject("numIntConfig",nullptr)) ;
533
534 return createIntegral(iset,nset,cfg,rangeName) ;
535}
536
537
538
539
540
541////////////////////////////////////////////////////////////////////////////////
542/// Create an object that represents the integral of the function over one or more observables listed in iset.
543/// The actual integration calculation is only performed when the return object is evaluated. The name
544/// of the integral object is automatically constructed from the name of the input function, the variables
545/// it integrates and the range integrates over. If nset is specified the integrand is request
546/// to be normalized over nset (only meaningful when the integrand is a pdf). If rangename is specified
547/// the integral is performed over the named range, otherwise it is performed over the domain of each
548/// integrated observable. If cfg is specified it will be used to configure any numeric integration
549/// aspect of the integral. It will not force the integral to be performed numerically, which is
550/// decided automatically by RooRealIntegral.
551
553 const RooNumIntConfig* cfg, const char* rangeName) const
554{
555 if (!rangeName || strchr(rangeName,',')==nullptr) {
556 // Simple case: integral over full range or single limited range
557 return createIntObj(iset,nset,cfg,rangeName);
558 }
559
560 // Integral over multiple ranges
561 std::vector<std::string> tokens = ROOT::Split(rangeName, ",");
562
564 std::stringstream errMsg;
565 errMsg << GetName() << " : integrating with respect to the variables " << iset << " on the ranges \"" << rangeName
566 << "\" is not possible because the ranges are overlapping";
567 const std::string errMsgString = errMsg.str();
568 coutE(Integration) << errMsgString << std::endl;
569 throw std::invalid_argument(errMsgString);
570 }
571
572 RooArgSet components ;
573 for (const std::string& token : tokens) {
574 components.addOwned(std::unique_ptr<RooAbsReal>{createIntObj(iset,nset,cfg, token.c_str())});
575 }
576
577 const std::string title = std::string("Integral of ") + GetTitle();
578 const std::string fullName = std::string(GetName()) + integralNameSuffix(iset,nset,rangeName).Data();
579
580 auto out = std::make_unique<RooAddition>(fullName.c_str(), title.c_str(), components);
581 out->addOwnedComponents(std::move(components));
582 return RooFit::makeOwningPtr<RooAbsReal>(std::move(out));
583}
584
585
586
587////////////////////////////////////////////////////////////////////////////////
588/// Internal utility function for createIntegral() that creates the actual integral object.
590 const RooNumIntConfig* cfg, const char* rangeName) const
591{
592 // Make internal use copies of iset and nset
594 const RooArgSet* nset = nset2 ;
595
596
597 // Initialize local variables perparing for recursive loop
598 bool error = false ;
599 const RooAbsReal* integrand = this ;
600 std::unique_ptr<RooAbsReal> integral;
601
602 // Handle trivial case of no integration here explicitly
603 if (iset.empty()) {
604
605 const std::string title = std::string("Integral of ") + GetTitle();
606 const std::string name = std::string(GetName()) + integralNameSuffix(iset,nset,rangeName).Data();
607
608 auto out = std::make_unique<RooRealIntegral>(name.c_str(), title.c_str(), *this, iset, nset, cfg, rangeName);
609 return RooFit::makeOwningPtr<RooAbsReal>(std::move(out));
610 }
611
612 // Process integration over remaining integration variables
613 while(!iset.empty()) {
614
615
616 // Find largest set of observables that can be integrated in one go
619
620 // If largest set of observables that can be integrated is empty set, problem was ill defined
621 // Postpone error messaging and handling to end of function, exit loop here
622 if (innerSet.empty()) {
623 error = true ;
624 break ;
625 }
626
627 // Prepare name and title of integral to be created
628 const std::string title = std::string("Integral of ") + integrand->GetTitle();
629 const std::string name = std::string(integrand->GetName()) + integrand->integralNameSuffix(innerSet,nset,rangeName).Data();
630
631 std::unique_ptr<RooAbsReal> innerIntegral = std::move(integral);
632
633 // Construct innermost integral
634 integral = std::make_unique<RooRealIntegral>(name.c_str(),title.c_str(),*integrand,innerSet,nset,cfg,rangeName);
635
636 // Integral of integral takes ownership of innermost integral
637 if (innerIntegral) {
638 integral->addOwnedComponents(std::move(innerIntegral));
639 }
640
641 // Remove already integrated observables from to-do list
642 iset.remove(innerSet) ;
643
644 // Send info message on recursion if needed
645 if (integrand == this && !iset.empty()) {
646 coutI(Integration) << GetName() << " : multidimensional integration over observables with parameterized ranges in terms of other integrated observables detected, using recursive integration strategy to construct final integral" << std::endl ;
647 }
648
649 // Prepare for recursion, next integral should integrate last integrand
650 integrand = integral.get();
651
652
653 // Only need normalization set in innermost integration
654 nset = nullptr;
655 }
656
657 if (error) {
658 coutE(Integration) << GetName() << " : ERROR while defining recursive integral over observables with parameterized integration ranges, please check that integration rangs specify uniquely defined integral " << std::endl;
659 return nullptr;
660 }
661
662
663 // After-burner: apply interpolating cache on (numeric) integral if requested by user
664 const char* cacheParamsStr = getStringAttribute("CACHEPARAMINT") ;
666
667 std::unique_ptr<RooArgSet> intParams{integral->getVariables()};
668
670
671 if (!cacheParams.empty()) {
672 cxcoutD(Caching) << "RooAbsReal::createIntObj(" << GetName() << ") INFO: constructing " << cacheParams.size()
673 << "-dim value cache for integral over " << iset2 << " as a function of " << cacheParams << " in range " << (rangeName?rangeName:"<none>") << std::endl ;
674 std::string name = std::string{integral->GetName()} + "_CACHE_[" + cacheParams.contentsString() + "]";
675 auto cachedIntegral = std::make_unique<RooCachedReal>(name.c_str(),name.c_str(),*integral,cacheParams);
676 cachedIntegral->setInterpolationOrder(2) ;
677 cachedIntegral->addOwnedComponents(std::move(integral));
678 cachedIntegral->setCacheSource(true) ;
679 if (integral->operMode()==ADirty) {
680 cachedIntegral->setOperMode(ADirty) ;
681 }
682 //cachedIntegral->disableCache(true) ;
683 return RooFit::makeOwningPtr<RooAbsReal>(std::move(cachedIntegral));
684 }
685 }
686
687 return RooFit::makeOwningPtr(std::move(integral));
688}
689
690
691
692////////////////////////////////////////////////////////////////////////////////
693/// Utility function for createIntObj() that aids in the construct of recursive integrals
694/// over functions with multiple observables with parameterized ranges. This function
695/// finds in a given set allObs over which integration is requested the largeset subset
696/// of observables that can be integrated simultaneously. This subset consists of
697/// observables with fixed ranges and observables with parameterized ranges whose
698/// parameterization does not depend on any observable that is also integrated.
699
701{
702 // Make lists of
703 // a) integrated observables with fixed ranges,
704 // b) integrated observables with parameterized ranges depending on other integrated observables
705 // c) integrated observables used in definition of any parameterized ranges of integrated observables
709
710 // Loop over all integrated observables
711 for (const auto aarg : allObs) {
712 // Check if observable is real-valued lvalue
713 if (auto arglv = dynamic_cast<RooAbsRealLValue*>(aarg)) {
714
715 // Check if range is parameterized
716 RooAbsBinning& binning = arglv->getBinning(rangeName,false,true) ;
717 if (binning.isParameterized()) {
720 binning.lowBoundFunc()->getObservables(&allObs, loBoundObs) ;
721 binning.highBoundFunc()->getObservables(&allObs, hiBoundObs) ;
722
723 // Check if range parameterization depends on other integrated observables
724 if (loBoundObs.overlaps(allObs) || hiBoundObs.overlaps(allObs)) {
725 obsWithParamRange.add(*aarg) ;
726 obsWithFixedRange.remove(*aarg) ;
729 }
730 }
731 }
732 }
733
734 // Make list of fixed-range observables that are _not_ involved in the parameterization of ranges of other observables
737
738 // Make list of param-range observables that are _not_ involved in the parameterization of ranges of other observables
741
742 // Construct inner-most integration: over observables (with fixed or param range) not used in any other param range definitions
743 innerObs.removeAll() ;
746
747}
748
749
750////////////////////////////////////////////////////////////////////////////////
751/// Construct string with unique suffix name to give to integral object that encodes
752/// integrated observables, normalization observables and the integration range name
753
755{
756 TString name ;
757 if (!iset.empty()) {
758 name.Append("_Int[" + RooHelpers::getColonSeparatedNameString(iset, ','));
759 if (rangeName) {
760 name.Append("|" + std::string{rangeName});
761 }
762 name.Append("]");
763 } else if (!omitEmpty) {
764 name.Append("_Int[]") ;
765 }
766
767 if (nset && !nset->empty()) {
768 name.Append("_Norm[" + RooHelpers::getColonSeparatedNameString(*nset, ','));
769 const RooAbsPdf* thisPdf = dynamic_cast<const RooAbsPdf*>(this) ;
770 if (thisPdf && thisPdf->normRange()) {
771 name.Append("|" + std::string{thisPdf->normRange()}) ;
772 }
773 name.Append("]") ;
774 }
775
776 return name ;
777}
778
779
780
781////////////////////////////////////////////////////////////////////////////////
782/// Utility function for plotOn() that creates a projection of a function or p.d.f
783/// to be plotted on a RooPlot.
784/// \ref createPlotProjAnchor "createPlotProjection()"
785
791
792
793////////////////////////////////////////////////////////////////////////////////
794/// Utility function for plotOn() that creates a projection of a function or p.d.f
795/// to be plotted on a RooPlot.
796/// \anchor createPlotProjAnchor
797///
798/// Create a new object \f$ G \f$ that represents the normalized projection:
799/// \f[
800/// G[x,p] = \frac{\int F[x,y,p] \; \mathrm{d}\{y\}}
801/// {\int F[x,y,p] \; \mathrm{d}\{x\} \, \mathrm{d}\{y\}}
802/// \f]
803/// where \f$ F[x,y,p] \f$ is the function we represent, and
804/// \f$ \{ p \} \f$ are the remaining variables ("parameters").
805///
806/// \param[in] dependentVars Dependent variables over which to normalise, \f$ \{x\} \f$.
807/// \param[in] projectedVars Variables to project out, \f$ \{ y \} \f$.
808/// \param[out] cloneSet Will be set to a RooArgSet*, which will contain a clone of *this plus its projection integral object.
809/// The latter will also be returned. The caller takes ownership of this set.
810/// \param[in] rangeName Optional range for projection integrals
811/// \param[in] condObs Conditional observables, which are not integrated for normalisation, even if they
812/// are in `dependentVars` or `projectedVars`.
813/// \return A pointer to the newly created object, or zero in case of an
814/// error. The caller is responsible for deleting the `cloneSet` (which includes the returned projection object).
816 RooArgSet *&cloneSet, const char* rangeName, const RooArgSet* condObs) const
817{
818 // Get the set of our leaf nodes
823
824
825 // Check that the dependents are all fundamental. Filter out any that we
826 // do not depend on, and make substitutions by name in our leaf list.
827 // Check for overlaps with the projection variables.
828 for (const auto arg : dependentVars) {
829 if(!arg->isFundamental() && !dynamic_cast<const RooAbsLValue*>(arg)) {
830 coutE(Plotting) << ClassName() << "::" << GetName() << ":createPlotProjection: variable \"" << arg->GetName()
831 << "\" of wrong type: " << arg->ClassName() << std::endl;
832 return nullptr;
833 }
834
835 RooAbsArg *found= treeNodes.find(arg->GetName());
836 if(!found) {
837 coutE(Plotting) << ClassName() << "::" << GetName() << ":createPlotProjection: \"" << arg->GetName()
838 << "\" is not a dependent and will be ignored." << std::endl;
839 continue;
840 }
841 if(found != arg) {
842 if (leafNodes.find(found->GetName())) {
843 leafNodes.replace(*found,*arg);
844 } else {
845 leafNodes.add(*arg) ;
846
847 // Remove any dependents of found, replace by dependents of LV node
850 for (const auto lvs : lvDep) {
851 RooAbsArg* tmp = leafNodes.find(lvs->GetName()) ;
852 if (tmp) {
853 leafNodes.remove(*tmp) ;
854 leafNodes.add(*lvs) ;
855 }
856 }
857 }
858 }
859
860 // check if this arg is also in the projection set
861 if(nullptr != projectedVars && projectedVars->find(arg->GetName())) {
862 coutE(Plotting) << ClassName() << "::" << GetName() << ":createPlotProjection: \"" << arg->GetName()
863 << "\" cannot be both a dependent and a projected variable." << std::endl;
864 return nullptr;
865 }
866 }
867
868 // Remove the projected variables from the list of leaf nodes, if necessary.
869 if(nullptr != projectedVars) leafNodes.remove(*projectedVars,true);
870
871 // Make a deep-clone of ourself so later operations do not disturb our original state
872 cloneSet = new RooArgSet;
873 if (RooArgSet(*this).snapshot(*cloneSet, true)) {
874 coutE(Plotting) << "RooAbsPdf::createPlotProjection(" << GetName() << ") Couldn't deep-clone PDF, abort," << std::endl ;
875 return nullptr ;
876 }
877 RooAbsReal *theClone= static_cast<RooAbsReal*>(cloneSet->find(GetName()));
878
879 // The remaining entries in our list of leaf nodes are the external
880 // dependents (x) and parameters (p) of the projection. Patch them back
881 // into the theClone. This orphans the nodes they replace, but the orphans
882 // are still in the cloneList and so will be cleaned up eventually.
883 //cout << "redirection leafNodes : " ; leafNodes.Print("1") ;
884
885 std::unique_ptr<RooArgSet> plotLeafNodes{leafNodes.selectCommon(dependentVars)};
886 theClone->recursiveRedirectServers(*plotLeafNodes,false,false,false);
887
888 // Create the set of normalization variables to use in the projection integrand
890 if(nullptr != projectedVars) normSet.add(*projectedVars);
891 if(nullptr != condObs) {
892 normSet.remove(*condObs,true,true) ;
893 }
894
895 // Try to create a valid projection integral. If no variables are to be projected,
896 // create a null projection anyway to bind our normalization over the dependents
897 // consistently with the way they would be bound with a non-trivial projection.
898 RooArgSet empty;
899 if(nullptr == projectedVars) projectedVars= &empty;
900
901 std::string name = GetName();
903
904 std::string title = std::string{"Projection of "} + GetTitle();
905
906 std::unique_ptr<RooAbsReal> projected{theClone->createIntegral(*projectedVars,normSet,rangeName)};
907
908 if(nullptr == projected || !projected->isValid()) {
909 coutE(Plotting) << ClassName() << "::" << GetName() << ":createPlotProjection: cannot integrate out ";
910 projectedVars->printStream(std::cout,kName|kArgs,kSingleLine);
911 return nullptr;
912 }
913
914 if(projected->InheritsFrom(RooRealIntegral::Class())){
915 static_cast<RooRealIntegral&>(*projected).setAllowComponentSelection(true);
916 }
917
918 projected->SetName(name.c_str()) ;
919 projected->SetTitle(title.c_str()) ;
920
921 // Add the projection integral to the cloneSet so that it eventually gets cleaned up by the caller.
923 cloneSet->addOwned(std::move(projected));
924
925 // return a const pointer to remind the caller that they do not delete the returned object
926 // directly (it is contained in the cloneSet instead).
927 return projectedPtr;
928}
929
930
931
932////////////////////////////////////////////////////////////////////////////////
933/// Fill the ROOT histogram 'hist' with values sampled from this
934/// function at the bin centers. Our value is calculated by first
935/// integrating out any variables in projectedVars and then scaling
936/// the result by scaleFactor. Returns a pointer to the input
937/// histogram, or zero in case of an error. The input histogram can
938/// be any TH1 subclass, and therefore of arbitrary
939/// dimension. Variables are matched with the (x,y,...) dimensions of
940/// the input histogram according to the order in which they appear
941/// in the input plotVars list. If scaleForDensity is true the
942/// histogram is filled with a the functions density rather than
943/// the functions value (i.e. the value at the bin center is multiplied
944/// with bin volume)
945
947 double scaleFactor, const RooArgSet *projectedVars, bool scaleForDensity,
948 const RooArgSet* condObs, bool setError) const
949{
950 // Do we have a valid histogram to use?
951 if(nullptr == hist) {
952 coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: no valid histogram to fill" << std::endl;
953 return nullptr;
954 }
955
956 // Check that the number of plotVars matches the input histogram's dimension
957 Int_t hdim= hist->GetDimension();
958 if(hdim != int(plotVars.size())) {
959 coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: plotVars has the wrong dimension" << std::endl;
960 return nullptr;
961 }
962
963
964 // Check that the plot variables are all actually RooRealVars and print a warning if we do not
965 // explicitly depend on one of them. Fill a set (not list!) of cloned plot variables.
967 for(std::size_t index= 0; index < plotVars.size(); index++) {
968 const RooAbsArg *var= plotVars.at(index);
969 const RooRealVar *realVar= dynamic_cast<const RooRealVar*>(var);
970 if(nullptr == realVar) {
971 coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot plot variable \"" << var->GetName()
972 << "\" of type " << var->ClassName() << std::endl;
973 return nullptr;
974 }
975 if(!this->dependsOn(*realVar)) {
976 coutE(InputArguments) << ClassName() << "::" << GetName()
977 << ":fillHistogram: WARNING: variable is not an explicit dependent: " << realVar->GetName() << std::endl;
978 }
979 plotClones.addClone(*realVar,true); // do not complain about duplicates
980 }
981
982 // Reconnect all plotClones to each other, imported when plotting N-dim integrals with entangled parameterized ranges
983 for(RooAbsArg * pc : plotClones) {
984 pc->recursiveRedirectServers(plotClones,false,false,true) ;
985 }
986
987 // Call checkObservables
989 if (projectedVars) {
990 allDeps.add(*projectedVars) ;
991 }
993 coutE(InputArguments) << "RooAbsReal::fillHistogram(" << GetName() << ") error in checkObservables, abort" << std::endl ;
994 return hist ;
995 }
996
997 // Create a standalone projection object to use for calculating bin contents
998 RooArgSet *cloneSet = nullptr;
1000
1001 cxcoutD(Plotting) << "RooAbsReal::fillHistogram(" << GetName() << ") plot projection object is " << projected->GetName() << std::endl ;
1002
1003 // Prepare to loop over the histogram bins
1004 Int_t xbins(0);
1005 Int_t ybins(1);
1006 Int_t zbins(1);
1007 RooRealVar *xvar = nullptr;
1008 RooRealVar *yvar = nullptr;
1009 RooRealVar *zvar = nullptr;
1010 TAxis *xaxis = nullptr;
1011 TAxis *yaxis = nullptr;
1012 TAxis *zaxis = nullptr;
1013 switch(hdim) {
1014 case 3:
1015 zbins= hist->GetNbinsZ();
1016 zvar= dynamic_cast<RooRealVar*>(plotClones.find(plotVars.at(2)->GetName()));
1017 zaxis= hist->GetZaxis();
1018 assert(nullptr != zvar && nullptr != zaxis);
1019 // fall through to next case...
1020 case 2:
1021 ybins= hist->GetNbinsY();
1022 yvar= dynamic_cast<RooRealVar*>(plotClones.find(plotVars.at(1)->GetName()));
1023 yaxis= hist->GetYaxis();
1024 assert(nullptr != yvar && nullptr != yaxis);
1025 // fall through to next case...
1026 case 1:
1027 xbins= hist->GetNbinsX();
1028 xvar= dynamic_cast<RooRealVar*>(plotClones.find(plotVars.at(0)->GetName()));
1029 xaxis= hist->GetXaxis();
1030 assert(nullptr != xvar && nullptr != xaxis);
1031 break;
1032 default:
1033 coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillHistogram: cannot fill histogram with "
1034 << hdim << " dimensions" << std::endl;
1035 break;
1036 }
1037
1038 // Loop over the input histogram's bins and fill each one with our projection's
1039 // value, calculated at the center.
1041 Int_t xbin(0);
1042 Int_t ybin(0);
1043 Int_t zbin(0);
1044 Int_t bins= xbins*ybins*zbins;
1045 for(Int_t bin= 0; bin < bins; bin++) {
1046 switch(hdim) {
1047 case 3:
1048 if(bin % (xbins*ybins) == 0) {
1049 zbin++;
1050 zvar->setVal(zaxis->GetBinCenter(zbin));
1051 }
1052 // fall through to next case...
1053 case 2:
1054 if(bin % xbins == 0) {
1055 ybin= (ybin%ybins) + 1;
1056 yvar->setVal(yaxis->GetBinCenter(ybin));
1057 }
1058 // fall through to next case...
1059 case 1:
1060 xbin= (xbin%xbins) + 1;
1061 xvar->setVal(xaxis->GetBinCenter(xbin));
1062 break;
1063 default:
1064 coutE(InputArguments) << "RooAbsReal::fillHistogram: Internal Error!" << std::endl;
1065 break;
1066 }
1067
1068 // Bin volume scaling
1069 double scaleFactorBin = scaleFactor;
1070 scaleFactorBin *= scaleForDensity && hdim > 2 ? hist->GetZaxis()->GetBinWidth(zbin) : 1.0;
1071 scaleFactorBin *= scaleForDensity && hdim > 1 ? hist->GetYaxis()->GetBinWidth(ybin) : 1.0;
1072 scaleFactorBin *= scaleForDensity && hdim > 0 ? hist->GetXaxis()->GetBinWidth(xbin) : 1.0;
1073
1074 double result= scaleFactorBin * projected->getVal();
1075 if (RooAbsReal::numEvalErrors()>0) {
1076 coutW(Plotting) << "WARNING: Function evaluation error(s) at coordinates [x]=" << xvar->getVal() ;
1077 if (hdim==2) ccoutW(Plotting) << " [y]=" << yvar->getVal() ;
1078 if (hdim==3) ccoutW(Plotting) << " [z]=" << zvar->getVal() ;
1079 ccoutW(Plotting) << std::endl ;
1080 // RooAbsReal::printEvalErrors(ccoutW(Plotting),10) ;
1081 result = 0 ;
1082 }
1084
1085 hist->SetBinContent(hist->GetBin(xbin,ybin,zbin),result);
1086 if (setError) {
1087 hist->SetBinError(hist->GetBin(xbin,ybin,zbin),sqrt(result)) ;
1088 }
1089
1090 //cout << "bin " << bin << " -> (" << xbin << "," << ybin << "," << zbin << ") = " << result << std::endl;
1091 }
1093
1094 // cleanup
1095 delete cloneSet;
1096
1097 return hist;
1098}
1099
1100
1101
1102////////////////////////////////////////////////////////////////////////////////
1103/// Fill a RooDataHist with values sampled from this function at the
1104/// bin centers. If extendedMode is true, the p.d.f. values is multiplied
1105/// by the number of expected events in each bin
1106///
1107/// An optional scaling by a given scaleFactor can be performed.
1108/// Returns a pointer to the input RooDataHist, or zero
1109/// in case of an error.
1110///
1111/// If correctForBinSize is true the RooDataHist
1112/// is filled with the functions density (function value times the
1113/// bin volume) rather than function value.
1114///
1115/// If showProgress is true
1116/// a process indicator is printed on stdout in steps of one percent,
1117/// which is mostly useful for the sampling of expensive functions
1118/// such as likelihoods
1119
1121 bool correctForBinSize, bool showProgress) const
1122{
1123 // Do we have a valid histogram to use?
1124 if(nullptr == hist) {
1125 coutE(InputArguments) << ClassName() << "::" << GetName() << ":fillDataHist: no valid RooDataHist to fill" << std::endl;
1126 return nullptr;
1127 }
1128
1129 // Call checkObservables
1130 RooArgSet allDeps(*hist->get()) ;
1131 if (checkObservables(&allDeps)) {
1132 coutE(InputArguments) << "RooAbsReal::fillDataHist(" << GetName() << ") error in checkObservables, abort" << std::endl ;
1133 return hist ;
1134 }
1135
1136 // Make deep clone of self and attach to dataset observables
1137 //RooArgSet* origObs = getObservables(hist) ;
1139 RooArgSet(*this).snapshot(cloneSet, true);
1140 RooAbsReal* theClone = static_cast<RooAbsReal*>(cloneSet.find(GetName()));
1141 theClone->recursiveRedirectServers(*hist->get()) ;
1142 //const_cast<RooAbsReal*>(this)->recursiveRedirectServers(*hist->get()) ;
1143
1144 // Iterator over all bins of RooDataHist and fill weights
1145 Int_t onePct = hist->numEntries()/100 ;
1146 if (onePct==0) {
1147 onePct++ ;
1148 }
1149 for (Int_t i=0 ; i<hist->numEntries() ; i++) {
1150 if (showProgress && (i%onePct==0)) {
1151 ccoutP(Eval) << "." << std::flush ;
1152 }
1153 const RooArgSet* obs = hist->get(i) ;
1154 double binVal = theClone->getVal(normSet?normSet:obs)*scaleFactor ;
1155 if (correctForBinSize) {
1156 binVal*= hist->binVolume(i) ;
1157 }
1158 hist->set(i, binVal, 0.);
1159 }
1160
1161 return hist;
1162}
1163
1164
1165
1166
1167////////////////////////////////////////////////////////////////////////////////
1168/// Create and fill a ROOT histogram TH1, TH2 or TH3 with the values of this function for the variables with given names.
1169/// \param[in] varNameList List of variables to use for x, y, z axis, separated by ':'
1170/// \param[in] xbins Number of bins for first variable
1171/// \param[in] ybins Number of bins for second variable
1172/// \param[in] zbins Number of bins for third variable
1173/// \return TH1*, which is one of TH[1-3]. The histogram is owned by the caller.
1174///
1175/// For a greater degree of control use
1176/// RooAbsReal::createHistogram(const char *, const RooAbsRealLValue&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&) const
1177///
1178
1180{
1181 std::unique_ptr<RooArgSet> vars{getVariables()};
1182
1183 auto varNames = ROOT::Split(varNameList, ",:");
1184 std::vector<RooRealVar*> histVars(3, nullptr);
1185
1186 for(std::size_t iVar = 0; iVar < varNames.size(); ++iVar) {
1187 if(varNames[iVar].empty()) continue;
1188 if(iVar >= 3) {
1189 std::stringstream errMsg;
1190 errMsg << "RooAbsPdf::createHistogram(" << GetName() << ") ERROR more than three variable names passed, but maximum number of supported variables is three";
1191 coutE(Plotting) << errMsg.str() << std::endl;
1192 throw std::invalid_argument(errMsg.str());
1193 }
1194 auto var = static_cast<RooRealVar*>(vars->find(varNames[iVar].c_str()));
1195 if(!var) {
1196 std::stringstream errMsg;
1197 errMsg << "RooAbsPdf::createHistogram(" << GetName() << ") ERROR variable " << varNames[iVar] << " does not exist in argset: " << *vars;
1198 coutE(Plotting) << errMsg.str() << std::endl;
1199 throw std::runtime_error(errMsg.str());
1200 }
1201 histVars[iVar] = var;
1202 }
1203
1204 // Construct list of named arguments to pass to the implementation version of createHistogram()
1205
1206 RooLinkedList argList ;
1207 if (xbins>0) {
1208 argList.Add(RooFit::Binning(xbins).Clone()) ;
1209 }
1210
1211 if (histVars[1]) {
1213 }
1214
1215 if (histVars[2]) {
1217 }
1218
1219 // Call implementation function
1220 TH1* result = createHistogram(GetName(), *histVars[0], argList) ;
1221
1222 // Delete temporary list of RooCmdArgs
1223 argList.Delete() ;
1224
1225 return result ;
1226}
1227
1228
1229#define CREATE_CMD_LIST \
1230 RooLinkedList l; \
1231 l.Add((TObject *)&arg1); \
1232 l.Add((TObject *)&arg2); \
1233 l.Add((TObject *)&arg3); \
1234 l.Add((TObject *)&arg4); \
1235 l.Add((TObject *)&arg5); \
1236 l.Add((TObject *)&arg6); \
1237 l.Add((TObject *)&arg7); \
1238 l.Add((TObject *)&arg8);
1239
1240
1241////////////////////////////////////////////////////////////////////////////////
1242/// Create and fill a ROOT histogram TH1, TH2 or TH3 with the values of this function.
1243///
1244/// \param[in] name Name of the ROOT histogram
1245/// \param[in] xvar Observable to be std::mapped on x axis of ROOT histogram
1246/// \param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 Arguments according to list below
1247/// \return TH1 *, one of TH{1,2,3}. The caller takes ownership.
1248///
1249/// <table>
1250/// <tr><th><th> Effect on histogram creation
1251/// <tr><td> `IntrinsicBinning()` <td> Apply binning defined by function or pdf (as advertised via binBoundaries() method)
1252/// <tr><td> `Binning(const char* name)` <td> Apply binning with given name to x axis of histogram
1253/// <tr><td> `Binning(RooAbsBinning& binning)` <td> Apply specified binning to x axis of histogram
1254/// <tr><td> `Binning(int nbins, [double lo, double hi])` <td> Apply specified binning to x axis of histogram
1255/// <tr><td> `ConditionalObservables(Args_t &&... argsOrArgSet)` <td> Do not normalise PDF over following observables when projecting PDF into histogram.
1256// Arguments can either be multiple RooRealVar or a single RooArgSet containing them.
1257/// <tr><td> `Scaling(bool)` <td> Apply density-correction scaling (multiply by bin volume), default is true
1258/// <tr><td> `Extended(bool)` <td> Plot event yield instead of probability density (for extended pdfs only)
1259///
1260/// <tr><td> `YVar(const RooAbsRealLValue& var,...)` <td> Observable to be std::mapped on y axis of ROOT histogram.
1261/// The YVar() and ZVar() arguments can be supplied with optional Binning() arguments to control the binning of the Y and Z axes, e.g.
1262/// ```
1263/// createHistogram("histo",x,Binning(-1,1,20), YVar(y,Binning(-1,1,30)), ZVar(z,Binning("zbinning")))
1264/// ```
1265/// <tr><td> `ZVar(const RooAbsRealLValue& var,...)` <td> Observable to be std::mapped on z axis of ROOT histogram
1266/// </table>
1267///
1268///
1269
1271 const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
1272 const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8) const
1273{
1275 return createHistogram(name,xvar,l) ;
1276}
1277
1278
1279////////////////////////////////////////////////////////////////////////////////
1280/// Internal method implementing createHistogram
1281
1283{
1284
1285 // Define configuration for this method
1286 RooCmdConfig pc("RooAbsReal::createHistogram(" + std::string(GetName()) + ")");
1287 pc.defineInt("scaling","Scaling",0,1) ;
1288 pc.defineInt("intBinning","IntrinsicBinning",0,2) ;
1289 pc.defineInt("extended","Extended",0,2) ;
1290
1291 pc.defineSet("compSet","SelectCompSet",0);
1292 pc.defineString("compSpec","SelectCompSpec",0) ;
1293 pc.defineSet("projObs","ProjectedObservables",0,nullptr) ;
1294 pc.defineObject("yvar","YVar",0,nullptr) ;
1295 pc.defineObject("zvar","ZVar",0,nullptr) ;
1296 pc.defineMutex("SelectCompSet","SelectCompSpec") ;
1297 pc.defineMutex("IntrinsicBinning","Binning") ;
1298 pc.defineMutex("IntrinsicBinning","BinningName") ;
1299 pc.defineMutex("IntrinsicBinning","BinningSpec") ;
1300 pc.allowUndefined() ;
1301
1302 // Process & check varargs
1303 pc.process(argList) ;
1304 if (!pc.ok(true)) {
1305 return nullptr ;
1306 }
1307
1308 RooArgList vars(xvar) ;
1309 RooAbsArg* yvar = static_cast<RooAbsArg*>(pc.getObject("yvar")) ;
1310 if (yvar) {
1311 vars.add(*yvar) ;
1312 }
1313 RooAbsArg* zvar = static_cast<RooAbsArg*>(pc.getObject("zvar")) ;
1314 if (zvar) {
1315 vars.add(*zvar) ;
1316 }
1317
1318 auto projObs = pc.getSet("projObs");
1319 RooArgSet* intObs = nullptr ;
1320
1321 bool doScaling = pc.getInt("scaling") ;
1322 Int_t doIntBinning = pc.getInt("intBinning") ;
1323 Int_t doExtended = pc.getInt("extended") ;
1324
1325 // If doExtended is two, selection is automatic, set to 1 of pdf is extended, to zero otherwise
1326 const RooAbsPdf* pdfSelf = dynamic_cast<const RooAbsPdf*>(this) ;
1327 if (!pdfSelf && doExtended == 1) {
1328 coutW(InputArguments) << "RooAbsReal::createHistogram(" << GetName() << ") WARNING extended mode requested for a non-pdf object, ignored" << std::endl ;
1329 doExtended=0 ;
1330 }
1331 if (pdfSelf && doExtended==1 && pdfSelf->extendMode()==RooAbsPdf::CanNotBeExtended) {
1332 coutW(InputArguments) << "RooAbsReal::createHistogram(" << GetName() << ") WARNING extended mode requested for a non-extendable pdf, ignored" << std::endl ;
1333 doExtended=0 ;
1334 }
1335 if (pdfSelf && doExtended==2) {
1336 doExtended = pdfSelf->extendMode()==RooAbsPdf::CanNotBeExtended ? 0 : 1 ;
1337 } else if(!pdfSelf) {
1338 doExtended = 0;
1339 }
1340
1341 const char* compSpec = pc.getString("compSpec") ;
1342 const RooArgSet* compSet = pc.getSet("compSet");
1343 bool haveCompSel = ( (compSpec && strlen(compSpec)>0) || compSet) ;
1344
1345 std::unique_ptr<RooBinning> intBinning;
1346 if (doIntBinning>0) {
1347 // Given RooAbsPdf* pdf and RooRealVar* obs
1348 std::unique_ptr<std::list<double>> bl{binBoundaries(const_cast<RooAbsRealLValue&>(xvar),xvar.getMin(),xvar.getMax())};
1349 if (!bl) {
1350 // Only emit warning when intrinsic binning is explicitly requested
1351 if (doIntBinning==1) {
1352 coutW(InputArguments) << "RooAbsReal::createHistogram(" << GetName()
1353 << ") WARNING, intrinsic model binning requested for histogram, but model does not define bin boundaries, reverting to default binning"<< std::endl ;
1354 }
1355 } else {
1356 if (doIntBinning==2) {
1357 coutI(InputArguments) << "RooAbsReal::createHistogram(" << GetName()
1358 << ") INFO: Model has intrinsic binning definition, selecting that binning for the histogram"<< std::endl ;
1359 }
1360 std::vector<double> edges(bl->size());
1361 int i=0 ;
1362 for (auto const& elem : *bl) { edges[i++] = elem ; }
1363 intBinning = std::make_unique<RooBinning>(bl->size()-1,edges.data()) ;
1364 }
1365 }
1366
1367 RooLinkedList argListCreate(argList) ;
1368 RooCmdConfig::stripCmdList(argListCreate,"Scaling,ProjectedObservables,IntrinsicBinning,SelectCompSet,SelectCompSpec,Extended") ;
1369
1370 TH1* histo(nullptr) ;
1371 if (intBinning) {
1373 argListCreate.Add(&tmp) ;
1374 histo = xvar.createHistogram(name,argListCreate) ;
1375 } else {
1376 histo = xvar.createHistogram(name,argListCreate) ;
1377 }
1378
1379 // Do component selection here
1380 if (haveCompSel) {
1381
1382 // Get complete set of tree branch nodes
1385
1386 // Discard any non-RooAbsReal nodes
1387 for(RooAbsArg * arg : branchNodeSet) {
1388 if (!dynamic_cast<RooAbsReal*>(arg)) {
1389 branchNodeSet.remove(*arg) ;
1390 }
1391 }
1392
1393 std::unique_ptr<RooArgSet> dirSelNodes;
1394 if (compSet) {
1395 dirSelNodes = std::unique_ptr<RooArgSet>{branchNodeSet.selectCommon(*compSet)};
1396 } else {
1397 dirSelNodes = std::unique_ptr<RooArgSet>{branchNodeSet.selectByName(compSpec)};
1398 }
1399 if (!dirSelNodes->empty()) {
1400 coutI(Plotting) << "RooAbsPdf::createHistogram(" << GetName() << ") directly selected PDF components: " << *dirSelNodes << std::endl ;
1401
1402 // Do indirect selection and activate both
1404 } else {
1405 if (compSet) {
1406 coutE(Plotting) << "RooAbsPdf::createHistogram(" << GetName() << ") ERROR: component selection set " << *compSet << " does not match any components of p.d.f." << std::endl ;
1407 } else {
1408 coutE(Plotting) << "RooAbsPdf::createHistogram(" << GetName() << ") ERROR: component selection expression '" << compSpec << "' does not select any components of p.d.f." << std::endl ;
1409 }
1410 return nullptr ;
1411 }
1412 }
1413
1414 double scaleFactor(1.0) ;
1415 if (doExtended) {
1416 scaleFactor = pdfSelf->expectedEvents(vars);
1417 }
1418
1419 fillHistogram(histo,vars,scaleFactor,intObs,doScaling,projObs,false) ;
1420
1421 // Deactivate component selection
1422 if (haveCompSel) {
1423 plotOnCompSelect(nullptr) ;
1424 }
1425
1426
1427 return histo ;
1428}
1429
1430
1431////////////////////////////////////////////////////////////////////////////////
1432/// Helper function for plotting of composite p.d.fs. Given
1433/// a set of selected components that should be plotted,
1434/// find all nodes that (in)directly depend on these selected
1435/// nodes. Mark all directly and indirectly selected nodes
1436/// as 'selected' using the selectComp() method
1437
1439{
1440 // Get complete set of tree branch nodes
1443
1444 // Discard any non-PDF nodes
1445 // Iterate by number because collection is being modified! Iterators may invalidate ...
1446 for (unsigned int i = 0; i < branchNodeSet.size(); ++i) {
1447 const auto arg = branchNodeSet[i];
1448 if (!dynamic_cast<RooAbsReal*>(arg)) {
1449 branchNodeSet.remove(*arg) ;
1450 }
1451 }
1452
1453 // If no set is specified, restored all selection bits to true
1454 if (!selNodes) {
1455 // Reset PDF selection bits to true
1456 for (const auto arg : branchNodeSet) {
1457 static_cast<RooAbsReal*>(arg)->selectComp(true);
1458 }
1459 return ;
1460 }
1461
1462
1463 // Add all nodes below selected nodes that are value servers
1464 RooArgSet tmp;
1465 for (const auto arg : branchNodeSet) {
1466 for (const auto selNode : *selNodes) {
1467 if (selNode->dependsOn(*arg, nullptr, /*valueOnly=*/true)) {
1468 tmp.add(*arg,true);
1469 }
1470 }
1471 }
1472
1473 // Add all nodes that depend on selected nodes by value
1474 for (const auto arg : branchNodeSet) {
1475 if (arg->dependsOn(*selNodes, nullptr, /*valueOnly=*/true)) {
1476 tmp.add(*arg,true);
1477 }
1478 }
1479
1480 tmp.remove(*selNodes, true);
1481 tmp.remove(*this);
1482 selNodes->add(tmp);
1483 coutI(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") indirectly selected PDF components: " << tmp << std::endl ;
1484
1485 // Set PDF selection bits according to selNodes
1486 for (const auto arg : branchNodeSet) {
1487 bool select = selNodes->find(arg->GetName()) != nullptr;
1488 static_cast<RooAbsReal*>(arg)->selectComp(select);
1489 }
1490}
1491
1492
1493
1494////////////////////////////////////////////////////////////////////////////////
1495/// Plot (project) PDF on specified frame. If a PDF is plotted in an empty frame, it
1496/// will show a unit normalized curve in the frame variable, taken at the present value
1497/// of other observables defined for this PDF.
1498///
1499/// \param[in] frame pointer to RooPlot
1500/// \param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8,arg9,arg10 Ordered arguments
1501///
1502/// If a PDF is plotted in a frame in which a dataset has already been plotted, it will
1503/// show a projected curve integrated over all variables that were present in the shown
1504/// dataset except for the one on the x-axis. The normalization of the curve will also
1505/// be adjusted to the event count of the plotted dataset. An informational message
1506/// will be printed for each projection step that is performed.
1507///
1508/// This function takes the following named arguments
1509/// <table>
1510/// <tr><th><th> Projection control
1511/// <tr><td> `Slice(const RooArgSet& set)` <td> Override default projection behaviour by omitting observables listed
1512/// in set from the projection, i.e. by not integrating over these.
1513/// Slicing is usually only sensible in discrete observables, by e.g. creating a slice
1514/// of the PDF at the current value of the category observable.
1515///
1516/// <tr><td> `Slice(RooCategory& cat, const char* label)` <td> Override default projection behaviour by omitting the specified category
1517/// observable from the projection, i.e., by not integrating over all states of this category.
1518/// The slice is positioned at the given label value. To pass multiple Slice() commands, please use the
1519/// Slice(std::map<RooCategory*, std::string> const&) argument explained below.
1520///
1521/// <tr><td> `Slice(std::map<RooCategory*, std::string> const&)` <td> Omits multiple categories from the projection, as explianed above.
1522/// Can be used with initializer lists for convenience, e.g.
1523/// ```{.cpp}
1524/// pdf.plotOn(frame, Slice({{&tagCategory, "2tag"}, {&jetCategory, "3jet"}});
1525/// ```
1526///
1527/// <tr><td> `Project(const RooArgSet& set)` <td> Override default projection behaviour by projecting over observables
1528/// given in the set, ignoring the default projection behavior. Advanced use only.
1529///
1530/// <tr><td> `ProjWData(const RooAbsData& d)` <td> Override default projection _technique_ (integration). For observables present in given dataset
1531/// projection of PDF is achieved by constructing an average over all observable values in given set.
1532/// Consult RooFit plotting tutorial for further explanation of meaning & use of this technique
1533///
1534/// <tr><td> `ProjWData(const RooArgSet& s, const RooAbsData& d)` <td> As above but only consider subset 's' of observables in dataset 'd' for projection through data averaging
1535///
1536/// <tr><td> `ProjectionRange(const char* rn)` <td> Override default range of projection integrals to a different range specified by given range name.
1537/// This technique allows you to project a finite width slice in a real-valued observable
1538///
1539/// <tr><td> `NumCPU(Int_t ncpu)` <td> Number of CPUs to use simultaneously to calculate data-weighted projections (only in combination with ProjWData)
1540///
1541///
1542/// <tr><th><th> Misc content control
1543/// <tr><td> `PrintEvalErrors(Int_t numErr)` <td> Control number of p.d.f evaluation errors printed per curve. A negative
1544/// value suppress output completely, a zero value will only print the error count per p.d.f component,
1545/// a positive value is will print details of each error up to numErr messages per p.d.f component.
1546///
1547/// <tr><td> `EvalErrorValue(double value)` <td> Set curve points at which (pdf) evaluation errors occur to specified value. By default the
1548/// function value is plotted.
1549///
1550/// <tr><td> `Normalization(double scale, ScaleType code)` <td> Adjust normalization by given scale factor. Interpretation of number depends on code:
1551/// - Relative: relative adjustment factor for a normalized function,
1552/// - NumEvent: scale to match given number of events.
1553/// - Raw: relative adjustment factor for an un-normalized function.
1554///
1555/// <tr><td> `Name(const chat* name)` <td> Give curve specified name in frame. Useful if curve is to be referenced later
1556///
1557/// <tr><td> `Asymmetry(const RooCategory& c)` <td> Show the asymmetry of the PDF in given two-state category [F(+)-F(-)] / [F(+)+F(-)] rather than
1558/// the PDF projection. Category must have two states with indices -1 and +1 or three states with
1559/// indices -1,0 and +1.
1560///
1561/// <tr><td> `ShiftToZero(bool flag)` <td> Shift entire curve such that lowest visible point is at exactly zero. Mostly useful when plotting \f$ -\log(L) \f$ or \f$ \chi^2 \f$ distributions
1562///
1563/// <tr><td> `AddTo(const char* name, double_t wgtSelf, double_t wgtOther)` <td> Add constructed projection to already existing curve with given name and relative weight factors
1564/// <tr><td> `Components(const char* names)` <td> When plotting sums of PDFs, plot only the named components (*e.g.* only
1565/// the signal of a signal+background model).
1566/// <tr><td> `Components(const RooArgSet& compSet)` <td> As above, but pass a RooArgSet of the components themselves.
1567///
1568/// <tr><th><th> Plotting control
1569/// <tr><td> `DrawOption(const char* opt)` <td> Select ROOT draw option for resulting TGraph object. Currently supported options are "F" (fill), "L" (line), and "P" (points).
1570/// \note Option "P" will cause RooFit to plot (and treat) this pdf as if it were data! This is intended for plotting "corrected data"-type pdfs such as "data-minus-background" or unfolded datasets.
1571///
1572/// <tr><td> `LineStyle(Int_t style)` <td> Select line style by ROOT line style code, default is solid
1573///
1574/// <tr><td> `LineColor(Int_t color)` <td> Select line color by ROOT color code, default is blue
1575///
1576/// <tr><td> `LineWidth(Int_t width)` <td> Select line with in pixels, default is 3
1577///
1578/// <tr><td> `MarkerStyle(Int_t style)` <td> Select the ROOT marker style, default is 21
1579///
1580/// <tr><td> `MarkerColor(Int_t color)` <td> Select the ROOT marker color, default is black
1581///
1582/// <tr><td> `MarkerSize(double size)` <td> Select the ROOT marker size
1583///
1584/// <tr><td> `FillStyle(Int_t style)` <td> Select fill style, default is not filled. If a filled style is selected, also use VLines()
1585/// to add vertical downward lines at end of curve to ensure proper closure. Add `DrawOption("F")` for filled drawing.
1586/// <tr><td> `FillColor(Int_t color)` <td> Select fill color by ROOT color code
1587///
1588/// <tr><td> `Range(const char* name)` <td> Only draw curve in range defined by given name
1589///
1590/// <tr><td> `Range(double lo, double hi)` <td> Only draw curve in specified range
1591///
1592/// <tr><td> `VLines()` <td> Add vertical lines to y=0 at end points of curve
1593///
1594/// <tr><td> `Precision(double eps)` <td> Control precision of drawn curve w.r.t to scale of plot, default is 1e-3. Higher precision
1595/// will result in more and more densely spaced curve points
1596///
1597/// <tr><td> `Invisible(bool flag)` <td> Add curve to frame, but do not display. Useful in combination AddTo()
1598///
1599/// <tr><td> `VisualizeError(const RooFitResult& fitres, double Z=1, bool linearMethod=true)`
1600/// <td> Visualize the uncertainty on the parameters, as given in fitres, at 'Z' sigma'. The linear method is fast but may not be accurate in the presence of strong correlations (~>0.9) and at Z>2 due to linear and Gaussian approximations made. Intervals from the sampling method can be asymmetric, and may perform better in the presence of strong correlations, but may take (much) longer to calculate
1601///
1602/// <tr><td> `VisualizeError(const RooFitResult& fitres, const RooArgSet& param, double Z=1, bool linearMethod=true)`
1603/// <td> Visualize the uncertainty on the subset of parameters 'param', as given in fitres, at 'Z' sigma'
1604/// </table>
1605///
1606/// Details on error band visualization
1607/// -----------------------------------
1608/// *VisualizeError() uses plotOnWithErrorBand(). Documentation of the latter:*
1609/// \see plotOnWithErrorBand()
1610
1612 const RooCmdArg& arg3, const RooCmdArg& arg4,
1613 const RooCmdArg& arg5, const RooCmdArg& arg6,
1614 const RooCmdArg& arg7, const RooCmdArg& arg8,
1615 const RooCmdArg& arg9, const RooCmdArg& arg10) const
1616{
1618 l.Add((TObject*)&arg9) ; l.Add((TObject*)&arg10) ;
1619 return plotOn(frame,l) ;
1620}
1621
1622
1623
1624////////////////////////////////////////////////////////////////////////////////
1625/// Internal back-end function of plotOn() with named arguments
1626
1628{
1629 // Special handling here if argList contains RangeWithName argument with multiple
1630 // range names -- Need to translate this call into multiple calls
1631
1632 RooCmdArg* rcmd = static_cast<RooCmdArg*>(argList.FindObject("RangeWithName")) ;
1633 if (rcmd && TString(rcmd->getString(0)).Contains(",")) {
1634
1635 // List joint ranges as choice of normalization for all later processing
1636 RooCmdArg rnorm = RooFit::NormRange(rcmd->getString(0)) ;
1637 argList.Add(&rnorm) ;
1638
1639 for (const auto& rangeString : ROOT::Split(rcmd->getString(0), ",")) {
1640 // Process each range with a separate command with a single range to be plotted
1641 rcmd->setString(0, rangeString.c_str());
1642 RooAbsReal::plotOn(frame,argList);
1643 }
1644 return frame ;
1645
1646 }
1647
1648 // Define configuration for this method
1649 RooCmdConfig pc("RooAbsReal::plotOn(" + std::string(GetName()) + ")");
1650 pc.defineString("drawOption","DrawOption",0,"L") ;
1651 pc.defineString("projectionRangeName","ProjectionRange",0,"",true) ;
1652 pc.defineString("curveNameSuffix","CurveNameSuffix",0,"") ;
1653 pc.defineString("sliceCatState","SliceCat",0,"",true) ;
1654 pc.defineDouble("scaleFactor","Normalization",0,1.0) ;
1655 pc.defineInt("scaleType","Normalization",0,Relative) ;
1656 pc.defineSet("sliceSet","SliceVars",0) ;
1657 pc.defineObject("sliceCatList","SliceCat",0,nullptr,true) ;
1658 // This dummy is needed for plotOn to recognize the "SliceCatMany" command.
1659 // It is not used directly, but the "SliceCat" commands are nested in it.
1660 // Removing this dummy definition results in "ERROR: unrecognized command: SliceCatMany".
1661 pc.defineObject("dummy1","SliceCatMany",0) ;
1662 pc.defineSet("projSet","Project",0) ;
1663 pc.defineObject("asymCat","Asymmetry",0) ;
1664 pc.defineDouble("precision","Precision",0,1e-3) ;
1665 pc.defineDouble("evalErrorVal","EvalErrorValue",0,0) ;
1666 pc.defineInt("doEvalError","EvalErrorValue",0,0) ;
1667 pc.defineInt("shiftToZero","ShiftToZero",0,0) ;
1668 pc.defineSet("projDataSet","ProjData",0) ;
1669 pc.defineObject("projData","ProjData",1) ;
1670 pc.defineObject("errorFR","VisualizeError",0) ;
1671 pc.defineDouble("errorZ","VisualizeError",0,1.) ;
1672 pc.defineSet("errorPars","VisualizeError",0) ;
1673 pc.defineInt("linearMethod","VisualizeError",0,0) ;
1674 pc.defineInt("binProjData","ProjData",0,0) ;
1675 pc.defineDouble("rangeLo","Range",0,-999.) ;
1676 pc.defineDouble("rangeHi","Range",1,-999.) ;
1677 pc.defineInt("numee","PrintEvalErrors",0,10) ;
1678 pc.defineInt("rangeAdjustNorm","Range",0,0) ;
1679 pc.defineInt("rangeWNAdjustNorm","RangeWithName",0,0) ;
1680 pc.defineInt("VLines","VLines",0,2) ; // 2==ExtendedWings
1681 pc.defineString("rangeName","RangeWithName",0,"") ;
1682 pc.defineString("normRangeName","NormRange",0,"") ;
1683 pc.defineInt("markerColor","MarkerColor",0,-999) ;
1684 pc.defineInt("markerStyle","MarkerStyle",0,-999) ;
1685 pc.defineDouble("markerSize","MarkerSize",0,-999) ;
1686 pc.defineInt("lineColor","LineColor",0,-999) ;
1687 pc.defineInt("lineStyle","LineStyle",0,-999) ;
1688 pc.defineInt("lineWidth","LineWidth",0,-999) ;
1689 pc.defineInt("fillColor","FillColor",0,-999) ;
1690 pc.defineInt("fillStyle","FillStyle",0,-999) ;
1691 pc.defineString("curveName","Name",0,"") ;
1692 pc.defineInt("curveInvisible","Invisible",0,0) ;
1693 pc.defineInt("showProg","ShowProgress",0,0) ;
1694 pc.defineInt("numCPU","NumCPU",0,1) ;
1695 pc.defineInt("interleave","NumCPU",1,0) ;
1696 pc.defineString("addToCurveName","AddTo",0,"") ;
1697 pc.defineDouble("addToWgtSelf","AddTo",0,1.) ;
1698 pc.defineDouble("addToWgtOther","AddTo",1,1.) ;
1699 pc.defineInt("moveToBack","MoveToBack",0,0) ;
1700 pc.defineMutex("SliceVars","Project") ;
1701 pc.defineMutex("AddTo","Asymmetry") ;
1702 pc.defineMutex("Range","RangeWithName") ;
1703 pc.defineMutex("VisualizeError","VisualizeErrorData") ;
1704
1705 // Process & check varargs
1706 pc.process(argList) ;
1707 if (!pc.ok(true)) {
1708 return frame ;
1709 }
1710
1711 TString drawOpt(pc.getString("drawOption"));
1712
1713 RooFitResult* errFR = static_cast<RooFitResult*>(pc.getObject("errorFR")) ;
1714 if (!drawOpt.Contains("P") && errFR) {
1715 return plotOnWithErrorBand(frame, *errFR, pc.getDouble("errorZ"), pc.getSet("errorPars"), argList,
1716 pc.getInt("linearMethod"));
1717 }
1718
1719 // Extract values from named arguments
1720 PlotOpt o ;
1721 o.numee = pc.getInt("numee") ;
1722 o.drawOptions = drawOpt.Data();
1723 o.curveNameSuffix = pc.getString("curveNameSuffix") ;
1724 o.scaleFactor = pc.getDouble("scaleFactor") ;
1725 o.stype = (ScaleType) pc.getInt("scaleType") ;
1726 o.projData = static_cast<const RooAbsData*>(pc.getObject("projData")) ;
1727 o.binProjData = pc.getInt("binProjData") ;
1728 o.projDataSet = pc.getSet("projDataSet");
1729 o.numCPU = pc.getInt("numCPU") ;
1730 o.interleave = (RooFit::MPSplit) pc.getInt("interleave") ;
1731 o.eeval = pc.getDouble("evalErrorVal") ;
1732 o.doeeval = pc.getInt("doEvalError") ;
1733 o.errorFR = errFR;
1734
1735 const RooArgSet* sliceSetTmp = pc.getSet("sliceSet");
1736 std::unique_ptr<RooArgSet> sliceSet{sliceSetTmp ? static_cast<RooArgSet*>(sliceSetTmp->Clone()) : nullptr};
1737 const RooArgSet* projSet = pc.getSet("projSet") ;
1738 const RooAbsCategoryLValue* asymCat = static_cast<const RooAbsCategoryLValue*>(pc.getObject("asymCat")) ;
1739
1740
1741 // Look for category slice arguments and add them to the master slice list if found
1742 if (const char* sliceCatState = pc.getString("sliceCatState",nullptr,true)) {
1743 const RooLinkedList& sliceCatList = pc.getObjectList("sliceCatList") ;
1744
1745 // Make the master slice set if it doesnt exist
1746 if (!sliceSet) {
1747 sliceSet = std::make_unique<RooArgSet>();
1748 }
1749
1750 // Loop over all categories provided by (multiple) Slice() arguments
1751 auto iter = sliceCatList.begin();
1752 for (auto const& catToken : ROOT::Split(sliceCatState, ",")) {
1753 if (auto scat = static_cast<RooCategory*>(*iter)) {
1754 // Set the slice position to the value indicate by slabel
1755 scat->setLabel(catToken);
1756 // Add the slice category to the master slice set
1757 sliceSet->add(*scat,false) ;
1758 }
1759 ++iter;
1760 }
1761 }
1762
1763 o.precision = pc.getDouble("precision") ;
1764 o.shiftToZero = (pc.getInt("shiftToZero")!=0) ;
1765 Int_t vlines = pc.getInt("VLines");
1766 if (pc.hasProcessed("Range")) {
1767 o.rangeLo = pc.getDouble("rangeLo") ;
1768 o.rangeHi = pc.getDouble("rangeHi") ;
1769 o.postRangeFracScale = pc.getInt("rangeAdjustNorm") ;
1770 if (vlines==2) vlines=0 ; // Default is NoWings if range was specified
1771 } else if (pc.hasProcessed("RangeWithName")) {
1772 o.normRangeName = pc.getString("rangeName",nullptr,true) ;
1773 o.rangeLo = frame->getPlotVar()->getMin(pc.getString("rangeName",nullptr,true)) ;
1774 o.rangeHi = frame->getPlotVar()->getMax(pc.getString("rangeName",nullptr,true)) ;
1775 o.postRangeFracScale = pc.getInt("rangeWNAdjustNorm") ;
1776 if (vlines==2) vlines=0 ; // Default is NoWings if range was specified
1777 }
1778
1779
1780 // If separate normalization range was specified this overrides previous settings
1781 if (pc.hasProcessed("NormRange")) {
1782 o.normRangeName = pc.getString("normRangeName") ;
1784 }
1785
1787 o.projectionRangeName = pc.getString("projectionRangeName",nullptr,true) ;
1788 o.curveName = pc.getString("curveName",nullptr,true) ;
1789 o.curveInvisible = pc.getInt("curveInvisible") ;
1790 o.progress = pc.getInt("showProg") ;
1791 o.addToCurveName = pc.getString("addToCurveName",nullptr,true) ;
1792 o.addToWgtSelf = pc.getDouble("addToWgtSelf") ;
1793 o.addToWgtOther = pc.getDouble("addToWgtOther") ;
1794
1796 coutE(InputArguments) << "RooAbsReal::plotOn(" << GetName() << ") cannot find existing curve " << o.addToCurveName << " to add to in RooPlot" << std::endl ;
1797 return frame ;
1798 }
1799
1801 if (sliceSet) {
1802 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") Preprocessing: have slice " << *sliceSet << std::endl ;
1803
1804 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
1805
1806 // Take out the sliced variables
1807 for (const auto sliceArg : *sliceSet) {
1808 if (RooAbsArg* arg = projectedVars.find(sliceArg->GetName())) {
1809 projectedVars.remove(*arg) ;
1810 } else {
1811 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") slice variable "
1812 << sliceArg->GetName() << " was not projected anyway" << std::endl ;
1813 }
1814 }
1815 } else if (projSet) {
1816 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") Preprocessing: have projSet " << *projSet << std::endl ;
1817 makeProjectionSet(frame->getPlotVar(),projSet,projectedVars,false) ;
1818 } else {
1819 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") Preprocessing: have neither sliceSet nor projSet " << std::endl ;
1820 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
1821 }
1822 o.projSet = &projectedVars ;
1823
1824 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") Preprocessing: projectedVars = " << projectedVars << std::endl ;
1825
1826
1827 // Forward to actual calculation
1829
1830 // Optionally adjust line/fill attributes
1831 Int_t lineColor = pc.getInt("lineColor") ;
1832 Int_t lineStyle = pc.getInt("lineStyle") ;
1833 Int_t lineWidth = pc.getInt("lineWidth") ;
1834 Int_t markerColor = pc.getInt("markerColor") ;
1835 Int_t markerStyle = pc.getInt("markerStyle") ;
1836 Size_t markerSize = pc.getDouble("markerSize") ;
1837 Int_t fillColor = pc.getInt("fillColor") ;
1838 Int_t fillStyle = pc.getInt("fillStyle") ;
1839 if (lineColor!=-999) ret->getAttLine()->SetLineColor(lineColor) ;
1840 if (lineStyle!=-999) ret->getAttLine()->SetLineStyle(lineStyle) ;
1841 if (lineWidth!=-999) ret->getAttLine()->SetLineWidth(lineWidth) ;
1842 if (fillColor!=-999) ret->getAttFill()->SetFillColor(fillColor) ;
1843 if (fillStyle!=-999) ret->getAttFill()->SetFillStyle(fillStyle) ;
1844 if (markerColor!=-999) ret->getAttMarker()->SetMarkerColor(markerColor) ;
1845 if (markerStyle!=-999) ret->getAttMarker()->SetMarkerStyle(markerStyle) ;
1846 if (markerSize!=-999) ret->getAttMarker()->SetMarkerSize(markerSize) ;
1847
1848 if ((fillColor != -999 || fillStyle != -999) && !drawOpt.Contains("F")) {
1849 coutW(Plotting) << "Fill color or style was set for plotting \"" << GetName()
1850 << "\", but these only have an effect when 'DrawOption(\"F\")' for fill is used at the same time." << std::endl;
1851 }
1852
1853 // Move last inserted object to back to drawing stack if requested
1854 if (pc.getInt("moveToBack") && frame->numItems()>1) {
1855 frame->drawBefore(frame->getObject(0)->GetName(), frame->getCurve()->GetName());
1856 }
1857
1858 return ret ;
1859}
1860
1861
1862
1863/// Plotting engine function for internal use
1864///
1865/// Plot ourselves on given frame. If frame contains a histogram, all dimensions of the plotted
1866/// function that occur in the previously plotted dataset are projected via partial integration,
1867/// otherwise no projections are performed. Optionally, certain projections can be performed
1868/// by summing over the values present in a provided dataset ('projData'), to correctly
1869/// project out data dependents that are not properly described by the PDF (e.g. per-event errors).
1870///
1871/// The functions value can be multiplied with an optional scale factor. The interpretation
1872/// of the scale factor is unique for generic real functions, for PDFs there are various interpretations
1873/// possible, which can be selection with 'stype' (see RooAbsPdf::plotOn() for details).
1874///
1875/// The default projection behaviour can be overridden by supplying an optional set of dependents
1876/// to project via RooFit command arguments.
1877//_____________________________________________________________________________
1878// coverity[PASS_BY_VALUE]
1880{
1881 // Sanity checks
1882 if (plotSanityChecks(frame)) return frame ;
1883
1884 // ProjDataVars is either all projData observables, or the user indicated subset of it
1886 if (o.projData) {
1887 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") have ProjData with observables = " << *o.projData->get() << std::endl ;
1888 if (o.projDataSet) {
1889 projDataVars.add(*std::unique_ptr<RooArgSet>{o.projData->get()->selectCommon(*o.projDataSet)}) ;
1890 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") have ProjDataSet = " << *o.projDataSet << " will only use this subset of projData" << std::endl ;
1891 } else {
1892 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") using full ProjData" << std::endl ;
1893 projDataVars.add(*o.projData->get()) ;
1894 }
1895 }
1896
1897 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") ProjDataVars = " << projDataVars << std::endl ;
1898
1899 // Make list of variables to be projected
1902 if (o.projSet) {
1903 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") have input projSet = " << *o.projSet << std::endl ;
1905 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") calculated projectedVars = " << *o.projSet << std::endl ;
1906
1907 // Print list of non-projected variables
1908 if (frame->getNormVars()) {
1911
1912 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") frame->getNormVars() that are also observables = " << sliceSetTmp << std::endl ;
1913
1914 sliceSetTmp.remove(projectedVars,true,true) ;
1915 sliceSetTmp.remove(*frame->getPlotVar(),true,true) ;
1916
1917 if (o.projData) {
1918 std::unique_ptr<RooArgSet> tmp{projDataVars.selectCommon(*o.projSet)};
1919 sliceSetTmp.remove(*tmp,true,true) ;
1920 }
1921
1922 if (!sliceSetTmp.empty()) {
1923 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot on "
1924 << frame->getPlotVar()->GetName() << " represents a slice in " << sliceSetTmp << std::endl ;
1925 }
1926 sliceSet.add(sliceSetTmp) ;
1927 }
1928 } else {
1929 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
1930 }
1931
1932 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") projectedVars = " << projectedVars << " sliceSet = " << sliceSet << std::endl ;
1933
1934
1935 RooArgSet* projDataNeededVars = nullptr ;
1936 // Take out data-projected dependents from projectedVars
1937 if (o.projData) {
1939 projectedVars.remove(projDataVars,true,true) ;
1940 }
1941
1942 // Get the plot variable and remember its original value
1943 auto* plotVar = static_cast<RooRealVar*>(frame->getPlotVar());
1944 double oldPlotVarVal = plotVar->getVal();
1945
1946 // Inform user about projections
1947 if (!projectedVars.empty()) {
1948 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot on " << plotVar->GetName()
1949 << " integrates over variables " << projectedVars
1950 << (o.projectionRangeName ? (" in range " + std::string{o.projectionRangeName}) : "") << std::endl;
1951 }
1952 if (projDataNeededVars && !projDataNeededVars->empty()) {
1953 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot on " << plotVar->GetName()
1954 << " averages using data variables " << *projDataNeededVars << std::endl ;
1955 }
1956
1957 // Create projection integral
1958 RooArgSet* projectionCompList = nullptr ;
1959
1960 RooArgSet deps;
1961 getObservables(frame->getNormVars(), deps) ;
1962 deps.remove(projectedVars,true,true) ;
1963 if (projDataNeededVars) {
1964 deps.remove(*projDataNeededVars,true,true) ;
1965 }
1966 deps.remove(*plotVar,true,true) ;
1967 deps.add(*plotVar) ;
1968
1969 // Now that we have the final set of dependents, call checkObservables()
1970
1971 // WVE take out conditional observables
1972 if (checkObservables(&deps)) {
1973 coutE(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") error in checkObservables, abort" << std::endl ;
1975 return frame ;
1976 }
1977
1979 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot projection object is " << projection->GetName() << std::endl ;
1980 if (dologD(Plotting)) {
1981 projection->printStream(ccoutD(Plotting),0,kVerbose) ;
1982 }
1983
1984 // Always fix RooAddPdf normalizations
1985 RooArgSet fullNormSet(deps) ;
1987 if (projDataNeededVars && !projDataNeededVars->empty()) {
1989 }
1990
1991 std::unique_ptr<RooArgSet> projectionComponents(projection->getComponents());
1993 if (pdf) {
1994 pdf->selectNormalization(&fullNormSet) ;
1995 }
1996 }
1997
1998 // Apply data projection, if requested
1999 if (o.projData && projDataNeededVars && !projDataNeededVars->empty()) {
2000
2001 // If data set contains more rows than needed, make reduced copy first
2002 RooAbsData* projDataSel = const_cast<RooAbsData*>(o.projData);
2003 std::unique_ptr<RooAbsData> projDataSelOwned;
2004
2005 if (projDataNeededVars->size() < o.projData->get()->size()) {
2006
2007 // Determine if there are any slice variables in the projection set
2009 sliceSet.selectCommon(*o.projData->get(), sliceDataSet);
2011
2012 if (!cutString.empty()) {
2013 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") reducing given projection dataset to entries with " << cutString << std::endl ;
2014 }
2015 projDataSelOwned = std::unique_ptr<RooAbsData>{projDataSel->reduce(RooFit::SelectVars(*projDataNeededVars), RooFit::Cut(cutString.c_str()))};
2017 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName()
2018 << ") only the following components of the projection data will be used: " << *projDataNeededVars << std::endl ;
2019 }
2020
2021 // Request binning of unbinned projection dataset that consists exclusively of category observables
2022 if (!o.binProjData && dynamic_cast<RooDataSet*>(projDataSel)!=nullptr) {
2023
2024 // Determine if dataset contains only categories
2025 bool allCat(true) ;
2026 for(RooAbsArg * arg2 : *projDataSel->get()) {
2027 if (!dynamic_cast<RooCategory*>(arg2)) allCat = false ;
2028 }
2029 if (allCat) {
2030 o.binProjData = true ;
2031 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") unbinned projection dataset consist only of discrete variables,"
2032 << " performing projection with binned copy for optimization." << std::endl ;
2033
2034 }
2035 }
2036
2037 // Bin projection dataset if requested
2038 if (o.binProjData) {
2039 projDataSelOwned = std::make_unique<RooDataHist>(std::string(projDataSel->GetName()) + "_binned","Binned projection data",*projDataSel->get(),*projDataSel);
2041 }
2042
2043 // Construct scaled data weighted average
2044 ScaledDataWeightedAverage scaleBind{*projection, *projDataSel, o.scaleFactor, *plotVar};
2045
2046 // Set default range, if not specified
2047 if (o.rangeLo==0 && o.rangeHi==0) {
2048 o.rangeLo = frame->GetXaxis()->GetXmin() ;
2049 o.rangeHi = frame->GetXaxis()->GetXmax() ;
2050 }
2051
2052 // Construct name of curve for data weighed average
2053 std::string curveName(projection->GetName()) ;
2054 curveName.append("_DataAvg[" + projDataSel->get()->contentsString() + "]");
2055 // Append slice set specification if any
2056 if (!sliceSet.empty()) {
2057 curveName.append("_Slice[" + sliceSet.contentsString() + "]");
2058 }
2059 // Append any suffixes imported from RooAbsPdf::plotOn
2060 if (o.curveNameSuffix) {
2061 curveName.append(o.curveNameSuffix) ;
2062 }
2063
2064 // Curve constructor for data weighted average
2066 RooCurve *curve = new RooCurve(projection->GetName(),projection->GetTitle(),scaleBind,
2069
2070 curve->SetName(curveName.c_str()) ;
2071
2072 // Add self to other curve if requested
2073 if (o.addToCurveName) {
2075
2076 // Curve constructor for sum of curves
2078 sumCurve->SetName(Form("%s_PLUS_%s",curve->GetName(),otherCurve->GetName())) ;
2079 delete curve ;
2080 curve = sumCurve ;
2081
2082 }
2083
2084 if (o.curveName) {
2085 curve->SetName(o.curveName) ;
2086 }
2087
2088 // add this new curve to the specified plot frame
2090
2091 } else {
2092
2093 // Set default range, if not specified
2094 if (o.rangeLo==0 && o.rangeHi==0) {
2095 o.rangeLo = frame->GetXaxis()->GetXmin() ;
2096 o.rangeHi = frame->GetXaxis()->GetXmax() ;
2097 }
2098
2099 // Calculate a posteriori range fraction scaling if requested (2nd part of normalization correction for
2100 // result fit on subrange of data)
2101 if (o.postRangeFracScale) {
2102 if (!o.normRangeName) {
2103 o.normRangeName = "plotRange" ;
2104 plotVar->setRange("plotRange",o.rangeLo,o.rangeHi) ;
2105 }
2106
2107 // Evaluate fractional correction integral always on full p.d.f, not component.
2109 std::unique_ptr<RooAbsReal> intFrac{projection->createIntegral(*plotVar,*plotVar,o.normRangeName)};
2110 if(o.stype != RooAbsReal::Raw || this->InheritsFrom(RooAbsPdf::Class())){
2111 // this scaling should only be !=1 when plotting partial ranges
2112 // still, raw means raw
2113 o.scaleFactor /= intFrac->getVal() ;
2114 }
2115 }
2116
2117 // create a new curve of our function using the clone to do the evaluations
2118 // Curve constructor for regular projections
2119
2120 // Set default name of curve
2121 std::string curveName(projection->GetName()) ;
2122 if (!sliceSet.empty()) {
2123 curveName.append("_Slice[" + sliceSet.contentsString() + "]");
2124 }
2125 if (o.curveNameSuffix) {
2126 // Append any suffixes imported from RooAbsPdf::plotOn
2127 curveName.append(o.curveNameSuffix) ;
2128 }
2129
2130 TString opt(o.drawOptions);
2131 if(opt.Contains("P")){
2133 RooHist *graph= new RooHist(*projection,*plotVar,1.,o.scaleFactor,frame->getNormVars(),o.errorFR);
2135
2136 // Override name of curve by user name, if specified
2137 if (o.curveName) {
2138 graph->SetName(o.curveName) ;
2139 }
2140
2141 // add this new curve to the specified plot frame
2142 frame->addPlotable(graph, o.drawOptions, o.curveInvisible);
2143 } else {
2148 curve->SetName(curveName.c_str()) ;
2149
2150 // Add self to other curve if requested
2151 if (o.addToCurveName) {
2154 sumCurve->SetName(Form("%s_PLUS_%s",curve->GetName(),otherCurve->GetName())) ;
2155 delete curve ;
2156 curve = sumCurve ;
2157 }
2158
2159 // Override name of curve by user name, if specified
2160 if (o.curveName) {
2161 curve->SetName(o.curveName) ;
2162 }
2163
2164 // add this new curve to the specified plot frame
2166 }
2167 }
2168
2170 delete projectionCompList ;
2171 plotVar->setVal(oldPlotVarVal); // reset the plot variable value to not disturb the original state
2172 return frame;
2173}
2174
2175
2176//_____________________________________________________________________________
2177// coverity[PASS_BY_VALUE]
2179
2180{
2181 // Plotting engine for asymmetries. Implements the functionality if plotOn(frame,Asymmetry(...)))
2182 //
2183 // Plot asymmetry of ourselves, defined as
2184 //
2185 // asym = f(asymCat=-1) - f(asymCat=+1) / ( f(asymCat=-1) + f(asymCat=+1) )
2186 //
2187 // on frame. If frame contains a histogram, all dimensions of the plotted
2188 // asymmetry function that occur in the previously plotted dataset are projected via partial integration.
2189 // Otherwise no projections are performed,
2190 //
2191 // The asymmetry function can be multiplied with an optional scale factor. The default projection
2192 // behaviour can be overridden by supplying an optional set of dependents to project.
2193
2194 // Sanity checks
2195 if (plotSanityChecks(frame)) return frame ;
2196
2197 // ProjDataVars is either all projData observables, or the user indicated subset of it
2199 if (o.projData) {
2200 if (o.projDataSet) {
2201 std::unique_ptr<RooArgSet> tmp{o.projData->get()->selectCommon(*o.projDataSet)};
2202 projDataVars.add(*tmp) ;
2203 } else {
2204 projDataVars.add(*o.projData->get()) ;
2205 }
2206 }
2207
2208 // The asymmetry category itself defines the two sides of the asymmetry, so it
2209 // must not be treated as a variable to be averaged over the projection data.
2210 if (RooAbsArg *asymCatInProjData = projDataVars.find(asymCat.GetName())) {
2212 }
2213
2214 // Must depend on asymCat
2215 if (!dependsOn(asymCat)) {
2216 coutE(Plotting) << "RooAbsReal::plotAsymOn(" << GetName()
2217 << ") function doesn't depend on asymmetry category " << asymCat.GetName() << std::endl ;
2218 return frame ;
2219 }
2220
2221 // asymCat must be a signCat
2222 if (!asymCat.isSignType()) {
2223 coutE(Plotting) << "RooAbsReal::plotAsymOn(" << GetName()
2224 << ") asymmetry category must have 2 or 3 states with index values -1,0,1" << std::endl ;
2225 return frame ;
2226 }
2227
2228 // Make list of variables to be projected
2231 if (o.projSet) {
2233
2234 // Print list of non-projected variables
2235 if (frame->getNormVars()) {
2238 sliceSetTmp.remove(projectedVars,true,true) ;
2239 sliceSetTmp.remove(*frame->getPlotVar(),true,true) ;
2240
2241 if (o.projData) {
2242 std::unique_ptr<RooArgSet> tmp{projDataVars.selectCommon(*o.projSet)};
2243 sliceSetTmp.remove(*tmp,true,true) ;
2244 }
2245
2246 if (!sliceSetTmp.empty()) {
2247 coutI(Plotting) << "RooAbsReal::plotAsymOn(" << GetName() << ") plot on "
2248 << frame->getPlotVar()->GetName() << " represents a slice in " << sliceSetTmp << std::endl ;
2249 }
2250 sliceSet.add(sliceSetTmp) ;
2251 }
2252 } else {
2253 makeProjectionSet(frame->getPlotVar(),frame->getNormVars(),projectedVars,true) ;
2254 }
2255
2256
2257 // Take out data-projected dependents from projectedVars
2258 std::unique_ptr<RooArgSet> projDataNeededVars;
2259 if (o.projData) {
2260 projDataNeededVars.reset(projectedVars.selectCommon(projDataVars));
2261 projectedVars.remove(projDataVars, true, true);
2262 }
2263
2264 // Take out plotted asymmetry from projection
2265 if (projectedVars.find(asymCat.GetName())) {
2266 projectedVars.remove(*projectedVars.find(asymCat.GetName())) ;
2267 }
2268
2269 // Clone the plot variable
2270 RooAbsReal* realVar = static_cast<RooRealVar*>(frame->getPlotVar()) ;
2271 RooRealVar* plotVar = static_cast<RooRealVar*>(realVar->Clone()) ;
2272
2273 // Inform user about projections
2274 if (!projectedVars.empty()) {
2275 coutI(Plotting) << "RooAbsReal::plotAsymOn(" << GetName() << ") plot on " << plotVar->GetName()
2276 << " projects variables " << projectedVars << std::endl ;
2277 }
2278 if (projDataNeededVars && !projDataNeededVars->empty()) {
2279 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") plot on " << plotVar->GetName()
2280 << " averages using data variables "<< *projDataNeededVars << std::endl ;
2281 }
2282
2283
2284 // Build two copies of the function with the asymmetry category fixed to its
2285 // negative and positive state. By default these are copies with the category
2286 // pinned via a RooCustomizer, but subclasses (RooSimultaneous) can provide a
2287 // more suitable construction.
2288 std::unique_ptr<RooAbsCategoryLValue> asymPos{static_cast<RooAbsCategoryLValue*>(asymCat.Clone("asym_pos"))};
2289 std::unique_ptr<RooAbsCategoryLValue> asymNeg{static_cast<RooAbsCategoryLValue*>(asymCat.Clone("asym_neg"))};
2290 asymPos->setIndex(1) ;
2291 asymNeg->setIndex(-1) ;
2292 std::unique_ptr<RooAbsReal> funcPos = createAsymmetryComponent(asymCat, *asymPos);
2293 std::unique_ptr<RooAbsReal> funcNeg = createAsymmetryComponent(asymCat, *asymNeg);
2294
2295 // Create projection integral
2298
2299 // Add projDataVars to normalized dependents of projection
2300 // This is needed only for asymmetries (why?)
2303 // Keep the fixed asymmetry category in the normalization set only if the
2304 // component function actually depends on it (i.e. it was pinned in place).
2305 if (funcPos->dependsOn(*asymPos)) depPos.add(*asymPos) ;
2306 if (funcNeg->dependsOn(*asymNeg)) depNeg.add(*asymNeg) ;
2307 depPos.add(projDataVars) ;
2308 depNeg.add(projDataVars) ;
2309
2310 const RooAbsReal *posProj = funcPos->createPlotProjection(depPos, &projectedVars, posProjCompList, o.projectionRangeName) ;
2311 const RooAbsReal *negProj = funcNeg->createPlotProjection(depNeg, &projectedVars, negProjCompList, o.projectionRangeName) ;
2312 if (!posProj || !negProj) {
2313 coutE(Plotting) << "RooAbsReal::plotAsymOn(" << GetName() << ") Unable to create projections, abort" << std::endl ;
2314 return frame ;
2315 }
2316
2317 // Create a RooFormulaVar representing the asymmetry
2319 asymName.Append("_Asym[") ;
2320 asymName.Append(asymCat.GetName()) ;
2321 asymName.Append("]") ;
2322 TString asymTitle(asymCat.GetName()) ;
2323 asymTitle.Append(" Asymmetry of ") ;
2324 asymTitle.Append(GetTitle()) ;
2326
2327 if (o.projData) {
2328
2329 // If data set contains more rows than needed, make reduced copy first
2330 RooAbsData* projDataSel = const_cast<RooAbsData*>(o.projData);
2331 std::unique_ptr<RooAbsData> projDataSelOwned;
2332 if (projDataNeededVars && projDataNeededVars->size() < o.projData->get()->size()) {
2333
2334 // Determine if there are any slice variables in the projection set
2336 sliceSet.selectCommon(*o.projData->get(), sliceDataSet);
2338
2339 if (!cutString.empty()) {
2340 coutI(Plotting) << "RooAbsReal::plotAsymOn(" << GetName()
2341 << ") reducing given projection dataset to entries with " << cutString << std::endl ;
2342 }
2343 projDataSelOwned = std::unique_ptr<RooAbsData>{projDataSel->reduce(RooFit::SelectVars(*projDataNeededVars),RooFit::Cut(cutString.c_str()))};
2345 coutI(Plotting) << "RooAbsReal::plotAsymOn(" << GetName()
2346 << ") only the following components of the projection data will be used: " << *projDataNeededVars << std::endl ;
2347 }
2348
2349
2350 // Construct scaled data weighted average
2351 ScaledDataWeightedAverage scaleBind{funcAsym, *projDataSel, o.scaleFactor, *plotVar};
2352
2353 // Set default range, if not specified
2354 if (o.rangeLo==0 && o.rangeHi==0) {
2355 o.rangeLo = frame->GetXaxis()->GetXmin() ;
2356 o.rangeHi = frame->GetXaxis()->GetXmax() ;
2357 }
2358
2359 // Construct name of curve for data weighed average
2360 TString curveName(funcAsym.GetName()) ;
2361 curveName.Append(Form("_DataAvg[%s]",projDataSel->get()->contentsString().c_str())) ;
2362 // Append slice set specification if any
2363 if (!sliceSet.empty()) {
2364 curveName.Append(Form("_Slice[%s]",sliceSet.contentsString().c_str())) ;
2365 }
2366 // Append any suffixes imported from RooAbsPdf::plotOn
2367 if (o.curveNameSuffix) {
2368 curveName.Append(o.curveNameSuffix) ;
2369 }
2370
2371
2373 RooCurve *curve = new RooCurve(funcAsym.GetName(),funcAsym.GetTitle(),scaleBind,
2374 o.rangeLo,o.rangeHi,frame->GetNbinsX(),o.precision,o.precision,false,o.wmode,o.numee,o.doeeval,o.eeval) ;
2376
2377 dynamic_cast<TAttLine*>(curve)->SetLineColor(2) ;
2378 // add this new curve to the specified plot frame
2379 frame->addPlotable(curve, o.drawOptions);
2380
2381 ccoutW(Eval) << std::endl ;
2382 } else {
2383
2384 // Set default range, if not specified
2385 if (o.rangeLo==0 && o.rangeHi==0) {
2386 o.rangeLo = frame->GetXaxis()->GetXmin() ;
2387 o.rangeHi = frame->GetXaxis()->GetXmax() ;
2388 }
2389
2392 o.scaleFactor,nullptr,o.precision,o.precision,false,o.wmode,o.numee,o.doeeval,o.eeval);
2394
2395 dynamic_cast<TAttLine*>(curve)->SetLineColor(2) ;
2396
2397
2398 // Set default name of curve
2399 std::stringstream curveName;
2400 curveName << funcAsym.GetName();
2401 if (!sliceSet.empty()) {
2402 curveName << "_Slice[" << sliceSet.contentsString() << "]";
2403 }
2404 if (o.curveNameSuffix) {
2405 // Append any suffixes imported from RooAbsPdf::plotOn
2406 curveName << o.curveNameSuffix;
2407 }
2408 curve->SetName(curveName.str().c_str());
2409
2410 // add this new curve to the specified plot frame
2411 frame->addPlotable(curve, o.drawOptions);
2412
2413 }
2414
2415 // Cleanup
2416 delete posProjCompList ;
2417 delete negProjCompList ;
2418
2419 delete plotVar ;
2420
2421 return frame;
2422}
2423
2424
2425////////////////////////////////////////////////////////////////////////////////
2426/// Build the component function of an asymmetry plot (see plotAsymOn()) that
2427/// corresponds to a fixed state of the asymmetry category. The default
2428/// implementation returns a copy of this function with the asymmetry category
2429/// pinned to the requested state via a RooCustomizer.
2430
2431std::unique_ptr<RooAbsReal>
2433{
2434 RooCustomizer cust{*this, asymCatState.GetName()};
2435 cust.replaceArg(asymCat, asymCatState);
2436 return std::unique_ptr<RooAbsReal>{static_cast<RooAbsReal *>(cust.build())};
2437}
2438
2439
2440
2441////////////////////////////////////////////////////////////////////////////////
2442/// \brief Propagates parameter uncertainties to an uncertainty estimate for this RooAbsReal.
2443///
2444/// Estimates the uncertainty \f$\sigma_f(x;\theta)\f$ on a function \f$f(x;\theta)\f$ represented by this RooAbsReal.
2445/// Here, \f$\theta\f$ is a vector of parameters with uncertainties \f$\sigma_\theta\f$, and \f$x\f$ are usually observables.
2446/// The uncertainty is estimated by *linearly* propagating the parameter uncertainties using the correlation matrix from a fit result.
2447///
2448/// The square of the uncertainty on \f$f(x;\theta)\f$ is calculated as follows:
2449/// \f[
2450/// \sigma_f(x)^2 = \Delta f_i(x) \cdot \mathrm{Corr}_{i, j} \cdot \Delta f_j(x),
2451/// \f]
2452/// where \f$ \Delta f_i(x) = \frac{1}{2} \left(f(x;\theta_i + \sigma_{\theta_i}) - f(x; \theta_i - \sigma_{\theta_i}) \right) \f$
2453/// is the vector of function variations when changing the parameters one at a time, and
2454/// \f$ \mathrm{Corr}_{i,j} = \left(\sigma_{\theta_i} \sigma_{\theta_j}\right)^{-1} \cdot \mathrm{Cov}_{i,j} \f$ is the correlation matrix from the fit result.
2455
2456double RooAbsReal::getPropagatedError(const RooFitResult &fr, const RooArgSet &nset) const
2457{
2458 // Calling getParameters() might be costly, but necessary to get the right
2459 // parameters in the RooAbsReal. The RooFitResult only stores snapshots.
2462
2463 RooArgList paramList;
2465
2466 auto rrvInAbsReal = static_cast<RooRealVar const*>(allParamsInAbsReal.find(*rrvFitRes));
2467
2468 // If this RooAbsReal is a RooRealVar in the fit result, we don't need to
2469 // propagate anything and can just return the error in the fit result
2470 if(rrvFitRes->namePtr() == namePtr()) return rrvFitRes->getError();
2471
2472 // Strip out parameters with zero error
2473 if (rrvFitRes->getError() <= std::abs(rrvFitRes->getVal()) * std::numeric_limits<double>::epsilon()) continue;
2474
2475 // Ignore parameters in the fit result that this RooAbsReal doesn't depend on
2476 if(!rrvInAbsReal) continue;
2477
2478 // Checking for float equality is a bad. We check if the values are
2479 // negligibly far away from each other, relative to the uncertainty.
2480 if(std::abs(rrvInAbsReal->getVal() - rrvFitRes->getVal()) > 0.01 * rrvFitRes->getError()) {
2481 std::stringstream errMsg;
2482 errMsg << "RooAbsReal::getPropagatedError(): the parameters of the RooAbsReal don't have"
2483 << " the same values as in the fit result! The logic of getPropagatedError is broken in this case.";
2484
2485 throw std::runtime_error(errMsg.str());
2486 }
2487
2488 paramList.add(*rrvInAbsReal);
2489 }
2490
2491 std::vector<double> plusVar;
2492 std::vector<double> minusVar;
2493 plusVar.reserve(paramList.size());
2494 minusVar.reserve(paramList.size());
2495
2496 // Create std::vector of plus,minus variations for each parameter
2497 TMatrixDSym V(paramList.size() == fr.floatParsFinal().size() ?
2498 fr.covarianceMatrix() :
2499 fr.reducedCovarianceMatrix(paramList)) ;
2500
2501 for (std::size_t ivar=0 ; ivar<paramList.size() ; ivar++) {
2502
2503 auto& rrv = static_cast<RooRealVar&>(paramList[ivar]);
2504
2505 double cenVal = rrv.getVal() ;
2506 double errVal = sqrt(V(ivar,ivar)) ;
2507
2508 // Check if the variations are still in the parameter range.
2509 if(!rrv.inRange(cenVal+errVal, nullptr) || !rrv.inRange(cenVal-errVal, nullptr)) {
2510 std::stringstream ss;
2511 ss << "RooAbsReal::getPropagatedError(" << GetName() << "): the 1-sigma variations for the parameter "
2512 << "\"" << rrv.GetName() << "\" are invalid "
2513 << " because their values (" << cenVal-errVal << ", " << cenVal+errVal
2514 << ") are outside the defined range [" << rrv.getMin() << ", " << rrv.getMax() << "]!\n"
2515 << " The variations will be clipped inside the range."
2516 << " This might or might not be acceptable in your usecase.";
2517 coutW(Plotting) << ss.str() << std::endl;
2518 }
2519
2520 // Make Plus variation
2521 rrv.setVal(std::min(cenVal+errVal, rrv.getMax())) ;
2522 plusVar.push_back(getVal(nset)) ;
2523
2524 // Make Minus variation
2525 rrv.setVal(std::max(cenVal-errVal, rrv.getMin())) ;
2526 minusVar.push_back(getVal(nset)) ;
2527
2528 rrv.setVal(cenVal) ;
2529 }
2530
2531 // Re-evaluate this RooAbsReal with the central parameters just to be
2532 // extra-safe that a call to `getPropagatedError()` doesn't change any state.
2533 // It should not be necessary because thanks to the dirty flag propagation
2534 // the RooAbsReal is re-evaluated anyway the next time getVal() is called.
2535 // Still there are imaginable corner cases where it would not be triggered,
2536 // for example if the user changes the RooFit operation more after the error
2537 // propagation.
2538 getVal(nset);
2539
2540 TMatrixDSym C(paramList.size()) ;
2541 std::vector<double> errVec(paramList.size()) ;
2542 for (std::size_t i=0 ; i<paramList.size() ; i++) {
2543 errVec[i] = std::sqrt(V(i,i)) ;
2544 for (std::size_t j=i ; j<paramList.size() ; j++) {
2545 C(i,j) = V(i,j) / std::sqrt(V(i,i)*V(j,j));
2546 C(j,i) = C(i,j) ;
2547 }
2548 }
2549
2550 // Make std::vector of variations
2551 TVectorD F(plusVar.size()) ;
2552 for (std::size_t j=0 ; j<plusVar.size() ; j++) {
2553 F[j] = (plusVar[j]-minusVar[j]) * 0.5;
2554 }
2555
2556 // Calculate error in linear approximation from variations and correlation coefficient
2557 double sum = F*(C*F) ;
2558
2559 return sqrt(sum) ;
2560}
2561
2562
2563
2564////////////////////////////////////////////////////////////////////////////////
2565/// Plot function or PDF on frame with support for visualization of the uncertainty encoded in the given fit result fr.
2566/// \param[in] frame RooPlot to plot on
2567/// \param[in] fr The RooFitResult, where errors can be extracted
2568/// \param[in] Z The desired significance (width) of the error band
2569/// \param[in] params If non-zero, consider only the subset of the parameters in fr for the error evaluation
2570/// \param[in] argList Optional `RooCmdArg` that can be applied to a regular plotOn() operation
2571/// \param[in] linMethod By default (linMethod=true), a linearized error is shown.
2572/// \return The RooPlot the band was plotted on (for chaining of plotting commands).
2573///
2574/// The linearized error is calculated as follows:
2575/// \f[
2576/// \mathrm{error}(x) = Z * F_a(x) * \mathrm{Corr}(a,a') * F_{a'}^\mathrm{T}(x),
2577/// \f]
2578///
2579/// where
2580/// \f[
2581/// F_a(x) = \frac{ f(x,a+\mathrm{d}a) - f(x,a-\mathrm{d}a) }{2},
2582/// \f]
2583/// with \f$ f(x) \f$ the plotted curve and \f$ \mathrm{d}a \f$ taken from the fit result, and
2584/// \f$ \mathrm{Corr}(a,a') \f$ = the correlation matrix from the fit result, and \f$ Z \f$ = requested signifance (\f$ Z \sigma \f$ band)
2585///
2586/// The linear method is fast (required 2*N evaluations of the curve, where N is the number of parameters), but may
2587/// not be accurate in the presence of strong correlations (~>0.9) and at Z>2 due to linear and Gaussian approximations made
2588///
2589/// Alternatively, a more robust error is calculated using a sampling method. In this method a number of curves
2590/// is calculated with variations of the parameter values, as drawn from a multi-variate Gaussian p.d.f. that is constructed
2591/// from the fit results covariance matrix. The error(x) is determined by calculating a central interval that capture N% of the variations
2592/// for each value of x, where N% is controlled by Z (i.e. Z=1 gives N=68%). The number of sampling curves is chosen to be such
2593/// that at least 30 curves are expected to be outside the N% interval, and is minimally 100 (e.g. Z=1->Ncurve=100, Z=2->Ncurve=659, Z=3->Ncurve=11111)
2594/// Intervals from the sampling method can be asymmetric, and may perform better in the presence of strong correlations, but may take (much)
2595/// longer to calculate.
2596
2597RooPlot* RooAbsReal::plotOnWithErrorBand(RooPlot* frame,const RooFitResult& fr, double Z,const RooArgSet* params, const RooLinkedList& argList, bool linMethod) const
2598{
2599 RooLinkedList plotArgListTmp(argList) ;
2600 RooCmdConfig::stripCmdList(plotArgListTmp,"VisualizeError,MoveToBack") ;
2601
2602 // Strip any 'internal normalization' arguments from list
2605 if (std::string("Normalization")==cmd->GetName()) {
2606 if (((RooCmdArg*)cmd)->getInt(1)!=0) {
2607 } else {
2608 plotArgList.Add(cmd) ;
2609 }
2610 } else {
2611 plotArgList.Add(cmd) ;
2612 }
2613 }
2614
2615 // Function to plot a single curve, creating a copy of the plotArgList to
2616 // pass as plot command arguments. The "FillColor" command is removed because
2617 // it has no effect on plotting single curves and would cause a warning.
2618 auto plotFunc = [&](RooAbsReal const& absReal) {
2620 RooCmdConfig::stripCmdList(tmp, "FillColor");
2621 absReal.plotOn(frame, tmp);
2622 };
2623
2624 // Generate central value curve
2625 plotFunc(*this);
2626 RooCurve* cenCurve = frame->getCurve() ;
2627 if(!cenCurve){
2628 coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOnWithErrorBand: no curve for central value available" << std::endl;
2629 return frame;
2630 }
2631 frame->remove(nullptr,false) ;
2632
2633 RooCurve* band(nullptr) ;
2634 if (!linMethod) {
2635
2636 // *** Interval method ***
2637 //
2638 // Make N variations of parameters samples from V and visualize N% central interval where N% is defined from Z
2639
2640 // Clone self for internal use
2641 RooAbsReal* cloneFunc = static_cast<RooAbsReal*>(cloneTree()) ;
2643 cloneFunc->getObservables(&fr.floatParsFinal(), cloneParams) ;
2645 if(params) {
2646 // clear and fill errorParams only with parameters that both in params and cloneParams
2647 cloneParams.selectCommon(*params, errorParams);
2648 }
2649
2650 // Generate 100 random parameter points distributed according to fit result covariance matrix
2652 Int_t n = Int_t(100./TMath::Erfc(Z/sqrt(2.))) ;
2653 if (n<100) n=100 ;
2654
2655 coutI(Plotting) << "RooAbsReal::plotOn(" << GetName() << ") INFO: visualizing " << Z << "-sigma uncertainties in parameters "
2656 << errorParams << " from fit result " << fr.GetName() << " using " << n << " samplings." << std::endl ;
2657
2658 // Generate variation curves with above set of parameter values
2659 double ymin = frame->GetMinimum() ;
2660 double ymax = frame->GetMaximum() ;
2661 std::unique_ptr<RooDataSet> generatedData{paramPdf->generate(errorParams,n)};
2662 std::vector<RooCurve*> cvec ;
2663 for (int i=0 ; i<generatedData->numEntries() ; i++) {
2664 cloneParams.assign(*generatedData->get(i)) ;
2666 cvec.push_back(frame->getCurve()) ;
2667 frame->remove(nullptr,false) ;
2668 }
2669 frame->SetMinimum(ymin) ;
2670 frame->SetMaximum(ymax) ;
2671
2672
2673 // Generate upper and lower curve points from 68% interval around each point of central curve
2674 band = cenCurve->makeErrorBand(cvec,Z) ;
2675
2676 // Cleanup
2677 delete paramPdf ;
2678 delete cloneFunc ;
2679 for (std::vector<RooCurve*>::iterator i=cvec.begin() ; i!=cvec.end() ; ++i) {
2680 delete (*i) ;
2681 }
2682
2683 } else {
2684
2685 // *** Linear Method ***
2686 //
2687 // Make a one-sigma up- and down fluctation for each parameter and visualize
2688 // a from a linearized calculation as follows
2689 //
2690 // error(x) = F(a) C_aa' F(a')
2691 //
2692 // Where F(a) = (f(x,a+da) - f(x,a-da))/2
2693 // and C_aa' is the correlation matrix
2694
2695 // Strip out parameters with zero error
2697 for (auto const* frv : static_range_cast<RooRealVar*>(fr.floatParsFinal())) {
2698 if (frv->getError() > frv->getVal() * std::numeric_limits<double>::epsilon()) {
2699 fpf_stripped.add(*frv);
2700 }
2701 }
2702
2703 // Clone self for internal use
2704 RooAbsReal* cloneFunc = static_cast<RooAbsReal*>(cloneTree()) ;
2706 cloneFunc->getObservables(&fpf_stripped, cloneParams) ;
2708 if(params) {
2709 // clear and fill errorParams only with parameters that both in params and cloneParams
2710 cloneParams.selectCommon(*params, errorParams);
2711 }
2712
2713
2714 // Make list of parameter instances of cloneFunc in order of error matrix
2715 RooArgList paramList ;
2716 const RooArgList& fpf = fr.floatParsFinal() ;
2717 std::vector<int> fpf_idx ;
2718 for (std::size_t i=0 ; i<fpf.size() ; i++) {
2719 RooAbsArg* par = errorParams.find(fpf[i].GetName()) ;
2720 if (par) {
2721 paramList.add(*par) ;
2722 fpf_idx.push_back(i) ;
2723 }
2724 }
2725
2726 std::vector<RooCurve *> plusVar;
2727 std::vector<RooCurve *> minusVar;
2728
2729 // Create std::vector of plus,minus variations for each parameter
2730
2731 TMatrixDSym V(paramList.size() == fr.floatParsFinal().size() ?
2732 fr.covarianceMatrix():
2733 fr.reducedCovarianceMatrix(paramList)) ;
2734
2735
2736 for (std::size_t ivar=0 ; ivar<paramList.size() ; ivar++) {
2737
2738 RooRealVar& rrv = static_cast<RooRealVar&>(fpf[fpf_idx[ivar]]) ;
2739
2740 double cenVal = rrv.getVal() ;
2741 double errVal = sqrt(V(ivar,ivar)) ;
2742
2743 auto * var = static_cast<RooRealVar*>(paramList.at(ivar));
2744
2745 // Check if the variations are still in the parameter range, otherwise we
2746 // can't compute the error bands and get an invalid plot!
2747 if(!var->inRange(cenVal+Z*errVal, nullptr) || !var->inRange(cenVal-Z*errVal, nullptr)) {
2748 std::stringstream ss;
2749 ss << "RooAbsReal::plotOn(" << GetName() << "): the " << Z << "-sigma error band for the parameter "
2750 << "\"" << var->GetName() << "\" is invalid"
2751 << " because the variations (" << cenVal-Z*errVal << ", " << cenVal+Z*errVal
2752 << ") are outside the defined range [" << var->getMin() << ", " << var->getMax() << "]!\n"
2753 << " The variations will be clipped inside the range."
2754 << " This might or might not be acceptable in your usecase.";
2755 coutW(Plotting) << ss.str() << std::endl;
2756 }
2757
2758 // Make Plus variation
2759 var->setVal(std::min(cenVal+Z*errVal, var->getMax()));
2760
2762 plusVar.push_back(frame->getCurve()) ;
2763 frame->remove(nullptr,false) ;
2764
2765
2766 // Make Minus variation
2767 var->setVal(std::max(cenVal-Z*errVal, var->getMin()));
2769 minusVar.push_back(frame->getCurve()) ;
2770 frame->remove(nullptr,false) ;
2771
2772 var->setVal(cenVal) ;
2773 }
2774
2775 TMatrixDSym C(paramList.size()) ;
2776 std::vector<double> errVec(paramList.size()) ;
2777 for (std::size_t i=0 ; i<paramList.size() ; i++) {
2778 errVec[i] = sqrt(V(i,i)) ;
2779 for (std::size_t j=i ; j<paramList.size() ; j++) {
2780 C(i,j) = V(i,j)/sqrt(V(i,i)*V(j,j)) ;
2781 C(j,i) = C(i,j) ;
2782 }
2783 }
2784
2785 band = cenCurve->makeErrorBand(plusVar,minusVar,C,Z) ;
2786
2787
2788 // Cleanup
2789 delete cloneFunc ;
2790 for (std::vector<RooCurve*>::iterator i=plusVar.begin() ; i!=plusVar.end() ; ++i) {
2791 delete (*i) ;
2792 }
2793 for (std::vector<RooCurve*>::iterator i=minusVar.begin() ; i!=minusVar.end() ; ++i) {
2794 delete (*i) ;
2795 }
2796
2797 }
2798
2799 delete cenCurve ;
2800 if (!band) return frame ;
2801
2802 // Define configuration for this method
2803 RooCmdConfig pc("RooAbsPdf::plotOn(" + std::string(GetName()) + ")");
2804 pc.defineString("drawOption","DrawOption",0,"F") ;
2805 pc.defineString("curveNameSuffix","CurveNameSuffix",0,"") ;
2806 pc.defineInt("lineColor","LineColor",0,-999) ;
2807 pc.defineInt("lineStyle","LineStyle",0,-999) ;
2808 pc.defineInt("lineWidth","LineWidth",0,-999) ;
2809 pc.defineInt("markerColor","MarkerColor",0,-999) ;
2810 pc.defineInt("markerStyle","MarkerStyle",0,-999) ;
2811 pc.defineDouble("markerSize","MarkerSize",0,-999) ;
2812 pc.defineInt("fillColor","FillColor",0,-999) ;
2813 pc.defineInt("fillStyle","FillStyle",0,-999) ;
2814 pc.defineString("curveName","Name",0,"") ;
2815 pc.defineInt("curveInvisible","Invisible",0,0) ;
2816 pc.defineInt("moveToBack","MoveToBack",0,0) ;
2817 pc.allowUndefined() ;
2818
2819 // Process & check varargs
2820 pc.process(argList) ;
2821 if (!pc.ok(true)) {
2822 return frame ;
2823 }
2824
2825 // Insert error band in plot frame
2826 frame->addPlotable(band,pc.getString("drawOption"),pc.getInt("curveInvisible")) ;
2827
2828 // Optionally adjust line/fill attributes
2829 Int_t lineColor = pc.getInt("lineColor") ;
2830 Int_t lineStyle = pc.getInt("lineStyle") ;
2831 Int_t lineWidth = pc.getInt("lineWidth") ;
2832 Int_t markerColor = pc.getInt("markerColor") ;
2833 Int_t markerStyle = pc.getInt("markerStyle") ;
2834 Size_t markerSize = pc.getDouble("markerSize") ;
2835 Int_t fillColor = pc.getInt("fillColor") ;
2836 Int_t fillStyle = pc.getInt("fillStyle") ;
2837 if (lineColor!=-999) frame->getAttLine()->SetLineColor(lineColor) ;
2838 if (lineStyle!=-999) frame->getAttLine()->SetLineStyle(lineStyle) ;
2839 if (lineWidth!=-999) frame->getAttLine()->SetLineWidth(lineWidth) ;
2840 if (fillColor!=-999) frame->getAttFill()->SetFillColor(fillColor) ;
2841 if (fillStyle!=-999) frame->getAttFill()->SetFillStyle(fillStyle) ;
2842 if (markerColor!=-999) frame->getAttMarker()->SetMarkerColor(markerColor) ;
2843 if (markerStyle!=-999) frame->getAttMarker()->SetMarkerStyle(markerStyle) ;
2844 if (markerSize!=-999) frame->getAttMarker()->SetMarkerSize(markerSize) ;
2845
2846 // Adjust name if requested
2847 if (pc.getString("curveName",nullptr,true)) {
2848 band->SetName(pc.getString("curveName",nullptr,true)) ;
2849 } else if (pc.getString("curveNameSuffix",nullptr,true)) {
2850 TString name(band->GetName()) ;
2851 name.Append(pc.getString("curveNameSuffix",nullptr,true)) ;
2852 band->SetName(name.Data()) ;
2853 }
2854
2855 // Move last inserted object to back to drawing stack if requested
2856 if (pc.getInt("moveToBack") && frame->numItems()>1) {
2857 frame->drawBefore(frame->getObject(0)->GetName(), frame->getCurve()->GetName());
2858 }
2859
2860
2861 return frame ;
2862}
2863
2864
2865
2866
2867////////////////////////////////////////////////////////////////////////////////
2868/// Utility function for plotOn(), perform general sanity check on frame to ensure safe plotting operations
2869
2871{
2872 // check that we are passed a valid plot frame to use
2873 if(nullptr == frame) {
2874 coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: frame is null" << std::endl;
2875 return true;
2876 }
2877
2878 // check that this frame knows what variable to plot
2879 RooAbsReal* var = frame->getPlotVar() ;
2880 if(!var) {
2881 coutE(Plotting) << ClassName() << "::" << GetName()
2882 << ":plotOn: frame does not specify a plot variable" << std::endl;
2883 return true;
2884 }
2885
2886 // check that the plot variable is not derived
2887 if(!dynamic_cast<RooAbsRealLValue*>(var)) {
2888 coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: cannot plot variable \""
2889 << var->GetName() << "\" of type " << var->ClassName() << std::endl;
2890 return true;
2891 }
2892
2893 // check if we actually depend on the plot variable
2894 if(!this->dependsOn(*var)) {
2895 coutE(Plotting) << ClassName() << "::" << GetName() << ":plotOn: WARNING: variable is not an explicit dependent: "
2896 << var->GetName() << std::endl;
2897 }
2898
2899 return false ;
2900}
2901
2902
2903
2904
2905////////////////////////////////////////////////////////////////////////////////
2906/// Utility function for plotOn() that constructs the set of
2907/// observables to project when plotting ourselves as function of
2908/// 'plotVar'. 'allVars' is the list of variables that must be
2909/// projected, but may contain variables that we do not depend on. If
2910/// 'silent' is cleared, warnings about inconsistent input parameters
2911/// will be printed.
2912
2914 RooArgSet& projectedVars, bool silent) const
2915{
2916 cxcoutD(Plotting) << "RooAbsReal::makeProjectionSet(" << GetName() << ") plotVar = " << plotVar->GetName()
2917 << " allVars = " << (allVars?(*allVars):RooArgSet()) << std::endl ;
2918
2919 projectedVars.removeAll() ;
2920 if (!allVars) return ;
2921
2922 // Start out with suggested list of variables
2923 projectedVars.add(*allVars) ;
2924
2925 // Take out plot variable
2926 RooAbsArg *found= projectedVars.find(plotVar->GetName());
2927 if(found) {
2928 projectedVars.remove(*found);
2929
2930 // Take out eventual servers of plotVar
2931 std::unique_ptr<RooArgSet> plotServers{plotVar->getObservables(&projectedVars)};
2932 for(RooAbsArg * ps : *plotServers) {
2933 RooAbsArg* tmp = projectedVars.find(ps->GetName()) ;
2934 if (tmp) {
2935 cxcoutD(Plotting) << "RooAbsReal::makeProjectionSet(" << GetName() << ") removing " << tmp->GetName()
2936 << " from projection set because it a server of " << plotVar->GetName() << std::endl ;
2937 projectedVars.remove(*tmp) ;
2938 }
2939 }
2940
2941 if (!silent) {
2942 coutW(Plotting) << "RooAbsReal::plotOn(" << GetName()
2943 << ") WARNING: cannot project out frame variable ("
2944 << found->GetName() << "), ignoring" << std::endl ;
2945 }
2946 }
2947
2948 // Take out all non-dependents of function
2949 for(RooAbsArg * arg : *allVars) {
2950 if (!dependsOnValue(*arg)) {
2951 projectedVars.remove(*arg,true) ;
2952
2953 cxcoutD(Plotting) << "RooAbsReal::plotOn(" << GetName()
2954 << ") function doesn't depend on projection variable "
2955 << arg->GetName() << ", ignoring" << std::endl ;
2956 }
2957 }
2958}
2959
2960
2961
2962
2963////////////////////////////////////////////////////////////////////////////////
2964/// If true, the current pdf is a selected component (for use in plotting)
2965
2967{
2968 return _selectComp || _globalSelectComp ;
2969}
2970
2971
2972
2973////////////////////////////////////////////////////////////////////////////////
2974/// Global switch controlling the activation of the selectComp() functionality
2975
2980
2981
2982
2983
2984////////////////////////////////////////////////////////////////////////////////
2985/// Create an interface adaptor f(vars) that binds us to the specified variables
2986/// (in arbitrary order). For example, calling bindVars({x1,x3}) on an object
2987/// F(x1,x2,x3,x4) returns an object f(x1,x3) that is evaluated using the
2988/// current values of x2 and x4. The caller takes ownership of the returned adaptor.
2989
2991{
2992 auto binding = std::make_unique<RooRealBinding>(*this,vars,nset,clipInvalid);
2993 if(!binding->isValid()) {
2994 coutE(InputArguments) << ClassName() << "::" << GetName() << ":bindVars: cannot bind to " << vars << std::endl ;
2995 return nullptr;
2996 }
2997 return RooFit::makeOwningPtr(std::unique_ptr<RooAbsFunc>{std::move(binding)});
2998}
2999
3000
3001
3002////////////////////////////////////////////////////////////////////////////////
3003/// Copy the cached value of another RooAbsArg to our cache.
3004/// Warning: This function just copies the cached values of source,
3005/// it is the callers responsibility to make sure the cache is clean.
3006
3007void RooAbsReal::copyCache(const RooAbsArg* source, bool /*valueOnly*/, bool setValDirty)
3008{
3009 auto other = static_cast<const RooAbsReal*>(source);
3010 assert(dynamic_cast<const RooAbsReal*>(source));
3011
3012 _value = other->_treeReadBuffer ? other->_treeReadBuffer->operator double() : other->_value;
3013
3014 if (setValDirty) {
3015 setValueDirty() ;
3016 }
3017}
3018
3019
3020////////////////////////////////////////////////////////////////////////////////
3021
3023{
3024 vstore.addReal(this)->setBuffer(this,&_value);
3025}
3026
3027
3028////////////////////////////////////////////////////////////////////////////////
3029/// Attach object to a branch of given TTree. By default it will
3030/// register the internal value cache RooAbsReal::_value as branch
3031/// buffer for a double tree branch with the same name as this
3032/// object. If no double branch is found with the name of this
3033/// object, this method looks for a Float_t Int_t, UChar_t and UInt_t, etc
3034/// branch. If any of these are found, a TreeReadBuffer
3035/// that branch is created, and saved in _treeReadBuffer.
3036/// TreeReadBuffer::operator double() can be used to convert the values.
3037/// This is used by copyCache().
3039{
3040 // First determine if branch is taken
3043 if (branch) {
3044
3045 // Determine if existing branch is Float_t or double
3046 TLeaf* leaf = static_cast<TLeaf*>(branch->GetListOfLeaves()->At(0)) ;
3047
3048 // Check that leaf is _not_ an array
3049 Int_t dummy ;
3050 TLeaf* counterLeaf = leaf->GetLeafCounter(dummy) ;
3051 if (counterLeaf) {
3052 coutE(Eval) << "RooAbsReal::attachToTree(" << GetName() << ") ERROR: TTree branch " << GetName()
3053 << " is an array and cannot be attached to a RooAbsReal" << std::endl ;
3054 return ;
3055 }
3056
3057 TString typeName(leaf->GetTypeName()) ;
3058
3059
3060 // For different type names, store three items:
3061 // first: A tag attached to this instance. Not used inside RooFit, any more, but users might rely on it.
3062 // second: A function to attach
3063 std::map<std::string, std::pair<std::string, std::function<std::unique_ptr<TreeReadBuffer>()>>> typeMap {
3064 {"Float_t", {"FLOAT_TREE_BRANCH", [&](){ return createTreeReadBuffer<Float_t >(cleanName, t); }}},
3065 {"Int_t", {"INTEGER_TREE_BRANCH", [&](){ return createTreeReadBuffer<Int_t >(cleanName, t); }}},
3066 {"UChar_t", {"BYTE_TREE_BRANCH", [&](){ return createTreeReadBuffer<UChar_t >(cleanName, t); }}},
3067 {"Bool_t", {"BOOL_TREE_BRANCH", [&](){ return createTreeReadBuffer<Bool_t >(cleanName, t); }}},
3068 {"Char_t", {"SIGNEDBYTE_TREE_BRANCH", [&](){ return createTreeReadBuffer<Char_t >(cleanName, t); }}},
3069 {"UInt_t", {"UNSIGNED_INTEGER_TREE_BRANCH", [&](){ return createTreeReadBuffer<UInt_t >(cleanName, t); }}},
3070 {"Long64_t", {"LONG_TREE_BRANCH", [&](){ return createTreeReadBuffer<Long64_t >(cleanName, t); }}},
3071 {"ULong64_t", {"UNSIGNED_LONG_TREE_BRANCH", [&](){ return createTreeReadBuffer<ULong64_t>(cleanName, t); }}},
3072 {"Short_t", {"SHORT_TREE_BRANCH", [&](){ return createTreeReadBuffer<Short_t >(cleanName, t); }}},
3073 {"UShort_t", {"UNSIGNED_SHORT_TREE_BRANCH", [&](){ return createTreeReadBuffer<UShort_t >(cleanName, t); }}},
3074 };
3075
3076 auto typeDetails = typeMap.find(typeName.Data());
3077 if (typeDetails != typeMap.end()) {
3078 coutI(DataHandling) << "RooAbsReal::attachToTree(" << GetName() << ") TTree " << typeDetails->first << " branch " << GetName()
3079 << " will be converted to double precision." << std::endl ;
3080 setAttribute(typeDetails->second.first.c_str(), true);
3081 _treeReadBuffer = typeDetails->second.second().release();
3082 } else {
3083 if (_treeReadBuffer) {
3084 delete _treeReadBuffer;
3085 }
3086 _treeReadBuffer = nullptr;
3087
3088 if (!typeName.CompareTo("Double_t")) {
3090 }
3091 else {
3092 coutE(InputArguments) << "RooAbsReal::attachToTree(" << GetName() << ") data type " << typeName << " is not supported." << std::endl ;
3093 }
3094 }
3095 } else {
3096
3098 format.Append("/D");
3100 }
3101
3102}
3103
3104
3105
3106////////////////////////////////////////////////////////////////////////////////
3107/// Fill the tree branch that associated with this object with its current value
3108
3110{
3111 // First determine if branch is taken
3113 if (!branch) {
3114 coutE(Eval) << "RooAbsReal::fillTreeBranch(" << GetName() << ") ERROR: not attached to tree: " << cleanBranchName() << std::endl ;
3115 assert(0) ;
3116 }
3117 branch->Fill() ;
3118
3119}
3120
3121
3122
3123
3124////////////////////////////////////////////////////////////////////////////////
3125/// Create a RooRealVar fundamental object with our properties. The new
3126/// object will be created without any fit limits.
3127
3129{
3130 auto fund = std::make_unique<RooRealVar>(newname?newname:GetName(),GetTitle(),_value,getUnit());
3131 fund->removeMin();
3132 fund->removeMax();
3133 fund->setPlotLabel(getPlotLabel());
3134 fund->setAttribute("fundamentalCopy");
3135 return RooFit::makeOwningPtr<RooAbsArg>(std::move(fund));
3136}
3137
3138////////////////////////////////////////////////////////////////////////////////
3139/// Utility function for use in getAnalyticalIntegral(). If the
3140/// contents of 'refset' occur in set 'allDeps' then the arguments
3141/// held in 'refset' are copied from allDeps to analDeps.
3142
3144 const RooArgSet& refset) const
3145{
3146 TList nameList ;
3147 for(RooAbsArg * arg : refset) {
3148 nameList.Add(new TObjString(arg->GetName())) ;
3149 }
3150
3152 nameList.Delete() ;
3153 return result ;
3154}
3155
3156
3157
3158////////////////////////////////////////////////////////////////////////////////
3159/// Check if allArgs contains matching elements for each name in nameList. If it does,
3160/// add the corresponding args from allArgs to matchedArgs and return true. Otherwise
3161/// return false and do not change matchedArgs.
3162
3164 const TList &nameList) const
3165{
3166 RooArgSet matched("matched");
3167 bool isMatched(true);
3169 RooAbsArg *found= allArgs.find(name->String().Data());
3170 if(found) {
3171 matched.add(*found);
3172 }
3173 else {
3174 isMatched= false;
3175 break;
3176 }
3177 }
3178
3179 // nameList may not contain multiple entries with the same name
3180 // that are both matched
3181 if (isMatched && int(matched.size())!=nameList.GetSize()) {
3182 isMatched = false ;
3183 }
3184
3185 if(isMatched) matchedArgs.add(matched);
3186 return isMatched;
3187}
3188
3189
3190
3191////////////////////////////////////////////////////////////////////////////////
3192/// Returns the default numeric integration configuration for all RooAbsReals
3193
3198
3199
3200////////////////////////////////////////////////////////////////////////////////
3201/// Returns the specialized integrator configuration for _this_ RooAbsReal.
3202/// If this object has no specialized configuration, a null pointer is returned.
3203
3208
3209
3210////////////////////////////////////////////////////////////////////////////////
3211/// Returns the specialized integrator configuration for _this_ RooAbsReal.
3212/// If this object has no specialized configuration, a null pointer is returned,
3213/// unless createOnTheFly is true in which case a clone of the default integrator
3214/// configuration is created, installed as specialized configuration, and returned
3215
3217{
3219 _specIntegratorConfig = std::make_unique<RooNumIntConfig>(*defaultIntegratorConfig()) ;
3220 }
3221 return _specIntegratorConfig.get();
3222}
3223
3224
3225
3226////////////////////////////////////////////////////////////////////////////////
3227/// Return the numeric integration configuration used for this object. If
3228/// a specialized configuration was associated with this object, that configuration
3229/// is returned, otherwise the default configuration for all RooAbsReals is returned
3230
3232{
3233 const RooNumIntConfig* config = specialIntegratorConfig() ;
3234 return config ? config : defaultIntegratorConfig();
3235}
3236
3237
3238////////////////////////////////////////////////////////////////////////////////
3239/// Return the numeric integration configuration used for this object. If
3240/// a specialized configuration was associated with this object, that configuration
3241/// is returned, otherwise the default configuration for all RooAbsReals is returned
3242
3248
3249
3250
3251////////////////////////////////////////////////////////////////////////////////
3252/// Set the given integrator configuration as default numeric integration
3253/// configuration for this object
3254
3256{
3257 _specIntegratorConfig = std::make_unique<RooNumIntConfig>(config);
3258}
3259
3260
3261
3262////////////////////////////////////////////////////////////////////////////////
3263/// Remove the specialized numeric integration configuration associated
3264/// with this object
3265
3270
3271////////////////////////////////////////////////////////////////////////////////
3272/// Interface function to force use of a given set of observables
3273/// to interpret function value. Needed for functions or p.d.f.s
3274/// whose shape depends on the choice of normalization such as
3275/// RooAddPdf
3276
3278
3279////////////////////////////////////////////////////////////////////////////////
3280/// Interface function to force use of a given normalization range
3281/// to interpret function value. Needed for functions or p.d.f.s
3282/// whose shape depends on the choice of normalization such as
3283/// RooAddPdf
3284
3285void RooAbsReal::selectNormalizationRange(const char *, bool) {}
3286
3287////////////////////////////////////////////////////////////////////////////////
3288/// Advertise capability to determine maximum value of function for given set of
3289/// observables. If no direct generator method is provided, this information
3290/// will assist the accept/reject generator to operate more efficiently as
3291/// it can skip the initial trial sampling phase to empirically find the function
3292/// maximum
3293
3295{
3296 return 0;
3297}
3298
3299////////////////////////////////////////////////////////////////////////////////
3300/// Return maximum value for set of observables identified by code assigned
3301/// in getMaxVal
3302
3303double RooAbsReal::maxVal(Int_t /*code*/) const
3304{
3305 assert(1) ;
3306 return 0 ;
3307}
3308
3309
3310
3311////////////////////////////////////////////////////////////////////////////////
3312/// Interface to insert remote error logging messages received by RooRealMPFE into current error logging stream.
3313
3314void RooAbsReal::logEvalError(const RooAbsReal* originator, const char* origName, const char* message, const char* serverValueString)
3315{
3316 if (evalErrorData().mode == Ignore) {
3317 return ;
3318 }
3319
3320 if (evalErrorData().mode == CountErrors) {
3321 evalErrorData().count++ ;
3322 return ;
3323 }
3324
3325 static bool inLogEvalError = false ;
3326
3327 if (inLogEvalError) {
3328 return ;
3329 }
3331
3332 EvalError ee ;
3333 ee.setMessage(message) ;
3334
3335 if (serverValueString) {
3336 ee.setServerValues(serverValueString) ;
3337 }
3338
3339 if (evalErrorData().mode == PrintErrors) {
3340 oocoutE(nullptr,Eval) << "RooAbsReal::logEvalError(" << "<STATIC>" << ") evaluation error, " << std::endl
3341 << " origin : " << origName << std::endl
3342 << " message : " << ee._msg << std::endl
3343 << " server values: " << ee._srvval << std::endl ;
3344 } else if (evalErrorData().mode == CollectErrors) {
3345 auto &evalErrorList = evalErrorData().errorList[originator];
3346 evalErrorList.first = origName ;
3347 evalErrorList.second.push_back(ee) ;
3348 }
3349
3350
3352}
3353
3354
3355
3356////////////////////////////////////////////////////////////////////////////////
3357/// Log evaluation error message. Evaluation errors may be routed through a different
3358/// protocol than generic RooFit warning message (which go straight through RooMsgService)
3359/// because evaluation errors can occur in very large numbers in the use of likelihood
3360/// evaluations. In logEvalError mode, controlled by global method enableEvalErrorLogging()
3361/// messages reported through this function are not printed but all stored in a list,
3362/// along with server values at the time of reporting. Error messages logged in this
3363/// way can be printed in a structured way, eliminating duplicates and with the ability
3364/// to truncate the list by printEvalErrors. This is the standard mode of error logging
3365/// during MINUIT operations. If enableEvalErrorLogging() is false, all errors
3366/// reported through this method are passed for immediate printing through RooMsgService.
3367/// A string with server names and values is constructed automatically for error logging
3368/// purposes, unless a custom string with similar information is passed as argument.
3369
3370void RooAbsReal::logEvalError(const char* message, const char* serverValueString) const
3371{
3372 if (evalErrorData().mode == Ignore) {
3373 return ;
3374 }
3375
3376 if (evalErrorData().mode == CountErrors) {
3377 evalErrorData().count++ ;
3378 return ;
3379 }
3380
3381 static bool inLogEvalError = false ;
3382
3383 if (inLogEvalError) {
3384 return ;
3385 }
3387
3388 EvalError ee ;
3389 ee.setMessage(message) ;
3390
3391 if (serverValueString) {
3392 ee.setServerValues(serverValueString) ;
3393 } else {
3394 std::string srvval ;
3395 std::ostringstream oss ;
3396 bool first(true) ;
3397 for (Int_t i=0 ; i<numProxies() ; i++) {
3398 RooAbsProxy* p = getProxy(i) ;
3399 if (!p) continue ;
3400 //if (p->name()[0]=='!') continue ;
3401 if (first) {
3402 first=false ;
3403 } else {
3404 oss << ", " ;
3405 }
3406 p->print(oss,true) ;
3407 }
3408 ee.setServerValues(oss.str().c_str()) ;
3409 }
3410
3411 std::ostringstream oss2 ;
3413
3414 if (evalErrorData().mode == PrintErrors) {
3415 coutE(Eval) << "RooAbsReal::logEvalError(" << GetName() << ") evaluation error, " << std::endl
3416 << " origin : " << oss2.str() << std::endl
3417 << " message : " << ee._msg << std::endl
3418 << " server values: " << ee._srvval << std::endl ;
3419 } else if (evalErrorData().mode == CollectErrors) {
3420 auto &evalErrorList = evalErrorData().errorList[this];
3421 if (evalErrorList.second.size() >= 2048) {
3422 // avoid overflowing the error list, so if there are very many, print
3423 // the oldest one first, and pop it off the list
3424 const EvalError& oee = evalErrorList.second.front();
3425 // print to debug stream, since these would normally be suppressed, and
3426 // we do not want to increase the error count in the message service...
3427 ccoutD(Eval) << "RooAbsReal::logEvalError(" << GetName()
3428 << ") delayed evaluation error, " << std::endl
3429 << " origin : " << oss2.str() << std::endl
3430 << " message : " << oee._msg << std::endl
3431 << " server values: " << oee._srvval << std::endl ;
3432 evalErrorList.second.pop_front();
3433 }
3434 evalErrorList.first = oss2.str() ;
3435 evalErrorList.second.push_back(ee) ;
3436 }
3437
3439 //coutE(Tracing) << "RooAbsReal::logEvalError(" << GetName() << ") message = " << message << std::endl ;
3440}
3441
3442
3443
3444
3445////////////////////////////////////////////////////////////////////////////////
3446/// Clear the stack of evaluation error messages
3447
3449{
3450 if (evalErrorData().mode == PrintErrors) {
3451 return ;
3452 } else if (evalErrorData().mode == CollectErrors) {
3453 evalErrorData().errorList.clear() ;
3454 } else {
3455 evalErrorData().count = 0 ;
3456 }
3457}
3458
3459
3460////////////////////////////////////////////////////////////////////////////////
3461/// Retrieve bin boundaries if this distribution is binned in `obs`.
3462/// \param[in] obs Observable to retrieve boundaries for.
3463/// \param[in] xlo Beginning of range.
3464/// \param[in] xhi End of range.
3465/// \return The caller owns the returned std::list.
3466std::list<double>* RooAbsReal::binBoundaries(RooAbsRealLValue& /*obs*/, double /*xlo*/, double /*xhi*/) const {
3467 return nullptr;
3468}
3469
3470
3471////////////////////////////////////////////////////////////////////////////////
3472/// Interface for returning an optional hint for initial sampling points when constructing a curve projected on observable `obs`.
3473/// \param[in] obs Observable to retrieve sampling hint for.
3474/// \param[in] xlo Beginning of range.
3475/// \param[in] xhi End of range.
3476/// \return The caller owns the returned std::list.
3477std::list<double>* RooAbsReal::plotSamplingHint(RooAbsRealLValue& /*obs*/, double /*xlo*/, double /*xhi*/) const {
3478 return nullptr;
3479}
3480
3481////////////////////////////////////////////////////////////////////////////////
3482/// Print all outstanding logged evaluation error on the given ostream. If maxPerNode
3483/// is zero, only the number of errors for each source (object with unique name) is listed.
3484/// If maxPerNode is greater than zero, up to maxPerNode detailed error messages are shown
3485/// per source of errors. A truncation message is shown if there were more errors logged
3486/// than shown.
3487
3489{
3490 if (evalErrorData().mode == CountErrors) {
3491 os << evalErrorData().count << " errors counted" << std::endl;
3492 }
3493
3494 if (maxPerNode < 0)
3495 return;
3496
3497 for (auto const &item : evalErrorData().errorList) {
3498 if (maxPerNode == 0) {
3499
3500 // Only print node name with total number of errors
3501 os << item.second.first;
3502 // item.first->printStream(os,kName|kClassName|kArgs,kInline) ;
3503 os << " has " << item.second.second.size() << " errors" << std::endl;
3504
3505 } else {
3506
3507 // Print node name and details of 'maxPerNode' errors
3508 os << item.second.first << std::endl;
3509 // item.first->printStream(os,kName|kClassName|kArgs,kSingleLine) ;
3510
3511 Int_t i(0);
3512 for (auto const &item2 : item.second.second) {
3513 os << " " << item2._msg << " @ " << item2._srvval << std::endl;
3514 if (i > maxPerNode) {
3515 os << " ... (remaining " << item.second.second.size() - maxPerNode << " messages suppressed)"
3516 << std::endl;
3517 break;
3518 }
3519 i++;
3520 }
3521 }
3522 }
3523}
3524
3525
3526
3527////////////////////////////////////////////////////////////////////////////////
3528/// Return the number of logged evaluation errors since the last clearing.
3529
3531{
3532 auto &evalErrors = evalErrorData();
3533 if (evalErrors.mode == CountErrors) {
3534 return evalErrors.count;
3535 }
3536
3537 Int_t ntot(0);
3538 for (auto const &elem : evalErrors.errorList) {
3539 ntot += elem.second.second.size();
3540 }
3541 return ntot;
3542}
3543
3544
3545
3546////////////////////////////////////////////////////////////////////////////////
3547/// Fix the interpretation of the coefficient of any RooAddPdf component in
3548/// the expression tree headed by this object to the given set of observables.
3549///
3550/// If the force flag is false, the normalization choice is only fixed for those
3551/// RooAddPdf components that have the default 'automatic' interpretation of
3552/// coefficients (i.e. the interpretation is defined by the observables passed
3553/// to getVal()). If force is true, also RooAddPdf that already have a fixed
3554/// interpretation are changed to a new fixed interpretation.
3555
3557{
3558 std::unique_ptr<RooArgSet> compSet{getComponents()};
3559 for(auto * pdf : dynamic_range_cast<RooAbsPdf*>(*compSet)) {
3560 if (pdf) {
3561 pdf->selectNormalization(addNormSet.empty() ? nullptr : &addNormSet,force);
3562 }
3563 }
3564}
3565
3566
3567
3568////////////////////////////////////////////////////////////////////////////////
3569/// Fix the interpretation of the coefficient of any RooAddPdf component in
3570/// the expression tree headed by this object to the given set of observables.
3571///
3572/// If the force flag is false, the normalization range choice is only fixed for those
3573/// RooAddPdf components that currently use the default full domain to interpret their
3574/// coefficients. If force is true, also RooAddPdf that already have a fixed
3575/// interpretation range are changed to a new fixed interpretation range.
3576
3578{
3579 std::unique_ptr<RooArgSet> compSet{getComponents()};
3580 for(auto * pdf : dynamic_range_cast<RooAbsPdf*>(*compSet)) {
3581 if (pdf) {
3582 pdf->selectNormalizationRange(rangeName,force) ;
3583 }
3584 }
3585}
3586
3587
3588
3589////////////////////////////////////////////////////////////////////////////////
3590/// Interface method for function objects to indicate their preferred order of observables
3591/// for scanning their values into a (multi-dimensional) histogram or RooDataSet. The observables
3592/// to be ordered are offered in argument 'obs' and should be copied in their preferred
3593/// order into argument 'orderedObs', This default implementation indicates no preference
3594/// and copies the original order of 'obs' into 'orderedObs'
3595
3597{
3598 // Dummy implementation, do nothing
3599 orderedObs.removeAll() ;
3600 orderedObs.add(obs) ;
3601}
3602
3603
3604
3605////////////////////////////////////////////////////////////////////////////////
3606/// Calls createRunningIntegral(const RooArgSet&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&)
3607
3612
3613
3614
3615////////////////////////////////////////////////////////////////////////////////
3616/// Create an object that represents the running integral of the function over one or more observables listed in iset, i.e.
3617/// \f[
3618/// \int_{x_\mathrm{lo}}^x f(x') \, \mathrm{d}x'
3619/// \f]
3620///
3621/// The actual integration calculation is only performed when the return object is evaluated. The name
3622/// of the integral object is automatically constructed from the name of the input function, the variables
3623/// it integrates and the range integrates over. The default strategy to calculate the running integrals is
3624///
3625/// - If the integrand (this object) supports analytical integration, construct an integral object
3626/// that calculate the running integrals value by calculating the analytical integral each
3627/// time the running integral object is evaluated
3628///
3629/// - If the integrand (this object) requires numeric integration to construct the running integral
3630/// create an object of class RooNumRunningInt which first samples the entire function and integrates
3631/// the sampled function numerically. This method has superior performance as there is no need to
3632/// perform a full (numeric) integration for each evaluation of the running integral object, but
3633/// only when one of its parameters has changed.
3634///
3635/// The choice of strategy can be changed with the ScanAll() argument, which forces the use of the
3636/// scanning technique implemented in RooNumRunningInt for all use cases, and with the ScanNone()
3637/// argument which forces the 'integrate each evaluation' technique for all use cases. The sampling
3638/// granularity for the scanning technique can be controlled with the ScanParameters technique
3639/// which allows to specify the number of samples to be taken, and to which order the resulting
3640/// running integral should be interpolated. The default values are 1000 samples and 2nd order
3641/// interpolation.
3642///
3643/// The following named arguments are accepted
3644/// | | Effect on integral creation
3645/// |-|-------------------------------
3646/// | `SupNormSet(const RooArgSet&)` | Observables over which should be normalized _in addition_ to the integration observables
3647/// | `ScanParameters(Int_t nbins, Int_t intOrder)` | Parameters for scanning technique of making CDF: number of sampled bins and order of interpolation applied on numeric cdf
3648/// | `ScanNum()` | Apply scanning technique if cdf integral involves numeric integration
3649/// | `ScanAll()` | Always apply scanning technique
3650/// | `ScanNone()` | Never apply scanning technique
3651
3653 const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5,
3654 const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
3655{
3656 // Define configuration for this method
3657 RooCmdConfig pc("RooAbsReal::createRunningIntegral(" + std::string(GetName()) + ")");
3658 pc.defineSet("supNormSet","SupNormSet",0,nullptr) ;
3659 pc.defineInt("numScanBins","ScanParameters",0,1000) ;
3660 pc.defineInt("intOrder","ScanParameters",1,2) ;
3661 pc.defineInt("doScanNum","ScanNum",0,1) ;
3662 pc.defineInt("doScanAll","ScanAll",0,0) ;
3663 pc.defineInt("doScanNon","ScanNone",0,0) ;
3664 pc.defineMutex("ScanNum","ScanAll","ScanNone") ;
3665
3666 // Process & check varargs
3668 if (!pc.ok(true)) {
3669 return nullptr ;
3670 }
3671
3672 // Extract values from named arguments
3673 RooArgSet nset ;
3674 if (const RooArgSet* snset = pc.getSet("supNormSet",nullptr)) {
3675 nset.add(*snset) ;
3676 }
3677 Int_t numScanBins = pc.getInt("numScanBins") ;
3678 Int_t intOrder = pc.getInt("intOrder") ;
3679 Int_t doScanNum = pc.getInt("doScanNum") ;
3680 Int_t doScanAll = pc.getInt("doScanAll") ;
3681 Int_t doScanNon = pc.getInt("doScanNon") ;
3682
3683 // If scanning technique is not requested make integral-based cdf and return
3684 if (doScanNon) {
3685 return createIntRI(iset,nset) ;
3686 }
3687 if (doScanAll) {
3688 return createScanRI(iset,nset,numScanBins,intOrder) ;
3689 }
3690 if (doScanNum) {
3691 std::unique_ptr<RooAbsReal> tmp{createIntegral(iset)} ;
3692 Int_t isNum= !static_cast<RooRealIntegral&>(*tmp).numIntRealVars().empty();
3693
3694 if (isNum) {
3695 coutI(NumericIntegration) << "RooAbsPdf::createRunningIntegral(" << GetName() << ") integration over observable(s) " << iset << " involves numeric integration," << std::endl
3696 << " constructing cdf though numeric integration of sampled pdf in " << numScanBins << " bins and applying order "
3697 << intOrder << " interpolation on integrated histogram." << std::endl
3698 << " To override this choice of technique use argument ScanNone(), to change scan parameters use ScanParameters(nbins,order) argument" << std::endl ;
3699 }
3700
3701 return isNum ? createScanRI(iset,nset,numScanBins,intOrder) : createIntRI(iset,nset) ;
3702 }
3703 return nullptr;
3704}
3705
3706
3707
3708////////////////////////////////////////////////////////////////////////////////
3709/// Utility function for createRunningIntegral that construct an object
3710/// implementing the numeric scanning technique for calculating the running integral
3711
3713{
3714 std::string name = std::string(GetName()) + "_NUMRUNINT_" + integralNameSuffix(iset,&nset).Data() ;
3715 RooRealVar* ivar = static_cast<RooRealVar*>(iset.first()) ;
3716 ivar->setBins(numScanBins,"numcdf") ;
3717 auto ret = std::make_unique<RooNumRunningInt>(name.c_str(),name.c_str(),*this,*ivar,"numrunint") ;
3718 ret->setInterpolationOrder(intOrder) ;
3719 return RooFit::makeOwningPtr<RooAbsReal>(std::move(ret));
3720}
3721
3722
3723
3724////////////////////////////////////////////////////////////////////////////////
3725/// Utility function for createRunningIntegral. It creates an
3726/// object implementing the standard (analytical) integration
3727/// technique for calculating the running integral.
3728
3730{
3731 // Make list of input arguments keeping only RooRealVars
3733 for(RooAbsArg * arg : iset) {
3734 if (dynamic_cast<RooRealVar*>(arg)) {
3735 ilist.add(*arg) ;
3736 } else {
3737 coutW(InputArguments) << "RooAbsPdf::createRunningIntegral(" << GetName() << ") WARNING ignoring non-RooRealVar input argument " << arg->GetName() << std::endl ;
3738 }
3739 }
3740
3744
3745 // Setup customizer that stores all cloned branches in our non-owning list
3746 RooCustomizer cust(*this,"cdf") ;
3747 cust.setCloneBranchSet(clonedBranchNodes) ;
3748 cust.setOwning(false) ;
3749
3750 // Make integration observable x_prime for each observable x as well as an x_lowbound
3752
3753 // Make clone x_prime of each c.d.f observable x represening running integral
3754 RooRealVar* cloneArg = static_cast<RooRealVar*>(rrv->clone(Form("%s_prime",rrv->GetName()))) ;
3755 cloneList.add(*cloneArg) ;
3756 cust.replaceArg(*rrv,*cloneArg) ;
3757
3758 // Make clone x_lowbound of each c.d.f observable representing low bound of x
3759 RooRealVar* cloneLo = static_cast<RooRealVar*>(rrv->clone(Form("%s_lowbound",rrv->GetName()))) ;
3760 cloneLo->setVal(rrv->getMin()) ;
3761 loList.add(*cloneLo) ;
3762
3763 // Make parameterized binning from [x_lowbound,x] for each x_prime
3764 RooParamBinning pb(*cloneLo,*rrv,100) ;
3765 cloneArg->setBinning(pb,"CDF") ;
3766
3767 }
3768
3769 RooAbsReal* tmp = static_cast<RooAbsReal*>(cust.build()) ;
3770
3771 // Construct final normalization set for c.d.f = integrated observables + any extra specified by user
3772 RooArgSet finalNset(nset) ;
3773 finalNset.add(cloneList,true) ;
3774 std::unique_ptr<RooAbsReal> cdf{tmp->createIntegral(cloneList,finalNset,"CDF")};
3775
3776 // Transfer ownership of cloned items to top-level c.d.f object
3777 cdf->addOwnedComponents(*tmp) ;
3778 cdf->addOwnedComponents(cloneList) ;
3779 cdf->addOwnedComponents(loList) ;
3780
3781 return RooFit::makeOwningPtr(std::move(cdf));
3782}
3783
3784
3785////////////////////////////////////////////////////////////////////////////////
3786/// Return a RooFunctor object bound to this RooAbsReal with given definition of observables
3787/// and parameters
3788
3789RooFunctor* RooAbsReal::functor(const RooArgList& obs, const RooArgList& pars, const RooArgSet& nset) const
3790{
3792 getObservables(&obs, realObs);
3793 if (realObs.size() != obs.size()) {
3794 coutE(InputArguments) << "RooAbsReal::functor(" << GetName() << ") ERROR: one or more specified observables are not variables of this p.d.f" << std::endl ;
3795 return nullptr;
3796 }
3798 getObservables(&pars, realPars);
3799 if (realPars.size() != pars.size()) {
3800 coutE(InputArguments) << "RooAbsReal::functor(" << GetName() << ") ERROR: one or more specified parameters are not variables of this p.d.f" << std::endl ;
3801 return nullptr;
3802 }
3803
3804 return new RooFunctor(*this,obs,pars,nset) ;
3805}
3806
3807
3808
3809////////////////////////////////////////////////////////////////////////////////
3810/// Return a ROOT TF1,2,3 object bound to this RooAbsReal with given definition of observables
3811/// and parameters
3812
3813TF1* RooAbsReal::asTF(const RooArgList& obs, const RooArgList& pars, const RooArgSet& nset) const
3814{
3815 // Check that specified input are indeed variables of this function
3817 getObservables(&obs, realObs) ;
3818 if (realObs.size() != obs.size()) {
3819 coutE(InputArguments) << "RooAbsReal::functor(" << GetName() << ") ERROR: one or more specified observables are not variables of this p.d.f" << std::endl ;
3820 return nullptr ;
3821 }
3823 getObservables(&pars, realPars) ;
3824 if (realPars.size() != pars.size()) {
3825 coutE(InputArguments) << "RooAbsReal::functor(" << GetName() << ") ERROR: one or more specified parameters are not variables of this p.d.f" << std::endl ;
3826 return nullptr ;
3827 }
3828
3829 // Check that all obs and par are of type RooRealVar
3830 for (std::size_t i=0 ; i<obs.size() ; i++) {
3831 if (dynamic_cast<RooRealVar*>(obs.at(i))==nullptr) {
3832 coutE(ObjectHandling) << "RooAbsReal::asTF(" << GetName() << ") ERROR: proposed observable " << obs.at(0)->GetName() << " is not of type RooRealVar" << std::endl ;
3833 return nullptr ;
3834 }
3835 }
3836 for (std::size_t i=0 ; i<pars.size() ; i++) {
3837 if (dynamic_cast<RooRealVar*>(pars.at(i))==nullptr) {
3838 coutE(ObjectHandling) << "RooAbsReal::asTF(" << GetName() << ") ERROR: proposed parameter " << pars.at(0)->GetName() << " is not of type RooRealVar" << std::endl ;
3839 return nullptr ;
3840 }
3841 }
3842
3843 // Create functor and TFx of matching dimension
3844 TF1* tf=nullptr ;
3845 RooFunctor* f ;
3846 switch(obs.size()) {
3847 case 1: {
3848 RooRealVar* x = static_cast<RooRealVar*>(obs.at(0)) ;
3849 f = functor(obs,pars,nset) ;
3850 tf = new TF1(GetName(),f,x->getMin(),x->getMax(),pars.size()) ;
3851 break ;
3852 }
3853 case 2: {
3854 RooRealVar* x = static_cast<RooRealVar*>(obs.at(0)) ;
3855 RooRealVar* y = static_cast<RooRealVar*>(obs.at(1)) ;
3856 f = functor(obs,pars,nset) ;
3857 tf = new TF2(GetName(),f,x->getMin(),x->getMax(),y->getMin(),y->getMax(),pars.size()) ;
3858 break ;
3859 }
3860 case 3: {
3861 RooRealVar* x = static_cast<RooRealVar*>(obs.at(0)) ;
3862 RooRealVar* y = static_cast<RooRealVar*>(obs.at(1)) ;
3863 RooRealVar* z = static_cast<RooRealVar*>(obs.at(2)) ;
3864 f = functor(obs,pars,nset) ;
3865 tf = new TF3(GetName(),f,x->getMin(),x->getMax(),y->getMin(),y->getMax(),z->getMin(),z->getMax(),pars.size()) ;
3866 break ;
3867 }
3868 default:
3869 coutE(InputArguments) << "RooAbsReal::asTF(" << GetName() << ") ERROR: " << obs.size()
3870 << " observables specified, but a ROOT TFx can only have 1,2 or 3 observables" << std::endl ;
3871 return nullptr ;
3872 }
3873
3874 // Set initial parameter values of TFx to those of RooRealVars
3875 for (std::size_t i=0 ; i<pars.size() ; i++) {
3876 RooRealVar* p = static_cast<RooRealVar*>(pars.at(i)) ;
3877 tf->SetParameter(i,p->getVal()) ;
3878 tf->SetParName(i,p->GetName()) ;
3879 //tf->SetParLimits(i,p->getMin(),p->getMax()) ;
3880 }
3881
3882 return tf ;
3883}
3884
3885
3886////////////////////////////////////////////////////////////////////////////////
3887/// Return function representing first, second or third order derivative of this function
3888
3890{
3891 return derivative(obs, {}, order, eps);
3892}
3893
3894
3895
3896////////////////////////////////////////////////////////////////////////////////
3897/// Return function representing first, second or third order derivative of this function
3898
3900{
3901 std::string name=Form("%s_DERIV_%d%s",GetName(),order,obs.GetName()) ;
3902 std::string title=Form("%dDerivative of %s w.r.t %s ",order,GetName(),obs.GetName()) ;
3903 return new RooDerivative(name.c_str(),title.c_str(),*this,obs,normSet,order,eps) ;
3904}
3905
3906
3907
3908////////////////////////////////////////////////////////////////////////////////
3909/// Return function representing moment of function of given order.
3910/// \param[in] obs Observable to calculate the moments for
3911/// \param[in] order Order of the moment
3912/// \param[in] central If true, the central moment is given by \f$ \langle (x- \langle x \rangle )^2 \rangle \f$
3913/// \param[in] takeRoot Calculate the square root
3914
3916{
3917 std::string name=Form("%s_MOMENT_%d%s_%s",GetName(),order,(central?"C":""),obs.GetName()) ;
3918 std::string title=Form("%sMoment of order %d of %s w.r.t %s ",(central?"Central ":""),order,GetName(),obs.GetName()) ;
3919 if (order==1) return new RooFirstMoment(name.c_str(),title.c_str(),*this,obs) ;
3920 if (order==2) return new RooSecondMoment(name.c_str(),title.c_str(),*this,obs,central,takeRoot) ;
3921 return new RooMoment(name.c_str(),title.c_str(),*this,obs,order,central,takeRoot) ;
3922}
3923
3924
3925////////////////////////////////////////////////////////////////////////////////
3926/// Return function representing moment of p.d.f (normalized w.r.t given observables) of given order.
3927/// \param[in] obs Observable to calculate the moments for
3928/// \param[in] normObs Normalise w.r.t. these observables
3929/// \param[in] order Order of the moment
3930/// \param[in] central If true, the central moment is given by \f$ \langle (x- \langle x \rangle )^2 \rangle \f$
3931/// \param[in] takeRoot Calculate the square root
3932/// \param[in] intNormObs If true, the moment of the function integrated over all normalization observables is returned.
3933
3935{
3936 std::string name=Form("%s_MOMENT_%d%s_%s",GetName(),order,(central?"C":""),obs.GetName()) ;
3937 std::string title=Form("%sMoment of order %d of %s w.r.t %s ",(central?"Central ":""),order,GetName(),obs.GetName()) ;
3938
3939 if (order==1) return new RooFirstMoment(name.c_str(),title.c_str(),*this,obs,normObs,intNormObs) ;
3940 if (order==2) return new RooSecondMoment(name.c_str(),title.c_str(),*this,obs,normObs,central,takeRoot,intNormObs) ;
3941 return new RooMoment(name.c_str(),title.c_str(),*this,obs,normObs,order,central,takeRoot,intNormObs) ;
3942}
3943
3944
3945
3946////////////////////////////////////////////////////////////////////////////////
3947///
3948/// Return value of x (in range xmin,xmax) at which function equals yval.
3949/// (Calculation is performed with Brent root finding algorithm)
3950
3951double RooAbsReal::findRoot(RooRealVar& x, double xmin, double xmax, double yval)
3952{
3953 double result(0) ;
3955 return result ;
3956}
3957
3958
3959////////////////////////////////////////////////////////////////////////////////
3960/// \fn RooAbsReal::chi2FitTo(RooDataHist& data, CmdArgs_t const&... cmdArgs)
3961///
3962/// Calls RooAbsReal::createChi2 and returns the fit result.
3963/// Perform a \f$ \chi^2 \f$ fit to given histogram. By default the fit is executed through the MINUIT
3964/// commands MIGRAD, HESSE in succession
3965///
3966/// The following named arguments are supported:
3967///
3968/// <table>
3969/// <tr><th> Type of CmdArg <th> Effect on \f$ \chi^2 \f$
3970/// <tr><td> `DataError()` <td> Choose between:
3971/// - RooAbsData::Expected: Expected Poisson error (\f$ \sqrt{n_\text{expected}} \f$ from the PDF).
3972/// - RooAbsData::SumW2: The observed error from the square root of the sum of weights squared,
3973/// i.e., symmetric errors calculated with the standard deviation of a Poisson distribution.
3974/// - RooAbsData::Poisson: Asymmetric errors from the central 68 % interval around a Poisson distribution with mean \f$ n_\text{observed} \f$.
3975/// If for a given bin \f$ n_\text{expected} \f$ is lower than the \f$ n_\text{observed} \f$, the lower uncertainty is taken
3976/// (e.g., the difference between the mean and the 16 % quantile).
3977/// If \f$ n_\text{expected} \f$ is higher than \f$ n_\text{observed} \f$, the higher uncertainty is taken
3978/// (e.g., the difference between the 84 % quantile and the mean).
3979/// - RooAbsData::Auto (default): RooAbsData::Expected for unweighted data, RooAbsData::SumW2 for weighted data.
3980/// <tr><td> `Extended(bool flag)` <td> **Only applicable when fitting a RooAbsPdf**. Scale the normalized pdf by the number of events predicted by the model instead of scaling by the total data weight.
3981/// This imposes a constraint on the predicted number of events analogous to the extended term in a likelihood fit.
3982/// - If you don't pass this command, an extended fit will be done by default if the pdf makes a prediction on the number of events
3983/// (in RooFit jargon, "if the pdf can be extended").
3984/// - Passing `Extended(true)` when the the pdf makes no prediction on the expected number of events will result in error messages,
3985/// and the chi2 will fall back to the total data weight to scale the normalized pdf.
3986/// - There are cases where the fit **must** be done in extended mode. This happens for example when you have a RooAddPdf
3987/// where the coefficients represent component yields. If the fit is not extended, these coefficients will not be
3988/// well-defined, as the RooAddPdf always normalizes itself. If you pass `Extended(false)` in such a case, an error will be
3989/// printed and you'll most likely get garbage results.
3990/// <tr><td> `Range(const char* name)` <td> Fit only data inside range with given name
3991/// <tr><td> `Range(double lo, double hi)` <td> Fit only data inside given range. A range named "fit" is created on the fly on all observables.
3992/// Multiple comma separated range names can be specified.
3993/// <tr><td> `NumCPU(int num)` <td> Parallelize NLL calculation on num CPUs
3994/// <tr><td> `IntegrateBins()` <td> Integrate PDF within each bin. This sets the desired precision.
3995/// <tr><td> `Verbose()` <td> Verbose output of GOF framework
3996/// <tr><td> `SumCoefRange()` <td> Set the range in which to interpret the coefficients of RooAddPdf components
3997/// <tr><td> `SplitRange()` <td> Fit ranges used in different categories get named after the category.
3998/// Using `Range("range"), SplitRange()` as switches, different ranges could be set like this:
3999/// ```
4000/// myVariable.setRange("range_pi0", 135, 210);
4001/// myVariable.setRange("range_gamma", 50, 210);
4002/// ```
4003/// <tr><td> `ConditionalObservables(Args_t &&... argsOrArgSet)` <td> Define projected observables.
4004/// Arguments can either be multiple RooRealVar or a single RooArgSet containing them.
4005///
4006/// <tr><th> <th> Options to control flow of fit procedure
4007/// <tr><td> `InitialHesse(bool flag)` <td> Flag controls if HESSE before MIGRAD as well, off by default
4008/// <tr><td> `Hesse(bool flag)` <td> Flag controls if HESSE is run after MIGRAD, on by default
4009/// <tr><td> `Minos(bool flag)` <td> Flag controls if MINOS is run after HESSE, on by default
4010/// <tr><td> `Minos(const RooArgSet& set)` <td> Only run MINOS on given subset of arguments
4011/// <tr><td> `Save(bool flag)` <td> Flag controls if RooFitResult object is produced and returned, off by default
4012/// <tr><td> `Strategy(Int_t flag)` <td> Set Minuit strategy (0 through 2, default is 1)
4013///
4014/// <tr><th> <th> Options to control informational output
4015/// <tr><td> `Verbose(bool flag)` <td> Flag controls if verbose output is printed (NLL, parameter changes during fit
4016/// <tr><td> `Timer(bool flag)` <td> Time CPU and wall clock consumption of fit steps, off by default
4017/// <tr><td> `PrintLevel(Int_t level)` <td> Set Minuit print level (-1 through 3, default is 1). At -1 all RooFit informational
4018/// messages are suppressed as well
4019/// <tr><td> `Warnings(bool flag)` <td> Enable or disable MINUIT warnings (enabled by default)
4020/// <tr><td> `PrintEvalErrors(Int_t numErr)` <td> Control number of p.d.f evaluation errors printed per likelihood evaluation. A negative
4021/// value suppress output completely, a zero value will only print the error count per p.d.f component,
4022/// a positive value is will print details of each error up to numErr messages per p.d.f component.
4023/// </table>
4024///
4025
4026std::unique_ptr<RooFitResult> RooAbsReal::chi2FitToImpl(RooDataHist &data, const RooLinkedList &cmdList)
4027{
4028 return RooFit::FitHelpers::fitTo(*this, data, cmdList, true);
4029}
4030
4031
4032////////////////////////////////////////////////////////////////////////////////
4033/// \fn RooAbsReal::createChi2(RooDataHist& data, CmdArgs_t const&... cmdArgs)
4034///
4035/// Create a \f$ \chi^2 \f$ variable from a histogram and this function.
4036///
4037/// See also RooAbsReal::chi2FitTo for the list of possible command arguments to this function.
4038///
4039/// It calculates:
4040///
4041/// \f{align*}{
4042/// \chi^2 &= \sum_{\mathrm{bins}} \left( \frac{N_\mathrm{PDF,bin} - N_\mathrm{Data,bin}}{\Delta_\mathrm{bin}} \right)^2
4043/// N_\mathrm{PDF,bin} &=
4044/// \begin{cases}
4045/// \mathrm{pdf}(\text{bin centre}) \cdot V_\mathrm{bin} \cdot N_\mathrm{Data,tot} &\text{normal PDF}
4046/// \mathrm{pdf}(\text{bin centre}) \cdot V_\mathrm{bin} \cdot N_\mathrm{Data,expected} &\text{extended PDF}
4047/// \end{cases}
4048/// \Delta_\mathrm{bin} &=
4049/// \begin{cases}
4050/// \sqrt{N_\mathrm{PDF,bin}} &\text{if } \mathtt{DataError == RooAbsData::Expected}
4051/// \mathtt{data{\rightarrow}weightError()} &\text{otherwise}
4052/// \end{cases}
4053/// \f}
4054///
4055/// If the dataset doesn't have user-defined errors, errors are assumed to be \f$ \sqrt{N} \f$.
4056/// In extended PDF mode, N_tot (total number of data events) is substituted with N_expected, the
4057/// expected number of events that the PDF predicts.
4058///
4059/// \note If the dataset has errors stored, empty bins will prevent the calculation of \f$ \chi^2 \f$, because those have
4060/// zero error. This leads to messages like:
4061/// ```
4062/// [#0] ERROR:Eval -- RooChi2Var::RooChi2Var(chi2_GenPdf_data_hist) INFINITY ERROR: bin 2 has zero error
4063/// ```
4064///
4065/// \note In this case, one can use the expected errors of the PDF instead of the data errors:
4066/// ```{.cpp}
4067/// RooChi2Var chi2(..., ..., RooFit::DataError(RooAbsData::Expected), ...);
4068/// ```
4069///
4070/// \param data Histogram with data
4071/// \param arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 ordered arguments
4072/// \return \f$ \chi^2 \f$ variable
4073
4075{
4076 return RooFit::FitHelpers::createChi2(*this, data, cmdList);
4077}
4078
4079////////////////////////////////////////////////////////////////////////////////
4080/// Return current evaluation error logging mode.
4081
4086
4087////////////////////////////////////////////////////////////////////////////////
4088/// Set evaluation error logging mode. Options are
4089///
4090/// PrintErrors - Print each error through RooMsgService() as it occurs
4091/// CollectErrors - Accumulate errors, but do not print them. A subsequent call
4092/// to printEvalErrors() will print a summary
4093/// CountErrors - Accumulate error count, but do not print them.
4094///
4095
4100
4101
4102////////////////////////////////////////////////////////////////////////////////
4103
4105{
4106 std::string plist ;
4107 for (auto const* arg : paramVars) {
4108 if (!dependsOnValue(*arg)) {
4109 coutW(InputArguments) << "RooAbsReal::setParameterizeIntegral(" << GetName()
4110 << ") function does not depend on listed parameter " << arg->GetName() << ", ignoring" << std::endl ;
4111 continue ;
4112 }
4113 if (!plist.empty()) plist += ":" ;
4114 plist += arg->GetName() ;
4115 }
4116 setStringAttribute("CACHEPARAMINT",plist.c_str()) ;
4117}
4118
4119
4120/** Base function for computing multiple values of a RooAbsReal.
4121\param ctx An evaluation context object
4122**/
4124{
4125 std::span<double> output = ctx.output();
4126
4127 // Find all servers that are serving real numbers to us, retrieve their batch data,
4128 // and switch them into "always clean" operating mode, so they return always the last-set value.
4129 struct ServerData {
4131 std::span<const double> batch;
4132 double oldValue;
4134 bool oldValueDirty;
4135 bool oldShapeDirty;
4136 };
4137 std::vector<ServerData> ourServers;
4138 ourServers.reserve(servers().size());
4139
4140 for (auto server : servers()) {
4141 auto serverValues = ctx.at(server);
4142 if(serverValues.empty()) continue;
4143
4144 if(!server->isValueServer(*this)) continue;
4145
4146 // maybe we are still missing inhibit dirty here
4147 auto oldOperMode = server->operMode();
4148 // See note at the bottom of this function to learn why we can only set
4149 // the operation mode to "always clean" if there are no other value
4150 // clients.
4151 server->setOperMode(RooAbsArg::AClean);
4152 ourServers.push_back({server,
4154 server->isCategory() ? static_cast<RooAbsCategory const*>(server)->getCurrentIndex() : static_cast<RooAbsReal const*>(server)->_value,
4156 server->_valueDirty,
4157 server->_shapeDirty});
4158 // Prevent the server from evaluating; just return cached result, which we will side load:
4159 }
4160
4161
4162 // Make sure that we restore all state when we finish:
4163 struct RestoreStateRAII {
4164 RestoreStateRAII(std::vector<ServerData>& servers) :
4165 _servers{servers} { }
4166
4168 for (auto& serverData : _servers) {
4169 serverData.server->setCachedValue(serverData.oldValue, true);
4170 serverData.server->setOperMode(serverData.oldOperMode);
4171 serverData.server->_valueDirty = serverData.oldValueDirty;
4172 serverData.server->_shapeDirty = serverData.oldShapeDirty;
4173 }
4174 }
4175
4176 std::vector<ServerData>& _servers;
4177 } restoreState{ourServers};
4178
4179 // Advising to implement the batch interface makes only sense if the batch was not a scalar.
4180 // Otherwise, there would be no speedup benefit. Warn only once per class, because doEval() is
4181 // called for every evaluation of the computation graph, e.g. in every minimizer iteration.
4182 if(output.size() > 1 && RooMsgService::instance().isActive(this, RooFit::FastEvaluations, RooFit::INFO)) {
4183 static std::set<std::string> warnedClasses;
4184 static std::mutex warnedClassesMutex;
4185 std::scoped_lock guard{warnedClassesMutex};
4186 if (warnedClasses.insert(ClassName()).second) {
4187 coutI(FastEvaluations) << "The class " << ClassName()
4188 << " does not implement the faster batch evaluation interface."
4189 << " Consider requesting or implementing it to benefit from a speed up." << std::endl;
4190 }
4191 }
4192
4193
4194 // For each event, write temporary values into our servers' caches, and run a single-value computation.
4195
4196 for (std::size_t i=0; i < output.size(); ++i) {
4197 for (auto& serv : ourServers) {
4198 serv.server->setCachedValue(serv.batch[std::min(i, serv.batch.size()-1)], false);
4199 }
4200
4201 output[i] = evaluate();
4202 }
4203}
4204
4206
4207 const bool tmpFast = _fast;
4208 const double tmp = _value;
4209
4210 double fullEval = 0.;
4211 try {
4213 }
4214 catch (CachingError& error) {
4215 throw CachingError(std::move(error),
4216 FormatPdfTree() << *this);
4217 }
4218
4219 const double ret = (_fast && !_inhibitDirty) ? _value : fullEval;
4220
4221 if (std::isfinite(ret) && ( ret != 0. ? (ret - fullEval)/ret : ret - fullEval) > 1.E-9) {
4222#ifndef NDEBUG
4224#endif
4226 formatter << "--> (Scalar computation wrong here:)\n"
4227 << GetName() << " " << this << " _fast=" << tmpFast
4228 << "\n\tcached _value=" << std::setprecision(16) << tmp
4229 << "\n\treturning =" << ret
4230 << "\n\trecomputed =" << fullEval
4231 << "\n\tnew _value =" << _value << "] ";
4232 formatter << "\nServers:";
4233 for (const auto server : _serverList) {
4234 formatter << "\n ";
4235 server->printStream(formatter.stream(), kName | kClassName | kArgs | kExtras | kAddress | kValue, kInline);
4236 }
4237
4238 throw CachingError(formatter);
4239 }
4240
4241 return ret;
4242}
4243
4244
4251
4252
4253////////////////////////////////////////////////////////////////////////////////
4254
4256{
4257 for (RooAbsArg* arg : servers()) {
4258 if(auto realArg = dynamic_cast<RooAbsReal*>(arg)) {
4259 realArg->enableOffsetting(flag) ;
4260 }
4261 }
4262}
4263
4264
4265RooAbsReal::Ref::Ref(double val) : _ref{RooFit::RooConst(val)} {}
4266
4267////////////////////////////////////////////////////////////////////////////////
4268/// Calling RooAbsReal::getVal() with an r-value reference is a common
4269/// performance trap, because this usually happens when implicitly constructing
4270/// the RooArgSet to be used as the parameter (for example, in calls like
4271/// `pdf.getVal(x)`).
4272///
4273/// Creating the RooArgSet can cause quite some overhead, especially when the
4274/// evaluated object is just a simple variable. Even worse, many RooFit objects
4275/// internally cache information using the uniqueId() of the normalization set
4276/// as the key. So by constructing normalization sets in place, RooFits caching
4277/// logic is broken.
4278///
4279/// To avoid these kind of problems, getVal() will just throw an error when
4280/// it's called with an r-value reference. This also catches the cases where
4281/// one uses it in Python, implicitly creating the normalization set from a
4282/// Python list or set.
4284{
4285 std::stringstream errMsg;
4286 errMsg << "calling RooAbsReal::getVal() with r-value references to the normalization set is not allowed, because "
4287 "it breaks RooFits caching logic and potentially introduces significant overhead. Please explicitly "
4288 "create the RooArgSet outside the call to getVal().";
4289 coutF(Eval) << errMsg.str() << std::endl;
4290 throw std::runtime_error(errMsg.str());
4291}
#define f(i)
Definition RSha256.hxx:104
#define e(i)
Definition RSha256.hxx:103
#define CREATE_CMD_LIST
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define coutI(a)
#define cxcoutD(a)
#define coutW(a)
#define ccoutP(a)
#define dologD(a)
#define coutF(a)
#define oocoutE(o, a)
#define coutE(a)
#define ccoutW(a)
#define ccoutD(a)
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
float Size_t
Attribute size (float)
Definition RtypesCore.h:104
char Text_t
General string (char)
Definition RtypesCore.h:77
static void indent(ostringstream &buf, int indent_level)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t SetLineColor
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char mode
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t format
char name[80]
Definition TGX11.cxx:142
float xmin
float ymin
float xmax
float ymax
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2571
R__EXTERN TSystem * gSystem
Definition TSystem.h:582
const_iterator begin() const
const_iterator end() const
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:76
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.
const TNamed * namePtr() const
De-duplicated pointer to this object's name.
Definition RooAbsArg.h:482
void setShapeDirty()
Notify that a shape-like property (e.g. binning) has changed.
Definition RooAbsArg.h:410
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
bool isValueDirtyAndClear() const
Definition RooAbsArg.h:351
bool _fast
Definition RooAbsArg.h:623
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
const Text_t * getStringAttribute(const Text_t *key) const
Get string attribute mapped under key 'key'.
RooFit::OwningPtr< RooArgSet > getComponents() const
Create a RooArgSet with all components (branch nodes) of the expression tree headed by this object.
const RefCountList_t & servers() const
List of all servers of this object.
Definition RooAbsArg.h:145
bool dependsOnValue(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=nullptr) const
Check whether this object depends on values from an element in the serverList.
Definition RooAbsArg.h:104
void setValueDirty()
Mark the element dirty. This forces a re-evaluation when a value is requested.
Definition RooAbsArg.h:404
RooFit::OwningPtr< RooArgSet > getVariables(bool stripDisconnected=true) const
Return RooArgSet with all variables (tree leaf nodes of expression tree)
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Implement multi-line detailed printing.
virtual RooAbsArg * cloneTree(const char *newname=nullptr) const
Clone tree expression of objects.
TString cleanBranchName() const
Construct a mangled name from the actual name that is free of any math symbols that might be interpre...
Int_t numProxies() const
Return the number of registered proxies.
static bool _inhibitDirty
Definition RooAbsArg.h:603
void setAttribute(const Text_t *name, bool value=true)
Set (default) or clear a named boolean attribute of this object.
void setProxyNormSet(const RooArgSet *nset)
Forward a change in the cached normalization argset to all the registered proxies.
void branchNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all branch nodes of the arg tree starting with ourself as top node.
RooAbsProxy * getProxy(Int_t index) const
Return the nth proxy from the proxy list.
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:88
RefCountList_t _serverList
Definition RooAbsArg.h:544
void leafNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool recurseNonDerived=false) const
Fill supplied list with all leaf nodes of the arg tree, starting with ourself as top node.
virtual bool isFundamental() const
Is this object a fundamental type that can be added to a dataset? Fundamental-type subclasses overrid...
Definition RooAbsArg.h:175
virtual bool redirectServersHook(const RooAbsCollection &newServerList, bool mustReplaceAll, bool nameChange, bool isRecursiveStep)
Function that is called at the end of redirectServers().
virtual bool checkObservables(const RooArgSet *nset) const
Overloadable function in which derived classes can implement consistency checks of the variables.
void treeNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=nullptr, bool doBranch=true, bool doLeaf=true, bool valueOnly=false, bool recurseNonDerived=false) const
Fill supplied list with nodes of the arg tree, following all server links, starting with ourself as t...
Abstract base class for RooRealVar binning definitions.
virtual bool isParameterized() const
Interface function.
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.
Abstract base class for objects that represent a discrete value that can be set from the outside,...
A space to attach TBranches.
Abstract container object that can hold multiple RooAbsArg objects.
RooFit::UniqueId< RooAbsCollection > const & uniqueId() const
Returns a unique ID that is different for every instantiated RooAbsCollection.
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.
Storage_t::size_type size() const
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:55
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Abstract interface for evaluating a real-valued function of one real variable and performing numerica...
Definition RooAbsFunc.h:27
Abstract base class for objects that are lvalues, i.e.
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:32
static TClass * Class()
@ CanNotBeExtended
Definition RooAbsPdf.h:208
Abstract interface for proxy classes.
Definition RooAbsProxy.h:37
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
virtual double getMax(const char *name=nullptr) const
Get maximum of currently defined range.
virtual void setVal(double value)=0
Set the current value of the object. Needs to be overridden by implementations.
virtual double getMin(const char *name=nullptr) const
Get minimum of currently defined range.
bool inRange(const char *name) const override
Check if current value is inside range with given name.
Ref(RooAbsReal &ref)
Definition RooAbsReal.h:74
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
RooDataHist * fillDataHist(RooDataHist *hist, const RooArgSet *nset, double scaleFactor, bool correctForBinVolume=false, bool showProgress=false) const
Fill a RooDataHist with values sampled from this function at the bin centers.
virtual void selectNormalizationRange(const char *rangeName=nullptr, bool force=false)
Interface function to force use of a given normalization range to interpret function value.
void plotOnCompSelect(RooArgSet *selNodes) const
Helper function for plotting of composite p.d.fs.
bool isSelectedComp() const
If true, the current pdf is a selected component (for use in plotting)
virtual std::list< double > * binBoundaries(RooAbsRealLValue &obs, double xlo, double xhi) const
Retrieve bin boundaries if this distribution is binned in obs.
void selectComp(bool flag)
Definition RooAbsReal.h:374
TString _label
Plot label for objects value.
Definition RooAbsReal.h:543
bool _selectComp
! Component selection flag for RooAbsPdf::plotCompOn
Definition RooAbsReal.h:547
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
double findRoot(RooRealVar &x, double xmin, double xmax, double yval)
Return value of x (in range xmin,xmax) at which function equals yval.
TreeReadBuffer * _treeReadBuffer
! A buffer for reading values from trees
Definition RooAbsReal.h:546
virtual double getValV(const RooArgSet *normalisationSet=nullptr) const
Return value of object.
static Int_t numEvalErrorItems()
RooAbsReal()
coverity[UNINIT_CTOR] Default constructor
friend class RooRealBinding
Definition RooAbsReal.h:401
virtual void fixAddCoefNormalization(const RooArgSet &addNormSet=RooArgSet(), bool force=true)
Fix the interpretation of the coefficient of any RooAddPdf component in the expression tree headed by...
virtual Int_t getAnalyticalIntegralWN(RooArgSet &allVars, RooArgSet &analVars, const RooArgSet *normSet, const char *rangeName=nullptr) const
Variant of getAnalyticalIntegral that is also passed the normalization set that should be applied to ...
bool _forceNumInt
Force numerical integration if flag set.
Definition RooAbsReal.h:544
~RooAbsReal() override
Destructor.
void setParameterizeIntegral(const RooArgSet &paramVars)
bool matchArgsByName(const RooArgSet &allArgs, RooArgSet &matchedArgs, const TList &nameList) const
Check if allArgs contains matching elements for each name in nameList.
static bool hideOffset()
TH1 * fillHistogram(TH1 *hist, const RooArgList &plotVars, double scaleFactor=1, const RooArgSet *projectedVars=nullptr, bool scaling=true, const RooArgSet *condObs=nullptr, bool setError=true) const
Fill the ROOT histogram 'hist' with values sampled from this function at the bin centers.
RooFit::OwningPtr< RooAbsReal > createScanRI(const RooArgSet &iset, const RooArgSet &nset, Int_t numScanBins, Int_t intOrder)
Utility function for createRunningIntegral that construct an object implementing the numeric scanning...
double _DEBUG_getVal(const RooArgSet *normalisationSet) const
Debug version of getVal(), which is slow and does error checking.
RooFit::OwningPtr< RooAbsArg > createFundamental(const char *newname=nullptr) const override
Create a RooRealVar fundamental object with our properties.
bool plotSanityChecks(RooPlot *frame) const
Utility function for plotOn(), perform general sanity check on frame to ensure safe plotting operatio...
RooFit::OwningPtr< RooAbsFunc > bindVars(const RooArgSet &vars, const RooArgSet *nset=nullptr, bool clipInvalid=false) const
Create an interface adaptor f(vars) that binds us to the specified variables (in arbitrary order).
virtual void selectNormalization(const RooArgSet *depSet=nullptr, bool force=false)
Interface function to force use of a given set of observables to interpret function value.
RooDerivative * derivative(RooRealVar &obs, Int_t order=1, double eps=0.001)
Return function representing first, second or third order derivative of this function.
TF1 * asTF(const RooArgList &obs, const RooArgList &pars=RooArgList(), const RooArgSet &nset=RooArgSet()) const
Return a ROOT TF1,2,3 object bound to this RooAbsReal with given definition of observables and parame...
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...
TString _unit
Unit for objects value.
Definition RooAbsReal.h:542
static RooNumIntConfig * defaultIntegratorConfig()
Returns the default numeric integration configuration for all RooAbsReals.
bool readFromStream(std::istream &is, bool compact, bool verbose=false) override
Read object contents from stream (dummy for now)
void fillTreeBranch(TTree &t) override
Fill the tree branch that associated with this object with its current value.
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Structure printing.
virtual RooPlot * plotAsymOn(RooPlot *frame, const RooAbsCategoryLValue &asymCat, PlotOpt o) const
bool operator==(double value) const
Equality operator comparing to a double.
static ErrorLoggingMode evalErrorLoggingMode()
Return current evaluation error logging mode.
bool redirectServersHook(const RooAbsCollection &newServerList, bool mustReplaceAll, bool nameChange, bool isRecursiveStep) override
Function that is called at the end of redirectServers().
virtual bool isValidReal(double, bool printError=false) const
Interface function to check if given value is a valid value for this object. Returns true unless over...
Definition RooAbsReal.h:447
void setIntegratorConfig()
Remove the specialized numeric integration configuration associated with this object.
void printValue(std::ostream &os) const override
Print object value.
bool isIdentical(const RooAbsArg &other, bool assumeSameType=false) const override
virtual RooFit::OwningPtr< RooAbsReal > createProfile(const RooArgSet &paramsOfInterest)
Create a RooProfileLL object that eliminates all nuisance parameters in the present function.
static bool _hideOffset
Offset hiding flag.
Definition RooAbsReal.h:551
void attachToVStore(RooVectorDataStore &vstore) override
void copyCache(const RooAbsArg *source, bool valueOnly=false, bool setValDirty=true) override
Copy the cached value of another RooAbsArg to our cache.
TH1 * createHistogram(RooStringView varNameList, Int_t xbins=0, Int_t ybins=0, Int_t zbins=0) const
Create and fill a ROOT histogram TH1, TH2 or TH3 with the values of this function for the variables w...
virtual void fixAddCoefRange(const char *rangeName=nullptr, bool force=true)
Fix the interpretation of the coefficient of any RooAddPdf component in the expression tree headed by...
double _value
Cache for current value of object.
Definition RooAbsReal.h:541
virtual double analyticalIntegral(Int_t code, const char *rangeName=nullptr) const
Implements the actual analytical integral(s) advertised by getAnalyticalIntegral.
void attachToTree(TTree &t, Int_t bufSize=32000) override
Attach object to a branch of given TTree.
RooNumIntConfig * specialIntegratorConfig() const
Returns the specialized integrator configuration for this RooAbsReal.
void writeToStream(std::ostream &os, bool compact) const override
Write object contents to stream (dummy for now)
double traceEval(const RooArgSet *set) const
Calculate current value of object, with error tracing wrapper.
double getPropagatedError(const RooFitResult &fr, const RooArgSet &nset={}) const
Propagates parameter uncertainties to an uncertainty estimate for this RooAbsReal.
static void setHideOffset(bool flag)
static void globalSelectComp(bool flag)
Global switch controlling the activation of the selectComp() functionality.
RooAbsMoment * moment(RooRealVar &obs, Int_t order, bool central, bool takeRoot)
Return function representing moment of function of given order.
RooPlot * plotOnWithErrorBand(RooPlot *frame, const RooFitResult &fr, double Z, const RooArgSet *params, const RooLinkedList &argList, bool method1) const
Plot function or PDF on frame with support for visualization of the uncertainty encoded in the given ...
RooFit::UniqueId< RooArgSet >::Value_t _lastNormSetId
!
Definition RooAbsReal.h:548
const char * getPlotLabel() const
Get the label associated with the variable.
RooFit::OwningPtr< RooAbsReal > createRunningIntegral(const RooArgSet &iset, const RooArgSet &nset={})
Calls createRunningIntegral(const RooArgSet&, const RooCmdArg&, const RooCmdArg&, const RooCmdArg&,...
std::unique_ptr< RooNumIntConfig > _specIntegratorConfig
Definition RooAbsReal.h:545
std::unique_ptr< RooFitResult > chi2FitToImpl(RooDataHist &data, const RooLinkedList &cmdList)
virtual Int_t getAnalyticalIntegral(RooArgSet &allVars, RooArgSet &analVars, const char *rangeName=nullptr) const
Interface function getAnalyticalIntergral advertises the analytical integrals that are supported.
static std::map< constRooAbsArg *, std::pair< std::string, std::list< RooAbsReal::EvalError > > >::iterator evalErrorIter()
static Int_t numEvalErrors()
Return the number of logged evaluation errors since the last clearing.
static void setEvalErrorLoggingMode(ErrorLoggingMode m)
Set evaluation error logging mode.
virtual void preferredObservableScanOrder(const RooArgSet &obs, RooArgSet &orderedObs) const
Interface method for function objects to indicate their preferred order of observables for scanning t...
virtual double maxVal(Int_t code) const
Return maximum value for set of observables identified by code assigned in getMaxVal.
void findInnerMostIntegration(const RooArgSet &allObs, RooArgSet &innerObs, const char *rangeName) const
Utility function for createIntObj() that aids in the construct of recursive integrals over functions ...
TString integralNameSuffix(const RooArgSet &iset, const RooArgSet *nset=nullptr, const char *rangeName=nullptr, bool omitEmpty=false) const
Construct string with unique suffix name to give to integral object that encodes integrated observabl...
virtual double evaluate() const =0
Evaluate this PDF / function / constant. Needs to be overridden by all derived classes.
TString getTitle(bool appendUnit=false) const
Return this variable's title string.
void logEvalError(const char *message, const char *serverValueString=nullptr) const
Log evaluation error message.
virtual double analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=nullptr) const
Implements the actual analytical integral(s) advertised by getAnalyticalIntegral.
const Text_t * getUnit() const
Definition RooAbsReal.h:149
const RooNumIntConfig * getIntegratorConfig() const
Return the numeric integration configuration used for this object.
static void printEvalErrors(std::ostream &os=std::cout, Int_t maxPerNode=10000000)
Print all outstanding logged evaluation error on the given ostream.
RooFit::OwningPtr< RooAbsReal > createIntRI(const RooArgSet &iset, const RooArgSet &nset={})
Utility function for createRunningIntegral.
virtual void enableOffsetting(bool)
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
RooFit::OwningPtr< RooAbsReal > createIntObj(const RooArgSet &iset, const RooArgSet *nset, const RooNumIntConfig *cfg, const char *rangeName) const
Internal utility function for createIntegral() that creates the actual integral object.
RooFunctor * functor(const RooArgList &obs, const RooArgList &pars=RooArgList(), const RooArgSet &nset=RooArgSet()) const
Return a RooFunctor object bound to this RooAbsReal with given definition of observables and paramete...
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.
const RooAbsReal * createPlotProjection(const RooArgSet &depVars, const RooArgSet &projVars, RooArgSet *&cloneSet) const
Utility function for plotOn() that creates a projection of a function or p.d.f to be plotted on a Roo...
virtual std::list< double > * plotSamplingHint(RooAbsRealLValue &obs, double xlo, double xhi) const
Interface for returning an optional hint for initial sampling points when constructing a curve projec...
void setPlotLabel(const char *label)
Set the label associated with this variable.
RooFit::OwningPtr< RooAbsReal > createIntegral(const RooArgSet &iset, 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 an object that represents the integral of the function over one or more observables listed in ...
virtual void doEval(RooFit::EvalContext &) const
Base function for computing multiple values of a RooAbsReal.
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...
virtual Int_t getMaxVal(const RooArgSet &vars) const
Advertise capability to determine maximum value of function for given set of observables.
bool matchArgs(const RooArgSet &allDeps, RooArgSet &analDeps, const RooArgProxy &a, const Proxies &... proxies) const
Definition RooAbsReal.h:425
virtual double offset() const
Definition RooAbsReal.h:368
std::unique_ptr< RooAbsReal > createChi2Impl(RooDataHist &data, const RooLinkedList &cmdList)
static bool _globalSelectComp
Definition RooAbsReal.h:550
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
Implement the abstract 1-dimensional root finding interface using the Brent-Decker method.
bool findRoot(double &result, double xlo, double xhi, double value=0) const
Do the root finding using the Brent-Decker method.
Object to represent discrete states.
Definition RooCategory.h:28
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
static const RooCmdArg & none()
Return reference to null argument.
Definition RooCmdArg.cxx:48
Configurable parser for RooCmdArg named arguments.
void defineMutex(const char *head, Args_t &&... tail)
Define arguments where any pair is mutually exclusive.
bool process(const RooCmdArg &arg)
Process given RooCmdArg.
bool hasProcessed(const char *cmdName) const
Return true if RooCmdArg with name 'cmdName' has been processed.
double getDouble(const char *name, double defaultValue=0.0) const
Return double property registered with name 'name'.
bool defineDouble(const char *name, const char *argName, int doubleNum, double defValue=0.0)
Define double property name 'name' mapped to double in slot 'doubleNum' in RooCmdArg with name argNam...
static void stripCmdList(RooLinkedList &cmdList, const char *cmdsToPurge)
Utility function that strips command names listed (comma separated) in cmdsToPurge from cmdList.
RooArgSet * getSet(const char *name, RooArgSet *set=nullptr) const
Return RooArgSet property registered with name 'name'.
bool defineSet(const char *name, const char *argName, int setNum, const RooArgSet *set=nullptr)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
bool ok(bool verbose) const
Return true of parsing was successful.
bool defineObject(const char *name, const char *argName, int setNum, const TObject *obj=nullptr, bool isArray=false)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
const char * getString(const char *name, const char *defaultValue="", bool convEmptyToNull=false) const
Return string property registered with name 'name'.
bool defineString(const char *name, const char *argName, int stringNum, const char *defValue="", bool appendMode=false)
Define double property name 'name' mapped to double in slot 'stringNum' in RooCmdArg with name argNam...
const RooLinkedList & getObjectList(const char *name) const
Return list of objects registered with name 'name'.
bool defineInt(const char *name, const char *argName, int intNum, int defValue=0)
Define integer property name 'name' mapped to integer in slot 'intNum' in RooCmdArg with name argName...
void allowUndefined(bool flag=true)
If flag is true the processing of unrecognized RooCmdArgs is not considered an error.
int getInt(const char *name, int defaultValue=0) const
Return integer property registered with name 'name'.
TObject * getObject(const char *name, TObject *obj=nullptr) const
Return TObject property registered with name 'name'.
One-dimensional graphical representation of a real-valued function.
Definition RooCurve.h:36
@ Extended
Definition RooCurve.h:39
@ NoWings
Definition RooCurve.h:39
@ Straight
Definition RooCurve.h:39
static TClass * Class()
RooCustomizer is a factory class to produce clones of a prototype composite PDF object with the same ...
Container class to hold N-dimensional binned data.
Definition RooDataHist.h:40
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 binVolume(std::size_t i) const
Return bin volume of i-th bin.
const RooArgSet * get() const override
Get bin centre of current bin.
Definition RooDataHist.h:82
Container class to hold unbinned data.
Definition RooDataSet.h:32
Represents the first, second, or third order derivative of any RooAbsReal as calculated (numerically)...
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
const TMatrixDSym & covarianceMatrix() const
Return covariance matrix.
TMatrixDSym reducedCovarianceMatrix(const RooArgList &params) const
Return a reduced covariance matrix (Note that Vred is a simple sub-matrix of V, row/columns are order...
const RooArgList & floatParsFinal() const
Return list of floating parameters after fit.
RooAbsPdf * createHessePdf(const RooArgSet &params) const
Return a p.d.f that represents the fit result as a multi-variate probability densisty function on the...
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
Lightweight interface adaptor that exports a RooAbsPdf as a functor.
Definition RooFunctor.h:25
Graphical representation of binned data based on the TGraphAsymmErrors class.
Definition RooHist.h:29
Collection class for internal use, storing a collection of RooAbsArg pointers in a doubly linked list...
void Delete(Option_t *o=nullptr) override
Remove all elements in collection and delete all elements NB: Collection does not own elements,...
virtual void Add(TObject *arg)
TObject * FindObject(const char *name) const override
Return pointer to object with given name.
static RooMsgService & instance()
Return reference to singleton instance.
Holds the configuration parameters of the various numeric integrators used by RooRealIntegral.
static RooNumIntConfig & defaultConfig()
Return reference to instance of default numeric integrator configuration object.
Implementation of RooAbsBinning that constructs a binning with a range definition that depends on ext...
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
void remove(const char *name=nullptr, bool deleteToo=true)
Remove object with given name, or last object added if no name is given.
Definition RooPlot.cxx:828
bool drawBefore(const char *before, const char *target)
Change the order in which our contained objects are drawn so that the target object is drawn just bef...
Definition RooPlot.cxx:866
TObject * findObject(const char *name, const TClass *tClass=nullptr) const
Find the named object in our list of items and return a pointer to it.
Definition RooPlot.cxx:902
virtual void SetMinimum(double minimum=-1111)
Set minimum value of Y axis.
Definition RooPlot.cxx:1013
const RooArgSet * getNormVars() const
Definition RooPlot.h:146
double GetMaximum(double maxval=FLT_MAX) const
Definition RooPlot.cxx:1238
TAttLine * getAttLine(const char *name=nullptr) const
Return a pointer to the line attributes of the named object in this plot, or zero if the named object...
Definition RooPlot.cxx:767
Stat_t numItems() const
Definition RooPlot.h:113
TAttFill * getAttFill(const char *name=nullptr) const
Return a pointer to the fill attributes of the named object in this plot, or zero if the named object...
Definition RooPlot.cxx:777
TObject * getObject(Int_t idx) const
Return the name of the object at slot 'idx' in this RooPlot.
Definition RooPlot.cxx:751
virtual void SetMaximum(double maximum=-1111)
Set maximum value of Y axis.
Definition RooPlot.cxx:1003
RooAbsRealLValue * getPlotVar() const
Definition RooPlot.h:137
TAttMarker * getAttMarker(const char *name=nullptr) const
Return a pointer to the marker attributes of the named object in this plot, or zero if the named obje...
Definition RooPlot.cxx:787
TAxis * GetXaxis() const
Definition RooPlot.cxx:1228
RooCurve * getCurve(const char *name=nullptr) const
Return a RooCurve pointer of the named object in this plot, or zero if the named object does not exis...
Definition RooPlot.cxx:808
Int_t GetNbinsX() const
Definition RooPlot.cxx:1232
void addPlotable(RooPlotable *plotable, Option_t *drawOptions="", bool invisible=false, bool refreshNorm=false)
Add the specified plotable object to our plot.
Definition RooPlot.cxx:476
double GetMinimum(double minval=-FLT_MAX) const
Definition RooPlot.cxx:1236
virtual void printStream(std::ostream &os, Int_t contents, StyleOption style, TString indent="") const
Print description of object on ostream, printing contents set by contents integer,...
Performs hybrid numerical/analytical integrals of RooAbsReal objects.
const RooArgSet & numIntRealVars() const
void setAllowComponentSelection(bool allow)
Set component selection to be allowed/forbidden.
static TClass * Class()
Variable that can be changed from the outside.
Definition RooRealVar.h:37
The RooStringView is a wrapper around a C-style string that can also be constructed from a std::strin...
Uses std::vector to store data columns.
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition TAttFill.h:40
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition TAttFill.h:42
Line Attributes class.
Definition TAttLine.h:21
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:46
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition TAttLine.h:47
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition TAttLine.h:44
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Class to manage histogram axis.
Definition TAxis.h:32
Double_t GetXmax() const
Definition TAxis.h:142
Double_t GetXmin() const
Definition TAxis.h:141
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition TAxis.cxx:546
A TTree is a list of TBranches.
Definition TBranch.h:93
1-Dim function class
Definition TF1.h:182
A 2-Dim function with parameters.
Definition TF2.h:29
TF3 defines a 3D Function with Parameters.
Definition TF3.h:28
void SetName(const char *name="") override
Set graph name.
Definition TGraph.cxx:2425
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:109
TAxis * GetZaxis()
Definition TH1.h:573
virtual Int_t GetNbinsY() const
Definition TH1.h:542
virtual Int_t GetNbinsZ() const
Definition TH1.h:543
virtual Int_t GetDimension() const
Definition TH1.h:527
TAxis * GetXaxis()
Definition TH1.h:571
virtual Int_t GetBin(Int_t binx, Int_t biny=0, Int_t binz=0) const
Return Global bin number corresponding to binx,y,z.
Definition TH1.cxx:5137
virtual Int_t GetNbinsX() const
Definition TH1.h:541
virtual void SetBinError(Int_t bin, Double_t error)
Set the bin Error Note that this resets the bin eror option to be of Normal Type and for the non-empt...
Definition TH1.cxx:9436
TAxis * GetYaxis()
Definition TH1.h:572
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition TH1.cxx:9452
A TLeaf describes individual elements of a TBranch See TBranch structure in TTree.
Definition TLeaf.h:57
A doubly linked list.
Definition TList.h:38
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
TString fName
Definition TNamed.h:32
Collectable string class.
Definition TObjString.h:28
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:226
Basic string class.
Definition TString.h:137
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
Definition TString.cxx:465
const char * Data() const
Definition TString.h:385
TString & Prepend(const char *cs)
Definition TString.h:683
Bool_t IsNull() const
Definition TString.h:423
TString & Append(const char *cs)
Definition TString.h:582
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:642
virtual void StackTrace()
Print a stack trace.
Definition TSystem.cxx:748
A TTree represents a columnar dataset.
Definition TTree.h:89
virtual Int_t SetBranchAddress(const char *bname, void *add, TBranch **ptr, TClass *realClass, EDataType datatype, bool isptr, bool suppressMissingBranchError)
Definition TTree.cxx:8818
virtual TBranch * GetBranch(const char *name)
Return pointer to the branch with the given name in this tree or its friends.
Definition TTree.cxx:5457
TBranch * Branch(const char *name, T *obj, Int_t bufsize=32000, Int_t splitlevel=99)
Add a new branch, and infer the data type from the type of obj being passed.
Definition TTree.h:405
RooCmdArg ZVar(const RooAbsRealLValue &var, const RooCmdArg &arg={})
RooCmdArg SupNormSet(const RooArgSet &nset)
RooCmdArg SelectVars(const RooArgSet &vars)
RooCmdArg YVar(const RooAbsRealLValue &var, const RooCmdArg &arg={})
RooCmdArg Binning(const RooAbsBinning &binning)
RooCmdArg NormRange(const char *rangeNameList)
RooCmdArg Cut(const char *cutSpec)
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
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)
std::unique_ptr< T > compileForNormSet(T const &arg, RooArgSet const &normSet)
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
@ FastEvaluations
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
Definition Config.h:40
RooArgSet selectFromArgSet(RooArgSet const &, std::string const &names)
bool checkIfRangesOverlap(RooArgSet const &observables, std::vector< std::string > const &rangeNames)
std::string getColonSeparatedNameString(RooArgSet const &argSet, char delim=':')
Bool_t IsNaN(Double_t x)
Definition TMath.h:905
Double_t Erfc(Double_t x)
Computes the complementary error function erfc(x).
Definition TMath.cxx:199
RooCurve::WingMode wmode
Definition RooAbsReal.h:476
const char * normRangeName
Definition RooAbsReal.h:472
RooFit::MPSplit interleave
Definition RooAbsReal.h:484
const char * projectionRangeName
Definition RooAbsReal.h:477
const RooArgSet * projDataSet
Definition RooAbsReal.h:471
const char * curveNameSuffix
Definition RooAbsReal.h:485
const char * addToCurveName
Definition RooAbsReal.h:480
const RooFitResult * errorFR
Definition RooAbsReal.h:490
const RooArgSet * projSet
Definition RooAbsReal.h:468
const char * curveName
Definition RooAbsReal.h:479
const RooAbsData * projData
Definition RooAbsReal.h:466
Option_t * drawOptions
Definition RooAbsReal.h:463
A UniqueId can be added as a class member to enhance any class with a unique identifier for each inst...
Definition UniqueId.h:39
constexpr Value_t value() const
Return numerical value of ID.
Definition UniqueId.h:59
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2335