Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HistoToWorkspaceFactory.cxx
Go to the documentation of this file.
1// @(#)root/roostats:$Id: cranmer $
2// Author: Kyle Cranmer, Akira Shibata
3/*************************************************************************
4 * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
5 * All rights reserved. *
6 * *
7 * For the licensing terms see $ROOTSYS/LICENSE. *
8 * For the list of contributors see $ROOTSYS/README/CREDITS. *
9 *************************************************************************/
10
11////////////////////////////////////////////////////////////////////////////////
12
13/** \class RooStats::HistFactory::HistoToWorkspaceFactory
14 * \ingroup HistFactory
15 */
16
17
18#ifndef __CINT__
19#include "RooGlobalFunc.h"
20#endif
21
22// Roofit/Roostat include
23#include "RooDataSet.h"
24#include "RooRealVar.h"
25#include "RooConstVar.h"
26#include "RooAddition.h"
27#include "RooProduct.h"
28#include "RooProdPdf.h"
29#include "RooAddPdf.h"
30#include "RooGaussian.h"
31#include "RooExponential.h"
32#include "RooRandom.h"
33#include "RooCategory.h"
34#include "RooSimultaneous.h"
35#include "RooMultiVarGaussian.h"
36#include "RooNumIntConfig.h"
37#include "RooNLLVar.h"
38#include "RooProfileLL.h"
39#include "RooFitResult.h"
40#include "RooDataHist.h"
41#include "RooHistPdf.h"
42#include "RooWorkspace.h"
43#include "RooCustomizer.h"
44#include "RooPlot.h"
45#include "RooMsgService.h"
48
49#include "TFile.h"
50#include "TCanvas.h"
51#include "TH1.h"
52#include "TLine.h"
53#include "TTree.h"
54#include "TStopwatch.h"
55#include "TStyle.h"
56#include "TVectorD.h"
57#include "TMatrixDSym.h"
58
59// specific to this package
62#include "Helper.h"
63
64#define VERBOSE
65
66#define alpha_Low "-5"
67#define alpha_High "5"
68#define NoHistConst_Low "0"
69#define NoHistConst_High "2000"
70
71// use this order for safety on library loading
72using namespace RooFit ;
73using namespace RooStats ;
74using namespace std ;
75//using namespace RooMsgService ;
76
78
79namespace RooStats{
80namespace HistFactory{
81
83 fNomLumi(0),
84 fLumiError(0),
85 fLowBin(0),
86 fHighBin(0),
87 fOut_f(0),
88 pFile(0)
89 {
90 }
91
93 fclose(pFile);
94 }
95
96 HistoToWorkspaceFactory::HistoToWorkspaceFactory(string filePrefix, string row, vector<string> syst, double nomL, double lumiE, int low, int high, TFile* f):
97 fFileNamePrefix(filePrefix),
98 fRowTitle(row),
99 fSystToFix(syst),
100 fNomLumi(nomL),
101 fLumiError(lumiE),
102 fLowBin(low),
103 fHighBin(high),
104 fOut_f(f) {
105
106 // fResultsPrefixStr<<"results" << "_" << fNomLumi<< "_" << fLumiError<< "_" << fLowBin<< "_" << fHighBin;
108 while(fRowTitle.find("\\ ")!=string::npos){
109 int pos=fRowTitle.find("\\ ");
110 fRowTitle.replace(pos, 1, "");
111 }
112 pFile = fopen ((filePrefix+"_results.table").c_str(),"a");
113 //RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;
114
115 }
116
118
119 stringstream ss;
120 ss << prefix << "_" << fNomLumi<< "_" << fLumiError<< "_" << fLowBin<< "_" << fHighBin<< "_"<<fRowTitle;
121
122 return ss.str();
123 }
124
125 void HistoToWorkspaceFactory::ProcessExpectedHisto(TH1* hist,RooWorkspace* proto, string prefix, string productPrefix, string systTerm, double low, double high, int lowBin, int highBin){
126 if(hist)
127 cout << "processing hist " << hist->GetName() << endl;
128 else
129 cout << "hist is empty" << endl;
130 RooArgSet argset(prefix.c_str());
131 string highStr = "inf";
132 for(Int_t i=lowBin; i<highBin; ++i){
133 std::stringstream str;
134 std::stringstream range;
135 str<<"_"<<i;
136 if(hist)
137 range<<"["<<hist->GetBinContent(i+1) << "," << low << "," << highStr << "]";
138 else
139 range<<"["<< low << "," << high << "]";
140 cout << "for bin N"+str.str() << " var " << prefix+str.str()+" with range " << range.str() << endl;
141 RooRealVar* var = (RooRealVar*) proto->factory((prefix+str.str()+range.str()).c_str());
142
143 // now create the product of the overall efficiency times the sigma(params) for this estimate
144 if(! (productPrefix.empty() || systTerm.empty()) )
145 proto->factory(("prod:"+productPrefix+str.str()+"("+prefix+str.str()+","+systTerm+")").c_str() );
146
147 var->setConstant();
148 argset.add(* var );
149 }
150 proto->defineSet(prefix.c_str(),argset);
151 // proto->Print();
152 }
153
154 void HistoToWorkspaceFactory::AddMultiVarGaussConstraint(RooWorkspace* proto, string prefix,int lowBin, int highBin, vector<string>& likelihoodTermNames){
155 // these are the nominal predictions: eg. the mean of some space of variations
156 // later fill these in a loop over histogram bins
157 TVectorD mean(highBin-lowBin);
158 cout << "a" << endl;
159 for(Int_t i=lowBin; i<highBin; ++i){
160 std::stringstream str;
161 str<<"_"<<i;
162 RooRealVar* temp = proto->var((prefix+str.str()).c_str());
163 mean(i) = temp->getVal();
164 }
165
166 TMatrixDSym Cov(highBin-lowBin);
167 for(int i=lowBin; i<highBin; ++i){
168 for(int j=0; j<highBin-lowBin; ++j){
169 if(i==j)
170 Cov(i,j) = sqrt(mean(i));
171 else
172 Cov(i,j) = 0;
173 }
174 }
175 // can't make MultiVarGaussian with factory yet, do it by hand
176 RooArgList floating( *(proto->set(prefix.c_str() ) ) );
177 RooMultiVarGaussian constraint((prefix+"Constraint").c_str(),"",
178 floating, mean, Cov);
179
180 proto->import(constraint);
181
182 likelihoodTermNames.push_back(constraint.GetName());
183
184 }
185
186
187 void HistoToWorkspaceFactory::LinInterpWithConstraint(RooWorkspace* proto, TH1* nominal, vector<TH1*> lowHist, vector<TH1*> highHist,
188 vector<string> sourceName, string prefix, string productPrefix, string systTerm,
189 int lowBin, int highBin, vector<string>& likelihoodTermNames){
190 // these are the nominal predictions: eg. the mean of some space of variations
191 // later fill these in a loop over histogram bins
192
193 // make list of abstract parameters that interpolate in space of variations
194 RooArgList params( ("alpha_Hist") );
195 // range is set using defined macro (see top of the page)
196 string range=string("[")+alpha_Low+","+alpha_High+"]";
197 for(unsigned int j=0; j<lowHist.size(); ++j){
198 std::stringstream str;
199 str<<"_"<<j;
200
201 RooRealVar* temp = (RooRealVar*) proto->var(("alpha_"+sourceName.at(j)).c_str());
202 if(!temp){
203 temp = (RooRealVar*) proto->factory(("alpha_"+sourceName.at(j)+range).c_str());
204
205 // now add a constraint term for these parameters
206 string command=("Gaussian::alpha_"+sourceName.at(j)+"Constraint(alpha_"+sourceName.at(j)+",nom_"+sourceName.at(j)+"[0.,-10,10],1.)");
207 cout << command << endl;
208 likelihoodTermNames.push_back( proto->factory( command.c_str() )->GetName() );
209 proto->var(("nom_"+sourceName.at(j)).c_str())->setConstant();
210 const_cast<RooArgSet*>(proto->set("globalObservables"))->add(*proto->var(("nom_"+sourceName.at(j)).c_str()));
211
212 }
213
214 params.add(* temp );
215
216 }
217
218 // now make function that linearly interpolates expectation between variations
219 for(Int_t i=lowBin; i<highBin; ++i){
220 std::stringstream str;
221 str<<"_"<<i;
222
223 // get low/high variations to interpolate between
224 vector<double> low, high;
225 for(unsigned int j=0; j<lowHist.size(); ++j){
226 low.push_back( lowHist.at(j)->GetBinContent(i+1) );
227 high.push_back( highHist.at(j)->GetBinContent(i+1) );
228 cout << "for "+prefix+" bin "+str.str()+" creating linear interp of nominal " << nominal->GetBinContent(i+1)
229 << " in parameter " << sourceName.at(j)
230 << " between " << low.back() << " - " << high.back()
231 << " about " << 100.*fabs(low.back() - high.back() )/nominal->GetBinContent(i+1) << " % error"
232 << endl;
233 }
234
235 // this is sigma(params), a piece-wise linear interpolation
236 LinInterpVar interp( (prefix+str.str()).c_str(), "", params, nominal->GetBinContent(i+1), low, high);
237
238 // cout << "check: " << interp.getVal() << endl;
239 proto->import(interp); // individual params have already been imported in first loop of this function
240
241 // now create the product of the overall efficiency times the sigma(params) for this estimate
242 proto->factory(("prod:"+productPrefix+str.str()+"("+prefix+str.str()+","+systTerm+")").c_str() );
243
244 }
245
246 }
247
248 string HistoToWorkspaceFactory::AddNormFactor(RooWorkspace * proto, string & channel, string & sigmaEpsilon, EstimateSummary & es, bool doRatio){
249 string overallNorm_times_sigmaEpsilon ;
250 string prodNames;
251 vector<EstimateSummary::NormFactor> norm=es.normFactor;
252 if(norm.size()){
253 for(vector<EstimateSummary::NormFactor>::iterator itr=norm.begin(); itr!=norm.end(); ++itr){
254 cout << "making normFactor: " << itr->name << endl;
255 // remove "doRatio" and name can be changed when ws gets imported to the combined model.
256 std::stringstream range;
257 range<<"["<<itr->val<<","<<itr->low<<","<<itr->high<<"]";
258 //RooRealVar* var = 0;
259
260 string varname;
261 if(!prodNames.empty()) prodNames+=",";
262 if(doRatio) {
263 varname=itr->name+"_"+channel;
264 }
265 else {
266 varname=itr->name;
267 }
268 proto->factory((varname+range.str()).c_str());
269 if(itr->constant){
270 // proto->var(varname.c_str())->setConstant();
271 // cout <<"setting " << varname << " constant"<<endl;
272 cout <<"WARNING: Const attribute to <NormFactor> tag is deprecated, will ignore."<<
273 " Instead, add \n\t<ParamSetting Const=\"True\">"<<varname<<"</ParamSetting>\n"<<
274 " to your top-level XML's <Measurment> entry"<< endl;
275 }
276 prodNames+=varname;
277 }
278 overallNorm_times_sigmaEpsilon = es.name+"_"+channel+"_overallNorm_x_sigma_epsilon";
279 proto->factory(("prod::"+overallNorm_times_sigmaEpsilon+"("+prodNames+","+sigmaEpsilon+")").c_str());
280 }
281
282 if(!overallNorm_times_sigmaEpsilon.empty())
283 return overallNorm_times_sigmaEpsilon;
284 else
285 return sigmaEpsilon;
286 }
287
288
289 void HistoToWorkspaceFactory::AddEfficiencyTerms(RooWorkspace* proto, string prefix, string interpName,
290 map<string,pair<double,double> > systMap,
291 vector<string>& likelihoodTermNames, vector<string>& totSystTermNames){
292 // add variables for all the relative overall uncertainties we expect
293
294 // range is set using defined macro (see top of the page)
295 string range=string("[0,")+alpha_Low+","+alpha_High+"]";
296 //string range="[0,-1,1]";
297 totSystTermNames.push_back(prefix);
298 //bool first=true;
299 RooArgSet params(prefix.c_str());
300 vector<double> lowVec, highVec;
301 for(map<string,pair<double,double> >::iterator it=systMap.begin(); it!=systMap.end(); ++it){
302 // add efficiency term
303 RooRealVar* temp = (RooRealVar*) proto->var((prefix+ it->first).c_str());
304 if(!temp){
305 temp = (RooRealVar*) proto->factory((prefix+ it->first +range).c_str());
306
307 string command=("Gaussian::"+prefix+it->first+"Constraint("+prefix+it->first+",nom_"+prefix+it->first+"[0.,-10,10],1.)");
308 cout << command << endl;
309 likelihoodTermNames.push_back( proto->factory( command.c_str() )->GetName() );
310 proto->var(("nom_"+prefix+it->first).c_str())->setConstant();
311 const_cast<RooArgSet*>(proto->set("globalObservables"))->add(*proto->var(("nom_"+prefix+it->first).c_str()));
312
313 }
314 params.add(*temp);
315
316 // add constraint in terms of bifrucated gauss with low/high as sigmas
317 std::stringstream lowhigh;
318 double low = it->second.first;
319 double high = it->second.second;
320 lowVec.push_back(low);
321 highVec.push_back(high);
322
323 }
324 if(systMap.size()>0){
325 // this is epsilon(alpha_j), a piece-wise linear interpolation
326 LinInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec);
327 proto->import(interp); // params have already been imported in first loop of this function
328 } else{
329 // some strange behavior if params,lowVec,highVec are empty.
330 //cout << "WARNING: No OverallSyst terms" << endl;
331 RooConstVar interp( (interpName).c_str(), "", 1.);
332 proto->import(interp); // params have already been imported in first loop of this function
333 }
334
335 }
336
337
338 void HistoToWorkspaceFactory::MakeTotalExpected(RooWorkspace* proto, string totName, string /**/, string /**/,
339 int lowBin, int highBin, vector<string>& syst_x_expectedPrefixNames,
340 vector<string>& normByNames){
341
342 // for ith bin calculate totN_i = lumi * sum_j expected_j * syst_j
343
344 for(Int_t i=lowBin; i<highBin; ++i){
345 std::stringstream str;
346 str<<"_"<<i;
347 string command="sum::"+totName+str.str()+"(";
348 //vector<string>::iterator it=syst_x_expectedPrefixNames.begin();
349 string prepend="";
350 for(unsigned int j=0; j<syst_x_expectedPrefixNames.size();++j){
351 command+=prepend+normByNames.at(j)+"*"+syst_x_expectedPrefixNames.at(j)+str.str();
352 prepend=",";
353 }
354 command+=")";
355 cout << "function to calculate total: " << command << endl;
356 proto->factory(command.c_str());
357 }
358 }
359
360 void HistoToWorkspaceFactory::AddPoissonTerms(RooWorkspace* proto, string prefix, string obsPrefix, string expPrefix, int lowBin, int highBin,
361 vector<string>& likelihoodTermNames){
362 /////////////////////////////////
363 // Relate observables to expected for each bin
364 // later modify variable named expPrefix_i to be product of terms
365 RooArgSet Pois(prefix.c_str());
366 for(Int_t i=lowBin; i<highBin; ++i){
367 std::stringstream str;
368 str<<"_"<<i;
369 //string command("Poisson::"+prefix+str.str()+"("+obsPrefix+str.str()+","+expPrefix+str.str()+")");
370 string command("Poisson::"+prefix+str.str()+"("+obsPrefix+str.str()+","+expPrefix+str.str()+",1)");//for no rounding
371 RooAbsArg* temp = (proto->factory( command.c_str() ) );
372
373 // output
374 cout << "Poisson Term " << command << endl;
375 ((RooAbsPdf*) temp)->setEvalErrorLoggingMode(RooAbsReal::PrintErrors);
376 //cout << temp << endl;
377
378 likelihoodTermNames.push_back( temp->GetName() );
379 Pois.add(* temp );
380 }
381 proto->defineSet(prefix.c_str(),Pois); // add argset to workspace
382 }
383
384 void HistoToWorkspaceFactory::SetObsToExpected(RooWorkspace* proto, string obsPrefix, string expPrefix, int lowBin, int highBin){
385 /////////////////////////////////
386 // set observed to expected
387 TTree* tree = new TTree();
388 Double_t* obsForTree = new Double_t[highBin-lowBin];
389 RooArgList obsList("obsList");
390
391 for(Int_t i=lowBin; i<highBin; ++i){
392 std::stringstream str;
393 str<<"_"<<i;
394 RooRealVar* obs = (RooRealVar*) proto->var((obsPrefix+str.str()).c_str());
395 cout << "expected number of events called: " << expPrefix << endl;
396 RooAbsReal* exp = proto->function((expPrefix+str.str()).c_str());
397 if(obs && exp){
398
399 //proto->Print();
400 obs->setVal( exp->getVal() );
401 cout << "setting obs"+str.str()+" to expected = " << exp->getVal() << " check: " << obs->getVal() << endl;
402
403 // add entry to array and attach to tree
404 obsForTree[i] = exp->getVal();
405 tree->Branch((obsPrefix+str.str()).c_str(), obsForTree+i ,(obsPrefix+str.str()+"/D").c_str());
406 obsList.add(*obs);
407 }else{
408 cout << "problem retrieving obs or exp " << obsPrefix+str.str() << obs << " " << expPrefix+str.str() << exp << endl;
409 }
410 }
411 tree->Fill();
412 RooDataSet* data = new RooDataSet("expData","", tree, obsList); // one experiment
413
414 proto->import(*data);
415 delete[] obsForTree;
416 obsForTree = nullptr;
417 }
418
419 void HistoToWorkspaceFactory::Customize(RooWorkspace* proto, const char* pdfNameChar, map<string,string> renameMap) {
420 cout << "in customizations" << endl;
421 string pdfName(pdfNameChar);
422 map<string,string>::iterator it;
423 string edit="EDIT::customized("+pdfName+",";
424 string precede="";
425 for(it=renameMap.begin(); it!=renameMap.end(); ++it) {
426 cout << it->first + "=" + it->second << endl;
427 edit+=precede + it->first + "=" + it->second;
428 precede=",";
429 }
430 edit+=")";
431 cout << edit<< endl;
432 proto->factory( edit.c_str() );
433 }
434
435 //////////////////////////////////////////////////////////////////////////////
436 /// cout << "in edit, gammamap.size = " << gammaSyst.size() << ", unimap.size = " << uniformSyst.size() << endl;
437
438 void HistoToWorkspaceFactory::EditSyst(RooWorkspace* proto, const char* pdfNameChar, map<string,double> gammaSyst, map<string,double> uniformSyst,map<string,double> logNormSyst) {
439 string pdfName(pdfNameChar);
440
441 ModelConfig * combined_config = (ModelConfig *) proto->obj("ModelConfig");
442 // const RooArgSet * constrainedParams=combined_config->GetNuisanceParameters();
443 // RooArgSet temp(*constrainedParams);
444 string edit="EDIT::newSimPdf("+pdfName+",";
445 string editList;
446 string lastPdf=pdfName;
447 string precede="";
448 unsigned int numReplacements = 0;
449 unsigned int nskipped = 0;
450 map<string,double>::iterator it;
451
452 // add gamma terms and their constraints
453 for(it=gammaSyst.begin(); it!=gammaSyst.end(); ++it) {
454 //cout << "edit for " << it->first << "with rel uncert = " << it->second << endl;
455 if(! proto->var(("alpha_"+it->first).c_str())){
456 //cout << "systematic not there" << endl;
457 nskipped++;
458 continue;
459 }
460 numReplacements++;
461
462 double relativeUncertainty = it->second;
463 double scale = 1/sqrt((1+1/pow(relativeUncertainty,2)));
464
465 // this is the Gamma PDF and in a form that doesn't have roundoff problems like the Poisson does
466 proto->factory(Form("beta_%s[1,0,10]",it->first.c_str()));
467 proto->factory(Form("y_%s[%f]",it->first.c_str(),1./pow(relativeUncertainty,2))) ;
468 proto->factory(Form("theta_%s[%f]",it->first.c_str(),pow(relativeUncertainty,2))) ;
469 proto->factory(Form("Gamma::beta_%sConstraint(beta_%s,sum::k_%s(y_%s,one[1]),theta_%s,zero[0])",
470 it->first.c_str(),
471 it->first.c_str(),
472 it->first.c_str(),
473 it->first.c_str(),
474 it->first.c_str())) ;
475
476 /*
477 // this has some problems because N in poisson is rounded to nearest integer
478 proto->factory(Form("Poisson::beta_%sConstraint(y_%s[%f],prod::taub_%s(taus_%s[%f],beta_%s[1,0,5]))",
479 it->first.c_str(),
480 it->first.c_str(),
481 1./pow(relativeUncertainty,2),
482 it->first.c_str(),
483 it->first.c_str(),
484 1./pow(relativeUncertainty,2),
485 it->first.c_str()
486 ) ) ;
487 */
488 // combined->factory(Form("expr::alphaOfBeta('(beta-1)/%f',beta)",scale));
489 // combined->factory(Form("expr::alphaOfBeta_%s('(beta_%s-1)/%f',beta_%s)",it->first.c_str(),it->first.c_str(),scale,it->first.c_str()));
490 proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",it->first.c_str(),it->first.c_str(),-1./scale,1./scale));
491
492 // set beta const status to be same as alpha
493 if(proto->var(Form("alpha_%s",it->first.c_str()))->isConstant())
494 proto->var(Form("beta_%s",it->first.c_str()))->setConstant(true);
495 else
496 proto->var(Form("beta_%s",it->first.c_str()))->setConstant(false);
497 // set alpha const status to true
498 // proto->var(Form("alpha_%s",it->first.c_str()))->setConstant(true);
499
500 // replace alphas with alphaOfBeta and replace constraints
501 //cout << "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint" << endl;
502 editList+=precede + "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint";
503 precede=",";
504 // cout << "alpha_"+it->first+"=alphaOfBeta_"+ it->first << endl;
505 editList+=precede + "alpha_"+it->first+"=alphaOfBeta_"+ it->first;
506
507 /*
508 if( proto->pdf(("alpha_"+it->first+"Constraint").c_str()) && proto->var(("alpha_"+it->first).c_str()) )
509 cout << " checked they are there" << proto->pdf(("alpha_"+it->first+"Constraint").c_str()) << " " << proto->var(("alpha_"+it->first).c_str()) << endl;
510 else
511 cout << "NOT THERE" << endl;
512 */
513
514 // EDIT seems to die if the list of edits is too long. So chunck them up.
515 if(numReplacements%10 == 0 && numReplacements+nskipped!=gammaSyst.size()){
516 edit="EDIT::"+lastPdf+"_("+lastPdf+","+editList+")";
517 lastPdf+="_"; // append an underscore for the edit
518 editList=""; // reset edit list
519 precede="";
520 cout << "Going to issue this edit command\n" << edit<< endl;
521 proto->factory( edit.c_str() );
522 RooAbsPdf* newOne = proto->pdf(lastPdf.c_str());
523 if(!newOne)
524 cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
525
526 }
527 }
528
529 // add uniform terms and their constraints
530 for(it=uniformSyst.begin(); it!=uniformSyst.end(); ++it) {
531 cout << "edit for " << it->first << "with rel uncert = " << it->second << endl;
532 if(! proto->var(("alpha_"+it->first).c_str())){
533 cout << "systematic not there" << endl;
534 nskipped++;
535 continue;
536 }
537 numReplacements++;
538
539 // this is the Uniform PDF
540 proto->factory(Form("beta_%s[1,0,10]",it->first.c_str()));
541 proto->factory(Form("Uniform::beta_%sConstraint(beta_%s)",it->first.c_str(),it->first.c_str()));
542 proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{-1,1})",it->first.c_str(),it->first.c_str()));
543
544 // set beta const status to be same as alpha
545 if(proto->var(Form("alpha_%s",it->first.c_str()))->isConstant())
546 proto->var(Form("beta_%s",it->first.c_str()))->setConstant(true);
547 else
548 proto->var(Form("beta_%s",it->first.c_str()))->setConstant(false);
549 // set alpha const status to true
550 // proto->var(Form("alpha_%s",it->first.c_str()))->setConstant(true);
551
552 // replace alphas with alphaOfBeta and replace constraints
553 cout << "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint" << endl;
554 editList+=precede + "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint";
555 precede=",";
556 cout << "alpha_"+it->first+"=alphaOfBeta_"+ it->first << endl;
557 editList+=precede + "alpha_"+it->first+"=alphaOfBeta_"+ it->first;
558
559 if( proto->pdf(("alpha_"+it->first+"Constraint").c_str()) && proto->var(("alpha_"+it->first).c_str()) )
560 cout << " checked they are there" << proto->pdf(("alpha_"+it->first+"Constraint").c_str()) << " " << proto->var(("alpha_"+it->first).c_str()) << endl;
561 else
562 cout << "NOT THERE" << endl;
563
564 // EDIT seems to die if the list of edits is too long. So chunck them up.
565 if(numReplacements%10 == 0 && numReplacements+nskipped!=gammaSyst.size()){
566 edit="EDIT::"+lastPdf+"_("+lastPdf+","+editList+")";
567 lastPdf+="_"; // append an underscore for the edit
568 editList=""; // reset edit list
569 precede="";
570 cout << edit<< endl;
571 proto->factory( edit.c_str() );
572 RooAbsPdf* newOne = proto->pdf(lastPdf.c_str());
573 if(!newOne)
574 cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
575
576 }
577 }
578
579 /////////////////////////////////////////
580 ////////////////////////////////////
581
582
583 // add lognormal terms and their constraints
584 for(it=logNormSyst.begin(); it!=logNormSyst.end(); ++it) {
585 cout << "edit for " << it->first << "with rel uncert = " << it->second << endl;
586 if(! proto->var(("alpha_"+it->first).c_str())){
587 cout << "systematic not there" << endl;
588 nskipped++;
589 continue;
590 }
591 numReplacements++;
592
593 double relativeUncertainty = it->second;
594 double kappa = 1+relativeUncertainty;
595 // when transforming beta -> alpha, need alpha=1 to be +1sigma value.
596 // the P(beta>kappa*\hat(beta)) = 16%
597 // and \hat(beta) is 1, thus
598 double scale = relativeUncertainty;
599 //double scale = kappa;
600
601 // this is the LogNormal
602 proto->factory(Form("beta_%s[1,0,10]",it->first.c_str()));
603 proto->factory(Form("kappa_%s[%f]",it->first.c_str(),kappa));
604 proto->factory(Form("Lognormal::beta_%sConstraint(beta_%s,one[1],kappa_%s)",
605 it->first.c_str(),
606 it->first.c_str(),
607 it->first.c_str())) ;
608 proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",it->first.c_str(),it->first.c_str(),-1./scale,1./scale));
609 // proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",it->first.c_str(),it->first.c_str(),-1.,1./scale));
610
611 // set beta const status to be same as alpha
612 if(proto->var(Form("alpha_%s",it->first.c_str()))->isConstant())
613 proto->var(Form("beta_%s",it->first.c_str()))->setConstant(true);
614 else
615 proto->var(Form("beta_%s",it->first.c_str()))->setConstant(false);
616 // set alpha const status to true
617 // proto->var(Form("alpha_%s",it->first.c_str()))->setConstant(true);
618
619 // replace alphas with alphaOfBeta and replace constraints
620 cout << "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint" << endl;
621 editList+=precede + "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint";
622 precede=",";
623 cout << "alpha_"+it->first+"=alphaOfBeta_"+ it->first << endl;
624 editList+=precede + "alpha_"+it->first+"=alphaOfBeta_"+ it->first;
625
626 if( proto->pdf(("alpha_"+it->first+"Constraint").c_str()) && proto->var(("alpha_"+it->first).c_str()) )
627 cout << " checked they are there" << proto->pdf(("alpha_"+it->first+"Constraint").c_str()) << " " << proto->var(("alpha_"+it->first).c_str()) << endl;
628 else
629 cout << "NOT THERE" << endl;
630
631 // EDIT seems to die if the list of edits is too long. So chunck them up.
632 if(numReplacements%10 == 0 && numReplacements+nskipped!=gammaSyst.size()){
633 edit="EDIT::"+lastPdf+"_("+lastPdf+","+editList+")";
634 lastPdf+="_"; // append an underscore for the edit
635 editList=""; // reset edit list
636 precede="";
637 cout << edit<< endl;
638 proto->factory( edit.c_str() );
639 RooAbsPdf* newOne = proto->pdf(lastPdf.c_str());
640 if(!newOne)
641 cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
642
643 }
644 }
645
646 /////////////////////////////////////////
647 ////////////////////////////////////
648
649 // commit last bunch of edits
650 edit="EDIT::newSimPdf("+lastPdf+","+editList+")";
651 cout << edit<< endl;
652 proto->factory( edit.c_str() );
653 // proto->writeToFile(("results/model_"+fRowTitle+"_edited.root").c_str());
654 RooAbsPdf* newOne = proto->pdf("newSimPdf");
655 if(newOne){
656 // newOne->graphVizTree(("results/"+pdfName+"_"+fRowTitle+"newSimPdf.dot").c_str());
657 combined_config->SetPdf(*newOne);
658 }
659 else{
660 cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
661 }
662 }
663
665 // FILE * pFile;
666 pFile = fopen ((filename).c_str(),"w");
667
668
669 TIter iti = params->createIterator();
670 TIter itj = params->createIterator();
671 RooRealVar *myargi, *myargj;
672 fprintf(pFile," ") ;
673 while ((myargi = (RooRealVar *)iti.Next())) {
674 if(myargi->isConstant()) continue;
675 fprintf(pFile," & %s", myargi->GetName());
676 }
677 fprintf(pFile,"\\\\ \\hline \n" );
678 iti.Reset();
679 while ((myargi = (RooRealVar *)iti.Next())) {
680 if(myargi->isConstant()) continue;
681 fprintf(pFile,"%s", myargi->GetName());
682 itj.Reset();
683 while ((myargj = (RooRealVar *)itj.Next())) {
684 if(myargj->isConstant()) continue;
685 cout << myargi->GetName() << "," << myargj->GetName();
686 fprintf(pFile, " & %.2f", result->correlation(*myargi, *myargj));
687 }
688 cout << endl;
689 fprintf(pFile, " \\\\\n");
690 }
691 fclose(pFile);
692
693 }
694
695
696 ///////////////////////////////////////////////
697 RooWorkspace* HistoToWorkspaceFactory::MakeSingleChannelModel(vector<EstimateSummary> summary, vector<string> systToFix, bool doRatio)
698 {
699
700 if (summary.empty() ) {
701 Error("MakeSingleChannelModel","vector of EstimateSummry is empty - return a nullptr");
702 return 0;
703 }
704
705 // to time the macro
706 TStopwatch t;
707 t.Start();
708 string channel=summary[0].channel;
709 cout << "\n\n-------------------\nStarting to process " << channel << " channel" << endl;
710
711 //
712 // our main workspace that we are using to construct the model
713 //
714 RooWorkspace* proto = new RooWorkspace("proto","proto workspace");
715 ModelConfig * proto_config = new ModelConfig("ModelConfig", proto);
716 proto_config->SetWorkspace(*proto);
717
718 RooArgSet likelihoodTerms("likelihoodTerms");
719 vector<string> likelihoodTermNames, totSystTermNames,syst_x_expectedPrefixNames, normalizationNames;
720
721 string prefix, range;
722
723 /////////////////////////////
724 // Make observables, set values to observed data if data is specified,
725 // otherwise use expected "Asimov" data
726 if (summary.at(0).name=="Data") {
727 ProcessExpectedHisto(summary.at(0).nominal,proto,"obsN","","",0,100000,fLowBin,fHighBin);
728 } else {
729 cout << "Will use expected (\"Asimov\") data set" << endl;
730 ProcessExpectedHisto(NULL,proto,"obsN","","",0,100000,fLowBin,fHighBin);
731 }
732
733
734
735 /////////////////////////////
736 // shared parameters
737 // this is ratio of lumi to nominal lumi. We will include relative uncertainty in model
738 std::stringstream lumiStr;
739 // lumi range
740 lumiStr<<"["<<fNomLumi<<",0,"<<10.*fNomLumi<<"]";
741 proto->factory(("Lumi"+lumiStr.str()).c_str());
742 cout << "lumi str = " << lumiStr.str() << endl;
743
744 std::stringstream lumiErrorStr;
745 // lumiErrorStr << "nominalLumi["<<fNomLumi << "]," << fLumiError ;
746 lumiErrorStr << "nominalLumi["<<fNomLumi << ",0,"<<fNomLumi+10*fLumiError<<"]," << fLumiError ;
747 proto->factory(("Gaussian::lumiConstraint(Lumi,"+lumiErrorStr.str()+")").c_str());
748 proto->var("nominalLumi")->setConstant();
749 proto->defineSet("globalObservables","nominalLumi");
750 likelihoodTermNames.push_back("lumiConstraint");
751 cout << "lumi Error str = " << lumiErrorStr.str() << endl;
752
753 //proto->factory((string("SigXsecOverSM[1.,0.5,1..8]").c_str()));
754 ///////////////////////////////////
755 // loop through estimates, add expectation, floating bin predictions,
756 // and terms that constrain floating to expectation via uncertainties
757 vector<EstimateSummary>::iterator it = summary.begin();
758 for(; it!=summary.end(); ++it){
759 if(it->name=="Data") continue;
760
761 string overallSystName = it->name+"_"+it->channel+"_epsilon";
762 string systSourcePrefix = "alpha_";
763 AddEfficiencyTerms(proto,systSourcePrefix, overallSystName,
764 it->overallSyst,
765 likelihoodTermNames, totSystTermNames);
766
767 overallSystName=AddNormFactor(proto, channel, overallSystName, *it, doRatio);
768 // get histogram
769 TH1* nominal = it->nominal;
770 if(it->lowHists.size() == 0){
771 cout << it->name+"_"+it->channel+" has no variation histograms " <<endl;
772 string expPrefix=it->name+"_"+it->channel+"_expN";
773 string syst_x_expectedPrefix=it->name+"_"+it->channel+"_overallSyst_x_Exp";
774 ProcessExpectedHisto(nominal,proto,expPrefix,syst_x_expectedPrefix,overallSystName,atoi(NoHistConst_Low),atoi(NoHistConst_High),fLowBin,fHighBin);
775 syst_x_expectedPrefixNames.push_back(syst_x_expectedPrefix);
776 } else if(it->lowHists.size() != it->highHists.size()){
777 cout << "problem in "+it->name+"_"+it->channel
778 << " number of low & high variation histograms don't match" << endl;
779 return 0;
780 } else {
781 string constraintPrefix = it->name+"_"+it->channel+"_Hist_alpha"; // name of source for variation
782 string syst_x_expectedPrefix = it->name+"_"+it->channel+"_overallSyst_x_HistSyst";
783 LinInterpWithConstraint(proto, nominal, it->lowHists, it->highHists, it->systSourceForHist,
784 constraintPrefix, syst_x_expectedPrefix, overallSystName,
785 fLowBin, fHighBin, likelihoodTermNames);
786 syst_x_expectedPrefixNames.push_back(syst_x_expectedPrefix);
787 }
788
789 // AddMultiVarGaussConstraint(proto, "exp"+it->first+"N", fLowBin, fHighBin, likelihoodTermNames);
790
791 if(it->normName=="")
792 normalizationNames.push_back( "Lumi" );
793 else
794 normalizationNames.push_back( it->normName);
795 }
796 //proto->Print();
797
798 ///////////////////////////////////
799 // for ith bin calculate totN_i = lumi * sum_j expected_j * syst_j
800 MakeTotalExpected(proto,channel+"_totN",channel+"_expN","Lumi",fLowBin,fHighBin,
801 syst_x_expectedPrefixNames, normalizationNames);
802
803 /////////////////////////////////
804 // Relate observables to expected for each bin
805 AddPoissonTerms(proto, "Pois_"+channel, "obsN", channel+"_totN", fLowBin, fHighBin, likelihoodTermNames);
806
807 /////////////////////////////////
808 // if no data histogram provided, make asimov data
809 if(summary.at(0).name!="Data"){
810 SetObsToExpected(proto, "obsN",channel+"_totN", fLowBin, fHighBin);
811 cout << " using asimov data" << endl;
812 } else{
813 SetObsToExpected(proto, "obsN","obsN", fLowBin, fHighBin);
814 cout << " using input data histogram" << endl;
815 }
816
817 //////////////////////////////////////
818 // fix specified parameters
819 for(unsigned int i=0; i<systToFix.size(); ++i){
820 RooRealVar* temp = proto->var((systToFix.at(i)).c_str());
821 if(temp) temp->setConstant();
822 else cout << "could not find variable " << systToFix.at(i) << " could not set it to constant" << endl;
823 }
824
825 //////////////////////////////////////
826 // final proto model
827 for(unsigned int i=0; i<likelihoodTermNames.size(); ++i){
828 // cout << likelihoodTermNames[i] << endl;
829 likelihoodTerms.add(* (proto->arg(likelihoodTermNames[i].c_str())) );
830 }
831 // likelihoodTerms.Print();
832
833 proto->defineSet("likelihoodTerms",likelihoodTerms);
834 // proto->Print();
835
836 cout <<"-----------------------------------------"<<endl;
837 cout <<"import model into workspace" << endl;
838 RooProdPdf* model = new RooProdPdf(("model_"+channel).c_str(),
839 "product of Poissons accross bins for a single channel",
840 likelihoodTerms);
841 proto->import(*model,RecycleConflictNodes());
842
843 proto_config->SetPdf(*model);
844 proto_config->SetGlobalObservables(*proto->set("globalObservables"));
845
846 proto->import(*proto_config,proto_config->GetName());
847 proto->importClassCode();
848 // proto->writeToFile(("results/model_"+channel+".root").c_str());
849
850 return proto;
851 }
852
853 RooWorkspace* HistoToWorkspaceFactory::MakeCombinedModel(vector<string> ch_names, vector<RooWorkspace*> chs)
854 {
855
856 //
857 /// These things were used for debugging. Maybe useful in the future
858 //
859 // RooAbsReal::defaultIntegratorConfig()->setEpsAbs(1e-8) ;
860 // RooAbsReal::defaultIntegratorConfig()->setEpsRel(1e-8) ;
861 // RooMsgService::instance().setGlobalKillBelow(RooMsgService::WARNING);
862 // RooMsgService::instance().setGlobalKillBelow(RooMsgService::WARNING) ;
863 // cout << "MsgSvc: " << RooMsgService::instance().globalKillBelow() << " INFO "
864 // << RooMsgService::INFO << " WARNING " << RooMsgService::WARNING << endl;
865
866 // RooArgSet* constrainedParams= new RooArgSet("constrainedParams");
867
868 // check inputs (see JIRA-6890)
869 if (ch_names.empty() || chs.empty() ) {
870 Error("MakeCombinedModel","Input vectors are empty - return a nullptr");
871 return 0;
872 }
873 if (chs.size() < ch_names.size() ) {
874 Error("MakeCombinedModel","Input vector of workspace has an invalid size - return a nullptr");
875 return 0;
876 }
877
878 map<string, RooAbsPdf*> pdfMap;
879 vector<RooAbsPdf*> models;
880 stringstream ss;
881
882 RooArgSet globalObs;
883 for(unsigned int i = 0; i< ch_names.size(); ++i){
884 string channel_name=ch_names[i];
885
886 if (ss.str().empty()) ss << channel_name ;
887 else ss << ',' << channel_name ;
888 RooWorkspace * ch=chs[i];
889
890 RooAbsPdf* model = ch->pdf(("model_"+channel_name).c_str());
891 models.push_back(model);
892 globalObs.add(*ch->set("globalObservables"));
893
894 // constrainedParams->add( * ch->set("constrainedParams") );
895 pdfMap[channel_name]=model;
896 }
897 //constrainedParams->Print();
898
899 cout << "\n\n------------------\n Entering combination" << endl;
900 RooWorkspace* combined = new RooWorkspace("combined");
901
902 RooCategory* channelCat = (RooCategory*) combined->factory(("channelCat["+ss.str()+"]").c_str());
903 RooSimultaneous * simPdf= new RooSimultaneous("simPdf","",pdfMap, *channelCat);
904 ModelConfig * combined_config = new ModelConfig("ModelConfig", combined);
905 combined_config->SetWorkspace(*combined);
906 // combined_config->SetNuisanceParameters(*constrainedParams);
907 combined->import(globalObs);
908 combined->defineSet("globalObservables",globalObs);
909 combined_config->SetGlobalObservables(*combined->set("globalObservables"));
910
911 ////////////////////////////////////////////
912 // Make toy simultaneous dataset
913 cout <<"-----------------------------------------"<<endl;
914 cout << "create toy data for " << ss.str() << endl;
915
916 const RooArgSet* obsN = chs[0]->set("obsN");
917
918 RooDataSet * simData=new RooDataSet("simData","master dataset", *obsN,
919 Index(*channelCat), Import(ch_names[0].c_str(),*((RooDataSet*)chs[0]->data("expData"))));
920 for(unsigned int i = 1; i< ch_names.size(); ++i){
921 RooDataSet * simData_ch=new RooDataSet("simData","master dataset", *obsN,
922 Index(*channelCat), Import(ch_names[i].c_str(),*((RooDataSet*)chs[i]->data("expData"))));
923 simData->append(*simData_ch);
924 }
925 //for(int i=0; i<simData->numEntries(); ++i)
926 // simData->get(i)->Print("v");
927
928 combined->import(*simData,RecycleConflictNodes());
929
930 cout << "\n\n----------------\n Importing combined model" << endl;
931 combined->import(*simPdf,RecycleConflictNodes());
932 //combined->import(*simPdf, RenameVariable("SigXsecOverSM","SigXsecOverSM_comb"));
933 cout << "check pointer " << simPdf << endl;
934
935 for(unsigned int i=0; i<fSystToFix.size(); ++i){
936 // make sure they are fixed
937 RooRealVar* temp = combined->var((fSystToFix.at(i)).c_str());
938 if(temp) {
939 temp->setConstant();
940 cout <<"setting " << fSystToFix.at(i) << " constant" << endl;
941 }
942 else cout << "could not find variable " << fSystToFix.at(i) << " could not set it to constant" << endl;
943 }
944
945 ///
946 /// writing out the model in graphViz
947 ///
948 // RooAbsPdf* customized=combined->pdf("simPdf");
949 //combined_config->SetPdf(*customized);
950 combined_config->SetPdf(*simPdf);
951 // customized->graphVizTree(("results/"+fResultsPrefixStr.str()+"_simul.dot").c_str());
952 combined->import(*combined_config,combined_config->GetName());
953 combined->importClassCode();
954 // combined->writeToFile("results/model_combined.root");
955
956 return combined;
957 }
958
959 ///////////////////////////////////////////////
960 void HistoToWorkspaceFactory::FitModel(RooWorkspace * combined, string channel, string /*model_name*/, string data_name, bool /*doParamInspect*/)
961 {
962
963 ModelConfig * combined_config = (ModelConfig *) combined->obj("ModelConfig");
964 RooDataSet * simData = (RooDataSet *) combined->obj(data_name.c_str());
965 // const RooArgSet * constrainedParams=combined_config->GetNuisanceParameters();
966 const RooArgSet * POIs=combined_config->GetParametersOfInterest();
967
968 /*
969 RooRealVar* poi = (RooRealVar*) combined->var("SigXsecOverSM");
970 RooArgSet * params= new RooArgSet;
971 params->add(*poi);
972 combined_config->SetParameters(*params);
973
974 RooAbsData* expData = combined->data("expData");
975 RooArgSet* temp = (RooArgSet*) combined->set("obsN")->Clone("temp");
976 temp->add(*poi);
977 RooAbsPdf* model=combined_config->GetPdf();
978 RooArgSet* constrainedParams = model->getParameters(temp);
979 combined->defineSet("constrainedParams", *constrainedParams);
980 */
981
982 //RooAbsPdf* model=combined->pdf(model_name.c_str());
983 RooAbsPdf* model=combined_config->GetPdf();
984 // RooArgSet* allParams = model->getParameters(*simData);
985
986 ///////////////////////////////////////
987 //Do combined fit
988 //RooMsgService::instance().setGlobalKillBelow(RooMsgService::INFO) ;
989 cout << "\n\n---------------" << endl;
990 cout << "---------------- Doing "<< channel << " Fit" << endl;
991 cout << "---------------\n\n" << endl;
992 // RooFitResult* result = model->fitTo(*simData, Minos(kTRUE), Save(kTRUE), PrintLevel(1));
993 model->fitTo(*simData, Minos(kTRUE), PrintLevel(1));
994 // PrintCovarianceMatrix(result, allParams, "results/"+FilePrefixStr(channel)+"_corrMatrix.table" );
995
996 //
997 // assuming there is only on poi
998 //
999 RooRealVar* poi = 0; // (RooRealVar*) POIs->first();
1000 // for results tables
1001 TIterator* params_itr=POIs->createIterator();
1002 TObject* params_obj=0;
1003 while((params_obj=params_itr->Next())){
1004 poi = (RooRealVar*) params_obj;
1005 cout << "printing results for " << poi->GetName() << " at " << poi->getVal()<< " high " << poi->getErrorLo() << " low " << poi->getErrorHi()<<endl;
1006 }
1007 delete params_itr;
1008 if (!poi) {
1009 cerr << "found no POI" << endl;
1010 return;
1011 }
1012 fprintf(pFile, " %.4f / %.4f ", poi->getErrorLo(), poi->getErrorHi());
1013
1014 RooAbsReal* nll = model->createNLL(*simData);
1015 RooAbsReal* profile = nll->createProfile(*poi);
1016 RooPlot* frame = poi->frame();
1018 TCanvas* c1 = new TCanvas( channel.c_str(), "",800,600);
1019 nll->plotOn(frame, ShiftToZero(), LineColor(kRed), LineStyle(kDashed));
1020 profile->plotOn(frame);
1021 frame->SetMinimum(0);
1022 frame->SetMaximum(2.);
1023 frame->Draw();
1024 // c1->SaveAs( ("results/"+FilePrefixStr(channel)+"_profileLR.eps").c_str() );
1025 c1->SaveAs( (fFileNamePrefix+"_"+channel+"_"+fRowTitle+"_profileLR.eps").c_str() );
1026
1027 fOut_f->mkdir(channel.c_str())->mkdir("Summary")->cd();
1028
1029 // an example of calculating profile for a nuisance parameter not poi
1030 /*
1031 RooRealVar* alpha_isrfsr = (RooRealVar*) combined->var("alpha_isrfsr");
1032 RooAbsReal* profile_isrfsr = nll->createProfile(*alpha_isrfsr);
1033 poi->setVal(0.55);
1034 poi->setConstant();
1035
1036 RooPlot* frame_isrfsr = alpha_isrfsr->frame();
1037 profile_isrfsr->plotOn(frame_isrfsr, Precision(0.1));
1038 TCanvas c_isrfsr = new TCanvas( "combined", "",800,600);
1039 FormatFrameForLikelihood(frame_isrfsr, "alpha_{isrfsr}");
1040 frame_isrfsr->Draw();
1041 fOut_f->cd("Summary");
1042 c1->Write((FilePrefixStr(channel).str()+"_profileLR_alpha_isrfsr").c_str() );
1043 delete frame; delete c1;
1044 poi->setConstant(kFALSE);
1045 */
1046
1047 RooCurve* curve=frame->getCurve();
1048 Int_t curve_N=curve->GetN();
1049 Double_t* curve_x=curve->GetX();
1050 delete frame; delete c1;
1051
1052 Double_t * x_arr = new Double_t[curve_N];
1053 Double_t * y_arr_nll = new Double_t[curve_N];
1054// Double_t y_arr_prof_nll[curve_N];
1055// Double_t y_arr_prof[curve_N];
1056
1057 for(int i=0; i<curve_N; i++){
1058 double f=curve_x[i];
1059 poi->setVal(f);
1060 x_arr[i]=f;
1061 y_arr_nll[i]=nll->getVal();
1062 }
1063 TGraph * g = new TGraph(curve_N, x_arr, y_arr_nll);
1064 g->SetName((FilePrefixStr(channel)+"_nll").c_str());
1065 g->Write();
1066 delete g;
1067 delete [] x_arr;
1068 delete [] y_arr_nll;
1069
1070 /** find out what's inside the workspace **/
1071 //combined->Print();
1072
1073 }
1074
1075
1076void HistoToWorkspaceFactory::FormatFrameForLikelihood(RooPlot* frame, string /*XTitle*/, string YTitle){
1077
1080 gStyle->SetPadColor(0);
1081 gStyle->SetCanvasColor(255);
1084 gStyle->SetStatColor(255);
1085
1086 RooAbsRealLValue* var = frame->getPlotVar();
1087 double xmin = var->getMin();
1088 double xmax = var->getMax();
1089
1090 frame->SetTitle("");
1091 // frame->GetXaxis()->SetTitle(XTitle.c_str());
1092 frame->GetXaxis()->SetTitle(var->GetTitle());
1093 frame->GetYaxis()->SetTitle(YTitle.c_str());
1094 frame->SetMaximum(2.);
1095 frame->SetMinimum(0.);
1096 TLine * line = new TLine(xmin,.5,xmax,.5);
1098 TLine * line90 = new TLine(xmin,2.71/2.,xmax,2.71/2.);
1099 line90->SetLineColor(kGreen);
1100 TLine * line95 = new TLine(xmin,3.84/2.,xmax,3.84/2.);
1101 line95->SetLineColor(kGreen);
1102 frame->addObject(line);
1103 frame->addObject(line90);
1104 frame->addObject(line95);
1105 }
1106
1108 if(! file) return file;
1109 string path="";
1110 TDirectory* ptr=0;
1111 for(vector<string>::iterator itr=names.begin(); itr != names.end(); ++itr){
1112 if( ! path.empty() ) path+="/";
1113 path+=(*itr);
1114 ptr=file->GetDirectory(path.c_str());
1115 if( ! ptr ) ptr=file->mkdir((*itr).c_str());
1116 file=file->GetDirectory(path.c_str());
1117 }
1118 return ptr;
1119 }
1121 if(! file) return file;
1122 TDirectory* ptr=0;
1123 ptr=file->GetDirectory(name.c_str());
1124 if( ! ptr ) ptr=file->mkdir(name.c_str());
1125 return ptr;
1126 }
1127
1128}
1129}
1130
#define alpha_Low
#define alpha_High
#define NoHistConst_High
#define NoHistConst_Low
#define f(i)
Definition RSha256.hxx:104
#define g(i)
Definition RSha256.hxx:105
const Bool_t kTRUE
Definition RtypesCore.h:100
#define ClassImp(name)
Definition Rtypes.h:364
@ kRed
Definition Rtypes.h:66
@ kGreen
Definition Rtypes.h:66
@ kDashed
Definition TAttLine.h:48
char name[80]
Definition TGX11.cxx:110
float xmin
float xmax
char * Form(const char *fmt,...)
R__EXTERN TStyle * gStyle
Definition TStyle.h:413
const char * proto
Definition civetweb.c:16613
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition RooAbsArg.h:69
Bool_t isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:377
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
TIterator * createIterator(Bool_t dir=kIterForward) const
TIterator-style iteration over contained elements.
virtual RooAbsReal * createNLL(RooAbsData &data, const RooLinkedList &cmdList)
Construct representation of -log(L) of PDFwith given dataset.
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.
RooAbsRealLValue is the common abstract base class for objects that represent a real value that may a...
virtual Double_t getMax(const char *name=0) const
Get maximum of currently defined range.
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,...
void setConstant(Bool_t value=kTRUE)
virtual Double_t getMin(const char *name=0) const
Get miniminum of currently defined range.
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition RooAbsReal.h:64
virtual RooAbsReal * createProfile(const RooArgSet &paramsOfInterest)
Create a RooProfileLL object that eliminates all nuisance parameters in the present function.
virtual RooPlot * plotOn(RooPlot *frame, const RooCmdArg &arg1=RooCmdArg(), const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg(), const RooCmdArg &arg9=RooCmdArg(), const RooCmdArg &arg10=RooCmdArg()) const
Plot (project) PDF on specified frame.
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:94
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:35
RooCategory is an object to represent discrete states.
Definition RooCategory.h:27
RooConstVar represent a constant real-valued object.
Definition RooConstVar.h:26
A RooCurve is a one-dimensional graphical representation of a real-valued function.
Definition RooCurve.h:32
RooDataSet is a container class to hold unbinned data.
Definition RooDataSet.h:36
void append(RooDataSet &data)
Add all data points of given data set to this data set.
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Double_t correlation(const RooAbsArg &par1, const RooAbsArg &par2) const
Return correlation between par1 and par2.
Multivariate Gaussian p.d.f.
A RooPlot is a plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:44
void addObject(TObject *obj, Option_t *drawOptions="", Bool_t invisible=kFALSE)
Add a generic object to this plot.
Definition RooPlot.cxx:392
void SetTitle(const char *name)
Set the title of the RooPlot to 'title'.
Definition RooPlot.cxx:1257
virtual void SetMinimum(Double_t minimum=-1111)
Set minimum value of Y axis.
Definition RooPlot.cxx:1061
TAxis * GetYaxis() const
Definition RooPlot.cxx:1278
RooAbsRealLValue * getPlotVar() const
Definition RooPlot.h:136
TAxis * GetXaxis() const
Definition RooPlot.cxx:1276
virtual void SetMaximum(Double_t maximum=-1111)
Set maximum value of Y axis.
Definition RooPlot.cxx:1051
RooCurve * getCurve(const char *name=0) const
Return a RooCurve pointer of the named object in this plot, or zero if the named object does not exis...
Definition RooPlot.cxx:877
virtual void Draw(Option_t *options=0)
Draw this plot and all of the elements it contains.
Definition RooPlot.cxx:661
RooProdPdf is an efficient implementation of a product of PDFs of the form.
Definition RooProdPdf.h:33
RooRealVar represents a variable that can be changed from the outside.
Definition RooRealVar.h:39
Double_t getErrorHi() const
Definition RooRealVar.h:72
Double_t getErrorLo() const
Definition RooRealVar.h:71
virtual void setVal(Double_t value)
Set value of variable to 'value'.
RooSimultaneous facilitates simultaneous fitting of multiple PDFs to subsets of a given dataset.
TDirectory * Mkdir(TDirectory *file, std::string name)
void SetObsToExpected(RooWorkspace *proto, std::string obsPrefix, std::string expPrefix, int lowBin, int highBin)
void EditSyst(RooWorkspace *proto, const char *pdfNameChar, std::map< std::string, double > gammaSyst, std::map< std::string, double > uniformSyst, std::map< std::string, double > logNormSyst)
cout << "in edit, gammamap.size = " << gammaSyst.size() << ", unimap.size = " << uniformSyst....
void FormatFrameForLikelihood(RooPlot *frame, std::string XTitle=std::string("#sigma / #sigma_{SM}"), std::string YTitle=std::string("-log likelihood"))
void AddPoissonTerms(RooWorkspace *proto, std::string prefix, std::string obsPrefix, std::string expPrefix, int lowBin, int highBin, std::vector< std::string > &likelihoodTermNames)
std::string AddNormFactor(RooWorkspace *, std::string &, std::string &, EstimateSummary &, bool)
void Customize(RooWorkspace *proto, const char *pdfNameChar, std::map< std::string, std::string > renameMap)
void MakeTotalExpected(RooWorkspace *proto, std::string totName, std::string, std::string, int lowBin, int highBin, std::vector< std::string > &syst_x_expectedPrefixNames, std::vector< std::string > &normByNames)
void PrintCovarianceMatrix(RooFitResult *result, RooArgSet *params, std::string filename)
void AddMultiVarGaussConstraint(RooWorkspace *proto, std::string prefix, int lowBin, int highBin, std::vector< std::string > &likelihoodTermNames)
void FitModel(RooWorkspace *, std::string, std::string, std::string, bool=false)
void LinInterpWithConstraint(RooWorkspace *proto, TH1 *nominal, std::vector< TH1 * > lowHist, std::vector< TH1 * > highHist, std::vector< std::string > sourceName, std::string prefix, std::string productPrefix, std::string systTerm, int lowBin, int highBin, std::vector< std::string > &likelihoodTermNames)
RooWorkspace * MakeCombinedModel(std::vector< std::string >, std::vector< RooWorkspace * >)
void ProcessExpectedHisto(TH1 *hist, RooWorkspace *proto, std::string prefix, std::string productPrefix, std::string systTerm, double low, double high, int lowBin, int highBin)
RooWorkspace * MakeSingleChannelModel(std::vector< RooStats::HistFactory::EstimateSummary > summary, std::vector< std::string > systToFix, bool doRatio=false)
TDirectory * Makedirs(TDirectory *file, std::vector< std::string > names)
void AddEfficiencyTerms(RooWorkspace *proto, std::string prefix, std::string interpName, std::map< std::string, std::pair< double, double > > systMap, std::vector< std::string > &likelihoodTermNames, std::vector< std::string > &totSystTermNames)
RooAbsReal that does piecewise-linear interpolations.
ModelConfig is a simple class that holds configuration information specifying how a model should be u...
Definition ModelConfig.h:30
virtual void SetWorkspace(RooWorkspace &ws)
Definition ModelConfig.h:66
const RooArgSet * GetParametersOfInterest() const
get RooArgSet containing the parameter of interest (return NULL if not existing)
virtual void SetGlobalObservables(const RooArgSet &set)
Specify the global observables.
RooAbsPdf * GetPdf() const
get model PDF (return NULL if pdf has not been specified or does not exist)
virtual void SetPdf(const RooAbsPdf &pdf)
Set the Pdf, add to the the workspace if not already there.
Definition ModelConfig.h:81
The RooWorkspace is a persistable container for RooFit projects.
Bool_t import(const RooAbsArg &arg, const RooCmdArg &arg1=RooCmdArg(), const RooCmdArg &arg2=RooCmdArg(), const RooCmdArg &arg3=RooCmdArg(), const RooCmdArg &arg4=RooCmdArg(), const RooCmdArg &arg5=RooCmdArg(), const RooCmdArg &arg6=RooCmdArg(), const RooCmdArg &arg7=RooCmdArg(), const RooCmdArg &arg8=RooCmdArg(), const RooCmdArg &arg9=RooCmdArg())
Import a RooAbsArg object, e.g.
Bool_t importClassCode(const char *pat="*", Bool_t doReplace=kFALSE)
Inport code of all classes in the workspace that have a class name that matches pattern 'pat' and whi...
Bool_t defineSet(const char *name, const RooArgSet &aset, Bool_t importMissing=kFALSE)
Define a named RooArgSet with given constituents.
RooRealVar * var(const char *name) const
Retrieve real-valued variable (RooRealVar) with given name. A null pointer is returned if not found.
RooFactoryWSTool & factory()
Return instance to factory tool.
const RooArgSet * set(const char *name)
Return pointer to previously defined named set with given nmame If no such set is found a null pointe...
TObject * obj(const char *name) const
Return any type of object (RooAbsArg, RooAbsData or generic object) with given name)
RooAbsPdf * pdf(const char *name) const
Retrieve p.d.f (RooAbsPdf) with given name. A null pointer is returned if not found.
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition TAttLine.h:40
The Canvas class.
Definition TCanvas.h:23
TDirectory * mkdir(const char *name, const char *title="", Bool_t returnExistingDirectory=kFALSE) override
Create a sub-directory "a" or a hierarchy of sub-directories "a/b/c/...".
Describe directory structure in memory.
Definition TDirectory.h:45
virtual Bool_t cd()
Change current directory to "this" directory.
virtual TDirectory * mkdir(const char *name, const char *title="", Bool_t returnExistingDirectory=kFALSE)
Create a sub-directory "a" or a hierarchy of sub-directories "a/b/c/...".
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format.
Definition TFile.h:54
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
Int_t GetN() const
Definition TGraph.h:125
Double_t * GetX() const
Definition TGraph.h:132
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:58
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition TH1.cxx:4994
TObject * Next()
void Reset()
Iterator abstract base class.
Definition TIterator.h:30
virtual TObject * Next()=0
Use the TLine constructor to create a simple line.
Definition TLine.h:22
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:164
virtual const char * GetTitle() const
Returns title of object.
Definition TNamed.h:48
virtual const char * GetName() const
Returns name of object.
Definition TNamed.h:47
Mother of all ROOT objects.
Definition TObject.h:41
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:429
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:963
Stopwatch class.
Definition TStopwatch.h:28
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void SetPadBorderMode(Int_t mode=1)
Definition TStyle.h:340
void SetFrameFillColor(Color_t color=1)
Definition TStyle.h:355
void SetCanvasColor(Color_t color=19)
Definition TStyle.h:327
void SetCanvasBorderMode(Int_t mode=1)
Definition TStyle.h:329
void SetTitleFillColor(Color_t color=1)
Definition TStyle.h:387
void SetStatColor(Color_t color=19)
Definition TStyle.h:373
void SetPadColor(Color_t color=19)
Definition TStyle.h:338
A TTree represents a columnar dataset.
Definition TTree.h:79
TLine * line
RooCmdArg RecycleConflictNodes(Bool_t flag=kTRUE)
RooCmdArg Index(RooCategory &icat)
RooCmdArg Import(const char *state, TH1 &histo)
RooCmdArg PrintLevel(Int_t code)
RooCmdArg Minos(Bool_t flag=kTRUE)
RooCmdArg ShiftToZero()
RooCmdArg LineColor(Color_t color)
RooCmdArg LineStyle(Style_t style)
return c1
Definition legend1.C:41
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition Common.h:18
Namespace for the RooStats classes.
Definition Asimov.h:19
Definition file.py:1
Definition tree.py:1
std::vector< NormFactor > normFactor