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