MCToyGenerationAndFit.cxx
Go to the documentation of this file.
2 #include "ProtoDUNEFitUtils.h"
3 
4 // ROOT
5 #include "TROOT.h"
6 #include "TList.h"
7 #include "TRandom3.h"
8 #include "TString.h"
9 #include "TTree.h"
10 #include <Math/MinimizerOptions.h>
11 
12 #include "RooAbsPdf.h"
13 #include "RooDataSet.h"
14 #include "RooRealVar.h"
15 #include "RooRandom.h"
16 #include "RooCategory.h"
17 #include "RooSimultaneous.h"
18 #include "RooPlot.h"
19 #include "RooChi2Var.h"
20 #include "RooDataHist.h"
21 #include "RooAbsData.h"
22 #include "RooWorkspace.h"
23 #include "RooMCStudy.h"
24 #include "RooFitResult.h"
25 #include "RooMultiVarGaussian.h"
26 #include "RooArgList.h"
27 #include "RooArgSet.h"
28 
29 #include "RooStats/ModelConfig.h"
30 #include "RooStats/ProfileLikelihoodTestStat.h"
31 #include "RooStats/ToyMCSampler.h"
32 #include "RooStats/HistFactory/Measurement.h"
33 
34 //********************************************************************
36  //********************************************************************
37 
38  _minimizer = "Minuit2";
39  _algorithm = TString(ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str());
40  _fitstrategy = 1;
41  _minoserror = false;
42  _conflevel = 0.95;
43 
44 }
45 
46 //********************************************************************
47 protoana::MCToyGenerationAndFit::MCToyGenerationAndFit(std::string minimizer, int fitstrategy, bool minoserror, double cl){
48  //********************************************************************
49 
50  _minimizer = TString(minimizer.c_str());
51  _algorithm = TString(ROOT::Math::MinimizerOptions::DefaultMinimizerAlgo().c_str());
52  _fitstrategy = fitstrategy;
53  _minoserror = minoserror;
54  _conflevel = cl;
55 
56 }
57 
58 //********************************************************************
60  //********************************************************************
61 
62 }
63 
64 //********************************************************************
65 RooAbsData* protoana::MCToyGenerationAndFit::GenerateToyMC(RooWorkspace* ws, bool datanorm){
66  //********************************************************************
67 
68  if(!ws){
69  std::cerr << "ERROR::NULL workspace. No dataset generated!" << std::endl;
70  return NULL;
71  }
72 
73  // Get the configuration model from workspace
74  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
75  if(!combined_config){
76  std::cerr << "ERROR::No model config " << " ModelConfig " << " in workspace!" << std::endl;
77  return NULL;
78  }
79 
80  // Get the pdf
81  RooAbsPdf* pdf = combined_config->GetPdf();
82  if(!pdf){
83  std::cerr << "ERROR::No pdf found in ModelConfig. No dataset generated!" << std::endl;
84  return NULL;
85  }
86 
87  RooAbsData* data = ws->data("obsData");
88  if(!data){
89  std::cerr << "ERROR::No dataset found in workspace. No dataset generated!" << std::endl;
90  return NULL;
91  }
92 
93  const RooArgSet* obs = combined_config->GetObservables();
94  if(!obs){
95  std::cerr << "ERROR::No observables found in ModelConfig. No dataset generated!" << std::endl;
96  return NULL;
97  }
98 
99  // Silence the output
100  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
101 
102  RooAbsData* mctoy;
103  if(datanorm){
104  Int_t NEventsToGenerate = (Int_t)(data->sumEntries());
105  mctoy = pdf->generate(*obs, RooFit::NumEvents(NEventsToGenerate), RooFit::AutoBinned(false));
106  }
107  else{
108  mctoy = pdf->generate(*obs, RooFit::AutoBinned(false), RooFit::Extended());
109  }
110 
111  // Reset verbosity
112  RooMsgService::instance().reset();
113 
114  return mctoy;
115 
116 }
117 
118 //********************************************************************
119 TTree* protoana::MCToyGenerationAndFit::GenerateAndFit(RooWorkspace* ws, int nexp){
120  //********************************************************************
121 
122  if(!ws){
123  std::cerr << "ERROR::NULL Workspace. Return empty fit!!" << std::endl;
124  return NULL;
125  }
126 
127  // Get the configuration model from workspace
128  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
129  if(!combined_config){
130  std::cerr << "ERROR::No model config " << " ModelConfig " << " in workspace. Return empty fit!!" << std::endl;
131  return NULL;
132  }
133 
134  // Silence the output
135  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
136 
137  RooAbsPdf* pdf = combined_config->GetPdf();
138  const RooArgSet* obs_set = combined_config->GetObservables();
139 
140  // Create mc study. Only used to store the fit result
141  RooMCStudy* mcstudy = new RooMCStudy( *pdf, *obs_set, RooFit::FitOptions("r"));
142 
143  // Create test statistics object
144  RooStats::ProfileLikelihoodTestStat ts(*combined_config->GetPdf());
145 
146  // Create toy mc sampler
147  RooStats::ToyMCSampler sampler(ts,nexp);
148  sampler.SetPdf(*combined_config->GetPdf());
149  sampler.SetObservables(*combined_config->GetObservables());
150  sampler.SetGlobalObservables(*combined_config->GetGlobalObservables());
151  sampler.SetParametersForTestStat(*combined_config->GetParametersOfInterest());
152 
153  RooArgSet poiAndNuisance;
154  poiAndNuisance.add(*combined_config->GetParametersOfInterest());
155  if(combined_config->GetNuisanceParameters())
156  poiAndNuisance.add(*combined_config->GetNuisanceParameters());
157  RooArgSet* nullParams = (RooArgSet*) poiAndNuisance.snapshot();
158  //nullParams->Print();
159 
160  // Will be used as start values of fit
161  ws->saveSnapshot("paramsToFit",poiAndNuisance);
162 
163  for(int i=0; i<nexp; ++i) {
164  if(i%10==0)
165  std::cout << "INFO::Running on toy " << i << std::endl;
166 
167  // Reset starting values of fit
168  ws->loadSnapshot("paramsToFit");
169 
170  RooAbsData* toyMC = sampler.GenerateToyData( *nullParams );
171  toyMC->Print();
172 
173  RooFitResult* fresult = combined_config->GetPdf()->fitTo(*toyMC, RooFit::Minimizer(_minimizer.Data(), _algorithm.Data()), RooFit::Save(), RooFit::Strategy(_fitstrategy), RooFit::Minos(_minoserror), RooFit::PrintLevel(-1), RooFit::Constrain(*combined_config->GetPdf()->getParameters(*toyMC)), RooFit::Extended(), RooFit::Offset(true));
174 
175  mcstudy->addFitResult(*fresult);
176 
177  delete toyMC;
178  }
179 
180  // Reset verbosity
181  RooMsgService::instance().reset();
182 
183  TTree* mcstree = RooMCStudyToTTree(mcstudy);
184 
185  delete mcstudy;
186 
187  return mcstree;
188 
189 }
190 
191 //********************************************************************
193  RooWorkspace* ws) {
194 //********************************************************************
195 
196  if(!ws){
197  std::cerr << "ERROR::NULL Workspace. Return empty fit!!" << std::endl;
198  return NULL;
199  }
200 
201  // Get the configuration model from workspace
202  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
203  if(!combined_config){
204  std::cerr << "ERROR::No model config " << " ModelConfig " << " in workspace. Return empty fit!!" << std::endl;
205  return NULL;
206  }
207 
208  // Silence the output
209  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
210 
211  //RooAbsPdf* pdf = combined_config->GetPdf();
212  // const RooArgSet* obs_set = combined_config->GetObservables();
213 
214  // Create mc study. Only used to store the fit result
215  //RooMCStudy* mcstudy = new RooMCStudy( *pdf, *obs_set, RooFit::FitOptions("r"));
216 
217  // Create test statistics object
218  RooStats::ProfileLikelihoodTestStat ts(*combined_config->GetPdf());
219 
220  // Create toy mc sampler
221  RooStats::ToyMCSampler sampler(ts, 1);
222  sampler.SetPdf(*combined_config->GetPdf());
223  sampler.SetObservables(*combined_config->GetObservables());
224  sampler.SetGlobalObservables(*combined_config->GetGlobalObservables());
225  sampler.SetParametersForTestStat(*combined_config->GetParametersOfInterest());
226 
227  RooArgSet poiAndNuisance;
228  poiAndNuisance.add(*combined_config->GetParametersOfInterest());
229  if(combined_config->GetNuisanceParameters())
230  poiAndNuisance.add(*combined_config->GetNuisanceParameters());
231  RooArgSet* nullParams = (RooArgSet*) poiAndNuisance.snapshot();
232  //nullParams->Print();
233 
234  // Will be used as start values of fit
235  ws->saveSnapshot("paramsToFit",poiAndNuisance);
236 
237 // for(int i=0; i<nexp; ++i) {
238 // if(i%10==0)
239 // std::cout << "INFO::Running on toy " << i << std::endl;
240 
241  // Reset starting values of fit
242  ws->loadSnapshot("paramsToFit");
243 
244  RooAbsData* toyMC = sampler.GenerateToyData( *nullParams );
245  toyMC->Print();
246 
247  RooFitResult* fresult = combined_config->GetPdf()->fitTo(*toyMC, RooFit::Minimizer(_minimizer.Data(), _algorithm.Data()), RooFit::Save(), RooFit::Strategy(_fitstrategy), RooFit::Minos(_minoserror), RooFit::PrintLevel(-1), RooFit::Constrain(*combined_config->GetPdf()->getParameters(*toyMC)), RooFit::Extended(), RooFit::Offset(true));
248 
249  return fresult;
250 
251 // mcstudy->addFitResult(*fresult);
252 //
253 // delete toyMC;
254 // }
255 
256 }
257 
258 //********************************************************************
259 RooFitResult* protoana::MCToyGenerationAndFit::FitData(RooWorkspace* ws, bool isWeighted){
260  //********************************************************************
261 
262  if(!ws){
263  std::cerr << "ERROR::NULL Workspace. Return empty fit!!" << std::endl;
264  return NULL;
265  }
266 
267  // Get the configuration model from workspace
268  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
269  if(!combined_config){
270  std::cerr << "ERROR::No model config " << "ModelConfig " << " in workspace. Return empty fit!!" << std::endl;
271  return NULL;
272  }
273 
274  // Silence the output
275  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
276 
277  // Dataset
278  RooAbsData *obsdata = ws->data("obsData");
279 
280  RooFitResult* fresult = NULL;
281  if(!isWeighted)
282  fresult = combined_config->GetPdf()->fitTo(*obsdata, RooFit::Minimizer(_minimizer.Data(), _algorithm.Data()), RooFit::Save(), RooFit::Strategy(_fitstrategy), RooFit::Minos(_minoserror), RooFit::PrintLevel(1), RooFit::Constrain(*combined_config->GetPdf()->getParameters(*obsdata)), RooFit::Extended(), RooFit::Offset(true) );
283  else
284  fresult = combined_config->GetPdf()->fitTo(*obsdata, RooFit::Minimizer(_minimizer.Data(), _algorithm.Data()), RooFit::Save(), RooFit::Strategy(_fitstrategy), RooFit::Minos(_minoserror), RooFit::Constrain(*combined_config->GetPdf()->getParameters(*obsdata)), RooFit::Extended(), RooFit::Offset(true), RooFit::SumW2Error(true) );
285 
286  // Reset the verbosity
287  RooMsgService::instance().reset();
288 
289  return fresult;
290 
291 }
292 
293 //********************************************************************
295  //********************************************************************
296 
297  if(!ws){
298  std::cerr << "ERROR::NULL Workspace. Return empty fit!!" << std::endl;
299  return NULL;
300  }
301 
302  // Get the configuration model from workspace
303  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
304  if(!combined_config){
305  std::cerr << "ERROR::No model config " << "ModelConfig " << " in workspace. Return empty fit!!" << std::endl;
306  return NULL;
307  }
308 
309  // Dataset
310  RooAbsData *obsdata = ws->data("asimovData");
311 
312  RooFitResult* fresult = combined_config->GetPdf()->fitTo(*obsdata, RooFit::Minimizer(_minimizer.Data(), _algorithm.Data()), RooFit::Save(), RooFit::Strategy(_fitstrategy), RooFit::Minos(_minoserror), RooFit::Constrain(*combined_config->GetPdf()->getParameters(*obsdata)), RooFit::Extended(), RooFit::Offset(true));
313 
314  return fresult;
315 
316 }
317 
318 //********************************************************************
319 RooFitResult* protoana::MCToyGenerationAndFit::FitToyData(RooWorkspace* ws, RooAbsData* obsdata){
320  //********************************************************************
321 
322  if(!ws){
323  std::cerr << "ERROR::NULL Workspace. Return empty fit!!" << std::endl;
324  return NULL;
325  }
326 
327  // Get the configuration model from workspace
328  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
329  if(!combined_config){
330  std::cerr << "ERROR::No model config " << "ModelConfig " << " in workspace. Return empty fit!!" << std::endl;
331  return NULL;
332  }
333 
334  RooFitResult* fresult = combined_config->GetPdf()->fitTo(*obsdata, RooFit::Minimizer(_minimizer.Data(), _algorithm.Data()), RooFit::Save(), RooFit::Strategy(_fitstrategy), RooFit::Minos(_minoserror), RooFit::PrintLevel(1), RooFit::Constrain(*combined_config->GetPdf()->getParameters(*obsdata)), RooFit::Extended(), RooFit::Offset(true) );
335 
336  return fresult;
337 
338 }
339 
340 //********************************************************************
341 TTree* protoana::MCToyGenerationAndFit::FitToyMCFromWorkspace(std::vector<RooWorkspace*> wsvec, bool fitdata){
342  //********************************************************************
343 
344  // List to store all trees
345  TList *list = new TList;
346 
347  for(UInt_t j = 0 ; j < wsvec.size(); j++){
348  RooWorkspace* ws = wsvec.at(j);
349  if(fitdata){
350  RooFitResult* result = FitData(ws);
351  TTree *tree = RooFitResultToTTree(ws, result);
352  if(tree)
353  list->Add(tree);
354  }
355  else{
356  RooDataSet* dataset = (RooDataSet*)GenerateToyMC(ws);
357  RooFitResult* result = FitToyData(ws, dataset);
358  TTree *tree = RooFitResultToTTree(ws, result);
359  if(tree)
360  list->Add(tree);
361  }
362  }
363 
364  TTree *newtree = TTree::MergeTrees(list);
365  newtree->SetName("MCToysFromWorkspace");
366 
367  return newtree;
368 
369 }
370 
371 //********************************************************************
372 TTree* protoana::MCToyGenerationAndFit::RooFitResultToTTree(RooWorkspace* ws, RooFitResult* res){
373  //********************************************************************
374 
375  if(!ws){
376  std::cerr << "ERROR::NULL Workspace. Return empty fit!!" << std::endl;
377  return NULL;
378  }
379 
380  // Get the configuration model from workspace
381  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
382  if(!combined_config){
383  std::cerr << "ERROR::No model config " << "ModelConfig " << " in workspace. Return empty fit!!" << std::endl;
384  return NULL;
385  }
386 
387  RooAbsPdf* pdf = combined_config->GetPdf();
388  const RooArgSet* obs_set = combined_config->GetObservables();
389 
390  // Create mc study. Only used to store the fit result
391  RooMCStudy* mcstudy = new RooMCStudy( *pdf, *obs_set, RooFit::FitOptions("r"));
392  mcstudy->addFitResult(*res);
393 
394  TTree* myTree = RooMCStudyToTTree(mcstudy);
395 
396  delete mcstudy;
397 
398  return myTree;
399 
400 }
401 
402 //********************************************************************
404  //********************************************************************
405 
406  TTree* myTree = new TTree("mcstree","mcstree");
407 
408  const RooDataSet& toydata = mc->fitParDataSet();
409 
410  // fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult
411  // Minuit will return 0 if fit is good and 4 if fit failed (for example migrad did not converge)
412 
413  // Fit status for Migrad / improveResult (Migrad mininimization followed by an improved search for global minima)
414  //status = 0 : OK
415  //status = 1 : Covariance was made pos defined
416  //status = 2 : Hesse is invalid
417  //status = 3 : Edm is above max
418  //status = 4 : Reached call limit
419  //status = 5 : Any other failure
420 
421  // Fit status for Hesse
422  // status = 0 : OK
423  // status = 1 : hesse failed
424  // status = 2 : matrix inversion failed
425  // status = 3 : matrix is not pos defined
426 
427  // Fit status for Minos
428  // status = 0 : OK
429  // status = 1 : maximum number of function calls exceeded when running for lower error
430  // status = 2 : maximum number of function calls exceeded when running for upper error
431  // status = 3 : new minimum found when running for lower error
432  // status = 4 : new minimum found when running for upper error
433  // status = 5 : any other failure
434 
435  // Covariance matrix status (covQual)
436  // -1 : not available (inversion failed or Hesse failed)
437  // 0 : available but not positive defined
438  // 1 : covariance only approximate
439  // 2 : full matrix but forced pos def
440  // 3 : full accurate matrix
441 
442  Int_t covQual=0, status=0, numInvalidNLL=0;
443  Float_t minNll=0, edm=0;
444  myTree->Branch("covQual", &covQual, "covQual/I" );
445  myTree->Branch("status", &status, "status/I" );
446  myTree->Branch("numInvalidNLL", &numInvalidNLL, "numInvalidNLL/I" );
447  myTree->Branch("minNll", &minNll, "minNll/F" );
448  myTree->Branch("edm", &edm, "edm/F" );
449 
450  std::vector<Float_t> varVals;
451  const RooArgSet* args = toydata.get();
452  varVals.resize( args->getSize(), -999. );
453 
454  RooRealVar* var(0);
455  TIterator* Itr = args->createIterator();
456  for(Int_t i=0; (var = (RooRealVar*)Itr->Next()); ++i){
457  TString varName = var->GetName();
458  TString varNameF = TString(var->GetName()) + "/F";
459  myTree->Branch( varName.Data(), &varVals[i], varNameF.Data() );
460  }
461  delete Itr;
462 
463  // Save correlations between parameters
464  std::vector<Float_t> corrVals;
465  const RooArgList& fitparams = mc->fitResult(0)->floatParsFinal();
466  corrVals.resize( fitparams.getSize()*fitparams.getSize(), -999. );
467 
468  Int_t counter = 0;
469  for(Int_t i=0; i < fitparams.getSize(); ++i){
470  RooRealVar* fvar = (RooRealVar*)fitparams.at(i);
471  TString varName = fvar->GetName();
472  for(Int_t j=0; j < fitparams.getSize(); ++j){
473  if(j == i) continue;
474  RooRealVar* fvar2 = (RooRealVar*)fitparams.at(j);
475  TString varName2 = varName + TString("_corr_") + TString(fvar2->GetName());
476  TString varNameF = varName2 + "/F";
477  myTree->Branch( varName2.Data(), &corrVals[counter], varNameF.Data() );
478  counter++;
479  }
480  }
481 
482  // Fill the tree by looping over mcstudy
483  for(int iToy=0; iToy<toydata.numEntries(); iToy++){
484  const RooFitResult* result = mc->fitResult(iToy);
485  edm = result->edm();
486  covQual = result->covQual();
487  status = result->status();
488  minNll = result->minNll();
489  numInvalidNLL = result->numInvalidNLL();
490 
491  toydata.get(iToy); // reset args to new value
492  Itr = args->createIterator();
493  for (Int_t i=0; (var=(RooRealVar*)Itr->Next()); ++i) { varVals[i] = var->getVal(); }
494  delete Itr;
495 
496  const RooArgList& fparams = result->floatParsFinal();
497  counter = 0;
498  for(Int_t i=0; i < fparams.getSize(); ++i){
499  RooRealVar* fvar = (RooRealVar*)fparams.at(i);
500  for(Int_t j=0; j < fparams.getSize(); ++j){
501  if(j == i) continue;
502  RooRealVar* fvar2 = (RooRealVar*)fparams.at(j);
503  corrVals[counter] = result->correlation(fvar->GetName(), fvar2->GetName());
504  counter++;
505  }
506  }
507 
508  myTree->Fill();
509  }
510 
511  return myTree;
512 
513 }
514 
515 //********************************************************************
516 TTree* protoana::MCToyGenerationAndFit::RooDataSetToTTree(RooAbsData* data, TString treename){
517  //********************************************************************
518 
519  if(!data){
520  std::cerr << "ERROR::No RooAbsData. Will return NULL TTree!" << std::endl;
521  return NULL;
522  }
523 
524  TTree* myTree = new TTree(treename, treename);
525 
526  std::vector<Float_t> varVals;
527  const RooArgSet* args = data->get();
528  varVals.resize( args->getSize(), -999. );
529 
530  RooRealVar* var(0);
531  TIterator* Itr = args->createIterator();
532  for(Int_t i=0; (var = (RooRealVar*)Itr->Next()); ++i) {
533  TString varName = var->GetName();
534  TString varNameF = TString(var->GetName()) + "/F";
535  myTree->Branch( varName.Data(), &varVals[i], varNameF.Data() );
536  }
537  delete Itr;
538 
539  // Fill the tree by looping over mcstudy
540  for(int iToy=0; iToy<data->numEntries(); iToy++){
541  data->get(iToy); // reset args to new value
542  TIterator* Itr2 = args->createIterator();
543  for (Int_t i=0; (var=(RooRealVar*)Itr2->Next()); ++i) {varVals[i] = var->getVal();}
544  delete Itr2;
545 
546  myTree->Fill();
547  }
548 
549  return myTree;
550 
551 }
552 
553 //********************************************************************
554 RooArgSet* protoana::MCToyGenerationAndFit::GetChi2Set(RooWorkspace *work, RooAbsData* data){
555  //********************************************************************
556 
557  if(!work){
558  std::cerr << "ERROR::NULL workspace. Will return empty vector!" << std::endl;
559  return NULL;
560  }
561 
562  // Get pdf from workspace
563  RooSimultaneous* pdf = (RooSimultaneous*)work->pdf("simPdf");
564  if(!pdf){
565  std::cerr << "ERROR::No pdf found in workspace. Will return empty vector!" << std::endl;
566  return NULL;
567  }
568 
569  // If not provide, get data from workspace
570  if(!data)
571  data = work->data("obsData");
572 
573  // Get category components
574  RooCategory* categories = work->cat("channelCat");
575 
576  // Silence output
577  RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
578  RooMsgService::instance().getStream(1).removeTopic(RooFit::Plotting);
579 
580  std::vector<TString> categoriesName;
581  TIterator* iter = categories->typeIterator();
582  RooCatType* catType;
583  while( (catType = (RooCatType*) iter->Next())) {
584  TString catname = catType->GetName();
585  categoriesName.push_back(catname);
586  }
587 
588  RooArgSet* chi2varset = new RooArgSet("chi2varset");
589  for(UInt_t i = 0; i < categoriesName.size(); i++){
590  TString catname = categoriesName[i];
591 
592  if(categories->setLabel(catname)){
593  std::cout << "WARNING::Category " << catname.Data() << " is not a member of channelCat" << std::endl;
594  continue;
595  }
596 
597  RooAbsPdf* subpdf = (RooAbsPdf*)pdf->getPdf(catname.Data());
598  if(!subpdf){
599  std::cout << "WARNING::Can't find sub-pdf for region " << catname.Data() << std::endl;
600  continue;
601  }
602 
603  TString subdataset_str = Form("channelCat==channelCat::%s",catname.Data());
604  RooAbsData* subdataset = (RooAbsData*) data->reduce(subdataset_str.Data());
605  if(!subdataset){
606  std::cout << "WARNING::Can't find sub-dataset for region " << catname.Data() << std::endl;
607  continue;
608  }
609 
610  RooRealVar* var =(RooRealVar*) ((RooArgSet*) subpdf->getObservables(*subdataset))->find(Form("obs_x_%s", catname.Data()));
611 
612  RooPlot* frame_dummy = var->frame();
613  subdataset->plotOn(frame_dummy,RooFit::Cut(subdataset_str),RooFit::DataError(RooAbsData::Poisson));
614  subpdf->plotOn(frame_dummy,RooFit::Normalization(1,RooAbsReal::RelativeExpected),RooFit::Precision(1e-5));
615 
616  RooRealVar* chi2var = new RooRealVar(Form("%s_var",subpdf->GetName()), Form("%s_var",subpdf->GetTitle()), frame_dummy->chiSquare());
617  chi2varset->add(*chi2var);
618  }
619 
620  return chi2varset;
621 
622 }
623 
624 //********************************************************************
625 TTree* protoana::MCToyGenerationAndFit::GenerateChi2Tree(RooWorkspace* ws, int nexp, int seed){
626  //********************************************************************
627 
628  if(!ws){
629  std::cerr << "ERROR::NULL Workspace. Return empty fit!!" << std::endl;
630  return NULL;
631  }
632 
633  // Get the configuration model from workspace
634  RooStats::ModelConfig *combined_config = (RooStats::ModelConfig*)ws->obj("ModelConfig");
635  if(!combined_config){
636  std::cerr << "ERROR::No model config " << " ModelConfig " << " in workspace. Return empty fit!!" << std::endl;
637  return NULL;
638  }
639 
640  RooAbsPdf* pdf = combined_config->GetPdf();
641  if(!pdf){
642  std::cerr << "ERROR::No pdf found in ModelConfig. No dataset generated!" << std::endl;
643  return NULL;
644  }
645 
646  const RooArgSet* obs = combined_config->GetObservables();
647  const RooArgSet* globalobs = combined_config->GetGlobalObservables();
648  if(!obs){
649  std::cerr << "ERROR::No observables found in ModelConfig. No dataset generated!" << std::endl;
650  return NULL;
651  }
652 
653  const RooArgSet* pars = pdf->getParameters(obs);
654  RooArgList floatParList;
655  if(pars){
656  TIterator* iter = pars->createIterator();
657  RooAbsArg* arg;
658  while((arg=(RooAbsArg*)iter->Next())){
659  if(arg->InheritsFrom("RooRealVar") && !arg->isConstant()){
660  floatParList.add(*arg);
661  }
662  }
663  delete iter;
664  }
665 
666  // Reset values and errors to nominal
668  protoana::ProtoDUNEFitUtils::ResetError(ws, floatParList);
670 
671  // Silence the output
672  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
673 
674  RooDataSet* chi2dataset = NULL;
675 
676  for(int i=0; i<nexp; ++i) {
677  if(i%10==0)
678  std::cout << "INFO::Generating toy " << i << std::endl;
679 
680  RooRandom::randomGenerator()->SetSeed(seed + i);
681 
682  RooAbsData* toyMC = pdf->generate(*obs, RooFit::AutoBinned(false), RooFit::Extended());
683  toyMC->Print();
684 
685  RooFitResult* toyfitresult = FitToyData(ws,toyMC);
686 
687  RooArgSet* chi2set = GetChi2Set(ws,toyMC);
688  if(i==0){
689  chi2dataset = new RooDataSet("chi2dataset","chi2dataset",*chi2set);
690  }
691 
692  // Only consider good quality fits
693  if(toyfitresult->status() == 0)
694  chi2dataset->add(*chi2set);
695 
697  protoana::ProtoDUNEFitUtils::ResetError(ws, floatParList);
699  }
700 
701  // Reset verbosity
702  RooMsgService::instance().reset();
703 
704  TTree* chi2_tree = RooDataSetToTTree(chi2dataset, "chi2tree");
705 
706  return chi2_tree;
707 
708 }
void ResetValues(RooWorkspace *ws, const RooArgList &parList)
TTree * RooMCStudyToTTree(RooMCStudy *mc)
RooFitResult * FitData(RooWorkspace *ws, bool isWeighted=false)
static QCString varName
static QCString result
std::string string
Definition: nybbler.cc:12
char & at(uint i) const
Definition: qcstring.h:326
const std::string instance
static QCString args
Definition: declinfo.cpp:674
QAsciiDict< Entry > cl
TTree * RooDataSetToTTree(RooAbsData *data, TString treename)
const double e
RooFitResult * FitAsimovData(RooWorkspace *w)
TTree * GenerateChi2Tree(RooWorkspace *ws, int nexp, int seed)
void ResetValuesToNominal(RooWorkspace *ws, const RooArgSet &parSet)
FixedTimeOffsetTool::Offset Offset
RooArgSet * GetChi2Set(RooWorkspace *work, RooAbsData *data)
int var
Definition: 018_def.c:9
TTree * FitToyMCFromWorkspace(std::vector< RooWorkspace * > wsvec, bool fitdata)
TTree * GenerateAndFit(RooWorkspace *ws, int nexp)
void ResetError(RooWorkspace *ws, const RooArgList &parList)
RooAbsData * GenerateToyMC(RooWorkspace *ws, bool datanorm=true)
TTree * RooFitResultToTTree(RooWorkspace *ws, RooFitResult *res)
RooFitResult * GenerateAndFitOneToy(RooWorkspace *ws)
RooFitResult * FitToyData(RooWorkspace *w, RooAbsData *obsdata)
QTextStream & endl(QTextStream &s)
#define ERROR