Logo ROOT  
Reference Guide
RooMCStudy.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * *
9 * Copyright (c) 2000-2005, Regents of the University of California *
10 * and Stanford University. All rights reserved. *
11 * *
12 * Redistribution and use in source and binary forms, *
13 * with or without modification, are permitted according to the terms *
14 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15 *****************************************************************************/
16
17/**
18\file RooMCStudy.cxx
19\class RooMCStudy
20\ingroup Roofitcore
21
22RooMCStudy is a helper class to facilitate Monte Carlo studies
23such as 'goodness-of-fit' studies, that involve fitting a PDF
24to multiple toy Monte Carlo sets. These may be generated from either same PDF
25or from a different PDF with similar parameters.
26
27Given a fit and a generator PDF (they might be identical), RooMCStudy can produce
28toyMC samples and/or fit these.
29It accumulates the post-fit parameters of each iteration in a dataset. These can be
30retrieved using fitParams() or fitParDataSet(). This dataset additionally contains the
31variables
32- NLL: The value of the negative log-likelihood for each run.
33- ngen: The number of events generated for each run.
34
35Additional plotting routines simplify the task of plotting
36the distribution of the minimized likelihood, the fitted parameter values,
37fitted error and pull distribution.
38
39RooMCStudy provides the option to insert add-in modules
40that modify the generate-and-fit cycle and allow to perform
41extra steps in the cycle. Output of these modules can be stored
42alongside the fit results in the aggregate results dataset.
43These study modules should derive from the class RooAbsMCStudyModule.
44
45Check the RooFit tutorials
46- rf801_mcstudy.C
47- rf802_mcstudy_addons.C
48- rf803_mcstudy_addons2.C
49- rf804_mcstudy_constr.C
50for usage examples.
51**/
52
53#include "snprintf.h"
54#include <iostream>
55
56#include "RooMCStudy.h"
57#include "RooAbsMCStudyModule.h"
58
59#include "RooGenContext.h"
60#include "RooAbsPdf.h"
61#include "RooDataSet.h"
62#include "RooDataHist.h"
63#include "RooRealVar.h"
64#include "RooFitResult.h"
65#include "RooErrorVar.h"
66#include "RooFormulaVar.h"
67#include "RooArgList.h"
68#include "RooPlot.h"
69#include "RooGenericPdf.h"
70#include "RooRandom.h"
71#include "RooCmdConfig.h"
72#include "RooGlobalFunc.h"
73#include "RooPullVar.h"
74#include "RooMsgService.h"
75#include "RooProdPdf.h"
76
77using namespace std ;
78
80 ;
81
82
83/**
84Construct Monte Carlo Study Manager. This class automates generating data from a given PDF,
85fitting the PDF to data and accumulating the fit statistics.
86
87\param[in] model The PDF to be studied
88\param[in] observables The variables of the PDF to be considered observables
89\param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 Optional arguments according to table below.
90
91<table>
92<tr><th> Optional arguments <th>
93<tr><td> Silence() <td> Suppress all RooFit messages during running below PROGRESS level
94<tr><td> FitModel(const RooAbsPdf&) <td> The PDF for fitting if it is different from the PDF for generating.
95<tr><td> ConditionalObservables(const RooArgSet& set) <td> The set of observables that the PDF should _not_ be normalized over
96<tr><td> Binned(bool flag) <td> Bin the dataset before fitting it. Speeds up fitting of large data samples
97<tr><td> FitOptions(....) <td> Options to be used for fitting. All named arguments inside FitOptions() are passed to RooAbsPdf::fitTo().
98 `Save()` is especially interesting to be able to retrieve fit results of each run using fitResult().
99<tr><td> Verbose(bool flag) <td> Activate informational messages in event generation phase
100<tr><td> Extended(bool flag) <td> Determine number of events for each sample anew from a Poisson distribution
101<tr><td> Constrain(const RooArgSet& pars) <td> Apply internal constraints on given parameters in fit and sample constrained parameter values from constraint p.d.f for each toy.
102<tr><td> ExternalConstraints(const RooArgSet& ) <td> Apply internal constraints on given parameters in fit and sample constrained parameter values from constraint p.d.f for each toy.
103<tr><td> ProtoData(const RooDataSet&, bool randOrder)
104 <td> Prototype data for the event generation. If the randOrder flag is set, the order of the dataset will be re-randomized for each generation
105 cycle to protect against systematic biases if the number of generated events does not exactly match the number of events in the prototype dataset
106 at the cost of reduced precision with mu equal to the specified number of events
107</table>
108*/
109RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables,
110 const RooCmdArg& arg1, const RooCmdArg& arg2,
111 const RooCmdArg& arg3,const RooCmdArg& arg4,const RooCmdArg& arg5,
112 const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) : TNamed("mcstudy","mcstudy")
113
114{
115 // Stuff all arguments in a list
116 RooLinkedList cmdList;
117 cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
118 cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
119 cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
120 cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
121
122 // Select the pdf-specific commands
123 RooCmdConfig pc(Form("RooMCStudy::RooMCStudy(%s)",model.GetName())) ;
124
125 pc.defineObject("fitModel","FitModel",0,0) ;
126 pc.defineObject("condObs","ProjectedDependents",0,0) ;
127 pc.defineObject("protoData","PrototypeData",0,0) ;
128 pc.defineSet("cPars","Constrain",0,0) ;
129 pc.defineSet("extCons","ExternalConstraints",0,0) ;
130 pc.defineInt("silence","Silence",0,0) ;
131 pc.defineInt("randProtoData","PrototypeData",0,0) ;
132 pc.defineInt("verboseGen","Verbose",0,0) ;
133 pc.defineInt("extendedGen","Extended",0,0) ;
134 pc.defineInt("binGenData","Binned",0,0) ;
135 pc.defineInt("dummy","FitOptArgs",0,0) ;
136
137 // Process and check varargs
138 pc.process(cmdList) ;
139 if (!pc.ok(true)) {
140 // WVE do something here
141 throw std::string("RooMCStudy::RooMCStudy() Error in parsing arguments passed to contructor") ;
142 return ;
143 }
144
145 // Save fit command options
146 if (pc.hasProcessed("FitOptArgs")) {
147 RooCmdArg* fitOptArg = static_cast<RooCmdArg*>(cmdList.FindObject("FitOptArgs")) ;
148 for (Int_t i=0 ; i<fitOptArg->subArgs().GetSize() ;i++) {
149 _fitOptList.Add(new RooCmdArg(static_cast<RooCmdArg&>(*fitOptArg->subArgs().At(i)))) ;
150 }
151 }
152
153 // Decode command line arguments
154 _silence = pc.getInt("silence") ;
155 _verboseGen = pc.getInt("verboseGen") ;
156 _extendedGen = pc.getInt("extendedGen") ;
157 _binGenData = pc.getInt("binGenData") ;
158 _randProto = pc.getInt("randProtoData") ;
159
160 // Process constraints specifications
161 const RooArgSet* cParsTmp = pc.getSet("cPars") ;
162 const RooArgSet* extCons = pc.getSet("extCons") ;
163
164 RooArgSet* cPars = new RooArgSet ;
165 if (cParsTmp) {
166 cPars->add(*cParsTmp) ;
167 }
168
169 // If constraints are specified, add to fit options
170 if (cPars) {
172 }
173 if (extCons) {
175 }
176
177 // Make list of all constraints
178 RooArgSet allConstraints ;
179 RooArgSet consPars ;
180 if (cPars) {
181 RooArgSet* constraints = model.getAllConstraints(observables,*cPars,true) ;
182 if (constraints) {
183 allConstraints.add(*constraints) ;
184 delete constraints ;
185 }
186 }
187
188 // Construct constraint p.d.f
189 if (allConstraints.getSize()>0) {
190 _constrPdf = new RooProdPdf("mcs_constr_prod","RooMCStudy constraints product",allConstraints) ;
191
192 if (cPars) {
193 consPars.add(*cPars) ;
194 } else {
195 RooArgSet* params = model.getParameters(observables) ;
196 RooArgSet* cparams = _constrPdf->getObservables(*params) ;
197 consPars.add(*cparams) ;
198 delete params ;
199 delete cparams ;
200 }
202
203 _perExptGenParams = true ;
204
205 coutI(Generation) << "RooMCStudy::RooMCStudy: INFO have pdf with constraints, will generate parameters from constraint pdf for each experiment" << endl ;
206
207
208 } else {
209 _constrPdf = 0 ;
211
212 _perExptGenParams = false ;
213 }
214
215
216 // Extract generator and fit models
217 _genModel = const_cast<RooAbsPdf*>(&model) ;
218 _genSample = 0 ;
219 RooAbsPdf* fitModel = static_cast<RooAbsPdf*>(pc.getObject("fitModel",0)) ;
220 _fitModel = fitModel ? fitModel : _genModel ;
221
222 // Extract conditional observables and prototype data
223 _genProtoData = static_cast<RooDataSet*>(pc.getObject("protoData",0)) ;
224 if (pc.getObject("condObs",0)) {
225 _projDeps.add(static_cast<RooArgSet&>(*pc.getObject("condObs",0))) ;
226 }
227
228 _dependents.add(observables) ;
229
231 _canAddFitResults = true ;
232
234 oocoutW(_fitModel,Generation) << "RooMCStudy::RooMCStudy: WARNING Using generator option 'e' (Poisson distribution of #events) together " << endl
235 << " with a prototype dataset implies incomplete sampling or oversampling of proto data." << endl
236 << " Use option \"r\" to randomize prototype dataset order and thus to randomize" << endl
237 << " the set of over/undersampled prototype events for each generation cycle." << endl ;
238 }
239
241 if (!_binGenData) {
244 } else {
245 _genContext = 0 ;
246 }
247
249
250 // Store list of parameters and save initial values separately
253
255
256 // Place holder for NLL
257 _nllVar = new RooRealVar("NLL","-log(Likelihood)",0) ;
258
259 // Place holder for number of generated events
260 _ngenVar = new RooRealVar("ngen","number of generated events",0) ;
261
262 // Create data set containing parameter values, errors and pulls
263 RooArgSet tmp2(*_fitParams) ;
264 tmp2.add(*_nllVar) ;
265 tmp2.add(*_ngenVar) ;
266
267 // Mark all variable to store their errors in the dataset
268 tmp2.setAttribAll("StoreError",true) ;
269 tmp2.setAttribAll("StoreAsymError",true) ;
270 TString fpdName ;
271 if (_fitModel==_genModel) {
272 fpdName = Form("fitParData_%s",_fitModel->GetName()) ;
273 } else {
274 fpdName= Form("fitParData_%s_%s",_fitModel->GetName(),_genModel->GetName()) ;
275 }
276
277 _fitParData = new RooDataSet(fpdName.Data(),"Fit Parameters DataSet",tmp2) ;
278 tmp2.setAttribAll("StoreError",false) ;
279 tmp2.setAttribAll("StoreAsymError",false) ;
280
281 if (_perExptGenParams) {
282 _genParData = new RooDataSet("genParData","Generated Parameters dataset",*_genParams) ;
283 } else {
284 _genParData = 0 ;
285 }
286
287 // Append proto variables to allDependents
288 if (_genProtoData) {
290 }
291
292 // Call module initializers
293 list<RooAbsMCStudyModule*>::iterator iter ;
294 for (iter=_modList.begin() ; iter!= _modList.end() ; ++iter) {
295 bool ok = (*iter)->doInitializeInstance(*this) ;
296 if (!ok) {
297 oocoutE(_fitModel,Generation) << "RooMCStudy::ctor: removing study module " << (*iter)->GetName() << " from analysis chain because initialization failed" << endl ;
298 iter = _modList.erase(iter) ;
299 }
300 }
301
302}
303
304
305////////////////////////////////////////////////////////////////////////////////
306
308{
311 delete _ngenVar ;
312 delete _fitParData ;
313 delete _genParData ;
314 delete _fitInitParams ;
315 delete _fitParams ;
316 delete _genInitParams ;
317 delete _genParams ;
318 delete _genContext ;
319 delete _nllVar ;
320 delete _constrPdf ;
321 delete _constrGenContext ;
322}
323
324
325
326////////////////////////////////////////////////////////////////////////////////
327/// Insert given RooMCStudy add-on module to the processing chain
328/// of this MCStudy object
329
331{
332 module.doInitializeInstance(*this) ;
333 _modList.push_back(&module) ;
334}
335
336
337
338////////////////////////////////////////////////////////////////////////////////
339/// Run engine method. Generate and/or fit, according to flags, 'nSamples' samples of 'nEvtPerSample' events.
340/// If keepGenData is set, all generated data sets will be kept in memory and can be accessed
341/// later via genData().
342///
343/// When generating, data sets will be written out in ascii form if the pattern string is supplied
344/// The pattern, which is a template for snprintf, should look something like "data/toymc_%04d.dat"
345/// and should contain one integer field that encodes the sample serial number.
346///
347/// When fitting only, data sets may optionally be read from ascii files, using the same file
348/// pattern.
349///
350
351bool RooMCStudy::run(bool doGenerate, bool DoFit, Int_t nSamples, Int_t nEvtPerSample, bool keepGenData, const char* asciiFilePat)
352{
354 if (_silence) {
357 }
358
359 list<RooAbsMCStudyModule*>::iterator iter ;
360 for (iter=_modList.begin() ; iter!= _modList.end() ; ++iter) {
361 (*iter)->initializeRun(nSamples) ;
362 }
363
364 Int_t prescale = nSamples>100 ? Int_t(nSamples/100) : 1 ;
365
366 while(nSamples--) {
367
368 if (nSamples%prescale==0) {
369 oocoutP(_fitModel,Generation) << "RooMCStudy::run: " ;
370 if (doGenerate) ooccoutI(_fitModel,Generation) << "Generating " ;
371 if (doGenerate && DoFit) ooccoutI(_fitModel,Generation) << "and " ;
372 if (DoFit) ooccoutI(_fitModel,Generation) << "fitting " ;
373 ooccoutP(_fitModel,Generation) << "sample " << nSamples << endl ;
374 }
375
376 _genSample = 0;
377 bool existingData = false ;
378 if (doGenerate) {
379 // Generate sample
380 Int_t nEvt(nEvtPerSample) ;
381
382 // Reset generator parameters to initial values
384
385 // If constraints are present, sample generator values from constraints
386 if (_constrPdf) {
388 _genParams->assign(*tmp->get()) ;
389 delete tmp ;
390 }
391
392 // Save generated parameters if required
393 if (_genParData) {
395 }
396
397 // Call module before-generation hook
398 list<RooAbsMCStudyModule*>::iterator iter2 ;
399 for (iter2=_modList.begin() ; iter2!= _modList.end() ; ++iter2) {
400 (*iter2)->processBeforeGen(nSamples) ;
401 }
402
403 if (_binGenData) {
404
405 // Calculate the number of (extended) events for this run
406 if (_extendedGen) {
408 nEvt = RooRandom::randomGenerator()->Poisson(nEvtPerSample==0?_nExpGen:nEvtPerSample) ;
409 }
410
411 // Binned generation
413
414 } else {
415
416 // Calculate the number of (extended) events for this run
417 if (_extendedGen) {
419 nEvt = RooRandom::randomGenerator()->Poisson(nEvtPerSample==0?_nExpGen:nEvtPerSample) ;
420 }
421
422 // Optional randomization of protodata for this run
424 oocoutI(_fitModel,Generation) << "RooMCStudy: (Re)randomizing event order in prototype dataset (Nevt=" << nEvt << ")" << endl ;
426 _genContext->setProtoDataOrder(newOrder) ;
427 delete[] newOrder ;
428 }
429
430 coutP(Generation) << "RooMCStudy: now generating " << nEvt << " events" << endl ;
431
432 // Actual generation of events
433 if (nEvt>0) {
435 } else {
436 // Make empty dataset
437 _genSample = new RooDataSet("emptySample","emptySample",_dependents) ;
438 }
439 }
440
441
442 //} else if (asciiFilePat && &asciiFilePat) { //warning: the address of 'asciiFilePat' will always evaluate as 'true'
443 } else if (asciiFilePat) {
444
445 // Load sample from ASCII file
446 char asciiFile[1024] ;
447 snprintf(asciiFile,1024,asciiFilePat,nSamples) ;
448 RooArgList depList(_allDependents) ;
449 _genSample = RooDataSet::read(asciiFile,depList,"q") ;
450
451 } else {
452
453 // Load sample from internal list
454 _genSample = (RooDataSet*) _genDataList.At(nSamples) ;
455 existingData = true ;
456 if (!_genSample) {
457 oocoutW(_fitModel,Generation) << "RooMCStudy::run: WARNING: Sample #" << nSamples << " not loaded, skipping" << endl ;
458 continue ;
459 }
460 }
461
462 // Save number of generated events
464
465 // Call module between generation and fitting hook
466 list<RooAbsMCStudyModule*>::iterator iter3 ;
467 for (iter3=_modList.begin() ; iter3!= _modList.end() ; ++iter3) {
468 (*iter3)->processBetweenGenAndFit(nSamples) ;
469 }
470
471 if (DoFit) fitSample(_genSample) ;
472
473 // Call module between generation and fitting hook
474 for (iter3=_modList.begin() ; iter3!= _modList.end() ; ++iter3) {
475 (*iter3)->processAfterFit(nSamples) ;
476 }
477
478 // Optionally write to ascii file
479 if (doGenerate && asciiFilePat && *asciiFilePat) {
480 char asciiFile[1024] ;
481 snprintf(asciiFile,1024,asciiFilePat,nSamples) ;
482 RooDataSet* unbinnedData = dynamic_cast<RooDataSet*>(_genSample) ;
483 if (unbinnedData) {
484 unbinnedData->write(asciiFile) ;
485 } else {
486 coutE(InputArguments) << "RooMCStudy::run(" << GetName() << ") ERROR: ASCII writing of binned datasets is not supported" << endl ;
487 }
488 }
489
490 // Add to list or delete
491 if (!existingData) {
492 if (keepGenData) {
494 } else {
495 delete _genSample ;
496 }
497 }
498 }
499
500 for (iter=_modList.begin() ; iter!= _modList.end() ; ++iter) {
501 RooDataSet* auxData = (*iter)->finalizeRun() ;
502 if (auxData) {
503 _fitParData->merge(auxData) ;
504 }
505 }
506
507 _canAddFitResults = false ;
508
509 if (_genParData) {
510 for(RooAbsArg * arg : *_genParData->get()) {
511 _genParData->changeObservableName(arg->GetName(),Form("%s_gen",arg->GetName())) ;
512 }
513
515 }
516
517 if (DoFit) calcPulls() ;
518
519 if (_silence) {
521 }
522
523 return false ;
524}
525
526
527
528
529
530
531////////////////////////////////////////////////////////////////////////////////
532/// Generate and fit 'nSamples' samples of 'nEvtPerSample' events.
533/// If keepGenData is set, all generated data sets will be kept in memory and can be accessed
534/// later via genData().
535///
536/// Data sets will be written out in ascii form if the pattern string is supplied.
537/// The pattern, which is a template for snprintf, should look something like "data/toymc_%04d.dat"
538/// and should contain one integer field that encodes the sample serial number.
539///
540
541bool RooMCStudy::generateAndFit(Int_t nSamples, Int_t nEvtPerSample, bool keepGenData, const char* asciiFilePat)
542{
543 // Clear any previous data in memory
544 _fitResList.Delete() ; // even though the fit results are owned by gROOT, we still want to scratch them here.
546 _fitParData->reset() ;
547
548 return run(true,true,nSamples,nEvtPerSample,keepGenData,asciiFilePat) ;
549}
550
551
552
553////////////////////////////////////////////////////////////////////////////////
554/// Generate 'nSamples' samples of 'nEvtPerSample' events.
555/// If keepGenData is set, all generated data sets will be kept in memory
556/// and can be accessed later via genData().
557///
558/// Data sets will be written out in ascii form if the pattern string is supplied.
559/// The pattern, which is a template for snprintf, should look something like "data/toymc_%04d.dat"
560/// and should contain one integer field that encodes the sample serial number.
561///
562
563bool RooMCStudy::generate(Int_t nSamples, Int_t nEvtPerSample, bool keepGenData, const char* asciiFilePat)
564{
565 // Clear any previous data in memory
567
568 return run(true,false,nSamples,nEvtPerSample,keepGenData,asciiFilePat) ;
569}
570
571
572
573////////////////////////////////////////////////////////////////////////////////
574/// Fit 'nSamples' datasets, which are read from ASCII files.
575///
576/// The ascii file pattern, which is a template for snprintf, should look something like "data/toymc_%04d.dat"
577/// and should contain one integer field that encodes the sample serial number.
578///
579
580bool RooMCStudy::fit(Int_t nSamples, const char* asciiFilePat)
581{
582 // Clear any previous data in memory
583 _fitResList.Delete() ; // even though the fit results are owned by gROOT, we still want to scratch them here.
584 _fitParData->reset() ;
585
586 return run(false,true,nSamples,0,false,asciiFilePat) ;
587}
588
589
590
591////////////////////////////////////////////////////////////////////////////////
592/// Fit 'nSamples' datasets, as supplied in 'dataSetList'
593///
594
595bool RooMCStudy::fit(Int_t nSamples, TList& dataSetList)
596{
597 // Clear any previous data in memory
598 _fitResList.Delete() ; // even though the fit results are owned by gROOT, we still want to scratch them here.
600 _fitParData->reset() ;
601
602 // Load list of data sets
603 TIterator* iter = dataSetList.MakeIterator() ;
604 RooAbsData* gset ;
605 while((gset=(RooAbsData*)iter->Next())) {
606 _genDataList.Add(gset) ;
607 }
608 delete iter ;
609
610 return run(false,true,nSamples,0,true,0) ;
611}
612
613
614
615////////////////////////////////////////////////////////////////////////////////
616/// Reset all fit parameters to the initial model
617/// parameters at the time of the RooMCStudy constructor
618
620{
622}
623
624
625
626////////////////////////////////////////////////////////////////////////////////
627/// Internal function. Performs actual fit according to specifications
628
630{
631 // Optionally bin dataset before fitting
633 if (_binGenData) {
634 RooArgSet* depList = _fitModel->getObservables(genSample) ;
635 data = new RooDataHist(genSample->GetName(),genSample->GetTitle(),*depList,*genSample) ;
636 delete depList ;
637 } else {
638 data = genSample ;
639 }
640
641 RooCmdArg save = RooFit::Save() ;
643 RooCmdArg plevel = RooFit::PrintLevel(_silence ? -1 : 1) ;
644
645 RooLinkedList fitOptList(_fitOptList) ;
646 fitOptList.Add(&save) ;
647 if (!_projDeps.empty()) {
648 fitOptList.Add(&condo) ;
649 }
650 fitOptList.Add(&plevel) ;
651 RooFitResult* fr = _fitModel->fitTo(*data,fitOptList) ;
652
653 if (_binGenData) delete data ;
654
655 return fr ;
656}
657
658
659
660////////////////////////////////////////////////////////////////////////////////
661/// Redo fit on 'current' toy sample, or if genSample is not nullptr
662/// do fit on given sample instead
663
665{
666 if (!genSample) {
667 genSample = _genSample ;
668 }
669
670 RooFitResult* fr(0) ;
671 if (genSample->sumEntries()>0) {
672 fr = doFit(genSample) ;
673 }
674
675 return fr ;
676}
677
678
679
680////////////////////////////////////////////////////////////////////////////////
681/// Internal method. Fit given dataset with fit model. If fit
682/// converges (TMinuit status code zero) The fit results are appended
683/// to the fit results dataset
684///
685/// If the fit option "r" is supplied, the RooFitResult
686/// objects will always be saved, regardless of the
687/// fit status. RooFitResults objects can be retrieved
688/// later via fitResult().
689///
690
692{
693 // Reset all fit parameters to their initial values
695
696 // Perform actual fit
697 bool ok ;
698 RooFitResult* fr(0) ;
699 if (genSample->sumEntries()>0) {
700 fr = doFit(genSample) ;
701 ok = (fr->status()==0) ;
702 } else {
703 ok = false ;
704 }
705
706 // If fit converged, store parameters and NLL
707 if (ok) {
708 _nllVar->setVal(fr->minNll()) ;
709 RooArgSet tmp(*_fitParams) ;
710 tmp.add(*_nllVar) ;
711 tmp.add(*_ngenVar) ;
712
713 _fitParData->add(tmp) ;
714 }
715
716 // Store fit result if requested by user
717 bool userSaveRequest = false ;
718 if (_fitOptList.GetSize()>0) {
719 if (_fitOptList.FindObject("Save")) userSaveRequest = true ;
720 }
721
722 if (userSaveRequest) {
723 _fitResList.Add(fr) ;
724 } else {
725 delete fr ;
726 }
727
728 return !ok ;
729}
730
731
732
733////////////////////////////////////////////////////////////////////////////////
734/// Utility function to add fit result from external fit to this RooMCStudy
735/// and process its results through the standard RooMCStudy statistics gathering tools.
736/// This function allows users to run the toy MC generation and/or fitting
737/// in a distributed way and to collect and analyze the results in a RooMCStudy
738/// as if they were run locally.
739///
740/// This method is only functional if this RooMCStudy object is cleanm, i.e. it was not used
741/// to generate and/or fit any samples.
742
744{
745 if (!_canAddFitResults) {
746 oocoutE(_fitModel,InputArguments) << "RooMCStudy::addFitResult: ERROR cannot add fit results in current state" << endl ;
747 return true ;
748 }
749
750 // Transfer contents of fit result to fitParams ;
752
753 // If fit converged, store parameters and NLL
754 bool ok = (fr.status()==0) ;
755 if (ok) {
756 _nllVar->setVal(fr.minNll()) ;
757 RooArgSet tmp(*_fitParams) ;
758 tmp.add(*_nllVar) ;
759 tmp.add(*_ngenVar) ;
760 _fitParData->add(tmp) ;
761 }
762
763 // Store fit result if requested by user
764 if (_fitOptList.FindObject("Save")) {
765 _fitResList.Add((TObject*)&fr) ;
766 }
767
768 return false ;
769}
770
771
772
773////////////////////////////////////////////////////////////////////////////////
774/// Calculate the pulls for all fit parameters in
775/// the fit results data set, and add them to that dataset.
776
778{
779 for (auto it = _fitParams->begin(); it != _fitParams->end(); ++it) {
780 const auto par = static_cast<RooRealVar*>(*it);
781 RooErrorVar* err = par->errorVar();
782 _fitParData->addColumn(*err);
783 delete err;
784
785 TString name(par->GetName()), title(par->GetTitle()) ;
786 name.Append("pull") ;
787 title.Append(" Pull") ;
788
789 if (!par->hasError(false)) {
790 coutW(Generation) << "Fit parameter '" << par->GetName() << "' does not have an error."
791 " A pull distribution cannot be generated. This might be caused by the parameter being constant or"
792 " because the fits were not run." << std::endl;
793 continue;
794 }
795
796 // First look in fitParDataset to see if per-experiment generated value has been stored
797 auto genParOrig = static_cast<RooAbsReal*>(_fitParData->get()->find(Form("%s_gen",par->GetName())));
798 if (genParOrig && _perExptGenParams) {
799
800 RooPullVar pull(name,title,*par,*genParOrig) ;
801 _fitParData->addColumn(pull,false) ;
802
803 } else {
804 // If not use fixed generator value
805 genParOrig = static_cast<RooAbsReal*>(_genInitParams->find(par->GetName()));
806
807 if (!genParOrig) {
808 std::size_t index = it - _fitParams->begin();
809 genParOrig = index < _genInitParams->size() ?
810 static_cast<RooAbsReal*>((*_genInitParams)[index]) :
811 nullptr;
812
813 if (genParOrig) {
814 coutW(Generation) << "The fit parameter '" << par->GetName() << "' is not in the model that was used to generate toy data. "
815 "The parameter '" << genParOrig->GetName() << "'=" << genParOrig->getVal() << " was found at the same position in the generator model."
816 " It will be used to compute pulls."
817 "\nIf this is not desired, the parameters of the generator model need to be renamed or reordered." << std::endl;
818 }
819 }
820
821 if (genParOrig) {
822 std::unique_ptr<RooAbsReal> genPar(static_cast<RooAbsReal*>(genParOrig->Clone("truth")));
823 RooPullVar pull(name,title,*par,*genPar);
824
825 _fitParData->addColumn(pull,false) ;
826 } else {
827 coutE(Generation) << "Cannot generate pull distribution for the fit parameter '" << par->GetName() << "'."
828 "\nNo similar parameter was found in the set of parameters that were used to generate toy data." << std::endl;
829 }
830 }
831 }
832}
833
834
835
836
837////////////////////////////////////////////////////////////////////////////////
838/// Return a RooDataSet containing the post-fit parameters of each toy cycle.
839/// This dataset also contains any additional output that was generated
840/// by study modules that were added to this RooMCStudy.
841/// By default, the two following variables are added (apart from fit parameters):
842/// - NLL: The value of the negative log-likelihood for each run.
843/// - ngen: Number of events generated for each run.
845{
846 if (_canAddFitResults) {
847 calcPulls() ;
848 _canAddFitResults = false ;
849 }
850
851 return *_fitParData ;
852}
853
854
855
856////////////////////////////////////////////////////////////////////////////////
857/// Return an argset with the fit parameters for the given sample number
858///
859/// NB: The fit parameters are only stored for successfull fits,
860/// thus the maximum sampleNum can be less that the number
861/// of generated samples and if so, the indeces will
862/// be out of synch with genData() and fitResult()
863
864const RooArgSet* RooMCStudy::fitParams(Int_t sampleNum) const
865{
866 // Check if sampleNum is in range
867 if (sampleNum<0 || sampleNum>=_fitParData->numEntries()) {
868 oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitParams: ERROR, invalid sample number: " << sampleNum << endl ;
869 return 0 ;
870 }
871
872 return _fitParData->get(sampleNum) ;
873}
874
875
876
877////////////////////////////////////////////////////////////////////////////////
878/// Return the RooFitResult of the fit with the given run number.
879///
880/// \note Fit results are not saved by default. This requires passing `FitOptions(Save(), ...)`
881/// to the constructor.
883{
884 // Check if sampleNum is in range
885 if (sampleNum<0 || sampleNum>=_fitResList.GetSize()) {
886 oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitResult: ERROR, invalid sample number: " << sampleNum << endl ;
887 return 0 ;
888 }
889
890 // Retrieve fit result object
891 const RooFitResult* fr = (RooFitResult*) _fitResList.At(sampleNum) ;
892 if (fr) {
893 return fr ;
894 } else {
895 oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitResult: ERROR, no fit result saved for sample "
896 << sampleNum << ", did you use the 'r; fit option?" << endl ;
897 }
898 return 0 ;
899}
900
901
902
903////////////////////////////////////////////////////////////////////////////////
904/// Return the given generated dataset. This method will only return datasets
905/// if during the run cycle it was indicated that generator data should be saved.
906
908{
909 // Check that generated data was saved
910 if (_genDataList.GetSize()==0) {
911 oocoutE(_fitModel,InputArguments) << "RooMCStudy::genData() ERROR, generated data was not saved" << endl ;
912 return 0 ;
913 }
914
915 // Check if sampleNum is in range
916 if (sampleNum<0 || sampleNum>=_genDataList.GetSize()) {
917 oocoutE(_fitModel,InputArguments) << "RooMCStudy::genData() ERROR, invalid sample number: " << sampleNum << endl ;
918 return 0 ;
919 }
920
921 return (RooAbsData*) _genDataList.At(sampleNum) ;
922}
923
924
925
926////////////////////////////////////////////////////////////////////////////////
927/// Plot the distribution of fitted values of a parameter. The parameter shown is the one from which the RooPlot
928/// was created, e.g.
929///
930/// RooPlot* frame = param.frame(100,-10,10) ;
931/// mcstudy.paramOn(frame,LineStyle(kDashed)) ;
932///
933/// Any named arguments passed to plotParamOn() are forwarded to the underlying plotOn() call
934
935RooPlot* RooMCStudy::plotParamOn(RooPlot* frame, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
936 const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
937{
938 _fitParData->plotOn(frame,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
939 return frame ;
940}
941
942
943
944////////////////////////////////////////////////////////////////////////////////
945/// Plot the distribution of the fitted value of the given parameter on a newly created frame.
946///
947/// <table>
948/// <tr><th> Optional arguments <th>
949/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
950/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
951/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
952/// for list of allowed arguments
953/// </table>
954/// If no frame specifications are given, the AutoRange() feature will be used to set the range
955/// Any other named argument is passed to the RooAbsData::plotOn() call. See that function for allowed options
956
957RooPlot* RooMCStudy::plotParam(const char* paramName, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
958 const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
959{
960
961 // Find parameter in fitParDataSet
962 RooRealVar* param = static_cast<RooRealVar*>(_fitParData->get()->find(paramName)) ;
963 if (!param) {
964 oocoutE(_fitModel,InputArguments) << "RooMCStudy::plotParam: ERROR: no parameter defined with name " << paramName << endl ;
965 return 0 ;
966 }
967
968 // Forward to implementation below
969 return plotParam(*param,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
970}
971
972
973
974////////////////////////////////////////////////////////////////////////////////
975/// Plot the distribution of the fitted value of the given parameter on a newly created frame.
976/// \copydetails RooMCStudy::plotParam(const char* paramName, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
977/// const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
978
979RooPlot* RooMCStudy::plotParam(const RooRealVar& param, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
980 const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
981{
982 // Stuff all arguments in a list
983 RooLinkedList cmdList;
984 cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
985 cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
986 cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
987 cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
988
989 RooPlot* frame = makeFrameAndPlotCmd(param, cmdList) ;
990 if (frame) {
991 _fitParData->plotOn(frame, cmdList) ;
992 }
993
994 return frame ;
995}
996
997
998
999////////////////////////////////////////////////////////////////////////////////
1000/// Plot the distribution of the -log(L) values on a newly created frame.
1001///
1002/// <table>
1003/// <tr><th> Optional arguments <th>
1004/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
1005/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
1006/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
1007/// for list of allowed arguments
1008/// </table>
1009///
1010/// If no frame specifications are given, the AutoRange() feature will be used to set the range.
1011/// Any other named argument is passed to the RooAbsData::plotOn() call. See that function for allowed options
1012
1014 const RooCmdArg& arg3, const RooCmdArg& arg4,
1015 const RooCmdArg& arg5, const RooCmdArg& arg6,
1016 const RooCmdArg& arg7, const RooCmdArg& arg8)
1017{
1018 return plotParam(*_nllVar,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
1019}
1020
1021
1022
1023////////////////////////////////////////////////////////////////////////////////
1024/// Plot the distribution of the fit errors for the specified parameter on a newly created frame.
1025///
1026/// <table>
1027/// <tr><th> Optional arguments <th>
1028/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
1029/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
1030/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
1031/// for list of allowed arguments
1032/// </table>
1033///
1034/// If no frame specifications are given, the AutoRange() feature will be used to set a default range.
1035/// Any other named argument is passed to the RooAbsData::plotOn() call. See that function for allowed options.
1036
1037RooPlot* RooMCStudy::plotError(const RooRealVar& param, const RooCmdArg& arg1, const RooCmdArg& arg2,
1038 const RooCmdArg& arg3, const RooCmdArg& arg4,
1039 const RooCmdArg& arg5, const RooCmdArg& arg6,
1040 const RooCmdArg& arg7, const RooCmdArg& arg8)
1041{
1042 if (_canAddFitResults) {
1043 calcPulls() ;
1044 _canAddFitResults=false ;
1045 }
1046
1047 RooErrorVar* evar = param.errorVar() ;
1048 RooRealVar* evar_rrv = static_cast<RooRealVar*>(evar->createFundamental()) ;
1049 RooPlot* frame = plotParam(*evar_rrv,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
1050 delete evar_rrv ;
1051 delete evar ;
1052 return frame ;
1053}
1054
1055
1056
1057////////////////////////////////////////////////////////////////////////////////
1058/// Plot the distribution of pull values for the specified parameter on a newly created frame. If asymmetric
1059/// errors are calculated in the fit (by MINOS) those will be used in the pull calculation.
1060///
1061/// If the parameters of the models for generation and fit differ, simple heuristics are used to find the
1062/// corresponding parameters:
1063/// - Parameters have the same name: They will be used to compute pulls.
1064/// - Parameters have different names: The position of the fit parameter in the set of fit parameters will be
1065/// computed. The parameter at the same position in the set of generator parameters will be used.
1066///
1067/// Further options:
1068/// <table>
1069/// <tr><th> Arguments <th> Effect
1070/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
1071/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
1072/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
1073/// for list of allowed arguments
1074/// <tr><td> FitGauss(bool flag) <td> Add a gaussian fit to the frame
1075/// </table>
1076///
1077/// If no frame specifications are given, the AutoSymRange() feature will be used to set a default range.
1078/// Any other named argument is passed to the RooAbsData::plotOn(). See that function for allowed options.
1079
1080RooPlot* RooMCStudy::plotPull(const RooRealVar& param, const RooCmdArg& arg1, const RooCmdArg& arg2,
1081 const RooCmdArg& arg3, const RooCmdArg& arg4,
1082 const RooCmdArg& arg5, const RooCmdArg& arg6,
1083 const RooCmdArg& arg7, const RooCmdArg& arg8)
1084{
1085 // Stuff all arguments in a list
1086 RooLinkedList cmdList;
1087 cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
1088 cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
1089 cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
1090 cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
1091
1092 TString name(param.GetName()), title(param.GetTitle()) ;
1093 name.Append("pull") ; title.Append(" Pull") ;
1094 RooRealVar pvar(name,title,-100,100) ;
1095 pvar.setBins(100) ;
1096
1097
1098 RooPlot* frame = makeFrameAndPlotCmd(pvar, cmdList, true) ;
1099 if (frame) {
1100
1101 // Pick up optonal FitGauss command from list
1102 RooCmdConfig pc(Form("RooMCStudy::plotPull(%s)",_genModel->GetName())) ;
1103 pc.defineInt("fitGauss","FitGauss",0,0) ;
1104 pc.allowUndefined() ;
1105 pc.process(cmdList) ;
1106 bool fitGauss=pc.getInt("fitGauss") ;
1107
1108 // Pass stripped command list to plotOn()
1109 pc.stripCmdList(cmdList,"FitGauss") ;
1110 const bool success = _fitParData->plotOn(frame,cmdList) ;
1111
1112 if (!success) {
1113 coutF(Plotting) << "No pull distribution for the parameter '" << param.GetName() << "'. Check logs for errors." << std::endl;
1114 return frame;
1115 }
1116
1117 // Add Gaussian fit if requested
1118 if (fitGauss) {
1119 RooRealVar pullMean("pullMean","Mean of pull",0,-10,10) ;
1120 RooRealVar pullSigma("pullSigma","Width of pull",1,0.1,5) ;
1121 RooGenericPdf pullGauss("pullGauss","Gaussian of pull",
1122 "exp(-0.5*(@0-@1)*(@0-@1)/(@2*@2))",
1123 RooArgSet(pvar,pullMean,pullSigma)) ;
1125 pullGauss.plotOn(frame) ;
1126 pullGauss.paramOn(frame,_fitParData) ;
1127 }
1128 }
1129 return frame;
1130}
1131
1132
1133
1134////////////////////////////////////////////////////////////////////////////////
1135/// Internal function. Construct RooPlot from given parameter and modify the list of named
1136/// arguments 'cmdList' to only contain the plot arguments that should be forwarded to
1137/// RooAbsData::plotOn()
1138
1139RooPlot* RooMCStudy::makeFrameAndPlotCmd(const RooRealVar& param, RooLinkedList& cmdList, bool symRange) const
1140{
1141 // Select the frame-specific commands
1142 RooCmdConfig pc(Form("RooMCStudy::plotParam(%s)",_genModel->GetName())) ;
1143 pc.defineInt("nbins","Bins",0,0) ;
1144 pc.defineDouble("xlo","Range",0,0) ;
1145 pc.defineDouble("xhi","Range",1,0) ;
1146 pc.defineInt("dummy","FrameArgs",0,0) ;
1147 pc.defineMutex("Bins","FrameArgs") ;
1148 pc.defineMutex("Range","FrameArgs") ;
1149
1150 // Process and check varargs
1151 pc.allowUndefined() ;
1152 pc.process(cmdList) ;
1153 if (!pc.ok(true)) {
1154 return 0 ;
1155 }
1156
1157 // Make frame according to specs
1158 Int_t nbins = pc.getInt("nbins") ;
1159 double xlo = pc.getDouble("xlo") ;
1160 double xhi = pc.getDouble("xhi") ;
1161 RooPlot* frame ;
1162
1163 if (pc.hasProcessed("FrameArgs")) {
1164 // Explicit frame arguments are given, pass them on
1165 RooCmdArg* frameArg = static_cast<RooCmdArg*>(cmdList.FindObject("FrameArgs")) ;
1166 frame = param.frame(frameArg->subArgs()) ;
1167 } else {
1168 // FrameBins, FrameRange or none are given, build custom frame command list
1169 RooCmdArg bins = RooFit::Bins(nbins) ;
1170 RooCmdArg range = RooFit::Range(xlo,xhi) ;
1172 RooLinkedList frameCmdList ;
1173
1174 if (pc.hasProcessed("Bins")) frameCmdList.Add(&bins) ;
1175 if (pc.hasProcessed("Range")) {
1176 frameCmdList.Add(&range) ;
1177 } else {
1178 frameCmdList.Add(&autor) ;
1179 }
1180 frame = param.frame(frameCmdList) ;
1181 }
1182
1183 // Filter frame command from list and pass on to plotOn()
1184 pc.stripCmdList(cmdList,"FrameArgs,Bins,Range") ;
1185
1186 return frame ;
1187}
1188
1189
1190
1191////////////////////////////////////////////////////////////////////////////////
1192/// Create a RooPlot of the -log(L) distribution in the range lo-hi
1193/// with 'nBins' bins
1194
1195RooPlot* RooMCStudy::plotNLL(double lo, double hi, Int_t nBins)
1196{
1197 RooPlot* frame = _nllVar->frame(lo,hi,nBins) ;
1198
1199 _fitParData->plotOn(frame) ;
1200 return frame ;
1201}
1202
1203
1204
1205////////////////////////////////////////////////////////////////////////////////
1206/// Create a RooPlot of the distribution of the fitted errors of the given parameter.
1207/// The frame is created with a range [lo,hi] and plotted data will be binned in 'nbins' bins
1208
1209RooPlot* RooMCStudy::plotError(const RooRealVar& param, double lo, double hi, Int_t nbins)
1210{
1211 if (_canAddFitResults) {
1212 calcPulls() ;
1213 _canAddFitResults=false ;
1214 }
1215
1216 RooErrorVar* evar = param.errorVar() ;
1217 RooPlot* frame = evar->frame(lo,hi,nbins) ;
1218 _fitParData->plotOn(frame) ;
1219
1220 delete evar ;
1221 return frame ;
1222}
1223
1224
1225
1226////////////////////////////////////////////////////////////////////////////////
1227/// Create a RooPlot of the pull distribution for the given
1228/// parameter. The range lo-hi is plotted in nbins. If fitGauss is
1229/// set, an unbinned ML fit of the distribution to a Gaussian p.d.f
1230/// is performed. The fit result is overlaid on the returned RooPlot
1231/// and a box with the fitted mean and sigma is added.
1232///
1233/// If the parameters of the models for generation and fit differ, simple heuristics are used to find the
1234/// corresponding parameters:
1235/// - Parameters have the same name: They will be used to compute pulls.
1236/// - Parameters have different names: The position of the fit parameter in the set of fit parameters will be
1237/// computed. The parameter at the same position in the set of generator parameters will be used.
1238
1239RooPlot* RooMCStudy::plotPull(const RooRealVar& param, double lo, double hi, Int_t nbins, bool fitGauss)
1240{
1241 if (_canAddFitResults) {
1242 calcPulls() ;
1243 _canAddFitResults=false ;
1244 }
1245
1246
1247 TString name(param.GetName()), title(param.GetTitle()) ;
1248 name.Append("pull") ; title.Append(" Pull") ;
1249 RooRealVar pvar(name,title,lo,hi) ;
1250 pvar.setBins(nbins) ;
1251
1252 RooPlot* frame = pvar.frame() ;
1253 const bool success = _fitParData->plotOn(frame);
1254
1255 if (!success) {
1256 coutF(Plotting) << "No pull distribution for the parameter '" << param.GetName() << "'. Check logs for errors." << std::endl;
1257 return frame;
1258 }
1259
1260 if (fitGauss) {
1261 RooRealVar pullMean("pullMean","Mean of pull",0,lo,hi) ;
1262 RooRealVar pullSigma("pullSigma","Width of pull",1,0,5) ;
1263 RooGenericPdf pullGauss("pullGauss","Gaussian of pull",
1264 "exp(-0.5*(@0-@1)*(@0-@1)/(@2*@2))",
1265 RooArgSet(pvar,pullMean,pullSigma)) ;
1267 pullGauss.plotOn(frame) ;
1268 pullGauss.paramOn(frame,_fitParData) ;
1269 }
1270
1271 return frame ;
1272}
1273
1274
1275////////////////////////////////////////////////////////////////////////////////
1276/// If one of the TObject we have a referenced to is deleted, remove the
1277/// reference.
1278
1280{
1284 if (_ngenVar == obj) _ngenVar = nullptr;
1285
1287 if (_fitParData == obj) _fitParData = nullptr;
1288
1290 if (_genParData == obj) _genParData = nullptr;
1291}
1292
#define coutI(a)
Definition: RooMsgService.h:34
#define coutP(a)
Definition: RooMsgService.h:35
#define oocoutW(o, a)
Definition: RooMsgService.h:51
#define coutW(a)
Definition: RooMsgService.h:36
#define coutF(a)
Definition: RooMsgService.h:38
#define oocoutE(o, a)
Definition: RooMsgService.h:52
#define oocoutI(o, a)
Definition: RooMsgService.h:49
#define coutE(a)
Definition: RooMsgService.h:37
#define ooccoutI(o, a)
Definition: RooMsgService.h:57
#define ooccoutP(o, a)
Definition: RooMsgService.h:58
#define oocoutP(o, a)
Definition: RooMsgService.h:50
int Int_t
Definition: RtypesCore.h:45
#define ClassImp(name)
Definition: Rtypes.h:375
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
char name[80]
Definition: TGX11.cxx:110
#define hi
Definition: THbookFile.cxx:128
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition: TString.cxx:2447
#define snprintf
Definition: civetweb.c:1540
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition: RooAbsArg.h:72
RooArgSet * getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
Definition: RooAbsArg.h:312
RooArgSet * getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
Definition: RooAbsArg.cxx:565
bool empty() const
Int_t getSize() const
Return the number of elements in the collection.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
void setAttribAll(const Text_t *name, bool value=true)
Set given attribute in each element of the collection by calling each elements setAttribute() functio...
const_iterator end() const
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
Storage_t::size_type size() const
const_iterator begin() const
RooAbsArg * find(const char *name) const
Find object with given name in list.
RooAbsData is the common abstract base class for binned and unbinned datasets.
Definition: RooAbsData.h:62
virtual double sumEntries() const =0
Return effective number of entries in dataset, i.e., sum all weights.
virtual void reset()
Definition: RooAbsData.cxx:386
virtual bool changeObservableName(const char *from, const char *to)
Definition: RooAbsData.cxx:359
void RecursiveRemove(TObject *obj) override
If one of the TObject we have a referenced to is deleted, remove the reference.
virtual Int_t numEntries() const
Return number of entries in dataset, i.e., count unweighted entries.
Definition: RooAbsData.cxx:379
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
Definition: RooAbsData.cxx:607
virtual void attach(const RooArgSet &params)
Interface to attach given parameters to object in this context.
virtual RooDataSet * generate(double nEvents=0, bool skipInit=false, bool extendedMode=false)
Generate the specified number of events with nEvents>0 and and return a dataset containing the genera...
virtual void setProtoDataOrder(Int_t *lut)
Set the traversal order of prototype data to that in the lookup tables passed as argument.
RooAbsMCStudyModule is a base class for add-on modules to RooMCStudy that can perform additional calc...
bool doInitializeInstance(RooMCStudy &)
Initializer method called upon attachement to given RooMCStudy object.
virtual double expectedEvents(const RooArgSet *nset) const
Return expected number of events to be used in calculation of extended likelihood.
Definition: RooAbsPdf.cxx:3215
Int_t * randomizeProtoOrder(Int_t nProto, Int_t nGen, bool resample=false) const
Return lookup table with randomized order for nProto prototype events.
Definition: RooAbsPdf.cxx:2249
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:1458
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:3063
virtual RooDataHist * generateBinned(const RooArgSet &whatVars, double nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2=RooCmdArg::none(), const RooCmdArg &arg3=RooCmdArg::none(), const RooCmdArg &arg4=RooCmdArg::none(), const RooCmdArg &arg5=RooCmdArg::none()) const
As RooAbsPdf::generateBinned(const RooArgSet&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,...
Definition: RooAbsPdf.h:112
virtual RooArgSet * getAllConstraints(const RooArgSet &observables, RooArgSet &constrainedParams, bool stripDisconnected=true) const
This helper function finds and collects all constraints terms of all component p.d....
Definition: RooAbsPdf.cxx:3394
virtual RooAbsGenContext * genContext(const RooArgSet &vars, const RooDataSet *prototype=0, const RooArgSet *auxProto=0, bool verbose=false) const
Interface function to create a generator context from a p.d.f.
Definition: RooAbsPdf.cxx:1887
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 override
Helper calling plotOn(RooPlot*, RooLinkedList&) const.
Definition: RooAbsPdf.h:126
RooPlot * frame(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 a new RooPlot on the heap with a drawing frame initialized for this object,...
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition: RooAbsReal.h:64
RooAbsArg * createFundamental(const char *newname=0) const override
Create a RooRealVar fundamental object with our properties.
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgList.h:22
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:57
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition: RooArgSet.h:180
RooCmdArg is a named container for two doubles, two integers two object points and three string point...
Definition: RooCmdArg.h:26
RooLinkedList const & subArgs() const
Return list of sub-arguments in this RooCmdArg.
Definition: RooCmdArg.h:52
TObject * Clone(const char *newName=0) const override
Make a clone of an object using the Streamer facility.
Definition: RooCmdArg.h:57
Class RooCmdConfig is a configurable parser for RooCmdArg named arguments.
Definition: RooCmdConfig.h:31
The RooDataHist is a container class to hold N-dimensional binned data.
Definition: RooDataHist.h:45
RooDataSet is a container class to hold unbinned data.
Definition: RooDataSet.h:55
const RooArgSet * get(Int_t index) const override
Return RooArgSet with coordinates of event 'index'.
virtual RooAbsArg * addColumn(RooAbsArg &var, bool adjustRange=true)
Add a column with the values of the given (function) argument to this dataset.
bool write(const char *filename) const
Write the contents of this dataset to an ASCII file with the specified name.
static RooDataSet * read(const char *filename, const RooArgList &variables, const char *opts="", const char *commonPath="", const char *indexCatName=0)
Read data from a text file and create a dataset from it.
bool merge(RooDataSet *data1, RooDataSet *data2=0, RooDataSet *data3=0, RooDataSet *data4=0, RooDataSet *data5=0, RooDataSet *data6=0)
void add(const RooArgSet &row, double weight=1.0, double weightError=0) override
Add one ore more rows of data.
RooErrorVar is an auxilary class that represents the error of a RooRealVar as a seperate object.
Definition: RooErrorVar.h:28
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Definition: RooFitResult.h:40
const RooArgList & floatParsFinal() const
Return list of floating parameters after fit.
Definition: RooFitResult.h:111
Int_t status() const
Return MINUIT status code.
Definition: RooFitResult.h:78
double minNll() const
Return minimized -log(L) value.
Definition: RooFitResult.h:99
RooGenericPdf is a concrete implementation of a probability density function, which takes a RooArgLis...
Definition: RooGenericPdf.h:25
RooLinkedList is an collection class for internal use, storing a collection of RooAbsArg pointers in ...
Definition: RooLinkedList.h:38
Int_t GetSize() const
Definition: RooLinkedList.h:63
TObject * At(int index) const
Return object stored in sequential position given by index.
void RecursiveRemove(TObject *obj) override
If one of the TObject we have a referenced to is deleted, remove the reference.
void Delete(Option_t *o=0) override
Remove all elements in collection and delete all elements NB: Collection does not own elements,...
virtual void Add(TObject *arg)
Definition: RooLinkedList.h:67
TObject * FindObject(const char *name) const override
Return pointer to obejct with given name.
RooMCStudy is a helper class to facilitate Monte Carlo studies such as 'goodness-of-fit' studies,...
Definition: RooMCStudy.h:32
bool addFitResult(const RooFitResult &fr)
Utility function to add fit result from external fit to this RooMCStudy and process its results throu...
Definition: RooMCStudy.cxx:743
RooAbsData * _genSample
Currently generated sample.
Definition: RooMCStudy.h:107
RooPlot * makeFrameAndPlotCmd(const RooRealVar &param, RooLinkedList &cmdList, bool symRange=false) const
Internal function.
RooArgSet _projDeps
List of projected dependents in fit.
Definition: RooMCStudy.h:113
RooPlot * plotNLL(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())
Plot the distribution of the -log(L) values on a newly created frame.
const RooArgSet * fitParams(Int_t sampleNum) const
Return an argset with the fit parameters for the given sample number.
Definition: RooMCStudy.cxx:864
bool generateAndFit(Int_t nSamples, Int_t nEvtPerSample=0, bool keepGenData=false, const char *asciiFilePat=0)
Generate and fit 'nSamples' samples of 'nEvtPerSample' events.
Definition: RooMCStudy.cxx:541
void calcPulls()
Calculate the pulls for all fit parameters in the fit results data set, and add them to that dataset.
Definition: RooMCStudy.cxx:777
~RooMCStudy() override
Definition: RooMCStudy.cxx:307
RooArgSet _dependents
List of dependents.
Definition: RooMCStudy.h:118
RooMCStudy(const RooAbsPdf &model, const RooArgSet &observables, 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())
Construct Monte Carlo Study Manager.
Definition: RooMCStudy.cxx:109
bool _verboseGen
Verbose generation?
Definition: RooMCStudy.h:137
std::list< RooAbsMCStudyModule * > _modList
List of additional study modules ;.
Definition: RooMCStudy.h:141
RooAbsGenContext * _constrGenContext
Generator context for constraints p.d.f.
Definition: RooMCStudy.h:116
RooFitResult * refit(RooAbsData *genSample=0)
Redo fit on 'current' toy sample, or if genSample is not nullptr do fit on given sample instead.
Definition: RooMCStudy.cxx:664
TList _fitResList
Definition: RooMCStudy.h:127
bool generate(Int_t nSamples, Int_t nEvtPerSample=0, bool keepGenData=false, const char *asciiFilePat=0)
Generate 'nSamples' samples of 'nEvtPerSample' events.
Definition: RooMCStudy.cxx:563
double _nExpGen
Definition: RooMCStudy.h:133
bool fitSample(RooAbsData *genSample)
Internal method.
Definition: RooMCStudy.cxx:691
RooDataSet * _genParData
Definition: RooMCStudy.h:128
bool _extendedGen
Definition: RooMCStudy.h:131
const RooDataSet * _genProtoData
Generator prototype data set.
Definition: RooMCStudy.h:112
bool _canAddFitResults
Allow adding of external fit results?
Definition: RooMCStudy.h:136
const RooFitResult * fitResult(Int_t sampleNum) const
Return the RooFitResult of the fit with the given run number.
Definition: RooMCStudy.cxx:882
bool _perExptGenParams
Do generation parameter change per event?
Definition: RooMCStudy.h:138
bool _binGenData
Definition: RooMCStudy.h:132
bool _silence
Silent running mode?
Definition: RooMCStudy.h:139
RooPlot * plotError(const RooRealVar &param, 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())
Plot the distribution of the fit errors for the specified parameter on a newly created frame.
RooAbsGenContext * _genContext
Generator context.
Definition: RooMCStudy.h:109
RooAbsPdf * _constrPdf
Constraints p.d.f.
Definition: RooMCStudy.h:115
RooArgSet * _fitInitParams
List of initial values of fit parameters.
Definition: RooMCStudy.h:121
RooAbsData * genData(Int_t sampleNum) const
Return the given generated dataset.
Definition: RooMCStudy.cxx:907
RooArgSet * _genInitParams
List of original generator parameters.
Definition: RooMCStudy.h:110
void RecursiveRemove(TObject *obj) override
If one of the TObject we have a referenced to is deleted, remove the reference.
RooAbsPdf * _genModel
Generator model.
Definition: RooMCStudy.h:108
const RooDataSet & fitParDataSet()
Return a RooDataSet containing the post-fit parameters of each toy cycle.
Definition: RooMCStudy.cxx:844
RooPlot * plotParamOn(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())
Plot the distribution of fitted values of a parameter.
Definition: RooMCStudy.cxx:935
RooLinkedList _fitOptList
Definition: RooMCStudy.h:130
RooArgSet _allDependents
List of generate + prototype dependents.
Definition: RooMCStudy.h:119
RooArgSet * _fitParams
List of actual fit parameters.
Definition: RooMCStudy.h:122
bool run(bool generate, bool fit, Int_t nSamples, Int_t nEvtPerSample, bool keepGenData, const char *asciiFilePat)
Run engine method.
Definition: RooMCStudy.cxx:351
void resetFitParams()
Reset all fit parameters to the initial model parameters at the time of the RooMCStudy constructor.
Definition: RooMCStudy.cxx:619
RooArgSet * _genParams
List of actual generator parameters.
Definition: RooMCStudy.h:111
RooAbsPdf * _fitModel
Fit model.
Definition: RooMCStudy.h:120
bool fit(Int_t nSamples, const char *asciiFilePat)
Fit 'nSamples' datasets, which are read from ASCII files.
Definition: RooMCStudy.cxx:580
RooRealVar * _ngenVar
Definition: RooMCStudy.h:124
TList _genDataList
Definition: RooMCStudy.h:126
bool _randProto
Definition: RooMCStudy.h:134
RooPlot * plotParam(const RooRealVar &param, 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())
Plot the distribution of the fitted value of the given parameter on a newly created frame.
Definition: RooMCStudy.cxx:979
void addModule(RooAbsMCStudyModule &module)
Insert given RooMCStudy add-on module to the processing chain of this MCStudy object.
Definition: RooMCStudy.cxx:330
RooFitResult * doFit(RooAbsData *genSample)
Internal function. Performs actual fit according to specifications.
Definition: RooMCStudy.cxx:629
RooRealVar * _nllVar
Definition: RooMCStudy.h:123
RooPlot * plotPull(const RooRealVar &param, 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())
Plot the distribution of pull values for the specified parameter on a newly created frame.
RooDataSet * _fitParData
Definition: RooMCStudy.h:129
static RooMsgService & instance()
Return reference to singleton instance.
void setGlobalKillBelow(RooFit::MsgLevel level)
RooFit::MsgLevel globalKillBelow() const
A RooPlot is a plot frame and a container for graphics objects within that frame.
Definition: RooPlot.h:43
RooProdPdf is an efficient implementation of a product of PDFs of the form.
Definition: RooProdPdf.h:33
RooPullVar represents the pull of a measurement w.r.t.
Definition: RooPullVar.h:24
static TRandom * randomGenerator()
Return a pointer to a singleton random-number generator implementation.
Definition: RooRandom.cxx:51
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:40
void setVal(double value) override
Set value of variable to 'value'.
Definition: RooRealVar.cxx:281
void setBins(Int_t nBins, const char *name=0)
Create a uniform binning under name 'name' for this variable.
Definition: RooRealVar.cxx:434
RooErrorVar * errorVar() const
Return a RooAbsRealLValue representing the error associated with this variable.
Definition: RooRealVar.cxx:317
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
Definition: TCollection.h:184
Iterator abstract base class.
Definition: TIterator.h:30
virtual TObject * Next()=0
A doubly linked list.
Definition: TList.h:38
void RecursiveRemove(TObject *obj) override
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition: TList.cxx:764
void Add(TObject *obj) override
Definition: TList.h:81
TIterator * MakeIterator(Bool_t dir=kIterForward) const override
Return a list iterator.
Definition: TList.cxx:722
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition: TList.cxx:470
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition: TList.cxx:357
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:29
const char * GetName() const override
Returns name of object.
Definition: TNamed.h:47
const char * GetTitle() const override
Returns title of object.
Definition: TNamed.h:48
Mother of all ROOT objects.
Definition: TObject.h:37
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:402
Basic string class.
Definition: TString.h:136
const char * Data() const
Definition: TString.h:369
TString & Append(const char *cs)
Definition: TString.h:564
RooCmdArg AutoRange(const RooAbsData &data, double marginFactor=0.1)
RooCmdArg AutoSymRange(const RooAbsData &data, double marginFactor=0.1)
RooCmdArg Bins(Int_t nbin)
RooCmdArg Constrain(const RooArgSet &params)
RooCmdArg Save(bool flag=true)
RooCmdArg ExternalConstraints(const RooArgSet &constraintPdfs)
RooCmdArg Minos(bool flag=true)
RooCmdArg PrintLevel(Int_t code)
RooCmdArg ConditionalObservables(Args_t &&... argsOrArgSet)
Create a RooCmdArg to declare conditional observables.
RooCmdArg Range(const char *rangeName, bool adjustNorm=true)
MsgLevel
Verbosity level for RooMsgService::StreamConfig in RooMsgService.
Definition: RooGlobalFunc.h:61
@ Generation
Definition: RooGlobalFunc.h:63
@ InputArguments
Definition: RooGlobalFunc.h:64
static constexpr double pc