Logo ROOT  
Reference Guide
RooAbsPdf.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 /** \class RooAbsPdf
19  \ingroup Roofitcore
20 
21 ## RooAbsPdf, the base class of all PDFs
22 
23 RooAbsPdf is the abstract interface for all probability density
24 functions. The class provides hybrid analytical/numerical
25 normalization for its implementations, error tracing and a MC
26 generator interface.
27 
28 ### A Minimal PDF Implementation
29 
30 A minimal implementation of a PDF class derived from RooAbsPdf
31 should override the `evaluate()` function. This function should
32 return the PDF's value (which does not need to be normalised).
33 
34 
35 #### Normalization/Integration
36 
37 Although the normalization of a PDF is an integral part of a
38 probability density function, normalization is treated separately
39 in RooAbsPdf. The reason is that a RooAbsPdf object is more than a
40 PDF: it can be a building block for a more complex, composite PDF
41 if any of its variables are functions instead of variables. In
42 such cases the normalization of the composite may not be simply the
43 integral over the dependents of the top level PDF as these are
44 functions with potentially non-trivial Jacobian terms themselves.
45 \note Therefore, no explicit attempt should be made to normalize the
46 function output in evaluate(). In particular, normalisation constants
47 can be omitted to speed up the function evaluations, and included later
48 in the integration of the PDF (see below), which is called rarely in
49 comparison to the `evaluate()` function.
50 
51 In addition, RooAbsPdf objects do not have a static concept of what
52 variables are parameters and what variables are dependents (which
53 need to be integrated over for a correct PDF normalization).
54 Instead, the choice of normalization is always specified each time a
55 normalized value is requested from the PDF via the getVal()
56 method.
57 
58 RooAbsPdf manages the entire normalization logic of each PDF with
59 help of a RooRealIntegral object, which coordinates the integration
60 of a given choice of normalization. By default, RooRealIntegral will
61 perform a fully numeric integration of all dependents. However,
62 PDFs can advertise one or more (partial) analytical integrals of
63 their function, and these will be used by RooRealIntegral, if it
64 determines that this is safe (i.e. no hidden Jacobian terms,
65 multiplication with other PDFs that have one or more dependents in
66 commen etc).
67 
68 #### Implementing analytical integrals
69 To implement analytical integrals, two functions must be implemented. First,
70 
71 ```
72 Int_t getAnalyticalIntegral(const RooArgSet& integSet, RooArgSet& anaIntSet)
73 ```
74 should return the analytical integrals that are supported. `integSet`
75 is the set of dependents for which integration is requested. The
76 function should copy the subset of dependents it can analytically
77 integrate to `anaIntSet`, and return a unique identification code for
78 this integration configuration. If no integration can be
79 performed, zero should be returned. Second,
80 
81 ```
82 Double_t analyticalIntegral(Int_t code)
83 ```
84 
85 implements the actual analytical integral(s) advertised by
86 `getAnalyticalIntegral()`. This function will only be called with
87 codes returned by `getAnalyticalIntegral()`, except code zero.
88 
89 The integration range for each dependent to be integrated can
90 be obtained from the dependent's proxy functions `min()` and
91 `max()`. Never call these proxy functions for any proxy not known to
92 be a dependent via the integration code. Doing so may be
93 ill-defined, e.g. in case the proxy holds a function, and will
94 trigger an assert. Integrated category dependents should always be
95 summed over all of their states.
96 
97 
98 
99 ### Direct generation of observables
100 
101 Distributions for any PDF can be generated with the accept/reject method,
102 but for certain PDFs, more efficient methods may be implemented. To
103 implement direct generation of one or more observables, two
104 functions need to be implemented, similar to those for analytical
105 integrals:
106 
107 ```
108 Int_t getGenerator(const RooArgSet& generateVars, RooArgSet& directVars)
109 ```
110 and
111 ```
112 void generateEvent(Int_t code)
113 ```
114 
115 The first function advertises observables, for which distributions can be generated,
116 similar to the way analytical integrals are advertised. The second
117 function implements the actual generator for the advertised observables.
118 
119 The generated dependent values should be stored in the proxy
120 objects. For this, the assignment operator can be used (i.e. `xProxy
121 = 3.0` ). Never call assign to any proxy not known to be a dependent
122 via the generation code. Doing so may be ill-defined, e.g. in case
123 the proxy holds a function, and will trigger an assert.
124 
125 
126 ### Batched function evaluations (Advanced usage)
127 
128 To speed up computations with large numbers of data events in unbinned fits,
129 it is beneficial to override `evaluateSpan()`. Like this, large spans of
130 computations can be done, without having to call `evaluate()` for each single data event.
131 `evaluateSpan()` should execute the same computation as `evaluate()`, but it
132 may choose an implementation that is capable of SIMD computations.
133 If evaluateSpan is not implemented, the classic and slower `evaluate()` will be
134 called for each data event.
135 */
136 
137 #include "RooAbsPdf.h"
138 
139 #include "RooFit.h"
140 #include "RooMsgService.h"
141 #include "RooDataSet.h"
142 #include "RooArgSet.h"
143 #include "RooArgProxy.h"
144 #include "RooRealProxy.h"
145 #include "RooRealVar.h"
146 #include "RooGenContext.h"
147 #include "RooBinnedGenContext.h"
148 #include "RooPlot.h"
149 #include "RooCurve.h"
150 #include "RooNLLVar.h"
151 #include "RooMinuit.h"
152 #include "RooCategory.h"
153 #include "RooNameReg.h"
154 #include "RooCmdConfig.h"
155 #include "RooGlobalFunc.h"
156 #include "RooAddition.h"
157 #include "RooRandom.h"
158 #include "RooNumIntConfig.h"
159 #include "RooProjectedPdf.h"
160 #include "RooInt.h"
161 #include "RooCustomizer.h"
162 #include "RooConstraintSum.h"
163 #include "RooParamBinning.h"
164 #include "RooNumCdf.h"
165 #include "RooFitResult.h"
166 #include "RooNumGenConfig.h"
167 #include "RooCachedReal.h"
168 #include "RooXYChi2Var.h"
169 #include "RooChi2Var.h"
170 #include "RooMinimizer.h"
171 #include "RooRealIntegral.h"
172 #include "RooWorkspace.h"
173 #include "RooNaNPacker.h"
174 #include "RooHelpers.h"
175 #include "RooBatchCompute.h"
176 #include "RooFormulaVar.h"
177 
178 #include "TClass.h"
179 #include "TMath.h"
180 #include "TPaveText.h"
181 #include "TList.h"
182 #include "TMatrixD.h"
183 #include "TMatrixDSym.h"
184 #include "Math/CholeskyDecomp.h"
185 #include "RooDerivative.h"
186 
187 #include <iostream>
188 #include <string>
189 #include <cmath>
190 #include <stdexcept>
191 
192 using namespace std;
193 
195 
197 
198 
201 
202 ////////////////////////////////////////////////////////////////////////////////
203 /// Default constructor
204 
205 RooAbsPdf::RooAbsPdf() : _norm(0), _normSet(0), _specGeneratorConfig(0)
206 {
207  _errorCount = 0 ;
208  _negCount = 0 ;
209  _rawValue = 0 ;
210  _selectComp = kFALSE ;
211  _traceCount = 0 ;
212 }
213 
214 
215 
216 ////////////////////////////////////////////////////////////////////////////////
217 /// Constructor with name and title only
218 
219 RooAbsPdf::RooAbsPdf(const char *name, const char *title) :
220  RooAbsReal(name,title), _norm(0), _normSet(0), _normMgr(this,10), _selectComp(kTRUE), _specGeneratorConfig(0)
221 {
223  setTraceCounter(0) ;
224 }
225 
226 
227 
228 ////////////////////////////////////////////////////////////////////////////////
229 /// Constructor with name, title, and plot range
230 
231 RooAbsPdf::RooAbsPdf(const char *name, const char *title,
232  Double_t plotMin, Double_t plotMax) :
233  RooAbsReal(name,title,plotMin,plotMax), _norm(0), _normSet(0), _normMgr(this,10), _selectComp(kTRUE), _specGeneratorConfig(0)
234 {
236  setTraceCounter(0) ;
237 }
238 
239 
240 
241 ////////////////////////////////////////////////////////////////////////////////
242 /// Copy constructor
243 
244 RooAbsPdf::RooAbsPdf(const RooAbsPdf& other, const char* name) :
245  RooAbsReal(other,name), _norm(0), _normSet(0),
246  _normMgr(other._normMgr,this), _selectComp(other._selectComp), _normRange(other._normRange)
247 {
248  resetErrorCounters() ;
249  setTraceCounter(other._traceCount) ;
250 
251  if (other._specGeneratorConfig) {
252  _specGeneratorConfig = new RooNumGenConfig(*other._specGeneratorConfig) ;
253  } else {
254  _specGeneratorConfig = 0 ;
255  }
256 }
257 
258 
259 
260 ////////////////////////////////////////////////////////////////////////////////
261 /// Destructor
262 
264 {
266 }
267 
268 
269 
270 ////////////////////////////////////////////////////////////////////////////////
271 /// Return current value, normalized by integrating over
272 /// the observables in `nset`. If `nset` is 0, the unnormalized value
273 /// is returned. All elements of `nset` must be lvalues.
274 ///
275 /// Unnormalized values are not cached.
276 /// Doing so would be complicated as `_norm->getVal()` could
277 /// spoil the cache and interfere with returning the cached
278 /// return value. Since unnormalized calls are typically
279 /// done in integration calls, there is no performance hit.
280 
282 {
283 
284  // Special handling of case without normalization set (used in numeric integration of pdfs)
285  if (!nset) {
286  RooArgSet* tmp = _normSet ;
287  _normSet = 0 ;
288  Double_t val = evaluate() ;
289  _normSet = tmp ;
290 
291  return TMath::IsNaN(val) ? 0. : val;
292  }
293 
294 
295  // Process change in last data set used
296  Bool_t nsetChanged(kFALSE) ;
297  if (nset!=_normSet || _norm==0) {
298  nsetChanged = syncNormalization(nset) ;
299  }
300 
301  // Return value of object. Calculated if dirty, otherwise cached value is returned.
302  if (isValueDirty() || nsetChanged || _norm->isValueDirty()) {
303 
304  // Evaluate numerator
305  const double rawVal = evaluate();
306 
307  // Evaluate denominator
308  const double normVal = _norm->getVal();
309 
310  if (normVal < 0. || (normVal == 0. && rawVal != 0)) {
311  //Unreasonable normalisations. A zero integral can be tolerated if the function vanishes, though.
312  const std::string msg = "p.d.f normalization integral is zero or negative: " + std::to_string(normVal);
313  logEvalError(msg.c_str());
315  return _value = RooNaNPacker::packFloatIntoNaN(-normVal + (rawVal < 0. ? -rawVal : 0.));
316  }
317 
318  if (rawVal < 0.) {
319  logEvalError(Form("p.d.f value is less than zero (%f), trying to recover", rawVal));
321  return _value = RooNaNPacker::packFloatIntoNaN(-rawVal);
322  }
323 
324  if (TMath::IsNaN(rawVal)) {
325  logEvalError("p.d.f value is Not-a-Number");
327  return _value = rawVal;
328  }
329 
330  _value = (rawVal == 0. && normVal == 0.) ? 0. : rawVal / normVal;
331 
333  }
334 
335  return _value ;
336 }
337 
338 
339 ////////////////////////////////////////////////////////////////////////////////
340 /// Compute batch of values for given input data, and normalise by integrating over
341 /// the observables in `normSet`. Store result in `evalData`, and return a span pointing to
342 /// it.
343 /// This uses evaluateSpan() to perform an (unnormalised) computation of data points. This computation
344 /// is finalised by normalising the bare values, and by checking for computation errors.
345 /// Derived classes should override evaluateSpan() to reach maximal performance.
346 ///
347 /// \param[in,out] evalData Object holding data that should be used in computations. Results are also stored here.
348 /// \param[in] normSet If not nullptr, normalise results by integrating over
349 /// the variables in this set. The normalisation is only computed once, and applied
350 /// to the full batch.
351 /// \return RooSpan with probabilities. The memory of this span is owned by `evalData`.
352 /// \see RooAbsReal::getValues().
354  auto item = evalData.spans.find(this);
355  if (item != evalData.spans.end()) {
356  return item->second;
357  }
358 
359  auto outputs = evaluateSpan(evalData, normSet);
360  assert(evalData.spans.count(this) > 0);
361 
362  if (normSet != nullptr) {
363  if (normSet != _normSet || _norm == nullptr) {
364  syncNormalization(normSet);
365  }
366  // Evaluate denominator
367  // In most cases, the integral will be a scalar. But it can still happen
368  // that the integral is a vector, for example in a conditional fit where
369  // pdf is parametrized by another observable that is also a batch. That's
370  // why we have to use the batch interface also for the integral.
371  auto const& normVals = _norm->getValues(evalData);
372 
373  if(normVals.size() > 1) {
374  for(std::size_t i = 0; i < outputs.size(); ++i) {
375  if (normVals[i] < 0. || (normVals[i] == 0. && outputs[i] != 0)) {
376  logEvalError(Form("p.d.f normalization integral is zero or negative."
377  "\n\tInt(%s) = %f", GetName(), normVals[i]));
378  }
379  if(normVals[i] != 1. && normVals[i] > 0.) {
380  outputs[i] /= normVals[i];
381  }
382  }
383 
384  } else {
385  const double normVal = normVals[0];
386  if (normVal < 0.
387  || (normVal == 0. && std::any_of(outputs.begin(), outputs.end(), [](double val){return val != 0;}))) {
388  logEvalError(Form("p.d.f normalization integral is zero or negative."
389  "\n\tInt(%s) = %f", GetName(), normVal));
390  }
391 
392  if (normVal != 1. && normVal > 0.) {
393  const double invNorm = 1./normVal;
394  for (double& val : outputs) { //CHECK_VECTORISE
395  val *= invNorm;
396  }
397  }
398  }
399  }
400 
401  return outputs;
402 }
403 
404 ////////////////////////////////////////////////////////////////////////////////
405 /// Analytical integral with normalization (see RooAbsReal::analyticalIntegralWN() for further information)
406 ///
407 /// This function applies the normalization specified by 'normSet' to the integral returned
408 /// by RooAbsReal::analyticalIntegral(). The passthrough scenario (code=0) is also changed
409 /// to return a normalized answer
410 
411 Double_t RooAbsPdf::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* rangeName) const
412 {
413  cxcoutD(Eval) << "RooAbsPdf::analyticalIntegralWN(" << GetName() << ") code = " << code << " normset = " << (normSet?*normSet:RooArgSet()) << endl ;
414 
415 
416  if (code==0) return getVal(normSet) ;
417  if (normSet) {
418  return analyticalIntegral(code,rangeName) / getNorm(normSet) ;
419  } else {
420  return analyticalIntegral(code,rangeName) ;
421  }
422 }
423 
424 
425 
426 ////////////////////////////////////////////////////////////////////////////////
427 /// Check that passed value is positive and not 'not-a-number'. If
428 /// not, print an error, until the error counter reaches its set
429 /// maximum.
430 
432 {
433  // check for a math error or negative value
434  Bool_t error(kFALSE) ;
435  if (TMath::IsNaN(value)) {
436  logEvalError(Form("p.d.f value is Not-a-Number (%f), forcing value to zero",value)) ;
437  error=kTRUE ;
438  }
439  if (value<0) {
440  logEvalError(Form("p.d.f value is less than zero (%f), forcing value to zero",value)) ;
441  error=kTRUE ;
442  }
443 
444  // do nothing if we are no longer tracing evaluations and there was no error
445  if(!error) return error ;
446 
447  // otherwise, print out this evaluations input values and result
448  if(++_errorCount <= 10) {
449  cxcoutD(Tracing) << "*** Evaluation Error " << _errorCount << " ";
450  if(_errorCount == 10) cxcoutD(Tracing) << "(no more will be printed) ";
451  }
452  else {
453  return error ;
454  }
455 
456  Print() ;
457  return error ;
458 }
459 
460 
461 ////////////////////////////////////////////////////////////////////////////////
462 /// Get normalisation term needed to normalise the raw values returned by
463 /// getVal(). Note that `getVal(normalisationVariables)` will automatically
464 /// apply the normalisation term returned here.
465 /// \param nset Set of variables to normalise over.
467 {
468  if (!nset) return 1 ;
469 
470  syncNormalization(nset,kTRUE) ;
471  if (_verboseEval>1) cxcoutD(Tracing) << IsA()->GetName() << "::getNorm(" << GetName() << "): norm(" << _norm << ") = " << _norm->getVal() << endl ;
472 
473  Double_t ret = _norm->getVal() ;
474  if (ret==0.) {
475  if(++_errorCount <= 10) {
476  coutW(Eval) << "RooAbsPdf::getNorm(" << GetName() << ":: WARNING normalization is zero, nset = " ; nset->Print("1") ;
477  if(_errorCount == 10) coutW(Eval) << "RooAbsPdf::getNorm(" << GetName() << ") INFO: no more messages will be printed " << endl ;
478  }
479  }
480 
481  return ret ;
482 }
483 
484 
485 
486 ////////////////////////////////////////////////////////////////////////////////
487 /// Return pointer to RooAbsReal object that implements calculation of integral over observables iset in range
488 /// rangeName, optionally taking the integrand normalized over observables nset
489 
490 const RooAbsReal* RooAbsPdf::getNormObj(const RooArgSet* nset, const RooArgSet* iset, const TNamed* rangeName) const
491 {
492 
493  // Check normalization is already stored
494  CacheElem* cache = (CacheElem*) _normMgr.getObj(nset,iset,0,rangeName) ;
495  if (cache) {
496  return cache->_norm ;
497  }
498 
499  // If not create it now
500  std::unique_ptr<RooArgSet> depList{getObservables(iset)} ;
501  RooAbsReal* norm = createIntegral(*depList,*nset, *getIntegratorConfig(), RooNameReg::str(rangeName)) ;
502 
503  // Store it in the cache
504  cache = new CacheElem(*norm) ;
505  _normMgr.setObj(nset,iset,cache,rangeName) ;
506 
507  // And return the newly created integral
508  return norm ;
509 }
510 
511 
512 
513 ////////////////////////////////////////////////////////////////////////////////
514 /// Verify that the normalization integral cached with this PDF
515 /// is valid for given set of normalization observables.
516 ///
517 /// If not, the cached normalization integral (if any) is deleted
518 /// and a new integral is constructed for use with 'nset'.
519 /// Elements in 'nset' can be discrete and real, but must be lvalues.
520 ///
521 /// For functions that declare to be self-normalized by overloading the
522 /// selfNormalized() function, a unit normalization is always constructed.
523 
524 Bool_t RooAbsPdf::syncNormalization(const RooArgSet* nset, Bool_t adjustProxies) const
525 {
526 
527 // cout << IsA()->GetName() << "::syncNormalization(" << GetName() << ") nset = " << nset << " = " << (nset?*nset:RooArgSet()) << endl ;
528 
529  _normSet = (RooArgSet*) nset ;
530 
531  // Check if data sets are identical
532  CacheElem* cache = (CacheElem*) _normMgr.getObj(nset) ;
533  if (cache) {
534 
535  Bool_t nsetChanged = (_norm!=cache->_norm) ;
536  _norm = cache->_norm ;
537 
538 
539 // cout << "returning existing object " << _norm->GetName() << endl ;
540 
541  if (nsetChanged && adjustProxies) {
542  // Update dataset pointers of proxies
543  ((RooAbsPdf*) this)->setProxyNormSet(nset) ;
544  }
545 
546  return nsetChanged ;
547  }
548 
549  // Update dataset pointers of proxies
550  if (adjustProxies) {
551  ((RooAbsPdf*) this)->setProxyNormSet(nset) ;
552  }
553 
554  std::unique_ptr<RooArgSet> depList(getObservables(nset));
555 
556  if (_verboseEval>0) {
557  if (!selfNormalized()) {
558  cxcoutD(Tracing) << IsA()->GetName() << "::syncNormalization(" << GetName()
559  << ") recreating normalization integral " << endl ;
560  if (depList) depList->printStream(ccoutD(Tracing),kName|kValue|kArgs,kSingleLine) ; else ccoutD(Tracing) << "<none>" << endl ;
561  } else {
562  cxcoutD(Tracing) << IsA()->GetName() << "::syncNormalization(" << GetName() << ") selfNormalized, creating unit norm" << endl;
563  }
564  }
565 
566  // Destroy old normalization & create new
567  if (selfNormalized() || !dependsOn(*depList)) {
568  auto ntitle = std::string(GetTitle()) + " Unit Normalization";
569  auto nname = std::string(GetName()) + "_UnitNorm";
570  _norm = new RooRealVar(nname.c_str(),ntitle.c_str(),1) ;
571  } else {
572  const char* nr = (_normRangeOverride.Length()>0 ? _normRangeOverride.Data() : (_normRange.Length()>0 ? _normRange.Data() : 0)) ;
573 
574 // cout << "RooAbsPdf::syncNormalization(" << GetName() << ") rangeName for normalization is " << (nr?nr:"<null>") << endl ;
575  RooAbsReal* normInt = createIntegral(*depList,*getIntegratorConfig(),nr) ;
576  normInt->getVal() ;
577 // cout << "resulting normInt = " << normInt->GetName() << endl ;
578 
579  const char* cacheParamsStr = getStringAttribute("CACHEPARAMINT") ;
580  if (cacheParamsStr && strlen(cacheParamsStr)) {
581 
582  std::unique_ptr<RooArgSet> intParams{normInt->getVariables()} ;
583 
584  RooNameSet cacheParamNames ;
585  cacheParamNames.setNameList(cacheParamsStr) ;
586  std::unique_ptr<RooArgSet> cacheParams{cacheParamNames.select(*intParams)} ;
587 
588  if (cacheParams->getSize()>0) {
589  cxcoutD(Caching) << "RooAbsReal::createIntObj(" << GetName() << ") INFO: constructing " << cacheParams->getSize()
590  << "-dim value cache for integral over " << *depList << " as a function of " << *cacheParams << " in range " << (nr?nr:"<default>") << endl ;
591  string name = Form("%s_CACHE_[%s]",normInt->GetName(),cacheParams->contentsString().c_str()) ;
592  RooCachedReal* cachedIntegral = new RooCachedReal(name.c_str(),name.c_str(),*normInt,*cacheParams) ;
593  cachedIntegral->setInterpolationOrder(2) ;
594  cachedIntegral->addOwnedComponents(*normInt) ;
595  cachedIntegral->setCacheSource(kTRUE) ;
596  if (normInt->operMode()==ADirty) {
597  cachedIntegral->setOperMode(ADirty) ;
598  }
599  normInt= cachedIntegral ;
600  }
601 
602  }
603  _norm = normInt ;
604  }
605 
606  // Register new normalization with manager (takes ownership)
607  cache = new CacheElem(*_norm) ;
608  _normMgr.setObj(nset,cache) ;
609 
610 // cout << "making new object " << _norm->GetName() << endl ;
611 
612  return kTRUE ;
613 }
614 
615 
616 
617 ////////////////////////////////////////////////////////////////////////////////
618 /// Reset error counter to given value, limiting the number
619 /// of future error messages for this pdf to 'resetValue'
620 
622 {
623  _errorCount = resetValue ;
624  _negCount = resetValue ;
625 }
626 
627 
628 
629 ////////////////////////////////////////////////////////////////////////////////
630 /// Reset trace counter to given value, limiting the
631 /// number of future trace messages for this pdf to 'value'
632 
634 {
635  if (!allNodes) {
636  _traceCount = value ;
637  return ;
638  } else {
639  RooArgList branchList ;
640  branchNodeServerList(&branchList) ;
641  TIterator* iter = branchList.createIterator() ;
642  RooAbsArg* arg ;
643  while((arg=(RooAbsArg*)iter->Next())) {
644  RooAbsPdf* pdf = dynamic_cast<RooAbsPdf*>(arg) ;
645  if (pdf) pdf->setTraceCounter(value,kFALSE) ;
646  }
647  delete iter ;
648  }
649 
650 }
651 
652 
653 
654 
655 ////////////////////////////////////////////////////////////////////////////////
656 /// Return the log of the current value with given normalization
657 /// An error message is printed if the argument of the log is negative.
658 
660 {
661  Double_t prob = getVal(nset) ;
662 
663  if (fabs(prob)>1e6) {
664  coutW(Eval) << "RooAbsPdf::getLogVal(" << GetName() << ") WARNING: large likelihood value: " << prob << endl ;
665  }
666 
667  if(prob < 0) {
668  logEvalError("getLogVal() top-level p.d.f evaluates to a negative number") ;
669  return RooNaNPacker::packFloatIntoNaN(-prob);
670  }
671 
672  if(prob == 0) {
673  logEvalError("getLogVal() top-level p.d.f evaluates to zero") ;
674 
675  return -std::numeric_limits<double>::infinity();
676  }
677 
678  if (TMath::IsNaN(prob)) {
679  logEvalError("getLogVal() top-level p.d.f evaluates to NaN") ;
680 
681  return prob;
682  }
683 
684  return log(prob);
685 }
686 
687 
688 ////////////////////////////////////////////////////////////////////////////////
689 /// Check for infinity or NaN.
690 /// \param[in] inputs Array to check
691 /// \return True if either infinity or NaN were found.
692 namespace {
693 template<class T>
694 bool checkInfNaNNeg(const T& inputs) {
695  // check for a math error or negative value
696  bool inf = false;
697  bool nan = false;
698  bool neg = false;
699 
700  for (double val : inputs) { //CHECK_VECTORISE
701  inf |= !std::isfinite(val);
702  nan |= TMath::IsNaN(val); // Works also during fast math
703  neg |= val < 0;
704  }
705 
706  return inf || nan || neg;
707 }
708 }
709 
710 
711 ////////////////////////////////////////////////////////////////////////////////
712 /// Scan through outputs and fix+log all nans and negative values.
713 /// \param[in,out] outputs Array to be scanned & fixed.
714 /// \param[in] begin Begin of event range. Only needed to print the correct event number
715 /// where the error occurred.
716 void RooAbsPdf::logBatchComputationErrors(RooSpan<const double>& outputs, std::size_t begin) const {
717  for (unsigned int i=0; i<outputs.size(); ++i) {
718  const double value = outputs[i];
719  if (TMath::IsNaN(outputs[i])) {
720  logEvalError(Form("p.d.f value of (%s) is Not-a-Number (%f) for entry %zu",
721  GetName(), value, begin+i));
722  } else if (!std::isfinite(outputs[i])){
723  logEvalError(Form("p.d.f value of (%s) is (%f) for entry %zu",
724  GetName(), value, begin+i));
725  } else if (outputs[i] < 0.) {
726  logEvalError(Form("p.d.f value of (%s) is less than zero (%f) for entry %zu",
727  GetName(), value, begin+i));
728  }
729  }
730 }
731 
732 
733 ////////////////////////////////////////////////////////////////////////////////
734 /// Compute the log-likelihoods for all events in the requested batch.
735 /// The arguments are passed over to getValues().
736 /// \param[in] evalData Struct with data that should be used for evaluation.
737 /// \param[in] normSet Optional normalisation set to be used during computations.
738 /// \return Returns a batch of doubles that contains the log probabilities.
740 {
741  auto pdfValues = getValues(evalData, normSet);
742 
743  evalData.logProbabilities.resize(pdfValues.size());
745 
746  if (checkInfNaNNeg(pdfValues)) {
747  logBatchComputationErrors(pdfValues, 0);
748 
749  for (std::size_t i = 0; i < pdfValues.size(); ++i) {
750  const double prob = pdfValues[i];
751  double theLog = RooBatchCompute::fast_log(prob);
752 
753  if (prob <= 0.) {
754  // Pass magnitude of undershoot to minimiser:
755  theLog = RooNaNPacker::packFloatIntoNaN(-prob);
756  } else if (std::isnan(prob)) {
757  theLog = prob;
758  }
759 
760  output[i] = theLog;
761  }
762 
763  return output;
764  }
765 
766  for (std::size_t i = 0; i < pdfValues.size(); ++i) { //CHECK_VECTORISE
767  const double prob = pdfValues[i];
768  output[i] = RooBatchCompute::fast_log(prob);;
769  }
770 
771  return output;
772 }
773 
774 ////////////////////////////////////////////////////////////////////////////////
775 /// Return the extended likelihood term (\f$ N_\mathrm{expect} - N_\mathrm{observed} \cdot \log(N_\mathrm{expect} \f$)
776 /// of this PDF for the given number of observed events.
777 ///
778 /// For successful operation, the PDF implementation must indicate that
779 /// it is extendable by overloading `canBeExtended()`, and must
780 /// implement the `expectedEvents()` function.
781 
783 {
784  // check if this PDF supports extended maximum likelihood fits
785  if(!canBeExtended()) {
786  coutE(InputArguments) << fName << ": this PDF does not support extended maximum likelihood"
787  << endl;
788  return 0;
789  }
790 
791  Double_t expected= expectedEvents(nset);
792  if(expected < 0) {
793  coutE(InputArguments) << fName << ": calculated negative expected events: " << expected
794  << endl;
795  logEvalError("extendedTerm #expected events is <0 return a NaN");
796  return TMath::QuietNaN();
797  }
798 
799 
800  // Explicitly handle case Nobs=Nexp=0
801  if (fabs(expected)<1e-10 && fabs(observed)<1e-10) {
802  return 0 ;
803  }
804 
805  // Check for errors in Nexpected
806  if (TMath::IsNaN(expected)) {
807  logEvalError("extendedTerm #expected events is a NaN") ;
808  return TMath::QuietNaN() ;
809  }
810 
811  // calculate and return the negative log-likelihood of the Poisson
812  // factor for this dataset, dropping the constant log(observed!)
813  // Double_t extra=0;
814  // if(observed<1000000) {
815  // Double_t Delta1 = (expected-observed);
816  // Double_t Delta2 = observed*(log(expected)-log(observed+1));
817  // Double_t Const3 = 0.5*log(observed+1);
818  // extra= Delta1 - Delta2 + Const3;
819 
820  // cout << " extra obs = " << observed << " exp = " << expected << endl ;
821  // cout << " extra orig = " << expected - observed*log(expected) << endl ;
822  // cout << " extra orig fix = " << expected - observed*log(expected) + log(TMath::Gamma(observed+1)) << endl ;
823  // cout << " extra new = " << extra << endl ;
824 
825  // } else {
826  // Double_t sigma_square=expected;
827  // Double_t diff=observed-expected;
828  // extra=-log(sigma_square)/2 + (diff*diff)/(2*sigma_square);
829  // }
830 
831  Double_t extra= expected - observed*log(expected);
832 
833 // cout << "RooAbsPdf::extendedTerm(" << GetName() << ") observed = " << observed << " expected = " << expected << endl ;
834 
835  Bool_t trace(kFALSE) ;
836  if(trace) {
837  cxcoutD(Tracing) << fName << "::extendedTerm: expected " << expected << " events, got "
838  << observed << " events. extendedTerm = " << extra << endl;
839  }
840 
841 // cout << "RooAbsPdf::extendedTerm(" << GetName() << ") nExp = " << expected << " nObs = " << observed << endl ;
842  return extra;
843 }
844 
845 
846 
847 ////////////////////////////////////////////////////////////////////////////////
848 /// Construct representation of -log(L) of PDF with given dataset. If dataset is unbinned, an unbinned likelihood is constructed. If the dataset
849 /// is binned, a binned likelihood is constructed.
850 ///
851 /// The following named arguments are supported
852 ///
853 /// <table>
854 /// <tr><th> Type of CmdArg <th> Effect on nll
855 /// <tr><td> `ConditionalObservables(const RooArgSet& set)` <td> Do not normalize PDF over listed observables
856 /// <tr><td> `Extended(Bool_t flag)` <td> Add extended likelihood term, off by default
857 /// <tr><td> `Range(const char* name)` <td> Fit only data inside range with given name
858 /// <tr><td> `Range(Double_t lo, Double_t hi)` <td> Fit only data inside given range. A range named "fit" is created on the fly on all observables.
859 /// Multiple comma separated range names can be specified.
860 /// <tr><td> `SumCoefRange(const char* name)` <td> Set the range in which to interpret the coefficients of RooAddPdf components
861 /// <tr><td> `NumCPU(int num, int strat)` <td> Parallelize NLL calculation on num CPUs
862 /// <table>
863 /// <tr><th> Strategy <th> Effect
864 /// <tr><td> 0 = RooFit::BulkPartition (Default) <td> Divide events in N equal chunks
865 /// <tr><td> 1 = RooFit::Interleave <td> Process event i%N in process N. Recommended for binned data with
866 /// a substantial number of zero-bins, which will be distributed across processes more equitably in this strategy
867 /// <tr><td> 2 = RooFit::SimComponents <td> Process each component likelihood of a RooSimultaneous fully in a single process
868 /// and distribute components over processes. This approach can be benificial if normalization calculation time
869 /// dominates the total computation time of a component (since the normalization calculation must be performed
870 /// in each process in strategies 0 and 1. However beware that if the RooSimultaneous components do not share many
871 /// parameters this strategy is inefficient: as most minuit-induced likelihood calculations involve changing
872 /// a single parameter, only 1 of the N processes will be active most of the time if RooSimultaneous components
873 /// do not share many parameters
874 /// <tr><td> 3 = RooFit::Hybrid <td> Follow strategy 0 for all RooSimultaneous components, except those with less than
875 /// 30 dataset entries, for which strategy 2 is followed.
876 /// </table>
877 /// <tr><td> `BatchMode(bool on)` <td> Batch evaluation mode. See fitTo().
878 /// <tr><td> `Optimize(Bool_t flag)` <td> Activate constant term optimization (on by default)
879 /// <tr><td> `SplitRange(Bool_t flag)` <td> Use separate fit ranges in a simultaneous fit. Actual range name for each subsample is assumed to
880 /// be `rangeName_indexState`, where `indexState` is the state of the master index category of the simultaneous fit.
881 /// Using `Range("range"), SplitRange()` as switches, different ranges could be set like this:
882 /// ```
883 /// myVariable.setRange("range_pi0", 135, 210);
884 /// myVariable.setRange("range_gamma", 50, 210);
885 /// ```
886 /// <tr><td> `Constrain(const RooArgSet&pars)` <td> For p.d.f.s that contain internal parameter constraint terms (that is usually product PDFs, where one
887 /// term of the product depends on parameters but not on the observable(s),), only apply constraints to the given subset of parameters.
888 /// <tr><td> `ExternalConstraints(const RooArgSet& )` <td> Include given external constraints to likelihood by multiplying them with the original likelihood.
889 /// <tr><td> `GlobalObservables(const RooArgSet&)` <td> Define the set of normalization observables to be used for the constraint terms.
890 /// If none are specified the constrained parameters are used.
891 /// <tr><td> `GlobalObservablesTag(const char* tagName)` <td> Define the set of normalization observables to be used for the constraint terms by
892 /// a string attribute associated with pdf observables that match the given tagName.
893 /// <tr><td> `Verbose(Bool_t flag)` <td> Controls RooFit informational messages in likelihood construction
894 /// <tr><td> `CloneData(Bool flag)` <td> Use clone of dataset in NLL (default is true)
895 /// <tr><td> `Offset(Bool_t)` <td> Offset likelihood by initial value (so that starting value of FCN in minuit is zero).
896 /// This can improve numeric stability in simultaneous fits with components with large likelihood values
897 /// <tr><td> `IntegrateBins(double precision)` <td> In binned fits, integrate the PDF over the bins instead of using the probability density at the bin centre.
898 /// This can reduce the bias observed when fitting functions with high curvature to binned data.
899 /// - precision > 0: Activate bin integration everywhere. Use precision between 0.01 and 1.E-6, depending on binning.
900 /// Note that a low precision such as 0.01 might yield identical results to 1.E-4, since the integrator might reach 1.E-4 already in its first
901 /// integration step. If lower precision is desired (more speed), a RooBinSamplingPdf has to be created manually, and its integrator
902 /// has to be manipulated directly.
903 /// - precision = 0: Activate bin integration only for continuous PDFs fit to a RooDataHist.
904 /// - precision < 0: Deactivate.
905 /// \see RooBinSamplingPdf
906 /// </table>
907 ///
908 ///
909 
910 RooAbsReal* RooAbsPdf::createNLL(RooAbsData& data, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
911  const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
912 {
913  RooLinkedList l ;
914  l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ;
915  l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ;
916  l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ;
917  l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ;
918  return createNLL(data,l) ;
919 }
920 
921 namespace {
922 
923 RooAbsReal *createMultiRangeNLLCorrectionTerm(RooAbsPdf const &pdf, RooAbsData const &data, std::string const &baseName,
924  std::string const &rangeNames)
925 {
926  double sumEntriesTotal = 0.0;
927 
928  RooArgList termList;
929  RooArgList integralList;
930 
931  for (const auto &currentRangeName : RooHelpers::tokenise(rangeNames, ",")) {
932  const std::string currentName = baseName + "_" + currentRangeName;
933 
934  auto sumEntriesCurrent = data.sumEntries("1", currentRangeName.c_str());
935  sumEntriesTotal += sumEntriesCurrent;
936 
937  auto pdfIntegralCurrent =
938  pdf.createIntegral(*pdf.getObservables(data), nullptr, nullptr, currentRangeName.c_str());
939 
940  auto term = new RooFormulaVar((currentName + "_correctionTerm").c_str(),
941  (std::string("-(") + std::to_string(sumEntriesCurrent) + " * log(x[0]))").c_str(),
942  RooArgList(*pdfIntegralCurrent));
943 
944  termList.add(*term);
945  integralList.add(*pdfIntegralCurrent);
946  }
947 
948  auto integralFull = new RooAddition((baseName + "_correctionFullIntegralTerm").c_str(),
949  "integral",
950  integralList,
951  true);
952 
953  auto fullRangeTerm = new RooFormulaVar((baseName + "_foobar").c_str(),
954  (std::string("(") + std::to_string(sumEntriesTotal) + " * log(x[0]))").c_str(),
955  RooArgList(*integralFull));
956 
957  termList.add(*fullRangeTerm);
958  return new RooAddition((baseName + "_correction").c_str(), "correction", termList, true);
959 }
960 
961 } // namespace
962 
963 
964 ////////////////////////////////////////////////////////////////////////////////
965 /// Construct representation of -log(L) of PDFwith given dataset. If dataset is unbinned, an unbinned likelihood is constructed. If the dataset
966 /// is binned, a binned likelihood is constructed.
967 ///
968 /// See RooAbsPdf::createNLL(RooAbsData& data, RooCmdArg arg1, RooCmdArg arg2, RooCmdArg arg3, RooCmdArg arg4,
969 /// RooCmdArg arg5, RooCmdArg arg6, RooCmdArg arg7, RooCmdArg arg8)
970 /// for documentation of options
971 
973 {
974 
975  // Select the pdf-specific commands
976  RooCmdConfig pc(Form("RooAbsPdf::createNLL(%s)",GetName())) ;
977 
978  pc.defineString("rangeName","RangeWithName",0,"",kTRUE) ;
979  pc.defineString("addCoefRange","SumCoefRange",0,"") ;
980  pc.defineString("globstag","GlobalObservablesTag",0,"") ;
981  pc.defineDouble("rangeLo","Range",0,-999.) ;
982  pc.defineDouble("rangeHi","Range",1,-999.) ;
983  pc.defineInt("splitRange","SplitRange",0,0) ;
984  pc.defineInt("ext","Extended",0,2) ;
985  pc.defineInt("numcpu","NumCPU",0,1) ;
986  pc.defineInt("interleave","NumCPU",1,0) ;
987  pc.defineInt("verbose","Verbose",0,0) ;
988  pc.defineInt("optConst","Optimize",0,0) ;
989  pc.defineInt("cloneData","CloneData", 0, 2);
990  pc.defineSet("projDepSet","ProjectedObservables",0,0) ;
991  pc.defineSet("cPars","Constrain",0,0) ;
992  pc.defineSet("glObs","GlobalObservables",0,0) ;
993 // pc.defineInt("constrAll","Constrained",0,0) ;
994  pc.defineInt("doOffset","OffsetLikelihood",0,0) ;
995  pc.defineSet("extCons","ExternalConstraints",0,0) ;
996  pc.defineInt("BatchMode", "BatchMode", 0, 0);
997  pc.defineDouble("IntegrateBins", "IntegrateBins", 0, -1.);
998  pc.defineMutex("Range","RangeWithName") ;
999 // pc.defineMutex("Constrain","Constrained") ;
1000  pc.defineMutex("GlobalObservables","GlobalObservablesTag") ;
1001 
1002  // Process and check varargs
1003  pc.process(cmdList) ;
1004  if (!pc.ok(kTRUE)) {
1005  return 0 ;
1006  }
1007 
1008  // Decode command line arguments
1009  const char* rangeName = pc.getString("rangeName",0,kTRUE) ;
1010  const char* addCoefRangeName = pc.getString("addCoefRange",0,kTRUE) ;
1011  const char* globsTag = pc.getString("globstag",0,kTRUE) ;
1012  Int_t ext = pc.getInt("ext") ;
1013  Int_t numcpu = pc.getInt("numcpu") ;
1014  Int_t numcpu_strategy = pc.getInt("interleave");
1015  // strategy 3 works only for RooSimultaneus.
1016  if (numcpu_strategy==3 && !this->InheritsFrom("RooSimultaneous") ) {
1017  coutW(Minimization) << "Cannot use a NumCpu Strategy = 3 when the pdf is not a RooSimultaneus, "
1018  "falling back to default strategy = 0" << endl;
1019  numcpu_strategy = 0;
1020  }
1021  RooFit::MPSplit interl = (RooFit::MPSplit) numcpu_strategy;
1022 
1023  Int_t splitr = pc.getInt("splitRange") ;
1024  Bool_t verbose = pc.getInt("verbose") ;
1025  Int_t optConst = pc.getInt("optConst") ;
1026  Int_t cloneData = pc.getInt("cloneData") ;
1027  Int_t doOffset = pc.getInt("doOffset") ;
1028 
1029  // If no explicit cloneData command is specified, cloneData is set to true if optimization is activated
1030  if (cloneData==2) {
1031  cloneData = optConst ;
1032  }
1033 
1034 
1035  RooArgSet* cPars = pc.getSet("cPars") ;
1036  RooArgSet* glObs = pc.getSet("glObs") ;
1037  if (pc.hasProcessed("GlobalObservablesTag")) {
1038  if (glObs) delete glObs ;
1039  RooArgSet* allVars = getVariables() ;
1040  glObs = (RooArgSet*) allVars->selectByAttrib(globsTag,kTRUE) ;
1041  coutI(Minimization) << "User-defined specification of global observables definition with tag named '" << globsTag << "'" << endl ;
1042  delete allVars ;
1043  } else if (!pc.hasProcessed("GlobalObservables")) {
1044 
1045  // Neither GlobalObservables nor GlobalObservablesTag has been processed - try if a default tag is defined in the head node
1046  // Check if head not specifies default global observable tag
1047  const char* defGlobObsTag = getStringAttribute("DefaultGlobalObservablesTag") ;
1048  if (defGlobObsTag) {
1049  coutI(Minimization) << "p.d.f. provides built-in specification of global observables definition with tag named '" << defGlobObsTag << "'" << endl ;
1050  if (glObs) delete glObs ;
1051  RooArgSet* allVars = getVariables() ;
1052  glObs = (RooArgSet*) allVars->selectByAttrib(defGlobObsTag,kTRUE) ;
1053  }
1054  }
1055 
1056 
1057  Bool_t doStripDisconnected=kFALSE ;
1058 
1059  // If no explicit list of parameters to be constrained is specified apply default algorithm
1060  // All terms of RooProdPdfs that do not contain observables and share a parameters with one or more
1061  // terms that do contain observables are added as constraints.
1062  if (!cPars) {
1063  cPars = getParameters(data,kFALSE) ;
1064  doStripDisconnected=kTRUE ;
1065  }
1066  const RooArgSet* extCons = pc.getSet("extCons") ;
1067 
1068  // Process automatic extended option
1069  if (ext==2) {
1070  ext = ((extendMode()==CanBeExtended || extendMode()==MustBeExtended)) ? 1 : 0 ;
1071  if (ext) {
1072  coutI(Minimization) << "p.d.f. provides expected number of events, including extended term in likelihood." << endl ;
1073  }
1074  }
1075 
1076  // Clear possible range attributes from previous fits.
1077  setStringAttribute("fitrange", nullptr);
1078 
1079  if (pc.hasProcessed("Range")) {
1080  Double_t rangeLo = pc.getDouble("rangeLo") ;
1081  Double_t rangeHi = pc.getDouble("rangeHi") ;
1082 
1083  // Create range with name 'fit' with above limits on all observables
1084  RooArgSet* obs = getObservables(&data) ;
1085  for (auto arg : *obs) {
1086  RooRealVar* rrv = dynamic_cast<RooRealVar*>(arg) ;
1087  if (rrv) rrv->setRange("fit",rangeLo,rangeHi) ;
1088  }
1089 
1090  // Set range name to be fitted to "fit"
1091  rangeName = "fit" ;
1092  }
1093 
1094  RooArgSet projDeps ;
1095  RooArgSet* tmp = pc.getSet("projDepSet") ;
1096  if (tmp) {
1097  projDeps.add(*tmp) ;
1098  }
1099 
1100  // Construct NLL
1102  RooAbsReal* nll ;
1103  string baseName = Form("nll_%s_%s",GetName(),data.GetName()) ;
1105  cfg.addCoefRangeName = addCoefRangeName ? addCoefRangeName : "";
1106  cfg.nCPU = numcpu;
1107  cfg.interleave = interl;
1108  cfg.verbose = verbose;
1109  cfg.splitCutRange = static_cast<bool>(splitr);
1110  cfg.cloneInputData = static_cast<bool>(cloneData);
1111  cfg.integrateOverBinsPrecision = pc.getDouble("IntegrateBins");
1112  cfg.binnedL = false;
1113  if (!rangeName || strchr(rangeName,',')==0) {
1114  // Simple case: default range, or single restricted range
1115  //cout<<"FK: Data test 1: "<<data.sumEntries()<<endl;
1116 
1117  cfg.rangeName = rangeName ? rangeName : "";
1118  auto theNLL = new RooNLLVar(baseName.c_str(),"-log(likelihood)",*this,data,projDeps,cfg, ext);
1119  theNLL->batchMode(pc.getInt("BatchMode"));
1120  nll = theNLL;
1121  } else {
1122  // Composite case: multiple ranges
1123  RooArgList nllList ;
1124  auto tokens = RooHelpers::tokenise(rangeName, ",");
1125  if (RooHelpers::checkIfRangesOverlap(*this, data, tokens)) {
1126  throw std::runtime_error(
1127  std::string("Error in RooAbsPdf::createNLL! The ranges ") + rangeName + " are overlapping!");
1128  }
1129  for (const auto& token : tokens) {
1130  cfg.rangeName = token;
1131  auto nllComp = new RooNLLVar((baseName + "_" + token).c_str(),"-log(likelihood)",
1132  *this,data,projDeps,cfg,ext);
1133  nllComp->batchMode(pc.getInt("BatchMode"));
1134  nllList.add(*nllComp) ;
1135  }
1136 
1137  if (!ext) {
1138  // Each RooNLLVar was created with the normalization set corresponding to
1139  // the subrange, not the union range like it should be. We have to add an
1140  // extra term to cancel this normalization problem. However, this is
1141  // only necessarry for the non-extended case, because adding an extension
1142  // term to the individual NLLs as done here is mathematicall equivalent
1143  // to adding the normalization correction terms plus a global extension
1144  // term.
1145  nllList.add(*createMultiRangeNLLCorrectionTerm(*this, data, baseName, rangeName));
1146  }
1147 
1148  nll = new RooAddition(baseName.c_str(),"-log(likelihood)",nllList,true) ;
1149  }
1151 
1152  // Collect internal and external constraint specifications
1153  RooArgSet allConstraints ;
1154 
1155  if (_myws && _myws->set(Form("CACHE_CONSTR_OF_PDF_%s_FOR_OBS_%s", GetName(), RooNameSet(*data.get()).content()))) {
1156 
1157  // retrieve from cache
1158  const RooArgSet *constr =
1159  _myws->set(Form("CACHE_CONSTR_OF_PDF_%s_FOR_OBS_%s", GetName(), RooNameSet(*data.get()).content()));
1160  coutI(Minimization) << "createNLL picked up cached constraints from workspace with " << constr->getSize()
1161  << " entries" << endl;
1162  allConstraints.add(*constr);
1163 
1164  } else {
1165 
1166  if (cPars && cPars->getSize() > 0) {
1167  RooArgSet *constraints = getAllConstraints(*data.get(), *cPars, doStripDisconnected);
1168  allConstraints.add(*constraints);
1169  delete constraints;
1170  }
1171  if (extCons) {
1172  allConstraints.add(*extCons);
1173  }
1174 
1175  // write to cache
1176  if (_myws) {
1177  // cout << "createNLL: creating cache for allconstraints=" << allConstraints << endl ;
1178  coutI(Minimization) << "createNLL: caching constraint set under name "
1179  << Form("CONSTR_OF_PDF_%s_FOR_OBS_%s", GetName(), RooNameSet(*data.get()).content())
1180  << " with " << allConstraints.getSize() << " entries" << endl;
1182  Form("CACHE_CONSTR_OF_PDF_%s_FOR_OBS_%s", GetName(), RooNameSet(*data.get()).content()), allConstraints);
1183  }
1184  }
1185 
1186  // Include constraints, if any, in likelihood
1187  RooAbsReal* nllCons(0) ;
1188  if (allConstraints.getSize()>0 && cPars) {
1189 
1190  coutI(Minimization) << " Including the following constraint terms in minimization: " << allConstraints << endl ;
1191  if (glObs) {
1192  coutI(Minimization) << "The following global observables have been defined: " << *glObs << endl ;
1193  }
1194  nllCons = new RooConstraintSum(Form("%s_constr",baseName.c_str()),"nllCons",allConstraints,glObs ? *glObs : *cPars) ;
1195  nllCons->setOperMode(ADirty) ;
1196  RooAbsReal* orignll = nll ;
1197 
1198  nll = new RooAddition(Form("%s_with_constr",baseName.c_str()),"nllWithCons",RooArgSet(*nll,*nllCons)) ;
1199  nll->addOwnedComponents(RooArgSet(*orignll,*nllCons)) ;
1200  }
1201 
1202 
1203  if (optConst) {
1205  }
1206 
1207  if (doStripDisconnected) {
1208  delete cPars ;
1209  }
1210 
1211  if (doOffset) {
1212  nll->enableOffsetting(kTRUE) ;
1213  }
1214 
1215  return nll ;
1216 }
1217 
1218 
1219 template <class Minimizer>
1221 {
1222  // Calculated corrected errors for weighted likelihood fits
1223  std::unique_ptr<RooFitResult> rw(minimizer.save());
1224  // Weighted inverse Hessian matrix
1225  const TMatrixDSym &matV = rw->covarianceMatrix();
1226  coutI(Fitting)
1227  << "RooAbsPdf::fitTo(" << this->GetName()
1228  << ") Calculating covariance matrix according to the asymptotically correct approach. If you find this "
1229  "method useful please consider citing https://arxiv.org/abs/1911.01303."
1230  << endl;
1231 
1232  // Initialise matrix containing first derivatives
1233  auto nFloatPars = rw->floatParsFinal().getSize();
1234  TMatrixDSym num(nFloatPars);
1235  for (int k = 0; k < nFloatPars; k++) {
1236  for (int l = 0; l < nFloatPars; l++) {
1237  num(k, l) = 0.0;
1238  }
1239  }
1240  RooArgSet *obs = this->getObservables(data);
1241  // Create derivative objects
1242  std::vector<std::unique_ptr<RooDerivative>> derivatives;
1243  const RooArgList &floated = rw->floatParsFinal();
1244  std::unique_ptr<RooArgSet> floatingparams{
1245  static_cast<RooArgSet *>(this->getParameters(data)->selectByAttrib("Constant", false))};
1246  for (const auto paramresult : floated) {
1247  auto paraminternal = static_cast<RooRealVar *>(floatingparams->find(*paramresult));
1248  assert(floatingparams->find(*paramresult)->IsA() == RooRealVar::Class());
1249  derivatives.emplace_back(this->derivative(*paraminternal, *obs, 1));
1250  }
1251 
1252  // Loop over data
1253  for (int j = 0; j < data.numEntries(); j++) {
1254  // Sets obs to current data point, this is where the pdf will be evaluated
1255  *obs = *data.get(j);
1256  // Determine first derivatives
1257  std::vector<double> diffs(floated.getSize(), 0.0);
1258  for (int k = 0; k < floated.getSize(); k++) {
1259  const auto paramresult = static_cast<RooRealVar *>(floated.at(k));
1260  auto paraminternal = static_cast<RooRealVar *>(floatingparams->find(*paramresult));
1261  // first derivative to parameter k at best estimate point for this measurement
1262  double diff = derivatives[k]->getVal();
1263  // need to reset to best fit point after differentiation
1264  *paraminternal = paramresult->getVal();
1265  diffs[k] = diff;
1266  }
1267  // Fill numerator matrix
1268  double prob = getVal(obs);
1269  for (int k = 0; k < floated.getSize(); k++) {
1270  for (int l = 0; l < floated.getSize(); l++) {
1271  num(k, l) += data.weight() * data.weight() * diffs[k] * diffs[l] / (prob * prob);
1272  }
1273  }
1274  }
1275  num.Similarity(matV);
1276 
1277  // Propagate corrected errors to parameters objects
1278  minimizer.applyCovarianceMatrix(num);
1279 
1280  // The derivatives are found in RooFit and not with the minimizer (e.g.
1281  // minuit), so the quality of the corrected covariance matrix corresponds to
1282  // the quality of the original covariance matrix
1283  return rw->covQual();
1284 }
1285 
1286 template <class Minimizer>
1288 {
1289 
1290  // Make list of RooNLLVar components of FCN
1291  std::vector<RooNLLVar *> nllComponents;
1292  std::unique_ptr<RooArgSet> comps{nll.getComponents()};
1293  for (auto const &arg : *comps) {
1294  if (RooNLLVar *nllComp = dynamic_cast<RooNLLVar *>(arg)) {
1295  nllComponents.push_back(nllComp);
1296  }
1297  }
1298 
1299  // Calculated corrected errors for weighted likelihood fits
1300  std::unique_ptr<RooFitResult> rw{minimizer.save()};
1301  for (auto &comp : nllComponents) {
1302  comp->applyWeightSquared(true);
1303  }
1304  coutI(Fitting) << "RooAbsPdf::fitTo(" << this->GetName()
1305  << ") Calculating sum-of-weights-squared correction matrix for covariance matrix"
1306  << std::endl;
1307  minimizer.hesse();
1308  std::unique_ptr<RooFitResult> rw2{minimizer.save()};
1309  for (auto &comp : nllComponents) {
1310  comp->applyWeightSquared(false);
1311  }
1312 
1313  // Apply correction matrix
1314  const TMatrixDSym &matV = rw->covarianceMatrix();
1315  TMatrixDSym matC = rw2->covarianceMatrix();
1316  ROOT::Math::CholeskyDecompGenDim<double> decomp(matC.GetNrows(), matC);
1317  if (!decomp) {
1318  coutE(Fitting) << "RooAbsPdf::fitTo(" << this->GetName()
1319  << ") ERROR: Cannot apply sum-of-weights correction to covariance matrix: correction "
1320  "matrix calculated with weight-squared is singular"
1321  << std::endl;
1322  return -1;
1323  }
1324 
1325  // replace C by its inverse
1326  decomp.Invert(matC);
1327  // the class lies about the matrix being symmetric, so fill in the
1328  // part above the diagonal
1329  for (int i = 0; i < matC.GetNrows(); ++i) {
1330  for (int j = 0; j < i; ++j) {
1331  matC(j, i) = matC(i, j);
1332  }
1333  }
1334  matC.Similarity(matV);
1335  // C now contiains V C^-1 V
1336  // Propagate corrected errors to parameters objects
1337  minimizer.applyCovarianceMatrix(matC);
1338 
1339  return std::min(rw->covQual(), rw2->covQual());
1340 }
1341 
1342 
1343 ////////////////////////////////////////////////////////////////////////////////
1344 /// Fit PDF to given dataset. If dataset is unbinned, an unbinned maximum likelihood is performed. If the dataset
1345 /// is binned, a binned maximum likelihood is performed. By default the fit is executed through the MINUIT
1346 /// commands MIGRAD, HESSE in succession.
1347 /// \param[in] data Data to fit the PDF to
1348 /// \param[in] arg1 One or more arguments to control the behaviour of the fit
1349 /// \return RooFitResult with fit status and parameters if option Save() is used, `nullptr` otherwise. The user takes ownership of the fit result.
1350 ///
1351 /// The following named arguments are supported
1352 ///
1353 /// <table>
1354 /// <tr><th> Type of CmdArg <th> Options to control construction of -log(L)
1355 /// <tr><td> `ConditionalObservables(const RooArgSet& set)` <td> Do not normalize PDF over listed observables
1356 /// <tr><td> `Extended(Bool_t flag)` <td> Add extended likelihood term, off by default
1357 /// <tr><td> `Range(const char* name)` <td> Fit only data inside range with given name. Multiple comma-separated range names can be specified.
1358 /// In this case, the unnormalized PDF \f$f(x)\f$ is normalized by the integral over all ranges \f$r_i\f$:
1359 /// \f[
1360 /// p(x) = \frac{f(x)}{\sum_i \int_{r_i} f(x) dx}.
1361 /// \f]
1362 /// <tr><td> `Range(Double_t lo, Double_t hi)` <td> Fit only data inside given range. A range named "fit" is created on the fly on all observables.
1363 /// <tr><td> `SumCoefRange(const char* name)` <td> Set the range in which to interpret the coefficients of RooAddPdf components
1364 /// <tr><td> `NumCPU(int num, int strat)` <td> Parallelize NLL calculation on `num` CPUs
1365 /// <table>
1366 /// <tr><th> Strategy <th> Effect
1367 /// <tr><td> 0 = RooFit::BulkPartition (Default) <td> Divide events in N equal chunks
1368 /// <tr><td> 1 = RooFit::Interleave <td> Process event i%N in process N. Recommended for binned data with
1369 /// a substantial number of zero-bins, which will be distributed across processes more equitably in this strategy
1370 /// <tr><td> 2 = RooFit::SimComponents <td> Process each component likelihood of a RooSimultaneous fully in a single process
1371 /// and distribute components over processes. This approach can be benificial if normalization calculation time
1372 /// dominates the total computation time of a component (since the normalization calculation must be performed
1373 /// in each process in strategies 0 and 1. However beware that if the RooSimultaneous components do not share many
1374 /// parameters this strategy is inefficient: as most minuit-induced likelihood calculations involve changing
1375 /// a single parameter, only 1 of the N processes will be active most of the time if RooSimultaneous components
1376 /// do not share many parameters
1377 /// <tr><td> 3 = RooFit::Hybrid <td> Follow strategy 0 for all RooSimultaneous components, except those with less than
1378 /// 30 dataset entries, for which strategy 2 is followed.
1379 /// </table>
1380 /// <tr><td> `SplitRange(Bool_t flag)` <td> Use separate fit ranges in a simultaneous fit. Actual range name for each subsample is assumed
1381 /// to by `rangeName_indexState` where indexState is the state of the master index category of the simultaneous fit.
1382 /// Using `Range("range"), SplitRange()` as switches, different ranges could be set like this:
1383 /// ```
1384 /// myVariable.setRange("range_pi0", 135, 210);
1385 /// myVariable.setRange("range_gamma", 50, 210);
1386 /// ```
1387 /// <tr><td> `Constrain(const RooArgSet&pars)` <td> For p.d.f.s that contain internal parameter constraint terms (that is usually product PDFs, where one
1388 /// term of the product depends on parameters but not on the observable(s),), only apply constraints to the given subset of parameters.
1389 /// <tr><td> `ExternalConstraints(const RooArgSet& )` <td> Include given external constraints to likelihood by multiplying them with the original likelihood.
1390 /// <tr><td> `GlobalObservables(const RooArgSet&)` <td> Define the set of normalization observables to be used for the constraint terms.
1391 /// If none are specified the constrained parameters are used.
1392 /// <tr><td> `Offset(Bool_t)` <td> Offset likelihood by initial value (so that starting value of FCN in minuit is zero).
1393 /// This can improve numeric stability in simultaneously fits with components with large likelihood values
1394 /// <tr><td> `BatchMode(bool on)` <td> **Experimental** batch evaluation mode. This computes a batch of likelihood values at a time,
1395 /// uses faster math functions and possibly auto vectorisation (this depends on the compiler flags).
1396 /// Depending on hardware capabilities, the compiler flags and whether a batch evaluation function was
1397 /// implemented for the PDFs of the model, likelihood computations are 2x to 10x faster.
1398 /// The relative difference of the single log-likelihoods w.r.t. the legacy mode is usually better than 1.E-12,
1399 /// and fit parameters usually agree to better than 1.E-6.
1400 /// <tr><td> `IntegrateBins(double precision)` <td> In binned fits, integrate the PDF over the bins instead of using the probability density at the bin centre.
1401 /// This can reduce the bias observed when fitting functions with high curvature to binned data.
1402 /// - precision > 0: Activate bin integration everywhere. Use precision between 0.01 and 1.E-6, depending on binning.
1403 /// Note that a low precision such as 0.01 might yield identical results to 1.E-4, since the integrator might reach 1.E-4 already in its first
1404 /// integration step. If lower precision is desired (more speed), a RooBinSamplingPdf has to be created manually, and its integrator
1405 /// has to be manipulated directly.
1406 /// - precision = 0: Activate bin integration only for continuous PDFs fit to a RooDataHist.
1407 /// - precision < 0: Deactivate.
1408 /// \see RooBinSamplingPdf
1409 ///
1410 /// <tr><th><th> Options to control flow of fit procedure
1411 /// <tr><td> `Minimizer("<type>", "<algo>")` <td> Choose minimization package and optionally the algorithm to use. Default is MINUIT/MIGRAD through the RooMinimizer interface,
1412 /// but others can be specified (through RooMinimizer interface). Select OldMinuit to use MINUIT through the old RooMinuit interface
1413 /// <table>
1414 /// <tr><th> Type <th> Algorithm
1415 /// <tr><td> OldMinuit <td> migrad, simplex, minimize (=migrad+simplex), migradimproved (=migrad+improve)
1416 /// <tr><td> Minuit <td> migrad, simplex, minimize (=migrad+simplex), migradimproved (=migrad+improve)
1417 /// <tr><td> Minuit2 <td> migrad, simplex, minimize, scan
1418 /// <tr><td> GSLMultiMin <td> conjugatefr, conjugatepr, bfgs, bfgs2, steepestdescent
1419 /// <tr><td> GSLSimAn <td> -
1420 /// </table>
1421 ///
1422 /// <tr><td> `InitialHesse(Bool_t flag)` <td> Flag controls if HESSE before MIGRAD as well, off by default
1423 /// <tr><td> `Optimize(Bool_t flag)` <td> Activate constant term optimization of test statistic during minimization (on by default)
1424 /// <tr><td> `Hesse(Bool_t flag)` <td> Flag controls if HESSE is run after MIGRAD, on by default
1425 /// <tr><td> `Minos(Bool_t flag)` <td> Flag controls if MINOS is run after HESSE, off by default
1426 /// <tr><td> `Minos(const RooArgSet& set)` <td> Only run MINOS on given subset of arguments
1427 /// <tr><td> `Save(Bool_t flag)` <td> Flag controls if RooFitResult object is produced and returned, off by default
1428 /// <tr><td> `Strategy(Int_t flag)` <td> Set Minuit strategy (0 to 2, default is 1)
1429 /// <tr><td> `EvalErrorWall(bool flag=true)` <td> When parameters are in disallowed regions (e.g. PDF is negative), return very high value to fitter
1430 /// to force it out of that region. This can, however, mean that the fitter gets lost in this region. If
1431 /// this happens, try switching it off.
1432 /// <tr><td> `RecoverFromUndefinedRegions(double strength)` <td> When PDF is invalid (e.g. parameter in undefined region), try to direct minimiser away from that region.
1433 /// `strength` controls the magnitude of the penalty term. Leaving out this argument defaults to 10. Switch off with `strength = 0.`.
1434 /// <tr><td> `FitOptions(const char* optStr)` <td> \deprecated Steer fit with classic options string (for backward compatibility).
1435 /// \attention Use of this option excludes use of any of the new style steering options.
1436 ///
1437 /// <tr><td> `SumW2Error(Bool_t flag)` <td> Apply correction to errors and covariance matrix.
1438 /// This uses two covariance matrices, one with the weights, the other with squared weights,
1439 /// to obtain the correct errors for weighted likelihood fits. If this option is activated, the
1440 /// corrected covariance matrix is calculated as \f$ V_\mathrm{corr} = V C^{-1} V \f$, where \f$ V \f$ is the original
1441 /// covariance matrix and \f$ C \f$ is the inverse of the covariance matrix calculated using the
1442 /// squared weights. This allows to switch between two interpretations of errors:
1443 /// <table>
1444 /// <tr><th> SumW2Error <th> Interpretation
1445 /// <tr><td> true <td> The errors reflect the uncertainty of the Monte Carlo simulation.
1446 /// Use this if you want to know how much accuracy you can get from the available Monte Carlo statistics.
1447 ///
1448 /// **Example**: Simulation with 1000 events, the average weight is 0.1.
1449 /// The errors are as big as if one fitted to 1000 events.
1450 /// <tr><td> false <td> The errors reflect the errors of a dataset, which is as big as the sum of weights.
1451 /// Use this if you want to know what statistical errors you would get if you had a dataset with as many
1452 /// events as the (weighted) Monte Carlo simulation represents.
1453 ///
1454 /// **Example** (Data as above):
1455 /// The errors are as big as if one fitted to 100 events.
1456 /// </table>
1457 /// \note If the `SumW2Error` correction is enabled, the covariance matrix quality stored in the RooFitResult
1458 /// object will be the minimum of the original covariance matrix quality and the quality of the covariance
1459 /// matrix calculated with the squared weights.
1460 /// <tr><td> `AsymptoticError()` <td> Use the asymptotically correct approach to estimate errors in the presence of weights.
1461 /// This is slower but more accurate than `SumW2Error`. See also https://arxiv.org/abs/1911.01303).
1462 /// <tr><td> `PrefitDataFraction(double fraction)`
1463 /// <td> Runs a prefit on a small dataset of size fraction*(actual data size). This can speed up fits
1464 /// by finding good starting values for the parameters for the actual fit.
1465 /// \warning Prefitting may give bad results when used in binned analysis.
1466 ///
1467 /// <tr><th><th> Options to control informational output
1468 /// <tr><td> `Verbose(Bool_t flag)` <td> Flag controls if verbose output is printed (NLL, parameter changes during fit).
1469 /// <tr><td> `Timer(Bool_t flag)` <td> Time CPU and wall clock consumption of fit steps, off by default.
1470 /// <tr><td> `PrintLevel(Int_t level)` <td> Set Minuit print level (-1 to 3, default is 1). At -1 all RooFit informational messages are suppressed as well.
1471 /// See RooMinimizer::PrintLevel for the meaning of the levels.
1472 /// <tr><td> `Warnings(Bool_t flag)` <td> Enable or disable MINUIT warnings (enabled by default)
1473 /// <tr><td> `PrintEvalErrors(Int_t numErr)` <td> Control number of p.d.f evaluation errors printed per likelihood evaluation.
1474 /// A negative value suppresses output completely, a zero value will only print the error count per p.d.f component,
1475 /// a positive value will print details of each error up to `numErr` messages per p.d.f component.
1476 /// </table>
1477 ///
1478 
1479 RooFitResult* RooAbsPdf::fitTo(RooAbsData& data, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
1480  const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
1481 {
1482  RooLinkedList l ;
1483  l.Add((TObject*)&arg1) ; l.Add((TObject*)&arg2) ;
1484  l.Add((TObject*)&arg3) ; l.Add((TObject*)&arg4) ;
1485  l.Add((TObject*)&arg5) ; l.Add((TObject*)&arg6) ;
1486  l.Add((TObject*)&arg7) ; l.Add((TObject*)&arg8) ;
1487  return fitTo(data,l) ;
1488 }
1489 
1490 
1491 
1492 ////////////////////////////////////////////////////////////////////////////////
1493 /// Fit PDF to given dataset. If dataset is unbinned, an unbinned maximum likelihood is performed. If the dataset
1494 /// is binned, a binned maximum likelihood is performed. By default the fit is executed through the MINUIT
1495 /// commands MIGRAD, HESSE and MINOS in succession.
1496 ///
1497 /// See RooAbsPdf::fitTo(RooAbsData&,RooCmdArg&,RooCmdArg&,RooCmdArg&,RooCmdArg&,RooCmdArg&,RooCmdArg&,RooCmdArg&,RooCmdArg&)
1498 ///
1499 /// for documentation of options
1500 
1502 {
1503  // Select the pdf-specific commands
1504  RooCmdConfig pc(Form("RooAbsPdf::fitTo(%s)",GetName())) ;
1505 
1506  RooLinkedList fitCmdList(cmdList) ;
1507  RooLinkedList nllCmdList = pc.filterCmdList(fitCmdList,"ProjectedObservables,Extended,Range,"
1508  "RangeWithName,SumCoefRange,NumCPU,SplitRange,Constrained,Constrain,ExternalConstraints,"
1509  "CloneData,GlobalObservables,GlobalObservablesTag,OffsetLikelihood,BatchMode,IntegrateBins");
1510 
1511  pc.defineDouble("prefit", "Prefit",0,0);
1512  pc.defineDouble("RecoverFromUndefinedRegions", "RecoverFromUndefinedRegions",0,10.);
1513  pc.defineString("fitOpt","FitOptions",0,"") ;
1514  pc.defineInt("optConst","Optimize",0,2) ;
1515  pc.defineInt("verbose","Verbose",0,0) ;
1516  pc.defineInt("doSave","Save",0,0) ;
1517  pc.defineInt("doTimer","Timer",0,0) ;
1518  pc.defineInt("plevel","PrintLevel",0,1) ;
1519  pc.defineInt("strat","Strategy",0,1) ;
1520  pc.defineInt("initHesse","InitialHesse",0,0) ;
1521  pc.defineInt("hesse","Hesse",0,1) ;
1522  pc.defineInt("minos","Minos",0,0) ;
1523  pc.defineInt("ext","Extended",0,2) ;
1524  pc.defineInt("numcpu","NumCPU",0,1) ;
1525  pc.defineInt("numee","PrintEvalErrors",0,10) ;
1526  pc.defineInt("doEEWall","EvalErrorWall",0,1) ;
1527  pc.defineInt("doWarn","Warnings",0,1) ;
1528  pc.defineInt("doSumW2","SumW2Error",0,-1) ;
1529  pc.defineInt("doAsymptoticError","AsymptoticError",0,-1) ;
1530  pc.defineInt("doOffset","OffsetLikelihood",0,0) ;
1531  pc.defineString("mintype","Minimizer",0,"Minuit") ;
1532  pc.defineString("minalg","Minimizer",1,"minuit") ;
1533  pc.defineObject("minosSet","Minos",0,0) ;
1534  pc.defineSet("cPars","Constrain",0,0) ;
1535  pc.defineSet("extCons","ExternalConstraints",0,0) ;
1536  pc.defineMutex("FitOptions","Verbose") ;
1537  pc.defineMutex("FitOptions","Save") ;
1538  pc.defineMutex("FitOptions","Timer") ;
1539  pc.defineMutex("FitOptions","Strategy") ;
1540  pc.defineMutex("FitOptions","InitialHesse") ;
1541  pc.defineMutex("FitOptions","Hesse") ;
1542  pc.defineMutex("FitOptions","Minos") ;
1543  pc.defineMutex("Range","RangeWithName") ;
1544  pc.defineMutex("InitialHesse","Minimizer") ;
1545 
1546  // Process and check varargs
1547  pc.process(fitCmdList) ;
1548  if (!pc.ok(kTRUE)) {
1549  return 0 ;
1550  }
1551 
1552  // Decode command line arguments
1553  Double_t prefit = pc.getDouble("prefit");
1554  const double recoverFromNaN = pc.getDouble("RecoverFromUndefinedRegions");
1555  const char* fitOpt = pc.getString("fitOpt",0,kTRUE) ;
1556  Int_t optConst = pc.getInt("optConst") ;
1557  Int_t verbose = pc.getInt("verbose") ;
1558  Int_t doSave = pc.getInt("doSave") ;
1559  Int_t doTimer = pc.getInt("doTimer") ;
1560  Int_t plevel = pc.getInt("plevel") ;
1561  Int_t strat = pc.getInt("strat") ;
1562  Int_t initHesse= pc.getInt("initHesse") ;
1563  Int_t hesse = pc.getInt("hesse") ;
1564  Int_t minos = pc.getInt("minos") ;
1565  Int_t numee = pc.getInt("numee") ;
1566  Int_t doEEWall = pc.getInt("doEEWall") ;
1567  Int_t doWarn = pc.getInt("doWarn") ;
1568  Int_t doSumW2 = pc.getInt("doSumW2") ;
1569  Int_t doAsymptotic = pc.getInt("doAsymptoticError");
1570  const RooArgSet* minosSet = static_cast<RooArgSet*>(pc.getObject("minosSet")) ;
1571 #ifdef __ROOFIT_NOROOMINIMIZER
1572  const char* minType =0 ;
1573 #else
1574  const char* minType = pc.getString("mintype","Minuit") ;
1575  const char* minAlg = pc.getString("minalg","minuit") ;
1576 #endif
1577 
1578  if (optConst > 1) {
1579  // optConst >= 2 is pre-computating values, which are never used when
1580  // the batchMode is on. This just wastes time.
1581 
1582  RooCmdConfig conf(Form("RooAbsPdf::fitTo(%s)", GetName()));
1583  conf.defineInt("BatchMode","BatchMode",0,0);
1584  conf.allowUndefined(true);
1585  conf.process(nllCmdList);
1586  if (conf.getInt("BatchMode") != 0) {
1587  optConst = 1;
1588  }
1589  }
1590 
1591 
1592  // Determine if the dataset has weights
1593  Bool_t weightedData = data.isNonPoissonWeighted() ;
1594 
1595  // Warn user that a method to determine parameter uncertainties should be provided if weighted data is offered
1596  if (weightedData && doSumW2==-1 && doAsymptotic==-1) {
1597  coutW(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << ") WARNING: a likelihood fit is requested of what appears to be weighted data.\n"
1598  << " While the estimated values of the parameters will always be calculated taking the weights into account,\n"
1599  << " there are multiple ways to estimate the errors of the parameters. You are advised to make an \n"
1600  << " explicit choice for the error calculation:\n"
1601  << " - Either provide SumW2Error(true), to calculate a sum-of-weights-corrected HESSE error matrix\n"
1602  << " (error will be proportional to the number of events in MC).\n"
1603  << " - Or provide SumW2Error(false), to return errors from original HESSE error matrix\n"
1604  << " (which will be proportional to the sum of the weights, i.e., a dataset with <sum of weights> events).\n"
1605  << " - Or provide AsymptoticError(true), to use the asymptotically correct expression\n"
1606  << " (for details see https://arxiv.org/abs/1911.01303)."
1607  << endl ;
1608  }
1609 
1610  if (minos && (doSumW2==1 || doAsymptotic == 1)) {
1611  coutE(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << "): sum-of-weights and asymptotic error correction do not work with MINOS errors. Not fitting." << endl;
1612  return nullptr;
1613  }
1614  if (doAsymptotic==1 && minos) {
1615  coutW(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << ") WARNING: asymptotic correction does not apply to MINOS errors" << endl ;
1616  }
1617 
1618  if (prefit != 0) {
1619  size_t nEvents = static_cast<size_t>(prefit*data.numEntries());
1620  if (prefit > 0.5 || nEvents < 100) {
1621  oocoutW(this,InputArguments) << "PrefitDataFraction should be in suitable range."
1622  << "With the current PrefitDataFraction=" << prefit
1623  << ", the number of events would be " << nEvents<< " out of "
1624  << data.numEntries() << ". Skipping prefit..." << endl;
1625  }
1626  else {
1627  size_t step = data.numEntries()/nEvents;
1628  RooArgSet tinyVars(*data.get());
1629  RooRealVar weight("weight","weight",1);
1630 
1631  if (data.isWeighted()) tinyVars.add(weight);
1632 
1633  RooDataSet tiny("tiny", "tiny", tinyVars,
1634  data.isWeighted() ? RooFit::WeightVar(weight) : RooCmdArg());
1635 
1636  for (int i=0; i<data.numEntries(); i+=step)
1637  {
1638  const RooArgSet *event = data.get(i);
1639  tiny.add(*event, data.weight());
1640  }
1641  RooLinkedList tinyCmdList(cmdList) ;
1642  pc.filterCmdList(tinyCmdList,"Prefit,Hesse,Minos,Verbose,Save,Timer");
1643  RooCmdArg hesse_option = RooFit::Hesse(false);
1644  RooCmdArg print_option = RooFit::PrintLevel(-1);
1645 
1646  tinyCmdList.Add(&hesse_option);
1647  tinyCmdList.Add(&print_option);
1648 
1649  fitTo(tiny,tinyCmdList);
1650  }
1651  }
1652 
1653  RooAbsReal* nll = createNLL(data,nllCmdList) ;
1654  RooFitResult *ret = 0 ;
1655 
1656  //avoid setting both SumW2 and Asymptotic for uncertainty correction
1657  if (doSumW2==1 && doAsymptotic==1) {
1658  coutE(InputArguments) << "RooAbsPdf::fitTo(" << GetName() << ") ERROR: Cannot compute both asymptotically correct and SumW2 errors." << endl ;
1659  return ret;
1660  }
1661 
1662  // Instantiate MINUIT
1663 
1664  if (string(minType)!="OldMinuit") {
1665 
1666 #ifndef __ROOFIT_NOROOMINIMIZER
1667  RooMinimizer m(*nll) ;
1668 
1669  m.setMinimizerType(minType) ;
1670 
1671  m.setEvalErrorWall(doEEWall) ;
1672  m.setRecoverFromNaNStrength(recoverFromNaN);
1673  if (doWarn==0) {
1674  // m.setNoWarn() ; WVE FIX THIS
1675  }
1676 
1677  m.setPrintEvalErrors(numee) ;
1678  if (plevel!=1) {
1679  m.setPrintLevel(plevel) ;
1680  }
1681 
1682  if (optConst) {
1683  // Activate constant term optimization
1684  m.optimizeConst(optConst) ;
1685  }
1686 
1687  if (fitOpt) {
1688 
1689  // Play fit options as historically defined
1690  ret = m.fit(fitOpt) ;
1691 
1692  } else {
1693 
1694  if (verbose) {
1695  // Activate verbose options
1696  m.setVerbose(1) ;
1697  }
1698  if (doTimer) {
1699  // Activate timer options
1700  m.setProfile(1) ;
1701  }
1702 
1703  if (strat!=1) {
1704  // Modify fit strategy
1705  m.setStrategy(strat) ;
1706  }
1707 
1708  if (initHesse) {
1709  // Initialize errors with hesse
1710  m.hesse() ;
1711  }
1712 
1713  // Minimize using chosen algorithm
1714  m.minimize(minType,minAlg) ;
1715 
1716  if (hesse) {
1717  // Evaluate errors with Hesse
1718  m.hesse() ;
1719  }
1720 
1721  int corrCovQual = -1;
1722 
1723  //asymptotically correct approach
1724  if (doAsymptotic==1 && m.getNPar()>0) {
1725  corrCovQual = calculateAsymptoticCorrectedCovMatrix(m, data);
1726  }
1727 
1728  if (doSumW2==1 && m.getNPar()>0) {
1729  corrCovQual = calculateSumW2CorrectedCovMatrix(m, *nll);
1730  }
1731 
1732  if (minos) {
1733  // Evaluate errs with Minos
1734  if (minosSet) {
1735  m.minos(*minosSet) ;
1736  } else {
1737  m.minos() ;
1738  }
1739  }
1740 
1741  // Optionally return fit result
1742  if (doSave) {
1743  string name = Form("fitresult_%s_%s",GetName(),data.GetName()) ;
1744  string title = Form("Result of fit of p.d.f. %s to dataset %s",GetName(),data.GetName()) ;
1745  ret = m.save(name.c_str(),title.c_str()) ;
1746  if((doSumW2==1 || doAsymptotic==1) && m.getNPar()>0) {
1747  ret->setCovQual(corrCovQual);
1748  }
1749  }
1750 
1751  }
1752 
1753  if (optConst) {
1754  m.optimizeConst(0) ;
1755  }
1756 
1757 #endif
1758 
1759  } else {
1760 
1761  RooMinuit m(*nll) ;
1762 
1763  m.setEvalErrorWall(doEEWall) ;
1764  if (doWarn==0) {
1765  m.setNoWarn() ;
1766  }
1767 
1768  m.setPrintEvalErrors(numee) ;
1769  if (plevel!=1) {
1770  m.setPrintLevel(plevel) ;
1771  }
1772 
1773  if (optConst) {
1774  // Activate constant term optimization
1775  m.optimizeConst(optConst) ;
1776  }
1777 
1778  if (fitOpt) {
1779 
1780  // Play fit options as historically defined
1781  ret = m.fit(fitOpt) ;
1782 
1783  } else {
1784 
1785  if (verbose) {
1786  // Activate verbose options
1787  m.setVerbose(1) ;
1788  }
1789  if (doTimer) {
1790  // Activate timer options
1791  m.setProfile(1) ;
1792  }
1793 
1794  if (strat!=1) {
1795  // Modify fit strategy
1796  m.setStrategy(strat) ;
1797  }
1798 
1799  if (initHesse) {
1800  // Initialize errors with hesse
1801  m.hesse() ;
1802  }
1803 
1804  // Minimize using migrad
1805  m.migrad() ;
1806 
1807  if (hesse) {
1808  // Evaluate errors with Hesse
1809  m.hesse() ;
1810  }
1811 
1812  int corrCovQual = -1;
1813 
1814  //asymptotically correct approach
1815  if (doAsymptotic==1 && m.getNPar()>0) {
1816  corrCovQual = calculateAsymptoticCorrectedCovMatrix(m, data);
1817  }
1818 
1819  if (doSumW2==1 && m.getNPar()>0) {
1820  corrCovQual = calculateSumW2CorrectedCovMatrix(m, *nll);
1821  }
1822 
1823  if (minos) {
1824  // Evaluate errs with Minos
1825  if (minosSet) {
1826  m.minos(*minosSet) ;
1827  } else {
1828  m.minos() ;
1829  }
1830  }
1831 
1832  // Optionally return fit result
1833  if (doSave) {
1834  string name = Form("fitresult_%s_%s",GetName(),data.GetName()) ;
1835  string title = Form("Result of fit of p.d.f. %s to dataset %s",GetName(),data.GetName()) ;
1836  ret = m.save(name.c_str(),title.c_str()) ;
1837  if((doSumW2==1 || doAsymptotic==1) && m.getNPar()>0) {
1838  ret->setCovQual(corrCovQual);
1839  }
1840  }
1841 
1842  }
1843 
1844  if (optConst) {
1845  m.optimizeConst(0) ;
1846  }
1847 
1848  }
1849 
1850 
1851 
1852  // Cleanup
1853  delete nll ;
1854  return ret ;
1855 }
1856 
1857 
1858 
1859 ////////////////////////////////////////////////////////////////////////////////
1860 /// Calls RooAbsPdf::createChi2(RooDataSet& data, const RooLinkedList& cmdList) and returns fit result.
1861 
1863 {
1864  // Select the pdf-specific commands
1865  RooCmdConfig pc(Form("RooAbsPdf::chi2FitTo(%s)",GetName())) ;
1866 
1867  // Pull arguments to be passed to chi2 construction from list
1868  RooLinkedList fitCmdList(cmdList) ;
1869  RooLinkedList chi2CmdList = pc.filterCmdList(fitCmdList,"Range,RangeWithName,NumCPU,Optimize,ProjectedObservables,AddCoefRange,SplitRange,DataError,Extended,IntegrateBins") ;
1870 
1871  RooAbsReal* chi2 = createChi2(data,chi2CmdList) ;
1872  RooFitResult* ret = chi2FitDriver(*chi2,fitCmdList) ;
1873 
1874  // Cleanup
1875  delete chi2 ;
1876  return ret ;
1877 }
1878 
1879 
1880 
1881 
1882 ////////////////////////////////////////////////////////////////////////////////
1883 /// Create a \f$ \chi^2 \f$ from a histogram and this function.
1884 ///
1885 /// Options to control construction of the \f$ \chi^2 \f$
1886 /// ------------------------------------------
1887 /// <table>
1888 /// <tr><th> Type of CmdArg <th> Effect on \f$ \chi^2 \f$
1889 /// <tr><td> `Extended()` <td> Use expected number of events of an extended p.d.f as normalization
1890 /// <tr><td> `DataError()` <td> Choose between:
1891 /// - Expected error [RooAbsData::Expected]
1892 /// - Observed error (e.g. Sum-of-weights) [RooAbsData::SumW2]
1893 /// - Poisson interval [RooAbsData::Poisson]
1894 /// - Default: Expected error for unweighted data, Sum-of-weights for weighted data [RooAbsData::Auto]
1895 /// <tr><td> `NumCPU()` <td> Activate parallel processing feature
1896 /// <tr><td> `Range()` <td> Fit only selected region
1897 /// <tr><td> `SumCoefRange()` <td> Set the range in which to interpret the coefficients of RooAddPdf components
1898 /// <tr><td> `SplitRange()` <td> Fit ranges used in different categories get named after the category.
1899 /// Using `Range("range"), SplitRange()` as switches, different ranges could be set like this:
1900 /// ```
1901 /// myVariable.setRange("range_pi0", 135, 210);
1902 /// myVariable.setRange("range_gamma", 50, 210);
1903 /// ```
1904 /// <tr><td> `ConditionalObservables()` <td> Define projected observables
1905 /// </table>
1906 
1908  const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5,
1909  const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
1910 {
1911  RooLinkedList cmdList ;
1912  cmdList.Add((TObject*)&arg1) ; cmdList.Add((TObject*)&arg2) ;
1913  cmdList.Add((TObject*)&arg3) ; cmdList.Add((TObject*)&arg4) ;
1914  cmdList.Add((TObject*)&arg5) ; cmdList.Add((TObject*)&arg6) ;
1915  cmdList.Add((TObject*)&arg7) ; cmdList.Add((TObject*)&arg8) ;
1916 
1917  RooCmdConfig pc(Form("RooAbsPdf::createChi2(%s)",GetName())) ;
1918  pc.defineString("rangeName","RangeWithName",0,"",kTRUE) ;
1919  pc.allowUndefined(kTRUE) ;
1920  pc.process(cmdList) ;
1921  if (!pc.ok(kTRUE)) {
1922  return 0 ;
1923  }
1924  const char* rangeName = pc.getString("rangeName",0,kTRUE) ;
1925 
1926  // Construct Chi2
1928  RooAbsReal* chi2 ;
1929  string baseName = Form("chi2_%s_%s",GetName(),data.GetName()) ;
1930 
1931  // Clear possible range attributes from previous fits.
1932  setStringAttribute("fitrange", nullptr);
1933 
1934  if (!rangeName || strchr(rangeName,',')==0) {
1935  // Simple case: default range, or single restricted range
1936 
1937  chi2 = new RooChi2Var(baseName.c_str(),baseName.c_str(),*this,data,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
1938 
1939  } else {
1940 
1941  // Find which argument is RangeWithName
1942  const RooCmdArg* rarg(0) ;
1943  string rcmd = "RangeWithName" ;
1944  if (arg1.GetName()==rcmd) rarg = &arg1 ;
1945  if (arg2.GetName()==rcmd) rarg = &arg2 ;
1946  if (arg3.GetName()==rcmd) rarg = &arg3 ;
1947  if (arg4.GetName()==rcmd) rarg = &arg4 ;
1948  if (arg5.GetName()==rcmd) rarg = &arg5 ;
1949  if (arg6.GetName()==rcmd) rarg = &arg6 ;
1950  if (arg7.GetName()==rcmd) rarg = &arg7 ;
1951  if (arg8.GetName()==rcmd) rarg = &arg8 ;
1952 
1953  // Composite case: multiple ranges
1954  RooArgList chi2List ;
1955  for (std::string& token : RooHelpers::tokenise(rangeName, ",")) {
1956  RooCmdArg subRangeCmd = RooFit::Range(token.c_str()) ;
1957  // Construct chi2 while substituting original RangeWithName argument with subrange argument created above
1958  RooAbsReal* chi2Comp = new RooChi2Var(Form("%s_%s", baseName.c_str(), token.c_str()), "chi^2", *this, data,
1959  &arg1==rarg?subRangeCmd:arg1,&arg2==rarg?subRangeCmd:arg2,
1960  &arg3==rarg?subRangeCmd:arg3,&arg4==rarg?subRangeCmd:arg4,
1961  &arg5==rarg?subRangeCmd:arg5,&arg6==rarg?subRangeCmd:arg6,
1962  &arg7==rarg?subRangeCmd:arg7,&arg8==rarg?subRangeCmd:arg8) ;
1963  chi2List.add(*chi2Comp) ;
1964  }
1965  chi2 = new RooAddition(baseName.c_str(),"chi^2",chi2List,kTRUE) ;
1966  }
1968 
1969 
1970  return chi2 ;
1971 }
1972 
1973 
1974 
1975 
1976 ////////////////////////////////////////////////////////////////////////////////
1977 /// Argument-list version of RooAbsPdf::createChi2()
1978 
1980 {
1981  // Select the pdf-specific commands
1982  RooCmdConfig pc(Form("RooAbsPdf::createChi2(%s)",GetName())) ;
1983 
1984  pc.defineInt("integrate","Integrate",0,0) ;
1985  pc.defineObject("yvar","YVar",0,0) ;
1986 
1987  // Process and check varargs
1988  pc.process(cmdList) ;
1989  if (!pc.ok(kTRUE)) {
1990  return 0 ;
1991  }
1992 
1993  // Decode command line arguments
1994  Bool_t integrate = pc.getInt("integrate") ;
1995  RooRealVar* yvar = (RooRealVar*) pc.getObject("yvar") ;
1996 
1997  string name = Form("chi2_%s_%s",GetName(),data.GetName()) ;
1998 
1999  if (yvar) {
2000  return new RooXYChi2Var(name.c_str(),name.c_str(),*this,data,*yvar,integrate) ;
2001  } else {
2002  return new RooXYChi2Var(name.c_str(),name.c_str(),*this,data,integrate) ;
2003  }
2004 }
2005 
2006 
2007 
2008 
2009 ////////////////////////////////////////////////////////////////////////////////
2010 /// Print value of p.d.f, also print normalization integral that was last used, if any
2011 
2012 void RooAbsPdf::printValue(ostream& os) const
2013 {
2014  // silent warning messages coming when evaluating a RooAddPdf without a normalization set
2016 
2017  getVal() ;
2018 
2019  if (_norm) {
2020  os << evaluate() << "/" << _norm->getVal() ;
2021  } else {
2022  os << evaluate() ;
2023  }
2024 }
2025 
2026 
2027 
2028 ////////////////////////////////////////////////////////////////////////////////
2029 /// Print multi line detailed information of this RooAbsPdf
2030 
2031 void RooAbsPdf::printMultiline(ostream& os, Int_t contents, Bool_t verbose, TString indent) const
2032 {
2034  os << indent << "--- RooAbsPdf ---" << endl;
2035  os << indent << "Cached value = " << _value << endl ;
2036  if (_norm) {
2037  os << indent << " Normalization integral: " << endl ;
2038  auto moreIndent = std::string(indent.Data()) + " " ;
2039  _norm->printStream(os,kName|kAddress|kTitle|kValue|kArgs,kSingleLine,moreIndent.c_str()) ;
2040  }
2041 }
2042 
2043 
2044 
2045 ////////////////////////////////////////////////////////////////////////////////
2046 /// Return a binned generator context
2047 
2049 {
2050  return new RooBinnedGenContext(*this,vars,0,0,verbose) ;
2051 }
2052 
2053 
2054 ////////////////////////////////////////////////////////////////////////////////
2055 /// Interface function to create a generator context from a p.d.f. This default
2056 /// implementation returns a 'standard' context that works for any p.d.f
2057 
2059  const RooArgSet* auxProto, Bool_t verbose) const
2060 {
2061  return new RooGenContext(*this,vars,prototype,auxProto,verbose) ;
2062 }
2063 
2064 
2065 ////////////////////////////////////////////////////////////////////////////////
2066 
2067 RooAbsGenContext* RooAbsPdf::autoGenContext(const RooArgSet &vars, const RooDataSet* prototype, const RooArgSet* auxProto,
2068  Bool_t verbose, Bool_t autoBinned, const char* binnedTag) const
2069 {
2070  if (prototype || (auxProto && auxProto->getSize()>0)) {
2071  return genContext(vars,prototype,auxProto,verbose);
2072  }
2073 
2074  RooAbsGenContext *context(0) ;
2075  if ( (autoBinned && isBinnedDistribution(vars)) || ( binnedTag && strlen(binnedTag) && (getAttribute(binnedTag)||string(binnedTag)=="*"))) {
2076  context = binnedGenContext(vars,verbose) ;
2077  } else {
2078  context= genContext(vars,0,0,verbose);
2079  }
2080  return context ;
2081 }
2082 
2083 
2084 
2085 ////////////////////////////////////////////////////////////////////////////////
2086 /// Generate a new dataset containing the specified variables with events sampled from our distribution.
2087 /// Generate the specified number of events or expectedEvents() if not specified.
2088 /// \param[in] whatVars Choose variables in which to generate events. Variables not listed here will remain
2089 /// constant and not be used for event generation.
2090 /// \param[in] argxx Optional RooCmdArg() to change behaviour of generate().
2091 /// \return RooDataSet *, owned by caller.
2092 ///
2093 /// Any variables of this PDF that are not in whatVars will use their
2094 /// current values and be treated as fixed parameters. Returns zero
2095 /// in case of an error.
2096 ///
2097 /// <table>
2098 /// <tr><th> Type of CmdArg <th> Effect on generate
2099 /// <tr><td> `Name(const char* name)` <td> Name of the output dataset
2100 /// <tr><td> `Verbose(Bool_t flag)` <td> Print informational messages during event generation
2101 /// <tr><td> `NumEvent(int nevt)` <td> Generate specified number of events
2102 /// <tr><td> `Extended()` <td> If no number of events to be generated is given,
2103 /// use expected number of events from extended likelihood term.
2104 /// This evidently only works for extended PDFs.
2105 /// <tr><td> `GenBinned(const char* tag)` <td> Use binned generation for all component pdfs that have 'setAttribute(tag)' set
2106 /// <tr><td> `AutoBinned(Bool_t flag)` <td> Automatically deploy binned generation for binned distributions (e.g. RooHistPdf, sums and products of
2107 /// RooHistPdfs etc)
2108 /// \note Datasets that are generated in binned mode are returned as weighted unbinned datasets. This means that
2109 /// for each bin, there will be one event in the dataset with a weight corresponding to the (possibly randomised) bin content.
2110 ///
2111 ///
2112 /// <tr><td> `AllBinned()` <td> As above, but for all components.
2113 /// \note The notion of components is only meaningful for simultaneous PDFs
2114 /// as binned generation is always executed at the top-level node for a regular
2115 /// PDF, so for those it only mattes that the top-level node is tagged.
2116 ///
2117 /// <tr><td> ProtoData(const RooDataSet& data, Bool_t randOrder)
2118 /// <td> Use specified dataset as prototype dataset. If randOrder in ProtoData() is set to true,
2119 /// the order of the events in the dataset will be read in a random order if the requested
2120 /// number of events to be generated does not match the number of events in the prototype dataset.
2121 /// \note If ProtoData() is used, the specified existing dataset as a prototype: the new dataset will contain
2122 /// the same number of events as the prototype (unless otherwise specified), and any prototype variables not in
2123 /// whatVars will be copied into the new dataset for each generated event and also used to set our PDF parameters.
2124 /// The user can specify a number of events to generate that will override the default. The result is a
2125 /// copy of the prototype dataset with only variables in whatVars randomized. Variables in whatVars that
2126 /// are not in the prototype will be added as new columns to the generated dataset.
2127 ///
2128 /// </table>
2129 ///
2130 /// #### Accessing the underlying event generator
2131 /// Depending on the fit model (if it is difficult to sample), it may be necessary to change generator settings.
2132 /// For the default generator (RooFoamGenerator), the number of samples or cells could be increased by e.g. using
2133 /// myPdf->specialGeneratorConfig()->getConfigSection("RooFoamGenerator").setRealValue("nSample",1e4);
2134 ///
2135 /// The foam generator e.g. has the following config options:
2136 /// - nCell[123N]D
2137 /// - nSample
2138 /// - chatLevel
2139 /// \see rf902_numgenconfig.C
2140 
2141 RooDataSet *RooAbsPdf::generate(const RooArgSet& whatVars, const RooCmdArg& arg1,const RooCmdArg& arg2,
2142  const RooCmdArg& arg3,const RooCmdArg& arg4, const RooCmdArg& arg5,const RooCmdArg& arg6)
2143 {
2144  // Select the pdf-specific commands
2145  RooCmdConfig pc(Form("RooAbsPdf::generate(%s)",GetName())) ;
2146  pc.defineObject("proto","PrototypeData",0,0) ;
2147  pc.defineString("dsetName","Name",0,"") ;
2148  pc.defineInt("randProto","PrototypeData",0,0) ;
2149  pc.defineInt("resampleProto","PrototypeData",1,0) ;
2150  pc.defineInt("verbose","Verbose",0,0) ;
2151  pc.defineInt("extended","Extended",0,0) ;
2152  pc.defineInt("nEvents","NumEvents",0,0) ;
2153  pc.defineInt("autoBinned","AutoBinned",0,1) ;
2154  pc.defineInt("expectedData","ExpectedData",0,0) ;
2155  pc.defineDouble("nEventsD","NumEventsD",0,-1.) ;
2156  pc.defineString("binnedTag","GenBinned",0,"") ;
2157  pc.defineMutex("GenBinned","ProtoData") ;
2158  pc.defineMutex("Extended", "NumEvents");
2159 
2160  // Process and check varargs
2161  pc.process(arg1,arg2,arg3,arg4,arg5,arg6) ;
2162  if (!pc.ok(kTRUE)) {
2163  return 0 ;
2164  }
2165 
2166  // Decode command line arguments
2167  RooDataSet* protoData = static_cast<RooDataSet*>(pc.getObject("proto",0)) ;
2168  const char* dsetName = pc.getString("dsetName") ;
2169  Bool_t verbose = pc.getInt("verbose") ;
2170  Bool_t randProto = pc.getInt("randProto") ;
2171  Bool_t resampleProto = pc.getInt("resampleProto") ;
2172  Bool_t extended = pc.getInt("extended") ;
2173  Bool_t autoBinned = pc.getInt("autoBinned") ;
2174  const char* binnedTag = pc.getString("binnedTag") ;
2175  Int_t nEventsI = pc.getInt("nEvents") ;
2176  Double_t nEventsD = pc.getInt("nEventsD") ;
2177  //Bool_t verbose = pc.getInt("verbose") ;
2178  Bool_t expectedData = pc.getInt("expectedData") ;
2179 
2180  Double_t nEvents = (nEventsD>0) ? nEventsD : Double_t(nEventsI);
2181 
2182  // Force binned mode for expected data mode
2183  if (expectedData) {
2184  binnedTag="*" ;
2185  }
2186 
2187  if (extended) {
2188  if (nEvents == 0) nEvents = expectedEvents(&whatVars);
2189  } else if (nEvents==0) {
2190  cxcoutI(Generation) << "No number of events specified , number of events generated is "
2191  << GetName() << "::expectedEvents() = " << expectedEvents(&whatVars)<< endl ;
2192  }
2193 
2194  if (extended && protoData && !randProto) {
2195  cxcoutI(Generation) << "WARNING Using generator option Extended() (Poisson distribution of #events) together "
2196  << "with a prototype dataset implies incomplete sampling or oversampling of proto data. "
2197  << "Set randomize flag in ProtoData() option to randomize prototype dataset order and thus "
2198  << "to randomize the set of over/undersampled prototype events for each generation cycle." << endl ;
2199  }
2200 
2201 
2202  // Forward to appropriate implementation
2203  RooDataSet* data ;
2204  if (protoData) {
2205  data = generate(whatVars,*protoData,Int_t(nEvents),verbose,randProto,resampleProto) ;
2206  } else {
2207  data = generate(whatVars,nEvents,verbose,autoBinned,binnedTag,expectedData, extended) ;
2208  }
2209 
2210  // Rename dataset to given name if supplied
2211  if (dsetName && strlen(dsetName)>0) {
2212  data->SetName(dsetName) ;
2213  }
2214 
2215  return data ;
2216 }
2217 
2218 
2219 
2220 
2221 
2222 
2223 ////////////////////////////////////////////////////////////////////////////////
2224 /// \note This method does not perform any generation. To generate according to generations specification call RooAbsPdf::generate(RooAbsPdf::GenSpec&) const
2225 ///
2226 /// Details copied from RooAbsPdf::generate():
2227 /// --------------------------------------------
2228 /// \copydetails RooAbsPdf::generate(const RooArgSet&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&)
2229 
2231  const RooCmdArg& arg1,const RooCmdArg& arg2,
2232  const RooCmdArg& arg3,const RooCmdArg& arg4,
2233  const RooCmdArg& arg5,const RooCmdArg& arg6)
2234 {
2235 
2236  // Select the pdf-specific commands
2237  RooCmdConfig pc(Form("RooAbsPdf::generate(%s)",GetName())) ;
2238  pc.defineObject("proto","PrototypeData",0,0) ;
2239  pc.defineString("dsetName","Name",0,"") ;
2240  pc.defineInt("randProto","PrototypeData",0,0) ;
2241  pc.defineInt("resampleProto","PrototypeData",1,0) ;
2242  pc.defineInt("verbose","Verbose",0,0) ;
2243  pc.defineInt("extended","Extended",0,0) ;
2244  pc.defineInt("nEvents","NumEvents",0,0) ;
2245  pc.defineInt("autoBinned","AutoBinned",0,1) ;
2246  pc.defineString("binnedTag","GenBinned",0,"") ;
2247  pc.defineMutex("GenBinned","ProtoData") ;
2248 
2249 
2250  // Process and check varargs
2251  pc.process(arg1,arg2,arg3,arg4,arg5,arg6) ;
2252  if (!pc.ok(kTRUE)) {
2253  return 0 ;
2254  }
2255 
2256  // Decode command line arguments
2257  RooDataSet* protoData = static_cast<RooDataSet*>(pc.getObject("proto",0)) ;
2258  const char* dsetName = pc.getString("dsetName") ;
2259  Int_t nEvents = pc.getInt("nEvents") ;
2260  Bool_t verbose = pc.getInt("verbose") ;
2261  Bool_t randProto = pc.getInt("randProto") ;
2262  Bool_t resampleProto = pc.getInt("resampleProto") ;
2263  Bool_t extended = pc.getInt("extended") ;
2264  Bool_t autoBinned = pc.getInt("autoBinned") ;
2265  const char* binnedTag = pc.getString("binnedTag") ;
2266 
2267  RooAbsGenContext* cx = autoGenContext(whatVars,protoData,0,verbose,autoBinned,binnedTag) ;
2268 
2269  return new GenSpec(cx,whatVars,protoData,nEvents,extended,randProto,resampleProto,dsetName) ;
2270 }
2271 
2272 
2273 ////////////////////////////////////////////////////////////////////////////////
2274 /// If many identical generation requests
2275 /// are needed, e.g. in toy MC studies, it is more efficient to use the prepareMultiGen()/generate()
2276 /// combination than calling the standard generate() multiple times as
2277 /// initialization overhead is only incurred once.
2278 
2280 {
2281  //Int_t nEvt = spec._extended ? RooRandom::randomGenerator()->Poisson(spec._nGen) : spec._nGen ;
2282  //Int_t nEvt = spec._extended ? RooRandom::randomGenerator()->Poisson(spec._nGen==0?expectedEvents(spec._whatVars):spec._nGen) : spec._nGen ;
2283  //Int_t nEvt = spec._nGen == 0 ? RooRandom::randomGenerator()->Poisson(expectedEvents(spec._whatVars)) : spec._nGen;
2284 
2285  Double_t nEvt = spec._nGen == 0 ? expectedEvents(spec._whatVars) : spec._nGen;
2286 
2287  RooDataSet* ret = generate(*spec._genContext,spec._whatVars,spec._protoData, nEvt,kFALSE,spec._randProto,spec._resampleProto,
2288  spec._init,spec._extended) ;
2289  spec._init = kTRUE ;
2290  return ret ;
2291 }
2292 
2293 
2294 
2295 
2296 
2297 ////////////////////////////////////////////////////////////////////////////////
2298 /// Generate a new dataset containing the specified variables with
2299 /// events sampled from our distribution.
2300 ///
2301 /// \param[in] whatVars Generate a dataset with the variables (and categories) in this set.
2302 /// Any variables of this PDF that are not in `whatVars` will use their
2303 /// current values and be treated as fixed parameters.
2304 /// \param[in] nEvents Generate the specified number of events or else try to use
2305 /// expectedEvents() if nEvents <= 0 (default).
2306 /// \param[in] verbose Show which generator strategies are being used.
2307 /// \param[in] autoBinned If original distribution is binned, return bin centers and randomise weights
2308 /// instead of generating single events.
2309 /// \param[in] binnedTag
2310 /// \param[in] expectedData Call setExpectedData on the genContext.
2311 /// \param[in] extended Randomise number of events generated according to Poisson(nEvents). Only useful
2312 /// if PDF is extended.
2313 /// \return New dataset. Returns zero in case of an error. The caller takes ownership of the returned
2314 /// dataset.
2315 
2316 RooDataSet *RooAbsPdf::generate(const RooArgSet &whatVars, Double_t nEvents, Bool_t verbose, Bool_t autoBinned, const char* binnedTag, Bool_t expectedData, Bool_t extended) const
2317 {
2318  if (nEvents==0 && extendMode()==CanNotBeExtended) {
2319  return new RooDataSet("emptyData","emptyData",whatVars) ;
2320  }
2321 
2322  // Request for binned generation
2323  RooAbsGenContext *context = autoGenContext(whatVars,0,0,verbose,autoBinned,binnedTag) ;
2324  if (expectedData) {
2325  context->setExpectedData(kTRUE) ;
2326  }
2327 
2328  RooDataSet *generated = 0;
2329  if(0 != context && context->isValid()) {
2330  generated= context->generate(nEvents, kFALSE, extended);
2331  }
2332  else {
2333  coutE(Generation) << "RooAbsPdf::generate(" << GetName() << ") cannot create a valid context" << endl;
2334  }
2335  if(0 != context) delete context;
2336  return generated;
2337 }
2338 
2339 
2340 
2341 
2342 ////////////////////////////////////////////////////////////////////////////////
2343 /// Internal method
2344 
2345 RooDataSet *RooAbsPdf::generate(RooAbsGenContext& context, const RooArgSet &whatVars, const RooDataSet *prototype,
2346  Double_t nEvents, Bool_t /*verbose*/, Bool_t randProtoOrder, Bool_t resampleProto,
2347  Bool_t skipInit, Bool_t extended) const
2348 {
2349  if (nEvents==0 && (prototype==0 || prototype->numEntries()==0)) {
2350  return new RooDataSet("emptyData","emptyData",whatVars) ;
2351  }
2352 
2353  RooDataSet *generated = 0;
2354 
2355  // Resampling implies reshuffling in the implementation
2356  if (resampleProto) {
2357  randProtoOrder=kTRUE ;
2358  }
2359 
2360  if (randProtoOrder && prototype && prototype->numEntries()!=nEvents) {
2361  coutI(Generation) << "RooAbsPdf::generate (Re)randomizing event order in prototype dataset (Nevt=" << nEvents << ")" << endl ;
2362  Int_t* newOrder = randomizeProtoOrder(prototype->numEntries(),Int_t(nEvents),resampleProto) ;
2363  context.setProtoDataOrder(newOrder) ;
2364  delete[] newOrder ;
2365  }
2366 
2367  if(context.isValid()) {
2368  generated= context.generate(nEvents,skipInit,extended);
2369  }
2370  else {
2371  coutE(Generation) << "RooAbsPdf::generate(" << GetName() << ") do not have a valid generator context" << endl;
2372  }
2373  return generated;
2374 }
2375 
2376 
2377 
2378 
2379 ////////////////////////////////////////////////////////////////////////////////
2380 /// Generate a new dataset using a prototype dataset as a model,
2381 /// with values of the variables in `whatVars` sampled from our distribution.
2382 ///
2383 /// \param[in] whatVars Generate for these variables.
2384 /// \param[in] prototype Use this dataset
2385 /// as a prototype: the new dataset will contain the same number of
2386 /// events as the prototype (by default), and any prototype variables not in
2387 /// whatVars will be copied into the new dataset for each generated
2388 /// event and also used to set our PDF parameters. The user can specify a
2389 /// number of events to generate that will override the default. The result is a
2390 /// copy of the prototype dataset with only variables in whatVars
2391 /// randomized. Variables in whatVars that are not in the prototype
2392 /// will be added as new columns to the generated dataset.
2393 /// \param[in] nEvents Number of events to generate. Defaults to 0, which means number
2394 /// of event in prototype dataset.
2395 /// \param[in] verbose Show which generator strategies are being used.
2396 /// \param[in] randProtoOrder Randomise order of retrieval of events from proto dataset.
2397 /// \param[in] resampleProto Resample from the proto dataset.
2398 /// \return The new dataset. Returns zero in case of an error. The caller takes ownership of the
2399 /// returned dataset.
2400 
2401 RooDataSet *RooAbsPdf::generate(const RooArgSet &whatVars, const RooDataSet& prototype,
2402  Int_t nEvents, Bool_t verbose, Bool_t randProtoOrder, Bool_t resampleProto) const
2403 {
2404  RooAbsGenContext *context= genContext(whatVars,&prototype,0,verbose);
2405  if (context) {
2406  RooDataSet* data = generate(*context,whatVars,&prototype,nEvents,verbose,randProtoOrder,resampleProto) ;
2407  delete context ;
2408  return data ;
2409  } else {
2410  coutE(Generation) << "RooAbsPdf::generate(" << GetName() << ") ERROR creating generator context" << endl ;
2411  return 0 ;
2412  }
2413 }
2414 
2415 
2416 
2417 ////////////////////////////////////////////////////////////////////////////////
2418 /// Return lookup table with randomized access order for prototype events,
2419 /// given nProto prototype data events and nGen events that will actually
2420 /// be accessed
2421 
2423 {
2424  // Make unsorted linked list of indeces
2425  RooLinkedList l ;
2426  Int_t i ;
2427  for (i=0 ; i<nProto ; i++) {
2428  l.Add(new RooInt(i)) ;
2429  }
2430 
2431  // Make output list
2432  Int_t* lut = new Int_t[nProto] ;
2433 
2434  // Randomly samply input list into output list
2435  if (!resampleProto) {
2436  // In this mode, randomization is a strict reshuffle of the order
2437  for (i=0 ; i<nProto ; i++) {
2438  Int_t iran = RooRandom::integer(nProto-i) ;
2439  RooInt* sample = (RooInt*) l.At(iran) ;
2440  lut[i] = *sample ;
2441  l.Remove(sample) ;
2442  delete sample ;
2443  }
2444  } else {
2445  // In this mode, we resample, i.e. events can be used more than once
2446  for (i=0 ; i<nProto ; i++) {
2447  lut[i] = RooRandom::integer(nProto);
2448  }
2449  }
2450 
2451 
2452  return lut ;
2453 }
2454 
2455 
2456 
2457 ////////////////////////////////////////////////////////////////////////////////
2458 /// Load generatedVars with the subset of directVars that we can generate events for,
2459 /// and return a code that specifies the generator algorithm we will use. A code of
2460 /// zero indicates that we cannot generate any of the directVars (in this case, nothing
2461 /// should be added to generatedVars). Any non-zero codes will be passed to our generateEvent()
2462 /// implementation, but otherwise its value is arbitrary. The default implemetation of
2463 /// this method returns zero. Subclasses will usually implement this method using the
2464 /// matchArgs() methods to advertise the algorithms they provide.
2465 
2466 Int_t RooAbsPdf::getGenerator(const RooArgSet &/*directVars*/, RooArgSet &/*generatedVars*/, Bool_t /*staticInitOK*/) const
2467 {
2468  return 0 ;
2469 }
2470 
2471 
2472 
2473 ////////////////////////////////////////////////////////////////////////////////
2474 /// Interface for one-time initialization to setup the generator for the specified code.
2475 
2477 {
2478 }
2479 
2480 
2481 
2482 ////////////////////////////////////////////////////////////////////////////////
2483 /// Interface for generation of an event using the algorithm
2484 /// corresponding to the specified code. The meaning of each code is
2485 /// defined by the getGenerator() implementation. The default
2486 /// implementation does nothing.
2487 
2489 {
2490 }
2491 
2492 
2493 
2494 ////////////////////////////////////////////////////////////////////////////////
2495 /// Check if given observable can be safely generated using the
2496 /// pdfs internal generator mechanism (if that existsP). Observables
2497 /// on which a PDF depends via more than route are not safe
2498 /// for use with internal generators because they introduce
2499 /// correlations not known to the internal generator
2500 
2502 {
2503  // Arg must be direct server of self
2504  if (!findServer(arg.GetName())) return kFALSE ;
2505 
2506  // There must be no other dependency routes
2507  for (const auto server : _serverList) {
2508  if(server == &arg) continue;
2509  if(server->dependsOn(arg)) {
2510  return kFALSE ;
2511  }
2512  }
2513 
2514  return kTRUE ;
2515 }
2516 
2517 
2518 ////////////////////////////////////////////////////////////////////////////////
2519 /// Generate a new dataset containing the specified variables with events sampled from our distribution.
2520 /// \param[in] whatVars Choose variables in which to generate events. Variables not listed here will remain
2521 /// constant and not be used for event generation
2522 /// \param[in] arg1 Optional RooCmdArg to change behaviour of generateBinned()
2523 /// \return RooDataHist *, to be managed by caller.
2524 ///
2525 /// Generate the specified number of events or expectedEvents() if not specified.
2526 ///
2527 /// Any variables of this PDF that are not in whatVars will use their
2528 /// current values and be treated as fixed parameters. Returns zero
2529 /// in case of an error. The caller takes ownership of the returned
2530 /// dataset.
2531 ///
2532 /// The following named arguments are supported
2533 /// | Type of CmdArg | Effect on generation
2534 /// |-------------------------|-----------------------
2535 /// | `Name(const char* name)` | Name of the output dataset
2536 /// | `Verbose(Bool_t flag)` | Print informational messages during event generation
2537 /// | `NumEvent(int nevt)` | Generate specified number of events
2538 /// | `Extended()` | The actual number of events generated will be sampled from a Poisson distribution with mu=nevt.
2539 /// This can be *much* faster for peaked PDFs, but the number of events is not exactly what was requested.
2540 /// | `ExpectedData()` | Return a binned dataset _without_ statistical fluctuations (also aliased as Asimov())
2541 ///
2542 
2543 RooDataHist *RooAbsPdf::generateBinned(const RooArgSet& whatVars, const RooCmdArg& arg1,const RooCmdArg& arg2,
2544  const RooCmdArg& arg3,const RooCmdArg& arg4, const RooCmdArg& arg5,const RooCmdArg& arg6) const
2545 {
2546 
2547  // Select the pdf-specific commands
2548  RooCmdConfig pc(Form("RooAbsPdf::generate(%s)",GetName())) ;
2549  pc.defineString("dsetName","Name",0,"") ;
2550  pc.defineInt("verbose","Verbose",0,0) ;
2551  pc.defineInt("extended","Extended",0,0) ;
2552  pc.defineInt("nEvents","NumEvents",0,0) ;
2553  pc.defineDouble("nEventsD","NumEventsD",0,-1.) ;
2554  pc.defineInt("expectedData","ExpectedData",0,0) ;
2555 
2556  // Process and check varargs
2557  pc.process(arg1,arg2,arg3,arg4,arg5,arg6) ;
2558  if (!pc.ok(kTRUE)) {
2559  return 0 ;
2560  }
2561 
2562  // Decode command line arguments
2563  Double_t nEvents = pc.getDouble("nEventsD") ;
2564  if (nEvents<0) {
2565  nEvents = pc.getInt("nEvents") ;
2566  }
2567  //Bool_t verbose = pc.getInt("verbose") ;
2568  Bool_t extended = pc.getInt("extended") ;
2569  Bool_t expectedData = pc.getInt("expectedData") ;
2570  const char* dsetName = pc.getString("dsetName") ;
2571 
2572  if (extended) {
2573  //nEvents = (nEvents==0?Int_t(expectedEvents(&whatVars)+0.5):nEvents) ;
2574  nEvents = (nEvents==0 ? expectedEvents(&whatVars) :nEvents) ;
2575  cxcoutI(Generation) << " Extended mode active, number of events generated (" << nEvents << ") is Poisson fluctuation on "
2576  << GetName() << "::expectedEvents() = " << nEvents << endl ;
2577  // If Poisson fluctuation results in zero events, stop here
2578  if (nEvents==0) {
2579  return 0 ;
2580  }
2581  } else if (nEvents==0) {
2582  cxcoutI(Generation) << "No number of events specified , number of events generated is "
2583  << GetName() << "::expectedEvents() = " << expectedEvents(&whatVars)<< endl ;
2584  }
2585 
2586  // Forward to appropriate implementation
2587  RooDataHist* data = generateBinned(whatVars,nEvents,expectedData,extended) ;
2588 
2589  // Rename dataset to given name if supplied
2590  if (dsetName && strlen(dsetName)>0) {
2591  data->SetName(dsetName) ;
2592  }
2593 
2594  return data ;
2595 }
2596 
2597 
2598 
2599 
2600 ////////////////////////////////////////////////////////////////////////////////
2601 /// Generate a new dataset containing the specified variables with
2602 /// events sampled from our distribution.
2603 ///
2604 /// \param[in] whatVars Variables that values should be generated for.
2605 /// \param[in] nEvents How many events to generate. If `nEvents <=0`, use the value returned by expectedEvents() as target.
2606 /// \param[in] expectedData If set to true (false by default), the returned histogram returns the 'expected'
2607 /// data sample, i.e. no statistical fluctuations are present.
2608 /// \param[in] extended For each bin, generate Poisson(x, mu) events, where `mu` is chosen such that *on average*,
2609 /// one would obtain `nEvents` events. This means that the true number of events will fluctuate around the desired value,
2610 /// but the generation happens a lot faster.
2611 /// Especially if the PDF is sharply peaked, the multinomial event generation necessary to generate *exactly* `nEvents` events can
2612 /// be very slow.
2613 ///
2614 /// The binning used for generation of events is the currently set binning for the variables.
2615 /// It can e.g. be changed using
2616 /// ```
2617 /// x.setBins(15);
2618 /// x.setRange(-5., 5.);
2619 /// pdf.generateBinned(RooArgSet(x), 1000);
2620 /// ```
2621 ///
2622 /// Any variables of this PDF that are not in `whatVars` will use their
2623 /// current values and be treated as fixed parameters.
2624 /// \return RooDataHist* owned by the caller. Returns `nullptr` in case of an error.
2625 RooDataHist *RooAbsPdf::generateBinned(const RooArgSet &whatVars, Double_t nEvents, Bool_t expectedData, Bool_t extended) const
2626 {
2627  // Create empty RooDataHist
2628  RooDataHist* hist = new RooDataHist("genData","genData",whatVars) ;
2629 
2630  // Scale to number of events and introduce Poisson fluctuations
2631  if (nEvents<=0) {
2632  if (!canBeExtended()) {
2633  coutE(InputArguments) << "RooAbsPdf::generateBinned(" << GetName() << ") ERROR: No event count provided and p.d.f does not provide expected number of events" << endl ;
2634  delete hist ;
2635  return 0 ;
2636  } else {
2637 
2638  // Don't round in expectedData or extended mode
2639  if (expectedData || extended) {
2640  nEvents = expectedEvents(&whatVars) ;
2641  } else {
2642  nEvents = std::round(expectedEvents(&whatVars));
2643  }
2644  }
2645  }
2646 
2647  // Sample p.d.f. distribution
2648  fillDataHist(hist,&whatVars,1,kTRUE) ;
2649 
2650  vector<int> histOut(hist->numEntries()) ;
2651  Double_t histMax(-1) ;
2652  Int_t histOutSum(0) ;
2653  for (int i=0 ; i<hist->numEntries() ; i++) {
2654  hist->get(i) ;
2655  if (expectedData) {
2656 
2657  // Expected data, multiply p.d.f by nEvents
2658  Double_t w=hist->weight()*nEvents ;
2659  hist->set(i, w, sqrt(w));
2660 
2661  } else if (extended) {
2662 
2663  // Extended mode, set contents to Poisson(pdf*nEvents)
2664  Double_t w = RooRandom::randomGenerator()->Poisson(hist->weight()*nEvents) ;
2665  hist->set(w,sqrt(w)) ;
2666 
2667  } else {
2668 
2669  // Regular mode, fill array of weights with Poisson(pdf*nEvents), but to not fill
2670  // histogram yet.
2671  if (hist->weight()>histMax) {
2672  histMax = hist->weight() ;
2673  }
2674  histOut[i] = RooRandom::randomGenerator()->Poisson(hist->weight()*nEvents) ;
2675  histOutSum += histOut[i] ;
2676  }
2677  }
2678 
2679 
2680  if (!expectedData && !extended) {
2681 
2682  // Second pass for regular mode - Trim/Extend dataset to exact number of entries
2683 
2684  // Calculate difference between what is generated so far and what is requested
2685  Int_t nEvtExtra = abs(Int_t(nEvents)-histOutSum) ;
2686  Int_t wgt = (histOutSum>nEvents) ? -1 : 1 ;
2687 
2688  // Perform simple binned accept/reject procedure to get to exact event count
2689  std::size_t counter = 0;
2690  bool havePrintedInfo = false;
2691  while(nEvtExtra>0) {
2692 
2693  Int_t ibinRand = RooRandom::randomGenerator()->Integer(hist->numEntries()) ;
2694  hist->get(ibinRand) ;
2695  Double_t ranY = RooRandom::randomGenerator()->Uniform(histMax) ;
2696 
2697  if (ranY<hist->weight()) {
2698  if (wgt==1) {
2699  histOut[ibinRand]++ ;
2700  } else {
2701  // If weight is negative, prior bin content must be at least 1
2702  if (histOut[ibinRand]>0) {
2703  histOut[ibinRand]-- ;
2704  } else {
2705  continue ;
2706  }
2707  }
2708  nEvtExtra-- ;
2709  }
2710 
2711  if ((counter++ > 10*nEvents || nEvents > 1.E7) && !havePrintedInfo) {
2712  havePrintedInfo = true;
2713  coutP(Generation) << "RooAbsPdf::generateBinned(" << GetName() << ") Performing costly accept/reject sampling. If this takes too long, use "
2714  << "extended mode to speed up the process." << std::endl;
2715  }
2716  }
2717 
2718  // Transfer working array to histogram
2719  for (int i=0 ; i<hist->numEntries() ; i++) {
2720  hist->get(i) ;
2721  hist->set(histOut[i],sqrt(1.0*histOut[i])) ;
2722  }
2723 
2724  } else if (expectedData) {
2725 
2726  // Second pass for expectedData mode -- Normalize to exact number of requested events
2727  // Minor difference may be present in first round due to difference between
2728  // bin average and bin integral in sampling bins
2729  Double_t corr = nEvents/hist->sumEntries() ;
2730  for (int i=0 ; i<hist->numEntries() ; i++) {
2731  hist->get(i) ;
2732  hist->set(hist->weight()*corr,sqrt(hist->weight()*corr)) ;
2733  }
2734 
2735  }
2736 
2737  return hist;
2738 }
2739 
2740 
2741 
2742 ////////////////////////////////////////////////////////////////////////////////
2743 /// Special generator interface for generation of 'global observables' -- for RooStats tools
2744 
2746 {
2747  return generate(whatVars,nEvents) ;
2748 }
2749 
2750 namespace {
2751 void removeRangeOverlap(std::vector<std::pair<double, double>>& ranges) {
2752  //Sort from left to right
2753  std::sort(ranges.begin(), ranges.end());
2754 
2755  for (auto it = ranges.begin(); it != ranges.end(); ++it) {
2756  double& startL = it->first;
2757  double& endL = it->second;
2758 
2759  for (auto innerIt = it+1; innerIt != ranges.end(); ++innerIt) {
2760  const double startR = innerIt->first;
2761  const double endR = innerIt->second;
2762 
2763  if (startL <= startR && startR <= endL) {
2764  //Overlapping ranges, extend left one
2765  endL = std::max(endL, endR);
2766  *innerIt = make_pair(0., 0.);
2767  }
2768  }
2769  }
2770 
2771  auto newEnd = std::remove_if(ranges.begin(), ranges.end(),
2772  [](const std::pair<double,double>& input){
2773  return input.first == input.second;
2774  });
2775  ranges.erase(newEnd, ranges.end());
2776 }
2777 }
2778 
2779 
2780 ////////////////////////////////////////////////////////////////////////////////
2781 /// Plot (project) PDF on specified frame.
2782 /// - If a PDF is plotted in an empty frame, it
2783 /// will show a unit-normalized curve in the frame variable. When projecting a multi-
2784 /// dimensional PDF onto the frame axis, hidden parameters are taken are taken at
2785 /// their current value.
2786 /// - If a PDF is plotted in a frame in which a dataset has already been plotted, it will
2787 /// show a projection integrated over all variables that were present in the shown
2788 /// dataset (except for the one on the x-axis). The normalization of the curve will
2789 /// be adjusted to the event count of the plotted dataset. An informational message
2790 /// will be printed for each projection step that is performed.
2791 /// - If a PDF is plotted in a frame showing a dataset *after* a fit, the above happens,
2792 /// but the PDF will be drawn and normalised only in the fit range. If this is not desired,
2793 /// plotting and normalisation range can be overridden using Range() and NormRange() as
2794 /// documented in the table below.
2795 ///
2796 /// This function takes the following named arguments (for more arguments, see also
2797 /// RooAbsReal::plotOn(RooPlot*,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,
2798 /// const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,
2799 /// const RooCmdArg&) const )
2800 ///
2801 ///
2802 /// <table>
2803 /// <tr><th> Type of argument <th> Controlling normalisation
2804 /// <tr><td> `NormRange(const char* name)` <td> Calculate curve normalization w.r.t. specified range[s].
2805 /// See the tutorial rf212_plottingInRanges_blinding.C
2806 /// \note Setting a Range() by default also sets a NormRange() on the same range, meaning that the
2807 /// PDF is plotted and normalised in the same range. Overriding this can be useful if the PDF was fit
2808 /// in limited range[s] such as side bands, `NormRange("sidebandLeft,sidebandRight")`, but the PDF
2809 /// should be drawn in the full range, `Range("")`.
2810 ///
2811 /// <tr><td> `Normalization(Double_t scale, ScaleType code)` <td> Adjust normalization by given scale factor.
2812 /// Interpretation of number depends on code:
2813 /// `RooAbsReal::Relative`: relative adjustment factor
2814 /// `RooAbsReal::NumEvent`: scale to match given number of events.
2815 ///
2816 /// <tr><th> Type of argument <th> Misc control
2817 /// <tr><td> `Name(const chat* name)` <td> Give curve specified name in frame. Useful if curve is to be referenced later
2818 /// <tr><td> `Asymmetry(const RooCategory& c)` <td> Show the asymmetry of the PDF in given two-state category
2819 /// \f$ \frac{F(+)-F(-)}{F(+)+F(-)} \f$ rather than the PDF projection. Category must have two
2820 /// states with indices -1 and +1 or three states with indeces -1,0 and +1.
2821 /// <tr><td> `ShiftToZero(Bool_t flag)` <td> Shift entire curve such that lowest visible point is at exactly zero.
2822 /// Mostly useful when plotting -log(L) or \f$ \chi^2 \f$ distributions
2823 /// <tr><td> `AddTo(const char* name, double_t wgtSelf, double_t wgtOther)` <td> Create a projection of this PDF onto the x-axis, but
2824 /// instead of plotting it directly, add it to an existing curve with given name (and relative weight factors).
2825 /// <tr><td> `Components(const char* names)` <td> When plotting sums of PDFs, plot only the named components (*e.g.* only
2826 /// the signal of a signal+background model).
2827 /// <tr><td> `Components(const RooArgSet& compSet)` <td> As above, but pass a RooArgSet of the components themselves.
2828 ///
2829 /// <tr><th> Type of argument <th> Projection control
2830 /// <tr><td> `Slice(const RooArgSet& set)` <td> Override default projection behaviour by omitting observables listed
2831 /// in set from the projection, i.e. by not integrating over these.
2832 /// Slicing is usually only sensible in discrete observables, by e.g. creating a slice
2833 /// of the PDF at the current value of the category observable.
2834 /// <tr><td> `Slice(RooCategory& cat, const char* label)` <td> Override default projection behaviour by omitting the specified category
2835 /// observable from the projection, i.e., by not integrating over all states of this category.
2836 /// The slice is positioned at the given label value. Multiple Slice() commands can be given to specify slices
2837 /// in multiple observables, e.g.
2838 /// ```{.cpp}
2839 /// pdf.plotOn(frame, Slice(tagCategory, "2tag"), Slice(jetCategory, "3jet"));
2840 /// ```
2841 /// <tr><td> `Project(const RooArgSet& set)` <td> Override default projection behaviour by projecting
2842 /// over observables given in set, completely ignoring the default projection behavior. Advanced use only.
2843 /// <tr><td> `ProjWData(const RooAbsData& d)` <td> Override default projection _technique_ (integration). For observables
2844 /// present in given dataset projection of PDF is achieved by constructing an average over all observable
2845 /// values in given set. Consult RooFit plotting tutorial for further explanation of meaning & use of this technique
2846 /// <tr><td> `ProjWData(const RooArgSet& s, const RooAbsData& d)` <td> As above but only consider subset 's' of
2847 /// observables in dataset 'd' for projection through data averaging
2848 /// <tr><td> `ProjectionRange(const char* rn)` <td> When projecting the PDF onto the plot axis, it is usually integrated
2849 /// over the full range of the invisible variables. The ProjectionRange overrides this.
2850 /// This is useful if the PDF was fitted in a limited range in y, but it is now projected onto x. If
2851 /// `ProjectionRange("<name of fit range>")` is passed, the projection is normalised correctly.
2852 ///
2853 /// <tr><th> Type of argument <th> Plotting control
2854 /// <tr><td> `LineStyle(Int_t style)` <td> Select line style by ROOT line style code, default is solid
2855 /// <tr><td> `LineColor(Int_t color)` <td> Select line color by ROOT color code, default is blue
2856 /// <tr><td> `LineWidth(Int_t width)` <td> Select line with in pixels, default is 3
2857 /// <tr><td> `FillStyle(Int_t style)` <td> Select fill style, default is not filled. If a filled style is selected,
2858 /// also use VLines() to add vertical downward lines at end of curve to ensure proper closure
2859 /// <tr><td> `FillColor(Int_t color)` <td> Select fill color by ROOT color code
2860 /// <tr><td> `Range(const char* name)` <td> Only draw curve in range defined by given name. Multiple comma-separated ranges can be given.
2861 /// An empty string "" or `nullptr` means to use the default range of the variable.
2862 /// <tr><td> `Range(double lo, double hi)` <td> Only draw curve in specified range
2863 /// <tr><td> `VLines()` <td> Add vertical lines to y=0 at end points of curve
2864 /// <tr><td> `Precision(Double_t eps)` <td> Control precision of drawn curve w.r.t to scale of plot, default is 1e-3. A higher precision will
2865 /// result in more and more densely spaced curve points. A negative precision value will disable
2866 /// adaptive point spacing and restrict sampling to the grid point of points defined by the binning
2867 /// of the plotted observable (recommended for expensive functions such as profile likelihoods)
2868 /// <tr><td> `Invisible(Bool_t flag)` <td> Add curve to frame, but do not display. Useful in combination AddTo()
2869 /// <tr><td> `VisualizeError(const RooFitResult& fitres, Double_t Z=1, Bool_t linearMethod=kTRUE)`
2870 /// <td> Visualize the uncertainty on the parameters, as given in fitres, at 'Z' sigma.
2871 ///
2872 /// <tr><td> `VisualizeError(const RooFitResult& fitres, const RooArgSet& param, Double_t Z=1, Bool_t linearMethod=kTRUE)`
2873 /// <td> Visualize the uncertainty on the subset of parameters 'param', as given in fitres, at 'Z' sigma.
2874 /// </table>
2875 
2877 {
2878 
2879  // Pre-processing if p.d.f. contains a fit range and there is no command specifying one,
2880  // add a fit range as default range
2881  RooCmdArg* plotRange(0) ;
2882  RooCmdArg* normRange2(0);
2883  if (getStringAttribute("fitrange") && !cmdList.FindObject("Range") &&
2884  !cmdList.FindObject("RangeWithName")) {
2885  plotRange = (RooCmdArg*) RooFit::Range(getStringAttribute("fitrange")).Clone() ;
2886  cmdList.Add(plotRange) ;
2887  }
2888 
2889  if (getStringAttribute("fitrange") && !cmdList.FindObject("NormRange")) {
2890  normRange2 = (RooCmdArg*) RooFit::NormRange(getStringAttribute("fitrange")).Clone() ;
2891  cmdList.Add(normRange2) ;
2892  }
2893 
2894  if (plotRange || normRange2) {
2895  coutI(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") p.d.f was fitted in a subrange and no explicit "
2896  << (plotRange?"Range()":"") << ((plotRange&&normRange2)?" and ":"")
2897  << (normRange2?"NormRange()":"") << " was specified. Plotting / normalising in fit range. To override, do one of the following"
2898  << "\n\t- Clear the automatic fit range attribute: <pdf>.setStringAttribute(\"fitrange\", nullptr);"
2899  << "\n\t- Explicitly specify the plotting range: Range(\"<rangeName>\")."
2900  << "\n\t- Explicitly specify where to compute the normalisation: NormRange(\"<rangeName>\")."
2901  << "\n\tThe default (full) range can be denoted with Range(\"\") / NormRange(\"\")."<< endl ;
2902  }
2903 
2904  // Sanity checks
2905  if (plotSanityChecks(frame)) return frame ;
2906 
2907  // Select the pdf-specific commands
2908  RooCmdConfig pc(Form("RooAbsPdf::plotOn(%s)",GetName())) ;
2909  pc.defineDouble("scaleFactor","Normalization",0,1.0) ;
2910  pc.defineInt("scaleType","Normalization",0,Relative) ;
2911  pc.defineObject("compSet","SelectCompSet",0) ;
2912  pc.defineString("compSpec","SelectCompSpec",0) ;
2913  pc.defineObject("asymCat","Asymmetry",0) ;
2914  pc.defineDouble("rangeLo","Range",0,-999.) ;
2915  pc.defineDouble("rangeHi","Range",1,-999.) ;
2916  pc.defineString("rangeName","RangeWithName",0,"") ;
2917  pc.defineString("normRangeName","NormRange",0,"") ;
2918  pc.defineInt("rangeAdjustNorm","Range",0,0) ;
2919  pc.defineInt("rangeWNAdjustNorm","RangeWithName",0,0) ;
2920  pc.defineMutex("SelectCompSet","SelectCompSpec") ;
2921  pc.defineMutex("Range","RangeWithName") ;
2922  pc.allowUndefined() ; // unknowns may be handled by RooAbsReal
2923 
2924  // Process and check varargs
2925  pc.process(cmdList) ;
2926  if (!pc.ok(kTRUE)) {
2927  return frame ;
2928  }
2929 
2930  // Decode command line arguments
2931  ScaleType stype = (ScaleType) pc.getInt("scaleType") ;
2932  Double_t scaleFactor = pc.getDouble("scaleFactor") ;
2933  const RooAbsCategoryLValue* asymCat = (const RooAbsCategoryLValue*) pc.getObject("asymCat") ;
2934  const char* compSpec = pc.getString("compSpec") ;
2935  const RooArgSet* compSet = (const RooArgSet*) pc.getObject("compSet") ;
2936  Bool_t haveCompSel = ( (compSpec && strlen(compSpec)>0) || compSet) ;
2937 
2938  // Suffix for curve name
2939  std::string nameSuffix ;
2940  if (compSpec && strlen(compSpec)>0) {
2941  nameSuffix.append("_Comp[") ;
2942  nameSuffix.append(compSpec) ;
2943  nameSuffix.append("]") ;
2944  } else if (compSet) {
2945  nameSuffix.append("_Comp[") ;
2946  nameSuffix.append(compSet->contentsString().c_str()) ;
2947  nameSuffix.append("]") ;
2948  }
2949 
2950  // Remove PDF-only commands from command list
2951  pc.stripCmdList(cmdList,"SelectCompSet,SelectCompSpec") ;
2952 
2953  // Adjust normalization, if so requested
2954  if (asymCat) {
2955  RooCmdArg cnsuffix("CurveNameSuffix",0,0,0,0,nameSuffix.c_str(),0,0,0) ;
2956  cmdList.Add(&cnsuffix);
2957  return RooAbsReal::plotOn(frame,cmdList) ;
2958  }
2959 
2960  // More sanity checks
2961  Double_t nExpected(1) ;
2962  if (stype==RelativeExpected) {
2963  if (!canBeExtended()) {
2964  coutE(Plotting) << "RooAbsPdf::plotOn(" << GetName()
2965  << "): ERROR the 'Expected' scale option can only be used on extendable PDFs" << endl ;
2966  return frame ;
2967  }
2968  nExpected = expectedEvents(frame->getNormVars()) ;
2969  }
2970 
2971  if (stype != Raw) {
2972 
2973  if (frame->getFitRangeNEvt() && stype==Relative) {
2974 
2975  Bool_t hasCustomRange(kFALSE), adjustNorm(kFALSE) ;
2976 
2977  std::vector<pair<Double_t,Double_t> > rangeLim;
2978 
2979  // Retrieve plot range to be able to adjust normalization to data
2980  if (pc.hasProcessed("Range")) {
2981 
2982  Double_t rangeLo = pc.getDouble("rangeLo") ;
2983  Double_t rangeHi = pc.getDouble("rangeHi") ;
2984  rangeLim.push_back(make_pair(rangeLo,rangeHi)) ;
2985  adjustNorm = pc.getInt("rangeAdjustNorm") ;
2986  hasCustomRange = kTRUE ;
2987 
2988  coutI(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") only plotting range ["
2989  << rangeLo << "," << rangeHi << "]" ;
2990  if (!pc.hasProcessed("NormRange")) {
2991  ccoutI(Plotting) << ", curve is normalized to data in " << (adjustNorm?"given":"full") << " range" << endl ;
2992  } else {
2993  ccoutI(Plotting) << endl ;
2994  }
2995 
2996  nameSuffix.append(Form("_Range[%f_%f]",rangeLo,rangeHi)) ;
2997 
2998  } else if (pc.hasProcessed("RangeWithName")) {
2999 
3000  for (const std::string& rangeNameToken : RooHelpers::tokenise(pc.getString("rangeName", "", false), ",", /*returnEmptyToken=*/true)) {
3001  const char* thisRangeName = rangeNameToken.empty() ? nullptr : rangeNameToken.c_str();
3002  if (thisRangeName && !frame->getPlotVar()->hasRange(thisRangeName)) {
3003  coutE(Plotting) << "Range '" << rangeNameToken << "' not defined for variable '"
3004  << frame->getPlotVar()->GetName() << "'. Ignoring ..." << std::endl;
3005  continue;
3006  }
3007  rangeLim.push_back(frame->getPlotVar()->getRange(thisRangeName));
3008  }
3009  adjustNorm = pc.getInt("rangeWNAdjustNorm") ;
3010  hasCustomRange = kTRUE ;
3011 
3012  coutI(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") only plotting range '" << pc.getString("rangeName", "", false) << "'" ;
3013  if (!pc.hasProcessed("NormRange")) {
3014  ccoutI(Plotting) << ", curve is normalized to data in " << (adjustNorm?"given":"full") << " range" << endl ;
3015  } else {
3016  ccoutI(Plotting) << endl ;
3017  }
3018 
3019  nameSuffix.append(Form("_Range[%s]",pc.getString("rangeName"))) ;
3020  }
3021  // Specification of a normalization range override those in a regular range
3022  if (pc.hasProcessed("NormRange")) {
3023  rangeLim.clear();
3024  for (const auto& rangeNameToken : RooHelpers::tokenise(pc.getString("normRangeName", "", false), ",", /*returnEmptyToken=*/true)) {
3025  const char* thisRangeName = rangeNameToken.empty() ? nullptr : rangeNameToken.c_str();
3026  if (thisRangeName && !frame->getPlotVar()->hasRange(thisRangeName)) {
3027  coutE(Plotting) << "Range '" << rangeNameToken << "' not defined for variable '"
3028  << frame->getPlotVar()->GetName() << "'. Ignoring ..." << std::endl;
3029  continue;
3030  }
3031  rangeLim.push_back(frame->getPlotVar()->getRange(thisRangeName));
3032  }
3033  adjustNorm = kTRUE ;
3034  hasCustomRange = kTRUE ;
3035  coutI(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") p.d.f. curve is normalized using explicit choice of ranges '" << pc.getString("normRangeName", "", false) << "'" << endl ;
3036 
3037  nameSuffix.append(Form("_NormRange[%s]",pc.getString("rangeName"))) ;
3038 
3039  }
3040 
3041  if (hasCustomRange && adjustNorm) {
3042  // If overlapping ranges were given, remove them now
3043  const std::size_t oldSize = rangeLim.size();
3044  removeRangeOverlap(rangeLim);
3045 
3046  if (oldSize != rangeLim.size() && !pc.hasProcessed("NormRange")) {
3047  // User gave overlapping ranges. This leads to double-counting events and integrals, and must
3048  // therefore be avoided. If a NormRange has been given, the overlap is alreay gone.
3049  // It's safe to plot even with overlap now.
3050  coutE(Plotting) << "Requested plot/integration ranges overlap. For correct plotting, new ranges "
3051  "will be defined." << std::endl;
3052  auto plotVar = dynamic_cast<RooRealVar*>(frame->getPlotVar());
3053  assert(plotVar);
3054  std::string rangesNoOverlap;
3055  for (auto it = rangeLim.begin(); it != rangeLim.end(); ++it) {
3056  std::stringstream rangeName;
3057  rangeName << "Remove_overlap_range_" << it - rangeLim.begin();
3058  plotVar->setRange(rangeName.str().c_str(), it->first, it->second);
3059  if (!rangesNoOverlap.empty())
3060  rangesNoOverlap += ",";
3061  rangesNoOverlap += rangeName.str();
3062  }
3063 
3064  auto rangeArg = static_cast<RooCmdArg*>(cmdList.FindObject("RangeWithName"));
3065  if (rangeArg)
3066  rangeArg->setString(0, rangesNoOverlap.c_str());
3067  else {
3068  plotRange = new RooCmdArg(RooFit::Range(rangesNoOverlap.c_str()));
3069  cmdList.Add(plotRange);
3070  }
3071  }
3072 
3073  Double_t rangeNevt(0) ;
3074  for (const auto& riter : rangeLim) {
3075  Double_t nevt= frame->getFitRangeNEvt(riter.first, riter.second);
3076  rangeNevt += nevt ;
3077  }
3078 
3079  scaleFactor *= rangeNevt/nExpected ;
3080 
3081  } else {
3082  scaleFactor *= frame->getFitRangeNEvt()/nExpected ;
3083  }
3084  } else if (stype==RelativeExpected) {
3085  scaleFactor *= nExpected ;
3086  } else if (stype==NumEvent) {
3087  scaleFactor /= nExpected ;
3088  }
3089  scaleFactor *= frame->getFitRangeBinW() ;
3090  }
3091  frame->updateNormVars(*frame->getPlotVar()) ;
3092 
3093  // Append overriding scale factor command at end of original command list
3094  RooCmdArg tmp = RooFit::Normalization(scaleFactor,Raw) ;
3095  tmp.setInt(1,1) ; // Flag this normalization command as created for internal use (so that VisualizeError can strip it)
3096  cmdList.Add(&tmp) ;
3097 
3098  // Was a component selected requested
3099  if (haveCompSel) {
3100 
3101  // Get complete set of tree branch nodes
3102  RooArgSet branchNodeSet ;
3103  branchNodeServerList(&branchNodeSet) ;
3104 
3105  // Discard any non-RooAbsReal nodes
3106  for (const auto arg : branchNodeSet) {
3107  if (!dynamic_cast<RooAbsReal*>(arg)) {
3108  branchNodeSet.remove(*arg) ;
3109  }
3110  }
3111 
3112  // Obtain direct selection
3113  RooArgSet* dirSelNodes ;
3114  if (compSet) {
3115  dirSelNodes = (RooArgSet*) branchNodeSet.selectCommon(*compSet) ;
3116  } else {
3117  dirSelNodes = (RooArgSet*) branchNodeSet.selectByName(compSpec) ;
3118  }
3119  if (dirSelNodes->getSize()>0) {
3120  coutI(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") directly selected PDF components: " << *dirSelNodes << endl ;
3121 
3122  // Do indirect selection and activate both
3123  plotOnCompSelect(dirSelNodes) ;
3124  } else {
3125  if (compSet) {
3126  coutE(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") ERROR: component selection set " << *compSet << " does not match any components of p.d.f." << endl ;
3127  } else {
3128  coutE(Plotting) << "RooAbsPdf::plotOn(" << GetName() << ") ERROR: component selection expression '" << compSpec << "' does not select any components of p.d.f." << endl ;
3129  }
3130  return 0 ;
3131  }
3132 
3133  delete dirSelNodes ;
3134  }
3135 
3136 
3137  RooCmdArg cnsuffix("CurveNameSuffix",0,0,0,0,nameSuffix.c_str(),0,0,0) ;
3138  cmdList.Add(&cnsuffix);
3139 
3140  RooPlot* ret = RooAbsReal::plotOn(frame,cmdList) ;
3141 
3142  // Restore selection status ;
3143  if (haveCompSel) plotOnCompSelect(0) ;
3144 
3145  if (plotRange) {
3146  delete plotRange ;
3147  }
3148  if (normRange2) {
3149  delete normRange2 ;
3150  }
3151 
3152  return ret ;
3153 }
3154 
3155 
3156 //_____________________________________________________________________________
3157 /// Plot oneself on 'frame'. In addition to features detailed in RooAbsReal::plotOn(),
3158 /// the scale factor for a PDF can be interpreted in three different ways. The interpretation
3159 /// is controlled by ScaleType
3160 /// ```
3161 /// Relative - Scale factor is applied on top of PDF normalization scale factor
3162 /// NumEvent - Scale factor is interpreted as a number of events. The surface area
3163 /// under the PDF curve will match that of a histogram containing the specified
3164 /// number of event
3165 /// Raw - Scale factor is applied to the raw (projected) probability density.
3166 /// Not too useful, option provided for completeness.
3167 /// ```
3168 // coverity[PASS_BY_VALUE]
3170 {
3171 
3172  // Sanity checks
3173  if (plotSanityChecks(frame)) return frame ;
3174 
3175  // More sanity checks
3176  Double_t nExpected(1) ;
3177  if (o.stype==RelativeExpected) {
3178  if (!canBeExtended()) {
3179  coutE(Plotting) << "RooAbsPdf::plotOn(" << GetName()
3180  << "): ERROR the 'Expected' scale option can only be used on extendable PDFs" << endl ;
3181  return frame ;
3182  }
3183  nExpected = expectedEvents(frame->getNormVars()) ;
3184  }
3185 
3186  // Adjust normalization, if so requested
3187  if (o.stype != Raw) {
3188 
3189  if (frame->getFitRangeNEvt() && o.stype==Relative) {
3190  // If non-default plotting range is specified, adjust number of events in fit range
3191  o.scaleFactor *= frame->getFitRangeNEvt()/nExpected ;
3192  } else if (o.stype==RelativeExpected) {
3193  o.scaleFactor *= nExpected ;
3194  } else if (o.stype==NumEvent) {
3195  o.scaleFactor /= nExpected ;
3196  }
3197  o.scaleFactor *= frame->getFitRangeBinW() ;
3198  }
3199  frame->updateNormVars(*frame->getPlotVar()) ;
3200 
3201  return RooAbsReal::plotOn(frame,o) ;
3202 }
3203 
3204 
3205 
3206 
3207 ////////////////////////////////////////////////////////////////////////////////
3208 /// The following named arguments are supported
3209 /// <table>
3210 /// <tr><th> Type of CmdArg <th> Effect on parameter box
3211 /// <tr><td> `Parameters(const RooArgSet& param)` <td> Only the specified subset of parameters will be shown. By default all non-constant parameters are shown.
3212 /// <tr><td> `ShowConstants(Bool_t flag)` <td> Also display constant parameters
3213 /// <tr><td> `Format(const char* optStr)` <td> \deprecated Classing parameter formatting options, provided for backward compatibility
3214 ///
3215 /// <tr><td> `Format(const char* what,...)` <td> Parameter formatting options.
3216 /// | Parameter | Format
3217 /// | ---------------------- | --------------------------
3218 /// | `const char* what` | Controls what is shown. "N" adds name, "E" adds error, "A" shows asymmetric error, "U" shows unit, "H" hides the value
3219 /// | `FixedPrecision(int n)`| Controls precision, set fixed number of digits
3220 /// | `AutoPrecision(int n)` | Controls precision. Number of shown digits is calculated from error + n specified additional digits (1 is sensible default)
3221 /// <tr><td> `Label(const chat* label)` <td> Add label to parameter box. Use `\n` for multi-line labels.
3222 /// <tr><td> `Layout(Double_t xmin, Double_t xmax, Double_t ymax)` <td> Specify relative position of left/right side of box and top of box.
3223 /// Coordinates are given as position on the pad between 0 and 1.
3224 /// The lower end of the box is calculated automatically from the number of lines in the box.
3225 /// </table>
3226 ///
3227 ///
3228 /// Example use:
3229 /// ```
3230 /// pdf.paramOn(frame, Label("fit result"), Format("NEU",AutoPrecision(1)) ) ;
3231 /// ```
3232 ///
3233 
3234 RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdArg& arg2,
3235  const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5,
3236  const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
3237 {
3238  // Stuff all arguments in a list
3239  RooLinkedList cmdList;
3240  cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
3241  cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
3242  cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
3243  cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
3244 
3245  // Select the pdf-specific commands
3246  RooCmdConfig pc(Form("RooAbsPdf::paramOn(%s)",GetName())) ;
3247  pc.defineString("label","Label",0,"") ;
3248  pc.defineDouble("xmin","Layout",0,0.65) ;
3249  pc.defineDouble("xmax","Layout",1,0.9) ;
3250  pc.defineInt("ymaxi","Layout",0,Int_t(0.9*10000)) ;
3251  pc.defineInt("showc","ShowConstants",0,0) ;
3252  pc.defineObject("params","Parameters",0,0) ;
3253  pc.defineString("formatStr","Format",0,"NELU") ;
3254  pc.defineInt("sigDigit","Format",0,2) ;
3255  pc.defineInt("dummy","FormatArgs",0,0) ;
3256  pc.defineMutex("Format","FormatArgs") ;
3257 
3258  // Process and check varargs
3259  pc.process(cmdList) ;
3260  if (!pc.ok(kTRUE)) {
3261  return frame ;
3262  }
3263 
3264  const char* label = pc.getString("label") ;
3265  Double_t xmin = pc.getDouble("xmin") ;
3266  Double_t xmax = pc.getDouble("xmax") ;
3267  Double_t ymax = pc.getInt("ymaxi") / 10000. ;
3268  Int_t showc = pc.getInt("showc") ;
3269 
3270 
3271  const char* formatStr = pc.getString("formatStr") ;
3272  Int_t sigDigit = pc.getInt("sigDigit") ;
3273 
3274  // Decode command line arguments
3275  RooArgSet* params = static_cast<RooArgSet*>(pc.getObject("params")) ;
3276  if (!params) {
3277  std::unique_ptr<RooArgSet> paramsPtr{getParameters(frame->getNormVars())} ;
3278  if (pc.hasProcessed("FormatArgs")) {
3279  const RooCmdArg* formatCmd = static_cast<RooCmdArg*>(cmdList.FindObject("FormatArgs")) ;
3280  paramOn(frame,*paramsPtr,showc,label,0,0,xmin,xmax,ymax,formatCmd) ;
3281  } else {
3282  paramOn(frame,*paramsPtr,showc,label,sigDigit,formatStr,xmin,xmax,ymax) ;
3283  }
3284  } else {
3285  std::unique_ptr<RooArgSet> pdfParams{getParameters(frame->getNormVars())} ;
3286  std::unique_ptr<RooArgSet> selParams{static_cast<RooArgSet*>(pdfParams->selectCommon(*params))} ;
3287  if (pc.hasProcessed("FormatArgs")) {
3288  const RooCmdArg* formatCmd = static_cast<RooCmdArg*>(cmdList.FindObject("FormatArgs")) ;
3289  paramOn(frame,*selParams,showc,label,0,0,xmin,xmax,ymax,formatCmd) ;
3290  } else {
3291  paramOn(frame,*selParams,showc,label,sigDigit,formatStr,xmin,xmax,ymax) ;
3292  }
3293  }
3294 
3295  return frame ;
3296 }
3297 
3298 
3299 
3300 
3301 ////////////////////////////////////////////////////////////////////////////////
3302 /// \deprecated Obsolete, provided for backward compatibility. Don't use.
3303 
3304 RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooAbsData* data, const char *label,
3305  Int_t sigDigits, Option_t *options, Double_t xmin,
3307 {
3308  std::unique_ptr<RooArgSet> params{getParameters(data)} ;
3309  TString opts(options) ;
3310  paramOn(frame,*params,opts.Contains("c"),label,sigDigits,options,xmin,xmax,ymax) ;
3311  return frame ;
3312 }
3313 
3314 
3315 
3316 ////////////////////////////////////////////////////////////////////////////////
3317 /// Add a text box with the current parameter values and their errors to the frame.
3318 /// Observables of this PDF appearing in the 'data' dataset will be omitted.
3319 ///
3320 /// An optional label will be inserted if passed. Multi-line labels can be generated
3321 /// by adding `\n` to the label string. Use 'sigDigits'
3322 /// to modify the default number of significant digits printed. The 'xmin,xmax,ymax'
3323 /// values specify the initial relative position of the text box in the plot frame.
3324 
3325 RooPlot* RooAbsPdf::paramOn(RooPlot* frame, const RooArgSet& params, Bool_t showConstants, const char *label,
3326  Int_t sigDigits, Option_t *options, Double_t xmin,
3327  Double_t xmax ,Double_t ymax, const RooCmdArg* formatCmd)
3328 {
3329 
3330  // parse the options
3331  TString opts = options;
3332  opts.ToLower();
3333  Bool_t showLabel= (label != 0 && strlen(label) > 0);
3334 
3335  // calculate the box's size, adjusting for constant parameters
3336 
3337  Double_t ymin(ymax), dy(0.06);
3338  for (const auto param : params) {
3339  auto var = static_cast<RooRealVar*>(param);
3340  if(showConstants || !var->isConstant()) ymin-= dy;
3341  }
3342 
3343  std::string labelString = label;
3344  unsigned int numLines = std::count(labelString.begin(), labelString.end(), '\n') + 1;
3345  if (showLabel) ymin -= numLines * dy;
3346 
3347  // create the box and set its options
3348  TPaveText *box= new TPaveText(xmin,ymax,xmax,ymin,"BRNDC");
3349  if(!box) return 0;
3350  box->SetName(Form("%s_paramBox",GetName())) ;
3351  box->SetFillColor(0);
3352  box->SetBorderSize(0);
3353  box->SetTextAlign(12);
3354  box->SetTextSize(0.04F);
3355  box->SetFillStyle(0);
3356 
3357  for (const auto param : params) {
3358  auto var = static_cast<const RooRealVar*>(param);
3359  if(var->isConstant() && !showConstants) continue;
3360 
3361  TString *formatted= options ? var->format(sigDigits, options) : var->format(*formatCmd) ;
3362  box->AddText(formatted->Data());
3363  delete formatted;
3364  }
3365 
3366  // add the optional label if specified
3367  if (showLabel) {
3368  for (const auto& line : RooHelpers::tokenise(label, "\n")) {
3369  box->AddText(line.c_str());
3370  }
3371  }
3372 
3373  // Add box to frame
3374  frame->addObject(box) ;
3375 
3376  return frame ;
3377 }
3378 
3379 
3380 
3381 
3382 ////////////////////////////////////////////////////////////////////////////////
3383 /// Return expected number of events from this p.d.f for use in extended
3384 /// likelihood calculations. This default implementation returns zero
3385 
3387 {
3388  return 0 ;
3389 }
3390 
3391 
3392 
3393 ////////////////////////////////////////////////////////////////////////////////
3394 /// Change global level of verbosity for p.d.f. evaluations
3395 
3397 {
3398  _verboseEval = stat ;
3399 }
3400 
3401 
3402 
3403 ////////////////////////////////////////////////////////////////////////////////
3404 /// Return global level of verbosity for p.d.f. evaluations
3405 
3407 {
3408  return _verboseEval ;
3409 }
3410 
3411 
3412 
3413 ////////////////////////////////////////////////////////////////////////////////
3414 /// Destructor of normalization cache element. If this element
3415 /// provides the 'current' normalization stored in RooAbsPdf::_norm
3416 /// zero _norm pointer here before object pointed to is deleted here
3417 
3419 {
3420  // Zero _norm pointer in RooAbsPdf if it is points to our cache payload
3421  if (_owner) {
3422  RooAbsPdf* pdfOwner = static_cast<RooAbsPdf*>(_owner) ;
3423  if (pdfOwner->_norm == _norm) {
3424  pdfOwner->_norm = 0 ;
3425  }
3426  }
3427 
3428  delete _norm ;
3429 }
3430 
3431 
3432 
3433 ////////////////////////////////////////////////////////////////////////////////
3434 /// Return a p.d.f that represent a projection of this p.d.f integrated over given observables
3435 
3437 {
3438  // Construct name for new object
3439  std::string name(GetName()) ;
3440  name.append("_Proj[") ;
3441  if (iset.getSize()>0) {
3442  bool first = true;
3443  for(auto const& arg : iset) {
3444  if (first) {
3445  first = false ;
3446  } else {
3447  name.append(",") ;
3448  }
3449  name.append(arg->GetName()) ;
3450  }
3451  }
3452  name.append("]") ;
3453 
3454  // Return projected p.d.f.
3455  return new RooProjectedPdf(name.c_str(),name.c_str(),*this,iset) ;
3456 }
3457 
3458 
3459 
3460 ////////////////////////////////////////////////////////////////////////////////
3461 /// Create a cumulative distribution function of this p.d.f in terms
3462 /// of the observables listed in iset. If no nset argument is given
3463 /// the c.d.f normalization is constructed over the integrated
3464 /// observables, so that its maximum value is precisely 1. It is also
3465 /// possible to choose a different normalization for
3466 /// multi-dimensional p.d.f.s: eg. for a pdf f(x,y,z) one can
3467 /// construct a partial cdf c(x,y) that only when integrated itself
3468 /// over z results in a maximum value of 1. To construct such a cdf pass
3469 /// z as argument to the optional nset argument
3470 
3472 {
3473  return createCdf(iset,RooFit::SupNormSet(nset)) ;
3474 }
3475 
3476 
3477 
3478 ////////////////////////////////////////////////////////////////////////////////
3479 /// Create an object that represents the integral of the function over one or more observables listed in `iset`.
3480 /// The actual integration calculation is only performed when the return object is evaluated. The name
3481 /// of the integral object is automatically constructed from the name of the input function, the variables
3482 /// it integrates and the range integrates over
3483 ///
3484 /// The following named arguments are accepted
3485 /// | Type of CmdArg | Effect on CDF
3486 /// | ---------------------|-------------------
3487 /// | SupNormSet(const RooArgSet&) | Observables over which should be normalized _in addition_ to the integration observables
3488 /// | ScanNumCdf() | Apply scanning technique if cdf integral involves numeric integration [ default ]
3489 /// | ScanAllCdf() | Always apply scanning technique
3490 /// | ScanNoCdf() | Never apply scanning technique
3491 /// | 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
3492 
3493 RooAbsReal* RooAbsPdf::createCdf(const RooArgSet& iset, const RooCmdArg& arg1, const RooCmdArg& arg2,
3494  const RooCmdArg& arg3, const RooCmdArg& arg4, const RooCmdArg& arg5,
3495  const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
3496 {
3497  // Define configuration for this method
3498  RooCmdConfig pc(Form("RooAbsReal::createCdf(%s)",GetName())) ;
3499  pc.defineObject("supNormSet","SupNormSet",0,0) ;
3500  pc.defineInt("numScanBins","ScanParameters",0,1000) ;
3501  pc.defineInt("intOrder","ScanParameters",1,2) ;
3502  pc.defineInt("doScanNum","ScanNumCdf",0,1) ;
3503  pc.defineInt("doScanAll","ScanAllCdf",0,0) ;
3504  pc.defineInt("doScanNon","ScanNoCdf",0,0) ;
3505  pc.defineMutex("ScanNumCdf","ScanAllCdf","ScanNoCdf") ;
3506 
3507  // Process & check varargs
3508  pc.process(arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
3509  if (!pc.ok(kTRUE)) {
3510  return 0 ;
3511  }
3512 
3513  // Extract values from named arguments
3514  const RooArgSet* snset = static_cast<const RooArgSet*>(pc.getObject("supNormSet",0)) ;
3515  RooArgSet nset ;
3516  if (snset) {
3517  nset.add(*snset) ;
3518  }
3519  Int_t numScanBins = pc.getInt("numScanBins") ;
3520  Int_t intOrder = pc.getInt("intOrder") ;
3521  Int_t doScanNum = pc.getInt("doScanNum") ;
3522  Int_t doScanAll = pc.getInt("doScanAll") ;
3523  Int_t doScanNon = pc.getInt("doScanNon") ;
3524 
3525  // If scanning technique is not requested make integral-based cdf and return
3526  if (doScanNon) {
3527  return createIntRI(iset,nset) ;
3528  }
3529  if (doScanAll) {
3530  return createScanCdf(iset,nset,numScanBins,intOrder) ;
3531  }
3532  if (doScanNum) {
3533  std::unique_ptr<RooRealIntegral> tmp{static_cast<RooRealIntegral*>(createIntegral(iset))} ;
3534  Int_t isNum= (tmp->numIntRealVars().getSize()>0) ;
3535 
3536  if (isNum) {
3537  coutI(NumIntegration) << "RooAbsPdf::createCdf(" << GetName() << ") integration over observable(s) " << iset << " involves numeric integration," << endl
3538  << " constructing cdf though numeric integration of sampled pdf in " << numScanBins << " bins and applying order "
3539  << intOrder << " interpolation on integrated histogram." << endl
3540  << " To override this choice of technique use argument ScanNone(), to change scan parameters use ScanParameters(nbins,order) argument" << endl ;
3541  }
3542 
3543  return isNum ? createScanCdf(iset,nset,numScanBins,intOrder) : createIntRI(iset,nset) ;
3544  }
3545  return 0 ;
3546 }
3547 
3548 RooAbsReal* RooAbsPdf::createScanCdf(const RooArgSet& iset, const RooArgSet& nset, Int_t numScanBins, Int_t intOrder)
3549 {
3550  string name = string(GetName()) + "_NUMCDF_" + integralNameSuffix(iset,&nset).Data() ;
3551  RooRealVar* ivar = (RooRealVar*) iset.first() ;
3552  ivar->setBins(numScanBins,"numcdf") ;
3553  RooNumCdf* ret = new RooNumCdf(name.c_str(),name.c_str(),*this,*ivar,"numcdf") ;
3554  ret->setInterpolationOrder(intOrder) ;
3555  return ret ;
3556 }
3557 
3558 
3559 
3560 
3561 ////////////////////////////////////////////////////////////////////////////////
3562 /// This helper function finds and collects all constraints terms of all component p.d.f.s
3563 /// and returns a RooArgSet with all those terms.
3564 
3565 RooArgSet* RooAbsPdf::getAllConstraints(const RooArgSet& observables, RooArgSet& constrainedParams, Bool_t stripDisconnected) const
3566 {
3567  RooArgSet* ret = new RooArgSet("AllConstraints") ;
3568 
3569  std::unique_ptr<RooArgSet> comps(getComponents());
3570  for (const auto arg : *comps) {
3571  auto pdf = dynamic_cast<const RooAbsPdf*>(arg) ;
3572  if (pdf && !ret->find(pdf->GetName())) {
3573  std::unique_ptr<RooArgSet> compRet(pdf->getConstraints(observables,constrainedParams,stripDisconnected));
3574  if (compRet) {
3575  ret->add(*compRet,kFALSE) ;
3576  }
3577  }
3578  }
3579 
3580  return ret ;
3581 }
3582 
3583 
3584 ////////////////////////////////////////////////////////////////////////////////
3585 /// Returns the default numeric MC generator configuration for all RooAbsReals
3586 
3588 {
3589  return &RooNumGenConfig::defaultConfig() ;
3590 }
3591 
3592 
3593 ////////////////////////////////////////////////////////////////////////////////
3594 /// Returns the specialized integrator configuration for _this_ RooAbsReal.
3595 /// If this object has no specialized configuration, a null pointer is returned
3596 
3598 {
3599  return _specGeneratorConfig ;
3600 }
3601 
3602 
3603 
3604 ////////////////////////////////////////////////////////////////////////////////
3605 /// Returns the specialized integrator configuration for _this_ RooAbsReal.
3606 /// If this object has no specialized configuration, a null pointer is returned,
3607 /// unless createOnTheFly is kTRUE in which case a clone of the default integrator
3608 /// configuration is created, installed as specialized configuration, and returned
3609 
3611 {
3612  if (!_specGeneratorConfig && createOnTheFly) {
3614  }
3615  return _specGeneratorConfig ;
3616 }
3617 
3618 
3619 
3620 ////////////////////////////////////////////////////////////////////////////////
3621 /// Return the numeric MC generator configuration used for this object. If
3622 /// a specialized configuration was associated with this object, that configuration
3623 /// is returned, otherwise the default configuration for all RooAbsReals is returned
3624 
3626 {
3627  const RooNumGenConfig* config = specialGeneratorConfig() ;
3628  if (config) return config ;
3629  return defaultGeneratorConfig() ;
3630 }
3631 
3632 
3633 
3634 ////////////////////////////////////////////////////////////////////////////////
3635 /// Set the given configuration as default numeric MC generator
3636 /// configuration for this object
3637 
3639 {
3640  if (_specGeneratorConfig) {
3641  delete _specGeneratorConfig ;
3642  }
3643  _specGeneratorConfig = new RooNumGenConfig(config) ;
3644 }
3645 
3646 
3647 
3648 ////////////////////////////////////////////////////////////////////////////////
3649 /// Remove the specialized numeric MC generator configuration associated
3650 /// with this object
3651 
3653 {
3654  if (_specGeneratorConfig) {
3655  delete _specGeneratorConfig ;
3656  }
3657  _specGeneratorConfig = 0 ;
3658 }
3659 
3660 
3661 
3662 ////////////////////////////////////////////////////////////////////////////////
3663 
3665 {
3666  delete _genContext ;
3667 }
3668 
3669 
3670 ////////////////////////////////////////////////////////////////////////////////
3671 
3672 RooAbsPdf::GenSpec::GenSpec(RooAbsGenContext* context, const RooArgSet& whatVars, RooDataSet* protoData, Int_t nGen,
3673  Bool_t extended, Bool_t randProto, Bool_t resampleProto, TString dsetName, Bool_t init) :
3674  _genContext(context), _whatVars(whatVars), _protoData(protoData), _nGen(nGen), _extended(extended),
3675  _randProto(randProto), _resampleProto(resampleProto), _dsetName(dsetName), _init(init)
3676 {
3677 }
3678 
3679 
3680 
3681 ////////////////////////////////////////////////////////////////////////////////
3682 
3683 void RooAbsPdf::setNormRange(const char* rangeName)
3684 {
3685  if (rangeName) {
3686  _normRange = rangeName ;
3687  } else {
3688  _normRange.Clear() ;
3689  }
3690 
3691  if (_norm) {
3692  _normMgr.sterilize() ;
3693  _norm = 0 ;
3694  }
3695 }
3696 
3697 
3698 ////////////////////////////////////////////////////////////////////////////////
3699 
3700 void RooAbsPdf::setNormRangeOverride(const char* rangeName)
3701 {
3702  if (rangeName) {
3703  _normRangeOverride = rangeName ;
3704  } else {
3706  }
3707 
3708  if (_norm) {
3709  _normMgr.sterilize() ;
3710  _norm = 0 ;
3711  }
3712 }
RooFormulaVar.h
RooAbsArg::Clone
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition: RooAbsArg.h:84
RooAbsReal::analyticalIntegral
virtual Double_t analyticalIntegral(Int_t code, const char *rangeName=0) const
Implements the actual analytical integral(s) advertised by getAnalyticalIntegral.
Definition: RooAbsReal.cxx:429
RooAbsRealLValue::getRange
std::pair< double, double > getRange(const char *name=0) const
Get low and high bound of the variable.
Definition: RooAbsRealLValue.h:93
RooAbsPdf::createScanCdf
RooAbsReal * createScanCdf(const RooArgSet &iset, const RooArgSet &nset, Int_t numScanBins, Int_t intOrder)
Definition: RooAbsPdf.cxx:3548
l
auto * l
Definition: textangle.C:4
RooAbsPdf::_normSet
RooArgSet * _normSet
Normalization integral (owned by _normMgr)
Definition: RooAbsPdf.h:322
RooCacheManager::setObj
Int_t setObj(const RooArgSet *nset, T *obj, const TNamed *isetRangeName=0)
Definition: RooCacheManager.h:49
m
auto * m
Definition: textangle.C:8
RooAbsPdf::chi2FitTo
virtual RooFitResult * chi2FitTo(RooDataHist &data, const RooCmdArg &arg1=RooCmdArg::none(), const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none(), const RooCmdArg &arg7=RooCmdArg::none(), const RooCmdArg &arg8=RooCmdArg::none())
Perform a fit to given histogram.
Definition: RooAbsReal.cxx:4391
RooBatchCompute.h
RooBinnedGenContext.h
RooAbsReal::evaluateSpan
virtual RooSpan< double > evaluateSpan(RooBatchCompute::RunContext &evalData, const RooArgSet *normSet) const
Evaluate this object for a batch/span of data points.
Definition: RooAbsReal.cxx:4898
RooAbsReal::NumEvent
@ NumEvent
Definition: RooAbsReal.h:266
RooAbsPdf::CacheElem
friend class CacheElem
Definition: RooAbsPdf.h:333
RooAbsArg::ADirty
@ ADirty
Definition: RooAbsArg.h:388
RooAbsPdf::_normRange
TString _normRange
MC generator configuration specific for this object.
Definition: RooAbsPdf.h:354
RooWorkspace.h
RooCmdArg
RooCmdArg is a named container for two doubles, two integers two object points and three string point...
Definition: RooCmdArg.h:27
RooAbsPdf::genContext
virtual RooAbsGenContext * genContext(const RooArgSet &vars, const RooDataSet *prototype=0, const RooArgSet *auxProto=0, Bool_t verbose=kFALSE) const
Interface function to create a generator context from a p.d.f.
Definition: RooAbsPdf.cxx:2058
first
Definition: first.py:1
RooHelpers.h
RooFit::Minimization
@ Minimization
Definition: RooGlobalFunc.h:60
ymax
float ymax
Definition: THbookFile.cxx:95
RooAbsArg::operMode
OperMode operMode() const
Query the operation mode of this node.
Definition: RooAbsArg.h:482
RooAbsPdf::generateSimGlobal
virtual RooDataSet * generateSimGlobal(const RooArgSet &whatVars, Int_t nEvents)
Special generator interface for generation of 'global observables' – for RooStats tools.
Definition: RooAbsPdf.cxx:2745
kTRUE
const Bool_t kTRUE
Definition: RtypesCore.h:100
RooCmdConfig.h
e
#define e(i)
Definition: RSha256.hxx:103
RooMinuit.h
RooAbsReal::setEvalErrorLoggingMode
static void setEvalErrorLoggingMode(ErrorLoggingMode m)
Set evaluation error logging mode.
Definition: RooAbsReal.cxx:4849
RooMsgService.h
RooAbsPdf::traceEvalPdf
Bool_t traceEvalPdf(Double_t value) const
Check that passed value is positive and not 'not-a-number'.
Definition: RooAbsPdf.cxx:431
ccoutD
#define ccoutD(a)
Definition: RooMsgService.h:37
RooCmdConfig::allowUndefined
void allowUndefined(Bool_t flag=kTRUE)
Definition: RooCmdConfig.h:39
RooAbsCollection::first
RooAbsArg * first() const
Definition: RooAbsCollection.h:191
RooPlot::updateNormVars
void updateNormVars(const RooArgSet &vars)
Install the given set of observables are reference normalization variables for this frame.
Definition: RooPlot.cxx:380
RooAbsPdf::calculateSumW2CorrectedCovMatrix
int calculateSumW2CorrectedCovMatrix(Minimizer &minimizer, RooAbsReal const &nll) const
Definition: RooAbsPdf.cxx:1287
Option_t
const char Option_t
Definition: RtypesCore.h:66
RooAbsPdf::autoGenContext
virtual RooAbsGenContext * autoGenContext(const RooArgSet &vars, const RooDataSet *prototype=0, const RooArgSet *auxProto=0, Bool_t verbose=kFALSE, Bool_t autoBinned=kTRUE, const char *binnedTag="") const
Definition: RooAbsPdf.cxx:2067
RooAbsReal::logEvalError
void logEvalError(const char *message, const char *serverValueString=0) const
Log evaluation error message.
Definition: RooAbsReal.cxx:3717
RooAbsData::isNonPoissonWeighted
virtual Bool_t isNonPoissonWeighted() const
Definition: RooAbsData.h:130
RooAbsData
RooAbsData is the common abstract base class for binned and unbinned datasets.
Definition: RooAbsData.h:49
RooDataHist::weight
double weight(std::size_t i) const
Return weight of i-th bin.
Definition: RooDataHist.h:98
RooNumIntConfig.h
RooAbsPdf::setNormRangeOverride
void setNormRangeOverride(const char *rangeName)
Definition: RooAbsPdf.cxx:3700
RooAbsPdf::generateEvent
virtual void generateEvent(Int_t code)
Interface for generation of an event using the algorithm corresponding to the specified code.
Definition: RooAbsPdf.cxx:2488
RooFit.h
TMath::QuietNaN
Double_t QuietNaN()
Returns a quiet NaN as defined by IEEE 754
Definition: TMath.h:901
RooFit::InputArguments
@ InputArguments
Definition: RooGlobalFunc.h:61
RooAbsArg::getComponents
RooArgSet * getComponents() const
Create a RooArgSet with all components (branch nodes) of the expression tree headed by this object.
Definition: RooAbsArg.cxx:712
RooCacheManager::getObj
T * getObj(const RooArgSet *nset, Int_t *sterileIndex=0, const TNamed *isetRangeName=0)
Definition: RooCacheManager.h:44
RooNaNPacker::packFloatIntoNaN
static double packFloatIntoNaN(float payload)
Pack float into mantissa of a NaN.
Definition: RooNaNPacker.h:109
RooAbsPdf::extendMode
virtual ExtendMode extendMode() const
Returns ability of PDF to provide extended likelihood terms.
Definition: RooAbsPdf.h:236
RooFit::PrintLevel
RooCmdArg PrintLevel(Int_t code)
Definition: RooGlobalFunc.cxx:204
RooArgSet.h
RooAbsReal::isBinnedDistribution
virtual Bool_t isBinnedDistribution(const RooArgSet &) const
Tests if the distribution is binned. Unless overridden by derived classes, this always returns false.
Definition: RooAbsReal.h:327
TString::Data
const char * Data() const
Definition: TString.h:369
coutP
#define coutP(a)
Definition: RooMsgService.h:31
RooAbsData::isWeighted
virtual Bool_t isWeighted() const
Definition: RooAbsData.h:126
RooAbsPdf::CanBeExtended
@ CanBeExtended
Definition: RooAbsPdf.h:232
RooAbsReal::createIntegral
RooAbsReal * createIntegral(const RooArgSet &iset, const RooCmdArg &arg1, const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none(), const RooCmdArg &arg7=RooCmdArg::none(), const RooCmdArg &arg8=RooCmdArg::none()) const
Create an object that represents the integral of the function over one or more observables listed in ...
Definition: RooAbsReal.cxx:548
RooBatchCompute::RunContext::logProbabilities
std::vector< double > logProbabilities
If evaluation should only occur in a range, the range name can be passed here.
Definition: RunContext.h:56
ClassImp
#define ClassImp(name)
Definition: Rtypes.h:364
Form
char * Form(const char *fmt,...)
TNamed::GetTitle
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
RooAbsTestStatistic::Configuration::cloneInputData
bool cloneInputData
Definition: RooAbsTestStatistic.h:51
RooCmdConfig::process
Bool_t process(const RooCmdArg &arg)
Process given RooCmdArg.
Definition: RooCmdConfig.cxx:513
RooAbsArg::Print
virtual void Print(Option_t *options=0) const
Print the object to the defaultPrintStream().
Definition: RooAbsArg.h:320
RooRandom::integer
static UInt_t integer(UInt_t max, TRandom *generator=randomGenerator())
Return an integer uniformly distributed from [0,n-1].
Definition: RooRandom.cxx:101
RooXYChi2Var.h
xmax
float xmax
Definition: THbookFile.cxx:95
RooAbsArg::_serverList
RefCountList_t _serverList
Definition: RooAbsArg.h:599
RooNumCdf
Class RooNumCdf is an implementation of RooNumRunningInt specialized to calculate cumulative distribu...
Definition: RooNumCdf.h:17
RooAbsReal::CollectErrors
@ CollectErrors
Definition: RooAbsReal.h:311
RooPlot::getFitRangeNEvt
Double_t getFitRangeNEvt() const
Return the number of events in the fit range.
Definition: RooPlot.h:141
coutE
#define coutE(a)
Definition: RooMsgService.h:33
RooAbsPdf::binnedGenContext
virtual RooAbsGenContext * binnedGenContext(const RooArgSet &vars, Bool_t verbose=kFALSE) const
Return a binned generator context.
Definition: RooAbsPdf.cxx:2048
RooCachedReal::setCacheSource
void setCacheSource(Bool_t flag)
Definition: RooCachedReal.h:44
RooAbsPdf::getLogProbabilities
RooSpan< const double > getLogProbabilities(RooBatchCompute::RunContext &evalData, const RooArgSet *normSet=nullptr) const
Compute the log-likelihoods for all events in the requested batch.
Definition: RooAbsPdf.cxx:739
coutW
#define coutW(a)
Definition: RooMsgService.h:32
output
static void output(int code)
Definition: gifencode.c:226
RooAbsPdf::createCdf
RooAbsReal * createCdf(const RooArgSet &iset, const RooArgSet &nset=RooArgSet())
Create a cumulative distribution function of this p.d.f in terms of the observables listed in iset.
Definition: RooAbsPdf.cxx:3471
RooArgList
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgList.h:21
RooGenContext
Class RooGenContext implement a universal generator context for all RooAbsPdf classes that do not hav...
Definition: RooGenContext.h:30
RooFit::WeightVar
RooCmdArg WeightVar(const char *name, Bool_t reinterpretAsWeight=kFALSE)
Definition: RooGlobalFunc.cxx:133
RooAbsData::weight
virtual Double_t weight() const =0
RooFit::Hesse
RooCmdArg Hesse(Bool_t flag=kTRUE)
Definition: RooGlobalFunc.cxx:208
RooAbsReal::plotSanityChecks
Bool_t plotSanityChecks(RooPlot *frame) const
Utility function for plotOn(), perform general sanity check on frame to ensure safe plotting operatio...
Definition: RooAbsReal.cxx:3066
RooAbsReal::getVal
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition: RooAbsReal.h:91
RooDataHist::sumEntries
Double_t sumEntries() const override
Sum the weights of all bins.
Definition: RooDataHist.cxx:1808
log
double log(double)
RooAbsTestStatistic::Configuration::rangeName
std::string rangeName
Stores the configuration parameters for RooAbsTestStatistic.
Definition: RooAbsTestStatistic.h:45
RooAbsGenContext::generate
virtual RooDataSet * generate(Double_t nEvents=0, Bool_t skipInit=kFALSE, Bool_t extendedMode=kFALSE)
Generate the specified number of events with nEvents>0 and and return a dataset containing the genera...
Definition: RooAbsGenContext.cxx:152
Int_t
int Int_t
Definition: RtypesCore.h:45
RooAbsPdf::getValV
virtual Double_t getValV(const RooArgSet *set=0) const
Return current value, normalized by integrating over the observables in nset.
Definition: RooAbsPdf.cxx:281
RooAbsPdf::printMultiline
virtual void printMultiline(std::ostream &os, Int_t contents, Bool_t verbose=kFALSE, TString indent="") const
Print multi line detailed information of this RooAbsPdf.
Definition: RooAbsPdf.cxx:2031
RooChi2Var
RooChi2Var implements a simple calculation from a binned dataset and a PDF.
Definition: RooChi2Var.h:25
box
void box(Int_t pat, Double_t x1, Double_t y1, Double_t x2, Double_t y2)
Definition: fillpatterns.C:1
RooAbsPdf::RooAbsPdf
RooAbsPdf()
Default constructor.
Definition: RooAbsPdf.cxx:205
TRandom::Uniform
virtual Double_t Uniform(Double_t x1=1)
Returns a uniform deviate on the interval (0, x1).
Definition: TRandom.cxx:672
RooFit::Normalization
RooCmdArg Normalization(Double_t scaleFactor)
Definition: RooGlobalFunc.cxx:57
RooFit::MPSplit
MPSplit
Definition: RooGlobalFunc.h:63
RooCmdArg::setInt
void setInt(Int_t idx, Int_t value)
Definition: RooCmdArg.h:66
RooAbsTestStatistic::Configuration::verbose
bool verbose
Definition: RooAbsTestStatistic.h:49
TNamed::fName
TString fName
Definition: TNamed.h:32
RooAbsCollection::find
RooAbsArg * find(const char *name) const
Find object with given name in list.
Definition: RooAbsCollection.cxx:827
RooAbsPdf::specialGeneratorConfig
RooNumGenConfig * specialGeneratorConfig() const
Returns the specialized integrator configuration for this RooAbsReal.
Definition: RooAbsPdf.cxx:3597
TGeant4Unit::pc
static constexpr double pc
Definition: TGeant4SystemOfUnits.h:130
TString::Contains
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:624
RooCurve.h
RooAbsArg::setOperMode
void setOperMode(OperMode mode, Bool_t recurseADirty=kTRUE)
Set the operation mode of this node.
Definition: RooAbsArg.cxx:1783
RooAbsPdf::CacheElem::_norm
RooAbsReal * _norm
Definition: RooAbsPdf.h:329
RooAbsPdf::GenSpec
Definition: RooAbsPdf.h:73
RooAbsPdf::getGenerator
virtual Int_t getGenerator(const RooArgSet &directVars, RooArgSet &generateVars, Bool_t staticInitOK=kTRUE) const
Load generatedVars with the subset of directVars that we can generate events for, and return a code t...
Definition: RooAbsPdf.cxx:2466
TString::Length
Ssiz_t Length() const
Definition: TString.h:410
RooAbsPdf::CacheElem
Normalization set with for above integral.
Definition: RooAbsPdf.h:324
coutI
#define coutI(a)
Definition: RooMsgService.h:30
TClass.h
TList.h
indent
static void indent(ostringstream &buf, int indent_level)
Definition: TClingCallFunc.cxx:87
RooObjCacheManager::sterilize
void sterilize()
Clear the cache payload but retain slot mapping w.r.t to normalization and integration sets.
Definition: RooObjCacheManager.cxx:159
RooPrintable::kAddress
@ kAddress
Definition: RooPrintable.h:33
RooAbsPdf::defaultGeneratorConfig
static RooNumGenConfig * defaultGeneratorConfig()
Returns the default numeric MC generator configuration for all RooAbsReals.
Definition: RooAbsPdf.cxx:3587
RooAbsReal
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition: RooAbsReal.h:61
RooFitResult::setCovQual
void setCovQual(Int_t val)
Definition: RooFitResult.h:171
RooAbsReal::getIntegratorConfig
const RooNumIntConfig * getIntegratorConfig() const
Return the numeric integration configuration used for this object.
Definition: RooAbsReal.cxx:3557
TMatrixTSym< Double_t >
RooDataSet::SetName
void SetName(const char *name) override
Change the name of this dataset into the given name.
Definition: RooDataSet.cxx:1980
RooAbsPdf::initGenerator
virtual void initGenerator(Int_t code)
Interface for one-time initialization to setup the generator for the specified code.
Definition: RooAbsPdf.cxx:2476
RooAbsPdf::_normMgr
RooObjCacheManager _normMgr
Definition: RooAbsPdf.h:331
RooNameSet::select
RooArgSet * select(const RooArgSet &list) const
Construct a RooArgSet of objects in input 'list' whose names match to those in the internal name list...
Definition: RooNameSet.cxx:185
TString
Basic string class.
Definition: TString.h:136
ROOT::Math::CholeskyDecompGenDim::Invert
bool Invert(M &m) const
place the inverse into m
Definition: CholeskyDecomp.h:389
RooLinkedList::FindObject
TObject * FindObject(const char *name) const
Return pointer to obejct with given name.
Definition: RooLinkedList.cxx:532
RooRealVar::setRange
void setRange(const char *name, Double_t min, Double_t max)
Set a fit or plotting range.
Definition: RooRealVar.cxx:526
RooWorkspace::set
const RooArgSet * set(const char *name)
Return pointer to previously defined named set with given nmame If no such set is found a null pointe...
Definition: RooWorkspace.cxx:977
RooAbsPdf::_traceCount
Int_t _traceCount
Definition: RooAbsPdf.h:347
TObject::InheritsFrom
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:445
RooDataSet.h
TString::Clear
void Clear()
Clear string without changing its capacity.
Definition: TString.cxx:1198
RooAbsPdf::isDirectGenSafe
virtual Bool_t isDirectGenSafe(const RooAbsArg &arg) const
Check if given observable can be safely generated using the pdfs internal generator mechanism (if tha...
Definition: RooAbsPdf.cxx:2501
RooNLLVar.h
RooFit::NumIntegration
@ NumIntegration
Definition: RooGlobalFunc.h:62
RooAbsArg::branchNodeServerList
void branchNodeServerList(RooAbsCollection *list, const RooAbsArg *arg=0, Bool_t recurseNonDerived=kFALSE) const
Fill supplied list with all branch nodes of the arg tree starting with ourself as top node.
Definition: RooAbsArg.cxx:521
RooAbsData::sumEntries
virtual Double_t sumEntries() const =0
Return effective number of entries in dataset, i.e., sum all weights.
RooAbsPdf::GenSpec::GenSpec
GenSpec()
Definition: RooAbsPdf.h:76
RooAbsPdf::plotOn
virtual RooPlot * plotOn(RooPlot *frame, const RooCmdArg &arg1=RooCmdArg::none(), const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none(), const RooCmdArg &arg7=RooCmdArg::none(), const RooCmdArg &arg8=RooCmdArg::none(), const RooCmdArg &arg9=RooCmdArg::none(), const RooCmdArg &arg10=RooCmdArg::none()) const
Helper calling plotOn(RooPlot*, RooLinkedList&) const.
Definition: RooAbsPdf.h:121
bool
CholeskyDecomp.h
header file containing the templated implementation of matrix inversion routines for use with ROOT's ...
TIterator
Iterator abstract base class.
Definition: TIterator.h:30
RooFitResult
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Definition: RooFitResult.h:40
RooAbsReal::ScaleType
ScaleType
Definition: RooAbsReal.h:266
RooChi2Var.h
RooInt
RooInt is a minimal implementation of a TObject holding a Int_t value.
Definition: RooInt.h:22
RooCmdConfig::getInt
Int_t getInt(const char *name, Int_t defaultValue=0)
Return integer property registered with name 'name'.
Definition: RooCmdConfig.cxx:690
TPaveText.h
RooAbsTestStatistic::Configuration::addCoefRangeName
std::string addCoefRangeName
Definition: RooAbsTestStatistic.h:46
RooAbsReal::PlotOpt::scaleFactor
Double_t scaleFactor
Definition: RooAbsReal.h:483
TMatrixDSym.h
RooConstraintSum.h
RooProjectedPdf.h
RooAbsPdf::verboseEval
static int verboseEval()
Return global level of verbosity for p.d.f. evaluations.
Definition: RooAbsPdf.cxx:3406
RooAbsGenContext::setProtoDataOrder
virtual void setProtoDataOrder(Int_t *lut)
Set the traversal order of prototype data to that in the lookup tables passed as argument.
Definition: RooAbsGenContext.cxx:348
RooSpan::size
constexpr std::span< T >::index_type size() const noexcept
Definition: RooSpan.h:121
RooAbsPdf::setTraceCounter
void setTraceCounter(Int_t value, Bool_t allNodes=kFALSE)
Reset trace counter to given value, limiting the number of future trace messages for this pdf to 'val...
Definition: RooAbsPdf.cxx:633
RooRealIntegral
RooRealIntegral performs hybrid numerical/analytical integrals of RooAbsReal objects.
Definition: RooRealIntegral.h:34
RooCmdArg::setString
void setString(Int_t idx, const char *value)
Definition: RooCmdArg.h:72
RooAbsPdf::getNormObj
virtual const RooAbsReal * getNormObj(const RooArgSet *set, const RooArgSet *iset, const TNamed *rangeName=0) const
Return pointer to RooAbsReal object that implements calculation of integral over observables iset in ...
Definition: RooAbsPdf.cxx:490
RooAbsPdf::setGeneratorConfig
void setGeneratorConfig()
Remove the specialized numeric MC generator configuration associated with this object.
Definition: RooAbsPdf.cxx:3652
RooCmdConfig
Class RooCmdConfig is a configurable parser for RooCmdArg named arguments.
Definition: RooCmdConfig.h:27
RooAbsPdf::_errorCount
Int_t _errorCount
Definition: RooAbsPdf.h:343
RooAbsPdf::extendedTerm
virtual Double_t extendedTerm(Double_t observedEvents, const RooArgSet *nset=0) const
Return the extended likelihood term ( ) of this PDF for the given number of observed events.
Definition: RooAbsPdf.cxx:782
RooAbsArg::getParameters
RooArgSet * getParameters(const RooAbsData *data, Bool_t stripDisconnected=kTRUE) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
Definition: RooAbsArg.cxx:579
RooPlot::addObject
void addObject(TObject *obj, Option_t *drawOptions="", Bool_t invisible=kFALSE)
Add a generic object to this plot.
Definition: RooPlot.cxx:422
TObject::GetName
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:359
RooPlot::getFitRangeBinW
Double_t getFitRangeBinW() const
Return the bin width that is being used to normalise the PDF.
Definition: RooPlot.h:144
RooAbsCollection::selectByName
RooAbsCollection * selectByName(const char *nameList, Bool_t verbose=kFALSE) const
Create a subset of the current collection, consisting only of those elements with names matching the ...
Definition: RooAbsCollection.cxx:737
ccoutI
#define ccoutI(a)
Definition: RooMsgService.h:38
RooAbsPdf::MustBeExtended
@ MustBeExtended
Definition: RooAbsPdf.h:232
RooDataSet::add
virtual void add(const RooArgSet &row, Double_t weight=1.0, Double_t weightError=0) override
Add a data point, with its coordinates specified in the 'data' argset, to the data set.
Definition: RooDataSet.cxx:1156
RooAbsArg::setStringAttribute
void setStringAttribute(const Text_t *key, const Text_t *value)
Associate string 'value' to this object under key 'key'.
Definition: RooAbsArg.cxx:324
RooAbsPdf::~RooAbsPdf
virtual ~RooAbsPdf()
Destructor.
Definition: RooAbsPdf.cxx:263
RooParamBinning.h
RooAbsReal::PlotOpt
Definition: RooAbsReal.h:477
RooAbsPdf::setNormRange
void setNormRange(const char *rangeName)
Definition: RooAbsPdf.cxx:3683
RooAbsTestStatistic::Configuration::interleave
RooFit::MPSplit interleave
Definition: RooAbsTestStatistic.h:48
ROOT::Math::fabs
VecExpr< UnaryOp< Fabs< T >, VecExpr< A, T, D >, T >, T, D > fabs(const VecExpr< A, T, D > &rhs)
Definition: UnaryOperators.h:131
RooFit::WARNING
@ WARNING
Definition: RooGlobalFunc.h:58
RooDataHist
The RooDataHist is a container class to hold N-dimensional binned data.
Definition: RooDataHist.h:37
RooCachedReal.h
RooPrintable::kName
@ kName
Definition: RooPrintable.h:33
RooAbsPdf::_rawValue
Double_t _rawValue
Definition: RooAbsPdf.h:320
RooFormulaVar
A RooFormulaVar is a generic implementation of a real-valued object, which takes a RooArgList of serv...
Definition: RooFormulaVar.h:30
RooDataHist::get
const RooArgSet * get() const override
Get bin centre of current bin.
Definition: RooDataHist.h:74
RooAbsPdf::CanNotBeExtended
@ CanNotBeExtended
Definition: RooAbsPdf.h:232
RooAbsPdf::getNorm
Double_t getNorm(const RooArgSet &nset) const
Get normalisation term needed to normalise the raw values returned by getVal().
Definition: RooAbsPdf.h:211
RooCustomizer.h
RooNumCdf.h
RooAbsPdf::GenSpec::~GenSpec
virtual ~GenSpec()
Definition: RooAbsPdf.cxx:3664
RooDerivative.h
xmin
float xmin
Definition: THbookFile.cxx:95
RooNaNPacker.h
RooAbsPdf::paramOn
virtual RooPlot * paramOn(RooPlot *frame, const RooCmdArg &arg1=RooCmdArg::none(), const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none(), const RooCmdArg &arg7=RooCmdArg::none(), const RooCmdArg &arg8=RooCmdArg::none())
Add a box with parameter values (and errors) to the specified frame.
Definition: RooAbsPdf.cxx:3234
RooAbsPdf.h
RooCachedReal
RooCachedReal is an implementation of RooAbsCachedReal that can cache any external RooAbsReal input f...
Definition: RooCachedReal.h:20
RooAbsGenContext::isValid
Bool_t isValid() const
Definition: RooAbsGenContext.h:34
TMath::IsNaN
Bool_t IsNaN(Double_t x)
Definition: TMath.h:892
RooAbsReal::integralNameSuffix
TString integralNameSuffix(const RooArgSet &iset, const RooArgSet *nset=0, const char *rangeName=0, Bool_t omitEmpty=kFALSE) const
Construct string with unique suffix name to give to integral object that encodes integrated observabl...
Definition: RooAbsReal.cxx:795
RooAbsArg::isValueDirty
Bool_t isValueDirty() const
Definition: RooAbsArg.h:419
TNamed
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:29
RooAbsPdf::prepareMultiGen
GenSpec * prepareMultiGen(const RooArgSet &whatVars, const RooCmdArg &arg1=RooCmdArg::none(), const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none())
Prepare GenSpec configuration object for efficient generation of multiple datasets from identical spe...
Definition: RooAbsPdf.cxx:2230
RooFit::Generation
@ Generation
Definition: RooGlobalFunc.h:60
kFALSE
const Bool_t kFALSE
Definition: RtypesCore.h:101
RooBinnedGenContext
RooBinnedGenContext is an efficient implementation of the generator context specific for binned pdfs.
Definition: RooBinnedGenContext.h:30
RooAbsPdf::analyticalIntegralWN
Double_t analyticalIntegralWN(Int_t code, const RooArgSet *normSet, const char *rangeName=0) const
Analytical integral with normalization (see RooAbsReal::analyticalIntegralWN() for further informatio...
Definition: RooAbsPdf.cxx:411
RooAbsArg::clearValueAndShapeDirty
void clearValueAndShapeDirty() const
Definition: RooAbsArg.h:561
RooRandom.h
RooFit::Fitting
@ Fitting
Definition: RooGlobalFunc.h:60
RooAbsPdf::createNLL
virtual RooAbsReal * createNLL(RooAbsData &data, const RooLinkedList &cmdList)
Construct representation of -log(L) of PDFwith given dataset.
Definition: RooAbsPdf.cxx:972
RooAbsReal::derivative
RooDerivative * derivative(RooRealVar &obs, Int_t order=1, Double_t eps=0.001)
Return function representing first, second or third order derivative of this function.
Definition: RooAbsReal.cxx:4261
RooAbsData::get
virtual const RooArgSet * get() const
Definition: RooAbsData.h:92
TMatrixTSym::Similarity
TMatrixTSym< Element > & Similarity(const TMatrixT< Element > &n)
Calculate B * (*this) * B^T , final matrix will be (nrowsb x nrowsb) This is a similarity transform w...
Definition: TMatrixTSym.cxx:1099
RooArgSet::add
Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE) override
Add element to non-owning set.
Definition: RooArgSet.cxx:261
RooAbsPdf::getGeneratorConfig
const RooNumGenConfig * getGeneratorConfig() const
Return the numeric MC generator configuration used for this object.
Definition: RooAbsPdf.cxx:3625
RooAbsCollection::selectCommon
RooAbsCollection * selectCommon(const RooAbsCollection &refColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
Definition: RooAbsCollection.cxx:714
RooFit::Plotting
@ Plotting
Definition: RooGlobalFunc.h:60
RooNLLVar
Class RooNLLVar implements a -log(likelihood) calculation from a dataset and a PDF.
Definition: RooNLLVar.h:30
RooLinkedList
RooLinkedList is an collection class for internal use, storing a collection of RooAbsArg pointers in ...
Definition: RooLinkedList.h:37
RooPlot.h
RooAbsCollection::createIterator
TIterator * createIterator(Bool_t dir=kIterForward) const
TIterator-style iteration over contained elements.
Definition: RooAbsCollection.h:133
RooAbsReal::evaluate
virtual Double_t evaluate() const =0
Evaluate this PDF / function / constant. Needs to be overridden by all derived classes.
RooAbsPdf::_normRangeOverride
static TString _normRangeOverride
Definition: RooAbsPdf.h:355
RooAbsReal::fillDataHist
RooDataHist * fillDataHist(RooDataHist *hist, const RooArgSet *nset, Double_t scaleFactor, Bool_t correctForBinVolume=kFALSE, Bool_t showProgress=kFALSE) const
Fill a RooDataHist with values sampled from this function at the bin centers.
Definition: RooAbsReal.cxx:1216
RooAbsReal::chi2FitDriver
RooFitResult * chi2FitDriver(RooAbsReal &fcn, RooLinkedList &cmdList)
Internal driver function for chi2 fits.
Definition: RooAbsReal.cxx:4620
RooWorkspace::defineSetInternal
Bool_t defineSetInternal(const char *name, const RooArgSet &aset)
Definition: RooWorkspace.cxx:891
RooAbsReal::PlotOpt::stype
ScaleType stype
Definition: RooAbsReal.h:484
RooAbsReal::createIntRI
RooAbsReal * createIntRI(const RooArgSet &iset, const RooArgSet &nset=RooArgSet())
Utility function for createRunningIntegral.
Definition: RooAbsReal.cxx:4091
RooAbsPdf::CacheElem::~CacheElem
virtual ~CacheElem()
Destructor of normalization cache element.
Definition: RooAbsPdf.cxx:3418
RooAbsArg::RooProjectedPdf
friend class RooProjectedPdf
Definition: RooAbsArg.h:598
RooPrintable::kArgs
@ kArgs
Definition: RooPrintable.h:33
RooRealProxy.h
RooAddition
RooAddition calculates the sum of a set of RooAbsReal terms, or when constructed with two sets,...
Definition: RooAddition.h:27
RooPlot
A RooPlot is a plot frame and a container for graphics objects within that frame.
Definition: RooPlot.h:44
RooAbsArg::RooArgSet
friend class RooArgSet
Definition: RooAbsArg.h:591
RooAbsGenContext
RooAbsGenContext is the abstract base class for generator contexts of RooAbsPdf objects.
Definition: RooAbsGenContext.h:26
RooAbsArg::setProxyNormSet
void setProxyNormSet(const RooArgSet *nset)
Forward a change in the cached normalization argset to all the registered proxies.
Definition: RooAbsArg.cxx:1304
RooAbsCacheElement::_owner
RooAbsArg * _owner
Definition: RooAbsCacheElement.h:53
RooNumGenConfig::defaultConfig
static RooNumGenConfig & defaultConfig()
Return reference to instance of default numeric integrator configuration object.
Definition: RooNumGenConfig.cxx:48
RooAbsPdf::getAllConstraints
virtual RooArgSet * getAllConstraints(const RooArgSet &observables, RooArgSet &constrainedParams, Bool_t stripDisconnected=kTRUE) const
This helper function finds and collects all constraints terms of all component p.d....
Definition: RooAbsPdf.cxx:3565
RooAbsCollection::add
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
Definition: RooAbsCollection.cxx:451
RooAddition.h
RooGenContext.h
RooAbsTestStatistic::Configuration
Definition: RooAbsTestStatistic.h:43
RooAbsArg::getStringAttribute
const Text_t * getStringAttribute(const Text_t *key) const
Get string attribute mapped under key 'key'.
Definition: RooAbsArg.cxx:337
isnan
int isnan(double)
RooAbsData::numEntries
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Definition: RooAbsData.cxx:304
RooCategory.h
RooLinkedList::Add
virtual void Add(TObject *arg)
Definition: RooLinkedList.h:64
RooPrintable::kValue
@ kValue
Definition: RooPrintable.h:33
sqrt
double sqrt(double)
RooAbsReal::_value
Double_t _value
Definition: RooAbsReal.h:464
RooAbsReal::enableOffsetting
virtual void enableOffsetting(Bool_t)
Definition: RooAbsReal.h:353
RooAbsArg::constOptimizeTestStatistic
virtual void constOptimizeTestStatistic(ConstOpCode opcode, Bool_t doAlsoTrackingOpt=kTRUE)
Interface function signaling a request to perform constant term optimization.
Definition: RooAbsArg.cxx:1770
oocoutW
#define oocoutW(o, a)
Definition: RooMsgService.h:47
RooAbsReal::plotOnCompSelect
void plotOnCompSelect(RooArgSet *selNodes) const
Helper function for plotting of composite p.d.fs.
Definition: RooAbsReal.cxx:1537
RooRealVar.h
line
TLine * line
Definition: entrylistblock_figure1.C:235
RooAbsPdf::logBatchComputationErrors
void logBatchComputationErrors(RooSpan< const double > &outputs, std::size_t begin) const
Scan through outputs and fix+log all nans and negative values.
Definition: RooAbsPdf.cxx:716
TRandom::Integer
virtual UInt_t Integer(UInt_t imax)
Returns a random integer uniformly distributed on the interval [ 0, imax-1 ].
Definition: TRandom.cxx:360
RooFitResult.h
TIterator::Next
virtual TObject * Next()=0
RooAbsCachedReal::setInterpolationOrder
void setInterpolationOrder(Int_t order)
Set interpolation order of RooHistFunct representing cache histogram.
Definition: RooAbsCachedReal.cxx:291
ROOT::Math::CholeskyDecompGenDim
class to compute the Cholesky decomposition of a matrix
Definition: CholeskyDecomp.h:311
RooAbsReal::plotOn
virtual RooPlot * plotOn(RooPlot *frame, const RooCmdArg &arg1=RooCmdArg(), const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg(), const RooCmdArg &arg9=RooCmdArg(), const RooCmdArg &arg10=RooCmdArg()) const
Plot (project) PDF on specified frame.
Definition: RooAbsReal.cxx:1704
ymin
float ymin
Definition: THbookFile.cxx:95
RooDataHist::SetName
void SetName(const char *name) override
Change the name of the RooDataHist.
Definition: RooDataHist.cxx:1947
RooGlobalFunc.h
RooHelpers::tokenise
std::vector< std::string > tokenise(const std::string &str, const std::string &delims, bool returnEmptyToken=true)
Tokenise the string by splitting at the characters in delims.
Definition: RooHelpers.cxx:66
RooAbsArg::Activate
@ Activate
Definition: RooAbsArg.h:386
RooAbsPdf::getConstraints
virtual RooArgSet * getConstraints(const RooArgSet &, RooArgSet &, Bool_t) const
Definition: RooAbsPdf.h:184
RooAbsReal::Raw
@ Raw
Definition: RooAbsReal.h:266
RooFit::SupNormSet
RooCmdArg SupNormSet(const RooArgSet &nset)
Definition: RooGlobalFunc.cxx:361
RooAbsPdf::printValue
virtual void printValue(std::ostream &os) const
Print value of p.d.f, also print normalization integral that was last used, if any.
Definition: RooAbsPdf.cxx:2012
RooFit::Tracing
@ Tracing
Definition: RooGlobalFunc.h:61
RooFit::Minimizer
RooCmdArg Minimizer(const char *type, const char *alg=0)
Definition: RooGlobalFunc.cxx:230
RooAbsPdf::_negCount
Int_t _negCount
Definition: RooAbsPdf.h:348
RooNameSet
RooNameSet is a utility class that stores the names the objects in a RooArget.
Definition: RooNameSet.h:24
RooCmdConfig::defineInt
Bool_t defineInt(const char *name, const char *argName, Int_t intNum, Int_t defValue=0)
Define integer property name 'name' mapped to integer in slot 'intNum' in RooCmdArg with name argName...
Definition: RooCmdConfig.cxx:316
RooDataHist::numEntries
Int_t numEntries() const override
Return the number of bins.
Definition: RooDataHist.cxx:1799
RooAbsRealLValue::hasRange
virtual Bool_t hasRange(const char *name) const
Check if variable has a binning with given name.
Definition: RooAbsRealLValue.h:102
RooAbsPdf::_selectComp
Bool_t _selectComp
Definition: RooAbsPdf.h:350
Double_t
double Double_t
Definition: RtypesCore.h:59
RooAbsArg::RooDataSet
friend class RooDataSet
Definition: RooAbsArg.h:636
RooNumGenConfig
RooNumGenConfig holds the configuration parameters of the various numeric integrators used by RooReal...
Definition: RooNumGenConfig.h:25
RooPlot::getNormVars
const RooArgSet * getNormVars() const
Definition: RooPlot.h:148
RooAbsArg::getObservables
RooArgSet * getObservables(const RooArgSet &set, Bool_t valueOnly=kTRUE) const
Given a set of possible observables, return the observables that this PDF depends on.
Definition: RooAbsArg.h:294
RooAbsArg::addOwnedComponents
Bool_t addOwnedComponents(const RooArgSet &comps)
Take ownership of the contents of 'comps'.
Definition: RooAbsArg.cxx:2182
RooAbsPdf::createProjection
virtual RooAbsPdf * createProjection(const RooArgSet &iset)
Return a p.d.f that represent a projection of this p.d.f integrated over given observables.
Definition: RooAbsPdf.cxx:3436
RooMinimizer.h
RooAbsPdf::_norm
RooAbsReal * _norm
Definition: RooAbsPdf.h:321
TRandom::Poisson
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:402
RooAbsPdf::_specGeneratorConfig
RooNumGenConfig * _specGeneratorConfig
Definition: RooAbsPdf.h:352
RooInt.h
RooAbsPdf::generate
RooDataSet * generate(const RooArgSet &whatVars, Int_t nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none())
See RooAbsPdf::generate(const RooArgSet&,const RooCmdArg&,const RooCmdArg&,const RooCmdArg&,...
Definition: RooAbsPdf.h:58
RooAbsTestStatistic::Configuration::nCPU
int nCPU
Definition: RooAbsTestStatistic.h:47
RooAbsPdf::calculateAsymptoticCorrectedCovMatrix
int calculateAsymptoticCorrectedCovMatrix(Minimizer &minimizer, RooAbsData const &data)
Definition: RooAbsPdf.cxx:1220
TObject
Mother of all ROOT objects.
Definition: TObject.h:37
RooNameSet::content
const char * content() const
Definition: RooNameSet.h:50
RooNumGenConfig.h
RooAbsPdf::getValues
RooSpan< const double > getValues(RooBatchCompute::RunContext &evalData, const RooArgSet *normSet) const
Compute batch of values for given input data, and normalise by integrating over the observables in no...
Definition: RooAbsPdf.cxx:353
RooNameReg::str
static const char * str(const TNamed *ptr)
Return C++ string corresponding to given TNamed pointer.
Definition: RooNameReg.cxx:103
RooAbsPdf::_verboseEval
static Int_t _verboseEval
Definition: RooAbsPdf.h:315
RooFit::NormRange
RooCmdArg NormRange(const char *rangeNameList)
Definition: RooGlobalFunc.cxx:60
RooFit::Range
RooCmdArg Range(const char *rangeName, Bool_t adjustNorm=kTRUE)
Definition: RooGlobalFunc.cxx:58
name
char name[80]
Definition: TGX11.cxx:110
RooMinuit
RooMinuit is a wrapper class around TFitter/TMinuit that provides a seamless interface between the MI...
Definition: RooMinuit.h:39
RooAbsArg::dependsOn
Bool_t dependsOn(const RooAbsCollection &serverList, const RooAbsArg *ignoreArg=0, Bool_t valueOnly=kFALSE) const
Test whether we depend on (ie, are served by) any object in the specified collection.
Definition: RooAbsArg.cxx:765
RooPrintable::kTitle
@ kTitle
Definition: RooPrintable.h:33
ROOT::Math::Chebyshev::T
double T(double x)
Definition: ChebyshevPol.h:34
RooNameSet::setNameList
void setNameList(const char *givenList)
Definition: RooNameSet.cxx:142
RooXYChi2Var
RooXYChi2Var implements a simple chi^2 calculation from an unbinned dataset with values x,...
Definition: RooXYChi2Var.h:29
RooAbsReal::printMultiline
virtual void printMultiline(std::ostream &os, Int_t contents, Bool_t verbose=kFALSE, TString indent="") const
Structure printing.
Definition: RooAbsReal.cxx:490
RooPrintable::printStream
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,...
Definition: RooPrintable.cxx:75
genreflex::verbose
bool verbose
Definition: rootcling_impl.cxx:133
RooPrintable::kSingleLine
@ kSingleLine
Definition: RooPrintable.h:34
RooFit::Caching
@ Caching
Definition: RooGlobalFunc.h:61
RooDataSet
RooDataSet is a container class to hold unbinned data.
Definition: RooDataSet.h:33
RooAbsPdf::generateBinned
virtual RooDataHist * generateBinned(const RooArgSet &whatVars, Double_t nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none()) const
As RooAbsPdf::generateBinned(const RooArgSet&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,...
Definition: RooAbsPdf.h:107
TPaveText
A Pave (see TPave) with text, lines or/and boxes inside.
Definition: TPaveText.h:21
RooAbsArg
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition: RooAbsArg.h:72
RooAbsReal::getValues
virtual RooSpan< const double > getValues(RooBatchCompute::RunContext &evalData, const RooArgSet *normSet=nullptr) const
by this change, please consult the release notes for ROOT 6.24 for guidance on how to make this trans...
Definition: RooAbsReal.cxx:312
RooAbsTestStatistic::Configuration::integrateOverBinsPrecision
double integrateOverBinsPrecision
Definition: RooAbsTestStatistic.h:52
RooRealIntegral.h
RooRandom::randomGenerator
static TRandom * randomGenerator()
Return a pointer to a singleton random-number generator implementation.
Definition: RooRandom.cxx:53
RooAbsGenContext::setExpectedData
virtual void setExpectedData(Bool_t)
Definition: RooAbsGenContext.h:66
RooAbsCollection::Print
virtual void Print(Option_t *options=0) const
This method must be overridden when a class wants to print itself.
Definition: RooAbsCollection.h:214
RooAbsPdf
Definition: RooAbsPdf.h:43
TNamed::GetName
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
RooAbsPdf::selfNormalized
virtual Bool_t selfNormalized() const
Shows if a PDF is self-normalized, which means that no attempt is made to add a normalization term.
Definition: RooAbsPdf.h:227
RooAbsArg::getVariables
RooArgSet * getVariables(Bool_t stripDisconnected=kTRUE) const
Return RooArgSet with all variables (tree leaf nodes of expresssion tree)
Definition: RooAbsArg.cxx:1974
RooAbsReal::Relative
@ Relative
Definition: RooAbsReal.h:266
RooAbsArg::findServer
RooAbsArg * findServer(const char *name) const
Return server of this with name name. Returns nullptr if not found.
Definition: RooAbsArg.h:203
RooRealVar::setBins
void setBins(Int_t nBins, const char *name=0)
Create a uniform binning under name 'name' for this variable.
Definition: RooRealVar.cxx:408
RooAbsArg::_myws
RooWorkspace * _myws
Prevent 'AlwaysDirty' mode for this node.
Definition: RooAbsArg.h:690
RooAbsPdf::syncNormalization
virtual Bool_t syncNormalization(const RooArgSet *dset, Bool_t adjustProxies=kTRUE) const
Verify that the normalization integral cached with this PDF is valid for given set of normalization o...
Definition: RooAbsPdf.cxx:524
RooConstraintSum
RooConstraintSum calculates the sum of the -(log) likelihoods of a set of RooAbsPfs that represent co...
Definition: RooConstraintSum.h:27
RooAbsReal::PrintErrors
@ PrintErrors
Definition: RooAbsReal.h:311
launcher.spec
spec
Definition: launcher.py:30
TMatrixD.h
RooAbsCategoryLValue
RooAbsCategoryLValue is the common abstract base class for objects that represent a discrete value th...
Definition: RooAbsCategoryLValue.h:25
RooAbsPdf::getLogVal
virtual Double_t getLogVal(const RooArgSet *set=0) const
Return the log of the current value with given normalization An error message is printed if the argum...
Definition: RooAbsPdf.cxx:659
Class
void Class()
Definition: Class.C:29
TString::ToLower
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1147
RooRealVar
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:39
RooAbsTestStatistic::Configuration::binnedL
bool binnedL
Definition: RooAbsTestStatistic.h:53
RooBatchCompute::fast_log
double fast_log(double x)
Definition: RooVDTHeaders.h:56
RooAbsTestStatistic::Configuration::splitCutRange
bool splitCutRange
Definition: RooAbsTestStatistic.h:50
RooFit::Eval
@ Eval
Definition: RooGlobalFunc.h:61
cxcoutI
#define cxcoutI(a)
Definition: RooMsgService.h:85
RooHelpers::LocalChangeMsgLevel
Switches the message service to a different level while the instance is alive.
Definition: RooHelpers.h:42
RooAbsCollection::selectByAttrib
RooAbsCollection * selectByAttrib(const char *name, Bool_t value) const
Create a subset of the current collection, consisting only of those elements with the specified attri...
Definition: RooAbsCollection.cxx:691
RooMinimizer
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
Definition: RooMinimizer.h:40
RooNameReg.h
RooAbsPdf::resetErrorCounters
virtual void resetErrorCounters(Int_t resetValue=10)
Reset error counter to given value, limiting the number of future error messages for this pdf to 'res...
Definition: RooAbsPdf.cxx:621
RooDataHist::set
void set(std::size_t binNumber, double weight, double wgtErr)
Set bin content of bin that was last loaded with get(std::size_t).
Definition: RooDataHist.cxx:1433
RooPlot::getPlotVar
RooAbsRealLValue * getPlotVar() const
Definition: RooPlot.h:139
RooBatchCompute::RunContext::spans
std::unordered_map< const RooAbsReal *, RooSpan< const double > > spans
Once an object has computed its value(s), the span pointing to the results is registered here.
Definition: RunContext.h:52
RooBatchCompute::RunContext
This struct enables passing computation data around between elements of a computation graph.
Definition: RunContext.h:31
RooArgProxy.h
RooAbsPdf::createChi2
virtual RooAbsReal * createChi2(RooDataHist &data, const RooLinkedList &cmdList)
Create a variable from a histogram and this function.
Definition: RooAbsReal.cxx:4460
RooAbsPdf::randomizeProtoOrder
Int_t * randomizeProtoOrder(Int_t nProto, Int_t nGen, Bool_t resample=kFALSE) const
Return lookup table with randomized access order for prototype events, given nProto prototype data ev...
Definition: RooAbsPdf.cxx:2422
RooAbsPdf::canBeExtended
Bool_t canBeExtended() const
If true, PDF can provide extended likelihood term.
Definition: RooAbsPdf.h:238
RooAbsCollection::getSize
Int_t getSize() const
Definition: RooAbsCollection.h:186
RooSpan
A simple container to hold a batch of data values.
Definition: RooSpan.h:34
RooHelpers::checkIfRangesOverlap
bool checkIfRangesOverlap(RooAbsPdf const &pdf, RooAbsData const &data, std::vector< std::string > const &rangeNames)
Check if there is any overlap when a list of ranges is applied to a set of observables.
Definition: RooHelpers.cxx:205
TMath.h
RooArgSet
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:33
cxcoutD
#define cxcoutD(a)
Definition: RooMsgService.h:81
RooAbsReal::RelativeExpected
@ RelativeExpected
Definition: RooAbsReal.h:266
int
RooAbsCollection::contentsString
std::string contentsString() const
Return comma separated list of contained object names as STL string.
Definition: RooAbsCollection.cxx:1040
RooAbsArg::getAttribute
Bool_t getAttribute(const Text_t *name) const
Check if a named attribute is set. By default, all attributes are unset.
Definition: RooAbsArg.cxx:315
RooAbsPdf::expectedEvents
virtual Double_t expectedEvents(const RooArgSet *nset) const
Return expected number of events from this p.d.f for use in extended likelihood calculations.
Definition: RooAbsPdf.cxx:3386
RooAbsPdf::fitTo
virtual RooFitResult * fitTo(RooAbsData &data, const RooCmdArg &arg1=RooCmdArg::none(), const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none(), const RooCmdArg &arg6=RooCmdArg::none(), const RooCmdArg &arg7=RooCmdArg::none(), const RooCmdArg &arg8=RooCmdArg::none())
Fit PDF to given dataset.
Definition: RooAbsPdf.cxx:1479