Esempio n. 1
0
void FitterUtils::PlotShape2D(RooDataSet& originDataSet, RooDataSet& genDataSet, RooAbsPdf& shape, string plotsfile, string canvName, RooRealVar& B_plus_M, RooRealVar& misPT)
{
   //**************Prepare TFile to save the plots

   TFile f2(plotsfile.c_str(), "UPDATE");

   //**************Plot Signal Zero Gamma

   TH2F* th2fKey = (TH2F*)shape.createHistogram("th2Shape", B_plus_M, Binning(20), YVar(misPT, Binning(20)));
   cout<<genDataSet.sumEntries()<<endl;
   TH2F* th2fGen = (TH2F*)genDataSet.createHistogram("th2fGen", B_plus_M, Binning(20), YVar(misPT, Binning(20)));

   RooPlot* plotM = B_plus_M.frame();
   originDataSet.plotOn(plotM);
   shape.plotOn(plotM);

   RooPlot* plotMisPT = misPT.frame();
   originDataSet.plotOn(plotMisPT);
   shape.plotOn(plotMisPT);

   TCanvas canv(canvName.c_str(), canvName.c_str(), 800, 800);
   canv.Divide(2,2);
   canv.cd(1); th2fGen->Draw("lego");
   canv.cd(2); th2fKey->Draw("surf");
   canv.cd(3); plotM->Draw();
   canv.cd(4); plotMisPT->Draw();

   canv.Write();

   f2.Close();
}
//____________________________________
void MakePlots(RooWorkspace* wks) {

  // Make plots of the data and the best fit model in two cases:
  // first the signal+background case
  // second the background-only case.

  // get some things out of workspace
  RooAbsPdf* model = wks->pdf("model");
  RooAbsPdf* sigModel = wks->pdf("sigModel");
  RooAbsPdf* zjjModel = wks->pdf("zjjModel");
  RooAbsPdf* qcdModel = wks->pdf("qcdModel");

  RooRealVar* mu = wks->var("mu");
  RooRealVar* invMass = wks->var("invMass");
  RooAbsData* data = wks->data("data");


  //////////////////////////////////////////////////////////
  // Make plots for the Alternate hypothesis, eg. let mu float

  mu->setConstant(kFALSE);

  model->fitTo(*data,Save(kTRUE),Minos(kFALSE), Hesse(kFALSE),PrintLevel(-1));

  //plot sig candidates, full model, and individual componenets
  new TCanvas();
  RooPlot* frame = invMass->frame() ;
  data->plotOn(frame ) ;
  model->plotOn(frame) ;
  model->plotOn(frame,Components(*sigModel),LineStyle(kDashed), LineColor(kRed)) ;
  model->plotOn(frame,Components(*zjjModel),LineStyle(kDashed),LineColor(kBlack)) ;
  model->plotOn(frame,Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;

  frame->SetTitle("An example fit to the signal + background model");
  frame->Draw() ;
  //  cdata->SaveAs("alternateFit.gif");

  //////////////////////////////////////////////////////////
  // Do Fit to the Null hypothesis.  Eg. fix mu=0

  mu->setVal(0); // set signal fraction to 0
  mu->setConstant(kTRUE); // set constant

  model->fitTo(*data, Save(kTRUE), Minos(kFALSE), Hesse(kFALSE),PrintLevel(-1));

  // plot signal candidates with background model and components
  new TCanvas();
  RooPlot* xframe2 = invMass->frame() ;
  data->plotOn(xframe2, DataError(RooAbsData::SumW2)) ;
  model->plotOn(xframe2) ;
  model->plotOn(xframe2, Components(*zjjModel),LineStyle(kDashed),LineColor(kBlack)) ;
  model->plotOn(xframe2, Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;

  xframe2->SetTitle("An example fit to the background-only model");
  xframe2->Draw() ;
  //  cbkgonly->SaveAs("nullFit.gif");

}
pair<double,double> bkgEvPerGeV(RooWorkspace *work, int m_hyp, int cat, int spin=false){
  
  RooRealVar *mass = (RooRealVar*)work->var("CMS_hgg_mass");
  if (spin) mass = (RooRealVar*)work->var("mass");
  mass->setRange(100,180);
  RooAbsPdf *pdf = (RooAbsPdf*)work->pdf(Form("pdf_data_pol_model_8TeV_cat%d",cat));
  RooAbsData *data = (RooDataSet*)work->data(Form("data_mass_cat%d",cat));
  RooPlot *tempFrame = mass->frame();
  data->plotOn(tempFrame,Binning(80));
  pdf->plotOn(tempFrame);
  RooCurve *curve = (RooCurve*)tempFrame->getObject(tempFrame->numItems()-1);
  double nombkg = curve->Eval(double(m_hyp));
 
  RooRealVar *nlim = new RooRealVar(Form("nlim%d",cat),"",0.,0.,1.e5);
  //double lowedge = tempFrame->GetXaxis()->GetBinLowEdge(FindBin(double(m_hyp)));
  //double upedge  = tempFrame->GetXaxis()->GetBinUpEdge(FindBin(double(m_hyp)));
  //double center  = tempFrame->GetXaxis()->GetBinUpCenter(FindBin(double(m_hyp)));

  nlim->setVal(nombkg);
  mass->setRange("errRange",m_hyp-0.5,m_hyp+0.5);
  RooAbsPdf *epdf = 0;
  epdf = new RooExtendPdf("epdf","",*pdf,*nlim,"errRange");
		
  RooAbsReal *nll = epdf->createNLL(*data,Extended(),NumCPU(4));
  RooMinimizer minim(*nll);
  minim.setStrategy(0);
  minim.setPrintLevel(-1);
  minim.migrad();
  minim.minos(*nlim);
  
  double error = (nlim->getErrorLo(),nlim->getErrorHi())/2.;
  data->Print(); 
  return pair<double,double>(nombkg,error); 
}
Esempio n. 4
0
void rf510_wsnamedsets()
{
  // C r e a t e   m o d e l   a n d   d a t a s e t
  // -----------------------------------------------

  RooWorkspace* w = new RooWorkspace("w") ;
  fillWorkspace(*w) ;

  // Exploit convention encoded in named set "parameters" and "observables"
  // to use workspace contents w/o need for introspected
  RooAbsPdf* model = w->pdf("model") ;

  // Generate data from p.d.f. in given observables
  RooDataSet* data = model->generate(*w->set("observables"),1000) ;

  // Fit model to data
  model->fitTo(*data) ;
  
  // Plot fitted model and data on frame of first (only) observable
  RooPlot* frame = ((RooRealVar*)w->set("observables")->first())->frame() ;
  data->plotOn(frame) ;
  model->plotOn(frame) ;

  // Overlay plot with model with reference parameters as stored in snapshots
  w->loadSnapshot("reference_fit") ;
  model->plotOn(frame,LineColor(kRed)) ;
  w->loadSnapshot("reference_fit_bkgonly") ;
  model->plotOn(frame,LineColor(kRed),LineStyle(kDashed)) ;


  // Draw the frame on the canvas
  new TCanvas("rf510_wsnamedsets","rf503_wsnamedsets",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


  // Print workspace contents
  w->Print() ;


  // Workspace will remain in memory after macro finishes
  gDirectory->Add(w) ;

}
Esempio n. 5
0
void MakeSpinPlots::PlotSignalFits(TString tag, TString mcName,TString cosThetaBin){
  TCanvas cv;
  TString cat=tag;
  if(cosThetaBin!="") tag = tag+"_"+cosThetaBin;

  float mean = ws->var(Form("%s_FIT_%s_mean",mcName.Data(),tag.Data()))->getVal();
  RooPlot *frame = ws->var("mass")->frame(105,140,70);//mean-10,mean+10,40);
  RooAbsData *d = ws->data(mcName+"_Combined")->reduce(TString("evtcat==evtcat::")+cat);
  if(cosThetaBin!=""){
    TObjArray *arr = cosThetaBin.Tokenize("_");
    float low  = atof(arr->At(1)->GetName());
    float high = atof(arr->At(2)->GetName());
    d = d->reduce( Form("cosT < %0.2f && cosT >= %0.2f",high,low) );
    delete arr;
  }

  d->plotOn(frame);
  RooFitResult *res = (RooFitResult*)ws->obj(Form("%s_FIT_%s_fitResult",mcName.Data(),tag.Data()));
  RooAbsPdf * pdf = ws->pdf(Form("%s_FIT_%s",mcName.Data(),tag.Data())); //signal model
  std::cout << pdf << "\t" << res << std::endl;
  pdf->plotOn(frame,RooFit::FillColor(kGreen),RooFit::VisualizeError(*res,2.0));
  pdf->plotOn(frame,RooFit::FillColor(kYellow),RooFit::VisualizeError(*res,1.0));
  pdf->plotOn(frame,RooFit::LineColor(kRed));
  d->plotOn(frame); //data
  
  tPair lbl(mcName,tag);

  TLatex *prelim = new TLatex(0.18,0.9,"CMS Preliminary Simulation");
  TLatex *sigL  = new TLatex(0.18,0.6,Form("#sigma_{eff} = %0.2f GeV",fitSigEff[lbl].first,fitSigEff[lbl].second));
  prelim->SetNDC();
  sigL->SetNDC();
  prelim->SetTextSize(0.05);
  sigL->SetTextSize(0.05);
  
  frame->addObject(prelim);
  frame->addObject(sigL);
  frame->Draw();
  cv.SaveAs(basePath+Form("/signalModels/sig_%s_%s_%s.png",mcName.Data(),outputTag.Data(),tag.Data()));
  cv.SaveAs(basePath+Form("/signalModels/C/sig_%s_%s_%s.C",mcName.Data(),outputTag.Data(),tag.Data()));
  cv.SaveAs(basePath+Form("/signalModels/sig_%s_%s_%s.pdf",mcName.Data(),outputTag.Data(),tag.Data()));

}
Esempio n. 6
0
void JetTagBin::plotOn( RooPlot * frame )
{
  if ( verbose ) cout << "Plotting data and combined pdf" << endl;
  jtData_->plotOn(frame);
  jtPdf_ ->plotOn(frame);
  vector<Template*>::iterator i = jtTemplates_.begin(), iend = jtTemplates_.end();
  int color=1;
  for ( ; i != iend ; ++i ) {
    color++;
    if (color == 5) color++;  // only dead yellow is good yellow
    if ( verbose ) cout << "Plotting component " << (*i)->epdf()->GetName()
                        << " with color " << color << endl;
    jtPdf_->plotOn(frame,Components((*i)->epdf()->GetName()),LineColor(color));
  }                                                               
}
Esempio n. 7
0
void plotFromWorkspace() {
    TFile* file = new TFile("card_m125_1JetIncl_XX_workspace.root");

    RooWorkspace* w = (RooWorkspace*)file->Get("w");

    RooRealVar* m = (RooRealVar*)w->var("CMS_hmumu_mass");
    RooRealVar* e = (RooRealVar*)w->var("CMS_hmumu_merr");
    RooDataSet* d = (RooDataSet*)w->data("data_pseudo");
    RooAbsPdf * b = w->pdf("bkg_mass_merr_1JetIncl_XX_pdf");
    RooAbsPdf * s = w->pdf("sig_mass_merr_ggH_1JetIncl_XX_pdf");

    RooPlot* frame = m->frame();
    d->plotOn(frame);
    b->plotOn(frame);
    //s->plotOn(frame, RooFit::ProjWData(*e, *d), RooFit::LineColor(kOrange+1));
    //s->plotOn(frame, RooFit::LineColor(kOrange+1));
    frame->Draw();
}
Esempio n. 8
0
void FitterUtils::plot_fit_result(string plotsfile, RooAbsPdf &totPdf, RooDataSet dataGenTot)
{

   //**************Prepare TFile to save the plots

   TFile f2(plotsfile.c_str(), "UPDATE");
   //**************Plot the results of the fit

   RooArgSet *var_set = totPdf.getObservables(dataGenTot);
   TIterator *iter = var_set->createIterator();
   RooRealVar *var;

   std::vector<RooPlot*> plots;
   RooPlot* frame;

   while((var = (RooRealVar*) iter->Next()))
   {

      frame = var->frame();
      dataGenTot.plotOn(frame);
      totPdf.plotOn(frame, Components("histPdfPartReco"), LineColor(kBlue));
      totPdf.plotOn(frame, Components("histPdfSignalZeroGamma"), LineColor(kGreen));
      totPdf.plotOn(frame, Components("histPdfSignalOneGamma"), LineColor(kMagenta));
      totPdf.plotOn(frame, Components("histPdfSignalTwoGamma"), LineColor(kOrange));
      totPdf.plotOn(frame, Components("histPdfJpsiLeak"), LineColor(14));
      totPdf.plotOn(frame, Components("combPDF"), LineColor(kBlack));
      totPdf.plotOn(frame, LineColor(kRed));

      plots.push_back(frame);

   }  

   if (!(plots.size())) return;

   TCanvas cFit("cFit", "cFit", 600, 800);
   cFit.Divide(1,2);
   cFit.cd(1); plots[0]->Draw();
   if (plots.size()>1){ 
      cFit.cd(2); plots[1]->Draw();
   }

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


}
Esempio n. 9
0
void MCStudy()
{
    
    string fileName = "h4l_Template_2012_lowmass_unconstrained_new_v00.root";
    
    const char * wsName      = "combined";    //"w";
    const char * modelSBName = "ModelConfig"; //"modelConfig";
    const char * dataName    = dataname.c_str();
    
    TFile* file = TFile::Open(fileName);

    // get the workspace out of file
    RooWorkspace* w = (RooWorkspace*) file->Get(wsName);
    if (!wsName) {
        cout << "workspace not found" << endl;
        return -1.0;
    }
    
    // get the modelConfig out of the file
    ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);
    
    // get the data out of file
    //RooAbsData* data = w->data(dataName);
    
    // get toy MC data
    TFile *fhist = new TFile("../ToyMC/toyMC_ggF125.root");
    TH1F *hsum = (TH1F*) fhist->Get("sumtoy1");
    
    RooRealVar m4l("m4l","m4l",120,130);
    RooDataHist* data = new RooDataHist("data","data",x,hsum);
    
    // get pdf
    RooAbsPdf* model = sbModel->GetPdf();
    
    RooPlot* xframe = m4l.frame();
    data->plotOn(xframe);
    model->fitTo(*data);
    model->plotOn(xframe,LineColor(kRed));
    
    TCanvas *c = new TCanvas("c","c");
    xframe->Draw();
    
}
Esempio n. 10
0
void FitterUtils::PlotShape1D(RooDataSet& originDataSet, RooDataSet& genDataSet, RooAbsPdf& shape, string plotsfile, string canvName, RooRealVar& B_plus_M)
{
   TFile f2(plotsfile.c_str(), "UPDATE");

   RooPlot* plotGen = B_plus_M.frame(Binning(20));
   genDataSet.plotOn(plotGen);

   RooPlot* plotM = B_plus_M.frame();
   originDataSet.plotOn(plotM);
   shape.plotOn(plotM);

   TCanvas canv(canvName.c_str(), canvName.c_str(), 800, 800);
   canv.Divide(1,2);
   canv.cd(1); plotGen->Draw();
   canv.cd(2); plotM->Draw();

   canv.Write();

   f2.Close();
}
void FitterUtilsSimultaneousExpOfPolyTimesX::plot_kemu_fit_result(string plotsfile, RooAbsPdf &totKemuPdf, RooDataSet const& dataGenKemu)
{

   //**************Prepare TFile to save the plots

   TFile f2(plotsfile.c_str(), "UPDATE");
   //**************Plot the results of the fit

   RooArgSet *var_set = totKemuPdf.getObservables(dataGenKemu);
   TIterator *iter = var_set->createIterator();
   RooRealVar *var;

   std::vector<RooPlot*> plots;
   RooPlot* frame;

   while((var = (RooRealVar*) iter->Next()))
   {
      frame = var->frame();
      dataGenKemu.plotOn(frame);
      totKemuPdf.plotOn(frame, LineColor(kRed));

      plots.push_back(frame);
   }

   if (!(plots.size())) return;

   TCanvas cFit("cKemuFit", "cKemuFit", 600, 800);
   cFit.Divide(1,2);
   cFit.cd(1); plots[0]->Draw();
   if (plots.size()>1){ 
      cFit.cd(2); plots[1]->Draw();
   }

   cFit.Write();
   f2.Close();
}
Esempio n. 12
0
double RunHypoTest(char *smwwFileName, char *ttbarFileName, char *wp3jetsFileName, char *wp4jetsFileName, char *opsFileName, char *outputFileName, double lambda) {
    TFile *smwwFile = new TFile(smwwFileName);
    TFile *ttbarFile = new TFile(ttbarFileName);
    TFile *wp3jetsFile = new TFile(wp3jetsFileName);
    TFile *wp4jetsFile = new TFile(wp4jetsFileName);
    TFile *opsFile = new TFile(opsFileName);

    TFile *outputFile = new TFile(outputFileName, "UPDATE");

    TH1F *smww = (TH1F*)smwwFile->Get(WW_MASS_HISTOGRAM_NAME);
    TH1F *ttbar = (TH1F*)ttbarFile->Get(WW_MASS_HISTOGRAM_NAME);
    TH1F *wp3jets = (TH1F*)wp3jetsFile->Get(WW_MASS_HISTOGRAM_NAME);
    TH1F *wp4jets = (TH1F*)wp4jetsFile->Get(WW_MASS_HISTOGRAM_NAME);

    //Histogram of ww-scattering with effective operator contributions
    TH1F *ops = (TH1F*)opsFile->Get(WW_MASS_HISTOGRAM_NAME);

    RooRealVar *mww = new RooRealVar("mww", "M_{WW}", 600, 2500, "GeV");

    RooDataHist smData("smData", "smData", RooArgList(*mww), smww);
    RooDataHist opsData("opsData", "opsData", RooArgList(*mww), ops);
    RooDataHist ttbarData("ttbarData", "ttbarData", RooArgList(*mww), ttbar);
    RooDataHist wp3jetsData("wp3jetsData", "wp3jetsData", RooArgList(*mww), wp3jets);
    RooDataHist wp4jetsData("wp4jetsData", "wp4jetsData", RooArgList(*mww), wp4jets);


    /*
    RooAbsPdf *opsModel;
    if (lambda == 400) {

        opsModel = SpecialCaseModel(&opsData, mww, (char*)"ops");
    }
    else {
        opsModel = MakeModel(&opsData, mww, (char*)"ops");
    }*/
    RooAbsPdf *opsModel = MakeModel(&opsData, mww, (char*)"ops");
    //RooPlot *xframe = mww->frame();
    //opsData.plotOn(xframe);
    //opsModel->plotOn(xframe);
    //printf("Chi-squared for lambda = %f: = %f\n", lambda, xframe->chiSquare("opsModel", "opsData", 3));


    RooAbsPdf *smModel = MakeModelNoSignal(&smData, mww, (char*)"sm");

    RooAbsPdf *ttbarModel = MakeModelNoSignal(&ttbarData, mww, (char*)"ttbar");
    RooAbsPdf *wp3jetsModel = MakeModelNoSignal(&wp3jetsData, mww, (char*)"wp3jets");
    RooAbsPdf *wp4jetsModel = MakeModelNoSignal(&wp4jetsData, mww, (char*)"wp4jets");

    TCanvas *canvas = new TCanvas(opsFileName);
    RooPlot *frame = mww->frame();
    frame->SetTitle("");
    //smData.plotOn(frame, RooFit::LineColor(kBlack), RooFit::Name("smData"));

    //smModel->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Name("smModel"));
    //ttbarModel->plotOn(frame, RooFit::LineColor(kRed), RooFit::Name("ttbarModel"));
    //wp3jetsModel->plotOn(frame, RooFit::LineColor(kYellow), RooFit::Name("wpjetsModel"));
    opsData.plotOn(frame);
    opsModel->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Name("opsModel"));
    //leg->AddEntry(frame->findObject("smModel"), "SM Model", "lep");
    //leg->AddEntry(frame->findObject("ttbarModel"), "TTBar Model", "lep");
    //leg->AddEntry(frame->findObject("wp3jetsModel"), "WP3Jets Model", "lep");
    //leg->AddEntry(frame->findObject("opsModel"), "Effective Operator Model", "lep");

    frame->Draw();
    canvas->Write();

    Double_t ww_x = WW_CROSS_SECTION * smww->GetEntries();
    Double_t ttbar_x = TTBAR_CROSS_SECTION * ttbar->GetEntries();
    Double_t wp3jets_x = WP3JETS_CROSS_SECTION * wp3jets->GetEntries();
    Double_t wp4jets_x = WP4JETS_CROSS_SECTION * wp4jets->GetEntries();


    Double_t ttbar_weight = ttbar_x/(ttbar_x + wp3jets_x + wp4jets_x + ww_x);
    Double_t wp3jets_weight = wp3jets_x/(wp3jets_x + ttbar_x + ww_x);
    Double_t wp4jets_weight = wp4jets_x/(wp4jets_x + ttbar_x + ww_x);

    RooRealVar *ttbarWeight = new RooRealVar("ttbarWeight", "ttbarWeight", 0.0, 1.0, ttbar_weight);
    RooRealVar *wp3jetsWeight = new RooRealVar("wp3jetsWeight", "wp3jetsWeight", 0.0, 1.0, wp3jets_weight);
    RooRealVar *wp4jetsWeight = new RooRealVar("wp4jetsWeight", "wp4jetsWeight", 0.0, 1.0, wp4jets_weight);

    ttbarWeight->setConstant();
    wp3jetsWeight->setConstant();
    wp4jetsWeight->setConstant();

    RooRealVar *mu = new RooRealVar("mu", "mu", 0.0, 1.0, "");
    RooAddPdf *wwModel = new RooAddPdf("wwModel", "u*effective_ww + (1-u)*SM_WW", 
            RooArgList(*opsModel, *smModel), RooArgList(*mu), kTRUE);

    RooAddPdf *model = new RooAddPdf("model", "Full model", 
            RooArgList(*ttbarModel, *wp3jetsModel, *wp4jetsModel, *wwModel), 
            RooArgList(*ttbarWeight, *wp3jetsWeight, *wp4jetsWeight), kTRUE);

    //Generate data under the alternate hypothesis
    mu->setVal(1.0);
    int nTestSetEvents = WW_CROSS_SECTION * TOTAL_INTEGRATED_LUMINOSITY;
    RooAbsData *generatedData = model->generate(*mww, nTestSetEvents);

    TCanvas *canvas2 = new TCanvas("CombinedModels");
    RooPlot *frame2 = mww->frame();
    //wwModel->plotOn(frame2, RooFit::LineColor(kRed), RooFit::Name("wwModel"));
    //generatedData->plotOn(frame2);
    mu->setVal(0.0);
    model->plotOn(frame2, RooFit::LineColor(kBlue), RooFit::Name("nullModel"));
    mu->setVal(1.0);
    model->plotOn(frame2, RooFit::LineColor(kRed), RooFit::Name("altModel"));
    TLegend *leg2 = new TLegend(0.65,0.73,0.86,0.87);
    //leg->AddEntry(frame2->findObject("wwModel"), "SM WW Scattering model with background",
    //        "lep");
    leg2->AddEntry(frame2->findObject("nullModel"), 
            "SM + Background", "lep");
    leg2->AddEntry(frame2->findObject("altModel"), 
            "Effective Operator + Background", "lep");
    frame2->SetTitle("");
    frame2->GetXaxis()->SetTitle("M_{WW} (GeV)");
    frame2->GetYaxis()->SetTitle("");
    frame2->Draw();
    leg2->Draw();
    canvas2->Write();
    outputFile->Close();

    
    RooArgSet poi(*mu);
    RooArgSet *nullParams = (RooArgSet*) poi.snapshot(); 

    nullParams->setRealValue("mu", 0.0); 

    RooStats::ProfileLikelihoodCalculator plc(*generatedData, *model, poi, 0.05, nullParams);


    RooStats::HypoTestResult* htr = plc.GetHypoTest();
    std::cerr << "P Value = " << htr->NullPValue() << "\n";
    return htr->Significance();
}
Esempio n. 13
0
void rf104_classfactory()
{
   // W r i t e   c l a s s   s k e l e t o n   c o d e
   // --------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b
   // To use this class,
   //    - Edit the file MyPdfV1.cxx and implement the evaluate() method in terms of x,a and b
   //    - Compile and link class with '.x MyPdfV1.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV1","x,A,B") ;


   // W i t h   a d d e d   i n i t i a l   v a l u e   e x p r e s s i o n
   // ---------------------------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b and given formula expression
   // To use this class,
   //    - Compile and link class with '.x MyPdfV2.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV2","x,A,B","","A*fabs(x)+pow(x-B,2)") ;


   // W i t h   a d d e d   a n a l y t i c a l   i n t e g r a l   e x p r e s s i o n
   // ---------------------------------------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b, given formula expression _and_
   // given expression for analytical integral over x
   // To use this class,
   //    - Compile and link class with '.x MyPdfV3.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV3","x,A,B","","A*fabs(x)+pow(x-B,2)",kTRUE,kFALSE,
            "x:(A/2)*(pow(x.max(rangeName),2)+pow(x.min(rangeName),2))+(1./3)*(pow(x.max(rangeName)-B,3)-pow(x.min(rangeName)-B,3))") ;



   // U s e   i n s t a n c e   o f   c r e a t e d   c l a s s
   // ---------------------------------------------------------

   // Compile MyPdfV3 class (only when running in CINT)
   gROOT->ProcessLineSync(".x MyPdfV3.cxx+") ;

   // Create instance of MyPdfV3 class
   RooRealVar a("a","a",1) ;
   RooRealVar b("b","b",2,-10,10) ;
   RooRealVar y("y","y",-10,10);
   MyPdfV3 pdf("pdf","pdf",y,a,b) ;

   // Generate toy data from pdf and plot data and p.d.f on frame
   RooPlot* frame1 = y.frame(Title("Compiled class MyPdfV3")) ;
   RooDataSet* data = pdf.generate(y,1000) ;
   pdf.fitTo(*data) ;
   data->plotOn(frame1) ;
   pdf.plotOn(frame1) ;


   // -----------------------------------------------------------------
   // C o m p i l e d   v e r s i o n   o f   e x a m p l e   r f 1 0 3
   // =================================================================

   // Declare observable x
   RooRealVar x("x","x",-20,20) ;

   // The RooClassFactory::makePdfInstance() function performs code writing, compiling, linking
   // and object instantiation in one go and can serve as a straight replacement of RooGenericPdf

   RooRealVar alpha("alpha","alpha",5,0.1,10) ;
   RooAbsPdf* genpdf = RooClassFactory::makePdfInstance("GenPdf","(1+0.1*fabs(x)+sin(sqrt(fabs(x*alpha+0.1))))",RooArgSet(x,alpha)) ;

   // Generate a toy dataset from the interpreted p.d.f
   RooDataSet* data2 = genpdf->generate(x,50000) ;

   // Fit the interpreted p.d.f to the generated data
   genpdf->fitTo(*data2) ;

   // Make a plot of the data and the p.d.f overlaid
   RooPlot* frame2 = x.frame(Title("Compiled version of pdf of rf103")) ;
   data2->plotOn(frame2) ;
   genpdf->plotOn(frame2) ;

   // Draw all frames on a canvas
   TCanvas* c = new TCanvas("rf104_classfactory","rf104_classfactory",800,400) ;
   c->Divide(2) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->Draw() ;

}
Esempio n. 14
0
void rf509_wsinteractive()
{
  // C r e a t e  a n d   f i l l   w o r k s p a c e
  // ------------------------------------------------

  // Create a workspace named 'w'
  // With CINT w could exports its contents to 
  // a same-name C++ namespace in CINT 'namespace w'.
  // but this does not work anymore in CLING. 
  // so this tutorial is an example on how to 
  // change the code
  RooWorkspace* w = new RooWorkspace("w",kTRUE) ;

  // Fill workspace with p.d.f. and data in a separate function
  fillWorkspace(*w) ;

  // Print workspace contents
  w->Print() ;

  // this does not work anymore with CLING 
  // use normal workspace functionality 

 
  // U s e   w o r k s p a c e   c o n t e n t s   
  // ----------------------------------------------


  // Old syntax to use the name space prefix operator to access the workspace contents
  //
  //RooDataSet* d = w::model.generate(w::x,1000) ;
  //RooFitResult* r = w::model.fitTo(*d) ;

  // use normal workspace methods
  RooAbsPdf * model = w->pdf("model");
  RooRealVar * x = w->var("x");

  RooDataSet* d = model->generate(*x,1000) ;
  RooFitResult* r = model->fitTo(*d) ;

  // old syntax to access the variable x
  // RooPlot* frame = w::x.frame() ;

  RooPlot* frame = x->frame() ;
  d->plotOn(frame) ;

  // OLD syntax to ommit x::
  // NB: The 'w::' prefix can be omitted if namespace w is imported in local namespace
  // in the usual C++ way
  //
  // using namespace w;
  // model.plotOn(frame) ;
  // model.plotOn(frame,Components(bkg),LineStyle(kDashed)) ;

  // new correct syntax 
  RooAbsPdf *bkg = w->pdf("bkg");
  model->plotOn(frame);
  model->plotOn(frame,Components(*bkg),LineStyle(kDashed)) ;

  // Draw the frame on the canvas
  new TCanvas("rf509_wsinteractive","rf509_wsinteractive",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


}
Esempio n. 15
0
void fit2015(
             TString FileName ="/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root", 
             int  oniamode  = 2,        // oniamode-> 3: Z,  2: Upsilon and 1: J/Psi
             bool isData    = true,     // isData = false for MC, true for Data
             bool isPbPb    = false,    // isPbPb = false for pp, true for PbPb
	     bool doFit = false ,
             bool inExcStat = true      // if inExcStat is true, then the excited states are fitted
             ) {

  InputOpt opt;
  SetOptions(&opt, isData, isPbPb, oniamode,inExcStat);

  if (isPbPb) {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/PbPbData/OniaTree_262548_262893.root";
  } else {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root";
  }
    
  int nbins = 1; //ceil((opt.dMuon->M->Max - opt.dMuon->M->Min)/binw);
  if (oniamode==1){
    nbins = 140;
  } else if (oniamode==2) {
    nbins = 70; 
  } else if (oniamode==3) {
    nbins = 40;
  } 
 
  RooWorkspace myws;
  TH1F* hDataOS =  new TH1F("hDataOS","hDataOS", nbins, opt.dMuon.M.Min, opt.dMuon.M.Max);
  makeWorkspace2015(myws, FileName, opt, hDataOS);

  RooRealVar* mass      = (RooRealVar*) myws.var("invariantMass"); 
  RooDataSet* dataOS_fit = (RooDataSet*) myws.data("dataOS");
  RooDataSet* dataSS_fit = (RooDataSet*) myws.data("dataSS");
  RooAbsPdf*  pdf = NULL;

  if (oniamode==3) { doFit=false; }
  if (doFit) {
    int sigModel=0, bkgModel=0;  
    if (isData) {
      if (oniamode==1){
        sigModel = inExcStat ? 2 : 3;
        bkgModel = 1;
      } else {
        sigModel = inExcStat ? 1 : 3; // gaussian   
        bkgModel = 2;
      }      
    } else {
      if (oniamode==1){
        sigModel = inExcStat ? 2 : 3; // gaussian   
        bkgModel = 2;
      } else {
        sigModel = inExcStat ? 2 : 3; // gaussian   
        bkgModel = 3;
      }
    }

    if (opt.oniaMode==1) buildModelJpsi2015(myws, sigModel, bkgModel,inExcStat);
    else if (opt.oniaMode==2) buildModelUpsi2015(myws, sigModel, bkgModel,inExcStat);

    pdf       =(RooAbsPdf*)  myws.pdf("pdf");
    RooFitResult* fitObject = pdf->fitTo(*dataOS_fit,Save(),Hesse(kTRUE),Extended(kTRUE)); // Fit
  }

  RooPlot* frame = mass->frame(Bins(nbins),Range(opt.dMuon.M.Min, opt.dMuon.M.Max));  
  RooPlot* frame2 = NULL;
  dataSS_fit->plotOn(frame, Name("dataSS_FIT"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  dataOS_fit->plotOn(frame, Name("dataOS_FIT"), MarkerColor(kBlue), LineColor(kBlue), MarkerSize(1.2));
  

  if (doFit) {
     pdf->plotOn(frame,Name("thePdf"),Normalization(dataOS_fit->sumEntries(),RooAbsReal::NumEvent));
     RooHist *hpull = frame -> pullHist(0,0,true);
     hpull -> SetName("hpull");
     frame2 = mass->frame(Title("Pull Distribution"),Bins(nbins),Range(opt.dMuon.M.Min,opt.dMuon.M.Max));
     frame2 -> addPlotable(hpull,"PX");  
     } 
  drawPlot(frame,frame2, pdf, opt, doFit,inExcStat);

  TString OutputFileName = "";
  if (isPbPb) {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/PbPbData/OniaTree_262548_262893.root";
    opt.RunNb.Start=262548;
    opt.RunNb.End=262893;
    if (oniamode==1) {OutputFileName = (TString)("JPSIPbPbDataset.root");}
    if (oniamode==2) {OutputFileName = (TString)("YPbPbDataset.root");}
    if (oniamode==3) {OutputFileName = (TString)("ZPbPbDataset.root");}
  } else {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root";
    opt.RunNb.Start=262163;
    opt.RunNb.End=262328;
    if (oniamode==1) {OutputFileName = (TString)("JPSIppDataset.root");}
    if (oniamode==2) {OutputFileName = (TString)("YppDataset.root");}
    if (oniamode==3) {OutputFileName = (TString)("ZppDataset.root");}
  }
  
  TFile* oFile =  new TFile(OutputFileName,"RECREATE");
  oFile->cd();
  hDataOS->Write("hDataOS");
  dataOS_fit->Write("dataOS_FIT");
  oFile->Write();
  oFile->Close();

}
void eregtesting_13TeV_Pi0(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/%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/%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 {
    if(dobarrel)
    {
    TFile *fdin = TFile::Open("/afs/cern.ch/work/z/zhicaiz/public/ECALpro_MC_TreeForRegression/Gun_Pi0_Pt1To15_FlatPU0to50RAW_withHLT_80X_mcRun2_GEN-SIM-RAW_ALL_EcalNtp_ALL_EB_combine_test.root");//("root://eoscms.cern.ch///eos/cms/store/cmst3/user/bendavid/idTreesAug1/hgg-2013Final8TeV_ID_s12-h124gg-gf-v7n_noskim.root");
   // TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPreselNoSmear");
	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");
	}
    }      
   else
    {
  TFile *fdin = TFile::Open("/afs/cern.ch/work/z/zhicaiz/public/ECALpro_MC_TreeForRegression/Gun_Pi0_Pt1To15_FlatPU0to50RAW_withHLT_80X_mcRun2_GEN-SIM-RAW_ALL_EcalNtp_ALL_EE_combine_test.root");//("root://eoscms.cern.ch///eos/cms/store/cmst3/user/bendavid/idTreesAug1/hgg-2013Final8TeV_ID_s12-h124gg-gf-v7n_noskim.root");
   // TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPreselNoSmear");
   	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_nocor/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03)";
  //TCut selcut = "(STr2_enG_nocor/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)<60)";
  //TCut selcut = "(STr2_enG_nocor/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)>60)";
  //TCut selcut = "(STr2_enG_nocor/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_nocor/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)";

  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 *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.8,1.1));
         hecor = hdata->createHistogram("hecor",*ecorvar, Binning(800,0.8,1.1));
  }
  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(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);
  }
  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_6");
  RooRealVar *scphiiYvar = ws->var("var_7");
 
   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;
  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_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;
  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 *iEtaOn5var = ws->var("var_8");
  iEtaOn5var->setRange(0,5);
  iEtaOn5var->setBins(5);
  TH2F *h_CC_iEtaOn5 = hdata->createHistogram(*iEtaOn5var, *ecorvar, "","cor_vs_iEtaOn5");
  h_CC_iEtaOn5->GetXaxis()->SetTitle("iEtaOn5"); 
  h_CC_iEtaOn5->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_iEtaOn5->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_iEtaOn5.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_iEtaOn5.png");
  TH2F *h_RC_iEtaOn5 = hdata->createHistogram(*iEtaOn5var, *rawvar, "","raw_vs_iEtaOn5");
  h_RC_iEtaOn5->GetXaxis()->SetTitle("iEtaOn5"); 
  h_RC_iEtaOn5->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_iEtaOn5->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_iEtaOn5.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_iEtaOn5.png");

  RooRealVar *iPhiOn2var = ws->var("var_9");
  iPhiOn2var->setRange(0,2);
  iPhiOn2var->setBins(2);
  TH2F *h_CC_iPhiOn2 = hdata->createHistogram(*iPhiOn2var, *ecorvar, "","cor_vs_iPhiOn2");
  h_CC_iPhiOn2->GetXaxis()->SetTitle("iPhiOn2"); 
  h_CC_iPhiOn2->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_iPhiOn2->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_iPhiOn2.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_iPhiOn2.png");
  TH2F *h_RC_iPhiOn2 = hdata->createHistogram(*iPhiOn2var, *rawvar, "","raw_vs_iPhiOn2");
  h_RC_iPhiOn2->GetXaxis()->SetTitle("iPhiOn2"); 
  h_RC_iPhiOn2->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_iPhiOn2->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_iPhiOn2.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_iPhiOn2.png");

  RooRealVar *iPhiOn20var = ws->var("var_10");
  iPhiOn20var->setRange(0,20);
  iPhiOn20var->setBins(20);
  TH2F *h_CC_iPhiOn20 = hdata->createHistogram(*iPhiOn20var, *ecorvar, "","cor_vs_iPhiOn20");
  h_CC_iPhiOn20->GetXaxis()->SetTitle("iPhiOn20"); 
  h_CC_iPhiOn20->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_iPhiOn20->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_iPhiOn20.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_iPhiOn20.png");
  TH2F *h_RC_iPhiOn20 = hdata->createHistogram(*iPhiOn20var, *rawvar, "","raw_vs_iPhiOn20");
  h_RC_iPhiOn20->GetXaxis()->SetTitle("iPhiOn20"); 
  h_RC_iPhiOn20->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_iPhiOn20->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_iPhiOn20.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_iPhiOn20.png");

  RooRealVar *iEtaOn2520var = ws->var("var_11");
  iEtaOn2520var->setRange(-25,25);
  iEtaOn2520var->setBins(50);
  TH2F *h_CC_iEtaOn2520 = hdata->createHistogram(*iEtaOn2520var, *ecorvar, "","cor_vs_iEtaOn2520");
  h_CC_iEtaOn2520->GetXaxis()->SetTitle("iEtaOn2520"); 
  h_CC_iEtaOn2520->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_iEtaOn2520->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_iEtaOn2520.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_iEtaOn2520.png");
  TH2F *h_RC_iEtaOn2520 = hdata->createHistogram(*iEtaOn2520var, *rawvar, "","raw_vs_iEtaOn2520");
  h_RC_iEtaOn2520->GetXaxis()->SetTitle("iEtaOn2520"); 
  h_RC_iEtaOn2520->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_iEtaOn2520->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_iEtaOn2520.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_iEtaOn2520.png");

}
	 

// other variables

  TCanvas *myC_variables = new TCanvas;

  RooRealVar *Nxtalvar = ws->var("var_3");
  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_4");

  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 *S1S9var = ws->var("var_5");
  S1S9var->setRange(0.3,1.0);
  S1S9var->setBins(100);
  TH2F *h_CC_S1S9 = hdata->createHistogram(*S1S9var, *ecorvar, "","cor_vs_S1S9");
  h_CC_S1S9->GetXaxis()->SetTitle("S1S9"); 
  h_CC_S1S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S1S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S1S9.pdf");
  TH2F *h_RC_S1S9 = hdata->createHistogram(*S1S9var, *rawvar, "","raw_vs_S1S9");
  h_RC_S1S9->GetXaxis()->SetTitle("S1S9"); 
  h_RC_S1S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S1S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S1S9.pdf");
 */

  RooRealVar *S2S9var = ws->var("var_5");
  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");
  

 
/* 
  RooRealVar *DeltaRvar = ws->var("var_6");
  DeltaRvar->setRange(0.0,0.1);
  DeltaRvar->setBins(100);
  TH2F *h_CC_DeltaR = hdata->createHistogram(*DeltaRvar, *ecorvar, "","cor_vs_DeltaR");
  h_CC_DeltaR->GetXaxis()->SetTitle("#Delta R"); 
  h_CC_DeltaR->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_DeltaR->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_DeltaR.pdf");
  myC_variables->SaveAs("cor_vs_DeltaR.png");
  TH2F *h_RC_DeltaR = hdata->createHistogram(*DeltaRvar, *rawvar, "","raw_vs_DeltaR");
  h_RC_DeltaR->GetXaxis()->SetTitle("#Delta R"); 
  h_RC_DeltaR->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_DeltaR->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_DeltaR.pdf");
  myC_variables->SaveAs("raw_vs_DeltaR.png");
*/

  if(EEorEB=="EE")
{

/*  RooRealVar *Es_e1var = ws->var("var_9");
  Es_e1var->setRange(0.0,200.0);
  Es_e1var->setBins(1000);
  TH2F *h_CC_Es_e1 = hdata->createHistogram(*Es_e1var, *ecorvar, "","cor_vs_Es_e1");
  h_CC_Es_e1->GetXaxis()->SetTitle("Es_e1"); 
  h_CC_Es_e1->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_Es_e1->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_Es_e1.pdf");
  myC_variables->SaveAs("cor_vs_Es_e1.png");
  TH2F *h_RC_Es_e1 = hdata->createHistogram(*Es_e1var, *rawvar, "","raw_vs_Es_e1");
  h_RC_Es_e1->GetXaxis()->SetTitle("Es_e1"); 
  h_RC_Es_e1->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_Es_e1->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_Es_e1.pdf");
  myC_variables->SaveAs("raw_vs_Es_e1.png");

  RooRealVar *Es_e2var = ws->var("var_10");
  Es_e2var->setRange(0.0,200.0);
  Es_e2var->setBins(1000);
  TH2F *h_CC_Es_e2 = hdata->createHistogram(*Es_e2var, *ecorvar, "","cor_vs_Es_e2");
  h_CC_Es_e2->GetXaxis()->SetTitle("Es_e2"); 
  h_CC_Es_e2->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_Es_e2->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_Es_e2.pdf");
  myC_variables->SaveAs("cor_vs_Es_e2.png");
  TH2F *h_RC_Es_e2 = hdata->createHistogram(*Es_e2var, *rawvar, "","raw_vs_Es_e2");
  h_RC_Es_e2->GetXaxis()->SetTitle("Es_e2"); 
  h_RC_Es_e2->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_Es_e2->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_Es_e2.pdf");
  myC_variables->SaveAs("raw_vs_Es_e2.png");
*/
}
	
  TProfile *p_CC_eta = h_CC_eta->ProfileX("p_CC_eta",1,-1,"s");
  p_CC_eta->GetYaxis()->SetRangeUser(0.7,1.2);
  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"); 
  
  TProfile *p_RC_eta = h_RC_eta->ProfileX("p_RC_eta",1,-1,"s");
  p_RC_eta->GetYaxis()->SetRangeUser(0.7,1.2);
  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"); 

  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.7,1.2);
  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"); 
  
  TProfile *p_RC_phi = h_RC_phi->ProfileX("p_RC_phi",1,-1,"s");
  p_RC_phi->GetYaxis()->SetRangeUser(0.7,1.2);
  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"); 

  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(); */   
  
  
}
void StandardHistFactoryPlotsWithCategories(const char* infile = "",
                                            const char* workspaceName = "combined",
                                            const char* modelConfigName = "ModelConfig",
                                            const char* dataName = "obsData"){


   double nSigmaToVary=5.;
   double muVal=0;
   bool doFit=false;

   // -------------------------------------------------------
   // 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";
      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;
#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;
   }

   // -------------------------------------------------------
   // 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;
   }

   // -------------------------------------------------------
   // now use the profile inspector

   RooRealVar* obs = (RooRealVar*)mc->GetObservables()->first();
   TList* list = new TList();


   RooRealVar * firstPOI = dynamic_cast<RooRealVar*>(mc->GetParametersOfInterest()->first());

   firstPOI->setVal(muVal);
   //  firstPOI->setConstant();
   if(doFit){
      mc->GetPdf()->fitTo(*data);
   }

   // -------------------------------------------------------


   mc->GetNuisanceParameters()->Print("v");
   int  nPlotsMax = 1000;
   cout <<" check expectedData by category"<<endl;
   RooDataSet* simData=NULL;
   RooSimultaneous* simPdf = NULL;
   if(strcmp(mc->GetPdf()->ClassName(),"RooSimultaneous")==0){
      cout <<"Is a simultaneous PDF"<<endl;
      simPdf = (RooSimultaneous *)(mc->GetPdf());
   } else {
      cout <<"Is not a simultaneous PDF"<<endl;
   }



   if(doFit) {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      tt=(RooCatType*) iter->Next();
      RooAbsPdf* pdftmp = ((RooSimultaneous*)mc->GetPdf())->getPdf(tt->GetName()) ;
      RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
      obs = ((RooRealVar*)obstmp->first());
      RooPlot* frame = obs->frame();
      cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
      cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
      data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

      Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

      pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;
      frame->Draw();
      cout <<"expected events = " << mc->GetPdf()->expectedEvents(*data->get()) <<endl;
      return;
   }



   int nPlots=0;
   if(!simPdf){

      TIterator* it = mc->GetNuisanceParameters()->createIterator();
      RooRealVar* var = NULL;
      while( (var = (RooRealVar*) it->Next()) != NULL){
         RooPlot* frame = obs->frame();
         frame->SetYTitle(var->GetName());
         data->plotOn(frame,MarkerSize(1));
         var->setVal(0);
         mc->GetPdf()->plotOn(frame,LineWidth(1.));
         var->setVal(1);
         mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(1));
         var->setVal(-1);
         mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(1));
         list->Add(frame);
         var->setVal(0);
      }


   } else {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      //    TIterator* iter = simPdf->indexCat().typeIterator() ;
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      while(nPlots<nPlotsMax && (tt=(RooCatType*) iter->Next())) {

         cout << "on type " << tt->GetName() << " " << endl;
         // Get pdf associated with state from simpdf
         RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;

         // Generate observables defined by the pdf associated with this state
         RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
         //      obstmp->Print();


         obs = ((RooRealVar*)obstmp->first());

         TIterator* it = mc->GetNuisanceParameters()->createIterator();
         RooRealVar* var = NULL;
         while(nPlots<nPlotsMax && (var = (RooRealVar*) it->Next())){
            TCanvas* c2 = new TCanvas("c2");
            RooPlot* frame = obs->frame();
            frame->SetName(Form("frame%d",nPlots));
            frame->SetYTitle(var->GetName());

            cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
            cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
            data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

            Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }
            // w->allVars().Print("v");
            // mc->GetNuisanceParameters()->Print("v");
            // pdftmp->plotOn(frame,LineWidth(2.));
            // mc->GetPdf()->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()+0.05);
               var->Print();
            } else{
               var->setVal(nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kRed),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()-0.05);
               var->Print();
            } else{
               var->setVal(-nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kGreen),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;



            // set them back to normal
            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }

            list->Add(frame);

            // quit making plots
            ++nPlots;

            frame->Draw();
            c2->SaveAs(Form("%s_%s_%s.pdf",tt->GetName(),obs->GetName(),var->GetName()));
            delete c2;
         }
      }
   }



   // -------------------------------------------------------


   // now make plots
   TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo",800,200);
   if(list->GetSize()>4){
      double n = list->GetSize();
      int nx = (int)sqrt(n) ;
      int ny = TMath::CeilNint(n/nx);
      nx = TMath::CeilNint( sqrt(n) );
      c1->Divide(ny,nx);
   } else
      c1->Divide(list->GetSize());
   for(int i=0; i<list->GetSize(); ++i){
      c1->cd(i+1);
      list->At(i)->Draw();
   }





}
Esempio n. 18
0
void eregtestingExample(bool dobarrel=true, bool doele=true) {
  
  //output dir
  TString dirname = "/data/bendavid/eregexampletest/eregexampletest_test/"; 
  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("/data/bendavid/eregexampletest/%s",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("root://eoscms.cern.ch///eos/cms/store/cmst3/user/bendavid/idTreesAug1/hgg-2013Final8TeV_ID_s12-h124gg-gf-v7n_noskim.root");
    TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPreselNoSmear");
    dtree = (TTree*)ddir->Get("hPhotonTreeSingle");       
  }
  
  //selection cuts for testing
  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 = "(evt%10==0)";
  TCut prescale10alt = "(evt%10==1)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale100 = "(evt%100==0)";  
  TCut prescale1000 = "(evt%1000==0)";  
  TCut evenevents = "(evt%2==0)";
  TCut oddevents = "(evt%2==1)";
  TCut prescale100alt = "(evt%100==1)";
  TCut prescale1000alt = "(evt%1000==1)";
  TCut prescale50alt = "(evt%50==1)";
  
  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 *scetavar = ws->var("var_1");
  
  //regressed output functions
  RooAbsReal *sigmeanlim = ws->function("sigmeanlim");
  RooAbsReal *sigwidthlim = ws->function("sigwidthlim");
  RooAbsReal *signlim = ws->function("signlim");
  RooAbsReal *sign2lim = ws->function("sign2lim");

  //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);
  
  
  //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.eps");
  craw->SetLogy();
  plot->SetMinimum(0.1);
  craw->SaveAs("RawElog.eps");
  
  //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.eps");
  
  
  TCanvas *cwidth = new TCanvas;
  RooPlot *plotwidth = widthvar->frame(0.,0.05,100);
  hdataclone->plotOn(plotwidth);
  plotwidth->Draw();
  cwidth->SaveAs("width.eps");
  
  TCanvas *cn = new TCanvas;
  RooPlot *plotn = nvar->frame(0.,111.,200);
  hdataclone->plotOn(plotn);
  plotn->Draw();
  cn->SaveAs("n.eps");

  TCanvas *cn2 = new TCanvas;
  RooPlot *plotn2 = n2var->frame(0.,111.,100);
  hdataclone->plotOn(plotn2);
  plotn2->Draw();
  cn2->SaveAs("n2.eps");
  
  TCanvas *ceta = new TCanvas;
  RooPlot *ploteta = scetavar->frame(-2.6,2.6,200);
  hdataclone->plotOn(ploteta);
  ploteta->Draw();      
  ceta->SaveAs("eta.eps");  
  

  //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);
  
  
  //heold->SetLineColor(kRed);
  hecor->SetLineColor(kBlue);
  heraw->SetLineColor(kMagenta);
  
  hecor->GetXaxis()->SetRangeUser(0.6,1.2);
  //heold->GetXaxis()->SetRangeUser(0.6,1.2);
  
  TCanvas *cresponse = new TCanvas;
  
  hecor->Draw("HIST");
  //heold->Draw("HISTSAME");
  heraw->Draw("HISTSAME");
  cresponse->SaveAs("response.eps");
  cresponse->SetLogy();
  cresponse->SaveAs("responselog.eps");
  
  
  printf("make fine histogram\n");
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(20e3,0.,2.));

  printf("calc effsigma\n");
  
  double effsigma = effSigma(hecorfine);
  
  printf("effsigma = %5f\n",effsigma);
  
/*  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(); */   
  
  
}
Esempio n. 19
0
  /***********************************************************************
   ***********************************************************************
   *   CONSTRUCTOR   MAKES ALLLLLLLL
   *******************************************************************
   *************************************************
   *****************************
   *****
   */
  Tbroomfit(double xlow, double xhi, TH1 *h2,  int npeak, double *peak, double *sigm, const char *chpol="p0"){
    int iq=0;
    printf("constructor - %d   %ld", iq++,  (int64_t)h2 );
    h2->Print();
    /*
     *   get global area, ranges for sigma, x
     */
    npeaks=npeak; // class defined int
    //    double areah2=h2->Integral( int(xlow), int(xhi) ); // WRONG - BINS
    min= h2->GetXaxis()->GetFirst();
    printf("constructor - %d   %f", iq++, min  );
    max= h2->GetXaxis()->GetLast();
    printf("constructor - %d   %f", iq++, max  );
    double areah2=h2->Integral( min, max );
    printf("constructor - %d   %f", iq++,  areah2 );
    min=xlow;
    max=xhi;


    double sigmamin=(max-min)/300;
    double sigmamax=(max-min)/4;
    double areamin=0;
    double areamax=2*areah2;
    printf("x:(%f,%f)  s:(%f,%f)  a:(%f,%f) \n", min,max,sigmamin, sigmamax,areamin, areamax );
  /*
   *   definition of  variables..............
   *
   */    
    RooRealVar       x("x",    "x",   min, max);

    int MAXPEAKS=6;  // later from 5 to 6 ???


    printf("RooFit: npeaks=%d\n",  npeaks );
    // ABOVE:  RooRealVar *msat[14][5]; //  POINTERS TO ALL variables
    // 0  m     Mean
    // 1  s     Sigma
    // 2  a     Area
    // 3  t     Tail
    // 4  [0] nalpha
    // 5  [0] n1

for (int ii=0;ii<14;ii++){
 for (int jj=0;jj<MAXPEAKS;jj++){
   msat[ii][jj]=NULL; 
   msat_values[ii][jj]=0.0;
 } //for for
 }// for for 

 printf("delete fitresult, why crash?\n%s","");
 fitresult=NULL;
 printf("delete fitresult, no crash?\n%s","");


    RooRealVar    mean1("mean1", "mean",  1*(max-min)/(npeaks+1)+min,    min,max);msat[0][0]=&mean1;
    RooRealVar    mean2("mean2", "mean",  2*(max-min)/(npeaks+1)+min,    min,max);msat[0][1]=&mean2;
    RooRealVar    mean3("mean3", "mean",  3*(max-min)/(npeaks+1)+min,    min,max);msat[0][2]=&mean3;
    RooRealVar    mean4("mean4", "mean",  4*(max-min)/(npeaks+1)+min,    min,max);msat[0][3]=&mean4;
    RooRealVar    mean5("mean5", "mean",  5*(max-min)/(npeaks+1)+min,    min,max);msat[0][4]=&mean5;
    RooRealVar    mean6("mean6", "mean",  6*(max-min)/(npeaks+1)+min,    min,max);msat[0][5]=&mean6;


    RooRealVar   sigma1("sigma1","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][0]=&sigma1;
    RooRealVar   sigma2("sigma2","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][1]=&sigma2;
    RooRealVar   sigma3("sigma3","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][2]=&sigma3;
    RooRealVar   sigma4("sigma4","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][3]=&sigma4;
    RooRealVar   sigma5("sigma5","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][4]=&sigma5;
    RooRealVar   sigma6("sigma6","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][5]=&sigma6;


    RooRealVar    area1("area1", "area",      areah2/npeaks,       areamin, areamax  );msat[2][0]=&area1;
    RooRealVar    area2("area2", "area",      areah2/npeaks,       areamin, areamax  );msat[2][1]=&area2; 
    RooRealVar    area3("area3", "area",      areah2/npeaks,       areamin, areamax  );msat[2][2]=&area3; 
    RooRealVar    area4("area4", "area",      areah2/npeaks,       areamin, areamax  );msat[2][3]=&area4; 
    RooRealVar    area5("area5", "area",      areah2/npeaks,       areamin, areamax  );msat[2][4]=&area5; 
    RooRealVar    area6("area6", "area",      areah2/npeaks,       areamin, areamax  );msat[2][5]=&area6; 

    RooRealVar   bgarea("bgarea", "bgarea", areah2/5, 0, 2*areah2);  



    double  tailstart=-1.0;//  tune the tails....
    double  tailmin=-1e+4;
    double  tailmax=1e+4;

    RooRealVar    tail1("tail1", "tail",      tailstart,       tailmin, tailmax  );msat[3][0]=&tail1;
    RooRealVar    tail2("tail2", "tail",      tailstart,       tailmin, tailmax  );msat[3][1]=&tail2;
    RooRealVar    tail3("tail3", "tail",      tailstart,       tailmin, tailmax  );msat[3][2]=&tail3;
    RooRealVar    tail4("tail4", "tail",      tailstart,       tailmin, tailmax  );msat[3][3]=&tail4;
    RooRealVar    tail5("tail5", "tail",      tailstart,       tailmin, tailmax  );msat[3][4]=&tail5;
    RooRealVar    tail6("tail6", "tail",      tailstart,       tailmin, tailmax  );msat[3][5]=&tail6;

    // for CBShape
    RooRealVar    nalpha1("nalpha1", "nalpha",      1.3, 0, 100  );msat[4][0]=&nalpha1;

    RooRealVar    n1("n1",          "n",         5.1, 0, 100  );  msat[5][0]=&n1;






    /*
     *   initial values  for  peak positions................
     */
    if (npeaks>=1) {mean1=peak[0];sigma1=sigm[0];}
    if (npeaks>=2) {mean2=peak[1];sigma2=sigm[1];}
    if (npeaks>=3) {mean3=peak[2];sigma3=sigm[2];}
    if (npeaks>=4) {mean4=peak[3];sigma4=sigm[3];}
    if (npeaks>=5) {mean5=peak[4];sigma5=sigm[4];}
    if (npeaks>=6) {mean6=peak[5];sigma6=sigm[5];}


    /*
     *    RooAbsPdf -> RooGaussian
     *                 RooNovosibirsk
     *                 RooLandau
     */
     RooAbsPdf *pk[6];                 // MAXIMUM PEAKS ==5    6 NOW!!             
     RooAbsPdf *pk_dicto[14][6];        // ALL DICTIONARY OF PEAKS..........
     //  Abstract Class.... carrefuly

    RooGaussian gauss1("gauss1","gauss(x,mean,sigma)", x, mean1, sigma1);pk_dicto[0][0]=&gauss1;
    RooGaussian gauss2("gauss2","gauss(x,mean,sigma)", x, mean2, sigma2);pk_dicto[0][1]=&gauss2;
    RooGaussian gauss3("gauss3","gauss(x,mean,sigma)", x, mean3, sigma3);pk_dicto[0][2]=&gauss3;
    RooGaussian gauss4("gauss4","gauss(x,mean,sigma)", x, mean4, sigma4);pk_dicto[0][3]=&gauss4;
    RooGaussian gauss5("gauss5","gauss(x,mean,sigma)", x, mean5, sigma5);pk_dicto[0][4]=&gauss5;
    RooGaussian gauss6("gauss6","gauss(x,mean,sigma)", x, mean6, sigma6);pk_dicto[0][5]=&gauss6;

    RooNovosibirsk ns1("ns1","novosib(x,mean,sigma,tail)", x, mean1,sigma1, tail1 );pk_dicto[1][0]=&ns1;
    RooNovosibirsk ns2("ns2","novosib(x,mean,sigma,tail)", x, mean2,sigma2, tail2 );pk_dicto[1][1]=&ns2;
    RooNovosibirsk ns3("ns3","novosib(x,mean,sigma,tail)", x, mean3,sigma3, tail3 );pk_dicto[1][2]=&ns3;
    RooNovosibirsk ns4("ns4","novosib(x,mean,sigma,tail)", x, mean4,sigma4, tail4 );pk_dicto[1][3]=&ns4;
    RooNovosibirsk ns5("ns5","novosib(x,mean,sigma,tail)", x, mean5,sigma5, tail5 );pk_dicto[1][4]=&ns5;
 
    // BreitWiegner  is  Lorentzian...?
    RooBreitWigner bw1("bw1","BreitWigner(x,mean,sigma)", x, mean1, sigma1 );pk_dicto[2][0]=&bw1;
    RooBreitWigner bw2("bw2","BreitWigner(x,mean,sigma)", x, mean2, sigma2 );pk_dicto[2][1]=&bw2;
    RooBreitWigner bw3("bw3","BreitWigner(x,mean,sigma)", x, mean3, sigma3 );pk_dicto[2][2]=&bw3;
    RooBreitWigner bw4("bw4","BreitWigner(x,mean,sigma)", x, mean4, sigma4 );pk_dicto[2][3]=&bw4;
    RooBreitWigner bw5("bw5","BreitWigner(x,mean,sigma)", x, mean5, sigma5 );pk_dicto[2][4]=&bw5;

    RooCBShape cb1("cb1","CBShape(x,mean,sigma)", x, mean1, sigma1, nalpha1, n1 );pk_dicto[3][0]=&cb1;
    RooCBShape cb2("cb2","CBShape(x,mean,sigma)", x, mean2, sigma2, nalpha1, n1 );pk_dicto[3][1]=&cb2;
    RooCBShape cb3("cb3","CBShape(x,mean,sigma)", x, mean3, sigma3, nalpha1, n1 );pk_dicto[3][2]=&cb3;
    RooCBShape cb4("cb4","CBShape(x,mean,sigma)", x, mean4, sigma4, nalpha1, n1 );pk_dicto[3][3]=&cb4;
    RooCBShape cb5("cb5","CBShape(x,mean,sigma)", x, mean5, sigma5, nalpha1, n1 );pk_dicto[3][4]=&cb5;
    RooCBShape cb6("cb6","CBShape(x,mean,sigma)", x, mean6, sigma6, nalpha1, n1 );pk_dicto[3][5]=&cb6;



    /*
     *    PEAK TYPES   BACKGROUND TYPE .........   COMMAND BOX  OPTIONS ......
     */
    /****************************************************************************
     *  PLAY  WITH  THE DEFINITION  COMMANDLINE...................... POLYNOM + PEAKS
     */
    // CALSS DECLARED TString s;
  s=chpol;
  /*
   *   peaks+bg== ALL BEFORE  ; or :          (after ...  it is a conditions/options)
   */
  TString command;
  int comstart=s.Index(":");   if (comstart<0){ comstart=s.Index(";");}
  if  (comstart<0){ command="";}else{
    command=s(comstart+1, s.Length()-comstart -1 ); // without ;
    s=s(0,comstart); // without ;
    printf("COMMANDLINE : %s\n",  command.Data()  );
    if (TPRegexp("scom").Match(command)!=0){
      
    }// COMMANDS - 
  }// there is some command
  /*************************************************
   *  PLAY WITH peaks+bg..................    s
   */
  s.Append("+"); s.Prepend("+");  s.ReplaceAll(" ","+");
  s.ReplaceAll("++++","+"); s.ReplaceAll("+++","+"); s.ReplaceAll("++","+");s.ReplaceAll("++","+");
  printf ("   regextp =  %s\n",  s.Data()  );
  if (TPRegexp("\\+p[\\dn]\\+").Match(s)==0){ // no match
     printf("NO polynomial demanded =>: %s\n",  "appending  pn command"  ); s.Append("pn+");
  }
  TString spk=s;   TString sbg=s;
  TPRegexp("\\+p[\\dn]\\+").Substitute(spk,"+");  // remove   +p.+   
  TPRegexp(".+(p[\\dn]).+").Substitute(sbg,"$1"); // remove   all but +p+   

  printf ("PEAKS=%s      BG=%s\n",  spk.Data() ,  sbg.Data()  );
  spk.ReplaceAll("+","");   //  VARIANT 1 ------- EACH  LETTER MEANS ONE PEAK 






  /************************************************************************
   *          PREPARE PEAKS  FOLLOWING THE COMMAND BOX................
   */
    //default PEAK types
    pk[0]=&gauss1;
    pk[1]=&gauss2;
    pk[2]=&gauss3;
    pk[3]=&gauss4;
    pk[4]=&gauss5;
    pk[5]=&gauss6;


  int maxi=spk.Length();
  if (maxi>npeaks){maxi=npeaks;}
  for (int i=0;i<maxi;i++){
    if (spk[i]=='n'){
      pk[i]=pk_dicto[1][i];//novosibirsk
      printf("PEAK #%d ... Novosibirsk\n", i );
    }else if(spk[i]=='b'){
      pk[i]=pk_dicto[2][i];//BreitWiegner
      printf("PEAK #%d ... BreitWigner\n", i );
    }else if(spk[i]=='c'){
      pk[i]=pk_dicto[3][i];//CBShape
      printf("PEAK #%d ... CBShape\n", i );
    }else if(spk[i]=='y'){
    }else if(spk[i]=='z'){
    }else{
      pk[i]=pk_dicto[0][i]; //gauss
      printf("PEAK #%d ... Gaussian\n", i );
    }// ELSE CHAIN
  }//i to maxi


  for (int i=0;i<npeaks;i++){ printf("Peak %d   at  %f  s=%f:  PRINT:\n  " ,  i, peak[i], sigm[i]  );pk[i]->Print();}



 /******************************************************** BACKGROUND pn-p4
     *   a0 == level - also skew
     *   a1 == p2
     *   a2 == p3
     */
 // Build Chebychev polynomial p.d.f.  
 // RooRealVar a0("a0","a0", 0.) ;
  RooRealVar a0("a0","a0",    0., -10, 10) ;
  RooRealVar a1("a1","a1",    0., -10, 10) ;
  RooRealVar a2("a2","a2",    0., -10, 10) ;
  RooRealVar a3("a3","a3",    0., -10, 10) ;
  RooArgSet setcheb;
  if ( sbg=="pn" ){ setcheb.add(a0);  a0=0.; a0.setConstant(kTRUE);bgarea=0.; bgarea.setConstant(kTRUE);}
  if ( sbg=="p0" ){ setcheb.add(a0);  a0=0.; a0.setConstant(kTRUE); }
  if ( sbg=="p1" ){ setcheb.add(a0); }
  if ( sbg=="p2" ){ setcheb.add(a1); setcheb.add(a0); }
  if ( sbg=="p3" ){ setcheb.add(a2); setcheb.add(a1); setcheb.add(a0); }
  if ( sbg=="p4" ){ setcheb.add(a3);setcheb.add(a2); setcheb.add(a1); setcheb.add(a0); }
  //  RooChebychev bkg("bkg","Background",x,RooArgSet(a0,a1,a2,a3) ) ;
  RooChebychev bkg("bkg","Background",x, setcheb ) ;

 


  /**********************************************************************
   * MODEL
   */
 
 
 RooArgList rl;  
 if (npeaks>0)rl.add( *pk[0] );  
 if (npeaks>1)rl.add( *pk[1] );  
 if (npeaks>2)rl.add( *pk[2] );  
 if (npeaks>3)rl.add( *pk[3] );  
 if (npeaks>4)rl.add( *pk[4] );  
 if (npeaks>5)rl.add( *pk[5] );  
 rl.add( bkg ); 
 RooArgSet rs;
 if (npeaks>0)rs.add( area1 );  
 if (npeaks>1)rs.add( area2 );  
 if (npeaks>2)rs.add( area3 );  
 if (npeaks>3)rs.add( area4 );  
 if (npeaks>4)rs.add( area5 );  
 if (npeaks>5)rs.add( area6 );  
 rs.add( bgarea );
 RooAddPdf modelV("model","model", rl, rs );


 /*
  *  WITH CUSTOMIZER - I can change parameters inside. But
  *             - then all is a clone and I dont know how to reach it
  */
   RooCustomizer cust( modelV ,"cust"); 
   /*
    *  Possibility to fix all sigma  or tails....
    */ 
   if (TPRegexp("scom").Match(command)!=0){//----------------------SCOM
     printf("all sigma have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(sigma2,sigma1) ;
     if (npeaks>2)cust.replaceArg(sigma3,sigma1) ;
     if (npeaks>3)cust.replaceArg(sigma4,sigma1) ;
     if (npeaks>4)cust.replaceArg(sigma5,sigma1) ;
     if (npeaks>5)cust.replaceArg(sigma6,sigma1) ;
    }
   if (TPRegexp("tcom").Match(command)!=0){//----------------------TCOM
     printf("all tails have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(tail2,tail1) ;
     if (npeaks>2)cust.replaceArg(tail3,tail1) ;
     if (npeaks>3)cust.replaceArg(tail4,tail1) ;
     if (npeaks>4)cust.replaceArg(tail5,tail1) ;
     if (npeaks>5)cust.replaceArg(tail6,tail1) ;
    }
   /*   if (TPRegexp("tcom").Match(command)!=0){//----------------------TCOM Neni dalsi ACOM,NCOM pro CB...
     printf("all tails have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(tail2,tail1) ;
     if (npeaks>2)cust.replaceArg(tail3,tail1) ;
     if (npeaks>3)cust.replaceArg(tail4,tail1) ;
     if (npeaks>4)cust.replaceArg(tail5,tail1) ;
    }
   */
   if  (TPRegexp("p1fix").Match(command)!=0){//----------------------
     mean1.setConstant();printf("position 1 set constant%s\n","");
   }
   if  (TPRegexp("p2fix").Match(command)!=0){//----------------------
     mean2.setConstant();printf("position 2 set constant%s\n","");
   }
   if  (TPRegexp("p3fix").Match(command)!=0){//----------------------
     mean3.setConstant();printf("position 3 set constant%s\n","");
   }
   if  (TPRegexp("p4fix").Match(command)!=0){//----------------------
     mean4.setConstant();printf("position 4 set constant%s\n","");
   }
   if  (TPRegexp("p5fix").Match(command)!=0){//----------------------
     mean5.setConstant();printf("position 5 set constant%s\n","");
   }
   if  (TPRegexp("p6fix").Match(command)!=0){//----------------------
     mean6.setConstant();printf("position 6 set constant%s\n","");
   }
   if  (TPRegexp("s1fix").Match(command)!=0){//----------------------
     sigma1.setConstant();printf("sigma 1 set constant%s\n","");
   }
   if  (TPRegexp("s2fix").Match(command)!=0){//----------------------
     sigma2.setConstant();printf("sigma 2 set constant%s\n","");
   }
   if  (TPRegexp("s3fix").Match(command)!=0){//----------------------
     sigma3.setConstant();printf("sigma 3 set constant%s\n","");
   }
   if  (TPRegexp("s4fix").Match(command)!=0){//----------------------
     sigma4.setConstant();printf("sigma 4 set constant%s\n","");
   }
   if  (TPRegexp("s5fix").Match(command)!=0){//----------------------
     sigma5.setConstant();printf("sigma 5 set constant%s\n","");
   }
   if  (TPRegexp("s6fix").Match(command)!=0){//----------------------
     sigma6.setConstant();printf("sigma 6 set constant%s\n","");
   }


   RooAbsPdf* model = (RooAbsPdf*) cust.build(kTRUE) ; //build a clone...comment on changes...
   //   model->Print("t") ;
   //delete model ; // eventualy delete the model...





 /*
  *  DISPLAY RESULTS            >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  */
   TPad *orig_gpad=(TPad*)gPad;


   TCanvas *c;
   c=(TCanvas*)gROOT->GetListOfCanvases()->FindObject("fitresult");
   if (c==NULL){
     printf("making new canvas\n%s","");
     c=new TCanvas("fitresult",h2->GetName(),1000,700);  
   }else{
     printf("using old canvas\n%s","");
     c->SetTitle( h2->GetName() );
   }
   c->Clear();
     printf(" canvas cleared\n%s","");
   c->Divide(1,2) ;
     printf(" canvas divided\n%s","");
  c->Modified();c->Update(); 

 RooDataHist datah("datah","datah with x",x,h2);
 RooPlot* xframe = x.frame();
 datah.plotOn(xframe,  DrawOption("logy") );

 // return;
   if (TPRegexp("chi2").Match(command)!=0){//----------------------CHI2
     //from lorenzo moneta
     //     TH1 * h1 = datah.createHistogram(x);
     //     TF1 * f = model->asTF(RooArgList(x) , parameters ); //??? 
     //     h2->Fit(f);
     //It will work but you need to create a THNSparse and fit it 
     //or use directly the ROOT::Fit::BinData class to create a ROOT::Fit::Chi2Function to minimize.
     // THIS CANNOT DO ZERO BINS
     fitresult = model->chi2FitTo( datah , Save()  );  
   }else{
     //   FIT    FIT    FIT    FIT    FIT    FIT    FIT     FIT    FIT   FIT   
      fitresult = model->fitTo( datah , Save()  );   
   }

   fitresult->SetTitle( h2->GetName() ); // I PUT histogram name to global fitresult
   
   // will be done by printResult ... fitresult->Print("v") ;
  //duplicite  fitresult->floatParsFinal().Print("s") ;
  // later - after  parsfinale .... : printResult();
    //    model->Print();  // not interesting........
    model->plotOn(xframe, LineColor(kRed),   DrawOption("l0z") );

  //,Minos(kFALSE)

 /*
  *  Posledni nakreslena vec je vychodiskem pro xframe->resid...?
  *   NA PORADI ZALEZI....
  */

    //unused RooHist* hresid = xframe->residHist() ;
 RooHist* hpull =  xframe->pullHist() ;

 // RooPlot* xframe2 = x.frame(Title("Residual Distribution")) ;
 // xframe2->addPlotable(hresid,"P") ;

  // Construct a histogram with the pulls of the data w.r.t the curve
 RooPlot* xframe3 = x.frame(Title("Pull Distribution")) ;
 xframe3->addPlotable(hpull,"P") ;

  /*
   *  plot components at the end....                     PLOT >>>>>>>>>>>>>>>>
   */

 int colorseq[10]={kRed,kGreen,kBlue,kYellow,kCyan,kMagenta,kViolet,kAzure,kGray,kOrange};

 // RooArgSet* model_params = model->getParameters(x); // this returns all parameters
 RooArgSet* model_params = model->getComponents();
 TIterator* iter = model_params->createIterator() ;
 RooAbsArg* arg ; int icomp=0, ipeak=0;
 //  printf("ENTERING COMPONENT ITERATOR x%dx.....................\n",  icomp );
  while((arg=(RooAbsArg*)iter->Next())) {
    //    printf("printing COMPONENT %d\n",  icomp );
    //    arg->Print();    
    //    printf("NAME==%s\n", arg->Class_Name()  ); //This returns only RooAbsArg
    //    printf("NAME==%s\n", arg->ClassName()  ); //This RooGaussian RooChebychev
    if ( IsPeak( arg->ClassName() )==1 ){
      pk[ipeak]=(RooAbsPdf*)arg; //?
      //      pk[ipeak]->Print();
      ipeak++;
      //      printf("adresses ... %d - %d - %d\n", pk[0], pk[1], pk[2]  );
    }// yes peak.
    icomp++; 
  }//iterations over all components


    model->plotOn(xframe, Components(bkg), LineColor(kRed), LineStyle(kDashed),  DrawOption("l0z") );
    for (int i=0;i<npeaks;i++){
      //      printf("plotting  %d. peak, color %d\n", i,  colorseq[i+1]  );
      //      printf("adresses ... %d - %d - %d\n", pk[0], pk[1], pk[2]  );
      //      pk[i]->Print();
      model->plotOn(xframe, Components( RooArgSet(*pk[i],bkg) ), LineColor(colorseq[i+1]), LineStyle(kDashed),
		    DrawOption("l0z") );
      //		    DrawOption("pz"),DataError(RooAbsData::SumW2) );???  pz removes complains...warnings
      //      model.plotOn(xframe, Components( RooArgSet(*pk[i],bkg) ), LineColor(colorseq[i+1]), LineStyle(kDashed));
    }
 

    // WE SET THE 1st PAD in "fitresult" to LOGY....  1
    //  .....  if the original window is LOGY.....   :)
    //
    //    printf("########### ORIGPAD LOGY==%d #########3\n",  orig_gpad->GetLogy()  );
    c->cd(1); xframe->Draw();  gPad->SetLogy(  orig_gpad->GetLogy()  );
 // c->cd(2); xframe2->Draw();  
 c->cd(2); xframe3->Draw();  
  c->Modified();c->Update(); 

 orig_gpad->cd();


 // printf("msat reference to peak 0 0 = %d,  (%f)\n",  msat[0][0] ,  msat[0][0]->getVal()  );
 for (int ii=0;ii<14;ii++){
 for (int jj=0;jj<MAXPEAKS;jj++){
   if ( msat[ii][jj]!=NULL){
     msat_values[ii][jj]=msat[ii][jj]->getVal();
   }//if
 } //for for
 }// for for   
 printf("at the total end of the constructor....%s\n","");
 // done in pirntResult .. fitresult->floatParsFinal().Print("s") ;
 printResult();
  }; // constructor
Esempio n. 20
0
void paper_fit_plot()
{
  SetAtlasStyle();

  // get the stuff from the file
  char fname_postfit[200] = "monoh_withsm_SRCR_bg11.7_bgslop-0.0_nsig0.0.root";
  TFile *tf = new TFile(fname_postfit);
  RooWorkspace *ws_post = (RooWorkspace*)tf->Get("wspace");

  // data and pdf
  RooAbsData *data = ws_post->data("data");
  RooAbsPdf *pdfc = ws_post->pdf("jointModeld");
  
  // variables to be constrained
  RooRealVar *mh = ws_post->var("mh");
  RooRealVar *sigma_h = ws_post->var("sigma_h");
  RooRealVar *eff = ws_post->var("eff");
  RooRealVar *theory = ws_post->var("theory");
  RooRealVar *lumi = ws_post->var("lumi");
  RooRealVar *x_mgg = ws_post->var("mgg");
  RooArgSet cas(*mh,*sigma_h,*eff,*theory,*lumi);  

  // redo the fit
  RooFitResult *r = pdfc->fitTo(*data,RooFit::Constrain(cas),RooFit::Save(true));

  // make the frame
  RooPlot *frame = x_mgg->frame();
  TCanvas *tc = new TCanvas("tc","",700,500);
  frame->GetXaxis()->SetTitle("m_{#gamma#gamma} [GeV]");
  frame->GetYaxis()->SetTitle("Events / 1 GeV");

  // add the data
  data->plotOn(frame,RooFit::Binning(55),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson));
  //data->plotOn(frame,RooFit::Binning(11),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson));


  ///  PDFs
  pdfc->plotOn(frame, RooFit::Components("E"), RooFit::LineColor(kRed),   RooFit::Name("xbackground"));
  pdfc->plotOn(frame, RooFit::Components("S"), RooFit::LineColor(kBlue),RooFit::LineStyle(kDotted),   RooFit::Name("xsm"));
  pdfc->plotOn(frame, RooFit::Components("G"), RooFit::LineColor(kGreen),RooFit::LineStyle(kDotted),   RooFit::Name("xbsm"));
  pdfc->plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed),RooFit::Name("xtotal"));

  frame->SetMinimum(1e-7);
  frame->SetMaximum(9);

  // Legend
  double x1,y1,x2,y2;
  GetX1Y1X2Y2(tc,x1,y1,x2,y2);
  TLegend *legend_sr=FastLegend(x1+0.02,y2-0.3,x1+0.35,y2-0.02,0.045);
  legend_sr->AddEntry(frame->findObject("xdata"),"Data","LEP");
  legend_sr->AddEntry(frame->findObject("xbackground"),"Background fit","L");
  legend_sr->AddEntry(frame->findObject("xsm"),"SM H","L");
  legend_sr->AddEntry(frame->findObject("xbsm"),"Best-fit BSM H","L");
  legend_sr->AddEntry(frame->findObject("xtotal"),"Total","L");
  frame->Draw();
  legend_sr->Draw("SAME");

  // descriptive text
  vector<TString> pavetext11;
  pavetext11.push_back("#bf{#it{ATLAS Internal}}");
  pavetext11.push_back("#sqrt{#it{s}} = 8 TeV #scale[0.6]{#int}#it{L} dt = 20.3 fb^{-1}");
  pavetext11.push_back("#it{H + E}_{T}^{miss} , #it{H #rightarrow #gamma#gamma}, #it{m}_{#it{H}} = 125.4 GeV");

  TPaveText* text11=CreatePaveText(x2-0.47,y2-0.25,x2-0.05,y2-0.05,pavetext11,0.045);
  text11->Draw();
  tc->Print("paper_fit_plot.pdf");
 }
Esempio n. 21
0
//____________________________________
void rs_bernsteinCorrection(){

  // set range of observable
  Double_t lowRange = -1, highRange =5;

  // make a RooRealVar for the observable
  RooRealVar x("x", "x", lowRange, highRange);

  // true model
  RooGaussian narrow("narrow","",x,RooConst(0.), RooConst(.8));
  RooGaussian wide("wide","",x,RooConst(0.), RooConst(2.));
  RooAddPdf reality("reality","",RooArgList(narrow, wide), RooConst(0.8));

  RooDataSet* data = reality.generate(x,1000);

  // nominal model
  RooRealVar sigma("sigma","",1.,0,10);
  RooGaussian nominal("nominal","",x,RooConst(0.), sigma);

  RooWorkspace* wks = new RooWorkspace("myWorksspace");

  wks->import(*data, Rename("data"));
  wks->import(nominal);

  // The tolerance sets the probability to add an unecessary term.
  // lower tolerance will add fewer terms, while higher tolerance
  // will add more terms and provide a more flexible function.
  Double_t tolerance = 0.05; 
  BernsteinCorrection bernsteinCorrection(tolerance);
  Int_t degree = bernsteinCorrection.ImportCorrectedPdf(wks,"nominal","x","data");

  cout << " Correction based on Bernstein Poly of degree " << degree << endl;

  RooPlot* frame = x.frame();
  data->plotOn(frame);
  // plot the best fit nominal model in blue
  nominal.fitTo(*data,PrintLevel(-1));
  nominal.plotOn(frame);

  // plot the best fit corrected model in red
  RooAbsPdf* corrected = wks->pdf("corrected");  
  corrected->fitTo(*data,PrintLevel(-1));
  corrected->plotOn(frame,LineColor(kRed));

  // plot the correction term (* norm constant) in dashed green
  // should make norm constant just be 1, not depend on binning of data
  RooAbsPdf* poly = wks->pdf("poly");  
  poly->plotOn(frame,LineColor(kGreen), LineStyle(kDashed));
  
  // this is a switch to check the sampling distribution
  // of -2 log LR for two comparisons:
  // the first is for n-1 vs. n degree polynomial corrections
  // the second is for n vs. n+1 degree polynomial corrections
  // Here we choose n to be the one chosen by the tolerance
  // critereon above, eg. n = "degree" in the code.
  // Setting this to true is takes about 10 min.
  bool checkSamplingDist = false;

  TCanvas* c1 = new TCanvas();
  if(checkSamplingDist) {
    c1->Divide(1,2);
    c1->cd(1);
  }
  frame->Draw();

  if(checkSamplingDist) {
    // check sampling dist
    TH1F* samplingDist = new TH1F("samplingDist","",20,0,10);
    TH1F* samplingDistExtra = new TH1F("samplingDistExtra","",20,0,10);
    int numToyMC = 1000;
    bernsteinCorrection.CreateQSamplingDist(wks,"nominal","x","data",samplingDist, samplingDistExtra, degree,numToyMC);
    
    c1->cd(2);
    samplingDistExtra->SetLineColor(kRed);
    samplingDistExtra->Draw();
    samplingDist->Draw("same");
  }
}
Esempio n. 22
0
void Fit3D::plotFitProjection(
    const RooRealVar &independant_variable,
    const RooDataSet &data,
    const RooFitResult& fit,
    const RooAbsPdf &model,
    const RooAbsPdf &bs_pdf,
    const RooAbsPdf &bd_pdf,
    const RooAbsPdf &cw_pdf,
    const RooAbsPdf &ww_pdf,
    const RooAbsPdf &cn_pdf,
    const TString &filename)
{
  RooPlot* frame = independant_variable.frame();
  TString frame_title = "Fit Projection on ";
  frame_title.Append(independant_variable.GetTitle());
  frame->SetTitle(frame_title);
  
  RooRealVar* bs_fit = (RooRealVar*) fit.floatParsFinal().find("n_bs_pp");
  RooRealVar* bd_fit = (RooRealVar*) fit.floatParsFinal().find("n_bd_pp");
  RooRealVar* cw_fit = (RooRealVar*) fit.floatParsFinal().find("n_cw_pp");
  RooRealVar* ww_fit = (RooRealVar*) fit.floatParsFinal().find("n_ww_pp");
  RooRealVar* cn_fit = (RooRealVar*) fit.floatParsFinal().find("n_cn_pp");
  
  if (!bs_fit) {
    bs_fit = (RooRealVar*) fit.floatParsFinal().find("n_bs_nn");
    bd_fit = (RooRealVar*) fit.floatParsFinal().find("n_bd_nn");
    cw_fit = (RooRealVar*) fit.floatParsFinal().find("n_cw_nn");
    ww_fit = (RooRealVar*) fit.floatParsFinal().find("n_ww_nn");
    cn_fit = (RooRealVar*) fit.floatParsFinal().find("n_cn_nn");
  }
  if (!bs_fit) {
    // Error. Quit while ahead.
    cout << "Error in plotFitAccuracy(): "
         << "Cannot find fit variables. Check names are valid."
         << endl;
    return;
  }
  
  data.plotOn(frame, RooFit::Name("data"));
  // model.plotOn(frame, RooFit::Name("model"), RooFit::LineColor(kBlue));
  bs_pdf.plotOn(frame,
      RooFit::Normalization(bs_fit->getVal(), RooAbsReal::NumEvent),
      RooFit::LineStyle(kDashed),
      RooFit::LineWidth(1),
      RooFit::LineColor(kYellow + 2));
  data.plotOn(frame, RooFit::Cut(bs_events_cut_),
      RooFit::LineColor(kYellow),
      RooFit::MarkerStyle(kFullDotMedium));
  
  bd_pdf.plotOn(frame,
      RooFit::Normalization(bd_fit->getVal(), RooAbsReal::NumEvent),
      RooFit::LineStyle(kDashed),
      RooFit::LineWidth(1),
      RooFit::LineColor(kRed + 2));
  data.plotOn(frame, RooFit::Cut(bd_events_cut_),
      RooFit::LineColor(kRed),
      RooFit::MarkerStyle(kFullDotMedium));
  cw_pdf.plotOn(frame,
      RooFit::Normalization(cw_fit->getVal(), RooAbsReal::NumEvent),
      RooFit::LineStyle(kDashed),
      RooFit::LineWidth(1),
      RooFit::LineColor(kGreen + 2));
  data.plotOn(frame, RooFit::Cut(cw_events_cut_),
      RooFit::LineColor(kGreen),
      RooFit::MarkerStyle(kFullDotMedium));
  ww_pdf.plotOn(frame,
      RooFit::Normalization(ww_fit->getVal(), RooAbsReal::NumEvent),
      RooFit::LineStyle(kDashed),
      RooFit::LineWidth(1),
      RooFit::LineColor(kBlue + 2));
  data.plotOn(frame, RooFit::Cut(ww_events_cut_),
      RooFit::LineColor(kBlue),
      RooFit::MarkerStyle(kFullDotMedium));
  cn_pdf.plotOn(frame,
      RooFit::Normalization(cn_fit->getVal(), RooAbsReal::NumEvent),
      RooFit::LineStyle(kDashed),
      RooFit::LineWidth(1),
      RooFit::LineColor(kCyan + 2));
  data.plotOn(frame, RooFit::Cut(cn_events_cut_),
      RooFit::LineColor(kCyan),
      RooFit::MarkerStyle(kFullDotMedium));
      
  TCanvas* c1 = new TCanvas("c1", "Projection", 200, 10, 700, 500);
  frame->Draw();
  c1->Print(output_path_ + filename);
}
Esempio n. 23
0
void draw_data_mgg(TString folderName,bool blind=true,float min=103,float max=160)
{
  TFile inputFile(folderName+"/data.root");
  
  const int nCat = 5;
  TString cats[5] = {"HighPt","Hbb","Zbb","HighRes","LowRes"};

  TCanvas cv;

  for(int iCat=0; iCat < nCat; iCat++) {

    RooWorkspace *ws  = (RooWorkspace*)inputFile.Get(cats[iCat]+"_mgg_workspace");
    RooFitResult* res = (RooFitResult*)ws->obj("fitresult_pdf_data");

    RooRealVar * mass = ws->var("mgg");
    mass->setRange("all",min,max);
    mass->setRange("blind",121,130);
    mass->setRange("low",106,121);
    mass->setRange("high",130,160);

    mass->setUnit("GeV");
    mass->SetTitle("m_{#gamma#gamma}");
    
    RooAbsPdf * pdf = ws->pdf("pdf");
    RooPlot *plot = mass->frame(min,max,max-min);
    plot->SetTitle("");
    
    RooAbsData* data = ws->data("data")->reduce(Form("mgg > %f && mgg < %f",min,max));
    double nTot = data->sumEntries();
    if(blind) data = data->reduce("mgg < 121 || mgg>130");
    double nBlind = data->sumEntries();
    double norm = nTot/nBlind; //normalization for the plot
    
    data->plotOn(plot);
    pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::Range("Full"),RooFit::LineWidth(0.1) );
    plot->Print();

    //add the fix error band
    RooCurve* c = plot->getCurve("pdf_Norm[mgg]_Range[Full]_NormRange[Full]");
    const int Nc = c->GetN();
    //TGraphErrors errfix(Nc);
    //TGraphErrors errfix2(Nc);
    TGraphAsymmErrors errfix(Nc);
    TGraphAsymmErrors errfix2(Nc);
    Double_t *x = c->GetX();
    Double_t *y = c->GetY();
    double NtotalFit = ws->var("Nbkg1")->getVal()*ws->var("Nbkg1")->getVal() + ws->var("Nbkg2")->getVal()*ws->var("Nbkg2")->getVal();
    for( int i = 0; i < Nc; i++ )
      {
	errfix.SetPoint(i,x[i],y[i]);
	errfix2.SetPoint(i,x[i],y[i]);
	mass->setVal(x[i]);      
	double shapeErr = pdf->getPropagatedError(*res)*NtotalFit;
	//double totalErr = TMath::Sqrt( shapeErr*shapeErr + y[i] );
	//total normalization error
	double totalErr = TMath::Sqrt( shapeErr*shapeErr + y[i]*y[i]/NtotalFit ); 
	if ( y[i] - totalErr > .0 )
	  {
	    errfix.SetPointError(i, 0, 0, totalErr, totalErr );
	  }
	else
	  {
	    errfix.SetPointError(i, 0, 0, y[i] - 0.01, totalErr );
	  }
	//2sigma
	if ( y[i] -  2.*totalErr > .0 )
	  {
	    errfix2.SetPointError(i, 0, 0, 2.*totalErr,  2.*totalErr );
	  }
	else
	  {
	    errfix2.SetPointError(i, 0, 0, y[i] - 0.01,  2.*totalErr );
	  }
	/*
	std::cout << x[i] << " " << y[i] << " "
		  << " ,pdf get Val: " << pdf->getVal()
		  << " ,pdf get Prop Err: " << pdf->getPropagatedError(*res)*NtotalFit
		  << " stat uncertainty: " << TMath::Sqrt(y[i]) << " Ntot: " << NtotalFit <<  std::endl;
	*/
      }
    errfix.SetFillColor(kYellow);
    errfix2.SetFillColor(kGreen);


    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kGreen),RooFit::Range("Full"), RooFit::VisualizeError(*res,2.0,kFALSE));
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kYellow),RooFit::Range("Full"), RooFit::VisualizeError(*res,1.0,kFALSE));
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kGreen),RooFit::Range("Full"), RooFit::VisualizeError(*res,2.0,kTRUE));
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kYellow),RooFit::Range("Full"), RooFit::VisualizeError(*res,1.0,kTRUE));
    plot->addObject(&errfix,"4");
    plot->addObject(&errfix2,"4");
    plot->addObject(&errfix,"4");
    data->plotOn(plot);
    TBox blindBox(121,plot->GetMinimum()-(plot->GetMaximum()-plot->GetMinimum())*0.015,130,plot->GetMaximum());
    blindBox.SetFillColor(kGray);
    if(blind) {
      plot->addObject(&blindBox);
      pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kGreen),RooFit::Range("Full"), RooFit::VisualizeError(*res,2.0,kTRUE));
      pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::FillColor(kYellow),RooFit::Range("Full"), RooFit::VisualizeError(*res,1.0,kTRUE));
    }
    //plot->addObject(&errfix,"4");
    //data->plotOn(plot);

    //pdf->plotOn(plot,RooFit::Normalization( norm ) );
    //pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::Range("Full"),RooFit::LineWidth(1.5) );
    pdf->plotOn(plot,RooFit::NormRange( "low,high" ),RooFit::Range("Full"), RooFit::LineWidth(1));
    data->plotOn(plot);
    /*
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::Range("all"),RooFit::LineWidth(0.8) );
    //pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kGreen),RooFit::Range("all"), RooFit::VisualizeError(*res,2.0,kFALSE));
    //pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kYellow),RooFit::Range("all"), RooFit::VisualizeError(*res,1.0,kFALSE));
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kGreen),RooFit::Range("all"), RooFit::VisualizeError(*res,2.0,kTRUE));
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::FillColor(kYellow),RooFit::Range("all"), RooFit::VisualizeError(*res,1.0,kTRUE));
    data->plotOn(plot);
    pdf->plotOn(plot,RooFit::Normalization(norm),RooFit::Range("all"),RooFit::LineWidth(0.8) );
    */
    TLatex lbl0(0.1,0.96,"CMS Preliminary");
    lbl0.SetNDC();
    lbl0.SetTextSize(0.042);
    plot->addObject(&lbl0);
    
    TLatex lbl(0.4,0.96,Form("%s Box",cats[iCat].Data()));
    lbl.SetNDC();
    lbl.SetTextSize(0.042);
    plot->addObject(&lbl);

    TLatex lbl2(0.6,0.96,"#sqrt{s}=8 TeV  L = 19.78 fb^{-1}");
    lbl2.SetNDC();
    lbl2.SetTextSize(0.042);
    plot->addObject(&lbl2);


    int iObj=-1;
    TNamed *obj;
    while( (obj = (TNamed*)plot->getObject(++iObj)) ) {
      obj->SetName(Form("Object_%d",iObj));
    }

    plot->Draw();
    TString tag = (blind ? "_BLIND" : "");
    cv.SaveAs(folderName+"/figs/mgg_data_"+cats[iCat]+tag+TString(Form("_%0.0f_%0.0f",min,max))+".png");
    cv.SaveAs(folderName+"/figs/mgg_data_"+cats[iCat]+tag+TString(Form("_%0.0f_%0.0f",min,max))+".pdf");
    cv.SaveAs(folderName+"/figs/mgg_data_"+cats[iCat]+tag+TString(Form("_%0.0f_%0.0f",min,max))+".C");
      
  }
  
}
Esempio n. 24
0
void rf105_funcbinding()
{

   // B i n d   T M a t h : : E r f   C   f u n c t i o n
   // ---------------------------------------------------

   // Bind one-dimensional TMath::Erf function as RooAbsReal function
   RooRealVar x("x","x",-3,3) ;
   RooAbsReal* errorFunc = bindFunction("erf",TMath::Erf,x) ;

   // Print erf definition
   errorFunc->Print() ;

   // Plot erf on frame 
   RooPlot* frame1 = x.frame(Title("TMath::Erf bound as RooFit function")) ;
   errorFunc->plotOn(frame1) ;


   // B i n d   R O O T : : M a t h : : b e t a _ p d f   C   f u n c t i o n
   // -----------------------------------------------------------------------

   // Bind pdf ROOT::Math::Beta with three variables as RooAbsPdf function
   RooRealVar x2("x2","x2",0,0.999) ;
   RooRealVar a("a","a",5,0,10) ;
   RooRealVar b("b","b",2,0,10) ;
   RooAbsPdf* beta = bindPdf("beta",ROOT::Math::beta_pdf,x2,a,b) ;

   // Perf beta definition
   beta->Print() ;

   // Generate some events and fit
   RooDataSet* data = beta->generate(x2,10000) ;
   beta->fitTo(*data) ;

   // Plot data and pdf on frame
   RooPlot* frame2 = x2.frame(Title("ROOT::Math::Beta bound as RooFit pdf")) ;
   data->plotOn(frame2) ;
   beta->plotOn(frame2) ;



   // B i n d   R O O T   T F 1   a s   R o o F i t   f u n c t i o n
   // ---------------------------------------------------------------

   // Create a ROOT TF1 function
   TF1 *fa1 = new TF1("fa1","sin(x)/x",0,10);

   // Create an observable 
   RooRealVar x3("x3","x3",0.01,20) ;

   // Create binding of TF1 object to above observable
   RooAbsReal* rfa1 = bindFunction(fa1,x3) ;

   // Print rfa1 definition
   rfa1->Print() ;

   // Make plot frame in observable, plot TF1 binding function
   RooPlot* frame3 = x3.frame(Title("TF1 bound as RooFit function")) ;
   rfa1->plotOn(frame3) ;



   TCanvas* c = new TCanvas("rf105_funcbinding","rf105_funcbinding",1200,400) ;
   c->Divide(3) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame1->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.6) ; frame2->Draw() ;
   c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;

}
void rs603_HLFactoryElaborateExample() {

  // --- Prepare the 2 needed datacards for this example ---

  TString card_name("rs603_card_WsMaker.rs");
  ofstream ofile(card_name);
  ofile << "// The simplest card for combination\n\n";
  ofile << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n";
  ofile << "flat1 = Polynomial(x,0);\n";
  ofile << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n\n";
  ofile << "echo In the middle!;\n\n";
  ofile << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n";
  ofile << "flat2 = Polynomial(x,0);\n";
  ofile << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n\n";
  ofile << "echo At the end!;\n";
  ofile.close();

  TString card_name2("rs603_card.rs");
  ofstream ofile2(card_name2);
  ofile2 << "// The simplest card for combination\n\n";
  ofile2 << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n";
  ofile2 << "flat1 = Polynomial(x,0);\n";
  ofile2 << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n\n";
  ofile2 << "echo In the middle!;\n\n";
  ofile2 << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n";
  ofile2 << "flat2 = Polynomial(x,0);\n";
  ofile2 << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n\n";
  ofile2 << "#include rs603_included_card.rs;\n\n";
  ofile2 << "echo At the end!;\n";
  ofile2.close();

  TString card_name3("rs603_included_card.rs");
  ofstream ofile3(card_name3);
  ofile3 << "echo Now reading the included file!;\n\n";
  ofile3 << "echo Including datasets in a Workspace in a Root file...;\n";
  ofile3 << "data1 = import(rs603_infile.root,\n";
  ofile3 << "               rs603_ws,\n";
  ofile3 << "               data1);\n\n";
  ofile3 << "data2 = import(rs603_infile.root,\n";
  ofile3 << "               rs603_ws,\n";
  ofile3 << "               data2);\n";
  ofile3.close();

// --- Produce the two separate datasets into a WorkSpace ---

HLFactory hlf("HLFactoryComplexExample",
              "rs603_card_WsMaker.rs",
              false);

RooRealVar* x = static_cast<RooRealVar*>(hlf.GetWs()->arg("x"));
RooAbsPdf* pdf1 = hlf.GetWs()->pdf("sb_model1");
RooAbsPdf* pdf2 = hlf.GetWs()->pdf("sb_model2");

RooWorkspace w("rs603_ws");

RooDataSet* data1 = pdf1->generate(RooArgSet(*x),Extended());
data1->SetName("data1");
w.import(*data1);

RooDataSet* data2 = pdf2->generate(RooArgSet(*x),Extended());
data2->SetName("data2");
w.import(*data2);

// --- Write the WorkSpace into a rootfile ---

TFile outfile("rs603_infile.root","RECREATE");
w.Write();
outfile.Close();

cout << "-------------------------------------------------------------------\n"
     << " Rootfile and Workspace prepared \n"
     << "-------------------------------------------------------------------\n";


HLFactory hlf_2("HLFactoryElaborateExample",
                "rs603_card.rs",
                false);

x = hlf_2.GetWs()->var("x");
pdf1 = hlf_2.GetWs()->pdf("sb_model1");
pdf2 = hlf_2.GetWs()->pdf("sb_model2");

hlf_2.AddChannel("model1","sb_model1","flat1","data1");
hlf_2.AddChannel("model2","sb_model2","flat2","data2");

RooDataSet* data = hlf_2.GetTotDataSet();
RooAbsPdf* pdf = hlf_2.GetTotSigBkgPdf();
RooCategory* thecat = hlf_2.GetTotCategory();

// --- Perform extended ML fit of composite PDF to toy data ---
pdf->fitTo(*data) ;

// --- Plot toy data and composite PDF overlaid ---
RooPlot* xframe = x->frame() ;

data->plotOn(xframe);
thecat->setIndex(0);
pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

thecat->setIndex(1);
pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

gROOT->SetStyle("Plain");

xframe->Draw();

}
Esempio n. 26
0
void buildAndFitModels(TDirectory *fout, RooWorkspace *wspace, RooRealVar &x, std::string proc="Zvv"){

   // Build and fit the model for the Zvv/Wlv background
   RooAbsPdf *pdfZvv 		   = wspace->pdf(doubleexp(wspace,x,Form("%s_control",proc.c_str())));
   RooAbsPdf *pdfZvv_mc 	   = wspace->pdf(doubleexp(wspace,x,Form("%s_control_mc",proc.c_str())));
   RooAbsPdf *pdfZvv_background_mc = wspace->pdf(doubleexp(wspace,x,Form("%s_control_bkg_mc",proc.c_str())));

   pdfZvv_mc->Print("v");
   // Fit control region MC
   std::cout << " Fit for control MC " << Form("%s_control_mc",proc.c_str())<< std::endl;
   RooFitResult *fit_res_control_mc  = pdfZvv_mc->fitTo(*(wspace->data(Form("%s_control_mc",proc.c_str()))),RooFit::Save(1),RooFit::SumW2Error(false));
   fout->cd(); fit_res_control_mc->SetName(Form("fitResult_%s_control_mc",proc.c_str())); fit_res_control_mc->Write();

   std::cout << " Fit for background MC " << Form("%s_control_bkg_mc",proc.c_str()) << std::endl;
   // Fit background MC and then fix it
   pdfZvv_background_mc->fitTo(*(wspace->data(Form("%s_control_bkg_mc",proc.c_str()))),RooFit::SumW2Error(true));
   freezeParameters(pdfZvv_background_mc->getParameters(RooArgSet(x)));
   
   // Now fit the Zvv Data 
   //RooRealVar frac_contamination_Zvv(Form("frac_contamination_%s",proc.c_str()),Form("frac_contamination_%s",proc.c_str()),0,1);
   double nbkgcont = wspace->data(Form("%s_control_bkg_mc",proc.c_str()))->sumEntries();
   double ncont    = wspace->data(Form("%s_control",proc.c_str()))->sumEntries()-nbkgcont;

   RooRealVar num_contamination_Zvv(Form("num_contamination_%s",proc.c_str()),Form("num_contamination_%s",proc.c_str()),nbkgcont,0,10E10);
   num_contamination_Zvv.setConstant();
   RooRealVar num_Zvv(Form("num_%s",proc.c_str()),Form("num_%s",proc.c_str()),ncont,0,10E10);
   num_Zvv.setConstant(true);// freeze the n_data now

   RooAddPdf modelZvv(Form("model_%s_control",proc.c_str()),Form("model_%s_control",proc.c_str()),RooArgList(*pdfZvv_background_mc,*pdfZvv),RooArgList(num_contamination_Zvv,num_Zvv));
   std::cout << " Fit for control Data " << Form("%s_control",proc.c_str()) << std::endl;
   RooFitResult *fit_res_control = modelZvv.fitTo(*(wspace->data(Form("%s_control",proc.c_str()))),RooFit::Save(1));
   fout->cd(); fit_res_control->SetName(Form("fitResult_%s_control",proc.c_str())); fit_res_control->Write();


   // Find the scale of ndata/nmc to normalize the yields
   double nmontecarlo = wspace->data(Form("%s_control_mc",proc.c_str()))->sumEntries();
   double ndata = num_Zvv.getVal();
   RooRealVar scalef(Form("scalef_%s",proc.c_str()),"scalef",ndata/nmontecarlo);
   // uncomment make this ONLY a shape correction!
   // scalef.setVal(1);
   scalef.setConstant(true);

   std::cout << proc.c_str() << " N Control Data == " << ndata       << std::endl;
   std::cout << proc.c_str() << " N Control MC   == " << nmontecarlo << std::endl;

   // Plot the fits
   TCanvas can_datafit(Form("%s_datafit",proc.c_str()),"Data Fit",800,600); 
   RooPlot *pl = x.frame();
   (wspace->data(Form("%s_control_bkg_mc",proc.c_str())))->plotOn(pl,RooFit::MarkerStyle(kOpenCircle));
   (wspace->data(Form("%s_control",proc.c_str())))->plotOn(pl);
   modelZvv.plotOn(pl);
   modelZvv.paramOn(pl);
   //pdfZvv_background_mc->plotOn(pl,RooFit::LineStyle(2));
   pl->Draw();
   fout->cd();can_datafit.Write();

   TCanvas can_mcfit(Form("%s_mcfit",proc.c_str()),"MC Fit",800,600); 
   RooPlot *plmc = x.frame();
   (wspace->data(Form("%s_control_mc",proc.c_str())))->plotOn(plmc,RooFit::MarkerColor(kBlack));
   pdfZvv_mc->plotOn(plmc,RooFit::LineStyle(1),RooFit::LineColor(2));
   pdfZvv_mc->paramOn(plmc);
   plmc->Draw();
   fout->cd();can_mcfit.Write();

   TCanvas can_mcdatafit(Form("%s_mcdatafit",proc.c_str()),"MC and Data Fits",800,600); 
   RooPlot *plmcdata = x.frame();
   pdfZvv_mc->plotOn(plmcdata,RooFit::LineColor(2),RooFit::Normalization(nmontecarlo));
   pdfZvv->plotOn(plmcdata,RooFit::Normalization(ndata));
   plmcdata->Draw();
   fout->cd();can_mcdatafit.Write();

   // Import the correction and the models 
   RooFormulaVar ratio(Form("ratio_%s",proc.c_str()),"@0*@1/@2",RooArgList(scalef,*pdfZvv,*pdfZvv_mc));
   wspace->import(ratio);
   wspace->import(num_Zvv);

   TCanvas can_ra(Form("%s_ratio",proc.c_str()),"MC Fit",800,600); 
   RooPlot *plra = x.frame();
   ratio.plotOn(plra,RooFit::LineStyle(1));
   plra->Draw();
   fout->cd();can_ra.Write();
}
Esempio n. 27
0
void MakePlots(RooWorkspace* ws){

  // Here we make plots of the discriminating variable (invMass) after the fit
  // and of the control variable (isolation) after unfolding with sPlot.
  std::cout << "make plots" << std::endl;

  // make our canvas
  TCanvas* cdata = new TCanvas("sPlot","sPlot demo", 400, 600);
  cdata->Divide(1,3);

  // get what we need out of the workspace
  RooAbsPdf* model = ws->pdf("model");
  RooAbsPdf* zModel = ws->pdf("zModel");
  RooAbsPdf* qcdModel = ws->pdf("qcdModel");

  RooRealVar* isolation = ws->var("isolation");
  RooRealVar* invMass = ws->var("invMass");

  // note, we get the dataset with sWeights
  RooDataSet* data = (RooDataSet*) ws->data("dataWithSWeights");

  // this shouldn't be necessary, need to fix something with workspace
  // do this to set parameters back to their fitted values.
  model->fitTo(*data, Extended() );

  //plot invMass for data with full model and individual componenets overlayed
  //  TCanvas* cdata = new TCanvas();
  cdata->cd(1);
  RooPlot* frame = invMass->frame() ; 
  data->plotOn(frame ) ; 
  model->plotOn(frame) ;   
  model->plotOn(frame,Components(*zModel),LineStyle(kDashed), LineColor(kRed)) ;   
  model->plotOn(frame,Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;   
    
  frame->SetTitle("Fit of model to discriminating variable");
  frame->Draw() ;
 

  // Now use the sWeights to show isolation distribution for Z and QCD.  
  // The SPlot class can make this easier, but here we demonstrait in more
  // detail how the sWeights are used.  The SPlot class should make this 
  // very easy and needs some more development.

  // Plot isolation for Z component.  
  // Do this by plotting all events weighted by the sWeight for the Z component.
  // The SPlot class adds a new variable that has the name of the corresponding
  // yield + "_sw".
  cdata->cd(2);

  // create weightfed data set 
  RooDataSet * dataw_z = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"zYield_sw") ;

  RooPlot* frame2 = isolation->frame() ; 
  dataw_z->plotOn(frame2, DataError(RooAbsData::SumW2) ) ; 
    
  frame2->SetTitle("isolation distribution for Z");
  frame2->Draw() ;

  // Plot isolation for QCD component.  
  // Eg. plot all events weighted by the sWeight for the QCD component.
  // The SPlot class adds a new variable that has the name of the corresponding
  // yield + "_sw".
  cdata->cd(3);
  RooDataSet * dataw_qcd = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"qcdYield_sw") ;
  RooPlot* frame3 = isolation->frame() ; 
  dataw_qcd->plotOn(frame3,DataError(RooAbsData::SumW2) ) ; 
    
  frame3->SetTitle("isolation distribution for QCD");
  frame3->Draw() ;

  //  cdata->SaveAs("SPlot.gif");

}
Esempio n. 28
0
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();
}
void Raa3S_Workspace(const char* name_pbpb="chad_ws_fits/centFits/ws_PbPbData_262548_263757_0cent10_0.0pt50.0_0.0y2.4.root", const char* name_pp="chad_ws_fits/centFits/ws_PPData_262157_262328_-1cent1_0.0pt50.0_0.0y2.4.root", const char* name_out="fitresult_combo.root"){

   //TFile File(filename);

   //RooWorkspace * ws = test_combine(name_pbpb, name_pp);

   TFile *f = new TFile("fitresult_combo_333.root") ;
   RooWorkspace * ws1 = (RooWorkspace*) f->Get("wcombo");

   //File.GetObject("wcombo", ws);
   ws1->Print();
   RooAbsData * data = ws1->data("data"); //dataOS, dataSS

   // RooDataSet * US_data = (RooDataSet*) data->reduce( "QQsign == QQsign::PlusMinus");
   // US_data->SetName("US_data");
   // ws->import(* US_data);
   // RooDataSet * hi_data = (RooDataSet*) US_data->reduce("dataCat == dataCat::hi");
   // hi_data->SetName("hi_data");
   // ws->import(* hi_data);
   // hi_data->Print();

   RooRealVar* raa3 = new RooRealVar("raa3","R_{AA}(#Upsilon (3S))",0.5,-1,1);
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",0);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",1);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*raa3, *leftEdge, *rightEdge));
   ws1->import(step);
   ws1->factory( "Uniform::flat(raa3)" );

   //pp Luminosities, Taa and efficiency ratios Systematics

   ws1->factory( "Taa_hi[5.662e-9]" );
   ws1->factory( "Taa_kappa[1.062]" ); // was 1.057
   ws1->factory( "expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])" );
   ws1->factory( "prod::Taa_nom(Taa_hi,alpha_Taa)" );
   ws1->factory( "Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)" );

   ws1->factory( "lumipp_hi[5.4]" );
   ws1->factory( "lumipp_kappa[1.037]" ); // was 1.06
   ws1->factory( "expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])" );
   ws1->factory( "prod::lumipp_nom(lumipp_hi,alpha_lumipp)" );
   ws1->factory( "Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)" );

   // ws->factory( "effRat1[1]" );
   // ws->factory( "effRat2[1]" );
   ws1->factory( "effRat3_hi[0.95]" );
   ws1->factory( "effRat_kappa[1.054]" );
   ws1->factory( "expr::alpha_effRat('pow(effRat_kappa,beta_effRat)',effRat_kappa,beta_effRat[0,-5,5])" );
   // ws->factory( "prod::effRat1_nom(effRat1_hi,alpha_effRat)" );
   ws1->factory( "Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)" );
   // ws->factory( "prod::effRat2_nom(effRat2_hi,alpha_effRat)" );
   ws1->factory( "prod::effRat3_nom(effRat3_hi,alpha_effRat)" );
   //  
   ws1->factory("Nmb_hi[1.161e9]");
   ws1->factory("prod::denominator(Taa_nom,Nmb_hi)");
   ws1->factory( "expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)");
   RooAbsReal *lumiOverTaaNmbmodified = ws1->function("lumiOverTaaNmbmodified"); //RooFormulaVar *lumiOverTaaNmbmodified = ws->function("lumiOverTaaNmbmodified");
   //  
   //  RooRealVar *raa1 = ws->var("raa1");
   //  RooRealVar* nsig1_pp = ws->var("nsig1_pp");
   //  RooRealVar* effRat1 = ws->function("effRat1_nom");
   //  RooRealVar *raa2 = ws->var("raa2");
   //  RooRealVar* nsig2_pp = ws->var("nsig2_pp");
   //  RooRealVar* effRat2 = ws->function("effRat2_nom");
   RooRealVar* nsig3_pp = ws1->var("R_{#frac{3S}{1S}}_pp"); //RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp");
   cout << nsig3_pp << endl;
   RooAbsReal* effRat3 = ws1->function("effRat3_nom"); //RooRealVar* effRat3 = ws->function("effRat3_nom");
   //  
   //  RooFormulaVar nsig1_hi_modified("nsig1_hi_modified", "@0*@1*@3/@2", RooArgList(*raa1, *nsig1_pp, *lumiOverTaaNmbmodified, *effRat1));
   //  ws->import(nsig1_hi_modified);
   //  RooFormulaVar nsig2_hi_modified("nsig2_hi_modified", "@0*@1*@3/@2", RooArgList(*raa2, *nsig2_pp, *lumiOverTaaNmbmodified, *effRat2));
   //  ws->import(nsig2_hi_modified);
   RooFormulaVar nsig3_hi_modified("nsig3_hi_modified", "@0*@1*@3/@2", RooArgList(*raa3, *nsig3_pp, *lumiOverTaaNmbmodified, *effRat3));
   ws1->import(nsig3_hi_modified);

   //  // background yield with systematics
   ws1->factory( "nbkg_hi_kappa[1.10]" );
   ws1->factory( "expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])" );
   ws1->factory( "SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)" );
   ws1->factory( "Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)" );
   RooAbsPdf* sig1S_hi = ws1->pdf("sig1S_hi"); //RooAbsPdf* sig1S_hi = ws->pdf("cbcb_hi");
   RooAbsPdf* sig2S_hi = ws1->pdf("sig2S_hi");
   RooAbsPdf* sig3S_hi = ws1->pdf("sig3S_hi");
   RooAbsPdf* LSBackground_hi = ws1->pdf("nbkg_hi_nom");
   RooRealVar* nsig1_hi = ws1->var("N_{#Upsilon(1S)}_hi");
   RooRealVar* nsig2_hi = ws1->var("R_{#frac{2S}{1S}}_hi");
   RooAbsReal* nsig3_hi = ws1->function("nsig3_hi_modified"); //RooFormulaVar* nsig3_hi = ws->function("nsig3_hi_modified");
   cout << nsig1_hi << " " << nsig2_hi << " " << nsig3_pp << endl;
   RooRealVar* norm_nbkg_hi = ws1->var("n_{Bkgd}_hi");

   RooArgList pdfs_hi( *sig1S_hi,*sig2S_hi,*sig3S_hi, *LSBackground_hi);
   RooArgList norms_hi(*nsig1_hi,*nsig2_hi,*nsig3_hi, *norm_nbkg_hi);

   ////////////////////////////////////////////////////////////////////////////////

   ws1->factory( "nbkg_pp_kappa[1.03]" );
   ws1->factory( "expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])" );
   ws1->factory( "SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)" );
   ws1->factory( "Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)" );
   RooAbsPdf* sig1S_pp = ws1->pdf("sig1S_pp"); //RooAbsPdf* sig1S_pp = ws1->pdf("cbcb_pp");
   RooAbsPdf* sig2S_pp = ws1->pdf("sig2S_pp");
   RooAbsPdf* sig3S_pp = ws1->pdf("sig3S_pp");
   RooAbsPdf* LSBackground_pp = ws1->pdf("nbkg_pp_nom");
   RooRealVar* nsig1_pp = ws1->var("N_{#Upsilon(1S)}_pp");
   RooRealVar* nsig2_pp = ws1->var("R_{#frac{2S}{1S}}_pp"); //RooRealVar* nsig2_pp = ws1->var("N_{#Upsilon(2S)}_pp");
   // RooRealVar* nsig3_pp = ws1->var("N_{#Upsilon(3S)}_pp");
   RooRealVar* norm_nbkg_pp = ws1->var("n_{Bkgd}_pp");

   RooArgList pdfs_pp( *sig1S_pp,*sig2S_pp,*sig3S_pp, *LSBackground_pp);
   RooArgList norms_pp( *nsig1_pp,*nsig2_pp,*nsig3_pp,*norm_nbkg_pp);

   RooAddPdf model_num("model_num", "model_num", pdfs_hi,norms_hi); 
   ws1->import(model_num);
   ws1->factory("PROD::model_hi(model_num, constr_nbkg_hi,constr_lumipp,constr_Taa,constr_effRat)");

   RooAddPdf model_den("model_den", "model_den", pdfs_pp,norms_pp); 
   ws1->import(model_den);
   ws1->factory("PROD::model_pp(model_den, constr_nbkg_pp)");

   ws1->factory("SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)");



   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws1->var("invariantMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws1->cat("dataCat"));    
   //  /////////////////////////////////////////////////////////////////////
   ws1->var("glob_lumipp")->setConstant(true);
   ws1->var("glob_Taa")->setConstant(true);
   ws1->var("glob_effRat")->setConstant(true);
   ws1->var("glob_nbkg_pp")->setConstant(true);
   ws1->var("glob_nbkg_hi")->setConstant(true);
   RooArgSet globalObs("global_obs");
   globalObs.add( *ws1->var("glob_lumipp") );
   globalObs.add( *ws1->var("glob_Taa") );
   globalObs.add( *ws1->var("glob_effRat") );
   globalObs.add( *ws1->var("glob_nbkg_hi") );
   globalObs.add( *ws1->var("glob_nbkg_pp") );
   cout << "66666" << endl;

   // ws1->Print();

   RooArgSet poi("poi");
   poi.add( *ws1->var("raa3") );



   cout << "77777" << endl;
   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   nuis.add( *ws1->var("beta_lumipp") );
   nuis.add( *ws1->var("beta_nbkg_hi") );
   nuis.add( *ws1->var("beta_nbkg_pp") );
   nuis.add( *ws1->var("beta_Taa") );
   nuis.add( *ws1->var("beta_effRat") );

   cout << "88888" << endl;
   ws1->var("#alpha_{CB}_hi")->setConstant(true);
   ws1->var("#alpha_{CB}_pp")->setConstant(true);
   ws1->var("#sigma_{CB1}_hi")->setConstant(true);
   ws1->var("#sigma_{CB1}_pp")->setConstant(true);
   ws1->var("#sigma_{CB2}/#sigma_{CB1}_hi")->setConstant(true);
   ws1->var("#sigma_{CB2}/#sigma_{CB1}_pp")->setConstant(true);
   //ws1->var("Centrality")->setConstant(true); //delete
   ws1->var("N_{#varUpsilon(1S)}_hi")->setConstant(true);
   ws1->var("N_{#varUpsilon(1S)}_pp")->setConstant(true);
   //ws1->var("N_{#Upsilon(2S)}_hi")->setConstant(true);
   //ws1->var("N_{#Upsilon(2S)}_pp")->setConstant(true);
   //ws1->var("N_{#Upsilon(3S)}_pp")->setConstant(true);

   ws1->var("R_{#frac{2S}{1S}}_hi")->setConstant(true); //new
   ws1->var("R_{#frac{2S}{1S}}_pp")->setConstant(true); //new
   ws1->var("R_{#frac{3S}{1S}}_hi")->setConstant(true); //new
   ws1->var("R_{#frac{3S}{1S}}_pp")->setConstant(true); //new

   ws1->var("Nmb_hi")->setConstant(true);
   // ws1->var("QQsign")->setConstant(true);
   ws1->var("Taa_hi")->setConstant(true);
   ws1->var("Taa_kappa")->setConstant(true);
   // ws1->var("beta_Taa")->setConstant(true);
   // ws1->var("beta_effRat")->setConstant(true);
   // ws1->var("beta_lumipp")->setConstant(true);
   // ws1->var("beta_nbkg_hi")->setConstant(true);
   // ws1->var("beta_nbkg_pp")->setConstant(true);
   // ws1->var("dataCat")->setConstant(true);
   ws1->var("decay_hi")->setConstant(true);
   ws1->var("decay_pp")->setConstant(true);
   ws1->var("effRat3_hi")->setConstant(true);
   ws1->var("effRat_kappa")->setConstant(true);
   // ws1->var("glob_Taa")->setConstant(true);
   // ws1->var("glob_effRat")->setConstant(true);
   // ws1->var("glob_lumipp")->setConstant(true);
   // ws1->var("glob_nbkg_hi")->setConstant(true);
   // ws1->var("glob_nbkg_pp")->setConstant(true);
   // ws1->var("invariantMass")->setConstant(true);
   ws1->var("leftEdge")->setConstant(true);
   ws1->var("lumipp_hi")->setConstant(true);
   ws1->var("lumipp_kappa")->setConstant(true);
   ws1->var("m_{ #varUpsilon(1S)}_hi")->setConstant(true); //ws1->var("mass1S_hi")->setConstant(true);
   ws1->var("m_{ #varUpsilon(1S)}_pp")->setConstant(true); //ws1->var("mass1S_pp")->setConstant(true);
   ws1->var("muMinusPt")->setConstant(true);
   ws1->var("muPlusPt")->setConstant(true);
   ws1->var("n_{Bkgd}_hi")->setConstant(true);
   ws1->var("n_{Bkgd}_pp")->setConstant(true);
   ws1->var("nbkg_hi_kappa")->setConstant(true);
   ws1->var("nbkg_pp_kappa")->setConstant(true);
   //ws1->var("n_{CB}")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   ws1->var("n_{CB}_hi")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   ws1->var("n_{CB}_pp")->setConstant(true); //ws1->var("n_{CB}")->setConstant(true); //ws1->var("npow")->setConstant(true);
   // ws1->var("raa3")->setConstant(true);
   ws1->var("rightEdge")->setConstant(true);
   ws1->var("sigmaFraction_hi")->setConstant(true);
   ws1->var("sigmaFraction_pp")->setConstant(true);
   ws1->var("turnOn_hi")->setConstant(true);
   ws1->var("turnOn_pp")->setConstant(true);
   ws1->var("dimuPt")->setConstant(true); //ws1->var("upsPt")->setConstant(true);
   ws1->var("dimuRapidity")->setConstant(true); //ws1->var("upsRapidity")->setConstant(true);
   ws1->var("vProb")->setConstant(true);
   ws1->var("width_hi")->setConstant(true);
   ws1->var("width_pp")->setConstant(true);
   // ws1->var("x3raw")->setConstant(true);
   //  RooArgSet fixed_again("fixed_again");
   //  fixed_again.add( *ws1->var("leftEdge") );
   //  fixed_again.add( *ws1->var("rightEdge") );
   //  fixed_again.add( *ws1->var("Taa_hi") );
   //  fixed_again.add( *ws1->var("Nmb_hi") );
   //  fixed_again.add( *ws1->var("lumipp_hi") );
   //  fixed_again.add( *ws1->var("effRat1_hi") );
   //  fixed_again.add( *ws1->var("effRat2_hi") );
   //  fixed_again.add( *ws1->var("effRat3_hi") );
   //  fixed_again.add( *ws1->var("nsig3_pp") );
   //  fixed_again.add( *ws1->var("nsig1_pp") );
   //  fixed_again.add( *ws1->var("nbkg_hi") );
   //  fixed_again.add( *ws1->var("alpha") );
   //  fixed_again.add( *ws1->var("nbkg_kappa") );
   //  fixed_again.add( *ws1->var("Taa_kappa") );
   //  fixed_again.add( *ws1->var("lumipp_kappa") );
   // fixed_again.add( *ws1->var("mean_hi") );
   // fixed_again.add( *ws1->var("mean_pp") );
   // fixed_again.add( *ws1->var("width_hi") );
   // fixed_again.add( *ws1->var("turnOn_hi") );
   // fixed_again.add( *ws1->var("bkg_a1_pp") );
   // fixed_again.add( *ws1->var("bkg_a2_pp") );
   // fixed_again.add( *ws1->var("decay_hi") );
   // fixed_again.add( *ws1->var("raa1") );
   // fixed_again.add( *ws1->var("raa2") );
   //  fixed_again.add( *ws1->var("nsig2_pp") );
   // fixed_again.add( *ws1->var("sigma1") );
   //  fixed_again.add( *ws1->var("nbkg_pp") );
   // fixed_again.add( *ws1->var("npow") );
   // fixed_again.add( *ws1->var("muPlusPt") );
   // fixed_again.add( *ws1->var("muMinusPt") );
   // fixed_again.add( *ws1->var("mscale_hi") );
   // fixed_again.add( *ws1->var("mscale_pp") );
   //  
   // ws1->Print();
   cout << "99999" << endl;

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

   // ws1->Print();
   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(10) );
   cout << "111111" << endl;
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   cout << "444444" << endl;
   RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title("LL and profileLL in raa3"));
   cout << "222222" << endl;
   pNll->plotOn(framepoi,ShiftToZero());
   cout << "333333" << endl;
   
   RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
   pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
   pProfile->plotOn(framepoi,LineColor(kRed));
   framepoi->SetMinimum(0);
   framepoi->SetMaximum(3);
   TCanvas *cpoi = new TCanvas();
   cpoi->cd(); framepoi->Draw();
   cpoi->SaveAs("cpoi.pdf");

   ((RooRealVar *)poi.first())->setMin(0.);
   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   // pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
   // pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeSB = pObs->frame(Title("SBhypo"));
   data->plotOn(xframeSB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfSB = sbHypo.GetPdf();
   RooCategory *dataCat = ws1->cat("dataCat");
   pdfSB->plotOn(xframeSB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c1 = new TCanvas();
   c1->cd(); xframeSB->Draw();
   c1->SaveAs("c1.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;
   ws1->import( sbHypo );
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws1);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(2) );
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   ((RooRealVar *)poi.first())->setVal( 0 );  // set raa3=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);

   RooPlot* xframeB = pObs->frame(Title("Bhypo"));
   data->plotOn(xframeB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfB = bHypo.GetPdf();
   pdfB->plotOn(xframeB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c2 = new TCanvas();
   c2->cd(); xframeB->Draw();
   c2->SaveAs("c2.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;

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

   // save workspace to file
   ws1 -> SaveAs(name_out);

   return;
}
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(); */   
  
  
}