Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Loading...
Searching...
No Matches
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
22Helper 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
54#include <RooMCStudy.h>
55
56#include <RooAbsMCStudyModule.h>
57#include <RooAbsPdf.h>
58#include <RooArgList.h>
59#include <RooCmdConfig.h>
60#include <RooDataHist.h>
61#include <RooDataSet.h>
62#include <RooErrorVar.h>
63#include <RooFitResult.h>
64#include <RooFormulaVar.h>
65#include <RooGenContext.h>
66#include <RooGlobalFunc.h>
67#include <RooMsgService.h>
68#include <RooPlot.h>
69#include <RooProdPdf.h>
70#include <RooPullVar.h>
71#include <RooRandom.h>
72#include <RooRealVar.h>
73#include <RooWorkspace.h>
74
75#include <snprintf.h>
76#include <iostream>
77
78
79/**
80Construct Monte Carlo Study Manager. This class automates generating data from a given PDF,
81fitting the PDF to data and accumulating the fit statistics.
82
83\param[in] model The PDF to be studied
84\param[in] observables The variables of the PDF to be considered observables
85\param[in] arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8 Optional arguments according to table below.
86
87<table>
88<tr><th> Optional arguments <th>
89<tr><td> Silence() <td> Suppress all RooFit messages during running below PROGRESS level
90<tr><td> FitModel(const RooAbsPdf&) <td> The PDF for fitting if it is different from the PDF for generating.
91<tr><td> ConditionalObservables(const RooArgSet& set) <td> The set of observables that the PDF should _not_ be normalized over
92<tr><td> Binned(bool flag) <td> Bin the dataset before fitting it. Speeds up fitting of large data samples
93<tr><td> FitOptions(....) <td> Options to be used for fitting. All named arguments inside FitOptions() are passed to RooAbsPdf::fitTo().
94 `Save()` is especially interesting to be able to retrieve fit results of each run using fitResult().
95<tr><td> Verbose(bool flag) <td> Activate informational messages in event generation phase
96<tr><td> Extended(bool flag) <td> Determine number of events for each sample anew from a Poisson distribution
97<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.
98<tr><td> ProtoData(const RooDataSet&, bool randOrder)
99 <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
100 cycle to protect against systematic biases if the number of generated events does not exactly match the number of events in the prototype dataset
101 at the cost of reduced precision with mu equal to the specified number of events
102</table>
103*/
104RooMCStudy::RooMCStudy(const RooAbsPdf& model, const RooArgSet& observables,
105 const RooCmdArg& arg1, const RooCmdArg& arg2,
106 const RooCmdArg& arg3,const RooCmdArg& arg4,const RooCmdArg& arg5,
107 const RooCmdArg& arg6,const RooCmdArg& arg7,const RooCmdArg& arg8) : TNamed("mcstudy","mcstudy")
108
109{
110 // Stuff all arguments in a list
112 cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
113 cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
114 cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
115 cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
116
117 // Select the pdf-specific commands
118 RooCmdConfig pc("RooMCStudy::RooMCStudy(" + std::string(model.GetName()) + ")");
119
120 pc.defineObject("fitModel","FitModel",0,nullptr) ;
121 pc.defineSet("condObs","ProjectedObservables",0,nullptr) ;
122 pc.defineObject("protoData","PrototypeData",0,nullptr) ;
123 pc.defineSet("cPars","Constrain",0,nullptr) ;
124 pc.defineSet("extCons","ExternalConstraints",0,nullptr) ;
125 pc.defineInt("silence","Silence",0,0) ;
126 pc.defineInt("randProtoData","PrototypeData",0,0) ;
127 pc.defineInt("verboseGen","Verbose",0,0) ;
128 pc.defineInt("extendedGen","Extended",0,0) ;
129 pc.defineInt("binGenData","Binned",0,0) ;
130 pc.defineInt("dummy","FitOptArgs",0,0) ;
131
132 // Process and check varargs
133 pc.process(cmdList) ;
134 if (!pc.ok(true)) {
135 // WVE do something here
136 throw std::string("RooMCStudy::RooMCStudy() Error in parsing arguments passed to constructor") ;
137 return ;
138 }
139
140 // Save fit command options
141 if (pc.hasProcessed("FitOptArgs")) {
142 RooCmdArg* fitOptArg = static_cast<RooCmdArg*>(cmdList.FindObject("FitOptArgs")) ;
143 for (int i=0 ; i<fitOptArg->subArgs().GetSize() ;i++) {
144 _fitOptList.Add(new RooCmdArg(static_cast<RooCmdArg&>(*fitOptArg->subArgs().At(i)))) ;
145 }
146 }
147
148 // Decode command line arguments
149 _silence = pc.getInt("silence") ;
150 _verboseGen = pc.getInt("verboseGen") ;
151 _extendedGen = pc.getInt("extendedGen") ;
152 _binGenData = pc.getInt("binGenData") ;
153 _randProto = pc.getInt("randProtoData") ;
154
155 // Process constraints specifications
156 const RooArgSet* cParsTmp = pc.getSet("cPars") ;
157 const RooArgSet* extCons = pc.getSet("extCons") ;
158
159 auto cPars = std::make_unique<RooArgSet>();
160 if (cParsTmp) {
161 cPars->add(*cParsTmp) ;
162 }
163
164 // If constraints are specified, add to fit options
165 if (cPars) {
167 }
168 if (extCons) {
170 }
171
172 // Make list of all constraints
175 if (cPars) {
176 if (std::unique_ptr<RooArgSet> constraints{model.getAllConstraints(observables,*cPars,true)}) {
177 allConstraints.add(*constraints) ;
178 }
179 }
180
181 // Construct constraint p.d.f
182 if (!allConstraints.empty()) {
183 _constrPdf = std::make_unique<RooProdPdf>("mcs_constr_prod","RooMCStudy constraints product",allConstraints);
184
185 if (cPars) {
186 consPars.add(*cPars) ;
187 } else {
188 RooArgSet params;
189 model.getParameters(&observables, params);
191 _constrPdf->getObservables(&params, cparams);
192 consPars.add(cparams) ;
193 }
194 _constrGenContext.reset(_constrPdf->genContext(consPars,nullptr,nullptr,_verboseGen));
195
197
198 coutI(Generation) << "RooMCStudy::RooMCStudy: INFO have pdf with constraints, will generate parameters from constraint pdf for each experiment" << std::endl ;
199 }
200
201
202 // Extract generator and fit models
203 _genModel = const_cast<RooAbsPdf*>(&model) ;
204 RooAbsPdf* fitModel = static_cast<RooAbsPdf*>(pc.getObject("fitModel",nullptr)) ;
205 _fitModel = fitModel ? fitModel : _genModel ;
206
207 // Extract conditional observables and prototype data
208 _genProtoData = static_cast<RooDataSet*>(pc.getObject("protoData",nullptr)) ;
209 if (auto condObs = pc.getSet("condObs",nullptr)) {
211 }
212
213 _dependents.add(observables) ;
214
217
219 oocoutW(_fitModel,Generation) << "RooMCStudy::RooMCStudy: WARNING Using generator option 'e' (Poisson distribution of #events) together " << std::endl
220 << " with a prototype dataset implies incomplete sampling or oversampling of proto data." << std::endl
221 << " Use option \"r\" to randomize prototype dataset order and thus to randomize" << std::endl
222 << " the set of over/undersampled prototype events for each generation cycle." << std::endl ;
223 }
224
226 if (!_binGenData) {
228 _genContext->attach(_genParams) ;
229 }
230
232
233 // Store list of parameters and save initial values separately
236
238
239 // Place holder for NLL
240 _nllVar = std::make_unique<RooRealVar>("NLL","-log(Likelihood)",0);
241
242 // Place holder for number of generated events
243 _ngenVar = std::make_unique<RooRealVar>("ngen","number of generated events",0);
244
245 // Create data set containing parameter values, errors and pulls
247 tmp2.add(*_nllVar) ;
248 tmp2.add(*_ngenVar) ;
249
250 // Mark all variable to store their errors in the dataset
251 tmp2.setAttribAll("StoreError",true) ;
252 tmp2.setAttribAll("StoreAsymError",true) ;
253 std::string fpdName;
254 if (_fitModel==_genModel) {
255 fpdName = "fitParData_" + std::string(_fitModel->GetName());
256 } else {
257 fpdName= "fitParData_" + std::string(_fitModel->GetName()) + "_" + std::string(_genModel->GetName());
258 }
259
260 _fitParData = std::make_unique<RooDataSet>(fpdName,"Fit Parameters DataSet",tmp2);
261 tmp2.setAttribAll("StoreError",false) ;
262 tmp2.setAttribAll("StoreAsymError",false) ;
263
264 if (_perExptGenParams) {
265 _genParData = std::make_unique<RooDataSet>("genParData","Generated Parameters dataset",_genParams);
266 }
267
268 // Append proto variables to allDependents
269 if (_genProtoData) {
270 _allDependents.add(*_genProtoData->get(),true) ;
271 }
272
273 // Call module initializers
274 for (auto iter=_modList.begin() ; iter!= _modList.end() ; ++iter) {
275 bool ok = (*iter)->doInitializeInstance(*this) ;
276 if (!ok) {
277 oocoutE(_fitModel,Generation) << "RooMCStudy::ctor: removing study module " << (*iter)->GetName() << " from analysis chain because initialization failed" << std::endl ;
278 iter = _modList.erase(iter) ;
279 }
280 }
281
282}
283
284
285////////////////////////////////////////////////////////////////////////////////
286
292
293
294
295////////////////////////////////////////////////////////////////////////////////
296/// Insert given RooMCStudy add-on module to the processing chain
297/// of this MCStudy object
298
300{
301 module.doInitializeInstance(*this) ;
302 _modList.push_back(&module) ;
303}
304
305
306
307////////////////////////////////////////////////////////////////////////////////
308/// Run engine method. Generate and/or fit, according to flags, 'nSamples' samples of 'nEvtPerSample' events.
309/// If keepGenData is set, all generated data sets will be kept in memory and can be accessed
310/// later via genData().
311///
312/// When generating, data sets will be written out in ascii form if the pattern string is supplied
313/// The pattern, which is a template for snprintf, should look something like "data/toymc_%04d.dat"
314/// and should contain one integer field that encodes the sample serial number.
315///
316/// When fitting only, data sets may optionally be read from ascii files, using the same file
317/// pattern.
318///
319
320bool RooMCStudy::run(bool doGenerate, bool DoFit, Int_t nSamples, Int_t nEvtPerSample, bool keepGenData, const char* asciiFilePat)
321{
323 if (_silence) {
324 oldLevel = RooMsgService::instance().globalKillBelow() ;
325 RooMsgService::instance().setGlobalKillBelow(RooFit::PROGRESS) ;
326 }
327
329 mod->initializeRun(nSamples) ;
330 }
331
332 int prescale = nSamples>100 ? int(nSamples/100) : 1 ;
333
334 while(nSamples--) {
335
336 if (nSamples%prescale==0) {
337 oocoutP(_fitModel,Generation) << "RooMCStudy::run: " ;
338 if (doGenerate) ooccoutI(_fitModel,Generation) << "Generating " ;
339 if (doGenerate && DoFit) ooccoutI(_fitModel,Generation) << "and " ;
340 if (DoFit) ooccoutI(_fitModel,Generation) << "fitting " ;
341 ooccoutP(_fitModel,Generation) << "sample " << nSamples << std::endl ;
342 }
343
344 std::unique_ptr<RooAbsData> ownedGenSample;
345 _genSample = nullptr;
346 bool existingData = false ;
347 if (doGenerate) {
348 // Generate sample
349 int nEvt(nEvtPerSample) ;
350
351 // Reset generator parameters to initial values
353
354 // If constraints are present, sample generator values from constraints
355 if (_constrPdf) {
356 _genParams.assign(*std::unique_ptr<RooDataSet>{_constrGenContext->generate(1)}->get());
357 }
358
359 // Save generated parameters if required
360 if (_genParData) {
361 _genParData->add(_genParams) ;
362 }
363
364 // Call module before-generation hook
366 mod->processBeforeGen(nSamples) ;
367 }
368
369 if (_binGenData) {
370
371 // Calculate the number of (extended) events for this run
372 if (_extendedGen) {
375 }
376
377 // Binned generation
378 ownedGenSample = std::unique_ptr<RooDataHist>{_genModel->generateBinned(_dependents,nEvt)};
379
380 } else {
381
382 // Calculate the number of (extended) events for this run
383 if (_extendedGen) {
386 }
387
388 // Optional randomization of protodata for this run
389 if (_randProto && _genProtoData && _genProtoData->numEntries()!=nEvt) {
390 oocoutI(_fitModel,Generation) << "RooMCStudy: (Re)randomizing event order in prototype dataset (Nevt=" << nEvt << ")" << std::endl ;
392 _genContext->setProtoDataOrder(newOrder) ;
393 delete[] newOrder ;
394 }
395
396 // Actual generation of events
397 if (nEvt>0) {
398 ownedGenSample = std::unique_ptr<RooAbsData>{_genContext->generate(nEvt)};
399 } else {
400 // Make empty dataset
401 ownedGenSample = std::make_unique<RooDataSet>("emptySample","emptySample",_dependents);
402 }
403 }
404
406
407 //} else if (asciiFilePat && &asciiFilePat) { //warning: the address of 'asciiFilePat' will always evaluate as 'true'
408 } else if (asciiFilePat) {
409
410 // Load sample from ASCII file
411 char asciiFile[1024] ;
412 snprintf(asciiFile,1024,asciiFilePat,nSamples) ;
414 ownedGenSample = std::unique_ptr<RooDataSet>{RooDataSet::read(asciiFile,depList,"q")};
416
417 } else {
418
419 // Load sample from internal list
420 _genSample = static_cast<RooDataSet*>(_genDataList.At(nSamples)) ;
422 if (!_genSample) {
423 oocoutW(_fitModel,Generation) << "RooMCStudy::run: WARNING: Sample #" << nSamples << " not loaded, skipping" << std::endl ;
424 continue ;
425 }
426 }
427
428 // Save number of generated events
429 _ngenVar->setVal(_genSample->sumEntries()) ;
430
431 // Call module between generation and fitting hook
433 mod->processBetweenGenAndFit(nSamples) ;
434 }
435
436 if (DoFit) fitSample(_genSample) ;
437
438 // Call module between generation and fitting hook
440 mod->processAfterFit(nSamples) ;
441 }
442
443 // Optionally write to ascii file
445 char asciiFile[1024] ;
446 snprintf(asciiFile,1024,asciiFilePat,nSamples) ;
447 if (RooDataSet* unbinnedData = dynamic_cast<RooDataSet*>(_genSample)) {
448 unbinnedData->write(asciiFile) ;
449 } else {
450 coutE(InputArguments) << "RooMCStudy::run(" << GetName() << ") ERROR: ASCII writing of binned datasets is not supported" << std::endl ;
451 }
452 }
453
454 // Add to list or delete
455 if (!existingData) {
456 if (keepGenData) {
457 _genDataList.Add(ownedGenSample.release()) ;
458 }
459 }
460 }
461
463 if (RooDataSet* auxData = mod->finalizeRun()) {
464 _fitParData->merge(auxData) ;
465 }
466 }
467
469
470 if (_genParData) {
471 for(RooAbsArg * arg : *_genParData->get()) {
472 _genParData->changeObservableName(arg->GetName(),(std::string(arg->GetName()) + "_gen").c_str());
473 }
474
475 _fitParData->merge(_genParData.get());
476 }
477
478 if (DoFit) calcPulls() ;
479
480 if (_silence) {
481 RooMsgService::instance().setGlobalKillBelow(oldLevel) ;
482 }
483
484 return false ;
485}
486
487
488
489
490
491
492////////////////////////////////////////////////////////////////////////////////
493/// Generate and fit 'nSamples' samples of 'nEvtPerSample' events.
494/// If keepGenData is set, all generated data sets will be kept in memory and can be accessed
495/// later via genData().
496///
497/// Data sets will be written out in ascii form if the pattern string is supplied.
498/// The pattern, which is a template for snprintf, should look something like "data/toymc_%04d.dat"
499/// and should contain one integer field that encodes the sample serial number.
500///
501
503{
504 // Clear any previous data in memory
505 _fitResList.Delete() ; // even though the fit results are owned by gROOT, we still want to scratch them here.
507 _fitParData->reset() ;
508
509 return run(true,true,nSamples,nEvtPerSample,keepGenData,asciiFilePat) ;
510}
511
512
513
514////////////////////////////////////////////////////////////////////////////////
515/// Generate 'nSamples' samples of 'nEvtPerSample' events.
516/// If keepGenData is set, all generated data sets will be kept in memory
517/// and can be accessed later via genData().
518///
519/// Data sets will be written out in ascii form if the pattern string is supplied.
520/// The pattern, which is a template for snprintf, should look something like "data/toymc_%04d.dat"
521/// and should contain one integer field that encodes the sample serial number.
522///
523
525{
526 // Clear any previous data in memory
528
529 return run(true,false,nSamples,nEvtPerSample,keepGenData,asciiFilePat) ;
530}
531
532
533
534////////////////////////////////////////////////////////////////////////////////
535/// Fit 'nSamples' datasets, which are read from ASCII files.
536///
537/// The ascii file 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::fit(Int_t nSamples, 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.
545 _fitParData->reset() ;
546
547 return run(false,true,nSamples,0,false,asciiFilePat) ;
548}
549
550
551
552////////////////////////////////////////////////////////////////////////////////
553/// Fit 'nSamples' datasets, as supplied in 'dataSetList'
554///
555
557{
558 // Clear any previous data in memory
559 _fitResList.Delete() ; // even though the fit results are owned by gROOT, we still want to scratch them here.
561 _fitParData->reset() ;
562
563 // Load list of data sets
566 }
567
568 return run(false,true,nSamples,0,true,nullptr) ;
569}
570
571
572
573////////////////////////////////////////////////////////////////////////////////
574/// Reset all fit parameters to the initial model
575/// parameters at the time of the RooMCStudy constructor
576
581
582
583
584////////////////////////////////////////////////////////////////////////////////
585/// Internal function. Performs actual fit according to specifications
586
588{
589 // Optionally bin dataset before fitting
590 std::unique_ptr<RooDataHist> ownedDataHist;
592 if (_binGenData) {
594 _fitModel->getObservables(genSample->get(), depList);
595 ownedDataHist = std::make_unique<RooDataHist>(genSample->GetName(),genSample->GetTitle(),depList,*genSample) ;
596 data = ownedDataHist.get();
597 } else {
598 data = genSample ;
599 }
600
601 RooCmdArg save = RooFit::Save() ;
604
605 RooLinkedList fitOptList(_fitOptList) ;
606 fitOptList.Add(&save) ;
607 if (!_projDeps.empty()) {
608 fitOptList.Add(&condo) ;
609 }
610 fitOptList.Add(&plevel) ;
611 return _fitModel->fitTo(*data,fitOptList);
612}
613
614
615
616////////////////////////////////////////////////////////////////////////////////
617/// Redo fit on 'current' toy sample, or if genSample is not nullptr
618/// do fit on given sample instead
619
621{
622 if (!genSample) {
623 genSample = _genSample ;
624 }
625
626 std::unique_ptr<RooFitResult> fr;
627 if (genSample->sumEntries()>0) {
628 fr = std::unique_ptr<RooFitResult>{doFit(genSample)};
629 }
630
631 return RooFit::makeOwningPtr(std::move(fr));
632}
633
634
635
636////////////////////////////////////////////////////////////////////////////////
637/// Internal method. Fit given dataset with fit model. If fit
638/// converges (TMinuit status code zero) The fit results are appended
639/// to the fit results dataset
640///
641/// If the fit option "r" is supplied, the RooFitResult
642/// objects will always be saved, regardless of the
643/// fit status. RooFitResults objects can be retrieved
644/// later via fitResult().
645///
646
648{
649 // Reset all fit parameters to their initial values
651
652 // Perform actual fit
653 bool ok ;
654 std::unique_ptr<RooFitResult> fr;
655 if (genSample->sumEntries()>0) {
656 fr = std::unique_ptr<RooFitResult>{doFit(genSample)};
657 ok = (fr->status()==0) ;
658 } else {
659 ok = false ;
660 }
661
662 // If fit converged, store parameters and NLL
663 if (ok) {
664 _nllVar->setVal(fr->minNll()) ;
665 RooArgSet tmp(_fitParams) ;
666 tmp.add(*_nllVar) ;
667 tmp.add(*_ngenVar) ;
668
669 _fitParData->add(tmp) ;
670 }
671
672 // Store fit result if requested by user
673 if (_fitOptList.FindObject("Save")) {
674 _fitResList.Add(fr.release()) ;
675 }
676
677 return !ok ;
678}
679
680
681
682////////////////////////////////////////////////////////////////////////////////
683/// Utility function to add fit result from external fit to this RooMCStudy
684/// and process its results through the standard RooMCStudy statistics gathering tools.
685/// This function allows users to run the toy MC generation and/or fitting
686/// in a distributed way and to collect and analyze the results in a RooMCStudy
687/// as if they were run locally.
688///
689/// This method is only functional if this RooMCStudy object is cleanm, i.e. it was not used
690/// to generate and/or fit any samples.
691
693{
694 if (!_canAddFitResults) {
695 oocoutE(_fitModel,InputArguments) << "RooMCStudy::addFitResult: ERROR cannot add fit results in current state" << std::endl ;
696 return true ;
697 }
698
699 // Transfer contents of fit result to fitParams ;
701
702 // If fit converged, store parameters and NLL
703 bool ok = (fr.status()==0) ;
704 if (ok) {
705 _nllVar->setVal(fr.minNll()) ;
706 RooArgSet tmp(_fitParams) ;
707 tmp.add(*_nllVar) ;
708 tmp.add(*_ngenVar) ;
709 _fitParData->add(tmp) ;
710 }
711
712 // Store fit result if requested by user
713 if (_fitOptList.FindObject("Save")) {
714 _fitResList.Add((TObject*)&fr) ;
715 }
716
717 return false ;
718}
719
720
721
722////////////////////////////////////////////////////////////////////////////////
723/// Calculate the pulls for all fit parameters in
724/// the fit results data set, and add them to that dataset.
725
727{
728 for (auto it = _fitParams.begin(); it != _fitParams.end(); ++it) {
729 const auto par = static_cast<RooRealVar*>(*it);
730 _fitParData->addColumn(*std::unique_ptr<RooErrorVar>{par->errorVar()});
731
732 TString name(par->GetName());
733 TString title(par->GetTitle());
734 name.Append("pull") ;
735 title.Append(" Pull") ;
736
737 if (!par->hasError(false)) {
738 coutW(Generation) << "Fit parameter '" << par->GetName() << "' does not have an error."
739 " A pull distribution cannot be generated. This might be caused by the parameter being constant or"
740 " because the fits were not run." << std::endl;
741 continue;
742 }
743
744 // First look in fitParDataset to see if per-experiment generated value has been stored
745 auto genParOrig = static_cast<RooAbsReal*>(_fitParData->get()->find(Form("%s_gen",par->GetName())));
747
748 RooPullVar pull(name,title,*par,*genParOrig) ;
749 _fitParData->addColumn(pull,false) ;
750
751 } else {
752 // If not use fixed generator value
753 genParOrig = static_cast<RooAbsReal*>(_genInitParams.find(par->GetName()));
754
755 if (!genParOrig) {
756 std::size_t index = it - _fitParams.begin();
758 static_cast<RooAbsReal*>(_genInitParams[index]) :
759 nullptr;
760
761 if (genParOrig) {
762 coutW(Generation) << "The fit parameter '" << par->GetName() << "' is not in the model that was used to generate toy data. "
763 "The parameter '" << genParOrig->GetName() << "'=" << genParOrig->getVal() << " was found at the same position in the generator model."
764 " It will be used to compute pulls."
765 "\nIf this is not desired, the parameters of the generator model need to be renamed or reordered." << std::endl;
766 }
767 }
768
769 if (genParOrig) {
770 std::unique_ptr<RooAbsReal> genPar(static_cast<RooAbsReal*>(genParOrig->Clone("truth")));
771 RooPullVar pull(name,title,*par,*genPar);
772
773 _fitParData->addColumn(pull,false) ;
774 } else {
775 coutE(Generation) << "Cannot generate pull distribution for the fit parameter '" << par->GetName() << "'."
776 "\nNo similar parameter was found in the set of parameters that were used to generate toy data." << std::endl;
777 }
778 }
779 }
780}
781
782
783
784
785////////////////////////////////////////////////////////////////////////////////
786/// Return a RooDataSet containing the post-fit parameters of each toy cycle.
787/// This dataset also contains any additional output that was generated
788/// by study modules that were added to this RooMCStudy.
789/// By default, the two following variables are added (apart from fit parameters):
790/// - NLL: The value of the negative log-likelihood for each run.
791/// - ngen: Number of events generated for each run.
793{
794 if (_canAddFitResults) {
795 calcPulls() ;
797 }
798
799 return *_fitParData ;
800}
801
802
803
804////////////////////////////////////////////////////////////////////////////////
805/// Return an argset with the fit parameters for the given sample number
806///
807/// NB: The fit parameters are only stored for successful fits,
808/// thus the maximum sampleNum can be less that the number
809/// of generated samples and if so, the indices will
810/// be out of synch with genData() and fitResult()
811
813{
814 // Check if sampleNum is in range
815 if (sampleNum<0 || sampleNum>=_fitParData->numEntries()) {
816 oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitParams: ERROR, invalid sample number: " << sampleNum << std::endl ;
817 return nullptr ;
818 }
819
820 return _fitParData->get(sampleNum) ;
821}
822
823
824
825////////////////////////////////////////////////////////////////////////////////
826/// Return the RooFitResult of the fit with the given run number.
827///
828/// \note Fit results are not saved by default. This requires passing `FitOptions(Save(), ...)`
829/// to the constructor.
831{
832 // Check if sampleNum is in range
834 oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitResult: ERROR, invalid sample number: " << sampleNum << std::endl ;
835 return nullptr ;
836 }
837
838 // Retrieve fit result object
839 const RooFitResult* fr = static_cast<RooFitResult*>(_fitResList.At(sampleNum)) ;
840 if (fr) {
841 return fr ;
842 } else {
843 oocoutE(_fitModel,InputArguments) << "RooMCStudy::fitResult: ERROR, no fit result saved for sample "
844 << sampleNum << ", did you use the 'r; fit option?" << std::endl ;
845 }
846 return nullptr ;
847}
848
849
850
851////////////////////////////////////////////////////////////////////////////////
852/// Return the given generated dataset. This method will only return datasets
853/// if during the run cycle it was indicated that generator data should be saved.
854
856{
857 // Check that generated data was saved
858 if (_genDataList.GetSize()==0) {
859 oocoutE(_fitModel,InputArguments) << "RooMCStudy::genData() ERROR, generated data was not saved" << std::endl ;
860 return nullptr ;
861 }
862
863 // Check if sampleNum is in range
865 oocoutE(_fitModel,InputArguments) << "RooMCStudy::genData() ERROR, invalid sample number: " << sampleNum << std::endl ;
866 return nullptr ;
867 }
868
869 return static_cast<RooAbsData*>(_genDataList.At(sampleNum)) ;
870}
871
872
873
874////////////////////////////////////////////////////////////////////////////////
875/// Plot the distribution of fitted values of a parameter. The parameter shown is the one from which the RooPlot
876/// was created, e.g.
877///
878/// RooPlot* frame = param.frame(100,-10,10) ;
879/// mcstudy.paramOn(frame,LineStyle(kDashed)) ;
880///
881/// Any named arguments passed to plotParamOn() are forwarded to the underlying plotOn() call
882
884 const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
885{
886 _fitParData->plotOn(frame,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
887 return frame ;
888}
889
890
891
892////////////////////////////////////////////////////////////////////////////////
893/// Plot the distribution of the fitted value of the given parameter on a newly created frame.
894///
895/// <table>
896/// <tr><th> Optional arguments <th>
897/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
898/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
899/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
900/// for list of allowed arguments
901/// </table>
902/// If no frame specifications are given, the AutoRange() feature will be used to set the range
903/// Any other named argument is passed to the RooAbsData::plotOn() call. See that function for allowed options
904
906 const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
907{
908
909 // Find parameter in fitParDataSet
910 RooRealVar* param = static_cast<RooRealVar*>(_fitParData->get()->find(paramName)) ;
911 if (!param) {
912 oocoutE(_fitModel,InputArguments) << "RooMCStudy::plotParam: ERROR: no parameter defined with name " << paramName << std::endl ;
913 return nullptr ;
914 }
915
916 // Forward to implementation below
917 return plotParam(*param,arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
918}
919
920
921
922////////////////////////////////////////////////////////////////////////////////
923/// Plot the distribution of the fitted value of the given parameter on a newly created frame.
924/// \copydetails RooMCStudy::plotParam(const char* paramName, const RooCmdArg& arg1, const RooCmdArg& arg2, const RooCmdArg& arg3, const RooCmdArg& arg4,
925/// const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
926
928 const RooCmdArg& arg5, const RooCmdArg& arg6, const RooCmdArg& arg7, const RooCmdArg& arg8)
929{
930 // Stuff all arguments in a list
932 cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
933 cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
934 cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
935 cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
936
937 RooPlot* frame = makeFrameAndPlotCmd(param, cmdList) ;
938 if (frame) {
939 _fitParData->plotOn(frame, cmdList) ;
940 }
941
942 return frame ;
943}
944
945
946
947////////////////////////////////////////////////////////////////////////////////
948/// Plot the distribution of the -log(L) values on a newly created frame.
949///
950/// <table>
951/// <tr><th> Optional arguments <th>
952/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
953/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
954/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
955/// for list of allowed arguments
956/// </table>
957///
958/// If no frame specifications are given, the AutoRange() feature will be used to set the range.
959/// Any other named argument is passed to the RooAbsData::plotOn() call. See that function for allowed options
960
962 const RooCmdArg& arg3, const RooCmdArg& arg4,
963 const RooCmdArg& arg5, const RooCmdArg& arg6,
964 const RooCmdArg& arg7, const RooCmdArg& arg8)
965{
967}
968
969
970
971////////////////////////////////////////////////////////////////////////////////
972/// Plot the distribution of the fit errors for the specified parameter on a newly created frame.
973///
974/// <table>
975/// <tr><th> Optional arguments <th>
976/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
977/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
978/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
979/// for list of allowed arguments
980/// </table>
981///
982/// If no frame specifications are given, the AutoRange() feature will be used to set a default range.
983/// Any other named argument is passed to the RooAbsData::plotOn() call. See that function for allowed options.
984
986 const RooCmdArg& arg3, const RooCmdArg& arg4,
987 const RooCmdArg& arg5, const RooCmdArg& arg6,
988 const RooCmdArg& arg7, const RooCmdArg& arg8)
989{
990 if (_canAddFitResults) {
991 calcPulls() ;
993 }
994
995 std::unique_ptr<RooErrorVar> evar{param.errorVar()};
996 std::unique_ptr<RooAbsArg> evar_rrv{evar->createFundamental()};
997 RooPlot* frame = plotParam(static_cast<RooRealVar&>(*evar_rrv),arg1,arg2,arg3,arg4,arg5,arg6,arg7,arg8) ;
998
999 // To make sure the frame has no dangling pointer to evar_rrv.
1001
1002 return frame ;
1003}
1004
1005namespace {
1006
1007// Fits a Gaussian to the pull distribution, plots the fit and prints the fit
1008// parameters on the canvas. Implementation detail of RooMCStudy::plotPull().
1010{
1011 // Build the Gaussian fit mode for the pulls, then fit it and plot it. We
1012 // have to use the RooWorkspace factory here, because different from the
1013 // RooMCStudy class, the RooGaussian is not in RooFitCore.
1014 RooWorkspace ws;
1015 auto plotVar = frame.getPlotVar();
1016 const std::string plotVarName = plotVar->GetName();
1017 ws.import(*plotVar);
1018 ws.factory("Gaussian::pullGauss(" + plotVarName + ", pullMean[0.0, -10.0, 10.0], pullSigma[1.0, 0.1, 5.0])");
1019
1020 RooRealVar& pullMean = *ws.var("pullMean");
1021 RooRealVar& pullSigma = *ws.var("pullSigma");
1022 RooAbsPdf& pullGauss = *ws.pdf("pullGauss");
1023
1025 pullGauss.plotOn(&frame) ;
1026
1027 // Instead of using paramOn() without command arguments to plot the fit
1028 // parameters, we are building the parameter label ourselves for more
1029 // flexibility and pass this together with an appropriate layout
1030 // parametrization to paramOn().
1031 const int sigDigits = 2;
1032 const char * options = "ELU";
1033 std::stringstream ss;
1034 ss << "Fit parameters:\n"
1035 << "#mu: " << pullMean.format(sigDigits, options)
1036 << "\n#sigma: " << pullSigma.format(sigDigits, options);
1037 // We set the parameters constant to disable the default label. Still, we
1038 // use param() on as a wrapper for the text box generation.
1039 pullMean.setConstant(true);
1040 pullSigma.setConstant(true);
1041 pullGauss.paramOn(&frame, RooFit::Label(ss.str().c_str()), RooFit::Layout(0.60, 0.9, 0.9));
1042}
1043
1044} // namespace
1045
1046
1047////////////////////////////////////////////////////////////////////////////////
1048/// Plot the distribution of pull values for the specified parameter on a newly created frame. If asymmetric
1049/// errors are calculated in the fit (by MINOS) those will be used in the pull calculation.
1050///
1051/// If the parameters of the models for generation and fit differ, simple heuristics are used to find the
1052/// corresponding parameters:
1053/// - Parameters have the same name: They will be used to compute pulls.
1054/// - Parameters have different names: The position of the fit parameter in the set of fit parameters will be
1055/// computed. The parameter at the same position in the set of generator parameters will be used.
1056///
1057/// Further options:
1058/// <table>
1059/// <tr><th> Arguments <th> Effect
1060/// <tr><td> FrameRange(double lo, double hi) <td> Set range of frame to given specification
1061/// <tr><td> FrameBins(int bins) <td> Set default number of bins of frame to given number
1062/// <tr><td> Frame() <td> Pass supplied named arguments to RooAbsRealLValue::frame() function. See there
1063/// for list of allowed arguments
1064/// <tr><td> FitGauss(bool flag) <td> Add a gaussian fit to the frame
1065/// </table>
1066///
1067/// If no frame specifications are given, the AutoSymRange() feature will be used to set a default range.
1068/// Any other named argument is passed to the RooAbsData::plotOn(). See that function for allowed options.
1069///
1070/// If you want to have more control over the Gaussian fit to the pull
1071/// distribution, you can also do it after the call to plotPull():
1072///
1073/// ~~~ {.cpp}
1074/// RooPlot *frame = mcstudy->plotPull(myVariable, RooFit::Bins(40), RooFit::FitGauss(false));
1075/// RooRealVar pullMean("pullMean","Mean of pull",0,-10,10) ;
1076/// RooRealVar pullSigma("pullSigma","Width of pull",1,0.1,5) ;
1077/// pullMean.setPlotLabel("pull #mu"); // optional (to get nicer plot labels if you want)
1078/// pullSigma.setPlotLabel("pull #sigma"); // optional
1079/// RooGaussian pullGauss("pullGauss","Gaussian of pull", *frame->getPlotVar(), pullMean, pullSigma);
1080/// pullGauss.fitTo(const_cast<RooDataSet&>(mcstudy->fitParDataSet()),
1081/// RooFit::Minos(0), RooFit::PrintLevel(-1)) ;
1082/// pullGauss.plotOn(frame) ;
1083/// pullGauss.paramOn(frame, RooFit::Layout(0.65, 0.9, 0.9)); // optionally specify label position (xmin, xmax, ymax)
1084/// ~~~
1085
1087 const RooCmdArg& arg3, const RooCmdArg& arg4,
1088 const RooCmdArg& arg5, const RooCmdArg& arg6,
1089 const RooCmdArg& arg7, const RooCmdArg& arg8)
1090{
1091 // Stuff all arguments in a list
1093 cmdList.Add(const_cast<RooCmdArg*>(&arg1)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg2)) ;
1094 cmdList.Add(const_cast<RooCmdArg*>(&arg3)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg4)) ;
1095 cmdList.Add(const_cast<RooCmdArg*>(&arg5)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg6)) ;
1096 cmdList.Add(const_cast<RooCmdArg*>(&arg7)) ; cmdList.Add(const_cast<RooCmdArg*>(&arg8)) ;
1097
1098 TString name(param.GetName());
1099 TString title(param.GetTitle());
1100 name.Append("pull") ; title.Append(" Pull") ;
1101 RooRealVar pvar(name,title,-100,100) ;
1102 pvar.setBins(100) ;
1103
1104
1105 RooPlot* frame = makeFrameAndPlotCmd(pvar, cmdList, true) ;
1106 if (frame) {
1107
1108 // Pick up optional FitGauss command from list
1109 RooCmdConfig pc("RooMCStudy::plotPull(" + std::string(_genModel->GetName()) + ")");
1110 pc.defineInt("fitGauss","FitGauss",0,0) ;
1111 pc.allowUndefined() ;
1112 pc.process(cmdList) ;
1113 bool fitGauss=pc.getInt("fitGauss") ;
1114
1115 // Pass stripped command list to plotOn()
1117 const bool success = _fitParData->plotOn(frame,cmdList) ;
1118
1119 if (!success) {
1120 coutF(Plotting) << "No pull distribution for the parameter '" << param.GetName() << "'. Check logs for errors." << std::endl;
1121 return frame;
1122 }
1123
1124 // Add Gaussian fit if requested
1125 if (fitGauss) {
1126 fitGaussToPulls(*frame, *_fitParData);
1127 }
1128
1129 // To make sure the frame has no dangling pointer to pvar.
1131 }
1132 return frame;
1133}
1134
1135
1136
1137////////////////////////////////////////////////////////////////////////////////
1138/// Internal function. Construct RooPlot from given parameter and modify the list of named
1139/// arguments 'cmdList' to only contain the plot arguments that should be forwarded to
1140/// RooAbsData::plotOn()
1141
1143{
1144 // Select the frame-specific commands
1145 RooCmdConfig pc("RooMCStudy::plotParam(" + std::string(_genModel->GetName()) + ")");
1146 pc.defineInt("nbins","Bins",0,0) ;
1147 pc.defineDouble("xlo","Range",0,0) ;
1148 pc.defineDouble("xhi","Range",1,0) ;
1149 pc.defineInt("dummy","FrameArgs",0,0) ;
1150 pc.defineMutex("Bins","FrameArgs") ;
1151 pc.defineMutex("Range","FrameArgs") ;
1152
1153 // Process and check varargs
1154 pc.allowUndefined() ;
1155 pc.process(cmdList) ;
1156 if (!pc.ok(true)) {
1157 return nullptr ;
1158 }
1159
1160 // Make frame according to specs
1161 Int_t nbins = pc.getInt("nbins") ;
1162 double xlo = pc.getDouble("xlo") ;
1163 double xhi = pc.getDouble("xhi") ;
1164 RooPlot* frame ;
1165
1166 if (pc.hasProcessed("FrameArgs")) {
1167 // Explicit frame arguments are given, pass them on
1168 RooCmdArg* frameArg = static_cast<RooCmdArg*>(cmdList.FindObject("FrameArgs")) ;
1169 frame = param.frame(frameArg->subArgs()) ;
1170 } else {
1171 // FrameBins, FrameRange or none are given, build custom frame command list
1172 RooCmdArg bins = RooFit::Bins(nbins) ;
1173 RooCmdArg range = RooFit::Range(xlo,xhi) ;
1176
1177 if (pc.hasProcessed("Bins")) frameCmdList.Add(&bins) ;
1178 if (pc.hasProcessed("Range")) {
1179 frameCmdList.Add(&range) ;
1180 } else {
1181 frameCmdList.Add(&autoRange) ;
1182 }
1183 frame = param.frame(frameCmdList) ;
1184 }
1185
1186 // Filter frame command from list and pass on to plotOn()
1187 RooCmdConfig::stripCmdList(cmdList,"FrameArgs,Bins,Range") ;
1188
1189 return frame ;
1190}
1191
1192
1193
1194////////////////////////////////////////////////////////////////////////////////
1195/// Create a RooPlot of the -log(L) distribution in the range lo-hi
1196/// with 'nBins' bins
1197
1198RooPlot* RooMCStudy::plotNLL(double lo, double hi, Int_t nBins)
1199{
1200 RooPlot* frame = _nllVar->frame(lo,hi,nBins) ;
1201
1202 _fitParData->plotOn(frame) ;
1203 return frame ;
1204}
1205
1206
1207
1208////////////////////////////////////////////////////////////////////////////////
1209/// Create a RooPlot of the distribution of the fitted errors of the given parameter.
1210/// The frame is created with a range [lo,hi] and plotted data will be binned in 'nbins' bins
1211
1212RooPlot* RooMCStudy::plotError(const RooRealVar& param, double lo, double hi, Int_t nbins)
1213{
1214 if (_canAddFitResults) {
1215 calcPulls() ;
1217 }
1218
1219 std::unique_ptr<RooErrorVar> evar{param.errorVar()};
1220 RooPlot* frame = evar->frame(lo,hi,nbins) ;
1221 _fitParData->plotOn(frame) ;
1222
1223 return frame ;
1224}
1225
1226
1227
1228////////////////////////////////////////////////////////////////////////////////
1229/// Create a RooPlot of the pull distribution for the given
1230/// parameter. The range lo-hi is plotted in nbins. If fitGauss is
1231/// set, an unbinned ML fit of the distribution to a Gaussian p.d.f
1232/// is performed. The fit result is overlaid on the returned RooPlot
1233/// and a box with the fitted mean and sigma is added.
1234///
1235/// If the parameters of the models for generation and fit differ, simple heuristics are used to find the
1236/// corresponding parameters:
1237/// - Parameters have the same name: They will be used to compute pulls.
1238/// - Parameters have different names: The position of the fit parameter in the set of fit parameters will be
1239/// computed. The parameter at the same position in the set of generator parameters will be used.
1240
1241RooPlot* RooMCStudy::plotPull(const RooRealVar& param, double lo, double hi, Int_t nbins, bool fitGauss)
1242{
1243 if (_canAddFitResults) {
1244 calcPulls() ;
1246 }
1247
1248 TString name(param.GetName());
1249 TString title(param.GetTitle());
1250 name.Append("pull") ; title.Append(" Pull") ;
1251 RooRealVar pvar(name,title,lo,hi) ;
1252 pvar.setBins(nbins) ;
1253
1254 RooPlot* frame = pvar.frame() ;
1255 const bool success = _fitParData->plotOn(frame);
1256
1257 if (!success) {
1258 coutF(Plotting) << "No pull distribution for the parameter '" << param.GetName() << "'. Check logs for errors." << std::endl;
1259 return frame;
1260 }
1261
1262 if (fitGauss) {
1263 fitGaussToPulls(*frame, *_fitParData);
1264 }
1265
1266 return frame ;
1267}
1268
1269
1270////////////////////////////////////////////////////////////////////////////////
1271/// If one of the TObject we have a referenced to is deleted, remove the
1272/// reference.
1273
1275{
1279 if (_ngenVar.get() == obj) _ngenVar.reset();
1280
1281 if (_fitParData) _fitParData->RecursiveRemove(obj);
1282 if (_fitParData.get() == obj) _fitParData.reset();
1283
1284 if (_genParData) _genParData->RecursiveRemove(obj);
1285 if (_genParData.get() == obj) _genParData.reset();
1286}
1287
#define coutI(a)
#define oocoutW(o, a)
#define coutW(a)
#define coutF(a)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
#define ooccoutI(o, a)
#define ooccoutP(o, a)
#define oocoutP(o, a)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2489
#define snprintf
Definition civetweb.c:1540
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
RooFit::OwningPtr< RooArgSet > getParameters(const RooAbsData *data, bool stripDisconnected=true) const
Create a list of leaf nodes in the arg tree starting with ourself as top node that don't match any of...
RooFit::OwningPtr< RooArgSet > getObservables(const RooArgSet &set, bool valueOnly=true) const
Given a set of possible observables, return the observables that this PDF depends on.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
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.
Abstract base class for binned and unbinned datasets.
Definition RooAbsData.h:57
virtual double sumEntries() const =0
Return effective number of entries in dataset, i.e., sum all weights.
virtual const RooArgSet * get() const
Definition RooAbsData.h:101
Base class for add-on modules to RooMCStudy that can perform additional calculations on each generate...
Abstract interface for all probability density functions.
Definition RooAbsPdf.h:40
virtual double expectedEvents(const RooArgSet *nset) const
Return expected number of events to be used in calculation of extended likelihood.
Int_t * randomizeProtoOrder(Int_t nProto, Int_t nGen, bool resample=false) const
Return lookup table with randomized order for nProto prototype events.
RooFit::OwningPtr< RooFitResult > fitTo(RooAbsData &data, CmdArgs_t const &... cmdArgs)
Fit PDF to given dataset.
Definition RooAbsPdf.h:157
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....
virtual RooFit::OwningPtr< RooDataHist > generateBinned(const RooArgSet &whatVars, double nEvents, const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}) const
As RooAbsPdf::generateBinned(const RooArgSet&, const RooCmdArg&,const RooCmdArg&, const RooCmdArg&,...
Definition RooAbsPdf.h:110
virtual RooAbsGenContext * genContext(const RooArgSet &vars, const RooDataSet *prototype=nullptr, const RooArgSet *auxProto=nullptr, bool verbose=false) const
Interface function to create a generator context from a p.d.f.
RooPlot * frame(const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}) const
Create a new RooPlot on the heap with a drawing frame initialized for this object,...
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:59
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:24
RooArgSet * snapshot(bool deepCopy=true) const
Use RooAbsCollection::snapshot(), but return as RooArgSet.
Definition RooArgSet.h:159
Named container for two doubles, two integers two object points and three string pointers that can be...
Definition RooCmdArg.h:26
TObject * Clone(const char *newName=nullptr) const override
Make a clone of an object using the Streamer facility.
Definition RooCmdArg.h:58
Configurable parser for RooCmdArg named arguments.
void defineMutex(const char *head, Args_t &&... tail)
Define arguments where any pair is mutually exclusive.
bool process(const RooCmdArg &arg)
Process given RooCmdArg.
bool hasProcessed(const char *cmdName) const
Return true if RooCmdArg with name 'cmdName' has been processed.
double getDouble(const char *name, double defaultValue=0.0) const
Return double property registered with name 'name'.
bool defineDouble(const char *name, const char *argName, int doubleNum, double defValue=0.0)
Define double property name 'name' mapped to double in slot 'doubleNum' in RooCmdArg with name argNam...
static void stripCmdList(RooLinkedList &cmdList, const char *cmdsToPurge)
Utility function that strips command names listed (comma separated) in cmdsToPurge from cmdList.
RooArgSet * getSet(const char *name, RooArgSet *set=nullptr) const
Return RooArgSet property registered with name 'name'.
bool defineSet(const char *name, const char *argName, int setNum, const RooArgSet *set=nullptr)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
bool ok(bool verbose) const
Return true of parsing was successful.
bool defineObject(const char *name, const char *argName, int setNum, const TObject *obj=nullptr, bool isArray=false)
Define TObject property name 'name' mapped to object in slot 'setNum' in RooCmdArg with name argName ...
bool defineInt(const char *name, const char *argName, int intNum, int defValue=0)
Define integer property name 'name' mapped to integer in slot 'intNum' in RooCmdArg with name argName...
void allowUndefined(bool flag=true)
If flag is true the processing of unrecognized RooCmdArgs is not considered an error.
int getInt(const char *name, int defaultValue=0) const
Return integer property registered with name 'name'.
TObject * getObject(const char *name, TObject *obj=nullptr) const
Return TObject property registered with name 'name'.
Container class to hold unbinned data.
Definition RooDataSet.h:34
static RooDataSet * read(const char *filename, const RooArgList &variables, const char *opts="", const char *commonPath="", const char *indexCatName=nullptr)
Read data from a text file and create a dataset from it.
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
const RooArgList & floatParsFinal() const
Return list of floating parameters after fit.
Int_t status() const
Return MINUIT status code.
double minNll() const
Return minimized -log(L) value.
Collection class for internal use, storing a collection of RooAbsArg pointers in a doubly linked list...
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=nullptr) override
Remove all elements in collection and delete all elements NB: Collection does not own elements,...
virtual void Add(TObject *arg)
TObject * FindObject(const char *name) const override
Return pointer to object with given name.
bool addFitResult(const RooFitResult &fr)
Utility function to add fit result from external fit to this RooMCStudy and process its results throu...
RooPlot * plotParam(const RooRealVar &param, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={})
Plot the distribution of the fitted value of the given parameter on a newly created frame.
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
RooArgSet _genParams
List of actual generator parameters.
Definition RooMCStudy.h:111
const RooArgSet * fitParams(Int_t sampleNum) const
Return an argset with the fit parameters for the given sample number.
void calcPulls()
Calculate the pulls for all fit parameters in the fit results data set, and add them to that dataset.
~RooMCStudy() override
RooArgSet _dependents
List of dependents.
Definition RooMCStudy.h:118
bool _verboseGen
Verbose generation?
Definition RooMCStudy.h:137
std::list< RooAbsMCStudyModule * > _modList
List of additional study modules ;.
Definition RooMCStudy.h:141
std::unique_ptr< RooDataSet > _genParData
Definition RooMCStudy.h:128
RooArgSet _genInitParams
List of original generator parameters.
Definition RooMCStudy.h:110
TList _fitResList
Definition RooMCStudy.h:127
double _nExpGen
Definition RooMCStudy.h:133
bool fitSample(RooAbsData *genSample)
Internal method.
RooPlot * plotNLL(const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={})
Plot the distribution of the -log(L) values on a newly created frame.
std::unique_ptr< RooDataSet > _fitParData
Definition RooMCStudy.h:129
bool generate(Int_t nSamples, Int_t nEvtPerSample=0, bool keepGenData=false, const char *asciiFilePat=nullptr)
Generate 'nSamples' samples of 'nEvtPerSample' events.
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.
RooFit::OwningPtr< RooFitResult > doFit(RooAbsData *genSample)
Internal function. Performs actual fit according to specifications.
std::unique_ptr< RooAbsGenContext > _constrGenContext
Generator context for constraints p.d.f.
Definition RooMCStudy.h:116
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 * plotParamOn(RooPlot *frame, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={})
Plot the distribution of fitted values of a parameter.
RooArgSet _fitParams
List of actual fit parameters.
Definition RooMCStudy.h:122
RooPlot * plotError(const RooRealVar &param, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={})
Plot the distribution of the fit errors for the specified parameter on a newly created frame.
std::unique_ptr< RooAbsGenContext > _genContext
Generator context.
Definition RooMCStudy.h:109
RooMCStudy(const RooAbsPdf &model, const RooArgSet &observables, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={})
Construct Monte Carlo Study Manager.
RooFit::OwningPtr< RooFitResult > refit(RooAbsData *genSample=nullptr)
Redo fit on 'current' toy sample, or if genSample is not nullptr do fit on given sample instead.
RooAbsData * genData(Int_t sampleNum) const
Return the given generated dataset.
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.
std::unique_ptr< RooRealVar > _nllVar
Definition RooMCStudy.h:123
RooLinkedList _fitOptList
Definition RooMCStudy.h:130
std::unique_ptr< RooAbsPdf > _constrPdf
Constraints p.d.f.
Definition RooMCStudy.h:115
RooArgSet _allDependents
List of generate + prototype dependents.
Definition RooMCStudy.h:119
bool run(bool generate, bool fit, Int_t nSamples, Int_t nEvtPerSample, bool keepGenData, const char *asciiFilePat)
Run engine method.
void resetFitParams()
Reset all fit parameters to the initial model parameters at the time of the RooMCStudy constructor.
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.
bool generateAndFit(Int_t nSamples, Int_t nEvtPerSample=0, bool keepGenData=false, const char *asciiFilePat=nullptr)
Generate and fit 'nSamples' samples of 'nEvtPerSample' events.
RooPlot * plotPull(const RooRealVar &param, const RooCmdArg &arg1, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={})
Plot the distribution of pull values for the specified parameter on a newly created frame.
TList _genDataList
Definition RooMCStudy.h:126
bool _randProto
Definition RooMCStudy.h:134
void addModule(RooAbsMCStudyModule &module)
Insert given RooMCStudy add-on module to the processing chain of this MCStudy object.
RooArgSet _fitInitParams
List of initial values of fit parameters.
Definition RooMCStudy.h:121
std::unique_ptr< RooRealVar > _ngenVar
Definition RooMCStudy.h:124
static RooMsgService & instance()
Return reference to singleton instance.
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
RooAbsRealLValue * getPlotVar() const
Definition RooPlot.h:137
void createInternalPlotVarClone()
Replaces the pointer to the plot variable with a pointer to a clone of the plot variable that is owne...
Definition RooPlot.cxx:1396
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:47
Variable that can be changed from the outside.
Definition RooRealVar.h:37
RooErrorVar * errorVar() const
Return a RooAbsRealLValue representing the error associated with this variable.
Persistable container for RooFit projects.
RooAbsPdf * pdf(RooStringView name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
RooFactoryWSTool & factory()
Return instance to factory tool.
RooRealVar * var(RooStringView name) const
Retrieve real-valued variable (RooRealVar) with given name. A null pointer is returned if not found.
bool import(const RooAbsArg &arg, const RooCmdArg &arg1={}, const RooCmdArg &arg2={}, const RooCmdArg &arg3={}, const RooCmdArg &arg4={}, const RooCmdArg &arg5={}, const RooCmdArg &arg6={}, const RooCmdArg &arg7={}, const RooCmdArg &arg8={}, const RooCmdArg &arg9={})
Import a RooAbsArg object, e.g.
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
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:762
void Add(TObject *obj) override
Definition TList.h:81
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:468
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:355
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:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
Mother of all ROOT objects.
Definition TObject.h:41
Basic string class.
Definition TString.h:139
TString & Append(const char *cs)
Definition TString.h:572
RooCmdArg AutoRange(const RooAbsData &data, double marginFactor=0.1)
RooCmdArg Label(const char *str)
RooCmdArg AutoSymRange(const RooAbsData &data, double marginFactor=0.1)
RooCmdArg Bins(Int_t nbin)
RooCmdArg Layout(double xmin, double xmax=0.99, double ymin=0.95)
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)
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
Definition Config.h:35
MsgLevel
Verbosity level for RooMsgService::StreamConfig in RooMsgService.
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
Definition Config.h:40