void makePlots_hlt_eventbyevent_comparison( std::string inputFile_="input.root", std::string target_label_="Target", std::string outputSuffix_="_out" ) {

  TFile *file = new TFile(inputFile_.c_str());

  std::string dirprefix = "Images" + outputSuffix_;
  struct stat st;
  if( stat(dirprefix.c_str(),&st) != 0 )  mkdir(dirprefix.c_str(),0777);

  std::string label_ref = "Reference";
  std::string label_tgt = target_label_;

  TH1D* h_ref = (TH1D*)file->Get("eventbyevent/HLT_Ref");
  TH1D* h_tgt = (TH1D*)file->Get("eventbyevent/HLT_Tgt");
  TH1D* h_tgt_sep = (TH1D*)file->Get("eventbyevent/HLT_Tgt_sep");

  std::map<std::string, int> hlt_counts_per_path_ref_;
  std::map<std::string, int> hlt_counts_per_path_tgt_;
  std::map<double, std::string> hlt_counts_per_path_diff_;

  std::vector<std::string> hlt_common_paths;

  TAxis * axis = h_ref->GetXaxis();

  // loop over target paths
  for( int iPath=0; iPath<h_tgt_sep->GetNbinsX(); iPath++ ){
    std::string name(h_tgt_sep->GetXaxis()->GetBinLabel(iPath+1));
    
    int bin = axis->FindBin(name.c_str());

    if( bin<1 ) continue;

    double cnt_ref = h_ref->GetBinContent(bin);
    double cnt_tgt = h_tgt->GetBinContent(bin);

    int diff = int( cnt_ref - cnt_tgt );
    double rel_diff = double(diff);

    if( cnt_ref>0 )      rel_diff = fabs(cnt_tgt - cnt_ref)/cnt_ref;
    else if( cnt_tgt>0 ) rel_diff = fabs(cnt_tgt - cnt_ref)/cnt_tgt;
    else                 rel_diff = 0.;

    // printf("%s\t %d\t %d\t %d\t %.3f \n",
    // 	   name.c_str(), int(cnt_ref), int(cnt_tgt), diff, rel_diff ); 

    hlt_counts_per_path_ref_[name] = int(cnt_ref);
    hlt_counts_per_path_tgt_[name] = int(cnt_tgt);

    hlt_counts_per_path_diff_[rel_diff] = name;

    if( rel_diff>0.15 ) hlt_common_paths.push_back(name);
  }


  std::map<double, std::string>::reverse_iterator rit;
  for( rit=hlt_counts_per_path_diff_.rbegin(); rit!=hlt_counts_per_path_diff_.rend(); ++rit )
    std::cout << "path: " << rit->second << "\t" << rit->first << "\t" << hlt_counts_per_path_ref_[rit->second] << "\t" << hlt_counts_per_path_tgt_[rit->second] << std::endl;


  int numPaths = int( hlt_counts_per_path_ref_.size() );
  TH1D* h_hlt_ref = new TH1D("h_hlt_ref",";HLT path", numPaths, 0, numPaths );
  TH1D* h_hlt_tgt = new TH1D("h_hlt_tgt",";HLT path", numPaths, 0, numPaths );
  TH1D* h_hlt_diff = new TH1D("h_hlt_diff",";HLT path", numPaths, 0, numPaths );

  int iHLT=0;
  for( std::map<std::string, int>::iterator it=hlt_counts_per_path_ref_.begin(); it!=hlt_counts_per_path_ref_.end(); ++it ){
    iHLT++;
    std::string name = it->first;

    double cnt_ref = double(hlt_counts_per_path_ref_[name]);
    double cnt_tgt = double(hlt_counts_per_path_tgt_[name]);

    double rel_diff = 1.0;
    if( cnt_ref>0 )      rel_diff = (cnt_tgt - cnt_ref)/cnt_ref;
    else if( cnt_tgt>0 ) rel_diff = (cnt_tgt - cnt_ref)/cnt_tgt;
    else                 rel_diff = 0.;

    h_hlt_ref->SetBinContent(iHLT,cnt_ref);
    h_hlt_tgt->SetBinContent(iHLT,cnt_tgt);
    h_hlt_diff->SetBinContent(iHLT,rel_diff);

    h_hlt_ref->GetXaxis()->SetBinLabel(iHLT,name.c_str());
    h_hlt_diff->GetXaxis()->SetBinLabel(iHLT,name.c_str());
  }


  h_hlt_ref->SetStats(0);

  h_hlt_ref->SetLineColor(kBlue);
  h_hlt_tgt->SetLineColor(kRed);

  if( true ){
    // TLegend *legend = new TLegend(0.255,0.78,0.92,0.89);
    TLegend *legend = new TLegend(0.255,0.92,0.92,0.99);

    legend->SetFillColor(kWhite);
    legend->SetLineColor(kWhite);
    legend->SetShadowColor(kWhite);
    legend->SetTextFont(42);
    legend->SetTextSize(0.035);

    legend->SetNColumns(2);

    legend->AddEntry(h_hlt_ref,label_ref.c_str(),"l");
    legend->AddEntry(h_hlt_tgt,label_tgt.c_str(),"l");


    //// Original
    // double ratioMin = -1.2;
    // double ratioMax = 1.2;
    double ratioMin = -0.6;
    double ratioMax = 0.6;

    //Hack to get it plotted with ratio plot
    TCanvas* myC = new TCanvas("myC", "myC", 1200,700);

    gStyle->SetPadBorderMode(0);
    gStyle->SetFrameBorderMode(0);
    Float_t small = 1.e-5;
    myC->Divide(1,2,small,small);
    const float padding=1e-5; const float ydivide=0.3;
    myC->GetPad(1)->SetPad( padding, ydivide + padding , 1-padding, 1-padding);
    myC->GetPad(2)->SetPad( padding, padding, 1-padding, ydivide-padding);
    myC->GetPad(1)->SetLeftMargin(.11);
    myC->GetPad(2)->SetLeftMargin(.11);
    myC->GetPad(1)->SetRightMargin(.05);
    myC->GetPad(2)->SetRightMargin(.05);
    myC->GetPad(1)->SetBottomMargin(.3);
    myC->GetPad(2)->SetBottomMargin(.3);
    myC->GetPad(1)->Modified();
    myC->GetPad(2)->Modified();
    myC->cd(1);
    gPad->SetBottomMargin(small);
    gPad->Modified();



    TH1D* myRatio = (TH1D*)h_hlt_diff->Clone("myRatio");

    myRatio->SetStats(0);
    myRatio->Sumw2();
    myRatio->SetLineColor(kBlack);
    myRatio->SetMarkerColor(kBlack);

    myRatio->SetMinimum(ratioMin);
    myRatio->SetMaximum(ratioMax);
    //myRatio->GetYaxis()->SetNdivisions(50000+404);
    myRatio->GetYaxis()->SetNdivisions(20000+505);
    myRatio->GetYaxis()->SetLabelSize(0.1); //make y label bigger
    myRatio->GetXaxis()->SetLabelSize(0.1); //make y label bigger
    myRatio->GetXaxis()->SetTitleOffset(1.1);
    myRatio->GetXaxis()->SetTitle(h_hlt_diff->GetXaxis()->GetTitle()); //make y label bigger
    myRatio->GetXaxis()->SetLabelSize(0.12);
    myRatio->GetXaxis()->SetLabelOffset(0.04);
    myRatio->GetXaxis()->SetTitleSize(0.12);
    // myRatio->GetYaxis()->SetTitle("Data/MC");
    myRatio->GetYaxis()->SetTitle("New - Old / Old");
    myRatio->GetYaxis()->SetTitleSize(0.1);
    myRatio->GetYaxis()->SetTitleOffset(.45);
    myC->cd(2);
    gPad->SetTopMargin(small);
    gPad->SetTickx();
    gPad->Modified();

    myC->cd(1);

    h_hlt_ref->GetYaxis()->SetTitle("Number of Events");
    h_hlt_ref->GetYaxis()->SetTitleSize(0.05);
    h_hlt_ref->GetYaxis()->SetTitleOffset(.95);

    h_hlt_ref->Draw();
    h_hlt_tgt->Draw("same");

    legend->Draw();

    double xmin = h_hlt_ref->GetBinLowEdge(1);
    double xmax = h_hlt_ref->GetBinLowEdge(h_hlt_ref->GetNbinsX()) + h_hlt_ref->GetBinWidth(h_hlt_ref->GetNbinsX());

    myC->cd(2);

    myRatio->SetLineWidth(2);

    myRatio->Draw("hist");

    TLine* myLine;
    myLine = new TLine(xmin, 0, xmax, 0);
    myLine->Draw();

    std::string outputFile = dirprefix + "/hlt_path_comparison" + outputSuffix_ + ".pdf";
    myC->Print(outputFile.c_str());

    delete legend;
    delete myC;
    delete myLine;
  }


  if( true ){
    int numCommonPaths = int(hlt_common_paths.size());

    for( int iPath=0; iPath<numCommonPaths; iPath++ ){
      std::cout << " ====================== " << std::endl;
      std::string name = hlt_common_paths[iPath];
      std::string pathName_ref = "eventbyevent/h_path_ref_" + name;
      std::string pathName_tgt = "eventbyevent/h_path_tgt_" + name;

      std::string diffname = "h_path_diff_" + name;

      //std::cout << " path is " << pathName_ref << std::endl;

      if( name=="HLT_LogMonitor" ) continue;

      TH1D* h_hlt_filt_ref = (TH1D*)file->Get(pathName_ref.c_str());
      TH1D* h_hlt_filt_tgt = (TH1D*)file->Get(pathName_tgt.c_str());
      TH1D* h_hlt_filt_diff = (TH1D*)h_hlt_filt_ref->Clone(diffname.c_str());

      bool printOut = true;
      for( int iBin=0; iBin<h_hlt_filt_tgt->GetNbinsX(); iBin++ ){
	double cnt_ref = h_hlt_filt_ref->GetBinContent(iBin+1);
	double cnt_tgt = h_hlt_filt_tgt->GetBinContent(iBin+1);

	double rel_diff = 1.0;
	if( cnt_ref>0 )      rel_diff = (cnt_tgt - cnt_ref)/cnt_ref;
	else if( cnt_tgt>0 ) rel_diff = (cnt_tgt - cnt_ref)/cnt_tgt;
	else                 rel_diff = 0.;

	h_hlt_filt_diff->SetBinContent(iBin+1,rel_diff);

	//if( fabs(rel_diff)>0.0002 ) printOut = true;
      }

      if( printOut ){
	double cnt_ref = double(hlt_counts_per_path_ref_[name]);
	double cnt_tgt = double(hlt_counts_per_path_tgt_[name]);

	double rel_diff = 1.0;
	if( cnt_ref>0 )      rel_diff = (cnt_tgt - cnt_ref)/cnt_ref;
	else if( cnt_tgt>0 ) rel_diff = (cnt_tgt - cnt_ref)/cnt_tgt;
	else                 rel_diff = 0.;

	printf("%s: relative difference = %.3f,\t reference = %d,\t target = %d \n",
	       name.c_str(), rel_diff, hlt_counts_per_path_ref_[name], hlt_counts_per_path_tgt_[name]);

	for( int iBin=0; iBin<h_hlt_filt_tgt->GetNbinsX(); iBin++ ){
	  double my_cnt_ref = h_hlt_filt_ref->GetBinContent(iBin+1);
	  double my_cnt_tgt = h_hlt_filt_tgt->GetBinContent(iBin+1);

	  double my_rel_diff = 1.0;
	  if( my_cnt_ref>0 )      my_rel_diff = (my_cnt_tgt - my_cnt_ref)/my_cnt_ref;
	  else if( my_cnt_tgt>0 ) my_rel_diff = (my_cnt_tgt - my_cnt_ref)/my_cnt_tgt;
	  else                   my_rel_diff = 0.;

	  printf("\t %s \t %.3f \t %.0f \t %.0f \n",
		 h_hlt_filt_ref->GetXaxis()->GetBinLabel(iBin+1), my_rel_diff, my_cnt_ref, my_cnt_tgt);
	}
      }

      h_hlt_filt_ref->SetStats(0);

      h_hlt_filt_ref->SetLineColor(kBlue);
      h_hlt_filt_tgt->SetLineColor(kRed);

      //TLegend *legend = new TLegend(0.255,0.78,0.92,0.89);
      TLegend *legend = new TLegend(0.255,0.92,0.92,0.99);

      legend->SetFillColor(kWhite);
      legend->SetLineColor(kWhite);
      legend->SetShadowColor(kWhite);
      legend->SetTextFont(42);
      legend->SetTextSize(0.035);

      legend->SetNColumns(2);

      legend->AddEntry(h_hlt_filt_ref,label_ref.c_str(),"l");
      legend->AddEntry(h_hlt_filt_tgt,label_tgt.c_str(),"l");


      double ratioMin = -1.2;
      double ratioMax = 1.2;

      //Hack to get it plotted with ratio plot
      TCanvas* myC = new TCanvas("myC", "myC", 600,700);

      gStyle->SetPadBorderMode(0);
      gStyle->SetFrameBorderMode(0);
      Float_t small = 1.e-5;
      myC->Divide(1,2,small,small);
      const float padding=1e-5; const float ydivide=0.3;
      myC->GetPad(1)->SetPad( padding, ydivide + padding , 1-padding, 1-padding);
      myC->GetPad(2)->SetPad( padding, padding, 1-padding, ydivide-padding);
      myC->GetPad(1)->SetLeftMargin(.11);
      myC->GetPad(2)->SetLeftMargin(.11);
      myC->GetPad(1)->SetRightMargin(.05);
      myC->GetPad(2)->SetRightMargin(.05);
      myC->GetPad(1)->SetBottomMargin(.3);
      myC->GetPad(2)->SetBottomMargin(.3);
      myC->GetPad(1)->Modified();
      myC->GetPad(2)->Modified();
      myC->cd(1);
      gPad->SetBottomMargin(small);
      gPad->Modified();



      TH1D* myRatio = (TH1D*)h_hlt_filt_diff->Clone();

      myRatio->SetStats(0);
      myRatio->Sumw2();
      myRatio->SetLineColor(kBlack);
      myRatio->SetMarkerColor(kBlack);

      myRatio->SetMinimum(ratioMin);
      myRatio->SetMaximum(ratioMax);
      myRatio->GetYaxis()->SetNdivisions(50000+404);
      myRatio->GetYaxis()->SetLabelSize(0.1); //make y label bigger
      myRatio->GetXaxis()->SetLabelSize(0.1); //make y label bigger
      myRatio->GetXaxis()->SetTitleOffset(1.1);
      myRatio->GetXaxis()->SetTitle(h_hlt_diff->GetXaxis()->GetTitle()); //make y label bigger
      myRatio->GetXaxis()->SetLabelSize(0.12);
      myRatio->GetXaxis()->SetLabelOffset(0.04);
      myRatio->GetXaxis()->SetTitleSize(0.12);
      // myRatio->GetYaxis()->SetTitle("Data/MC");
      myRatio->GetYaxis()->SetTitle("New - Old / Old");
      myRatio->GetYaxis()->SetTitleSize(0.1);
      myRatio->GetYaxis()->SetTitleOffset(.45);
      myC->cd(2);
      gPad->SetTopMargin(small);
      gPad->SetTickx();
      gPad->Modified();

      myC->cd(1);

      h_hlt_filt_ref->GetYaxis()->SetTitle("Number of Events");
      h_hlt_filt_ref->GetYaxis()->SetTitleSize(0.05);
      h_hlt_filt_ref->GetYaxis()->SetTitleOffset(.95);

      h_hlt_filt_ref->Draw();
      h_hlt_filt_tgt->Draw("same");

      legend->Draw();

      double xmin = h_hlt_filt_ref->GetBinLowEdge(1);
      double xmax = h_hlt_filt_ref->GetBinLowEdge(h_hlt_filt_ref->GetNbinsX()) + h_hlt_filt_ref->GetBinWidth(h_hlt_filt_ref->GetNbinsX());

      myC->cd(2);

      myRatio->SetLineWidth(2);

      myRatio->Draw("hist");

      TLine* myLine;
      myLine = new TLine(xmin, 0, xmax, 0);
      myLine->Draw();

      std::string outputFile = dirprefix + "/hlt_path_" + name + outputSuffix_ + ".pdf";
      myC->Print(outputFile.c_str());

      delete legend;
      delete myC;
      delete myLine;
    }
    std::cout << " ====================== " << std::endl;

  }

  // close file
  file->Close();

}
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);
}
Esempio n. 3
0
void fitWe(const TString  outputDir="test",   // output directory
           const Double_t lumi=18.7,        // integrated luminosity (/fb)
	   const Int_t    Ecm=8,         // center-of-mass energy
	   const Int_t    doPU=1         // option for PU-reweighting
) {
  gBenchmark->Start("fitWe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS  = 50;
  const Double_t METMAX = 100;

  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.5;

  // file format for output plots
  const TString format("png"); 
    
  // file name with recoil correction
  TString recoilfname("../RecoilSyst/ZeeData/fits.root");
  
  // file name(s) with PU weights
  TString pufname("");
  if(doPU>0) {
    if(doPU==1) { pufname = "Utils/PileupReweighting.Summer11DYmm_To_Run2011A.root"; }
    else        { cout << "Invalid option for PU re-weighting! Aborting..." << endl; assert(0); }
  }
  
  //
  // input ntuple file names
  //
  enum { eData, eWenu, eEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("../Selection/Wenu/ntuples/data_m23_select.root");   typev.push_back(eData);
  fnamev.push_back("../Selection/Wenu/ntuples/we_select.root");         typev.push_back(eWenu);
  fnamev.push_back("../Selection/Wenu/ntuples/ewk_select.root");        typev.push_back(eEWK);
  fnamev.push_back("../Selection/Wenu/ntuples/top_select.root");        typev.push_back(eEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  // Get pile-up weights
  TFile *pufile    = 0;
  TH1D  *puWeights = 0;
  if(doPU>0) {
    pufile = new TFile(pufname);
    assert(pufile);
    puWeights = (TH1D*)pufile->Get("puWeights");
    assert(puWeights);
  }
  
  // Access recoil corrections
  //RecoilCorrector recoilCorr(recoilfname);
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet  = new TH1D("hDataMet", "",NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm = new TH1D("hDataMetm","",NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp = new TH1D("hDataMetp","",NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWenuMet  = new TH1D("hWenuMet", "",NBINS,0,METMAX); hWenuMet->Sumw2();
  TH1D *hWenuMetp = new TH1D("hWenuMetp","",NBINS,0,METMAX); hWenuMetp->Sumw2();
  TH1D *hWenuMetm = new TH1D("hWenuMetm","",NBINS,0,METMAX); hWenuMetm->Sumw2();
  TH1D *hEWKMet   = new TH1D("hEWKMet",  "",NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp  = new TH1D("hEWKMetp", "",NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm  = new TH1D("hEWKMetm", "",NBINS,0,METMAX); hEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genWPt, genWPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  LorentzVector *sc=0;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genWPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genWPhi);   // GEN W boson phi (signal MC)
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);         // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("sc",       &sc);        // electron Supercluster 4-vector
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(mt< 40)  continue;	// LUCA ADD
      TLorentzVector muPosP, muNegP, JpsiP;
      muPosP.SetPtEtaPhiM(lep->Pt(),lep->Eta(),lep->Phi(),lep->M()); // always use the muon
      muNegP.SetPtEtaPhiM(met,0,metPhi,0); // always use the neutrino
      JpsiP = muPosP + muNegP;
      
      // if(JpsiP.Pt() < 15 
      // || JpsiP.Pt() > 25 )  continue;	

      
      if(sc->Pt()        < PT_CUT)  continue;	
      if(fabs(sc->Eta()) > ETA_CUT) continue;
   
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
        if(puWeights)
	  weight *= puWeights->GetBinContent(npu+1);
	
	if(typev[ifile]==eWenu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  //recoilCorr.Correct(corrMet,corrMetPhi,genWPt,genWPhi,lep->Pt(),lep->Phi());
	
          hWenuMet->Fill(corrMet,weight);
	  if(q>0) { hWenuMetp->Fill(corrMet,weight); } 
	  else    { hWenuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWenuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWenuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWenuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  
  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wenuMet ("wenuMET", "wenuMET", RooArgSet(pfmet),hWenuMet);  RooHistPdf pdfWe ("we", "we", pfmet,wenuMet, 1);
  RooDataHist wenuMetp("wenuMETp","wenuMETp",RooArgSet(pfmet),hWenuMetp); RooHistPdf pdfWep("wep","wep",pfmet,wenuMetp,1);
  RooDataHist wenuMetm("wenuMETm","wenuMETm",RooArgSet(pfmet),hWenuMetm); RooHistPdf pdfWem("wem","wem",pfmet,wenuMetm,1); 
  
  // EWK+top PDFs
  RooDataHist ewkMet ("ewkMET", "ewkMET", RooArgSet(pfmet),hEWKMet);  RooHistPdf pdfEWK ("ewk", "ewk", pfmet,ewkMet, 1);
  RooDataHist ewkMetp("ewkMETp","ewkMETp",RooArgSet(pfmet),hEWKMetp); RooHistPdf pdfEWKp("ewkp","ewkp",pfmet,ewkMetp,1); 
  RooDataHist ewkMetm("ewkMETm","ewkMETm",RooArgSet(pfmet),hEWKMetm); RooHistPdf pdfEWKm("ewkm","ewkm",pfmet,ewkMetm,1); 
  
  // QCD Pdfs
  CPepeModel1 qcd("qcd",pfmet);
  CPepeModel1 qcdp("qcdp",pfmet);
  CPepeModel1 qcdm("qcdm",pfmet);
  
  // Signal + Background PDFs
  RooAddPdf pdfMet ("pdfMet", "pdfMet", RooArgList(pdfWe,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWep,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWem,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  //
  // Perform fits
  //
  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet),hDataMet);
  RooFitResult *fitRes = pdfMet.fitTo(dataMet,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp","dataMetp",RooArgSet(pfmet),hDataMetp);
  RooFitResult *fitResp = pdfMetp.fitTo(dataMetp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm","dataMetm",RooArgSet(pfmet),hDataMetm);
  RooFitResult *fitResm = pdfMetm.fitTo(dataMetm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.18);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.18);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.400,"Y");
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = %i TeV",lumi*1000.,Ecm);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = %i TeV",lumi,Ecm);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *weframe = pfmet.frame(Bins(NBINS));    
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(weframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(weframe,LineColor(linecolorW));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(weframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(weframe,Components(RooArgSet(pdfWe)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(weframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",weframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrowe#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
//  plotMet.Draw(c,kFALSE,format,1);
  plotMet.Draw(c,kTRUE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wepframe = pfmet.frame(Bins(NBINS));    
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wepframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wepframe,LineColor(linecolorW));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wepframe,Components(RooArgSet(pdfWep)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wepframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wepframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrowe^{+}#nu","F");
  plotMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetp.SetYRange(0.1,1.1*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kFALSE,format,1);

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wemframe = pfmet.frame(Bins(NBINS)); 
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wemframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wemframe,LineColor(linecolorW));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wemframe,Components(RooArgSet(pdfWem)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wemframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wemframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrowe^{-}#bar{#nu}","F");
  plotMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMetm.SetYRange(0.1,1.1*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kFALSE,format,1);

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWe.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWep.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl;  
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWem.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWe");
}
Esempio n. 4
0
void plotBalance(int cbin,
		 TString infname,
		 TString pythia,
		 TString mix,
		 bool drawXLabel,
		 bool drawLeg)
{

  bool showPbPb = 0;
  if(iPlot == 0 || iPlot == 3) showPbPb = 1;

  if(iPlot != 3) dijet = dijet&&deltaPhi;

  TCut centHF("");
  TCut centNtrk("");

  if(centMode == 0){
    cout<<"Obsolete centrality usage."<<endl;
    return;
    if(cbin==0) centHF = "bin>=20 && bin<26";
    if(cbin==1) centHF = "bin>=26 && bin<27";
    if(cbin==2) centHF = "bin>=27 && bin<28";
    if(cbin==3) centHF = "bin>=28 && bin<29";
    if(cbin==4) centHF = "bin>=29 && bin<31";
    if(cbin==5) centHF = "bin>=31";

    if(cbin==0) centNtrk = "ntrk >= 180";
    if(cbin==1) centNtrk = "150 <= ntrk && ntrk < 180";
    if(cbin==2) centNtrk = "110 <= ntrk && ntrk < 150";
    if(cbin==3) centNtrk = "90 <= ntrk && ntrk < 150";
    if(cbin==4) centNtrk = "60 <= ntrk && ntrk < 90";
    if(cbin==5) centNtrk = "ntrk < 60";
  }

  if(centMode == 1){
    centHF = hfPlusBins[cbin];
    centNtrk = centHF;
  }

  cout<<"plotting ntrk bin : "<<cbin<<endl;

  // open the data file

  if(iPlot > 100) entryMode = 1;

  string treeName = "ntdijet";
  string wName = "ntw";
  if(entryMode == 1){
    treeName = "ntjet";
    wName = "ntjetw";
  }

  if(entryMode == 2){
    treeName = "nttrk";
    wName = "nttrkw";
  }

  TFile *inf = new TFile(infname.Data());
  TTree *nt =(TTree*)inf->FindObjectAny(treeName.data());
  TTree *ntevt =(TTree*)inf->FindObjectAny("ntevt");
  if(entryMode < 1) nt->AddFriend(ntevt);

  // open the pythia (MC) file
  TFile *infReference = new TFile(pythia.Data());
  TTree *ntReference;
  TTree *ntevtReference;

  ntReference = (TTree*) infReference->FindObjectAny(treeName.data());
  ntevtReference = (TTree*) infReference->FindObjectAny("ntevt");
  if(entryMode < 1) ntReference->AddFriend(ntevtReference);
  
  // open the datamix file
  TFile *infMix = new TFile(mix.Data());
  TTree *ntMix =(TTree*)infMix->FindObjectAny(treeName.data());
  TTree *ntevtMix =(TTree*)infMix->FindObjectAny("ntevt");
  //  TFile *infW = new TFile("weights_hydjet.root");
  //  TTree *ntw =(TTree*)infW->FindObjectAny("ntw");

  TTree *ntw =(TTree*)infMix->FindObjectAny(wName.data());
  ntMix->AddFriend(ntw);
  if(entryMode < 1) ntMix->AddFriend(ntevtMix);

  int Nbin = 10;
  double max = 1.;
  double min = 0;

  if(iPlot == 1 || iPlot == 21 || iPlot == 22){
    Nbin = 20;
    max = 2;
    min = -2;
  };

  if(iPlot == 3){
    Nbin = 30;
    max = pi;
  };

  if(iPlot == 8){
    Nbin = 50;
    max = 25;
    min = -25;
  };

  if(iPlot == 9){
    Nbin = 50;
    max = 250;
  };

  if(iPlot == 11 || iPlot == 12){
    Nbin = 50;
    max = 25;
  };

  if(iPlot == 13 || iPlot == 14){
    Nbin = 75;
    max = 150;
  }

  if(iPlot == 101){
    Nbin = 20;
    max = 2;
    min = -2;
  }

  // projection histogram
  TH1D *h = new TH1D(Form("h",cbin),"",Nbin,min,max);
  TH1D *hReference = new TH1D(Form("hReference",cbin),"",Nbin,min,max);
  TH1D *hDataMix = new TH1D(Form("hDataMix",cbin),"",Nbin,min,max);

  TH1D *hB = new TH1D(Form("hB",cbin),"",Nbin,min,max);
  TH1D *hReferenceB = new TH1D(Form("hReferenceB",cbin),"",Nbin,min,max);
  TH1D *hDataMixB = new TH1D(Form("hDataMixB",cbin),"",Nbin,min,max);

  TH1D *hFull = new TH1D("hFull","",Nbin,min,max);
  TH1D *hReferenceFull = new TH1D("hReferenceFull","",Nbin,min,max);
  TH1D *hDataMixFull = new TH1D("hDataMixFull","",Nbin,min,max);

  TH1D* hNorm = new TH1D("hNorm","",1000,0,1000);
  TH1D* hNormReference = new TH1D("hNormReference","",1000,0,1000);
  TH1D* hNormDataMix = new TH1D("hNormDataMix","",1000,0,1000);

  hB->SetLineStyle(2);
  hReferenceB->SetLineStyle(2);
  hDataMixB->SetLineStyle(2);

  //  ntReference->SetAlias("pt1","et1");
  //  ntReference->SetAlias("pt2","et2");

  nt->SetAlias("pt1","jtpt1");
  nt->SetAlias("pt2","jtpt2");
  nt->SetAlias("eta1","jteta1");
  nt->SetAlias("eta2","jteta2");
  nt->SetAlias("phi1","jtphi1");
  nt->SetAlias("phi2","jtphi2");
  ntMix->SetAlias("pt1","jtpt1");
  ntMix->SetAlias("pt2","jtpt2");
  ntMix->SetAlias("eta1","jteta1");
  ntMix->SetAlias("eta2","jteta2");
  ntMix->SetAlias("phi1","jtphi1");
  ntMix->SetAlias("phi2","jtphi2");
  ntReference->SetAlias("pt1","jtpt1");
  ntReference->SetAlias("pt2","jtpt2");
  ntReference->SetAlias("eta1","jteta1");
  ntReference->SetAlias("eta2","jteta2");
  ntReference->SetAlias("phi1","jtphi1");
  ntReference->SetAlias("phi2","jtphi2");

  nt->SetAlias("cent","hfp");
  ntMix->SetAlias("cent","hfp");
  ntReference->SetAlias("cent","hfp");

  nt->SetAlias("dphi","acos(cos(phi1-phi2))");
  ntMix->SetAlias("dphi","acos(cos(phi1-phi2))");
  ntReference->SetAlias("dphi","acos(cos(phi1-phi2))");

  if(iPlot == 0){
    nt->SetAlias("var","pt2/pt1");
    ntReference->SetAlias("var","pt2/pt1");
    ntMix->SetAlias("var","pt2/pt1");
  }

  if(iPlot == 1){
    nt->SetAlias("var","(eta1+eta2)/2");
    ntReference->SetAlias("var","(eta1+eta2)/2");
    ntMix->SetAlias("var","(eta1+eta2)/2");
  }

  if(iPlot == 3){
    nt->SetAlias("var","acos(cos(phi1-phi2))");
    ntReference->SetAlias("var","acos(cos(phi1-phi2))");
    ntMix->SetAlias("var","acos(cos(phi1-phi2))");
  }

  if(iPlot == 8){
    nt->SetAlias("var","pu1-pu2");
    ntReference->SetAlias("var","pu1-pu2");
    ntMix->SetAlias("var","pu1-pu2");
  }

  if(iPlot == 11){
    nt->SetAlias("var","pu1");
    ntReference->SetAlias("var","pu1");
    ntMix->SetAlias("var","pu1");
  }

  if(iPlot == 12){
    nt->SetAlias("var","pu2");
    ntReference->SetAlias("var","pu2");
    ntMix->SetAlias("var","pu2");
  }

  if(iPlot == 13){
    nt->SetAlias("var","trkMax1");
    ntReference->SetAlias("var","trkMax1");
    ntMix->SetAlias("var","trkMax1");
  }

  if(iPlot == 14){
    nt->SetAlias("var","trkMax2");
    ntReference->SetAlias("var","trkMax2");
    ntMix->SetAlias("var","trkMax2");
  }

  if(iPlot == 9){
    nt->SetAlias("var","ntrk");
    ntReference->SetAlias("var","ntrk");
    ntMix->SetAlias("var","ntrk");
  }

  if(iPlot == 21){
    nt->SetAlias("var","eta1");
    ntReference->SetAlias("var","eta1");
    ntMix->SetAlias("var","eta1");
  }

  if(iPlot == 22){
    nt->SetAlias("var","eta2");
    ntReference->SetAlias("var","eta2");
    ntMix->SetAlias("var","eta2");
  }



  if(iPlot == 101){
    nt->SetAlias("var","eta");
    ntReference->SetAlias("var","eta");
    ntMix->SetAlias("var","eta");
  }

  if(iPlot == 51){
    nt->SetAlias("var","matchPt1/pt1");
    ntReference->SetAlias("var","matchPt1/pt1");
    ntMix->SetAlias("var","matchPt1/pt1");
  }

  if(iPlot == 52){
    nt->SetAlias("var","matchPt2/pt2");
    ntReference->SetAlias("var","matchPt2/pt2");
    ntMix->SetAlias("var","matchPt2/pt2");
  }


  nt->Draw("var>>hFull",dijet&&noise&&jetID&&centHF&&vtx); 
  nt->Draw("var>>hB",side&&noise&&jetID&&centHF&&vtx);
  nt->Draw("pt1>>hNorm",lead&&noise&&jetID&&centHF&&vtx);
   
  ntMix->Draw("var>>hDataMixFull",weight*(dijet&&jetID&&centHF&&vtx));
  ntMix->Draw("var>>hDataMixB",weight*(side&&jetID&&centHF&&vtx));
  ntMix->Draw("pt1>>hNormDataMix",weight*(lead&&jetID&&centHF&&vtx));
  
  ntReference->Draw("var>>hReferenceFull",dijet&&noise&&jetID&&centHF&&vtx);
  ntReference->Draw("var>>hReferenceB",side&&noise&&jetID&&centHF&&vtx);
  ntReference->Draw("pt1>>hNormReference",lead&&noise&&jetID&&centHF&&vtx);

  hDataMix->Add(hDataMixFull);
  h->Add(hFull);
  hReference->Add(hReferenceFull);

  if(subtract){
    hDataMix->Add(hDataMixB,-1);
    h->Add(hB,-1);
    hReference->Add(hReferenceB,-1);
  }

  hB->SetFillStyle(3005);
  hB->SetFillColor(15);

  // calculate the statistical error and normalize
  h->SetLineColor(dataColor);
  h->SetMarkerColor(dataColor);
  h->Sumw2();
  if(normLead){
    h->Scale(1./hNorm->Integral());
    hB->Scale(1./hNorm->Integral());
  }else{
    hB->Scale(1./h->Integral());
    h->Scale(1./h->Integral());
  }
  h->SetMarkerStyle(20);

  if(hReference->Integral() > 0){
    hReference->Scale(1./hNormReference->Integral());
  }

  hReference->SetLineColor(kBlue);
  hReference->SetFillColor(kAzure-8);
  hReference->SetFillStyle(3005);

  if(normLead){
    hDataMixB->Scale(1./hNormDataMix->Integral());
    hDataMix->Scale(1./hNormDataMix->Integral());
  }else{
    hDataMixB->Scale(1./hDataMix->Integral());
    hDataMix->Scale(1./hDataMix->Integral());
  }
  hDataMix->SetLineColor(mixColor);
  hDataMix->SetFillColor(mixColor);
  hDataMix->SetFillStyle(3004);
  
  hDataMix->SetMarkerSize(0);
  hDataMix->SetStats(0);

  hDataMix->GetXaxis()->SetLabelSize(22);
  hDataMix->GetXaxis()->SetLabelFont(43);
  hDataMix->GetXaxis()->SetTitleSize(28);
  hDataMix->GetXaxis()->SetTitleFont(43);
  hDataMix->GetXaxis()->SetTitleOffset(2.2);
  hDataMix->GetXaxis()->CenterTitle();
  
  
  hDataMix->GetYaxis()->SetLabelSize(22);
  hDataMix->GetYaxis()->SetLabelFont(43);
  hDataMix->GetYaxis()->SetTitleSize(28);
  hDataMix->GetYaxis()->SetTitleFont(43);
  hDataMix->GetYaxis()->SetTitleOffset(2.2);
  hDataMix->GetYaxis()->CenterTitle();
  
  if(drawXLabel) hDataMix->SetXTitle("A_{J} = (p_{T,1}-p_{T,2})/(p_{T,1}+p_{T,2})");  
  hDataMix->SetYTitle("Event Fraction");

  if(iPlot==1) hDataMix->SetXTitle("#eta_{dijet} = (#eta_{1}+#eta_{2})/2");
  if(iPlot==21) hDataMix->SetXTitle("#eta_{1}");
  if(iPlot==22) hDataMix->SetXTitle("#eta_{2}");

  if(iPlot==8) hDataMix->SetXTitle("p_{T,1}^{background}-p_{T,2}^{background}");
  if(iPlot==9) hDataMix->SetXTitle("N_{trk}^{offline}");

  if(iPlot==11) hDataMix->SetXTitle("p_{T,1}^{background}");
  if(iPlot==12) hDataMix->SetXTitle("p_{T,2}^{background}");

  if(iPlot==13) hDataMix->SetXTitle("p_{T} leading track in leading jet");
  if(iPlot==14) hDataMix->SetXTitle("p_{T} leading track in subleading jet");


  if(drawXLabel){
    if(iPlot==0) hDataMix->SetXTitle("p_{T,2}/p_{T,1}");
    if(iPlot==3) hDataMix->SetXTitle("#Delta #phi_{1,2}");
  }

  if(iPlot==0) hDataMix->SetMaximum(0.32);

  if(iPlot == 1 || iPlot==21 || iPlot==22){
    hDataMix->SetMaximum(0.3);
    hDataMix->SetMinimum(0);
  }


  if(iPlot==3){
    hDataMix->SetMaximum(2.52);
    hDataMix->SetMinimum(0.00004);
  }

  if(iPlot==8){
    hDataMix->SetMaximum(10);
    hDataMix->SetMinimum(0.00004);
  }

  if(iPlot==9){
    hDataMix->SetMaximum(0.15);
    hDataMix->SetMinimum(0.);
  }

  if(iPlot==11 || iPlot == 12){
    hDataMix->SetMaximum(10);
    hDataMix->SetMinimum(0.00004);
  }



  //hDataMix->GetXaxis()->SetNdivisions(905,true);
  hDataMix->GetYaxis()->SetNdivisions(505,true);

  hReference->SetMarkerColor(ppColor);
  hReference->SetLineColor(ppColor);
  hReference->SetMarkerStyle(25);

	hDataMix->Draw();//"hist");
	hDataMix->Draw("hist same");
	if(showPbPb) hReference->Draw("same");

	cout<<"PbPb ENTRIES : "<<endl;
	cout<<hReference->GetEntries()<<endl;

        cout<<"PbPb integral : "<<endl;
        cout<<hReference->Integral()<<endl;

	cout<<"pPb integral : "<<endl;
        cout<<h->Integral()<<endl;

	cout<<"Mix integral : "<<endl;
        cout<<hDataMix->Integral()<<endl;

	h->SetLineWidth(1);
	h->Draw("same");
	h->SetLineWidth(2);
	h->Draw("same");

	//	hDataMixB->Draw("same hist");
	//        hB->Draw("same hist");

	 cout<<" mean value of data "<<h->GetMean()<<endl;

  if(drawLeg){
    TLegend *t3=new TLegend(0.01,0.7,0.3,0.95);
    t3->AddEntry(h,"pPb #sqrt{s}=5.02 TeV","p");
    if(showPbPb) t3->AddEntry(hReference,"PbPb #sqrt{s}=2.76 TeV","p");
    t3->AddEntry(hDataMix,"PYTHIA+HIJING","lf");

    t3->SetFillColor(0);
    t3->SetBorderSize(0);
    t3->SetFillStyle(0);
    t3->SetTextFont(63);
    t3->SetTextSize(15);
    t3->Draw();
  }

}
Esempio n. 5
0
void MatchComparison()
{
	//
	// Initialize AliRun manager
	//
	
	//
	// Initialize run loader and load Kinematics
	//
	AliRunLoader *runLoader = AliRunLoader::Open("galice.root");
	if (!runLoader) return;
	runLoader->LoadgAlice();
	gAlice = runLoader->GetAliRun();
	runLoader->LoadKinematics();
	
	//
	// Initialize histograms with their error computation
	//
	TH1D *hgood  = new TH1D("hgood", "Well matched tracks", 40, 0.0,  40.0);
	TH1D *hfake  = new TH1D("hfake", "Fake matched tracks", 40, 0.0,  40.0);
	TH1D *htrue  = new TH1D("htrue", "True matches"       , 40, 0.0,  40.0);
	TH1D *hfound = new TH1D("hfound","Found matches"      , 40, 0.0,  40.0);
	hgood->Sumw2();
	hfake->Sumw2();
	htrue->Sumw2();
	hfound->Sumw2();
	
	//
	// Open file containing true matches,
	// retrieve the Tree and link to a cursor.
	//
	TFile *fileTrue = TFile::Open("true-matches.root");
	match_t trueMatch;
	
	//
	// Open file of found matches,
	// link the modified ESD container.
	//
	TFile *fileFound = TFile::Open("matchESD.root");
	TTree *treeFound = (TTree*)fileFound->Get("esdTree");
	AliESDEvent* esd = new AliESDEvent();
	esd->ReadFromTree(treeFound);
	Long64_t nEvents = treeFound->GetEntries();
	
	//
	// Loop on all events
	//
	Int_t im, it, ic, nTrueMatches, nTracks;
	Int_t label, trkLabel, cluLabel;
	for (Long64_t iev = 0; iev < nEvents; iev++) {
		
		// get true matches tree of given event
		TTree *treeTrue = (TTree*)fileTrue->Get(Form("tm_%d", iev));
		treeTrue->SetBranchAddress("matches", &trueMatch);
		nTrueMatches = treeTrue->GetEntries();
		
		// set TTree pointers to selected event
		runLoader->GetEvent(iev);
		treeFound->GetEntry(iev);
		AliStack *stack = runLoader->Stack();
		nTracks = esd->GetNumberOfTracks();
		
		// read all true pairs
		for (im = 0; im < nTrueMatches; im++) {
			treeTrue->GetEntry(im);
			AliESDtrack *track = esd->GetTrack(trueMatch.indexT);
			if (!track) continue;
			
			label = TMath::Abs(track->GetLabel());
			TParticle *p = stack->Particle(label);
			htrue->Fill(p->Pt());
			cout <<"filling true"<< endl;
		}
		
		// compare found matches
		for (Int_t it = 0; it < nTracks; it++) {
			AliESDtrack *track = esd->GetTrack(it);
			ic = track->GetEMCALcluster();
			if (ic == AliEMCALTracker::kUnmatched) continue;
			ic = TMath::Abs(ic);
			AliESDCaloCluster *cl = esd->GetCaloCluster(ic);
			if (!cl) continue;
			if (!cl->IsEMCAL()) continue ;
			trkLabel = TMath::Abs(track->GetLabel());
			cluLabel = cl->GetLabel();
			if (trkLabel == cluLabel && trkLabel >= 0) {
				TParticle *p = stack->Particle(TMath::Abs(trkLabel));
				hgood->Fill(p->Pt());
				hfound->Fill(p->Pt());
				cout <<"filling GOOD, pt:" << p->Pt()<< endl;
			}
			else  {
				TParticle *p = stack->Particle(TMath::Abs(trkLabel));
				hfake->Fill(p->Pt());
				hfound->Fill(p->Pt());
				cout <<"filling FAKE" << endl;
			}
		}
	}
	
	cout << "True matches : " << htrue->GetEntries() << endl;
	cout << "Found matches: " << hfound->GetEntries() << endl;
	cout << "Good matches : " << hgood->GetEntries() << endl;
	cout << "Fake matches : " << hfake->GetEntries() << endl;
	
	TFile *fout = TFile::Open("match-comparison.root", "RECREATE");
	hgood->Write();
	hfake->Write();
	htrue->Write();
	hfound->Write();
	fout->Close();
}
void limit() {
//This program demonstrates the computation of 95 % C.L. limits.
//It uses a set of randomly created histograms.
//
//Author:  [email protected] on 21.08.02

// Create a new canvas.
  TCanvas *c1 = new TCanvas("c1","Dynamic Filling Example",200,10,700,500);
  c1->SetFillColor(42);
  
// Create some histograms
  TH1D* background = new TH1D("background","The expected background",30,-4,4);
  TH1D* signal     = new TH1D("signal","the expected signal",30,-4,4);
  TH1D* data       = new TH1D("data","some fake data points",30,-4,4);
  background->SetFillColor(48);
  signal->SetFillColor(41);
  data->SetMarkerStyle(21);
  data->SetMarkerColor(kBlue);
  background->Sumw2(); // needed for stat uncertainty
  signal->Sumw2(); // needed for stat uncertainty
  
// Fill histograms randomly
  TRandom2 r;
  Float_t bg,sig,dt;
  for (Int_t i = 0; i < 25000; i++) {
     bg  = r.Gaus(0,1);
     sig = r.Gaus(1,.2);
     background->Fill(bg,0.02);
     signal->Fill(sig,0.001);
  }
  for (Int_t i = 0; i < 500; i++) {
     dt = r.Gaus(0,1);
     data->Fill(dt);
  }
  THStack *hs = new THStack("hs","Signal and background compared to data...");
  hs->Add(background);
  hs->Add(signal);
  hs->Draw("hist");
  data->Draw("PE1,Same");
  c1->Modified();
  c1->Update();
  c1->GetFrame()->SetFillColor(21);
  c1->GetFrame()->SetBorderSize(6);
  c1->GetFrame()->SetBorderMode(-1);
  c1->Modified();
  c1->Update();
  gSystem->ProcessEvents();

// Compute the limits
  cout << "Computing limits... " << endl;
  TLimitDataSource* mydatasource = new TLimitDataSource(signal,background,data);
  TConfidenceLevel *myconfidence = TLimit::ComputeLimit(mydatasource,50000);
  cout << "CLs    : "   << myconfidence->CLs()  << endl;
  cout << "CLsb   : "   << myconfidence->CLsb() << endl;
  cout << "CLb    : "   << myconfidence->CLb()  << endl;
  cout << "< CLs >  : " << myconfidence->GetExpectedCLs_b()  << endl;
  cout << "< CLsb > : " << myconfidence->GetExpectedCLsb_b() << endl;
  cout << "< CLb >  : " << myconfidence->GetExpectedCLb_b()  << endl;

// Add stat uncertainty
  cout << endl << "Computing limits with stat systematics... " << endl;
  TConfidenceLevel *mystatconfidence = TLimit::ComputeLimit(mydatasource,50000,true);
  cout << "CLs    : "   << mystatconfidence->CLs()  << endl;
  cout << "CLsb   : "   << mystatconfidence->CLsb() << endl;
  cout << "CLb    : "   << mystatconfidence->CLb()  << endl;
  cout << "< CLs >  : " << mystatconfidence->GetExpectedCLs_b()  << endl;
  cout << "< CLsb > : " << mystatconfidence->GetExpectedCLsb_b() << endl;
  cout << "< CLb >  : " << mystatconfidence->GetExpectedCLb_b()  << endl;

// Add some systematics
  cout << endl << "Computing limits with systematics... " << endl;
  TVectorD errorb(2);
  TVectorD errors(2);
  TObjArray* names = new TObjArray();
  TObjString name1("bg uncertainty");
  TObjString name2("sig uncertainty");
  names->AddLast(&name1);
  names->AddLast(&name2);
  errorb[0]=0.05; // error source 1: 5%
  errorb[1]=0;    // error source 2: 0%
  errors[0]=0;    // error source 1: 0%
  errors[1]=0.01; // error source 2: 1%
  TLimitDataSource* mynewdatasource  = new TLimitDataSource();
  mynewdatasource->AddChannel(signal,background,data,&errors,&errorb,names);
  TConfidenceLevel *mynewconfidence = TLimit::ComputeLimit(mynewdatasource,50000,true);
  cout << "CLs    : " << mynewconfidence->CLs()  << endl;
  cout << "CLsb   : " << mynewconfidence->CLsb() << endl;
  cout << "CLb    : " << mynewconfidence->CLb()  << endl;
  cout << "< CLs >  : " << mynewconfidence->GetExpectedCLs_b()  << endl;
  cout << "< CLsb > : " << mynewconfidence->GetExpectedCLsb_b() << endl;
  cout << "< CLb >  : " << mynewconfidence->GetExpectedCLb_b()  << endl;

// show canonical -2lnQ plots in a new canvas
// - The histogram of -2lnQ for background hypothesis (full)
// - The histogram of -2lnQ for signal and background hypothesis (dashed)
  TCanvas *c2 = new TCanvas("c2");
  myconfidence->Draw();
  
// clean up (except histograms and canvas)
  delete myconfidence;
  delete mydatasource;
  delete mystatconfidence;
  delete mynewconfidence;
  delete mynewdatasource;
}
Esempio n. 7
0
void MVA_allsrcComp()
{
  //InpFile = new TFile("../srcbatch/scTTMuon/TTsemiMuon.root");
  //InpFile = new TFile("../srcbatch/scTTElectron/TTsemiElectron.root");
  //InpFile = new TFile("../srcbatch/MonoJet_MET/MonoJet.root");
  InpFile = new TFile("../srcbatch/mSUGRA_MET/mSUGRA.root");
  //InpFile = new TFile("../srcbatch/scTT2Hadron/TT2Hadron.root");
  //InpFile = new TFile("../srcbatch/scWToENu/WToENu.root");
  //InpFile = new TFile("../srcbatch/scWToMuNu/WToMuNu.root");
  //InpFile = new TFile("../srcbatch/scDYElEl/DYElEl.root");
  //InpFile = new TFile("../srcbatch/scDYMuMu/DYMuMu.root");
  //InpFile = new TFile("../srcbatch/scZZ4Mu/ZZ4Mu.root");
  //InpFile = new TFile("../srcbatch/scZZ4El/ZZ4El.root");
  //InpFile = new TFile("../srcbatch/scZZMuEl/ZZMuEl.root");
  //InpFile = new TFile("../srcbatch/ZZ2Mu2Nu_MET/ZZ2Mu2Nu.root");
  //InpFile = new TFile("../srcbatch/ZZ2El2Nu_MET/ZZ2El2Nu.root");
  //InpFile = new TFile("../srcbatch/scWW/WW.root");
  //InpFile = new TFile("../srcbatch/scWZ/WZ.root");
  //InpFile = new TFile("../srcbatch/scMonoPhoton/MonoPhoton.root");
  
  //InpFileall = new TFile("../allbatch/TTsemiMuon_MET/TTsemiMuon.root");
  //InpFileall = new TFile("../allbatch/TTsemiElectron_MET/TTsemiElectron.root");
  //InpFileall = new TFile("../allbatch/MonoJet_MET/MonoJet.root");
  InpFileall = new TFile("../allbatch/mSUGRA_MET/mSUGRA.root");
  //InpFileall = new TFile("../allbatch/TT2Hadron_MET/TT2Hadron.root");
  //InpFileall = new TFile("../allbatch/WToENu_MET/WToENu.root");
  //InpFileall = new TFile("../allbatch/WToMuNu_MET/WToMuNu.root");
  //InpFileall = new TFile("../allbatch/DYElEl_MET/DYElEl.root");
  //InpFileall = new TFile("../allbatch/DYMuMu_MET/DYMuMu.root");
  //InpFileall = new TFile("../allbatch/ZZ4Mu_MET/ZZ4Mu.root");
  //InpFileall = new TFile("../allbatch/ZZ4El_MET/ZZ4El.root");
  //InpFileall = new TFile("../allbatch/ZZMuEl_MET/ZZMuEl.root");
  //InpFileall = new TFile("../allbatch/ZZ2Mu2Nu_MET/ZZ2Mu2Nu.root");
  //InpFileall = new TFile("../allbatch/ZZ2El2Nu_MET/ZZ2El2Nu.root");
  //InpFileall = new TFile("../allbatch/WW_MET/WW.root");
  //InpFileall = new TFile("../allbatch/WZ_MET/WZ.root");
  //InpFileall = new TFile("../allbatch/MonoPhoton_MET/MonoPhoton.root");

  char ylabel[100];
  char histName[100];
  char histName_org[100];
  
  TH1D *pfMet;
  TH1D *NoPUmet;
  TH1D *MVAmet;
  TH1D *NoPUmetall;
  TH1D *MVAmetall;
 
    sprintf(histName,"pfMet");
    sprintf(histName_org,"pfMET_0");
    pfMet =(TH1D*)InpFile->Get(histName_org)->Clone(histName);pfMet->Sumw2();
    
    sprintf(histName,"NoPUmet");
    sprintf(histName_org,"NoPuMET_0");
    NoPUmet =(TH1D*)InpFile->Get(histName_org)->Clone(histName);NoPUmet->Sumw2();
    
    sprintf(histName,"NoPUmetall");
    sprintf(histName_org,"NoPuMET_0");
    NoPUmetall =(TH1D*)InpFileall->Get(histName_org)->Clone(histName);NoPUmetall->Sumw2();
    
    sprintf(histName,"MVAmet");
    sprintf(histName_org,"MVaMET_0");
    MVAmet =(TH1D*)InpFile->Get(histName_org)->Clone(histName);MVAmet->Sumw2();

    sprintf(histName,"MVAmetall");
    sprintf(histName_org,"MVaMET_0");
    MVAmetall =(TH1D*)InpFileall->Get(histName_org)->Clone(histName);MVAmetall->Sumw2();

    pfMet->SetLineWidth(2);
    pfMet->SetLineColor(kBlack);
    pfMet->SetMarkerStyle(26);
    pfMet->SetMarkerColor(kBlack);
    NoPUmet->SetLineWidth(2);
    NoPUmet->SetLineColor(kRed);
    NoPUmet->SetMarkerStyle(kFullCircle);
    NoPUmet->SetMarkerColor(kRed);
    NoPUmetall->SetLineWidth(2);
    NoPUmetall->SetLineColor(kRed);
    NoPUmetall->SetMarkerStyle(kCircle);
    NoPUmetall->SetMarkerColor(kRed);
    MVAmet->SetLineWidth(2);
    MVAmet->SetLineColor(kBlue);
    MVAmet->SetMarkerStyle(kFullSquare);
    MVAmet->SetMarkerColor(kBlue);
    MVAmetall->SetLineWidth(2);
    MVAmetall->SetLineColor(kBlue);
    MVAmetall->SetMarkerStyle(25);
    MVAmetall->SetMarkerColor(kBlue);

    sprintf(ylabel,"MET-genMEtTrue",MVAmet->GetBinWidth(1));
    MVAmet->GetYaxis()->SetTitle(ylabel);
    MVAmet->GetYaxis()->SetTitleOffset(1.2);
    MVAmet->GetYaxis()->SetTitleSize(0.04);
    MVAmet->GetYaxis()->SetLabelSize(0.04);
    MVAmet->GetXaxis()->SetTitle("genMEt");
    MVAmet->GetXaxis()->SetTitleOffset(1.0);
    //MVAmet->GetXaxis()->SetTitleSize(0.13);
   
    //MVAmet->GetYaxis()->SetRangeUser(-15,30);//WJet TTsemiPU012
    //MVAmet->GetYaxis()->SetRangeUser(-25,30);// TTsemiPU3
    //MVAmet->GetYaxis()->SetRangeUser(-20,30);//WW
    
    //MVAmet->GetYaxis()->SetRangeUser(-5,20);//WZ   1
    //MVAmet->GetYaxis()->SetRangeUser(-15,25);//WZ  0,2
    //MVAmet->GetYaxis()->SetRangeUser(-20,35);//WZ  3
    
    //MVAmet->GetYaxis()->SetRangeUser(-15,30);//W
    //MVAmet->GetYaxis()->SetRangeUser(-20,30);//W muon3
    
    //MVAmet->GetYaxis()->SetRangeUser(-20,55);//ZZ4El
    
    //MVAmet->GetYaxis()->SetRangeUser(-25,55);//ZZ4Mu012
    //MVAmet->GetYaxis()->SetRangeUser(-25,65);//ZZ4Mu3
    
    //MVAmet->GetYaxis()->SetRangeUser(-70,70);//ZZMuEl 1
    //MVAmet->GetYaxis()->SetRangeUser(-30,40);//ZZMuEl 0 2
    //MVAmet->GetYaxis()->SetRangeUser(-50,50);//ZZMuEl 3
    
    //MVAmet->GetYaxis()->SetRangeUser(-30,30);//ZZ2El2Nu  0 2
    //MVAmet->GetYaxis()->SetRangeUser(-50,70);//ZZ2El2Nu  3
    //MVAmet->GetYaxis()->SetRangeUser(-30,60);//ZZ2El2Nu  1
    
    //MVAmet->GetYaxis()->SetRangeUser(-20,30);//DY 012
    //MVAmet->GetYaxis()->SetRangeUser(-30,60);//DYmuon1
    //MVAmet->GetYaxis()->SetRangeUser(-40,70);//DYele3
    //MVAmet->GetYaxis()->SetRangeUser(-50,85);//DYmuon3
    
    //MVAmet->GetYaxis()->SetRangeUser(-10,35);//TThadron
    //MVAmet->GetYaxis()->SetRangeUser(0,700);//monoJet
    
    MVAmet->GetYaxis()->SetRangeUser(-90,80);//mSUGRA 0
    //MVAmet->GetYaxis()->SetRangeUser(-130,110);//mSUGRA 1
    //MVAmet->GetYaxis()->SetRangeUser(-80,80);//mSUGRA 2
    //MVAmet->GetYaxis()->SetRangeUser(-140,130);//mSUGRA 3
    
    //MVAmet->GetYaxis()->SetRangeUser(-50,1000);//monoPhoton0
    //MVAmet->GetYaxis()->SetRangeUser(-50,1300);//monoPhoton2
    //MVAmet->GetYaxis()->SetRangeUser(-50,750);//monoPhoton13
    
    //MVAmet->GetXaxis()->SetRangeUser(0,75);//X-axis 80

    TCanvas c1("c1","c1",800,700);
    gStyle->SetOptTitle(0);

    MVAmet->Draw("E1");
    pfMet->Draw("E1 same");
    NoPUmet->Draw("E1 same");
    MVAmetall->Draw("E1 same");
    NoPUmetall->Draw("E1 same");
    
    TLegend *rL =new TLegend(0.55,0.68,0.99,0.95);
    rL->SetFillColor(0); rL->SetBorderSize(0);
    rL->AddEntry(pfMet,"pfMet","PL");
    rL->AddEntry(NoPUmet,"NoPU_wSrcLept","PL");
    rL->AddEntry(NoPUmetall,"NoPU_wAllSrcLept","PL");
    rL->AddEntry(MVAmet,"MVA_wSrcLept","PL");
    rL->AddEntry(MVAmetall,"MVA_wAllSrcLept","PL");
    rL->Draw();
 
    //midile line
    //TLine line(0,0,200,0);//TTsemi
    //TLine line(0,0,300,0);//ZZ2Lept2Nu
    //TLine line(0,0,100,0);
    TLine line(0,0,1500,0);//mSUGRA
    //TLine line(0,0,80,0);//ZZ4Mu ZZMuEl MonoPhoton
    line->Draw();
    
    //All 0To7 7To21 21To
    //sprintf(histName,"muonTTJetsemiLept_PURange_All.png");
    //sprintf(histName,"electronTTJetsemiLept_PURange_All.png");
    //sprintf(histName,"monoJet_PURange_All.png");
    sprintf(histName,"mSUGRA_PURange_All.png");
    //sprintf(histName,"hadronTT2hadron_PURange_All.png");
    //sprintf(histName,"electronWToENu_PURange_All.png");
    //sprintf(histName,"muonWToMuNu_PURange_All.png");
    //sprintf(histName,"electronDYElEl_PURange_All.png");
    //sprintf(histName,"muonDYMuNu_PURange_All.png");
    //sprintf(histName,"ZZ4Mu_PURange_All.png");
    //sprintf(histName,"ZZ4El_PURange_All.png");
    //sprintf(histName,"ZZ2Mu2El_PURange_All.png");
    //sprintf(histName,"ZZ2Mu2Nu_PURange_All.png");
    //sprintf(histName,"ZZ2El2Nu_PURange_All.png");
    //sprintf(histName,"WW_PURange_All.png");
    //sprintf(histName,"WZ_PURange_All.png");
    //sprintf(histName,"monoPhoton_PURange_All.png");
    c1.SaveAs(histName);

}
Esempio n. 8
0
void PhotTaggTime( UInt_t ebin = 8, Bool_t print = kFALSE)
{
	UInt_t i, chan_lo, chan_hi, bin_lo, bin_hi;
	UInt_t prompt[2], acc[4];
	Double_t yy, ym, y1, y2;
	Double_t energy, temin, temax;
	TString name;

	TFile* file;

	gROOT->ProcessLine( ".L ReadParams.C");
	ReadTagEng( "xs/tageng855.dat");

	// Middle channel bin and bin limits
	i = tchan[ebin];
	chan_lo = i-2;
	chan_hi = i+2;

	file = full;
	energy = WeightedPar( file, "energy", chan_lo, chan_hi);
	temin = tcd[chan_hi].energy - tcd[chan_hi].denergy;
	temax = tcd[chan_lo].energy + tcd[chan_lo].denergy;

	gStyle->SetOptStat( 0);

	prompt[0] = 92;
	prompt[1] = 106;
	acc[0] = 20;
	acc[1] = 80;
	acc[2] = 118;
	acc[3] = 178;

	TCanvas *c1 = new TCanvas ( "c1", "Canvas", 200, 0, 1200, 500);
	c1->Divide( 3,1);

	// Phot Tagger Time
	c1->cd( 1);

	name = "COMP_PhotTaggTime_v_TChanHit";
	TH2D *h2D = (TH2D*)full.Get( name);

	bin_lo = h2D->GetXaxis()->FindBin( chan_lo);
	bin_hi = h2D->GetXaxis()->FindBin( chan_hi);
	TH1D *h1 = h2D->ProjectionY( "PhotTaggTime", bin_lo, bin_hi);

	name = Form( " E_{#gamma} = %5.1f (%5.1f - %5.1f) MeV", energy, temin,
			temax);
	h1->SetTitle( name);
	h1->SetLineWidth(2);
	h1->GetXaxis()->SetTitleOffset( 1.1);
	h1->GetYaxis()->SetTitleOffset( 1.3);
	h1->GetXaxis()->SetTitle( "Photon - Tagger Time (ns)");
	h1->GetYaxis()->SetTitle( "Counts");
	h1->GetXaxis()->SetLabelSize( 0.03);
	h1->GetYaxis()->SetLabelSize( 0.03);
	h1->GetXaxis()->CenterTitle();
	h1->GetYaxis()->CenterTitle();
	h1->Draw();

	h1->SetMinimum( 0);
	yy = h1->GetMaximum();
	ym = yy*1.05;
	h1->SetMaximum( ym);
	y1 = yy*0.9;
	y2 = yy;

	l1 = new TLine( prompt[0], 0,prompt[0], ym);
	l1->SetLineWidth(3);
	l1->Draw();
	l2 = new TLine( prompt[1], 0,prompt[1], ym);
	l2->SetLineWidth(3);
	l2->Draw();
	l3 = new TLine( acc[0], 0,acc[0], ym);
	l3->SetLineStyle(2);
	l3->SetLineWidth(3);
	l3->Draw();
	l4 = new TLine( acc[1], 0,acc[1], ym);
	l4->SetLineStyle(2);
	l4->SetLineWidth(3);
	l4->Draw();
	l5 = new TLine( acc[2], 0,acc[2], ym);
	l5->SetLineStyle(2);
	l5->SetLineWidth(3);
	l5->Draw();
	l6 = new TLine( acc[3], 0,acc[3], ym);
	l6->SetLineStyle(2);
	l6->SetLineWidth(3);
	l6->Draw();

	// Photon Missing Mass
	c1->cd( 2);

	name = "COMP_PhotonMmissP_v_TChanPhotP";
	TH2D *h2P = (TH2D*)full.Get( name);
	name = "COMP_PhotonMmissR_v_TChanPhotR";
	TH2D *h2R = (TH2D*)full.Get( name);

	bin_lo = h2P->GetXaxis()->FindBin( chan_lo);
	bin_hi = h2P->GetXaxis()->FindBin( chan_hi);
	TH1D *hP = h2P->ProjectionY( "PhotonMmissP", bin_lo, bin_hi);
	TH1D *hR = h2R->ProjectionY( "PhotonMmissR", bin_lo, bin_hi);
	TH1D *hS = (TH1D*)hP->Clone( "subt");

	// TDC Spectrum
	hP->SetTitle();
	hP->SetLineWidth( 2);
	hP->GetXaxis()->SetTitleOffset( 1.1);
	hP->GetXaxis()->SetTitle( "Proton Missing Mass (MeV)");
	hP->GetXaxis()->SetLabelSize( 0.03);
	hP->GetXaxis()->CenterTitle();
	hP->GetXaxis()->SetRangeUser( 800, 1200);
	hP->Draw();

	hR->SetLineWidth( 2);
	hR->SetLineStyle( 2);
	hR->Scale( 0.0833);
	hR->Draw( "same");

	tl = new TLegend( 0.2, 0.7, 0.4, 0.8);
	tl->SetFillStyle( 0);
	tl->SetBorderSize( 0);
	tl->SetTextSize( 0.05);
	tl->SetTextFont( 132);
	tl->AddEntry( hP, "prompt");
	tl->AddEntry( hR, "random");
	tl->Draw();

	c1->cd( 3);
	hS->Sumw2();
	hS->Add( hR, -1.0);

	hS->SetTitle();
	hS->GetXaxis()->SetTitleOffset( 1.1);
	hS->GetXaxis()->SetTitle( "Proton Missing Mass (MeV)");
	hS->GetXaxis()->SetLabelSize( 0.03);
	hS->GetXaxis()->CenterTitle();
	hS->SetLineWidth( 2);
	hS->SetMarkerStyle( 20);
	hS->SetMarkerSize( 0.5);
	hS->GetXaxis()->SetRangeUser( 800, 1200);
	hS->Draw();

	tl = new TLegend( 0.2, 0.7, 0.4, 0.8);
	tl->SetFillStyle( 0);
	tl->SetBorderSize( 0);
	tl->SetTextSize( 0.05);
	tl->SetTextFont( 132);
	tl->AddEntry( hS, "subtracted", "p");
	tl->Draw();

	name = Form( "plots/Compton/random_subt_%d", ebin);
	name.Append( ".pdf");
	if ( print == kTRUE) c1->Print( name);
}
Esempio n. 9
0
void RooFitMacro()
{	
    gROOT->Reset();
    gSystem->Load("libRooFit");
    gROOT->LoadMacro("RooCMSShape.cc+");

    //gStyle->SetOptStat(111111);
    //gROOT->ProcessLine(".x ~/rootlogon.C");

    TFile f("TagAndProbeResults_Marco.root");


    TH1F * Z_mass = new TH1F("Z","Z" , 200, 0, 200);
    //TH1D *results = new TH1D("results", "results", 200, 0, 200);
    //results->Sumw2();

    // We need to include NJetCut because there is depedence w.r.t. jet multiplicity
    Z_mass = (TH1F*)f.Get("Zmass_Inclusive_NoElectronVeto_Numerator;1");
    //Z_mass = (TH1F*)f.Get("Zmass_Inclusive_NoElectronVeto_Denominator;1");

    //float bincontent = Z_mass->GetBinContent(60);
    //cout << "60.bin content  : " << bincontent << endl;

    double hmin = 60;
    double hmax = 120;
    double r  = .25;
    double sl = 1. / ( 1. - r );

    // Declare observable x
    RooRealVar x("x","x",hmin,hmax) ;
    RooDataHist dh("dh","dh",x,Import(*Z_mass)) ;
    //  Breit-Wigner Lineshape 
    //  Parameters for Breit-Wigner Distribution
    RooRealVar  M("M_{Z^{0}}", "Z0 Resonance  Mass", 91.18, 85.0, 95.0, "GeV/c^{2}");
    RooRealVar  gamma("#Gamma", "#Gamma", 2.4952, 2.0, 3.0, "GeV/c^{2}");
    M.setConstant();
    //gamma.setConstant();
    RooBreitWigner bw("bw", "A Breit-Wigner Distribution", x, M, gamma);
    //  Mass resolution model - Crystal Ball Lineshape
    //  Parameters for Crystal Ball Lineshape 
    RooRealVar  M_CB("#Delta m_{0}", "Bias", -2.0, -10.0, 10.0, "GeV/c^{2}");
    RooRealVar  sigma("#sigma_{CB}", "Width", 1.6, 0.1, 15.0, "GeV/c^{2}");
    //	RooRealVar  sigma("#sigma_{CB}", "Width", 2.5, 0.1, 15.0, "GeV/c^{2}");
    RooRealVar  alpha("#alpha", "Cut", 1.5, 0.1, 15.0);
    RooRealVar  n("n", "Power", 1.8, 0.5, 5.0);
    RooCBShape  cb("resCBF", "A  Crystal Ball Lineshape", x, M_CB, sigma, alpha, n);
    // background p.d.f
    RooRealVar cms_alpha("alpha", "alpha", 60, 50, 70);
    RooRealVar cms_beta("beta", "beta", 0.01, 0.001, 0.05);
    RooRealVar cms_gamma("gamma", "gamma", 0.05, 0.005, 0.5);
    RooRealVar peak("peak", "peak", 60, 50, 70);
    RooCMSShape bag("bag", "RooCMSShape", x, cms_alpha, cms_beta, cms_gamma, peak);
    RooRealVar  frac("frac", "f", 0.01, 0, 1.0);
    RooFFTConvPdf signal("signal", "Convolution", x, bw, cb);

    RooRealVar signal_yield("signal_yield", "signal_yield", 100, 0, Z_mass->Integral());
    RooRealVar bag_yield("bag_yield", "bag_yield", 0, 0, Z_mass->Integral());

    RooArgList shapes;
    RooArgList yields;

    shapes.add(signal);  
    shapes.add(bag);


    yields.add(signal_yield);  
    yields.add(bag_yield);

    RooRealVar fsig("fsig", "fsig", 0, 0, 1.);
    //RooAddPdf model("model","model",shapes,yields);

    // model = fsig x signal + (1-fsig) x bag
    RooAddPdf model("model","model",shapes,fsig,kTRUE);

    // Signal p.d.f.
    //RooFFTConvPdf sum("sum", "Convolution", x, bw, cb);
    //RooAddPdf sum("sum","sum",bw,cb,frac);
    //RooAddPdf model("model","model",RooArgList(sum, bag),frac);
    //RooFFTConvPdf model("model","model",x,sum,bag);
    //RooFitResult* filters = sum.fitTo(dh,Range(0,200),"qr");
    //filters->Print("v");


    //RooFitResult* filters = model.fitTo(dh,Range(0,200),"qr");
    RooFitResult* filters = model.fitTo(dh, RooFit::Minimizer("Minuit", "migradimproved"), RooFit::NumCPU(4), RooFit::Save(true), RooFit::Extended(false), RooFit::PrintLevel(-1));
    //RooFitResult* filters = model.fitTo(dh, RooFit::Extended(true), RooFit::PrintLevel(-1));
    //RooFitResult* filters = model.fitTo(dh, "mhe");
    //RooFitResult* filters = cb.fitTo(dh,Range(0,200),"qr");
    //RooFitResult* filters = bw.fitTo(dh,Range(0,100),"qr");
    //RooFitResult* filters = bag.fitTo(dh,"qr");


    TCanvas* canvas = new TCanvas("ZmassHisto","ZmassHisto",0, 0, 1000,700) ;
    canvas->cd() ; //gPad->SetLeftMargin(0.15);
    //gPad->SetLogy();
    RooPlot* frame = x.frame(Title("e #gamma invariant mass fit")) ;
    dh.plotOn(frame,MarkerSize(0.5),Name("data_hist"));  //this will show histogram data points on canvas

    dh.statOn(frame,Layout(0.15,0.37,0.85),What("N")) ;


    //dh.statOn(frame);  //this will display hist stat on canvas

    //sum.plotOn(frame,LineColor(4));//this will show fit overlay on canvas
    //sum.paramOn(frame); //this will display the fit parameters on canvas

    //bag.plotOn(frame,LineColor(2));//this will show fit overlay on canvas 
    //bag.paramOn(frame); //this will display the fit parameters on canvas

    model.plotOn(frame,Components(bag),LineColor(2));//this will show fit overlay on canvas 
    model.plotOn(frame,Components(signal),LineColor(3));//this will show fit overlay on canvas 
    model.plotOn(frame,LineColor(kBlue),Name("main_curve"));//this will show fit overlay on canvas 

    //	model.paramOn(frame); //this will display the fit parameters on canvas
    model.paramOn(frame, Layout(0.6, 0.95, 0.92)); //this will display the fit parameters on canvas
    //model.paramOn(frame, Layout(0.6, 0.99, 0.75));
    //	model.plotOn(frame,LineColor(4));//this will show fit overlay on canvas 
    //	model.paramOn(frame); //this will display the fit parameters on canvas

    RooHist* histogram = frame->getHist("data_hist");
    RooCurve* curve = frame->getCurve("main_curve");
    TH1D* hresidual  = residualHist(histogram,curve);
    hresidual->Sumw2();
    canvas->Divide( 1, 2, .1, .1 );
    TPad* padHisto = (TPad*) canvas->cd(1);
    TPad* padResid = (TPad*) canvas->cd(2);
    double small = 0.1;
    padHisto->SetPad( 0., r , 1., 1. );
    padHisto->SetBottomMargin( small );
    padResid->SetPad( 0., 0., 1., r  );
    padResid->SetBottomMargin( 0.3  );
    padResid->SetTopMargin   ( small );
    padHisto->cd();


    //float fitvalue = frame.GetX()[60];
    //Double_t nX = x.getVal();
    //cout << "nX  : " << nX << endl;
    //results->SetBinContent(results->GetXaxis()->FindBin(60), nX);
    //float fitvalue = results->GetBinContent(59);
    //cout << "59.5daki fit value  : " << fitvalue << endl;

    //cb.plotOn(frame,LineColor(2));//this will show fit overlay on canvas 
    //cb.paramOn(frame); //this will display the fit parameters on canvas

    //bw.plotOn(frame,LineColor(4));//this will show fit overlay on canvas 
    //bw.paramOn(frame); //this will display the fit parameters on canvas


    //gPad->SetLogy();
    cout << "chisquare : " << frame->chiSquare() << endl ;

    //cout << "Total Number of events: " << Z_mass->Integral() << endl;
    //cout << "Number of signal events: " << fsig.getVal() *  Z_mass->Integral() << endl;
    //cout << "Number of background events: " << (1 - fsig.getVal()) * Z_mass->Integral() << endl;

    //Draw all frames on a canvas

    //TPaveLabel *label1 = new TPaveLabel(1,500,15,700,"Chisquare:");
    frame->GetXaxis()->SetTitle("Invariant mass w/ NoElectronVeto photon (in GeV/c^{2})");  
    //frame->GetXaxis()->SetTitle("Invariant mass w/ TIGHT photon (in GeV/c^{2})");  
    //frame->GetXaxis()->SetTitleOffset(1.2);
    frame->Draw();
    //float binsize = Z_mass->GetBinWidth(1);
    //char Bsize[50]; 
    //sprintf(Bsize,"Events per %2.2f",binsize);
    //frame->GetYaxis()->SetTitle(Bsize);  
    //frame->GetYaxis()->SetTitleOffset(1.2);
    //results->Sumw2();
    padResid->cd();
    hresidual->Draw();
    Lines( hresidual );
    hresidual->Draw( "SAME" );

    //frame->Draw();
    //results->Draw();

    //canvas->Update();
    //title->Draw("same");
    //hresidual->Draw();

    canvas->SaveAs("pdf_TagAndProbe/ResidualNumerator_binned_negligible_errorfit.pdf");
    //canvas->SaveAs("pdf_TagAndProbe/ResidualDenominator_binned_negligible_errorfit.pdf");


}
Esempio n. 10
0
void allCutFlow(){
setTDRStyle();
gROOT->SetBatch();

//stuff to choose
bool logPlot = true; //true for log plot

TString Cut = "EventCount/";

TString Nbtags = "";
TString Obj = "";
TString RefSelection = "";
TString Type = "";
TString Next = "";
int RebinFact = 1;

TString Systematic = "central/";

//TString Variable = "TTbarMuMuRefSelection"; 
//TString Variable = "TTbarMuMuRefSelectionUnweighted";
//TString Variable = "TTbarEERefSelection";  
//TString Variable = "TTbarEERefSelectionUnweighted";
TString Variable = "TTbarEMuRefSelection"; 
//TString Variable = "TTbarEMuRefSelectionUnweighted";

 
TString Xtitle = "Cuts";

//if( Variable == "TTbarMuMuRefSelection" || Variable == "TTbarEERefSelection" )
//TString step[10] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "m(Z) veto", "#geq 1 jet", "#geq 2 jets", "#slash{E_{T}} cut", "#geq1 CSV b-tag", "#geq1 Good Photon" , "1 Good Photon"};
//TString step_latex[10] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "m(Z) veto", "$\\geq$ 1 jets", "$\\geq$ 2 jets", "$\\slash{E_{T}}$ cut", "$\\geq$ 1 CSV b-tag", "$\\geq$ 1 Good Photon" , "1 Good Photon"};
//if( Variable == "TTbarEMuRefSelection" )
TString step[8] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "#geq 1 jets", "#geq 2 jets", "#geq1 CSV b-tag", "#geq1 Good Photon", "1 Good Photon" };		
TString step_latex[8] = {"Skim" ,"Cleaning and HLT","Di-lepton Sel", "$\\geq$ 1 jets", "$\\geq$ 2 jets", "$\\geq$ 1 CSV b-tag", "$\\geq$ 1 Good Photon" , "1 Good Photon"};


//Data
if( Variable == "TTbarMuMuRefSelection" || Variable == "TTbarMuMuRefSelectionUnweighted" )
TH1D* data = getSample("DoubleMu", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
if( Variable == "TTbarEERefSelection" || Variable == "TTbarEERefSelectionUnweighted" )
TH1D* data = getSample("DoubleElectron", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
if( Variable == "TTbarEMuRefSelection" || Variable == "TTbarEMuRefSelectionUnweighted" )
TH1D* data = getSample("MuEG", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

//MC
TH1D* ttgamma = getSample("TTGamma", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* tt = getSample("TTJet", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* wjets = getSample("WJetsToLNu", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* DY1 = getSample("DYJetsToLL_M-10To50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* DY2 = getSample("DYJetsToLL_M-50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* T_tW = getSample("T_tW-channel", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* Tbar_tW = getSample("Tbar_tW-channel",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* ZZ = getSample("ZZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* WW = getSample("WWtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* WZ = getSample("WZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

//QCD
TH1D* QCD_Pt_20_30_BCtoE = getSample("QCD_Pt_20_30_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_20_30_EMEnriched = getSample("QCD_Pt_20_30_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_20_MuEnrichedPt_15 = getSample("QCD_Pt_20_MuEnrichedPt_15",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_30_80_BCtoE = getSample("QCD_Pt_30_80_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_30_80_EMEnriched = getSample("QCD_Pt_30_80_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_80_170_BCtoE = getSample("QCD_Pt_80_170_BCtoE",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
TH1D* QCD_Pt_80_170_EMEnriched = getSample("QCD_Pt_80_170_EMEnriched",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);

TH1D* QCD_all = getSample("QCD_Pt_20_MuEnrichedPt_15",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  QCD_all->Add(QCD_Pt_20_30_BCtoE);
  QCD_all->Add(QCD_Pt_20_30_EMEnriched);
  QCD_all->Add(QCD_Pt_30_80_BCtoE);
  QCD_all->Add(QCD_Pt_30_80_EMEnriched);
  QCD_all->Add(QCD_Pt_80_170_BCtoE);
  QCD_all->Add(QCD_Pt_80_170_EMEnriched);
  
TH1D* DY = getSample("DYJetsToLL_M-10To50", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  DY->Add(DY2);
  
TH1D* Diboson = getSample("ZZtoAnything",1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  Diboson->Add(WW);
  Diboson->Add(WZ);
  
TH1D* SingleTop = getSample("T_tW-channel", 1, Obj, RefSelection, Type, Next, Variable, RebinFact, Systematic, Cut);
  SingleTop->Add(Tbar_tW); 
 
cout << "got samples" << endl;

THStack *hs = new THStack("hs","test");

  hs->Add(QCD_all);
  hs->Add(wjets);
  hs->Add(WZ); 
  hs->Add(WW);
  hs->Add(ZZ);
  hs->Add(DY1);
  hs->Add(DY2);
  hs->Add(T_tW); 
  hs->Add(Tbar_tW);
  hs->Add(tt);
  hs->Add(ttgamma);
  

TH1D* allMC = (TH1D*)ttgamma->Clone("ratio");
  allMC->Add(tt);
  allMC->Add(wjets);
  allMC->Add(DY1);
  allMC->Add(DY2);
  allMC->Add(T_tW);
  allMC->Add(Tbar_tW);
  allMC->Add(ZZ);
  allMC->Add(WW);
  allMC->Add(WZ);
  allMC->Add(QCD_all);
  
TH1D* dataEff = new TH1D("data eff","data eff",9,0,9);
TH1D* mcEff = new TH1D("mc eff","mc eff",9,0,9);

mcEff->Sumw2();
dataEff->Sumw2();

for(int q =1; q<ttgamma->GetNbinsX(); q++){
mcEff->GetXaxis()->SetBinLabel(q, step[q]);
dataEff->SetBinContent(q, data->GetBinContent(q+1)/data->GetBinContent(q));
dataEff->SetBinError(q, dataEff->GetBinContent(q)*sqrt(pow(data->GetBinError(q+1)/data->GetBinContent(q+1),2)+pow(data->GetBinError(q)/data->GetBinContent(q),2)));
mcEff->SetBinContent(q, allMC->GetBinContent(q+1)/allMC->GetBinContent(q));

}  

	
	TCanvas *c2 = new TCanvas("cutflow eff","cutflow eff",600, 500);
  	
	mcEff->SetLineColor(kRed);
	mcEff->Draw();
	dataEff->Draw("Esame");
	
	TLegend *tleg3;
	tleg3 = new TLegend(0.7,0.7,0.8,0.9);
	tleg3->SetTextSize(0.04);
	tleg3->SetBorderSize(0);
	tleg3->SetFillColor(10);
	tleg3->AddEntry(dataEff , "data", "l");
	tleg3->AddEntry(mcEff , "mc", "l");
	
	tleg3->Draw("same");
	
	c2->SaveAs("plots/cutFlow/cutEff_"+Variable+".pdf");
	c2->SaveAs("plots/cutFlow/cutEff_"+Variable+".png");
	delete c2;

  //draw histos to files
  TCanvas *c1 = new TCanvas("cutflow","cutflow",900, 600);

  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.3);
  
  if(logPlot ==true)
  hs->SetMinimum(10.);

  hs->Draw("hist");
  
  for(int q =0; q<ttgamma->GetNbinsX(); q++)
  hs->GetXaxis()->SetBinLabel(q+1, step[q]);
  
  data->Draw("E same");
  data->SetMarkerStyle(20);
  
//  hs->GetXaxis()->SetLimits(MinX, MaxX);
  hs->GetXaxis()->SetTitle(Xtitle); hs->GetXaxis()->SetTitleSize(0.05);
  hs->GetYaxis()->SetTitle("Number of Events");hs->GetYaxis()->SetTitleSize(0.05);
  
  
  	TLegend *tleg2;
	tleg2 = new TLegend(0.7,0.7,0.8,0.9);
	tleg2->SetTextSize(0.04);
	tleg2->SetBorderSize(0);
	tleg2->SetFillColor(10);
	tleg2->AddEntry(data , "2012 data", "lpe");
	tleg2->AddEntry(ttgamma , "t#bar{t}+gamma", "lf");
	tleg2->AddEntry(tt , "t#bar{t}", "lf");
	tleg2->AddEntry(T_tW, "single top", "lf");
	tleg2->AddEntry(DY1 , "Drell-Yan", "lf");
	tleg2->AddEntry(ZZ , "Di-boson", "lf");
	tleg2->AddEntry(wjets , "w+jets", "lf");
	tleg2->AddEntry(QCD_all , "QCD", "lf");
	
	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	
	
	TText* textstuff = dostuff(0.22,0.96, Variable);
	textstuff->Draw();
	
  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("plots/cutFlow/");
  
  if(logPlot ==true){
    plotName += Variable+"_Log";
    plotName += Nbtags;
    
  }else{
    plotName += Variable+"";  
    plotName += Nbtags;
  }
 
 
  c1->SaveAs(plotName+".png");
  c1->SaveAs(plotName+".pdf");
  delete c1;
 
 //print out
 
    std::cout.setf(std::ios::fixed);
    std::cout.precision(0);

 cout << "& ttgamma & ttbar & single-t  & wjets & zjets & diboson & qcd & all MC & data  \\\\" << endl; 
 
 for(int q = 0; q < ttgamma->GetNbinsX(); q++){
 cout << step_latex[q] << " & " << ttgamma->GetBinContent(q+1) << " $\\pm$ " << ttgamma->GetBinError(q+1)  << " & " <<
 tt->GetBinContent(q+1) << " $\\pm$ " << tt->GetBinError(q+1)  << " & " << SingleTop->GetBinContent(q+1) << " $\\pm$ " <<
 SingleTop->GetBinError(q+1)  << " & " << DY->GetBinContent(q+1) << " $\\pm$ " << DY->GetBinError(q+1)  << " & " <<
 Diboson->GetBinContent(q+1) << " $\\pm$ " << Diboson->GetBinError(q+1)  << " & "<< wjets->GetBinContent(q+1) << " $\\pm$ "
 << wjets->GetBinError(q+1)  << " & " << QCD_all->GetBinContent(q+1) << " $\\pm$ " << QCD_all->GetBinError(q+1)  << " & " <<
 allMC->GetBinContent(q+1) << " $\\pm$ " << allMC->GetBinError(q+1)  << " & " << data->GetBinContent(q+1) << " $\\pm$ " <<
 data->GetBinError(q+1) << " \\\\ " << endl;
 
 }

// for(int r = 0; r < ttgamma->GetNbinsX(); r++){
// std::cout << ttgamma->GetBinContent(r+1) << std::endl;
// }
  	
}
Esempio n. 11
0
void diffXsecZbb( TString inputFile1Name,
		  TString inputFile2Name,
		  TString inputFile3Name,
		  TString eventsNumberHistoName,
		  TString HistoName) {
  // general root setting
  gROOT->Reset(); 
  //  gROOT->SetBatch(kTRUE);
  gStyle->SetOptStat(0);
  gStyle->SetTitleSize(0.1);
  gStyle->SetLabelSize(0.04,"X");
  gStyle->SetLabelSize(0.04,"Y");
  gStyle->SetPadBorderMode(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasColor(0);

  const double xSec_Zbb0jets_  = 1.66; // in pb	  
  const double xSec_Zbb1jets_  = 0.29; // in pb	  
  const double xSec_Zbb2jets_  = 0.05; // in pb	  
  const double xSec_Zbb3jets_  = 0.01; // in pb	  

  const double leptonFactor = 2.0;

  const double luminosityFactor = 100000.; // 100fb^-1 of luminosity assumed in histograms

  TFile * inputFile1 = new TFile(inputFile1Name);
  TFile * inputFile2 = new TFile(inputFile2Name);
  TFile * inputFile3 = new TFile(inputFile3Name);
 
  TH1D * eventsNumberHisto1 = dynamic_cast<TH1D*>(inputFile1->Get(eventsNumberHistoName));
  TH1D * histo1 = dynamic_cast<TH1D*>(inputFile1->Get(HistoName));
  TH1D * histoirrBkg1 = dynamic_cast<TH1D*>(inputFile1->Get(HistoName+"irrBkg"));
  TH1D * eventsNumberHisto2 = dynamic_cast<TH1D*>(inputFile2->Get(eventsNumberHistoName));
  TH1D * histo2 = dynamic_cast<TH1D*>(inputFile2->Get(HistoName));
  TH1D * histoirrBkg2 = dynamic_cast<TH1D*>(inputFile2->Get(HistoName+"irrBkg"));
  TH1D * eventsNumberHisto3 = dynamic_cast<TH1D*>(inputFile3->Get(eventsNumberHistoName));
  TH1D * histo3 = dynamic_cast<TH1D*>(inputFile3->Get(HistoName));
  TH1D * histoirrBkg3 = dynamic_cast<TH1D*>(inputFile3->Get(HistoName+"irrBkg"));

  TString HistoTitle = histo1->GetTitle();
  int nbin = histo1->GetNbinsX();
  double xmin = histo1->GetXaxis()->GetXmin();
  double xmax = histo1->GetXaxis()->GetXmax();
  TH1D * histoTot       = new TH1D(HistoName+"TOT",      "inclusive "+HistoTitle,nbin,xmin,xmax);
  TH1D * histoirrBkgTot = new TH1D(HistoName+"irrBkgTOT","inclusive irrudicible background "+HistoTitle,nbin,xmin,xmax);

  histo1->SetTitle(HistoTitle+ " for Zbb 0 jets");
  histo2->SetTitle(HistoTitle+ " for Zbb 1 jets");
  histo3->SetTitle(HistoTitle+ " for Zbb 2 jets");
  histoirrBkg1->SetTitle("irriducible background "+HistoTitle+ " for Zbb 0 jets");
  histoirrBkg2->SetTitle("irriducible background "+HistoTitle+ " for Zbb 1 jets");
  histoirrBkg3->SetTitle("irriducible background "+HistoTitle+ " for Zbb 2 jets");

  double histo1Entries = histo1->GetEntries();
  double histo2Entries = histo2->GetEntries();
  double histo3Entries = histo3->GetEntries();
  double histoirrBkg1Entries = histoirrBkg1->GetEntries();
  double histoirrBkg2Entries = histoirrBkg2->GetEntries();
  double histoirrBkg3Entries = histoirrBkg3->GetEntries();
  double events1 = (double)eventsNumberHisto1->GetMaximum(); 
  double events2 = (double)eventsNumberHisto2->GetMaximum();
  double events3 = (double)eventsNumberHisto3->GetMaximum();
  double xSecEff1  = leptonFactor*xSec_Zbb0jets_;
  double xSecEff2  = leptonFactor*xSec_Zbb1jets_;
  double xSecEff3  = leptonFactor*xSec_Zbb2jets_;
  double invLuminosityEff1 = xSecEff1/events1;
  double invLuminosityEff2 = xSecEff2/events2;
  double invLuminosityEff3 = xSecEff3/events3;


  TLegend * legend1 = new TLegend(0.5,0.6,0.89,0.8);
  legend1->SetFillColor(0);
  legend1->SetBorderSize(0);  
  legend1->SetTextFont(72);
  legend1->SetTextSize(0.035);
  legend1->SetFillColor(0);
  TLegend * legend2 = new TLegend(0.5,0.6,0.89,0.8);
  legend2->SetFillColor(0);
  legend2->SetBorderSize(0);  
  legend2->SetTextFont(72);
  legend2->SetTextSize(0.035);
  legend2->SetFillColor(0);
  TLegend * legend3 = new TLegend(0.5,0.6,0.89,0.8);
  legend3->SetFillColor(0);
  legend3->SetBorderSize(0);  
  legend3->SetTextFont(72);
  legend3->SetTextSize(0.035);
  legend3->SetFillColor(0);
  TLegend * legendTot = new TLegend(0.7,0.65,0.89,0.85);
  legendTot->SetFillColor(0);
  legendTot->SetBorderSize(0);  
  legendTot->SetTextFont(72);
  legendTot->SetTextSize(0.035);
  legendTot->SetFillColor(0);
  char nev[50];

  TCanvas * canvas = new TCanvas ( "diffxSec", "differential xSec", 1200, 400 );
  gStyle->SetOptStat(0);
  //  canvas->UseCurrentStyle();
  canvas->Divide(3,1);
  canvas->cd(1);
  histo1->SetNormFactor(histo1Entries*invLuminosityEff1*luminosityFactor);
  histo1->Draw();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histo1Entries*invLuminosityEff1*luminosityFactor);
  legend1->AddEntry(histo1,nev,"");
  legend1->Draw();
  canvas->cd(2);
  histo2->SetNormFactor(histo2Entries*invLuminosityEff2*luminosityFactor);
  histo2->Draw();
  legend2->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histo2Entries*invLuminosityEff2*luminosityFactor);
  legend2->AddEntry(histo2,nev,"");
  legend2->Draw();
  canvas->cd(3);
  histo3->SetNormFactor(histo3Entries*invLuminosityEff3*luminosityFactor);
  histo3->Draw();
  legend3->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histo3Entries*invLuminosityEff3*luminosityFactor);
  legend3->AddEntry(histo3,nev,"");
  legend3->Draw();

  histoTot->Sumw2();
  histoTot->Add(histo1);
  histoTot->Add(histo2);
  histoTot->Add(histo3);

  TCanvas * canvasTot = new TCanvas ( "inclusivediffxSec", "differential xSec", 1200, 400 );
  gStyle->SetOptStat(0);
  canvasTot->UseCurrentStyle();
  canvasTot->cd();
  histo1->SetTitle("4-body mass (100 fb^{-1})");
  histo1->GetXaxis()->SetTitle("m_{llbb} (GeV)");
  histo1->GetYaxis()->SetTitle("d#sigma/dm_{llbb} events/10GeV");
  histo1->SetMinimum(0.001);
  histo1->SetLineColor(51);
  histo1->Draw();
  histo2->SetLineColor(56);
  histo2->Draw("same");
  histo3->SetLineColor(60);
  histo3->Draw("same");
  histoTot->Draw("same");

  legendTot->Clear();
  sprintf(nev,"Zb\\bar{b}+0jets");
  legendTot->AddEntry(histo1,nev,"l");
  sprintf(nev,"Zb\\bar{b}+1jets");
  legendTot->AddEntry(histo2,nev,"l");
  sprintf(nev,"Zb\\bar{b}+2jets");
  legendTot->AddEntry(histo3,nev,"l");
  sprintf(nev,"inclusive");
  legendTot->AddEntry(histoTot,nev,"l");
  legendTot->Draw();



  TCanvas * canvasirrBkg = new TCanvas ( "diffxSecirrbkg", "differential xSec for irriducible background", 1200, 400 );
  gStyle->SetOptStat(0);
  canvasirrBkg->UseCurrentStyle();
  canvasirrBkg->Divide(3,1);
  canvasirrBkg->cd(1);
  histoirrBkg1->SetNormFactor(histoirrBkg1Entries*invLuminosityEff1*luminosityFactor);
  histoirrBkg1->Draw();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histoirrBkg1Entries*invLuminosityEff1*luminosityFactor);
  legend1->AddEntry(histoirrBkg1,nev,"");
  legend1->Draw();
  canvasirrBkg->cd(2);
  histoirrBkg2->SetNormFactor(histoirrBkg2Entries*invLuminosityEff2*luminosityFactor);
  histoirrBkg2->Draw();
  legend2->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histoirrBkg2Entries*invLuminosityEff2*luminosityFactor);
  legend2->AddEntry(histoirrBkg2,nev,"");
  legend2->Draw();
  canvasirrBkg->cd(3);
  histoirrBkg3->SetNormFactor(histoirrBkg3Entries*invLuminosityEff3*luminosityFactor);
  histoirrBkg3->Draw();
  legend3->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histoirrBkg3Entries*invLuminosityEff3*luminosityFactor);
  legend3->AddEntry(histoirrBkg3,nev,"");
  legend3->Draw();

  histoirrBkgTot->Sumw2();
  histoirrBkgTot->Add(histoirrBkg1);
  histoirrBkgTot->Add(histoirrBkg2);
  histoirrBkgTot->Add(histoirrBkg3);

  TCanvas * canvasirrBkgTot = new TCanvas ( "inclusivediffxSecirrBkg", "differential xSec", 1200, 400 );
  gStyle->SetOptStat(0);
  canvasirrBkgTot->UseCurrentStyle();
  canvasirrBkgTot->cd();
  gPad->SetLogy();
  histoirrBkg1->SetTitle("4-body mass (100 fb^{-1})");
  histoirrBkg1->GetXaxis()->SetTitle("m_{llbb} (GeV)");
  histoirrBkg1->GetYaxis()->SetTitle("d#sigma/dm_{llbb} events/10GeV");
  histoirrBkg1->SetMinimum(0.001);
  histoirrBkg1->SetLineColor(51);
  histoirrBkg1->Draw();
  histoirrBkg2->SetLineColor(56);
  histoirrBkg2->Draw("same");
  histoirrBkg3->SetLineColor(60);
  histoirrBkg3->Draw("same");
  histoirrBkgTot->Draw("same");

  legendTot->Clear();
  sprintf(nev,"Zb\\bar{b}+0jets");
  legendTot->AddEntry(histoirrBkg1,nev,"l");
  sprintf(nev,"Zb\\bar{b}+1jets");
  legendTot->AddEntry(histoirrBkg2,nev,"l");
  sprintf(nev,"Zb\\bar{b}+2jets");
  legendTot->AddEntry(histoirrBkg3,nev,"l");
  sprintf(nev,"inclusive");
  legendTot->AddEntry(histoirrBkgTot,nev,"l");
  legendTot->Draw();

  canvas->Print("Zbb.jpg");
  canvasTot->Print("Zbbtot.jpg");
  canvasirrBkg->Print("ZbbIrr.jpg");
  canvasirrBkgTot->Print("ZbbIrrtot.jpg");

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

  histo1->Write();
  histo2->Write();
  histo3->Write();
  histoTot->Write();
  histoirrBkg1->Write();
  histoirrBkg2->Write();
  histoirrBkg3->Write();
  histoirrBkgTot->Write();

  outputFile->Close();

}
Esempio n. 12
0
int resbosComp(const TString BaseName)
{
  TString tmpTStr;
  CPlot* pltComp;
  CPlot* pltCompLog;

  TFile *F_29;
  TFile *F_30;
  TFile *F_31;
  TFile *F_32;
  TFile *F_33;
  TFile *F_34;
  TFile *F_35;
  TFile *F_Data;

  F_29 = new TFile("../"+BaseName+"/29lResbos.root");
  F_30 = new TFile("../"+BaseName+"/30lResbos.root");
  F_31 = new TFile("../"+BaseName+"/31lResbos.root");
  F_32 = new TFile("../"+BaseName+"/32lResbos.root");
  F_33 = new TFile("../"+BaseName+"/33lResbos.root");
  F_34 = new TFile("../"+BaseName+"/34lResbos.root");
  F_35 = new TFile("../"+BaseName+"/35lResbos.root");
  F_Data = new TFile("../RstUnfold/Result_"+BaseName+".root");

  TString resultDir = "Result";
  gSystem->mkdir(resultDir,kTRUE);
  TFile f_out(resultDir+"/Resbos_"+BaseName+".root","recreate");

  const int nBins = 14;
  double WptBins[nBins]    = {0.0,7.5,12.5,17.5,24,30,40,50,70,110,150,190,250,600};
  double WptLogBins[nBins] = {1.0,7.5,12.5,17.5,24,30,40,50,70,110,150,190,250,600};
  
  TH1D *hResbos29 = new TH1D("hResbos29","hResbos29",nBins-1,WptBins);hResbos29->Sumw2();
  TH1D *hResbos30 = new TH1D("hResbos30","hResbos30",nBins-1,WptBins);hResbos30->Sumw2();
  TH1D *hResbos31 = new TH1D("hResbos31","hResbos31",nBins-1,WptBins);hResbos31->Sumw2();
  TH1D *hResbos32 = new TH1D("hResbos32","hResbos32",nBins-1,WptBins);hResbos32->Sumw2();
  TH1D *hResbos33 = new TH1D("hResbos33","hResbos33",nBins-1,WptBins);hResbos33->Sumw2();
  TH1D *hResbos34 = new TH1D("hResbos34","hResbos34",nBins-1,WptBins);hResbos34->Sumw2();
  TH1D *hResbos35 = new TH1D("hResbos35","hResbos35",nBins-1,WptBins);hResbos35->Sumw2();
  TH1D *hData = new TH1D("hData","hData",nBins-1,WptBins);hData->Sumw2();
  
  TH1D *hResbosLog29 = new TH1D("hResbosLog29","hResbosLog29",13,WptLogBins);hResbosLog29->Sumw2();
  TH1D *hResbosLog30 = new TH1D("hResbosLog30","hResbosLog30",13,WptLogBins);hResbosLog30->Sumw2();
  TH1D *hResbosLog31 = new TH1D("hResbosLog31","hResbosLog31",13,WptLogBins);hResbosLog31->Sumw2();
  TH1D *hResbosLog32 = new TH1D("hResbosLog32","hResbosLog32",13,WptLogBins);hResbosLog32->Sumw2();
  TH1D *hResbosLog33 = new TH1D("hResbosLog33","hResbosLog33",13,WptLogBins);hResbosLog33->Sumw2();
  TH1D *hResbosLog34 = new TH1D("hResbosLog34","hResbosLog34",13,WptLogBins);hResbosLog34->Sumw2();
  TH1D *hResbosLog35 = new TH1D("hResbosLog35","hResbosLog35",13,WptLogBins);hResbosLog35->Sumw2();
  TH1D *hDataLog = new TH1D("hDataLog","hDataLog",13,WptLogBins);hDataLog->Sumw2();
  
  TH1D* lResbos29;
  TH1D* lResbos30;
  TH1D* lResbos31;
  TH1D* lResbos32;
  TH1D* lResbos33;
  TH1D* lResbos34;
  TH1D* lResbos35;
  TH1D* lData;

  lResbos29 =(TH1D*)F_29->Get("lResbos")->Clone();
  lResbos30 =(TH1D*)F_30->Get("lResbos")->Clone();
  lResbos31 =(TH1D*)F_31->Get("lResbos")->Clone();
  lResbos32 =(TH1D*)F_32->Get("lResbos")->Clone();
  lResbos33 =(TH1D*)F_33->Get("lResbos")->Clone();
  lResbos34 =(TH1D*)F_34->Get("lResbos")->Clone();
  lResbos35 =(TH1D*)F_35->Get("lResbos")->Clone();
  lData =(TH1D*)F_Data->Get("BornEffCorr")->Clone();

  lData->Scale(1./18.429);
  
  for( int ipt(1);ipt<nBins;ipt++)
  {
    hResbos29->SetBinContent(ipt,lResbos29->GetBinContent(ipt));
    hResbos30->SetBinContent(ipt,lResbos30->GetBinContent(ipt));
    hResbos31->SetBinContent(ipt,lResbos31->GetBinContent(ipt));
    hResbos32->SetBinContent(ipt,lResbos32->GetBinContent(ipt));
    hResbos33->SetBinContent(ipt,lResbos33->GetBinContent(ipt));
    hResbos34->SetBinContent(ipt,lResbos34->GetBinContent(ipt));
    hResbos35->SetBinContent(ipt,lResbos35->GetBinContent(ipt));
    hData->SetBinContent(ipt,lData->GetBinContent(ipt));
    hData->SetBinError(ipt,lData->GetBinError(ipt));
    
    hResbos29->SetBinError(ipt,lResbos29->GetBinError(ipt));
    hResbos30->SetBinError(ipt,lResbos30->GetBinError(ipt));
    hResbos31->SetBinError(ipt,lResbos31->GetBinError(ipt));
    hResbos32->SetBinError(ipt,lResbos32->GetBinError(ipt));
    hResbos33->SetBinError(ipt,lResbos33->GetBinError(ipt));
    hResbos34->SetBinError(ipt,lResbos34->GetBinError(ipt));
    hResbos35->SetBinError(ipt,lResbos35->GetBinError(ipt));
    
    hResbosLog29->SetBinContent(ipt,lResbos29->GetBinContent(ipt));
    hResbosLog30->SetBinContent(ipt,lResbos30->GetBinContent(ipt));
    hResbosLog31->SetBinContent(ipt,lResbos31->GetBinContent(ipt));
    hResbosLog32->SetBinContent(ipt,lResbos32->GetBinContent(ipt));
    hResbosLog33->SetBinContent(ipt,lResbos33->GetBinContent(ipt));
    hResbosLog34->SetBinContent(ipt,lResbos34->GetBinContent(ipt));
    hResbosLog35->SetBinContent(ipt,lResbos35->GetBinContent(ipt));
    hDataLog->SetBinContent(ipt,lData->GetBinContent(ipt));
    hDataLog->SetBinError(ipt,lData->GetBinError(ipt));
  }
  
  hResbos29->Write();
  hResbos30->Write();
  hResbos31->Write();
  hResbos32->Write();
  hResbos33->Write();
  hResbos34->Write();
  hResbos35->Write();

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

  tmpTStr = BaseName+"_ResbosComp_Lin";
  pltComp = new CPlot(tmpTStr,"","W p_{T} [Gev]","Xsec [pb]");
  pltComp->setOutDir(resultDir);
  pltComp->AddHist1D(hResbos29,"Resbos grid29","HIST",3,1,0);
  pltComp->AddHist1D(hResbos30,"Resbos grid30","HIST",2,1,0);
  pltComp->AddHist1D(hResbos31,"Resbos grid31","HIST",4,1,0);
  pltComp->AddHist1D(hResbos32,"Resbos grid32","HIST",5,1,0);
  pltComp->AddHist1D(hResbos33,"Resbos grid33","HIST",6,1,0);
  pltComp->AddHist1D(hResbos34,"Resbos grid34","HIST",9,1,0);
  pltComp->AddHist1D(hResbos35,"Resbos grid35","HIST",7,1,0);
  pltComp->AddHist1D(hData,"Unfolded","E");
  pltComp->AddTextBox(BaseName,0.7,0.6,.9,0.63,0,1,0);
  pltComp->SetLegend(0.7,0.65,.9,0.88);
  pltComp->Draw(c1,kTRUE,"png");
  
  tmpTStr = BaseName+"_ResbosComp_Log";
  pltCompLog = new CPlot(tmpTStr,"","W p_{T} [Gev]","Xsec [pb]");
  pltCompLog->setOutDir(resultDir);
  pltCompLog->AddHist1D(hResbosLog29,"Resbos grid29","HIST",3,1,0);
  pltCompLog->AddHist1D(hResbosLog30,"Resbos grid30","HIST",2,1,0);
  pltCompLog->AddHist1D(hResbosLog31,"Resbos grid31","HIST",4,1,0);
  pltCompLog->AddHist1D(hResbosLog32,"Resbos grid32","HIST",5,1,0);
  pltCompLog->AddHist1D(hResbosLog33,"Resbos grid33","HIST",6,1,0);
  pltCompLog->AddHist1D(hResbosLog34,"Resbos grid34","HIST",9,1,0);
  pltCompLog->AddHist1D(hResbosLog35,"Resbos grid35","HIST",7,1,0);
  pltCompLog->AddHist1D(hDataLog,"Unfolded","E");
  pltCompLog->AddTextBox(BaseName,0.7,0.6,.9,0.63,0,1,0);
  pltCompLog->SetLegend(0.7,0.65,.9,0.88);
  pltCompLog->SetLogx();
  pltCompLog->Draw(c1,kTRUE,"png");
  return 0;
}
void drawQGFraction(){

	const double PI = 3.14159;

	TChain *mix = new TChain("mixing_tree");
	mix->Add("/data/kurtjung/JetTrackCorr_skims/2p76TeV_MC_Pythia6/MergedPythia_withPartonFlavor.root");
	//mix->Add("/data/kurtjung/JetTrackCorr_skims/5TeV_MC_Pythia6/*");

	//double xsecs[11] = {5.335E-01, 3.378E-02, 3.778E-03, 4.412E-04, 6.147E-05, 1.018E-05, 2.477E-06, 6.160E-07, 1.088E-07, 3.216E-08, 0}; //pythia6 5.02 tev weights
    double xsecs[11] = {2.043e-01, 1.075E-02, 1.025E-03, 9.865E-05, 1.129E-05, 1.465E-06, 2.837E-07, 5.323E-08, 5.934e-09, 8.125e-10, 0}; //2.76 tev weights
	int recalculatedEntries[10] = {0,0,0,0,0,0,0,0,0,0};
	double pthatbins[11] = {15,30,50,80,120,170,220,280,370,460,9999};

	TFile *fout = new TFile("QGFrac_pythia6_2p76TeV.root","recreate");

	TH1D *quarkFracIncl = new TH1D("quarkFracIncl","",20,120,500); quarkFracIncl->Sumw2();
	TH1D *glueFracIncl = new TH1D("glueFracIncl","",20,120,500); glueFracIncl->Sumw2();
	TH1D *inclJets = new TH1D("inclJets","",20,120,500); inclJets->Sumw2();

	TH1D *quarkFracLead = new TH1D("quarkFracLead","",20,120,500); quarkFracLead->Sumw2();
	TH1D *glueFracLead = new TH1D("glueFracLead","",20,120,500); glueFracLead->Sumw2();
	TH1D *leadJets = new TH1D("leadJets","",20,120,500); leadJets->Sumw2();


	Int_t HBHENoiseFilterResultRun2Loose, pPAprimaryVertexFilter;
	vector<float> *calo_corrpt=0, *calo_jtphi=0;
	vector<int> *calo_refparton_flavor=0;
	float pthat;

	mix->SetBranchAddress("calo_corrpt",&calo_corrpt);
	mix->SetBranchAddress("calo_jtphi",&calo_jtphi);
	mix->SetBranchAddress("calo_refparton_flavor",&calo_refparton_flavor);
	mix->SetBranchAddress("pthat",&pthat);

	mix->SetBranchAddress("HBHENoiseFilterResultRun2Loose",&HBHENoiseFilterResultRun2Loose);
	mix->SetBranchAddress("pPAprimaryVertexFilter",&pPAprimaryVertexFilter);


	TH1D *pthatHisto = new TH1D("pthatHisto","",10,pthatbins);
	mix->Project("pthatHisto","pthat");
	for(int i=0; i<10; i++){
		recalculatedEntries[i] = pthatHisto->GetBinContent(i+1);
		cout << "entries between pthat " << pthatbins[i] << " and " << pthatbins[i+1] << ": " << recalculatedEntries[i] << endl;
		cout << "weight: " << (xsecs[i]-xsecs[i+1])/recalculatedEntries[i] <<endl;
	}

	int totEntries = mix->GetEntries();
	cout << "entries: "<< totEntries << endl;
	totEntries=100000;
	for(int ievt=0; ievt<totEntries; ievt++){
		mix->GetEntry(ievt);
		if(ievt && ievt%10000==0) cout << "entry: " << ievt << endl;

		//if(!HBHENoiseFilterResultRun2Loose || !pPAprimaryVertexFilter) continue;

		int ibin=0;
		double weight=0.;
		while(pthat>pthatbins[ibin]) ibin++;
		ibin--;
		weight = (xsecs[ibin]-xsecs[ibin+1])/recalculatedEntries[ibin];
		if(weight>1){ 
			cout << "xsec: "<< xsecs[ibin]-xsecs[ibin+1] << " entries: " << recalculatedEntries[ibin] << endl;
			cout << "pthat: "<< pthat << " bin " << ibin << endl;
		}
		
		for(unsigned int ijet=0; ijet<calo_corrpt->size(); ijet++){
			
			if(abs(calo_refparton_flavor->at(ijet))>0 && abs(calo_refparton_flavor->at(ijet))<6) quarkFracIncl->Fill(calo_corrpt->at(ijet), weight);
			if(abs(calo_refparton_flavor->at(ijet))==21){ glueFracIncl->Fill(calo_corrpt->at(ijet), weight); }
			inclJets->Fill(calo_corrpt->at(ijet), weight);

			if(ijet==0 && calo_corrpt->size()>1){
				double dphi = abs(calo_jtphi->at(0) - calo_jtphi->at(1));
				if(dphi>(7*PI/8.) && dphi<(9*PI/8.) && calo_corrpt->at(1)>50) {

					if(abs(calo_refparton_flavor->at(ijet))>0 && abs(calo_refparton_flavor->at(ijet))<6) quarkFracLead->Fill(calo_corrpt->at(ijet), weight);
					if(abs(calo_refparton_flavor->at(ijet))==21) glueFracLead->Fill(calo_corrpt->at(ijet), weight);
					leadJets->Fill(calo_corrpt->at(ijet), weight);

				}
			}
		}
	}

	//quarkFracLead->Divide(leadJets);
	//glueFracLead->Divide(leadJets);

	//quarkFracIncl->Divide(inclJets);
	//glueFracIncl->Divide(inclJets);

	fout->cd();

	formatHisto(quarkFracLead,1);
	formatHisto(glueFracLead,2);
	formatHisto(quarkFracIncl,4);
	formatHisto(glueFracIncl,8);

	quarkFracLead->Write();
	glueFracLead->Write();
	quarkFracIncl->Write();
	glueFracIncl->Write();
	leadJets->Write();
	inclJets->Write();

	fout->Close();

}
Esempio n. 14
0
TH1D* getSample(TString sample, int rebinFact, TString Obj, TString dir, bool ge4){
		
	TFile* file = new TFile();
	
	//cout << "file: " << "rootFilesV3/"+dir+"/"+ sample + "_5814pb_PFElectron_PFMuon_PF2PATJets_PFMET.root" << endl;
	
	if(dir == "central" || (dir == "Scale_up_tt" && sample != "TTJet") || (dir == "Scale_down_tt" && sample != "TTJet") || ((dir == "Scale_up" && sample != "WJetsToLNu") && (dir == "Scale_up"  && sample != "DYJetsToLL"))  || ((dir == "Scale_down" && sample != "WJetsToLNu") && (dir == "Scale_down"  && sample != "DYJetsToLL")) || (dir == "Match_up_tt" && sample != "TTJet") || (dir == "Match_down_tt" && sample != "TTJet") || ((dir == "Match_up" && sample != "WJetsToLNu") && (dir == "Match_up"  && sample != "DYJetsToLL"))  || ((dir == "Match_down" && sample != "WJetsToLNu") && (dir == "Match_down"  && sample != "DYJetsToLL")) || dir == "UnclusteredEnUp" || dir == "UnclusteredEnDown" || dir == "JetEnUp" || dir == "JetEnDown" || dir == "JetResUp" || dir == "JetResDown" || dir == "TauEnUp" || dir == "TauEnDown" || dir == "MuonEnUp" || dir == "MuonEnDown" || dir == "ElectronEnUp" || dir == "ElectronEnDown"){
	file = new TFile("rootFilesV4/central/"+ sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	}else if(dir == "JES_up")
	file = new TFile("rootFilesV4/"+ dir +"/"+ sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_plusJES.root");
	else if(dir == "JES_down")
	file = new TFile("rootFilesV4/"+ dir +"/"+ sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_minusJES.root");
	else if(dir == "BJet_up")
	file = new TFile("rootFilesV4/"+ dir +"/"+ sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_plusBjet.root");
	else if(dir == "BJet_down")
	file = new TFile("rootFilesV4/"+ dir +"/"+ sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_minusBJet.root");
	else if(dir == "PU_up")
	file = new TFile("rootFilesV4/"+ dir +"/"+ sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_PU_72765mb.root");
	else if(dir == "PU_down")
	file = new TFile("rootFilesV4/"+ dir +"/"+ sample + "_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_PU_65835mb.root");
	else if(dir == "Scale_up_tt" && sample == "TTJet")
	file = new TFile("rootFilesV4/central/TTJets-scaleup_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Scale_down_tt" && sample == "TTJet")
	file = new TFile("rootFilesV4/central/TTJets-scaledown_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Scale_up" && sample == "WJetsToLNu")
	file = new TFile("rootFilesV4/central/WJets-scaleup_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Scale_up" && sample == "DYJetsToLL")
	file = new TFile("rootFilesV4/central/ZJets-scaleup_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Scale_down" && sample == "WJetsToLNu")
	file = new TFile("rootFilesV4/central/WJets-scaledown_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Scale_down" && sample == "DYJetsToLL")
	file = new TFile("rootFilesV4/central/ZJets-scaledown_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Match_up_tt" && sample == "TTJet")
	file = new TFile("rootFilesV4/central/TTJets-matchingup_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Match_down_tt" && sample == "TTJet")
	file = new TFile("rootFilesV4/central/TTJets-matchingdown_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Match_up" && sample == "WJetsToLNu")
	file = new TFile("rootFilesV4/central/WJets-matchingup_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Match_up" && sample == "DYJetsToLL")
	file = new TFile("rootFilesV4/central/ZJets-matchingup_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Match_down" && sample == "WJetsToLNu")
	file = new TFile("rootFilesV4/central/WJets-matchingdown_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(dir == "Match_down" && sample == "DYJetsToLL")
	file = new TFile("rootFilesV4/central/ZJets-matchingdown_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET.root");
	else if(sample == "TTJet_MCNLO")
	file = new TFile("rootFilesV4/central/TTJet_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_MCatNLO.root");
	else if(sample == "TTJet_POWHEG")
	file = new TFile("rootFilesV4/central/TTJet_19584pb_PFElectron_PFMuon_PF2PATJets_PFMET_POWHEG.root");
	
	TH1D* plot; 
	TH1D* plot2;
	TH1D* plot3;
	TH1D* plot4;
	TH1D* plot5;
	
	
	cout<< "folder: " << "TTbar_plus_X_analysis/MuPlusJets/Ref selection/"+Obj+"/muon_absolute_eta_2btags" << endl;
	
	plot = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/Ref selection/"+Obj+"/muon_absolute_eta_2btags");
	plot2 = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/Ref selection/"+Obj+"/muon_absolute_eta_3btags");
	plot3 = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/Ref selection/"+Obj+"/muon_absolute_eta_4orMoreBtags");
	plot4 = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/Ref selection/"+Obj+"/muon_absolute_eta_0btag");
	plot5 = (TH1D*) file->Get("TTbar_plus_X_analysis/MuPlusJets/Ref selection/"+Obj+"/muon_absolute_eta_1btag");		
	plot->Sumw2();
	plot2->Sumw2();
	plot3->Sumw2();
	plot4->Sumw2();
	plot5->Sumw2();
	
	plot->Add(plot2);
	plot->Add(plot3);
	
	if(ge4 ==true){
	plot->Add(plot4);
	plot->Add(plot5);
	}
	
        if(dir == "central"){
	//plot->SetFillColor(kRed+1);
        plot->SetLineColor(kRed+1);
	}else if(dir == "JES_up"){
	plot->SetLineColor(kGreen-3);	  
  	//plot->SetFillColor(kGreen-3);
	}else if(dir == "JES_down"){
	//plot->SetFillColor(kAzure-2);
	plot->SetLineColor(kAzure-2);
	}
	
	plot->Scale(1/plot->Integral());
	plot->Rebin(rebinFact);
	
	plot->SetDirectory(gROOT);
	
	file->Close();
	return plot;

}
Esempio n. 15
0
TH1D * fillPlot2012_gammaJets::Plot(string var, string name, int nbin, double min, double max, int signal) {
  
  Long64_t nentries = fChain->GetEntriesFast();
  Long64_t nbytes = 0, nb = 0;
  
  TH1D * tempplot = new TH1D(name.c_str(),name.c_str(),nbin,min,max);
  tempplot->Sumw2();

  ofstream outfile;

  if (writetxt != "") {
    string filename(writetxt);
    outfile.open(filename.c_str()); 
  }

  // photonID MVA
  tmvaReaderID_Single_Endcap=0;
  tmvaReaderID_Single_Barrel=0;
  if (!tmvaReaderID_Single_Barrel || !tmvaReaderID_Single_Endcap) SetAllMVA();  

  // Loop over entries
  int enMax = nentries; 
  for (Long64_t jentry=0; jentry<enMax;jentry++) {
    Long64_t ientry = LoadTree(jentry);

    if (jentry%100000==0) cout << jentry << endl;

    if (ientry < 0) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;

    // patological events
    if (npu>=60) continue;    

    // test to remove possible duplicated events between samples
    // if ( signal<6 && (ISRGamma>0 || FSRGamma>0) ) continue; // chiara

    // first vertex must be good
    if (vtxId<0) continue;

    // HLT selection - for data only
    if ( signal==100 && hltcut==30 && !isHLT_30() )  continue;
    if ( signal==100 && hltcut==50 && !isHLT_50() )  continue;
    if ( signal==100 && hltcut==75 && !isHLT_75() )  continue;
    if ( signal==100 && hltcut==90 && !isHLT_90() )  continue;

    // vector with index of fully selected gammas
    vector<int> fullSelected;

    // apply the full cut based photonID selection (medium WP)
    // https://twiki.cern.ch/twiki/bin/view/CMS/CutBasedPhotonID2012
    float EA_chargedH[7] = { 0.012, 0.010, 0.014, 0.012, 0.016, 0.020, 0.012};
    float EA_neutralH[7] = { 0.030, 0.057, 0.039, 0.015, 0.024, 0.039, 0.072};
    float EA_photons[7]  = { 0.148, 0.130, 0.112, 0.216, 0.262, 0.260, 0.266};

    int theNumber = nPhot_presel;
    if (nPhot_presel>100) theNumber = 100;
    for (int theGamma=0; theGamma<theNumber; theGamma++) {

      // for effective area calculation
      int theEAregion = effectiveAreaRegion(etaPhot_presel[theGamma]); 
      if (theEAregion>6) continue;

      // ---------------------------------------------------------------------------
      // preselection to really emulate the single gamma HLT requirements (current preselection is H->gg one)
      bool isReallyPresel = true;      
      float preselECAL    = pid_jurECAL03_presel[theGamma]  - 0.012*ptPhot_presel[theGamma];  
      float preselHCAL    = pid_twrHCAL03_presel[theGamma]  - 0.005*ptPhot_presel[theGamma]; 
      float preselTracker = pid_hlwTrack03_presel[theGamma] - 0.002*ptPhot_presel[theGamma]; 
      if ( preselECAL > 5.5)    isReallyPresel = false;
      if ( preselHCAL > 3.5)    isReallyPresel = false;
      if ( preselTracker > 3.5) isReallyPresel = false;
      if ( theEAregion<2) {  // EB
	if ( pid_HoverE_presel[theGamma]>0.15 )   isReallyPresel = false;       
	if ( sEtaEtaPhot_presel[theGamma]>0.024 ) isReallyPresel = false;
      } else {     // EE
	if(pid_HoverE_presel[theGamma]>0.10)      isReallyPresel = false;       
	if (sEtaEtaPhot_presel[theGamma]>0.040)   isReallyPresel = false;
      }
      if( !isReallyPresel ) continue;

      // ---------------------------------------------------------------------------
      /*
      // full 2012 egamma pog cut based selection
      bool isFullySel = true;

      // isolations corrected with effective areas
      float rhoCorrCharged = pid_pfIsoCharged03ForCiC_presel[theGamma] - rhoAllJets*EA_chargedH[theEAregion];   
      float rhoCorrNeutral = pid_pfIsoNeutrals03ForCiC_presel[theGamma] - rhoAllJets*EA_neutralH[theEAregion];
      float rhoCorrPhoton  = pid_pfIsoPhotons03ForCiC_presel[theGamma] - rhoAllJets*EA_photons[theEAregion];
      if (rhoCorrCharged<0) rhoCorrCharged = 0.;
      if (rhoCorrNeutral<0) rhoCorrNeutral = 0.;
      if (rhoCorrPhoton<0)  rhoCorrPhoton  = 0.;

      // if(pid_hasMatchedPromptElephot[theGamma]) isFullySel = false;   // already applied at preselection level
      if (pid_HoverE_presel[theGamma]>0.05)     isFullySel = false;       
      if (theEAregion<2) {  // EB
	if (sEtaEtaPhot_presel[theGamma]>0.011) isFullySel = false;
	if (rhoCorrCharged > 1.5)               isFullySel = false;
	if (rhoCorrNeutral > 1.0 + 0.04*ptPhot_presel[theGamma])  isFullySel = false;
	if (rhoCorrPhoton  > 0.7 + 0.005*ptPhot_presel[theGamma]) isFullySel = false;
      } else {     // EE
	if (sEtaEtaPhot_presel[theGamma]>0.033) isFullySel = false;
	if (rhoCorrCharged > 1.2)               isFullySel = false;
	if (rhoCorrNeutral > 1.5 + 0.04*ptPhot_presel[theGamma])  isFullySel = false;
	if (rhoCorrPhoton  > 1.0 + 0.005*ptPhot_presel[theGamma]) isFullySel = false;
      }
      if( !isFullySel ) continue;
      */

      // photon ID MVA
      // float theIdMva = PhotonIDMVA(theGamma);

      fullSelected.push_back(theGamma); 
    }

    // choose the two highest pT preselected gammas 
    // if (fullSelected.size()<2) continue;            // chiara: per check Z
    if (fullSelected.size()<1) continue;
    int firstG = -1;
    int secG   = -1;
    float firstGpt  = -999.;
    float secGpt    = -1000.;
    float firstGeta = -999.;
    for (int ii=0; ii<fullSelected.size(); ii++) {
      int index = fullSelected[ii];
      if (ptPhot_presel[index]>firstGpt) {
	secGpt    = firstGpt;
	firstGpt  = ptPhot_presel[index];
	firstGeta = etaPhot_presel[index];
	secG      = firstG;
	firstG    = index;
      } else if (ptPhot_presel[index]>secGpt) {
	secGpt = ptPhot_presel[index];
	secG   = index;
      }
    } 

    // ptcut to restrict to the wanted range - matching HLT
    if (firstGpt<ptphot1_mincut) continue;	
    if (firstGpt>ptphot1_maxcut) continue;	

    // make the invariant mass of the two highest pT photons
    TLorentzVector gamma1, gamma2;
    gamma1.SetPtEtaPhiM(ptPhot_presel[firstG],etaPhot_presel[firstG],phiPhot_presel[firstG],0.);
    gamma2.SetPtEtaPhiM(ptPhot_presel[secG],etaPhot_presel[secG],phiPhot_presel[secG],0.);
    float invMass = (gamma1+gamma2).M();

    // only for Z studies
    // if (invMass>110 || invMass<70) continue;         // chiara: per check Z

    // for ID variables, splitting EB/EE
    if (var == "HoE_EB"         && fabs(firstGeta)>1.5) continue;
    if (var == "HoE_EE"         && fabs(firstGeta)<1.5) continue;
    if (var == "sigmaIeIe_EB"   && fabs(firstGeta)>1.5) continue;
    if (var == "sigmaIeIe_EE"   && fabs(firstGeta)<1.5) continue;
    if (var == "photonIdMva_EB" && fabs(firstGeta)>1.5) continue;
    if (var == "photonIdMva_EE" && fabs(firstGeta)<1.5) continue;

    // finding variable to be plotted
    double variable(0);
    if (var == "nvtx") variable = nvtx;
    else if (var == "ngamma")    variable = nPhot_presel;
    else if (var == "sigmaIeIe") variable = sEtaEtaPhot_presel[firstG];
    else if (var == "sigmaIeIe_EB") variable = sEtaEtaPhot_presel[firstG];
    else if (var == "sigmaIeIe_EE") variable = sEtaEtaPhot_presel[firstG];
    else if (var == "HoE")       variable = pid_HoverE_presel[firstG]; 
    else if (var == "HoE_EB")    variable = pid_HoverE_presel[firstG]; 
    else if (var == "HoE_EE")    variable = pid_HoverE_presel[firstG]; 
    else if (var == "photonIdMva")    variable = PhotonIDMVA(firstG);
    else if (var == "photonIdMva_EB") variable = PhotonIDMVA(firstG);
    else if (var == "photonIdMva_EE") variable = PhotonIDMVA(firstG);
    else if (var == "chargedIso") variable = pid_pfIsoCharged03ForCiC_presel[firstG];
    else if (var == "neutralIso") variable = pid_pfIsoNeutrals03ForCiC_presel[firstG];
    else if (var == "gammaIso") variable   = pid_pfIsoPhotons03ForCiC_presel[firstG];
    else if (var == "etaL") variable = gamma1.Eta();
    else if (var == "ptL")  variable = firstGpt;
    else if (var == "mass") variable = invMass;
    else{
      cout << "NO SUCH VARIABLE IMPLEMENTED!" << endl;
      break;
    }
    
    // pu/pt reweighting
    float weight(1);
    if (dopureweight && hltcut==30) weight *= pu_weight30;
    if (dopureweight && hltcut==50) weight *= pu_weight50;
    if (dopureweight && hltcut==75) weight *= pu_weight75;
    if (dopureweight && hltcut==90) weight *= pu_weight90;
    tempplot->Fill(variable, weight);
  }
  
  if (writetxt != "")  outfile.close(); 

  return tempplot;
}
Esempio n. 16
0
void QCDxcheck_shape() {

    setTDRStyle();

//MET will need choice of variable at the top
//  TString Variable = "MET";
//  int Nbins = 6;
//  TString bins[6] = {"_bin_0-25", "_bin_25-45", "_bin_45-70", "_bin_70-100", "_bin_100-150", "_bin_150-inf"};
//  double xbins[7] = {0,25,45,70,100,150, 250};
//  TString Xtitle = "E_{T}^{miss} ";

    TString Variable ="WPT";
    int Nbins = 6;
    TString bins[6] = {"_bin_0-40", "_bin_40-70", "_bin_70-100", "_bin_100-130", "_bin_130-170", "_bin_170-inf"};
    double xbins[7] = {1,40,70,100,130,170,220};
    TString Xtitle = "p_{T}(W)";

//  TString Variable ="MT";
//  int Nbins = 5;
//  TString bins[5] = {"_bin_0-30", "_bin_30-50", "_bin_50-80", "_bin_80-100", "_bin_100-inf"};
//  double xbins[6] = {1,30,50,80,100,150};
//  TString Xtitle = "M(W)_{T}";

//  TString Variable ="ST";
//  int Nbins = 7;
//  TString bins[7] = {"_bin_0-350","_bin_350-400", "_bin_400-450", "_bin_450-500", "_bin_500-580", "_bin_580-700", "_bin_700-inf"};
//  double xbins[8] = {1,350,400,450,500,580,700,1000};
//  TString Xtitle = "S_{T}";

// TString Variable ="HT";
// int Nbins = 7;
// TString bins[7] = {"_bin_0-240", "_bin_240-280", "_bin_280-330", "_bin_330-380", "_bin_380-450", "_bin_450-600", "_bin_600-inf"};
// double xbins[8] = {1,240,280,330,380,450,600,800};
// TString Xtitle = "H_{T}";

    //differential histo
    TH1D *qcd_data = new TH1D("qcd data", "", Nbins, xbins);


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

        TString Obj;

        if(Variable == "MET") {
            Obj = "Binned_"+Variable+"_Analysis/patType1CorrectedPFMet"+bins[i]+"/muon_absolute_eta_";
        } else if(Variable == "HT") {
            Obj = "Binned_"+Variable+"_Analysis/HT"+bins[i]+"/muon_absolute_eta_";
        } else {
            Obj = "Binned_"+Variable+"_Analysis/"+Variable+"_with_patType1CorrectedPFMet"+bins[i]+"/muon_absolute_eta_";
        }

        double error;

        double content = getQCD(Variable, Obj, 1, &error);
        qcd_data->SetBinContent(i+1, content);
        qcd_data->SetBinError(i+1, error);

    }

    qcd_data->Sumw2();
    qcd_data->Scale(1./qcd_data->Integral());

    for(int i = 0; i < Nbins; i++) {
        cout << qcd_data->GetBinContent(i+1) << ", ";

    }

    cout << " " << endl;

//get fit results
    TFile* fit_file = new TFile("outFiles/diffResults_"+Variable+"_bin_0-40.root");
    TH1D*  fit = (TH1D*) fit_file->Get("central_dir/central_qcd_fit");
    fit->SetLineColor(kRed);
    fit->SetMarkerColor(kRed);
    fit->SetMarkerSize(0.1);
    fit->Sumw2();
    fit->Scale(1./fit->Integral());

    TFile* fit_200f = new TFile("outFiles/diffResults_"+Variable+".root");
    TH1D*  fit_200 = (TH1D*) fit_200f->Get("central_dir/central_qcd_fit");
    fit_200->SetLineColor(kGreen);
    fit_200->SetMarkerColor(kGreen);
    fit_200->SetMarkerSize(0.1);
    fit_200->Sumw2();
    fit_200->Scale(1./fit_200->Integral());

    TFile* fit_noconf = new TFile("outFiles/diffResults_"+Variable+"_bin_100-130.root");
    TH1D*  fit_nocon = (TH1D*) fit_noconf->Get("central_dir/central_qcd_fit");
    fit_nocon->SetLineColor(kMagenta);
    fit_nocon->SetMarkerColor(kMagenta);
    fit_nocon->SetMarkerSize(0.1);
    fit_nocon->Sumw2();
    fit_nocon->Scale(1./fit_nocon->Integral());

    TFile* fit_dataf = new TFile("outFiles/diffResults_"+Variable+"_bins.root");
    TH1D*  fit_data = (TH1D*) fit_dataf->Get("central_dir/central_qcd_fit");
    fit_data->SetLineColor(kYellow);
    fit_data->SetMarkerColor(kYellow);
    fit_data->Sumw2();
    fit_data->Scale(1./fit_data->Integral());

    TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);

//qcd_data->Draw("E");
//qcd_data->SetAxisRange(MinXs[3], MaxXs[3], "X");


    fit_200->Draw("E1");
    fit->Draw("E1same");
    fit_data->Draw("E1same");
    fit_nocon->Draw("E1same");
//qcd_data->Draw("E1same");

    TLegend *tleg;
    tleg = new TLegend(0.45,0.55,0.85,0.9);
    tleg->SetTextSize(0.03);
    tleg->SetBorderSize(0);
    tleg->SetFillColor(10);

    //tleg->AddEntry(qcd_data  , "Data Driven E_{T}^{miss} (QCD non-iso)"      , "lep");
    tleg->AddEntry(fit_data  , "Fit Results, different bins "      , "lep");
    tleg->AddEntry(fit  , "Fit Results, |#eta| from WPT 0-40"      , "lep");
    tleg->AddEntry(fit_200  , "Fit Results, nominal |#eta|"      , "lep");
    tleg->AddEntry(fit_nocon  , "Fit Results, |#eta| from WPT 100-130"      , "lep");

    tleg->Draw();



    fit_200->GetYaxis()->SetTitle("Normalised Events");
    fit_200->GetYaxis()->SetTitleSize(0.05);
    fit_200->GetXaxis()->SetTitle(Xtitle+" [GeV]");
    fit_200->GetXaxis()->SetTitleSize(0.05);

    TText* textPrelim = doPrelim(0.12,0.96);
    textPrelim->Draw();

    c1->SaveAs("plots/QCDxcheck_shape/"+Variable+"shapecheck.png");

}
Esempio n. 17
0
void plotTurnonCurve(char* var, double min, double max, int NPVmin=0, int NPVmax=50) {
  
  TString path("./uct15-plots/turnon/Taus/noPUC/isoStudies");
  
  float PUcut = 1.0;
  
  TFile * f1;
  
  if( 1 ) {
    
    f1 =  TFile::Open("/uscms_data/d2/aosorio/scratch0/UCT2015_BKP/root_files/uct_eff_trees_mutau_BC.root");

  } 

  TTree* tree1 = (TTree*) gDirectory->Get("rlxTauEfficiency/Ntuple");
    
  int nBins = 10;
  if(var=="Pt") nBins = (int) ((max - min) / 2);
  if(var=="Eta") nBins = (int) ((max - min) / 0.5);

  nBins = 20;

  double RecoPtmin = 0.0;
  
  ////////////////////////////////////////////////////////////////////////////////
  // read the same selection used for the Rate/Efficiency plots
  //
  int lineWidth = 2;

  std::ifstream *m_in = new std::ifstream("config/efficiency_TS_WP_WI_Selection.dat");
  
  if ( !m_in->is_open() ) {
    std::cout << " I could not open this file" << std::endl;
    exit(1);
  }
  
  TList * v_Selection = new TList();
  
  char line[256];
  while(1) {
    
    m_in->getline( line, 256 );
    TObjString *selection = new TObjString( line );
    v_Selection->Add( selection );
    if ( m_in->eof() ) break;
    
  }
  
  v_Selection->RemoveLast();

  TList * v_Labels = new TList();
  
  TObjString *label;
  label = new TObjString( "L1 Upgrade Tau" );
  v_Labels->Add( label ); 
  label = new TObjString( "L1 Upgrade Iso Tau" );
  v_Labels->Add( label ); 

  ////////////////////////////////////////////////////////////////////////////////
  //This is the standard cut based on nPVS
  
  char cuts[100];
  sprintf(cuts, " l1gMatch && recoPt > %d ", NPVmin, NPVmax, RecoPtmin);
  
  int min_sel = 0; 
  int max_sel = v_Selection->GetEntries();

  max_sel = 1; //Only focus on the relaxed tau plots - they go to TDR

  for( int k = min_sel; k < max_sel; ++k ) {
    
    TString egsel = ((TObjString*)v_Selection->At(k))->GetString();
    
    std::cout << egsel.Data() << std::endl;
    
    ///// ----- Create all the histograms ----------
    TH1D* allReco = new TH1D("allReco", "", nBins, min, max);
    allReco->SetLineWidth(2);
    allReco->Sumw2();
    
    TH1D* l1Pt20 = allReco->Clone("l1Pt20");
    if(var=="Pt") l1Pt20->GetYaxis()->SetRangeUser(0.0, 1.1);
    if(var=="Eta") l1Pt20->GetYaxis()->SetRangeUser(0.55, 1.05);
    
    l1Pt20->GetYaxis()->SetTitle("Efficiency");
    char* xtitle = var;
    if(var=="Pt") xtitle = "Offline tau p_{T} [GeV]";
    if(var=="Eta") xtitle = "Offline tau #eta";
    l1Pt20->GetXaxis()->SetTitle(xtitle);
    l1Pt20->GetXaxis()->SetTitleOffset(1.3);
    l1Pt20->SetMinimum(0.);
    l1Pt20->SetMaximum(1.2);

    
    TH1D* l1Pt25 = allReco->Clone("l1Pt25");
    l1Pt25->SetLineColor(6);
    l1Pt25->SetMarkerColor(6);
    
    TH1D* l1Pt30 = allReco->Clone("l1Pt30");
    l1Pt30->SetLineColor(7);
    l1Pt30->SetMarkerColor(7);
    TString varName = TString("reco") + TString(var);
    
    TH1D* l1Pt40 = allReco->Clone("l1Pt40");
    l1Pt40->SetLineColor(8);
    l1Pt40->SetMarkerColor(8);
    TString varName = TString("reco") + TString(var);
    
    TH1D* l1Pt60 = allReco->Clone("l1Pt60");
    l1Pt60->SetLineColor(2);
    l1Pt60->SetMarkerColor(2);
    TString varName = TString("reco") + TString(var);
    
    ///// ----- Draw from tree ----------
    tree1->Draw(varName+TString(">>allReco"),cuts,"goff");
    tree1->Draw(varName+TString(">>l1Pt20"),TString(cuts)+TString(" && l1gPt>20. && ")+egsel,"goff");
    tree1->Draw(varName+TString(">>l1Pt25"),TString(cuts)+TString(" && l1gPt>25. && ")+egsel,"goff");
    tree1->Draw(varName+TString(">>l1Pt30"),TString(cuts)+TString(" && l1gPt>30. && ")+egsel,"goff");
    tree1->Draw(varName+TString(">>l1Pt40"),TString(cuts)+TString(" && l1gPt>40. && ")+egsel,"goff");
    tree1->Draw(varName+TString(">>l1Pt60"),TString(cuts)+TString(" && l1gPt>60. && ")+egsel,"goff");
    
    //// ---- Now divide by allReco histogram to obtain efficiency ----
    l1Pt20->Divide(allReco);
    l1Pt25->Divide(allReco);
    l1Pt30->Divide(allReco);
    l1Pt40->Divide(allReco);
    l1Pt60->Divide(allReco);
    
    
    
    TCanvas* canEffIso = new TCanvas("canEffIso","",500,500);
    l1Pt20->Draw("e");
    l1Pt20->Draw("hist same");
    l1Pt25->Draw("esame");
    l1Pt25->Draw("hist same");
    l1Pt30->Draw("esame");
    l1Pt30->Draw("hist same");
    l1Pt40->Draw("esame");
    l1Pt40->Draw("hist same");
    l1Pt60->Draw("esame");
    l1Pt60->Draw("hist same");
    
    TString legend_Label = ((TObjString*)v_Labels->At(k))->GetString();

    TLegend* legend = new TLegend(0.5,0.22,0.9,0.45);
    legend->SetFillColor(0);
    legend->SetBorderSize(0);
    legend->SetTextFont(62);
    legend->SetTextSize(0.034);
    legend->AddEntry(l1Pt20, "L1 p_{T} > 20 GeV", "PLE"); 
    legend->AddEntry(l1Pt25, "L1 p_{T} > 25 GeV", "PLE"); 
    legend->AddEntry(l1Pt30, "L1 p_{T} > 30 GeV", "PLE"); 
    legend->AddEntry(l1Pt40, "L1 p_{T} > 40 GeV", "PLE"); 
    legend->AddEntry(l1Pt60, "L1 p_{T} > 60 GeV", "PLE"); 
    legend->Draw();
    cmsPrelim();
    canEffIso->SetGridx();
    canEffIso->SetGridy();

    TLatex * tex = new TLatex(15.4, 1.1, legend_Label.Data() );
    tex->SetTextFont(42);
    tex->SetLineWidth(2);
    tex->Draw();

    canEffIso->Modified();

    std::stringstream saveAs;
    
    saveAs.str("");
    saveAs << path << "/eps/rlx_tau_eff_trg20_WP_" << varName << "_" << NPVmin << "_" << NPVmax << "_" << k << "_" << PUcut 
	   << "_" << lineWidth << ".eps";
    canEffIso->SaveAs( saveAs.str().c_str() );

    saveAs.str("");
    saveAs << path << "/eps/rlx_tau_eff_trg20_WP_" << varName << "_" << NPVmin << "_" << NPVmax << "_" << k << "_" << PUcut 
	   << "_" << lineWidth << ".pdf";
    canEffIso->SaveAs( saveAs.str().c_str() );
    
    saveAs.str("");
    saveAs << path << "/png/rlx_tau_eff_trg20_WP_" << varName << "_" << NPVmin << "_" << NPVmax << "_" << k << "_" << PUcut 
	   << "_" << lineWidth << ".png";
    canEffIso->SaveAs( saveAs.str().c_str() );
    
    //--------- Finally clean up the memory -------
    delete allReco;
    delete l1Pt20;
    delete l1Pt25;
    delete l1Pt30;
    delete l1Pt40;
    delete l1Pt60;
    delete canEffIso;
    delete legend;
    
  }

  

  
}
Esempio n. 18
0
void secondJet(const std::string& dataset, std::string algoType, std::string partonType="ALL") {

  PARTONTYPE = partonType;

  std::string infile_dataset = dataset;

  TChain* tree = new TChain("jetTree");
  
  std::string infileName;

  std::string prefix = "PhotonJet_2ndLevelTree_";
  std::string suffix = "_"+algoType;

  if( dataset=="PhotonJet") {

    tree->Add("PhotonJet_2ndLevelTree_PhotonJet15.root/jetTree");
    tree->Add("PhotonJet_2ndLevelTree_PhotonJet30.root/jetTree");
    tree->Add("PhotonJet_2ndLevelTree_PhotonJet80.root/jetTree");
    tree->Add("PhotonJet_2ndLevelTree_PhotonJet170.root/jetTree");
    tree->Add("PhotonJet_2ndLevelTree_PhotonJet300.root/jetTree");
    tree->Add("PhotonJet_2ndLevelTree_PhotonJet470.root/jetTree");
    tree->Add("PhotonJet_2ndLevelTree_PhotonJet800.root/jetTree");
    tree->Add("PhotonJet_2ndLevelTree_PhotonJet1400.root/jetTree");

  } else if( dataset=="PhotonJet_Summer09") {

    infileName = prefix + "PhotonJet_Summer09_Pt15" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;
    infileName = prefix + "PhotonJet_Summer09_Pt30" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;
    infileName = prefix + "PhotonJet_Summer09_Pt80" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;
    infileName = prefix + "PhotonJet_Summer09_Pt170" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;
    infileName = prefix + "PhotonJet_Summer09_Pt300" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;
    infileName = prefix + "PhotonJet_Summer09_Pt470" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;
    infileName = prefix + "PhotonJet_Summer09_Pt800" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;
    infileName = prefix + "PhotonJet_Summer09_Pt1400" + suffix + ".root/jetTree";
    tree->Add(infileName.c_str());
    std::cout << "-> Added " << infileName << ". Tree has " << tree->GetEntries() << " entries." << std::endl;

  } else {

    if( dataset=="" )
      infileName = "PhotonJet_2ndLevelTree.root/jetTree";
    else
      infileName = "PhotonJet_2ndLevelTree_"+infile_dataset+".root/jetTree";

    std::cout << "Opening file: " << infileName << std::endl;
    tree->Add(infileName.c_str());

  }

  if( NOEVENTWEIGHTS_ ) suffix = "_NOWEIGHTS" + suffix;


  bool draw=true;


  TH1D* h1_deltaR_phot_2ndJet = new TH1D("deltaR_phot_2ndJet", "", 100, 0., 1.);


  Float_t eventWeight;
  tree->SetBranchAddress("eventWeight", &eventWeight);
  Bool_t matchedToMC;
  tree->SetBranchAddress("matchedToMC", &matchedToMC);
  Bool_t passedPhotonID_medium;
  tree->SetBranchAddress("passedPhotonID_medium", &passedPhotonID_medium);

  Float_t ptHat;
  tree->SetBranchAddress("ptHat", &ptHat);

  Float_t ePhotReco;
  tree->SetBranchAddress("ePhotReco", &ePhotReco);
  Float_t ptPhotReco;
  tree->SetBranchAddress("ptPhotReco", &ptPhotReco);
  Float_t etaPhotReco;
  tree->SetBranchAddress("etaPhotReco", &etaPhotReco);
  Float_t phiPhotReco;
  tree->SetBranchAddress("phiPhotReco", &phiPhotReco);

  Float_t ePhotGen;
  tree->SetBranchAddress("ePhotGen", &ePhotGen);
  Float_t ptPhotGen;
  tree->SetBranchAddress("ptPhotGen", &ptPhotGen);
  Float_t etaPhotGen;
  tree->SetBranchAddress("etaPhotGen", &etaPhotGen);
  Float_t phiPhotGen;
  tree->SetBranchAddress("phiPhotGen", &phiPhotGen);

  Float_t hcalIsoPhotReco;
  tree->SetBranchAddress("hcalIsoPhotReco", &hcalIsoPhotReco);
  Float_t ecalIsoPhotReco;
  tree->SetBranchAddress("ecalIsoPhotReco", &ecalIsoPhotReco);
  Int_t nTrkIsoPhotReco;
  tree->SetBranchAddress("nTrkIsoPhotReco", &nTrkIsoPhotReco);
  Float_t ptTrkIsoPhotReco;
  tree->SetBranchAddress("ptTrkIsoPhotReco", &ptTrkIsoPhotReco);
  Float_t clusterMajPhotReco;
  tree->SetBranchAddress("clusterMajPhotReco", &clusterMajPhotReco);
  Float_t clusterMinPhotReco;
  tree->SetBranchAddress("clusterMinPhotReco", &clusterMinPhotReco);

  Float_t eJetReco;
  tree->SetBranchAddress("eJetReco", &eJetReco);
  Float_t ptJetReco;
  tree->SetBranchAddress("ptJetReco", &ptJetReco);
  Float_t etaJetReco;
  tree->SetBranchAddress("etaJetReco", &etaJetReco);
  Float_t phiJetReco;
  tree->SetBranchAddress("phiJetReco", &phiJetReco);
  Float_t eTracksReco;
  tree->SetBranchAddress("eTracksReco", &eTracksReco);

  Float_t eJetGen;
  tree->SetBranchAddress("eJetGen", &eJetGen);
  Float_t ptJetGen;
  tree->SetBranchAddress("ptJetGen", &ptJetGen);
  Float_t etaJetGen;
  tree->SetBranchAddress("etaJetGen", &etaJetGen);
  Float_t phiJetGen;
  tree->SetBranchAddress("phiJetGen", &phiJetGen);
  Float_t eTracksGen;
  tree->SetBranchAddress("eTracksGen", &eTracksGen);

  Float_t ptPart;
  tree->SetBranchAddress("ptPart", &ptPart);
  Float_t etaPart;
  tree->SetBranchAddress("etaPart", &etaPart);
  Float_t phiPart;
  tree->SetBranchAddress("phiPart", &phiPart);
  Int_t pdgIdPart;
  tree->SetBranchAddress("pdgIdPart", &pdgIdPart);

  Float_t pt2ndJetReco;
  tree->SetBranchAddress("pt2ndJetReco", &pt2ndJetReco);
  Float_t eta2ndJetReco;
  tree->SetBranchAddress("eta2ndJetReco", &eta2ndJetReco);
  Float_t phi2ndJetReco;
  tree->SetBranchAddress("phi2ndJetReco", &phi2ndJetReco);

  Float_t pt2ndJetGen;
  tree->SetBranchAddress("pt2ndJetGen", &pt2ndJetGen);
  Float_t eta2ndJetGen;
  tree->SetBranchAddress("eta2ndJetGen", &eta2ndJetGen);
  Float_t phi2ndJetGen;
  tree->SetBranchAddress("phi2ndJetGen", &phi2ndJetGen);

  Float_t ptSecondaryJetsReco;
  tree->SetBranchAddress("ptSecondaryJetsReco", &ptSecondaryJetsReco);
  Float_t ptSecondaryJetsGen;
  tree->SetBranchAddress("ptSecondaryJetsGen", &ptSecondaryJetsGen);



  Int_t nPoints = 5;

  //absolute 2nd jet pt binning histograms
  std::vector< std::vector< TH1D* > > h1_RecoPhot_vs_gen;
  std::vector< std::vector< TH1D* > > h1_RecoGen_vs_gen;
  std::vector< std::vector< TH1D* > > h1_GenPart_vs_gen;
  std::vector< std::vector< TH1D* > > h1_PartPhot_vs_gen;
  std::vector< std::vector< TH1D* > > h1_GenPhot_vs_gen;
  std::vector< std::vector< TH1D* > > h1_pt2ndJetGenMean;

  std::vector< std::vector< TH1D* > > h1_RecoPhot_vs_reco;
  std::vector< std::vector< TH1D* > > h1_RecoGen_vs_reco;
  std::vector< std::vector< TH1D* > > h1_GenPart_vs_reco;
  std::vector< std::vector< TH1D* > > h1_PartPhot_vs_reco;
  std::vector< std::vector< TH1D* > > h1_GenPhot_vs_reco;
  std::vector< std::vector< TH1D* > > h1_pt2ndJetRecoMean;

  //relative 2nd jet pt binning histograms
  std::vector< std::vector< TH1D* > > h1_RecoPhot_vs_genRel;
  std::vector< std::vector< TH1D* > > h1_RecoGen_vs_genRel;
  std::vector< std::vector< TH1D* > > h1_GenPart_vs_genRel;
  std::vector< std::vector< TH1D* > > h1_PartPhot_vs_genRel;
  std::vector< std::vector< TH1D* > > h1_GenPhot_vs_genRel;
  std::vector< std::vector< TH1D* > > h1_pt2ndJetGenRelMean;

  std::vector< std::vector< TH1D* > > h1_RecoPhot_vs_recoRel;
  std::vector< std::vector< TH1D* > > h1_RecoGen_vs_recoRel;
  std::vector< std::vector< TH1D* > > h1_GenPart_vs_recoRel;
  std::vector< std::vector< TH1D* > > h1_PartPhot_vs_recoRel;
  std::vector< std::vector< TH1D* > > h1_GenPhot_vs_recoRel;
  std::vector< std::vector< TH1D* > > h1_pt2ndJetRecoRelMean;

  //pt bins:
  //int nBins_pt = 24;
  int nBins_pt = 16;
  int i=0;

  Double_t Lower[nBins_pt];
  Lower[i++] = 20.;
  Lower[i++] = 42.;
  Lower[i++] = 62.;
  Lower[i++] = 87.;
  Lower[i++] = 108.;
  Lower[i++] = 140.;
  Lower[i++] = 183.;
  Lower[i++] = 239.;
  Lower[i++] = 312.;
  Lower[i++] = 407.;
  Lower[i++] = 530.;
  Lower[i++] = 691.;
  Lower[i++] = 902.;
  Lower[i++] = 1176.;
  Lower[i++] = 1533.;
  Lower[i++] = 2000.;

  //Lower[i++] = 97.;
  //Lower[i++] = 108.;
  //Lower[i++] = 121.;
  //Lower[i++] = 135.;
  //Lower[i++] = 152.;
  //Lower[i++] = 172.;
  //Lower[i++] = 197.;
  //Lower[i++] = 231.;
  //Lower[i++] = 283.;
  //Lower[i++] = 397.;
  //Lower[i++] = 600.;
  //Lower[i++] = 1000.;
  //Lower[i++] = 2000.;

  //Lower[i++] = 20.;
  //Lower[i++] = 25.;
  //Lower[i++] = 30.;
  //Lower[i++] = 36.;
  //Lower[i++] = 42.;
  //Lower[i++] = 48.;
  //Lower[i++] = 55.;
  //Lower[i++] = 62.;
  //Lower[i++] = 70.;
  //Lower[i++] = 78.;
  //Lower[i++] = 87.;
  //Lower[i++] = 97.;
  //Lower[i++] = 108.;
  //Lower[i++] = 121.;
  //Lower[i++] = 135.;
  //Lower[i++] = 152.;
  //Lower[i++] = 172.;
  //Lower[i++] = 197.;
  //Lower[i++] = 231.;
  //Lower[i++] = 283.;
  //Lower[i++] = 397.;
  //Lower[i++] = 600.;
  //Lower[i++] = 1000.;
  //Lower[i++] = 2000.;
  
  TH2D* h2_response_vs_ptPhot = new TH2D("response_vs_ptPhot", "", nBins_pt-1, Lower, 120, 0., 2.);
  h2_response_vs_ptPhot->Sumw2();

  TH2D* h2_ptPhotMean_vs_pt_cutOn2ndJet = new TH2D("ptPhotMean_vs_pt_cutOn2ndJet", "", nBins_pt-1, Lower, 2200, 0., 2200.);
  h2_ptPhotMean_vs_pt_cutOn2ndJet->Sumw2();


  //ptPhot TH2 for x-axis points on vs. pt spectra:
  TH2D* h2_ptPhotMean_vs_pt= new TH2D("ptPhotMean_vs_pt", "", nBins_pt-1, Lower, 2200, 0., 2200.);
  h2_ptPhotMean_vs_pt->Sumw2();


  Float_t minPt = 5.;
  Float_t ptStep = 5.;


  for( int i_ptBin=0; i_ptBin<nBins_pt; ++i_ptBin ) {

    std::vector< TH1D* > RecoPhot_vs_gen;
    h1_RecoPhot_vs_gen.push_back( RecoPhot_vs_gen );
    std::vector< TH1D* > RecoGen_vs_gen;
    h1_RecoGen_vs_gen.push_back( RecoGen_vs_gen );
    std::vector< TH1D* > GenPart_vs_gen;
    h1_GenPart_vs_gen.push_back( GenPart_vs_gen );
    std::vector< TH1D* > PartPhot_vs_gen;
    h1_PartPhot_vs_gen.push_back( PartPhot_vs_gen );
    std::vector< TH1D* > GenPhot_vs_gen;
    h1_GenPhot_vs_gen.push_back( GenPhot_vs_gen );
    std::vector< TH1D* > pt2ndJetGenMean;
    h1_pt2ndJetGenMean.push_back( pt2ndJetGenMean );

    std::vector< TH1D* > RecoPhot_vs_reco;
    h1_RecoPhot_vs_reco.push_back( RecoPhot_vs_reco );
    std::vector< TH1D* > RecoGen_vs_reco;
    h1_RecoGen_vs_reco.push_back( RecoGen_vs_reco );
    std::vector< TH1D* > GenPart_vs_reco;
    h1_GenPart_vs_reco.push_back( GenPart_vs_reco );
    std::vector< TH1D* > PartPhot_vs_reco;
    h1_PartPhot_vs_reco.push_back( PartPhot_vs_reco );
    std::vector< TH1D* > GenPhot_vs_reco;
    h1_GenPhot_vs_reco.push_back( GenPhot_vs_reco );
    std::vector< TH1D* > pt2ndJetRecoMean;
    h1_pt2ndJetRecoMean.push_back( pt2ndJetRecoMean );

    std::vector< TH1D* > RecoPhot_vs_genRel;
    h1_RecoPhot_vs_genRel.push_back( RecoPhot_vs_genRel );
    std::vector< TH1D* > RecoGen_vs_genRel;
    h1_RecoGen_vs_genRel.push_back( RecoGen_vs_genRel );
    std::vector< TH1D* > GenPart_vs_genRel;
    h1_GenPart_vs_genRel.push_back( GenPart_vs_genRel );
    std::vector< TH1D* > PartPhot_vs_genRel;
    h1_PartPhot_vs_genRel.push_back( PartPhot_vs_genRel );
    std::vector< TH1D* > GenPhot_vs_genRel;
    h1_GenPhot_vs_genRel.push_back( GenPhot_vs_genRel );
    std::vector< TH1D* > pt2ndJetGenRelMean;
    h1_pt2ndJetGenRelMean.push_back( pt2ndJetGenRelMean );

    std::vector< TH1D* > RecoPhot_vs_recoRel;
    h1_RecoPhot_vs_recoRel.push_back( RecoPhot_vs_recoRel );
    std::vector< TH1D* > RecoGen_vs_recoRel;
    h1_RecoGen_vs_recoRel.push_back( RecoGen_vs_recoRel );
    std::vector< TH1D* > GenPart_vs_recoRel;
    h1_GenPart_vs_recoRel.push_back( GenPart_vs_recoRel );
    std::vector< TH1D* > PartPhot_vs_recoRel;
    h1_PartPhot_vs_recoRel.push_back( PartPhot_vs_recoRel );
    std::vector< TH1D* > GenPhot_vs_recoRel;
    h1_GenPhot_vs_recoRel.push_back( GenPhot_vs_recoRel );
    std::vector< TH1D* > pt2ndJetRecoRelMean;
    h1_pt2ndJetRecoRelMean.push_back( pt2ndJetRecoRelMean );

    int iPt = minPt;
    char histName[30];
    Int_t nBins = 50;
 
    //absolute second jet pt binning histograms:
    //absolute binning:  5-10GeV 10-15GeV 15-20GeV 20-25GeV 25-30GeV

    for( int i=0; i<nPoints; ++i) {
      TH1D* tmp;

      sprintf(histName, "r_RecoPhot_vs_Gen_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoPhot_vs_gen[i_ptBin].push_back(tmp);
      sprintf(histName, "r_RecoGen_vs_Gen_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoGen_vs_gen[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPart_vs_Gen_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPart_vs_gen[i_ptBin].push_back(tmp);
      sprintf(histName, "r_PartPhot_vs_Gen_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_PartPhot_vs_gen[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPhot_vs_Gen_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPhot_vs_gen[i_ptBin].push_back(tmp);
      sprintf(histName, "pt2ndJetGenMean_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, iPt, iPt+ptStep);
      tmp->Sumw2();
      h1_pt2ndJetGenMean[i_ptBin].push_back(tmp);

      sprintf(histName, "r_RecoPhot_vs_Reco_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoPhot_vs_reco[i_ptBin].push_back(tmp);
      sprintf(histName, "r_RecoGen_vs_Reco_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoGen_vs_reco[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPart_vs_Reco_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPart_vs_reco[i_ptBin].push_back(tmp);
      sprintf(histName, "r_PartPhot_vs_Reco_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_PartPhot_vs_reco[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPhot_vs_Reco_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPhot_vs_reco[i_ptBin].push_back(tmp);
      sprintf(histName, "pt2ndJetRecoMean_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, iPt, iPt+ptStep);
      tmp->Sumw2();
      h1_pt2ndJetRecoMean[i_ptBin].push_back(tmp);

      iPt+=ptStep;

    } //for nPoints

    //relative second jet pt binning histograms:
    //relative binning:  5-8%, 8-11%, 11-14%, 14-17%, 17-20% of pt_photon

    Float_t minPerc;
    Float_t percStep;

    //variable relative binning range in different pt regions
    //if( Lower[i_ptBin]<=60.) {
    //  minPerc = 15.;
    //  percStep = 3.;
    if( Lower[i_ptBin]<=80.) {
      minPerc = 8.;
      percStep = 3.;
    } else if( Lower[i_ptBin]<=350.) {
      minPerc = 5.;
      percStep = 3.;
    } else {
      minPerc = 2.;
      percStep = 2.;
    }


    int iPerc = minPerc;


    for( int i=0; i<nPoints; ++i) {
      TH1D* tmp;

      sprintf(histName, "r_RecoPhot_vs_GenRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoPhot_vs_genRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_RecoGen_vs_GenRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoGen_vs_genRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPart_vs_GenRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPart_vs_genRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_PartPhot_vs_GenRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_PartPhot_vs_genRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPhot_vs_GenRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPhot_vs_genRel[i_ptBin].push_back(tmp);
      sprintf(histName, "pt2ndJetGenRelMean_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, iPerc, iPerc+percStep);
      tmp->Sumw2();
      h1_pt2ndJetGenRelMean[i_ptBin].push_back(tmp);

      sprintf(histName, "r_RecoPhot_vs_RecoRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoPhot_vs_recoRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_RecoGen_vs_RecoRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_RecoGen_vs_recoRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPart_vs_RecoRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPart_vs_recoRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_PartPhot_vs_RecoRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_PartPhot_vs_recoRel[i_ptBin].push_back(tmp);
      sprintf(histName, "r_GenPhot_vs_RecoRel_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, 0., 2.); 
      tmp->Sumw2();
      h1_GenPhot_vs_recoRel[i_ptBin].push_back(tmp);
      sprintf(histName, "pt2ndJetRecoRelMean_%d_%d", i_ptBin, i);
      tmp = new TH1D(histName, "", nBins, iPerc, iPerc+percStep);
      tmp->Sumw2();
      h1_pt2ndJetRecoRelMean[i_ptBin].push_back(tmp);

      iPerc+=percStep;

    } //for nPoints

  } //for ptBins




  int nEntries = tree->GetEntries();
//nEntries = 100000;

  for(int iEntry=0; iEntry<nEntries; ++iEntry) {

    if( (iEntry % 100000)==0 ) std::cout << "Entry: " << iEntry << " /" << nEntries << std::endl;

    tree->GetEntry(iEntry);

    if( eventWeight <= 0. ) eventWeight = 1.;
    if( NOEVENTWEIGHTS_ )   eventWeight = 1.;

    //both photon and jet in barrel (maybe jet requirement could induce bias):
    if( fabs(etaPhotReco)>1.3 ) continue;
    if( fabs(etaJetReco)>1.4 ) continue;

    
    //leading jet and photon back2back in transverse plane
    bool back2back = true;
    Float_t deltaPhi_jet = phiPhotReco - phiJetReco;
    Float_t pi = 3.14159;
    if( fabs(deltaPhi_jet) < (pi - 0.2) ) back2back = false;
    //if( !back2back ) continue;  //09.11.09 deltaPhi cut is actually useless: proved it.


    if( MCASSOC_ )
      if( !matchedToMC ) continue;
    else
      if( !passedPhotonID_medium ) continue;
    
    if( PARTONTYPE=="GLUON" )
      if( fabs(pdgIdPart)!=21 ) continue;
    if( PARTONTYPE=="QUARK" )
      if( fabs(pdgIdPart)>9 ) continue;

    Double_t r_RecoPhot = (ptPhotReco!=0.) ? ptJetReco/ptPhotReco : 0.;
    Double_t r_RecoGen = (ptJetGen!=0.) ? ptJetReco/ptJetGen : 0.;
    Double_t r_GenPart = (ptPart!=0.) ? ptJetGen/ptPart : 0.;
    Double_t r_GenPhot = (ptPhotReco!=0.) ? ptJetGen/ptPhotReco : 0.;
    Double_t r_PartPhot = (ptPhotReco!=0.) ? ptPart/ptPhotReco : 0.;


    Int_t ptBin = -1;

    for( int i=0; i<nBins_pt; ++i) {
      if( (ptPhotReco<Lower[i+1])&&(ptPhotReco>Lower[i]) )
        ptBin = i;
    }

    if( ptBin<0 ) continue;


    //------------ STANDARD CUT ON SECOND JET ------------------------
    
    if( (pt2ndJetReco<0.1*ptPhotReco)||(pt2ndJetReco<10.) ) {
      if(r_RecoPhot!=0.) h2_response_vs_ptPhot->Fill(ptPhotReco, r_RecoPhot, eventWeight); 
      h2_ptPhotMean_vs_pt_cutOn2ndJet->Fill(ptPhotReco, ptPhotReco, eventWeight);
    } 

   
    // --- REQUIRE THAT 2nd JET IS NOT IN PHOTON HEMISPHERE:
    Float_t deltaPhi_phot2nd = phi2ndJetReco - phiPhotReco;
    if( deltaPhi_phot2nd >= TMath::Pi() ) deltaPhi_phot2nd -= 2.*TMath::Pi();
    if( deltaPhi_phot2nd < -TMath::Pi() ) deltaPhi_phot2nd += 2.*TMath::Pi();
   
    if( !NOHEMISPHERE_ ) 
      if( fabs(deltaPhi_phot2nd) < (TMath::Pi()/2.) ) continue;


    h2_ptPhotMean_vs_pt->Fill( ptPhotReco, ptPhotReco, eventWeight );

    //------------ ABSOLUTE SECOND JET PT BINNING --------------------

    int iGen = (int)floor((pt2ndJetGen-minPt)/ptStep);

    if( (iGen>=0)&&(iGen<5) ) {
      if(r_RecoPhot!=0.) h1_RecoPhot_vs_gen[ptBin][iGen]->Fill(r_RecoPhot, eventWeight);
      if(r_RecoGen!=0.)  h1_RecoGen_vs_gen[ptBin][iGen]->Fill(r_RecoGen, eventWeight);
      if(r_GenPart!=0.)  h1_GenPart_vs_gen[ptBin][iGen]->Fill(r_GenPart, eventWeight);
      if(r_PartPhot!=0.) h1_PartPhot_vs_gen[ptBin][iGen]->Fill(r_PartPhot, eventWeight);
      if(r_GenPhot!=0.)  h1_GenPhot_vs_gen[ptBin][iGen]->Fill(r_GenPhot, eventWeight);
      h1_pt2ndJetGenMean[ptBin][iGen]->Fill(pt2ndJetGen, eventWeight);
      //h1_pt2ndJetGenMean[ptBin][iGen]->Fill(ptSecondaryJetsGen, eventWeight);
    } 


    int iReco = (int)floor((pt2ndJetReco-minPt)/ptStep);

    if( (iReco>=0)&&(iReco<5) ) {
      if(r_RecoPhot!=0.) h1_RecoPhot_vs_reco[ptBin][iReco]->Fill(r_RecoPhot, eventWeight);
      if(r_RecoGen!=0.)  h1_RecoGen_vs_reco[ptBin][iReco]->Fill(r_RecoGen, eventWeight);
      if(r_GenPart!=0.)  h1_GenPart_vs_reco[ptBin][iReco]->Fill(r_GenPart, eventWeight);
      if(r_PartPhot!=0.) h1_PartPhot_vs_reco[ptBin][iReco]->Fill(r_PartPhot, eventWeight);
      if(r_GenPhot!=0.)  h1_GenPhot_vs_reco[ptBin][iReco]->Fill(r_GenPhot, eventWeight);
      h1_pt2ndJetRecoMean[ptBin][iReco]->Fill(pt2ndJetReco, eventWeight);
      //h1_pt2ndJetRecoMean[ptBin][iReco]->Fill(ptSecondaryJetsReco, eventWeight);
    } 



    //------------ RELATIVE SECOND JET PT BINNING --------------------

    Double_t pt2ndJetGenRel = 100.*pt2ndJetGen/ptPhotReco; //in percentage
    Float_t minPerc = h1_pt2ndJetRecoRelMean[ptBin][0]->GetXaxis()->GetXmin();
    Float_t percStep = h1_pt2ndJetRecoRelMean[ptBin][0]->GetXaxis()->GetXmax()  - minPerc;

    int iGenRel = (int)floor((pt2ndJetGenRel-minPerc)/percStep);

    if( DEBUG_ ) {
      std::cout << std::endl << "---------" << std::endl;
      std::cout << "ptSecondJet: " << pt2ndJetGen << "\tptPhot: " << ptPhotReco << "\tpt2ndJetRel: " << pt2ndJetGenRel << std::endl;
      std::cout << "pt2ndJetGenRel: " << pt2ndJetGenRel << " minPerc: " << minPerc << " percStep: " << percStep << std::endl;
      std::cout << "iGenRel: " << iGenRel << std::endl;
      std::cout << std::endl << "---------" << std::endl;
    }

    if( (iGenRel>=0)&&(iGenRel<5) ) {
      if(r_RecoPhot!=0.) h1_RecoPhot_vs_genRel[ptBin][iGenRel]->Fill(r_RecoPhot, eventWeight);
      if(r_RecoGen!=0.)  h1_RecoGen_vs_genRel[ptBin][iGenRel]->Fill(r_RecoGen, eventWeight);
      if(r_GenPart!=0.)  h1_GenPart_vs_genRel[ptBin][iGenRel]->Fill(r_GenPart, eventWeight);
      if(r_PartPhot!=0.) h1_PartPhot_vs_genRel[ptBin][iGenRel]->Fill(r_PartPhot, eventWeight);
      if(r_GenPhot!=0.)  h1_GenPhot_vs_genRel[ptBin][iGenRel]->Fill(r_GenPhot, eventWeight);
      h1_pt2ndJetGenRelMean[ptBin][iGenRel]->Fill(pt2ndJetGenRel, eventWeight);
      //std::cout << "Filling : iGenRel: " << iGenRel << "pt2ndJetGenRel: " << pt2ndJetGenRel << std::endl;
      //h1_pt2ndJetGenMean[ptBin][iGenRel]->Fill(ptSecondaryJetsGen, eventWeight);
    } 

    Double_t pt2ndJetRecoRel = 100.*pt2ndJetReco/ptPhotReco; //in percentage
    int iRecoRel = (int)floor((pt2ndJetRecoRel-minPerc)/percStep);

    if( (iRecoRel>=0)&&(iRecoRel<5) ) {
      if(r_RecoPhot!=0.) h1_RecoPhot_vs_recoRel[ptBin][iRecoRel]->Fill(r_RecoPhot, eventWeight);
      if(r_RecoGen!=0.)  h1_RecoGen_vs_recoRel[ptBin][iRecoRel]->Fill(r_RecoGen, eventWeight);
      if(r_GenPart!=0.)  h1_GenPart_vs_recoRel[ptBin][iRecoRel]->Fill(r_GenPart, eventWeight);
      if(r_PartPhot!=0.) h1_PartPhot_vs_recoRel[ptBin][iRecoRel]->Fill(r_PartPhot, eventWeight);
      if(r_GenPhot!=0.)  h1_GenPhot_vs_recoRel[ptBin][iRecoRel]->Fill(r_GenPhot, eventWeight);
      h1_pt2ndJetRecoRelMean[ptBin][iRecoRel]->Fill(pt2ndJetRecoRel, eventWeight);
      //h1_pt2ndJetGenMean[ptBin][iRecoRel]->Fill(ptSecondaryJetsGen, eventWeight);
    } 



  } //for entries



  //TFile* outFile = TFile::Open("secondJet_yesPtHat.root", "recreate");
  
  std::string outfileName;

  if( DEBUG_ ) outfileName = "provaSecondJet_"+dataset;
  else {
   if(dataset!="") outfileName = "SecondJet_"+dataset;
   else outfileName = "SecondJet";
  }

  if( PARTONTYPE!="ALL" ) suffix = "_" + PARTONTYPE + suffix;
  if( MCASSOC_ ) suffix = "_MCassoc" + suffix;
  if( NOHEMISPHERE_ ) suffix = "_NOHEMISPHERE" + suffix;
  outfileName = outfileName + suffix;
  outfileName += ".root";

  TFile* outFile = new TFile(outfileName.c_str(), "RECREATE");
  outFile->cd();


  h2_ptPhotMean_vs_pt->Write();

  for( int i_pt=0; i_pt<(nBins_pt-1); ++i_pt) {

    char dirName[40];
    sprintf(dirName, "ptBin_%d_%d", (int)Lower[i_pt], (int)Lower[i_pt+1]);
    outFile->mkdir(dirName);
    outFile->cd(dirName);

    for( int i=0; i<nPoints; ++i) {
      
      TF1* gaussian = new TF1("gaussian", "gaus");

      Float_t nSigma = 2.5;
   
      fitTools::fitProjection(h1_RecoPhot_vs_gen[i_pt][i], gaussian, nSigma);
      h1_RecoPhot_vs_gen[i_pt][i]->Write();
      fitTools::fitProjection(h1_RecoGen_vs_gen[i_pt][i], gaussian, nSigma);
      h1_RecoGen_vs_gen[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPart_vs_gen[i_pt][i], gaussian, nSigma);
      h1_GenPart_vs_gen[i_pt][i]->Write();
      fitTools::fitProjection(h1_PartPhot_vs_gen[i_pt][i], gaussian, nSigma);
      h1_PartPhot_vs_gen[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPhot_vs_gen[i_pt][i], gaussian, nSigma);
      h1_GenPhot_vs_gen[i_pt][i]->Write();
      h1_pt2ndJetGenMean[i_pt][i]->Write();

      fitTools::fitProjection(h1_RecoPhot_vs_reco[i_pt][i], gaussian, nSigma);
      h1_RecoPhot_vs_reco[i_pt][i]->Write();
      fitTools::fitProjection(h1_RecoGen_vs_reco[i_pt][i], gaussian, nSigma);
      h1_RecoGen_vs_reco[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPart_vs_reco[i_pt][i], gaussian, nSigma);
      h1_GenPart_vs_reco[i_pt][i]->Write();
      fitTools::fitProjection(h1_PartPhot_vs_reco[i_pt][i], gaussian, nSigma);
      h1_PartPhot_vs_reco[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPhot_vs_reco[i_pt][i], gaussian, nSigma);
      h1_GenPhot_vs_reco[i_pt][i]->Write();
      h1_pt2ndJetRecoMean[i_pt][i]->Write();

      fitTools::fitProjection(h1_RecoPhot_vs_genRel[i_pt][i], gaussian, nSigma);
      h1_RecoPhot_vs_genRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_RecoGen_vs_genRel[i_pt][i], gaussian, nSigma);
      h1_RecoGen_vs_genRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPart_vs_genRel[i_pt][i], gaussian, nSigma);
      h1_GenPart_vs_genRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_PartPhot_vs_genRel[i_pt][i], gaussian, nSigma);
      h1_PartPhot_vs_genRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPhot_vs_genRel[i_pt][i], gaussian, nSigma);
      h1_GenPhot_vs_genRel[i_pt][i]->Write();
      h1_pt2ndJetGenRelMean[i_pt][i]->Write();

      fitTools::fitProjection(h1_RecoPhot_vs_recoRel[i_pt][i], gaussian, nSigma);
      h1_RecoPhot_vs_recoRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_RecoGen_vs_recoRel[i_pt][i], gaussian, nSigma);
      h1_RecoGen_vs_recoRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPart_vs_recoRel[i_pt][i], gaussian, nSigma);
      h1_GenPart_vs_recoRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_PartPhot_vs_recoRel[i_pt][i], gaussian, nSigma);
      h1_PartPhot_vs_recoRel[i_pt][i]->Write();
      fitTools::fitProjection(h1_GenPhot_vs_recoRel[i_pt][i], gaussian, nSigma);
      h1_GenPhot_vs_recoRel[i_pt][i]->Write();
      h1_pt2ndJetRecoRelMean[i_pt][i]->Write();

    } //for n points

  } //for pt bins


  outFile->Close();

  std::string distribFileName = "SecondJet_barrel"+suffix+"_RECO";

  fitTools::fitDistribution_TGraph(h2_response_vs_ptPhot, h2_ptPhotMean_vs_pt_cutOn2ndJet, "response", "pt", "barrel", "", algoType, outfileName, distribFileName, 0.95);



}
void
makeUnfoldingSystematicsComparisonPlots (int whichobservable, int whichjet, int whichlepton, int inclusive)
{
  //Open the file and form the name
  string fileSystematics; 
  string suffix="/gpfs/cms/data/2011/Systematics/postApproval_v58_Journal/";
  //string suffix="/tmp/";

  if (whichlepton==1) suffix=suffix+"ele/";
  if (whichlepton==2) suffix=suffix+"muo/";

  //  setTDRStyle ();
  gStyle->SetErrorX(0);
  gStyle->SetPadGridX(0);
  gStyle->SetPadGridY(0);

  bool absoluteNormalization = true;
  int lepton = 3; //1 -> electron,  2-> muon , 3 -> combined reults!
  bool addLumiUncertainties = true;
  double lumiError = 0.025;
  int use_case = whichobservable;
  int whichjet = whichjet;
  string version = "_v2_32";

  //string s         = "/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v41/SVDBayes/";
  string s="/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v58_Journal/UnfoldingSyst/ele/";
  //  string s         = "/gpfs/cms/users/schizzi/EleMuComparisonPlots/PostUnfolding/";
  string  eleplotpath = "/gpfs/cms/users/schizzi/Systematics/ele/";
  string  muoplotpath = "/gpfs/cms/users/schizzi/Systematics/muo/";

  gStyle->SetOptStat (0);

  TCanvas *plots = new TCanvas ("plots", "EB", 200, 100, 600, 800);

  //DATA:
  //string elepathFile   ="/gpfs/cms/data/2011/Unfolding/testReferenceMu.root";
  //string muopathFile   ="/gpfs/cms/data/2011/Unfolding/testMu.root";
  string elepathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_afterCWR.root";
  string muopathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_BinWidth.root";
  string thirdpathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_SherpaV2.root";

  if (whichlepton==2){
  elepathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_afterCWRMu.root";
  muopathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_BinWidthMu.root";
thirdpathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV58_SherpaV2Mu.root";
  s="/afs/infn.it/ts/user/marone/html/ZJets/FinalPlotsForAN/v58_Journal/UnfoldingSyst/muo/";
  }
  //string elepathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3NoSQRT.root";
  //string muopathFile   ="/gpfs/cms/data/2011/Unfolding/UnfoldingOfficialV57_3NoMCToy.root";
    
  TFile *histof = TFile::Open (elepathFile.c_str ());
  histof->cd ("");
  TDirectory *dir = gDirectory;
  TList *mylist = (TList *) dir->GetListOfKeys ();
  TIter iter (mylist);
  TObject *tobj = 0;

  TFile *histof2 = TFile::Open (thirdpathFile.c_str ());
  histof2->cd ("");
  TDirectory *dir2 = gDirectory;
  TList *mylist2 = (TList *) dir2->GetListOfKeys ();
  TIter iter2 (mylist);
  TObject *tobj2 = 0;


  TFile *histofmuo = TFile::Open (muopathFile.c_str ());


  string stringmatch;
  string systPathFile;
  string systPathFileMuo;

  histof->cd ("");

  int i = 0;			// solo di servizio quando debuggo...
  while ((tobj = iter.Next ()))
    {
      string name = tobj->GetName ();

      if (use_case == 1) 
	{ // Jet Multiplicity
	  stringmatch = "JetMultiplicityUnfolded";
	  systPathFile = eleplotpath + "systematicsEff_jetMult" + version + ".txt";
	  systPathFileMuo = muoplotpath + "systematicsEff_jetMult" + version + ".txt";
	  fileSystematics = suffix+"systematicsUnfReweight_jetMult" + version + ".txt"; 
	}

      if (use_case == 2) 
	{ // Jet Pt
	  if (whichjet == 1)
	    {
	      stringmatch = "jReco_leading";
	      systPathFile = eleplotpath + "systematicsEff_jet1Pt" + version + ".txt";
	      systPathFileMuo = muoplotpath + "systematicsEff_jet1Pt" + version + ".txt";
	      fileSystematics = suffix+"systematicsUnfReweight_jet1Pt" + version + ".txt"; 
	    }
	  
	  if (whichjet == 2)
	    {
	      stringmatch = "jReco_subleading";
	      systPathFile = eleplotpath + "systematicsEff_jet2Pt" + version + ".txt";
	      systPathFileMuo = muoplotpath + "systematicsEff_jet2Pt" + version + ".txt";
	      fileSystematics = suffix+"systematicsUnfReweight_jet2Pt" + version + ".txt"; 
	    }
	  
	  if (whichjet == 3)
	    {
	      stringmatch = "jReco_subsubleading";
	      systPathFile = eleplotpath + "systematicsEff_jet3Pt" + version + ".txt";
	      systPathFileMuo = muoplotpath + "systematicsEff_jet3Pt" + version + ".txt";
	      fileSystematics = suffix+"systematicsUnfReweight_jet3Pt" + version + ".txt"; 
	    }
	  
	  if (whichjet == 4)
	    {
	      stringmatch = "jReco_subsubsubleading";
	      systPathFile = eleplotpath + "systematicsEff_jet4Pt" + version + ".txt";
	      systPathFileMuo = muoplotpath + "systematicsEff_jet4Pt" + version + ".txt";
	      fileSystematics = suffix+"systematicsUnfReweight_jet4Pt" + version + ".txt"; 
	    }
	}
      
      if (use_case == 3) { // Jet Eta
	if (whichjet == 1)
	  {
	    stringmatch = "jReco_leadingeta";
	    systPathFile = eleplotpath + "systematicsEff_jet1Eta" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet1Eta" + version + ".txt";
	    fileSystematics = suffix+"systematicsUnfReweight_jet1Eta" + version + ".txt"; 
	  }
	
	if (whichjet == 2)
	  {
	    stringmatch = "jReco_subleadingeta";
	    systPathFile = eleplotpath + "systematicsEff_jet2Eta" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet2Eta" + version + ".txt";
	    fileSystematics = suffix+"systematicsUnfReweight_jet2Eta" + version + ".txt"; 
	  }

	if (whichjet == 3)
	  {
	    stringmatch = "jReco_subsubleadingeta";
	    systPathFile = eleplotpath + "systematicsEff_jet3Eta" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet3Eta" + version + ".txt";
	    fileSystematics = suffix+"systematicsUnfReweight_jet3Eta" + version + ".txt"; 
	  }
	
	if (whichjet == 4)
	  {
	    stringmatch = "jReco_subsubsubleadingeta";
	    systPathFile = eleplotpath + "systematicsEff_jet4Eta" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet4Eta" + version + ".txt";
	    fileSystematics = suffix+"systematicsUnfReweight_jet4Eta" + version + ".txt"; 
	  }
      }
      
      if (use_case == 4) { // Ht
	if (whichjet == 1)
	  {
	    stringmatch = "HReco_leading";
	    systPathFile = eleplotpath + "systematicsEff_jet1Ht" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet1Ht" + version + ".txt";
	    fileSystematics = suffix+"systematicsUnfReweight_jet1Ht" + version + ".txt"; 
	  }
	if (whichjet == 2)
	  {
	    stringmatch = "HReco_subleading";
	    systPathFile = eleplotpath + "systematicsEff_jet2Ht" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet2Ht" + version + ".txt";
	    fileSystematics = suffix+"systematicsUnfReweight_jet2Ht" + version + ".txt"; 
	  }
	
	if (whichjet == 3)
	  {
	    stringmatch = "HReco_subsubleading";
	    systPathFile = eleplotpath + "systematicsEff_jet3Ht" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet3Ht" + version + ".txt";
	    fileSystematics = suffix+"systematicsUnfReweight_jet3Ht" + version + ".txt"; 
	  }

	if (whichjet == 4)
	  {
	    stringmatch = "HReco_subsubsubleading";
	    fileSystematics = suffix+"systematicsUnfReweight_jet4Ht" + version + ".txt"; 
	    systPathFile = eleplotpath + "systematicsEff_jet4Ht" + version + ".txt";
	    systPathFileMuo = muoplotpath + "systematicsEff_jet4Ht" + version + ".txt";
	  }
      }

      
      if (name == stringmatch) {

	cout << "CONFIGURATION:" << endl;
	cout << "stringmatch: " <<stringmatch<< endl;
	cout << "systPathFile: " <<systPathFile<< endl;

	TH1D *leading;
	gDirectory->GetObject (name.c_str (), leading);
	leading->SetMarkerSize(0.9);
	leading->Sumw2();

	histofmuo->cd ("");
	TH1D *leadingmuo;
	gDirectory->GetObject (name.c_str (), leadingmuo);
	leadingmuo->SetMarkerSize(0.9);
	leadingmuo->Sumw2();

	histof2->cd ("");
	TH1D *leadingthird;
	gDirectory->GetObject (name.c_str (), leadingthird);
	leadingmuo->SetMarkerSize(0.9);
	leadingmuo->Sumw2();
	
	if (inclusive==1){
	  TH1D* leadingIncl=turnExclusiveHistoInInclusive(leading);
	  TH1D* leadingmuoIncl=turnExclusiveHistoInInclusive(leadingmuo);
	  TH1D* leadingthirdIncl=turnExclusiveHistoInInclusive(leadingthird);
	  leading=leadingIncl;
	  leadingmuo=leadingmuoIncl;
	  leadingthird=leadingthirdIncl;
	}
	//	/// EFFICIENCY Systematics:
	//	for (int nnbins=1;nnbins<=leading->GetNbinsX ();nnbins++) {
	  //	  cout << fabs(leading->GetBinContent(nnbins)-leadingmuo->GetBinContent(nnbins))/(2*leading->GetBinContent(nnbins)) << endl;
	  //	  cout << leading->GetBinContent(nnbins)-leadingmuo->GetBinContent(nnbins) << endl;
	//	}

	// read from file ---------------------------------------------
	double dat;
	ifstream inM;
	cout << "reading ...  " << systPathFile << endl;
	inM.open (systPathFile.c_str ());
	std::vector < double >systTmpM;
	while (1)
	  {
	    inM >> dat;
	    if (!inM.good ())
	      break;
	    systTmpM.push_back (dat);
	  }
	inM.close ();
	// ------------------------------------------------------------
	// read from file ---------------------------------------------
	ifstream inM2;
	cout << "reading ...  " << systPathFileMuo << endl;
	inM2.open (systPathFileMuo.c_str ());
	std::vector < double >systTmpMmuo;
	while (1)
	  {
	    inM2 >> dat;
	    if (!inM2.good ())
	      break;
	    systTmpMmuo.push_back (dat);
	  }
	inM2.close ();
	// ------------------------------------------------------------

        TH1D *leadingRatioSystematics;
	leadingRatioSystematics = (TH1D *) leading->Clone ("leading");

	if (systTmpM.size () != leadingRatioSystematics->GetNbinsX ())
	  cout << "TE SON MONA! WRONG NUMBER OF BINS (# syst from file->" <<systTmpM.size()<<" - # bins->"<<leadingRatioSystematics->GetNbinsX()<<")"<<endl;
	for (int i = 0; i < leadingRatioSystematics->GetNbinsX (); i++)
	  {
	    //leadingRatioSystematics->SetBinContent(i + 1, 1.0);
	    //leadingRatioSystematics->SetBinError (i + 1,sqrt(systTmpM[i]*systTmpM[i] + systTmpMmuo[i]*systTmpMmuo[i]));
	    //	    leadingRatioSystematics->SetBinContent(i + 1, 1.0);
	    //	    leadingRatioSystematics->SetBinError (i + 1,max(systTmpM[i]/100.0,systTmpMmuo[i]/100.0));
	  }

	plots->cd ();
	TPad *pad1 = new TPad("pad1","pad1",0.01,0.3,0.99,0.99);

	pad1->Draw();
	pad1->cd();
	pad1->SetTopMargin(0.1);
	pad1->SetBottomMargin(0.0);
	pad1->SetLeftMargin(0.2);
	pad1->SetRightMargin(0.0);
	pad1->SetFillStyle(0);
	if (use_case !=3) pad1->SetLogy(1); 
	else pad1->SetLogy(0);

	if (use_case ==3){
	  leading->SetMinimum((0.5-0.05*(whichjet-1))*leading->GetMinimum());
	  leading->SetMaximum((1.25+0.35*(whichjet-1))*leading->GetMaximum());
	}
	leading->SetLineColor (kRed+1);
	leading->SetMarkerStyle (20);
	leading->SetFillColor (kRed+1);
	leading->SetMarkerColor (kRed+1);

	leading->GetXaxis ()->SetTitleOffset (1.1);
	leading->GetXaxis ()->SetTitleSize (0.05);
	leading->GetXaxis ()->SetLabelSize (0.0);
	leading->GetXaxis ()->SetLabelFont (42);
	leading->GetXaxis ()->SetTitleFont (42);

	leading->GetYaxis ()->SetTitleOffset (1.);
	leading->GetYaxis ()->SetTitleSize (0.07);
	leading->GetYaxis ()->SetLabelSize (0.06);
	leading->GetYaxis ()->SetLabelFont (42);
	leading->GetYaxis ()->SetTitleFont (42);

	leading->SetTitle ();
	leading->GetXaxis ()->SetTitle ();
	    

	if (use_case ==1) {
	  if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dN [pb]");
	  else {
	    if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dN");
	    if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dN");
	    if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dN");
	  }
	}

	if (use_case ==2) {
	  if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dp_{T} [pb/GeV]");
	  else {
	    if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dp_{T}");
	    if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dp_{T}");
	    if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dp_{T}");
	  }
	}

	if (use_case ==3) {
	  if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/d#eta [pb]");
	  else {
	    if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/d#eta");
	    if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/d#eta");
	    if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/d#eta");
	  }
	}
	  
	if (use_case ==4) {
	  if (absoluteNormalization) leading->GetYaxis ()->SetTitle ("d#sigma/dH_{T} [pb/GeV]");
	  else {
	    if (lepton == 1) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow e^{+}e^{-}}) d#sigma/dH_{T}");
	    if (lepton == 2) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow #mu^{+}#mu^{-}}) d#sigma/dH_{T}");
	    if (lepton == 3) leading->GetYaxis ()->SetTitle ("(1/#sigma_{Z #rightarrow l^{+}l^{-}}) d#sigma/dH_{T}");
	  }
	}
	  
	leading->SetFillColor (kBlack);
	leading->SetFillStyle (3001);
	leading->SetMarkerColor (kBlack);
	leading->SetLineColor (kBlack);
	leading->SetMarkerStyle (20);
	leading->Draw ("E1");

	leadingmuo->SetFillColor (kBlue);
	leadingmuo->SetFillStyle (3001);
	leadingmuo->SetMarkerColor (kBlue);
	leadingmuo->SetLineColor (kBlue);
	leadingmuo->SetMarkerStyle (21);
	leadingmuo->Draw ("E1SAME");

	leadingthird->SetFillColor (kRed);
	leadingthird->SetFillStyle (3001);
	leadingthird->SetMarkerColor (kRed);
	leadingthird->SetLineColor (kRed);
	leadingthird->SetMarkerStyle (21);
	leadingthird->Sumw2();
	//for (int j=1; j<=leadingthird->GetNbinsX();j++){
	  
	  //leadingmuo->SetBinError(j,leadingmuo->GetBinError(j)/4980.0);
	  //leadingthird->SetBinError(j,sqrt(leadingthird->GetBinContent(j))/(4980.0*100));
	//}
	leadingthird->Draw ("E1SAME");


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

	TLegend *legendsx_d;
	legendsx_d = new TLegend (0.74, 0.6, 0.98, 0.88);	   

	legendsx_d->SetFillColor (kWhite);
	legendsx_d->SetBorderSize (1);
	legendsx_d->SetNColumns(1);
	legendsx_d->SetTextSize(.040);
	legendsx_d->AddEntry (leading, "Central", "PEL");
	legendsx_d->AddEntry (leadingmuo, "Sherpa", "PEL");
	legendsx_d->AddEntry (leadingthird, "Reweighting", "PEL");
	legendsx_d->Draw ("same");

	// Draw the ratio plot: ----------------------

	leadingRatio = (TH1D *) leading->Clone ("leading");
	leadingRatio->Divide(leadingmuo);

	leadingRatio2 = (TH1D *) leading->Clone ("leading");
	leadingRatio2->Divide(leadingthird);

	for (int mem=1; mem<=leadingRatio->GetNbinsX(); mem++) {
	  cout << "Syst for bin nr." << mem << ":\t" << fabs(leadingRatio->GetBinContent(mem)-1.0)/2 << endl;
	}

	plots->cd();
	TPad *pad3 = new TPad("pad3","pad3",0.01,0.01,0.99,0.30);
	pad3->Draw();
	pad3->cd();
	pad3->SetTopMargin(0.0);
	pad3->SetBottomMargin(0.3);
	pad3->SetLeftMargin(0.2);
	pad3->SetRightMargin(0);
	pad3->SetFillStyle(0);

	leadingRatio->GetXaxis()->SetLabelFont (42);
	leadingRatio->GetXaxis()->SetTitleFont (42);
	leadingRatio->GetXaxis()->SetTitleSize(0.11);
	leadingRatio->GetXaxis()->SetLabelSize(0.11);
	leadingRatio->GetXaxis()->SetTitleOffset (1.1);
	leadingRatio->GetYaxis()->SetTitleSize(0.11);
	leadingRatio->GetYaxis()->SetLabelSize(0.10);
	leadingRatio->GetYaxis()->SetTitleOffset(0.65);
	leadingRatio->GetYaxis()->SetTitle("Ratio");   
	leadingRatio->GetYaxis()->SetNdivisions(5);
	leadingRatio->GetYaxis()->SetRangeUser(0.4,1.6);


	if (use_case ==1) {
	  leadingRatio->GetXaxis ()->SetTitle ("Exclusive jet multiplicity");
	}
	if (use_case ==2) {
	  if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("Leading jet p_{T} [GeV]");
	  if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("Second jet p_{T} [GeV]");
	  if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("Third jet p_{T} [GeV]");
	  if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("Fourth jet p_{T} [GeV]");
	}
	if (use_case ==3) {
	  if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("Leading jet #eta");
	  if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("Second jet #eta");
	  if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("Third jet #eta");
	  if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("Fourth jet #eta");
	}
	if (use_case ==4) {
	  if (whichjet == 1) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 1 [GeV]");
	  if (whichjet == 2) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 2 [GeV]");
	  if (whichjet == 3) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 3 [GeV]");
	  if (whichjet == 4) leadingRatio->GetXaxis ()->SetTitle ("H_{T}, N_{jet} >= 4 [GeV]");
	}

	leadingRatio->SetFillColor (kRed+2);
	leadingRatio->SetMarkerColor (kRed+2);
	leadingRatio->SetLineColor (kRed+2);
	leadingRatio->Draw ("E0");

	leadingRatioSystematics->SetFillColor (kGreen+3);
	leadingRatioSystematics->SetFillStyle (3004);
	leadingRatioSystematics->SetMarkerColor (kGreen+3);
	leadingRatioSystematics->SetLineColor (kGreen+3);
	leadingRatioSystematics->SetMarkerStyle (1);
	//leadingRatioSystematics->Draw ("E3SAME");

	leadingRatio->Draw ("E1SAME");
	leadingRatio2->SetMarkerColor(kBlue);
	leadingRatio2->SetLineColor(kBlue);
	leadingRatio2->Draw ("E1SAME");

	myfile.open (fileSystematics.c_str());
	cout<<"TXT file saved in "<<fileSystematics<<endl;
	loopAndDumpEntries(leadingRatio,leadingmuo);

	TLine *OLine2 = new TLine(leading->GetXaxis()->GetXmin(),1.,leading->GetXaxis()->GetXmax(),1.);
	OLine2->SetLineColor(kBlack);
	OLine2->SetLineStyle(2);
	OLine2->Draw();
	  
	//latexLabel->SetTextSize(0.09);
	//	latexLabel->DrawLatex(0.2,0.35,"Ratio");	  

	/////////////////////////////////////////////////////
	  
	string title1;
	title1 = s + "DifferentialX" + stringmatch + ".pdf";
	cout << title1 << endl;
	plots->Print (title1.c_str ());
	plots->Draw();
	return;
      }
    }
Esempio n. 20
0
void ncDmBsFit(TString infname="",bool doweight = 1)
{
   if (doweight==0) weight="1";
   if (infname=="") infname=inputdata.Data();
   TFile *inf = new TFile(infname.Data());
   TTree *nt = (TTree*) inf->Get("ntphi");

   TFile *infMC = new TFile(inputmc.Data());
   TTree *ntGen = (TTree*)infMC->Get("ntGen");
   TTree *ntMC = (TTree*)infMC->Get("ntphi");

   ntGen->AddFriend(ntMC);

   const int nBins = 6;
   double ptBins[nBins+1] = {0.5,1.0,1.5,2.0,2.5,3.0,3.5};

   TH1D *hPt = new TH1D("hPt","",nBins,ptBins);
   TH1D *hPtBase = new TH1D("hPtBase","",nBins,ptBins);
   TH1D *hPtMC = new TH1D("hPtMC","",nBins,ptBins);
   TH1D *hPtMCBase = new TH1D("hPtMCBase","",nBins,ptBins);

   TF1 *fbase = fit(nt,ntMC,10,60,0,false);
   double yieldBase = fbase->Integral(5,6)/0.02;
   double yieldErrBase = fbase->Integral(5,6)/0.02*fbase->GetParError(0)/fbase->GetParameter(0);

   TF1 *fmcbase = fit(ntMC,ntMC,10,60,0,true);
   double yieldMCBase = fmcbase->Integral(5,6)/0.02;

   for (int i=0;i<nBins;i++)
     {
       TF1 *f = fit(nt,ntMC,10,60,ptBins[i],false);
       double yield = f->Integral(5,6)/0.02;
       double yieldErr = f->Integral(5,6)/0.02*f->GetParError(0)/f->GetParameter(0);
       hPt->SetBinContent(i+1,yield);
       hPt->SetBinError(i+1,yieldErr);
       hPtBase->SetBinContent(i+1,yieldBase);
       hPtBase->SetBinError(i+1,yieldErrBase);

       TF1 *fMC = fit(ntMC,ntMC,10,60,ptBins[i],true);
       double yieldMC = fMC->Integral(5,6)/0.02;
       hPtMC->SetBinContent(i+1,yieldMC);
       hPtMCBase->SetBinContent(i+1,yieldMCBase);
     }  

   hPt->Sumw2();
   hPtBase->Sumw2();
   hPt->Divide(hPt,hPtBase,1,1,"B");
   hPtMC->Divide(hPtMCBase);

   for(int i=0;i<nBins;i++)
     {
       double tem=0;
       tem = hPt->GetBinContent(i+1);
       hPt->SetBinContent(i+1,1-tem);
       tem = hPtMC->GetBinContent(i+1);
       hPtMC->SetBinContent(i+1,1-tem);
     }

   hPtMC->SetXTitle("#mu p_{T} larger than (GeV)");
   hPtMC->SetYTitle("Candidate losing fraction");
   hPtMC->SetTitleOffset(1.5,"Y");
   hPtMC->SetMaximum(0.5);
   //  if(hPt->GetMaximum()>hPtMC->GetMaximum()) hPtMC->SetMaximum(hPt->GetMaximum()*1.03);
   //  else hPtMC->SetMaximum(hPtMC->GetMaximum()*1.03);

   hPt->SetMarkerStyle(8);
   hPt->SetStats(0);
   hPtMC->SetLineColor(kRed);
   hPtMC->SetFillStyle(3004);
   hPtMC->SetFillColor(kRed);
   hPtMC->SetLineWidth(3);
   hPtMC->SetStats(0);
  
   TCanvas *cfinal = new TCanvas("cfinal","",600,600);

   hPtMC->Draw();
   hPt->Draw("same lep");

   TLegend *legi = new TLegend(0.13,0.72,0.33,0.84);
   legi->AddEntry(hPt,"data","pl");
   legi->AddEntry(hPtMC,"MC","f");
   legi->SetBorderSize(0);
   legi->SetFillStyle(0);
   legi->Draw("same");
   TLegend *leg1i = new TLegend(0.20,0.7,0.50,0.9);
   leg1i->AddEntry((TObject*)0,Form("%s",particle.Data()),"");
   leg1i->AddEntry((TObject*)0,Form("%.0f<p_{T}<%.0f GeV",10.0,60.0),"");
   leg1i->AddEntry((TObject*)0,Form("%.1f<y_{CM}<%.1f",-2.4,2.4),"");
   leg1i->SetBorderSize(0);
   leg1i->SetFillStyle(0);
   leg1i->Draw("same");

   cfinal->SaveAs("MuonPt/Bs/muonpt.pdf");


   /*
   divideBinWidth(hPtMC);
   divideBinWidth(hPtGen);

   TCanvas *c=  new TCanvas("cResult","",600,600);
   hPt->SetXTitle("B_{s} p_{T} (GeV/c)");
   hPt->SetYTitle("Uncorrected B_{s} dN/dp_{T}");
   hPt->Draw();
   hRecoTruth->Draw("same hist");
   
   hPtMC->Sumw2();
   TH1D *hEff = (TH1D*)hPtMC->Clone("hEff");
   hPtMC->Sumw2();
   hEff->Divide(hPtGen);
  
  TH1D *hPtCor = (TH1D*)hPt->Clone("hPtCor");
  hPtCor->Divide(hEff);
  TCanvas *cCor=  new TCanvas("cCorResult","",600,600);
  hPtCor->SetYTitle("Correctd B_{s} dN/dp_{T}");
  hPtCor->Draw();
  hPtGen->Draw("same");

  TH1D *hPtSigma= (TH1D*)hPtCor->Clone("hPtSigma");
  double BRchain=2.89977e-5;
  hPtSigma->Scale(1./(2*luminosity*BRchain));
  hPtSigma->SetYTitle("d#sigma/dp_{T} (B_{s})");

  TCanvas *cSigma=  new TCanvas("cSigma","",600,600);

  hPtSigma->Draw();
  
  TFile *outf = new TFile("../ResultsBs/SigmaBs.root","recreate");
  outf->cd();
  hPt->Write();
  hEff->Write();
  hPtCor->Write();
  hPtSigma->Write();
  outf->Close();
  delete outf;
  */
}
Esempio n. 21
0
void fitD(TString inputdata="/data/dmeson2015/DataDntuple/nt_20160112_DfinderData_pp_20160111_dPt0tkPt1_D0Dstar3p5p_DCSJSON_v2.root", TString inputmc="/afs/cern.ch/work/w/wangj/public/Dmeson/ntD_20151110_DfinderMC_20151110_EvtMatching_Pythia_D0pt15p0_Pthat15_TuneZ2_5020GeV_GENSIM_75x_1015_20151110_ppGlobaTrackingPPmenuHFlowpuv11_MBseed_twang-Pythia_1107.root", TString trgselection="((HLT_DmesonPPTrackingGlobal_Dpt15_v1&&Dpt>25&&Dpt<40)||(HLT_DmesonPPTrackingGlobal_Dpt30_v1&&Dpt>40&&Dpt<60)||(HLT_DmesonPPTrackingGlobal_Dpt50_v1&&Dpt>60))",  TString cut="Dy>-1.&&Dy<1.&&(Dtrk1highPurity&&Dtrk2highPurity)&&(DsvpvDistance/DsvpvDisErr)>3.5&&Dchi2cl>0.05&&Dalpha<0.12&&Dtrk1Pt>1.5&&Dtrk2Pt>1.5", TString selmcgen="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))", int isMC=0, Double_t luminosity=26., int doweight=0, TString collsyst="PbPb", TString outputfile="mytest.root")
{
  collisionsystem=collsyst;
  seldata = Form("%s&&%s",trgselection.Data(),cut.Data());
  selmc = Form("%s",cut.Data());

  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);

  void clean0 (TH1D* h);
  TF1* fit (TTree* nt, TTree* ntMC, double ptmin, double ptmax, int isMC);

  if(!doweight) weight="1";
  TFile* inf = new TFile(inputdata.Data());
  TFile* infMC = new TFile(inputmc.Data());

  TTree* nt = (TTree*) inf->Get("ntDkpi");
  TTree* HltTree= (TTree*) inf->Get("ntHlt");
  HltTree->AddFriend(nt);
  nt->AddFriend(HltTree);
  TTree* ntHid = (TTree*) inf->Get("ntHi");
  nt->AddFriend(ntHid);
  
  TTree* ntMC = (TTree*)infMC->Get("ntDkpi");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  TTree* ntHi = (TTree*)infMC->Get("ntHi");
  
  ntGen->AddFriend(ntMC);
  ntGen->AddFriend(ntHi);
  ntMC->AddFriend(ntGen);
  ntMC->AddFriend(ntHi);
  ntHi->AddFriend(ntMC);
  
  TH1D* hPt = new TH1D("hPt","",nBins,ptBins);
  TH1D* hPtRecoTruth = new TH1D("hPtRecoTruth","",nBins,ptBins);
  TH1D* hPtMC = new TH1D("hPtMC","",nBins,ptBins);
  TH1D* hPtGen = new TH1D("hPtGen","",nBins,ptBins);

  TH1D* hMean = new TH1D("hMean","",nBins,ptBins);                       
  TH1D* hSigmaGaus1 = new TH1D("hSigmaGaus1","",nBins,ptBins); 
  TH1D* hSigmaGaus2 = new TH1D("hSigmaGaus2","",nBins,ptBins); 
  TH1D* hRelMagnGaus1Gaus2 = new TH1D("hRelMagnGaus1Gaus2","",nBins,ptBins); 
  
  for(int i=0;i<nBins;i++)
    {
      TF1* f = fit(nt,ntMC,ptBins[i],ptBins[i+1],isMC);
      double yield = f->Integral(minhisto,maxhisto)/binwidthmass;
      double yieldErr = f->Integral(minhisto,maxhisto)/binwidthmass*f->GetParError(0)/f->GetParameter(0);
      hPt->SetBinContent(i+1,yield/(ptBins[i+1]-ptBins[i]));
      hPt->SetBinError(i+1,yieldErr/(ptBins[i+1]-ptBins[i]));
      hMean->SetBinContent(i+1,f->GetParameter(1));
      hMean->SetBinError(i+1,f->GetParError(1));
      hSigmaGaus1->SetBinContent(i+1,f->GetParameter(2));
      hSigmaGaus1->SetBinError(i+1,f->GetParError(2));
      hSigmaGaus2->SetBinContent(i+1,f->GetParameter(5));
      hSigmaGaus2->SetBinError(i+1,f->GetParError(5));
      hRelMagnGaus1Gaus2->SetBinContent(i+1,f->GetParameter(4));
      hRelMagnGaus1Gaus2->SetBinError(i+1,f->GetParError(4));
    }  

  ntMC->Project("hPtMC","Dpt",TCut(weight)*(TCut(selmc.Data())&&"(Dgen==23333)"));
  divideBinWidth(hPtMC);
  ntMC->Project("hPtRecoTruth","Dpt",TCut(selmc.Data())&&"(Dgen==23333)");
  divideBinWidth(hPtRecoTruth);
  ntGen->Project("hPtGen","Gpt",TCut(weight)*(TCut(selmcgen.Data())));
  divideBinWidth(hPtGen);

  TCanvas* cPt =  new TCanvas("cPt","",600,600);
  cPt->SetLogy();
  hPt->SetXTitle("D^{0} p_{T} (GeV/c)");
  hPt->SetYTitle("Uncorrected dN(D^{0})/dp_{T}");
  hPt->Sumw2();
  hPt->Draw();
  if(isMC)
    {
      hPtMC->Draw("same hist");
      TLegend* legPt = myLegend(0.55,0.80,0.90,0.94);
      legPt->AddEntry(hPt,"Signal extraction","pl");
      legPt->AddEntry(hPtMC,"Matched reco","lf");
      legPt->Draw("same");  
    }
  hPtMC->Sumw2();
  TH1D* hEff = (TH1D*)hPtMC->Clone("hEff");
  hEff->SetTitle(";D^{0} p_{T} (GeV/c);Efficiency");
  hEff->Sumw2();
  hEff->Divide(hPtGen);
  TCanvas* cEff = new TCanvas("cEff","",600,600);
  hEff->Draw();
  
  TH1D* hPtCor = (TH1D*)hPt->Clone("hPtCor");
  hPtCor->SetTitle(";D^{0} p_{T} (GeV/c);Corrected dN(D^{0})/dp_{T}");
  hPtCor->Divide(hEff);
  TCanvas* cPtCor=  new TCanvas("cCorResult","",600,600);
  cPtCor->SetLogy();
  hPtCor->Draw();
  if(isMC)
    {
      hPtGen->Draw("same hist");
      TLegend* legPtCor = myLegend(0.55,0.80,0.90,0.94);
      legPtCor->AddEntry(hPtCor,"Corrected signal","pl");
      legPtCor->AddEntry(hPtGen,"Generated D^{0}","lf");
      legPtCor->Draw("same");  
    }

  TH1D* hPtSigma= (TH1D*)hPtCor->Clone("hPtSigma");
  hPtSigma->SetTitle(";D^{0} p_{T} (GeV/c);d#sigma(D^{0})/dp_{T} (pb/GeV)");
  hPtSigma->Scale(1./(2*luminosity*BRchain));
  TCanvas* cPtSigma=  new TCanvas("cPtSigma","",600,600);
  cPtSigma->SetLogy();
  hPtSigma->Draw();
  
  TFile* outf = new TFile(outputfile.Data(),"recreate");
  outf->cd();
  hPt->Write();
  hEff->Write();
  hPtGen->Write();
  hPtMC->Write();
  hPtCor->Write();
  hPtSigma->Write();
  hMean->Write();
  hSigmaGaus1->Write();
  hSigmaGaus2->Write();
  hRelMagnGaus1Gaus2->Write();
  outf->Close();
}
Esempio n. 22
0
int plotMass(const char* cut, char *filename) {
  
  // ------ root settings ---------
  gROOT->Reset();  
  gROOT->SetStyle("Plain");
  gStyle->SetPadGridX(kTRUE);
  gStyle->SetPadGridY(kTRUE);
  //gStyle->SetOptStat("kKsSiourRmMen");
  //gStyle->SetOptStat("iourme");
  gStyle->SetOptStat("rme");
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(1111);
  gStyle->SetPadLeftMargin(0.14);
  gStyle->SetPadRightMargin(0.06);
  // ------------------------------ 

  float min=75;
  float max=105;
  int nbins=70;
  float step=(max-min)/float(nbins);
  char stepstr[20];
  sprintf(stepstr,"Events/%4.2f GeV",step);

  TFile *fileData = TFile::Open("results/hzzTree.root");
  TFile *fileDY = TFile::Open("results/hzzTree_id111.root");

  TTree *treeData = (TTree*)fileData->Get("zeetree/probe_tree");
  TTree *treeDY = (TTree*)fileDY->Get("zeetree/probe_tree");
  treeDY->AddFriend( "zeetree/pu_probe_tree = zeetree/probe_tree", "results/hzzTree_id111_puw.root" );

  TH1D *massDYsmear = new TH1D("massDYsmear","",nbins,min,max);
  TH1D *massData = new TH1D("massData","",nbins,min,max);

  // cosmetics
  massDYsmear->Sumw2();
  massDYsmear->SetFillColor(kCyan-9);
  massDYsmear->SetFillStyle(3003);
  massDYsmear->SetLineColor(kAzure+3);
  massDYsmear->GetXaxis()->SetTitle("M_{ee} (GeV/c^{2})");
  massDYsmear->GetYaxis()->SetTitle(stepstr);
  massData->SetMarkerSize(0.8);
  massData->SetMarkerStyle(21);
  massData->SetMaximum(massData->GetMaximum()+0.1*massData->GetMaximum());
  
  TString finalcutData = TString("(")+TString(cut)+TString(")*1");
  TString finalcutMC = TString("(")+TString(cut)+TString(")*puW");
  
  treeData->Project("massData","zmll",finalcutData);
  treeDY->Project("massDYsmear","zmll",finalcutMC);

  massDYsmear->Scale(massData->Integral()/massDYsmear->Integral());

  TLegend* leg = new TLegend(0.2,0.7,0.4,0.89);
  leg->SetBorderSize(     0);
  leg->SetFillColor (     0);
  leg->SetTextAlign (    12);
  leg->SetTextFont  (    42);
  leg->SetTextSize  (0.05);
  leg->SetFillColor(0);
  leg->AddEntry(massDYsmear,"MC smeared","F");
  leg->AddEntry(massData,"Data","pe");

  TCanvas *c1 = new TCanvas("c1","c1");
  massDYsmear->Draw("hist");
  massData->Draw("same pe1");
  leg->Draw();

  c1->SaveAs(filename);

  fileData->Close();
  fileDY->Close();

  return 0;
 
}
Esempio n. 23
0
void drawRAA(bool doInclusiveJet=0, bool useUnfolded=1, bool drawTheory=1){

  bool drawPowheg = 0;
  
  float etalo=-2;
  float etahi=2;

  TH1D *dEta80To110 = new TH1D("dEta80To110","",4,-2.465,1.535);
  TH1D *dEta110To150 = new TH1D("dEta110To150","",4,-2.365,1.635);
  TH1D *dEta70To80 = new TH1D("dEta70To80","",4,-2.565,1.435);
  TH1D *dEta150To190 = new TH1D("dEta150To190","",4,-2.265,1.735);

  int nbins = 3;
  double xbins[4] = {0,20,50,100};
  double xbins2[4] = {2,22,52,102};
  double xbins3[4] = {-2,18,48,98};
  double xbins4[4] = {4,24,54,104};
  TH1D *dCent70To80 = new TH1D("dCent70To80","",nbins,xbins3);
  TH1D *dCent80To110 = new TH1D("dCent80To110","",nbins,xbins);
  TH1D *dCent110To150 = new TH1D("dCent110To150","",nbins,xbins2);
  TH1D *dCent150To190 = new TH1D("dCent150To190","",nbins,xbins4);
  
  //for(int ieta=-2; ieta<2; ieta++){
  //  etalo=(float)(ieta+0.5);
  //  etahi=(float)(ieta+1.5);

  int binLo, binHi;
  //for(int icent=0; icent<3; icent++){
  //  if(icent==0){ binLo = 0; binHi=20; }
  //  if(icent==1){ binLo = 20; binHi=50; }
  //  if(icent==2){ binLo = 50; binHi=100; }
  
    TH1D *h = new TH1D();
    TH1D *h2 = new TH1D();
    TH1D *h_den = new TH1D();
    h->Sumw2();
    h2->Sumw2();
    h_den->Sumw2();
    TH1D *he1 = new TH1D();
    TH1D *he2 = new TH1D();
    TH1D *he3 = new TH1D();
    TH1D *he4 = new TH1D();
    he1->Sumw2(); he2->Sumw2(); he3->Sumw2(); he4->Sumw2();

    //grab unfolded histograms from the unfolding output (inclusive)
    TFile *f0, *f2, *f5,*f6,*f7,*f8;
    TFile *fIncl = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-inc_eta-1.0To1.0.root");
    TFile *fInclB = new TFile("~/bTagTrees/pPb/raa_pp_denomForpA-inc_eta-1.0To1.0.root");
    TH1D *hinclTop = (TH1D*)fIncl->Get("hReco0")->Clone("hinclTop");
    TH1D *hinclBot = (TH1D*)fInclB->Get("hGen_cent1")->Clone("hinclBot");
    for(int i=1; i<=hinclTop->GetNbinsX(); i++){
      hinclTop->SetBinError(i,hinclTop->GetBinError(i)/hinclTop->GetBinWidth(i));
      hinclTop->SetBinContent(i,hinclTop->GetBinContent(i)/hinclTop->GetBinWidth(i));
      hinclBot->SetBinError(i,hinclBot->GetBinError(i)/hinclBot->GetBinWidth(i));
      hinclBot->SetBinContent(i,hinclBot->GetBinContent(i)/hinclBot->GetBinWidth(i));
    }
    hinclTop->Scale(1./6.9);
    hinclTop->Divide(hinclBot);
    hinclTop->SetMarkerColor(4);
    //hinclTop->Scale(0.689);

    //grab unfolded histograms from the unfolding output (bjet)
    if(doInclusiveJet) f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-inc_eta%.1fTo%.1f.root",etalo,etahi));
    //else f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-Incljet_FullDataset_ssvhe20_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi)); //incl jet unfolding
    else if(useUnfolded){
      f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi)); //bjet unfolding
      f5 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta-2.0To-1.0.root");
      f6 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta-1.0To0.0.root");
      f7 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta0.0To1.0.root");
      f8 = new TFile("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_FullDataset_ssvhe20_etaCM_eta1.0To2.0.root");
    }
    else{
      f0 = new TFile(Form("~/bTagTrees/pPb/raa_pPb_numerator-Bjet_NoUnfolding_FullDataset_ssvhe20_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi));
    }

    if(useUnfolded){
      h = (TH1D*)(f0->Get("hReco0"));
      he1 = (TH1D*)(f5->Get("hReco0"));
      he2 = (TH1D*)(f6->Get("hReco0"));
      he3 = (TH1D*)(f7->Get("hReco0"));
      he4 = (TH1D*)(f8->Get("hReco0"));
    }
    else if(doInclusiveJet) h = (TH1D*)(f0->Get("hIncJetsData"));
    else h = (TH1D*)(f0->Get("hReco0"));

    //h = (TH1D*)he1->Clone("h");
    //he1->Add(he2);
    //he1->Add(he3);
    //he1->Add(he4);
    //h->Scale(1./6.9);

    /* for(int i=1; i<=h->GetNbinsX(); i++){
       h->SetBinError(i, h->GetBinError(i)/h->GetBinWidth(i));
       h->SetBinContent(i, h->GetBinContent(i)/h->GetBinWidth(i));
       }*/
    //h->Scale(1./6.9); //pPb total N coll (L*pp x-sec * A, sigma_pp = 70 mb @ CERN)  
  
    if(doInclusiveJet) f2 = new TFile(Form("~/bTagTrees/pPb/raa_pp_denomForpA-inc_eta%.1fTo%.1f.root",etalo,etahi),"OLD");
    else f2 = new TFile(Form("~/bTagTrees/pPb/raa_pp_denomForpA-Bjet_etaCM_v2_bin0_100_eta%.1fTo%.1f.root",etalo,etahi),"OLD"); //incl jet unfolding
    //else f2 = new TFile(Form("raa_pp_denomForpA-Bjet_etaLab_eta%.1fTo%.1f.root",etalo,etahi),"OLD"); //bjet unfolding
    f2->cd();
    //h_den = (TH1D*)(f2->Get("hRawBMC"));
    if(useUnfolded) h_den = (TH1D*)f2->Get("hGen_cent1");
    else if(doInclusiveJet) h_den = (TH1D*)(f2->Get("hIncJetsMC"));
    else h_den = (TH1D*)(f2->Get("hGen_cent1"));

    TFile *xchk = new TFile("histos/ppMC_ppReco_akPu3PF_QCDjetTrig_etashift_Fix2Sample_MCWeightFinalWithVz_noTrgSelection_Full.root");
    TTree *nt1 = (TTree*)xchk->Get("nt");
    double xbinsXchk[19] = {0, 5, 10, 15, 20, 25, 30, 35, 40, 55, 70, 90, 110, 140, 170, 220, 400, 700, 1000};
    TH1D *hf = new TH1D("hf","",18,xbinsXchk); hf->Sumw2();
    nt1->Project("hf","refpt","weight*(abs(refparton_flavorForB)==5 && jteta<2 && jteta>-2 && jtpt>35 && rawpt>20)");
    for(int i=1; i<=hf->GetNbinsX(); i++){
      hf->SetBinError(i,hf->GetBinError(i)/hf->GetBinWidth(i));
      hf->SetBinContent(i,hf->GetBinContent(i)/hf->GetBinWidth(i));
    }
    hf->SetLineColor(kRed+2);
    //hf->Scale(1E9);
    //hf->Scale(1./70.);
    //hf->Scale(10.);
    //h_den = hf;

    TFile *ff = new TFile("pPb_Unfo_inCM_v31_officialMC_ak3PF_akPu3PF_noGplus_FirstHalfOnly_Converged_usedParameterizedUnfold0_jtpt35_bJets_clo0_chi100_v8_eta_-2.00To2.00_.root");
    TH1D *hfCheck2 = (TH1D*)ff->Get("hGen_cent1");
    TFile *ff2 = new TFile("pPb_Unfo_inCM_v31_officialMC_Reverse_WithResCorr_ak3PF_akPu3PF_noGplus_SecondHalfOnly_Converged_usedParameterizedUnfold0_jtpt35_bJets_clo0_chi100_v8_eta_-2.00To2.00_.root");
    TH1D *hfCheck3 = (TH1D*)ff2->Get("hGen_cent1");
    hfCheck2->Add(hfCheck3);
    //hfCheck2 = (TH1D*)hfCheck2->Rebin(16,hfCheck2->GetName(),xbinsXchk);
    
    //Fix raw B MC histogram to have 14 bins to be compatible with the unfolded nonsense
    /*const int fixNbin = h->GetNbinsX();
    Double_t binBoundaries[15];
    for(int ibin=0; ibin<fixNbin; ibin++){
      binBoundaries[ibin] = h->GetBinLowEdge(ibin+1);
    }
    binBoundaries[fixNbin] = h->GetBinLowEdge(fixNbin)+h->GetBinWidth(fixNbin);
    TH1D *h_den_fix = new TH1D("h_den_fix","",fixNbin,binBoundaries); h_den_fix->Sumw2();
    for(int ibin=0; ibin<fixNbin-h_den->GetNbinsX(); ibin++){
      h_den_fix->SetBinContent(ibin+1,0);
      h_den_fix->SetBinError(ibin+1,0);
    }
    for(int ibin=fixNbin-h_den->GetNbinsX(); ibin<fixNbin; ibin++){
      h_den_fix->SetBinContent(ibin+1,h_den->GetBinContent(ibin-(fixNbin-h_den->GetNbinsX())+1));
      h_den_fix->SetBinError(ibin+1,h_den->GetBinError(ibin-(fixNbin-h_den->GetNbinsX())+1));
      }*/
    //end fix

    //h->Draw();
    h->SetTitle("");
    //h_den->SetMarkerColor(2);
    //h_den->Draw("same");
    //h->Divide(h_den);
    h->SetYTitle("#frac{1}{T_{pA}} #frac{d#sigma}{dp_{T}} (1/GeV/c)");
    h->SetMaximum(1E-6);
    h->SetMinimum(1E-11);
    h->Draw();
    h_den->SetMarkerColor(4);
    h_den->Draw("same");
    hfCheck2->Scale(1./70.);
    hfCheck2->SetLineColor(kGreen+2);
    hf->Draw("same");
    he2->SetMarkerColor(kOrange+2);
    he2->Draw("same");
    //hfCheck2->Draw("same");
    //h_den = hfCheck2;
    //c1->SetLogy();

    for(int j=1; j<=h->GetNbinsX(); j++){
      cout << h->GetBinLowEdge(j) << " ";
    }
    cout << h->GetBinLowEdge(h->GetNbinsX())+h->GetBinWidth(h->GetNbinsX()) << endl;

    for(int j=1; j<=h_den->GetNbinsX(); j++){
      cout << h_den->GetBinLowEdge(j) << " ";
    }
    cout << h_den->GetBinLowEdge(h_den->GetNbinsX())+h_den->GetBinWidth(h_den->GetNbinsX()) << endl;

    TH1F *hpow, *hpow15;
    //if(drawPowheg){
      TFile *fpowheg50 = new TFile("Powheg/CMS-Dijet-Analysis-5tev-kt0-pt50Cut-mstwCL60PDF.root");
      hpow = (TH1F*)fpowheg50->Get("d05-x01-y01")->Clone("hpow"); //inclusive eta, ak3 jets
      TFile *fpowheg15 = new TFile("Powheg/CMS-Dijet-Analysis-5tev-kt0-pt20Cut-mstwCL60PDF.root");
      hpow15 = (TH1F*)fpowheg15->Get("d05-x01-y01")->Clone("hpow15");
      hpow15->Scale(25.4); //pthat20 relative (to pthat50) efficiency
      //hpow15->Scale(405.); //pthat 5 relative efficiency
      //hpow15->Scale(15.95);
      for(int i=1; i<=hpow->GetNbinsX(); i++){
	if(hpow->GetBinLowEdge(i)<100){
	  //cout << "edge: "<< hpow->GetBinLowEdge(i) << endl;
	  //cout << "hpow: "<< hpow->GetBinContent(i) << " hpow15: "<< hpow15->GetBinContent(i) << endl;
	  hpow->SetBinContent(i, hpow15->GetBinContent(i));
	  hpow->SetBinError(i, hpow15->GetBinError(i));
	}
      }
      hpow->SetMarkerStyle(20);
      hpow->SetMarkerColor(kOrange+2);
      hpow->SetLineColor(kOrange+2);
      hpow->Scale(2./10.); //fix eta selection
      hpow->Scale(1./70E-3); //correct for sigma_pp
      hpow->Scale(1.851e-3); //correct pthat50 efficiency (148086/80M)
      //hpow->Scale(4.7e-2);
      hpow->Scale(1e-9); //correct ncoll & translate to mb, not pb
      //hpow->Scale(1./50.);
      //hpow->Scale(0.85/(30.));
      if(drawPowheg) hpow->Draw("same");
      // }

    TLegend *t1 = new TLegend(0.5,0.697,0.879,0.906);
    t1->AddEntry(h,"pPb data b-jet spec.","p");
    t1->AddEntry(h2,"pPb MC b-jet spec.","p");
    t1->AddEntry(h_den,"pp MC b-jet spec.","p");
    if(drawPowheg) t1->AddEntry(hpow,"Powheg Spec.","p");
    t1->SetFillColor(0);
    t1->Draw("same");

    TCanvas *c2 = new TCanvas("c2","",600,600); //800,800
    //formatCanvas(c2);
    TH1D *hcln = (TH1D*)h->Clone("hcln");
    cout << "nbin: "<< hcln->GetNbinsX() << endl;
    //double xbinsrebin[17] = {0,5,10,15,20,25,30,35,40,55,70,90,110,140,170,220,400};
    //TH1D *hcln = new TH1D("hcln","",16,xbinsrebin);
    for(int ibin=1; ibin<=hcln->GetNbinsX(); ibin++){
      cout << "content bin " << ibin << " " << hcln->GetBinContent(ibin) << endl;
      cout << "powheg content bin " << ibin << " " << hpow->GetBinContent(ibin) << endl;
      //hcln->SetBinError(ibin,hcln_tmp->GetBinError(ibin));
      //hcln->SetBinContent(ibin,hcln_tmp->GetBinContent(ibin));
      }
    TH1D *hdencln = (TH1D*)h_den->Clone("hdencln");
    TH1D *hclnpow = (TH1D*)hcln->Clone("hclnpow");
    //cout << "WARNING! Scaling denominator for neutrinoless definition change!" << endl;
    //hdencln->Scale(1./1.243);
    if(!drawPowheg) hcln->Divide(hdencln);
    else{
      for(int ibin=1; ibin<=16; ibin++){
	int powbin=ibin;
	if(!useUnfolded) powbin+=8;
	if(!useUnfolded && ibin>8) continue;
	hcln->SetBinError(powbin,sqrt(pow(h_den->GetBinError(ibin)/h_den->GetBinContent(ibin),2)+pow(hpow->GetBinError(powbin)/hpow->GetBinContent(powbin),2)));
	hcln->SetBinContent(powbin,h_den->GetBinContent(ibin)/hpow->GetBinContent(powbin));
      }
    }
    //hcln->Divide(hcln);
    
    //Apply systematic errors to the inclusive eta plot
    TGraphErrors *systErr[7];
    TGraphErrors *unfoldErr[7];

    //set systematics
    const int nBins = 18;
    double xp[nBins], yp[nBins], xerr[nBins], yerr[nBins];
    //double yerrTot[nBins] = {0,0,0,0,0,0,0,0,0.13729, 0.1306, 0.1235, 0.146166, 0.16266, 0.1437,0.1816,0.23813}; //before recalibration
    double yerrTot[nBins] = {0,0,0,0,0,0,0,0,0,0.131694,0.0976, 0.0957, 0.1139, 0.1209, 0.1773, 0.2162,0,0}; //after recalibration
    double unfoldErrTot[nBins] = {0,0,0,0,0,0,0,0,0,0.05,0.05,0.05,0.05,0.05,0.05,0.06,0,0};
    double unfoldErrTotEta1[nBins] = {0,0,0,0,0,0,0,0,0,0.15,0.08,0.06,0.06,0.08,0.04,0.04,0,0};
    //double pythiaSysErr[nBins+1] = {0,0,0,0,0,0,0,0.136,0.138,0.140,0.142,0.148,0.152,0.157,0.164,0.174,0.182}; //option B
    // double optionBExtra[nBins+1] = {0,0,0,0,0,0,0,0,0,0.10,0.111,0.078,0.119,0.108,0.053,0.122,0.168};
    double pythiaSysErr[1] = {0.22}; //option A
    double pythiaYpoints[1] = {1};
    double pythiaXpoints[1] = {10};
    double pythiaXerr[1] = {10};
    for(int i=0; i<nBins; i++){ yerrTot[i] = sqrt(pow(yerrTot[i],2)+pow(unfoldErrTot[i],2)); }
    int j=0;
    if(!doInclusiveJet){
      for(int i=1; i<=hcln->GetNbinsX(); i++){
	xp[i-1] = hcln->GetBinLowEdge(i)+hcln->GetBinWidth(i)/2.;
	yp[i-1] = hcln->GetBinContent(i);
	xerr[i-1] = hcln->GetBinWidth(i)*0.495;
	yerr[i-1] = yerrTot[i-1];
	//pythiaXpoints[i-1] = xp[i-1];
	//pythiaXerr[i-1] = xerr[i-1];

	if(yerr[i-1]>0.001 && yp[i-1]>-1){ 
	  systErr[j] = new TGraphErrors(1,&xp[i-1],&yp[i-1],&xerr[i-1],&yerrTot[i-1]);
	  unfoldErr[j] = new TGraphErrors(1,&xp[i-1],&yp[i-1],&xerr[i-1],&unfoldErrTot[i-1]);
	  systErr[j]->SetName(Form("RpA_SystErr_bin%d",j));
	  j++;
	}
      }
      //pythiaXerr[16] = 0.;
      //pythiaXpoints[16] = 400.;
      /*for(int jj=0; jj<nBins+1; jj++){
	pythiaSysErr[jj]*=(1+optionBExtra[jj]);
	}*/
      TGraphErrors *pythiaErr = new TGraphErrors(1,pythiaXpoints,pythiaYpoints,pythiaXerr,pythiaSysErr);
    }
    //TGraphErrors *systErr = new TGraphErrors(nBins,xp,yp,xerr,yerr);
    double jesx[1]={2.365};
    double jesy[1]={1};
    double jesxerr[1]={.1};
    double jesyerr[1]={0.035};
    TGraphErrors *JESNorm = new TGraphErrors(1,jesx,jesy,jesxerr,jesyerr);
    JESNorm->SetFillColor(kGreen+3);

    hcln->SetMaximum(2.5);
    hcln->SetMinimum(0);
    if(doInclusiveJet) hcln->SetYTitle("Inclusive Jet R_{pA}");
    else hcln->SetYTitle("Nuclear Modification Factor");
    //else hcln->SetYTitle("b-jet R_{pA}^{PYTHIA}");
    hcln->SetXTitle("b-jet p_{T} [GeV/c]");
    hcln->GetXaxis()->SetRangeUser(0,400);
    hcln->GetXaxis()->CenterTitle(0);
    hcln->GetYaxis()->CenterTitle(0);
    hcln->SetMarkerStyle(20);
    hcln->SetMarkerColor(1);
    hcln->SetMarkerSize(1.2);
    for(int i=1; i<hcln->GetNbinsX(); i++){
      if(hcln->GetBinLowEdge(i) < 55){
	hcln->SetBinContent(i,-1);
	hcln->SetBinError(i,0.0001);
      }
    }
    hcln->Draw();
    hclnpow->SetMarkerColor(kOrange+2);
    hclnpow->SetLineColor(kOrange+2);
    if(drawPowheg) hclnpow->Draw("same");
    TLine *at2 = new TLine(0,1,400,1);
    at2->SetLineStyle(7);
    at2->SetLineWidth(1);
    pythiaErr->SetFillColor(kRed-7);
    //pythiaErr->SetFillStyle(1); //3844
    if(!doInclusiveJet){
      for(int i=0; i<7; i++){
	unfoldErr[i]->SetFillColor(kCyan-7);
	systErr[i]->SetFillColor(kYellow-7);
	systErr[i]->SetMarkerStyle(20);
	systErr[i]->Draw("2,same");
	//unfoldErr[i]->Draw("2,same");
      }
    }
    pythiaErr->Draw("2,same");
    double lumix[1] = {10}; double lumiy[1] = {1}; double lumierrx[1] = {10}; double lumierry[1] = {0.035};
    TGraphErrors *lumiErr = new TGraphErrors(1,lumix,lumiy,lumierrx,lumierry);
    lumiErr->SetFillColor(kGreen+3);
    lumiErr->Draw("2,same");
    at2->Draw("same");
    //JESNorm->Draw("2,same");
    hcln->Draw("same");
    
    //JESNorm->Draw("2,same");
  TLine *phigh1 = new TLine(380,1.22,400,1.22);
  phigh1->SetLineColor(2);
  phigh1->SetLineStyle(4);
  phigh1->SetLineWidth(1);
  //phigh1->Draw("same");
  TLine *phigh2 = new TLine(380,0.78,400,0.78);
  phigh2->SetLineColor(2);
  phigh2->SetLineStyle(4);
  phigh2->SetLineWidth(1);
  //phigh2->Draw("same");
  double zeroTemp[1] = {0};
  TGraphErrors *inclJetSys = new TGraphErrors(1,zeroTemp,zeroTemp,zeroTemp,zeroTemp);
  inclJetSys->SetMarkerColor(2);
  inclJetSys->SetMarkerStyle(21);
  inclJetSys->SetFillColor(8);
  //gROOT->ProcessLine(".x ~/Downloads/UnfoldedakPu3PFIncJetRpAvsPtInterpolatedRefEtaBin7.C");
  //gROOT->ProcessLine(".x ~/Downloads/RAA_drawFinal.C");
  if(drawTheory){
    gROOT->ProcessLine(".x ~/Downloads/drawpPbTheory.C");
  }
  TGraph *raaErr = new TGraph();
  raaErr->SetFillColor(kMagenta+1);
  raaErr->SetMarkerStyle(20);
  raaErr->SetMarkerSize(1.2);

  TLegend *leg1 = new TLegend(0.41,0.729,0.88,0.886);
  leg1->SetFillColor(0);
  //leg1->AddEntry(inclJetSys,"Inclusive-Jet R_{pA}, |#eta_{CM}|<0.5","fp");
  //leg1->AddEntry(raaErr,"b-jet R_{AA}, (0-100%), |#eta|<2","fp");
  leg1->AddEntry(systErr[0],"pPb Data, -2 < #eta_{CM} < 2","fp");
  leg1->AddEntry(grepPbtheory,"Ref. [32]","lp");
  //leg1->AddEntry(pythiaErr,"Reference Unc.","f");
  //leg1->AddEntry(lumiErr,"Luminosity Unc.","f");
  //leg1->AddEntry(systErr[0],"Total Systematic Error","f");
  //leg1->AddEntry(unfoldErr[0],"Unfolding Uncertainty","f");
  leg1->Draw("same");

  TLegend *leg3 = new TLegend(0.2,0.207,0.567,0.328);
  leg3->SetFillColor(0);
  leg3->AddEntry(lumiErr,"pPb Luminosity Unc.","f");
  leg3->AddEntry(pythiaErr,"pPb Reference Unc.","f");
  leg3->Draw("same");

  grepPbtheory->Draw("C,same");

  c2->SetTopMargin(0.0734);
  c2->RedrawAxis();

  TLatex *cmsP = new TLatex(16.7,2.25,"CMS ");
  cmsP->SetTextFont(62);
  cmsP->SetTextSize(0.0558);
  cmsP->Draw("same");
  TLatex *l1 = new TLatex(-0.5,0.18,Form("0-100%%",etalo,etahi));
  //l1->Draw("same");
  TLatex *l4 = new TLatex(236.8,2.56,"35 nb^{-1} (5.02 TeV)");//; PbPb L = 150 #mub^{-1}");
  l4->SetTextFont(43);
  l4->SetTextSize(25);
  l4->Draw("same");
  TLatex *l2 = new TLatex(20.77,0.175,"pPb #sqrt{s_{NN}} = 5.02 TeV #int L dt = 35 nb^{-1}"); //35, 20.7, 14
  l2->SetTextSize(0.035);
  //l2->Draw("same");
  TLatex *l3 = new TLatex(-2,0.22,"PbPb #sqrt{s_{NN}} = 2.76 TeV #int L dt = 150 #mub^{-1}");
  l3->SetTextSize(0.035);
  //l3->Draw("same");
  //TLatex *ltag = new TLatex(65,2.2,"CSV > 0.679");
  TLatex *ltag = new TLatex(65,2.2,"SSVHE > 2.0");
  //ltag->Draw("same");
  TFile *out = new TFile("RpA_BJet_Output.root","RECREATE");
  out->cd();
  hcln->SetName("RpA");//,"b jet RpA");
  hcln->Write();
  h->Write();
  h_den->Write();
  for(int i=0; i<7; i++){
    systErr[i]->Write();
  }
  out->Close();

  // hcln->Fit("pol0","","",45,250);
  //hcln->Fit("pol1","","",45,250);

  cout << "values: { ";
  for(int i=1; i<=hcln->GetNbinsX(); i++){
    cout << hcln->GetBinContent(i) << " ";
  }
  cout << " }" << endl;

  cout << "stat err: { ";
  for(int i=1; i<=hcln->GetNbinsX(); i++){
    cout << hcln->GetBinError(i) << " ";
  }
  cout << " }" << endl;

  cout << "syst err: { ";
  for(int i=1; i<=hcln->GetNbinsX(); i++){
    cout << yerrTot[i-1]+(yerrTot[i-1]*hcln->GetBinContent(i)) << " ";
  }
  cout << " }" << endl;
}
Esempio n. 24
0
void MCefficiency(TString inputmc="/data/wangj/MC2015/Dntuple/pp/revised/ntD_pp_Dzero_kpi_prompt/ntD_EvtBase_20160303_Dfinder_20160302_pp_Pythia8_prompt_D0_dPt0tkPt0p5_pthatweight.root", TString selmcgen="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))",TString selmcgenacceptance="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))&&abs(Gtk1eta)<2.0&&abs(Gtk2eta)<2.0&&Gtk1pt>2.0&&Gtk2pt>2.0", TString cut_recoonly="Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>2.0&&Dtrk2Pt>2.0&&Dtrk1PtErr/Dtrk1Pt<0.1&&Dtrk2PtErr/Dtrk2Pt<0.1&&abs(Dtrk1Eta)<2.0&&abs(Dtrk2Eta)<2.0&&Dtrk1Algo>3&&Dtrk1Algo<8&&(Dtrk1PixelHit+Dtrk1StripHit)>=11", TString cut="Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>2.0&&Dtrk2Pt>2.0&&(DsvpvDistance/DsvpvDisErr)>3.5&&(DlxyBS/DlxyBSErr)>1.5&&Dchi2cl>0.05&&Dalpha<0.12&&Dtrk1PtErr/Dtrk1Pt<0.1&&Dtrk2PtErr/Dtrk2Pt<0.1&&abs(Dtrk1Eta)<2.0&&abs(Dtrk2Eta)<2.0&&Dtrk1Algo>3&&Dtrk1Algo<8&&Dtrk2Algo>3&&Dtrk2Algo<8&&(Dtrk1PixelHit+Dtrk1StripHit)>=11&&(Dtrk1Chi2ndf/(Dtrk1nStripLayer+Dtrk1nPixelLayer)<0.15)&&(Dtrk2Chi2ndf/(Dtrk2nStripLayer+Dtrk2nPixelLayer)<0.15)",TString label="PP",TString outputfile="test", int useweight=1, int minfit=2,int maxfit=100)
{
 std::cout<<"option="<<useweight<<std::endl;
 selmc=cut;
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetEndErrorSize(0);
  gStyle->SetMarkerStyle(20);
 
  TFile* infMC = new TFile(inputmc.Data());
  TTree* ntMC = (TTree*)infMC->Get("ntDkpi");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  ntMC->AddFriend(ntGen);
  

  TTree* nthi = (TTree*)infMC->Get("ntHi");
  ntGen->AddFriend(nthi);
  nthi->AddFriend(ntMC);
  ntMC->AddFriend(nthi);

  if (useweight==0){
       weightfunctiongen="1"; 
       weightfunctionreco="1";  
   }   
  if (useweight==1){
     weightfunctiongen="pthatweight";
     weightfunctionreco="pthatweight";  
  }
  
  //ptweight pp
  if (useweight==2){
    weightfunctiongen="pow(10,-0.168499*Gpt+3.872855+Gpt*Gpt*0.000556)+pow(10,-0.068599*Gpt+2.512265+Gpt*Gpt*0.000331)";  
    weightfunctionreco="pow(10,-0.168499*Dgenpt+3.872855+Dgenpt*Dgenpt*0.000556)+pow(10,-0.068599*Dgenpt+2.512265+Dgenpt*Dgenpt*0.000331)"; 
  }
  //ptweight pbpb 
  if (useweight==3){
    weightfunctiongen="pow(10,-0.091618*Gpt+2.966262+Gpt*Gpt*0.000524)+pow(10,-0.167553*Gpt+3.800779+Gpt*Gpt*-0.000798) +1.437905+-0.029141*Gpt+0.000146*Gpt*Gpt"; 
    weightfunctionreco="pow(10,-0.091618*Dgenpt+2.966262+Dgenpt*Dgenpt*0.000524)+pow(10,-0.167553*Dgenpt+3.800779+Dgenpt*Dgenpt*-0.000798) +1.437905+-0.029141*Dgenpt+0.000146*Dgenpt*Dgenpt";
  }
  
   std::cout<<"fit function parameters="<<weightfunctiongen<<std::endl;

  TH1D* hPtMC = new TH1D("hPtMC","",nBins,ptBins);
  TH1D* hPtMCrecoonly = new TH1D("hPtMCrecoonly","",nBins,ptBins);
  TH1D* hPtGen = new TH1D("hPtGen","",nBins,ptBins);
  TH1D* hPtGenAcc = new TH1D("hPtGenAcc","",nBins,ptBins);
  TH1D* hPthat = new TH1D("hPthat","",100,0,500);
  TH1D* hPthatweight = new TH1D("hPthatweight","",100,0,500);
  
  ntMC->Project("hPtMC","Dpt",TCut(weightfunctionreco)*(TCut(selmc.Data())&&"(Dgen==23333)"));
  divideBinWidth(hPtMC);
  ntMC->Project("hPtMCrecoonly","Dpt",TCut(weightfunctionreco)*(TCut(cut_recoonly.Data())&&"(Dgen==23333)"));
  divideBinWidth(hPtMCrecoonly);
  ntGen->Project("hPtGen","Gpt",TCut(weightfunctiongen)*(TCut(selmcgen.Data())));
  divideBinWidth(hPtGen);
  ntGen->Project("hPtGenAcc","Gpt",TCut(weightfunctiongen)*(TCut(selmcgenacceptance.Data())));
  divideBinWidth(hPtGenAcc);

  ntMC->Project("hPthat","pthat","1");
  ntMC->Project("hPthatweight","pthat",TCut("1"));

  hPtMC->Sumw2();
  TH1D* hEff = (TH1D*)hPtMC->Clone("hEff");
  hEff->Divide(hPtGen);

  TH1D* hEffReco = (TH1D*)hPtMCrecoonly->Clone("hEffReco");
  hEffReco->Sumw2();
  hEffReco->Divide(hPtGen);

  TH1D* hEffAcc = (TH1D*)hPtGenAcc->Clone("hEffAcc");
  hEffAcc->Sumw2();
  hEffAcc->Divide(hEffAcc,hPtGen,1,1,"b");
  
  TH1D* hEffSelection = (TH1D*)hPtMC->Clone("hEffSelection");
  hEffSelection->Sumw2();
  hEffSelection->Divide(hEffSelection,hPtMCrecoonly,1,1,"b");
  
  TH2F* hemptyEff=new TH2F("hemptyEff","",50,ptBins[0]-5.,ptBins[nBins]+5.,10.,0,1.5);  
  hemptyEff->GetXaxis()->CenterTitle();
  hemptyEff->GetYaxis()->CenterTitle();
  hemptyEff->GetYaxis()->SetTitle("acceptance x #epsilon_{reco} x #epsilon_{sel} ");
  hemptyEff->GetXaxis()->SetTitle("p_{T} (GeV/c)");
  hemptyEff->GetXaxis()->SetTitleOffset(0.9);
  hemptyEff->GetYaxis()->SetTitleOffset(0.95);
  hemptyEff->GetXaxis()->SetTitleSize(0.05);
  hemptyEff->GetYaxis()->SetTitleSize(0.05);
  hemptyEff->GetXaxis()->SetTitleFont(42);
  hemptyEff->GetYaxis()->SetTitleFont(42);
  hemptyEff->GetXaxis()->SetLabelFont(42);
  hemptyEff->GetYaxis()->SetLabelFont(42);
  hemptyEff->GetXaxis()->SetLabelSize(0.035);
  hemptyEff->GetYaxis()->SetLabelSize(0.035);  
  hemptyEff->SetMaximum(2);
  hemptyEff->SetMinimum(0.);
  hemptyEff->Draw();

  TH2F* hemptyEffAcc=(TH2F*)hemptyEff->Clone("hemptyEffAcc");
  TH2F* hemptyEffReco=(TH2F*)hemptyEff->Clone("hemptyEffReco");
  TH2F* hemptyEffSelection=(TH2F*)hemptyEff->Clone("hemptyEffSelection");
  
  TCanvas*canvasEff=new TCanvas("canvasEff","canvasEff",1000.,500);
  canvasEff->Divide(2,1);
  canvasEff->cd(1);
  
  hemptyEffAcc->SetYTitle("#alpha");
  hemptyEffAcc->Draw();
  hEffAcc->Draw("same");
  /*
  canvasEff->cd(2);
  hEffReco->GetYaxis()->SetTitleOffset(1.2);
  hemptyEffReco->SetYTitle("#alpha x #epsilon_{reco} ");
  hemptyEffReco->Draw();
  hEffReco->Draw("same");
  canvasEff->cd(3);
  hemptyEffSelection->SetYTitle(" #epsilon_{sel}");
  hemptyEffSelection->Draw();  
  hEffSelection->Draw("same");  
  */
  canvasEff->cd(2);
  hemptyEff->Draw();
  hEff->Draw("same");
  canvasEff->SaveAs(Form("canvasEff_study%s.pdf",Form(label.Data())));
  
  
  TH2F* hemptyPthat=new TH2F("hemptyPthat","",50,0.,500.,10,1e-5,1e9);  
  hemptyPthat->GetXaxis()->CenterTitle();
  hemptyPthat->GetYaxis()->CenterTitle();
  hemptyPthat->GetYaxis()->SetTitle("Entries");
  hemptyPthat->GetXaxis()->SetTitle("pthat");
  hemptyPthat->GetXaxis()->SetTitleOffset(0.9);
  hemptyPthat->GetYaxis()->SetTitleOffset(0.95);
  hemptyPthat->GetXaxis()->SetTitleSize(0.05);
  hemptyPthat->GetYaxis()->SetTitleSize(0.05);
  hemptyPthat->GetXaxis()->SetTitleFont(42);
  hemptyPthat->GetYaxis()->SetTitleFont(42);
  hemptyPthat->GetXaxis()->SetLabelFont(42);
  hemptyPthat->GetYaxis()->SetLabelFont(42);
  hemptyPthat->GetXaxis()->SetLabelSize(0.035);
  hemptyPthat->GetYaxis()->SetLabelSize(0.035);  
  hemptyPthat->SetMaximum(2);
  hemptyPthat->SetMinimum(0.);


  TH2F* hemptySpectra=new TH2F("hemptySpectra","",50,0.,130.,10,1,1e5);  
  hemptySpectra->GetXaxis()->CenterTitle();
  hemptySpectra->GetYaxis()->CenterTitle();
  hemptySpectra->GetYaxis()->SetTitle("Entries");
  hemptySpectra->GetXaxis()->SetTitle("p_{T}");
  hemptySpectra->GetXaxis()->SetTitleOffset(0.9);
  hemptySpectra->GetYaxis()->SetTitleOffset(0.95);
  hemptySpectra->GetXaxis()->SetTitleSize(0.05);
  hemptySpectra->GetYaxis()->SetTitleSize(0.05);
  hemptySpectra->GetXaxis()->SetTitleFont(42);
  hemptySpectra->GetYaxis()->SetTitleFont(42);
  hemptySpectra->GetXaxis()->SetLabelFont(42);
  hemptySpectra->GetYaxis()->SetLabelFont(42);
  hemptySpectra->GetXaxis()->SetLabelSize(0.035);
  hemptySpectra->GetYaxis()->SetLabelSize(0.035);  

  TH2F* hemptyPthatWeighted=(TH2F*)hemptyPthat->Clone("hemptyPthatWeighted");
  hemptyPthatWeighted->GetXaxis()->SetTitle("pthat reweighted");
  
  TCanvas*canvasPthat=new TCanvas("canvasPthat","canvasPthat",1000.,500);
  canvasPthat->Divide(2,1);
  canvasPthat->cd(1);
  gPad->SetLogy();
  hemptyPthat->Draw("same");
  hPthat->Draw("same");
  canvasPthat->cd(2);
  gPad->SetLogy();
  hemptyPthatWeighted->Draw();
  hPthatweight->Draw("same");
 // canvasPthat->SaveAs(Form("canvasPthat_%s.pdf",Form(label.Data())));
  
  TCanvas*canvasSpectra=new TCanvas("canvasSpectra","canvasSpectra",1000.,500);
  canvasSpectra->Divide(2,1);
  canvasSpectra->cd(1);
  gPad->SetLogy();
  hemptySpectra->Draw();
  hPtMC->Draw("same");
  canvasSpectra->cd(2);
  gPad->SetLogy();
  hemptySpectra->Draw();
  hPtGen->Draw("same");
  //canvasSpectra->SaveAs(Form("canvasSpectra_%s.pdf",Form(label.Data())));

  TFile *fout=new TFile(outputfile.Data(),"recreate");
  fout->cd();
  hPtGen->Write();
  hEffAcc->Write();
  hEffReco->Write();
  hEffSelection->Write();
  hEff->Write();
  hPtMC->Write();
  fout->Close();  

}
Esempio n. 25
0
int main(int argc, char* argv[])
{
  TApplication theApp(srcName.Data(), &argc, argv);
//=============================================================================

  for (int i=0; i<argc; i++) cout << i << ", " << argv[i] << endl;
//=============================================================================

  if (argc<5) return -1;
  TString sPath = argv[1]; if (sPath.IsNull()) return -1;
  TString sFile = argv[2]; if (sFile.IsNull()) return -1;
  TString sJetR = argv[3]; if (sJetR.IsNull()) return -1;
  TString sSjeR = argv[4]; if (sSjeR.IsNull()) return -1;
//=============================================================================

  sPath.ReplaceAll("#", "/");
//=============================================================================

  double dJetR = -1.;
  if (sJetR=="JetR02") dJetR = 0.2;
  if (sJetR=="JetR03") dJetR = 0.3;
  if (sJetR=="JetR04") dJetR = 0.4;
  if (sJetR=="JetR05") dJetR = 0.5;

  if (dJetR<0.) return -1;
  cout << "Jet R = " << dJetR << endl;
//=============================================================================

  double dSjeR = -1.;
  if (sSjeR=="SjeR01") dSjeR = 0.1;
  if (sSjeR=="SjeR02") dSjeR = 0.2;
  if (sSjeR=="SjeR03") dSjeR = 0.3;
  if (sSjeR=="SjeR04") dSjeR = 0.4;

  if (dSjeR<0.) return -1;
  cout << "Sub-jet R = " << dSjeR << endl;
//=============================================================================

  const double dJetsPtMin  = 0.001;
  const double dCutEtaMax  = 1.6;
  const double dJetEtaMax  = 1.;
  const double dJetAreaRef = TMath::Pi() * dJetR * dJetR;

  fastjet::GhostedAreaSpec areaSpc(dCutEtaMax);
  fastjet::JetDefinition   jetsDef(fastjet::antikt_algorithm, dJetR, fastjet::BIpt_scheme, fastjet::Best);

//fastjet::AreaDefinition  areaDef(fastjet::active_area,areaSpc);
  fastjet::AreaDefinition  areaDef(fastjet::active_area_explicit_ghosts,areaSpc);

//fastjet::JetDefinition   bkgsDef(fastjet::kt_algorithm, 0.2, fastjet::BIpt_scheme, fastjet::Best);
//fastjet::AreaDefinition  aBkgDef(fastjet::active_area_explicit_ghosts, areaSpc);

  fastjet::Selector selectJet = fastjet::SelectorAbsEtaMax(dJetEtaMax);
//fastjet::Selector selectRho = fastjet::SelectorAbsEtaMax(dCutEtaMax-0.2);
//fastjet::Selector selecHard = fastjet::SelectorNHardest(2);
//fastjet::Selector selectBkg = selectRho * (!(selecHard));
//fastjet::JetMedianBackgroundEstimator bkgsEstimator(selectBkg, bkgsDef, aBkgDef);
//fastjet::Subtractor                   bkgSubtractor(&bkgsEstimator);

  fastjet::JetDefinition subjDef(fastjet::antikt_algorithm, dSjeR, fastjet::BIpt_scheme, fastjet::Best);
//=============================================================================

  std::vector<fastjet::PseudoJet> fjInput;
//=============================================================================

  TList *list = new TList();
  TH1D *hPtHat = new TH1D("hPtHat", "", 1000, 0., 1000.);

  TH1D *hJet = new TH1D("hJet", "", 1000, 0., 1000.); hJet->Sumw2(); list->Add(hJet);
  TH2D *hJetNsj = new TH2D("hJetNsj", "", 1000, 0., 1000., 101, -0.5, 100.5); hJetNsj->Sumw2(); list->Add(hJetNsj);

  TH2D *hJetIsj = new TH2D("hJetIsj", "", 1000, 0., 1000., 1000, 0., 1000.); hJetIsj->Sumw2(); list->Add(hJetIsj);
  TH2D *hJet1sj = new TH2D("hJet1sj", "", 1000, 0., 1000., 1000, 0., 1000.); hJet1sj->Sumw2(); list->Add(hJet1sj);
  TH2D *hJet2sj = new TH2D("hJet2sj", "", 1000, 0., 1000., 1000, 0., 1000.); hJet2sj->Sumw2(); list->Add(hJet2sj);
  TH2D *hJetDsj = new TH2D("hJetDsj", "", 1000, 0., 1000., 1000, 0., 1000.); hJetDsj->Sumw2(); list->Add(hJetDsj);

  TH2D *hJetIsz = new TH2D("hJetIsz", "", 1000, 0., 1000., 120, 0., 1.2); hJetIsz->Sumw2(); list->Add(hJetIsz);
  TH2D *hJet1sz = new TH2D("hJet1sz", "", 1000, 0., 1000., 120, 0., 1.2); hJet1sz->Sumw2(); list->Add(hJet1sz);
  TH2D *hJet2sz = new TH2D("hJet2sz", "", 1000, 0., 1000., 120, 0., 1.2); hJet2sz->Sumw2(); list->Add(hJet2sz);
  TH2D *hJetDsz = new TH2D("hJetDsz", "", 1000, 0., 1000., 120, 0., 1.2); hJetDsz->Sumw2(); list->Add(hJetDsz);
//=============================================================================

  AliRunLoader *rl = AliRunLoader::Open(Form("%s/galice.root",sPath.Data())); if (!rl) return -1;

  if (rl->LoadHeader()) return -1;
  if (rl->LoadKinematics("READ")) return -1;
//=============================================================================

  for (Int_t iEvent=0; iEvent<rl->GetNumberOfEvents(); iEvent++) {
    fjInput.resize(0);
    if (rl->GetEvent(iEvent)) continue;
//=============================================================================

    AliStack  *pStack  = rl->Stack();     if (!pStack)  continue;
    AliHeader *pHeader = rl->GetHeader(); if (!pHeader) continue;
//=============================================================================

    AliGenPythiaEventHeader *pHeadPy = (AliGenPythiaEventHeader*)pHeader->GenEventHeader();

    if (!pHeadPy) continue;
    hPtHat->Fill(pHeadPy->GetPtHard());
//=============================================================================

    for (Int_t i=0; i<pStack->GetNtrack(); i++) if (pStack->IsPhysicalPrimary(i)) {
      TParticle *pTrk = pStack->Particle(i); if (!pTrk) continue;
      if (TMath::Abs(pTrk->Eta())>dCutEtaMax) { pTrk = 0; continue; }
//    TParticlePDG *pPDG = pTrk->GetPDG(); if (!pPDG) { pTrk = 0; continue; }

      fjInput.push_back(fastjet::PseudoJet(pTrk->Px(), pTrk->Py(), pTrk->Pz(), pTrk->P()));

//    pPDG = 0;
      pTrk = 0;
    }
//=============================================================================

    fastjet::ClusterSequenceArea clustSeq(fjInput, jetsDef, areaDef);
    std::vector<fastjet::PseudoJet> includJets = clustSeq.inclusive_jets(dJetsPtMin);
//  std::vector<fastjet::PseudoJet> subtedJets = bkgSubtractor(includJets);
    std::vector<fastjet::PseudoJet> selectJets = selectJet(includJets);
//  std::vector<fastjet::PseudoJet> sortedJets = fastjet::sorted_by_pt(selectJets);

    for (int j=0; j<selectJets.size(); j++) {
      double dJet = selectJets[j].pt();

      hJet->Fill(dJet);
//=============================================================================

      fastjet::Filter trimmer(subjDef, fastjet::SelectorPtFractionMin(0.));
      fastjet::PseudoJet trimmdJet = trimmer(selectJets[j]);
      std::vector<fastjet::PseudoJet> trimmdSj = trimmdJet.pieces();

      double nIsj = 0.;
      double d1sj = -1.; int k1sj = -1;
      double d2sj = -1.; int k2sj = -1;
      for (int i=0; i<trimmdSj.size(); i++) {
        double dIsj = trimmdSj[i].pt(); if (dIsj<0.001) continue;

        hJetIsj->Fill(dJet, dIsj);
        hJetIsz->Fill(dJet, dIsj/dJet);

        if (dIsj>d1sj) {
          d2sj = d1sj; k2sj = k1sj;
          d1sj = dIsj; k1sj = i;
        } else if (dIsj>d2sj) {
          d2sj = dIsj; k2sj = i;
        } nIsj += 1.;
      }

      hJetNsj->Fill(dJet, nIsj);
      if (d1sj>0.) { hJet1sj->Fill(dJet, d1sj); hJet1sz->Fill(dJet, d1sj/dJet); }
      if (d2sj>0.) { hJet2sj->Fill(dJet, d2sj); hJet2sz->Fill(dJet, d2sj/dJet); }

      if ((d1sj>0.) && (d2sj>0.)) {
        double dsj = d1sj - d2sj;
        double dsz = dsj / dJet;

        hJetDsj->Fill(dJet, dsj);
        hJetDsz->Fill(dJet, dsz);
      }
    }
//=============================================================================

    pStack  = 0;
    pHeadPy = 0;
    pHeader = 0;
  }
//=============================================================================

  rl->UnloadgAlice();
  rl->UnloadHeader();
  rl->UnloadKinematics();
  rl->RemoveEventFolder();
//=============================================================================

  TFile *file = TFile::Open(Form("%s/pyxsec_hists.root",sPath.Data()), "READ");
  TList *lXsc = (TList*)file->Get("cFilterList");
  file->Close();

  TH1D     *hWeightSum = (TH1D*)lXsc->FindObject("h1Trials");   hWeightSum->SetName("hWeightSum");
  TProfile *hSigmaGen  = (TProfile*)lXsc->FindObject("h1Xsec"); hSigmaGen->SetName("hSigmaGen");
//=============================================================================

  file = TFile::Open(Form("%s.root",sFile.Data()), "NEW");
  hPtHat->Write();
  hWeightSum->Write();
  hSigmaGen->Write();
  list->Write();
  file->Close();
//=============================================================================

  cout << "DONE" << endl;
//=============================================================================

  return 0;
}
Esempio n. 26
0
void makePlots_hltEleHT_Zcr( bool printPDF_ = false, double sfMC_ = 1., bool renorm_ = false ){

  TH1::SetDefaultSumw2();

  TFile* file_data = new TFile("HistoFiles/hltEleHT_treeReader_Zcr_SingleElectron_Run2015D_PromptReco_254231_258158_histo.root");
  TFile* file_mc   = new TFile("HistoFiles/hltEleHT_treeReader_Zcr_DYJets_M50_13TeV_Spring15_Asympt25ns_histo.root");

  std::vector<TString> histLabels(2);
  histLabels[0] = "SingleElectron";
  histLabels[1] = "DYJetsToLL_M50";

  Color_t color[8];
  color[0] = kBlue;
  color[1] = kRed;

  // color[2] = kBlack;
  // color[3] = kGreen+1;
  // color[4] = kMagenta+2;
  // color[5] = kRed+1;
  // color[6] = kGreen-5;
  // color[7] = kRed+3;


  TString dirprefix = "Images/Images_2015_11_06_hltEleHT_Zcr/";
  if( renorm_ ) dirprefix = "Images/Images_2015_11_06_hltEleHT_Zcr_renorm/";

  struct stat st;
  if( stat(dirprefix.Data(),&st) != 0 )  mkdir(dirprefix.Data(),0777);


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

  std::vector<std::string> histoname1;
  std::vector<std::string> histoname2;

  histoname1.push_back("h_probe_pt");
  histoname1.push_back("h_probe_eta");
  histoname1.push_back("h_probe_phi");
  histoname1.push_back("h_probe_numPVs");
  histoname1.push_back("h_HT30");
  histoname1.push_back("h_HT30_v2");

  histoname2.push_back("h_numPVs");
  histoname2.push_back("h_numPVs_PUwgt");
  histoname2.push_back("h_event_selection");
  histoname2.push_back("h_diele_mass");
  histoname2.push_back("h_diele_mass_closestZmass");
  histoname2.push_back("h_diele_deltaR");
  histoname2.push_back("h_L1HTT");
  histoname2.push_back("h_HT30");
  histoname2.push_back("h_HT30_L1HTT125");
  histoname2.push_back("h_HT30_L1HTT125_passHLTEle27HT200");

  histoname2.push_back("h_met_pt");

  histoname2.push_back("h_jet_1_pt");
  histoname2.push_back("h_jet_2_pt");
  histoname2.push_back("h_jet_3_pt");
  histoname2.push_back("h_jet_4_pt");

  histoname2.push_back("h_jet_pt");
  histoname2.push_back("h_jet_eta");
  histoname2.push_back("h_jet_phi");
  histoname2.push_back("h_jet_csv");

  histoname2.push_back("h_numJet");
  histoname2.push_back("h_numBtag");

  histoname2.push_back("h_deltaR_jet_ele");

  histoname2.push_back("h_numL1EG25");
  histoname2.push_back("h_l1EG25_pt");
  histoname2.push_back("h_l1EG25_eta");
  histoname2.push_back("h_l1EG25_phi");
  histoname2.push_back("h_l1EG25_1_pt");
  histoname2.push_back("h_l1EG25_2_pt");
  histoname2.push_back("h_l1EG25_1_eta");
  histoname2.push_back("h_l1EG25_2_eta");


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

  TGaxis::SetMaxDigits(3);

  TString lumiinfo = "553 pb^{-1} (13 TeV)";
  TLatex LumiInfoLatex(0.70, 0.91, lumiinfo);
  LumiInfoLatex.SetNDC(); LumiInfoLatex.SetTextFont(42);
  LumiInfoLatex.SetTextSize(0.04);

  //TString cmsinfo =   "CMS Preliminary";
  TString cmsinfo =   "CMS";
  TLatex CMSInfoLatex(0.18, 0.91, cmsinfo);
  CMSInfoLatex.SetNDC(); CMSInfoLatex.SetTextFont(42);
  CMSInfoLatex.SetTextFont(61);
  CMSInfoLatex.SetTextSize(0.055); //SBOUTLE

  std::string publishinfo =   "Preliminary"; //DPUIGH
  TLatex PublishInfoLatex(0.28, 0.91, publishinfo.c_str()); //SBOUTLE
  PublishInfoLatex.SetNDC();
  PublishInfoLatex.SetTextFont(52);
  PublishInfoLatex.SetTextSize(0.045); //SBOUTLE


  TString plotname;

  TCanvas* myC1 = new TCanvas("myC1", "myC1", 600,700);
  gStyle->SetPadBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  Float_t small = 1.e-5;
  myC1->Divide(1,2,small,small);
  const float padding=1e-5; const float ydivide=0.3;
  myC1->GetPad(1)->SetPad( padding, ydivide + padding , 1-padding, 1-padding);
  myC1->GetPad(2)->SetPad( padding, padding, 1-padding, ydivide-padding);
  myC1->GetPad(1)->SetLeftMargin(.11);
  myC1->GetPad(2)->SetLeftMargin(.11);
  myC1->GetPad(1)->SetRightMargin(.05);
  myC1->GetPad(2)->SetRightMargin(.05);
  myC1->GetPad(1)->SetBottomMargin(.3);
  myC1->GetPad(2)->SetBottomMargin(.3);
  myC1->GetPad(1)->Modified();
  myC1->GetPad(2)->Modified();
  myC1->cd(1);
  gPad->SetBottomMargin(small);
  gPad->Modified();


  for( int i=0; i<int(histoname1.size()); i++ ){

    TString temp = histoname1[i];
    
    TString temp_mh = temp;
    temp_mh.ReplaceAll("h_","");

    // TLegend *legend = new TLegend(0.1,0.91,0.9,0.99);
    //TLegend *legend = new TLegend(0.2,0.91,0.9,0.99);
    //TLegend *legend = new TLegend(0.1,0.91,0.9,0.99);
    TLegend *legend = new TLegend(0.2,0.83,0.9,0.89);

    legend->SetFillColor(kWhite);
    legend->SetLineColor(kWhite);
    legend->SetShadowColor(kWhite);
    legend->SetTextFont(42);
    legend->SetTextSize(0.04);

    legend->SetNColumns(2);

    int rebin = 1;

    if( temp.Contains("_HT30") ) rebin = 10;

    TString s_all = temp+"_all";
    TString s_l1t = temp+"_pL1T";
    TString s_hlt = temp+"_pHLT";

    if( temp.Contains("_HT30") ){
      s_all = temp+"";
      s_l1t = temp+"_L1HTT125";
      s_hlt = temp+"_L1HTT125_passHLTEle27HT200";
    }
    if( temp.Contains("_HT30_v2") ){
      s_all = temp+"";
      s_l1t = temp+"_L1HTT";
      s_hlt = temp+"_L1HTT_HLTHT";
    }

    TH1D* h_data_all = (TH1D*)file_data->Get(s_all);
    TH1D* h_data_l1t = (TH1D*)file_data->Get(s_l1t);
    TH1D* h_data_hlt = (TH1D*)file_data->Get(s_hlt);

    TH1D* h_mc_all = (TH1D*)file_mc->Get(s_all);
    TH1D* h_mc_l1t = (TH1D*)file_mc->Get(s_l1t);
    TH1D* h_mc_hlt = (TH1D*)file_mc->Get(s_hlt);


    h_data_all->Rebin(rebin);
    h_data_l1t->Rebin(rebin);
    h_data_hlt->Rebin(rebin);

    h_mc_all->Rebin(rebin);
    h_mc_l1t->Rebin(rebin);
    h_mc_hlt->Rebin(rebin);

    double eps = 0.001;
    int nbins = h_data_all->GetNbinsX();

    for( int iBin=0; iBin<nbins+1; iBin++ ){
      double content1 = h_mc_hlt->GetBinContent(iBin+1);
      double content2 = h_mc_l1t->GetBinContent(iBin+1);
      double content3 = h_mc_all->GetBinContent(iBin+1);

      double diff12 = content1 - content2;
      if( diff12>0 ) content2 += diff12 + eps;

      double diff23 = content2 - content3;
      if( diff23>0 ) content3 += diff23 + eps;

      h_mc_l1t->SetBinContent(iBin+1,content2);
      h_mc_all->SetBinContent(iBin+1,content3);
    }


    TEfficiency* h_eff_data_l1t_all = new TEfficiency(*h_data_l1t, *h_data_all);
    TEfficiency* h_eff_data_hlt_all = new TEfficiency(*h_data_hlt, *h_data_all);
    TEfficiency* h_eff_data_hlt_l1t = new TEfficiency(*h_data_hlt, *h_data_l1t);

    TEfficiency* h_eff_mc_l1t_all = new TEfficiency(*h_mc_l1t, *h_mc_all);
    TEfficiency* h_eff_mc_hlt_all = new TEfficiency(*h_mc_hlt, *h_mc_all);
    TEfficiency* h_eff_mc_hlt_l1t = new TEfficiency(*h_mc_hlt, *h_mc_l1t);

    h_eff_data_l1t_all->SetLineColor(color[0]);
    h_eff_data_l1t_all->SetMarkerColor(color[0]);
    h_eff_data_l1t_all->SetMarkerStyle(20);

    h_eff_data_hlt_all->SetLineColor(color[0]);
    h_eff_data_hlt_all->SetMarkerColor(color[0]);
    h_eff_data_hlt_all->SetMarkerStyle(20);

    h_eff_data_hlt_l1t->SetLineColor(color[0]);
    h_eff_data_hlt_l1t->SetMarkerColor(color[0]);
    h_eff_data_hlt_l1t->SetMarkerStyle(20);

    h_eff_mc_l1t_all->SetLineColor(color[1]);
    h_eff_mc_l1t_all->SetMarkerColor(color[1]);
    h_eff_mc_l1t_all->SetMarkerStyle(20);

    h_eff_mc_hlt_all->SetLineColor(color[1]);
    h_eff_mc_hlt_all->SetMarkerColor(color[1]);
    h_eff_mc_hlt_all->SetMarkerStyle(20);

    h_eff_mc_hlt_l1t->SetLineColor(color[1]);
    h_eff_mc_hlt_l1t->SetMarkerColor(color[1]);
    h_eff_mc_hlt_l1t->SetMarkerStyle(20);


    legend->AddEntry(h_eff_data_l1t_all,histLabels[0],"p");
    legend->AddEntry(h_eff_mc_l1t_all,histLabels[1],"p");


    TH1D* h_ratio_eff_l1t_all = divide_ratio_plots(h_data_l1t, h_data_all, h_mc_l1t, h_mc_all);
    TH1D* h_ratio_eff_hlt_all = divide_ratio_plots(h_data_hlt, h_data_all, h_mc_hlt, h_mc_all);
    TH1D* h_ratio_eff_hlt_l1t = divide_ratio_plots(h_data_hlt, h_data_l1t, h_mc_hlt, h_mc_l1t);

    h_ratio_eff_l1t_all->SetMarkerStyle(20);
    h_ratio_eff_hlt_all->SetMarkerStyle(20);
    h_ratio_eff_hlt_l1t->SetMarkerStyle(20);


    h_data_all->SetStats(0);

    //c3->SetTopMargin(.05);
    //c1->SetRightMargin(.05);

    double ratioMax = 1.6;
    double ratioMin = 0.5;

    double xmin = h_data_all->GetBinLowEdge(1);
    double xmax = h_data_all->GetBinLowEdge(nbins) + h_data_all->GetBinWidth(nbins);


    TH1D* myRatio = (TH1D*)h_data_all->Clone("ratio_"+temp);
    //new TH1D("ratio", "", nbins, xmin, xmax );

    myRatio->SetStats(0);
    myRatio->Sumw2();
    myRatio->SetLineColor(kBlack);
    myRatio->SetMarkerColor(kBlack);
    //myRatio->Divide(hist[bin_one],hist[bin_two]);

    myRatio->SetMinimum(ratioMin);
    myRatio->SetMaximum(ratioMax);
    //myRatio->GetYaxis()->SetNdivisions(50000+404);
    myRatio->GetYaxis()->SetNdivisions(50000+204);
    myRatio->GetYaxis()->SetLabelSize(0.1); //make y label bigger
    myRatio->GetXaxis()->SetLabelSize(0.1); //make y label bigger
    myRatio->GetXaxis()->SetTitleOffset(1.1);
    myRatio->GetXaxis()->SetTitle(h_data_all->GetXaxis()->GetTitle()); //make y label bigger
    myRatio->GetXaxis()->SetLabelSize(0.12);
    myRatio->GetXaxis()->SetLabelOffset(0.04);
    myRatio->GetXaxis()->SetTitleSize(0.12);
    myRatio->GetYaxis()->SetTitle("Data/MC");
    myRatio->GetYaxis()->SetTitleSize(0.09);
    myRatio->GetYaxis()->SetTitleOffset(.55);
    myC1->cd(2);
    gPad->SetTopMargin(small);
    gPad->SetTickx();
    gPad->Modified();


    myRatio->GetYaxis()->CenterTitle(kTRUE);


    double maxPt = 499.9999;
    double minPt = 0.000001;

    h_data_all->GetYaxis()->SetTitleOffset(1.0);
    h_data_all->GetYaxis()->SetTitleSize(0.05);

    h_data_all->GetYaxis()->SetTitle("Efficiency");

    h_data_all->GetYaxis()->SetRangeUser(0.,1.15);


    bool rerange = false;
    //if( (temp.Contains("_pt")) ){ rerange=true; xmin = 10.0001; xmax = 199.9; }
    if( (temp.Contains("_pt")) ){ rerange=true; xmin = 30.001; xmax = 199.9; }

    if( rerange ){
      h_data_all->GetXaxis()->SetRangeUser(xmin,xmax);
      myRatio->GetXaxis()->SetRangeUser(xmin,xmax);
    }

    if( temp.Contains("_pt") ){
      h_data_all->GetYaxis()->SetRangeUser(0.5,1.05);
    }

    if( temp.Contains("_numPVs") ){
      h_data_all->GetYaxis()->SetRangeUser(0.45,1.05);
    }

    // if( temp.Contains("_eta") ) h_all->GetYaxis()->SetRangeUser(0.4,1.1);
    // if( temp.Contains("_numGenPVs") ) h_all->GetYaxis()->SetRangeUser(0.4,1.1);
    // if( temp.Contains("_numJets") ) h_all->GetYaxis()->SetRangeUser(0.4,1.1);


    TLine* myLine;
    myLine = new TLine(xmin, 1, xmax, 1);


    //// l1t_all
    myC1->cd(1);
    h_data_all->Draw("axis");
    h_eff_data_l1t_all->Draw("pe1same");
    h_eff_mc_l1t_all->Draw("pe1same");
    legend->Draw();
    LumiInfoLatex.Draw();
    CMSInfoLatex.Draw();
    PublishInfoLatex.Draw();

    myC1->cd(2);
    myRatio->SetLineWidth(2);
    myRatio->Draw("axis");
    myLine->Draw();

    h_ratio_eff_l1t_all->Draw("pe1same");

    plotname = dirprefix + temp_mh + "_data2mc_eff_l1t_all_lin.png";
    myC1->Print(plotname);

    plotname = dirprefix + temp_mh + "_data2mc_eff_l1t_all_lin.pdf";
    if( printPDF_ ) myC1->Print(plotname);


    //// hlt_all
    myC1->cd(1);
    h_data_all->Draw("axis");
    h_eff_data_hlt_all->Draw("pe1same");
    h_eff_mc_hlt_all->Draw("pe1same");
    legend->Draw();
    LumiInfoLatex.Draw();
    CMSInfoLatex.Draw();
    PublishInfoLatex.Draw();

    myC1->cd(2);
    myRatio->SetLineWidth(2);
    myRatio->Draw("axis");
    myLine->Draw();

    h_ratio_eff_hlt_all->Draw("pe1same");

    plotname = dirprefix + temp_mh + "_data2mc_eff_hlt_all_lin.png";
    myC1->Print(plotname);

    plotname = dirprefix + temp_mh + "_data2mc_eff_hlt_all_lin.pdf";
    if( printPDF_ ) myC1->Print(plotname);


    //// hlt_l1t
    myC1->cd(1);
    h_data_all->Draw("axis");
    h_eff_data_hlt_l1t->Draw("pe1same");
    h_eff_mc_hlt_l1t->Draw("pe1same");
    legend->Draw();
    LumiInfoLatex.Draw();
    CMSInfoLatex.Draw();
    PublishInfoLatex.Draw();

    myC1->cd(2);
    myRatio->SetLineWidth(2);
    myRatio->Draw("axis");
    myLine->Draw();

    h_ratio_eff_hlt_l1t->Draw("pe1same");

    plotname = dirprefix + temp_mh + "_data2mc_eff_hlt_l1t_lin.png";
    myC1->Print(plotname);

    plotname = dirprefix + temp_mh + "_data2mc_eff_hlt_l1t_lin.pdf";
    if( printPDF_ ) myC1->Print(plotname);



    delete myRatio;
    delete myLine;
    delete legend;
  } // end loop on hists


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


  for( int i=0; i<int(histoname2.size()); i++ ){

    TString temp = histoname2[i];
    
    TString temp_mh = temp;
    temp_mh.ReplaceAll("h_","");

    //TLegend *legend = new TLegend(0.1,0.91,0.9,0.99);
    TLegend *legend = new TLegend(0.2,0.83,0.88,0.89);

    legend->SetFillColor(kWhite);
    legend->SetLineColor(kWhite);
    legend->SetShadowColor(kWhite);
    legend->SetTextFont(42);
    legend->SetTextSize(0.04);

    legend->SetNColumns(2);

    int rebin = 1;

    if( temp.Contains("_mass") ) rebin = 2;
    if( temp.Contains("_L1HTT") ) rebin = 2;
    if( temp.Contains("_met") ) rebin = 5;
    if( temp.Contains("_jet_") && temp.Contains("_pt") ) rebin = 10;
    if( temp.Contains("_jet_") && temp.Contains("_eta") ) rebin = 4;
    if( temp.Contains("_jet_") && temp.Contains("_phi") ) rebin = 4;
    if( temp.Contains("_csv") ) rebin = 8;

    if( temp.Contains("_diele_mass_closestZmass") ) rebin = 5;


    TH1D* h_data = (TH1D*)file_data->Get(temp.Data());
    TH1D* h_mc   = (TH1D*)file_mc->Get(temp.Data());

    h_data->Rebin(rebin);
    h_mc->Rebin(rebin);

    h_mc->Scale(sfMC_);

    if( temp.Contains("_numPV") || renorm_ ){
      h_mc->Scale( h_data->Integral() / h_mc->Integral() );
    }


    h_data->SetLineColor(color[0]);
    h_mc->SetLineColor(color[1]);

    h_data->SetMarkerColor(color[0]);
    h_mc->SetMarkerColor(color[1]);

    h_data->SetMarkerStyle(20);
    h_mc->SetMarkerStyle(20);

    legend->AddEntry(h_data,histLabels[0],"pe1");
    legend->AddEntry(h_mc,histLabels[1],"pe1");

    //c3->SetTopMargin(.05);
    //c1->SetRightMargin(.05);

    double ratioMax = 1.6;
    double ratioMin = 0.5;

    int nbins = h_data->GetNbinsX();

    double xmin = h_data->GetBinLowEdge(1);
    double xmax = h_data->GetBinLowEdge(nbins) + h_data->GetBinWidth(nbins);

    TH1D* myRatio = new TH1D("ratio", "", nbins, xmin, xmax );

    myRatio->SetStats(0);
    myRatio->Sumw2();
    myRatio->SetLineColor(kBlack);
    myRatio->SetMarkerColor(kBlack);
    myRatio->Divide(h_data,h_mc);

    myRatio->SetMinimum(ratioMin);
    myRatio->SetMaximum(ratioMax);
    //myRatio->GetYaxis()->SetNdivisions(50000+404);
    myRatio->GetYaxis()->SetNdivisions(50000+204);
    myRatio->GetYaxis()->SetLabelSize(0.1); //make y label bigger
    myRatio->GetXaxis()->SetLabelSize(0.1); //make y label bigger
    myRatio->GetXaxis()->SetTitleOffset(1.1);
    myRatio->GetXaxis()->SetTitle(h_data->GetXaxis()->GetTitle()); //make y label bigger
    myRatio->GetXaxis()->SetLabelSize(0.12);
    myRatio->GetXaxis()->SetLabelOffset(0.04);
    myRatio->GetXaxis()->SetTitleSize(0.12);
    myRatio->GetYaxis()->SetTitle("Data/MC");
    myRatio->GetYaxis()->SetTitleSize(0.09);
    myRatio->GetYaxis()->SetTitleOffset(.55);
    myC1->cd(2);
    gPad->SetTopMargin(small);
    gPad->SetTickx();
    gPad->Modified();

    myRatio->GetYaxis()->CenterTitle(kTRUE);


    if( temp.Contains("_selection") ){
      for( int iBin=0; iBin<nbins; iBin++ ) myRatio->GetXaxis()->SetBinLabel(iBin+1,h_data->GetXaxis()->GetBinLabel(iBin+1));
      myRatio->GetXaxis()->SetBinLabel(2,"HLT Ele27WPL");
      myRatio->GetXaxis()->SetBinLabel(8,"HLT HT200");
      myC1->GetPad(2)->SetBottomMargin(.4);
      myC1->GetPad(1)->SetRightMargin(.10);
      myC1->GetPad(2)->SetRightMargin(.10);
      myRatio->GetXaxis()->SetTitle("");
    }
    else{
      myC1->GetPad(2)->SetBottomMargin(.3);
      myC1->GetPad(1)->SetRightMargin(.05);
      myC1->GetPad(2)->SetRightMargin(.05);
    }

    h_data->SetStats(0);

    h_data->GetYaxis()->SetTitleOffset(1.0);
    h_data->GetYaxis()->SetTitleSize(0.05);

    h_data->GetYaxis()->SetTitle("Number of Events");


    int max_bin_data = h_data->GetMaximumBin();
    double max_data = h_data->GetBinContent(max_bin_data) + h_data->GetBinError(max_bin_data);

    int max_bin_mc = h_mc->GetMaximumBin();
    double max_mc = h_mc->GetBinContent(max_bin_mc) + h_mc->GetBinError(max_bin_mc);

    double max_content = std::max(max_data, max_mc);

    h_data->GetYaxis()->SetRangeUser(0.,1.2 * max_content);

    if( temp.Contains("_mass") ){
      h_data->GetXaxis()->SetRangeUser(40.,140.);
      myRatio->GetXaxis()->SetRangeUser(40.,140.);
    }

    if( temp.Contains("_met") ){
      h_data->GetXaxis()->SetRangeUser(0.,150.);
      myRatio->GetXaxis()->SetRangeUser(0.,150.);
    }
    // if( temp.Contains("_eta") ) h_all->GetYaxis()->SetRangeUser(0.4,1.1);
    // if( temp.Contains("_numGenPVs") ) h_all->GetYaxis()->SetRangeUser(0.4,1.1);
    // if( temp.Contains("_numJets") ) h_all->GetYaxis()->SetRangeUser(0.4,1.1);


    TLine* myLine;
    if( temp.Contains("_mass") )     myLine = new TLine(40, 1, 140, 1);
    else if( temp.Contains("_met") ) myLine = new TLine(0, 1, 150, 1);
    else                             myLine = new TLine(h_data->GetXaxis()->GetXmin(), 1, h_data->GetXaxis()->GetXmax(), 1);


    // HLT
    myC1->cd(1);
    h_data->Draw("pe1");
    h_mc->Draw("pe1same");
    legend->Draw();
    LumiInfoLatex.Draw();
    CMSInfoLatex.Draw();
    PublishInfoLatex.Draw();

    myC1->cd(2);
    myRatio->SetLineWidth(2);
    myRatio->Draw("pe1");
    myLine->Draw();

    plotname = dirprefix + temp_mh + "_data2mc_lin.png";
    myC1->Print(plotname);

    plotname = dirprefix + temp_mh + "_data2mc_lin.pdf";
    if( printPDF_ ) myC1->Print(plotname);


    // log
    h_data->GetYaxis()->SetRangeUser(0.4,12 * max_content);
    if( temp.Contains("_selection") ){
      h_data->GetYaxis()->SetRangeUser(1000,12 * max_content);
    }

    myC1->cd(1);
    gPad->SetLogy(1);

    plotname = dirprefix + temp_mh + "_data2mc_log.png";
    myC1->Print(plotname);

    plotname = dirprefix + temp_mh + "_data2mc_log.pdf";
    if( printPDF_ ) myC1->Print(plotname);

    gPad->SetLogy(0);



    delete myRatio;
    delete myLine;
    delete legend;
  } // end loop on hists



  // Close the file
  file_data->Close();
  file_mc->Close();
}
void CombineSpectra_minbias_NoOLDAlignmentRuns()
{

   gROOT->Reset();
   gROOT->ProcessLine(".x rootlogonChristof.C");
   gROOT->ForceStyle();
   gStyle->SetPalette(1);
   gStyle->SetTitleYOffset(1.30);
   gStyle->SetPadRightMargin(0.16);

   bool doSave = true;
   TFile * f_output = new TFile("CombineSpectra_minbias_NoOLDAlignmentRuns.root","recreate");

   // Define the input file and HiForest
   char *infName_1 = "root://eoscms//eos/cms/store/group/phys_heavyions/kjung/MinBiasUPCForest_v71/MergedForest_withCones_MinBiasUPC_v71_1.root";
   char *infName_2 = "root://eoscms//eos/cms/store/group/phys_heavyions/kjung/MinBiasUPCForest_v71/MergedForest_withCones_MinBiasUPC_v71_2.root";
   HiForest *c_minbias_1 = new HiForest(infName_1,"",cPPb);
   HiForest *c_minbias_2 = new HiForest(infName_2,"",cPPb);
//   c_minbias_1->doTrackCorrections=1;
//   c_minbias_1->InitTree();

   std::vector<Double_t> ptBins;
   const Double_t small = 1e-3;
   Double_t pt;
   for(pt =   0.  ; pt <   48.-small; pt +=  2./2.) ptBins.push_back(pt);
   for(pt =   48.; pt <   60.-small; pt +=  4./2. ) ptBins.push_back(pt); 
   for(pt =   60.; pt <   76.-small; pt +=  8./2. ) ptBins.push_back(pt); 
   for(pt =   76.; pt <   140.-small; pt +=  16./2. ) ptBins.push_back(pt); 
   for(pt =   140.; pt <   364.-small; pt +=  32./2. ) ptBins.push_back(pt); 
   ptBins.push_back(364.0);

   std::vector<Double_t> ptBins_smaller;
   Double_t pt_smaller;
   for(pt_smaller = 0.2; pt_smaller < 20.0-small; pt_smaller += 0.1 ) ptBins_smaller.push_back(pt_smaller);
   for(pt_smaller = 20.0; pt_smaller < 40.0-small; pt_smaller += 0.2 ) ptBins_smaller.push_back(pt_smaller);
   for(pt_smaller = 40.0; pt_smaller < 103.6-small; pt_smaller += 0.4 ) ptBins_smaller.push_back(pt_smaller);
   ptBins_smaller.push_back(103.6);

/*
   std::vector<Double_t> ptBins_part;
   Double_t pt_part;
   for(pt_part =   0.2  ; pt_part <   1.2-small; pt_part +=  0.05) ptBins_part.push_back(pt_part);
   for(pt_part =   1.2; pt_part <   2.4-small; pt_part +=  0.1 ) ptBins_part.push_back(pt_part); //12 bins
   for(pt_part =   2.4; pt_part <   7.2-small; pt_part +=  0.4 ) ptBins_part.push_back(pt_part); //12 bins
   for(pt_part =   7.2; pt_part <  16.8-small; pt_part +=  1.6 ) ptBins_part.push_back(pt_part);//it was 3.2
   for(pt_part =  16.8; pt_part <  30.0-small; pt_part +=  6.6 ) ptBins_part.push_back(pt_part);
   for(pt_part =  30.0; pt_part <  100.0-small; pt_part +=  17.5 ) ptBins_part.push_back(pt_part);
   for(pt_part =  100.0; pt_part <  300.0-small; pt_part += 25. ) ptBins_part.push_back(pt_part);
   ptBins_part.push_back(300.0);
*/
   //orig
//   Int_t NumOfPtBins_part = 34;
//   double ptBins_part[] = {0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 3.2, 4.0, 4.8, 5.6, 6.4, 7.2, 9.6, 12.0, 14.4, 19.2, 24.0, 28.8, 35.2, 41.6, 48.0, 60.8, 73.6, 86.4, 103.6};//, 120.8, 138., 155.2, 172.4};
   Int_t NumOfPtBins_part = 40;
   double ptBins_part[] = {0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 3.2, 4.0, 4.8, 5.6, 6.4, 7.2, 9.6, 12.0, 14.4, 19.2, 24.0, 28.8, 35.2, 41.6, 48.0, 60.8, 73.6, 86.4, 103.6, 120.8, 138., 155.2, 172.4, 189.6, 206.8};

   TTree * t = new TTree("t","whatever");
   JetData data(t,1);

   TH1D * hPartPt_minbias = new TH1D("hPartPt_minbias","hPartPt_minbias",NumOfPtBins_part-1,&ptBins_part[0]);
   TH1D * hPartPt_minbias_trkCorr = new TH1D("hPartPt_minbias_trkCorr","hPartPt_minbias_trkCorr",NumOfPtBins_part-1,&ptBins_part[0]);
   TH1D * hPartPt_minbias_trkCorr_trigCorr = new TH1D("hPartPt_minbias_trkCorr_trigCorr","hPartPt_minbias_trkCorr_trigCorr",NumOfPtBins_part-1,&ptBins_part[0]);
   TH1D * hPartPt_minbias_trkCorr_trigCorr_smallerBins = new TH1D("hPartPt_minbias_trkCorr_trigCorr_smallerBins","hPartPt_minbias_trkCorr_trigCorr_smallerBins",ptBins_smaller.size()-1,&ptBins_smaller[0]);
   TH1D * hPartPt_0_14_minbias = new TH1D("hPartPt_0_14_minbias","hPartPt_0_14_minbias",NumOfPtBins_part-1,&ptBins_part[0]);
   TH1D * hPartPt_0_14_minbias_trkCorr = new TH1D("hPartPt_0_14_minbias_trkCorr","hPartPt_0_14_minbias_trkCorr",NumOfPtBins_part-1,&ptBins_part[0]);
   TH1D * hPartPt_0_14_minbias_trkCorr_trigCorr = new TH1D("hPartPt_0_14_minbias_trkCorr_trigCorr","hPartPt_0_14_minbias_trkCorr_trigCorr",NumOfPtBins_part-1,&ptBins_part[0]);
   TH1D * hNumEv_minbias = new TH1D("hNumEv_minbias","hNumEv_minbias",1,0.,1.);
   TH1D * hNumEv_minbias_trigCorr = new TH1D("hNumEv_minbias_trigCorr","hNumEv_minbias_trigCorr",1,0.,1.);
   TH1D * hNumEv_0_14_minbias = new TH1D("hNumEv_0_14_minbias","hNumEv_0_14_minbias",1,0.,1.);
   TH1D * hNumEv_0_14_minbias_trigCorr = new TH1D("hNumEv_0_14_minbias_trigCorr","hNumEv_0_14_minbias_trigCorr",1,0.,1.);
   TH1D * hNumEv_14_22_minbias = new TH1D("hNumEv_14_22_minbias","hNumEv_14_22_minbias",1,0.,1.);
   TH1D * hNumEv_14_22_minbias_trigCorr = new TH1D("hNumEv_14_22_minbias_trigCorr","hNumEv_14_22_minbias_trigCorr",1,0.,1.);
   TH1D * hNumEv_22_32_minbias = new TH1D("hNumEv_22_32_minbias","hNumEv_22_32_minbias",1,0.,1.);
   TH1D * hNumEv_22_32_minbias_trigCorr = new TH1D("hNumEv_22_32_minbias_trigCorr","hNumEv_22_32_minbias_trigCorr",1,0.,1.);
   TH1D * hNumEv_32_X_minbias = new TH1D("hNumEv_32_X_minbias","hNumEv_32_X_minbias",1,0.,1.);

   TH1D * hRecMultiplicity = new TH1D("hRecMultiplicity","hRecMultiplicity",300.,0.,300.);

   hPartPt_minbias->Sumw2();
   hPartPt_minbias_trkCorr->Sumw2();
   hPartPt_minbias_trkCorr_trigCorr->Sumw2();
   hPartPt_minbias_trkCorr_trigCorr_smallerBins->Sumw2();
   hPartPt_0_14_minbias->Sumw2();
   hPartPt_0_14_minbias_trkCorr->Sumw2();
   hPartPt_0_14_minbias_trkCorr_trigCorr->Sumw2();

   hRecMultiplicity->Sumw2();

   int numev_minbias = 0;
   float numev_minbias_trigCorr = 0;
   int numev_0_14_minbias = 0;
   float numev_0_14_minbias_trigCorr = 0;
   int numev_14_22_minbias = 0;
   float numev_14_22_minbias_trigCorr = 0;
   int numev_22_32_minbias = 0;
   float numev_22_32_minbias_trigCorr = 0;
   int numev_32_X_minbias = 0;

   fillHistograms(c_minbias_1, data, numev_minbias, numev_minbias_trigCorr, numev_0_14_minbias, numev_0_14_minbias_trigCorr, numev_14_22_minbias, numev_14_22_minbias_trigCorr, numev_22_32_minbias, numev_22_32_minbias_trigCorr, numev_32_X_minbias, hPartPt_minbias, hPartPt_minbias_trkCorr, hPartPt_minbias_trkCorr_trigCorr, hPartPt_minbias_trkCorr_trigCorr_smallerBins, hPartPt_0_14_minbias, hPartPt_0_14_minbias_trkCorr, hPartPt_0_14_minbias_trkCorr_trigCorr,hRecMultiplicity);
   fillHistograms(c_minbias_2, data, numev_minbias, numev_minbias_trigCorr, numev_0_14_minbias, numev_0_14_minbias_trigCorr, numev_14_22_minbias, numev_14_22_minbias_trigCorr, numev_22_32_minbias, numev_22_32_minbias_trigCorr, numev_32_X_minbias, hPartPt_minbias, hPartPt_minbias_trkCorr, hPartPt_minbias_trkCorr_trigCorr, hPartPt_minbias_trkCorr_trigCorr_smallerBins, hPartPt_0_14_minbias, hPartPt_0_14_minbias_trkCorr, hPartPt_0_14_minbias_trkCorr_trigCorr,hRecMultiplicity);

   hNumEv_minbias->SetBinContent(1,numev_minbias);
   hNumEv_minbias_trigCorr->SetBinContent(1,numev_minbias_trigCorr);
   hNumEv_0_14_minbias->SetBinContent(1,numev_0_14_minbias);
   hNumEv_0_14_minbias_trigCorr->SetBinContent(1,numev_0_14_minbias_trigCorr);
   hNumEv_14_22_minbias->SetBinContent(1,numev_14_22_minbias);
   hNumEv_14_22_minbias_trigCorr->SetBinContent(1,numev_14_22_minbias_trigCorr);
   hNumEv_22_32_minbias->SetBinContent(1,numev_22_32_minbias);
   hNumEv_22_32_minbias_trigCorr->SetBinContent(1,numev_22_32_minbias_trigCorr);
   hNumEv_32_X_minbias->SetBinContent(1,numev_32_X_minbias);
   normalizeByBinWidth(hPartPt_minbias);
   normalizeByBinWidth(hPartPt_minbias_trkCorr);
   normalizeByBinWidth(hPartPt_minbias_trkCorr_trigCorr);
   normalizeByBinWidth(hPartPt_minbias_trkCorr_trigCorr_smallerBins);
   normalizeByBinWidth(hPartPt_0_14_minbias);
   normalizeByBinWidth(hPartPt_0_14_minbias_trkCorr);
   normalizeByBinWidth(hPartPt_0_14_minbias_trkCorr_trigCorr);

   f_output->cd();
   hPartPt_minbias->Write();
   hPartPt_minbias_trkCorr->Write();
   hPartPt_minbias_trkCorr_trigCorr->Write();
   hPartPt_minbias_trkCorr_trigCorr_smallerBins->Write();
   hPartPt_0_14_minbias->Write();
   hPartPt_0_14_minbias_trkCorr->Write();
   hPartPt_0_14_minbias_trkCorr_trigCorr->Write();
   hNumEv_minbias->Write();
   hNumEv_minbias_trigCorr->Write();
   hNumEv_0_14_minbias->Write();
   hNumEv_0_14_minbias_trigCorr->Write();
   hNumEv_14_22_minbias->Write();
   hNumEv_14_22_minbias_trigCorr->Write();
   hNumEv_22_32_minbias->Write();
   hNumEv_22_32_minbias_trigCorr->Write();
   hNumEv_32_X_minbias->Write();
   hRecMultiplicity->Write();
   f_output->Close();
}
Esempio n. 28
0
void M2gChan( UInt_t chan = 250, UInt_t rebin = 1, TString tgt = "full")
{
	UInt_t left, right, bin_lo, bin_hi, rebin;
	Double_t eg, deg;
	TString name;

	gStyle->SetOptStat( 0);

	if ( !gROOT->GetListOfCanvases()->IsEmpty()) {
		delete c1;
	}

	TCanvas *c1 = new TCanvas ( "c1", "Subtraction", 200, 20, 700, 400);
   c1->SetGrid();
   c1->GetFrame()->SetFillColor( 21);
   c1->GetFrame()->SetBorderSize( 12);
	c1->Divide( 2, 1);

	eg = tcd[chan].energy;
	deg = tcd[chan].denergy;

	name = Form( "Egamma = %5.1f +/- %3.1f MeV", eg, deg/2);
	cout << name << endl;

	left = 0;
	right = 200;

	// Prompt
	name = "THR_M2gTaggP_v_TChanM2gP";
	if ( tgt == "full") TH2D *hp2d = (TH2D*)full.Get( name);
	else if ( tgt == "empty") TH2D *hp2d = (TH2D*)empty.Get( name);
	bin_lo = hp2d->GetXaxis()->FindBin( chan);
	bin_hi = hp2d->GetXaxis()->FindBin( chan);
	hp2d->GetXaxis()->SetRange( bin_lo, bin_hi);
	name = Form( "M2gP_r%d", rebin);
	TH1D *hp = hp2d->ProjectionY( name);
	hp->Rebin( rebin);

	// Random
	name = "THR_M2gTaggR_v_TChanM2gR";
	if ( tgt == "full") TH2D *hr2d = (TH2D*)full.Get( name);
	else if ( tgt == "empty") TH2D *hr2d = (TH2D*)empty.Get( name);
	hr2d->GetXaxis()->SetRange( bin_lo, bin_hi);
	name = Form( "M2gR_r%d", rebin);
	TH1D *hr = hr2d->ProjectionY( name);
	hr->Rebin( rebin);

	c1->cd( 1);
	// Prompt
	hp->SetLineWidth( 3);
	hp->SetLineColor( 4);
	name = Form( "2#gamma Invariant Mass for E_{#gamma} = %5.1f #pm %3.1f MeV",
			eg, deg/2);
	hp->SetTitle( name);
	hp->GetXaxis()->SetTitleOffset( 1.1);
	hp->GetXaxis()->SetLabelSize( 0.03);
	hp->GetXaxis()->CenterTitle();
	hp->GetXaxis()->SetTitle( "M_{#gamma#gamma} (MeV)");
	hp->GetXaxis()->SetRangeUser( left, right);
	hp->DrawCopy();

	// Random
	hr->Scale( 0.5);
	hr->SetLineWidth( 3);
	hr->SetLineColor( 2);
	hr->Draw( "same");

	// Subtracted
	hp->Sumw2();
	hp->Add( hr, -1.0);
	hp->SetMarkerStyle( 21);
	hp->SetMarkerColor( 1);
	hp->SetLineWidth( 3);
	hp->SetLineColor( 1);
	c1->cd(2);
	hp->SetTitle();
	hp->Draw( "E");
	hp->GetXaxis()->SetRangeUser( left, right);

	l = new TLine( left, 0, right, 0);
	l->SetLineStyle( 2);
	l->Draw();
}
Esempio n. 29
0
void checkTrkInputs(
    TString infrec="nt_djhp_HyUQ110v0_djcalo.root",
    TString infgen="nt_djhp_HyUQ110v0_djcalo_genp.root",
    TCut evtCut="cent<30")
{
  //TH1::SetDefaultSumw2();
  TChain * trec = new TChain("tjttrk");
  trec->Add(infrec);
  setupAlias(trec);
  TChain * tgen = new TChain("tjttrk");
  tgen->Add(infgen);
  cout << infrec << " cut " << TString(evtCut) << ": " << trec->GetEntries() << endl;
  cout << infgen << " cut " << TString(evtCut) << ": " << tgen->GetEntries() << endl;
   
  // Correction Histograms
  TFile * fTrkCorr = new TFile("djtrkhist_hydjetBassv2_djuq110.root");
  TString corrModule = "hitrkEffAnalyzer";
  TH2F * hrec = (TH2F*)fTrkCorr->Get(Form("%s/hrec",corrModule.Data()));
  TH1D * hrec_pt = (TH1D*)hrec->ProjectionY();
  TH2F * hsim = (TH2F*)fTrkCorr->Get(Form("%s/hsim",corrModule.Data()));
  TH1D * hsim_pt = (TH1D*)hsim->ProjectionY();
  
  // Frag Histograms
  //TH1D * hPPtRecRaw = new TH1D("hPPtRecRaw",";p_{T} (GeV/c); count;");
  TH1D * hPPtRecRaw = (TH1D*)hrec_pt->Clone("hPPtRecRaw");
  hPPtRecRaw->Reset();
  TH1D * hPPtGen = (TH1D*)hrec_pt->Clone("hPPtGen");
  hPPtGen->Reset();
  trec->Project("hPPtRecRaw","ppt","");
  tgen->Project("hPPtGen","ppt","");
  TH1D * hRecSimRat_pt = (TH1D*)hrec_pt->Clone("hRecSimRat_pt");
  hRecSimRat_pt->Sumw2();
  hRecSimRat_pt->Divide(hrec_pt,hsim_pt);
  TH1D * hPPtRat = (TH1D*)hrec_pt->Clone("hPPtRat");
  hPPtRat->Sumw2();
  hPPtRat->Divide(hPPtRecRaw,hPPtGen);

  // Normalize
  normHist(hsim_pt,0,true,1);
  normHist(hrec_pt,0,true,1);
  normHist(hPPtGen,0,true,1);
  normHist(hPPtRecRaw,0,true,1);

  // Plot
  hsim_pt->SetAxisRange(0,100,"X");
  hsim_pt->SetTitle(";p_{T} (GeV/c); count");
  hRecSimRat_pt->SetTitle(";p_{T} (GeV/c); reco/gen ratio");
  hsim_pt->SetLineColor(kRed);
  hPPtGen->SetMarkerColor(kRed);
  hPPtGen->SetLineColor(kRed);
  hRecSimRat_pt->SetAxisRange(0,100,"X");
  hRecSimRat_pt->SetAxisRange(-0.2,1.2,"Y");
  hRecSimRat_pt->SetLineColor(kRed);
  TCanvas *cRec = new TCanvas("cRec","Rec",500,900);
  cRec->Divide(1,2);
  cRec->cd(1);
  cRec->GetPad(1)->SetLogy();
  hsim_pt->Draw("hist");
  hPPtGen->Draw("sameE");
  hrec_pt->Draw("hist same");
  hPPtRecRaw->Draw("sameE");
  cRec->cd(2);
  hRecSimRat_pt->Draw("hist");
  hPPtRat->Draw("sameE");

  // ====================
  TLegend *leg = new TLegend(0.61,0.78,0.91,0.91);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetTextSize(0.035);
}
Esempio n. 30
0
// File: ST_Monitoring_Efficiency.C
// Last Modified: 05/27/2015
// Creator: Mahmoud Kamel [email protected]
// Purpose: Displaying histograms for online monitoring purposes
void ST_Monitoring_Eff () {
  // Define the directory that contains the histograms
  TDirectory *dir = (TDirectory*)gDirectory->FindObjectAny("st_tracking");
  if(dir) dir->cd();
  // Grab 1D histograms 
  TH1D *MacropEff     = (TH1D*)dir->FindObjectAny("MacropEff");
  TH1D *MacropEff_adc     = (TH1D*)dir->FindObjectAny("MacropEff_adc");
  TH1D *h_phi_sec_pred_hit_cntr = (TH1D*)dir->FindObjectAny("h_phi_sec_pred_hit_cntr");
  TH1D *h_phi_sec_hit_cntr  = (TH1D*)dir->FindObjectAny("h_phi_sec_hit_cntr");
  TH1D *h_phi_sec_adc_cntr = (TH1D*)dir->FindObjectAny("h_phi_sec_adc_cntr");

  // get Binomial errors in an efficiency plot
  // hit object efficiency
  h_phi_sec_hit_cntr->Sumw2();
  h_phi_sec_pred_hit_cntr->Sumw2();
  MacropEff->Sumw2();
  MacropEff->Divide(h_phi_sec_hit_cntr,h_phi_sec_pred_hit_cntr,1,1,"B");

  // adc efficiency
  h_phi_sec_adc_cntr->Sumw2();
  MacropEff_adc->Sumw2();
  MacropEff_adc->Divide(h_phi_sec_adc_cntr,h_phi_sec_pred_hit_cntr,1,1,"B");

  //Create the canvas
  if(gPad == NULL)
    {
      TCanvas *c1 = new TCanvas("c1","Start Counter 1D Histograms", 200, 10, 600, 480);
      c1->cd(0);
      c1->Draw();
      c1->Update();
    }
  if(!gPad) return;
  TCanvas *c1 = gPad->GetCanvas();
  c1->Divide(2,1);
  // ST ADC Efficiency histogram
  c1->cd(1);
  gStyle->SetOptStat(0);
  gStyle->SetErrorX(0); 
  gPad->SetTicks();
  gPad->SetGrid();
  if (MacropEff_adc) {
   MacropEff_adc->Draw("E1");
   MacropEff_adc->SetMarkerStyle(21);
   MacropEff_adc->SetMarkerSize(1.5);
   MacropEff_adc->SetMarkerColor(4.0);
   MacropEff_adc->SetAxisRange(0., 1.,"Y");
   MacropEff_adc->GetYaxis()->SetTitleOffset(1.26);
   Double_t TWA_adc=0;
   Double_t sumE_adc=0;
   Double_t Final_adc=0;
   Double_t error_adc=0.;
   Double_t BC_adc=0.;
   Double_t WA_adc=0.;
   //Double_t Final_adc=0.;
   for (int i = 0; i < 30; i++)
     {
       error_adc =   MacropEff_adc->GetBinError(i+2);
       sumE_adc = sumE_adc + error_adc;
       BC_adc =   MacropEff_adc->GetBinContent(i+2);
       WA_adc = BC_adc*error_adc;
       TWA_adc = TWA_adc + WA_adc ;
       Final_adc = TWA_adc/sumE_adc;
       // cout << "error_adc =  "<< error_adc << endl;
       // cout << "BC_adc =  "<< BC_adc << endl;
       // cout << "Final_adc =  "<< Final_adc << endl;
     } 
   TLine *line = new TLine(1,Final_adc,30,Final_adc);
   line->SetLineWidth(3);
   line->SetLineColor(2);
   //Write the eff value on the histogram 
   char tFinal_adc[40];
   char terror_adc[40];
   sprintf(tFinal_adc,"ADC Efficiency (%%) = %g",Final_adc*100);
   sprintf(terror_adc,"ADC Efficiency error (%%) = %g",error_adc*100);
   line->Draw();
   TPaveLabel *p = new TPaveLabel(0.3,0.6,0.7,0.7,tFinal_adc,"brNDC");
   p->Draw();
   TPaveLabel *p1 = new TPaveLabel(0.3,0.5,0.7,0.6,terror_adc,"brNDC");
   p1->Draw();
  }
  // ST Hit Efficiency histogram
  c1->cd(2);
  gPad->SetTicks();
  gPad->SetGrid();
  if (MacropEff) {
    MacropEff->Draw("E1");
    MacropEff->SetMarkerStyle(21);
    MacropEff->SetMarkerSize(1.5);
    MacropEff->SetMarkerColor(4.0);
    MacropEff->SetAxisRange(0., 1.,"Y");
    MacropEff->GetYaxis()->SetTitleOffset(1.26);
    Double_t TWA=0;
    Double_t sumE=0;
    Double_t Final=0; 
    Double_t error=0.;
    Double_t BC=0.;
    Double_t WA=0.;
    //Double_t Final=0.;
    for (int i = 0; i < 30; i++)
      {
	error =   MacropEff->GetBinError(i+2);
	sumE = sumE+error;
	BC =   MacropEff->GetBinContent(i+2);
	WA = BC*error;
	TWA = TWA + WA ;
	Final = TWA/sumE;
	//	cout << "error =  "<< error << endl;
	//	cout << "BC =  "<< BC << endl;
	//	cout << "Final =  "<< Final << endl;
      } 
    TLine *line = new TLine(1,Final,30,Final);
    line->SetLineWidth(3);
    line->SetLineColor(2);
    //Write the eff value on the histogram 
   char tFinal[40];
   char terror[40];
   sprintf(tFinal,"Hit Efficiency (%%) = %g",Final*100);
   sprintf(terror,"Hit Efficiency error (%%) = %g",error*100);
   line->Draw();
   TPaveLabel *p = new TPaveLabel(0.3,0.6,0.7,0.7,tFinal,"brNDC");
   p->Draw();
   TPaveLabel *p1 = new TPaveLabel(0.3,0.5,0.7,0.6,terror,"brNDC");
   p1->Draw();
  }
}