Example #1
0
void THSRooFit::PlotDataModel(){
  //Function to plot the data and fitted model for each variable

  TCanvas *canvas=0;
  if(!fCanvases){fCanvases=new TList();fCanvases->SetOwner();fCanvases->SetName(TString("RFPlots")+GetName());}
  //Loop over variables
  for(Int_t idr=0;idr<fVariables.getSize();idr++){
    cout<<"Plotting versus "<<fVariables[idr].GetName()<<endl;
    RooRealVar* var=fWS->var(fVariables[idr].GetName());//get variable
    
    if(!var) continue;
    fCanvases->Add(canvas=new TCanvas(TString(GetName())+fVariables[idr].GetName()+Form("%d",fFiti),TString(GetName())+fVariables[idr].GetName()));//create new canvas for drawing on
    RooPlot* frame = var->frame(); // RooFit frame 
    fData->plotOn(frame, DataError(RooAbsData::SumW2) ) ; //plot the data
    fModel->plotOn(frame,LineColor(kRed)) ; //model = signal + back fit result 
    //Get the chi2
    fChi2=frame->chiSquare();
    cout<<fFiti<<" THSRooFit::PlotDataModel() chi2 = "<<fChi2<<endl;
    fModel->paramOn(frame,
		    Layout(0.1, 0.4, 0.9),
		    Format("NEU",AutoPrecision(2)),
		    ShowConstants()); //show fit parameters
    frame->SetTitle(TString("Fit components for ")+fVariables[idr].GetName());
    //Loop over components
    for(Int_t ic=0;ic<fPDFs.getSize();ic++)
      fModel->plotOn(frame,Components(fPDFs[ic]),LineStyle(kDashed),LineColor(ic%8+1)) ; //just the back fit result  
    frame->Draw() ;
    canvas->Modified();
    canvas->Update();
  }
}
void plot2(RooRealVar *mass, RooAbsPdf *pdf, RooAbsPdf *pdf1, RooAbsPdf *pdf2, float frac, RooDataSet *data, string name, int bins, int mhLow, int mhHigh){
 
 
  RooPlot *plot = mass->frame();
  mass->setRange("unblindReg_1",85,95);
  mass->setRange("unblindReg_2",110,120);
  if (BLIND) {
    data->plotOn(plot,Binning(bins),CutRange("unblindReg_1"));
    data->plotOn(plot,Binning(bins),CutRange("unblindReg_2"));
    data->plotOn(plot,Binning(bins),Invisible());
  }
  else data->plotOn(plot,Binning(bins));

  TCanvas *canv = new TCanvas();

  pdf->plotOn(plot);
  pdf->plotOn(plot,Components(*pdf1),LineColor(kRed),LineStyle(2)) ;
  pdf->plotOn(plot,Components(*pdf2),LineColor(kGreen),LineStyle(2)) ;

//,RooFit::NormRange("fitdata_1,fitdata_2"));
  //pdf->paramOn(plot,RooFit::Layout(0.35,0.89,0.89),RooFit::Format("NEA",AutoPrecision(1)));  
  //plot->getAttText()->SetTextSize(0.01); 
  //plot->SetMaximum(plot->GetMaximum()*2);    
  if (BLIND) plot->SetMinimum(0.0001);
  plot->SetTitle("");
  plot->SetYTitle(Form("Events / %.2fGeV",float(mhHigh-mhLow)/float(bins)));
  //plot->GetYaxis()->SetLabelSize(0.05);
  plot->SetTitleSize(0.045, "Y");
  plot->SetTitleOffset(1.,"Y");
  //plot->GetXaxis()->SetLabelSize(0.15);
  //plot->GetYaxis()->SetLabelSize(0.15);
  plot->SetXTitle("m_{#gamma#gamma}(GeV)");
  plot->SetTitleSize(0.15, "X");
  plot->Draw();

  TLatex *lat = new TLatex();
  lat->SetNDC();
  lat->SetTextFont(42);
  lat->DrawLatex(0.68,0.93,"19.7fb^{-1}(8TeV)"); 
  lat->DrawLatex(0.12,0.85,"CMS Preliminary");   
  lat->DrawLatex(0.7,0.7,Form("Frac = %.3f",frac));  
  string nameTemp = name;
  int catNum = nameTemp.find("cat");
  string catNameOLD = nameTemp.replace(0, catNum, "");
  string catName = catNameOLD.replace(catNameOLD.length()-4, 4, "");
  lat->DrawLatex(0.1,0.92, Form("%s", catName.c_str()));  

     TLegend *leg = new TLegend(0.12,0.7,0.32,0.8);
     leg->SetFillColor(0);
     leg->SetLineColor(1);
     leg->AddEntry(data,"Data","lep");
     leg->Draw("same");

  canv->SaveAs(Form("%s.png",name.c_str()));
  canv->SaveAs(Form("%s.pdf",name.c_str()));
 
  delete canv;
  delete lat;
}
void Plot(RooRealVar *mass, RooDataSet *data, RooAbsPdf *pdf, pair<double,double> sigRange, vector<double> fwhmRange, string title, string savename){

  double semin=sigRange.first;
  double semax=sigRange.second;
  double fwmin=fwhmRange[0];
  double fwmax=fwhmRange[1];
  double halfmax=fwhmRange[2];
  double binwidth=fwhmRange[3];

  RooPlot *plot = mass->frame(Bins(binning_),Range("higgsRange"));
  if (data) data->plotOn(plot,Invisible());
  pdf->plotOn(plot,NormRange("higgsRange"),Range(semin,semax),FillColor(19),DrawOption("F"),LineWidth(2),FillStyle(1001),VLines(),LineColor(15));
  TObject *seffLeg = plot->getObject(int(plot->numItems()-1));
  pdf->plotOn(plot,NormRange("higgsRange"),Range(semin,semax),LineColor(15),LineWidth(2),FillStyle(1001),VLines());
  pdf->plotOn(plot,NormRange("higgsRange"),Range("higgsRange"),LineColor(kBlue),LineWidth(2),FillStyle(0));
  TObject *pdfLeg = plot->getObject(int(plot->numItems()-1));
  if (data) data->plotOn(plot,MarkerStyle(kOpenSquare));
  TObject *dataLeg = plot->getObject(int(plot->numItems()-1));
  TLegend *leg = new TLegend(0.15,0.89,0.5,0.55);
  leg->SetFillStyle(0);
  leg->SetLineColor(0);
  leg->SetTextSize(0.03);
  if (data) leg->AddEntry(dataLeg,"Simulation","lep");
  leg->AddEntry(pdfLeg,"Parametric model","l");
  leg->AddEntry(seffLeg,Form("#sigma_{eff} = %1.2f GeV",0.5*(semax-semin)),"fl");

  plot->GetXaxis()->SetNdivisions(509);
  halfmax*=(plot->getFitRangeBinW()/binwidth);
  TArrow *fwhmArrow = new TArrow(fwmin,halfmax,fwmax,halfmax,0.02,"<>");
  fwhmArrow->SetLineWidth(2.);
  TPaveText *fwhmText = new TPaveText(0.15,0.45,0.45,0.58,"brNDC");
  fwhmText->SetFillColor(0);
  fwhmText->SetLineColor(kWhite);
  fwhmText->SetTextSize(0.03);
  fwhmText->AddText(Form("FWHM = %1.2f GeV",(fwmax-fwmin)));

  TLatex lat1(0.65,0.85,"#splitline{CMS Preliminary}{Simulation}");
  lat1.SetNDC(1);
  lat1.SetTextSize(0.03);
  TLatex lat2(0.65,0.75,title.c_str());
  lat2.SetNDC(1);
  lat2.SetTextSize(0.025);

  TCanvas *canv = new TCanvas("c","c",600,600);
  plot->SetTitle("");
  plot->GetXaxis()->SetTitle("m_{#gamma#gamma} (GeV)");
  plot->Draw();
  leg->Draw("same");
  fwhmArrow->Draw("same <>");
  fwhmText->Draw("same");
  lat1.Draw("same");
  lat2.Draw("same");
  canv->Print(Form("%s.pdf",savename.c_str()));
  canv->Print(Form("%s.png",savename.c_str()));
  string path = savename.substr(0,savename.find('/'));
  canv->Print(Form("%s/animation.gif+100",path.c_str()));
  delete canv;

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

}
//#include "/uscms_data/d3/cvernier/DiH_13TeV/CMSSW_7_1_5/src/HiggsAnalysis/CombinedLimit/interface/RooMultiPdf.h"
//#include "HiggsAnalysis/CombinedLimit/interface/RooMultiPdf.h"
void makeRooMultiPdfWorkspace(){

   // Load the combine Library 
   gSystem->Load("libHiggsAnalysisCombinedLimit.so");

   // Open the dummy H->gg workspace 
   TFile *f_hgg = TFile::Open("w_background_Bern.root");
   RooWorkspace *w_hgg = (RooWorkspace*)f_hgg->Get("HbbHbb");
   // The observable (CMS_hgg_mass in the workspace)
   RooRealVar *mass =  w_hgg->var("x");

   // Get three of the functions inside, exponential, linear polynomial, power law
   RooAbsPdf *pdf_exp = w_hgg->pdf("bg_exp");
   RooAbsPdf *pdf_pol = w_hgg->pdf("bg");


   // Fit the functions to the data to set the "prefit" state (note this can and should be redone with combine when doing 
   // bias studies as one typically throws toys from the "best-fit"
   RooAbsData *data = w_hgg->data("data_obs");
   pdf_exp->fitTo(*data);  // index 0
   pdf_pol->fitTo(*data);   // index 2

   // Make a plot (data is a toy dataset)
   RooPlot *plot = mass->frame();   data->plotOn(plot);
   pdf_exp->plotOn(plot,RooFit::LineColor(kBlue));
   pdf_pol->plotOn(plot,RooFit::LineColor(kRed));
   plot->SetTitle("PDF fits to toy data");
   plot->Draw();

   // Make a RooCategory object. This will control which of the pdfs is "active"
   RooCategory cat("pdf_index","Index of Pdf which is active");

   // Make a RooMultiPdf object. The order of the pdfs will be the order of their index, ie for below 
   // 0 == exponential
   // 1 == linear function
   // 2 == powerlaw
   RooArgList mypdfs;
   mypdfs.add(*pdf_exp);
   mypdfs.add(*pdf_pol);
   
   RooMultiPdf multipdf("roomultipdf","All Pdfs",cat,mypdfs);
   
   // As usual make an extended term for the background with _norm for freely floating yield
   RooRealVar norm("roomultipdf_norm","Number of background events",0,10000);
   
   // Save to a new workspace
   TFile *fout = new TFile("background_pdfs.root","RECREATE");
   RooWorkspace wout("backgrounds","backgrounds");
   wout.import(cat);
   wout.import(norm);
   wout.import(multipdf);
   wout.Print();
   wout.Write();

}
Example #6
0
void THSRooFit::PlotModel(TString varName,TString pdfName){
  TCanvas *canvas=0;
  if(!fCanvases){fCanvases=new TList();fCanvases->SetOwner();}
  RooRealVar* var=fWS->var(varName);//get variable
  fCanvases->Add(canvas=new TCanvas(TString(GetName())+varName+pdfName,TString(GetName())+varName+pdfName));//create new canvas for drawing on
  RooPlot* frame = var->frame(); // RooFit frame
  fWS->pdf(pdfName)->plotOn(frame,LineStyle(kSolid), LineColor(kRed));
  frame->SetTitle(pdfName+TString(" versus ")+varName);
  frame->Draw();
  canvas->Modified();
  canvas->Update();

}
Example #7
0
void Plot(RooRealVar *mass, RooCategory *category, RooDataSet *data, RooSimultaneous *pdf, int nBDTCats, int nSpinCats, bool sm, string name, bool correlateCosThetaCategories=false){

  TCanvas *canv = new TCanvas();
  for (int c=0; c<nBDTCats; c++){
    for (int s=0; s<nSpinCats; s++){
      RooPlot *plot = mass->frame();
      data->plotOn(plot,Cut(Form("category==category::cat%d_spin%d",c,s)));
      if(!correlateCosThetaCategories)
        pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("data_pol_model_cat%d_spin%d",c,s)),ProjWData(*category,*data),LineStyle(kDashed),LineColor(kRed));
      else
        pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("data_pol_model_cat%d",c)),ProjWData(*category,*data),LineStyle(kDashed),LineColor(kRed));
      if (sm) pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("sigModel_SM_cat%d_spin%d",c,s)),ProjWData(*category,*data),LineColor(kRed));
      else pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),Components(Form("sigModel_GRAV_cat%d_spin%d",c,s)),ProjWData(*category,*data),LineColor(kBlue));
      pdf->plotOn(plot,Slice(*category,Form("cat%d_spin%d",c,s)),ProjWData(*category,*data),LineColor(kRed));
      plot->GetXaxis()->SetTitle("m_{#gamma#gamma}");
      plot->SetTitle(Form("cat%d_spin%d",c,s));
      plot->Draw();
      canv->Print(Form("%s_cat%d_spin%d.pdf",name.c_str(),c,s));
      canv->Print(Form("%s_cat%d_spin%d.png",name.c_str(),c,s));
    }
  }
  delete canv;

}
Example #8
0
void drawMassFrom2DPlot(RooWorkspace& myws,   // Local workspace
                  string outputDir,     // Output directory
                  struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                  struct KinCuts cut,   // Variable with current kinematic cuts
                  map<string, string>  parIni,   // Variable containing all initial parameters
                  string plotLabel,     // The label used to define the output file name
                  // Select the type of datasets to fit
                  string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                  bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                  // Select the type of object to fit
                  bool incJpsi,         // Includes Jpsi model
                  bool incPsi2S,        // Includes Psi(2S) model
                  bool incBkg,          // Includes Background model                  
                  // Select the fitting options
                  // Select the drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  double  binWidth,     // Bin width
                  bool paperStyle=false // if true, print less info
                  ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;
  
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  int nBins = min(int( round((cut.dMuon.M.Max - cut.dMuon.M.Min)/binWidth) ), 1000);
  
  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiPRName  = Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfJpsiNoPRName  = Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SPRName  = Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"));
  string pdfPsi2SNoPRName  = Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  bool isMC = (DSTAG.find("MC")!=std::string::npos);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  
  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));

 
  if (paperStyle) TGaxis::SetMaxDigits(3); // to display powers of 10
 
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet(*myws.pdf(Form("pdfMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                       FillStyle(paperStyle ? 0 : 1001), FillColor(kAzure-9), VLines(), DrawOption("LCF"), LineColor(kBlue), LineStyle(kDashed)
                                       );
  if (!paperStyle) {
    if (incJpsi) {
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))), *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
    }
    if (incPsi2S) {
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kRed+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }
      if ( myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))) ) {
        myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet(*myws.pdf(Form("pdfCTAUMASS_Psi2SNoPR_%s", (isPbPb?"PbPb":"PP"))))),
                                             ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                             Normalization(normDSTot, RooAbsReal::NumEvent),
                                             LineColor(kGreen+3), LineStyle(1), Precision(1e-4), NumCPU(32)
                                             );
      }      
    } 
  }
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  // Create the pull distribution of the fit 
  RooPlot* frameTMP = (RooPlot*)frame->Clone("TMP");
  int nBinsTMP = nBins;
  RooHist *hpull = frameTMP->pullHist(0, 0, true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("invMass")->frame(Title("Pull Distribution"), Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  frame2->addPlotable(hpull, "PX"); 
  
  // set the CMS style
  setTDRStyle();
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cMassFig_%s", (isPbPb?"PbPb":"PP")), "cMassFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,paperStyle ? 0 : 0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(cut.dMuon.M.Min, 0.0, cut.dMuon.M.Max, 0.0);
  
  // TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,paperStyle ? 0.29 : 0.36,0.97,paperStyle ? 0.70 : 0.77);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  if (!paperStyle) {
     frame->GetXaxis()->SetTitle("");
     frame->GetXaxis()->SetTitleSize(0.045);
     frame->GetXaxis()->SetTitleFont(42);
     frame->GetXaxis()->SetTitleOffset(3);
     frame->GetXaxis()->SetLabelOffset(3);
     frame->GetYaxis()->SetLabelSize(0.04);
     frame->GetYaxis()->SetTitleSize(0.04);
     frame->GetYaxis()->SetTitleOffset(1.7);
     frame->GetYaxis()->SetTitleFont(42);
  } else {
     frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setMassFrom2DRange(myws, frame, dsOSName, setLogScale);
  if (paperStyle) {
     double Ydown = 0.;//frame->GetMinimum();
     double Yup = 0.9*frame->GetMaximum();
     frame->GetYaxis()->SetRangeUser(Ydown,Yup);
  }
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  if (!paperStyle) pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printMassFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  if (!paperStyle) { // do not print selection details for paper style
     t->DrawLatex(0.20, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
     if (isPbPb) {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } else {
        t->DrawLatex(0.20, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=2.0*0.045;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.5175, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;}
  else {t->DrawLatex(0.5175, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=0.045;}
  t->DrawLatex(0.5175, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.5175, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  if (paperStyle) { ymin = 0.72; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  if (frame->findObject("dOS")) { leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe"); }
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if (frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","l"); }
  if (frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"Prompt J/#psi","l"); }
  if (frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"Non-Prompt J/#psi","l"); }
  if (incBkg && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background",paperStyle ? "l" : "fl"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  // CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  if (!paperStyle) gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  if (!paperStyle) {
     //---plot pull
     pad2->Draw();
     pad2->cd();

     frame2->SetTitle("");
     frame2->GetYaxis()->CenterTitle(kTRUE);
     frame2->GetYaxis()->SetTitleOffset(0.4);
     frame2->GetYaxis()->SetTitleSize(0.1);
     frame2->GetYaxis()->SetLabelSize(0.1);
     frame2->GetYaxis()->SetTitle("Pull");
     frame2->GetXaxis()->CenterTitle(kTRUE);
     frame2->GetXaxis()->SetTitleOffset(1);
     frame2->GetXaxis()->SetTitleSize(0.12);
     frame2->GetXaxis()->SetLabelSize(0.1);
     frame2->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
     frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

     frame2->Draw(); 

     // *** Print chi2/ndof 
     printChi2(myws, pad2, frameTMP, "invMass", dsOSName.c_str(), pdfTotName.c_str(), nBinsTMP, false);

     pline->Draw("same");
     pad2->Update();
  }

  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "MASS", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  
  cFig->Clear();
  cFig->Close();
};
Example #9
0
void BackgroundPrediction(std::string pname,int rebin_factor,int model_number = 0,int imass=750, bool plotBands = false)
{
    rebin = rebin_factor;
    std::string fname = std::string("../fitFilesMETPT34/") + pname + std::string("/histos_bkg.root");
    
    stringstream iimass ;
    iimass << imass;
    std::string dirName = "info_"+iimass.str()+"_"+pname;
    
    
    gStyle->SetOptStat(000000000);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    
    setTDRStyle();
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gStyle->SetOptStat(0000);
    
    writeExtraText = true;       // if extra text
    extraText  = "Preliminary";  // default extra text is "Preliminary"
    lumi_13TeV  = "2.7 fb^{-1}"; // default is "19.7 fb^{-1}"
    lumi_7TeV  = "4.9 fb^{-1}";  // default is "5.1 fb^{-1}"
    
    
    double ratio_tau=-1;
    
    TFile *f=new TFile(fname.c_str());
    TH1F *h_mX_CR_tau=(TH1F*)f->Get("distribs_18_10_1")->Clone("CR_tau");
    TH1F *h_mX_SR=(TH1F*)f->Get("distribs_18_10_0")->Clone("The_SR");
    double maxdata = h_mX_SR->GetMaximum();
    double nEventsSR = h_mX_SR->Integral(600,4000);
    ratio_tau=(h_mX_SR->GetSumOfWeights()/(h_mX_CR_tau->GetSumOfWeights()));
    //double nEventsSR = h_mX_SR->Integral(600,4000);
    
    std::cout<<"ratio tau "<<ratio_tau<<std::endl;
    
    TH1F *h_SR_Prediction;
    TH1F *h_SR_Prediction2;
    
    if(blind) {
        h_SR_Prediction2 = (TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction2");
        h_mX_CR_tau->Rebin(rebin);
        h_mX_CR_tau->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_CR_tau->Clone("h_SR_Prediction");
    } else {
        h_SR_Prediction2=(TH1F*)h_mX_SR->Clone("h_SR_Prediction2");
        h_mX_SR->Rebin(rebin);
        h_mX_SR->SetLineColor(kBlack);
        h_SR_Prediction=(TH1F*)h_mX_SR->Clone("h_SR_Prediction");
        
    }
    h_SR_Prediction->SetMarkerSize(0.7);
    h_SR_Prediction->GetYaxis()->SetTitleOffset(1.2);
    h_SR_Prediction->Sumw2();
    
    /*TFile *f_sig = new TFile((dirName+"/w_signal_"+iimass.str()+".root").c_str());
    RooWorkspace* xf_sig = (RooWorkspace*)f_sig->Get("Vg");
    RooAbsPdf *xf_sig_pdf = (RooAbsPdf *)xf_sig->pdf((std::string("signal_fixed_")+pname).c_str());
    
    RooWorkspace w_sig("w");
    w_sig.import(*xf_sig_pdf,RooFit::RenameVariable((std::string("signal_fixed_")+pname).c_str(),(std::string("signal_fixed_")+pname+std::string("low")).c_str()),RooFit::RenameAllVariablesExcept("low","x"));
    xf_sig_pdf = w_sig.pdf((std::string("signal_fixed_")+pname+std::string("low")).c_str());
   
    RooArgSet* biasVars = xf_sig_pdf->getVariables();
    TIterator *it = biasVars->createIterator();
    RooRealVar* var = (RooRealVar*)it->Next();
    while (var) {
        var->setConstant(kTRUE);
        var = (RooRealVar*)it->Next();
    }
    */
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    
    RooRealVar nBackground((std::string("bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    RooRealVar nBackground2((std::string("alt_bg_")+pname+std::string("_norm")).c_str(),"nbkg",h_mX_SR->GetSumOfWeights());
    std::string blah = pname;
    //pname=""; //Antibtag=tag to constrain b-tag to the anti-btag shape
    
    
    /* RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 4.2, 0, 200.);
     RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", 4.5, 0, 300.);
     RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", 0.000047, 0, 10.1);
     RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(1-@0/13000,@1)/pow(@0/13000,@2+@3*log(@0/13000)))",RooArgList(x,bg_p0,bg_p1,bg_p2));
   */
    RooRealVar bg_p0((std::string("bg_p0_")+pname).c_str(), "bg_p0", 0., -1000, 200.);
    RooRealVar bg_p1((std::string("bg_p1_")+pname).c_str(), "bg_p1", -13, -1000, 1000.);
    RooRealVar bg_p2((std::string("bg_p2_")+pname).c_str(), "bg_p2", -1.4, -1000, 1000.);
    bg_p0.setConstant(kTRUE);
    //RooGenericPdf bg_pure = RooGenericPdf((std::string("bg_pure_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
    RooGenericPdf bg = RooGenericPdf((std::string("bg_")+blah).c_str(),"(pow(@0/13000,@1+@2*log(@0/13000)))",RooArgList(x,bg_p1,bg_p2));
  

    /*TF1* biasFunc = new TF1("biasFunc","(0.63*x/1000-1.45)",1350,3600);
    TF1* biasFunc2 = new TF1("biasFunc2","TMath::Min(2.,2.3*x/1000-3.8)",1350,3600);
    double bias_term_s = 0;
    if ((imass > 2450 && blah == "antibtag") || (imass > 1640 && blah == "btag")) {
        if (blah == "antibtag") {
            bias_term_s = 2.7*biasFunc->Eval(imass);
        } else {
            bias_term_s = 2.7*biasFunc2->Eval(imass);
        }
       bias_term_s/=nEventsSR;
    }
    
    RooRealVar bias_term((std::string("bias_term_")+blah).c_str(), "bias_term", 0., -bias_term_s, bias_term_s);
    //bias_term.setConstant(kTRUE);
    RooAddPdf bg((std::string("bg_")+blah).c_str(), "bg_all", RooArgList(*xf_sig_pdf, bg_pure), bias_term);
    */
    string name_output = "CR_RooFit_Exp";
    
    std::cout<<"Nevents "<<nEventsSR<<std::endl;
    RooDataHist pred("pred", "Prediction from SB", RooArgList(x), h_SR_Prediction);
    RooFitResult *r_bg=bg.fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save());
    //RooFitResult *r_bg=bg.fitTo(pred, RooFit::Range(SR_lo, SR_hi), RooFit::Save(),RooFit::SumW2Error(kTRUE));
    std::cout<<" --------------------- Building Envelope --------------------- "<<std::endl;
    //std::cout<< "bg_p0_"<< pname << "   param   "<<bg_p0.getVal() <<  " "<<bg_p0.getError()<<std::endl;
    std::cout<< "bg_p1_"<< pname << "   param   "<<bg_p1.getVal() <<  " "<<100*bg_p1.getError()<<std::endl;
    std::cout<< "bg_p2_"<< pname << "   param   "<<bg_p2.getVal() <<  " "<<100*bg_p2.getError()<<std::endl;
    //std::cout<< "bias_term_"<< blah << "   param   0 "<<bias_term_s<<std::endl;
    
    RooPlot *aC_plot=x.frame();
    pred.plotOn(aC_plot, RooFit::MarkerColor(kPink+2));
    if (!plotBands) {
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 2), RooFit::FillColor(kYellow));
        bg.plotOn(aC_plot, RooFit::VisualizeError(*r_bg, 1), RooFit::FillColor(kGreen));
    }
    bg.plotOn(aC_plot, RooFit::LineColor(kBlue));
    //pred.plotOn(aC_plot, RooFit::LineColor(kBlack), RooFit::MarkerColor(kBlack));
    
    TGraph* error_curve[5]; //correct error bands
    TGraphAsymmErrors* dataGr = new TGraphAsymmErrors(h_SR_Prediction->GetNbinsX()); //data w/o 0 entries

    for (int i=2; i!=5; ++i) {
        error_curve[i] = new TGraph();
    }
    error_curve[2] = (TGraph*)aC_plot->getObject(1)->Clone("errs");
    int nPoints = error_curve[2]->GetN();
    
    error_curve[0] = new TGraph(2*nPoints);
    error_curve[1] = new TGraph(2*nPoints);
    
    error_curve[0]->SetFillStyle(1001);
    error_curve[1]->SetFillStyle(1001);
    
    error_curve[0]->SetFillColor(kGreen);
    error_curve[1]->SetFillColor(kYellow);
    
    error_curve[0]->SetLineColor(kGreen);
    error_curve[1]->SetLineColor(kYellow);
    
    if (plotBands) {
        RooDataHist pred2("pred2", "Prediction from SB", RooArgList(x), h_SR_Prediction2);

        error_curve[3]->SetFillStyle(1001);
        error_curve[4]->SetFillStyle(1001);
        
        error_curve[3]->SetFillColor(kGreen);
        error_curve[4]->SetFillColor(kYellow);
        
        error_curve[3]->SetLineColor(kGreen);
        error_curve[4]->SetLineColor(kYellow);
        
        error_curve[2]->SetLineColor(kBlue);
        error_curve[2]->SetLineWidth(3);
        
        double binSize = rebin;
        
        for (int i=0; i!=nPoints; ++i) {
            double x0,y0, x1,y1;
            error_curve[2]->GetPoint(i,x0,y0);
            
            RooAbsReal* nlim = new RooRealVar("nlim","y0",y0,-100000,100000);
            //double lowedge = x0 - (SR_hi - SR_lo)/double(2*nPoints);
            //double upedge = x0 + (SR_hi - SR_lo)/double(2*nPoints);
            
            double lowedge = x0 - binSize/2.;
            double upedge = x0 + binSize/2.;
            
            x.setRange("errRange",lowedge,upedge);
            
            RooExtendPdf* epdf = new RooExtendPdf("epdf","extpdf",bg, *nlim,"errRange");
            
            // Construct unbinned likelihood
            RooAbsReal* nll = epdf->createNLL(pred2,NumCPU(2));
            // Minimize likelihood w.r.t all parameters before making plots
            RooMinimizer* minim = new RooMinimizer(*nll);
            minim->setMinimizerType("Minuit2");
            minim->setStrategy(2);
            minim->setPrintLevel(-1);
            minim->migrad();
            
            minim->hesse();
            RooFitResult* result = minim->lastMinuitFit();
            double errm = nlim->getPropagatedError(*result);
            
            //std::cout<<x0<<" "<<lowedge<<" "<<upedge<<" "<<y0<<" "<<nlim->getVal()<<" "<<errm<<std::endl;
            
            error_curve[0]->SetPoint(i,x0,(y0-errm));
            error_curve[0]->SetPoint(2*nPoints-i-1,x0,y0+errm);
            
            error_curve[1]->SetPoint(i,x0,(y0-2*errm));
            error_curve[1]->SetPoint(2*nPoints-i-1,x0,(y0+2*errm));
            
            error_curve[3]->SetPoint(i,x0,-errm/sqrt(y0));
            error_curve[3]->SetPoint(2*nPoints-i-1,x0,errm/sqrt(y0));
            
            error_curve[4]->SetPoint(i,x0,-2*errm/sqrt(y0));
            error_curve[4]->SetPoint(2*nPoints-i-1,x0,2*errm/sqrt(y0));
            
        }
        
        int npois = 0;
        dataGr->SetMarkerSize(1.0);
        dataGr->SetMarkerStyle (20);
        
        const double alpha = 1 - 0.6827;
        
        for (int i=0; i!=h_SR_Prediction->GetNbinsX(); ++i){
            if (h_SR_Prediction->GetBinContent(i+1) > 0) {
                
                int N = h_SR_Prediction->GetBinContent(i+1);
                double L =  (N==0) ? 0  : (ROOT::Math::gamma_quantile(alpha/2,N,1.));
                double U =  ROOT::Math::gamma_quantile_c(alpha/2,N+1,1) ;
                
                dataGr->SetPoint(npois,h_SR_Prediction->GetBinCenter(i+1),h_SR_Prediction->GetBinContent(i+1));
                dataGr->SetPointEYlow(npois, N-L);
                dataGr->SetPointEYhigh(npois, U-N);
                npois++;
            }
        }
    }
    
    double xG[2] = {-10,4000};
    double yG[2] = {0.0,0.0};
    TGraph* unityG = new TGraph(2, xG, yG);
    unityG->SetLineColor(kBlue);
    unityG->SetLineWidth(1);

    double xPad = 0.3;
    TCanvas *c_rooFit=new TCanvas("c_rooFit", "c_rooFit", 800*(1.-xPad), 600);
    c_rooFit->SetFillStyle(4000);
    c_rooFit->SetFrameFillColor(0);
    
    TPad *p_1=new TPad("p_1", "p_1", 0, xPad, 1, 1);
    p_1->SetFillStyle(4000);
    p_1->SetFrameFillColor(0);
    p_1->SetBottomMargin(0.02);
    TPad* p_2 = new TPad("p_2", "p_2",0,0,1,xPad);
    p_2->SetBottomMargin((1.-xPad)/xPad*0.13);
    p_2->SetTopMargin(0.03);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    
    int nbins = (int) (SR_hi- SR_lo)/rebin;
    x.setBins(nbins);
    
    std::cout << "chi2(data) " <<  aC_plot->chiSquare()<<std::endl;
    
    //std::cout << "p-value: data     under hypothesis H0:  " << TMath::Prob(chi2_data->getVal(), nbins - 1) << std::endl;
    
    aC_plot->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    aC_plot->GetXaxis()->SetLabelOffset(0.02);
    aC_plot->GetYaxis()->SetRangeUser(0.1, 1000.);
    h_SR_Prediction->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    string rebin_ = itoa(rebin);
    
    aC_plot->GetXaxis()->SetTitle("M_{Z#gamma} [GeV] ");
    aC_plot->GetYaxis()->SetTitle(("Events / "+rebin_+" GeV ").c_str());
    aC_plot->SetMarkerSize(0.7);
    aC_plot->GetYaxis()->SetTitleOffset(1.2);
    aC_plot->Draw();
    
    if (plotBands) {
        error_curve[1]->Draw("Fsame");
        error_curve[0]->Draw("Fsame");
        error_curve[2]->Draw("Lsame");
        dataGr->Draw("p e1 same");
    }
    
    aC_plot->SetTitle("");
    TPaveText *pave = new TPaveText(0.85,0.4,0.67,0.5,"NDC");
    pave->SetBorderSize(0);
    pave->SetTextSize(0.05);
    pave->SetTextFont(42);
    pave->SetLineColor(1);
    pave->SetLineStyle(1);
    pave->SetLineWidth(2);
    pave->SetFillColor(0);
    pave->SetFillStyle(0);
    char name[1000];
    sprintf(name,"#chi^{2}/n = %.2f",aC_plot->chiSquare());
    pave->AddText(name);
    //pave->Draw();
    
    TLegend *leg = new TLegend(0.88,0.65,0.55,0.90,NULL,"brNDC");
    leg->SetBorderSize(0);
    leg->SetTextSize(0.05);
    leg->SetTextFont(42);
    leg->SetLineColor(1);
    leg->SetLineStyle(1);
    leg->SetLineWidth(2);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    h_SR_Prediction->SetMarkerColor(kBlack);
    h_SR_Prediction->SetLineColor(kBlack);
    h_SR_Prediction->SetMarkerStyle(20);
    h_SR_Prediction->SetMarkerSize(1.0);
    //h_mMMMMa_3Tag_SR->GetXaxis()->SetTitleSize(0.09);
    if (blind)
        leg->AddEntry(h_SR_Prediction, "Data: sideband", "ep");
    else {
        if (blah == "antibtag" )
            leg->AddEntry(h_SR_Prediction, "Data: anti-b-tag SR", "ep");
        else
            leg->AddEntry(h_SR_Prediction, "Data: b-tag SR", "ep");
        
    }
    
    leg->AddEntry(error_curve[2], "Fit model", "l");
    leg->AddEntry(error_curve[0], "Fit #pm1#sigma", "f");
    leg->AddEntry(error_curve[1], "Fit #pm2#sigma", "f");
    leg->Draw();
    
    aC_plot->Draw("axis same");
    
    
    CMS_lumi( p_1, iPeriod, iPos );
    
    p_2->cd();
    RooHist* hpull;
    hpull = aC_plot->pullHist();
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetRangeUser(-7,7);
    frameP->GetYaxis()->SetNdivisions(505);
    frameP->GetYaxis()->SetTitle("#frac{(data-fit)}{#sigma_{stat}}");
    
    frameP->GetYaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    frameP->GetYaxis()->SetTitleOffset(1.0/((1.-xPad)/xPad));
    frameP->GetXaxis()->SetTitleSize((1.-xPad)/xPad*0.06);
    //frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    frameP->GetYaxis()->SetLabelSize((1.-xPad)/xPad*0.05);
    
    
    frameP->Draw();
    if (plotBands) {
        error_curve[4]->Draw("Fsame");
        error_curve[3]->Draw("Fsame");
        unityG->Draw("same");
        hpull->Draw("psame");
        
        frameP->Draw("axis same");
    }
    
    
    c_rooFit->SaveAs((dirName+"/"+name_output+".pdf").c_str());
    
    const int nModels = 9;
    TString models[nModels] = {
        "env_pdf_0_13TeV_dijet2", //0
        "env_pdf_0_13TeV_exp1", //1
        "env_pdf_0_13TeV_expow1", //2
        "env_pdf_0_13TeV_expow2", //3 => skip
        "env_pdf_0_13TeV_pow1", //4
        "env_pdf_0_13TeV_lau1", //5
        "env_pdf_0_13TeV_atlas1", //6
        "env_pdf_0_13TeV_atlas2", //7 => skip
        "env_pdf_0_13TeV_vvdijet1" //8
    };
    
    int nPars[nModels] = {
        2, 1, 2, 3, 1, 1, 2, 3, 2
    };
    
    TString parNames[nModels][3] = {
        "env_pdf_0_13TeV_dijet2_log1","env_pdf_0_13TeV_dijet2_log2","",
        "env_pdf_0_13TeV_exp1_p1","","",
        "env_pdf_0_13TeV_expow1_exp1","env_pdf_0_13TeV_expow1_pow1","",
        "env_pdf_0_13TeV_expow2_exp1","env_pdf_0_13TeV_expow2_pow1","env_pdf_0_13TeV_expow2_exp2",
        "env_pdf_0_13TeV_pow1_p1","","",
        "env_pdf_0_13TeV_lau1_l1","","",
        "env_pdf_0_13TeV_atlas1_coeff1","env_pdf_0_13TeV_atlas1_log1","",
        "env_pdf_0_13TeV_atlas2_coeff1","env_pdf_0_13TeV_atlas2_log1","env_pdf_0_13TeV_atlas2_log2",
        "env_pdf_0_13TeV_vvdijet1_coeff1","env_pdf_0_13TeV_vvdijet1_log1",""
    }
    
    if(bias){
        //alternative model
        gSystem->Load("libHiggsAnalysisCombinedLimit");
        gSystem->Load("libdiphotonsUtils");
        
        TFile *f = new TFile("antibtag_multipdf.root");
        RooWorkspace* xf = (RooWorkspace*)f->Get("wtemplates");
        RooWorkspace *w_alt=new RooWorkspace("Vg");
        for(int i=model_number; i<=model_number; i++){
            RooMultiPdf *alternative = (RooMultiPdf *)xf->pdf("model_bkg_AntiBtag");
            std::cout<<"Number of pdfs "<<alternative->getNumPdfs()<<std::endl;
            for (int j=0; j!=alternative->getNumPdfs(); ++j){
                std::cout<<alternative->getPdf(j)->GetName()<<std::endl;
            }
            RooAbsPdf *alt_bg = alternative->getPdf(alternative->getCurrentIndex()+i);//->clone();
            w_alt->import(*alt_bg, RooFit::RenameVariable(alt_bg->GetName(),("alt_bg_"+blah).c_str()));
            w_alt->Print("V");
            std::cerr<<w_alt->var("x")<<std::endl;
            RooRealVar * range_ = w_alt->var("x");
            range_->setRange(SR_lo,SR_hi);
            char* asd = ("alt_bg_"+blah).c_str()	;
            w_alt->import(nBackground2);
            std::cout<<alt_bg->getVal() <<std::endl;
            w_alt->pdf(asd)->fitTo(pred, RooFit::Minimizer("Minuit2"), RooFit::Range(SR_lo, SR_hi), RooFit::SumW2Error(kTRUE), RooFit::Save());

    	    RooArgSet* altVars = w_alt->pdf(asd)->getVariables();
            TIterator *it2 = altVars->createIterator();
            RooRealVar* varAlt = (RooRealVar*)it2->Next();
            while (varAlt) {
               varAlt->setConstant(kTRUE);
               varAlt = (RooRealVar*)it2->Next();
            }



            alt_bg->plotOn(aC_plot, RooFit::LineColor(i+1), RooFit::LineStyle(i+2));
            p_1->cd();
            aC_plot->GetYaxis()->SetRangeUser(0.01, maxdata*50.);
            aC_plot->Draw("same");
            TH1F *h=new TH1F();
            h->SetLineColor(1+i);
            h->SetLineStyle(i+2);
            leg->AddEntry(h, alt_bg->GetName(), "l");
            
            
            w_alt->SaveAs((dirName+"/w_background_alternative.root").c_str());
        }
        leg->Draw();
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+blah+"_multipdf.pdf").c_str());
        
        for (int i=0; i!=nPars[model_number]; ++i) {
            std::cout<<parNames[model_number][i]<<" param "<< w_alt->var(parNames[model_number][i])->getVal()<<"   "<<w_alt->var(parNames[model_number][i])->getError()<<std::endl;
        }
        
        
    } else {
        p_1->SetLogy();
        c_rooFit->Update();
        c_rooFit->SaveAs((dirName+"/"+name_output+"_log.pdf").c_str());
    }
    
    RooWorkspace *w=new RooWorkspace("Vg");
    w->import(bg);
    w->import(nBackground);
    w->SaveAs((dirName+"/w_background_GaussExp.root").c_str());
    
    TH1F *h_mX_SR_fakeData=(TH1F*)h_mX_SR->Clone("h_mX_SR_fakeData");
    h_mX_SR_fakeData->Scale(nEventsSR/h_mX_SR_fakeData->GetSumOfWeights());
    RooDataHist data_obs("data_obs", "Data", RooArgList(x), h_mX_SR_fakeData);
    std::cout<<" Background number of events = "<<nEventsSR<<std::endl;
    RooWorkspace *w_data=new RooWorkspace("Vg");
    w_data->import(data_obs);
    w_data->SaveAs((dirName+"/w_data.root").c_str());
    
}
Example #10
0
void crossfeeds_nondiag(TString title, 
			TString bkgfile,
			TString epsfile,
			TString txtfile,
			Double_t alpha_,
			Double_t mass_,
			Double_t n_,
			Double_t sigma_
			)
{

  RooRealVar mbc("mbc", "m_{BC}", 1.83, 1.89, "GeV");
  RooRealVar ebeam("ebeam", "Ebeam", 0., 100., "GeV");
  RooRealVar chg("chg", "Charge", -2, 2);
  RooCategory passed("passed", "Event should be used for plot");

  passed.defineType("yes", 1);
  passed.defineType("no", 0);

  RooRealVar arg_cutoff ("arg_cutoff", "Argus cutoff", 1.8865, 1.885, 1.8875,"GeV"); 
  RooRealVar arg_slope ("arg_slope", "Argus slope", -13, -100, 40);

  RooRealVar mbc_float ("mbc_float", "Floating D mass", mass_, "GeV"); 
  RooRealVar sigma ("sigma", "CB width", sigma_, "GeV"); 
  RooRealVar alpha("alpha", "CB shape cutoff", alpha_);
  RooRealVar n("n", "CB tail parameter", n_);

  RooCBShape cb_float ("cb_float", "Floating Crystal Barrel", mbc, mbc_float, sigma, alpha, n); 
  RooArgusBG argus("argus", "Argus BG", mbc, arg_cutoff, arg_slope);

  RooRealVar yld("yield", "D yield", 0, -30, 100000); 
  RooRealVar bkg("bkg", "Background", 20, 0, 40000);

  // Build pdf
  RooAddPdf sumpdf_float("sumpdf_float", "Generic D sum pdf", RooArgList(cb_float, argus),
			   RooArgList(yld, bkg));
  
  RooDataSet* dset = RooDataSet::read(bkgfile, RooArgList(mbc, ebeam, passed), "", "");

  RooPlot* xframe  = mbc.frame();

  RooDataSet* dset2 = dset->reduce("passed==1");

  dset2->plotOn(xframe);
  
  // RooFitResult* rv = sumpdf_float.fitTo(*dset2, Extended(kTRUE), Save(kTRUE),
  // 					Hesse(kTRUE), Verbose(kTRUE));
  RooFitResult* rv = sumpdf_float.fitTo(*dset2, "ermh");

  sumpdf_float.paramOn(xframe, dset2);

  if ((yld.getVal() < 0) && (-yld.getVal()/bkg.getVal() > 0.5)){
    yld.setVal(0);
    bkg.setVal(1);
  }
  
  sumpdf_float.plotOn(xframe);
  sumpdf_float.plotOn(xframe, Components(RooArgSet(argus)),
                      LineColor(kRed), LineStyle(kDashed));

  TCanvas* c1 = new TCanvas("c1","Canvas", 2);
  
  xframe->SetTitleOffset(2.2, "Y");
  xframe->SetTitleOffset(1.1, "X");
  xframe->SetTitle(title);

  c1->SetLeftMargin(0.17);
  xframe->Draw();
  
  if ( rv && rv->covQual() != 3){
    // fit has failed
    TText *txt = new TText();
    txt->SetTextSize(.08);
    txt->SetTextAlign(22);
    txt->SetTextAngle(30);
    txt->DrawTextNDC(0.5, 0.5, "FAILED");
  }
  

  c1->Update();
  c1->Print(epsfile);
  c1->Clear();

  FILE* table = fopen(txtfile.Data(), "w+");
  fprintf(table, "Name\t|| Value\t|| Error\n");
  //  fprintf(table, "yldsigma\t| %.10f\t| \n", yld.getVal()/yld.getError());
  fprintf(table, "entries\t| %.10f\t| \n", dset->numEntries());
  fprintf(table, "yld\t| %.10f\t| %.10f\n",  yld.getVal(), yld.getError());
  //  fprintf(table, "ratio\t| %.10f\t| \n",  yld.getVal()/dset->numEntries());
  //  fprintf(table, "ratioerr\t| %.10f\t| \n",  yld.getError()/dset->numEntries());
  fclose(table);

  cout << "Saved output as: " << txtfile << endl;

  rv->Delete();
}
//-------------------------------------------------------------
//Plot the model fitting function for signal+background
//=============================================================
void MakePlots(RooWorkspace *ws, RooFitResult *fitResult2D) {
  
  RooPlot* framex = 0;
  RooPlot* framey = 0;
  
  //Import yield variables
  RooRealVar *nsig = ws->var("N (Sig)");
  RooRealVar *nres = ws->var("N (ResBkg)");
  RooRealVar *nnonres = ws->var("N (NonResBkg)");
  //Select and plot only one experiment
  if (! (nsig->getVal() >= 15.6 && nsig->getVal() <= 17.0
  				&& nres->getVal() >= 27.9 && nres->getVal() <= 28.0
  				&& nnonres->getVal() <= 287.))
  	return;
  if (alreadyPlotted) return;  
  alreadyPlotted = 1;
  
  //Import the PDF's
  RooAbsPdf *model2Dpdf = ws->pdf("model2Dpdf");
  RooAbsPdf *sigPDFPho = ws->pdf("sigPDFPho");
  RooAbsPdf *resPDFPho = ws->pdf("resPDFPho");
  RooAbsPdf *nonresPDFPho = ws->pdf("nonresPDFPho");
  RooAbsPdf *sigPDFBjet = ws->pdf("sigPDFBjet");
  RooAbsPdf *sigPDFBjetCut = ws->pdf("sigPDFBjetCut");
  RooAbsPdf *resPDFBjet = ws->pdf("resPDFBjet");
  RooAbsPdf *resPDFBjetExt = ws->pdf("resPDFBjetExt");
  RooAbsPdf *nonresPDFBjet = ws->pdf("nonresPDFBjet");
  //x-axis variables
  RooRealVar *massPho = ws->var("massPho");
  RooRealVar *massBjet = ws->var("massBjet");
  RooRealVar *massBjetExt = ws->var("massBjetExt");
  RooRealVar *massBjetCut = ws->var("massBjetCut");
  //sig variables
  RooRealVar *sigMeanBjet = ws->var("sigMeanBjet");
  RooRealVar *sigSigmaBjet = ws->var("sigSigmaBjet");
  RooRealVar *sigAlpha = ws->var("sigAlpha");
  RooRealVar *sigPower = ws->var("sigPower");
  //res bkg variables
  RooRealVar *resMeanBjet = ws->var("resMeanBjet");
  RooRealVar *resSigmaBjet = ws->var("resSigmaBjet");
  RooRealVar *resAlpha = ws->var("resAlpha");
  RooRealVar *resPower = ws->var("resPower");
  RooRealVar *resExpo = ws->var("resExpo");
  RooRealVar *nbbH = ws->var("nbbH");
  RooRealVar *nOthers = ws->var("nOthers");
  //simulated data
  RooDataHist *sigBjetData = (RooDataHist *)ws->data("sigBjetData");
  RooDataHist *resBjetDataExt = (RooDataHist *)ws->data("resBjetDataExt");
  RooDataSet *pseudoData2D = (RooDataSet *)ws->data("pseudoData2D");
  
  //Plot of 2D generated data and fits
  TH1 *data2d = pseudoData2D->createHistogram("2D Data", *massBjet,Binning(25), YVar(*massPho,Binning(25)));
  data2d->SetStats(0);
  TH1 *fit2d = model2Dpdf->createHistogram("2D Fit", *massBjet, YVar(*massPho));
  fit2d->SetStats(0);
  
  cv = new TCanvas("cv","cv",1600,600);
  cv->Divide(2);
  cv->cd(1); gPad->SetLeftMargin(0.15); data2d->Draw("LEGO2");
  data2d->SetTitle("");
  data2d->GetXaxis()->SetTitleOffset(2); data2d->GetXaxis()->SetTitle("M_{bb} [GeV/c^{2}]");
  data2d->GetYaxis()->SetTitleOffset(2.2); data2d->GetYaxis()->SetTitle("M_{#gamma#gamma} [GeV/c^{2}]");
  data2d->GetZaxis()->SetTitleOffset(1.75);
  
  cv->cd(2); gPad->SetLeftMargin(0.15); fit2d->Draw("SURF1");
  fit2d->SetTitle("");
  fit2d->GetXaxis()->SetTitleOffset(2); data2d->GetXaxis()->SetTitle("M_{bb} [GeV/c^{2}]");
  fit2d->GetYaxis()->SetTitleOffset(2.2); data2d->GetYaxis()->SetTitle("M_{#gamma#gamma} [GeV/c^{2}]");
  fit2d->GetZaxis()->SetTitleOffset(1.75);
  cv->SaveAs(Form("Plots/AllSignalBkgd/Fits/Toys/twoDimensionalFits_%d.gif",1));
  
  //Plot of massBjet and massPho projections from 2D fit
  massPho->setRange("PhoWindow",120,130);
  framex = massBjet->frame(Bins(50)); 
  framex->SetTitle(""); framex->SetXTitle("M_{bb} [GeV/c^{2}]");  framex->SetYTitle("Number of Events");
  pseudoData2D->plotOn(framex, CutRange("PhoWindow"));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), VisualizeError(*fitResult2D), FillStyle(3001));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), Components("sigPDFBjet"), LineStyle(kDashed), LineColor(kRed));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), Components("resPDFBjet"), LineStyle(kDashed), LineColor(kOrange));
  model2Dpdf->plotOn(framex, ProjectionRange("PhoWindow"), Components("nonresPDFBjet"), LineStyle(kDashed), LineColor(kGreen));
  
  framey = massPho->frame(Bins(50)); 
  framey->SetTitle(""); framey->SetXTitle("M_{#gamma#gamma} [GeV/c^{2}]");  framey->SetYTitle("Number of Events");
  pseudoData2D->plotOn(framey);
  model2Dpdf->plotOn(framey, VisualizeError(*fitResult2D), FillStyle(3001));
  model2Dpdf->plotOn(framey);
  model2Dpdf->plotOn(framey,Components("sigPDFPho"), LineStyle(kDashed), LineColor(kRed));
  model2Dpdf->plotOn(framey,Components("resPDFPho"), LineStyle(kDashed), LineColor(kOrange));
  model2Dpdf->plotOn(framey,Components("nonresPDFPho"), LineStyle(kDashed), LineColor(kGreen));
  
  cv = new TCanvas("cv","cv",1600,600);
  cv->Divide(2);
  cv->cd(1); framex->Draw();
  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(0.042);
  tex->SetTextFont(42);
  tex->DrawLatex(0.52, 0.84, Form("N_{Sig} = %.2f +/- %.2f", nsig->getVal(), nsig->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.79, Form("N_{ResBkg} = %.2f +/- %.2f", nres->getVal(), nres->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.74, Form("N_{NonResBkg} = %.2f +/- %.2f", nnonres->getVal(), nnonres->getPropagatedError(*fitResult2D)));
  tex->Draw();
  cv->Update();
  cv->cd(2); framey->Draw();
  tex->DrawLatex(0.52, 0.84, Form("N_{Sig} = %.2f +/- %.2f", nsig->getVal(), nsig->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.79, Form("N_{ResBkg} = %.2f +/- %.2f", nres->getVal(), nres->getPropagatedError(*fitResult2D)));
  tex->DrawLatex(0.52, 0.74, Form("N_{NonResBkg} = %.2f +/- %.2f", nnonres->getVal(), nnonres->getPropagatedError(*fitResult2D)));
  tex->Draw();
  cv->Update();
  cv->SaveAs(Form("Plots/AllSignalBkgd/Fits/Toys/projectionFits_%d.gif",1));
}
Example #12
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");
      
  }
  
}
Example #13
0
void drawCtauFrom2DPlot(RooWorkspace& myws,   // Local workspace
                        string outputDir,     // Output directory
                        struct InputOpt opt,  // Variable with run information (kept for legacy purpose)
                        struct KinCuts cut,   // Variable with current kinematic cuts
                        map<string, string>  parIni,   // Variable containing all initial parameters
                        string plotLabel,     // The label used to define the output file name
                        // Select the type of datasets to fit
                        string DSTAG,         // Specifies the type of datasets: i.e, DATA, MCJPSINP, ...
                        bool isPbPb,          // Define if it is PbPb (True) or PP (False)
                        // Select the type of object to fit
                        bool incJpsi,         // Includes Jpsi model
                        bool incPsi2S,        // Includes Psi(2S) model
                        bool incBkg,          // Includes Background model     
                        // Select the fitting options
                        // Select the drawing options
                        bool setLogScale,     // Draw plot with log scale
                        bool incSS,           // Include Same Sign data
                        double binWidth       // Bin width
                        ) 
{

  RooMsgService::instance().getStream(0).removeTopic(Caching);  
  RooMsgService::instance().getStream(1).removeTopic(Caching);
  RooMsgService::instance().getStream(0).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(0).removeTopic(Integration);
  RooMsgService::instance().getStream(1).removeTopic(Integration);
  RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;

  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));

  string pdfTotName  = Form("pdfCTAUMASS_Tot_%s", (isPbPb?"PbPb":"PP"));
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsOSNameCut = dsOSName+"_CTAUCUT";
  string hOSName = Form("dhCTAUERRTot_Tot_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameBkg  = Form("dhCTAUERR_Bkg_%s", (isPbPb?"PbPb":"PP"));
  string hOSNameJpsi = Form("dhCTAUERR_Jpsi_%s", (isPbPb?"PbPb":"PP"));
  string hOSNamePsi2S = Form("dhCTAUERR_Psi2S_%s", (isPbPb?"PbPb":"PP"));
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  bool isWeighted = myws.data(dsOSName.c_str())->isWeighted();
  vector<double> range; range.push_back(cut.dMuon.ctau.Min); range.push_back(cut.dMuon.ctau.Max);

  double minRange = -4.0;
  double maxRange = 7.0;
  Double_t outTot = myws.data(dsOSName.c_str())->numEntries();
  Double_t outErr = myws.data(dsOSName.c_str())->reduce(Form("(ctau>%.6f || ctau<%.6f)", range[1], range[0]))->numEntries();
  int nBins = min(int( round((maxRange - minRange)/binWidth) ), 1000);

  double normDSTot   = 1.0;  if (myws.data(dsOSNameCut.c_str()))  { normDSTot   = myws.data(dsOSName.c_str())->sumEntries()/myws.data(dsOSNameCut.c_str())->sumEntries();  }
  double normJpsi  = 1.0;  if (myws.data(hOSNameJpsi.c_str()))  { normJpsi  = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameJpsi.c_str())->sumEntries();  }
  double normPsi2S = 1.0;  if (myws.data(hOSNamePsi2S.c_str())) { normPsi2S = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNamePsi2S.c_str())->sumEntries(); }
  double normBkg   = 1.0;  if (myws.data(hOSNameBkg.c_str()))   { normBkg   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSNameBkg.c_str())->sumEntries();   }
  double normTot   = 1.0;  if (myws.data(hOSName.c_str()))  { normTot   = myws.data(dsOSName.c_str())->sumEntries()*normDSTot/myws.data(hOSName.c_str())->sumEntries();  }

  // Create the main plot of the fit
  RooPlot*   frame     = myws.var("ctau")->frame(Bins(nBins), Range(minRange, maxRange));
  frame->updateNormVars(RooArgSet(*myws.var("invMass"), *myws.var("ctau"), *myws.var("ctauErr"))) ;
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDF"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kViolet+6), VLines(), DrawOption("LF"), NumCPU(32), LineColor(kBlack)
                                       );
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("BKG"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Bkg_%s", (isPbPb?"PbPb":"PP"))) )),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent),
                                       FillStyle(1001), FillColor(kAzure-9), VLines(), DrawOption("LF"), NumCPU(32)
                                       );
  if (incJpsi) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSIPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("JPSINOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_JpsiNoPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }
  if (incPsi2S) {
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SPR_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kRed+3), Precision(1e-5), NumCPU(32)
                                         );
    myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PSI2SNOPR"),Components(RooArgSet( *myws.pdf(Form("pdfCTAUMASS_Psi2SNo_%s", (isPbPb?"PbPb":"PP"))) )),
                                         ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSName.c_str()), kTRUE),
                                         Normalization(normDSTot, RooAbsReal::NumEvent),
                                         LineColor(kGreen+3), Precision(1e-5), NumCPU(32)
                                         );
  }  
  if (incSS) { 
    myws.data(dsSSName.c_str())->plotOn(frame, Name("dSS"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  }
  myws.data(dsOSName.c_str())->plotOn(frame, Name("dOS"), DataError(RooAbsData::SumW2), XErrorSize(0), MarkerColor(kBlack), LineColor(kBlack), MarkerSize(1.2));
  myws.pdf(pdfTotName.c_str())->plotOn(frame,Name("PDFLINE"),
                                       ProjWData(RooArgSet(*myws.var("ctauErr")), *myws.data(dsOSNameCut.c_str()), kTRUE),
                                       Normalization(normDSTot, RooAbsReal::NumEvent), 
                                       LineColor(kBlack), NumCPU(32)
                                       );
  
  
  // set the CMS style
  setTDRStyle();

  // Create the pull distribution of the fit 
  RooHist *hpull = frame->pullHist(0, "PDF", true);
  hpull->SetName("hpull");
  RooPlot* frame2 = myws.var("ctau")->frame(Title("Pull Distribution"), Bins(nBins), Range(minRange, maxRange));
  frame2->addPlotable(hpull, "PX"); 
  
  // Create the main canvas
  TCanvas *cFig  = new TCanvas(Form("cCtauFig_%s", (isPbPb?"PbPb":"PP")), "cCtauFig",800,800);
  TPad    *pad1  = new TPad(Form("pad1_%s", (isPbPb?"PbPb":"PP")),"",0,0.23,1,1);
  TPad    *pad2  = new TPad(Form("pad2_%s", (isPbPb?"PbPb":"PP")),"",0,0,1,.228);
  TLine   *pline = new TLine(minRange, 0.0, maxRange, 0.0);
  
  TPad *pad4 = new TPad("pad4","This is pad4",0.55,0.46,0.97,0.87);
  pad4->SetFillStyle(0);
  pad4->SetLeftMargin(0.28);
  pad4->SetRightMargin(0.10);
  pad4->SetBottomMargin(0.21);
  pad4->SetTopMargin(0.072);

  frame->SetTitle("");
  frame->GetXaxis()->SetTitle("");
  frame->GetXaxis()->CenterTitle(kTRUE);
  frame->GetXaxis()->SetTitleSize(0.045);
  frame->GetXaxis()->SetTitleFont(42);
  frame->GetXaxis()->SetTitleOffset(3);
  frame->GetXaxis()->SetLabelOffset(3);
  frame->GetYaxis()->SetLabelSize(0.04);
  frame->GetYaxis()->SetTitleSize(0.04);
  frame->GetYaxis()->SetTitleOffset(1.7);
  frame->GetYaxis()->SetTitleFont(42);
  setCtauFrom2DRange(myws, frame, dsOSNameCut, setLogScale, range, outErr);
 
  cFig->cd();
  pad2->SetTopMargin(0.02);
  pad2->SetBottomMargin(0.4);
  pad2->SetFillStyle(4000); 
  pad2->SetFrameFillStyle(4000); 
  pad1->SetBottomMargin(0.015); 
  //plot fit
  pad1->Draw();
  pad1->cd(); 
  frame->Draw();

  printCtauFrom2DParameters(myws, pad1, isPbPb, pdfTotName, isWeighted);
  pad1->SetLogy(setLogScale);

  // Drawing the text in the plot
  TLatex *t = new TLatex(); t->SetNDC(); t->SetTextSize(0.032);
  float dy = 0; 
  
  t->SetTextSize(0.03);
  t->DrawLatex(0.21, 0.86-dy, "2015 HI Soft Muon ID"); dy+=0.045;
  if (isPbPb) {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } else {
    t->DrawLatex(0.21, 0.86-dy, "HLT_HIL1DoubleMu0_v1"); dy+=0.045;
  } 
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq p_{T}^{#mu#mu} < %.1f GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  t->DrawLatex(0.21, 0.86-dy, Form("%.1f #leq |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.21, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}
  if (outErr>0.0) {
    t->DrawLatex(0.21, 0.86-dy, Form("Excl: (%.4f%%) %.0f evts", (outErr*100.0/outTot), outErr)); dy+=1.5*0.045;
  }

  // Drawing the Legend
  double ymin = 0.7602;
  if (incPsi2S && incJpsi && incSS)  { ymin = 0.7202; } 
  if (incPsi2S && incJpsi && !incSS) { ymin = 0.7452; }
  TLegend* leg = new TLegend(0.5175, ymin, 0.7180, 0.8809); leg->SetTextSize(0.03);
  leg->AddEntry(frame->findObject("dOS"), (incSS?"Opposite Charge":"Data"),"pe");
  if (incSS) { leg->AddEntry(frame->findObject("dSS"),"Same Charge","pe"); }
  if(frame->findObject("PDF")) { leg->AddEntry(frame->findObject("PDF"),"Total fit","fl"); }
  if((incBkg && (incJpsi || incPsi2S)) && frame->findObject("BKG")) { leg->AddEntry(frame->findObject("BKG"),"Background","fl");  }
  if(incBkg && incJpsi && frame->findObject("JPSIPR")) { leg->AddEntry(frame->findObject("JPSIPR"),"J/#psi Prompt","l"); }
  if(incBkg && incJpsi && frame->findObject("JPSINOPR")) { leg->AddEntry(frame->findObject("JPSINOPR"),"J/#psi Non-Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SPR")) { leg->AddEntry(frame->findObject("PSI2SPR"),"#psi(2S) Prompt","l"); }
  if(incBkg && incPsi2S && frame->findObject("PSI2SNOPR")) { leg->AddEntry(frame->findObject("PSI2SNOPR"),"#psi(2S) Non-Prompt","l"); }
  leg->Draw("same");

  //Drawing the title
  TString label;
  if (isPbPb) {
    if (opt.PbPb.RunNb.Start==opt.PbPb.RunNb.End){
      label = Form("PbPb Run %d", opt.PbPb.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PbPb", "HIOniaL1DoubleMu0", opt.PbPb.RunNb.Start, opt.PbPb.RunNb.End);
    }
  } else {
    if (opt.pp.RunNb.Start==opt.pp.RunNb.End){
      label = Form("PP Run %d", opt.pp.RunNb.Start);
    } else {
      label = Form("%s [%s %d-%d]", "PP", "DoubleMu0", opt.pp.RunNb.Start, opt.pp.RunNb.End);
    }
  }
  
  //CMS_lumi(pad1, isPbPb ? 105 : 104, 33, label);
  CMS_lumi(pad1, isPbPb ? 108 : 107, 33, "");
  gStyle->SetTitleFontSize(0.05);
  
  pad1->Update();
  cFig->cd(); 

  //---plot pull
  pad2->Draw();
  pad2->cd();
    
  frame2->SetTitle("");
  frame2->GetYaxis()->CenterTitle(kTRUE);
  frame2->GetYaxis()->SetTitleOffset(0.4);
  frame2->GetYaxis()->SetTitleSize(0.1);
  frame2->GetYaxis()->SetLabelSize(0.1);
  frame2->GetYaxis()->SetTitle("Pull");
  frame2->GetXaxis()->CenterTitle(kTRUE);
  frame2->GetXaxis()->SetTitleOffset(1);
  frame2->GetXaxis()->SetTitleSize(0.12);
  frame2->GetXaxis()->SetLabelSize(0.1);
  frame2->GetXaxis()->SetTitle("#font[12]{l}_{J/#psi} (mm)");
  frame2->GetYaxis()->SetRangeUser(-7.0, 7.0);

  frame2->Draw(); 
  
  // *** Print chi2/ndof 
  printChi2(myws, pad2, frame, "ctau", dsOSName.c_str(), pdfTotName.c_str(), nBins, false);
  
  pline->Draw("same");
  pad2->Update();
  
  // Save the plot in different formats
  gSystem->mkdir(Form("%sctauMass/%s/plot/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%sctauMass/%s/plot/root/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/png/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  gSystem->mkdir(Form("%sctauMass/%s/plot/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%sctauMass/%s/plot/pdf/PLOT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), "CTAU", DSTAG.c_str(), (isPbPb?"PbPb":"PP"), plotLabel.c_str(), (cut.dMuon.Pt.Min*10.0), (cut.dMuon.Pt.Max*10.0), (cut.dMuon.AbsRap.Min*10.0), (cut.dMuon.AbsRap.Max*10.0), cut.Centrality.Start, cut.Centrality.End));
  

  cFig->Clear();
  cFig->Close();

}
Example #14
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");

}
Example #15
0
fit_info* do_oneflavor_fit(double scale, TString bg, TString chrg, bool temp, bool redice) {

  RooRealVar *x = new RooRealVar("x","LP variable",-0.4,1.6) ;

  /* RooRealVar *f1 = new RooRealVar("f_{L}","f_{L}",500.,0.,10000.) ; */
  /* RooRealVar *f2 = new RooRealVar("f_{R}","f_{R}",100.,0.,10000.) ; */

  RooRealVar *f1 = new RooRealVar("f_{L}","f_{L}",0.51,0.,1.) ;
  RooRealVar *f2 = new RooRealVar("f_{R}","f_{R}",0.29,0.,1.) ;
  //  RooRealVar *f3 = new RooRealVAr("f_{0}","f_{0}",(1-0.51-0.29),0.,1.);

  bool addqcd=false;
  if(bg.Contains("qcd")) addqcd=true;

  PDF ePDF = PDF(chrg, scale,addqcd,x,f1,f2,redice);

  // Toy MC Study
  TString canvasName_2="pulls";
  canvasName_2+=scale;
  
  if (addqcd) canvasName_2+="_qcd";
  else canvasName_2+="_Wonly";

   TCanvas *cp0 = new TCanvas(canvasName_2,"");

  TLegend *leg = new TLegend(.5,.5,.8,.8,"");
  leg->SetTextSize(0.04);
  leg->SetFillColor(0);
  leg->SetLineColor(0);


  // Correction factors
  TH1D *temp1=ePDF.mc1->Clone(); TH1D *temp2=ePDF.mc2->Clone(); TH1D *temp3=ePDF.mc3->Clone();
 
  float allmc = temp1->Integral()+temp2->Integral()+temp3->Integral();
  float scalef_1 = allmc/temp1->Integral();
  float scalef_2 = allmc/temp2->Integral();
  float scalef_3 = allmc/temp3->Integral();
  /*
  RooCategory tagCat("tagCat","tagging Category");
  tagCat.defineType("eplus");  tagCat.defineType("eminus");

  // Construct combined dataset in (x,tagCat)
  if (redice) {
    RooDataSet combData("ecombData","combined data",*x,Index(tagCat),Import("eplus",*(ePDF.test1_plus)),
		       Import("eminus",*(ePDF.test1_minus)) );
  } else {
    RooDataHist combData("ecombData","combined data",*x,Index(tagCat),Import("eplus",*(ePDF.rtest1_plus)),
		       Import("eminus",*(ePDF.rtest1_minus)) );
  }
  */

  //  (*ePDF.model).fitTo(*ePDF.rtest1,Minos(kTRUE));

  RooNLLVar nll("nll","nll",*ePDF.model,*ePDF.rtest1);
  
  RooMinuit m(nll);

  // Activate constant-term optimization (always recommended)
  m.optimizeConst(kTRUE) ;

  // Activate profile timing
  m.setProfile(kTRUE) ;

  // Activate verbose logging
  m.setVerbose(kTRUE) ;

  // Run HESSE (mx,my,sx,sy free)
  m.hesse() ;

  // Deactivate verbose logging
  m.setVerbose(kFALSE) ;

// Run MIGRAD (mx,my free)
  m.migrad() ;
   // Run MINOS (mx,my,sx free)
  m.minos() ;

  RooFitResult *fitr=m.save();
  fitr->Print();
  //  return;
 //  if (redice) {
//     RooDataSet mdata("d","d",ePDF.test1,*x);
//   } else {
//     RooDataHist mdata("d","d",*x,*ePDF.rtest1);
//   }

  // RooFormulaVar con("constrain","(1-f_{L}-f_{R})<0.",RooArgList(*f1,*f2));
  
  //  RooFitResult *fitr = (*ePDF.model).fitTo(*ePDF.rtest1,Minos(kTRUE),Save(kTRUE));

  fit_info* fit=new fit_info();
 
  /*
  fit->val1 = f1->getVal();
  fit->val2 = f2->getVal();
  fit->err1 =  f1->getError();
  fit->err2  =  f2->getError();
  */
  // Change interpretation of parameters
  fit->val1 = f1->getVal();
  fit->val2 = (1-fit->val1)*f2->getVal();
  fit->err1 =  f1->getError();

  double alpha=(1-fit->val1); double beta=fit->val2;
  double dalpha=-fit->err1; double dbeta=f2->getError();


  fit->err2 = sqrt( beta*beta*dalpha*dalpha + alpha*alpha*dbeta*dbeta +
		    2.*alpha*beta*dalpha*dbeta*fitr->correlation(*f1,*f2) );
		    
  //  fit->err2 = sqrt( (dalpha/alpha)*(dalpha/alpha) +  (dbeta/beta)*(dbeta/beta) +
  //		       2. *((dalpha*dbeta)/(alpha*beta))*fitr->correlation(*f1,*f2)  );

  fit->corr1 = 3*scalef_1/(scalef_1+scalef_2+scalef_3);
  fit->corr2 = 3*scalef_2/(scalef_1+scalef_2+scalef_3);
  fit->corr3 =  3*scalef_3/(scalef_1+scalef_2+scalef_3);
  fit->val1_corr = fit->val1 * fit->corr1;
  fit->val2_corr = fit->val2 * fit->corr2;
  fit->err1_corr = fit->err1 * fit->corr1;
  fit->err2_corr = fit->err2 * fit->corr2;
  fit->gcor1 = fitr->globalCorr(*f1);
  fit->gcor2 = fitr->globalCorr(*f2);
  fit->gcor12 = fitr->correlation(*f1,*f2);

  TString ecanvasName="e";
  TString canvasName="c";
  canvasName+=scale;
  ecanvasName+=scale;
  //  if( plus) canvasName+="plus";
  // else canvasName+="Minus";
  if (addqcd) {
    canvasName+="_qcd";
  }
  else canvasName+="_Wonly";
  ecanvasName+=canvasName;

  setStyles();


  TCanvas *ce = new TCanvas(ecanvasName,"");
 
  RooPlot * xframe = x->frame();
 
  (*ePDF.rtest1).plotOn(xframe,Binning(20));
  (*ePDF.model).plotOn(xframe); (*ePDF.model).paramOn(xframe);
  
  (*ePDF.model).plotOn(xframe,Components(*ePDF.h1),LineColor(kRed),LineStyle(kDashed));
  (*ePDF.model).plotOn(xframe,Components(*ePDF.h2),LineColor(kGreen),LineStyle(kDashed));
  (*ePDF.model).plotOn(xframe,Components(*ePDF.h3),LineColor(kYellow),LineStyle(kDashed));
  
  if (addqcd) {
    (*ePDF.model).plotOn(xframe,Components(*ePDF.bkg),LineColor(kBlack),LineStyle(kDashed));
  } 
  
  xframe->Draw();

  ce->Update();

  //  return;

   // Likelihood contours in two-dimensions

  TString canvasName_1="nll";
  canvasName_1+=scale;
  //  if( plus) canvasName+="plus";
  // else canvasName+="Minus";
  if (addqcd) canvasName_1+="_qcd";
  else canvasName_1+="_Wonly";

  TString canvasName_2="pulls_";
  canvasName_2+=canvasName_1;

  TCanvas *c0 = new TCanvas(canvasName_1,"");

  TLegend *leg = new TLegend(.5,.5,.8,.8,"");
  leg->SetTextSize(0.04);
  leg->SetFillColor(0);
  leg->SetLineColor(0);
  double lumi=(10.*scale);
  
  TString head="L ="; head+=lumi; head+=" pb-1";
  if (addqcd) head+=" (W+QCD)";
  leg->SetHeader(head);

  c0->Divide(2,1);
  c0->cd(1);
  RooPlot *contour = m.contour(*f1,*f2); 
  contour->Draw();

  // m.contour(*f1,*f2)->Draw();
  contour->SetTitle(";f_{1};f_{2}");

  leg->Draw("SAME");

  c0->cd(2);

  RooPlot *ncontour = transform(contour,1.,1.,0);
  //  RooPlot *ncontour = transform(contour,fit->corr1,fit->corr2,0);
  ncontour->Draw();
  //  ncontour->SetTitle(";f_{L};f_{R}");
  //  if (addqcd) 
    return fit;

  // MC STudies
  Int_t nevt=(int)ePDF.stat;

  RooMCStudy mgr(*ePDF.model,*ePDF.model,*x,"","mhv");
  mgr.generateAndFit(500,nevt,kTRUE);

  TCanvas *cp0 = new TCanvas(canvasName_2,"");

  RooPlot* m1pframe = mgr.plotPull(*f1,-4,4,40,kTRUE);
  m1pframe->Draw();

  canvasName_2+="_fr";
  TCanvas *cp02 = new TCanvas(canvasName_2,"");

  RooPlot* m2pframe = mgr.plotPull(*f2,-4,4,40,kTRUE);
  m2pframe->Draw();
  
  canvasName_2+="_f0";
  TCanvas *cp03 = new TCanvas(canvasName_2,"");

  RooPlot* m3pframe = mgr.plotPull(*ePDF.f3,-4,4,40,kTRUE);
  m3pframe->Draw();

  return fit;
}
Example #16
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);
}
Example #17
0
int main(int argc, char *argv[]){
 
  OptionParser(argc,argv);

  TStopwatch sw;
  sw.Start();

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

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

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

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

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

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

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

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

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

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

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

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

  inFile->Close();
  return 0;
}
void makejpsifit(string inputFilename, string outFilename, 
		 Int_t ptBin, Int_t etaBin,
		 double minMass, double maxMass, 
		 double mean_bw, double gamma_bw, double cutoff_cb, double power_cb, 
		 const char* plotOpt, const int nbins, Int_t isMC) {

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

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

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

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

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

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

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

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

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

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

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

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

    data->add(zMassArgSet);
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}
void AddModels(RooWorkspace *ws, const string inputfilePho, Int_t plotOption, Int_t constbkg) {

  gStyle->SetOptFit(0111);
  
  //Import the sample histograms
  TFile *filePho = new TFile(inputfilePho.c_str(), "READ");
  TH1F *sigPhoMass = (TH1F*)filePho->Get("sigPhoMassBJetWin");
  TH1F *nonresPhoMass = (TH1F*)filePho->Get("nonresPhoMassBJetWin");
  
  //-------------------------------------------------------------
  //Make Variables for Fit
  //=============================================================
    
  //Variables for diPhoton
  RooRealVar massPho("massPho","M_{#gamma#gamma}",100.,150.,"GeV/c^{2}");
  RooRealVar massPhoCut("massPhoCut","M_{#gamma#gamma} (Cut)",115.,130.,"GeV/c^{2}");
  //Signal diPhoton
  RooRealVar sigMeanPho("sigMeanPho", "#bar{M}_{#gamma#gamma}", 125., 120., 130., "GeV/c^{2}");
  RooRealVar sigSigmaPho("sigSigmaPho", "#sigma_{#gamma#gamma}", 1.5, 1., 2., "GeV/c^{2}");
  RooRealVar sigAlphaPho("sigAlphaPho","#alpha_{#gamma#gamma} (cut)", 1., 0.1, 2.);
  RooRealVar sigPowerPho("sigPowerPho", "n_{#gamma#gamma} (power)", 3., 1., 5.);
  //Non-Resonant Background diPhoton
  RooRealVar expRatePho("expRatePho", "#lambda_{#gamma#gamma}", -.027, -.1, 0.);
  
  //Weights for the fit
  RooRealVar nsig("N (Sig)", "# signal events", 18.5, -50,100); //(12.7 + 5.8)
  RooRealVar nnonres("N (NonResBkg)", "# non-resonant background events", 99.7, 0,1000);
  
  //-------------------------------------------------------------
  //Make PDFs for Signal + Background
  //=============================================================
  //PDFs for diPhoton
  //Preliminary Fit for Cut Signal
  RooCBShape sigPDFPhoCut("sigPDFPhoCut", "Signal PDF #gamma#gamma", massPhoCut, sigMeanPho, sigSigmaPho, sigAlphaPho, sigPowerPho);
  RooDataHist sigPhoData("sigPhoData", "sigPhoData", massPhoCut, sigPhoMass);
  RooFitResult *sigPhoCBResult = sigPDFPhoCut.fitTo(sigPhoData, RooFit::Strategy(2));
  //Signal
  RooCBShape sigPDFPho("sigPDFPho", "Signal PDF #gamma#gamma", massPho, sigMeanPho, sigSigmaPho, sigAlphaPho, sigPowerPho);

  //Non-Resonant Background
  RooDataHist nonresPhoData("nonresPhoData", "nonresPhoData", massPho, nonresPhoMass);
  RooExponential nonresPDFPho("nonresPDFPho", "Non-Resonant Background PDF #gamma#gamma", massPho, expRatePho);
  RooFitResult *nonresPhoResult = nonresPDFPho.fitTo(nonresPhoData, RooFit::Strategy(2));
  
  RooAddPdf modelpdf("modelpdf", "Signal+Background PDF", RooArgList(sigPDFPho, nonresPDFPho), RooArgList(nsig, nnonres));
  
  //Variables to set constant
  sigMeanPho.setConstant();
  sigSigmaPho.setConstant();
  sigAlphaPho.setConstant();
  sigPowerPho.setConstant();
  expRatePho.setConstant(); 
  
  //Add all stuff to workspace
  modelpdf.graphVizTree("fullModel.dot");
  ws->import(sigPhoData, Rename("sigPhoData"));
  ws->import(nonresPhoData, Rename("nonresPhoData"));
  ws->import(sigPDFPhoCut);
  
  ws->import(modelpdf);
  
  //-------------------------------------------------------------
  //Plot the fitting functions for signal+background
  //=============================================================
  if (plotOption == 1) {
    RooPlot *framex = 0;
    
    //Plot the Crystal Ball Fit for Signal Photon
    cv = new TCanvas("cv","cv",800,600);
    framex = massPhoCut.frame(Bins(50));
    sigPhoData.plotOn(framex, DrawOption("B"), DataError(RooAbsData::None), FillColor(kRed));
    sigPDFPhoCut.plotOn(framex);
    framex->SetTitle(""); framex->SetXTitle("M_{#gamma#gamma} [GeV/c^{2}]");  framex->SetYTitle("Number of Events");
    framex->Draw();
    tex = new TLatex();
    tex->SetNDC();
    tex->SetTextSize(0.048);
    tex->SetTextFont(42);
    tex->DrawLatex(0.64, 0.84, Form("#bar{M}_{#gamma#gamma} = %.2f", sigMeanPho.getVal()));
    tex->DrawLatex(0.64, 0.79, Form("#sigma_{#gamma#gamma} = %.2f", sigSigmaPho.getVal()));
    //tex->DrawLatex(0.64, 0.74, Form("#alpha_{#gamma#gamma} = %.2f", sigAlpha.getVal()));
    //tex->DrawLatex(0.64, 0.69, Form("n_{#gamma#gamma} = %.2f", sigPower.getVal()));
    tex->Draw();
    cv->Update();
    cv->SaveAs("Plots/AllSignalBkgd/Fits/InitialFits/sigPhoCutCB.gif");
    
   
    //Plot Exponential Fit to Non-Resonant Background Bjet 
    cv = new TCanvas("cv","cv",800,600);
    framex = massPho.frame(Bins(50));
    nonresPhoData.plotOn(framex, DrawOption("B"), DataError(RooAbsData::None), FillColor(kGreen));
    nonresPDFPho.plotOn(framex);
    framex->SetTitle(""); framex->SetXTitle("M_{#gamma#gamma} [GeV/c^{2}]");  framex->SetYTitle("Number of Events");
    framex->Draw();
    tex = new TLatex();
    tex->SetNDC();
    tex->SetTextSize(0.048);
    tex->SetTextFont(42);
    tex->DrawLatex(0.64, 0.84, Form("#lambda_{#gamma#gamma} = %.3f", expRatePho.getVal()));
    tex->Draw();
    cv->Update();
    cv->SaveAs("Plots/AllSignalBkgd/Fits/InitialFits/nonresPhoExpo.gif");
    
    
  }//end of plotting
}
Example #20
0
void fitDilMass(){
  
  using namespace RooFit;
  gROOT->SetStyle("Plain");

  //declare variables
  RooRealVar mll("mll",      "dilepton mass",              0,100 ,"GeV");
  RooRealVar edge("edge",    "dilepton mass edge",         0,100 ,"GeV");
  RooRealVar min("min",      "min dilepton mass",          0,100 ,"GeV");
  RooRealVar k("k",          "constant",                   0,100 ,"GeV");
  RooRealVar mean("mean",    "mean of mll resolution",     0,100 ,"GeV");
  RooRealVar sigma("sigma",  "sigma of mll resolution",    0,10  ,"GeV");

  //set variables
  mll.setBins(100);
  edge.setVal(50.);
  mean.setVal(0.);
  sigma.setVal(2.);
  min.setVal(10.);
  min.setConstant();
  k.setVal(1.);
  mean.setConstant();
  sigma.setConstant();
  mll.setMin(0);
  mll.setMax(100);

  //get data
  TFile* file = TFile::Open("LM0_dilmass.root");
  TH1D*  hist = static_cast<TH1D *>((file)->Get("dilmass"));
  RooDataHist data("data","data histogram",RooArgSet(mll),hist);

  //declare and make PDFs
  RooGenericPdf tri("tri","( (mll < min && mll > 0) * k + (mll > min && mll < edge ) * (mll - min) + (mll > edge && mll < 200) * k)", RooArgList(mll , edge, min, k) );
  RooGaussian gaus("gaus","Detector Gaussian",mll,mean,sigma); 
  RooNumConvPdf trigaus("trigaus","triangle + gaussian function",mll,tri,gaus); 
  trigaus.setConvolutionWindow(mean,sigma,25);

  //do fit
  RooFitResult *result = trigaus.fitTo( data , Save() , Minos(kFALSE) , SumW2Error(kFALSE));

  //make plot
  TCanvas *c1=new TCanvas("c1","",800,600);
  c1->cd();

  RooPlot* frame = mll.frame();
  frame->SetXTitle("dilepton mass (GeV)");
  frame->SetYTitle("");
  frame->SetTitle("");
  data.plotOn(frame);
  tri.plotOn(frame , LineStyle(kDashed));
  trigaus.plotOn( frame );
  trigaus.paramOn( frame );
  frame->Draw();
  //frame->SetMinimum(-10);
  //frame->SetMaximum(100);

 
  int nfloatpars = result->floatParsFinal().getSize();
  int ndf        = 20 - nfloatpars;
  float chi2     = frame->chiSquare(nfloatpars)*ndf;
  float prob     = TMath::Prob(chi2,ndf);
 
  cout << endl << endl;
  cout << "Fit Results-------------------------------------------"     << endl;
  cout << "chi2/ndf = " << chi2 << " / " << ndf                        << endl;
  cout << "prob     = " << prob                                        << endl;  
  cout << "edge     = " << edge.getVal() << " +/- " << edge.getError() << endl;
  cout << "k        = " << k.getVal()    << " +/- " << k.getError()    << endl;
  cout << "------------------------------------------------------"     << endl;
  cout << endl << endl;
}
Example #21
0
TCanvas* comparePlots2(RooPlot *plot_bC, RooPlot *plot_bS, TH1F *data, TH1F *qcd, std::string title)
{
    
    RooRealVar x("x", "m_{X} (GeV)", SR_lo, SR_hi);
    TCanvas *c=new TCanvas(("c_RooFit_"+title).c_str(), "c", 700, 700);
    TPad *p_1=new TPad("p_1", "p_1", 0, 0.35, 1, 1);
    gStyle->SetPadGridX(0);
    gStyle->SetPadGridY(0);
    gROOT->SetStyle("Plain");
    p_1->SetFrameFillColor(0);
    TPad *p_2 = new TPad("p_2", "p_2",0,0.003740648,0.9975278,0.3391022);
    p_2->Range(160.1237,-0.8717948,1008.284,2.051282);
    p_2->SetFillColor(0);
    p_2->SetBorderMode(0);
    p_2->SetBorderSize(2);
    p_2->SetTopMargin(0.02);
    p_2->SetBottomMargin(0.3);
    p_2->SetFrameBorderMode(0);
    p_2->SetFrameBorderMode(0);
    
    p_1->Draw();
    p_2->Draw();
    p_1->cd();
    double maxdata=data->GetMaximum();
    double maxqcd=qcd->GetMaximum();
    double maxy=(maxdata>maxqcd) ? maxdata : maxqcd;
    
    title=";m_{X} (GeV); Events / "+itoa(data->GetBinWidth(1))+" GeV";
    p_1->DrawFrame(SR_lo, 0, SR_hi, maxy*1., title.c_str());
    plot_bS->SetMarkerStyle(20);
    plot_bS->Draw("same");
    // plot_bS->Draw("same");
    CMS_lumi( p_1, iPeriod, iPos );
    p_2->cd();
    /* TH1F *h_ratio=(TH1F*)data->Clone("h_ratio");
     h_ratio->GetYaxis()->SetTitle("VR/VSB Ratio");
     h_ratio->GetXaxis()->SetTitle("m_{X} (GeV)");
     h_ratio->SetTitle("");//("VR/VR-SB Ratio "+title+" ; VR/VR-SB Ratio").c_str());
     h_ratio->GetYaxis()->SetTitleSize(0.07);
     h_ratio->GetYaxis()->SetTitleOffset(0.5);
     h_ratio->GetXaxis()->SetTitleSize(0.09);
     h_ratio->GetXaxis()->SetTitleOffset(1.0);
     h_ratio->GetXaxis()->SetLabelSize(0.07);
     h_ratio->GetYaxis()->SetLabelSize(0.06);
     
     h_ratio->Divide(qcd);
     h_ratio->SetLineColor(1);
     h_ratio->SetMarkerStyle(20);
     h_ratio->GetXaxis()->SetRangeUser(SR_lo, SR_hi-10);
     h_ratio->GetYaxis()->SetRangeUser(0.,2.);
     */
    RooHist* hpull;
    hpull = plot_bS->pullHist();
    hpull->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    RooPlot* frameP = x.frame() ;
    frameP->SetTitle("");
    frameP->GetYaxis()->SetTitle("Pull");
    frameP->GetXaxis()->SetRangeUser(SR_lo, SR_hi);
    
    frameP->addPlotable(hpull,"P");
    frameP->GetYaxis()->SetTitle("Pull");
    
    frameP->GetYaxis()->SetTitleSize(0.07);
    frameP->GetYaxis()->SetTitleOffset(0.5);
    frameP->GetXaxis()->SetTitleSize(0.09);
    frameP->GetXaxis()->SetTitleOffset(1.0);
    frameP->GetXaxis()->SetLabelSize(0.07);
    frameP->GetYaxis()->SetLabelSize(0.06);
    
    frameP->Draw();
    
    
    //  TLine *m_one_line = new TLine(SR_lo,1,SR_hi,1);
    
    
    // h_ratio->Draw("");
    // m_one_line->Draw("same");
    p_1->cd();
    return c;
}
Example #22
0
RooPlot *transform(RooPlot *contour, double corx, double cory, bool mode) {

  RooPlot *h;

  if (mode) {
    h = new RooPlot(0.,1.,0.,1.);//contour->Clone(); h->Reset();
  } else {
    h = new RooPlot(0.,1.,0.,1.2);
  }

  contour->Print();
  TGraph *g1 = (TGraph*)contour->findObject("contour_nll_n1.000000");
  TGraph *g2 = (TGraph*)contour->findObject("contour_nll_n2.000000");
  TMarker *point= (TMarker*)contour->findObject("TMarker");

  Double_t ix1[50], ix2[50];
  Double_t iy1prime[50], iy2prime[50];

  Double_t idiff1[50], isum1[50];
  Double_t idiff2[50], isum2[50];

  for (int i=0; i<50; i++) {
     

    ix1[i]=corx*g1->GetX()[i];
    ix2[i]=corx*g2->GetX()[i];

    iy1prime[i]=cory*(1.-(g1->GetX()[i]))*(g1->GetY()[i]);
    iy2prime[i]=cory*(1.-(g2->GetX()[i]))*(g2->GetY()[i]);

    idiff1[i]=ix1[i]-iy1prime[i];
    isum1[i]=ix1[i]+iy1prime[i];

    idiff2[i]=ix2[i]-iy2prime[i];
    isum2[i]=ix2[i]+iy2prime[i];

  }

  Double_t mx=corx*point->GetX();
  Double_t my=cory*(1-point->GetX())*point->GetY();
  TMarker *dpoint; //= new TMarker(mx, my, 8);

  TGraph *c1, *c2;
  if (mode) {
    c1 = new TGraph(50,ix1,iy1prime);
    c2 = new TGraph(50,ix2,iy2prime);
    dpoint=new TMarker(mx,my,8);
    h->SetTitle(";f_{L};f_{R}");
  } else {
    c1 = new TGraph(50,idiff1,isum1);
    c2 = new TGraph(50,idiff2,isum2);
    dpoint=new TMarker((mx-my),(mx+my),8);
    h->SetTitle(";f_{L}-f_{R};f_{L}+f_{R}");
  }
    	c1->SetLineStyle(1) ;
	c1->SetLineWidth(2) ;
	c1->SetLineColor(kBlue) ;

	c2->SetLineStyle(2) ;
	c2->SetLineWidth(2) ;
	c2->SetLineColor(kBlue) ;

  //  c1->Draw("A");
	h->addObject(dpoint);
  h->addObject(c1,"L");
  h->addObject(c2,"L");
  
 /*
  for (int ix=0; ix<=contour->GetNbinsX(); ix++) {
    for (int iy=0; iy<=contour->GetNbinsY(); iy++) {

      double content=contour->GetBinContent(ix,iy);
      
      double y1=contour->GetXaxis()->GetBinCenter(ix);
      double y2=contour->GetYaxis()->GetBinCenter(iy);

      double yprime=(1-y1)*y2;
      int iyprime=contour->GetYaxis()->FindBin(yprime);

      h->SetBinContent(ix,iyprime);
   
    }
  }
 */
  //  h->Draw();
  return h;

}
Example #23
0
int FitInvMassBkg(TH1D* histo, TH1D* histo_bkg, TString signal,TString _bkg){

	//Set Style
	setTDRStyle();

	cout<<"21"<<endl;

	//Path for input and output file. Written in FitDataPath.txt
	ifstream file("FitDataPath.txt");
	string str;
	getline(file,str);
	TString _path = str;

	//Rebin(histo);

	//Getting info about the histogram to fit
	int n = histo->GetEntries();
	double w = histo->GetXaxis()->GetBinWidth(1);
	int ndf;
	double hmin0 = histo->GetXaxis()->GetXmin();
	double hmax0 = histo->GetXaxis()->GetXmax();
	histo->GetXaxis()->SetRangeUser(hmin0,hmax0);

	//Declare observable x
	//Try to rebin using this. Doesn't work for now
        //RooBinning xbins = Rebin2(histo);
	RooRealVar x("x","x",hmin0,hmax0) ;
	RooDataHist dh("dh","dh",x,Import(*histo)) ;

	//Define the frame
	RooPlot* frame;
	frame = x.frame();
	dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7));  //this will show histogram data points on canvas

	//x.setRange("R0",0,200) ;
	x.setRange("R1",55,200) ;

        /////////////////////
	//Define fit function 
	/////////////////////
	
	//fsig for adding two funciton i.e. F(x) = fsig*sig(x) + (1-fsig)*bkg(x)
	RooRealVar fsig("fsig","sigal fraction",0.5, 0., 1.);//before 0.9

	//Various parameters
	
	//True mean
	RooRealVar mean("mean","PDG mean of Z",91.186);//, 70.0, 120.0);
	//For the BW
	RooRealVar width("width","PDG width of Z",2.4952);//, 0., 5.);
	//For the Gauss and the CB alone 
	RooRealVar sigma("sigma","sigma",1, 0., 10.);
	RooRealVar alpha("alpha","alpha",0.7, 0., 7);
	RooRealVar ncb("ncb","ncb",7, 0, 150);
	//For the CB used for convolution, i.e. CBxBW
	RooRealVar cb_bias("cb_bias","bias",0, -3.,3.);
	RooRealVar cb_sigma("cb_sigma","response",1, 0.,5);
	RooRealVar cb_alpha("cb_alpha","alpha",1.,0.,7);
	RooRealVar cb_ncb("cb_ncb","ncb",2, 0, 10);

	mean.setRange(88,94);
	width.setRange(0,20);
	sigma.setRange(0.5,10);
	//fsig.setConstant(kTRUE);
	//alpha.setConstant(kTRUE);

	RooVoigtian sig_bwgau("sig_bwgau","BWxgauss",x,mean,width,sigma);
	RooBreitWigner sig_bw("sig_bw","BW",x,mean,width);
	RooGaussian sig_gau("sig_gau","gauss",x,mean,sigma);
	RooCBShape sig_cb("sig_cb", "Crystal Ball",x,mean,sigma,alpha,ncb);
	RooCBShape sig_cb_resp("sig_cb_resp", "Crystal Ball for conv.",x,cb_bias,cb_sigma,cb_alpha,cb_ncb);

	x.setBins(10000,"cache");
	RooFFTConvPdf sig_cbbw("sig_cbbw","CBxBW",x,sig_cb_resp,sig_bw);

	//NB: The CrystalBall shape is Gaussian that is 'connected' to an exponential taill at 'alpha' sigma of the Gaussian. The sign determines if it happens on the left or right side. The 'n' parameter control the slope of the exponential part. 

	RooAbsPdf* sig;
	if(signal == "BWxGau"){sig = &sig_bwgau;}
	else if(signal == "BW"){sig = &sig_bw;}
	else if(signal == "Gau"){sig = &sig_gau;}
	else if(signal == "CB"){sig = &sig_cb;}
	else if(signal == "CBxBW"){ sig = &sig_cbbw;}
	else{ cout<<"Wrong signal function name"<<endl;
		return 1;
	}

	/////////////////////////////
	//Background fitting function
	/////////////////////////////
	
	//Get the initial parameter of the background
	//


	vector<double> vec = FitBkg(histo_bkg,_bkg);

	//Chebychev
	RooRealVar a0("a0","a0",vec[0],-5.,0.) ;
	RooRealVar a1("a1","a1",vec[1],-2,1.2) ;
	RooRealVar a2("a2","a2",vec[2],-1.,1.) ;
	RooRealVar a3("a3","a3",vec[3],-2.5,0.) ;
	RooRealVar a4("a4","a4",vec[4],-1.,1.) ;
	RooRealVar a5("a5","a5",vec[5],-1.,1.) ;
	RooRealVar a6("a6","a6",vec[6],-1.,1.) ;

	RooChebychev bkg_cheb("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6));

	//Novo

	RooRealVar peak_bkg("peak_bkg","peak",vec[0],0,250);
	RooRealVar width_bkg("width_bkg","width",vec[1],0,1) ;
	RooRealVar tail_bkg("tail_bkg","tail",vec[2],0,10) ;

	RooNovosibirsk bkg_nov("bkg","Background",x,peak_bkg,width_bkg,tail_bkg);

	RooAbsPdf* bkg;

	if(_bkg == "Cheb"){bkg = &bkg_cheb;}
	if(_bkg == "Novo"){bkg = &bkg_nov;}


	//////////////////////////
	//Adding the two functions
	//////////////////////////
	
	RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),fsig);
	 
	//Perform the fit
	RooAbsPdf* fit_func;
	fit_func = &model;
	
	RooFitResult* filters = fit_func->fitTo(dh,Range("R1"),"qr");
	fit_func->plotOn(frame);
	fit_func->plotOn(frame,Components(*sig),LineStyle(kDashed),LineColor(kRed));
	fit_func->plotOn(frame,Components(*bkg),LineStyle(kDashed),LineColor(kGreen));
	frame->Draw();
	fit_func->paramOn(frame); 
	dh.statOn(frame);  //this will display hist stat on canvas

	frame->SetTitle(histo->GetTitle());  
	frame->GetXaxis()->SetTitle("m (in GeV/c^{2})");  
	frame->GetXaxis()->SetTitleOffset(1.2);
	float binsize = histo->GetBinWidth(1); 

	//Store result in .root file
	frame->SetName(histo->GetName());
	frame->Write();
	
	return 0;

}
void test(int numbersigmas = 0, Bool_t debugtest = true)
{

    using namespace RooFit;
    using namespace std;

    TCanvas *canvas = new TCanvas("canvas","canvas",900,100,500,500);

    gSystem->Load("libRooFit");
    gSystem->AddIncludePath("-I$ROOFITSYS/include");


    float ptbinsarray[] = {20.,40.,60.,80.,100.,120.,200.,600.};

    std::vector<float> ptbins(ptbinsarray,ptbinsarray+sizeof(ptbinsarray)/sizeof(ptbinsarray[0]));

    std::vector<std::vector<float> > allbins;
    allbins.push_back(ptbins);

    std::vector<TString> VarString;
    VarString.push_back("VsPt");

    std::vector<TString> HistoNameString;
    HistoNameString.push_back("ptbin");

    std::vector<TString> GraphXTitleString;
    GraphXTitleString.push_back("p_{t} (GeV)");

    std::vector<TString> SideBandDefinitions;
    SideBandDefinitions.push_back("SideBand5_10");



    //   ------------FOR TESTING----------------
    unsigned int sidebandloopmax = 1;//5_10, 5_20, ...
    unsigned int templatevarsloopmax = 1;//sinin with conv safe veto, sinin, ch isol
    unsigned int binsloopmax = 1;//pt, eta, phi, pu

    //----------Open .root Templates

    //All the Jet Templates
    TFile *histojetfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/TemplateHistosJetCheckBinsEndcapsLoose.root");
    //TFile *histojetdenfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/Denominator_FREndCaps.root");
// TFile *histojetdatafile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/Num_Templates.root");

    //Real Photon Templates
    TFile *historealmcfile = TFile::Open("/afs/cern.ch/user/c/ciperez/CMSSW_7_4_5/src/RealPhotonTemplatesEndCaps.root");

    //--- Write NEW .root Historams for Fake Rate
    TFile *FRhistosfile = new TFile("FakeRatePlotsCheckBins.root","recreate");

    //loop on error systematics

    for(unsigned int m = 0; m<templatevarsloopmax; m++) {
        for(unsigned int l = 0; l<binsloopmax; l++) {


            TMultiGraph *mg = new TMultiGraph();
            TLegend *legendAllGraphs = new TLegend(0.37,0.59,0.57,0.79);
            legendAllGraphs->SetTextSize(0.02);
            legendAllGraphs->SetFillColor(kWhite);
            legendAllGraphs->SetLineColor(kWhite);


            std::vector<float> fakeratevalues;
            std::vector<float> fakerateptvalues;
            std::vector<float> fakerateerrorvalues;

            for(unsigned int k = 0; k<allbins[0].size()-1; k++) {
// for(unsigned int k = 0;k<1;k++){
                float binlow = allbins[0][k];
                float binmax = allbins[0][k+1];

                TString binstring = TString::Format("%4.2f_%4.2f",binlow,binmax);
                binstring.ReplaceAll(".00","");
                binstring.ReplaceAll("-","m");
                binstring.ReplaceAll(".","p");
                binstring.ReplaceAll("10000","Inf");
                cout<<binstring.Data()<<endl;

                //Histograms for templates
                //Get histograms from each of the histojetfiles declared earlier

                //Numerator Fakes - FakePhotonNumEndCaps.root - FakePhoton_num2040...
                TH1F *h1 = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedFakeJetptbin"+binstring).Data());// .Data() changes to char*
                h1->Print();

                //Numerator Real Photons - RealPhotonTemplatesEndCaps.root - EndCapsMCReal_20_40
                TH1F *h2 = (TH1F*)historealmcfile->Get(("EndCapsMCReal_"+binstring).Data());
                h2->Print();

                //Numerator Templates - Num_Templates.root - num2040...
                TH1F *hData = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedDataJetptbin"+binstring).Data());
                hData->Print();

                //Denominator Templates - Denominator_FREndCaps.root -FakePhoton_den2040...
                TH1F *hnum = (TH1F*)histojetfile->Get(("histoSininWithPixelSeedTightAndFakeJetptbin"+binstring).Data());
                hnum->Print();

                //avoiding 0 entries in the histograms
                //fake and real mc histos are the most critical
                for(int bincount = 1; bincount <= h1->GetNbinsX(); bincount++) {
                    if(h1->GetBinContent(bincount) == 0.) h1->SetBinContent(bincount,1.e-6);
                }
                for(int bincount = 1; bincount <= h2->GetNbinsX(); bincount++) {
                    if(h2->GetBinContent(bincount) == 0.) h2->SetBinContent(bincount,1.e-6);
                }

                int ndataentries = hData->GetEntries();

                float sininmin = 0.; //? sigmaIetaIeta
                float sininmax = 0.1; //? sigmaIetaIeta

                // ----------------- Probability Density Function

                TString roofitvartitle = "#sigma_{i #eta i #eta}";

                RooRealVar sinin("sinin",roofitvartitle.Data(),sininmin,sininmax);
                sinin.setRange("sigrange",0.018,0.06); //? this is the range because? Need to recall.
                //sinin.setRange("sigrange",0.005, 0.011);

                //Fake Template pdf
                RooDataHist faketemplate("faketemplate","fake template",sinin,h1);
                RooHistPdf fakepdf("fakepdf","test hist fake pdf",sinin,faketemplate);

                //Real Template pdf
                RooDataHist realtemplate("realtemplate","real template",sinin,h2);
                RooHistPdf realpdf("realpdf","test hist real pdf",sinin,realtemplate);

                //Data to be fitted to
                RooDataHist data("data","data to be fitted to",sinin,hData);


                //Declaration of Variables for Fake Rate
                RooRealVar fsig("fsig","signal fraction",0.1,0,1);//

                RooRealVar signum("signum","signum",0,ndataentries);// #of real contamination
                RooRealVar fakenum("fakenum","fakenum",0,ndataentries); //# of fake

                //Extend
                RooExtendPdf extpdfsig("Signal","extpdfsig",realpdf,signum,"sigrange");
                RooExtendPdf extpdffake("Background","extpdffake",fakepdf,fakenum,"sigrange");

                RooAddPdf model("model","sig + background",RooArgList(extpdfsig,extpdffake));


                //----------- FITTING TO DATA -------------------
                model.fitTo(data,RooFit::Minos());

                //Define Plot Frame
                RooPlot *xframe = sinin.frame();
                xframe->SetTitle("");

                data.plotOn(xframe);
                model.plotOn(xframe);
                model.plotOn(xframe,Components(extpdfsig),LineColor(2),LineStyle(2));
                model.plotOn(xframe,Components(extpdffake),LineColor(8),LineStyle(2));

                canvas->cd();
                canvas->SetGridx(true);
                canvas->SetGridy(true);

                xframe->GetXaxis()->SetRangeUser(0.,0.1);
                float xframemax = xframe->GetMaximum();
                xframe->GetYaxis()->SetRangeUser(1.e-1,1.1*xframemax);

                xframe->Draw();

                // ----- DEFINE LEGENDS and their position
                TLegend *legend = new TLegend(0.62,0.65,0.82,0.85); //Why these values?
                legend->SetTextSize(0.02);
                legend->SetFillColor(kWhite);
                legend->SetLineColor(kWhite);

                //Legend Header which tells the bin
                TString legendheader = "Pt (GeV):["+ binstring;

                legendheader.ReplaceAll("_",",");
                legendheader.ReplaceAll("m","-");
                legendheader.ReplaceAll("p",".");
                legendheader.Append("]");

                cout<<"legend "<<legendheader.Data()<<endl;
                legend->SetHeader(legendheader.Data());

                TObject *objdata;  //What is TObect?
                TObject *objmodel;
                TObject *objsignal;
                TObject *objfake;

                for(int i=0; i<xframe->numItems(); i++) {
                    cout<<xframe->nameOf(i)<<endl;
                    TString objname = xframe->nameOf(i);
                    if(objname.Contains("data")) objdata = (TObject*)xframe->findObject(objname.Data());
                    if(objname.Contains("model") && !objname.Contains("Comp")) objmodel = (TObject*)xframe->findObject(objname.Data());
                    if(objname.Contains("model") && objname.Contains("Signal")) objsignal = (TObject*)xframe->findObject(objname.Data());
                    if(objname.Contains("model") && objname.Contains("Background")) objfake = (TObject*)xframe->findObject(objname.Data());
                }

                //------ LEGEND --------
                legend->AddEntry(objdata,"Data","lp");
                legend->AddEntry(objsignal,"Signal","l");
                legend->AddEntry(objfake,"Background","l");
                legend->AddEntry(objmodel,"Signal + Background","l");
                legend->Draw("same");//make them overlap for comparison

                canvas->Print(("Endcapfits"+binstring+".png").Data());
                canvas->Print(("TemplateFitResultEndcap"+binstring+".C").Data());

                float fakevalue = fakenum.getValV();
                float fakeerrorhi = fakenum.getErrorHi();
                float fakeerrorlo = fakenum.getErrorLo();
                float fakeerrormax = max(fabs(fakeerrorhi),fabs(fakeerrorlo));
                TString fakeresults = TString::Format("Fake results %f +%f %f",fakevalue,fakeerrorhi,fakeerrorlo);

                canvas->SetLogy(0);

                float sigvalue = signum.getValV();
                float sigerrorhi = signum.getErrorHi();
                float sigerrorlo = signum.getErrorLo();
                float sigerrormax = max(fabs(sigerrorhi),fabs(sigerrorlo));
                TString sigresults = TString::Format("Signal results %f +%f %f",sigvalue,sigerrorhi,sigerrorlo);

                cout<<"sigvalue "<<sigvalue<<" sigerrormax "<<sigerrormax<<" sigerrormax/sigvalue "<<sigerrormax/sigvalue<<endl;
                cout<<"fakevalue "<<fakevalue<<" fakeerrormax "<<fakeerrormax<<" fakeerrormax/fakevalue "<<fakeerrormax/fakevalue<<endl;

                cout<<fakeresults.Data()<<endl;
                cout<<sigresults.Data()<<endl;

                float Ratio = (fakevalue/(fakevalue+sigvalue));
                float RatioError = Ratio*sqrt( ((fakeerrormax/fakevalue)*(fakeerrormax/fakevalue) + (sigerrormax/sigvalue)*(sigerrormax/sigvalue)) );
                cout<<"Ratio "<<Ratio<<" +- "<<RatioError<<endl;

                //---------------------- FAKE RATE CALCULATOR -------------------------
                //find the bin corresponding to 0.011
                //int binnr = 22;
                int binnr = 34;


                //compute the integral of tight and fake in that range
                float numerator = hData->Integral(0,binnr); //Is the Integral function part of RooFit?
                float denominator = hnum->Integral();


                float contamination = sigvalue;
                cout<<numerator<<" "<<denominator<<" "<<contamination<<endl;

                float fakerate = (numerator-contamination)/denominator;
                float fakerateerror = fakerate * sqrt( (1./numerator) + (1./denominator) + ((sigerrormax/sigvalue)*(sigerrormax/sigvalue)) );

                cout<<"Here: "<<fakerate<<" "<<fakerateerror<<endl;

                //fakerateptvalues.push_back(hnumvspt->GetMean());
                fakeratevalues.push_back(fakerate);
                fakerateerrorvalues.push_back(fakerateerror);

                cout<<""<<endl;
                cout<<"***********************************************************"<<endl;
                cout<<"So in sigmaietaieta < 0.011 there are "<<contamination<<" to subtract from "<<numerator<<endl;
                cout<<"and thus there are "<<(numerator-contamination)<<" total tight entries "<<endl;
                cout<<"and there are "<<denominator<<" entries in the tight and fake sample "<<endl;
                cout<<"and so the fake rate for the pt range "<<binlow<<"-"<<binmax<<" is "<<fakerate<<"+-"<<fakerateerror<<endl;
                cout<<"***********************************************************"<<endl;
                cout<<""<<endl;

            }//loop on all bins


            /*
            	  cout<<fakeratevalues.size()<<endl;
            	  for(int k=0;k<fakeratevalues.size();k++){
            	    cout<<"Range: ["<<allbins[l][k]<<"-"<<allbins[l][k+1]<<"] --> fake rate: ("<<fakeratevalues[k]*100<<" +- "<<fakerateerrorvalues[k]*100<<")%"<<endl;
            	  }//end of loop over all fake rate values


                // *************************************************************-//

                //
            	  TGraphErrors *FRgraph = new TGraphErrors(fakeratevalues.size());
            	  for(int k=0;k<fakeratevalues.size();k++){
            	    cout<<(allbins[l][k+1]+allbins[l][k])/2.<<endl;
            	    FRgraph->SetPoint(k,(allbins[l][k+1]+allbins[l][k])/2.,fakeratevalues[k]);
            	    FRgraph->SetPointError(k,(allbins[l][k+1]-allbins[l][k])/2.,fakerateerrorvalues[k]);
            	  }//end of filling TGraph

               //// FRGraph->SetName(FakeRate.Data());
            	  FRgraph->SetTitle("");

            	  canvas->cd();
                canvas->SetLogy(0);
            	  FRgraph->Draw("a*");


                // **********************************************************-//



                 //  *****************************************

            	  //float maxFRvalue = max_element(fakeratevalues.begin(),fakeratevalues.end());
            	  FRgraph->GetYaxis()->SetRangeUser(0.,0.2);
            	  FRgraph->GetYaxis()->SetTitle("#epsilon_{FR}");
            	  FRgraph->GetXaxis()->SetTitle((GraphXTitleString[l]).Data());

                TString FakeRateFunctionName = "
                TF1 *FRfunc = new TF1(FakeRateFunctionName.Data(),"[0]+[1]/pow(x,[2])", allbins[l][0],allbins[l][fakeratevalues.size()]);
                FRfunc->SetParameters(1.,1.,1.);
                if(l==0){
            	    FRgraph->Fit(FakeRateFunctionName.Data(),"R");
            	    FRgraph->Fit(FakeRateFunctionName.Data());
            	    FRfunc->Draw("same");
            	  }


                // ********************************************
            	  cout<<"***** Fit function parameters *****"<<endl;
            	  cout<<FRfunc->GetParameter(0)<<" "
            	      <<FRfunc->GetParameter(1)<<" "
            	      <<FRfunc->GetParameter(2)<<" "
            	      <<endl;

            	  cout<<"***** Fit function errors *****"<<endl;
            	  cout<<FRfunc->GetParError(0)<<" "
            	      <<FRfunc->GetParError(1)<<" "
            	      <<FRfunc->GetParError(2)<<" "
            	      <<endl;

            	  if(!debugtest){
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.png").Data(),"png");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.gif").Data(),"gif");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.eps").Data(),"eps");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoos.pdf").Data(),"pdf");
            	    canvas->Print(("FakeRateJetRun2012ABCD13JulLoose.C").Data(),"cxx");
            	  }

                canvas->Print(("FakeRateEndCaps.png").Data(),"png");
                canvas->Print(("FakeRateEndCaps.C").Data(),"cxx");
                // ************************************************

            	  if(!debugtest){
            	    if(count == 0){
            	      FRhistosfile->cd();
            	      FRgraph->Write();
            	      FRfunc->Write();
            	    }
            	  }
            	  if(numbersigmas != 0){
            	    FRgraph->SetLineColor(count+numbersigmas+1);
            	    FRgraph->SetMarkerColor(count+numbersigmas+1);
            	    TString numsigmastring = TString::Format("%d #sigma",count);
            	    legendAllGraphs->AddEntry(FRgraph,numsigmastring.Data(),"lep");
            	  }

            	  mg->Add(FRgraph);*/
//	}//end of loop over systematic errors


            if(numbersigmas != 0) {
                mg->Draw();
                legendAllGraphs->Draw("same");
            }

        }//end of loop over all variables (pt, eta, phi, pu)

    }//end of loop over template variables

    histojetfile->cd();
    histojetfile->Close();

    historealmcfile->cd();
    historealmcfile->Close();

    FRhistosfile->cd();
    FRhistosfile->Close();

// }//end of loop over sideband definitions

}//end of method
Example #25
0
int main(){

  RooRealVar zero("zero","",0,0,150); 

  //input parameters for the distribution
  double alpha_double = 2.38;
  double beta_double = 0.092;
  double lambda_double = 2.21;
  double theta_double = 1.12;
  double c_frac = 0.5;
  //RooRealVar fsig("fsig","signal fraction",0.3) ;

  string epsname = "plots/gamma_pion20";

  
  hit_info multi_shower("fullsim/example_pi20Gev.root");
  //hit_info multi_shower("fullsim/example_ele_20GeV.root");
  
 
  double beta_gflash_factor = 1.49;
  double theta_gflash_factor = 16.42;

  beta_double = beta_double/beta_gflash_factor;
  theta_double = theta_double/theta_gflash_factor;
  
  // --- Observable --- 
  RooRealVar depth("depth","depth [cm]",0,800); 
  depth.removeMax(); // set infinite range
  // --- Weight ---
  RooRealVar* weight = new RooRealVar("weight","1/E dE/dr", 0.0, 1.0);
 
  // --- Gamma pdf --- 
  //if one of the Values is set to const you can not ask for it in RooFitModel, otherwise the program will crash
  //RooRealVar alpha("alpha","alpha",alpha_double,0.0,4);
  RooRealVar alpha("alpha","alpha",0.0,20.);
  //alpha.removeMax(); // set infinite range
  //RooRealVar beta("beta","beta",1./beta_double,0.0,100.);
  RooRealVar beta("beta","beta",0.1,.1,3.5);
  //beta.removeMax(); // set infinite range

  RooRealVar mu("mu","mu",0); // no ranges means variable is fixed in fit
  RooRealVar nu("nu","nu",0); // no ranges means variable is fixed in fit
  
  //RooRealVar lambda("lambda","lambda",lambda_double,0.0,6.);
  RooRealVar lambda("lambda","lambda",0.0,40.);
  //lambda.removeMax(); // set infinite range
  //RooRealVar theta("theta","theta",1./theta_double,0.0,100.) ;  
  RooRealVar theta("theta","theta",1.,47) ;  
  //theta.removeMax(); // set infinite range

  RooGamma gamma_one("gamma_one","gamma_one pdf",depth,alpha,beta,mu) ; 
  RooGamma gamma_two("gamma_two","gamma_two pdf",depth,lambda,theta,nu) ; 

  RooRealVar fsig("fsig","signal fraction",c_frac,0.0,1.);
  //RooRealVar fsig("fsig","signal fraction",c_frac);

  RooAddPdf model("model","model",RooArgList(gamma_two,gamma_one),fsig) ;
   
  RooDataSet mean("mean","mean",RooArgSet(depth,weight),"weight"); 
  TH1F* mean_fithist = new TH1F("mean_fithist"," mean fit hist",50,0,150);


  TH1F* log_alpha1 = new TH1F("log_alpha1"," log(#alpha_{1})",20,-1,3);
  TH1F* log_beta1  = new TH1F("log_beta1"," log(#beta_{1})",20,-1,3);
  TH2F* log_corr1  = new TH2F("log_corr1"," correlation #alpha_{1} #beta_{1}",20,-1,3,20,-1,3);
  TH1F* log_alpha2 = new TH1F("log_alpha2"," log(#alpha_{2})",20,-1,3);
  TH1F* log_beta2  = new TH1F("log_beta2"," log(#beta_{2})",20,-1,3);
  TH2F* log_corr2  = new TH2F("log_corr2"," correlation #alpha_{2} #beta_{2}",20,-1,3,20,-1,3);

  TH2F* mean_hist = new TH2F("mean_hist"," mean hist",100,0,150,100.,0.,.0015);
  
  TCanvas * can = new TCanvas("can", "can", 600, 500); 
  can->cd();
  set_style();
  
  
  //can->Print(epsname+"[");

  double c_tot =0;

  unsigned int n_part =100;

  for(unsigned int p = 0; p<n_part ; ++p){

    TLegend * legend = new TLegend(0.5,0.65,.88,0.88);
    legend->SetTextFont(72);
    legend->SetTextSize(0.04);
    legend->SetFillColor(kWhite);
    legend->SetBorderSize(0);

    one_shower shower =  multi_shower.all_shower.at(p); 
   
    //DataSet I am looking at
    RooDataSet full_sim_data("full_sim_data","full_sim_data",RooArgSet(depth,weight),"weight");
    TH1F* datahisto = new TH1F("datahist","datahist",15,0,120);

    double sumHCAL=0;

    double deltar =-1; 
    for(unsigned int i = 0; i < shower.mytype.size(); ++i){	
      sumHCAL += shower.myenergy.at(i);
      double x_val = shower.myz.at(i);
      double y_val = shower.myy.at(i);
      double z_val = shower.myz.at(i);
      
      z_val = z_val - shower.interactPoint; 
      double distance=-1;
      if(sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10 < 200) distance = sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10;

      if(deltar < distance) deltar = z_val;
    }

    deltar=deltar/shower.mytype.size();
    
    c_tot += shower.ePi0first_energy/n_part;
    fsig.setVal(shower.ePi0first_energy);
    fsig.setRange(shower.ePi0first_energy-0.05 > 0 ? shower.ePi0first_energy-0.05: 0,shower.ePi0first_energy+0.05<1?shower.ePi0first_energy+0.05:1);
    //fsig.setRange(1-shower.ePi0first_energy-0.05 > 0 ? 1-shower.ePi0first_energy-0.05: 0,1-shower.ePi0first_energy+0.05<1 ? 1-shower.ePi0first_energy+0.05:1);

    for(unsigned int i = 0; i < shower.mytype.size(); ++i){	
      double x_val = shower.myx.at(i);
      double y_val = shower.myy.at(i);
      double z_val = shower.myz.at(i);

      // if(shower.mytype.at(i) !=2)continue;
     
      z_val = z_val - shower.interactPoint; 
      //if(z_val<=0) continue;
      depth.setVal(sqrt(x_val*x_val+y_val*y_val+z_val*z_val)/10);
      //depth.setVal(z_val);
      //cout <<depth.getVal()<<endl;
      datahisto->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar);
      mean_fithist->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar/n_part);
      mean_hist->Fill(depth.getVal(),shower.myenergy.at(i)/sumHCAL/deltar);
      full_sim_data.add(depth,shower.myenergy.at(i)/sumHCAL/deltar,0);
      mean.add(depth,shower.myenergy.at(i)/sumHCAL/deltar,0);
    }
  

    RooDataHist roodatahist("roodatahist","roodatahist",depth,Import(*datahisto)) ;

    //model.fitTo(roodatahist, Strategy(2) );
    model.fitTo(full_sim_data);
      
    RooDataHist* full_sim_binned = full_sim_data.binnedClone("full_sim_binned","full sim binned");
    //prepare to plot fits
    
    RooPlot * depthFrame = depth.frame(0,120,100);
    depthFrame->SetTitle("");
    depthFrame->SetTitleOffset(1.2,"Y");
    depthFrame->SetLabelSize(0.02,"Y");
    depthFrame->SetYTitle("1/E dE/dr");
    //zero.plotOn(depthFrame,LineStyle(kDashed),LineColor(kBlack));
    //full_sim_data.plotOn(depthFrame);
    roodatahist.plotOn(depthFrame);
    //full_sim_binned->plotOn(depthFrame);
    
    model.plotOn(depthFrame,Components(gamma_one),LineStyle(kDashed),LineColor(kGreen),Name("gamma_one"));
    model.plotOn(depthFrame,Components(gamma_two),LineStyle(kDashed),LineColor(kRed),Name("gamma_two"));
    model.plotOn(depthFrame,Name("model"));
    
    stringstream gamma_one_text;
    gamma_one_text.precision(3);
    gamma_one_text << "#Gamma_{1} ("<<alpha.getVal()<<","<<(1/beta.getVal()*beta_gflash_factor)<<")"<<endl;
    stringstream gamma_two_text; 
    gamma_two_text.precision(3);
    gamma_two_text << "#Gamma_{2} (" <<lambda.getVal()<<","<<(1/theta.getVal()*theta_gflash_factor)<< ")"<<endl;
    
    stringstream gamma_text; 
    gamma_text.precision(2);
    gamma_text << "#Gamma_{1/2} c=" <<fsig.getVal() <<"("<<shower.ePi0first_energy<<")"<<endl;
    
    stringstream  chi2; 
    chi2.precision(2);
    chi2 << "#chi^{2} prob. = " << TMath::Prob(depthFrame->chiSquare(),14) <<endl;

    legend->AddEntry(depthFrame->findObject("gamma_one"),gamma_one_text.str().c_str(),"L");
    legend->AddEntry(depthFrame->findObject("gamma_two"),gamma_two_text.str().c_str(),"L");
    legend->AddEntry(depthFrame->findObject("model"),gamma_text.str().c_str(),"L");
    legend->AddEntry((TObject*)0, chi2.str().c_str(), "");
    cout << "alpha,  beta "<< alpha.getVal() << " " << 1/beta.getVal()*beta_gflash_factor << std::endl;
    cout << "lambda, theta "<<lambda.getVal() << " " << 1/theta.getVal()*theta_gflash_factor << std::endl;
    cout <<"c, chi2 "<< fsig.getVal() << " "<<depthFrame->chiSquare()<< std::endl;
    cout <<"starting , interacting Points "<<shower.startingPoint<<" "<<shower.interactPoint <<endl;
    cout<< "pi0first, pi0tot "<<shower.ePi0first_energy <<" "<<shower.ePi0tot_energy<<endl;
    
    /*
    log_alpha1->Fill(log10(alpha.getVal()));
    log_alpha2->Fill(log10(lambda.getVal()));
    //cout<<log(1/beta.getVal()*beta_gflash_factor)<<endl;
    log_beta1 ->Fill(log10(1/beta.getVal()*beta_gflash_factor));
    log_beta2 ->Fill(log10(1/theta.getVal()*theta_gflash_factor));
    log_corr1 ->Fill(log10(alpha.getVal()),log10(1/beta.getVal()*beta_gflash_factor));
    log_corr2 ->Fill(log10(lambda.getVal()),log10(1/theta.getVal()*theta_gflash_factor));
    */
    
    if(fsig.getVal()>0.1)log_alpha1->Fill(log(alpha.getVal()));
    if(fsig.getVal()<0.9)log_alpha2->Fill(log(lambda.getVal()));
    //cout<<log(1/beta.getVal()*beta_gflash_factor)<<endl;
    if(fsig.getVal()>0.1)log_beta1 ->Fill(log(1/beta.getVal()*beta_gflash_factor));
    if(fsig.getVal()<0.9)log_beta2 ->Fill(log(1/theta.getVal()*theta_gflash_factor));
    if(fsig.getVal()>0.1)log_corr1 ->Fill(log(alpha.getVal()),log(1/beta.getVal()*beta_gflash_factor));
    if(fsig.getVal()<0.9)log_corr2 ->Fill(log(lambda.getVal()),log(1/theta.getVal()*theta_gflash_factor));
    

    //prepare to dump all the plots in the ps file
    
    
    // one data sample and its fit is drawn
    /*
    datahisto->Draw();
    datahisto0->SetLineColor(kRed);
    datahisto0->Draw("same");
    datahisto1->SetLineColor(kGreen);
    datahisto1->Draw("same");
    datahisto2->SetLineColor(kBlue);
    datahisto2->Draw("same");
    can->Print(epsname);
    */
    //if(depthFrame->chiSquare()>5) continue;
    depthFrame->Draw("HIST p");
    legend->Draw();

    stringstream  particle_number; 
    particle_number.precision(1);
    particle_number << p <<endl;
    
    can->Print((epsname+"_"+particle_number.str()+".pdf").c_str());
  }

  RooDataHist roomeandatahist("roomeandatahist","roomeandatahist",depth,Import(*mean_fithist)) ;


  fsig.setVal(c_tot);
  alpha.removeMax(); // set infinite range
  beta.removeMax(); // set infinite range
  lambda.removeMax(); // set infinite range
  theta.removeMax(); // set infinite range

  //model.fitTo(roomeandatahist);
  //model.fitTo(mean,SumW2Error(kTRUE));

  TLegend * mean_legend = new TLegend(0.5,0.65,.9,0.9);
  mean_legend->SetTextFont(72);
  mean_legend->SetTextSize(0.04);
  mean_legend->SetFillColor(kWhite);
  mean_legend->SetBorderSize(0);

  stringstream  mean_gamma_one_text;
  mean_gamma_one_text.precision(3);
  mean_gamma_one_text << "#Gamma_{1} ("<<alpha.getVal()<<","<<(1/beta.getVal()*beta_gflash_factor)<<")"<<endl;
  stringstream mean_gamma_two_text; 
  mean_gamma_two_text.precision(3);
  mean_gamma_two_text << "#Gamma_{2} (" <<lambda.getVal()<<","<<(1/theta.getVal()*theta_gflash_factor)<< ")"<<endl;
  
  stringstream  mean_gamma_text; 
  mean_gamma_text.precision(2);
  mean_gamma_text << "#Gamma_{1/2} c=" <<fsig.getVal() <<"("<< c_tot<<")"<<endl;
  
  stringstream  mean_chi2; 
  mean_chi2.precision(2);
  //mean_chi2 << "#chi^{2} " <<depthFrame->chiSquare() <<endl;
  
  RooPlot * meanFrame = depth.frame(0,120,200);
  //meanFrame->SetMaximum(1);
  meanFrame->SetTitle("Mean Fit");
  meanFrame->SetYTitle("1/E dE/dr");
  model.plotOn(meanFrame,Components(gamma_one),LineStyle(kDashed),LineColor(kGreen),Name("gamma_one"));
  model.plotOn(meanFrame,Components(gamma_two),LineStyle(kDashed),LineColor(kRed),Name("gamma_two"));
  model.plotOn(meanFrame,Name("model"));
  //mean.plotOn(meanFrame);
  //roomeandatahist.plotOn(meanFrame);

  mean_legend->AddEntry(meanFrame->findObject("gamma_one"),mean_gamma_one_text.str().c_str(),"L");
  mean_legend->AddEntry(meanFrame->findObject("gamma_two"),mean_gamma_two_text.str().c_str(),"L");
  mean_legend->AddEntry(meanFrame->findObject("model"),mean_gamma_text.str().c_str(),"L");
  
  meanFrame->Draw();
  mean_legend->Draw();
  //datahisto->Draw();
  //can->Print(epsname);

  //mean_hist->Draw("box");
  //can->Print(epsname);
 
  can->Print((epsname+"_mean.pdf").c_str());
  log_alpha1->Draw();
  can->Print((epsname+"_alpha1_log.pdf").c_str());
  log_beta1->Draw();
  can->Print((epsname+"_beta1_log.pdf").c_str());
  log_corr1->Draw("colz");
  can->Print((epsname+"corr1_log.pdf").c_str());
  log_alpha2->Draw();
  can->Print((epsname+"apha2_log.pdf").c_str());
  log_beta2->Draw();
  can->Print((epsname+"beta2_log.pdf").c_str());
  log_corr2->Draw("colz");
  can->Print((epsname+"corr2_log.pdf").c_str());

  ///can->Print(epsname+"]");
  return 0;
}
void RegressionPlottingAll(bool doEBEE=true, bool doEB=false, bool doEE=false){

  TString name1;
  TString name2;
  TString name3;
  string dir;

  if (doEBEE){ 
  name1="results_noPU_new.root";
  name2="results_bx50_new.root";
  name3="results_bx25_new.root";
  dir="plots";
  }
  if (doEB){ 
 name1="resultsEB_noPU_new.root";
  name2="resultsEB_bx50_new.root";
  name3="resultsEB_bx25_new.root";
  dir="plotsEB";
  }
  if (doEE){ 
 name1="resultsEE_noPU_new.root";
  name2="resultsEE_bx50_new.root";
  name3="resultsEE_bx25_new.root";
  dir="plotsEE";
  }

  TFile *fResults1 = TFile::Open(name1);
  TFile *fResults2 = TFile::Open(name2);
  TFile *fResults3 = TFile::Open(name3);

  //Plot eraw/etrue and ecor/etrue to quantify regression performance
  
  //Get Histograms
  TH1 *hecor1 = (TH1*)fResults1->Get("hCor_true");
  TH1 *heraw1 = (TH1*)fResults1->Get("hRaw_true");
  TH1 *hecor2 = (TH1*)fResults2->Get("hCor_true");
  TH1 *heraw2 = (TH1*)fResults2->Get("hRaw_true");
  TH1 *hecor3 = (TH1*)fResults3->Get("hCor_true");
  TH1 *heraw3 = (TH1*)fResults3->Get("hRaw_true");
  hecor1->Scale(1./hecor1->Integral());
  heraw1->Scale(1./heraw1->Integral());
  hecor2->Scale(1./hecor2->Integral());
  heraw2->Scale(1./heraw2->Integral());
  hecor3->Scale(1./hecor3->Integral());
  heraw3->Scale(1./heraw3->Integral());
  //Compute peak of the distributions by fitting histograms with double Crystal Ball
  double PeakRaw1,PeakRawErr1,PeakCor1,PeakCorErr1;
  double PeakRaw2,PeakRawErr2,PeakCor2,PeakCorErr2;
  double PeakRaw3,PeakRawErr3,PeakCor3,PeakCorErr3;
  RooRealVar *bias=new RooRealVar("Ecor/Etrue","Ecor/Etrue",0.8,1.2);
  const RooArgList *var=new RooArgList(*bias,"");
  RooPlot *plot = bias->frame(Range(0.9,1.07));
  plot->SetTitle("");
  plot->GetYaxis()->SetTitle("");
  RooDataHist *Hraw1=new RooDataHist("","",*var,heraw1);
  RooDoubleCBFast *DoubleCBraw1=FitWithDCB(Hraw1,bias,PeakRaw1,PeakRawErr1); 
  Hraw1->plotOn(plot,MarkerSize(0.8),MarkerColor(kBlue+2),MarkerStyle(24));
  DoubleCBraw1->plotOn(plot,LineColor(kBlue+2),LineStyle(2),LineWidth(2),Name("hraw1"));
  RooDataHist *Hcor1=new RooDataHist("","",*var,hecor1);
  RooDoubleCBFast *DoubleCBcor1=FitWithDCB(Hcor1,bias,PeakCor1,PeakCorErr1); 
  Hcor1->plotOn(plot,MarkerSize(0.6),MarkerColor(kBlue+2));
  DoubleCBcor1->plotOn(plot,LineColor(kBlue+2),LineWidth(2),Name("hcor1"));
  RooDataHist *Hraw2=new RooDataHist("","",*var,heraw2);
  RooDoubleCBFast *DoubleCBraw2=FitWithDCB(Hraw2,bias,PeakRaw2,PeakRawErr2); 
  Hraw2->plotOn(plot,MarkerSize(0.8),MarkerColor(kRed+1),MarkerStyle(24));
  DoubleCBraw2->plotOn(plot,LineColor(kRed+1),LineStyle(2),LineWidth(2),Name("hraw2"));
  RooDataHist *Hcor2=new RooDataHist("","",*var,hecor2);
  RooDoubleCBFast *DoubleCBcor2=FitWithDCB(Hcor2,bias,PeakCor2,PeakCorErr2); 
  Hcor2->plotOn(plot,MarkerSize(0.6),MarkerColor(kRed+1));
  DoubleCBcor2->plotOn(plot,LineColor(kRed+1),LineWidth(2),Name("hcor2"));
  RooDataHist *Hraw3=new RooDataHist("","",*var,heraw3);
  RooDoubleCBFast *DoubleCBraw3=FitWithDCB(Hraw3,bias,PeakRaw3,PeakRawErr3); 
  Hraw3->plotOn(plot,MarkerSize(0.8),MarkerColor(kOrange+1),MarkerStyle(24));
  DoubleCBraw3->plotOn(plot,LineColor(kOrange+1),LineStyle(2),LineWidth(2),Name("hraw3"));
  RooDataHist *Hcor3=new RooDataHist("","",*var,hecor3);
  RooDoubleCBFast *DoubleCBcor3=FitWithDCB(Hcor3,bias,PeakCor3,PeakCorErr3); 
  Hcor3->plotOn(plot,MarkerSize(0.6),MarkerColor(kOrange+1));
  DoubleCBcor3->plotOn(plot,LineColor(kOrange+1),LineWidth(2),Name("hcor3"));
  //Compute Effective Sigma of the distributions
  /*double SigEffRaw1=effSigma(heraw1);
  double SigEffCor1=effSigma(hecor1);
  double SigEffRaw2=effSigma(heraw2);
  double SigEffCor2=effSigma(hecor2);
  double SigEffRaw3=effSigma(heraw3);
  double SigEffCor3=effSigma(hecor3);
  double SigEffErr=0.001;*/
  //Legend and StatBox
  TLegend *leg = new TLegend(0.11,0.39,0.4,0.89);
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->AddEntry(plot->findObject("hraw1"),"Eraw/Etrue, no PU","l");
  leg->AddEntry(plot->findObject("hcor1"),"Ecor/Etrue, no PU","l");
  leg->AddEntry(plot->findObject("hraw2"),"Eraw/Etrue, bx 50","l");
  leg->AddEntry(plot->findObject("hcor2"),"Ecor/Etrue, bx 50","l");
  leg->AddEntry(plot->findObject("hraw3"),"Eraw/Etrue, bx 25","l");
  leg->AddEntry(plot->findObject("hcor3"),"Ecor/Etrue, bx 25","l");
  //leg->SetTextFont(62);
  //leg->SetTextSize(0.06);
  plot->addObject(leg);
  /*TPaveText *stats = new TPaveText(0.58,0.39,0.89,0.89,"NDC");
  stats->SetBorderSize(0);
  stats->SetFillColor(0);
  stats->AddText(Form("Peak Raw = %.4f +/- %.0e",PeakRaw,PeakRawErr));
  stats->AddText(Form("Peak Cor = %.4f +/- %.0e",PeakCor,PeakCorErr));
  stats->AddText(Form("Sigma Eff Raw = %.3f +/- %.3f",SigEffRaw,SigEffErr));
  stats->AddText(Form("Sigma Eff Cor = %.3f +/- %.3f",SigEffCor,SigEffErr));
  stats->SetTextSize(0.035);
  plot->addObject(stats);*/
  //Plot
  TCanvas *cresponse=new TCanvas;
  plot->Draw();
  cresponse->SaveAs(Form("plotsAll/%s/Performance.pdf",dir.c_str()));
  cresponse->SaveAs(Form("plotsAll/%s/Performance.png",dir.c_str()));
  

  //Plot ecor/eraw
/*  TH1 *hecor_raw = (TH1*)fResults->Get("hCor_raw");
  TCanvas *canCor=new TCanvas;
  hecor_raw->Draw("HIST");
  hecor_raw->SetLineWidth(2);
  hecor_raw->GetXaxis()->SetTitle("Ecor/Eraw");
  hecor_raw->SetTitle("Ecor/Eraw");  
  canCor->SaveAs(Form("plotsAll/%s/Correction.png",dir.c_str()));
*/

  //Plot |ecor-etrue|/eraw and |eraw-etrue|/eraw
  TH1 *hres1 = (TH1*)fResults1->Get("hRes");
  TH1 *hres2 = (TH1*)fResults2->Get("hRes");
  TH1 *hres3 = (TH1*)fResults3->Get("hRes");
  hres1->Scale(1./hres1->Integral());
  hres2->Scale(1./hres2->Integral());
  hres3->Scale(1./hres3->Integral());
  TCanvas *canR=new TCanvas;
  canR->SetLogy();
  hres1->Draw("HIST,SAME");
  hres1->SetLineWidth(2);
  hres1->SetLineColor(kBlue+2);
  hres1->GetXaxis()->SetRangeUser(0,0.05);
  hres2->Draw("HIST,SAME");
  hres2->SetLineWidth(2);
  hres2->SetLineColor(kRed+1);
  hres2->GetXaxis()->SetRangeUser(0,0.05);
  hres3->Draw("HIST,SAME");
  hres3->SetLineWidth(2);
  hres3->SetLineColor(kOrange+1);
  hres3->GetXaxis()->SetRangeUser(0,0.05);
  hres1->GetXaxis()->SetTitle("#sigma(E)/E");
  hres1->SetTitle("");
  hres1->GetYaxis()->SetTitle("");
  hres1->SetStats(0);
TLegend *leg2 = new TLegend(0.59,0.11,0.89,0.41);
  leg2->SetBorderSize(0);
  leg2->SetFillColor(0);
  leg2->AddEntry(hres1,"#sigma(E)/E, no PU","l");
  leg2->AddEntry(hres2,"#sigma(E)/E, bx 50","l");
  leg2->AddEntry(hres3,"#sigma(E)/E, bx 25","l");  
  leg2->Draw(); 
 canR->SaveAs(Form("plotsAll/%s/Resolution.pdf",dir.c_str()));
 canR->SaveAs(Form("plotsAll/%s/Resolution.png",dir.c_str()));


  // Plot Correction vs input variables

/*
  TCanvas *canCoreta=new TCanvas;
  gStyle->SetOptStat(0);
  TProfile *profCorEta=(TProfile*)fResults->Get("profEta");
  TProfile *profRawEta=(TProfile*)fResults->Get("profEta0");
  profRawEta->Draw();
  profCorEta->Draw("same");
  profRawEta->GetXaxis()->SetTitle("Eta");
  profRawEta->GetYaxis()->SetTitle("E/Eraw");
  profRawEta->SetTitle("Profile of E/Eraw vs Eta");
  profCorEta->SetMarkerStyle(8);
  profCorEta->SetLineColor(kRed);
  profCorEta->SetMarkerColor(kRed);
  profRawEta->SetMarkerStyle(4);
  profRawEta->SetLineColor(kBlue);
  profRawEta->SetMarkerColor(kBlue);
  TLegend *leg2 = new TLegend(0.68,0.12,0.88,0.27);
  leg2->SetBorderSize(0);
  leg2->SetFillColor(0);
  leg2->AddEntry(profRawEta,"Eraw/Etrue","lp");
  leg2->AddEntry(profCorEta,"Ecor/Etrue","lp");
  leg2->SetTextFont(62);
  //leg2->SetTextSize(0.06);
  leg2->Draw();
  canCoreta->SaveAs(Form("plotsAll/%s/CorEta.png",dir.c_str()));


  TCanvas *canCorPhi=new TCanvas;
  gStyle->SetOptStat(0);
  TProfile *profCorPhi=(TProfile*)fResults->Get("profPhi");
  TProfile *profRawPhi=(TProfile*)fResults->Get("profPhi0");
  profRawPhi->Draw();
  profCorPhi->Draw("same");
  profRawPhi->GetXaxis()->SetTitle("Phi");
  profRawPhi->GetYaxis()->SetTitle("E/Eraw");
  profRawPhi->SetTitle("Profile of E/Eraw vs Phi");
  profCorPhi->SetMarkerStyle(8);
  profCorPhi->SetLineColor(kRed);
  profCorPhi->SetMarkerColor(kRed);
  profRawPhi->SetMarkerStyle(4);
  profRawPhi->SetLineColor(kBlue);
  profRawPhi->SetMarkerColor(kBlue);
  leg2->Draw();
  canCorPhi->SaveAs(Form("plotsAll/%s/CorPhi.png",dir.c_str()));

  TCanvas *canCorEtaWidth=new TCanvas;
  gStyle->SetOptStat(0);
  TProfile *profCorEtaWidth=(TProfile*)fResults->Get("profEtaWidth");
  TProfile *profRawEtaWidth=(TProfile*)fResults->Get("profEtaWidth0");
  profRawEtaWidth->Draw();
  profCorEtaWidth->Draw("same");
  profRawEtaWidth->GetXaxis()->SetTitle("EtaWidth");
  profRawEtaWidth->GetYaxis()->SetTitle("E/Eraw");
  profRawEtaWidth->SetTitle("Profile of E/Eraw vs EtaWidth");
  profCorEtaWidth->SetMarkerStyle(8);
  profCorEtaWidth->SetLineColor(kRed);
  profCorEtaWidth->SetMarkerColor(kRed);
  profRawEtaWidth->SetMarkerStyle(4);
  profRawEtaWidth->SetLineColor(kBlue);
  profRawEtaWidth->SetMarkerColor(kBlue);
  leg2->Draw();
  canCorEtaWidth->SaveAs(Form("plotsAll/%s/CorEtaWidth.png",dir.c_str()));

  TCanvas *canCorPhiWidth=new TCanvas;
  gStyle->SetOptStat(0);
  TProfile *profCorPhiWidth=(TProfile*)fResults->Get("profPhiWidth");
  TProfile *profRawPhiWidth=(TProfile*)fResults->Get("profPhiWidth0");
  profRawPhiWidth->Draw();
  profCorPhiWidth->Draw("same");
  profRawPhiWidth->GetXaxis()->SetTitle("PhiWidth");
  profRawPhiWidth->GetYaxis()->SetTitle("E/Eraw");
  profRawPhiWidth->SetTitle("Profile of E/Eraw vs PhiWidth");
  profCorPhiWidth->SetMarkerStyle(8);
  profCorPhiWidth->SetLineColor(kRed);
  profCorPhiWidth->SetMarkerColor(kRed);
  profRawPhiWidth->SetMarkerStyle(4);
  profRawPhiWidth->SetLineColor(kBlue);
  profRawPhiWidth->SetMarkerColor(kBlue);
  leg2->Draw();
  canCorPhiWidth->SaveAs(Form("plotsAll/%s/CorPhiWidth.png",dir.c_str()));

  TCanvas *canCorR9=new TCanvas;
  gStyle->SetOptStat(0);
  TProfile *profCorR9=(TProfile*)fResults->Get("profR9");
  TProfile *profRawR9=(TProfile*)fResults->Get("profR90");
  profRawR9->Draw();
  profCorR9->Draw("same");
  profRawR9->GetXaxis()->SetTitle("R9");
  profRawR9->GetYaxis()->SetTitle("E/Eraw");
  profRawR9->SetTitle("Profile of E/Eraw vs R9");
  profCorR9->SetMarkerStyle(8);
  profCorR9->SetLineColor(kRed);
  profCorR9->SetMarkerColor(kRed);
  profRawR9->SetMarkerStyle(4);
  profRawR9->SetLineColor(kBlue);
  profRawR9->SetMarkerColor(kBlue);
  leg2->Draw();
  canCorR9->SaveAs(Form("plotsAll/%s/CorR9.png",dir.c_str()));

  TCanvas *canCorNvtx=new TCanvas;
  gStyle->SetOptStat(0);
  TProfile *profCorNvtx=(TProfile*)fResults->Get("profNvtx");
  TProfile *profRawNvtx=(TProfile*)fResults->Get("profNvtx0");
  profRawNvtx->Draw();
  profCorNvtx->Draw("same");
  profRawNvtx->GetXaxis()->SetTitle("Nvtx");
  profRawNvtx->GetYaxis()->SetTitle("E/Eraw");
  profRawNvtx->SetTitle("Profile of E/Eraw vs Nvtx");
  profCorNvtx->SetMarkerStyle(8);
  profCorNvtx->SetLineColor(kRed);
  profCorNvtx->SetMarkerColor(kRed);
  profRawNvtx->SetMarkerStyle(4);
  profRawNvtx->SetLineColor(kBlue);
  profRawNvtx->SetMarkerColor(kBlue);
  leg2->Draw();
  canCorNvtx->SaveAs(Form("plotsAll/%s/CorNvtx.png",dir.c_str()));

  TCanvas *canCorPt=new TCanvas;
  gStyle->SetOptStat(0);
  TProfile *profCorPt=(TProfile*)fResults->Get("profPt");
  TProfile *profRawPt=(TProfile*)fResults->Get("profPt0");
  profRawPt->Draw();
  profCorPt->Draw("same");
  profRawPt->GetXaxis()->SetTitle("Pt");
  profRawPt->GetYaxis()->SetTitle("E/Eraw");
  profRawPt->SetTitle("Profile of E/Eraw vs Pt");
  profCorPt->SetMarkerStyle(8);
  profCorPt->SetLineColor(kRed);
  profCorPt->SetMarkerColor(kRed);
  profRawPt->SetMarkerStyle(4);
  profRawPt->SetLineColor(kBlue);
  profRawPt->SetMarkerColor(kBlue);
  leg2->Draw();
  canCorPt->SaveAs(Form("plotsAll/%s/CorPt.png",dir.c_str()));


*/

  //Plot Bias and Resolution vs Pt

 /* TCanvas *canResPt=new TCanvas;
  TProfile *profResPt=(TProfile*)fResults->Get("profPtRes");
  profResPt->Draw();
  profResPt->GetXaxis()->SetTitle("Pt");
  profResPt->GetYaxis()->SetTitle("|Ecor-Etrue|/Eraw");
  profResPt->SetTitle("Profile of SigmaE/E vs Pt");
  profResPt->SetMarkerStyle(3);
  profResPt->SetLineColor(kRed);
  canResPt->SaveAs(Form("plotsAll/%s/ResPt.png",dir.c_str()));
*/

//Plot Bias and resolution in bins of Pt and eta


  double errpt[9];
  double pt[9];
  double sigeff11[9];
  double errsigeff11[9];
  double sigeff12[9];
  double errsigeff12[9];
  double sigeff13[9];
  double errsigeff13[9];
  double sigeff14[9];
  double errsigeff14[9];
  double mean11[9];
  double errmean11[9];
  double mean12[9];
  double errmean12[9];
  double mean13[9];
  double errmean13[9];
  double mean14[9];
  double errmean14[9];
  double sigeff21[9];
  double errsigeff21[9];
  double sigeff22[9];
  double errsigeff22[9];
  double sigeff23[9];
  double errsigeff23[9];
  double sigeff24[9];
  double errsigeff24[9];
  double mean21[9];
  double errmean21[9];
  double mean22[9];
  double errmean22[9];
  double mean23[9];
  double errmean23[9];
  double mean24[9];
  double errmean24[9];
  double sigeff31[9];
  double errsigeff31[9];
  double sigeff32[9];
  double errsigeff32[9];
  double sigeff33[9];
  double errsigeff33[9];
  double sigeff34[9];
  double errsigeff34[9];
  double mean31[9];
  double errmean31[9];
  double mean32[9];
  double errmean32[9];
  double mean33[9];
  double errmean33[9];
  double mean34[9];
  double errmean34[9];

/*  TCanvas *can10 = new TCanvas("can7","can7",1200,700);
  can10->Divide(5,4);
  TCanvas *can11 = new TCanvas("can8","can8",1200,700);
  can11->Divide(5,4);
  TCanvas *can12 = new TCanvas("can9","can9",1200,700);
  can12->Divide(5,4);
  TCanvas *can13 = new TCanvas("can10","can10",1200,700);
  can13->Divide(5,4);
*/
  for (int i=1;i<10;i++){
  	
	pt[i-1]=(i+1)*20.;
        errpt[i-1]=20;

	TH1 *HistPt11=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta1",(i+1)*20));
  	//RooDataHist *HistPtclone11=new RooDataHist("","",*var,HistPt11);
  	//RooDoubleCBFast *CB11=FitWithDCB(HistPtclone11,bias,mean11[i-1],errmean11[i-1]);  
  	sigeff11[i-1]=effSigma(HistPt11);
	errsigeff11[i-1]=0.4/199;

	TH1 *HistPt12=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta2",(i+1)*20));
  	//RooDataHist *HistPtclone12=new RooDataHist("","",*var,HistPt12);
  	//RooDoubleCBFast *CB12=FitWithDCB(HistPtclone12,bias,mean12[i-1],errmean12[i-1]);  
  	sigeff12[i-1]=effSigma(HistPt12);
	errsigeff12[i-1]=0.4/99;

	TH1 *HistPt13=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta3",(i+1)*20));
  	//RooDataHist *HistPtclone13=new RooDataHist("","",*var,HistPt13);
  	//RooDoubleCBFast *CB13=FitWithDCB(HistPtclone13,bias,mean13[i-1],errmean13[i-1]);  
  	sigeff13[i-1]=effSigma(HistPt13);
	errsigeff13[i-1]=0.4/99;
 

	TH1 *HistPt14=(TH1*)fResults1->Get(Form("hBias_Pt%i_eta4",(i+1)*20));
  	//RooDataHist *HistPtclone14=new RooDataHist("","",*var,HistPt14);
	//RooDoubleCBFast *CB14=FitWithDCB(HistPtclone14,bias,mean14[i-1],errmean14[i-1]);  
  	sigeff14[i-1]=effSigma(HistPt14);
	errsigeff14[i-1]=0.4/99;	

	TH1 *HistPt21=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta1",(i+1)*20));
  	//RooDataHist *HistPtclone21=new RooDataHist("","",*var,HistPt21);
  	//RooDoubleCBFast *CB21=FitWithDCB(HistPtclone21,bias,mean21[i-1],errmean21[i-1]);  
  	sigeff21[i-1]=effSigma(HistPt21);
	errsigeff21[i-1]=0.4/199;

	TH1 *HistPt22=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta2",(i+1)*20));
  	//RooDataHist *HistPtclone22=new RooDataHist("","",*var,HistPt22);
  	//RooDoubleCBFast *CB22=FitWithDCB(HistPtclone22,bias,mean22[i-1],errmean22[i-1]);  
  	sigeff22[i-1]=effSigma(HistPt22);
	errsigeff22[i-1]=0.4/99;

	TH1 *HistPt23=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta3",(i+1)*20));
  	//RooDataHist *HistPtclone23=new RooDataHist("","",*var,HistPt23);
  	//RooDoubleCBFast *CB23=FitWithDCB(HistPtclone23,bias,mean23[i-1],errmean23[i-1]);  
  	sigeff23[i-1]=effSigma(HistPt23);
	errsigeff23[i-1]=0.4/99;
 

	TH1 *HistPt24=(TH1*)fResults2->Get(Form("hBias_Pt%i_eta4",(i+1)*20));
  	//RooDataHist *HistPtclone24=new RooDataHist("","",*var,HistPt24);
	//RooDoubleCBFast *CB24=FitWithDCB(HistPtclone24,bias,mean24[i-1],errmean24[i-1]);  
  	sigeff24[i-1]=effSigma(HistPt24);
	errsigeff24[i-1]=0.4/99;

	TH1 *HistPt31=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta1",(i+1)*20));
  	//RooDataHist *HistPtclone31=new RooDataHist("","",*var,HistPt31);
  	//RooDoubleCBFast *CB31=FitWithDCB(HistPtclone31,bias,mean31[i-1],errmean31[i-1]);  
  	sigeff31[i-1]=effSigma(HistPt31);
	errsigeff31[i-1]=0.4/199;

	TH1 *HistPt32=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta2",(i+1)*20));
  	//RooDataHist *HistPtclone32=new RooDataHist("","",*var,HistPt32);
  	//RooDoubleCBFast *CB32=FitWithDCB(HistPtclone32,bias,mean32[i-1],errmean32[i-1]);  
  	sigeff32[i-1]=effSigma(HistPt32);
	errsigeff32[i-1]=0.4/99;

	TH1 *HistPt33=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta3",(i+1)*20));
  	//RooDataHist *HistPtclone33=new RooDataHist("","",*var,HistPt33);
  	//RooDoubleCBFast *CB33=FitWithDCB(HistPtclone33,bias,mean33[i-1],errmean33[i-1]);  
  	sigeff33[i-1]=effSigma(HistPt33);
	errsigeff33[i-1]=0.4/99;
 

	TH1 *HistPt34=(TH1*)fResults3->Get(Form("hBias_Pt%i_eta4",(i+1)*20));
  	//RooDataHist *HistPtclone34=new RooDataHist("","",*var,HistPt34);
	//RooDoubleCBFast *CB34=FitWithDCB(HistPtclone34,bias,mean34[i-1],errmean34[i-1]);  
  	sigeff34[i-1]=effSigma(HistPt34);
	errsigeff34[i-1]=0.4/99;
  }



  TCanvas *can15=new TCanvas;
  can15->Divide(2,2);
  can15->cd(1);
  TGraphErrors *graphRes_Pt11 = new TGraphErrors(9,pt,sigeff11,errpt,errsigeff11);
  graphRes_Pt11->SetMarkerStyle(8);
  graphRes_Pt11->SetMarkerColor(kBlue+2);
  graphRes_Pt11->SetLineColor(kBlue+2);
  TGraphErrors *graphRes_Pt21 = new TGraphErrors(9,pt,sigeff21,errpt,errsigeff21);
  graphRes_Pt21->SetMarkerStyle(8);
  graphRes_Pt21->SetMarkerColor(kRed+1);
  graphRes_Pt21->SetLineColor(kRed+1);
  TGraphErrors *graphRes_Pt31 = new TGraphErrors(9,pt,sigeff31,errpt,errsigeff31);
  graphRes_Pt31->SetMarkerStyle(8);
  graphRes_Pt31->SetMarkerColor(kOrange+1);
  graphRes_Pt31->SetLineColor(kOrange+1);
  TMultiGraph *graphRes_Pt1=new TMultiGraph();
  graphRes_Pt1->Add(graphRes_Pt11);
  graphRes_Pt1->Add(graphRes_Pt21);
  graphRes_Pt1->Add(graphRes_Pt31);
  graphRes_Pt1->Draw("AP");
  //graphRes_Pt1->GetXaxis()->SetTitle("pt");
  //graphRes_Pt1->GetYaxis()->SetTitle("Ecor/Etrue effective width");
  graphRes_Pt1->SetTitle("Ecor/Etrue effective width vs Pt for |#eta|<1;pt;Ecor/Etrue effective width"); 
  TLegend *leg3 = new TLegend(0.69,0.69,0.89,0.89);
  leg3->SetBorderSize(0);
  leg3->SetFillColor(0);
  leg3->AddEntry(graphRes_Pt11, "no PU","lp");
  leg3->AddEntry(graphRes_Pt21, "bx 50","lp");
  leg3->AddEntry(graphRes_Pt31, "bx 25","lp");
  leg3->Draw(); 
  
  can15->cd(2);
  TGraphErrors *graphRes_Pt12 = new TGraphErrors(9,pt,sigeff12,errpt,errsigeff12);
  graphRes_Pt12->SetMarkerStyle(8);
  graphRes_Pt12->SetMarkerColor(kBlue+2);
  graphRes_Pt12->SetLineColor(kBlue+2);
  TGraphErrors *graphRes_Pt22 = new TGraphErrors(9,pt,sigeff22,errpt,errsigeff22);
  graphRes_Pt22->SetMarkerStyle(8);
  graphRes_Pt22->SetMarkerColor(kRed+1);
  graphRes_Pt22->SetLineColor(kRed+1);
  TGraphErrors *graphRes_Pt32 = new TGraphErrors(9,pt,sigeff32,errpt,errsigeff32);
  graphRes_Pt32->SetMarkerStyle(8);
  graphRes_Pt32->SetMarkerColor(kOrange+1);
  graphRes_Pt32->SetLineColor(kOrange+1);
  TMultiGraph *graphRes_Pt2=new TMultiGraph();
  graphRes_Pt2->Add(graphRes_Pt12);
  graphRes_Pt2->Add(graphRes_Pt22);
  graphRes_Pt2->Add(graphRes_Pt32);
  graphRes_Pt2->Draw("AP");
  //graphRes_Pt2->GetXaxis()->SetTitle("pt");
  //graphRes_Pt2->GetYaxis()->SetTitle("Ecor/Etrue effective width");
  graphRes_Pt2->SetTitle("Ecor/Etrue effective width vs Pt for 1<|#eta|<1.5;pt;Ecor/Etrue effective width"); 
  leg3->Draw();

  can15->cd(3);
  TGraphErrors *graphRes_Pt13 = new TGraphErrors(9,pt,sigeff13,errpt,errsigeff13);
  graphRes_Pt13->SetMarkerStyle(8);
  graphRes_Pt13->SetMarkerColor(kBlue+2);
  graphRes_Pt13->SetLineColor(kBlue+2);
  TGraphErrors *graphRes_Pt23 = new TGraphErrors(9,pt,sigeff23,errpt,errsigeff23);
  graphRes_Pt23->SetMarkerStyle(8);
  graphRes_Pt23->SetMarkerColor(kRed+1);
  graphRes_Pt23->SetLineColor(kRed+1);
  TGraphErrors *graphRes_Pt33 = new TGraphErrors(9,pt,sigeff33,errpt,errsigeff33);
  graphRes_Pt33->SetMarkerStyle(8);
  graphRes_Pt33->SetMarkerColor(kOrange+1);
  graphRes_Pt33->SetLineColor(kOrange+1);
  TMultiGraph *graphRes_Pt3=new TMultiGraph();
  graphRes_Pt3->Add(graphRes_Pt13);
  graphRes_Pt3->Add(graphRes_Pt23);
  graphRes_Pt3->Add(graphRes_Pt33);
  graphRes_Pt3->Draw("AP");
  //graphRes_Pt3->GetXaxis()->SetTitle("pt");
  //graphRes_Pt3->GetYaxis()->SetTitle("Ecor/Etrue effective width");
  graphRes_Pt3->SetTitle("Ecor/Etrue effective width vs Pt for 1.5<|#eta|<2;pt;Ecor/Etrue effective width"); 
  leg3->Draw(); 

  can15->cd(4);
  TGraphErrors *graphRes_Pt14 = new TGraphErrors(9,pt,sigeff14,errpt,errsigeff14);
  graphRes_Pt14->SetMarkerStyle(8);
  graphRes_Pt14->SetMarkerColor(kBlue+2);
  graphRes_Pt14->SetLineColor(kBlue+2);
  TGraphErrors *graphRes_Pt24 = new TGraphErrors(9,pt,sigeff24,errpt,errsigeff24);
  graphRes_Pt24->SetMarkerStyle(8);
  graphRes_Pt24->SetMarkerColor(kRed+1);
  graphRes_Pt24->SetLineColor(kRed+1);
  TGraphErrors *graphRes_Pt34 = new TGraphErrors(9,pt,sigeff34,errpt,errsigeff34);
  graphRes_Pt34->SetMarkerStyle(8);
  graphRes_Pt34->SetMarkerColor(kOrange+1);
  graphRes_Pt34->SetLineColor(kOrange+1);
  TMultiGraph *graphRes_Pt4=new TMultiGraph();
  graphRes_Pt4->Add(graphRes_Pt14);
  graphRes_Pt4->Add(graphRes_Pt24);
  graphRes_Pt4->Add(graphRes_Pt34);
  graphRes_Pt4->Draw("AP");
  //graphRes_Pt4->GetXaxis()->SetTitle("pt");
  //graphRes_Pt4->GetYaxis()->SetTitle("Ecor/Etrue effective width");
  graphRes_Pt4->SetTitle("Ecor/Etrue effective width vs Pt for 1.5<|#eta|;pt;Ecor/Etrue effective width"); 
  leg3->Draw();

  can15->SaveAs(Form("plotsAll/%s/Res_Pt_Eta.pdf",dir.c_str()));
  can15->SaveAs(Form("plotsAll/%s/Res_Pt_Eta.png",dir.c_str()));

/*
  TCanvas *can14=new TCanvas;
  can14->Divide(2,2);
  can14->cd(1);
  TGraphErrors *graphCor_Pt1 = new TGraphErrors(9,pt,mean1,errpt,errmean1);
  graphCor_Pt1->Draw("AL*");
  graphCor_Pt1->SetMarkerStyle(8);
  graphCor_Pt1->GetXaxis()->SetTitle("pt");
  graphCor_Pt1->GetYaxis()->SetTitle("Ecor/Etrue mean");
  graphCor_Pt1->SetTitle("Ecor/Etrue peak value vs Pt for 0<|eta|<1"); 
  can14->cd(2);
  TGraphErrors *graphCor_Pt2 = new TGraphErrors(9,pt,mean2,errpt,errmean2);
  graphCor_Pt2->Draw("AL*");
  graphCor_Pt2->SetMarkerStyle(8);
  graphCor_Pt2->GetXaxis()->SetTitle("pt");
  graphCor_Pt2->GetYaxis()->SetTitle("Ecor/Etrue mean");
  graphCor_Pt2->SetTitle("Ecor/Etrue peak value vs Pt for 1<|eta|<1.48"); 
  can14->cd(3);
  TGraphErrors *graphCor_Pt3 = new TGraphErrors(9,pt,mean3,errpt,errmean3);
  graphCor_Pt3->Draw("AL*");
  graphCor_Pt3->SetMarkerStyle(8);
  graphCor_Pt3->GetXaxis()->SetTitle("pt");
  graphCor_Pt3->GetYaxis()->SetTitle("Ecor/Etrue mean");
  graphCor_Pt3->SetTitle("Ecor/Etrue peak value vs Pt for 1.48<|eta|<2"); 
  can14->cd(4);
  TGraphErrors *graphCor_Pt4 = new TGraphErrors(9,pt,mean4,errpt,errmean4);
  graphCor_Pt4->Draw("AL*");
  graphCor_Pt4->SetMarkerStyle(8);
  graphCor_Pt4->GetXaxis()->SetTitle("pt");
  graphCor_Pt4->GetYaxis()->SetTitle("Ecor/Etrue mean");
  graphCor_Pt4->SetTitle("Ecor/Etrue peak value vs Pt for 2<|eta|<2.5"); 
  can14->SaveAs(Form("plotsAll/%s/Bias_Pt_Eta.png",dir.c_str()));
*/
}
void ZeeGammaMassFitSystematicStudy(string workspaceFile, const Int_t seed = 1234, 
                                    Int_t Option = 0, Int_t NToys = 1) {


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

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

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

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

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

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

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

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

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

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

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

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

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


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



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

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

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

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

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


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

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

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

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

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

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


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

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

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





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

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

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


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




  } //for loop over all toys
  



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

}
Example #28
0
//before: gROOT->ProcessLine(".include /afs/cern.ch/cms/slc5_ia32_gcc434/lcg/roofit/5.26.00-cms5/include")
//5_3_6:  gROOT->ProcessLine(".include /afs/cern.ch/cms/slc5_amd64_gcc462/lcg/roofit/5.32.03-cms9/include/")
//Usage: .x Gaussian_fit.C+("Compare2012DMINECCnot","2012D_EtaRingMY_Vs_MYnoCC.root")
void Gaussian_fit( string Dir, string File ){

    string PathL = Dir + "/" + File;
    TCanvas* myc1 = new TCanvas("myc1", "CMS", 600, 600);
    TString outname = Dir + "/Gaus_Fit.root";

    //Files
    cout<<"Opening: "<<PathL<<endl;
    TFile* fin = TFile::Open(PathL.c_str());
    //Histos
    string List[4]={"Ratio1D_EB","Ratio1D_EEm","Ratio1D_EEp","Ratio1D_EB_eta1"};

    for(int nH=0; nH<4; nH++){

	  TH1F *h_toFit = (TH1F*) fin->Get( List[nH].c_str() );
	  float hmean = h_toFit->GetMean();
	  float hrms = h_toFit->GetRMS();
	  TString outName = Dir + "/" + "Ratio1D_EB.png";
	  if(nH==1) outName = Dir + "/" + "Ratio1D_EEm.png";
	  if(nH==2) outName = Dir + "/" + "Ratio1D_EEp.png";
	  if(nH==3) outName = Dir + "/" + "Ratio1D_EB_eta1.png";

	  //Fit Method
	  RooRealVar x("x","IC distribution",hmean-1.6*hrms, hmean+1.6*hrms, "");
	  RooDataHist dh("dh","#gamma#gamma invariant mass",RooArgList(x),h_toFit);
	  RooRealVar mean("mean","mean",hmean, hmean-1.5*hrms,hmean+1.5*hrms,"");
	  RooRealVar sigma("sigma","#sigma",hrms, hrms-hrms/40.,hrms+hrms/40.,"");
	  mean.setRange(hmean-hmean/2.,hmean+hmean/2.);
	  sigma.setRange(0.,hrms+hrms/2.);
	  RooGaussian gaus("gaus","Core Gaussian",x, mean,sigma);
	  RooRealVar Nsig("Nsig","#pi^{0} yield",1000.,0.,1.e7);
	  Nsig.setVal( h_toFit->Integral()-h_toFit->Integral()/1000. );
	  Nsig.setRange(h_toFit->Integral()/50.,h_toFit->Integral());

	  RooRealVar cb0("cb0","cb0", 0.2, -1.,1.);
	  RooRealVar cb1("cb1","cb1",-0.1, -1.,1.);
	  RooRealVar cb2("cb2","cb2", 0.1, -1.,1.);
	  RooArgList cbpars(cb0,cb1,cb2);
	  RooChebychev bkg("bkg","bkg model", x, cbpars );
	  RooRealVar Nbkg("Nbkg","background yield",h_toFit->Integral()/100.,0.,h_toFit->Integral());
	  Nbkg.setVal( h_toFit->Integral()/100. );


	  RooAddPdf model1("model","only_gaus",RooArgList(gaus),RooArgList(Nsig));
	  RooAddPdf model2("model","sig+bkg",RooArgList(gaus,bkg),RooArgList(Nsig,Nbkg));
	  RooAbsPdf* model=0; model = &model2;
	  RooNLLVar nll("nll","log likelihood var",*model,dh);//,Extended());
	  RooMinuit m(nll);
	  m.setVerbose(kFALSE);
	  m.migrad();
	  //RooFitResult* res = m.save();

	  RooPlot*  xframe = x.frame(h_toFit->GetNbinsX());
	  xframe->SetTitle("");
	  dh.plotOn(xframe);
	  model->plotOn(xframe);
	  //model->plotOn(xframe,Components(bkg),LineStyle(kDashed), LineColor(kRed));
	  h_toFit->Draw();
	  xframe->Draw("same");
	  //myc1->SaveAs(outName.Data());
	  float sigma_plot  = sigma.getVal();

	  TLatex lat;
	  char line[300];
	  lat.SetNDC();
	  lat.SetTextSize(0.030);
	  lat.SetTextColor(1);
	  sprintf(line,"SIGMA: %.6f ", sigma_plot );
	  float xmin(0.55), yhi(0.80);// ypass(0.05);
	  lat.DrawLatex(xmin,yhi, line);
	  myc1->SaveAs(outName.Data());
    }
    //rms_EB->Write();
    //rms_EEp->Write();
    //rms_EEm->Write();
    //output->Close();
}
Example #29
0
void fitSignalShapeW(int massBin,int id, int channels,int categ, int sample, 
		     /* float lumi, bool doSfLepton, */double rangeLow, double rangeHigh,
		     double bwSigma,
		     double fitValues[9], double fitErrors[9], double covQual[1]){
 // ------ root settings ---------
  gROOT->Reset();  
  gROOT->SetStyle("Plain");
  gStyle->SetPadGridX(kFALSE);
  gStyle->SetPadGridY(kFALSE);
  //gStyle->SetOptStat("kKsSiourRmMen");
  gStyle->SetOptStat("iourme");
  //gStyle->SetOptStat("rme");
  //gStyle->SetOptStat("");
  gStyle->SetOptFit(11);
  gStyle->SetPadLeftMargin(0.14);
  gStyle->SetPadRightMargin(0.06);
  // ------------------------------ 

  ROOT::Math::MinimizerOptions::SetDefaultTolerance( 1.E-7);

  stringstream FileName;
  //Insert the file here
  if(sample==1) FileName <<"root://lxcms03//data3/Higgs/150915/ZH125/ZZ4lAnalysis.root" ;
  else if(sample==2) FileName << "root://lxcms03//data3/Higgs/150915/WplusH125/ZZ4lAnalysis.root";
  else if(sample==3) FileName << "root://lxcms03//data3/Higgs/150915/WminusH125/ZZ4lAnalysis.root";
  else if(sample==4) FileName << "root://lxcms03//data3/Higgs/150915/ttH125/ZZ4lAnalysis.root";
  else {
    cout << "Wrong sample." << endl;
    return;
  }
    

  cout << "Using " << FileName.str() << endl;
  
 
  TFile* ggFile = TFile::Open(FileName.str().c_str()); 

  TTree* ggTree = (TTree*) ggFile->Get("ZZTree/candTree");

  float m4l;
  
  Short_t z1flav, z2flav; 
  float weight;

  Short_t nExtraLeptons;   
  float ZZPt;
  Short_t nJets;
  Short_t nBTaggedJets;
  std::vector<float> * jetpt = 0;
  std::vector<float> * jeteta = 0;
  std::vector<float> * jetphi = 0;
  std::vector<float> * jetmass = 0;
  float jet30pt[10];
  float jet30eta[10];
  float jet30phi[10];
  float jet30mass[10];
  float Fisher;
  
  int  nentries = ggTree->GetEntries();
 
  //--- ggTree part
  ggTree->SetBranchAddress("ZZMass",&m4l);
  ggTree->SetBranchAddress("Z1Flav",&z1flav);
  ggTree->SetBranchAddress("Z2Flav",&z2flav);
  ggTree->SetBranchAddress("genHEPMCweight",&weight);
  ggTree->SetBranchAddress("nExtraLep",&nExtraLeptons);
  ggTree->SetBranchAddress("nCleanedJets",&nJets);
  ggTree->SetBranchAddress("nCleanedJetsPt30BTagged",&nBTaggedJets);
  ggTree->SetBranchAddress("DiJetFisher",&Fisher);
  
  ggTree->SetBranchAddress("JetPt",&jetpt);
  ggTree->SetBranchAddress("JetEta",&jeteta);
  ggTree->SetBranchAddress("JetPhi",&jetphi);
  ggTree->SetBranchAddress("JetMass",&jetmass);
  ggTree->SetBranchAddress("ZZPt",&ZZPt);

  //--- rooFit part
  double xMin,xMax,xInit;
  xInit = (double) massBin;
  xMin = rangeLow;
  xMax = rangeHigh ;
  cout << "Fit range: [" << xMin << " , " << xMax << "]. Init value = " << xInit << endl;
  
  TH1F *hmass = new TH1F("hmass","hmass",200,xMin,xMax);
  //---------  
  RooRealVar x("mass","m_{4l}",xInit,xMin,xMax,"GeV");
  RooRealVar w("myW","myW",1.0,0.,1000.);
  RooArgSet ntupleVarSet(x,w);
  RooDataSet dataset("mass4l","mass4l",ntupleVarSet,WeightVar("myW"));

  for(int k=0; k<nentries; k++){
    ggTree->GetEvent(k);

    int njet30 = 0;
    for (unsigned int ijet = 0; ijet < jetpt->size(); ijet++) { 
      if ( (*jetpt)[ijet] > 30. ) {
	jet30pt[njet30] = (*jetpt)[ijet];      
	jet30eta[njet30] = (*jeteta)[ijet];
	jet30phi[njet30] = (*jetphi)[ijet];
	jet30mass[njet30] = (*jetmass)[ijet];
	njet30++;
      }
    }  
    int Cat = category(nExtraLeptons, ZZPt, m4l, njet30, nBTaggedJets, jet30pt, jet30eta, jet30phi,jet30mass, Fisher); 
    if (categ >= 0 && categ != Cat ) continue;

 
    if(channels==0 && z1flav*z2flav != 28561) continue;
    if(channels==1 && z1flav*z2flav != 14641) continue;
    if (weight <= 0 ) cout << "Warning! Negative weight events" << endl;
    if(channels==2 && z1flav*z2flav != 20449) continue;
    

    ntupleVarSet.setRealValue("mass",m4l);
    ntupleVarSet.setRealValue("myW",weight);
    if(x.getVal()>xMin && x.getVal()<xMax)
      dataset.add(ntupleVarSet, weight);
    hmass->Fill(m4l);

  }
  //---------

  cout << "dataset n entries: " << dataset.sumEntries() << endl;


  TCanvas *c1 = new TCanvas("c1","c1",725,725);


  c1->cd();

  TPad *pad1 = new TPad("pad1","This is pad1",0.05,0.35,0.95,0.97);
  pad1->Draw();
  TPad *pad2 = new TPad("pad2","This is pad2",0.05,0.02,0.95,0.35);
  pad2->Draw();

  //--- double CrystalBall
  RooRealVar mean("bias","mean of gaussian",0,-5.,5.) ;
  RooRealVar sigma("sigma","width of gaussian",1.5,0.,30.); 
  RooRealVar a1("a1","a1",1.46,0.5,5.);
  RooRealVar n1("n1","n1",1.92,0.,10.);   
  RooRealVar a2("a2","a2",1.46,1.,10.);
  RooRealVar n2("n2","n2",20,1.,50.);   
  RooDoubleCB DCBall("DCBall","Double Crystal ball",x,mean,sigma,a1,n1,a2,n2);
  if (channels== 1) mean.setVal(-1.);
  //--- Breit-Wigner
  float bwSigmaMax,bwSigmaMin;
  if(massBin<400) bwSigmaMin=bwSigmaMax=bwSigma;
  else { 
    bwSigmaMin=bwSigma-20.; 
    bwSigmaMax=bwSigma+20.; 
  }
  RooRealVar mean3("mean3","mean3",xInit) ;
  RooRealVar sigma3("sigma3","width3",bwSigma,bwSigmaMin,bwSigmaMax); 
  RooRealVar scale3("scale3","scale3 ",1.); 

  RooRelBWUFParam bw("bw","bw",x,mean3,scale3);
  //Chebyshev-Polynomial
  RooRealVar A1("A1","A1",-1,-3,3.);
  RooRealVar A2("A2","A2",0.5,-3.,3.);
  RooChebychev BkgPDF("BkgPDF","BkgPDF",x ,RooArgList(A1,A2));
  //Fraction
  RooRealVar frac("frac","Fraction for PDF",0.5,0.,1.);

  x.setBins(10000,"fft");
  RooFFTConvPdf model("model","model",x,bw,DCBall);
  

  RooAddPdf totPDF("totPDF","Total PDF ",RooArgList(model,BkgPDF),RooArgList(frac));
  
  RooArgSet* params = totPDF.getParameters(x);
  
  if(sample!=1 && categ!=0 && id!=125){
  if(channels==0 ){params->readFromFile("Ch0_Cat0_paraT.txt");}// Read the Parameter for the Resonance + Bkg(ChebyChev) 

  if(channels==1 ){params->readFromFile("Ch1_Cat0_paraT.txt");}// Read the Parameter for the Resonance + Bkg(ChebyChev)

  if(channels==2 ){params->readFromFile("Ch2_Cat0_paraT.txt");}//  Read the Parameter for the Resonance + Bkg(ChebyChev)
  }
  
  RooFitResult *fitres = (RooFitResult*)totPDF.fitTo(dataset,SumW2Error(1),Range(xMin,xMax),Strategy(2),NumCPU(8),Save(true));

  if (sample==1 && categ==0 && id==125){
 
  mean.setConstant(kTRUE);
  sigma.setConstant(kTRUE);
  a1.setConstant(kTRUE);
  n1.setConstant(kTRUE);
  a2.setConstant(kTRUE);
  n2.setConstant(kTRUE);
  mean3.setConstant(kTRUE);
  sigma3.setConstant(kTRUE);
  scale3.setConstant(kTRUE);
  A1.setConstant(kTRUE);
  A2.setConstant(kTRUE);
  frac.setConstant(kTRUE);

  if(channels==0 ){
  params->readFromFile("Ch0_Cat0_para.txt");  // Read the Parameter for the Resonance as ggH sample
  params->writeToFile("Ch0_Cat0_paraT.txt");} // Writing the Parameter for Full PDF including the Chebyshev-Polynomial

  if(channels==1 )
  {params->readFromFile("Ch1_Cat0_para.txt"); // Read the Parameter for the Resonance as in ggH sample
   params->writeToFile("Ch1_Cat0_paraT.txt");}// Writing the Parameter for Full PDF including the Chebyshev-Polynomial

  if(channels==2 ){
  params->readFromFile("Ch2_Cat0_para.txt"); // Read the Parameter for the Resonance as ggH sample
  params->writeToFile("Ch2_Cat0_paraT.txt");}// Writing the Parameter for Full PDF including the Chebyshev-Polynomial
  }
  
  stringstream frameTitle;
  if(channels==0){frameTitle << "4#mu, m_{H} = "; }
  if(channels==1){frameTitle << "4e, m_{H} = ";}
  if(channels==2){frameTitle << "2e2#mu, m_{H} = ";}
  frameTitle << massBin << " GeV";

  stringstream nameFileRoot;
  nameFileRoot << "fitM" << massBin << ".root";
  TFile *fileplot = TFile::Open(nameFileRoot.str().c_str(), "recreate");

  RooPlot* xframe = x.frame() ;
  xframe->SetTitle("");
  xframe->SetName("m4lplot");
  dataset.plotOn(xframe,DataError(RooAbsData::SumW2), MarkerStyle(kOpenCircle), MarkerSize(1.1) );
  int col;
  if(channels==0) col=kOrange+7;
  if(channels==1) col=kAzure+2;
  if(channels==2) col=kGreen+3;
  totPDF.plotOn(xframe,LineColor(col));


  RooHist* hpull = xframe->pullHist();

  RooPlot* frame3 = x.frame(Title("Pull Distribution")) ;
  frame3->addPlotable(hpull,"P");
  
  // cosmetics
  TLegend *legend = new TLegend(0.20,0.45,0.45,0.60,NULL,"brNDC");
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  legend->SetTextAlign(12);
  legend->SetTextFont (42);
  legend->SetTextSize (0.03);

  TH1F *dummyPoints = new TH1F("dummyP","dummyP",1,0,1);
  TH1F *dummyLine = new TH1F("dummyL","dummyL",1,0,1);
  dummyPoints->SetMarkerStyle(kOpenCircle);
  dummyPoints->SetMarkerSize(1.1);
  dummyLine->SetLineColor(col);
  
  legend->AddEntry(dummyPoints, "Simulation", "pe");
  legend->AddEntry(dummyLine, "Parametric Model", "l");
  
  TPaveText *text = new TPaveText(0.15,0.90,0.77,0.98,"brNDC");
  text->AddText("CMS Simulation");
  text->SetBorderSize(0);
  text->SetFillStyle(0);
  text->SetTextAlign(12);
  text->SetTextFont(42);
  text->SetTextSize(0.03);

  TPaveText *titlet = new TPaveText(0.15,0.80,0.60,0.85,"brNDC");
  titlet->AddText(frameTitle.str().c_str());
  titlet->SetBorderSize(0);
  titlet->SetFillStyle(0);
  titlet->SetTextAlign(12);
  titlet->SetTextFont(132);
  titlet->SetTextSize(0.045);

  TPaveText *sigmat = new TPaveText(0.15,0.65,0.77,0.78,"brNDC");
  stringstream sigmaval0, sigmaval1, sigmaval2;
  sigmaval0 << fixed;
  sigmaval0 << setprecision(1);
  sigmaval0 << "m_{dCB} = " << mean.getVal() + massBin << " GeV";
  sigmaval1 << fixed;
  sigmaval1 << setprecision(1);
  sigmaval1 << "#sigma_{dCB} = " << sigma.getVal() << " GeV";
  sigmaval2 << fixed;
  sigmaval2 << setprecision(1);
  sigmaval2 << "RMS_{eff} = " << effSigma(hmass) << " GeV";
  
  sigmat->AddText(sigmaval1.str().c_str());
  sigmat->AddText(sigmaval2.str().c_str());
  sigmat->SetBorderSize(0);
  sigmat->SetFillStyle(0);
  sigmat->SetTextAlign(12);
  sigmat->SetTextFont(132);
  sigmat->SetTextSize(0.04);
  
  xframe->GetYaxis()->SetTitleOffset(1.5);

  cout << "EFF RMS = " << effSigma(hmass) << "    RMS = " << hmass->GetRMS() << endl;

  pad1->cd();
  stringstream nameFile, nameFileC, nameFilePng;
  nameFile << "fitM" << massBin << "_channel" << channels<< "_category"<< categ << ".pdf";
  nameFileC << "fitM" << massBin << "_channel" << channels << "_category"<< categ << ".C";
  nameFilePng << "fitM" << massBin << "_channel" << channels << "_category"<< categ << ".png";

  xframe->Draw(); 
  gPad->Update(); legend->Draw(); text->Draw(); sigmat->Draw(); titlet->Draw();

  pad2->cd() ;
  frame3->Draw() ;
  frame3->SetMinimum(-3);
  frame3->SetMaximum(3);

  TLine *line1 = new TLine(105,0,140,0);
  line1->SetLineColor(kRed);
  line1->Draw();
  

  c1->Print(nameFile.str().c_str());
  c1->SaveAs(nameFileC.str().c_str());
  c1->SaveAs(nameFilePng.str().c_str());

  fileplot->cd();
  xframe->Write();
  sigmat->Write();
  hmass->Write();

  fileplot->Close();

  if(fitValues!=0){
    fitValues[0] = a1.getVal();
    fitValues[1] = a2.getVal();
    fitValues[2] = mean.getVal();
    fitValues[3] = mean3.getVal();
    fitValues[4] = n1.getVal();
    fitValues[5] = n2.getVal();
    fitValues[6] = sigma.getVal();
    fitValues[7] = A1.getVal();
    fitValues[8] = A2.getVal();

  }  

  if(fitErrors!=0){
    fitErrors[0] = a1.getError();
    fitErrors[1] = a2.getError();
    fitErrors[2] = mean.getError();
    fitErrors[3] = mean3.getError();
    fitErrors[4] = n1.getError();
    fitErrors[5] = n2.getError();
    fitErrors[6] = sigma.getError();
    fitErrors[7] = A1.getError();
    fitErrors[8] = A2.getError();

  }

  covQual[0] = fitres->covQual();
  
}
double FitInvMassBkg_v3(TH1D* histo, TH1D* histo_bkg, TString signal = "CBxBW",TString _bkg = "Cheb", TString option = ""){


	//Set Style
	setTDRStyle();

	if(option.Contains("nentries")){return histo->GetEntries()-histo_bkg->GetEntries();}
	else{

	//Getting info about the histogram to fit
	int n = histo->GetEntries();
	double w = histo->GetXaxis()->GetBinWidth(1);
	int ndf;
	double hmin0 = histo->GetXaxis()->GetXmin();
	double hmax0 = histo->GetXaxis()->GetXmax();
	histo->GetXaxis()->SetRangeUser(hmin0,hmax0);

	//Declare observable x
	//Try to rebin using this. Doesn't work for now
        //RooBinning xbins = Rebin2(histo);
	RooRealVar x("x","x",hmin0,hmax0) ;
	RooDataHist dh("dh","dh",x,Import(*histo)) ;

	//Define the frame
	RooPlot* frame;
	frame = x.frame();
	dh.plotOn(frame,DataError(RooAbsData::SumW2), MarkerColor(1),MarkerSize(0.9),MarkerStyle(7));  //this will show histogram data points on canvas

	//x.setRange("R0",0,200) ;
	x.setRange("R1",55,200) ;
	x.setRange("D",55,120) ;

        /////////////////////
	//Define fit function 
	/////////////////////
	cout<<"Debug4"<<endl;
	
	//fsig for adding two funciton i.e. F(x) = fsig*sig(x) + (1-fsig)*bkg(x)
	//RooRealVar fsig("fsig","sigal fraction",0.5, 0., 1.);
	RooRealVar nsig("nsig","signal events",histo->GetEntries()/2., 1,histo->GetEntries());
	RooRealVar nbkg("nbkg","background events",histo_bkg->GetEntries()/2.,1,histo_bkg->GetEntries());
	RooArgList pdfval(nsig,nbkg);

	//Various parameters
	
	//True mean
	RooRealVar mean("mean","PDG mean of Z",91.186);//, 70.0, 120.0);
	//For the BW
	RooRealVar width("width","PDG width of Z",2.4952);//, 0., 5.);
	//For the Gauss and the CB alone 
	RooRealVar sigma("sigma","sigma",1, 0., 10.);
	RooRealVar alpha("alpha","alpha",0.7, 0., 7);
	RooRealVar ncb("ncb","ncb",7, 0, 150);
	//For the CB used for convolution, i.e. CBxBW
	RooRealVar cb_bias("cb_bias","bias",0, -3.,3.);
	RooRealVar cb_sigma("cb_sigma","response",1, 0.,5);
	RooRealVar cb_alpha("cb_alpha","alpha",1.,0.,7);
	RooRealVar cb_ncb("cb_ncb","ncb",2, 0, 10);
	//Gauss used for convolution
	RooRealVar gau_bias("gau_bias","alpha",0, -3., 3.);
	RooRealVar gau_sigma("gau_sigma","bias",1, 0., 7.);
	cout<<"Debug5"<<endl;

	mean.setRange(88,94);
	width.setRange(0,20);
	sigma.setRange(0.5,10);
	//fsig.setConstant(kTRUE);
	//alpha.setConstant(kTRUE);

	RooVoigtian sig_voigtian("sig_voigtian","Voigtian",x,mean,width,sigma);
	RooBreitWigner sig_bw("sig_bw","BW",x,mean,width);
	//RooGaussian sig_gau("sig_gau","gauss",x,mean,sigma);
	RooCBShape sig_cb("sig_cb", "Crystal Ball",x,mean,sigma,alpha,ncb);
	RooCBShape sig_cb_resp("sig_cb_resp", "Crystal Ball for conv.",x,cb_bias,cb_sigma,cb_alpha,cb_ncb);
	RooGaussian sig_gau_resp("sig_gau_resp", "Gaussian for conv.",x,gau_bias,gau_sigma);

	x.setBins(10000,"cache");
	RooFFTConvPdf sig_cbbw("sig_cbbw","CBxBW",x,sig_cb_resp,sig_bw);
	RooFFTConvPdf sig_bwgau("sig_bwgau","BWxGau",x,sig_bw,sig_gau_resp);

	//NB: The CrystalBall shape is Gaussian that is 'connected' to an exponential taill at 'alpha' sigma of the Gaussian. The sign determines if it happens on the left or right side. The 'n' parameter control the slope of the exponential part. 
	cout<<"Debug6"<<endl;

	RooAbsPdf* sig;
	if(signal == "Vo"){sig = &sig_bwgau;}
	else if(signal == "BW"){sig = &sig_bw;}
	//else if(signal == "Gau"){sig = &sig_gau;}
	else if(signal == "CB"){sig = &sig_cb;}
	else if(signal == "CBxBW"){ sig = &sig_cbbw;}
	else if(signal == "BWxGau"){ sig = &sig_bwgau;}
	else{ cout<<"Wrong signal function name"<<endl;
		return 1;
	}

	/////////////////////////////
	//Background fitting function
	/////////////////////////////
	
	//Get the initial parameter of the background
	//


	cout<<"Debug7"<<endl;
	vector<double> vec = FitBkg(histo_bkg,_bkg);

	//Chebychev
	RooRealVar a0("a0","a0",vec[0],-5.,0.) ;
	RooRealVar a1("a1","a1",vec[1],-2.5,1.2) ;
	RooRealVar a2("a2","a2",vec[2],-1.5,1.) ;
	RooRealVar a3("a3","a3",vec[3],-3,1.) ;
	RooRealVar a4("a4","a4",vec[4],-1.5,1.) ;
	RooRealVar a5("a5","a5",vec[5],-1.,1.) ;
	RooRealVar a6("a6","a6",vec[6],-1.,1.) ;

	RooChebychev bkg_cheb("bkg","Background",x,RooArgSet(a0,a1,a2,a3,a4,a5,a6));

	//Novo

	RooRealVar peak_bkg("peak_bkg","peak",vec[0],0,250);
	RooRealVar width_bkg("width_bkg","width",vec[1],0,1) ;
	RooRealVar tail_bkg("tail_bkg","tail",vec[2],0,10) ;

	RooNovosibirsk bkg_nov("bkg","Background",x,peak_bkg,width_bkg,tail_bkg);

	RooAbsPdf* bkg;

	if(_bkg == "Cheb"){bkg = &bkg_cheb;}
	if(_bkg == "Novo"){bkg = &bkg_nov;}


	//////////////////////////
	//Adding the two functions
	//////////////////////////
	
	//RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),fsig);
	RooAddPdf model("model","Signal+Background", RooArgList(*sig,*bkg),pdfval);
	 
	//Perform the fit
	RooAbsPdf* fit_func;
	fit_func = &model;
	
	RooFitResult* filters = fit_func->fitTo(dh,Range("R1"),"qr");
	fit_func->plotOn(frame);
	fit_func->plotOn(frame,Components(*sig),LineStyle(kDashed),LineColor(kRed));
	fit_func->plotOn(frame,Components(*bkg),LineStyle(kDashed),LineColor(kGreen));
	frame->SetAxisRange(50,120);
	frame->Draw();
	fit_func->paramOn(frame); 
	dh.statOn(frame);  //this will display hist stat on canvas

	frame->SetTitle(histo->GetTitle());  
	frame->GetXaxis()->SetTitle("m (in GeV/c^{2})");  
	frame->GetXaxis()->SetTitleOffset(1.2);
	float binsize = histo->GetBinWidth(1); 

	//Store result in .root file
	frame->SetName(histo->GetName());
	frame->Write();

	///////////////////////
	//Plot the efficiency//
	///////////////////////
	
	//Old stuff
	
	//ofstream myfile;
	//myfile.open("/Users/GLP/Desktop/integrals.txt");
	//This one doesn't take the normalisation into account !
	//myfile<<"integral 1 "<<histo->GetName()<<endl;
	////Integral of sig
	//RooAbsReal* integral_sig = sig->createIntegral(x,x,"D") ;
	//myfile<<fsig.getVal()*integral_sig->getVal()<<endl;
	//Integral of sig+bkg
	//RooAbsReal* total = fit_func->createIntegral(x, NormSet(x), Range("D")) ;
	//Integral of sig only
	//RooAbsReal* background = bkg->createIntegral(x, NormSet(x), Range("D"));
	//cout<<"The total integral is"<<n*total->getVal();
	//cout<<"The bkg integral is"<<n*bkg->getVal();
	//cout<<"The bkg with the fsig is"<<fsig.getVal()*n*bkg->getVal();
	//cout<<"The returned value is"<<n*(total->getVal()-fsig.getVal()*background->getVal());
	//myfile<<"integral 2 "<<endl;
	//myfile<<n*(total->getVal()-(1-fsig.getVal())*background->getVal())<<endl;
	//myfile.close();
	//return n*(total->getVal()-(1-fsig.getVal())*background->getVal());
	
	return nsig.getVal();
	
	}
}