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