コード例 #1
0
ファイル: BiasStudy.cpp プロジェクト: ETHZ/h2gglobe
int main(int argc, char* argv[]){

  string bkgFileName;
  string sigFileName;
  string sigWSName;
  string bkgWSName;
  string outFileName;
  string datFileName;
  string outDir;
  int cat;
  int ntoys;
  int jobn;
  int seed;
  float mu_low;
  float mu_high;
  float mu_step;
  float expectSignal;
  int expectSignalMass;
  bool skipPlots=false;
  int verbosity;
  bool throwHybridToys=false;
  vector<float> switchMass;
  vector<string> switchFunc;

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h",                                                                                  "Show help")
    ("sigfilename,s", po::value<string>(&sigFileName),                                          "Signal file name")
    ("bkgfilename,b", po::value<string>(&bkgFileName),                                          "Background file name")
    ("sigwsname", po::value<string>(&sigWSName)->default_value("cms_hgg_workspace"),            "Signal workspace name")
    ("bkgwsname", po::value<string>(&bkgWSName)->default_value("cms_hgg_workspace"),            "Background workspace name")
    ("outfilename,o", po::value<string>(&outFileName)->default_value("BiasStudyOut.root"),      "Output file name")
    ("datfile,d", po::value<string>(&datFileName)->default_value("config.dat"),                 "Name of datfile containing pdf info")
    ("outDir,D", po::value<string>(&outDir)->default_value("./"),                               "Name of out directory for plots")
    ("cat,c", po::value<int>(&cat),                                                             "Category")
    ("ntoys,t", po::value<int>(&ntoys)->default_value(0),                                       "Number of toys to run")
    ("jobn,j", po::value<int>(&jobn)->default_value(0),                                         "Job number")
    ("seed,r", po::value<int>(&seed)->default_value(0),                                         "Set random seed")
    ("mulow,L", po::value<float>(&mu_low)->default_value(-3.),                                  "Value of mu to start scan")
    ("muhigh,H", po::value<float>(&mu_high)->default_value(3.),                                 "Value of mu to end scan")
    ("mustep,S", po::value<float>(&mu_step)->default_value(0.01),                               "Value of mu step size")
    ("expectSignal", po::value<float>(&expectSignal)->default_value(0.),                        "Inject signal into toy")
    ("expectSignalMass", po::value<int>(&expectSignalMass)->default_value(125),                 "Inject signal at this mass")
    ("skipPlots",                                                                               "Skip full profile and toy plots")                        
    ("verbosity,v", po::value<int>(&verbosity)->default_value(0),                               "Verbosity level")
  ;    
  
  po::variables_map vm;
  po::store(po::parse_command_line(argc,argv,desc),vm);
  po::notify(vm);
  if (vm.count("help")) { cout << desc << endl; exit(1); }
  if (vm.count("skipPlots")) skipPlots=true;
  if (expectSignalMass!=110 && expectSignalMass!=115 && expectSignalMass!=120 && expectSignalMass!=125 && expectSignalMass!=130 && expectSignalMass!=135 && expectSignalMass!=140 && expectSignalMass!=145 && expectSignalMass!=150){
    cerr << "ERROR - expectSignalMass has to be integer in range (110,150,5)" << endl;
    exit(1);
  }

  vector<pair<int,pair<string,string> > > toysMap;
  vector<pair<int,pair<string,string> > > fabianMap;
  vector<pair<int,pair<string,string> > > paulMap;
  readDatFile(datFileName,cat,toysMap,fabianMap,paulMap);
  
  cout << "Toy vector.." << endl;
  printOptionsMap(toysMap);
  cout << "Fabian vector.." << endl;
  printOptionsMap(fabianMap);
  cout << "Paul vector.." << endl;
  printOptionsMap(paulMap);
  
  TStopwatch sw;
  sw.Start();
 
  if (verbosity<1) {
    RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
    RooMsgService::instance().setSilentMode(true);
  }
  
  TFile *bkgFile = TFile::Open(bkgFileName.c_str());
  TFile *sigFile = TFile::Open(sigFileName.c_str());

  //RooWorkspace *bkgWS = (RooWorkspace*)bkgFile->Get("cms_hgg_workspace");
  RooWorkspace *bkgWS = (RooWorkspace*)bkgFile->Get(bkgWSName.c_str());
  RooWorkspace *sigWS = (RooWorkspace*)sigFile->Get(sigWSName.c_str());

  if (!bkgWS || !sigWS){
    cerr << "ERROR - one of signal or background workspace is NULL" << endl;
    exit(1);
  }

  RooRealVar *mass = (RooRealVar*)bkgWS->var("CMS_hgg_mass");
  RooRealVar *mu = new RooRealVar("mu","mu",0.,mu_low,mu_high);

  TFile *outFile = new TFile(outFileName.c_str(),"RECREATE");
  TTree *muTree = new TTree("muTree","muTree");
  int toyn;
  vector<string> truthModel;
  vector<double> muFab;
  vector<double> muPaul;
  vector<double> muChi2;
  vector<double> muAIC;
  vector<double> muFabErrLow;
  vector<double> muPaulErrLow;
  vector<double> muChi2ErrLow;
  vector<double> muAICErrLow;
  vector<double> muFabErrHigh;
  vector<double> muPaulErrHigh;
  vector<double> muChi2ErrHigh;
  vector<double> muAICErrHigh;
  muTree->Branch("jobn",&jobn);
  muTree->Branch("toyn",&toyn);
  muTree->Branch("truthModel",&truthModel);
  muTree->Branch("muFab",&muFab);
  muTree->Branch("muPaul",&muPaul);
  muTree->Branch("muChi2",&muChi2);
  muTree->Branch("muAIC",&muAIC);
  muTree->Branch("muFabErrLow",&muFabErrLow);
  muTree->Branch("muPaulErrLow",&muPaulErrLow);
  muTree->Branch("muChi2ErrLow",&muChi2ErrLow);
  muTree->Branch("muAICErrLow",&muAICErrLow);
  muTree->Branch("muFabErrHigh",&muFabErrHigh);
  muTree->Branch("muPaulErrHigh",&muPaulErrHigh);
  muTree->Branch("muChi2ErrHigh",&muChi2ErrHigh);
  muTree->Branch("muAICErrHigh",&muAICErrHigh);
  
  //TH1F *muDistFab = new TH1F("muDistFab","muDistFab",int(20*(mu_high-mu_low)),mu_low,mu_high);
  //TH1F *muDistPaul = new TH1F("muDistPaul","muDistPaul",int(20*(mu_high-mu_low)),mu_low,mu_high);
  //TH1F *muDistChi2 = new TH1F("muDistChi2","muDistChi2",int(20*(mu_high-mu_low)),mu_low,mu_high);
  //TH1F *muDistAIC = new TH1F("muDistAIC","muDistAIC",int(20*(mu_high-mu_low)),mu_low,mu_high);
  
  mass->setBins(320);
  RooDataSet *data = (RooDataSet*)bkgWS->data(Form("data_mass_cat%d",cat));
  //RooDataSet *data = (RooDataSet*)bkgWS->data(Form("data_cat%d_7TeV",cat));
  RooDataHist *dataBinned = new RooDataHist(Form("roohist_data_mass_cat%d",cat),Form("roohist_data_mass_cat%d",cat),RooArgSet(*mass),*data);
  RooDataSet *sigMC = (RooDataSet*)sigWS->data(Form("sig_ggh_mass_m%d_cat%d",expectSignalMass,cat));
  RooDataSet *sigMC_vbf = (RooDataSet*)sigWS->data(Form("sig_wzh_mass_m%d_cat%d",expectSignalMass,cat));
  RooDataSet *sigMC_wzh = (RooDataSet*)sigWS->data(Form("sig_vbf_mass_m%d_cat%d",expectSignalMass,cat));
  RooDataSet *sigMC_tth = (RooDataSet*)sigWS->data(Form("sig_tth_mass_m%d_cat%d",expectSignalMass,cat));
  sigMC->append(*sigMC_vbf);
  sigMC->append(*sigMC_wzh);
  sigMC->append(*sigMC_tth);
  //RooExtendPdf *ggh_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_ggh",cat));
  //RooExtendPdf *vbf_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_vbf",cat));
  //RooExtendPdf *wzh_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_wzh",cat));
  //RooExtendPdf *tth_pdf = (RooExtendPdf*)sigWS->pdf(Form("sigpdfsmrel_cat%d_7TeV_tth",cat));
  //RooAbsPdf *sigPdf = new RooAddPdf(Form("sigpdfsmrel_cat%d_7TeV",cat),Form("sigpdfsmrel_cat%d_7TeV",cat),RooArgList(*ggh_pdf,*vbf_pdf,*wzh_pdf,*tth_pdf));
  
  if (!dataBinned || !sigMC){
    cerr << "ERROR -- one of data or signal is NULL" << endl;
    exit(1);
  }
  
  // set of truth models to throw toys from
  PdfModelBuilder toysModel;
  toysModel.setObsVar(mass);
  toysModel.setSignalModifier(mu);
  // add truth pdfs from config datfile these need to be cached
  // to throw a toy from the SB fit make sure that the cache happens at makeSBPdfs
  for (vector<pair<int,pair<string,string> > >::iterator it=toysMap.begin(); it!=toysMap.end(); it++){
    if (it->first==-1) { // this is a hyrbid toy
      throwHybridToys=true;
      vector<string> temp;
      split(temp,it->second.first,boost::is_any_of(","));
      split(switchFunc,it->second.second,boost::is_any_of(","));
      for (unsigned int i=0; i<temp.size(); i++){
        switchMass.push_back(atof(temp[i].c_str()));
      }
      continue; 
    }
    if (it->first==-2) { // this is a keys pdf toy
      double rho = lexical_cast<double>(it->second.first);
      toysModel.setKeysPdfAttributes(data,rho);
      toysModel.addBkgPdf("KeysPdf",0,Form("truth_%s_cat%d",it->second.second.c_str(),cat),false);
      continue;
    }
    if (it->first==-3) { // this is read pdf from file
      toysModel.addBkgPdf(it->second.second,it->first,it->second.first,false);
      continue;
    }
    toysModel.addBkgPdf(it->second.second,it->first,Form("truth_%s_cat%d",it->second.first.c_str(),cat),false); 
  }
  toysModel.setSignalPdfFromMC(sigMC);
  //toysModel.setSignalPdf(sigPdf);
  toysModel.makeSBPdfs(true);
  map<string,RooAbsPdf*> toyBkgPdfs = toysModel.getBkgPdfs();
  map<string,RooAbsPdf*> toySBPdfs = toysModel.getSBPdfs();
  toysModel.setSeed(seed);

  // fabians chosen model
  PdfModelBuilder fabianModel;
  fabianModel.setObsVar(mass);
  fabianModel.setSignalModifier(mu);
  // add pdfs from config datfile - should be no need to cache these
  for (vector<pair<int,pair<string,string> > >::iterator it=fabianMap.begin(); it!=fabianMap.end(); it++){
    fabianModel.addBkgPdf(it->second.second,it->first,Form("fabian_%s_cat%d",it->second.first.c_str(),cat),false); 
  }
  fabianModel.setSignalPdfFromMC(sigMC);
  //fabianModel.setSignalPdf(sigPdf);
  fabianModel.makeSBPdfs(false);
  map<string,RooAbsPdf*> fabianBkgPdfs = fabianModel.getBkgPdfs();
  map<string,RooAbsPdf*> fabianSBPdfs = fabianModel.getSBPdfs();

  // set of models to profile 
  PdfModelBuilder paulModel;
  paulModel.setObsVar(mass);
  paulModel.setSignalModifier(mu);
  // add pdfs from config datfile - should be no need to cache these
  for (vector<pair<int,pair<string,string> > >::iterator it=paulMap.begin(); it!=paulMap.end(); it++){
    paulModel.addBkgPdf(it->second.second,it->first,Form("paul_%s_cat%d",it->second.first.c_str(),cat),false); 
  }
  paulModel.setSignalPdfFromMC(sigMC);
  //paulModel.setSignalPdf(sigPdf);
  paulModel.makeSBPdfs(false);
  map<string,RooAbsPdf*> paulBkgPdfs = paulModel.getBkgPdfs();
  map<string,RooAbsPdf*> paulSBPdfs = paulModel.getSBPdfs();

  // set up profile for Fabians models
  ProfileMultiplePdfs fabianProfiler;
  for (map<string,RooAbsPdf*>::iterator pdf=fabianSBPdfs.begin(); pdf!=fabianSBPdfs.end(); pdf++){
    fabianProfiler.addPdf(pdf->second);
  }
  cout << "Fabian profiler pdfs:" << endl;
  fabianProfiler.printPdfs();

  // set up profile for Pauls models
  ProfileMultiplePdfs paulProfiler;
  for (map<string,RooAbsPdf*>::iterator pdf=paulSBPdfs.begin(); pdf!=paulSBPdfs.end(); pdf++){
    paulProfiler.addPdf(pdf->second);
  }
  cout << "Paul profiler pdfs:" << endl;
  paulProfiler.printPdfs();

  if (!skipPlots) {
    system(Form("mkdir -p %s/plots/truthToData",outDir.c_str()));
    system(Form("mkdir -p %s/plots/envelopeNlls",outDir.c_str()));
    system(Form("mkdir -p %s/plots/toys",outDir.c_str()));
  }
  
  // throw toys - only need to fit data once as result will be cached
  cout << "------ FITTING TRUTH TO DATA ------" << endl;
  // sometimes useful to do best fit first to get reasonable starting value
  toysModel.setSignalModifierConstant(false);
  toysModel.fitToData(dataBinned,false,false,true);
  // -----
  toysModel.setSignalModifierVal(expectSignal);
  toysModel.setSignalModifierConstant(true);
  toysModel.fitToData(dataBinned,false,true,true);
  if (!skipPlots) toysModel.plotPdfsToData(dataBinned,80,Form("%s/plots/truthToData/datafit_mu%3.1f",outDir.c_str(),expectSignal),false);
  toysModel.setSignalModifierConstant(false);
  toysModel.saveWorkspace(outFile);
  
  for (int toy=0; toy<ntoys; toy++){
    cout << "---------------------------" << endl;
    cout << "--- RUNNING TOY " << toy << " / " << ntoys << " ----" << endl;
    cout << "---------------------------" << endl;
    // wipe stuff for tree
    truthModel.clear();
    muFab.clear();
    muPaul.clear();
    muChi2.clear();
    muAIC.clear();
    muFabErrLow.clear();
    muPaulErrLow.clear();
    muChi2ErrLow.clear();
    muAICErrLow.clear();
    muFabErrHigh.clear();
    muPaulErrHigh.clear();
    muChi2ErrHigh.clear();
    muAICErrHigh.clear();
    // throw toy
    map<string,RooAbsData*> toys; 
    if (throwHybridToys) {
      toysModel.throwHybridToy(Form("truth_job%d_toy%d",jobn,toy),dataBinned->sumEntries(),switchMass,switchFunc,false,true,true,true);
      toys = toysModel.getHybridToyData();
      if (!skipPlots) toysModel.plotToysWithPdfs(Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),80,false);
      if (!skipPlots) toysModel.plotHybridToy(Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),80,switchMass,switchFunc,false);
    }
    else {
      toysModel.throwToy(Form("truth_job%d_toy%d",jobn,toy),dataBinned->sumEntries(),false,true,true,true);
      toys = toysModel.getToyData();
      if (!skipPlots) toysModel.plotToysWithPdfs(Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),80,false);
    }
    for (map<string,RooAbsData*>::iterator it=toys.begin(); it!=toys.end(); it++){
      // ----- USEFUL DEBUG -----------
      //  --- this can be a useful check that the truth model values are being cached properly ---
      //toysModel.fitToData(it->second,true,false,true);
      //toysModel.plotPdfsToData(it->second,80,Form("%s/plots/toys/job%d_toy%d",outDir.c_str(),jobn,toy),true,"NONE");
      if (!skipPlots) fabianProfiler.plotNominalFits(it->second,mass,80,Form("%s/plots/toys/job%d_toy%d_fit_fab",outDir.c_str(),jobn,toy));
      if (!skipPlots) paulProfiler.plotNominalFits(it->second,mass,80,Form("%s/plots/toys/job%d_toy%d_fit_paul",outDir.c_str(),jobn,toy));
      //continue;
      // --------------------------------
      cout << "Fitting toy for truth model " << distance(toys.begin(),it) << "/" << toys.size() << " (" << it->first << ") " << endl;
      // get Fabian envelope
      pair<double,map<string,TGraph*> > fabianMinNlls = fabianProfiler.profileLikelihood(it->second,mass,mu,mu_low,mu_high,mu_step);
      pair<double,map<string,TGraph*> > fabianEnvelope = fabianProfiler.computeEnvelope(fabianMinNlls,Form("fabEnvelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),0.);
      if (!skipPlots) fabianProfiler.plot(fabianEnvelope.second,Form("%s/plots/envelopeNlls/nlls_fab_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
     
      // get Paul envelopes
      pair<double,map<string,TGraph*> > paulMinNlls = paulProfiler.profileLikelihood(it->second,mass,mu,mu_low,mu_high,mu_step);
      pair<double,map<string,TGraph*> > paulEnvelope = paulProfiler.computeEnvelope(paulMinNlls,Form("paulEnvelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),0.);
      if (!skipPlots) paulProfiler.plot(paulEnvelope.second,Form("%s/plots/envelopeNlls/nlls_paul_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
      pair<double,map<string,TGraph*> > chi2Envelope = paulProfiler.computeEnvelope(paulMinNlls,Form("chi2Envelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),1.);
      if (!skipPlots) paulProfiler.plot(chi2Envelope.second,Form("%s/plots/envelopeNlls/nlls_chi2_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
      pair<double,map<string,TGraph*> > aicEnvelope = paulProfiler.computeEnvelope(paulMinNlls,Form("aicEnvelope_job%d_%s_cat%d_toy%d",jobn,it->first.c_str(),cat,toy),2.);
      if (!skipPlots) paulProfiler.plot(aicEnvelope.second,Form("%s/plots/envelopeNlls/nlls_aic_%s_cat%d_toy%d",outDir.c_str(),it->first.c_str(),cat,toy));
     
      pair<double,pair<double,double> > muFabInfo = ProfileMultiplePdfs::getMinAndErrorAsymm(fabianEnvelope.second["envelope"],1.);
      pair<double,pair<double,double> > muPaulInfo = ProfileMultiplePdfs::getMinAndErrorAsymm(paulEnvelope.second["envelope"],1.);
      pair<double,pair<double,double> > muChi2Info = ProfileMultiplePdfs::getMinAndErrorAsymm(chi2Envelope.second["envelope"],1.);
      pair<double,pair<double,double> > muAICInfo = ProfileMultiplePdfs::getMinAndErrorAsymm(aicEnvelope.second["envelope"],1.);

      truthModel.push_back(it->first);
      muFab.push_back(muFabInfo.first);
      muPaul.push_back(muPaulInfo.first);
      muChi2.push_back(muChi2Info.first);
      muAIC.push_back(muAICInfo.first);
      muFabErrLow.push_back(muFabInfo.second.first);
      muPaulErrLow.push_back(muPaulInfo.second.first);
      muChi2ErrLow.push_back(muChi2Info.second.first);
      muAICErrLow.push_back(muAICInfo.second.first);
      muFabErrHigh.push_back(muFabInfo.second.second);
      muPaulErrHigh.push_back(muPaulInfo.second.second);
      muChi2ErrHigh.push_back(muChi2Info.second.second);
      muAICErrHigh.push_back(muAICInfo.second.second);

      cout << "Fab mu = " << muFabInfo.first << " - " << muFabInfo.second.first << " + " << muFabInfo.second.second << endl;
      cout << "Paul mu = " << muPaulInfo.first << " - " << muPaulInfo.second.first << " + " << muPaulInfo.second.second << endl;
      cout << "Chi2 mu = " << muChi2Info.first << " - " << muChi2Info.second.first << " + " << muChi2Info.second.second << endl;
      cout << "AIC mu = " << muAICInfo.first << " - " << muAICInfo.second.first << " + " << muAICInfo.second.second << endl;

      outFile->cd();
      fabianEnvelope.second["envelope"]->Write();
      paulEnvelope.second["envelope"]->Write();
      chi2Envelope.second["envelope"]->Write();
      aicEnvelope.second["envelope"]->Write();
    }
    toyn=toy;
    muTree->Fill();
  }

  outFile->cd();
  muTree->Write();
  cout << "Done." << endl;
  cout << "Whole process took..." << endl;
  cout << "\t "; sw.Print();
 
  outFile->Close();

  return 0;
}
コード例 #2
0
void StandardBayesianNumericalDemo(const char* infile = "",
		      const char* workspaceName = "combined",
		      const char* modelConfigName = "ModelConfig",
		      const char* dataName = "obsData"){

  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file 
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
  TString filename = infile;
  if (filename.IsNull()) { 
    filename = "results/example_combined_GaussExample_model.root";
    std::cout << "Use standard file generated with HistFactory : " << filename << std::endl;
  }

  // Check if example input file exists
  TFile *file = TFile::Open(filename);

  // if input file was specified but not found, quit
  if(!file && !TString(infile).IsNull()){
     cout <<"file " << filename << " not found" << endl;
     return;
  } 

  // if default file not found, try to create it
  if(!file ){
    // Normally this would be run on the command line
    cout <<"will run standard hist2workspace example"<<endl;
    gROOT->ProcessLine(".! prepareHistFactory .");
    gROOT->ProcessLine(".! hist2workspace config/example.xml");
    cout <<"\n\n---------------------"<<endl;
    cout <<"Done creating example input"<<endl;
    cout <<"---------------------\n\n"<<endl;

    // now try to access the file again
    file = TFile::Open(filename);
  }

  if(!file){
    // if it is still not there, then we can't continue
    cout << "Not able to run hist2workspace to create example input" <<endl;
    return;
  }

  
  /////////////////////////////////////////////////////////////
  // Tutorial starts here
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }

  // get the modelConfig out of the file
  ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !mc){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }

  /////////////////////////////////////////////
  // create and use the BayesianCalculator
  // to find and plot the 95% credible interval
  // on the parameter of interest as specified
  // in the model config
  
  // before we do that, we must specify our prior
  // it belongs in the model config, but it may not have
  // been specified
  RooUniform prior("prior","",*mc->GetParametersOfInterest());
  w->import(prior);
  mc->SetPriorPdf(*w->pdf("prior"));

  // do without systematics
  //mc->SetNuisanceParameters(RooArgSet() );

  
  BayesianCalculator bayesianCalc(*data,*mc);
  bayesianCalc.SetConfidenceLevel(0.95); // 95% interval

  // default of the calculator is central interval.  here use shortest , central or upper limit depending on input
  // doing a shortest interval might require a longer time since it requires a scan of the posterior function
  if (intervalType == 0)  bayesianCalc.SetShortestInterval(); // for shortest interval
  if (intervalType == 1)  bayesianCalc.SetLeftSideTailFraction(0.5); // for central interval
  if (intervalType == 2)  bayesianCalc.SetLeftSideTailFraction(0.); // for upper limit

  if (!integrationType.IsNull() ) { 
     bayesianCalc.SetIntegrationType(integrationType); // set integrationType
     bayesianCalc.SetNumIters(nToys); // set number of ietrations (i.e. number of toys for MC integrations)
  }

  // compute interval by scanning the posterior function
  if (scanPosterior)   
     bayesianCalc.SetScanOfPosterior(nScanPoints);


  SimpleInterval* interval = bayesianCalc.GetInterval();

  // print out the iterval on the first Parameter of Interest
  RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
  cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
    interval->LowerLimit() << ", "<<
    interval->UpperLimit() <<"] "<<endl;


  // make a plot 
  // since plotting may take a long time (it requires evaluating 
  // the posterior in many points) this command will speed up 
  // by reducing the number of points to plot - do 50

  cout << "\nDrawing plot of posterior function....." << endl;

  bayesianCalc.SetScanOfPosterior(nScanPoints);

  RooPlot * plot = bayesianCalc.GetPosteriorPlot();
  plot->Draw();  

}
コード例 #3
0
void RA2bHypoTestInvDemo(const char * fileName =0,
			 const char * wsName = "combined",
			 const char * modelSBName = "ModelConfig",
			 const char * modelBName = "",
			 const char * dataName = "obsData",                 
			 int calculatorType = 0,
			 int testStatType = 3, 
			 bool useCls = true ,  
			 int npoints = 5,   
			 double poimin = 0,  
			 double poimax = 5, 
			 int ntoys=1000,
			 int mgl = -1,
			 int mlsp = -1,
			 const char * outFileName = "test")    
{
/*

   Other Parameter to pass in tutorial
   apart from standard for filename, ws, modelconfig and data

    type = 0 Freq calculator 
    type = 1 Hybrid 

    testStatType = 0 LEP
                 = 1 Tevatron 
                 = 2 Profile Likelihood
                 = 3 Profile Likelihood one sided (i.e. = 0 if mu < mu_hat)

    useCLs          scan for CLs (otherwise for CLs+b)    

    npoints:        number of points to scan , for autoscan set npoints = -1 

    poimin,poimax:  min/max value to scan in case of fixed scans 
                    (if min >= max, try to find automatically)                           

    ntoys:         number of toys to use 

    extra options are available as global paramters of the macro. They are: 

    plotHypoTestResult   plot result of tests at each point (TS distributions) 
    useProof = true;
    writeResult = true;
    nworkers = 4;


   */

   if (fileName==0) { 
      fileName = "results/example_combined_GaussExample_model.root";
      std::cout << "Use standard file generated with HistFactory :" << fileName << std::endl;
   }
   TFile * file = new TFile(fileName); 

   RooWorkspace * w = dynamic_cast<RooWorkspace*>( file->Get(wsName) );
   HypoTestInverterResult * r = 0; 
   std::cout << w << "\t" << fileName << std::endl;
   if (w != NULL) {
      r = RunInverter(w, modelSBName, modelBName, dataName, calculatorType, testStatType, npoints, poimin, poimax,  ntoys, useCls );    
      if (!r) { 
         std::cerr << "Error running the HypoTestInverter - Exit " << std::endl;
         return;          
      }
   }
   else 
   { 
      // case workspace is not present look for the inverter result
      std::cout << "Reading an HypoTestInverterResult with name " << wsName << " from file " << fileName << std::endl;
      r = dynamic_cast<HypoTestInverterResult*>( file->Get(wsName) ); //
      if (!r) { 
         std::cerr << "File " << fileName << " does not contain a workspace or an HypoTestInverterResult - Exit " 
                   << std::endl;
         file->ls();
         return; 
      }
   }		
      		


   printf("\n\n") ;
   HypoTestResult* htr = r->GetResult(0) ;
   printf("  Data value for test stat : %7.3f\n", htr->GetTestStatisticData() ) ;
   printf("  CLsplusb : %9.4f\n", r->CLsplusb(0) ) ;
   printf("  CLb      : %9.4f\n", r->CLb(0) ) ;
   printf("  CLs      : %9.4f\n", r->CLs(0) ) ;
   printf("\n\n") ;
   cout << flush ;

   double upperLimit = r->UpperLimit();
   double ulError = r->UpperLimitEstimatedError();


   std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;
 
   const int nEntries = r->ArraySize();


   const char *  typeName = (calculatorType == 0) ? "Frequentist" : "Hybrid";
   const char * resultName = (w) ? w->GetName() : r->GetName();
   TString plotTitle = TString::Format("%s CL Scan for workspace %s",typeName,resultName);
   HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot",plotTitle,r);
   TCanvas* c1 = new TCanvas() ;
   plot->Draw("CLb 2CL");  // plot all and Clb
   c1->Update() ;
   c1->SaveAs("cls-canv1.png") ;
   c1->SaveAs("cls-canv1.pdf") ;

   if (plotHypoTestResult) { 
      TCanvas * c2 = new TCanvas();
      c2->Divide( 2, TMath::Ceil(nEntries/2));
      for (int i=0; i<nEntries; i++) {
         c2->cd(i+1);
         SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
         pl->SetLogYaxis(true);
         pl->Draw();
      }
      c2->Update() ;
      c2->SaveAs("cls-canv2.png") ;
      c2->SaveAs("cls-canv2.pdf") ;
   }


   std::cout << " expected limit (median) " <<  r->GetExpectedUpperLimit(0) << std::endl;
   std::cout << " expected limit (-1 sig) " << r->GetExpectedUpperLimit(-1) << std::endl;
   std::cout << " expected limit (+1 sig) " << r->GetExpectedUpperLimit(1) << std::endl;


   // save 2d histograms bin to file

   TH2F *result = new TH2F("result","result",22,100,1200,23,50,1200); 
   TH2F *exp_res = new TH2F("exp_res","exp_res",22,100,1200,23,50,1200); 
   TH2F *exp_res_minus = new TH2F("exp_res_minus","exp_res_minus",22,100,1200,23,50,1200); 
   TH2F *exp_res_plus = new TH2F("exp_res_plus","exp_res_plus",22,100,1200,23,50,1200); 

   result->Fill(mgl,mlsp,upperLimit);
   exp_res->Fill(mgl,mlsp,r->GetExpectedUpperLimit(0));
   exp_res_minus->Fill(mgl,mlsp,r->GetExpectedUpperLimit(-1));
   exp_res_plus->Fill(mgl,mlsp,r->GetExpectedUpperLimit(1));


   TFile *f = new TFile(outFileName,"RECREATE");
   f->cd();

   result->Write();
   exp_res->Write();
   exp_res_minus->Write();
   exp_res_plus->Write();

   f->Close();


   if (w != NULL && writeResult) {

      // write to a file the results
      const char *  calcType = (calculatorType == 0) ? "Freq" : "Hybr";
      const char *  limitType = (useCls) ? "CLs" : "Cls+b";
      const char * scanType = (npoints < 0) ? "auto" : "grid";
      TString resultFileName = TString::Format("%s_%s_%s_ts%d_",calcType,limitType,scanType,testStatType);      
      resultFileName += fileName;
      
      TFile * fileOut = new TFile(resultFileName,"RECREATE");
      r->Write();
      fileOut->Close();                                                                     
   }   

}
double StandardFrequentistDiscovery(
   const char* infile = "",
   const char* workspaceName = "channel1",
   const char* modelConfigNameSB = "ModelConfig",
   const char* dataName = "obsData",
   int toys = 1000,
   double poiValueForBackground = 0.0,
   double poiValueForSignal = 1.0
) {

   // The workspace contains the model for s+b. The b model is "autogenerated"
   // by copying s+b and setting the one parameter of interest to zero.
   // To keep the script simple, multiple parameters of interest or different
   // functional forms of the b model are not supported.

   // for now, assume there is only one parameter of interest, and these are
   // its values:

   /////////////////////////////////////////////////////////////
   // First part is just to access a user-defined file
   // or create the standard example file if it doesn't exist
   ////////////////////////////////////////////////////////////
   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_channel1_GammaExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
      // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return -1;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }
      
   }
   else
      filename = infile;
   
   // Try to open the file
   TFile *file = TFile::Open(filename);
   
   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return -1;
   } 


   /////////////////////////////////////////////////////////////
   // Tutorial starts here
   ////////////////////////////////////////////////////////////

   TStopwatch *mn_t = new TStopwatch;
   mn_t->Start();

   // get the workspace out of the file
   RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
   if (!w) {
      cout << "workspace not found" << endl;
      return -1.0;
   }

   // get the modelConfig out of the file
   ModelConfig* mc = (ModelConfig*) w->obj(modelConfigNameSB);

   // get the data out of the file
   RooAbsData* data = w->data(dataName);

   // make sure ingredients are found
   if (!data || !mc) {
      w->Print();
      cout << "data or ModelConfig was not found" << endl;
      return -1.0;
   }


   RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
   firstPOI->setVal(poiValueForSignal);
   mc->SetSnapshot(*mc->GetParametersOfInterest());
   // create null model
   ModelConfig *mcNull = mc->Clone("ModelConfigNull");
   firstPOI->setVal(poiValueForBackground);
   mcNull->SetSnapshot(*(RooArgSet*)mcNull->GetParametersOfInterest()->snapshot());



   // ----------------------------------------------------
   // Configure a ProfileLikelihoodTestStat and a SimpleLikelihoodRatioTestStat
   // to use simultaneously with ToyMCSampler
   ProfileLikelihoodTestStat* plts =  new ProfileLikelihoodTestStat(*mc->GetPdf());
   plts->SetOneSidedDiscovery(true);
   plts->SetVarName( "q_{0}/2" );
   
   // ----------------------------------------------------
   // configure the ToyMCImportanceSampler with two test statistics
   ToyMCSampler toymcs(*plts, 50);



   // Since this tool needs to throw toy MC the PDF needs to be
   // extended or the tool needs to know how many entries in a dataset
   // per pseudo experiment.
   // In the 'number counting form' where the entries in the dataset
   // are counts, and not values of discriminating variables, the
   // datasets typically only have one entry and the PDF is not
   // extended.
   if (!mc->GetPdf()->canBeExtended()) {
      if (data->numEntries() == 1) {
         toymcs.SetNEventsPerToy(1);
      } else cout << "Not sure what to do about this model" << endl;
   }

   // We can use PROOF to speed things along in parallel
   // ProofConfig pc(*w, 2, "user@yourfavoriteproofcluster", false);
   ProofConfig pc(*w, 2, "", false);
   //toymcs.SetProofConfig(&pc);    // enable proof


   // instantiate the calculator
   FrequentistCalculator freqCalc(*data, *mc, *mcNull, &toymcs);
   freqCalc.SetToys( toys,toys ); // null toys, alt toys

   // Run the calculator and print result
   HypoTestResult* freqCalcResult = freqCalc.GetHypoTest();
   freqCalcResult->GetNullDistribution()->SetTitle( "b only" );
   freqCalcResult->GetAltDistribution()->SetTitle( "s+b" );
   freqCalcResult->Print();
   double pvalue = freqCalcResult->NullPValue();

   // stop timing
   mn_t->Stop();
   cout << "total CPU time: " << mn_t->CpuTime() << endl;
   cout << "total real time: " << mn_t->RealTime() << endl;

   // plot
   TCanvas* c1 = new TCanvas();
   HypoTestPlot *plot = new HypoTestPlot(*freqCalcResult, 100, -0.49, 9.51 );
   plot->SetLogYaxis(true);
   
   // add chi2 to plot
   int nPOI = 1;
   TF1* f = new TF1("f", TString::Format("1*ROOT::Math::chisquared_pdf(2*x,%d,0)",nPOI), 0,20);
   f->SetLineColor( kBlack );
   f->SetLineStyle( 7 );
   plot->AddTF1( f, TString::Format("#chi^{2}(2x,%d)",nPOI) );
   
   plot->Draw();
   c1->SaveAs("standard_discovery_output.pdf");
   

   return pvalue;
}
コード例 #5
0
ファイル: MakeAICFits.C プロジェクト: vlambert/AIC
MakeAICFits::MakeAICFits() {
  //RooRandom::randomGenerator()->SetSeed(314159);
  TFile *f = TFile::Open("/mnt/hadoop/store/user/amott/Hgg2013/Hgg/workspaces/hgg_22Jan2013_R9_CIC.root");
  RooWorkspace *w = (RooWorkspace*) f->Get("cms_hgg_spin_workspace");
  RooAbsData *d = w->data("Data_Combined");
  RooCategory* cat = (RooCategory*)cms_hgg_spin_workspace->obj("evtcat");
  RooAbsData *dc = d->reduce("evtcat==evtcat::cat4");
  //RooAbsData *dc = w->data("Data_Combined")->reduce("evtcar==evtcat::cat0");
  RooRealVar *mass = w->var("mass");

  const Int_t nToys = 1;

  std::cout<<"==========  Data Set Made    ==========="<<std::endl;
  
  Double_t LogLikelihood[8] = {0,0,0,0,0,0,0,0};
  Double_t AIC_bkg_array[8] = {0,0,0,0,0,0,0,0};
  Double_t AICc_bkg_array[8] = {0,0,0,0,0,0,0,0};
  Int_t avgcov[8] = {0,0,0,0,0,0,0};
  std::cout<<"======================   Starting Toys  ==============="<<std::endl;
  for (Int_t i=0; i<nToys; i++) {
    if (i%10==0) {
      std::cout<<">> Processing Toy Trial " << i << "/" << nToys << std::endl;
    }
    int SampleSize = dc->sumEntries();
    RooPlot* frame = mass->frame();
    TLegend *leg = new TLegend(0.55,0.55,0.9,0.9, NULL, "NDC");
    dc->plotOn(frame);
    leg->AddEntry(dc,"Hgg Background Cat 4", "lep");

    for (int type=0; type<7; type++) {
      std::cout<<type<<endl;
    }
    int display = 7;
    for (int type=0; type<display; type++) {
      RooAbsPdf* ModelShape;
      if (type<7) {
	//std::cout<<"Model Shape:    "<<type<<std::endl;
	ModelShape = MakeAICFits::getBackgroundPdf(type,mass);
	//std::cout<<"Model Shape made"<<std::endl;
	int k = MakeAICFits::Num_Params(type);
	//std::cout<<"Params counted"<<std::endl;
      }
      if (type==7) {
	RooAbsPdf* Model1 = MakeAICFits::getBackgroundPdf(0,mass);
	RooAbsPdf* Model2 = MakeAICFits::getBackgroundPdf(1,mass);
	RooAbsPdf* Model3 = MakeAICFits::getBackgroundPdf(2,mass);
	RooAbsPdf* Model4 = MakeAICFits::getBackgroundPdf(3,mass);
	RooAbsPdf* Model5 = MakeAICFits::getBackgroundPdf(4,mass);
	int k = MakeAICFits::Num_Params(3);
	k+= MakeAICFits::Num_Params(1);
	k+= MakeAICFits::Num_Params(0);
	//k+= MakeAICFits::Num_Params(3);
	//k+= MakeAICFits::Num_Params(4);
	RooRealVar* modratio1 = new RooRealVar("modrat1", "modrat1", 0.62, 0.6, 0.7);
	RooRealVar* modratio2 = new RooRealVar("modrat2", "modrat2", 0.29, 0.25, 0.35);
	RooRealVar* modratio3 = new RooRealVar("modrat3", "modrat3", 0.01);
	//RooRealVar* modratio4 = new RooRealVar("modrat4", "modrat4", 0.25);
	ModelShape = new RooAddPdf("Composite", "Background Model", RooArgList(*Model1, *Model4, *Model2), RooArgList(*modratio1, *modratio2));
      }
      RooRealVar *Nbkg = new RooRealVar("Nbkg","N Background Events", SampleSize,0,1e9);
      RooExtendPdf *BkgModel = new RooExtendPdf("BKGFIT_bkgModel", "Background Model", *ModelShape, *Nbkg);
      TH1F* Model = new TH1F("Model", "Model", 100,0,100);
 
      RooFitResult *bkg_databkg = BkgModel->fitTo(*dc, RooFit::Save(kTRUE), RooFit::Optimize(0));
      if (type == 0) {
	BkgModel->plotOn(frame, RooFit::LineColor(kBlue));
	Model->SetLineColor(kBlue);
	leg->AddEntry(Model, "Exponential Model", "l");
      }
      if (type == 4) { 
	BkgModel->plotOn(frame, RooFit::LineColor(kRed));
	Model->SetLineColor(kRed);
	leg->AddEntry(Model, "Polynomial Model", "l");
      }
      if (type == 5) { 
	BkgModel->plotOn(frame, RooFit::LineColor(kGreen));
	Model->SetLineColor(kGreen);
	leg->AddEntry(Model, "Power Model", "l");
      }
      if (type == 7) {
	BkgModel->plotOn(frame, RooFit::LineColor(kMagenta));
	Model->SetLineColor(kMagenta);
	leg->AddEntry(Model, "Composite Model", "l");
      }
      Double_t bkg_databkg_Nll = bkg_databkg->minNll();
      Int_t covariance = bkg_databkg->covQual();
      avgcov[type] += covariance;
      //assert (covariance == 3);
      // Calculate AIC for each model
      LogLikelihood[type] += -bkg_databkg_Nll;
      AICc_bkg_array[type] += 2.*(k + k*(k + 1.)/(SampleSize - (k + 1.)) + bkg_databkg_Nll);
      AIC_bkg_array[type] += 2.*(k + bkg_databkg_Nll);
      // Clean up objects
      delete bkg_databkg;
      bkg_databkg_Nll = 0.;
    }
    //delete databkg;
    TCanvas *c = new TCanvas("", "", 800, 600);
    frame->Draw();
    leg->Draw();
    c->Update();
    c->Print("HggData_cat4.pdf");
  }
  
  std::cout<<"Printing AIC Values" << std::endl;
  //std::cout<<"Log Likelihood Data :    " << LogLikelihood_data <<std::endl;
  int display = 7;
  for (int type = 0; type<display; type++) {
    avgcov[type] = avgcov[type]/nToys;
    LogLikelihood[type] = LogLikelihood[type]/nToys;
    AIC_bkg_array[type] = AIC_bkg_array[type]/nToys;
    AICc_bkg_array[type] = AICc_bkg_array[type]/nToys;
    std::cout<<"average covariance quality" << type <<" ===" << avgcov[type] <<std::endl;
    std::cout<<"Log Likelihood for Model " << type << " ==== " << LogLikelihood[type] <<std::endl;
    std::cout<<"AICc Value for Model: " << type << " ==== " << AICc_bkg_array[type] <<std::endl;
    std::cout<<"AIC Value for Model: " << type << " ==== " << AIC_bkg_array[type]  << std::endl;
  }
  double minAIC = 10000000000.;
  for (int type = 0; type<display; type++) {
    if (AICc_bkg_array[type] < minAIC) {
      minAIC = AICc_bkg_array[type];
    }
  }
  std::cout<<"Minimum AIC: " << minAIC << std::endl;
  double DeltaIA[8];
  double sumExpA=0;
  int bestmodelA;
  for (int type = 0; type<display; type++) {
    DeltaIA[type] = AICc_bkg_array[type] - minAIC;
    if (DeltaIA[type] == 0) {
      bestmodelA = type;
    }
    std::cout<<"Delta AIC values : " << type << " ====" << DeltaIA[type] <<std::endl;
    sumExpA+= exp(-DeltaIA[type]/2);
  }
  double AICweights[8];
  for (int type = 0; type<display; type++) {
    AICweights[type] = exp(-DeltaIA[type]/2)/sumExpA;
    std::cout<<"Relative Likelihood AIC " << type << " ==== " <<exp(-DeltaIA[type]/2)<<std::endl;
    std::cout<<"AIC Weights  : " << type << " =====" << AICweights[type] <<std::endl;
  }
  for (int type2 = 0; type2<display; type2++) {
    std::cout<< "AIC Ratio for:  " << "Model " << bestmodelA << " / " << "Model " << type2 << "  =  " << AICweights[bestmodelA]/AICweights[type2] <<std::endl;
  }
}
void OneSidedFrequentistUpperLimitWithBands_intermediate(const char* infile = "",
					    const char* workspaceName = "combined",
					    const char* modelConfigName = "ModelConfig",
					    const char* dataName = "obsData"){


  double confidenceLevel=0.95;
  // degrade/improve number of pseudo-experiments used to define the confidence belt.  
  // value of 1 corresponds to default number of toys in the tail, which is 50/(1-confidenceLevel)
  double additionalToysFac = 1.;  
  int nPointsToScan = 30; // number of steps in the parameter of interest 
  int nToyMC = 100; // number of toys used to define the expected limit and band

  TStopwatch t;
  t.Start();
  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file 
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
  const char* filename = "";
  if (!strcmp(infile,""))
    filename = "results/example_combined_GaussExample_model.root";
  else
    filename = infile;
  // Check if example input file exists
  TFile *file = TFile::Open(filename);

  // if input file was specified byt not found, quit
  if(!file && strcmp(infile,"")){
    cout <<"file not found" << endl;
    return;
  } 

  // if default file not found, try to create it
  if(!file ){
    // Normally this would be run on the command line
    cout <<"will run standard hist2workspace example"<<endl;
    gROOT->ProcessLine(".! prepareHistFactory .");
    gROOT->ProcessLine(".! hist2workspace config/example.xml");
    cout <<"\n\n---------------------"<<endl;
    cout <<"Done creating example input"<<endl;
    cout <<"---------------------\n\n"<<endl;
  }

  // now try to access the file again
  file = TFile::Open(filename);
  if(!file){
    // if it is still not there, then we can't continue
    cout << "Not able to run hist2workspace to create example input" <<endl;
    return;
  }

  
  /////////////////////////////////////////////////////////////
  // Now get the data and workspace
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }

  // get the modelConfig out of the file
  ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !mc){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }

  cout << "Found data and ModelConfig:" <<endl;
  mc->Print();

  /////////////////////////////////////////////////////////////
  // Now get the POI for convenience
  // you may want to adjust the range of your POI
  ////////////////////////////////////////////////////////////
  RooRealVar* firstPOI = (RooRealVar*) mc->GetParametersOfInterest()->first();
  //  firstPOI->setMin(0);
  //  firstPOI->setMax(10);

  /////////////////////////////////////////////
  // create and use the FeldmanCousins tool
  // to find and plot the 95% confidence interval
  // on the parameter of interest as specified
  // in the model config
  // REMEMBER, we will change the test statistic
  // so this is NOT a Feldman-Cousins interval
  FeldmanCousins fc(*data,*mc);
  fc.SetConfidenceLevel(confidenceLevel); 
  fc.AdditionalNToysFactor(additionalToysFac); // improve sampling that defines confidence belt
  //  fc.UseAdaptiveSampling(true); // speed it up a bit, but don't use for expectd limits
  fc.SetNBins(nPointsToScan); // set how many points per parameter of interest to scan
  fc.CreateConfBelt(true); // save the information in the belt for plotting

  /////////////////////////////////////////////
  // Feldman-Cousins is a unified limit by definition
  // but the tool takes care of a few things for us like which values
  // of the nuisance parameters should be used to generate toys.
  // so let's just change the test statistic and realize this is 
  // no longer "Feldman-Cousins" but is a fully frequentist Neyman-Construction.
  //  ProfileLikelihoodTestStatModified onesided(*mc->GetPdf());
  //  fc.GetTestStatSampler()->SetTestStatistic(&onesided);
  // ((ToyMCSampler*) fc.GetTestStatSampler())->SetGenerateBinned(true);
  ToyMCSampler*  toymcsampler = (ToyMCSampler*) fc.GetTestStatSampler(); 
  ProfileLikelihoodTestStat* testStat = dynamic_cast<ProfileLikelihoodTestStat*>(toymcsampler->GetTestStatistic());
  testStat->SetOneSided(true);


  // test speedups:
  testStat->SetReuseNLL(true);
  //  toymcsampler->setUseMultiGen(true); // not fully validated

  // Since this tool needs to throw toy MC the PDF needs to be
  // extended or the tool needs to know how many entries in a dataset
  // per pseudo experiment.  
  // In the 'number counting form' where the entries in the dataset
  // are counts, and not values of discriminating variables, the
  // datasets typically only have one entry and the PDF is not
  // extended.  
  if(!mc->GetPdf()->canBeExtended()){
    if(data->numEntries()==1)     
      fc.FluctuateNumDataEntries(false);
    else
      cout <<"Not sure what to do about this model" <<endl;
  }

  // We can use PROOF to speed things along in parallel
  ProofConfig pc(*w, 4, "",false); 
  if(mc->GetGlobalObservables()){
    cout << "will use global observables for unconditional ensemble"<<endl;
    mc->GetGlobalObservables()->Print();
    toymcsampler->SetGlobalObservables(*mc->GetGlobalObservables());
  }
  toymcsampler->SetProofConfig(&pc);	// enable proof


  // Now get the interval
  PointSetInterval* interval = fc.GetInterval();
  ConfidenceBelt* belt = fc.GetConfidenceBelt();
 
  // print out the iterval on the first Parameter of Interest
  cout << "\n95% interval on " <<firstPOI->GetName()<<" is : ["<<
    interval->LowerLimit(*firstPOI) << ", "<<
    interval->UpperLimit(*firstPOI) <<"] "<<endl;

  // get observed UL and value of test statistic evaluated there
  RooArgSet tmpPOI(*firstPOI);
  double observedUL = interval->UpperLimit(*firstPOI);
  firstPOI->setVal(observedUL);
  double obsTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*data,tmpPOI);


  // Ask the calculator which points were scanned
  RooDataSet* parameterScan = (RooDataSet*) fc.GetPointsToScan();
  RooArgSet* tmpPoint;

  // make a histogram of parameter vs. threshold
  TH1F* histOfThresholds = new TH1F("histOfThresholds","",
				    parameterScan->numEntries(),
				    firstPOI->getMin(),
				    firstPOI->getMax());
  histOfThresholds->GetXaxis()->SetTitle(firstPOI->GetName());
  histOfThresholds->GetYaxis()->SetTitle("Threshold");

  // loop through the points that were tested and ask confidence belt
  // what the upper/lower thresholds were.
  // For FeldmanCousins, the lower cut off is always 0
  for(Int_t i=0; i<parameterScan->numEntries(); ++i){
    tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
    double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
    double poiVal = tmpPoint->getRealValue(firstPOI->GetName()) ;
    histOfThresholds->Fill(poiVal,arMax);
  }
  TCanvas* c1 = new TCanvas();
  c1->Divide(2);
  c1->cd(1);
  histOfThresholds->SetMinimum(0);
  histOfThresholds->Draw();
  c1->cd(2);

  /////////////////////////////////////////////////////////////
  // Now we generate the expected bands and power-constriant
  ////////////////////////////////////////////////////////////

  // First: find parameter point for mu=0, with conditional MLEs for nuisance parameters
  RooAbsReal* nll = mc->GetPdf()->createNLL(*data);
  RooAbsReal* profile = nll->createProfile(*mc->GetParametersOfInterest());
  firstPOI->setVal(0.);
  profile->getVal(); // this will do fit and set nuisance parameters to profiled values
  RooArgSet* poiAndNuisance = new RooArgSet();
  if(mc->GetNuisanceParameters())
    poiAndNuisance->add(*mc->GetNuisanceParameters());
  poiAndNuisance->add(*mc->GetParametersOfInterest());
  w->saveSnapshot("paramsToGenerateData",*poiAndNuisance);
  RooArgSet* paramsToGenerateData = (RooArgSet*) poiAndNuisance->snapshot();
  cout << "\nWill use these parameter points to generate pseudo data for bkg only" << endl;
  paramsToGenerateData->Print("v");


  double CLb=0;
  double CLbinclusive=0;

  // Now we generate background only and find distribution of upper limits
  TH1F* histOfUL = new TH1F("histOfUL","",100,0,firstPOI->getMax());
  histOfUL->GetXaxis()->SetTitle("Upper Limit (background only)");
  histOfUL->GetYaxis()->SetTitle("Entries");
  for(int imc=0; imc<nToyMC; ++imc){

    // set parameters back to values for generating pseudo data
    w->loadSnapshot("paramsToGenerateData");

    // in 5.30 there is a nicer way to generate toy data  & randomize global obs
    RooAbsData* toyData = toymcsampler->GenerateToyData(*paramsToGenerateData);

    // get test stat at observed UL in observed data
    firstPOI->setVal(observedUL);
    double toyTSatObsUL = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);
    //    toyData->get()->Print("v");
    //    cout <<"obsTSatObsUL " <<obsTSatObsUL << "toyTS " << toyTSatObsUL << endl;
    if(obsTSatObsUL < toyTSatObsUL) // (should be checked)
      CLb+= (1.)/nToyMC;
    if(obsTSatObsUL <= toyTSatObsUL) // (should be checked)
      CLbinclusive+= (1.)/nToyMC;


    // loop over points in belt to find upper limit for this toy data
    double thisUL = 0;
    for(Int_t i=0; i<parameterScan->numEntries(); ++i){
      tmpPoint = (RooArgSet*) parameterScan->get(i)->clone("temp");
      double arMax = belt->GetAcceptanceRegionMax(*tmpPoint);
      firstPOI->setVal( tmpPoint->getRealValue(firstPOI->GetName()) );
      double thisTS = fc.GetTestStatSampler()->EvaluateTestStatistic(*toyData,tmpPOI);

      if(thisTS<=arMax){
	thisUL = firstPOI->getVal();
      } else{
	break;
      }
    }
    

    histOfUL->Fill(thisUL);

    
    delete toyData;
  }
  histOfUL->Draw();
  c1->SaveAs("one-sided_upper_limit_output.pdf");

  // if you want to see a plot of the sampling distribution for a particular scan point:

  // Now find bands and power constraint
  Double_t* bins = histOfUL->GetIntegral();
  TH1F* cumulative = (TH1F*) histOfUL->Clone("cumulative");
  cumulative->SetContent(bins);
  double band2sigDown=0, band1sigDown=0, bandMedian=0, band1sigUp=0,band2sigUp=0;
  for(int i=1; i<=cumulative->GetNbinsX(); ++i){
    if(bins[i]<RooStats::SignificanceToPValue(2))
      band2sigDown=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(1))
      band1sigDown=cumulative->GetBinCenter(i);
    if(bins[i]<0.5)
      bandMedian=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(-1))
      band1sigUp=cumulative->GetBinCenter(i);
    if(bins[i]<RooStats::SignificanceToPValue(-2))
      band2sigUp=cumulative->GetBinCenter(i);
  }

  t.Stop();
  t.Print();

  cout << "-2 sigma  band " << band2sigDown << endl;
  cout << "-1 sigma  band " << band1sigDown  << endl;
  cout << "median of band " << bandMedian << " [Power Constriant)]" << endl;
  cout << "+1 sigma  band " << band1sigUp << endl;
  cout << "+2 sigma  band " << band2sigUp << endl;

  // print out the iterval on the first Parameter of Interest
  cout << "\nobserved 95% upper-limit "<< interval->UpperLimit(*firstPOI) <<endl;
  cout << "CLb strict [P(toy>obs|0)] for observed 95% upper-limit "<< CLb <<endl;
  cout << "CLb inclusive [P(toy>=obs|0)] for observed 95% upper-limit "<< CLbinclusive <<endl;

  delete profile;
  delete nll;

}
コード例 #7
0
ファイル: create_tight.C プロジェクト: pbgeff/UserCode
void new_RA4(){
  
  // let's time this challenging example
  TStopwatch t;
  t.Start();

  // set RooFit random seed for reproducible results
  RooRandom::randomGenerator()->SetSeed(4357);

  // make model
  RooWorkspace* wspace = new RooWorkspace("wspace");

  wspace->factory("Gaussian::sigCons(prime_SigEff[0,-5,5], nom_SigEff[0,-5,5], 1)");
  wspace->factory("expr::SigEff('1.0*pow(1.20,@0)',prime_SigEff)"); // // 1+-20%, 1.20=exp(20%)

  wspace->factory("Poisson::on(non[0,50], sum::splusb(prod::SigUnc(s[0,0,50],SigEff),mainb[8.8,0,50],dilep[0.9,0,20],tau[2.3,0,20],QCD[0.,0,10],MC[0.1,0,4]))");

  wspace->factory("Gaussian::mcCons(prime_rho[0,-5,5], nom_rho[0,-5,5], 1)");
  wspace->factory("expr::rho('1.0*pow(1.39,@0)',prime_rho)"); // // 1+-39%
  wspace->factory("Poisson::off(noff[0,200], prod::rhob(mainb,rho,mu_plus_e[0.74,0.01,10],1.08))");
  wspace->factory("Gaussian::mcCons2(mu_plus_enom[0.74,0.01,4], mu_plus_e, sigmatwo[.05])");

  wspace->factory("Gaussian::dilep_pred(dilep_nom[0.9,0,20], dilep, sigma3[2.2])");
  wspace->factory("Gaussian::tau_pred(tau_nom[2.3,0,20], tau, sigma4[0.5])");
  wspace->factory("Gaussian::QCD_pred(QCD_nom[0.0,0,10], QCD, sigma5[1.0])");
  wspace->factory("Gaussian::MC_pred(MC_nom[0.1,0.01,4], MC, sigma7[0.14])");

  wspace->factory("PROD::model(on,off,mcCons,mcCons2,sigCons,dilep_pred,tau_pred,QCD_pred,MC_pred)");

  RooArgSet obs(*wspace->var("non"), *wspace->var("noff"), *wspace->var("mu_plus_enom"), *wspace->var("dilep_nom"), *wspace->var("tau_nom"), "obs");
  obs.add(*wspace->var("QCD_nom"));  obs.add(*wspace->var("MC_nom"));
  RooArgSet globalObs(*wspace->var("nom_SigEff"), *wspace->var("nom_rho"), "global_obs");
  // fix global observables to their nominal values
  wspace->var("nom_SigEff")->setConstant();
  wspace->var("nom_rho")->setConstant();

  RooArgSet poi(*wspace->var("s"), "poi");
  RooArgSet nuis(*wspace->var("mainb"), *wspace->var("prime_rho"), *wspace->var("prime_SigEff"), *wspace->var("mu_plus_e"), *wspace->var("dilep"), *wspace->var("tau"), "nuis");
  nuis.add(*wspace->var("QCD"));  nuis.add(*wspace->var("MC"));


  wspace->factory("Uniform::prior_poi({s})");
  wspace->factory("Uniform::prior_nuis({mainb,mu_plus_e,dilep,tau,QCD,MC})");
  wspace->factory("PROD::prior(prior_poi,prior_nuis)");

  wspace->var("non")->setVal(8); //observed
  //wspace->var("non")->setVal(12); //expected observation
  wspace->var("noff")->setVal(7); //observed events in control region
  wspace->var("mu_plus_enom")->setVal(0.74);
  wspace->var("dilep_nom")->setVal(0.9);
  wspace->var("tau_nom")->setVal(2.3);
  wspace->var("QCD")->setVal(0.0);
  wspace->var("MC")->setVal(0.1);


  RooDataSet * data = new RooDataSet("data","",obs);
  data->add(obs);
  wspace->import(*data);


  /////////////////////////////////////////////////////
  // Now the statistical tests
  // model config
  ModelConfig* pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*wspace);
  pSbModel->SetPdf(*wspace->pdf("model"));
  pSbModel->SetPriorPdf(*wspace->pdf("prior"));
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);
  wspace->import(*pSbModel);

  // set all but obs, poi and nuisance to const
  SetConstants(wspace, pSbModel);
  wspace->import(*pSbModel);


  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)wspace->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*wspace);
  wspace->import(*pBModel);


  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*data);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  //if(pSbModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  pNll = pBModel->GetPdf()->createNLL(*data);
  pProfile = pNll->createProfile(poi);
  ((RooRealVar *)poi.first())->setVal(poiValueForBModel);
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet();
  //if(pBModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pBModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pBModel->GetParametersOfInterest());
  cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
  pPoiAndNuisance->Print("v");
  pBModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  // inspect workspace
  wspace->Print();

  // save workspace to file
  wspace->writeToFile("tight.root");
  //wspace->writeToFile("tight_median.root");


  // clean up
  delete wspace;
  delete data;
  delete pSbModel;
  delete pBModel;

}
コード例 #8
0
void StandardHypoTestDemo(const char* infile = "",
                          const char* workspaceName = "combined",
                          const char* modelSBName = "ModelConfig",
                          const char* modelBName = "",
                          const char* dataName = "obsData", 
                          int calcType = 0, // 0 freq 1 hybrid, 2 asymptotic
                          int testStatType = 3,   // 0 LEP, 1 TeV, 2 LHC, 3 LHC - one sided
                          int ntoys = 5000, 
                          bool useNC = false, 
                          const char * nuisPriorName = 0)
{

/*

  Other Parameter to pass in tutorial
  apart from standard for filename, ws, modelconfig and data

  type = 0 Freq calculator 
  type = 1 Hybrid calculator
  type = 2 Asymptotic calculator  

  testStatType = 0 LEP
  = 1 Tevatron 
  = 2 Profile Likelihood
  = 3 Profile Likelihood one sided (i.e. = 0 if mu < mu_hat)

  ntoys:         number of toys to use 

  useNumberCounting:  set to true when using number counting events 

  nuisPriorName:   name of prior for the nnuisance. This is often expressed as constraint term in the global model
  It is needed only when using the HybridCalculator (type=1)
  If not given by default the prior pdf from ModelConfig is used. 

  extra options are available as global paramwters of the macro. They major ones are: 
 
  generateBinned       generate binned data sets for toys (default is false) - be careful not to activate with 
  a too large (>=3) number of observables 
  nToyRatio            ratio of S+B/B toys (default is 2)
  printLevel
  
*/

   // disable - can cause some problems
   //ToyMCSampler::SetAlwaysUseMultiGen(true);

   SimpleLikelihoodRatioTestStat::SetAlwaysReuseNLL(true);
   ProfileLikelihoodTestStat::SetAlwaysReuseNLL(true);
   RatioOfProfiledLikelihoodsTestStat::SetAlwaysReuseNLL(true);

   //RooRandom::randomGenerator()->SetSeed(0);

   // to change minimizers 
   // ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
   // ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2");
   // ROOT::Math::MinimizerOptions::SetDefaultTolerance(1);

  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file 
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////
  const char* filename = "";
  if (!strcmp(infile,""))
    filename = "results/example_combined_GaussExample_model.root";
  else
    filename = infile;
  // Check if example input file exists
  TFile *file = TFile::Open(filename);

  // if input file was specified byt not found, quit
  if(!file && strcmp(infile,"")){
    cout <<"file not found" << endl;
    return;
  } 

  // if default file not found, try to create it
  if(!file ){
    // Normally this would be run on the command line
    cout <<"will run standard hist2workspace example"<<endl;
    gROOT->ProcessLine(".! prepareHistFactory .");
    gROOT->ProcessLine(".! hist2workspace config/example.xml");
    cout <<"\n\n---------------------"<<endl;
    cout <<"Done creating example input"<<endl;
    cout <<"---------------------\n\n"<<endl;
  }

  // now try to access the file again
  file = TFile::Open(filename);
  if(!file){
    // if it is still not there, then we can't continue
    cout << "Not able to run hist2workspace to create example input" <<endl;
    return;
  }

  
  /////////////////////////////////////////////////////////////
  // Tutorial starts here
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }
  w->Print();

  // get the modelConfig out of the file
  ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);


  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !sbModel){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }
  // make b model
  ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);


   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) { 
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) { 
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) { 
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar) 
            RooStats::SetAllConstant(*bnuisPar);
      }
   }


  if (!bModel ) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("B_only"));      
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return;
      double oldval = var->getVal();
      var->setVal(0);
      //bModel->SetSnapshot( RooArgSet(*var, *w->var("lumi"))  );
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
  }
  
   if (!sbModel->GetSnapshot() || poiValue > 0) { 
      Info("StandardHypoTestDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      RooRealVar * var = dynamic_cast<RooRealVar*>(sbModel->GetParametersOfInterest()->first());
      if (!var) return;
      double oldval = var->getVal();
      if (poiValue > 0)  var->setVal(poiValue);
      //sbModel->SetSnapshot( RooArgSet(*var, *w->var("lumi") ) );
      sbModel->SetSnapshot( RooArgSet(*var) );
      if (poiValue > 0) var->setVal(oldval);
      //sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }

   



   // part 1, hypothesis testing 
   SimpleLikelihoodRatioTestStat * slrts = new SimpleLikelihoodRatioTestStat(*bModel->GetPdf(), *sbModel->GetPdf());
   // null parameters must includes snapshot of poi plus the nuisance values 
   RooArgSet nullParams(*bModel->GetSnapshot());
   if (bModel->GetNuisanceParameters()) nullParams.add(*bModel->GetNuisanceParameters());
   
   slrts->SetNullParameters(nullParams);
   RooArgSet altParams(*sbModel->GetSnapshot());
   if (sbModel->GetNuisanceParameters()) altParams.add(*sbModel->GetNuisanceParameters());
   slrts->SetAltParameters(altParams);


   ProfileLikelihoodTestStat * profll = new ProfileLikelihoodTestStat(*bModel->GetPdf());


   RatioOfProfiledLikelihoodsTestStat * 
      ropl = new RatioOfProfiledLikelihoodsTestStat(*bModel->GetPdf(), *sbModel->GetPdf(), sbModel->GetSnapshot());
   ropl->SetSubtractMLE(false);

   if (testStatType == 3) profll->SetOneSidedDiscovery(1);
   profll->SetPrintLevel(printLevel);

   // profll.SetReuseNLL(mOptimize);
   // slrts.SetReuseNLL(mOptimize);
   // ropl.SetReuseNLL(mOptimize);

   AsymptoticCalculator::SetPrintLevel(printLevel);

   HypoTestCalculatorGeneric *  hypoCalc = 0;
   // note here Null is B and Alt is S+B
   if (calcType == 0) hypoCalc = new  FrequentistCalculator(*data, *sbModel, *bModel);
   else if (calcType == 1) hypoCalc= new  HybridCalculator(*data, *sbModel, *bModel);
   else if (calcType == 2) hypoCalc= new  AsymptoticCalculator(*data, *sbModel, *bModel);

   if (calcType == 0) 
       ((FrequentistCalculator*)hypoCalc)->SetToys(ntoys, ntoys/nToysRatio);
   if (calcType == 1) 
       ((HybridCalculator*)hypoCalc)->SetToys(ntoys, ntoys/nToysRatio);
   if (calcType == 2 ) { 
      if (testStatType == 3) ((AsymptoticCalculator*) hypoCalc)->SetOneSidedDiscovery(true);  
      if (testStatType != 2 && testStatType != 3)  
         Warning("StandardHypoTestDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");
      

   }


   // check for nuisance prior pdf in case of nuisance parameters 
   if (calcType == 1 && (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() )) {
         RooAbsPdf * nuisPdf = 0; 
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  { 
            Info("StandardHypoTestDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the   model");
            if (bModel->GetPdf() && bModel->GetObservables() ) 
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else 
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }   
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  { 
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());            
            }
            else { 
               Error("StandardHypoTestDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();
      
         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) { 
            Warning("StandardHypoTestDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;
      
         ((HybridCalculator*)hypoCalc)->ForcePriorNuisanceAlt(*nuisPdf);
         ((HybridCalculator*)hypoCalc)->ForcePriorNuisanceNull(*nuisPdf);
   }

   // hypoCalc->ForcePriorNuisanceAlt(*sbModel->GetPriorPdf());
   // hypoCalc->ForcePriorNuisanceNull(*bModel->GetPriorPdf());

   ToyMCSampler * sampler = (ToyMCSampler *)hypoCalc->GetTestStatSampler();

   if (sampler && (calcType == 0 || calcType == 1) ) { 

      // look if pdf is number counting or extended
      if (sbModel->GetPdf()->canBeExtended() ) { 
         if (useNC)   Warning("StandardHypoTestDemo","Pdf is extended: but number counting flag is set: ignore it ");
      }
      else {
         // for not extended pdf
         if (!useNC)  { 
            int nEvents = data->numEntries();
            Info("StandardHypoTestDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
            sampler->SetNEventsPerToy(nEvents);
         }
         else {
            Info("StandardHypoTestDemo","using a number counting pdf");
            sampler->SetNEventsPerToy(1);
         }
      }
      
      if (data->isWeighted() && !generateBinned) { 
         Info("StandardHypoTestDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set generateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      if (generateBinned)  sampler->SetGenerateBinned(generateBinned);


      // set the test statistic
      if (testStatType == 0) sampler->SetTestStatistic(slrts); 
      if (testStatType == 1) sampler->SetTestStatistic(ropl); 
      if (testStatType == 2 || testStatType == 3) sampler->SetTestStatistic(profll); 

   }
   
   HypoTestResult *  htr = hypoCalc->GetHypoTest();
   htr->SetPValueIsRightTail(true);
   htr->SetBackgroundAsAlt(false);
   htr->Print(); // how to get meaningfull CLs at this point?

   delete sampler;
   delete slrts; 
   delete ropl; 
   delete profll;

   if (calcType != 2) {
      HypoTestPlot * plot = new HypoTestPlot(*htr,100);
      plot->SetLogYaxis(true);
      plot->Draw();
   }
   else { 
      std::cout << "Asymptotic results " << std::endl;
      
   }

   // look at expected significances 
   // found median of S+B distribution
   if (calcType != 2) { 

      SamplingDistribution * altDist = htr->GetAltDistribution();   
      HypoTestResult htExp("Expected Result");
      htExp.Append(htr);
      // find quantiles in alt (S+B) distribution 
      double p[5];
      double q[5];
      for (int i = 0; i < 5; ++i) { 
         double sig = -2  + i;
         p[i] = ROOT::Math::normal_cdf(sig,1);
      }
      std::vector<double> values = altDist->GetSamplingDistribution();
      TMath::Quantiles( values.size(), 5, &values[0], q, p, false);  

      for (int i = 0; i < 5; ++i) { 
         htExp.SetTestStatisticData( q[i] );
         double sig = -2  + i;      
         std::cout << " Expected p -value and significance at " << sig << " sigma = " 
                   << htExp.NullPValue() << " significance " << htExp.Significance() << " sigma " << std::endl; 
         
      }
   }
   else { 
      // case of asymptotic calculator 
      for (int i = 0; i < 5; ++i) { 
         double sig = -2  + i;      
         // sigma is inverted here 
         double pval = AsymptoticCalculator::GetExpectedPValues( htr->NullPValue(), htr->AlternatePValue(), -sig, false);
         std::cout << " Expected p -value and significance at " << sig << " sigma = " 
                   << pval << " significance " << ROOT::Math::normal_quantile_c(pval,1) << " sigma " << std::endl; 
         
      }
   }

}
コード例 #9
0
ファイル: asimov.C プロジェクト: ghl3/histfactoryUnitTests
void asimov() {


  std::string InputFile = "./data/example.root";

  // Create the measurement
  Measurement meas("meas", "meas");

  meas.SetOutputFilePrefix( "./results/asimov_UsingC" );
  meas.SetPOI( "SigXsecOverSM" );
  meas.AddConstantParam("alpha_syst1");
  meas.AddConstantParam("Lumi");

  meas.SetLumi( 1.0 );
  meas.SetLumiRelErr( 0.10 );
  meas.SetExportOnly( false );
  meas.SetBinHigh( 2 );

  // Create a channel

  Channel chan( "channel1" );
  chan.SetData( "data", InputFile );
  chan.SetStatErrorConfig( 0.05, "Poisson" );

  
  // Now, create some samples


  // Create the signal sample
  Sample signal( "signal", "signal", InputFile );
  signal.AddOverallSys( "syst1",  0.95, 1.05 );
  signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 );
  chan.AddSample( signal );

  // Background 1
  Sample background1( "background1", "background1", InputFile );
  background1.ActivateStatError( "background1_statUncert", InputFile );
  background1.AddOverallSys( "syst2", 0.95, 1.05  );
  chan.AddSample( background1 );


  // Background 1
  Sample background2( "background2", "background2", InputFile );
  background2.ActivateStatError();
  background2.AddOverallSys( "syst3", 0.95, 1.05  );
  chan.AddSample( background2 );
  

  // Done with this channel
  // Add it to the measurement:
  meas.AddChannel( chan );

  // Collect the histograms from their files,
  // print some output, 
  meas.CollectHistograms();
  //meas.PrintTree();

  // One can print XML code to an
  // output directory:
  // meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() );

  RooWorkspace* wspace = RooStats::HistFactory::HistoToWorkspaceFactoryFast::MakeCombinedModel(meas);

  // Get the pdf, obs
  RooAbsPdf* pdf = wspace->pdf("simPdf");
  RooDataSet* obsData = (RooDataSet*) wspace->data("obsData");
  RooDataSet* asimovData = (RooDataSet*) wspace->data("asimovData");

  // fit the pdf to the asimov data
  std::cout << "Fitting to Observed Data" << std::endl;
  pdf->fitTo(*obsData);

  std::cout << "Fitting to Asimov Data" << std::endl;
  pdf->fitTo(*asimovData);

  return;

}
コード例 #10
0
int main (int argc, char **argv)
{
  const char* chInFile = "ws.root";
  const char* chOutFile = "ws_data.root";
  const char* chRootFile = "BDT20.root";
  const char* chCut = "";

  char option_char;
  while ( (option_char = getopt(argc,argv, "i:o:r:c:")) != EOF )
    switch (option_char)
      {
         case 'i': chInFile = optarg; break;
         case 'o': chOutFile = optarg; break;
         case 'r': chRootFile = optarg; break;
         case 'c': chCut = optarg; break;
         case '?': fprintf (stderr,
                            "usage: %s [i<input file> o<output file>]\n", argv[0]);
      }

  cout << "In  Ws = " << chInFile << endl;
  cout << "Out Ws = " << chOutFile << endl;
  cout << "Data From = " << chRootFile << endl;
  cout << "Extra Cut = " << chCut << endl;


   TFile* in_file = new TFile(chInFile);
   RooWorkspace *rws = (RooWorkspace*) in_file->Get("rws");

   TFile* tree_file = new TFile(chRootFile);
   TTree* tree = (TTree*) tree_file->Get("tree");

   TFile* out_file = new TFile(chOutFile, "RECREATE");

   RooArgSet allVars(*rws->var("m"),*rws->var("t"),*rws->var("et"),*rws->var("cpsi"),*rws->var("ctheta"),*rws->var("phi"),*rws->var("d"),*rws->cat("dilution"));
   RooDataSet* data = new RooDataSet("data","data",allVars);
   RooDataSet* dataBkg = new RooDataSet("dataBkg","dataBkg",allVars);

   //TCut* cut = new TCut("5.17<bs_mass && bs_mass<5.57 && bs_pdl>-0.044 && bs_pdl<0.3 ");
   TCut* cut = new TCut("5.17<bs_mass && bs_mass<5.57 && bs_epdl<0.025 && bs_pdl<0.4 && bs_pdl>-0.44");
   *cut += chCut;
   tree->Draw(">>entry_list", *cut, "entrylist");
   TEntryList* event_list = (TEntryList*) out_file->Get("entry_list");

   Double_t dM, dT, dEt, dCpsi, dCtheta, dPhi, dd;
   Int_t ddDefined;
   tree->SetBranchAddress("bs_mass", &dM);
   tree->SetBranchAddress("bs_pdl", &dT);
   tree->SetBranchAddress("bs_epdl", &dEt);
   tree->SetBranchAddress("bs_angle_cpsi", &dCpsi);
   tree->SetBranchAddress("bs_angle_ctheta", &dCtheta);
   tree->SetBranchAddress("bs_angle_phi", &dPhi);
   tree->SetBranchAddress("newtag_ost", &dd);
   tree->SetBranchAddress("newtag_ost_defined", &ddDefined);


   for (Long_t i=0; i<event_list->GetN(); i++){
     tree->GetEntry(event_list->GetEntry(i));

       *rws->var("m")=dM;
       *rws->var("t")=dT/0.0299792458;
       *rws->var("et")=dEt/0.0299792458;
       *rws->var("cpsi")=dCpsi;
       *rws->var("ctheta")=dCtheta;
       *rws->var("phi")=dPhi;

       *rws->var("d")=0;
       rws->cat("dilution")->setIndex(0);
       if ( ddDefined==1 ){
    	   rws->cat("dilution")->setIndex(1);
    	   *rws->var("d")=dd;
       }

       data->add(allVars);
       if (dM<5.29 || dM>5.44)
           dataBkg->add(allVars);
   }

   rws->import(*data);
   rws->import(*dataBkg);
   rws->Write("rws");
   out_file->Close();
   in_file->Close();
   tree_file->Close();

   cout << endl << "Done." << endl;
}
コード例 #11
0
ファイル: makeWorkspace2015.C プロジェクト: vabdulla/Dimuons
void makeWorkspace2015(RooWorkspace& ws, const TString FileName, struct InputOpt opt){
  double binw=0.05;
 
  std::string finput(FileName);
  TFile *f = new TFile(finput.c_str());
  TTree* theTree       = (TTree*)gROOT->FindObject("myTree"); // OS --- all mass
 
  RooRealVar* mass       = new RooRealVar("invariantMass","#mu#mu mass", opt.dMuon.M.Min, opt.dMuon.M.Max, "GeV/c^{2}");	
  //  ws.import(*mass);
  RooRealVar* dimuPt     = new RooRealVar("dimuPt","p_{T}(#DiMuon)",0,60,"GeV/c");
  RooRealVar* dimuRapidity = new RooRealVar("dimuRapidity",  "dimuRapidity",-2.4, 2.4);
  RooRealVar* vProb      = new RooRealVar("vProb",  "vProb"  ,0.01,1.00);
  RooRealVar* QQsign     = new RooRealVar("QQsign",  "QQsign"  ,-1,5);
  RooRealVar* Centrality = new RooRealVar("Centrality","Centrality",0,200);
  RooRealVar* RunNb      = new RooRealVar("RunNb","RunNb",0,350000);
  RooRealVar* muPlusPt   = new RooRealVar("muPlusPt","muPlusPt", 0, 1000);
  RooRealVar* muMinusPt  = new RooRealVar("muMinusPt","muMinusPt", 0, 1000);
  RooRealVar* muPlusEta  = new RooRealVar("muPlusEta","muPlusEta", -2.4, 2.4);
  RooRealVar* muMinusEta = new RooRealVar("muMinusEta","muMinusEta", -2.4, 2.4);
  RooDataSet* data0, *dataOS, *dataSS;
  RooArgSet cols(*mass,*dimuPt,*dimuRapidity,*muPlusPt,*muMinusPt,*muPlusEta,*muMinusEta, *RunNb, *QQsign);
  data0 = new RooDataSet("data","data",cols); 

  // import the tree to the RooDataSet
  UInt_t          runNb;
  Int_t           centrality;
  ULong64_t       HLTriggers;
  Int_t           Reco_QQ_size;
  Int_t           Reco_QQ_sign[99];   //[Reco_QQ_size]
  TClonesArray    *Reco_QQ_4mom;
  TClonesArray    *Reco_QQ_mupl_4mom;
  TClonesArray    *Reco_QQ_mumi_4mom;
  ULong64_t       Reco_QQ_trig[99];   //[Reco_QQ_size]
  Float_t         Reco_QQ_VtxProb[99];   //[Reco_QQ_size]

  TBranch        *b_runNb;   //!
  TBranch        *b_centrality;   //!
  TBranch        *b_HLTriggers;   //!
  TBranch        *b_Reco_QQ_size;   //!
  TBranch        *b_Reco_QQ_sign;   //!
  TBranch        *b_Reco_QQ_4mom;   //!
  TBranch        *b_Reco_QQ_mupl_4mom;   //!
  TBranch        *b_Reco_QQ_mumi_4mom;   //!
  TBranch        *b_Reco_QQ_trig;   //!
  TBranch        *b_Reco_QQ_VtxProb;   //!

  Reco_QQ_4mom = 0;
  Reco_QQ_mupl_4mom = 0;
  Reco_QQ_mumi_4mom = 0;
  theTree->SetBranchAddress("runNb", &runNb, &b_runNb);
  theTree->SetBranchAddress("Centrality", &centrality, &b_centrality);
  theTree->SetBranchAddress("HLTriggers", &HLTriggers, &b_HLTriggers);
  theTree->SetBranchAddress("Reco_QQ_size", &Reco_QQ_size, &b_Reco_QQ_size);
  theTree->SetBranchAddress("Reco_QQ_sign", Reco_QQ_sign, &b_Reco_QQ_sign);
  theTree->GetBranch("Reco_QQ_4mom")->SetAutoDelete(kFALSE);
  theTree->SetBranchAddress("Reco_QQ_4mom", &Reco_QQ_4mom, &b_Reco_QQ_4mom);
  theTree->GetBranch("Reco_QQ_mupl_4mom")->SetAutoDelete(kFALSE);
  theTree->SetBranchAddress("Reco_QQ_mupl_4mom", &Reco_QQ_mupl_4mom, &b_Reco_QQ_mupl_4mom);
  theTree->GetBranch("Reco_QQ_mumi_4mom")->SetAutoDelete(kFALSE);
  theTree->SetBranchAddress("Reco_QQ_mumi_4mom", &Reco_QQ_mumi_4mom, &b_Reco_QQ_mumi_4mom);
  theTree->SetBranchAddress("Reco_QQ_trig", Reco_QQ_trig, &b_Reco_QQ_trig);
  theTree->SetBranchAddress("Reco_QQ_VtxProb", Reco_QQ_VtxProb, &b_Reco_QQ_VtxProb);

   if (theTree == 0) return;

   Long64_t nentries = theTree->GetEntriesFast();

   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      // Long64_t ientry = LoadTree(jentry);
      // if (ientry < 0) break;
      nb = theTree->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;

      for (int i=0; i<Reco_QQ_size; i++) {
         TLorentzVector *qq4mom = (TLorentzVector*) Reco_QQ_4mom->At(i);
         TLorentzVector *qq4mupl = (TLorentzVector*) Reco_QQ_mupl_4mom->At(i);
         TLorentzVector *qq4mumi = (TLorentzVector*) Reco_QQ_mumi_4mom->At(i);
         mass->setVal(qq4mom->M());
         dimuPt->setVal(qq4mom->Pt());
         dimuRapidity->setVal(qq4mom->Rapidity());
         vProb->setVal(Reco_QQ_VtxProb[i]);
         QQsign->setVal(Reco_QQ_sign[i]);
         Centrality->setVal(centrality);
         muPlusPt->setVal(qq4mupl->Pt());
         muMinusPt->setVal(qq4mumi->Pt());
         muPlusEta->setVal(qq4mupl->Eta());
         muMinusEta->setVal(qq4mumi->Eta());
         RunNb->setVal(runNb);

         data0->add(cols);
      }
   }

   TString cut_ap(Form("(%.2f<invariantMass && invariantMass<%.2f) &&"
		       "(%.2f<muPlusEta && muPlusEta < %.2f) &&" 
		       "(%.2f<muMinusEta && muMinusEta < %.2f) &&" 
		       "(%.2f<dimuPt && dimuPt<%.2f) &&"
		       "(abs(dimuRapidity)>%.2f && abs(dimuRapidity)<%.2f)  &&"
		       "(muPlusPt > %.2f && muMinusPt > %.2f) &&"
		       "(%d<=RunNb && RunNb<=%d)",
		       opt.dMuon.M.Min, opt.dMuon.M.Max,
		       opt.sMuon.Eta.Min, opt.sMuon.Eta.Max,
		       opt.sMuon.Eta.Min, opt.sMuon.Eta.Max,
		       opt.dMuon.Pt.Min, opt.dMuon.Pt.Max,
		       opt.dMuon.AbsRap.Min, opt.dMuon.AbsRap.Max,
		       opt.sMuon.Pt.Min, opt.sMuon.Pt.Min,
		       opt.RunNb.Start, opt.RunNb.End));
   TString cut_ap_OS(TString("(QQsign==0) && ") + cut_ap);
   TString cut_ap_SS(TString("(QQsign<0 || QQsign>0) && ") + cut_ap);
   
   dataOS = ( RooDataSet*) data0->reduce(Name("dataOS"), Cut(cut_ap_OS));
   dataSS = ( RooDataSet*) data0->reduce(Name("dataSS"), Cut(cut_ap_SS));

   ws.import(*dataSS);
   ws.import(*dataOS);
   f->Close();
}
コード例 #12
0
void combinedWorkspace_4WS(const char* name_pbpb_pass="******", const char* name_pbpb_fail="fitresult_pbpb_fail.root", const char* name_pp_pass="******", const char* name_pp_fail="fitresult_pp_fail.root", const char* name_out="fitresult_combo.root", const float systval = 0., const char* subDirName ="wsTest", int nCPU=2){
   // subdir: Directory to save workspaces under currentPATH/CombinedWorkspaces/subDir/

   // set things silent
   gErrorIgnoreLevel=kError;
   RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  
   bool dosyst = (systval > 0.);

   TString nameOut(name_out);
  
   RooWorkspace * ws = test_combine_4WS(name_pbpb_pass, name_pp_pass, name_pbpb_fail, name_pp_fail, false, nCPU);
   RooAbsData * data = ws->data("dOS_DATA");

   RooRealVar* RFrac2Svs1S_PbPbvsPP_P = ws->var("RFrac2Svs1S_PbPbvsPP_P");
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",-10);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",10);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*RFrac2Svs1S_PbPbvsPP_P, *leftEdge, *rightEdge));
   ws->import(step);
   ws->factory( "Uniform::flat(RFrac2Svs1S_PbPbvsPP_P)" );

   // systematics
   if (dosyst) {
     ws->factory( Form("kappa_syst[%f]",systval) );
     ws->factory( "expr::alpha_syst('kappa_syst*beta_syst',kappa_syst,beta_syst[0,-5,5])" );
     ws->factory( "Gaussian::constr_syst(beta_syst,glob_syst[0,-5,5],1)" );
     
     // add systematics into the double ratio
     ws->factory( "expr::RFrac2Svs1S_PbPbvsPP_P_syst('@0+@1',RFrac2Svs1S_PbPbvsPP_P,alpha_syst)" );
     
     // build the pbpb pdf
     RooRealVar* effjpsi_pp_P = (RooRealVar*)ws->var("effjpsi_pp_P");
     RooRealVar* effpsip_pp_P = (RooRealVar*)ws->var("effpsip_pp_P");
     RooRealVar* effjpsi_pp_NP = (RooRealVar*)ws->var("effjpsi_pp_NP");
     Double_t Npsi2SPbPbPass = npsip_pbpb_pass_from_doubleratio_prompt(ws, RooArgList(*effjpsi_pp_P,*effpsip_pp_P,*effjpsi_pp_NP),true); // Create and import N_Psi2S_PbPb_pass_syst
     
     ws->factory( "SUM::pdfMASS_Tot_PbPb_pass_syst(N_Jpsi_PbPb_pass * pdfMASS_Jpsi_PbPb_pass, N_Psi2S_PbPb_pass_syst * pdfMASS_Psi2S_PbPb_pass, N_Bkg_PbPb_pass * pdfMASS_Bkg_PbPb_pass)" );
     ws->factory( "PROD::pdfMASS_Tot_PbPb_pass_constr(pdfMASS_Tot_PbPb_pass_syst,constr_syst)" );
     
     // build the combined pdf
     ws->factory("SIMUL::simPdf_syst_noconstr(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass_syst,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)");
     RooSimultaneous *simPdf = (RooSimultaneous*) ws->pdf("simPdf_syst_noconstr");
     RooGaussian *constr_syst = (RooGaussian*) ws->pdf("constr_syst");
     RooProdPdf *simPdf_constr = new RooProdPdf("simPdf_syst","simPdf_syst",RooArgSet(*simPdf,*constr_syst));
     ws->import(*simPdf_constr);
     
   } else {
      ws->factory("SIMUL::simPdf_syst(sample,PbPb_pass=pdfMASS_Tot_PbPb_pass,PbPb_fail=pdfMASS_Tot_PbPb_fail,PP_pass=pdfMASS_Tot_PP_pass,PP_fail=pdfMASS_Tot_PP_fail)");
   }

   ws->Print();

   if (dosyst) ws->var("beta_syst")->setConstant(kFALSE);


   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws->var("invMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws->cat("sample"));    
   //  /////////////////////////////////////////////////////////////////////

   if (dosyst) ws->var("glob_syst")->setConstant(true);
   RooArgSet globalObs("global_obs");
   if (dosyst) globalObs.add( *ws->var("glob_syst") );

   // ws->Print();

   RooArgSet poi("poi");
   poi.add( *ws->var("RFrac2Svs1S_PbPbvsPP_P") );



   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   if (dosyst) nuis.add( *ws->var("beta_syst") );

   // set parameters constant
   RooArgSet allVars = ws->allVars();
   TIterator* it = allVars.createIterator();
   RooRealVar *theVar = (RooRealVar*) it->Next();
   while (theVar) {
      TString varname(theVar->GetName());
//      if (varname != "RFrac2Svs1S_PbPbvsPP"
//            && varname != "invMass"
//            && varname != "sample"
//            )
//         theVar->setConstant();
     if ( varname.Contains("f_Jpsi_PP") || varname.Contains("f_Jpsi_PbPb") ||
           varname.Contains("rSigma21_Jpsi_PP") || 
           varname.Contains("m_Jpsi_PP") || varname.Contains("m_Jpsi_PbPb") || 
           varname.Contains("sigma1_Jpsi_PP") || varname.Contains("sigma1_Jpsi_PbPb") || 
           (varname.Contains("lambda")) ||
           (varname.Contains("_fail") && !varname.Contains("RFrac2Svs1S")))
         {
           theVar->setConstant();
         }
      if (varname=="glob_syst"
            || varname=="beta_syst"
         ) {
         cout << varname << endl;
         theVar->setConstant(!dosyst);
      }
      theVar = (RooRealVar*) it->Next();
   }

   // create signal+background Model Config
   RooStats::ModelConfig sbHypo("SbHypo");
   sbHypo.SetWorkspace( *ws );
   sbHypo.SetPdf( *ws->pdf("simPdf_syst") );
   sbHypo.SetObservables( obs );
   sbHypo.SetGlobalObservables( globalObs );
   sbHypo.SetParametersOfInterest( poi );
   sbHypo.SetNuisanceParameters( nuis );
   sbHypo.SetPriorPdf( *ws->pdf("step") ); // this is optional


   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) );
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
  
   if (controlPlots)
   {
     RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,1),Title("LL and profileLL in RFrac2Svs1S_PbPbvsPP_P"));
     pNll->plotOn(framepoi,ShiftToZero());
     framepoi->SetMinimum(0);
     framepoi->SetMaximum(10);
     TCanvas *cpoi = new TCanvas();
     cpoi->cd(); framepoi->Draw();
     cpoi->SaveAs("cpoi.pdf");
   }
  
   ((RooRealVar *)poi.first())->setMin(0.);
   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);
  
   if (controlPlots)
   {
     RooPlot* xframeSB_PP_pass = pObs->frame(Title("SBhypo_PP_pass"));
     data->plotOn(xframeSB_PP_pass,Cut("sample==sample::PP_pass"));
     RooAbsPdf *pdfSB_PP_pass = sbHypo.GetPdf();
     RooCategory *sample = ws->cat("sample");
     pdfSB_PP_pass->plotOn(xframeSB_PP_pass,Slice(*sample,"PP_pass"),ProjWData(*sample,*data));
     TCanvas *c1 = new TCanvas();
     c1->cd(); xframeSB_PP_pass->Draw();
     c1->SaveAs("c1.pdf");
    
     RooPlot* xframeSB_PP_fail = pObs->frame(Title("SBhypo_PP_fail"));
     data->plotOn(xframeSB_PP_fail,Cut("sample==sample::PP_fail"));
     RooAbsPdf *pdfSB_PP_fail = sbHypo.GetPdf();
     pdfSB_PP_fail->plotOn(xframeSB_PP_fail,Slice(*sample,"PP_fail"),ProjWData(*sample,*data));
     TCanvas *c2 = new TCanvas();
     c2->cd(); xframeSB_PP_fail->Draw();
     c2->SaveAs("c1.pdf");
    
     RooPlot* xframeB_PbPb_pass = pObs->frame(Title("SBhypo_PbPb_pass"));
     data->plotOn(xframeB_PbPb_pass,Cut("sample==sample::PbPb_pass"));
     RooAbsPdf *pdfB_PbPb_pass = sbHypo.GetPdf();
     pdfB_PbPb_pass->plotOn(xframeB_PbPb_pass,Slice(*sample,"PbPb_pass"),ProjWData(*sample,*data));
     TCanvas *c3 = new TCanvas();
     c3->cd(); xframeB_PbPb_pass->Draw();
     c3->SetLogy();
     c3->SaveAs("c2.pdf");
    
     RooPlot* xframeB_PbPb_fail = pObs->frame(Title("SBhypo_PbPb_fail"));
     data->plotOn(xframeB_PbPb_fail,Cut("sample==sample::PbPb_fail"));
     RooAbsPdf *pdfB_PbPb_fail = sbHypo.GetPdf();
     pdfB_PbPb_fail->plotOn(xframeB_PbPb_fail,Slice(*sample,"PbPb_fail"),ProjWData(*sample,*data));
     TCanvas *c4 = new TCanvas();
     c4->cd(); xframeB_PbPb_fail->Draw();
     c4->SetLogy();
     c4->SaveAs("c2.pdf");
   }
  
   delete pNll;
   delete pPoiAndNuisance;
   ws->import( sbHypo );
  
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(nCPU) );
   // RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   RooAbsReal * pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   ((RooRealVar *)poi.first())->setVal( 0 );  // set RFrac2Svs1S_PbPbvsPP=0 here
   pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
   pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   bHypo.SetSnapshot(*pPoiAndNuisance);


   delete pNll;
   delete pPoiAndNuisance;

   // import model config into workspace
   bHypo.SetWorkspace(*ws);
   ws->import( bHypo );
  
   /////////////////////////////////////////////////////////////////////
   ws->Print();
   bHypo.Print();
   sbHypo.Print();

   // save workspace to file
   string mainDIR = gSystem->ExpandPathName(gSystem->pwd());
   string wsDIR = mainDIR + "/CombinedWorkspaces/";
   string ssubDirName="";
   if (subDirName) ssubDirName.append(subDirName);
   string subDIR = wsDIR + ssubDirName;
  
   void * dirp = gSystem->OpenDirectory(wsDIR.c_str());
   if (dirp) gSystem->FreeDirectory(dirp);
   else gSystem->mkdir(wsDIR.c_str(), kTRUE);

   void * dirq = gSystem->OpenDirectory(subDIR.c_str());
   if (dirq) gSystem->FreeDirectory(dirq);
   else gSystem->mkdir(subDIR.c_str(), kTRUE);
  
   const char* saveName = Form("%s/%s",subDIR.c_str(),nameOut.Data());
   ws->writeToFile(saveName);
}
コード例 #13
0
ファイル: signalFTest.cpp プロジェクト: ETHZ/h2gglobe
int main(int argc, char *argv[]){
 
  OptionParser(argc,argv);

  TStopwatch sw;
  sw.Start();

  RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
  RooMsgService::instance().setSilentMode(true);

  system("mkdir -p plots/fTest");

  vector<string> procs;
  split(procs,procString_,boost::is_any_of(","));
  
  TFile *inFile = TFile::Open(filename_.c_str());
  RooWorkspace *inWS = (RooWorkspace*)inFile->Get("cms_hgg_workspace");
  
  RooRealVar *mass = (RooRealVar*)inWS->var("CMS_hgg_mass");
  //mass->setBins(320);
  //mass->setRange(mass_-10,mass_+10);
  //mass->setBins(20);
  RooRealVar *MH = new RooRealVar("MH","MH",mass_);
  MH->setVal(mass_);
  MH->setConstant(true);

  map<string,pair<int,int> > choices;
  map<string,vector<RooPlot*> > plotsRV;
  map<string,vector<RooPlot*> > plotsWV;

  for (unsigned int p=0; p<procs.size(); p++){
    vector<RooPlot*> tempRV;
    vector<RooPlot*> tempWV;
    for (int cat=0; cat<ncats_; cat++){
      RooPlot *plotRV = mass->frame(Range(mass_-10,mass_+10));
      plotRV->SetTitle(Form("%s_cat%d_RV",procs[p].c_str(),cat));
      tempRV.push_back(plotRV);
      RooPlot *plotWV = mass->frame(Range(mass_-10,mass_+10));
      plotWV->SetTitle(Form("%s_cat%d_WV",procs[p].c_str(),cat));
      tempWV.push_back(plotWV);
    }
    plotsRV.insert(pair<string,vector<RooPlot*> >(procs[p],tempRV));
    plotsWV.insert(pair<string,vector<RooPlot*> >(procs[p],tempWV));
  }

  vector<int> colors;
  colors.push_back(kBlue);
  colors.push_back(kRed);
  colors.push_back(kGreen+2);
  colors.push_back(kMagenta+1);
  
  for (int cat=0; cat<ncats_; cat++){
    for (unsigned int p=0; p<procs.size(); p++){
      string proc = procs[p];
      RooDataSet *dataRV = (RooDataSet*)inWS->data(Form("sig_%s_mass_m%d_rv_cat%d",proc.c_str(),mass_,cat));
      RooDataSet *dataWV = (RooDataSet*)inWS->data(Form("sig_%s_mass_m%d_wv_cat%d",proc.c_str(),mass_,cat));
      //mass->setBins(160);
      //RooDataHist *dataRV = dataRVtemp->binnedClone();
      //RooDataHist *dataWV = dataWVtemp->binnedClone();
      //RooDataSet *dataRVw = (RooDataSet*)dataRVtemp->reduce(Form("CMS_hgg_mass>=%3d && CMS_hgg_mass<=%3d",mass_-10,mass_+10)); 
      //RooDataSet *dataWVw = (RooDataSet*)dataWVtemp->reduce(Form("CMS_hgg_mass>=%3d && CMS_hgg_mass<=%3d",mass_-10,mass_+10));
      //RooDataHist *dataRV = new RooDataHist(Form("roohist_%s",dataRVtemp->GetName()),Form("roohist_%s",dataRVtemp->GetName()),RooArgSet(*mass),*dataRVtemp);
      //RooDataHist *dataWV = new RooDataHist(Form("roohist_%s",dataWVtemp->GetName()),Form("roohist_%s",dataWVtemp->GetName()),RooArgSet(*mass),*dataWVtemp);
      //RooDataSet *dataRV = stripWeights(dataRVweight,mass);
      //RooDataSet *dataWV = stripWeights(dataWVweight,mass);
      //RooDataSet *data = (RooDataSet*)inWS->data(Form("sig_%s_mass_m%d_cat%d",proc.c_str(),mass_,cat));
     
      int rvChoice=0;
      int wvChoice=0;
      
      // right vertex
      int order=1;
      int prev_order=0;
      int cache_order=0;
      double thisNll=0.;
      double prevNll=1.e6;
      double chi2=0.;
      double prob=0.;

      dataRV->plotOn(plotsRV[proc][cat]);
      //while (prob<0.8) {
      while (order<5) {
        RooAddPdf *pdf = buildSumOfGaussians(Form("cat%d_g%d",cat,order),mass,MH,order);
        RooFitResult *fitRes = pdf->fitTo(*dataRV,Save(true),SumW2Error(true));//,Range(mass_-10,mass_+10));
        double myNll=0.;
        thisNll = fitRes->minNll();
        //double myNll = getMyNLL(mass,pdf,dataRV);
        //thisNll = getMyNLL(mass,pdf,dataRV);
        //RooAbsReal *nll = pdf->createNLL(*dataRV);
        //RooMinuit m(*nll);
        //m.migrad();
        //thisNll = nll->getVal();
        //plot(Form("plots/fTest/%s_cat%d_g%d_rv",proc.c_str(),cat,order),mass_,mass,dataRV,pdf);
        pdf->plotOn(plotsRV[proc][cat],LineColor(colors[order-1]));
        chi2 = 2.*(prevNll-thisNll);
        //if (chi2<0. && order>1) chi2=0.;
        int diffInDof = (2*order+(order-1))-(2*prev_order+(prev_order-1));
        prob = TMath::Prob(chi2,diffInDof);
        cout << "\t RV: " << cat << " " << order << " " << diffInDof << " " << prevNll << " " << thisNll << " " << myNll << " " << chi2 << " " << prob << endl;
        prevNll=thisNll;
        cache_order=prev_order;
        prev_order=order;
        order++;
      }
      rvChoice=cache_order;
      
      // wrong vertex
      order=1;
      prev_order=0;
      cache_order=0;
      thisNll=0.;
      prevNll=1.e6;
      chi2=0.;
      prob=0.;

      dataWV->plotOn(plotsWV[proc][cat]);
      while (order<4) {
      //while (prob<0.8) {
        RooAddPdf *pdf = buildSumOfGaussians(Form("cat%d_g%d",cat,order),mass,MH,order);
        RooFitResult *fitRes = pdf->fitTo(*dataWV,Save(true),SumW2Error(true));//,Range(mass_-10,mass_+10));
        double myNll=0.;
        thisNll = fitRes->minNll();
        //double myNll = getMyNLL(mass,pdf,dataRV);
        //thisNll = getMyNLL(mass,pdf,dataRV);
        //RooAbsReal *nll = pdf->createNLL(*dataWV);
        //RooMinuit m(*nll);
        //m.migrad();
        //thisNll = nll->getVal();
        //plot(Form("plots/fTest/%s_cat%d_g%d_wv",proc.c_str(),cat,order),mass_,mass,dataWV,pdf);
        pdf->plotOn(plotsWV[proc][cat],LineColor(colors[order-1]));
        chi2 = 2.*(prevNll-thisNll);
        //if (chi2<0. && order>1) chi2=0.;
        int diffInDof = (2*order+(order-1))-(2*prev_order+(prev_order-1));
        prob = TMath::Prob(chi2,diffInDof);
        cout << "\t WV: " << cat << " " << order << " " << diffInDof << " " << prevNll << " " << thisNll << " " << myNll << " " << chi2 << " " << prob << endl;
        prevNll=thisNll;
        cache_order=prev_order;
        prev_order=order;
        order++;
      }
      wvChoice=cache_order;

      choices.insert(pair<string,pair<int,int> >(Form("%s_cat%d",proc.c_str(),cat),make_pair(rvChoice,wvChoice)));
    } 
  }

  TLegend *leg = new TLegend(0.6,0.6,0.89,0.89);
  leg->SetFillColor(0);
  leg->SetLineColor(0);
  TH1F *h1 = new TH1F("h1","",1,0,1);
  h1->SetLineColor(colors[0]);
  leg->AddEntry(h1,"1st order","L");
  TH1F *h2 = new TH1F("h2","",1,0,1);
  h2->SetLineColor(colors[1]);
  leg->AddEntry(h2,"2nd order","L");
  TH1F *h3 = new TH1F("h3","",1,0,1);
  h3->SetLineColor(colors[2]);
  leg->AddEntry(h3,"3rd order","L");
  TH1F *h4 = new TH1F("h4","",1,0,1);
  h4->SetLineColor(colors[3]);
  leg->AddEntry(h4,"4th order","L");

  TCanvas *canv = new TCanvas();
  for (map<string,vector<RooPlot*> >::iterator plotIt=plotsRV.begin(); plotIt!=plotsRV.end(); plotIt++){
    string proc = plotIt->first;
    for (int cat=0; cat<ncats_; cat++){
      RooPlot *plot = plotIt->second.at(cat);
      plot->Draw();
      leg->Draw();
      canv->Print(Form("plots/fTest/rv_%s_cat%d.pdf",proc.c_str(),cat));
    }
  }
  for (map<string,vector<RooPlot*> >::iterator plotIt=plotsWV.begin(); plotIt!=plotsWV.end(); plotIt++){
    string proc = plotIt->first;
    for (int cat=0; cat<ncats_; cat++){
      RooPlot *plot = plotIt->second.at(cat);
      plot->Draw();
      leg->Draw();
      canv->Print(Form("plots/fTest/wv_%s_cat%d.pdf",proc.c_str(),cat));
    }
  }
  delete canv;

  cout << "Recommended options" << endl;
  for (map<string,pair<int,int> >::iterator it=choices.begin(); it!=choices.end(); it++){
    cout << "\t " << it->first << " - " << it->second.first << " " << it->second.second << endl; 
  }

  inFile->Close();
  return 0;
}
コード例 #14
0
void eregtraining_fixalpha(bool dobarrel, bool doele) {
   
//   gSystem->Setenv("OMP_WAIT_POLICY","PASSIVE");
  
  //candidate to set fixed alpha values (0.9,3.8)
  //TString dirname = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregtesteleJul30_sig5_01_alphafloat5_%i/",int(minevents)); 
  
  TString dirname = "/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/"; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);  
  
  std::vector<std::string> *varsf = new std::vector<std::string>;
  varsf->push_back("ph.scrawe");
  varsf->push_back("ph.sceta");
  varsf->push_back("ph.scphi");
  varsf->push_back("ph.r9");  
  varsf->push_back("ph.scetawidth");
  varsf->push_back("ph.scphiwidth");  
  varsf->push_back("ph.scnclusters");
  varsf->push_back("ph.hoveretower");
  varsf->push_back("rho");
  varsf->push_back("nVtx");  
 
  varsf->push_back("ph.etaseed-ph.sceta");
  varsf->push_back("atan2(sin(ph.phiseed-ph.scphi),cos(ph.phiseed-ph.scphi))");
  varsf->push_back("ph.eseed/ph.scrawe");
  
  varsf->push_back("ph.e3x3seed/ph.e5x5seed");
  varsf->push_back("ph.sigietaietaseed");   
  varsf->push_back("ph.sigiphiphiseed");   
  varsf->push_back("ph.covietaiphiseed");
  varsf->push_back("ph.emaxseed/ph.e5x5seed");
  varsf->push_back("ph.e2ndseed/ph.e5x5seed");
  varsf->push_back("ph.etopseed/ph.e5x5seed");
  varsf->push_back("ph.ebottomseed/ph.e5x5seed");
  varsf->push_back("ph.eleftseed/ph.e5x5seed");
  varsf->push_back("ph.erightseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5maxseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5topseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5bottomseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5leftseed/ph.e5x5seed");
  varsf->push_back("ph.e2x5rightseed/ph.e5x5seed");
  
  std::vector<std::string> *varseb = new std::vector<std::string>(*varsf);
  std::vector<std::string> *varsee = new std::vector<std::string>(*varsf);
  
  varseb->push_back("ph.e5x5seed/ph.eseed");
  
  varseb->push_back("ph.ietaseed");
  varseb->push_back("ph.iphiseed");
  varseb->push_back("ph.ietaseed%5");
  varseb->push_back("ph.iphiseed%2");       
  varseb->push_back("(abs(ph.ietaseed)<=25)*(ph.ietaseed%25) + (abs(ph.ietaseed)>25)*((ph.ietaseed-25*abs(ph.ietaseed)/ph.ietaseed)%20)");
  varseb->push_back("ph.iphiseed%20"); 
  varseb->push_back("ph.etacryseed");
  varseb->push_back("ph.phicryseed");

  varsee->push_back("ph.scpse/ph.scrawe");
    
  std::vector<std::string> *varslist;
  if (dobarrel) varslist = varseb;
  else varslist = varsee;
  
  RooArgList vars;
  for (unsigned int ivar=0; ivar<varslist->size(); ++ivar) {
    RooRealVar *var = new RooRealVar(TString::Format("var_%i",ivar),varslist->at(ivar).c_str(),0.);
    vars.addOwned(*var);
  }
  
  RooArgList condvars(vars);
  
//   RooRealVar *tgtvar = new RooRealVar("tgtvar","ph.scrawe/ph.gene",1.);
//   if (!dobarrel) tgtvar->SetTitle("(ph.scrawe + ph.scpse)/ph.gene");
  
  RooRealVar *tgtvar = new RooRealVar("tgtvar","ph.gene/ph.scrawe",1.);
  if (!dobarrel) tgtvar->SetTitle("ph.gene/(ph.scrawe + ph.scpse)");  
  
  //tgtvar->setRange(0.,5.);
  
  vars.addOwned(*tgtvar);


  
  //varstest.add(*tgtvar);
    
  RooRealVar weightvar("weightvar","",1.);

  //TFile *fdin = TFile::Open("/home/mingyang/cms/hist/hgg-2013Moriond/merged/hgg-2013Moriond_s12-diphoj-3-v7a_noskim.root");
//   TFile *fdin = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/trainingtreesJul1/hgg-2013Final8TeV_s12-zllm50-v7n_noskim.root");
//   TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterSingleInvert");
//   TTree *dtree = (TTree*)ddir->Get("hPhotonTreeSingle");    
  
/*  TFile *fdinsig = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/trainingtreesJul1/hgg-2013Moriond_s12-h125gg-gf-v7a_noskim.root");
  TDirectory *ddirsig = (TDirectory*)fdinsig->FindObjectAny("PhotonTreeWriterPreselNoSmear");
  TTree *dtreesig = (TTree*)ddirsig->Get("hPhotonTreeSingle");     */ 
  
  TString treeloc;
  if (doele) {
    treeloc = "RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPreselInvert/PhotonTreeWriterSingleInvert/hPhotonTreeSingle";
  }
  else {
    treeloc = "RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle";
  }

  TChain *tree;
  float xsecs[50];

      
  if (doele) {
    tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPreselInvert/PhotonTreeWriterSingleInvert/hPhotonTreeSingle");
    tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    
    xsecs[0] = 1.;
    initweights(tree,xsecs,1.);      
    
    xsecweights[0] = 1.0;
    
  }
  else {
    tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle");
    tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj20_40-2em-v7n_noskim.root");
    tree->Add("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-pj40-2em-v7n_noskim.root");
    
    xsecs[0] = 0.001835*81930.0;
    xsecs[1] = 0.05387*8884.0;    
    initweights(tree,xsecs,1.);  
    
    double weightscale = xsecweights[1];
    xsecweights[0] /= weightscale;
    xsecweights[1] /= weightscale;
  }
  
  
  TCut selcut;
  if (dobarrel) {
    selcut = "ph.genpt>16. && ph.isbarrel && ph.ispromptgen"; 
  }
  else {
    selcut = "ph.genpt>16. && !ph.isbarrel && ph.ispromptgen";     
  }
  

  
  TCut selweight = "xsecweight(procidx)";
  TCut prescale10 = "(evt%10==0)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale50 = "(evt%50==0)";
  TCut prescale100 = "(evt%100==0)";  
  TCut prescale1000 = "(evt%1000==0)";  
  TCut evenevents = "(evt%2==0)";
  TCut oddevents = "(evt%2==1)";
  //TCut oddevents = prescale100; 
  
  //weightvar.SetTitle(prescale10*selcut);
  
/*  new TCanvas;
  tree->Draw("ph.genpt>>hpt(200,0.,100.)",selweight*selcut);

  return;*/  
  
  if (doele) {
    weightvar.SetTitle(evenevents*selcut);
  }
  else {
    weightvar.SetTitle(selweight*selcut);
  }
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",tree,vars,weightvar);   
  
//   weightvar.SetTitle(prescale1000*selcut);
//   RooDataSet *hdatasig = RooTreeConvert::CreateDataSet("hdatasig",dtree,vars,weightvar);   
//   RooDataSet *hdatasigtest = RooTreeConvert::CreateDataSet("hdatasigtest",dtree,varstest,weightvar); 
  
  RooDataSet *hdatasig = 0;
  RooDataSet *hdatasigtest = 0;
  
//   weightvar.SetTitle(prescale10*selcut);
//   RooDataSet *hdatasigsmall = RooTreeConvert::CreateDataSet("hdatasigsmall",dtreesig,vars,weightvar);   
  
  RooRealVar sigwidthtvar("sigwidthtvar","",0.01);
  sigwidthtvar.setConstant(false);
  
  RooRealVar sigmeantvar("sigmeantvar","",1.);
  sigmeantvar.setConstant(false); 

  RooRealVar sigalphavar("sigalphavar","",1.);
  sigalphavar.setConstant(false);   
  
  RooRealVar signvar("signvar","",2.);
  signvar.setConstant(false);     

  RooRealVar sigalpha2var("sigalpha2var","",1.);
  sigalpha2var.setConstant(false);   
  
  RooRealVar sign2var("sign2var","",2.);
  sign2var.setConstant(false);     
  
  
   
  RooArgList tgts;
  RooGBRFunction func("func","",condvars,4);
  RooGBRTarget sigwidtht("sigwidtht","",func,0,sigwidthtvar);
  RooGBRTarget sigmeant("sigmeant","",func,1,sigmeantvar);
  RooGBRTarget signt("signt","",func,2,signvar);
  RooGBRTarget sign2t("sign2t","",func,3,sign2var);
  
  tgts.add(sigwidtht);
  tgts.add(sigmeant);
  tgts.add(signt);
  tgts.add(sign2t);
  
  RooRealConstraint sigwidthlim("sigwidthlim","",sigwidtht,0.0002,0.5);
  RooRealConstraint sigmeanlim("sigmeanlim","",sigmeant,0.2,2.0);
  //RooRealConstraint sigmeanlim("sigmeanlim","",sigmeant,-2.0,-0.2); 
  
  RooRealConstraint signlim("signlim","",signt,1.01,110.); 

  RooRealConstraint sign2lim("sign2lim","",sign2t,1.01,110.); 
  
  RooLinearVar tgtscaled("tgtscaled","",*tgtvar,sigmeanlim,RooConst(0.));
  
  RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(2.0),signlim,RooConst(1.0),sign2lim);
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(2.0),signlim,RooConst(1.0),sign2lim);
  
  //RooCBExp sigpdf("sigpdf","",tgtscaled,RooConst(-1.),sigwidthlim,sigalpha2lim,sign2lim,sigalphalim);
  
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,RooConst(100.),RooConst(100.),sigalpha2lim,sign2lim);
  //RooDoubleCBFast sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,sigalphalim,signlim,RooConst(3.),sign2lim);
  //RooCBShape sigpdf("sigpdf","",tgtscaled,RooConst(1.),sigwidthlim,sigalphalim,signlim);
  
  RooConstVar etermconst("etermconst","",0.);  
  //RooFormulaVar etermconst("etermconst","","1000.*(@0-1.)*(@0-1.)",RooArgList(tgtscaled));
   
  RooRealVar r("r","",1.);
  r.setConstant();

  std::vector<RooAbsReal*> vpdf;
  vpdf.push_back(&sigpdf);  

  double minweight = 200.;

  std::vector<double> minweights;
  minweights.push_back(minweight);
  
  //ntot.setConstant();

  TFile *fres = new TFile("fres.root","RECREATE");

  if (1) {  
    std::vector<RooAbsData*> vdata;
    vdata.push_back(hdata);    
    
    RooHybridBDTAutoPdf bdtpdfdiff("bdtpdfdiff","",func,tgts,etermconst,r,vdata,vpdf);
    bdtpdfdiff.SetMinCutSignificance(5.);
    bdtpdfdiff.SetPrescaleInit(100);
   // bdtpdfdiff.SetPrescaleInit(10);
    //bdtpdfdiff.SetMaxNSpurious(300.);
    //bdtpdfdiff.SetMaxNSpurious(2400.);
    bdtpdfdiff.SetShrinkage(0.1);
    bdtpdfdiff.SetMinWeights(minweights);
    //bdtpdfdiff.SetMaxNodes(270);
    //bdtpdfdiff.SetMaxNodes(750);
    bdtpdfdiff.SetMaxNodes(500);
    //bdtpdfdiff.SetMaxDepth(8);
    bdtpdfdiff.TrainForest(1e6);  
    
  }   
     
  
  RooWorkspace *wereg = new RooWorkspace("wereg");
  wereg->import(sigpdf);
  
  if (doele && dobarrel)
    wereg->writeToFile("wereg_ele_eb.root");    
  else if (doele && !dobarrel) 
    wereg->writeToFile("wereg_ele_ee.root");    
  else if (!doele && dobarrel)
    wereg->writeToFile("wereg_ph_eb.root");    
  else if (!doele && !dobarrel)
    wereg->writeToFile("wereg_ph_ee.root");    
  
  
  return;
  
  
}
コード例 #15
0
void fastEfficiencyNadir(unsigned int iEG, int iECAL1, int iColl1, int iECAL2, int iColl2,
			 TString dirIn="result/", 
			 TString lumi="200 pb", int nCPU=4, 
			 int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
			 TString probe="WP80", TString tag="WP80", TString fileIn="tree_effi_TagProbe.root")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // EG THRESHOLDS //
  const int nEG = 71;
  double thres[nEG];
  for(int i=0 ; i<nEG ; i++) thres[i]=i;

  TString names[nEG];
  ostringstream ossi;
  for(int i=0;i<(int)nEG;i++) {
    ossi.str("");
    ossi << thres[i] ;
    names[i] = ossi.str();
  }

  // NAMES //
  const int nECAL=2;
  const int nColl=2;

  TString name_leg_ecal[nECAL] = {"Barrel","Endcaps"};
  TString name_leg_coll[nColl] = {"Online","Emulation"};  

  TString name_ecal[nECAL] = {"_EB","_EE"};
  TString name_coll[nColl] = {"_N","_M"};

  TString dirResults = dirIn + "/turnons/EG"+names[iEG]+"/" ;
  TString name_image = 
    dirResults + "eff_EG"+names[iEG]+"_tag"+tag+"_probe"+probe+name_ecal[iECAL1]+name_coll[iColl1]+"_vs"+name_ecal[iECAL2]+name_coll[iColl2] ;

  // Output log //
  ofstream fichier(name_image+".txt", ios::out);


  // BINNING //
  const int nbins[nEG] = {29,29,29,29,21,21,21,22,22,21,22,21,22,18,19,18,18,18,18,20,20,20,20,19,20,20,20,20,21,21,
			  21,21,21,21,21,21,21,21,21,21, //EG30
			  22,22,22,22,22,22,22,22,22,22, //EG40
			  29,29,29,29,29,29,29,29,29,29, //EG50
			  29,29,29,29,29,29,29,29,29,29};//EG60

  Double_t bins_0[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG0
  Double_t bins_1[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG1
  Double_t bins_2[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG2 
  Double_t bins_3[29] = {1,1.5,1.8,2,2.2,2.4,2.6,2.8, 3, 3.5, 4,4.2,4.5,4.7,5,5.5,6,6.5,7,7.5,8,8.5,9,10,12,15,20,50,150};// EG3

  Double_t bins_4[21] = {1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 19, 21, 27, 32, 41, 50, 60, 70, 150}; // EG4
  Double_t bins_5[21] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 31, 40, 50, 60, 70, 150}; // EG5
  Double_t bins_6[21] = {3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17, 19, 21, 23, 27, 32, 41, 50, 60, 70, 150}; // EG6

  Double_t bins_7[22] = {2, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG7
  Double_t bins_8[22] = {3, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 21, 23, 25, 27, 32, 41, 50, 60, 70, 150}; // EG8
  Double_t bins_9[21] = {4, 6, 7, 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 31, 40, 50, 60, 70, 150}; // EG9

  Double_t bins_10[22] = {5, 7, 8, 9, 10, 11, 12, 13, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG10
  Double_t bins_11[21] = {6, 8, 9, 10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 26, 28, 31, 40, 50, 60, 70, 150}; // EG11
  Double_t bins_12[22] = {5, 7, 9, 10, 11, 12, 13, 14, 15, 17, 19, 21, 23, 25, 27, 29, 32, 41, 50, 60, 70, 150}; // EG12

  Double_t bins_13[18] = {5, 7, 9, 11, 12, 13, 14, 15, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG13
  Double_t bins_14[19] = {6, 8, 10, 12, 13, 14, 15, 16, 18, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG14
  Double_t bins_15[18] = {5, 7, 9, 11, 13, 14, 15, 16, 17, 19, 22, 25, 29, 37, 50, 60, 70, 150}; // EG15

  Double_t bins_16[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG16
  Double_t bins_17[18] = {9, 11, 13, 15, 16, 17, 18, 19, 21, 23, 25, 30, 35, 40, 50, 60, 70, 150}; // EG17
  Double_t bins_18[18] = {8, 10, 12, 14, 16, 17, 18, 19, 20, 22, 25, 30, 35, 40, 50, 60, 70, 150}; // EG18

  Double_t bins_19[20] = {9, 11, 13, 15, 17, 18, 19, 20, 21, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG19
  Double_t bins_20[20] = {8, 10, 12, 14, 16, 18, 19, 20, 21, 22, 24, 26, 30, 35, 40, 45, 50, 60, 70, 100}; // EG20
  Double_t bins_21[20] = {9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG21

  Double_t bins_22[20] = {10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG22
  Double_t bins_23[19] = {11, 13, 15, 17, 19, 21, 22, 23, 24, 25, 27, 30, 35, 40, 45, 50, 60, 70, 150}; // EG23
  Double_t bins_24[20] = {10, 12, 14, 16, 18, 20, 22, 23, 24, 25, 26, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG24

  Double_t bins_25[20] = {11, 13, 15, 17, 19, 21, 23, 24, 25, 26, 27, 29, 30, 35, 40, 45, 50, 60, 70, 150}; // EG25
  Double_t bins_26[20] = {10, 12, 14, 16, 18, 20, 22, 24, 25, 26, 27, 28, 30, 35, 40, 45, 50, 60, 70, 150}; // EG26
  Double_t bins_27[20] = {11, 13, 15, 17, 19, 21, 23, 25, 26, 27, 28, 29, 33, 35, 40, 45, 50, 60, 70, 150}; // EG27

  Double_t bins_28[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 27, 28, 29, 30, 32, 35, 40, 45, 50, 60, 70, 150}; // EG28
  Double_t bins_29[21] = {11, 13, 15, 17, 19, 21, 23, 25, 27, 28, 29, 30, 31, 33, 35, 40, 45, 50, 60, 70, 150}; // EG29
  Double_t bins_30[21] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 29, 30, 31, 32, 35, 40, 45, 50, 60, 70, 150}; // EG30

  Double_t bins_40[22] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 38, 39, 40, 42, 45, 50, 60, 70, 150}; // EG40
  Double_t bins_50[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG50
  Double_t bins_60[29] = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 48, 50, 55, 60, 70, 90, 110, 130, 150, 170, 190}; // EG60

  vector< Double_t* > bins;
  bins.push_back( bins_0 ); bins.push_back( bins_1 ); bins.push_back( bins_2 ); bins.push_back( bins_3 ); bins.push_back( bins_4 ); 
  bins.push_back( bins_5 ); bins.push_back( bins_6 ); bins.push_back( bins_7 ); bins.push_back( bins_8 ); bins.push_back( bins_9 ); 
  bins.push_back( bins_10 ); bins.push_back( bins_11 ); bins.push_back( bins_12 ); bins.push_back( bins_13 ); bins.push_back( bins_14 ); 
  bins.push_back( bins_15 ); bins.push_back( bins_16 ); bins.push_back( bins_17 ); bins.push_back( bins_18 ); bins.push_back( bins_19 ); 
  bins.push_back( bins_20 ); bins.push_back( bins_21 ); bins.push_back( bins_22 ); bins.push_back( bins_23 ); bins.push_back( bins_24 ); 
  bins.push_back( bins_25 ); bins.push_back( bins_26 ); bins.push_back( bins_27 ); bins.push_back( bins_28 ); bins.push_back( bins_29 ); 

  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_30 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_40 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_50 );
  for(int iV=0 ; iV<10 ; iV++) bins.push_back( bins_60 );

  RooBinning binning = RooBinning(nbins[iEG]-1, bins[iEG], "binning");


  // INPUT DATA //
  TFile* f1 = TFile::Open(dirIn+"/"+fileIn);

  TTree* treenew;
  TTree* treenew_2;

  treenew = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL1]+name_coll[iColl1] ) ;
  treenew_2 = (TTree*) gDirectory->Get( "treenew"+name_ecal[iECAL2]+name_coll[iColl2] ) ;

  TString name_scet[2], name_scdr[2], name_l1bin[2];
  name_scet[0] = "sc_et"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scet[1] = "sc_et"+name_ecal[iECAL2]+name_coll[iColl2];
  name_scdr[0] = "sc_dr"+name_ecal[iECAL1]+name_coll[iColl1];
  name_scdr[1] = "sc_dr"+name_ecal[iECAL2]+name_coll[iColl2];
  
  name_l1bin[0] = "l1_"+names[iEG]+name_ecal[iECAL1]+name_coll[iColl1];
  name_l1bin[1] = "l1_"+names[iEG]+name_ecal[iECAL2]+name_coll[iColl2];

  RooRealVar et_plot(name_scet[0],name_scet[0],0,150) ;
  RooRealVar dr(name_scdr[0],name_scdr[0],0.5,1.5) ; 
  RooRealVar et_plot2(name_scet[1],name_scet[1],0,150) ;
  RooRealVar dr2(name_scdr[1],name_scdr[1],0.5,1.5) ;

  // Acceptance state cut (1 or 0)
  RooCategory cut(name_l1bin[0],name_l1bin[0]) ;
  cut.defineType("accept",1) ;
  cut.defineType("reject",0) ;
  RooCategory cut2(name_l1bin[1],name_l1bin[1]) ;
  cut2.defineType("accept",1) ;
  cut2.defineType("reject",0) ;
  
  // PARAMETRES ROOFIT CRYSTAL BALL
  RooRealVar norm("norm","N",1,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.671034,0.01,8);
  RooRealVar n("n","n",4.07846,1.1,35);
  RooRealVar mean("mean","mean",20.8,0,100);
  //mean.setVal(thres[iEG]);
  RooRealVar sigma("sigma","#sigma",0.972825,0.01,5);
  //RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  RooRealVar norm2("norm2","N",0.999069,0.6,1);
  RooRealVar alpha2("alpha2","#alpha",0.492303,0.01,8);
  RooRealVar n2("n2","n",11.6694,1.1,35);
  RooRealVar mean2("mean2","mean",21.4582,0,100);
  //mean2.setVal(thres[iEG]);
  RooRealVar sigma2("sigma2","#sigma",1.19,0.01,5);
  //RooRealVar pedestal2("pedestal2","pedestal",0.01,0,0.4);

  FuncCB cb("cb","Crystal Ball Integree",et_plot,mean,sigma,alpha,n,norm) ;
  FuncCB cb2("cb2","Crystal Ball Integree",et_plot2,mean2,sigma2,alpha2,n2,norm2) ;
  
  // EFFICIENCY //
  RooEfficiency eff("eff","efficiency",cb,cut,"accept");
  RooEfficiency eff2("eff2","efficiency",cb2,cut2,"accept");

  // DATASETS //
  RooDataSet dataSet("data","data",RooArgSet(et_plot, cut,dr),Import(*treenew)); 
  RooDataSet dataSet2("data2","data2",RooArgSet(et_plot2, cut2,dr2),Import(*treenew_2));

  dataSet.Print();
  dataSet2.Print();
  
  // PLOT //
  RooPlot* frame = et_plot.frame(Bins(18000),Title("Fitted efficiency")) ;
  RooPlot* frame2 = et_plot2.frame(Bins(18000),Title("Fitted efficiency")) ;

  dataSet.plotOn(frame, Binning(binning), Efficiency(cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSet2.plotOn(frame2, Binning(binning), Efficiency(cut2), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );


  /////////////////////// FITTING /////////////////////////////

  double fit_cuts_min = thres[iEG]-1.5 ;
  double fit_cuts_max = 150;

  et_plot.setRange("interesting",fit_cuts_min,fit_cuts_max);
  et_plot2.setRange("interesting",fit_cuts_min,fit_cuts_max);

  RooFitResult* roofitres1 = new RooFitResult("roofitres1","roofitres1");
  RooFitResult* roofitres2 = new RooFitResult("roofitres2","roofitres2");

  fichier << "Fit characteristics :"   << endl ;
  fichier << "EG "     << names[iEG] << endl ;
  fichier << "Fit Range , EB Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "Fit Range , EE Coll : [" << fit_cuts_min << "," << fit_cuts_max << "]" << endl ;
  fichier << "----------------------"  << endl ;

  // Fit #1 //
  roofitres1 = eff.fitTo(dataSet,ConditionalObservables(et_plot),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
  
  cb.plotOn(frame,LineColor(color1),LineWidth(2));

  double res_norm1  = norm.getVal();
  double err_norm1  = norm.getErrorLo();
  double res_mean1  = mean.getVal();
  double err_mean1  = mean.getError();
  double res_sigma1 = sigma.getVal();
  double err_sigma1 = sigma.getError();
  double res_n1     = n.getVal();
  double err_n1     = n.getError();
  double res_alpha1 = alpha.getVal();
  double err_alpha1 = alpha.getError();

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << res_mean1  << "; "
	  << "double res_sigma=" << res_sigma1 << "; "
          << "double res_alpha=" << res_alpha1 << "; "
          << "double res_n="     << res_n1     << "; "
          << "double res_norm="  << res_norm1  << "; "
	  << endl
	  << "double err_mean="  << err_mean1  << "; "
	  << "double err_sigma=" << err_sigma1 << "; "
          << "double err_alpha=" << err_alpha1 << "; "
          << "double err_n="     << err_n1     << "; "
          << "double err_norm="  << err_norm1  << "; "
	  << endl;

  // Fit #2 //
  roofitres2 = eff2.fitTo(dataSet2,ConditionalObservables(et_plot2),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE));
 
  cb2.plotOn(frame2,LineColor(color2),LineWidth(2));

  double res_norm2  = norm2.getVal();
  double err_norm2  = norm2.getErrorLo();
  double res_mean2  = mean2.getVal();
  double err_mean2  = mean2.getError();
  double res_sigma2 = sigma2.getVal();
  double err_sigma2 = sigma2.getError();
  double res_n2     = n2.getVal();
  double err_n2     = n2.getError();
  double res_alpha2 = alpha2.getVal();
  double err_alpha2 = alpha2.getError();

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << res_mean2  << "; "
	  << "double res_sigma=" << res_sigma2 << "; "
	  << "double res_alpha=" << res_alpha2 << "; "
	  << "double res_n="     << res_n2     << "; "
	  << "double res_norm="  << res_norm2  << "; "
	  << endl
	  << "double err_mean="  << err_mean2  << "; "
	  << "double err_sigma=" << err_sigma2 << "; "
	  << "double err_alpha=" << err_alpha2 << "; "
	  << "double err_n="     << err_n2     << "; "
	  << "double err_norm="  << err_norm2  << "; "
	  << endl;
    

  ////////////////////////////  DRAWING PLOTS AND LEGENDS /////////////////////////////////
  TCanvas* ca = new TCanvas("ca","Trigger Efficiency") ;

  ca->SetGridx();
  ca->SetGridy();
  ca->cd();
  
  gPad->SetLogx();
  gPad->SetObjectStat(1);

  frame->GetYaxis()->SetRangeUser(0,1.05);
  frame->GetXaxis()->SetRangeUser(1,100.);
  frame->GetYaxis()->SetTitle("Efficiency");
  frame->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame->Draw() ;

  frame2->GetYaxis()->SetRangeUser(0,1.05);
  frame2->GetXaxis()->SetRangeUser(1,100.);
  frame2->GetYaxis()->SetTitle("Efficiency");
  frame2->GetXaxis()->SetTitle("E_{T} [GeV]");
  frame2->Draw("same") ;

  TH1F *SCeta1 = new TH1F("SCeta1","SCeta1",50,-2.5,2.5);
  TH1F *SCeta2 = new TH1F("SCeta2","SCeta2",50,-2.5,2.5);

  SCeta1->SetLineColor(color1) ;
  SCeta1->SetMarkerColor(color1);
  SCeta1->SetMarkerStyle(style1);

  SCeta2->SetLineColor(color2) ;
  SCeta2->SetMarkerColor(color2);
  SCeta2->SetMarkerStyle(style2);

  TLegend *leg = new TLegend(0.246,0.435,0.461,0.560,NULL,"brNDC"); // mid : x=353.5
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);
  leg->SetMargin(0.25);
  TLegendEntry *entry=leg->AddEntry("NULL","L1_SingleEG"+names[iEG],"h");
//   leg->AddEntry(SCeta1,name_leg_ecal[iECAL1]+" "+name_leg_coll[iColl1],"p");
//   leg->AddEntry(SCeta2,name_leg_ecal[iECAL2]+" "+name_leg_coll[iColl2],"p");
  leg->AddEntry(SCeta1,name_leg_ecal[iECAL1],"p");
  leg->AddEntry(SCeta2,name_leg_ecal[iECAL2],"p");
  leg->Draw();

  leg = new TLegend(0.16,0.725,0.58,0.905,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.03);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+names[iEG]+" GeV","h");
  leg->Draw();

  TPaveText *pt2 = new TPaveText(0.220,0.605,0.487,0.685,"brNDC"); // mid : x=353.5                                          
  pt2->SetLineColor(1);
  pt2->SetTextColor(1);
  pt2->SetTextFont(42);
  pt2->SetTextSize(0.03);
  pt2->SetFillColor(kWhite);
  pt2->SetShadowColor(kWhite);
  pt2->AddText("L1 E/Gamma Trigger");
  pt2->AddText("Electrons from Z");
  pt2->Draw();
  
  //TString name_image="eff_EG20_2012_12fb";

  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");
  ca->Print(name_image+".eps","eps");

  /////////////////////////////
  // SAVE THE ROO FIT RESULT //
  /////////////////////////////

  RooWorkspace *w = new RooWorkspace("workspace","workspace") ;

  w->import(dataSet);
  w->import(dataSet2);
  
  w->import(*roofitres1,"roofitres1");
  w->import(*roofitres2,"roofitres2");

  cout << "CREATES WORKSPACE : " << endl;
  w->Print();
  
  w->writeToFile(name_image+"_fitres.root") ;
  //gDirectory->Add(w) ;

  //f1->Close();
}
コード例 #16
0
///
/// Fit to the minimum using an improve method.
/// The idea is to kill known minima. For this, we add a multivariate
/// Gaussian to the chi2 at the position of the minimum. Ideally it should
/// be a parabola shaped function, but the Gaussian is readily available.
/// A true parabola like in the original IMPROVE algorithm doesn't work
/// because apparently it affects the other regions of
/// the chi2 too much. There are two parameters to tune: the width of the
/// Gaussian, which is controlled by the error definition of the first fit,
/// and the height of the Gaussian, which is set to 16 (=4 sigma).
/// Three fits are performed: 1) initial fit, 2) fit with improved FCN,
/// 3) fit of the non-improved FCN using the result from step 2 as the start
/// parameters.
/// So far it is only available for the Prob method, via the probimprove
/// command line flag.
///
RooFitResult* Utils::fitToMinImprove(RooWorkspace *w, TString name)
{
	TString parsName = "par_"+name;
	TString obsName  = "obs_"+name;
	TString pdfName  = "pdf_"+name;
	int printlevel = -1;
	RooMsgService::instance().setGlobalKillBelow(ERROR);

	// step 1: find a minimum to start with
	RooFitResult *r1 = 0;
	{
		RooFormulaVar ll("ll", "ll", "-2*log(@0)", RooArgSet(*w->pdf(pdfName)));
		// RooFitResult* r1 = fitToMin(&ll, printlevel);
		RooMinuit m(ll);
		m.setPrintLevel(-2);
		m.setNoWarn();
		m.setErrorLevel(4.0); ///< define 2 sigma errors. This will make the hesse PDF 2 sigma wide!
		int status = m.migrad();
		r1 = m.save();
		// if ( 102<RadToDeg(w->var("g")->getVal())&&RadToDeg(w->var("g")->getVal())<103 )
		// {
		//   cout << "step 1" << endl;
		//   r1->Print("v");
		//   gStyle->SetPalette(1);
		//   float xmin = 0.;
		//   float xmax = 3.14;
		//   float ymin = 0.;
		//   float ymax = 0.2;
		//   TH2F* histo = new TH2F("histo", "histo", 100, xmin, xmax, 100, ymin, ymax);
		//   for ( int ix=0; ix<100; ix++ )
		//   for ( int iy=0; iy<100; iy++ )
		//   {
		//     float x = xmin + (xmax-xmin)*(double)ix/(double)100;
		//     float y = ymin + (ymax-ymin)*(double)iy/(double)100;
		//     w->var("d_dk")->setVal(x);
		//     w->var("r_dk")->setVal(y);
		//     histo->SetBinContent(ix+1,iy+1,ll.getVal());
		//   }
		//   newNoWarnTCanvas("c2");
		//   histo->GetZaxis()->SetRangeUser(0,20);
		//   histo->Draw("colz");
		//   setParameters(w, parsName, r1);
		// }
	}

	// step 2: build and fit the improved fcn
	RooFitResult *r2 = 0;
	{
		// create a Hesse PDF, import both PDFs into a new workspace,
		// so that their parameters are linked
		RooAbsPdf* hessePdf = r1->createHessePdf(*w->set(parsName));
		if ( !hessePdf ) return r1;
		// RooWorkspace* wImprove = (RooWorkspace*)w->Clone();
		RooWorkspace* wImprove = new RooWorkspace();
		wImprove->import(*w->pdf(pdfName));
		wImprove->import(*hessePdf);
		hessePdf = wImprove->pdf(hessePdf->GetName());
		RooAbsPdf* fullPdf = wImprove->pdf(pdfName);

		RooFormulaVar ll("ll", "ll", "-2*log(@0) +16*@1", RooArgSet(*fullPdf, *hessePdf));
		// RooFitResult *r2 = fitToMin(&ll, printlevel);
		RooMinuit m(ll);
		m.setPrintLevel(-2);
		m.setNoWarn();
		m.setErrorLevel(1.0);
		int status = m.migrad();
		r2 = m.save();

		// if ( 102<RadToDeg(w->var("g")->getVal())&&RadToDeg(w->var("g")->getVal())<103 )
		// {
		//   cout << "step 3" << endl;
		//   r2->Print("v");
		//
		//   gStyle->SetPalette(1);
		//   float xmin = 0.;
		//   float xmax = 3.14;
		//   float ymin = 0.;
		//   float ymax = 0.2;
		//   TH2F* histo = new TH2F("histo", "histo", 100, xmin, xmax, 100, ymin, ymax);
		//   for ( int ix=0; ix<100; ix++ )
		//   for ( int iy=0; iy<100; iy++ )
		//   {
		//     float x = xmin + (xmax-xmin)*(double)ix/(double)100;
		//     float y = ymin + (ymax-ymin)*(double)iy/(double)100;
		//     wImprove->var("d_dk")->setVal(x);
		//     wImprove->var("r_dk")->setVal(y);
		//     histo->SetBinContent(ix+1,iy+1,ll.getVal());
		//   }
		//   newNoWarnTCanvas("c7");
		//   histo->GetZaxis()->SetRangeUser(0,20);
		//   histo->Draw("colz");
		//   // setParameters(wImprove, parsName, r1);
		// }
		delete wImprove;
	}

	// step 3: use the fit result of the improved fit as
	// start parameters for the nominal fcn
	RooFitResult* r3;
	{
		setParameters(w, parsName, r2);
		RooFormulaVar ll("ll", "ll", "-2*log(@0)", RooArgSet(*w->pdf(pdfName)));
		RooMinuit m(ll);
		m.setPrintLevel(-2);
		m.setNoWarn();
		m.setErrorLevel(1.0);
		int status = m.migrad();
		r3 = m.save();
		// if ( 102<RadToDeg(w->var("g")->getVal())&&RadToDeg(w->var("g")->getVal())<103 )
		// {
		//   cout << "step 3" << endl;
		//   r3->Print("v");
		// }
	}

	// step 5: chose better minimum
	// cout << r1->minNll() << " " << r3->minNll() << endl;
	RooFitResult* r = 0;
	if ( r1->minNll()<r3->minNll() )
	{
		delete r3;
		r = r1;
	}
	else
	{
		delete r1;
		r = r3;
		// cout << "Utils::fitToMinImprove() : improved fit is better!" << endl;
	}

	RooMsgService::instance().setGlobalKillBelow(INFO);

	// set to best parameters
	setParameters(w, parsName, r);
	return r;
}
コード例 #17
0
ファイル: buildPdf.C プロジェクト: carlpan/HZZResearch
void buildPdf()
{
    
    Double_t lorange = 100.;
    Double_t hirange = 140.;
    
    // Import data
    TFile *file = new TFile("/atlas/data18a/yupan/HZZ4l2012/MiniTree/data12.root");
    TTree *tree = (TTree*)file->Get("tree_incl_4mu");
    // should include all channels, for now just testing...
    
    // Define variables
    Float_t m4l = 0;
    Float_t m4lerr = 0;
   // Float_t wgt = 0;
    
    // Get number of entries and setbranchaddress
    Int_t nevents = tree->GetEntries();
    
    tree->SetBranchStatus("*",0);
    tree->SetBranchStatus("m4l_unconstrained",1);
    tree->SetBranchStatus("m4lerr_unconstrained",1);
    //tree->SetBranchStatus("weight",1);
    
    tree->SetBranchAddress("m4l_unconstrained",&m4l);
    tree->SetBranchAddress("m4lerr_unconstrained",&m4lerr);
    //tree->SetBranchAddress("weight",&wgt);
    
    ///////////////
    // Build pdfs
    //////////////
    RooRealVar* mass = new RooRealVar("m4l","mass",lorange,hirange,"GeV");
    RooRealVar merr("m4lerr","mass err",0.1,4.0,"GeV");
    //RooRealVar weight("weight","weight",0,10);
    
    RooRealVar scale("scale","per-event error scale factor",1.0,0.2,4.0);
    RooProduct sigmaErr("sigmaErr","sigmaErr",RooArgSet(scale,merr));
   
    /*
    float totalwgt(0);
    for (Int_t i=0; i<nevents; i++) {
        tree->GetEntry(i);
        totalwgt+=wgt;
    }
    std::cout<<"total weight = "<<totalwgt<<std::endl;
   */ 
    /// Make DataSet
    RooDataSet signal("signal","signal",RooArgSet(*mass,merr));
    
    std::cout<<"Reading in events from signal minitree"<<std::endl;
    for (Int_t i=0; i<nevents; i++) {
        tree->GetEntry(i);
        mass->setVal(m4l);
        merr.setVal(m4lerr);
        //weight.setVal(wgt/totalwgt);
        signal.add(RooArgSet(*mass,merr));
    }
    
    // Create 1D kernel estimation for signal mass
    std::cout<<"Building mass keys"<<std::endl;
    RooKeysPdf kestsig("kestsig","kestsig",*mass,signal);
    TH1F* hm = (TH1F*)kestsig.createHistogram("hm",*mass);
    kestsig.fillHistogram(hm,RooArgList(*mass));
    std::cout<<"Building mass pdf"<<std::endl;
    RooDataHist* dmass = new RooDataHist("dmass","binned dataset",*mass,hm);
    RooHistPdf* masspdf = new RooHistPdf("masspdf","pdf(dm)",*mass,*dmass,2);
    
    // Create 1D kernel estimation for mass err
    std::cout<<"Building error keys"<<std::endl;
    RooKeysPdf kestsigerr("kestsigerr","kestsigerr",merr,signal,RooKeysPdf::MirrorBoth,2);
    TH1F* herr = (TH1F*)kestsigerr.createHistogram("herr",merr);
    kestsigerr.fillHistogram(herr,RooArgList(merr));
    std::cout<<"Integral "<<herr->Integral()<<std::endl;
    std::cout<<"Building error pdf"<<std::endl;
    RooDataHist* derr = new RooDataHist("derr","binned dataset",merr,herr);
    RooHistPdf* errpdf = new RooHistPdf("errpdf","pdf(de)",merr,*derr,2);
    
    
    //Make the crystal ball resolution model with CB sigma = mass error
    RooRealVar 	meanCB 	("meanCB",  "mean CB", hmass, hmass-10., hmass+5.);
    RooRealVar 	alphaCB	("alphaCB", "alpha CB", 7, 0., 10.);
    RooRealVar 	nnCB   	("nnCB", "nn CB", 1.5, 0., 15.);
    RooCBShape* shapeCB = new RooCBShape("shapeCB", "crystal ball pdf", *mass, meanCB, sigmaErr, alphaCB, nnCB);

    // Make conditional pdf
    RooProdPdf* sigmodel = new RooProdPdf("sigmodel","sigmodel", *errpdf, Conditional(*shapeCB, *mass));

    
    
    // Make a workspace to store the fit model
    RooWorkspace* pdfWsp = new RooWorkspace("pdfWspCB");
    pdfWsp->import(*sigmodel,RecycleConflictNodes());
    pdfWsp->import(*masspdf);
    pdfWsp->import(*errpdf,RecycleConflictNodes());
    pdfWsp->import(signal);
    pdfWsp->Print();
    pdfWsp->writeToFile("pdfWspCB.root");
    
    
    // Make some plots
    TCanvas *c = new TCanvas("c","c",500,500);
    c->Divide(2);
    RooPlot* frame = merr.frame(Title("keys signal error"));
    signal.plotOn(frame);
    kestsigerr.plotOn(frame,LineColor(kRed));
    errpdf->plotOn(frame);
    
    RooPlot* frame2 = mass->frame(Title("keys signal"));
    signal.plotOn(frame2);
    kestsig.plotOn(frame2,LineColor(kRed));
    masspdf->plotOn(frame2);
    
    c->cd(2);
    frame->Draw();
    c->cd(1);
    grame2->Draw();
    
    c->Print("testPdf.png");
    
    
}
コード例 #18
0
void ZeeGammaMassFitSystematicStudy(string workspaceFile, const Int_t seed = 1234, 
                                    Int_t Option = 0, Int_t NToys = 1) {


  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================    
  TRandom3 *randomnumber = new TRandom3(seed);
//   RooRealVar m("m","mass",60,130);

  RooCategory sample("sample","");
  sample.defineType("Pass",1);
  sample.defineType("Fail",2);

  //--------------------------------------------------------------------------------------------------------------
  //Load Workspace
  //==============================================================================================================    
  TFile *f = new TFile (workspaceFile.c_str(), "READ");
  RooWorkspace *w = (RooWorkspace*)f->Get("MassFitWorkspace");

  //--------------------------------------------------------------------------------------------------------------
  //Setup output tree
  //==============================================================================================================    
  TFile *outputfile = new TFile (Form("EffToyResults_Option%d_Seed%d.root",Option, seed), "RECREATE");
  float varEff = 0;
  float varEffErrL = 0;
  float varEffErrH = 0;
  TTree *outTree = new TTree("eff","eff");
  outTree->Branch("eff",&varEff, "eff/F");
  outTree->Branch("efferrl",&varEffErrL, "efferrl/F");
  outTree->Branch("efferrh",&varEffErrH, "efferrh/F");
  
  //--------------------------------------------------------------------------------------------------------------
  //Load Model
  //==============================================================================================================    
  RooSimultaneous *totalPdf = (RooSimultaneous*)w->pdf("totalPdf");
  RooRealVar *m_default = (RooRealVar*)w->var("m");
  m_default->setRange("signalRange",85, 95);
  
  //get default models
  RooAddPdf *modelPass_default = (RooAddPdf*)w->pdf("modelPass");
  RooAddPdf *modelFail_default = (RooAddPdf*)w->pdf("modelFail");

  //get variables
  RooRealVar *Nsig = (RooRealVar*)w->var("Nsig");
  RooRealVar *eff = (RooRealVar*)w->var("eff");
  RooRealVar *NbkgFail = (RooRealVar*)w->var("NbkgFail");

  RooFormulaVar NsigPass("NsigPass","eff*Nsig",RooArgList(*eff,*Nsig));	 
  RooFormulaVar NsigFail("NsigFail","(1.0-eff)*Nsig",RooArgList(*eff,*Nsig));

  //get number of expected events
  Double_t npass = 100;
  Double_t nfail = 169;

  //*************************************************************************************
  //make alternative model
  //*************************************************************************************
  RooRealVar *tFail_default = (RooRealVar*)w->var("tFail");
  RooRealVar *fracFail_default = (RooRealVar*)w->var("fracFail");
 

  RooRealVar *meanFail_default = (RooRealVar*)w->var("meanFail");
  RooRealVar *sigmaFail_default = (RooRealVar*)w->var("sigmaFail");
  RooHistPdf *bkgFailTemplate_default = (RooHistPdf*)w->pdf("bkgHistPdfFail");
  RooFFTConvPdf *sigFail_default = (RooFFTConvPdf*)w->pdf("signalFail");
  RooFFTConvPdf *bkgFail_default = (RooFFTConvPdf*)w->pdf("bkgConvPdfFail");
  RooExtendPdf *esignalFail_default = (RooExtendPdf *)w->pdf("esignalFail");
  RooExtendPdf *ebackgroundFail_default = (RooExtendPdf *)w->pdf("ebackgroundFail");
  RooExponential *bkgexpFail_default = (RooExponential*)w->pdf("bkgexpFail");
  RooAddPdf *backgroundFail_default = (RooAddPdf*)w->pdf("backgroundFail");
  RooGaussian *bkggausFail_default = (RooGaussian*)w->pdf("bkggausFail");

  //shifted mean
  RooRealVar *meanFail_shifted = new RooRealVar("meanFail_shifted","meanFail_shifted", 0, -5, 5);
  meanFail_shifted->setVal(meanFail_default->getVal());
  if (Option == 1) meanFail_shifted->setVal(meanFail_default->getVal()-1.0);
  else if (Option == 2) meanFail_shifted->setVal(meanFail_default->getVal()+1.0);  
  else if (Option == 11) meanFail_shifted->setVal(meanFail_default->getVal()-2.0);
  else if (Option == 12) meanFail_shifted->setVal(meanFail_default->getVal()+2.0);  

  RooRealVar *sigmaFail_shifted = new RooRealVar("sigmaFail_shifted","sigmaFail_shifted", 0, -5, 5);
  sigmaFail_shifted->setVal(sigmaFail_default->getVal());
  if (Option == 3) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*1.2);
  else if (Option == 4) sigmaFail_shifted->setVal(sigmaFail_default->getVal()*0.8);

  CMCBkgTemplateConvGaussianPlusExp *bkgFailModel = new CMCBkgTemplateConvGaussianPlusExp(*m_default,bkgFailTemplate_default,false,meanFail_shifted,sigmaFail_shifted, "shifted");
  bkgFailModel->t->setVal(tFail_default->getVal());
  bkgFailModel->frac->setVal(fracFail_default->getVal());

  cout << "mean : " << meanFail_default->getVal() << " - " << meanFail_shifted->getVal() << endl;
  cout << "sigma : " << sigmaFail_default->getVal() << " - " << sigmaFail_shifted->getVal() << endl;
  cout << "t: " << tFail_default->getVal() << " - " << bkgFailModel->t->getVal() << endl;
  cout << "frac: " << fracFail_default->getVal() << " - " << bkgFailModel->frac->getVal() << endl;
  
  cout << "eff: " << eff->getVal() << " : " << NsigPass.getVal() << " / " << (NsigPass.getVal() + NsigFail.getVal()) << endl;
  cout << "NbkgFail: " << NbkgFail->getVal() << endl;


  //make alternative fail model
  RooAddPdf *modelFail=0;
  RooExtendPdf *esignalFail=0, *ebackgroundFail=0;
  ebackgroundFail = new RooExtendPdf("ebackgroundFail_shifted","ebackgroundFail_shifted",*(bkgFailModel->model),*NbkgFail,"signalRange");
  modelFail       = new RooAddPdf("modelFail","Model for FAIL sample", RooArgList(*esignalFail_default,*ebackgroundFail));



  cout << "*************************************\n";
  ebackgroundFail->Print();
  cout << "*************************************\n";
  ebackgroundFail_default->Print();
  cout << "*************************************\n";
  modelFail->Print();
  cout << "*************************************\n";
  modelFail_default->Print();
  cout << "*************************************\n";

  TCanvas *cv = new TCanvas("cv","cv",800,600);

  RooPlot *mframeFail_default = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail_default->plotOn(mframeFail_default);
  modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
  modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail_default->GetYaxis()->SetTitle("");
  mframeFail_default->GetYaxis()->SetTitleOffset(1.2);
  mframeFail_default->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail_default->GetXaxis()->SetTitleOffset(1.05);
  mframeFail_default->SetTitle("");
  mframeFail_default->Draw();

  cv->SaveAs("DefaultModel.gif");

  RooPlot *mframeFail = m_default->frame(Bins(Int_t(130-60)/2));
  modelFail->plotOn(mframeFail);
  modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
  modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));
  mframeFail->GetYaxis()->SetTitle("");
  mframeFail->GetYaxis()->SetTitleOffset(1.2);
  mframeFail->GetXaxis()->SetTitle("m_{ee#gamma} [GeV/c^{2}]");
  mframeFail->GetXaxis()->SetTitleOffset(1.05);
  mframeFail->SetTitle("");
  mframeFail->Draw();
  cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


  //*************************************************************************************
  //Do Toys
  //*************************************************************************************
  for(uint t=0; t < NToys; ++t) {

    RooDataSet *pseudoData_pass    = modelPass_default->generate(*m_default, randomnumber->Poisson(npass));
    RooDataSet *pseudoData_fail  = 0;
    pseudoData_fail    = modelFail->generate(*m_default, randomnumber->Poisson(nfail));
    RooDataSet *pseudoDataCombined = new RooDataSet("pseudoDataCombined","pseudoDataCombined",RooArgList(*m_default),
                                                    RooFit::Index(sample),
                                                    RooFit::Import("Pass",*pseudoData_pass),
                                                    RooFit::Import("Fail",*pseudoData_fail));

    pseudoDataCombined->write(Form("toy%d.txt",t));

    RooFitResult *fitResult=0;
    fitResult = totalPdf->fitTo(*pseudoDataCombined,
                                RooFit::Extended(),
                                RooFit::Strategy(2),
                                //RooFit::Minos(RooArgSet(eff)),
                                RooFit::Save());

    cout << "\n\n";
    cout << "Eff Fit: " << eff->getVal() << " -" << fabs(eff->getErrorLo()) << " +" << eff->getErrorHi() << endl;

    //Fill Tree
    varEff = eff->getVal();
    varEffErrL = fabs(eff->getErrorLo());
    varEffErrH = eff->getErrorHi();
    outTree->Fill();


//   //*************************************************************************************
//   //Plot Toys
//   //*************************************************************************************
//   TCanvas *cv = new TCanvas("cv","cv",800,600);
//   char pname[50];
//   char binlabelx[100];
//   char binlabely[100];
//   char yield[50];
//   char effstr[100];
//   char nsigstr[100];
//   char nbkgstr[100];
//   char chi2str[100];

//   //
//   // Plot passing probes
//   //

//   RooPlot *mframeFail_default = m.frame(Bins(Int_t(130-60)/2));
//   modelFail_default->plotOn(mframeFail_default);
//   modelFail_default->plotOn(mframeFail_default,Components("ebackgroundFail"),LineStyle(kDashed),LineColor(kRed));
//   modelFail_default->plotOn(mframeFail_default,Components("bkgexpFail"),LineStyle(kDashed),LineColor(kGreen+2));
//   mframeFail_default->Draw();
//   cv->SaveAs("DefaultModel.gif");





//   RooPlot *mframeFail = m.frame(Bins(Int_t(130-60)/2));
//   modelFail->plotOn(mframeFail);
//   modelFail->plotOn(mframeFail,Components("ebackgroundFail_shifted"),LineStyle(kDashed),LineColor(kRed));
//   modelFail->plotOn(mframeFail,Components("bkgexpFail_shifted"),LineStyle(kDashed),LineColor(kGreen+2));

//   sprintf(yield,"%u Events",(Int_t)passTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigPass.getVal(),NsigPass.getPropagatedError(*fitResult));
//     plotPass.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   plotPass.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);
//     plotPass.AddTextBox(0.70,0.73,0.94,0.83,0,kBlack,-1,1,nsigstr);//,chi2str);

//   mframeFail->Draw();
//   cv->SaveAs(Form("ShiftedModel_%d.gif",Option));


 
//   //
//   // Plot failing probes
//   //
//   sprintf(pname,"fail%s_%i",name.Data(),ibin);
//   sprintf(yield,"%u Events",(Int_t)failTree->GetEntries());
//   sprintf(nsigstr,"N_{sig} = %.1f #pm %.1f",NsigFail.getVal(),NsigFail.getPropagatedError(*fitResult));
//   sprintf(nbkgstr,"N_{bkg} = %.1f #pm %.1f",NbkgFail.getVal(),NbkgFail.getPropagatedError(*fitResult));
//   sprintf(chi2str,"#chi^{2}/DOF = %.3f",mframePass->chiSquare(nflfail));
//   CPlot plotFail(pname,mframeFail,"Failing probes","tag-probe mass [GeV/c^{2}]","Events / 2.0 GeV/c^{2}");
//   plotFail.AddTextBox(binlabelx,0.21,0.85,0.51,0.90,0,kBlack,-1);
//   if((name.CompareTo("etapt")==0) || (name.CompareTo("etaphi")==0)) {
//     plotFail.AddTextBox(binlabely,0.21,0.80,0.51,0.85,0,kBlack,-1);    
//     plotFail.AddTextBox(yield,0.21,0.76,0.51,0.80,0,kBlack,-1);    
//   } else {
//     plotFail.AddTextBox(yield,0.21,0.81,0.51,0.85,0,kBlack,-1);
//   }
//   plotFail.AddTextBox(effstr,0.70,0.85,0.94,0.90,0,kBlack,-1);  
//   plotFail.AddTextBox(0.70,0.68,0.94,0.83,0,kBlack,-1,2,nsigstr,nbkgstr);//,chi2str);
//   plotFail.Draw(cfail,kTRUE,format);  




  } //for loop over all toys
  



  //*************************************************************************************
  //Save To File
  //*************************************************************************************
  outputfile->WriteTObject(outTree, outTree->GetName(), "WriteDelete");

}
コード例 #19
0
ファイル: test.cpp プロジェクト: ETHZ/h2gglobe
int main(){

  TFile *inFile = TFile::Open("../AnalysisScripts/MK_signal_test/CMS-HGG_sig.root");
  RooWorkspace *inWS = (RooWorkspace*)inFile->Get("cms_hgg_workspace");

  RooRealVar *mass = (RooRealVar*)inWS->var("CMS_hgg_mass");
  RooRealVar *intLumi = (RooRealVar*)inWS->var("IntLumi");
  RooRealVar *MH = new RooRealVar("MH","MH",110,150);

  InitialFit initFitRV(mass,MH,110,150);
  initFitRV.setVerbosity(0);
  initFitRV.buildSumOfGaussians("ggh_cat0",3);

  InitialFit initFitWV(mass,MH,110,150);
  initFitWV.setVerbosity(0);
  initFitWV.buildSumOfGaussians("ggh_cat0",1);

  for (int mh=110; mh<=150; mh+=5){
    RooDataSet *dataRV = (RooDataSet*)inWS->data(Form("sig_ggh_mass_m%d_rv_cat0",mh));
    initFitRV.addDataset(mh,dataRV);
    RooDataSet *dataWV = (RooDataSet*)inWS->data(Form("sig_ggh_mass_m%d_wv_cat0",mh));
    initFitWV.addDataset(mh,dataWV);
  }
  initFitRV.runFits(1);
  initFitRV.saveParamsToFileAtMH("dat/in/ggh_cat0_rv.dat",125);
  initFitRV.loadPriorConstraints("dat/in/ggh_cat0_rv.dat",0.1);
  initFitRV.runFits(1);
  initFitRV.plotFits("plots/test/rv");
  initFitWV.runFits(1);
  initFitWV.saveParamsToFileAtMH("dat/in/ggh_cat0_wv.dat",125);
  initFitWV.loadPriorConstraints("dat/in/ggh_cat0_wv.dat",0.1);
  initFitWV.runFits(1);
  initFitWV.plotFits("plots/test/wv");

  map<int,map<string,RooRealVar*> > fitParamsRV = initFitRV.getFitParams();
  map<int,map<string,RooRealVar*> > fitParamsWV = initFitWV.getFitParams();


  LinearInterp linInterpRV(MH,110,150,fitParamsRV,false);
  linInterpRV.setVerbosity(0);
  linInterpRV.interpolate(3);
  map<string,RooSpline1D*> splinesRV = linInterpRV.getSplines();
  LinearInterp linInterpWV(MH,110,150,fitParamsWV,false);
  linInterpWV.setVerbosity(0);
  linInterpWV.interpolate(1);
  map<string,RooSpline1D*> splinesWV = linInterpWV.getSplines();

  FinalModelConstruction finalModel(mass,MH,intLumi,110,150,"ggh",0,false,"dat/photonCatSyst.dat",1,false);
  finalModel.setRVsplines(splinesRV);
  finalModel.setWVsplines(splinesWV);
  map<int,RooDataSet*> datasetsRV;
  map<int,RooDataSet*> datasetsWV;
  map<int,RooDataSet*> datasetsSTD;
  for (int mh=110; mh<=150; mh+=5){
    RooDataSet *dataRV = (RooDataSet*)inWS->data(Form("sig_ggh_mass_m%d_rv_cat0",mh));
    RooDataSet *dataWV = (RooDataSet*)inWS->data(Form("sig_ggh_mass_m%d_wv_cat0",mh));
    RooDataSet *dataSTD = (RooDataSet*)inWS->data(Form("sig_ggh_mass_m%d_cat0",mh));
    datasetsRV.insert(pair<int,RooDataSet*>(mh,dataRV));
    datasetsWV.insert(pair<int,RooDataSet*>(mh,dataWV));
    datasetsSTD.insert(pair<int,RooDataSet*>(mh,dataSTD));
  }
  finalModel.setRVdatasets(datasetsRV);
  finalModel.setWVdatasets(datasetsWV);
  finalModel.setSTDdatasets(datasetsSTD);
  finalModel.buildRvWvPdf("hggpdfsmrel",3,1,false);
  finalModel.getNormalization();
  finalModel.plotPdf("plots/test/final");
  
  TFile *outFile = new TFile("tempFile.root","RECREATE");
  RooWorkspace *outWS = new RooWorkspace("wsig");
  finalModel.save(outWS);
  outFile->cd();
  outWS->Write();
  outFile->Close();
  inFile->Close();
  return 0;
}
コード例 #20
0
ファイル: results2tree.C プロジェクト: echapon/HiCharm2015
void results2tree(
      const char* workDirName, 
      bool isMC=false,
      const char* thePoiNames="RFrac2Svs1S,N_Jpsi,f_Jpsi,m_Jpsi,sigma1_Jpsi,alpha_Jpsi,n_Jpsi,sigma2_Jpsi,MassRatio,rSigma21_Jpsi,lambda1_Bkg,lambda2_Bkg,lambda3_Bkg,lambda4_Bkg,lambda5__Bkg,N_Bkg"
      ) {
   // workDirName: usual tag where to look for files in Output
   // thePoiNames: comma-separated list of parameters to store ("par1,par2,par3"). Default: all

   TFile *f = new TFile(treeFileName(workDirName,isMC),"RECREATE");
   TTree *tr = new TTree("fitresults","fit results");


   // bin edges
   float ptmin, ptmax, ymin, ymax, centmin, centmax;
   // model names
   Char_t jpsiName[128], psipName[128], bkgName[128];
   // collision system
   Char_t collSystem[8];
   // goodness of fit
   float nll, chi2, normchi2; int npar, ndof;
   // parameters to store: make it a vector
   vector<poi> thePois;
   TString thePoiNamesStr(thePoiNames);
   TString t; Int_t from = 0;
   while (thePoiNamesStr.Tokenize(t, from , ",")) {
      poi p; strcpy(p.name, t.Data());
      cout << p.name << endl;
      thePois.push_back(p);
   }

   // create tree branches
   tr->Branch("ptmin",&ptmin,"ptmin/F");
   tr->Branch("ptmax",&ptmax,"ptmax/F");
   tr->Branch("ymin",&ymin,"ymin/F");
   tr->Branch("ymax",&ymax,"ymax/F");
   tr->Branch("centmin",&centmin,"centmin/F");
   tr->Branch("centmax",&centmax,"centmax/F");
   tr->Branch("jpsiName",jpsiName,"jpsiName/C");
   tr->Branch("psipName",psipName,"psipName/C");
   tr->Branch("bkgName",bkgName,"bkgName/C");
   tr->Branch("collSystem",collSystem,"collSystem/C");
   tr->Branch("nll",&nll,"nll/F");
   tr->Branch("chi2",&chi2,"chi2/F");
   tr->Branch("normchi2",&normchi2,"normchi2/F");
   tr->Branch("npar",&npar,"npar/I");
   tr->Branch("ndof",&ndof,"ndof/I");

   for (vector<poi>::iterator it=thePois.begin(); it!=thePois.end(); it++) {
      tr->Branch(Form("%s_val",it->name),&(it->val),Form("%s_val/F",it->name));
      tr->Branch(Form("%s_err",it->name),&(it->err),Form("%s_err/F",it->name));
   }

   // list of files
   vector<TString> theFiles = fileList(workDirName,"",isMC);

   int cnt=0;
   for (vector<TString>::const_iterator it=theFiles.begin(); it!=theFiles.end(); it++) {
      cout << "Parsing file " << cnt << " / " << theFiles.size() << ": " << *it << endl;

      // parse the file name to get info
      anabin thebin = binFromFile(*it);
      ptmin = thebin.ptbin().low();
      ptmax = thebin.ptbin().high();
      ymin = thebin.rapbin().low();
      ymax = thebin.rapbin().high();
      centmin = thebin.centbin().low();
      centmax = thebin.centbin().high();
      strcpy(collSystem, (it->Index("PbPb")>0) ? "PbPb" : "PP");

      // get the model names
      from = 0;
      bool catchjpsi=false, catchpsip=false, catchbkg=false;
      while (it->Tokenize(t, from, "_")) {
         if (catchjpsi) {strcpy(jpsiName, t.Data()); catchjpsi=false;}
         if (catchpsip) {strcpy(psipName, t.Data()); catchpsip=false;}
         if (catchbkg) {strcpy(bkgName, t.Data()); catchbkg=false;}
         if (t=="Jpsi") catchjpsi=true;
         if (t=="Psi2S") catchpsip=true;
         if (t=="Bkg") catchbkg=true;
      }

      TFile *f = new TFile(*it); RooWorkspace *ws = NULL;
      if (!f) {
         cout << "Error, file " << *it << " does not exist." << endl;
      } else {
         ws = (RooWorkspace*) f->Get("workspace");
         if (!ws) {
            cout << "Error, workspace not found in " << *it << "." << endl;
         }
      }

      nll=0; chi2=0; npar=0; ndof=0;
      if (f && ws) {
         // get the model for nll and npar
         RooAbsPdf *model = pdfFromWS(ws, Form("_%s",collSystem), "pdfMASS_Tot");
         if (model) {
            RooAbsData *dat = dataFromWS(ws, Form("_%s",collSystem), "dOS_DATA");
            if (dat) {
               RooAbsReal *NLL = model->createNLL(*dat);
               if (NLL) nll = NLL->getVal();
               npar = model->getParameters(dat)->selectByAttrib("Constant",kFALSE)->getSize();

               // compute the chi2 and the ndof
               RooPlot* frame = ws->var("invMass")->frame(Bins(nBins));
               dat->plotOn(frame);
               model->plotOn(frame);
               TH1 *hdatact = dat->createHistogram("hdatact", *(ws->var("invMass")), Binning(nBins));
               RooHist *hpull = frame->pullHist(0,0, true);
               double* ypulls = hpull->GetY();
               unsigned int nFullBins = 0;
               for (int i = 0; i < nBins; i++) {
                  if (hdatact->GetBinContent(i+1) > 0.0) {
                     chi2 += ypulls[i]*ypulls[i];
                     nFullBins++;
                  }
               }
               ndof = nFullBins - npar;
               normchi2 = chi2/ndof;
            }
         }

         // get the POIs
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            RooRealVar *thevar = poiFromWS(ws, Form("_%s",collSystem), itpoi->name);
            itpoi->val = thevar ? thevar->getVal() : 0;
            itpoi->err = thevar ? thevar->getError() : 0;
         }

         f->Close();
         delete f;
      } else {
         for (vector<poi>::iterator itpoi=thePois.begin(); itpoi!=thePois.end(); itpoi++) {
            itpoi->val = 0;
            itpoi->err = 0;
         }
      }

      // fill the tree
      tr->Fill();
      cnt++;
   } // loop on the files

   f->Write();
   f->Close();
}
コード例 #21
0
void eregmerge(bool doele) {
  
  TString dirname = "/afs/cern.ch/user/b/bendavid/CMSSWhgg/CMSSW_5_3_11_patch5/src/HiggsAnalysis/GBRLikelihoodEGTools/data/"; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);    
  
  TString fnameeb;
  TString fnameee;
  if (doele) { 
    fnameeb = "wereg_ele_eb.root";
    fnameee = "wereg_ele_ee.root";
  }
  else if (!doele) {
    fnameeb = "wereg_ph_eb.root";
    fnameee = "wereg_ph_ee.root";
  }    
    
   
  TString infileeb = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/%s",fnameeb.Data());
  TString infileee = TString::Format("/afs/cern.ch/work/b/bendavid/bare/eregAug10RCalphafix/%s",fnameee.Data());
  
  TFile *fwseb = TFile::Open(infileeb); 
  TFile *fwsee = TFile::Open(infileee); 
  
  RooWorkspace *wseb = (RooWorkspace*)fwseb->Get("wereg");
  RooWorkspace *wsee = (RooWorkspace*)fwsee->Get("wereg");
  
  RooAbsPdf *sigpdfeborig = wseb->pdf("sigpdf");
  RooAbsPdf *sigpdfeeorig = wsee->pdf("sigpdf");
  
  RooAbsPdf *sigpdfeb = static_cast<RooAbsPdf*>(cloneRecursiveRename(sigpdfeborig,"EB"));
  RooAbsPdf *sigpdfee = static_cast<RooAbsPdf*>(cloneRecursiveRename(sigpdfeeorig,"EE"));
    
  RooWorkspace *wsout = new RooWorkspace("EGRegressionWorkspace");
  wsout->import(*sigpdfeb);
  wsout->import(*sigpdfee);
  
  TString outname;
  if (doele) outname = "regweights_v4_ele.root";
  else outname = "regweights_v4_ph.root";
  
  wsout->writeToFile(outname);
  
  RooArgList pdfeblist;
  RooArgSet *pdfebcomps = sigpdfeb->getComponents();
  RooArgSet *pdfebvars = sigpdfeb->getVariables();
  pdfeblist.add(*pdfebcomps);
  pdfeblist.add(*pdfebvars);
  delete pdfebcomps;
  delete pdfebvars;
  
  
  RooArgList pdfeelist;
  RooArgSet *pdfeecomps = sigpdfee->getComponents();
  RooArgSet *pdfeevars = sigpdfee->getVariables();
  pdfeelist.add(*pdfeecomps);
  pdfeelist.add(*pdfeevars);
  delete pdfeecomps;
  delete pdfeevars;  
  
  
//   RooArgList components(ws->components());
//   for (int iarg=0; iarg<components.getSize(); ++iarg) {
//     components.at(iarg)->SetName(TString::Format("%s_1",components.at(iarg)->GetName()));
//   }
  
  RooGBRFunction *funceb = static_cast<RooGBRFunction*>(pdfeblist.find("func_EB"));
  RooGBRFunction *funcee = static_cast<RooGBRFunction*>(pdfeelist.find("func_EE"));
  
//   funceb->Vars().Print("V");
//   funcee->Vars().Print("V");

  for (int ivar=0; ivar<funceb->Vars().getSize(); ++ivar) {
    printf("%i: %s, %s\n",ivar,funceb->Vars().at(ivar)->GetName(),funceb->Vars().at(ivar)->GetTitle());
  }
  
  for (int ivar=0; ivar<funcee->Vars().getSize(); ++ivar) {
    printf("%i: %s, %s\n",ivar,funcee->Vars().at(ivar)->GetName(),funcee->Vars().at(ivar)->GetTitle());
  }
  
  TString outnameforest;
  if (doele) outnameforest = "regweights_v4_forest_ele.root";
  else outnameforest = "regweights_v4_forest_ph.root";  
  
  TFile *fforest = new TFile(outnameforest,"RECREATE");
  fforest->WriteObject(funceb->Forest(),"EGRegressionForest_EB");
  fforest->WriteObject(funcee->Forest(),"EGRegressionForest_EE");
  fforest->Close();
  
}
コード例 #22
0
ファイル: runQ.C プロジェクト: lspiller/limitcode
void runQ(const char* inFileName,
	    const char* wsName = "combined",
	    const char* modelConfigName = "ModelConfig",
	    const char* dataName = "obsData",
	    const char* asimov0DataName = "asimovData_0",
	    const char* conditional0Snapshot = "conditionalGlobs_0",
	    const char* asimov1DataName = "asimovData_1",
	    const char* conditional1Snapshot = "conditionalGlobs_1",
	    const char* nominalSnapshot = "nominalGlobs",
	    string smass = "130",
	    string folder = "test")
{
  double mass;
  stringstream massStr;
  massStr << smass;
  massStr >> mass;

  bool errFast = 0;
  bool goFast = 1;
  bool remakeData = 1;
  bool doRightSided = 1;
  bool doInj = 0;
  bool doObs = 1;
  bool doMedian = 1;

  TStopwatch timer;
  timer.Start();

  TFile f(inFileName);
  RooWorkspace* ws = (RooWorkspace*)f.Get(wsName);
  if (!ws)
  {
    cout << "ERROR::Workspace: " << wsName << " doesn't exist!" << endl;
    return;
  }
  ModelConfig* mc = (ModelConfig*)ws->obj(modelConfigName);
  if (!mc)
  {
    cout << "ERROR::ModelConfig: " << modelConfigName << " doesn't exist!" << endl;
    return;
  }
  RooDataSet* data = (RooDataSet*)ws->data(dataName);
  if (!data)
  {
    cout << "ERROR::Dataset: " << dataName << " doesn't exist!" << endl;
    return;
  }





  mc->GetNuisanceParameters()->Print("v");

  RooNLLVar::SetIgnoreZeroEntries(1);
  ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2");
  ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
  ROOT::Math::MinimizerOptions::SetDefaultPrintLevel(1);
  cout << "Setting max function calls" << endl;
  //ROOT::Math::MinimizerOptions::SetDefaultMaxFunctionCalls(20000);
  RooMinimizer::SetMaxFunctionCalls(10000);

  ws->loadSnapshot("conditionalNuis_0");
  RooArgSet nuis(*mc->GetNuisanceParameters());

  RooRealVar* mu = (RooRealVar*)mc->GetParametersOfInterest()->first();



  if (string(mc->GetPdf()->ClassName()) == "RooSimultaneous" && remakeData)
  {
    RooSimultaneous* simPdf = (RooSimultaneous*)mc->GetPdf();
    double min_mu;
    data = makeData(data, simPdf, mc->GetObservables(), mu, mass, min_mu);
  }







  RooDataSet* asimovData0 = (RooDataSet*)ws->data(asimov0DataName);
  if (!asimovData0)
  {
    cout << "Asimov data doesn't exist! Please, allow me to build one for you..." << endl;
    makeAsimovData(mc, true, ws, mc->GetPdf(), data, 1);
    ws->Print();
    asimovData0 = (RooDataSet*)ws->data("asimovData_0");
  }

  RooDataSet* asimovData1 = (RooDataSet*)ws->data(asimov1DataName);
  if (!asimovData1)
  {
    cout << "Asimov data doesn't exist! Please, allow me to build one for you..." << endl;
    makeAsimovData(mc, true, ws, mc->GetPdf(), data, 0);
    ws->Print();
    asimovData1 = (RooDataSet*)ws->data("asimovData_1");
  }
  
  if (!doRightSided) mu->setRange(0, 40);
  else mu->setRange(-40, 40);






  bool old = false;
  if (old)
  {

    mu->setVal(0);
    RooArgSet poi(*mu);
    ProfileLikelihoodTestStat_modified asimov_testStat_sig(*mc->GetPdf());
    asimov_testStat_sig.SetRightSided(doRightSided);
    asimov_testStat_sig.SetNuis(&nuis);
    if (!doInj) asimov_testStat_sig.SetDoAsimov(true, 1);
    asimov_testStat_sig.SetWorkspace(ws);

    ProfileLikelihoodTestStat_modified testStat(*mc->GetPdf());
    testStat.SetRightSided(doRightSided);
    testStat.SetNuis(&nuis);
    testStat.SetWorkspace(ws);





    //RooMinimizerFcn::SetOverrideEverything(true);
    double med_sig = 0;
    double med_testStat_val = 0;

    //gRandom->SetSeed(1);
    //RooRandom::randomGenerator()->SetSeed(1);


    RooNLLVar::SetIgnoreZeroEntries(1);
    if (asimov1DataName != "" && doMedian)
    {
      mu->setVal(0);
      if (!doInj) mu->setRange(0, 2);
      ws->loadSnapshot("conditionalNuis_0");
      asimov_testStat_sig.SetLoadUncondSnapshot("conditionalNuis_1");
      if (string(conditional1Snapshot) != "") ws->loadSnapshot(conditional1Snapshot);
      med_testStat_val = 2*asimov_testStat_sig.Evaluate(*asimovData1, poi);
      if (med_testStat_val < 0 && !doInj) 
      {
	mu->setVal(0);
	med_testStat_val = 2*asimov_testStat_sig.Evaluate(*asimovData1, poi); // just try again
      }
      int sign = med_testStat_val != 0 ? med_testStat_val/fabs(med_testStat_val) : 0;
      med_sig = sign*sqrt(fabs(med_testStat_val));
      if (string(nominalSnapshot) != "") ws->loadSnapshot(nominalSnapshot);

      if (!doRightSided) mu->setRange(0, 40);
      else mu->setRange(-40, 40);
    }
    RooNLLVar::SetIgnoreZeroEntries(0);


    //gRandom->SetSeed(1);
    //RooRandom::randomGenerator()->SetSeed(1);

    //RooMinimizerFcn::SetOverrideEverything(false);

    cout << "med test stat: " << med_testStat_val << endl;
    ws->loadSnapshot("nominalGlobs");

    ws->loadSnapshot("conditionalNuis_0");
    mu->setVal(0);


    testStat.SetWorkspace(ws);
    testStat.SetLoadUncondSnapshot("ucmles");
    double obsTestStat_val = doObs ? 2*testStat.Evaluate(*data, poi) : 0;
    cout << "obs test stat: " << obsTestStat_val << endl;
//   obsTestStat_val = 2*testStat.Evaluate(*data, poi);
//   cout << "obs test stat: " << obsTestStat_val << endl;
//   obsTestStat_val = 2*testStat.Evaluate(*data, poi);
//   cout << "obs test stat: " << obsTestStat_val << endl;

    double obs_sig;
    int sign = obsTestStat_val == 0 ? 0 : obsTestStat_val / fabs(obsTestStat_val);
    if (!doRightSided && (obsTestStat_val < 0 && obsTestStat_val > -0.1 || mu->getVal() < 0.001)) obs_sig = 0; 
    else obs_sig = sign*sqrt(fabs(obsTestStat_val));
    if (obs_sig != obs_sig) //nan, do by hand
    {
      cout << "Obs test stat gave nan: try by hand" << endl;

      mu->setVal(0);
      mu->setConstant(1);
      mc->GetPdf()->fitTo(*data, Hesse(0), Minos(0), PrintLevel(-1), Constrain(*mc->GetNuisanceParameters()));
      mu->setConstant(0);

      double L_0 = mc->GetPdf()->getVal();

      //mu->setVal(0);
      //mu->setConstant(1);
      mc->GetPdf()->fitTo(*data, Hesse(0), Minos(0), PrintLevel(-1), Constrain(*mc->GetNuisanceParameters()));
      //mu->setConstant(0);
      double L_muhat = mc->GetPdf()->getVal();

      cout << "L_0: " << L_0 << ", L_muhat: " << L_muhat << endl;
      obs_sig = sqrt(-2*TMath::Log(L_0/L_muhat));

//still nan
      if (obs_sig != obs_sig && fabs(L_0 - L_muhat) < 0.000001) obs_sig = 0;
    }
    cout << "obs: " << obs_sig << endl;

    cout << "Observed significance: " << obs_sig << endl;
    if (med_sig)
    {
      cout << "Median test stat val: " << med_testStat_val << endl;
      cout << "Median significance:   " << med_sig << endl;
    }


    f.Close();

    stringstream fileName;
    fileName << "root_files/" << folder << "/" << mass << ".root";
    system(("mkdir -vp root_files/" + folder).c_str());
    TFile f2(fileName.str().c_str(),"recreate");

//   stringstream fileName;
//   fileName << "results_sig/" << mass << ".root";
//   system("mkdir results_sig");
//   TFile f(fileName.str().c_str(),"recreate");

    TH1D* h_hypo = new TH1D("hypo","hypo",2,0,2);
    h_hypo->SetBinContent(1, obs_sig);
    h_hypo->SetBinContent(2, med_sig);


    f2.Write();
    f2.Close();
    //mc->GetPdf()->fitTo(*data, PrintLevel(0));

    timer.Stop();
    timer.Print();
  }
  else
  {

    RooAbsPdf* pdf = mc->GetPdf();



    RooArgSet nuis_tmp1 = *mc->GetNuisanceParameters();
    RooNLLVar* asimov_nll0 = (RooNLLVar*)pdf->createNLL(*asimovData0, Constrain(nuis_tmp1));

    RooArgSet nuis_tmp2 = *mc->GetNuisanceParameters();
    RooNLLVar* asimov_nll1 = (RooNLLVar*)pdf->createNLL(*asimovData1, Constrain(nuis_tmp2));

    RooArgSet nuis_tmp3 = *mc->GetNuisanceParameters();
    RooNLLVar* obs_nll = (RooNLLVar*)pdf->createNLL(*data, Constrain(nuis_tmp3));

    
//do asimov

    int status;




//get sigma_b

    ws->loadSnapshot(conditional0Snapshot);
    status = ws->loadSnapshot("conditionalNuis_0");
    if (status != 0 && goFast) errFast = 1;

    mu->setVal(0);
    mu->setConstant(1);
    status = goFast ? 0 : minimize(asimov_nll0, ws);
    if (status < 0) 
    {
      cout << "Retrying" << endl;
      //ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll0, ws);
      if (status >= 0) cout << "Success!" << endl;
    }
    double asimov0_nll0 = asimov_nll0->getVal();

    mu->setVal(1);
    ws->loadSnapshot("conditionalNuis_1");
    status = minimize(asimov_nll0, ws);
    if (status < 0) 
    {
      cout << "Retrying" << endl;
      //ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll0, ws);
      if (status >= 0) cout << "Success!" << endl;
    }

    double asimov0_nll1 = asimov_nll0->getVal();
    double asimov0_q = 2*(asimov0_nll1 - asimov0_nll0);
    double sigma_b = sqrt(1./asimov0_q);

    ws->loadSnapshot(nominalSnapshot);





//get sigma_sb

    ws->loadSnapshot(conditional1Snapshot);
    ws->loadSnapshot("conditionalNuis_0");

    mu->setVal(0);
    mu->setConstant(1);
    status = minimize(asimov_nll1, ws);
    if (status < 0) 
    {
      cout << "Retrying" << endl;
      //ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll1, ws);
      if (status >= 0) cout << "Success!" << endl;
    }
    double asimov1_nll0 = asimov_nll1->getVal();

    mu->setVal(1);
    status = ws->loadSnapshot("conditionalNuis_1");
    if (status != 0 && goFast) errFast = 1;
    status = goFast ? 0 : minimize(asimov_nll1, ws);
    if (status < 0) 
    {
      cout << "Retrying" << endl;
      //ws->loadSnapshot("conditionalNuis_0");
      status = minimize(asimov_nll1, ws);
      if (status >= 0) cout << "Success!" << endl;
    }

    double asimov1_nll1 = asimov_nll1->getVal();
    double asimov1_q = 2*(asimov1_nll1 - asimov1_nll0);
    double sigma_sb = sqrt(-1./asimov1_q);

    ws->loadSnapshot(nominalSnapshot);



//do obs

    mu->setVal(0);
    status = ws->loadSnapshot("conditionalNuis_0");
    if (status != 0 && goFast) errFast = 1;
    mu->setConstant(1);
    status = goFast ? 0 : minimize(obs_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(obs_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }
    double obs_nll0 = obs_nll->getVal();



    status = ws->loadSnapshot("conditionalNuis_1");
    if (status != 0 && goFast) errFast = 1;
    mu->setVal(1);
    status = goFast ? 0 : minimize(obs_nll, ws);
    if (status < 0) 
    {
      cout << "Retrying with conditional snapshot at mu=1" << endl;
      ws->loadSnapshot("conditionalNuis_0");
      status = minimize(obs_nll, ws);
      if (status >= 0) cout << "Success!" << endl;
    }

    double obs_nll1 = obs_nll->getVal();
    double obs_q = 2*(obs_nll1 - obs_nll0);



    double Zobs = (1./sigma_b/sigma_b - obs_q) / (2./sigma_b);
    double Zexp = (1./sigma_b/sigma_b - asimov1_q) / (2./sigma_b);

    double pb_obs = 1-ROOT::Math::gaussian_cdf(Zobs);
    double pb_exp = 1-ROOT::Math::gaussian_cdf(Zexp);


    cout << "asimov0_q = " << asimov0_q << endl;
    cout << "asimov1_q = " << asimov1_q << endl;
    cout << "obs_q     = " << obs_q << endl;
    cout << "sigma_b   = " << sigma_b << endl;
    cout << "sigma_sb  = " << sigma_sb << endl;
    cout << "Z obs     = " << Zobs << endl;
    cout << "Z exp     = " << Zexp << endl;



    f.Close();

    stringstream fileName;
    fileName << "root_files/" << folder << "/" << mass << ".root";
    system(("mkdir -vp root_files/" + folder).c_str());
    TFile f2(fileName.str().c_str(),"recreate");

    TH1D* h_hypo = new TH1D("hypo_tev","hypo_tev",2,0,2);
    h_hypo->SetBinContent(1, pb_obs);
    h_hypo->SetBinContent(2, pb_exp);


    f2.Write();
    f2.Close();

    stringstream fileName3;
    fileName3 << "root_files/" << folder << "_llr/" << mass << ".root";
    system(("mkdir -vp root_files/" + folder + "_llr").c_str());
    TFile f3(fileName3.str().c_str(),"recreate");

    TH1D* h_hypo3 = new TH1D("hypo_llr","hypo_llr",7,0,7);
    h_hypo3->SetBinContent(1, -obs_q);
    h_hypo3->SetBinContent(2, -asimov1_q);
    h_hypo3->SetBinContent(3, -asimov0_q);
    h_hypo3->SetBinContent(4, -asimov0_q-2*2/sigma_b);
    h_hypo3->SetBinContent(5, -asimov0_q-1*2/sigma_b);
    h_hypo3->SetBinContent(6, -asimov0_q+1*2/sigma_b);
    h_hypo3->SetBinContent(7, -asimov0_q+2*2/sigma_b);


    f3.Write();
    f3.Close();

    timer.Stop();
    timer.Print();




  }
}
コード例 #23
0
void hggfitmceerr(double nommass=123., double tgtr=1., int ijob=0) {
    
  //gSystem->cd("/scratch/bendavid/root/bare/fitplotsJun10test/");
  
  int seed = 65539+ijob+1; 
  
  TString dirname = "/scratch/bendavid/root/bare/hggfiteerrtestall_large2/";
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);
  
  
  //nommass=150.;
 // gSystem->cd("/scratch/bendavid/root/bare/fitplotsJun8_150_2x/");
  
  gRandom->SetSeed(seed);
  RooRandom::randomGenerator()->SetSeed(seed);    
  
//   TFile *fin = TFile::Open("/home/mingyang/cms/hist_approval/hgg-2013Moriond/merged/hgg-2013Moriond_s12-h150gg-gf-v7a_noskim.root");
//   TDirectory *hdir = (TDirectory*)fin->FindObjectAny("PhotonTreeWriterPresel");
//   TTree *htree = (TTree*)hdir->Get("hPhotonTree");

//   TFile *fdin = TFile::Open("/home/mingyang/cms/hist/hgg-2013Moriond/merged/hgg-2013Moriond_r12_ABCD.root");
//   TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPresel");
//   TTree *dtree = (TTree*)ddir->Get("hPhotonTree");  
  
  //TCut selcut = "(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)";
  TCut selcut = "(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)";
  //TCut selweight = "xsecweight(procidx)*puweight(numPU,procidx)";
  TCut selweight = "xsecweight(procidx)*mcweight*kfact(procidx,ph1.ispromptgen,ph2.ispromptgen)";
  
  TCut sigFcut = "(procidx==0 || procidx==3)";
  TCut sigVcut = "(procidx==1 || procidx==2)";
  
  TCut bkgPPcut = "(procidx==4)";
  TCut bkgPFcut = "(procidx==5 || procidx==6)";
  TCut bkgFFcut = "(procidx==7 || procidx==8)";
  
  
  
  TCut bkgcut = "(procidx>3)";
  TCut bkgcutnoq = "(procidx>3 && procidx<7)";
  
  TCut prescalenone = "(1==1)";
  TCut evenevents = "(evt%2==0)";
  TCut oddevents =  "(evt%2==1)";
  TCut prescale10 = "(evt%10==0)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale50 = "(evt%50==0)";
  TCut prescale100 = "(evt%100==0)";
  
  
  
  TCut fcut = prescale50;  
  
  
  float xsecs[50];

  
  //TCut selcutsingle = "ph.pt>25. && ph.isbarrel && ph.ispromptgen";
  //TCut selcutsingle = "ph.pt>25.&& ph.ispromptgen";
  TCut selcutsingle = "ph.genpt>16.&& ph.ispromptgen";
  TCut selweightsingle = "xsecweight(procidx)";
  
  
//   TChain *tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonMvaMod/JetPub/JetCorrectionMod/SeparatePileUpMod/ElectronIDMod/MuonIDMod/PhotonPairSelectorPresel/PhotonTreeWriterPresel/hPhotonTreeSingle");
//   tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV/merged/hgg-2013Final8TeV_s12-diphoj-v7n_noskim.root");

  TChain *tree = new TChain("RunLumiSelectionMod/MCProcessSelectionMod/HLTModP/GoodPVFilterMod/PhotonMvaMod/PhotonIDModPresel/PhotonTreeWriterSingle/hPhotonTreeSingle");
  tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV_reg_trans/merged/hgg-2013Final8TeV_reg_trans_s12-pj20_40-2em-v7n_noskim.root");
  tree->Add("/home/mingyang/cms/hist/hgg-2013Final8TeV_reg_trans/merged/hgg-2013Final8TeV_reg_trans_s12-pj40-2em-v7n_noskim.root");
  
  xsecs[0] = 0.001835*81930.0;
  xsecs[1] = 0.05387*8884.0;
  initweights(tree,xsecs,1.);
  
  double weightscale = xsecweights[1];
  xsecweights[0] /= weightscale;
  xsecweights[1] /= weightscale;  
 
  
  
  tree->SetCacheSize(64*1024*1024);
  
  

  RooRealVar energy("energy","ph.e",0);
  RooRealVar sceta("sceta","ph.sceta",0.);
  RooRealVar idmva("idmva","ph.idmva",0.,-1.,1.);  
  RooRealVar eerr("eerr","(ph.isbarrel + 0.5*!ph.isbarrel)*ph.eerr/ph.e",0.);
  RooRealVar evt("evt","evt",0.);
  
  
  RooArgList vars;
  vars.add(energy);
  vars.add(sceta);
  //vars.add(idmva);
  
  
  RooArgList condvars(vars);
  
  vars.add(eerr);  
  
  RooArgList condvarsid(vars);
  
  vars.add(idmva);
  vars.add(evt);
  

//   RooPowerLaw("testpow","",pt1,pt2);
//   return;
  

//    new TCanvas;
//    tree->Draw("mass>>htmpall(80,100.,180.)",bkgcut*selcut*selweight,"HIST");
// 
//    new TCanvas;
//    tree->Draw("mass>>htmpallid(80,100.,180.)",idcut*bkgcut*selcut*selweight,"HIST");   
//    
//    new TCanvas;
//    tree->Draw("mass>>htmp(80,100.,180.)",bkgcutnoq*selcut*selweight,"HIST");   
// //   
//    return;
    
  
  
  //RooRealVar weightvar("weightvar","(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2 && evt%100!=0)",1.);
  RooRealVar weightvar("weightvar","",1.);
  //RooRealVar weightvar("weightvar","(ph1.pt > (mass/3.0) && ph2.pt > (mass/4.0) && mass>100. && mass<180. && ph1.idmva>-0.2 && ph2.idmva>-0.2)",1.);
  
  weightvar.SetTitle(selcutsingle*selweightsingle);
  RooDataSet *hdataSingle = RooTreeConvert::CreateDataSet("hdataSingle",tree,vars,weightvar);    
  
  int ngauseerr = 4;
  //int nparmseerr = 3*ngauseerr + 2;
  //int nparmseerr = 3*ngauseerr + 2;
  int nparmseerr = 5*ngauseerr;
  
  RooArgList tgtseerr;
  RooGBRFunction funceerr("funceerr","",condvars,nparmseerr);
 
  int iparmeerr = 0;  
  
  
  RooArgList eerrgauspdfs;
  RooArgList eerrgauscoeffs;
  
  double stepeerr = 0.07/double(std::max(1,ngauseerr-1));
  
//    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_eerr_%i",0),"",0.007+stepeerr*0);
//    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_eerr_%i",0),"",0.01);
// //   //RooRealVar *gsigmaRvar = new RooRealVar(TString::Format("gsigmaRvar_eerr_%i",0),"",0.02);
// //   
// //   //if (0==0) gmeanvar->setVal(0.007);
// //   
//    gmeanvar->setConstant(false);
//    gsigmavar->setConstant(false);
// //   //gsigmaRvar->setConstant(false);
// //   
// //   
//    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_eerr_%i",0),"",funceerr,iparmeerr++,*gmeanvar);
//    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_eerr_%i",0),"",funceerr,iparmeerr++,*gsigmavar);
// //   //RooGBRTarget *gsigmaR = new RooGBRTarget(TString::Format("gsigmaR_eerr_%i",0),"",funceerr,iparmeerr++,*gsigmaRvar);
// // 
//    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_eerr_%i",0),"",*gmean,0.,0.5);   
//    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_eerr_%i",0),"",*gsigma,1e-7,0.5);
//   //RooRealConstraint *gsigmaRlim = new RooRealConstraint(TString::Format("gsigmaRlim_eerr_%i",0),"",*gsigmaR,1e-7,0.2);  
//   
//   tgtseerr.add(*gmean);
//   tgtseerr.add(*gsigma);
  
  for (int igaus=0; igaus<ngauseerr; ++igaus) {
    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_eerr_%i",igaus),"",0.007+stepeerr*igaus);
    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_eerr_%i",igaus),"",0.01);
    RooRealVar *galphavar = new RooRealVar(TString::Format("galphavar_eerr_%i",igaus),"",1.0);
    RooRealVar *gnvar = new RooRealVar(TString::Format("gnvar_eerr_%i",igaus),"",2.);    
    RooRealVar *gfracvar = new RooRealVar(TString::Format("gfracvar_eerr_%i",igaus),"",1.0);  
    
    //if (igaus==0) gmeanvar->setVal(0.007);
    
    gmeanvar->setConstant(false);
    gsigmavar->setConstant(false);
    galphavar->setConstant(false);
    gnvar->setConstant(false);    
    gfracvar->setConstant(false);
    
    
    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_eerr_%i",igaus),"",funceerr,iparmeerr++,*gmeanvar);
    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_eerr_%i",igaus),"",funceerr,iparmeerr++,*gsigmavar);
    RooGBRTarget *galpha = new RooGBRTarget(TString::Format("galpha_eerr_%i",igaus),"",funceerr,iparmeerr++,*galphavar);
    RooGBRTarget *gn = new RooGBRTarget(TString::Format("gn_eerr_%i",igaus),"",funceerr,iparmeerr++,*gnvar);    
    RooGBRTarget *gfrac = new RooGBRTarget(TString::Format("gfrac_eerr_%i",igaus),"",funceerr,iparmeerr++,*gfracvar);

    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_eerr_%i",igaus),"",*gmean,0.,0.5);   
    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_eerr_%i",igaus),"",*gsigma,1e-5,0.1);
    RooRealConstraint *galphalim = new RooRealConstraint(TString::Format("galphalim_eerr_%i",igaus),"",*galpha,0.05,8.);
    RooRealConstraint *gnlim = new RooRealConstraint(TString::Format("gnlim_eerr_%i",igaus),"",*gn,1.01,5000.);
    //RooRealConstraint *gfraclim = new RooRealConstraint(TString::Format("gfraclim_eerr_%i",igaus),"",*gfrac,0.,1.);
    RooAbsReal *gfraclim = new RooProduct(TString::Format("gfraclim_eerr_%i",igaus),"",RooArgList(*gfrac,*gfrac));
 
    
    if (igaus==0) {
      gfraclim = new RooConstVar(TString::Format("gfraclimconst_eerr_%i",igaus),"",1.);
    }
    else {
      tgtseerr.add(*gfrac);   
    }
    
    //RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim);
    //RooBifurGauss *gpdf = new RooBifurGauss(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim,*galphalim);
    
    
    if (igaus==0) {
      RooRevCBFast *gpdf = new RooRevCBFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim,*galphalim, *gnlim);
    
      tgtseerr.add(*gmean);
      tgtseerr.add(*gsigma);
      tgtseerr.add(*galpha);
      tgtseerr.add(*gn);
      
      eerrgauspdfs.add(*gpdf);      
    
    }
    else {
      RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_eerr_%i",igaus),"",eerr,*gmeanlim,*gsigmalim);
    
      tgtseerr.add(*gmean);
      tgtseerr.add(*gsigma);
      
      eerrgauspdfs.add(*gpdf);

    }      
      
    
    eerrgauscoeffs.add(*gfraclim);    
    
  }
  RooCondAddPdf eerrpdf("eerrpdf","",eerrgauspdfs,eerrgauscoeffs);  
  
  
  RooAbsPdf *pdf0 = static_cast<RooAbsPdf*>(eerrgauspdfs.at(0));
  
  
  int ngaus = 6;
  int nparms = 4*ngaus;
  
  RooArgList tgtsid;
  RooGBRFunction funcid("funcid","",condvarsid,nparms);  
  
  RooArgList gauspdfs;
  RooArgList gauscoeffs;
  
  double step = 0.5/double(std::max(1,ngaus-1));
  
  int iparm = 0;
  for (int igaus=0; igaus<ngaus; ++igaus) {
    RooRealVar *gmeanvar = new RooRealVar(TString::Format("gmeanvar_%i",igaus),"",-0.2+step*igaus);
    RooRealVar *gsigmavar = new RooRealVar(TString::Format("gsigmavar_%i",igaus),"",0.1);
    RooRealVar *gsigmaRvar = new RooRealVar(TString::Format("gsigmaRvar_%i",igaus),"",0.1);
    RooRealVar *gfracvar = new RooRealVar(TString::Format("gfracvar_%i",igaus),"",1.0);  
    
    gmeanvar->setConstant(false);
    gsigmavar->setConstant(false);
    gsigmaRvar->setConstant(false);
    gfracvar->setConstant(false);
    
    RooGBRTarget *gmean = new RooGBRTarget(TString::Format("gmean_%i",igaus),"",funcid,iparm++,*gmeanvar);
    RooGBRTarget *gsigma = new RooGBRTarget(TString::Format("gsigma_%i",igaus),"",funcid,iparm++,*gsigmavar);
    RooGBRTarget *gsigmaR = new RooGBRTarget(TString::Format("gsigmaR_%i",igaus),"",funcid,iparm++,*gsigmaRvar);
    RooGBRTarget *gfrac = new RooGBRTarget(TString::Format("gfrac_%i",igaus),"",funcid,iparm++,*gfracvar);

    RooRealConstraint *gmeanlim = new RooRealConstraint(TString::Format("gmeanlim_%i",igaus),"",*gmean,-1.,1.);   
    RooRealConstraint *gsigmalim = new RooRealConstraint(TString::Format("gsigmalim_%i",igaus),"",*gsigma,1e-4,2.);
    RooRealConstraint *gsigmaRlim = new RooRealConstraint(TString::Format("gsigmaRlim_%i",igaus),"",*gsigmaR,1e-4,2.);
    //RooRealConstraint *gfraclim = new RooRealConstraint(TString::Format("gfraclim_%i",igaus),"",*gfrac,0.,1.);
    
    RooAbsReal *gfraclim = new RooProduct(TString::Format("gfraclim_%i",igaus),"",RooArgList(*gfrac,*gfrac));
 
    
    if (igaus==0) {
      gfraclim = new RooConstVar(TString::Format("gfraclimconst_%i",igaus),"",1.);
    }
    else {
      tgtsid.add(*gfrac);   
    }    
    
    
    RooGaussianFast *gpdf = new RooGaussianFast(TString::Format("gdf_%i",igaus),"",idmva,*gmeanlim,*gsigmalim);
    //RooBifurGauss *gpdf = new RooBifurGauss(TString::Format("gdf_%i",igaus),"",idmva,*gmeanlim,*gsigmalim,*gsigmaRlim);
    
    gauspdfs.add(*gpdf);
    gauscoeffs.add(*gfraclim);
    
    tgtsid.add(*gmean);
    tgtsid.add(*gsigma);
    //tgtsid.add(*gsigmaR);
    //tgtsid.add(*gfrac);    
  }
  RooCondAddPdf idpdf("idpdf","",gauspdfs,gauscoeffs);
  
  RooConstVar etermconst("etermconst","",0.);  
  RooAbsReal &eterm = etermconst;
  RooRealVar dummy("dummy","",1.0);
   

  std::vector<RooAbsData*> vdata;
  vdata.push_back(hdataSingle);

  
  std::vector<RooAbsReal*> vpdf;
  vpdf.push_back(&eerrpdf);
  //vpdf.push_back(pdf0);

  std::vector<RooAbsReal*> vpdfid;
  vpdfid.push_back(&idpdf);  
 
  
  RooHybridBDTAutoPdf bdtpdf("bdtpdf","",funceerr,tgtseerr,eterm,dummy,vdata,vpdf);
  bdtpdf.SetPrescaleInit(100);
  bdtpdf.SetMinCutSignificance(5.0);
  bdtpdf.SetShrinkage(0.1);
  bdtpdf.SetMinWeightTotal(200.);
  bdtpdf.SetMaxNodes(200);
  bdtpdf.TrainForest(1e6);   
  
  RooHybridBDTAutoPdf bdtpdfid("bdtpdfid","",funcid,tgtsid,eterm,dummy,vdata,vpdfid);
  bdtpdfid.SetPrescaleInit(100);
  bdtpdfid.SetMinCutSignificance(5.0);
  bdtpdfid.SetShrinkage(0.1);
  bdtpdfid.SetMinWeightTotal(200.);
  bdtpdfid.SetMaxNodes(200);
  bdtpdfid.TrainForest(1e6);    
  
  
  RooAbsReal *finalcdferr = eerrpdf.createCDF(eerr);
  
  RooFormulaVar transerr("transerr","","sqrt(2.)*TMath::ErfInverse(2.*@0-1.)",*finalcdferr);
  


  RooAbsReal *finalcdfid = idpdf.createCDF(idmva);
  
  RooFormulaVar transid("transid","","sqrt(2.)*TMath::ErfInverse(2.*@0-1.)",*finalcdfid);
  
  
  RooWorkspace *wsout = new RooWorkspace("wsfiteerr");
  wsout->import(*hdataSingle);
  
  wsout->import(eerrpdf,RecycleConflictNodes());
  wsout->import(idpdf,RecycleConflictNodes());
//   wsout->import(transerr,RecycleConflictNodes());
//   wsout->import(transid,RecycleConflictNodes());
  
  wsout->defineSet("datavars",vars,true);
    
  wsout->writeToFile("hggfiteerr.root");  
  
  
    
  
  RooRealVar *cdfidvar = (RooRealVar*)hdataSingle->addColumn(*finalcdfid);    
  RooRealVar *transidvar = (RooRealVar*)hdataSingle->addColumn(transid);
    
  RooGaussianFast unormpdfid("unormpdfid","",*transidvar,RooConst(0.),RooConst(1.));    

  RooRealVar *cdferrvar = (RooRealVar*)hdataSingle->addColumn(*finalcdferr);    
  RooRealVar *transerrvar = (RooRealVar*)hdataSingle->addColumn(transerr);
    
  RooGaussianFast unormpdferr("unormpdferr","",*transerrvar,RooConst(0.),RooConst(1.));    
  
  
  //RooDataSet *testdata = (RooDataSet*)hdataSingle->reduce("abs(sceta)>1.3 && abs(sceta)<1.4");
  RooDataSet *testdata = hdataSingle;
    
  
  new TCanvas;
  RooPlot *eerrplot = eerr.frame(0.,0.1,200);
  testdata->plotOn(eerrplot);
  eerrpdf.plotOn(eerrplot,ProjWData(*testdata));
  eerrplot->Draw();    
  

  
  new TCanvas;
  RooPlot *transplot = transerrvar->frame(-5.,5.,100);
  hdataSingle->plotOn(transplot);
  unormpdferr.plotOn(transplot);
  transplot->Draw();
  //return;
  
  new TCanvas;
  RooPlot *cdfploterr = cdferrvar->frame(0.,1.,100);
  hdataSingle->plotOn(cdfploterr);
  //unormpdf.plotOn(transplot);
  cdfploterr->Draw();
  //return;    
  
  
  
  new TCanvas;
  RooPlot *idplot = idmva.frame(-1.,1.,200);
  testdata->plotOn(idplot);
  idpdf.plotOn(idplot,ProjWData(*testdata));
  idplot->Draw();  
  

  
  new TCanvas;
  RooPlot *transplotid = transidvar->frame(-5.,5.,100);
  testdata->plotOn(transplotid);
  unormpdfid.plotOn(transplotid);
  transplotid->Draw();
  //return;
  
  new TCanvas;
  RooPlot *cdfplotid = cdfidvar->frame(0.,1.,100);
  testdata->plotOn(cdfplotid);
  //unormpdf.plotOn(transplot);
  cdfplotid->Draw();
  //return;        
  

  TH1 *herrid = testdata->createHistogram("herrid",eerr,Binning(30,0.,0.1), YVar(idmva,Binning(30,-0.5,0.6)));
  TH1 *herre = testdata->createHistogram("herre",energy,Binning(30,0.,200.), YVar(eerr,Binning(30,0.,0.1)));
  TH1 *hideta = testdata->createHistogram("hideta",sceta,Binning(40,-2.5,2.5), YVar(idmva,Binning(30,-0.5,0.6)));

  TH1 *herridtrans = testdata->createHistogram("herridtrans",*transerrvar,Binning(30,-5.,5.), YVar(*transidvar,Binning(30,-5.,5.)));
  TH1 *herrtranse = testdata->createHistogram("herrtranse",energy,Binning(30,0.,200.), YVar(*transerrvar,Binning(30,-5.,5.)));
  TH1 *hidtranseta = testdata->createHistogram("hidtranseta",sceta,Binning(40,-2.5,2.5), YVar(*transidvar,Binning(30,-5.,5.)));  

  new TCanvas;
  herrid->Draw("COLZ");

  new TCanvas;
  herre->Draw("COLZ");
  
  new TCanvas;
  hideta->Draw("COLZ");    
  
  
  new TCanvas;
  herridtrans->Draw("COLZ");

  new TCanvas;
  herrtranse->Draw("COLZ");
  
  new TCanvas;
  hidtranseta->Draw("COLZ");  
  

  
//   new TCanvas;
//   RooRealVar *meanvar = (RooRealVar*)hdataSingle->addColumn(eerrmeanlim);
//   RooPlot *meanplot = meanvar->frame(0.,0.1,200);
//   hdataSingle->plotOn(meanplot);
//   meanplot->Draw();
  

  return;
  
}
コード例 #24
0
ファイル: runBATCalculator.C プロジェクト: Kaoschuks/bat
void runBATCalculator()
{
    // Definiton of a RooWorkspace containing the statistics model. Later the
    // information for BATCalculator is retrieved from the workspace. This is
    // certainly a bit of overhead but better from an educative point of view.
    cout << "preparing the RooWorkspace object" << endl;

    RooWorkspace* myWS = new RooWorkspace("myWS", true);

    // combined prior for signal contribution
    myWS->factory("Product::signal({sigma_s[0,20],L[5,15],epsilon[0,1]})");
    myWS->factory("N_bkg[0,3]");
    // define prior functions
    // uniform prior for signal crosssection
    myWS->factory("Uniform::prior_sigma_s(sigma_s)");
    // (truncated) prior for efficiency
    myWS->factory("Gaussian::prior_epsilon(epsilon,0.51,0.0765)");
    // (truncated) Gaussian prior for luminosity
    myWS->factory("Gaussian::prior_L(L,10,1)");
    // (truncated) Gaussian prior for bkg crosssection
    myWS->factory("Gaussian::prior_N_bkg(N_bkg,0.52,0.156)");

    // Poisson distribution with mean signal+bkg
    myWS->factory("Poisson::model(n[0,300],sum(signal,N_bkg))");

    // define the global prior function
    myWS->factory("PROD::prior(prior_sigma_s,prior_epsilon,prior_L,prior_N_bkg)");

    // Definition of observables and parameters of interest
    myWS->defineSet("obsSet", "n");
    myWS->defineSet("poiSet", "sigma_s");
    myWS->defineSet("nuisanceSet", "N_bkg,L,epsilon");

    // ->model complete (Additional information can be found in the
    // RooStats manual)

    //  feel free to vary the parameters, but don't forget to choose reasonable ranges for the
    // variables. Currently the Bayesian methods will often not work well if the variable ranges
    // are either too short (for obvious reasons) or too large (for technical reasons).

    // A ModelConfig object is used to associate parts of your workspace with their statistical
    // meaning (it is also possible to initialize BATCalculator directly with elements from the
    // workspace but if you are sharing your workspace with others or if you want to use several
    // different methods the use of ModelConfig will most often turn out to be the better choice.)

    // setup the ModelConfig object
    cout << "preparing the ModelConfig object" << endl;

    ModelConfig modelconfig("modelconfig", "ModelConfig for this example");
    modelconfig.SetWorkspace(*myWS);

    modelconfig.SetPdf(*(myWS->pdf("model")));
    modelconfig.SetParametersOfInterest(*(myWS->set("poiSet")));
    modelconfig.SetPriorPdf(*(myWS->pdf("prior")));
    modelconfig.SetNuisanceParameters(*(myWS->set("nuisanceSet")));
    modelconfig.SetObservables(*(myWS->set("obsSet")));


    // use BATCalculator to the derive credibility intervals as a function of the observed number of
    // events in the hypothetical experiment

    // define vector with tested numbers of events
    TVectorD obsEvents;
    // define vectors which will be filled with the lower and upper limits for each tested number
    // of observed events
    TVectorD BATul;
    TVectorD BATll;

    // fix upper limit of tested observed number of events
    int obslimit = 10;

    obsEvents.ResizeTo(obslimit);
    BATul.ResizeTo(obslimit);
    BATll.ResizeTo(obslimit);


    cout << "starting the calculation of Bayesian credibility intervals with BATCalculator" << endl;
    // loop over observed number of events in the hypothetical experiment
    for (int obs = 1; obs <= obslimit; obs++) {

        obsEvents[obs - 1] = (static_cast<double>(obs));

        // prepare data input for the the observed number of events
        // adjust number of observed events in the workspace. This is communicated to ModelConfig!
        myWS->var("n")->setVal(obs);
        // create data
        RooDataSet data("data", "", *(modelconfig.GetObservables()));
        data.add( *(modelconfig.GetObservables()));

        // prepare BATCalulator
        BATCalculator batcalc(data, modelconfig);

        // give the BATCalculator a unique name (always a good idea in ROOT)
        TString namestring = "mybatc_";
        namestring += obs;
        batcalc.SetName(namestring);

        // fix amount of posterior probability in the calculated interval.
        // the name confidence level is incorrect here
        batcalc.SetConfidenceLevel(0.90);

        // fix length of the Markov chain. (in general: the longer the Markov chain the more
        // precise will be the results)
        batcalc.SetnMCMC(20000);

        // retrieve SimpleInterval object containing the information about the interval (this
        // triggers the actual calculations)
        SimpleInterval* interval = batcalc.GetInterval1D("sigma_s");

        std::cout << "BATCalculator: 90% credibility interval: [ " << interval->LowerLimit() << " - " << interval->UpperLimit() << " ] or 95% credibility upper limit\n";

        // add the interval borders for the current number of observed events to the vectors
        // containing the lower and upper limits
        BATll[obs - 1] = interval->LowerLimit();
        BATul[obs - 1] = interval->UpperLimit();

        // clean up for next loop element
        batcalc.CleanCalculatorForNewData();
        delete interval;
    }
    cout << "all limits calculated" << endl;

    // summarize the results in a plot

    TGraph* grBATll = new TGraph(obsEvents, BATll);
    grBATll->SetLineColor(kGreen);
    grBATll->SetLineWidth(200);
    grBATll->SetFillStyle(3001);
    grBATll->SetFillColor(kGreen);

    TGraph* grBATul = new TGraph(obsEvents, BATul);
    grBATul->SetLineColor(kGreen);
    grBATul->SetLineWidth(-200);
    grBATul->SetFillStyle(3001);
    grBATul->SetFillColor(kGreen);

    // create and draw multigraph
    TMultiGraph* mg = new TMultiGraph("BayesianLimitsBATCalculator", "BayesianLimitsBATCalculator");
    mg->SetTitle("example of Bayesian credibility intervals derived with BATCAlculator ");

    mg->Add(grBATll);
    mg->Add(grBATul);

    mg->Draw("AC");

    mg->GetXaxis()->SetTitle ("# observed events");
    mg->GetYaxis()->SetTitle("limits on signal S (size of test: 0.1)");

    mg->Draw("AC");
}
コード例 #25
0
void FitScenariosTwoD_RequiredPerformance_card(const string inputfilePho = "/afs/cern.ch/work/d/daan/public/releases/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/HHToBBGG_SignalBkgd_AfterCuts_diphotonMass.root", const string inputfileBjet = "/afs/cern.ch/work/d/daan/public/releases/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/HHToBBGG_SignalBkgd_AfterCuts_dibjetMass.root", const string inputfileTwoD = "/afs/cern.ch/work/d/daan/public/releases/CMSSW_5_3_9_patch3/src/CMSAna/HHToBBGG/data/HHToBBGG_SignalBkgd_AfterCuts_twoDMass.root", const string scanOption = "lum", Int_t NToys = 500, Int_t s = 5) {
	
  

  TRandom3 *randomNumber = new TRandom3(1200);
  TFile *file = new TFile(Form("HHToBBGGWorkspace_%s_%d.root",scanOption.c_str(),s),"RECREATE");
  RooWorkspace* ws = new RooWorkspace("CMSAna/HHToBBGG/fits/Workspace");
  AddModels(ws, inputfilePho, inputfileBjet, inputfileTwoD, scanOption, s);

  //Import variables from workspace
  RooAbsPdf *model2Dpdf = ws->pdf("model2Dpdf");
  RooAbsPdf *model2Dpdf_cat0 = ws->pdf("model2Dpdf_cat0");
  RooAbsPdf *model2Dpdf_cat1 = ws->pdf("model2Dpdf_cat1");
  RooRealVar *massBjet = ws->var("massBjet");
  RooRealVar *massPho = ws->var("massPho");
  RooCategory *sampleCategory = ws->cat("sampleCategory");

  RooRealVar *nsig = ws->var("nsig"); RooRealVar constNsig(*nsig);
  RooRealVar *nres_cat0 = ws->var("nres_cat0"); RooRealVar constNres_cat0(*nres_cat0);
  RooRealVar *nnonres_cat0 = ws->var("nnonres_cat0"); RooRealVar constNnonres_cat0(*nnonres_cat0);
  RooRealVar *nres_cat1 = ws->var("nres_cat1"); RooRealVar constNres_cat1(*nres_cat1);
  RooRealVar *nnonres_cat1 = ws->var("nnonres_cat1"); RooRealVar constNnonres_cat1(*nnonres_cat1);
  
  //Create TTree to store the resulting yield data
  TFile *f = new TFile(Form(("CMSAna/HHToBBGG/data/MassFitResults/ResolutionAnalysis/OptionB_Categories/tmp/"+scanOption+"FitScenario%d.root").c_str(), s), "RECREATE");
  TTree *resultTree = new TTree("resultTree", "Parameter results from fitting");
  Float_t nsigOut, nresOut, nnonresOut;
  Float_t nsigStd, nresStd, nnonresStd;
  
  resultTree->Branch("nsigOut",&nsigOut, "nsigOut/F");
  resultTree->Branch("nresOut",&nresOut, "nresOut/F");
  resultTree->Branch("nnonresOut",&nnonresOut, "nnonresOut/F");
  resultTree->Branch("nsigStd",&nsigStd, "nsigStd/F");
  resultTree->Branch("nresStd",&nresStd, "nresStd/F");
  resultTree->Branch("nnonresStd",&nnonresStd, "nnonresStd/F");
  
  //-------------------------------------------------------------
  //Yield Information
  //=============================================================     
  double myPhoEffRatio = 1.00;
  double myBtagEffRatio = 1.00;
  double myEndcapPhotonFakerateRatio = 1.0;
  if (scanOption == "phoEff") {
    myPhoEffRatio = phoEffRatio[s];
    myBtagEffRatio = 1.25;
  }
  if (scanOption == "btagEff") {
    myBtagEffRatio = btagEffRatio[s];
    myPhoEffRatio = 1.25;
  }
  if (scanOption == "endcapPhotonFakerate") myEndcapPhotonFakerateRatio = endcapPhotonFakerate[s];
  
  double totalYield = 
    6.11*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    7.88*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +      
    31.1*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 26.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 48.7*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio
    + 1.8*myBtagEffRatio*myBtagEffRatio
    +
    2.41*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    17.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 17.2*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 206.0*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio*myEndcapPhotonFakerateRatio
    + 1.7*myBtagEffRatio*myBtagEffRatio
    ;
  double cat0Yield = 6.11*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    7.88*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +      
    31.1*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 26.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 48.7*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio
    + 1.8*myBtagEffRatio*myBtagEffRatio;
  double cat1Yield = 2.41*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio +
    17.4*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 17.2*myPhoEffRatio*myPhoEffRatio*myBtagEffRatio*myBtagEffRatio
    + 206.0*myBtagEffRatio*myBtagEffRatio*myPhoEffRatio*myEndcapPhotonFakerateRatio
    + 1.7*myBtagEffRatio*myBtagEffRatio;
  double cat0Fraction = cat0Yield / totalYield;
  double cat1Fraction = cat1Yield / totalYield;

  //-------------------------------------------------------------
  //Generate Toy MC experiment data and fit
  //=============================================================     
  for(UInt_t t=0; t < NToys; ++t) {
    cout << t << "|" << s << endl;
    nsig->setVal(constNsig.getVal());
    nres_cat0->setVal(constNres_cat0.getVal());
    nnonres_cat0->setVal(constNnonres_cat0.getVal());
    nres_cat1->setVal(constNres_cat1.getVal());
    nnonres_cat1->setVal(constNnonres_cat1.getVal());
    Float_t ran;

    //if (scanOption == "lum") ran = randomNumber->Poisson(totalYield*luminosity[s]);
    //else ran = randomNumber->Poisson(totalYield);

    if (scanOption == "lum") ran = totalYield*luminosity[s];
    else ran = totalYield;


    RooDataSet *pseudoData2D = model2Dpdf->generate(RooArgList(*massBjet,*massPho, *sampleCategory), ran);
    RooFitResult *fitResult2D = model2Dpdf->fitTo(*pseudoData2D, RooFit::Save(), RooFit::Extended(kTRUE), RooFit::Strategy(2));
    ws->import(*pseudoData2D, kTRUE);
    ws->import(*pseudoData2D, Rename("pseudoData2D"));

    RooDataSet *pseudoData2D_cat0 = model2Dpdf_cat0->generate(RooArgList(*massBjet,*massPho), ran*cat0Fraction);
    RooDataSet *pseudoData2D_cat1 = model2Dpdf_cat1->generate(RooArgList(*massBjet,*massPho), ran*cat1Fraction);
    ws->import(*pseudoData2D_cat0, kTRUE);
    ws->import(*pseudoData2D_cat0, Rename("pseudoData2D_cat0"));
    ws->import(*pseudoData2D_cat1, kTRUE);
    ws->import(*pseudoData2D_cat1, Rename("pseudoData2D_cat1"));
    
    //Save variables into separate branches of root tree
    nsigOut = nsig->getVal();
    nresOut = nres_cat0->getVal();
    nnonresOut = nnonres_cat0->getVal();
    nsigStd = nsig->getPropagatedError(*fitResult2D);
    nresStd = nres_cat0->getPropagatedError(*fitResult2D);
    nnonresStd = nnonres_cat0->getPropagatedError(*fitResult2D);
    
    resultTree->Fill();      
  }
  
  //Write to the TTree and close it
  resultTree->Write();

  file->WriteTObject(ws, Form("HHToBBGGWorkspace",scanOption.c_str(),s), "WriteDelete");
  file->Close();
  delete file;




}
コード例 #26
0
void makeSystPlot( TFile * f, TString oldFolder, RooWorkspace *WS,  string channel, string syst, int toMassNo, int fromMassNo) //massNo 0-51, see xSec7TeV.h 
{

  RooArgList  * hobs = new RooArgList("hobs");
  RooRealVar BDT("CMS_vhbb_BDT_Zll", "CMS_vhbb_BDT_Zll", -1, 1);///OLD VARIABLE NAME HERE
  hobs->add(*WS->var("CMS_vhbb_BDT_Zll"));  ///NEW VARIABLE NAME HERE
  RooWorkspace *tempWS =  (RooWorkspace*) f->Get(oldFolder.Data());
  TString systT(syst);
  TString chanT(channel);
  bool writeIt = 1;
 
  if(chanT.Contains("QCD") || chanT.Contains("Wj"))
  if(!(systT.Contains("stat"))) writeIt = 0;
 

  if((kount < 3) && (channel=="data_obs"))
  {
    kount++;
    std::string namen  = channel;
    
    std::cout << "reading WS "<< oldFolder.Data() << std::endl;
    std::cout << namen << std::endl;
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,Binning(bins));
    std::cout << namen << std::endl;

    RooDataHist *DHnom = new RooDataHist(channel.c_str(),"",*hobs,tempHistNom);  
    WS->import(*(new RooHistPdf(channel.c_str(),"",*hobs,*DHnom)));
 
 }

 if (channel!="data_obs")
 {
  std::string nameUp; 
  std::string namen; 
  std::string nameDown;


  if((syst == "stat"))
  {
    if(IFILE.Contains("7TeV"))
    {
      nameUp  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Up";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Down";
    }
    if(IFILE.Contains("8TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Up";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_stats_" + channel + "_" + oldFolder.Data() + "Down";
    }

  }
  else
  {
  nameUp  = channel + "CMS_" + syst + "Up";
  namen  = channel;
  nameDown = channel + "CMS_" + syst + "Down";
  }
  if((syst == "ZJModel"))
  {
    if(IFILE.Contains("7TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_7TeVUp";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_7TeVDown";
    }
    if(IFILE.Contains("8TeV"))
    { 
      nameUp  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_8TeVUp";
      namen  = channel;
      nameDown  = channel + "CMS_vhbb_ZJModel_" + oldFolder.Data() + "_8TeVDown";
    }

  }
  
  if(writeIt)
   {
    RooDataHist* tempRooDataHistUp = (RooDataHist*)  tempWS->data(nameUp.c_str());
    RooDataHist* tempRooDataHistDown = (RooDataHist*)  tempWS->data(nameDown.c_str());
    RooDataHist* tempRooDataHistNom = (RooDataHist*)  tempWS->data(namen.c_str());


   
    std::cout << oldFolder.Data() << std::endl; 
    std::cout << nameUp.c_str() << std::endl; 
 	 
    TH1 *tempHistUp = tempRooDataHistUp->createHistogram(nameUp.c_str(),BDT,Binning(bins));
    TH1 *tempHistDown = tempRooDataHistDown->createHistogram(nameDown.c_str(),BDT,Binning(bins));
    std::cout << namen.c_str() << std::endl;
    TH1 *tempHistNom = tempRooDataHistNom->createHistogram(namen.c_str(),BDT,Binning(bins));

    if(chanT.Contains("VH") && IFILE.Contains("7TeV"))
    {
     tempHistUp->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
     tempHistDown->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
     tempHistNom->Scale(xSec7ZH[toMassNo]/xSec7ZH[fromMassNo]);
    }  
 
   if(chanT.Contains("VH") && IFILE.Contains("8TeV"))
   {
     tempHistUp->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
     tempHistDown->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
     tempHistNom->Scale(xSec8ZH[toMassNo]/xSec8ZH[fromMassNo]);
   }  
   
   std::cout<< "channel--> " << channel << std::endl;


   tempHistUp->SetLineColor(kRed);
   tempHistUp->SetLineWidth(3);
   tempHistUp->SetFillColor(0);
  
   tempHistDown->SetLineColor(kBlue);
   tempHistDown->SetFillColor(0);
   tempHistDown->SetLineWidth(3);
  
   tempHistNom->SetFillColor(0);
   tempHistNom->SetMarkerStyle(20);
   tempHistUp->SetTitle((channel + syst).c_str());
 
 
   RooDataHist *DHnom;
   RooDataHist *DHup = new RooDataHist(nameUp.c_str(),"",*hobs,tempHistUp);  
   if(kount2 < 3) DHnom = new RooDataHist(namen.c_str(),"",*hobs,tempHistNom);
   RooDataHist *DHdown = new RooDataHist(nameDown.c_str(),"",*hobs,tempHistDown);  

   WS->import(*(new RooHistPdf(nameUp.c_str(),"",*hobs,*DHup)));
   WS->import(*(new RooHistPdf(nameDown.c_str(),"",*hobs,*DHdown)));
   if(kount2 < 3){ WS->import(*(new RooHistPdf(namen.c_str(),"",*hobs,*DHnom))); kount2++;}
   }
 }


}
コード例 #27
0
ファイル: CreateMuonFakeRateMap.C プロジェクト: sixie/CMSAna
void FitLeptonResponseModels(const string Label = "ZZ", Int_t Option = 0, Int_t PtBin = -1, Int_t EtaBin = -1) {

  string label = Label;
  if (Label != "") label = "_" + Label;
  TFile *fileInput = new TFile(("FakeRate" + label + ".root").c_str(), "READ");

  //********************************************************
  // Bins
  //********************************************************
  const UInt_t NPtBins = 4;
  const UInt_t NEtaBins = 3;
  double ptBins[NPtBins+1] = { 5, 7, 10, 15, 25 };
  double etaBins[NEtaBins+1] = { 0.0, 1.2, 2.2, 2.4 };

  
  //********************************************************
  // Output
  //********************************************************
  TFile *fileOutput = new TFile(("FakeMuonPtResolutionModel" + label + ".root").c_str(), "UPDATE");
  
  TH2F* GaussParamArray_Muons_mean = (TH2F*)fileOutput->Get("GaussParamArray_Muons_mean");
  TH2F* GaussParamArray_Muons_sigma = (TH2F*)fileOutput->Get("GaussParamArray_Muons_sigma");


  if (!GaussParamArray_Muons_mean) {
    GaussParamArray_Muons_mean = new TH2F( "GaussParamArray_Muons_mean", "", NPtBins, 0, NPtBins, NEtaBins, 0, NEtaBins);
    for (uint i=0; i < NPtBins+2; ++i) {
      for (uint j=0; j < NEtaBins+2; ++j) {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0.0);
      }
    }
  }
  if (!GaussParamArray_Muons_sigma) {
    GaussParamArray_Muons_sigma = new TH2F( "GaussParamArray_Muons_sigma", "", NPtBins, 0, NPtBins, NEtaBins, 0, NEtaBins);
    for (uint i=0; i < NPtBins+2; ++i) {
      for (uint j=0; j < NEtaBins+2; ++j) {
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0.0);
      }
    }
  }

  for (uint i=0; i < NPtBins+2; ++i) {
    for (uint j=0; j < NEtaBins+2; ++j) {
      if (i >= 1 && ( j >= 1 && j <= NEtaBins )) {
      } else {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0);
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0);        
      }
    }
  }

  //********************************************************
  // Fit for resolution function 
  //******************************************************** 
  for (uint i=0; i < NPtBins+2; ++i) {
    for (uint j=0; j < NEtaBins+2; ++j) {

      if (PtBin >= 0 && EtaBin >= 0) {
        if (!(i==PtBin && j==EtaBin)) continue;
      }
      
      TH1F* hist = (TH1F*)fileInput->Get(Form("LeptonPtResolution_Muons_PtBin%d_EtaBin%d",i,j));
      assert(hist);

      RooRealVar leptonPtRes("leptonPtRes","leptonPtRes",-1.0,0.25);
      leptonPtRes.setRange("range",-1.00,0.25);
      leptonPtRes.setBins(100);
      RooDataHist *data=0;
      data = new RooDataHist("data","data",RooArgSet(leptonPtRes),hist);

      RooRealVar     *mean  = new RooRealVar("mean","mean",-0.25,-10,10);
      RooRealVar     *sigma = new RooRealVar("sigma","sigma",0.05,0.00001,0.5);

      RooGaussian *model = new RooGaussian("LeptonPtResModel","LeptonPtResModel",leptonPtRes,*mean,*sigma);

      RooFitResult *fitResult=0;
      fitResult = model->fitTo(*data,
                               RooFit::Binned(true),
                               RooFit::Strategy(1),
                               RooFit::Save());

      cout << "Fitted parameters\n";
      cout << mean->getVal() << endl;
      cout << sigma->getVal() << endl;
     
      if (i >= 1 && ( j >= 1 && j <= NEtaBins )) {
        GaussParamArray_Muons_mean->SetBinContent(i,j,mean->getVal());
        GaussParamArray_Muons_sigma->SetBinContent(i,j,sigma->getVal());
      } else {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0);
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0);        
      }




      //Save Workspace
      RooWorkspace *w = new RooWorkspace(Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j),Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j));
      w->import(*model);
      w->import(*data);
      //w->Print();

      //Make Plot
      RooPlot *frame = leptonPtRes.frame(RooFit::Bins(100));
      data->plotOn(frame,RooFit::MarkerStyle(kFullCircle),RooFit::MarkerSize(0.8),RooFit::DrawOption("ZP"));    
      model->plotOn(frame);

      TCanvas *cv = new TCanvas("cv","cv",800,600);
      
      frame->Draw();
      cv->SaveAs(Form("LeptonPtResolution_Muons%s_PtBin%d_EtaBin%d.gif",label.c_str(),i,j)); 

      fileOutput->WriteTObject(model, Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j), "WriteDelete");
      fileOutput->WriteTObject(cv, Form("LeptonPtResolutionFit_Muons_PtBin%d_EtaBin%d",i,j), "WriteDelete");
      fileOutput->WriteTObject(w, w->GetName(), "WriteDelete");

      fileOutput->WriteTObject(GaussParamArray_Muons_mean, "GaussParamArray_Muons_mean", "WriteDelete");
      fileOutput->WriteTObject(GaussParamArray_Muons_sigma, "GaussParamArray_Muons_sigma", "WriteDelete");


    }
  }

  //********************************************************
  // Produce output lookup table
  //******************************************************** 
  ofstream outf_e("FakeMuonResponseMap.h");

  outf_e << "UInt_t FindFakeMuonResponseBin( double value, double bins[], UInt_t nbins) {" << endl;
  outf_e << "  UInt_t nbinboundaries = nbins+1;" << endl;
  outf_e << "  UInt_t bin = 0;" << endl;
  outf_e << "  for (uint i=0; i < nbinboundaries; ++i) {" << endl;
  outf_e << "    if (i < nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i] && value < bins[i+1]) {" << endl;
  outf_e << "        bin = i+1;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    } else if (i == nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i]) {" << endl;
  outf_e << "        bin = nbinboundaries;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    }    " << endl;
  outf_e << "  }" << endl;
  outf_e << "  return bin;" << endl;
  outf_e << "}" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "Double_t GetMuonResponseMeanPtEta(Double_t Pt, Double_t Eta) {" << endl;

  outf_e << endl;
  outf_e << "  Double_t ptBins[" << NPtBins+1 << "] = {";
  for (uint i=0; i < NPtBins+1; ++i) {
    outf_e << ptBins[i];
    if (i < NPtBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";

  outf_e << "  Double_t etaBins[" << NEtaBins+1 << "] = {";
  for (uint i=0; i < NEtaBins+1; ++i) {
    outf_e << etaBins[i];
    if (i < NEtaBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";


  outf_e << endl;
  outf_e << endl;

  outf_e << "  Double_t ResponseMean[" << NPtBins+2 << "][" << NEtaBins+2 << "] = {";
  outf_e << endl;

  for (uint i=0; i < NPtBins+2; ++i) {
    outf_e << "    {";
    for (uint j=0; j < NEtaBins+2; ++j) {
      outf_e << GaussParamArray_Muons_mean->GetBinContent(i,j);
      if (j< NEtaBins+1) {
        outf_e << ",";
      }
    }
    if (i< NPtBins+1) {
      outf_e << "    },";
    } else {
      outf_e << "}";
    }
    outf_e << endl;
  }
  
  outf_e << "  };" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "  Int_t tmpPtBin = FindFakeMuonResponseBin( Pt , ptBins, " << NPtBins << ");" << endl;
  outf_e << "  Int_t tmpEtaBin = FindFakeMuonResponseBin( Eta , etaBins, " << NEtaBins << ");" << endl;
  outf_e << "  return ResponseMean[tmpPtBin][tmpEtaBin];" << endl;
  outf_e << "}" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "Double_t GetMuonResponseSigmaPtEta(Double_t Pt, Double_t Eta) {" << endl;

  outf_e << endl;
  outf_e << "  Double_t ptBins[" << NPtBins+1 << "] = {";
  for (uint i=0; i < NPtBins+1; ++i) {
    outf_e << ptBins[i];
    if (i < NPtBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";

  outf_e << "  Double_t etaBins[" << NEtaBins+1 << "] = {";
  for (uint i=0; i < NEtaBins+1; ++i) {
    outf_e << etaBins[i];
    if (i < NEtaBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";


  outf_e << endl;
  outf_e << endl;

  outf_e << "  Double_t ResponseSigma[" << NPtBins+2 << "][" << NEtaBins+2 << "] = {";
  outf_e << endl;

  for (uint i=0; i < NPtBins+2; ++i) {
    outf_e << "    {";
    for (uint j=0; j < NEtaBins+2; ++j) {
      outf_e << GaussParamArray_Muons_sigma->GetBinContent(i,j);
      if (j< NEtaBins+1) {
        outf_e << ",";
      }
    }
    if (i< NPtBins+1) {
      outf_e << "    },";
    } else {
      outf_e << "}";
    }
    outf_e << endl;
  }
  
  outf_e << "  };" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "  Int_t tmpPtBin = FindFakeMuonResponseBin( Pt , ptBins, " << NPtBins << ");" << endl;
  outf_e << "  Int_t tmpEtaBin = FindFakeMuonResponseBin( Eta , etaBins, " << NEtaBins << ");" << endl;
  outf_e << "  return ResponseSigma[tmpPtBin][tmpEtaBin];" << endl;
  outf_e << "}" << endl;


  outf_e.close();


  fileInput->Close();
  delete fileInput;
  fileOutput->Close();

  gBenchmark->Show("WWTemplate");       
}
コード例 #28
0
void eregtesting_13TeV_Eta(bool dobarrel=true, bool doele=false,int gammaID=0) {
  
  //output dir
  TString EEorEB = "EE";
  if(dobarrel)
	{
	EEorEB = "EB";
	}
  TString gammaDir = "bothGammas";
  if(gammaID==1)
  {
   gammaDir = "gamma1";
  }
  else if(gammaID==2)
  {
   gammaDir = "gamma2";
  }
  TString dirname = TString::Format("ereg_test_plots_Eta/%s_%s",gammaDir.Data(),EEorEB.Data());
  
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);    
  
  //read workspace from training
  TString fname;
  if (doele && dobarrel) 
    fname = "wereg_ele_eb.root";
  else if (doele && !dobarrel) 
    fname = "wereg_ele_ee.root";
  else if (!doele && dobarrel) 
    fname = "wereg_ph_eb.root";
  else if (!doele && !dobarrel) 
    fname = "wereg_ph_ee.root";
  
  TString infile = TString::Format("../../ereg_ws_Eta/%s/%s",gammaDir.Data(),fname.Data());
  
  TFile *fws = TFile::Open(infile); 
  RooWorkspace *ws = (RooWorkspace*)fws->Get("wereg");
  
  //read variables from workspace
  RooGBRTargetFlex *meantgt = static_cast<RooGBRTargetFlex*>(ws->arg("sigmeant"));  
  RooRealVar *tgtvar = ws->var("tgtvar");
  
  
  RooArgList vars;
  vars.add(meantgt->FuncVars());
  vars.add(*tgtvar);
   
  //read testing dataset from TTree
  RooRealVar weightvar("weightvar","",1.);

  TTree *dtree;
  
  if (doele) {
    //TFile *fdin = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    TFile *fdin = TFile::Open("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");

    TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterSingleInvert");
    dtree = (TTree*)ddir->Get("hPhotonTreeSingle");       
  }
  else {
    //TFile *fdin = TFile::Open("/eos/cms/store/group/dpg_ecal/alca_ecalcalib/piZero2017/zhicaiz/Gun_MultiPion_FlatPt-1To15/Gun_FlatPt1to15_MultiPion_withPhotonPtFilter_pythia8/photons_0_half2.root");
    //TFile *fdin = TFile::Open("/eos/cms/store/group/dpg_ecal/alca_ecalcalib/piZero2017/zhicaiz/Gun_MultiEta_FlatPt-1To15/Gun_FlatPt1to15_MultiEta_withPhotonPtFilter_pythia8/photons_22Aug2017_V3_half2.root");
    TFile *fdin = TFile::Open("/eos/cms/store/group/dpg_ecal/alca_ecalcalib/piZero2017/zhicaiz/Gun_MultiEta_FlatPt-1To15/Gun_FlatPt1to15_MultiEtaToGG_withPhotonPtFilter_pythia8/photons_20171008_half2.root");
   	if(gammaID==0)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma");
	}
	else if(gammaID==1)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma1");
	}
	else if(gammaID==2)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma2");
	}
  }
  
  //selection cuts for testing
  //TCut selcut = "(STr2_enG1_true/cosh(STr2_Eta_1)>1.0) && (STr2_S4S9_1>0.75)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03)  && (STr2_enG_true/STr2_enG_rec)<3.0 && STr2_EOverEOther < 10.0 && STr2_EOverEOther > 0.1";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03)  && (STr2_mPi0_nocor>0.1)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.1) && (STr2_mPi0_nocor < 0.2)";
  TCut selcut = "";
  if(dobarrel) selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.2) && (STr2_mPi0_nocor < 1.0) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)<1.479 && (!STr2_fromPi0)";
  //if(dobarrel) selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.1) && (STr2_mPi0_nocor < 0.2) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)<1.479";
  else selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.2) && (STr2_mPi0_nocor < 1.0) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)>1.479 && (!STr2_fromPi0)";
  //else selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.1) && (STr2_mPi0_nocor < 0.2) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)>1.479";

  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (STr2_iEta_on2520==0 || STr2_iPhi_on20==0) ";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)<60)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)>60)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.9) && (STr2_S2S9>0.85)&& (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)<60)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.9) && (STr2_S2S9>0.85)&& (STr2_isMerging < 2) && (STr2_DeltaR < 0.03)";
/*  
TCut selcut;
  if (dobarrel) 
    selcut = "ph.genpt>25. && ph.isbarrel && ph.ispromptgen"; 
  else
    selcut = "ph.genpt>25. && !ph.isbarrel && ph.ispromptgen"; 
 */ 
  TCut selweight = "xsecweight(procidx)*puweight(numPU,procidx)";
  TCut prescale10 = "(Entry$%10==0)";
  TCut prescale10alt = "(Entry$%10==1)";
  TCut prescale25 = "(Entry$%25==0)";
  TCut prescale100 = "(Entry$%100==0)";  
  TCut prescale1000 = "(Entry$%1000==0)";  
  TCut evenevents = "(Entry$%2==0)";
  TCut oddevents = "(Entry$%2==1)";
  TCut prescale100alt = "(Entry$%100==1)";
  TCut prescale1000alt = "(Entry$%1000==1)";
  TCut prescale50alt = "(Entry$%50==1)";
  TCut Events3_4 = "(Entry$%4==3)";
  TCut Events1_4 = "(Entry$%4==1)";
  TCut Events2_4 = "(Entry$%4==2)";
  TCut Events0_4 = "(Entry$%4==0)";

  TCut Events01_4 = "(Entry$%4<2)";
  TCut Events23_4 = "(Entry$%4>1)";

  TCut EventsTest = "(Entry$%2==1)";

  //weightvar.SetTitle(EventsTest*selcut);
  weightvar.SetTitle(selcut);
/*
  if (doele) 
    weightvar.SetTitle(prescale100alt*selcut);
  else
    weightvar.SetTitle(selcut);
  */
  //make testing dataset
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",dtree,vars,weightvar);   

  if (doele) 
    weightvar.SetTitle(prescale1000alt*selcut);
  else
    weightvar.SetTitle(prescale10alt*selcut);
  //make reduced testing dataset for integration over conditional variables
  RooDataSet *hdatasmall = RooTreeConvert::CreateDataSet("hdatasmall",dtree,vars,weightvar);     
    
  //retrieve full pdf from workspace
  RooAbsPdf *sigpdf = ws->pdf("sigpdf");
  
  //input variable corresponding to sceta
  RooRealVar *scEraw = ws->var("var_0");
  scEraw->setRange(1.,2.);
  scEraw->setBins(100);
//  RooRealVar *scetavar = ws->var("var_1");
//  RooRealVar *scphivar = ws->var("var_2");
  
 
  //regressed output functions
  RooAbsReal *sigmeanlim = ws->function("sigmeanlim");
  RooAbsReal *sigwidthlim = ws->function("sigwidthlim");
  RooAbsReal *signlim = ws->function("signlim");
  RooAbsReal *sign2lim = ws->function("sign2lim");

//  RooAbsReal *sigalphalim = ws->function("sigalphalim");
  //RooAbsReal *sigalpha2lim = ws->function("sigalpha2lim");


  //formula for corrected energy/true energy ( 1.0/(etrue/eraw) * regression mean)
  RooFormulaVar ecor("ecor","","1./(@0)*@1",RooArgList(*tgtvar,*sigmeanlim));
  RooRealVar *ecorvar = (RooRealVar*)hdata->addColumn(ecor);
  ecorvar->setRange(0.,2.);
  ecorvar->setBins(800);
  
  //formula for raw energy/true energy (1.0/(etrue/eraw))
  RooFormulaVar raw("raw","","1./@0",RooArgList(*tgtvar));
  RooRealVar *rawvar = (RooRealVar*)hdata->addColumn(raw);
  rawvar->setRange(0.,2.);
  rawvar->setBins(800);

  //clone data and add regression outputs for plotting
  RooDataSet *hdataclone = new RooDataSet(*hdata,"hdataclone");
  RooRealVar *meanvar = (RooRealVar*)hdataclone->addColumn(*sigmeanlim);
  RooRealVar *widthvar = (RooRealVar*)hdataclone->addColumn(*sigwidthlim);
  RooRealVar *nvar = (RooRealVar*)hdataclone->addColumn(*signlim);
  RooRealVar *n2var = (RooRealVar*)hdataclone->addColumn(*sign2lim);
 
//  RooRealVar *alphavar = (RooRealVar*)hdataclone->addColumn(*sigalphalim);
//  RooRealVar *alpha2var = (RooRealVar*)hdataclone->addColumn(*sigalpha2lim);
  
  
  //plot target variable and weighted regression prediction (using numerical integration over reduced testing dataset)
  TCanvas *craw = new TCanvas;
  //RooPlot *plot = tgtvar->frame(0.6,1.2,100);
  RooPlot *plot = tgtvar->frame(0.6,2.0,100);
  hdata->plotOn(plot);
  sigpdf->plotOn(plot,ProjWData(*hdatasmall));
  plot->Draw();
  craw->SaveAs("RawE.pdf");
  craw->SaveAs("RawE.png");
  craw->SetLogy();
  plot->SetMinimum(0.1);
  craw->SaveAs("RawElog.pdf");
  craw->SaveAs("RawElog.png");
  
  //plot distribution of regressed functions over testing dataset
  TCanvas *cmean = new TCanvas;
  RooPlot *plotmean = meanvar->frame(0.8,2.0,100);
  hdataclone->plotOn(plotmean);
  plotmean->Draw();
  cmean->SaveAs("mean.pdf");
  cmean->SaveAs("mean.png");
  
  
  TCanvas *cwidth = new TCanvas;
  RooPlot *plotwidth = widthvar->frame(0.,0.05,100);
  hdataclone->plotOn(plotwidth);
  plotwidth->Draw();
  cwidth->SaveAs("width.pdf");
  cwidth->SaveAs("width.png");
  
  TCanvas *cn = new TCanvas;
  RooPlot *plotn = nvar->frame(0.,111.,200);
  hdataclone->plotOn(plotn);
  plotn->Draw();
  cn->SaveAs("n.pdf");
  cn->SaveAs("n.png");

  TCanvas *cn2 = new TCanvas;
  RooPlot *plotn2 = n2var->frame(0.,111.,100);
  hdataclone->plotOn(plotn2);
  plotn2->Draw();
  cn2->SaveAs("n2.pdf");
  cn2->SaveAs("n2.png");

/*
  TCanvas *calpha = new TCanvas;
  RooPlot *plotalpha = alphavar->frame(0.,5.,200);
  hdataclone->plotOn(plotalpha);
  plotalpha->Draw();
  calpha->SaveAs("alpha.pdf");
  calpha->SaveAs("alpha.png");

  TCanvas *calpha2 = new TCanvas;
  RooPlot *plotalpha2 = alpha2var->frame(0.,5.,200);
  hdataclone->plotOn(plotalpha2);
  plotalpha2->Draw();
  calpha2->SaveAs("alpha2.pdf");
  calpha2->SaveAs("alpha2.png");
*/

/* 
  TCanvas *ceta = new TCanvas;
  RooPlot *ploteta = scetavar->frame(-2.6,2.6,200);
  hdataclone->plotOn(ploteta);
  ploteta->Draw();      
  ceta->SaveAs("eta.pdf");  
  ceta->SaveAs("eta.png");  
  */

  //create histograms for eraw/etrue and ecor/etrue to quantify regression performance
  TH1 *heraw;// = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.));
  TH1 *hecor;// = hdata->createHistogram("hecor",*ecorvar);
  if (EEorEB == "EB")
  {
         heraw = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.0));
         hecor = hdata->createHistogram("hecor",*ecorvar, Binning(800,0.,2.0));
  }
  else
  {
         heraw = hdata->createHistogram("hraw",*rawvar,Binning(200,0.,2.));
         hecor = hdata->createHistogram("hecor",*ecorvar, Binning(200,0.,2.));
  }

  
  
  //heold->SetLineColor(kRed);
  hecor->SetLineColor(kBlue);
  heraw->SetLineColor(kMagenta);
  
  hecor->GetYaxis()->SetRangeUser(1.0,1.3*hecor->GetMaximum());
  heraw->GetYaxis()->SetRangeUser(1.0,1.3*hecor->GetMaximum());

  hecor->GetXaxis()->SetRangeUser(0.0,1.5);
  heraw->GetXaxis()->SetRangeUser(0.0,1.5);
  
/*if(EEorEB == "EE")
{
  heraw->GetYaxis()->SetRangeUser(10.0,200.0);
  hecor->GetYaxis()->SetRangeUser(10.0,200.0);
}
*/ 
 
//heold->GetXaxis()->SetRangeUser(0.6,1.2);
  double effsigma_cor, effsigma_raw, fwhm_cor, fwhm_raw;

  if(EEorEB == "EB")
  {
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(800,0.,2.));
  effsigma_cor = effSigma(hecorfine);
  fwhm_cor = FWHM(hecorfine);
  TH1 *herawfine = hdata->createHistogram("herawfine",*rawvar,Binning(800,0.,2.));
  effsigma_raw = effSigma(herawfine);
  fwhm_raw = FWHM(herawfine);
  }
  else
  {
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(200,0.,2.));
  effsigma_cor = effSigma(hecorfine);
  fwhm_cor = FWHM(hecorfine);
  TH1 *herawfine = hdata->createHistogram("herawfine",*rawvar,Binning(200,0.,2.));
  effsigma_raw = effSigma(herawfine);
  fwhm_raw = FWHM(herawfine);
  }


  TCanvas *cresponse = new TCanvas;
  gStyle->SetOptStat(0); 
  gStyle->SetPalette(107);
  hecor->SetTitle("");
  heraw->SetTitle("");
  hecor->Draw("HIST");
  //heold->Draw("HISTSAME");
  heraw->Draw("HISTSAME");

  //show errSigma in the plot
  TLegend *leg = new TLegend(0.1, 0.75, 0.7, 0.9);
  leg->AddEntry(hecor,Form("E_{cor}/E_{true}, #sigma_{eff}=%4.3f, FWHM=%4.3f", effsigma_cor, fwhm_cor),"l");
  leg->AddEntry(heraw,Form("E_{raw}/E_{true}, #sigma_{eff}=%4.3f, FWHM=%4.3f", effsigma_raw, fwhm_raw),"l");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
 // leg->SetTextColor(kRed);
  leg->Draw();

  cresponse->SaveAs("response.pdf");
  cresponse->SaveAs("response.png");
  cresponse->SetLogy();
  cresponse->SaveAs("responselog.pdf");
  cresponse->SaveAs("responselog.png");
 

  // draw CCs vs eta and phi
/*
  TCanvas *c_eta = new TCanvas;
  TH1 *h_eta = hdata->createHistogram("h_eta",*scetavar,Binning(100,-3.2,3.2));
  h_eta->Draw("HIST");
  c_eta->SaveAs("heta.pdf");
  c_eta->SaveAs("heta.png");

  TCanvas *c_phi = new TCanvas;
  TH1 *h_phi = hdata->createHistogram("h_phi",*scphivar,Binning(100,-3.2,3.2));
  h_phi->Draw("HIST");
  c_phi->SaveAs("hphi.pdf");
  c_phi->SaveAs("hphi.png");
*/

  RooRealVar *scetaiXvar = ws->var("var_4");
  RooRealVar *scphiiYvar = ws->var("var_5");
 
   if(EEorEB=="EB")
   {
   scetaiXvar->setRange(-90,90);
   scetaiXvar->setBins(180);
   scphiiYvar->setRange(0,360);
   scphiiYvar->setBins(360);
   }
   else
   {
   scetaiXvar->setRange(0,50);
   scetaiXvar->setBins(50);
   scphiiYvar->setRange(0,50);
   scphiiYvar->setBins(50);
 
   }
   ecorvar->setRange(0.5,1.5);
   ecorvar->setBins(800);
   rawvar->setRange(0.5,1.5);
   rawvar->setBins(800);
  

  TCanvas *c_cor_eta = new TCanvas;

  TH3F *h3_CC_eta_phi = (TH3F*) hdata->createHistogram("var_5,var_4,ecor",(EEorEB=="EB") ? 170 : 100, (EEorEB=="EB") ? 360 : 100,25);
  TProfile2D *h_CC_eta_phi = h3_CC_eta_phi->Project3DProfile();

  h_CC_eta_phi->SetTitle("E_{cor}/E_{true}");
  if(EEorEB=="EB")
  {
  h_CC_eta_phi->GetXaxis()->SetTitle("i#eta");
  h_CC_eta_phi->GetYaxis()->SetTitle("i#phi");
  h_CC_eta_phi->GetXaxis()->SetRangeUser(-85,85);
  h_CC_eta_phi->GetYaxis()->SetRangeUser(0,360);
  }
  else
  {
  h_CC_eta_phi->GetXaxis()->SetTitle("iX");
  h_CC_eta_phi->GetYaxis()->SetTitle("iY");
  }

  h_CC_eta_phi->SetMinimum(0.5);
  h_CC_eta_phi->SetMaximum(1.5);

  h_CC_eta_phi->Draw("COLZ");
  c_cor_eta->SaveAs("cor_vs_eta_phi.pdf");
  c_cor_eta->SaveAs("cor_vs_eta_phi.png");

  TH2F *h_CC_eta = hdata->createHistogram(*scetaiXvar, *ecorvar, "","cor_vs_eta");
  if(EEorEB=="EB")
  {
  h_CC_eta->GetXaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_CC_eta->GetXaxis()->SetTitle("iX");
  }
  h_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_eta->Draw("COLZ");
  c_cor_eta->SaveAs("cor_vs_eta.pdf");
  c_cor_eta->SaveAs("cor_vs_eta.png");

 
  TCanvas *c_cor_scEraw = new TCanvas;
  TH2F *h_CC_scEraw = hdata->createHistogram(*scEraw, *ecorvar, "","cor_vs_scEraw");
  h_CC_scEraw->GetXaxis()->SetTitle("E_{raw}"); 
  h_CC_scEraw->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_scEraw->Draw("COLZ");
  c_cor_scEraw->SaveAs("cor_vs_scEraw.pdf");
  c_cor_scEraw->SaveAs("cor_vs_scEraw.png");

  TCanvas *c_raw_scEraw = new TCanvas;
  TH2F *h_RC_scEraw = hdata->createHistogram(*scEraw, *rawvar, "","raw_vs_scEraw");
  h_RC_scEraw->GetXaxis()->SetTitle("E_{raw}"); 
  h_RC_scEraw->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_scEraw->Draw("COLZ");
  c_raw_scEraw->SaveAs("raw_vs_scEraw.pdf");
  c_raw_scEraw->SaveAs("raw_vs_scEraw.png");

 
 	
  TCanvas *c_cor_phi = new TCanvas;
  TH2F *h_CC_phi = hdata->createHistogram(*scphiiYvar, *ecorvar, "","cor_vs_phi"); 
  if(EEorEB=="EB")
  {
  h_CC_phi->GetXaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_CC_phi->GetXaxis()->SetTitle("iY");
  }

  h_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_phi->Draw("COLZ");
  c_cor_phi->SaveAs("cor_vs_phi.pdf");
  c_cor_phi->SaveAs("cor_vs_phi.png");
 
  TCanvas *c_raw_eta = new TCanvas;

  TH3F *h3_RC_eta_phi = (TH3F*) hdata->createHistogram("var_5,var_4,raw",(EEorEB=="EB") ? 170 : 100, (EEorEB=="EB") ? 360 : 100,25);
  TProfile2D *h_RC_eta_phi = h3_RC_eta_phi->Project3DProfile();

  h_RC_eta_phi->SetTitle("E_{raw}/E_{true}");
  if(EEorEB=="EB")
  {
  h_RC_eta_phi->GetXaxis()->SetTitle("i#eta");
  h_RC_eta_phi->GetYaxis()->SetTitle("i#phi");
  h_RC_eta_phi->GetXaxis()->SetRangeUser(-85,85);
  h_RC_eta_phi->GetYaxis()->SetRangeUser(0,360);
  }
  else
  {
  h_RC_eta_phi->GetXaxis()->SetTitle("iX");
  h_RC_eta_phi->GetYaxis()->SetTitle("iY");
  }

  h_RC_eta_phi->SetMinimum(0.5);
  h_RC_eta_phi->SetMaximum(1.5);

  h_RC_eta_phi->Draw("COLZ");
  c_raw_eta->SaveAs("raw_vs_eta_phi.pdf");
  c_raw_eta->SaveAs("raw_vs_eta_phi.png");
  TH2F *h_RC_eta = hdata->createHistogram(*scetaiXvar, *rawvar, "","raw_vs_eta");
  if(EEorEB=="EB")
  {
  h_RC_eta->GetXaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_RC_eta->GetXaxis()->SetTitle("iX");
  }

  h_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_eta->Draw("COLZ");
  c_raw_eta->SaveAs("raw_vs_eta.pdf");
  c_raw_eta->SaveAs("raw_vs_eta.png");
	
  TCanvas *c_raw_phi = new TCanvas;
  TH2F *h_RC_phi = hdata->createHistogram(*scphiiYvar, *rawvar, "","raw_vs_phi"); 
  if(EEorEB=="EB")
  {
  h_RC_phi->GetXaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_RC_phi->GetXaxis()->SetTitle("iY");
  }

  h_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_phi->Draw("COLZ");
  c_raw_phi->SaveAs("raw_vs_phi.pdf");
  c_raw_phi->SaveAs("raw_vs_phi.png");


//on2,5,20, etc
if(EEorEB == "EB")
{

  TCanvas *myC_iCrystal_mod = new TCanvas;

  RooRealVar *SM_distvar = ws->var("var_6");
  SM_distvar->setRange(0,10);
  SM_distvar->setBins(10);
  TH2F *h_CC_SM_dist = hdata->createHistogram(*SM_distvar, *ecorvar, "","cor_vs_SM_dist");
  h_CC_SM_dist->GetXaxis()->SetTitle("SM_dist"); 
  h_CC_SM_dist->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_SM_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_SM_dist.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_SM_dist.png");
  TH2F *h_RC_SM_dist = hdata->createHistogram(*SM_distvar, *rawvar, "","raw_vs_SM_dist");
  h_RC_SM_dist->GetXaxis()->SetTitle("distance to SM gap"); 
  h_RC_SM_dist->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_SM_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_SM_dist.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_SM_dist.png");

  RooRealVar *M_distvar = ws->var("var_7");
  M_distvar->setRange(0,13);
  M_distvar->setBins(10);
  TH2F *h_CC_M_dist = hdata->createHistogram(*M_distvar, *ecorvar, "","cor_vs_M_dist");
  h_CC_M_dist->GetXaxis()->SetTitle("M_dist"); 
  h_CC_M_dist->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_M_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_M_dist.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_M_dist.png");
  TH2F *h_RC_M_dist = hdata->createHistogram(*M_distvar, *rawvar, "","raw_vs_M_dist");
  h_RC_M_dist->GetXaxis()->SetTitle("distance to module gap"); 
  h_RC_M_dist->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_M_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_M_dist.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_M_dist.png");

/*
  RooRealVar *DeltaRG1G2var = ws->var("var_8");
  DeltaRG1G2var->setRange(0,0.2);
  DeltaRG1G2var->setBins(100);
  TH2F *h_CC_DeltaRG1G2 = hdata->createHistogram(*DeltaRG1G2var, *ecorvar, "","cor_vs_DeltaRG1G2");
  h_CC_DeltaRG1G2->GetXaxis()->SetTitle("DeltaRG1G2"); 
  h_CC_DeltaRG1G2->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_DeltaRG1G2->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_DeltaRG1G2.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_DeltaRG1G2.png");
  TH2F *h_RC_DeltaRG1G2 = hdata->createHistogram(*DeltaRG1G2var, *rawvar, "","raw_vs_DeltaRG1G2");
  h_RC_DeltaRG1G2->GetXaxis()->SetTitle("distance to module gap"); 
  h_RC_DeltaRG1G2->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_DeltaRG1G2->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_DeltaRG1G2.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_DeltaRG1G2.png");
*/
}
	 

// other variables

  TCanvas *myC_variables = new TCanvas;

  RooRealVar *Nxtalvar = ws->var("var_1");
  Nxtalvar->setRange(0,10);
  Nxtalvar->setBins(10);
  TH2F *h_CC_Nxtal = hdata->createHistogram(*Nxtalvar, *ecorvar, "","cor_vs_Nxtal");
  h_CC_Nxtal->GetXaxis()->SetTitle("Nxtal"); 
  h_CC_Nxtal->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_Nxtal->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_Nxtal.pdf");
  myC_variables->SaveAs("cor_vs_Nxtal.png");
  TH2F *h_RC_Nxtal = hdata->createHistogram(*Nxtalvar, *rawvar, "","raw_vs_Nxtal");
  h_RC_Nxtal->GetXaxis()->SetTitle("Nxtal"); 
  h_RC_Nxtal->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_Nxtal->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_Nxtal.pdf");
  myC_variables->SaveAs("raw_vs_Nxtal.png");
	
  RooRealVar *S4S9var = ws->var("var_2");

  int Nbins_S4S9 = 100;
  double Low_S4S9 = 0.6;
  double High_S4S9 = 1.0; 
  S4S9var->setRange(Low_S4S9,High_S4S9);
  S4S9var->setBins(Nbins_S4S9);
 
  TH2F *h_CC_S4S9 = hdata->createHistogram(*S4S9var, *ecorvar, "","cor_vs_S4S9");
  h_CC_S4S9->GetXaxis()->SetTitle("S4S9"); 
  h_CC_S4S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S4S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S4S9.pdf");
  myC_variables->SaveAs("cor_vs_S4S9.png");
  TH2F *h_RC_S4S9 = hdata->createHistogram(*S4S9var, *rawvar, "","raw_vs_S4S9");
  h_RC_S4S9->GetXaxis()->SetTitle("S4S9"); 
  h_RC_S4S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S4S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S4S9.pdf");
  myC_variables->SaveAs("raw_vs_S4S9.png");
	
  RooRealVar *S2S9var = ws->var("var_3");
  int Nbins_S2S9 = 100;
  double Low_S2S9 = 0.5;
  double High_S2S9 = 1.0; 
  S2S9var->setRange(Low_S2S9,High_S2S9);
  S2S9var->setBins(Nbins_S2S9);
  TH2F *h_CC_S2S9 = hdata->createHistogram(*S2S9var, *ecorvar, "","cor_vs_S2S9");
  h_CC_S2S9->GetXaxis()->SetTitle("S2S9"); 
  h_CC_S2S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S2S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S2S9.pdf");
  myC_variables->SaveAs("cor_vs_S2S9.png");
  TH2F *h_RC_S2S9 = hdata->createHistogram(*S2S9var, *rawvar, "","raw_vs_S2S9");
  h_RC_S2S9->GetXaxis()->SetTitle("S2S9"); 
  h_RC_S2S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S2S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S2S9.pdf");
  myC_variables->SaveAs("raw_vs_S2S9.png");

  TH2F *h_S2S9_eta = hdata->createHistogram(*scetaiXvar, *S2S9var, "","S2S9_vs_eta");
  h_S2S9_eta->GetYaxis()->SetTitle("S2S9"); 
  if(EEorEB=="EB")
  {
  h_CC_eta->GetYaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_CC_eta->GetYaxis()->SetTitle("iX");
  }
  h_S2S9_eta->Draw("COLZ");
  myC_variables->SaveAs("S2S9_vs_eta.pdf");
  myC_variables->SaveAs("S2S9_vs_eta.png");
  
  TH2F *h_S4S9_eta = hdata->createHistogram(*scetaiXvar, *S4S9var, "","S4S9_vs_eta");
  h_S4S9_eta->GetYaxis()->SetTitle("S4S9"); 
  if(EEorEB=="EB")
  {
  h_CC_eta->GetYaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_CC_eta->GetYaxis()->SetTitle("iX");
  }
  h_S4S9_eta->Draw("COLZ");
  myC_variables->SaveAs("S4S9_vs_eta.pdf");
  myC_variables->SaveAs("S4S9_vs_eta.png");
  
  TH2F *h_S2S9_phi = hdata->createHistogram(*scphiiYvar, *S2S9var, "","S2S9_vs_phi");
  h_S2S9_phi->GetYaxis()->SetTitle("S2S9"); 
  if(EEorEB=="EB")
  {
  h_CC_phi->GetYaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_CC_phi->GetYaxis()->SetTitle("iY");
  }
  h_S2S9_phi->Draw("COLZ");
  myC_variables->SaveAs("S2S9_vs_phi.pdf");
  myC_variables->SaveAs("S2S9_vs_phi.png");
  
  TH2F *h_S4S9_phi = hdata->createHistogram(*scphiiYvar, *S4S9var, "","S4S9_vs_phi");
  h_S4S9_phi->GetYaxis()->SetTitle("S4S9"); 
  if(EEorEB=="EB")
  {
  h_CC_phi->GetYaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_CC_phi->GetYaxis()->SetTitle("iY");
  }
  h_S4S9_phi->Draw("COLZ");
  myC_variables->SaveAs("S4S9_vs_phi.pdf");
  myC_variables->SaveAs("S4S9_vs_phi.png");
  
 
  if(EEorEB=="EE")
{

}
	
  TProfile *p_CC_eta = h_CC_eta->ProfileX("p_CC_eta");//,1,-1,"s");
  p_CC_eta->GetYaxis()->SetRangeUser(0.8,1.05);
  if(EEorEB == "EB")
  {
//   p_CC_eta->GetYaxis()->SetRangeUser(0.85,1.0);
//   p_CC_eta->GetXaxis()->SetRangeUser(-1.5,1.5);
  }
  p_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  p_CC_eta->SetTitle("");
  p_CC_eta->Draw();
  myC_variables->SaveAs("profile_cor_vs_eta.pdf"); 
  myC_variables->SaveAs("profile_cor_vs_eta.png"); 

  gStyle->SetOptStat(111);
  gStyle->SetOptFit(1);
  TH1F *h1_fit_CC_eta = new TH1F("h1_fit_CC_eta","h1_fit_CC_eta",(EEorEB=="EB") ? 180 : 50,(EEorEB=="EB") ? -90 : 0, (EEorEB=="EB") ? 90 : 50);

  for(int ix = 1;ix <= h_CC_eta->GetNbinsX(); ix++)
  {
        stringstream os_iEta;
        os_iEta << ((EEorEB=="EB") ? (-90 + ix -1) : (0 + ix -1));
        string ss_iEta = os_iEta.str();
        TH1D * h_temp = h_CC_eta->ProjectionY("h_temp",ix,ix);
        h_temp->Rebin(4);
        TF1 *f_temp = new TF1("f_temp","gaus(0)",0.95,1.07);
        h_temp->Fit("f_temp","R");
        h1_fit_CC_eta->SetBinContent(ix, f_temp->GetParameter(1));
        h1_fit_CC_eta->SetBinError(ix, f_temp->GetParError(1));
	h_temp->GetXaxis()->SetTitle("E_{cor}/E_{true}");
        h_temp->SetTitle("");
        h_temp->Draw();
        myC_variables->SaveAs(("fits/CC_iEta_"+ss_iEta+".pdf").c_str());
        myC_variables->SaveAs(("fits/CC_iEta_"+ss_iEta+".png").c_str());
        myC_variables->SaveAs(("fits/CC_iEta_"+ss_iEta+".C").c_str());
  }
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_CC_eta->GetYaxis()->SetRangeUser(0.95,1.05);
  h1_fit_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  h1_fit_CC_eta->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#eta" : "iX");
  h1_fit_CC_eta->SetTitle("");
  h1_fit_CC_eta->Draw();
  myC_variables->SaveAs("profile_fit_cor_vs_eta.pdf");
  myC_variables->SaveAs("profile_fit_cor_vs_eta.png");
  myC_variables->SaveAs("profile_fit_cor_vs_eta.C");
 
 
  TProfile *p_RC_eta = h_RC_eta->ProfileX("p_RC_eta");//,1,-1,"s");
  p_RC_eta->GetYaxis()->SetRangeUser(0.8,1.05);
  if(EEorEB=="EB")
  {
//   p_RC_eta->GetYaxis()->SetRangeUser(0.80,0.95);
  // p_RC_eta->GetXaxis()->SetRangeUser(-1.5,1.5);
  }
  p_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  p_RC_eta->SetTitle("");
  p_RC_eta->Draw();
  myC_variables->SaveAs("profile_raw_vs_eta.pdf"); 
  myC_variables->SaveAs("profile_raw_vs_eta.png"); 

  gStyle->SetOptStat(111);
  gStyle->SetOptFit(1);
  TH1F *h1_fit_RC_eta = new TH1F("h1_fit_RC_eta","h1_fit_RC_eta",(EEorEB=="EB") ? 180 : 50,(EEorEB=="EB") ? -90 : 0, (EEorEB=="EB") ? 90 : 50);
  for(int ix = 1;ix <= h_RC_eta->GetNbinsX(); ix++)
  {
        stringstream os_iEta;
        os_iEta << ((EEorEB=="EB") ? (-90 + ix -1) : (0 + ix -1));
        string ss_iEta = os_iEta.str();
        TH1D * h_temp = h_RC_eta->ProjectionY("h_temp",ix,ix);
        h_temp->Rebin(4);
        TF1 *f_temp = new TF1("f_temp","gaus(0)",0.87,1.05);
        h_temp->Fit("f_temp","R");

        h1_fit_RC_eta->SetBinContent(ix, f_temp->GetParameter(1));
        h1_fit_RC_eta->SetBinError(ix, f_temp->GetParError(1));
	h_temp->GetXaxis()->SetTitle("E_{raw}/E_{true}");
        h_temp->SetTitle("");
        h_temp->Draw();

        myC_variables->SaveAs(("fits/RC_iEta_"+ss_iEta+".pdf").c_str());
        myC_variables->SaveAs(("fits/RC_iEta_"+ss_iEta+".png").c_str());
        myC_variables->SaveAs(("fits/RC_iEta_"+ss_iEta+".C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_RC_eta->GetYaxis()->SetRangeUser(0.9,1.0);
  h1_fit_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  h1_fit_RC_eta->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#eta" : "iX");
  h1_fit_RC_eta->SetTitle("");
  h1_fit_RC_eta->Draw();
  myC_variables->SaveAs("profile_fit_raw_vs_eta.pdf");
  myC_variables->SaveAs("profile_fit_raw_vs_eta.png");
  myC_variables->SaveAs("profile_fit_raw_vs_eta.C");



  int Nbins_iEta = EEorEB=="EB" ? 180 : 50;
  int nLow_iEta  = EEorEB=="EB" ? -90 : 0;
  int nHigh_iEta = EEorEB=="EB" ? 90 : 50;
  
  TH1F *h1_RC_eta = new TH1F("h1_RC_eta","h1_RC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  for(int i=1;i<=Nbins_iEta;i++)
  {
    h1_RC_eta->SetBinContent(i,p_RC_eta->GetBinError(i)); 
  } 
  h1_RC_eta->GetXaxis()->SetTitle("i#eta");
  h1_RC_eta->GetYaxis()->SetTitle("#sigma_{E_{raw}/E_{true}}");
  h1_RC_eta->SetTitle("");
  h1_RC_eta->Draw();
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_eta.png");
 
  TH1F *h1_CC_eta = new TH1F("h1_CC_eta","h1_CC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  for(int i=1;i<=Nbins_iEta;i++)
  {
    h1_CC_eta->SetBinContent(i,p_CC_eta->GetBinError(i)); 
  } 
  h1_CC_eta->GetXaxis()->SetTitle("i#eta");
  h1_CC_eta->GetYaxis()->SetTitle("#sigma_{E_{cor}/E_{true}}");
  h1_CC_eta->SetTitle("");
  h1_CC_eta->Draw();
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_eta.png");
 
  TProfile *p_CC_phi = h_CC_phi->ProfileX("p_CC_phi");//,1,-1,"s");
  p_CC_phi->GetYaxis()->SetRangeUser(0.9,1.0);
  if(EEorEB == "EB")
  {
//   p_CC_phi->GetYaxis()->SetRangeUser(0.94,1.00);
  }
  p_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  p_CC_phi->SetTitle("");
  p_CC_phi->Draw();
  myC_variables->SaveAs("profile_cor_vs_phi.pdf"); 
  myC_variables->SaveAs("profile_cor_vs_phi.png"); 
 
  gStyle->SetOptStat(111);
  gStyle->SetOptFit(1);
  TH1F *h1_fit_CC_phi = new TH1F("h1_fit_CC_phi","h1_fit_CC_phi",(EEorEB=="EB") ? 360 : 50,(EEorEB=="EB") ? 0 : 0, (EEorEB=="EB") ? 360 : 50);
  for(int ix = 1;ix <= h_CC_phi->GetNbinsX(); ix++)
  {
        stringstream os_iPhi;
        os_iPhi << ((EEorEB=="EB") ? (0 + ix -1) : (0 + ix -1));
        string ss_iPhi = os_iPhi.str();
        TH1D * h_temp = h_CC_phi->ProjectionY("h_temp",ix,ix);
        h_temp->Rebin(4);
        TF1 *f_temp = new TF1("f_temp","gaus(0)",0.95,1.07);
        h_temp->Fit("f_temp","R");

        h1_fit_CC_phi->SetBinContent(ix, f_temp->GetParameter(1));
        h1_fit_CC_phi->SetBinError(ix, f_temp->GetParError(1));
	h_temp->GetXaxis()->SetTitle("E_{cor}/E_{true}");
        h_temp->SetTitle("");
        h_temp->Draw();

        myC_variables->SaveAs(("fits/CC_iPhi_"+ss_iPhi+".pdf").c_str());
        myC_variables->SaveAs(("fits/CC_iPhi_"+ss_iPhi+".png").c_str());
        myC_variables->SaveAs(("fits/CC_iPhi_"+ss_iPhi+".C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_CC_phi->GetYaxis()->SetRangeUser(0.95,1.05);
  h1_fit_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  h1_fit_CC_phi->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#phi" : "iX");
  h1_fit_CC_phi->SetTitle("");
  h1_fit_CC_phi->Draw();
  myC_variables->SaveAs("profile_fit_cor_vs_phi.pdf");
  myC_variables->SaveAs("profile_fit_cor_vs_phi.png");
  myC_variables->SaveAs("profile_fit_cor_vs_phi.C");


 
  TProfile *p_RC_phi = h_RC_phi->ProfileX("p_RC_phi");//,1,-1,"s");
  p_RC_phi->GetYaxis()->SetRangeUser(0.8,0.9);
  if(EEorEB=="EB")
  {
 //  p_RC_phi->GetYaxis()->SetRangeUser(0.89,0.95);
  }
  p_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  p_RC_phi->SetTitle("");
  p_RC_phi->Draw();
  myC_variables->SaveAs("profile_raw_vs_phi.pdf"); 
  myC_variables->SaveAs("profile_raw_vs_phi.png"); 


  gStyle->SetOptStat(111);
  gStyle->SetOptFit(1);
  TH1F *h1_fit_RC_phi = new TH1F("h1_fit_RC_phi","h1_fit_RC_phi",(EEorEB=="EB") ? 360 : 50,(EEorEB=="EB") ? 0 : 0, (EEorEB=="EB") ? 360 : 50);
  for(int ix = 1;ix <= h_RC_phi->GetNbinsX(); ix++)
  {
        stringstream os_iPhi;
        os_iPhi << ((EEorEB=="EB") ? (0 + ix -1) : (0 + ix -1));
        string ss_iPhi = os_iPhi.str();
        TH1D * h_temp = h_RC_phi->ProjectionY("h_temp",ix,ix);
        h_temp->Rebin(4);
        TF1 *f_temp = new TF1("f_temp","gaus(0)",0.87,1.05);
        h_temp->Fit("f_temp","R");

        h1_fit_RC_phi->SetBinContent(ix, f_temp->GetParameter(1));
        h1_fit_RC_phi->SetBinError(ix, f_temp->GetParError(1));
	h_temp->GetXaxis()->SetTitle("E_{raw}/E_{true}");
        h_temp->SetTitle("");
        h_temp->Draw();

        myC_variables->SaveAs(("fits/RC_iPhi_"+ss_iPhi+".pdf").c_str());
        myC_variables->SaveAs(("fits/RC_iPhi_"+ss_iPhi+".png").c_str());
        myC_variables->SaveAs(("fits/RC_iPhi_"+ss_iPhi+".C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_RC_phi->GetYaxis()->SetRangeUser(0.9,1.0);
  h1_fit_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  h1_fit_RC_phi->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#phi" : "iX");
  h1_fit_RC_phi->SetTitle("");
  h1_fit_RC_phi->Draw();
  myC_variables->SaveAs("profile_fit_raw_vs_phi.pdf");
  myC_variables->SaveAs("profile_fit_raw_vs_phi.png");
  myC_variables->SaveAs("profile_fit_raw_vs_phi.C");


  int Nbins_iPhi = EEorEB=="EB" ? 360 : 50;
  int nLow_iPhi  = EEorEB=="EB" ? 0 : 0;
  int nHigh_iPhi = EEorEB=="EB" ? 360 : 50;
  
  TH1F *h1_RC_phi = new TH1F("h1_RC_phi","h1_RC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  for(int i=1;i<=Nbins_iPhi;i++)
  {
    h1_RC_phi->SetBinContent(i,p_RC_phi->GetBinError(i)); 
  } 
  h1_RC_phi->GetXaxis()->SetTitle("i#phi");
  h1_RC_phi->GetYaxis()->SetTitle("#sigma_{E_{raw}/E_{true}}");
  h1_RC_phi->SetTitle("");
  h1_RC_phi->Draw();
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_phi.png");
 
  TH1F *h1_CC_phi = new TH1F("h1_CC_phi","h1_CC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  for(int i=1;i<=Nbins_iPhi;i++)
  {
    h1_CC_phi->SetBinContent(i,p_CC_phi->GetBinError(i)); 
  } 
  h1_CC_phi->GetXaxis()->SetTitle("i#phi");
  h1_CC_phi->GetYaxis()->SetTitle("#sigma_{E_{cor}/E_{true}}");
  h1_CC_phi->SetTitle("");
  h1_CC_phi->Draw();
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_phi.png");


// FWHM over sigma_eff vs. eta/phi
   
  TH1F *h1_FoverS_RC_phi = new TH1F("h1_FoverS_RC_phi","h1_FoverS_RC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  TH1F *h1_FoverS_CC_phi = new TH1F("h1_FoverS_CC_phi","h1_FoverS_CC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  TH1F *h1_FoverS_RC_eta = new TH1F("h1_FoverS_RC_eta","h1_FoverS_RC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  TH1F *h1_FoverS_CC_eta = new TH1F("h1_FoverS_CC_eta","h1_FoverS_CC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  TH1F *h1_FoverS_CC_S2S9 = new TH1F("h1_FoverS_CC_S2S9","h1_FoverS_CC_S2S9",Nbins_S2S9,Low_S2S9,High_S2S9);
  TH1F *h1_FoverS_RC_S2S9 = new TH1F("h1_FoverS_RC_S2S9","h1_FoverS_RC_S2S9",Nbins_S2S9,Low_S2S9,High_S2S9);
  TH1F *h1_FoverS_CC_S4S9 = new TH1F("h1_FoverS_CC_S4S9","h1_FoverS_CC_S4S9",Nbins_S4S9,Low_S4S9,High_S4S9);
  TH1F *h1_FoverS_RC_S4S9 = new TH1F("h1_FoverS_RC_S4S9","h1_FoverS_RC_S4S9",Nbins_S4S9,Low_S4S9,High_S4S9);

  float FWHMoverSigmaEff = 0.0;  
  TH1F *h_tmp_rawvar = new TH1F("tmp_rawvar","tmp_rawvar",800,0.5,1.5);
  TH1F *h_tmp_corvar = new TH1F("tmp_corvar","tmp_corvar",800,0.5,1.5);

  for(int i=1;i<=Nbins_iPhi;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_phi->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_phi->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_phi->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_phi->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_phi->GetXaxis()->SetTitle("i#phi");
  h1_FoverS_CC_phi->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_phi->SetTitle("");
  h1_FoverS_CC_phi->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_phi.png");

  h1_FoverS_RC_phi->GetXaxis()->SetTitle("i#phi");
  h1_FoverS_RC_phi->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_phi->SetTitle("");
  h1_FoverS_RC_phi->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_phi.png");


  for(int i=1;i<=Nbins_iEta;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_eta->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_eta->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_eta->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_eta->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_eta->GetXaxis()->SetTitle("i#eta");
  h1_FoverS_CC_eta->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_eta->SetTitle("");
  h1_FoverS_CC_eta->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_eta.png");

  h1_FoverS_RC_eta->GetXaxis()->SetTitle("i#eta");
  h1_FoverS_RC_eta->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_eta->SetTitle("");
  h1_FoverS_RC_eta->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_eta.png");


  for(int i=1;i<=Nbins_S2S9;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_S2S9->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_S2S9->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_S2S9->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_S2S9->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_S2S9->GetXaxis()->SetTitle("S2S9");
  h1_FoverS_CC_S2S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_S2S9->GetYaxis()->SetRangeUser(0.0,1.0);
  h1_FoverS_CC_S2S9->SetTitle("");
  h1_FoverS_CC_S2S9->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S2S9.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S2S9.png");

  h1_FoverS_RC_S2S9->GetXaxis()->SetTitle("S2S9");
  h1_FoverS_RC_S2S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_S2S9->GetYaxis()->SetRangeUser(0.0,2.0);
  h1_FoverS_RC_S2S9->SetTitle("");
  h1_FoverS_RC_S2S9->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S2S9.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S2S9.png");


  for(int i=1;i<=Nbins_S4S9;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_S4S9->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_S4S9->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_S4S9->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_S4S9->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_S4S9->GetXaxis()->SetTitle("S4S9");
  h1_FoverS_CC_S4S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_S4S9->GetYaxis()->SetRangeUser(0.0,1.0);
  h1_FoverS_CC_S4S9->SetTitle("");
  h1_FoverS_CC_S4S9->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S4S9.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S4S9.png");

  h1_FoverS_RC_S4S9->GetXaxis()->SetTitle("S4S9");
  h1_FoverS_RC_S4S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_S4S9->GetYaxis()->SetRangeUser(0.0,2.0);
  h1_FoverS_RC_S4S9->SetTitle("");
  h1_FoverS_RC_S4S9->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S4S9.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S4S9.png");




  printf("calc effsigma\n");
  std::cout<<"_"<<EEorEB<<std::endl;
  printf("corrected curve effSigma= %5f, FWHM=%5f \n",effsigma_cor, fwhm_cor);
  printf("raw curve effSigma= %5f FWHM=%5f \n",effsigma_raw, fwhm_raw);

  
/*  new TCanvas;
  RooPlot *ploteold = testvar.frame(0.6,1.2,100);
  hdatasigtest->plotOn(ploteold);
  ploteold->Draw();    
  
  new TCanvas;
  RooPlot *plotecor = ecorvar->frame(0.6,1.2,100);
  hdatasig->plotOn(plotecor);
  plotecor->Draw(); */   
  
  
}
コード例 #29
0
void AllInOne_combineLepton(const std::string& dataset,int btag=0, double timesX=1, bool useNewShape=false){

  std::string useNewShapeText = (useNewShape) ? "_newshape" : "";

  char wsFileName[700];
  sprintf(wsFileName,"datacards/400/hzz2l2q_ee%db.input.root",btag);
  //sprintf(wsFileName,"PROVA/datacards_%s%s/hzz2l2q_ee%db.input.root",dataset.c_str(), useNewShapeText.c_str(),btag);

  gSystem->Load("libRooFit");
  gSystem->Load("libFFTW");

  string histoName[3];
  histoName[0]="mZZ_kinfit_hiMass_0btag";
  histoName[1]="mZZ_kinfit_hiMass_1btag";
  histoName[2]="mZZ_kinfit_hiMass_2btag";
  string btagName[3]={"0b","1b","2b"};

  double LumiScale=0.;
  if( dataset=="Run2011A_FULL" ) LumiScale = 2100.;
  else if( dataset=="LP11" ) LumiScale = 1600.;
  else {
    std::cout << "Unknown dataset '" << dataset << "'. Exiting." << std::endl;
  }

  RooDataSet *data_bkg;  
  RooDataSet *data_temp;
  TFile *file;

  string cutString[3];
  cutString[0]="nBTags==0 && (mZjj>75 && mZjj<105) && mZZ>183";
  cutString[1]="nBTags==1 && (mZjj>75 && mZjj<105) && mZZ>183";
  cutString[2]="nBTags==2 && (mZjj>75 && mZjj<105) && mZZ>183";

  int binWidth=20;
  int highBin=750;
  int lowBin=150;

//double muonEff[3]={.576,.548,.489};

//double expSig[3];
//expSig[0]=5.65*LumiScale ;
//expSig[1]=4.89*LumiScale ;
//expSig[2]=2.37*LumiScale ;

  char alphaFileName[200];
  sprintf( alphaFileName, "alphaFile_%s_%dbtag_ALL.root", dataset.c_str(), btag);
  TFile* alphaFile = TFile::Open(alphaFileName);
  TTree* treeSidebandsDATA_alphaCorr = (TTree*)alphaFile->Get("sidebandsDATA_alpha");
  TH1D* h1_mZZ_sidebands_alpha = new TH1D("mZZ_sidebands_alpha", "", 65, 150., 800.);
  char sidebandsCut_alpha[500];
  sprintf(sidebandsCut_alpha, "eventWeight_alpha*(isSidebands && nBTags==%d)", btag);
  treeSidebandsDATA_alphaCorr->Project("mZZ_sidebands_alpha", "mZZ", sidebandsCut_alpha);
  float expBkg = h1_mZZ_sidebands_alpha->Integral();
  std::cout <<  "++++ expBkg: " << expBkg << std::endl;



  stringstream convert;

  // --------------------- measurable (ZZ invariant mass) ----------------
  string temp;
  temp="m_{ZZ}";
  RooRealVar mZZ("mZZ",temp.c_str(),lowBin,highBin);
  RooRealVar nBTags("nBTags","nBTags",-1.,3.);
  RooRealVar leptType("leptType","leptType",0,1);
  RooRealVar mZjj("mZjj","mZjj",0,200.);

  // ----------------- get parameters from data cards! -----------------
  
  TFile *wsFile = new TFile(wsFileName);
  RooWorkspace *ws = (RooWorkspace*) wsFile->Get("w");

  // ==================== defining bkg PDF ==========================
  // ------------------------ fermi ------------------------------
  RooRealVar cutOff("cutOff","position of fermi",ws->var("cutOff_BKG")->getVal());
  cutOff.setConstant(kTRUE);
  RooRealVar beta("beta","width of fermi",ws->var("beta_BKG")->getVal());
  beta.setConstant(kTRUE);
	     		       
  RooFermi fermi("fermi","fermi function",mZZ,cutOff,beta);
  // -------------------- double gauss ---------------------------
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p1";
  RooRealVar m("m","m",ws->var(temp.c_str())->getVal());
  m.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p2";
  RooRealVar wdth("wdth","wdth",ws->var(temp.c_str())->getVal());
  wdth.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p3";
  RooRealVar n("n","n",ws->var(temp.c_str())->getVal());
  n.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p4";
  RooRealVar alpha("alpha","alpha",ws->var(temp.c_str())->getVal());
  alpha.setConstant(kTRUE);
  temp="CMS_hzz2l2q_bkg"+btagName[btag]+"p5";
  RooRealVar theta("theta","theta",ws->var(temp.c_str())->getVal());
  theta.setConstant(kTRUE);

  RooCB CB("CB","Crystal ball",mZZ,m,wdth,alpha,n,theta);
  
  RooProdPdf background("background","background",RooArgSet(fermi,CB));


  // ------------------ get data --------------------------
  // for reading sideband extrapolated data...
  std::string fileName = "HZZlljjRM_DATA_" + dataset + "_optLD_looseBTags_v2_ALL.root";
  file = new TFile(fileName.c_str());
  //file = new TFile("../HZZlljjRM_DATA_Run2011A_FULL_optLD_looseBTags_v2_ALL.root");
  TTree* t=(TTree*)file->Get("tree_passedEvents");
  data_bkg=new RooDataSet("data_bkg","data_bkg",t,
			  RooArgSet(mZZ,leptType,nBTags,mZjj),
			  cutString[btag].c_str());

  // --------- draw MC data -------------------
  RooPlot *plot_MCbkg = mZZ.frame(lowBin,highBin,(int)(highBin-lowBin)/binWidth);

  //-----------------------------------------------------------------------
  TCanvas *c2 = new TCanvas("c2","c2",600,600);

  TPaveText* cmslabel = new TPaveText( 0.145, 0.953, 0.6, 0.975, "brNDC" );
  cmslabel->SetFillColor(kWhite);
  cmslabel->SetTextSize(0.038);
  cmslabel->SetTextAlign(11);
  cmslabel->SetTextFont(62);
  cmslabel->SetBorderSize(0);
  char lumilabel[500];
  sprintf( lumilabel, "CMS Preliminary 2011, %.1f fb^{-1}", LumiScale/1000.);
  cmslabel->AddText(lumilabel);

  TPaveText* label_sqrt = new TPaveText(0.7,0.953,0.96,0.975, "brNDC");
  label_sqrt->SetFillColor(kWhite);
  label_sqrt->SetTextSize(0.038);
  label_sqrt->SetTextFont(42);
  label_sqrt->SetTextAlign(31); // align right
  label_sqrt->SetBorderSize(0);
  label_sqrt->AddText("#sqrt{s} = 7 TeV");
  //-----------------------------------------------------------------------

  background.plotOn(plot_MCbkg,Normalization(expBkg));
  data_bkg->plotOn(plot_MCbkg,Binning((int)(highBin-lowBin)/binWidth));
  // -------------------- get histograms -----------------
  
  TFile *ZjetsFile = new TFile("HZZlljjRM_DYJetsToLL_TuneZ2_M-50_7TeV-madgraph-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *TTFile = new TFile("HZZlljjRM_TT_TW_TuneZ2_7TeV-powheg-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *VVFile = new TFile("HZZlljjRM_VV_TuneZ2_7TeV-pythia6-tauola_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");
  TFile *H400File = new TFile("HZZlljjRM_GluGluToHToZZTo2L2Q_M-400_7TeV-powheg-pythia6_Summer11-PU_S4_START42_V11-v1_optLD_looseBTags_v2_ALL.root");

  TH1F *hZjets =(TH1F*)ZjetsFile->Get(histoName[btag].c_str());
  hZjets->SetName("hZjets");
  hZjets->Scale(LumiScale);
  hZjets->Rebin(binWidth);
  hZjets->SetFillColor(30);

  TH1F *hTT =(TH1F*)TTFile->Get(histoName[btag].c_str());
  hTT->SetName("hTT");
  convert << binWidth;
  temp=";m_{ZZ} [GeV]; Events / "+convert.str()+" GeV";
  hTT->SetTitle(temp.c_str());
  hTT->Scale(LumiScale);
  hTT->Rebin(binWidth);
  hTT->SetFillColor(39);
  gStyle->SetOptStat(0);

  //if(btag==0)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,245);
  //if(btag==1)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,245);
  //if(btag==2)
  //  hTT->GetYaxis()->SetRangeUser(0.0001,25);

  //hTT->Draw();


  TH1F *hVV =(TH1F*)VVFile->Get(histoName[btag].c_str());
  hVV->SetName("hVV");
  hVV->Scale(LumiScale);
  hVV->Rebin(binWidth);
  hVV->SetFillColor(38);

  TH1F* hH400 = (TH1F*)H400File->Get(histoName[btag].c_str());
  hH400->SetName("hH400");
  hH400->Scale(LumiScale*timesX);
  cout << "SIGNAL NORMALIZATION: " << hH400->Integral() << endl;
  hH400->Rebin(binWidth);
  hH400->SetFillColor(kYellow);//kRed+3);

  temp = ";m_{ZZ} [GeV];Events / "+convert.str()+" GeV";
  THStack *hBkg = new THStack("hBkg",temp.c_str());
  convert.str("");

  hBkg->Add(hVV);
  hBkg->Add(hTT);
  hBkg->Add(hZjets);
  hBkg->Add(hH400);

  float xMin = 150.;
  float xMax = 750.;
  float yMin = 0.;
  float yMax = 1.3*hBkg->GetMaximum();

  char yAxisName[500];
  sprintf( yAxisName, "Events / %.0f GeV", hVV->GetXaxis()->GetBinWidth(1) );
  //std::string yAxisName = "Events / "+convert.str()+" GeV";
  convert.str("");

//char xAxisName[400];
//sprintf( xAxisName, "m_{%s%sjj} [GeV]", leptType_forLegend.c_str(), leptType_forLegend.c_str() );

  TH2D* h2_axes = new TH2D("axes", "", 10, xMin, xMax, 10, yMin, yMax);
  h2_axes->SetXTitle("m_{lljj} [GeV]");
  h2_axes->SetYTitle(yAxisName);
  h2_axes->Draw();

  hBkg->Draw("SAMEHIST");
  plot_MCbkg->Draw("SAME");
  cmslabel->Draw();
  label_sqrt->Draw();
  // ---------------legend ---------------------------

  TLegend *leg = new TLegend(.4,.5,.8,.9);
  leg->SetTextSize(0.036);
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  convert.str("");
  convert << LumiScale/1000;
  temp="CMS Preliminary #sqrt{s}=7 TeV "+convert.str()+" fb^{-1}";
  //leg->SetHeader(temp.c_str());
  leg->AddEntry("background_Norm[mZZ]","Sideband Extrapolated Fit","l");
  //leg->AddEntry("model_Norm[mZZ]","Background+10#timesSignal","l");

  if(btag==0)
    temp="0 b-tag 2l2q data";
  if(btag==1)
    temp="1 b-tag 2l2q data";
  if(btag==2)
    temp="2 b-tag 2l2q data";

  leg->AddEntry("h_data_bkg",temp.c_str(),"p");
  leg->AddEntry("hZjets","Z + Jets","f");
  leg->AddEntry("hTT","tt/tW","f");
  leg->AddEntry("hVV","ZZ/WZ/WW","f");
  convert.str("");
  convert << timesX;
  temp="400 GeV SM Higgs#times"+convert.str();
  leg->AddEntry("hH400",temp.c_str(),"f");
  leg->Draw();

  string saveFileName="AllInOne_"+dataset + "_"+btagName[btag]+"tag_ll_LIMIT" + useNewShapeText + ".eps";

  c2->SaveAs(saveFileName.c_str()); 

}
コード例 #30
0
void makejpsifit(string inputFilename, string outFilename, 
		 Int_t ptBin, Int_t etaBin,
		 double minMass, double maxMass, 
		 double mean_bw, double gamma_bw, double cutoff_cb, double power_cb, 
		 const char* plotOpt, const int nbins, Int_t isMC) {

  TStyle *mystyle = RooHZZStyle("ZZ");
  mystyle->cd();

  //Create Data Set
  RooRealVar mass("zmass","m(e^{+}e^{-})",minMass,maxMass,"GeV/c^{2}");

  // Reading everything from root tree instead
  TFile *tfile = TFile::Open(inputFilename.c_str());
  TTree *ttree = (TTree*)tfile->Get("zeetree/probe_tree");
  hzztree *zeeTree = new hzztree(ttree);

  RooArgSet zMassArgSet(mass);
  RooDataSet* data = new RooDataSet("data", "ntuple parameters", zMassArgSet);

  for (int i = 0; i < zeeTree->fChain->GetEntries(); i++) {
    if(i%100000==0) cout << "Processing Event " << i << endl;
    zeeTree->fChain->GetEntry(i);

    //*************************************************************************
    //Electron Selection
    //*************************************************************************
    // already passed for this tree

    //*************************************************************************
    //Compute electron four vector;
    //*************************************************************************
    double ele1pt = zeeTree->l1pt;
    double ele2pt = zeeTree->l2pt;

    double ELECTRONMASS = 0.51e-3;
    TLorentzVector ele1FourVector;
    ele1FourVector.SetPtEtaPhiM(zeeTree->l1pt, zeeTree->l1eta, zeeTree->l1phi, ELECTRONMASS);
    TLorentzVector ele2FourVector;
    ele2FourVector.SetPtEtaPhiM(zeeTree->l2pt, zeeTree->l2eta, zeeTree->l2phi, ELECTRONMASS);

    
    //*************************************************************************
    //pt and eta cuts on electron
    //*************************************************************************
    if (! (ele1pt > 7 && ele2pt > 7
           && fabs( zeeTree->l1eta) < 2.5 
           && fabs( zeeTree->l2eta) < 2.5 )) continue;

    //*************************************************************************
    //pt bins and eta bins
    //*************************************************************************
    Int_t Ele1PtBin = -1;
    Int_t Ele1EtaBin = -1;
    Int_t Ele2PtBin = -1;
    Int_t Ele2EtaBin = -1;
    if (ele1pt > 7 && ele1pt < 10) Ele1PtBin = 0;
    else if (ele1pt < 20) Ele1PtBin = 1;
    else Ele1PtBin = 2;
    if (ele2pt > 7 && ele2pt < 10) Ele2PtBin = 0;
    else if (ele2pt < 20) Ele2PtBin = 1;
    else Ele2PtBin = 2;
    if (fabs(zeeTree->l1sceta) < 1.479) Ele1EtaBin = 0;
    else Ele1EtaBin = 1;
    if (fabs(zeeTree->l2sceta) < 1.479) Ele2EtaBin = 0;
    else Ele2EtaBin = 1;

    if (!(Ele1PtBin == ptBin || Ele2PtBin == ptBin)) continue; 
    if (!(Ele1EtaBin == etaBin && Ele2EtaBin == etaBin)) continue; 
    
    //*************************************************************************
    // restrict range of mass
    //*************************************************************************
    double zMass = (ele1FourVector+ele2FourVector).M();
    if (zMass < minMass || zMass > maxMass) continue;

    //*************************************************************************
    //set mass variable
    //*************************************************************************
    zMassArgSet.setRealValue("zmass", zMass);    

    data->add(zMassArgSet);
  }

  // do binned fit to gain time...
  mass.setBins(nbins);
  RooDataHist *bdata = new RooDataHist("data_binned","data_binned", zMassArgSet, *data);

  cout << "dataset size: " << data->numEntries() << endl;

//   // Closing file
//   treeFile->Close();
  //====================== Parameters===========================

  //Crystal Ball parameters
//   RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
//   RooRealVar cbSigma("sigma_{CB}", "CB Width", 1.7, 0.8, 5.0, "GeV/c^{2}");
//   RooRealVar cbCut  ("a_{CB}","CB Cut", 1.05, 1.0, 3.0);
//   RooRealVar cbPower("n_{CB}","CB Order", 2.45, 0.1, 20.0);
  RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
  RooRealVar cbSigma("#sigma_{CB}", "CB Width", 1.5, 0.01, 5.0, "GeV/c^{2}");
  RooRealVar cbCut  ("a_{CB}","CB Cut", 1.0, 1.0, 3.0);
  RooRealVar cbPower("n_{CB}","CB Order", 2.5, 0.1, 20.0);
  cbCut.setVal(cutoff_cb);
  cbPower.setVal(power_cb);

  // Just checking
  //cbCut.Print();
  //cbPower.Print();

  //Breit_Wigner parameters
  RooRealVar bwMean("m_{JPsi}","BW Mean", 3.096916, "GeV/c^{2}");
  bwMean.setVal(mean_bw);
  RooRealVar bwWidth("#Gamma_{JPsi}", "BW Width", 92.9e-6, "GeV/c^{2}");
  bwWidth.setVal(gamma_bw);

  // Fix the Breit-Wigner parameters to PDG values
  bwMean.setConstant(kTRUE);
  bwWidth.setConstant(kTRUE);

  // Exponential Background parameters
  RooRealVar expRate("#lambda_{exp}", "Exponential Rate", -0.064, -1, 1);
  RooRealVar c0("c_{0}", "c0", 1., 0., 50.);

  //Number of Signal and Background events
  RooRealVar nsig("N_{S}", "# signal events", 524, 0.1, 10000000000.);
  RooRealVar nbkg("N_{B}", "# background events", 43, 1., 10000000.);

  //============================ P.D.F.s=============================

  // Mass signal for two decay electrons p.d.f.
  RooBreitWigner bw("bw", "bw", mass, bwMean, bwWidth);
  RooCBShape  cball("cball", "Crystal Ball", mass, cbBias, cbSigma, cbCut, cbPower);
  RooFFTConvPdf BWxCB("BWxCB", "bw X crystal ball", mass, bw, cball);

  // Mass background p.d.f.
  RooExponential bg("bg", "exp. background", mass, expRate);

  // Mass model for signal electrons p.d.f.
  RooAddPdf model("model", "signal", RooArgList(BWxCB), RooArgList(nsig));

  TStopwatch t ;
  t.Start() ;
  double fitmin, fitmax;
  if(isMC) {
    fitmin = (etaBin==0) ? 3.00 : 2.7;
    fitmax = (etaBin==0) ? 3.20 : 3.4;
  } else {
    fitmin = (etaBin==0) ? ( (ptBin>=2) ? 3.01 : 3.02 ) : 2.7;
    fitmax = (etaBin==0) ? ( (ptBin==3) ? 3.23 : 3.22 ) : 3.4;
  }
  RooFitResult *fitres = model.fitTo(*bdata,Range(fitmin,fitmax),Hesse(1),Minos(1),Timer(1),Save(1));
  fitres->SetName("fitres");
  t.Print() ;

  TCanvas* c = new TCanvas("c","Unbinned Invariant Mass Fit", 0,0,800,600);

  //========================== Plotting  ============================
  //Create a frame
  RooPlot* plot = mass.frame(Range(minMass,maxMass),Bins(nbins));
  // Add data and model to canvas
  int col = (isMC ? kAzure+4 : kGreen+1);
  data->plotOn(plot);
  model.plotOn(plot,LineColor(col));
  data->plotOn(plot);
  model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(cbBias, cbSigma, cbCut, cbPower, bwMean, bwWidth, expRate, nsig, nbkg)), Layout(0.15,0.45,0.80));
  plot->getAttText()->SetTextSize(.03);
  plot->SetTitle("");
  plot->Draw();

  // Print Fit Values
  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(.1);
  tex->SetTextFont(132);
  //  tex->Draw();
  tex->SetTextSize(0.057);
  if(isMC) tex->DrawLatex(0.65, 0.75, "J/#psi #rightarrow e^{+}e^{-} MC");
  else tex->DrawLatex(0.65, 0.75, "J/#psi #rightarrow e^{+}e^{-} data");
  tex->SetTextSize(0.030);
  tex->DrawLatex(0.645, 0.65, Form("BW Mean = %.2f GeV/c^{2}", bwMean.getVal()));
  tex->DrawLatex(0.645, 0.60, Form("BW #sigma = %.2f GeV/c^{2}", bwWidth.getVal()));
  c->Update();
  c->SaveAs((outFilename + ".pdf").c_str());
  c->SaveAs((outFilename + ".png").c_str());

  // tablefile << Form(Outfile + "& $ %f $ & $ %f $ & $ %f $\\ \hline",cbBias.getVal(), cbSigma.getVal(), cbCut.getVal());
  // Output workspace with model and data

  RooWorkspace *w = new RooWorkspace("JPsieeMassScaleAndResolutionFit");
  w->import(model);
  w->import(*bdata);
  w->writeToFile((outFilename + ".root").c_str());  

  TFile *tfileo = TFile::Open((outFilename + ".root").c_str(),"update");
  fitres->Write();
  tfileo->Close();

}