HistoToWorkspaceFactory.cxx

Go to the documentation of this file.
00001 // @(#)root/roostats:$Id:  cranmer $
00002 // Author: Kyle Cranmer, Akira Shibata
00003 /*************************************************************************
00004  * Copyright (C) 1995-2008, Rene Brun and Fons Rademakers.               *
00005  * All rights reserved.                                                  *
00006  *                                                                       *
00007  * For the licensing terms see $ROOTSYS/LICENSE.                         *
00008  * For the list of contributors see $ROOTSYS/README/CREDITS.             *
00009  *************************************************************************/
00010 
00011 //_________________________________________________
00012 /*
00013 BEGIN_HTML
00014 <p>
00015 </p>
00016 END_HTML
00017 */
00018 //
00019 
00020 
00021 #ifndef __CINT__
00022 #include "RooGlobalFunc.h"
00023 #endif
00024 
00025 // Roofit/Roostat include
00026 #include "RooDataSet.h"
00027 #include "RooRealVar.h"
00028 #include "RooConstVar.h"
00029 #include "RooAddition.h"
00030 #include "RooProduct.h"
00031 #include "RooProdPdf.h"
00032 #include "RooAddPdf.h"
00033 #include "RooGaussian.h"
00034 #include "RooExponential.h"
00035 #include "RooRandom.h"
00036 #include "RooCategory.h"
00037 #include "RooSimultaneous.h"
00038 #include "RooMultiVarGaussian.h"
00039 #include "RooNumIntConfig.h"
00040 #include "RooMinuit.h"
00041 #include "RooNLLVar.h"
00042 #include "RooProfileLL.h"
00043 #include "RooFitResult.h"
00044 #include "RooDataHist.h"
00045 #include "RooHistPdf.h"
00046 #include "RooProduct.h"
00047 #include "RooWorkspace.h"
00048 #include "RooCustomizer.h"
00049 #include "RooPlot.h"
00050 #include "RooMsgService.h"
00051 #include "RooStats/RooStatsUtils.h"
00052 #include "RooStats/ModelConfig.h"
00053 
00054 #include "TH2F.h"
00055 #include "TH3F.h"
00056 #include "TFile.h"
00057 #include "TCanvas.h"
00058 #include "TH1F.h"
00059 #include "TLine.h"
00060 #include "TTree.h"
00061 #include "TMarker.h"
00062 #include "TStopwatch.h"
00063 #include "TROOT.h"
00064 #include "TStyle.h"
00065 #include "TVectorD.h"
00066 #include "TMatrixDSym.h"
00067 
00068 // specific to this package
00069 //#include "RooStats/HistFactory/Helper.h"
00070 #include "Helper.h"
00071 #include "RooStats/HistFactory/LinInterpVar.h"
00072 #include "RooStats/HistFactory/HistoToWorkspaceFactory.h"
00073 
00074 #define VERBOSE
00075 
00076 #define alpha_Low "-5"
00077 #define alpha_High "5"
00078 #define NoHistConst_Low "0"
00079 #define NoHistConst_High "2000"
00080 
00081 // use this order for safety on library loading
00082 using namespace RooFit ;
00083 using namespace RooStats ;
00084 using namespace std ;
00085 //using namespace RooMsgService ;
00086 
00087 ClassImp(RooStats::HistFactory::HistoToWorkspaceFactory)
00088 
00089 namespace RooStats{
00090 namespace HistFactory{
00091 
00092   HistoToWorkspaceFactory::HistoToWorkspaceFactory(){}
00093   HistoToWorkspaceFactory::~HistoToWorkspaceFactory(){
00094     fclose(pFile);
00095   }
00096 
00097   HistoToWorkspaceFactory::HistoToWorkspaceFactory(string filePrefix, string row, vector<string> syst, double nomL, double lumiE, int low, int high, TFile* f):
00098       fFileNamePrefix(filePrefix),
00099       fRowTitle(row),
00100       fSystToFix(syst),
00101       fNomLumi(nomL),
00102       fLumiError(lumiE),
00103       fLowBin(low),
00104       fHighBin(high),
00105       fOut_f(f) {
00106 
00107     //    fResultsPrefixStr<<"results" << "_" << fNomLumi<< "_" << fLumiError<< "_" << fLowBin<< "_" << fHighBin;
00108     fResultsPrefixStr<< "_" << fRowTitle;
00109     while(fRowTitle.find("\\ ")!=string::npos){
00110       int pos=fRowTitle.find("\\ ");
00111       fRowTitle.replace(pos, 1, "");
00112     }
00113     pFile = fopen ((filePrefix+"_results.table").c_str(),"a"); 
00114     //RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;
00115 
00116   }
00117 
00118   string HistoToWorkspaceFactory::FilePrefixStr(string prefix){
00119 
00120     stringstream ss;
00121     ss << prefix << "_" << fNomLumi<< "_" << fLumiError<< "_" << fLowBin<< "_" << fHighBin<< "_"<<fRowTitle;
00122 
00123     return ss.str();
00124   }
00125 
00126   void HistoToWorkspaceFactory::ProcessExpectedHisto(TH1F* hist,RooWorkspace* proto, string prefix, string productPrefix, string systTerm, double low, double high, int lowBin, int highBin){
00127     if(hist)
00128       cout << "processing hist " << hist->GetName() << endl;
00129     else
00130       cout << "hist is empty" << endl;
00131     RooArgSet argset(prefix.c_str());
00132     string highStr = "inf";
00133     for(Int_t i=lowBin; i<highBin; ++i){
00134       std::stringstream str;
00135       std::stringstream range;
00136       str<<"_"<<i;
00137       if(hist)
00138         range<<"["<<hist->GetBinContent(i+1) << "," << low << "," << highStr << "]";
00139       else
00140         range<<"["<< low << "," << high << "]";
00141       cout << "for bin N"+str.str() << " var " << prefix+str.str()+" with range " << range.str() << endl;
00142       RooRealVar* var = (RooRealVar*) proto->factory((prefix+str.str()+range.str()).c_str());
00143 
00144       // now create the product of the overall efficiency times the sigma(params) for this estimate
00145       if(! (productPrefix.empty() || systTerm.empty()) )
00146          proto->factory(("prod:"+productPrefix+str.str()+"("+prefix+str.str()+","+systTerm+")").c_str() );
00147 
00148       var->setConstant();
00149       argset.add(* var );
00150     }
00151     proto->defineSet(prefix.c_str(),argset);
00152     // proto->Print();
00153   }
00154 
00155   void HistoToWorkspaceFactory::AddMultiVarGaussConstraint(RooWorkspace* proto, string prefix,int lowBin, int highBin, vector<string>& likelihoodTermNames){
00156     // these are the nominal predictions: eg. the mean of some space of variations
00157     // later fill these in a loop over histogram bins
00158     TVectorD mean(highBin-lowBin);
00159     cout << "a" << endl;
00160     for(Int_t i=lowBin; i<highBin; ++i){
00161       std::stringstream str;
00162       str<<"_"<<i;
00163       RooRealVar* temp = proto->var((prefix+str.str()).c_str());
00164       mean(i) = temp->getVal();
00165     }
00166 
00167     TMatrixDSym Cov(highBin-lowBin);
00168     for(int i=lowBin; i<highBin; ++i){
00169       for(int j=0; j<highBin-lowBin; ++j){
00170         if(i==j) 
00171     Cov(i,j) = sqrt(mean(i));
00172         else
00173     Cov(i,j) = 0;
00174       }
00175     }
00176     // can't make MultiVarGaussian with factory yet, do it by hand
00177     RooArgList floating( *(proto->set(prefix.c_str() ) ) );
00178     RooMultiVarGaussian constraint((prefix+"Constraint").c_str(),"",
00179              floating, mean, Cov);
00180              
00181     proto->import(constraint);
00182 
00183     likelihoodTermNames.push_back(constraint.GetName());
00184 
00185   }
00186 
00187 
00188   void HistoToWorkspaceFactory::LinInterpWithConstraint(RooWorkspace* proto, TH1F* nominal, vector<TH1F*> lowHist, vector<TH1F*> highHist, 
00189              vector<string> sourceName, string prefix, string productPrefix, string systTerm, 
00190              int lowBin, int highBin, vector<string>& likelihoodTermNames){
00191     // these are the nominal predictions: eg. the mean of some space of variations
00192     // later fill these in a loop over histogram bins
00193 
00194     // make list of abstract parameters that interpolate in space of variations
00195     RooArgList params( ("alpha_Hist") );
00196     // range is set using defined macro (see top of the page)
00197     string range=string("[")+alpha_Low+","+alpha_High+"]";
00198     for(unsigned int j=0; j<lowHist.size(); ++j){
00199       std::stringstream str;
00200       str<<"_"<<j;
00201 
00202       RooRealVar* temp = (RooRealVar*) proto->var(("alpha_"+sourceName.at(j)).c_str());
00203       if(!temp){
00204         temp = (RooRealVar*) proto->factory(("alpha_"+sourceName.at(j)+range).c_str());
00205 
00206         // now add a constraint term for these parameters
00207         string command=("Gaussian::alpha_"+sourceName.at(j)+"Constraint(alpha_"+sourceName.at(j)+",nom_"+sourceName.at(j)+"[0.,-10,10],1.)");
00208         cout << command << endl;
00209         likelihoodTermNames.push_back(  proto->factory( command.c_str() )->GetName() );
00210         proto->var(("nom_"+sourceName.at(j)).c_str())->setConstant();
00211         const_cast<RooArgSet*>(proto->set("globalObservables"))->add(*proto->var(("nom_"+sourceName.at(j)).c_str()));
00212 
00213       } 
00214 
00215       params.add(* temp );
00216 
00217     }
00218 
00219     // now make function that linearly interpolates expectation between variations
00220     for(Int_t i=lowBin; i<highBin; ++i){
00221       std::stringstream str;
00222       str<<"_"<<i;
00223 
00224       // get low/high variations to interpolate between
00225       vector<double> low, high;
00226       for(unsigned int j=0; j<lowHist.size(); ++j){
00227         low.push_back( lowHist.at(j)->GetBinContent(i+1) );
00228         high.push_back( highHist.at(j)->GetBinContent(i+1) );
00229         cout << "for "+prefix+" bin "+str.str()+" creating linear interp of nominal " << nominal->GetBinContent(i+1) 
00230        << " in parameter " << sourceName.at(j)
00231        << " between " << low.back() << " - " <<  high.back() 
00232        << " about " <<  100.*fabs(low.back() -  high.back() )/nominal->GetBinContent(i+1) << " % error" 
00233        << endl;
00234       }
00235      
00236       // this is sigma(params), a piece-wise linear interpolation
00237       LinInterpVar interp( (prefix+str.str()).c_str(), "", params, nominal->GetBinContent(i+1), low, high);
00238 
00239       //    cout << "check: " << interp.getVal() << endl;
00240       proto->import(interp); // individual params have already been imported in first loop of this function
00241       
00242       // now create the product of the overall efficiency times the sigma(params) for this estimate
00243       proto->factory(("prod:"+productPrefix+str.str()+"("+prefix+str.str()+","+systTerm+")").c_str() );
00244          
00245     }                              
00246 
00247   }
00248 
00249   string HistoToWorkspaceFactory::AddNormFactor(RooWorkspace * proto, string & channel, string & sigmaEpsilon, EstimateSummary & es, bool doRatio){
00250     string overallNorm_times_sigmaEpsilon ;
00251     string prodNames;
00252     vector<EstimateSummary::NormFactor> norm=es.normFactor;
00253     if(norm.size()){
00254       for(vector<EstimateSummary::NormFactor>::iterator itr=norm.begin(); itr!=norm.end(); ++itr){
00255         cout << "making normFactor: " << itr->name << endl;
00256         // remove "doRatio" and name can be changed when ws gets imported to the combined model.
00257         std::stringstream range;
00258         range<<"["<<itr->val<<","<<itr->low<<","<<itr->high<<"]";
00259         RooRealVar* var = 0;
00260 
00261         string varname;
00262         if(!prodNames.empty()) prodNames+=",";
00263         if(doRatio) {
00264           varname=itr->name+"_"+channel;
00265         }
00266         else {
00267           varname=itr->name;
00268         }
00269         var = (RooRealVar*) proto->factory((varname+range.str()).c_str());
00270         prodNames+=varname;
00271       }
00272       overallNorm_times_sigmaEpsilon = es.name+"_"+channel+"_overallNorm_x_sigma_epsilon";
00273       proto->factory(("prod::"+overallNorm_times_sigmaEpsilon+"("+prodNames+","+sigmaEpsilon+")").c_str());
00274     }
00275 
00276     if(!overallNorm_times_sigmaEpsilon.empty())
00277       return overallNorm_times_sigmaEpsilon;
00278     else
00279       return sigmaEpsilon;
00280   }        
00281 
00282 
00283   void HistoToWorkspaceFactory::AddEfficiencyTerms(RooWorkspace* proto, string prefix, string interpName,
00284         map<string,pair<double,double> > systMap, 
00285         vector<string>& likelihoodTermNames, vector<string>& totSystTermNames){
00286     // add variables for all the relative overall uncertainties we expect
00287     
00288     // range is set using defined macro (see top of the page)
00289     string range=string("[0,")+alpha_Low+","+alpha_High+"]";
00290     //string range="[0,-1,1]";
00291     totSystTermNames.push_back(prefix);
00292     //bool first=true;
00293     RooArgSet params(prefix.c_str());
00294     vector<double> lowVec, highVec;
00295     for(map<string,pair<double,double> >::iterator it=systMap.begin(); it!=systMap.end(); ++it){
00296       // add efficiency term
00297       RooRealVar* temp = (RooRealVar*) proto->var((prefix+ it->first).c_str());
00298       if(!temp){
00299         temp = (RooRealVar*) proto->factory((prefix+ it->first +range).c_str());
00300 
00301         string command=("Gaussian::"+prefix+it->first+"Constraint("+prefix+it->first+",nom_"+prefix+it->first+"[0.,-10,10],1.)");
00302         cout << command << endl;
00303         likelihoodTermNames.push_back(  proto->factory( command.c_str() )->GetName() );
00304         proto->var(("nom_"+prefix+it->first).c_str())->setConstant();
00305         const_cast<RooArgSet*>(proto->set("globalObservables"))->add(*proto->var(("nom_"+prefix+it->first).c_str()));
00306 
00307       } 
00308       params.add(*temp);
00309 
00310       // add constraint in terms of bifrucated gauss with low/high as sigmas
00311       std::stringstream lowhigh;
00312       double low = it->second.first; 
00313       double high = it->second.second;
00314       lowVec.push_back(low);
00315       highVec.push_back(high);
00316       
00317     }
00318     if(systMap.size()>0){
00319       // this is epsilon(alpha_j), a piece-wise linear interpolation
00320       LinInterpVar interp( (interpName).c_str(), "", params, 1., lowVec, highVec);
00321       proto->import(interp); // params have already been imported in first loop of this function
00322     } else{
00323       // some strange behavior if params,lowVec,highVec are empty.  
00324       //cout << "WARNING: No OverallSyst terms" << endl;
00325       RooConstVar interp( (interpName).c_str(), "", 1.);
00326       proto->import(interp); // params have already been imported in first loop of this function
00327     }
00328     
00329   }
00330 
00331 
00332   void  HistoToWorkspaceFactory::MakeTotalExpected(RooWorkspace* proto, string totName, string /**/, string /**/, 
00333         int lowBin, int highBin, vector<string>& syst_x_expectedPrefixNames, 
00334         vector<string>& normByNames){
00335 
00336     // for ith bin calculate totN_i =  lumi * sum_j expected_j * syst_j 
00337 
00338     for(Int_t i=lowBin; i<highBin; ++i){
00339       std::stringstream str;
00340       str<<"_"<<i;
00341       string command="sum::"+totName+str.str()+"(";
00342       vector<string>::iterator it=syst_x_expectedPrefixNames.begin();
00343       string prepend="";
00344       for(unsigned int j=0; j<syst_x_expectedPrefixNames.size();++j){
00345         command+=prepend+normByNames.at(j)+"*"+syst_x_expectedPrefixNames.at(j)+str.str();
00346         prepend=",";
00347       }
00348       command+=")";
00349       cout << "function to calculate total: " << command << endl;
00350       proto->factory(command.c_str());
00351     }
00352   }
00353 
00354   void HistoToWorkspaceFactory::AddPoissonTerms(RooWorkspace* proto, string prefix, string obsPrefix, string expPrefix, int lowBin, int highBin, 
00355            vector<string>& likelihoodTermNames){
00356     /////////////////////////////////
00357     // Relate observables to expected for each bin
00358     // later modify variable named expPrefix_i to be product of terms
00359     RooArgSet Pois(prefix.c_str());
00360     for(Int_t i=lowBin; i<highBin; ++i){
00361       std::stringstream str;
00362       str<<"_"<<i;
00363       //string command("Poisson::"+prefix+str.str()+"("+obsPrefix+str.str()+","+expPrefix+str.str()+")");
00364       string command("Poisson::"+prefix+str.str()+"("+obsPrefix+str.str()+","+expPrefix+str.str()+",1)");//for no rounding
00365       RooAbsArg* temp = (proto->factory( command.c_str() ) );
00366 
00367       // output
00368       cout << "Poisson Term " << command << endl;
00369       ((RooAbsPdf*) temp)->setEvalErrorLoggingMode(RooAbsReal::PrintErrors);
00370       //cout << temp << endl;
00371 
00372       likelihoodTermNames.push_back( temp->GetName() );
00373       Pois.add(* temp );
00374     }  
00375     proto->defineSet(prefix.c_str(),Pois); // add argset to workspace
00376   }
00377 
00378    void HistoToWorkspaceFactory::SetObsToExpected(RooWorkspace* proto, string obsPrefix, string expPrefix, int lowBin, int highBin){ 
00379     /////////////////////////////////
00380     // set observed to expected
00381      TTree* tree = new TTree();
00382      Double_t* obsForTree = new Double_t[highBin-lowBin];
00383      RooArgList obsList("obsList");
00384 
00385      for(Int_t i=lowBin; i<highBin; ++i){
00386        std::stringstream str;
00387        str<<"_"<<i;
00388        RooRealVar* obs = (RooRealVar*) proto->var((obsPrefix+str.str()).c_str());
00389        cout << "expected number of events called: " << expPrefix << endl;
00390        RooAbsReal* exp = proto->function((expPrefix+str.str()).c_str());
00391        if(obs && exp){
00392          
00393          //proto->Print();
00394          obs->setVal(  exp->getVal() );
00395          cout << "setting obs"+str.str()+" to expected = " << exp->getVal() << " check: " << obs->getVal() << endl;
00396          
00397          // add entry to array and attach to tree
00398          obsForTree[i] = exp->getVal();
00399          tree->Branch((obsPrefix+str.str()).c_str(), obsForTree+i ,(obsPrefix+str.str()+"/D").c_str());
00400          obsList.add(*obs);
00401        }else{
00402          cout << "problem retrieving obs or exp " << obsPrefix+str.str() << obs << " " << expPrefix+str.str() << exp << endl;
00403        }
00404      }  
00405      tree->Fill();
00406      RooDataSet* data = new RooDataSet("expData","", tree, obsList); // one experiment
00407 
00408      proto->import(*data);
00409 
00410   }
00411 
00412   void HistoToWorkspaceFactory::Customize(RooWorkspace* proto, const char* pdfNameChar, map<string,string> renameMap) {
00413     cout << "in customizations" << endl;
00414     string pdfName(pdfNameChar);
00415     map<string,string>::iterator it;
00416     string edit="EDIT::customized("+pdfName+",";
00417     string preceed="";
00418     for(it=renameMap.begin(); it!=renameMap.end(); ++it) {
00419       cout << it->first + "=" + it->second << endl;
00420       edit+=preceed + it->first + "=" + it->second;
00421       preceed=",";
00422     }
00423     edit+=")";
00424     cout << edit<< endl;
00425     proto->factory( edit.c_str() );
00426   }
00427 
00428   //_____________________________________________________________
00429   void HistoToWorkspaceFactory::EditSyst(RooWorkspace* proto, const char* pdfNameChar, map<string,double> gammaSyst, map<string,double> uniformSyst,map<string,double> logNormSyst) {
00430     //    cout << "in edit, gammamap.size = " << gammaSyst.size() << ", unimap.size = " << uniformSyst.size() << endl;
00431     string pdfName(pdfNameChar);
00432 
00433     ModelConfig * combined_config = (ModelConfig *) proto->obj("ModelConfig");
00434     //    const RooArgSet * constrainedParams=combined_config->GetNuisanceParameters();
00435     //    RooArgSet temp(*constrainedParams);
00436     string edit="EDIT::newSimPdf("+pdfName+",";
00437     string editList;
00438     string lastPdf=pdfName;
00439     string preceed="";
00440     unsigned int numReplacements = 0;
00441     unsigned int nskipped = 0;
00442     map<string,double>::iterator it;
00443 
00444     // add gamma terms and their constraints
00445     for(it=gammaSyst.begin(); it!=gammaSyst.end(); ++it) {
00446       //cout << "edit for " << it->first << "with rel uncert = " << it->second << endl;
00447       if(! proto->var(("alpha_"+it->first).c_str())){
00448         //cout << "systematic not there" << endl;
00449         nskipped++; 
00450         continue;
00451       }
00452       numReplacements++;      
00453 
00454       double relativeUncertainty = it->second;
00455       double scale = 1/sqrt((1+1/pow(relativeUncertainty,2)));
00456       
00457       // this is the Gamma PDF and in a form that doesn't have roundoff problems like the Poisson does
00458       proto->factory(Form("beta_%s[1,0,10]",it->first.c_str()));
00459       proto->factory(Form("y_%s[%f]",it->first.c_str(),1./pow(relativeUncertainty,2))) ;
00460       proto->factory(Form("theta_%s[%f]",it->first.c_str(),pow(relativeUncertainty,2))) ;
00461       proto->factory(Form("Gamma::beta_%sConstraint(beta_%s,sum::k_%s(y_%s,one[1]),theta_%s,zero[0])",
00462                           it->first.c_str(),
00463                           it->first.c_str(),
00464                           it->first.c_str(),
00465                           it->first.c_str(),
00466                           it->first.c_str())) ;
00467 
00468       /*
00469       // this has some problems because N in poisson is rounded to nearest integer     
00470       proto->factory(Form("Poisson::beta_%sConstraint(y_%s[%f],prod::taub_%s(taus_%s[%f],beta_%s[1,0,5]))",
00471                           it->first.c_str(),
00472                           it->first.c_str(),
00473                           1./pow(relativeUncertainty,2),
00474                           it->first.c_str(),
00475                             it->first.c_str(),
00476                           1./pow(relativeUncertainty,2),
00477                           it->first.c_str()
00478                           ) ) ;
00479       */
00480       //        combined->factory(Form("expr::alphaOfBeta('(beta-1)/%f',beta)",scale));
00481       //        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()));
00482       proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",it->first.c_str(),it->first.c_str(),-1./scale,1./scale));
00483         
00484       // set beta const status to be same as alpha
00485       if(proto->var(Form("alpha_%s",it->first.c_str()))->isConstant())
00486         proto->var(Form("beta_%s",it->first.c_str()))->setConstant(true);
00487       else
00488         proto->var(Form("beta_%s",it->first.c_str()))->setConstant(false);
00489       // set alpha const status to true
00490       //      proto->var(Form("alpha_%s",it->first.c_str()))->setConstant(true);
00491 
00492       // replace alphas with alphaOfBeta and replace constraints
00493       //cout <<         "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint" << endl;
00494       editList+=preceed + "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint";
00495       preceed=",";
00496       //      cout <<         "alpha_"+it->first+"=alphaOfBeta_"+ it->first << endl;
00497       editList+=preceed + "alpha_"+it->first+"=alphaOfBeta_"+ it->first;
00498 
00499       /*
00500       if( proto->pdf(("alpha_"+it->first+"Constraint").c_str()) && proto->var(("alpha_"+it->first).c_str()) )
00501       cout << " checked they are there" << proto->pdf(("alpha_"+it->first+"Constraint").c_str()) << " " << proto->var(("alpha_"+it->first).c_str()) << endl;
00502       else
00503         cout << "NOT THERE" << endl;
00504       */
00505 
00506       // EDIT seems to die if the list of edits is too long.  So chunck them up.
00507       if(numReplacements%10 == 0 && numReplacements+nskipped!=gammaSyst.size()){
00508         edit="EDIT::"+lastPdf+"_("+lastPdf+","+editList+")";
00509         lastPdf+="_"; // append an underscore for the edit
00510         editList=""; // reset edit list
00511         preceed="";
00512         cout << "Going to issue this edit command\n" << edit<< endl;
00513         proto->factory( edit.c_str() );
00514         RooAbsPdf* newOne = proto->pdf(lastPdf.c_str());
00515         if(!newOne)
00516           cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
00517         
00518       }
00519     }
00520 
00521     // add uniform terms and their constraints
00522     for(it=uniformSyst.begin(); it!=uniformSyst.end(); ++it) {
00523       cout << "edit for " << it->first << "with rel uncert = " << it->second << endl;
00524       if(! proto->var(("alpha_"+it->first).c_str())){
00525         cout << "systematic not there" << endl;
00526         nskipped++; 
00527         continue;
00528       }
00529       numReplacements++;      
00530 
00531       // this is the Uniform PDF
00532       proto->factory(Form("beta_%s[1,0,10]",it->first.c_str()));
00533       proto->factory(Form("Uniform::beta_%sConstraint(beta_%s)",it->first.c_str(),it->first.c_str()));
00534       proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{-1,1})",it->first.c_str(),it->first.c_str()));
00535       
00536       // set beta const status to be same as alpha
00537       if(proto->var(Form("alpha_%s",it->first.c_str()))->isConstant())
00538         proto->var(Form("beta_%s",it->first.c_str()))->setConstant(true);
00539       else
00540         proto->var(Form("beta_%s",it->first.c_str()))->setConstant(false);
00541       // set alpha const status to true
00542       //      proto->var(Form("alpha_%s",it->first.c_str()))->setConstant(true);
00543 
00544       // replace alphas with alphaOfBeta and replace constraints
00545       cout <<         "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint" << endl;
00546       editList+=preceed + "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint";
00547       preceed=",";
00548       cout <<         "alpha_"+it->first+"=alphaOfBeta_"+ it->first << endl;
00549       editList+=preceed + "alpha_"+it->first+"=alphaOfBeta_"+ it->first;
00550 
00551       if( proto->pdf(("alpha_"+it->first+"Constraint").c_str()) && proto->var(("alpha_"+it->first).c_str()) )
00552         cout << " checked they are there" << proto->pdf(("alpha_"+it->first+"Constraint").c_str()) << " " << proto->var(("alpha_"+it->first).c_str()) << endl;
00553       else
00554         cout << "NOT THERE" << endl;
00555 
00556       // EDIT seems to die if the list of edits is too long.  So chunck them up.
00557       if(numReplacements%10 == 0 && numReplacements+nskipped!=gammaSyst.size()){
00558         edit="EDIT::"+lastPdf+"_("+lastPdf+","+editList+")";
00559         lastPdf+="_"; // append an underscore for the edit
00560         editList=""; // reset edit list
00561         preceed="";
00562         cout << edit<< endl;
00563         proto->factory( edit.c_str() );
00564         RooAbsPdf* newOne = proto->pdf(lastPdf.c_str());
00565         if(!newOne)
00566           cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
00567         
00568       }
00569     }
00570 
00571     /////////////////////////////////////////
00572     ////////////////////////////////////
00573 
00574 
00575     // add lognormal terms and their constraints
00576     for(it=logNormSyst.begin(); it!=logNormSyst.end(); ++it) {
00577       cout << "edit for " << it->first << "with rel uncert = " << it->second << endl;
00578       if(! proto->var(("alpha_"+it->first).c_str())){
00579         cout << "systematic not there" << endl;
00580         nskipped++; 
00581         continue;
00582       }
00583       numReplacements++;      
00584 
00585       double relativeUncertainty = it->second;
00586       double kappa = 1+relativeUncertainty;
00587       // when transforming beta -> alpha, need alpha=1 to be +1sigma value.
00588       // the P(beta>kappa*\hat(beta)) = 16%
00589       // and \hat(beta) is 1, thus
00590       double scale = relativeUncertainty;
00591       //double scale = kappa; 
00592 
00593       // this is the LogNormal
00594       proto->factory(Form("beta_%s[1,0,10]",it->first.c_str()));
00595       proto->factory(Form("kappa_%s[%f]",it->first.c_str(),kappa));
00596       proto->factory(Form("Lognormal::beta_%sConstraint(beta_%s,one[1],kappa_%s)",
00597                           it->first.c_str(),
00598                           it->first.c_str(),
00599                           it->first.c_str())) ;
00600       proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",it->first.c_str(),it->first.c_str(),-1./scale,1./scale));
00601       //      proto->factory(Form("PolyVar::alphaOfBeta_%s(beta_%s,{%f,%f})",it->first.c_str(),it->first.c_str(),-1.,1./scale));
00602       
00603       // set beta const status to be same as alpha
00604       if(proto->var(Form("alpha_%s",it->first.c_str()))->isConstant())
00605         proto->var(Form("beta_%s",it->first.c_str()))->setConstant(true);
00606       else
00607         proto->var(Form("beta_%s",it->first.c_str()))->setConstant(false);
00608       // set alpha const status to true
00609       //      proto->var(Form("alpha_%s",it->first.c_str()))->setConstant(true);
00610 
00611       // replace alphas with alphaOfBeta and replace constraints
00612       cout <<         "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint" << endl;
00613       editList+=preceed + "alpha_"+it->first+"Constraint=beta_" + it->first+ "Constraint";
00614       preceed=",";
00615       cout <<         "alpha_"+it->first+"=alphaOfBeta_"+ it->first << endl;
00616       editList+=preceed + "alpha_"+it->first+"=alphaOfBeta_"+ it->first;
00617 
00618       if( proto->pdf(("alpha_"+it->first+"Constraint").c_str()) && proto->var(("alpha_"+it->first).c_str()) )
00619         cout << " checked they are there" << proto->pdf(("alpha_"+it->first+"Constraint").c_str()) << " " << proto->var(("alpha_"+it->first).c_str()) << endl;
00620       else
00621         cout << "NOT THERE" << endl;
00622 
00623       // EDIT seems to die if the list of edits is too long.  So chunck them up.
00624       if(numReplacements%10 == 0 && numReplacements+nskipped!=gammaSyst.size()){
00625         edit="EDIT::"+lastPdf+"_("+lastPdf+","+editList+")";
00626         lastPdf+="_"; // append an underscore for the edit
00627         editList=""; // reset edit list
00628         preceed="";
00629         cout << edit<< endl;
00630         proto->factory( edit.c_str() );
00631         RooAbsPdf* newOne = proto->pdf(lastPdf.c_str());
00632         if(!newOne)
00633           cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
00634         
00635       }
00636     }
00637 
00638     /////////////////////////////////////////
00639     ////////////////////////////////////
00640 
00641     // commit last bunch of edits
00642     edit="EDIT::newSimPdf("+lastPdf+","+editList+")";
00643     cout << edit<< endl;
00644     proto->factory( edit.c_str() );
00645     //    proto->writeToFile(("results/model_"+fRowTitle+"_edited.root").c_str());
00646     RooAbsPdf* newOne = proto->pdf("newSimPdf");
00647     if(newOne){
00648       // newOne->graphVizTree(("results/"+pdfName+"_"+fRowTitle+"newSimPdf.dot").c_str());
00649       combined_config->SetPdf(*newOne);
00650     }
00651     else{
00652       cout << "\n\n ---------------------\n WARNING: failed to make EDIT\n\n" << endl;
00653     }
00654   }
00655 
00656   void HistoToWorkspaceFactory::PrintCovarianceMatrix(RooFitResult* result, RooArgSet* params, string filename){
00657     //    FILE * pFile;
00658     pFile = fopen ((filename).c_str(),"w"); 
00659 
00660 
00661     TIter iti = params->createIterator();
00662     TIter itj = params->createIterator();
00663     RooRealVar *myargi, *myargj; 
00664     fprintf(pFile," ") ;
00665     while ((myargi = (RooRealVar *)iti.Next())) { 
00666       if(myargi->isConstant()) continue;
00667       fprintf(pFile," & %s",  myargi->GetName());
00668     }
00669     fprintf(pFile,"\\\\ \\hline \n" );
00670     iti.Reset();
00671     while ((myargi = (RooRealVar *)iti.Next())) { 
00672       if(myargi->isConstant()) continue;
00673       fprintf(pFile,"%s", myargi->GetName());
00674       itj.Reset();
00675       while ((myargj = (RooRealVar *)itj.Next())) { 
00676         if(myargj->isConstant()) continue;
00677         cout << myargi->GetName() << "," << myargj->GetName();
00678         fprintf(pFile, " & %.2f", result->correlation(*myargi, *myargj));
00679       }
00680       cout << endl;
00681       fprintf(pFile, " \\\\\n");
00682     }
00683     fclose(pFile);
00684     
00685   }
00686 
00687 
00688   ///////////////////////////////////////////////
00689   RooWorkspace* HistoToWorkspaceFactory::MakeSingleChannelModel(vector<EstimateSummary> summary, vector<string> systToFix, bool doRatio)
00690   {
00691     
00692     // to time the macro
00693     TStopwatch t;
00694     t.Start();
00695     string channel=summary[0].channel;
00696     cout << "\n\n-------------------\nStarting to process " << channel << " channel" << endl;
00697 
00698     //
00699     // our main workspace that we are using to construct the model
00700     //
00701     RooWorkspace* proto = new RooWorkspace("proto","proto workspace");
00702     ModelConfig * proto_config = new ModelConfig("ModelConfig", proto);
00703     proto_config->SetWorkspace(*proto);
00704 
00705     RooArgSet likelihoodTerms("likelihoodTerms");
00706     vector<string> likelihoodTermNames, totSystTermNames,syst_x_expectedPrefixNames, normalizationNames;
00707 
00708     string prefix, range;
00709 
00710     /////////////////////////////
00711     // Make observables, set values to observed data if data is specified,
00712     // otherwise use expected "Asimov" data
00713     if (summary.at(0).name=="Data") {
00714       ProcessExpectedHisto(summary.at(0).nominal,proto,"obsN","","",0,100000,fLowBin,fHighBin);
00715     } else {
00716       cout << "Will use expected (\"Asimov\") data set" << endl;
00717       ProcessExpectedHisto(NULL,proto,"obsN","","",0,100000,fLowBin,fHighBin);
00718     }
00719 
00720 
00721 
00722     /////////////////////////////
00723     // shared parameters
00724     // this is ratio of lumi to nominal lumi.  We will include relative uncertainty in model
00725     std::stringstream lumiStr;
00726     // lumi range
00727     lumiStr<<"["<<fNomLumi<<",0,"<<10.*fNomLumi<<"]";
00728     proto->factory(("Lumi"+lumiStr.str()).c_str());
00729     cout << "lumi str = " << lumiStr.str() << endl;
00730     
00731     std::stringstream lumiErrorStr;
00732     //    lumiErrorStr << "nominalLumi["<<fNomLumi << "]," << fLumiError ;
00733     lumiErrorStr << "nominalLumi["<<fNomLumi << ",0,"<<fNomLumi+10*fLumiError<<"]," << fLumiError ;
00734     proto->factory(("Gaussian::lumiConstraint(Lumi,"+lumiErrorStr.str()+")").c_str());
00735     proto->var("nominalLumi")->setConstant();
00736     proto->defineSet("globalObservables","nominalLumi");
00737     likelihoodTermNames.push_back("lumiConstraint");
00738     cout << "lumi Error str = " << lumiErrorStr.str() << endl;
00739     
00740     //proto->factory((string("SigXsecOverSM[1.,0.5,1..8]").c_str()));
00741     ///////////////////////////////////
00742     // loop through estimates, add expectation, floating bin predictions, 
00743     // and terms that constrain floating to expectation via uncertainties
00744     vector<EstimateSummary>::iterator it = summary.begin();
00745     for(; it!=summary.end(); ++it){
00746       if(it->name=="Data") continue;
00747 
00748       string overallSystName = it->name+"_"+it->channel+"_epsilon"; 
00749       string systSourcePrefix = "alpha_";
00750       AddEfficiencyTerms(proto,systSourcePrefix, overallSystName,
00751              it->overallSyst, 
00752              likelihoodTermNames, totSystTermNames);    
00753 
00754       overallSystName=AddNormFactor(proto, channel, overallSystName, *it, doRatio); 
00755       // get histogram
00756       TH1F* nominal = it->nominal;
00757       if(it->lowHists.size() == 0){
00758         cout << it->name+"_"+it->channel+" has no variation histograms " <<endl;
00759         string expPrefix=it->name+"_"+it->channel+"_expN";
00760         string syst_x_expectedPrefix=it->name+"_"+it->channel+"_overallSyst_x_Exp";
00761         ProcessExpectedHisto(nominal,proto,expPrefix,syst_x_expectedPrefix,overallSystName,atoi(NoHistConst_Low),atoi(NoHistConst_High),fLowBin,fHighBin);
00762         syst_x_expectedPrefixNames.push_back(syst_x_expectedPrefix);
00763       } else if(it->lowHists.size() != it->highHists.size()){
00764         cout << "problem in "+it->name+"_"+it->channel 
00765        << " number of low & high variation histograms don't match" << endl;
00766         return 0;
00767       } else {
00768         string constraintPrefix = it->name+"_"+it->channel+"_Hist_alpha"; // name of source for variation
00769         string syst_x_expectedPrefix = it->name+"_"+it->channel+"_overallSyst_x_HistSyst";
00770         LinInterpWithConstraint(proto, nominal, it->lowHists, it->highHists, it->systSourceForHist,
00771               constraintPrefix, syst_x_expectedPrefix, overallSystName, 
00772               fLowBin, fHighBin, likelihoodTermNames);
00773         syst_x_expectedPrefixNames.push_back(syst_x_expectedPrefix);
00774       }
00775 
00776       //    AddMultiVarGaussConstraint(proto, "exp"+it->first+"N", fLowBin, fHighBin, likelihoodTermNames);
00777 
00778       if(it->normName=="")
00779         normalizationNames.push_back( "Lumi" );
00780       else
00781         normalizationNames.push_back( it->normName);
00782     }
00783     //proto->Print();
00784 
00785     ///////////////////////////////////
00786     // for ith bin calculate totN_i =  lumi * sum_j expected_j * syst_j 
00787     MakeTotalExpected(proto,channel+"_totN",channel+"_expN","Lumi",fLowBin,fHighBin, 
00788           syst_x_expectedPrefixNames, normalizationNames);
00789 
00790     /////////////////////////////////
00791     // Relate observables to expected for each bin
00792     AddPoissonTerms(proto, "Pois_"+channel, "obsN", channel+"_totN", fLowBin, fHighBin, likelihoodTermNames);
00793 
00794     /////////////////////////////////
00795     // if no data histogram provided, make asimov data
00796     if(summary.at(0).name!="Data"){
00797       SetObsToExpected(proto, "obsN",channel+"_totN", fLowBin, fHighBin);
00798       cout << " using asimov data" << endl;
00799     }  else{
00800       SetObsToExpected(proto, "obsN","obsN", fLowBin, fHighBin);
00801       cout << " using input data histogram" << endl;
00802     }
00803 
00804     //////////////////////////////////////
00805     // fix specified parameters
00806     for(unsigned int i=0; i<systToFix.size(); ++i){
00807       RooRealVar* temp = proto->var((systToFix.at(i)).c_str());
00808       if(temp) temp->setConstant();
00809       else cout << "could not find variable " << systToFix.at(i) << " could not set it to constant" << endl;
00810     }
00811 
00812     //////////////////////////////////////
00813     // final proto model
00814     for(unsigned int i=0; i<likelihoodTermNames.size(); ++i){
00815       //    cout << likelihoodTermNames[i] << endl;
00816       likelihoodTerms.add(* (proto->arg(likelihoodTermNames[i].c_str())) );
00817     }
00818     //  likelihoodTerms.Print();
00819 
00820     proto->defineSet("likelihoodTerms",likelihoodTerms);
00821     //  proto->Print();
00822 
00823     cout <<"-----------------------------------------"<<endl;
00824     cout <<"import model into workspace" << endl;
00825     RooProdPdf* model = new RooProdPdf(("model_"+channel).c_str(),
00826                "product of Poissons accross bins for a single channel",
00827                likelihoodTerms);
00828     proto->import(*model,RecycleConflictNodes());
00829 
00830     proto_config->SetPdf(*model);
00831     proto_config->SetGlobalObservables(*proto->set("globalObservables"));
00832 
00833     proto->import(*proto_config,proto_config->GetName());
00834     proto->importClassCode();
00835     //    proto->writeToFile(("results/model_"+channel+".root").c_str());
00836 
00837     return proto;
00838   }
00839 
00840   RooWorkspace* HistoToWorkspaceFactory::MakeCombinedModel(vector<string> ch_names, vector<RooWorkspace*> chs)
00841   {
00842 
00843     //
00844     /// These things were used for debugging. Maybe useful in the future
00845     //
00846     //  RooAbsReal::defaultIntegratorConfig()->setEpsAbs(1e-8) ;
00847     //  RooAbsReal::defaultIntegratorConfig()->setEpsRel(1e-8) ;
00848     //  RooMsgService::instance().setGlobalKillBelow(RooMsgService::WARNING);
00849     //  RooMsgService::instance().setGlobalKillBelow(RooMsgService::WARNING) ;
00850     //  cout << "MsgSvc: " << RooMsgService::instance().globalKillBelow() << " INFO " 
00851     //       << RooMsgService::INFO << " WARNING " << RooMsgService::WARNING << endl;
00852 
00853     //    RooArgSet* constrainedParams= new RooArgSet("constrainedParams");
00854 
00855     map<string, RooAbsPdf*> pdfMap;
00856     vector<RooAbsPdf*> models;
00857     stringstream ss;
00858 
00859     RooArgSet globalObs;
00860     for(unsigned int i = 0; i< ch_names.size(); ++i){
00861       string channel_name=ch_names[i];
00862 
00863       if (ss.str().empty()) ss << channel_name ;
00864       else ss << ',' << channel_name ;
00865       RooWorkspace * ch=chs[i];
00866       
00867       RooAbsPdf* model = ch->pdf(("model_"+channel_name).c_str());
00868       models.push_back(model);
00869       globalObs.add(*ch->set("globalObservables"));
00870 
00871       //      constrainedParams->add( * ch->set("constrainedParams") );
00872       pdfMap[channel_name]=model;
00873     }
00874     //constrainedParams->Print();
00875 
00876     cout << "\n\n------------------\n Entering combination" << endl;
00877     RooWorkspace* combined = new RooWorkspace("combined");
00878 
00879     RooCategory* channelCat = (RooCategory*) combined->factory(("channelCat["+ss.str()+"]").c_str());
00880     RooSimultaneous * simPdf= new RooSimultaneous("simPdf","",pdfMap, *channelCat);
00881     ModelConfig * combined_config = new ModelConfig("ModelConfig", combined);
00882     combined_config->SetWorkspace(*combined);
00883     //    combined_config->SetNuisanceParameters(*constrainedParams);
00884     combined->import(globalObs);
00885     combined->defineSet("globalObservables",globalObs);
00886     combined_config->SetGlobalObservables(*combined->set("globalObservables"));
00887 
00888     ////////////////////////////////////////////
00889     // Make toy simultaneous dataset
00890     cout <<"-----------------------------------------"<<endl;
00891     cout << "create toy data for " << ss.str() << endl;
00892     
00893     const RooArgSet* obsN = chs[0]->set("obsN");
00894 
00895     RooDataSet * simData=new RooDataSet("simData","master dataset", *obsN, 
00896             Index(*channelCat), Import(ch_names[0].c_str(),*((RooDataSet*)chs[0]->data("expData"))));
00897     for(unsigned int i = 1; i< ch_names.size(); ++i){
00898       RooDataSet * simData_ch=new RooDataSet("simData","master dataset", *obsN, 
00899               Index(*channelCat), Import(ch_names[i].c_str(),*((RooDataSet*)chs[i]->data("expData"))));
00900       simData->append(*simData_ch);
00901     }
00902     //for(int i=0; i<simData->numEntries(); ++i)
00903     //  simData->get(i)->Print("v");
00904 
00905     combined->import(*simData,RecycleConflictNodes());
00906 
00907     cout << "\n\n----------------\n Importing combined model" << endl;
00908     combined->import(*simPdf,RecycleConflictNodes());
00909     //combined->import(*simPdf, RenameVariable("SigXsecOverSM","SigXsecOverSM_comb"));
00910     cout << "check pointer " << simPdf << endl;
00911 
00912     for(unsigned int i=0; i<fSystToFix.size(); ++i){
00913       // make sure they are fixed
00914       RooRealVar* temp = combined->var((fSystToFix.at(i)).c_str());
00915       if(temp) {
00916         temp->setConstant();
00917         cout <<"setting " << fSystToFix.at(i) << " constant" << endl;
00918       }
00919       else cout << "could not find variable " << fSystToFix.at(i) << " could not set it to constant" << endl;
00920     }
00921 
00922     ///
00923     /// writing out the model in graphViz
00924     /// 
00925     //    RooAbsPdf* customized=combined->pdf("simPdf"); 
00926     //combined_config->SetPdf(*customized);
00927     combined_config->SetPdf(*simPdf);
00928     //    customized->graphVizTree(("results/"+fResultsPrefixStr.str()+"_simul.dot").c_str());
00929     combined->import(*combined_config,combined_config->GetName());
00930     combined->importClassCode();
00931     //    combined->writeToFile("results/model_combined.root");
00932 
00933     return combined;
00934   }
00935 
00936   ///////////////////////////////////////////////
00937    void HistoToWorkspaceFactory::FitModel(RooWorkspace * combined, string channel, string /*model_name*/, string data_name, bool /*doParamInspect*/)
00938   {
00939 
00940     ModelConfig * combined_config = (ModelConfig *) combined->obj("ModelConfig");
00941     RooDataSet * simData = (RooDataSet *) combined->obj(data_name.c_str());
00942     //    const RooArgSet * constrainedParams=combined_config->GetNuisanceParameters();
00943     const RooArgSet * POIs=combined_config->GetParametersOfInterest();
00944 
00945     /*
00946           RooRealVar* poi = (RooRealVar*) combined->var("SigXsecOverSM");
00947           RooArgSet * params= new RooArgSet;
00948           params->add(*poi);
00949           combined_config->SetParameters(*params);
00950 
00951           RooAbsData* expData = combined->data("expData");
00952           RooArgSet* temp =  (RooArgSet*) combined->set("obsN")->Clone("temp");
00953           temp->add(*poi);
00954           RooAbsPdf* model=combined_config->GetPdf();
00955           RooArgSet* constrainedParams = model->getParameters(temp);
00956           combined->defineSet("constrainedParams", *constrainedParams);
00957     */
00958 
00959     //RooAbsPdf* model=combined->pdf(model_name.c_str()); 
00960     RooAbsPdf* model=combined_config->GetPdf();
00961     //    RooArgSet* allParams = model->getParameters(*simData);
00962 
00963     ///////////////////////////////////////
00964     //Do combined fit
00965     //RooMsgService::instance().setGlobalKillBelow(RooMsgService::INFO) ;
00966     cout << "\n\n---------------" << endl;
00967     cout << "---------------- Doing "<< channel << " Fit" << endl;
00968     cout << "---------------\n\n" << endl;
00969     //    RooFitResult* result = model->fitTo(*simData, Minos(kTRUE), Save(kTRUE), PrintLevel(1));
00970     model->fitTo(*simData, Minos(kTRUE), PrintLevel(1));
00971     //    PrintCovarianceMatrix(result, allParams, "results/"+FilePrefixStr(channel)+"_corrMatrix.table" );
00972 
00973     //
00974     // assuming there is only on poi
00975     // 
00976     RooRealVar* poi = 0; // (RooRealVar*) POIs->first();
00977     // for results tables
00978     TIterator* params_itr=POIs->createIterator();
00979     TObject* params_obj=0;
00980     while((params_obj=params_itr->Next())){
00981       poi = (RooRealVar*) params_obj;
00982       cout << "printing results for " << poi->GetName() << " at " << poi->getVal()<< " high " << poi->getErrorLo() << " low " << poi->getErrorHi()<<endl;
00983     }
00984     fprintf(pFile, " %.4f / %.4f  ", poi->getErrorLo(), poi->getErrorHi());
00985 
00986     RooAbsReal* nll = model->createNLL(*simData);
00987     RooAbsReal* profile = nll->createProfile(*poi);
00988     RooPlot* frame = poi->frame();
00989     FormatFrameForLikelihood(frame);
00990     TCanvas* c1 = new TCanvas( channel.c_str(), "",800,600);
00991     nll->plotOn(frame, ShiftToZero(), LineColor(kRed), LineStyle(kDashed));
00992     profile->plotOn(frame);
00993     frame->SetMinimum(0);
00994     frame->SetMaximum(2.);
00995     frame->Draw();
00996     //    c1->SaveAs( ("results/"+FilePrefixStr(channel)+"_profileLR.eps").c_str() );
00997     c1->SaveAs( (fFileNamePrefix+"_"+channel+"_"+fRowTitle+"_profileLR.eps").c_str() );
00998 
00999     fOut_f->mkdir(channel.c_str())->mkdir("Summary")->cd();
01000 
01001     // an example of calculating profile for a nuisance parameter not poi
01002     /*
01003     RooRealVar* alpha_isrfsr = (RooRealVar*) combined->var("alpha_isrfsr");
01004     RooAbsReal* profile_isrfsr = nll->createProfile(*alpha_isrfsr);
01005     poi->setVal(0.55);
01006     poi->setConstant();
01007 
01008     RooPlot* frame_isrfsr = alpha_isrfsr->frame();
01009     profile_isrfsr->plotOn(frame_isrfsr, Precision(0.1));
01010     TCanvas c_isrfsr = new TCanvas( "combined", "",800,600);
01011     FormatFrameForLikelihood(frame_isrfsr, "alpha_{isrfsr}");
01012     frame_isrfsr->Draw();
01013     fOut_f->cd("Summary");
01014     c1->Write((FilePrefixStr(channel).str()+"_profileLR_alpha_isrfsr").c_str() );
01015     delete frame; delete c1;
01016     poi->setConstant(kFALSE);
01017     */
01018 
01019     RooCurve* curve=frame->getCurve();
01020     Int_t curve_N=curve->GetN();
01021     Double_t* curve_x=curve->GetX();
01022     delete frame; delete c1;
01023 
01024     //
01025     // Verbose output from MINUIT
01026     //
01027     /*
01028     RooMsgService::instance().setGlobalKillBelow(RooFit::DEBUG) ;
01029     profile->getVal();
01030     RooMinuit* minuit = ((RooProfileLL*) profile)->minuit();
01031     minuit->setPrintLevel(5) ; // Print MINUIT messages
01032     minuit->setVerbose(5) ; // Print RooMinuit messages with parameter 
01033                                 // changes (corresponds to the Verbose() option of fitTo()
01034     */
01035   
01036     Double_t * x_arr = new Double_t[curve_N];
01037     Double_t * y_arr_nll = new Double_t[curve_N];
01038 //     Double_t y_arr_prof_nll[curve_N];
01039 //     Double_t y_arr_prof[curve_N];
01040 
01041     for(int i=0; i<curve_N; i++){
01042       double f=curve_x[i];
01043       poi->setVal(f);
01044       x_arr[i]=f;
01045       y_arr_nll[i]=nll->getVal();
01046     }
01047     TGraph * g = new TGraph(curve_N, x_arr, y_arr_nll);
01048     g->SetName((FilePrefixStr(channel)+"_nll").c_str());
01049     g->Write(); 
01050     delete g;
01051     delete [] x_arr;
01052     delete [] y_arr_nll;
01053 
01054     /** find out what's inside the workspace **/
01055     //combined->Print();
01056 
01057   }
01058 
01059 
01060 void HistoToWorkspaceFactory::FormatFrameForLikelihood(RooPlot* frame, string /*XTitle*/, string YTitle){
01061 
01062       gStyle->SetCanvasBorderMode(0);
01063       gStyle->SetPadBorderMode(0);
01064       gStyle->SetPadColor(0);
01065       gStyle->SetCanvasColor(255);
01066       gStyle->SetTitleFillColor(255);
01067       gStyle->SetFrameFillColor(0);  
01068       gStyle->SetStatColor(255);
01069       
01070       RooAbsRealLValue* var = frame->getPlotVar();
01071       double xmin = var->getMin();
01072       double xmax = var->getMax();
01073       
01074       frame->SetTitle("");
01075       //      frame->GetXaxis()->SetTitle(XTitle.c_str());
01076       frame->GetXaxis()->SetTitle(var->GetTitle());
01077       frame->GetYaxis()->SetTitle(YTitle.c_str());
01078       frame->SetMaximum(2.);
01079       frame->SetMinimum(0.);
01080       TLine * line = new TLine(xmin,.5,xmax,.5);
01081       line->SetLineColor(kGreen);
01082       TLine * line90 = new TLine(xmin,2.71/2.,xmax,2.71/2.);
01083       line90->SetLineColor(kGreen);
01084       TLine * line95 = new TLine(xmin,3.84/2.,xmax,3.84/2.);
01085       line95->SetLineColor(kGreen);
01086       frame->addObject(line);
01087       frame->addObject(line90);
01088       frame->addObject(line95);
01089   }
01090 
01091   TDirectory * HistoToWorkspaceFactory::Makedirs( TDirectory * file, vector<string> names ){
01092     if(! file) return file;
01093     string path="";
01094     TDirectory* ptr=0;
01095     for(vector<string>::iterator itr=names.begin(); itr != names.end(); ++itr){
01096       if( ! path.empty() ) path+="/";
01097       path+=(*itr);
01098       ptr=file->GetDirectory(path.c_str());
01099       if( ! ptr ) ptr=file->mkdir((*itr).c_str());
01100       file=file->GetDirectory(path.c_str());
01101     }
01102     return ptr;
01103   }
01104   TDirectory * HistoToWorkspaceFactory::Mkdir( TDirectory * file, string name ){
01105     if(! file) return file;
01106     TDirectory* ptr=0;
01107     ptr=file->GetDirectory(name.c_str());
01108     if( ! ptr )  ptr=file->mkdir(name.c_str());
01109     return ptr;
01110   }
01111 
01112 }
01113 }
01114 

Generated on Tue Jul 5 14:52:33 2011 for ROOT_528-00b_version by  doxygen 1.5.1