Ejemplo n.º 1
0
void Wpt_ZmassCompEtaBins_Gaus(const TString Mode,//Channel - Muon or Electron
    const TString corrName,
    const TString outputDir 
    )
{
  TString plotTitle;
  TString mu_etaRange[6];
  mu_etaRange[0] = "-2.1 #geq eta < -1.4";
  mu_etaRange[1] = "-1.4 #geq eta < -0.7";
  mu_etaRange[2] = "-0.7 #geq eta < 0";
  mu_etaRange[3] = "0 #geq eta < 0.7";
  mu_etaRange[4] = "0.7 #geq eta < 1.4";
  mu_etaRange[5] = "1.4 #geq eta < 2.1";

  TH1D* makeDiffHist(TH1D* h1, TH1D* h2, const TString name);
  const TString format("png"); 
  Int_t ratioColor = kGray+2;

  TFile *fname_MC;
  TFile *fname_RD;

  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;

  fname_MC = new TFile("Muon2012LoPU/Muon_DYToMuMu_S8.root");
  fname_RD = new TFile("Muon2012LoPU/Muon_RD_LowPU.root");

  if(Mode=="Electron")
  {
    fname_MC = new TFile("Electron2012LoPU/Ele_DYToEE_S8.root");
    fname_RD = new TFile("Electron2012LoPU/Ele_RD_LowPU.root");
  }

  CPlot *plotMllEtaBinP;
  CPlot *plotMllEtaBinM;
  CPlot *plotMllEtameanP;
  CPlot *plotMllEtameanM;
  CPlot *plotMllEtawidthP;
  CPlot *plotMllEtawidthM;

  TH1D *hMCetaBinP[ScaleBins];
  TH1D *hRDetaBinP[ScaleBins];
  TH1D *hMCetaBinM[ScaleBins];
  TH1D *hRDetaBinM[ScaleBins];

  RooDataHist *h1_MCetaBinP;
  RooDataHist *h1_RDetaBinP;
  RooDataHist *h1_MCetaBinM;
  RooDataHist *h1_RDetaBinM;

  TH1D *hMCmeanp = new TH1D("hMCmeanp","hMCmeanp",ScaleBins,-2.1,2.1);hMCmeanp->Sumw2();
  TH1D *hRDmeanp = new TH1D("hRDmeanp","hRDmeanp",ScaleBins,-2.1,2.1);hRDmeanp->Sumw2();
  TH1D *hMCmeanm = new TH1D("hMCmeanm","hMCmeanm",ScaleBins,-2.1,2.1);hMCmeanm->Sumw2();
  TH1D *hRDmeanm = new TH1D("hRDmeanm","hRDmeanm",ScaleBins,-2.1,2.1);hRDmeanm->Sumw2();

  TH1D *hMCwidthp = new TH1D("hMCwidthp","hMCwidthp",ScaleBins,-2.1,2.1);hMCwidthp->Sumw2();
  TH1D *hRDwidthp = new TH1D("hRDwidthp","hRDwidthp",ScaleBins,-2.1,2.1);hRDwidthp->Sumw2();
  TH1D *hMCwidthm = new TH1D("hMCwidthm","hMCwidthm",ScaleBins,-2.1,2.1);hMCwidthm->Sumw2();
  TH1D *hRDwidthm = new TH1D("hRDwidthm","hRDwidthm",ScaleBins,-2.1,2.1);hRDwidthm->Sumw2();

  char histName[50];
  char tmpName[50];

  TCanvas *myCan;
  myCan = MakeCanvas("myCan","myCan",800,600);

  myCan->SetPad(0,0,1.0,1.0);
  myCan->SetTopMargin(0.11);
  myCan->SetBottomMargin(0.15);
  myCan->SetLeftMargin(0.15);  
  myCan->SetRightMargin(0.05);  
  myCan->SetTickx(1);
  myCan->SetTicky(1);  

  //=============================
  //Read Zmass histograms for each pt bin
  //=============================
  for(int i(0);i<ScaleBins;i++){
    sprintf(tmpName,"h1_Zmass_muEtaP_%d",i);
    if(corrName=="CorrTotalRegion")
      sprintf(tmpName,"h1_ZmassCorr_muEtaP_%d",i);

    if(outputDir=="Wpt_ZmassPlotsEtaBins_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_noOverLap_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_noOverLap_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_noOverLap_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_noOverLap_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_noOverLap_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_noOverLap_muEtaP_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_muEtaP_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_muEtaP_%d",i);
    }

    sprintf(histName,"hMCetaBinP_%d",i);
    hMCetaBinP[i]= (TH1D*)fname_MC->Get(tmpName)->Clone(histName); hMCetaBinP[i]->Sumw2();
    sprintf(histName,"hRDetaBinP_%d",i);
    hRDetaBinP[i]= (TH1D*)fname_RD->Get(tmpName)->Clone(histName); hRDetaBinP[i]->Sumw2();

    sprintf(tmpName,"h1_Zmass_muEtaM_%d",i);
    if(corrName=="CorrTotalRegion")
      sprintf(tmpName,"h1_ZmassCorr_muEtaM_%d",i);

    if(outputDir=="Wpt_ZmassPlotsEtaBins_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_noOverLap_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_noOverLap_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_noOverLap_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_noOverLap_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_LeadingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_LeadingLept_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_LeadingLept_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_noOverLap_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_noOverLap_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_noOverLap_muEtaM_%d",i);
    }

    if(outputDir=="Wpt_ZmassPlotsEtaBins_TrailingLept_Gaus")
    {
      sprintf(tmpName,"h1_Zmass_TrailingLept_muEtaM_%d",i);
      if(corrName=="CorrTotalRegion")
	sprintf(tmpName,"h1_ZmassCorr_TrailingLept_muEtaM_%d",i);
    }

    sprintf(histName,"hMCetaBinM_%d",i);
    hMCetaBinM[i]= (TH1D*)fname_MC->Get(tmpName)->Clone(histName); hMCetaBinM[i]->Sumw2();
    sprintf(histName,"hRDetaBinM_%d",i);
    hRDetaBinM[i]= (TH1D*)fname_RD->Get(tmpName)->Clone(histName); hRDetaBinM[i]->Sumw2();
    
    hMCetaBinP[i] -> SetMarkerSize(0.9);
    hMCetaBinP[i] -> SetMarkerColor(kRed);
    hMCetaBinP[i] -> SetLineColor(kRed);
    hRDetaBinP[i] -> SetMarkerSize(0.9);
    hRDetaBinP[i] -> SetMarkerColor(kBlack);
    hRDetaBinP[i] -> SetLineColor(kBlack);
    hMCetaBinM[i] -> SetMarkerSize(0.9);
    hMCetaBinM[i] -> SetMarkerColor(kRed);
    hMCetaBinM[i] -> SetLineColor(kRed);
    hRDetaBinM[i] -> SetMarkerSize(0.9);
    hRDetaBinM[i] -> SetMarkerColor(kBlack);
    hRDetaBinM[i] -> SetLineColor(kBlack);

    RooRealVar x("x", "x",80,100);
    x.setBins(40);
    x.setRange("R0",86,96);

    h1_MCetaBinP = new RooDataHist("h1_MCetaBinP","h1_MCetaBinP",RooArgSet(x),hMCetaBinP[i]);
    h1_MCetaBinM = new RooDataHist("h1_MCetaBinM","h1_MCetaBinM",RooArgSet(x),hMCetaBinM[i]);
    h1_RDetaBinP = new RooDataHist("h1_RDetaBinP","h1_RDetaBinP",RooArgSet(x),hRDetaBinP[i]);
    h1_RDetaBinM = new RooDataHist("h1_RDetaBinM","h1_RDetaBinM",RooArgSet(x),hRDetaBinM[i]);

    //=============================
    //Gauss function
    //=============================
    RooRealVar meanMCp("meanMCp","",91.2,80,100);
    RooRealVar meanRDp("meanRDp","",91.2,80,100);
    RooRealVar meanMCm("meanMCm","",91.2,80,100);
    RooRealVar meanRDm("meanRDm","",91.2,80,100);
    RooRealVar sigmaMCp("sigmaMCp","",5,-50.,50.);
    RooRealVar sigmaRDp("sigmaRDp","",5,-50.,50.);
    RooRealVar sigmaMCm("sigmaMCm","",5,-50.,50.);
    RooRealVar sigmaRDm("sigmaRDm","",5,-50.,50.);

    RooGaussian mcModelp("mcModelp", "",x,meanMCp,sigmaMCp);
    RooGaussian mcModelm("mcModelm", "",x,meanMCm,sigmaMCm);
    RooGaussian dataModelp("dataModelp", "",x,meanRDp,sigmaRDp);
    RooGaussian dataModelm("dataModelm", "",x,meanRDm,sigmaRDm);

    //==================================
    //Fit Zmass distribution with Gaussian function
    //=============================
    mcModelp.fitTo(*h1_MCetaBinP,Range("R0"));
    mcModelm.fitTo(*h1_MCetaBinM,Range("R0"));
    dataModelp.fitTo(*h1_RDetaBinP,Range("R0"));
    dataModelm.fitTo(*h1_RDetaBinM,Range("R0"));

    //==================================
    //Fill 2D plots: etaBins and mean values
    //=============================
    hMCmeanp->SetBinContent(i+1,meanMCp.getVal());
    hRDmeanp->SetBinContent(i+1,meanRDp.getVal());
    hMCmeanm->SetBinContent(i+1,meanMCm.getVal());
    hRDmeanm->SetBinContent(i+1,meanRDm.getVal());

    hMCmeanp->SetBinError(i+1,meanMCp.getError());
    hRDmeanp->SetBinError(i+1,meanRDp.getError());
    hMCmeanm->SetBinError(i+1,meanMCm.getError());
    hRDmeanm->SetBinError(i+1,meanRDm.getError());

    hMCwidthp->SetBinContent(i+1,sigmaMCp.getVal());
    hRDwidthp->SetBinContent(i+1,sigmaRDp.getVal());
    hMCwidthm->SetBinContent(i+1,sigmaMCm.getVal());
    hRDwidthm->SetBinContent(i+1,sigmaRDm.getVal());

    hMCwidthp->SetBinError(i+1,sigmaMCp.getError());
    hRDwidthp->SetBinError(i+1,sigmaRDp.getError());
    hMCwidthm->SetBinError(i+1,sigmaMCm.getError());
    hRDwidthm->SetBinError(i+1,sigmaRDm.getError());

    cout<<meanMCp.getVal()<<"\t"<<meanMCm.getVal()<<"\t"<<meanRDp.getVal()<<"\t"<<meanRDm.getVal()<<endl;
    RooPlot* pframe = x.frame(Bins(40));
    RooPlot* mframe = x.frame(Bins(40));

    //==================================
    //Draw muon plus
    //==================================
    sprintf(tmpName,"pFit_etaBin%d_noCorr",i);
    plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{+}, before correction";
    if(corrName=="CorrTotalRegion")
    {
      sprintf(tmpName,"pFit_etaBin%d_Corr",i);
      plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{+}, after correction";
    }
    sprintf(histName,"Events / %.1f",hMCetaBinP[i]->GetBinWidth(1));
    plotMllEtaBinP = new CPlot(tmpName,pframe,plotTitle,"M_{#mu#mu} [GeV]",histName);
    plotMllEtaBinP->setOutDir(CPlot::sOutDir);

    plotMllEtaBinP->SetLegend(0.7,0.7,0.88,0.82);
    h1_MCetaBinP->plotOn(pframe,LineColor(kRed),MarkerColor(kRed),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    mcModelp.plotOn(pframe,LineColor(kRed));
    h1_RDetaBinP->plotOn(pframe,LineColor(kBlack),MarkerColor(kBlack),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    dataModelp.plotOn(pframe,LineColor(kBlack));
    plotMllEtaBinP->GetLegend()->AddEntry(hMCetaBinP[i],"Z #rightarrow #mu#mu","pl");
    plotMllEtaBinP->GetLegend()->AddEntry(hRDetaBinP[i],"Data","pl");

    sprintf(tmpName,"MC: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanMCp.getVal(),meanMCp.getError(),sigmaMCp.getVal(),sigmaMCp.getError());
    plotMllEtaBinP->AddTextBox(tmpName,0.20,0.83,0.6,0.88,0);
    sprintf(tmpName,"Data: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanRDp.getVal(),meanRDp.getError(),sigmaRDp.getVal(),sigmaRDp.getError());
    plotMllEtaBinP->AddTextBox(tmpName,0.20,0.78,0.6,0.83,0);

    plotMllEtaBinP->SetYRange(0.,1.4*TMath::Max(hRDetaBinP[i]->GetMaximum(),hMCetaBinP[i]->GetMaximum()));

    plotMllEtaBinP->Draw(myCan,kTRUE,"png");

    //==================================
    //Draw muon minus
    //=============================
    sprintf(tmpName,"mFit_etaBin%d_noCorr",i);
    plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{-}, before correction";
    if(corrName=="CorrTotalRegion")
    {
      sprintf(tmpName,"mFit_etaBin%d_Corr",i);
      plotTitle = "Wpt: " + mu_etaRange[i] + " of #mu^{-}, after correction";
    }
    sprintf(histName,"Events / %.1f",hMCetaBinM[i]->GetBinWidth(1));
    plotMllEtaBinM = new CPlot(tmpName,mframe,plotTitle,"M_{#mu#mu} [GeV]",histName);
    plotMllEtaBinM->setOutDir(CPlot::sOutDir);

    plotMllEtaBinM->SetLegend(0.7,0.7,0.88,0.82);
    h1_MCetaBinM->plotOn(mframe,LineColor(kRed),MarkerColor(kRed),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    mcModelm.plotOn(mframe,LineColor(kRed));
    h1_RDetaBinM->plotOn(mframe,LineColor(kBlack),MarkerColor(kBlack),MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"),DataError(RooAbsData::SumW2));
    dataModelm.plotOn(mframe,LineColor(kBlack));
    plotMllEtaBinM->GetLegend()->AddEntry(hMCetaBinM[i],"Z #rightarrow #mu#mu","pl");
    plotMllEtaBinM->GetLegend()->AddEntry(hRDetaBinM[i],"Data","pl");

    sprintf(tmpName,"MC: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanMCm.getVal(),meanMCm.getError(),sigmaMCm.getVal(),sigmaMCm.getError());
    plotMllEtaBinM->AddTextBox(tmpName,0.20,0.83,0.6,0.88,0);
    sprintf(tmpName,"Data: #mu=%.2f #pm %.2f, #sigma=%.2f #pm %.2f",meanRDm.getVal(),meanRDm.getError(),sigmaRDm.getVal(),sigmaRDm.getError());
    plotMllEtaBinM->AddTextBox(tmpName,0.20,0.78,0.6,0.83,0);

    plotMllEtaBinM->SetYRange(0.,1.4*TMath::Max(hRDetaBinM[i]->GetMaximum(),hMCetaBinM[i]->GetMaximum()));

    plotMllEtaBinM->Draw(myCan,kTRUE,"png");
  }

  //==================================
  //Save Mean and Width histograms to root file
  //==================================
  TString filename = outputDir + "/Wpt_MeanWidth_Gaus_" + corrName + ".root";
  TFile *outfile = new TFile(filename,"RECREATE");
  hMCmeanp ->Write();
  hMCmeanm ->Write();
  hMCwidthp->Write();
  hMCwidthm->Write();
  hRDmeanp ->Write();
  hRDmeanm ->Write();
  hRDwidthp->Write();
  hRDwidthm->Write();
  outfile->Close();

  //==================================
  //Draw 2D plots
  //==================================
  TString histoName = "plusMean_" + corrName;
  plotTitle = "Wpt: mean at #eta of #mu^{+}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: mean at #eta of #mu^{+}, after correction";
  plotMllEtameanP= new CPlot(histoName,plotTitle,"#eta of #mu^{+}","Mean of M(#mu^{+}#mu^{-})");
  plotMllEtameanP->setOutDir(CPlot::sOutDir);
  plotMllEtameanP->AddHist1D(hMCmeanp,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtameanP->AddHist1D(hRDmeanp,"Data","E1",kBlack);
                
  plotMllEtameanP->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtameanP->SetYRange(90,92);
  plotMllEtameanP->Draw(myCan,kTRUE,format);

  histoName = "minusMean_" + corrName;
  plotTitle = "Wpt: mean at #eta of #mu^{-}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: mean at #eta of #mu^{-}, after correction";
  plotMllEtameanM= new CPlot(histoName,plotTitle,"#eta of #mu^{-}","Mean of M(#mu^{+}#mu^{-})");
  plotMllEtameanM->setOutDir(CPlot::sOutDir);
  plotMllEtameanM->AddHist1D(hMCmeanm,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtameanM->AddHist1D(hRDmeanm,"Data","E1",kBlack);
                
  plotMllEtameanM->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtameanM->SetYRange(90,92);
  plotMllEtameanM->Draw(myCan,kTRUE,format);

  histoName = "plusWidth_" + corrName;
  plotTitle = "Wpt: width at #eta of #mu^{+}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: width at #eta of #mu^{+}, after correction";
  plotMllEtawidthP= new CPlot(histoName,plotTitle,"#eta of #mu^{+}","Width of M(#mu^{+}#mu^{-})");
  plotMllEtawidthP->setOutDir(CPlot::sOutDir);
  plotMllEtawidthP->AddHist1D(hMCwidthp,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtawidthP->AddHist1D(hRDwidthp,"Data","E1",kBlack);
                 
  plotMllEtawidthP->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtawidthP->SetYRange(1.5,3);
  plotMllEtawidthP->Draw(myCan,kTRUE,format);

  histoName = "minusWidth_" + corrName;
  plotTitle = "Wpt: width at #eta of #mu^{-}, before correction";
  if(corrName=="CorrTotalRegion")
    plotTitle = "Wpt: width at #eta of #mu^{-}, after correction";
  plotMllEtawidthM= new CPlot(histoName,plotTitle,"#eta of #mu^{-}","Width of M(#mu^{+}#mu^{-})");
  plotMllEtawidthM->setOutDir(CPlot::sOutDir);
  plotMllEtawidthM->AddHist1D(hMCwidthm,"Z#rightarrow #mu#mu","E1",kRed);
  plotMllEtawidthM->AddHist1D(hRDwidthm,"Data","E1",kBlack);
                 
  plotMllEtawidthM->SetLegend(0.7,0.7,0.88,0.82);
  plotMllEtawidthM->SetYRange(1.5,3);
  plotMllEtawidthM->Draw(myCan,kTRUE,format);
}
Ejemplo n.º 2
0
void drawCtauPlot(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
                  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 drawing options
                  bool setLogScale,     // Draw plot with log scale
                  bool incSS,           // Include Same Sign data
                  int  nBins,           // Number of bins used for plotting
                  bool paperStyle=false,// if true, print less info
                  bool saveWS=true      // save the workspace into a file
                  ) 
{
  if (DSTAG.find("_")!=std::string::npos) DSTAG.erase(DSTAG.find("_"));
  
  string dsOSName = Form("dOS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));
  string dsSSName = Form("dSS_%s_%s", DSTAG.c_str(), (isPbPb?"PbPb":"PP"));

  
  // Create the main plot of the fit
  // RooPlot*   frame     = myws.var("invMass")->frame(Bins(nBins), Range(cut.dMuon.M.Min, cut.dMuon.M.Max));
  RooPlot*   frame     = myws.var("ctau")->frame(Bins(nBins), Range(-1,3));
  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
    
  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));

  
  // 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("#font[12]{l}_{J/#psi} (mm)");
     frame->GetXaxis()->SetTitleOffset(1.1);
     frame->GetYaxis()->SetTitleOffset(1.45);
     frame->GetXaxis()->SetTitleSize(0.05);
     frame->GetYaxis()->SetTitleSize(0.05);
  }
  setRange(myws, frame, dsOSName, setLogScale, cut.dMuon.AbsRap.Min);
  if (paperStyle) {
     double Ydown = 0.1;//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();

  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.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;
     } 
  }
  if (cut.dMuon.AbsRap.Min>0.1) {t->DrawLatex(0.20, 0.86-dy, Form("%.1f < |y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Min,cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;}
  else {t->DrawLatex(0.20, 0.86-dy, Form("|y^{#mu#mu}| < %.1f",cut.dMuon.AbsRap.Max)); dy+=1.5*0.045;}
  t->DrawLatex(0.20, 0.86-dy, Form("%g < p_{T}^{#mu#mu} < %g GeV/c",cut.dMuon.Pt.Min,cut.dMuon.Pt.Max)); dy+=0.045;
  t->DrawLatex(0.20, 0.86-dy, Form("%g < M^{#mu#mu} < %g GeV/c^{2}",cut.dMuon.M.Min,cut.dMuon.M.Max)); dy+=0.045;
  if (isPbPb) {t->DrawLatex(0.20, 0.86-dy, Form("Cent. %d-%d%%", (int)(cut.Centrality.Start/2), (int)(cut.Centrality.End/2))); dy+=0.045;}
  dy+=0.5*0.045; t->DrawLatex(0.20, 0.86-dy, "#mu in acceptance"); dy+=0.045;

  // Drawing the Legend
  double ymin = 0.7802;
  if (paperStyle) { ymin = 0.72; }
  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"); }
  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(); 


  // Save the plot in different formats
  gSystem->mkdir(Form("%splot/%s/root/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
  cFig->SaveAs(Form("%splot/%s/root/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(),  "Psi2SJpsi", (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("%splot/%s/png/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%splot/%s/png/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.png", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (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("%splot/%s/pdf/", outputDir.c_str(), DSTAG.c_str()), kTRUE);
  cFig->SaveAs(Form("%splot/%s/pdf/%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.pdf", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (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();
  
  // Save the workspace
  if (saveWS) {
     gSystem->mkdir(Form("%sresult/%s/", outputDir.c_str(), DSTAG.c_str()), kTRUE); 
     TFile *file = NULL;
     file = new TFile(Form("%sresult/%s/FIT_%s_%s_%s%s_pt%.0f%.0f_rap%.0f%.0f_cent%d%d.root", outputDir.c_str(), DSTAG.c_str(), DSTAG.c_str(), "Psi2SJpsi", (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), "RECREATE");  
     if (!file) { 
        cout << "[ERROR] Output root file with fit results could not be created!" << endl; 
     } else {
        file->cd();    
        myws.Write("workspace"); 
        file->Write(); file->Close(); delete file;
     }
  }
}
void fitEfficiency(float thres,
		   float mLow=45, float mHigh=70,
		   TString cutdef="pt_HLT>=20", TString cut_choice="HLT",
		   TString dirIn="/data_CMS/cms/ndaci/ndaci_2012/HTauTau/TriggerStudy/SingleMu/MuMu/Run2012A_PRV1/Pairs/", 
		   TString dirResults="/home//llr/cms/ndaci/SKWork/macro/HTauTau/results/TriggerStudies/MuMu/Run2012A_PRV1/",
		   TString lumi="200 pb", int nCPU=4, 
		   int color1=kBlack, int style1=kFullCircle, int color2=kRed, int style2=kOpenSquare,
		   TString fileIn="*.root", TString image="eff_HLT_MuTau")
{
  // STYLE //
  gROOT->Reset();
  loadPresentationStyle();  
  gROOT->ForceStyle();

  // OUTPUT //
  TString name_image = dirResults+"/"+image;
  ofstream fichier(name_image+".txt", ios::out);

  // BINNING //
  const int nbinsEB = 14;
  Double_t binsEB[nbinsEB] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEB = RooBinning(nbinsEB-1, binsEB, "binningEB");

  const int nbinsEE = 14;
  Double_t binsEE[nbinsEE] = {10., 14., 18., 20., 22., 26., 30., 40., 50., 60., 70., 80, 90, 100};
  RooBinning binningEE = RooBinning(nbinsEE-1, binsEE, "binningEE");

  // EB/EE eta cuts //
  TString etacutEB="eta>-1.479 && eta<1.479", etacutEE="eta<=-1.479 || eta>=1.479";
  TString cutdefEB, cutdefEE;
  if(cutdef=="") { 
    cutdefEB=etacutEB;
    cutdefEE=etacutEE;
  }
  else {
    cutdefEB=cutdef+" && "+etacutEB ;
    cutdefEB=cutdef+" && "+etacutEE ;
  }

  // INPUT DATA //
  TChain* treeTnP = new TChain("treeTnP");
  treeTnP->Add(dirIn+"/"+fileIn);

  RooRealVar xaxis("pt","P_{T} [GeV]",0,150) ;
  RooRealVar mass("mass","mass",mLow,mHigh) ;// consider only this mass range when importing data                                      
  RooRealVar eta("eta","eta",-3., 3) ;
  RooRealVar weight("weight","weight",-1,1000) ;
  RooRealVar pt_HLT_tag("pt_HLT_tag","P_{T} [GeV]",0,150) ;
  RooRealVar pt_HLT_tag_sanity("pt_HLT_tag_sanity","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L3("pt_L3","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L25("pt_L25","P_{T} [GeV]",0,150) ;
  RooRealVar pt_L2("pt_L2","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1jet("et_L1_jet","P_{T} [GeV]",0,150) ;
  RooRealVar et_L1tau("et_L1_tau","P_{T} [GeV]",0,150) ;

  // DEFINE EFFICIENCY CUT //
  RooCategory cutHLT("match","") ;
  cutHLT.defineType("accept",1) ;
  cutHLT.defineType("reject",0) ;

  RooCategory cutL1("L1match","") ;
  cutL1.defineType("accept",1) ;
  cutL1.defineType("reject",0) ;

  RooCategory cutL1L2("L1L2match","") ;
  cutL1L2.defineType("accept",1) ;
  cutL1L2.defineType("reject",0) ;

  RooCategory cutL1L2L25("L1L2L25match","") ;
  cutL1L2L25.defineType("accept",1) ;
  cutL1L2L25.defineType("reject",0) ;

  RooCategory cutL1L2L25L3("L1L2L25L3match","") ;
  cutL1L2L25L3.defineType("accept",1) ;
  cutL1L2L25L3.defineType("reject",0) ;

  RooCategory *cut;
  if(cut_choice=="HLT") cut = &cutHLT;
  if(cut_choice=="L1") cut = &cutL1;
  if(cut_choice=="L1L2") cut = &cutL1L2;
  if(cut_choice=="L1L2L25") cut = &cutL1L2L25;
  if(cut_choice=="L1L2L25L3") cut = &cutL1L2L25L3;

  RooDataSet dataSetEB("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEB) );
  
  RooDataSet dataSetEE("data","data from tree",
		       RooArgSet(xaxis, *cut,
				 pt_HLT_tag, pt_L3, pt_L25, pt_L2,
				 mass, weight, eta),
		       WeightVar(weight), Import(*treeTnP), Cut(cutdefEE) );
  
  dataSetEB.Print();
  dataSetEE.Print();

  // PLOT //
  RooPlot* frame = xaxis.frame(Bins(18000),Title("Fitted efficiency")) ;
  dataSetEB.plotOn(frame, Binning(binningEB), Efficiency(*cut), MarkerColor(color1), LineColor(color1), MarkerStyle(style1) );
  dataSetEE.plotOn(frame, Binning(binningEE), Efficiency(*cut), MarkerColor(color2), LineColor(color2), MarkerStyle(style2) );

  // PARAMETRES ROOFIT CRYSTAL BALL //
  RooRealVar norm("norm","N",0.95,0.6,1);
  RooRealVar alpha("alpha","#alpha",0.2,0.01,8);
  RooRealVar n("n","n",2,1.1,35);
  RooRealVar mean("mean","mean",10,5,30);
  mean.setVal(thres);
  RooRealVar sigma("sigma","#sigma",0.23,0.01,5);
  RooRealVar pedestal("pedestal","pedestal",0.01,0,0.4);

  FuncCB cb_EB("cb_EB","Fit function EB (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  FuncCB cb_EE("cb_EE","Fit function EE (cb)",xaxis,mean,sigma,alpha,n,norm) ;
  
  RooEfficiency eff_EB("eff_EB","efficiency EB", cb_EB, *cut, "accept");
  RooEfficiency eff_EE("eff_EE","efficiency EE", cb_EE, *cut, "accept");  

  // FIT //
  double fit_cuts_min = thres-1.5 ;
  double fit_cuts_max = 150;
  xaxis.setRange("interesting",fit_cuts_min,fit_cuts_max);

  fichier << "Fit characteristics :" << endl
	  << "Threshold : "          << thres << endl 
	  << "Fit Range : ["         << fit_cuts_min << "," << fit_cuts_max << "]" << endl 
	  << endl << endl;

  RooFitResult* roofitres_EB = new RooFitResult("roofitres_EB","roofitres_EB");
  RooFitResult* roofitres_EE = new RooFitResult("roofitres_EE","roofitres_EE");

  // Fit #1 //
  roofitres_EB = eff_EB.fitTo(dataSetEB,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EB.plotOn(frame,LineColor(color1),LineWidth(2));

  fichier << "<----------------- EB ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;

  // Fit #2 //
  roofitres_EE = eff_EE.fitTo(dataSetEE,ConditionalObservables(xaxis),Range("interesting"),Minos(kTRUE),Warnings(kFALSE),NumCPU(nCPU),Save(kTRUE),SumW2Error(kTRUE));
  cb_EE.plotOn(frame,LineColor(color2),LineWidth(2));

  fichier << "<----------------- EE ----------------->" << endl
	  << "double res_mean="  << mean.getVal()   << "; "
	  << "double res_sigma=" << sigma.getVal()  << "; "
          << "double res_alpha=" << alpha.getVal()  << "; "
          << "double res_n="     << n.getVal()      << "; "
          << "double res_norm="  << norm.getVal()   << "; "
	  << endl
	  << "double err_mean="  << mean.getError()  << "; "
	  << "double err_sigma=" << sigma.getError() << "; "
          << "double err_alpha=" << alpha.getError() << "; "
          << "double err_n="     << n.getError()     << "; "
          << "double err_norm="  << norm.getErrorLo()<< "; "
	  << endl;


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

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

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

  TH1F *SCeta_EB = new TH1F("SCeta_EB","SCeta_EB",50,-2.5,2.5);
  TH1F *SCeta_EE = new TH1F("SCeta_EE","SCeta_EE",50,-2.5,2.5);

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

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

  TLegend *leg = new TLegend(0.40, 0.14, 0.63, 0.34, NULL, "brNDC");
  leg->SetLineColor(1);
  leg->SetTextColor(1);
  leg->SetTextFont(42);
  leg->SetTextSize(0.0244755);
  leg->SetShadowColor(kWhite);
  leg->SetFillColor(kWhite);  
  leg->AddEntry("NULL","e #tau electrons efficiency","h");
  //    entry->SetLineColor(1);
  //    entry->SetLineStyle(1);
  //    entry->SetLineWidth(1);
  //    entry->SetMarkerColor(1);
  //    entry->SetMarkerStyle(21);
  //    entry->SetMarkerSize(1);
  //    entry->SetTextFont(62);
  leg->AddEntry(SCeta_EB,"Barrel","p");
  leg->AddEntry(SCeta_EE,"Endcaps","p");
  leg->Draw(); 
  
  ostringstream ossi("");
  ossi << thres;
  TString tossi = ossi.str();

  leg = new TLegend(0.40, 0.30, 0.50, 0.50, NULL, "brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.0297203);
  leg->SetLineColor(0);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->AddEntry("NULL","CMS Preliminary 2012 pp  #sqrt{s}=8 TeV","h");
  leg->AddEntry("NULL","#int L dt = "+lumi+"^{-1}","h");
  leg->AddEntry("NULL","Threshold : "+tossi+" GeV","h");
  leg->Draw();
  
  ca->Print(name_image+".C","C");
  ca->Print(name_image+".cxx","cxx");
  ca->Print(name_image+".png","png");
  ca->Print(name_image+".gif","gif");
  ca->Print(name_image+".pdf","pdf");
  ca->Print(name_image+".ps","ps");

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

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

  w->import(dataSetEB);
  w->import(dataSetEE);
  
  w->import(*roofitres_EB,"roofitres_EB");
  w->import(*roofitres_EE,"roofitres_EE");

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

  // DELETE POINTERS
  // int a=0;
//   cin >> a;
//   delete treeTnP; delete cut; delete frame; delete roofitres_EB; delete roofitres_EE; delete ca; delete SCeta_EB; delete SCeta_EE; delete leg; delete w;

}