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