TF1* GetFitFunc_ZYAM(TH1D* h)
{
                    TH1D* hcorrphi = (TH1D*)h->Clone(h->GetName());
                    double histminY = hcorrphi->GetBinContent(10);
                    double histminX = 1.0;

                    //hcorrphi->SetAxisRange(-0.01,1.2,"X"); 
                    TF1* fitfunc = new TF1(Form("fitfunc_%s",h->GetName()),"[0]+[1]*(x-[2])*(x-[2])",1.0,2.4); //std 0.6 1.55 vs pT ; 0.6 1.8 vs eta
                    fitfunc->SetParameters(histminY,0.0002,histminX);
                    fitfunc->SetParLimits(1,0,1000);
                    fitfunc->SetParLimits(2,1.0,2.4);
                   
/*
//                    hcorrphi->SetAxisRange(-0.01,1.2,"X"); 
                    TF1* fitfunc = new TF1(Form("fitfunc_%s",h->GetName()),"[0]+[1]*(x-[2])*(x-[2])",0.65,1.3); 
                    fitfunc->SetParameters(histminY,0.0002,histminX);
                    fitfunc->SetParLimits(1,0,1000);
                    fitfunc->SetParLimits(2,0.05,1000);
*/
                    for(int ifit=0;ifit<3;ifit++) hcorrphi->Fit(Form("fitfunc_%s",h->GetName()),"RNO");
                    return fitfunc;
}
Exemple #2
0
Spectrum roothist_to_spectrum(const TH1D & hist, const TH2D * cov, bool use_hist_uncertainties){
    const int n = hist.GetNbinsX();
    if(cov){
        if(cov->GetDimension() != 2 || cov->GetNbinsX() != n || cov->GetNbinsY() != n){
            throw runtime_error(string("covariance histogram '") + cov->GetName() + "' has wrong dimension");
        }
    }
    Spectrum s(n);
    for(int i=0; i<n; ++i){
        double c = hist.GetBinContent(i+1);
        if(!isfinite(c)){
            throw runtime_error(string("non-finite entry in histogram '") + hist.GetName() + "'");
        }
        s[i] = c;
        if(use_hist_uncertainties){
            double e = hist.GetBinError(i+1);
            if(!isfinite(e)){
                throw runtime_error(string("non-finite error in histogram '") + hist.GetName() + "'");
            }
            s.cov()(i,i) += e*e;
        }
    }
    if(cov){
        for(int i=0; i<n; ++i){
            for(int j=0; j<n; ++j){
                double c_ij = cov->GetBinContent(i+1, j+1);
                double c_ji = cov->GetBinContent(j+1, i+1);
                if(!isfinite(c_ij)){
                    throw runtime_error(string("covariance histogram '") + cov->GetName() + "' does have non-finite entry");
                }
                if(fabs(c_ij - c_ji) > 1e-8 * max(fabs(c_ij), 1.0)){
                    cerr << "covariance histogram '" << cov->GetName() <<  "' is not symmetric: C(" << i << ","<< j << ") = " << c_ij << "; transposed: " << c_ji << "; diff = " << (c_ij - c_ji) << endl;
                }
                s.cov()(i,j) += c_ij;
            }
        }
    }
    return s;
}
double CalcChiSqr(TH1D* hist, Double_t coeff, Double_t expo, Int_t xMin, Int_t xMax)
{
  {
    TH1D* myHist = hist->Clone();
    int bins = myHist->GetSize()-2;
    double chiSqr = 0;
    for(int i = xMin+1; i < xMax+1; i++)
      {
	double x = myHist->GetBinCenter(i);
	double o = myHist->GetBinContent(i);
	double e = coeff*(TMath::Power(x,expo));
	//cout << x << "\t" << o << "\t" << e;
	if(o != 0)
	  chiSqr += ((o-e)*(o-e))/o;
	//cout << "\tchiSqr: " << chiSqr << endl;
      }
    return chiSqr/2;
    
  }
  
  
}
void fitpapvar(const char* infilename, const char* histname) {
  TFile* infile = new TFile(Form("%s",infilename),"read");
  TH1D* hcf = (TH1D*)infile->Get(histname);
  hcf->GetXaxis()->SetRangeUser(0,2);

   TF1 *fc2 = new TF1("fc2","[3]+[2]*TMath::Gaus(x,[0],[1])",0.4,1);
   fc2->SetParameters(1.5,0.3,-0.2,1);

  // TF1 *fc2 = new TF1("fc2","[1]+[0]*x*x",0,1);
  // fc2->SetParameters(-0.01,1.0);

  // TF1 *fc2 = new TF1("fc2","[2]+[1]*x*x*x*x*x",0,1);
  // fc2->SetParameters(-0.01,0.01,1.0);

  // TF1 *fc2 = new TF1("fc2","[3]+[2]*x*x+[1]*x*x*x+[0]*x*x*x*x",0.,1);
  // fc2->SetParameters(-0.01,0.01,1.0,1.0);

  hcf->Fit("fc2","r","",0.3,1);
  TH1D* hnew = new TH1D("hnew","hnew",hcf->GetNbinsX(),0,1);
  for(int i=1;i<=hcf->GetNbinsX();++i){
    // cout << i << endl;
    // cout << hcf->GetBinContent(i)/fc2->Eval(2.*i/hcf->GetNbinsX()) << endl;
    // cout << hcf->GetBinContent(i) << endl;
    // cout << fc2->Eval(2.*i/hcf->GetNbinsX()) << endl << endl;
    hnew->SetBinContent(i, hcf->GetBinContent(i)/fc2->Eval(1.*i/hcf->GetNbinsX()));
    hnew->SetBinError(i, hcf->GetBinError(i));

  }
  hnew->Draw("same");
  fc2->Draw("same");
  hnew->SetName(Form("divp4%s",histname));
  TFile* ofile = new TFile(Form("divp4%s",infilename),"update");
  hnew->Write();
  hcf->Write();
  ofile->Close();
}
TF1* fitDstar(TTree* nt, TTree* ntMC, Float_t ptmin, Bool_t plotgenmatch)
{
  TCanvas* c = new TCanvas(Form("c_5p_%.0f",ptmin),"",600,600);
  TH1D* h = new TH1D(Form("h_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSignal = new TH1D(Form("hMCSignal_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSignalplot = new TH1D(Form("hMCSignalplot_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSwapped = new TH1D(Form("hMCSwapped_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);
  TH1D* hMCSwappedplot = new TH1D(Form("hMCSwappedplot_5p_%.0f",ptmin),"",BINNUM,BINMIN,BINMAX);

  TF1* f = new TF1(Form("f_5p_%.0f",ptmin),"[0]*([4]*([6]*([12]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[12])*Gaus(x,[1],[11])/(sqrt(2*3.14159)*[11]))+(1-[6])*Gaus(x,[1],[5])/(sqrt(2*3.14159)*[5]))+(1-[4])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3]))+[10]*((1-exp((0.13957-x)/[7]))*pow(x/0.13957,[8])+[9]*(x/0.13957-1))",BINMIN,BINMAX);
  nt->Project(Form("h_5p_%.0f",ptmin),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f)",weightdata[isData].Data(),seldata5p[isData].Data(),triggerselectiondata[isData].Data(),ptmin));
  ntMC->Project(Form("hMCSignal_5p_%.0f",ptmin),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f)",weightmc[isData].Data(),selmc5p[isData].Data(),triggerselectionmc[isData].Data(),ptmin));
  ntMC->Project(Form("hMCSwapped_5p_%.0f",ptmin),"Dmass-DtktkResmass",Form("%s*(%s&&%s&&Dpt>%f)",weightmc[isData].Data(),selswp5p[isData].Data(),triggerselectionmc[isData].Data(),ptmin));
  for(int ibin=0;ibin<BINNUM;ibin++) hMCSignalplot->SetBinContent(ibin+1,hMCSignal->GetBinContent(ibin+1));
  for(int ibin=0;ibin<BINNUM;ibin++) hMCSwappedplot->SetBinContent(ibin+1,hMCSwapped->GetBinContent(ibin+1));
  f->FixParameter(4,1.);
  f->FixParameter(1,0.145491);
  f->FixParameter(10,0);

  f->SetParLimits(0,0,1.e+5);
  f->SetParLimits(6,0,1.);
  f->SetParLimits(12,0,1.);
  f->SetParLimits(2,3.e-4,1.e-3);
  f->SetParameter(2,5.e-4);
  f->SetParLimits(11,1.6e-4,3.e-4);//1.5e-4 keyong
  f->SetParameter(11,2.e-4);
  f->SetParLimits(5,1.e-3,1.6e-3);
  f->SetParameter(5,1.e-3);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  f->ReleaseParameter(1);
  f->SetParLimits(1,minmass,maxmass);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",minmass,maxmass);
  hMCSignal->Fit(Form("f_5p_%.0f",ptmin),"LL","",minmass,maxmass);

  f->FixParameter(1,f->GetParameter(1));
  f->FixParameter(2,f->GetParameter(2));
  f->FixParameter(5,f->GetParameter(5));
  f->FixParameter(11,f->GetParameter(11));
  f->FixParameter(6,f->GetParameter(6));
  f->FixParameter(12,f->GetParameter(12));
  f->FixParameter(4,0);
  f->SetParLimits(3,2.e-4,2.e-3);
  f->SetParameter(3,1.e-3);

  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",BINMIN,BINMAX);
  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",BINMIN,BINMAX);
  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",minmass,maxmass);
  hMCSwapped->Fit(Form("f_5p_%.0f",ptmin),"L q","",minmass,maxmass);

  f->FixParameter(4,hMCSignal->Integral(0,1000)/(hMCSwapped->Integral(0,1000)+hMCSignal->Integral(0,1000)));
  f->FixParameter(3,f->GetParameter(3));

  f->SetParLimits(7,5.e-4,1.e-2);
  f->SetParameter(7,1.6e-3);
  f->SetParLimits(8,0.,15.);
  f->SetParameter(8,0.35);
  f->SetParLimits(9,-2.e+1,2.e+1);
  f->SetParameter(9,13.);

  f->ReleaseParameter(10);
  f->SetParLimits(10,0,1.e+6);

  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);

  f->ReleaseParameter(1);
  f->SetParLimits(1,minmass,maxmass);
  f->SetParameter(1,f->GetParameter(1));
  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);
  h->Fit(Form("f_5p_%.0f",ptmin),"LL","",BINMIN,BINMAX);

  TF1* background = new TF1(Form("background_5p_%.0f",ptmin),"[3]*((1-exp((0.13957-x)/[0]))*pow(x/0.13957,[1])+[2]*(x/0.13957-1))");
  background->SetParameters(f->GetParameter(7),f->GetParameter(8),f->GetParameter(9),f->GetParameter(10));
  background->SetRange(BINMIN,BINMAX);
  background->SetLineColor(4);
  background->SetLineWidth(3);
  background->SetLineStyle(2);

  TF1* mass = new TF1(Form("fmass_5p_%.0f",ptmin),"[0]*[3]*([5]*([7]*Gaus(x,[1],[2])/(sqrt(2*3.14159)*[2])+(1-[7])*Gaus(x,[1],[6])/(sqrt(2*3.14159)*[6]))+(1-[5])*Gaus(x,[1],[4])/(sqrt(2*3.14159)*[4]))");
  mass->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(2),f->GetParameter(4),f->GetParameter(5),f->GetParameter(6),f->GetParameter(11),f->GetParameter(12));
  mass->SetParError(0,f->GetParError(0));
  mass->SetParError(1,f->GetParError(1));
  mass->SetParError(2,f->GetParError(2));
  mass->SetParError(3,f->GetParError(4));
  mass->SetParError(4,f->GetParError(5));
  mass->SetParError(5,f->GetParError(6));
  mass->SetRange(BINMIN,BINMAX);
  mass->SetFillColor(kOrange-3);
  mass->SetFillStyle(3002);
  mass->SetLineColor(kOrange-3);
  mass->SetLineWidth(3);
  mass->SetLineStyle(2);

  TF1* massSwap = new TF1(Form("fmassSwap_5p_%.0f",ptmin),"[0]*(1-[2])*Gaus(x,[1],[3])/(sqrt(2*3.14159)*[3])");
  massSwap->SetParameters(f->GetParameter(0),f->GetParameter(1),f->GetParameter(4),f->GetParameter(3));
  massSwap->SetRange(BINMIN,BINMAX);
  massSwap->SetFillColor(kGreen+4);
  massSwap->SetFillStyle(3005);
  massSwap->SetLineColor(kGreen+4);
  massSwap->SetLineWidth(3);
  massSwap->SetLineStyle(1);

  h->SetXTitle("M_{K#pi#pi#pi#pi}-M_{K#pi#pi#pi} (GeV/c^{2})");
  h->SetYTitle("Entries / (0.4 MeV/c^{2})");
  h->SetStats(0);
  h->SetAxisRange(0,h->GetMaximum()*1.3,"Y");
  h->GetXaxis()->CenterTitle();
  h->GetYaxis()->CenterTitle();
  h->GetXaxis()->SetTitleOffset(1.3);
  h->GetYaxis()->SetTitleOffset(1.8);
  h->GetXaxis()->SetLabelOffset(0.007);
  h->GetYaxis()->SetLabelOffset(0.007);
  h->GetXaxis()->SetTitleSize(0.045);
  h->GetYaxis()->SetTitleSize(0.045);
  h->GetXaxis()->SetTitleFont(42);
  h->GetYaxis()->SetTitleFont(42);
  h->GetXaxis()->SetLabelFont(42);
  h->GetYaxis()->SetLabelFont(42);
  h->GetXaxis()->SetLabelSize(0.04);
  h->GetYaxis()->SetLabelSize(0.04);
  h->SetMarkerSize(0.8);
  h->SetMarkerStyle(20);
  h->SetStats(0);

  h->Draw("e");
  mass->Draw("same");
  massSwap->Draw("same");
  background->Draw("same");
  f->Draw("same");

  if(plotgenmatch&&(isData==MC_MB||isData==MC))
    {
      hMCSignalplot->SetMarkerSize(0.8);
      hMCSignalplot->SetMarkerColor(kMagenta+2);
      hMCSignalplot->Draw("psame");
      hMCSwappedplot->SetMarkerSize(0.8);
      hMCSwappedplot->SetMarkerColor(kGray+2);
      hMCSwappedplot->Draw("psame");
    }

  Float_t yield = mass->Integral(BINMIN,BINMAX)/BINWID;
  Float_t yieldErr = mass->Integral(BINMIN,BINMAX)/BINWID*mass->GetParError(0)/mass->GetParameter(0);
  cout<<mass->GetParameter(0)<<" "<<mass->Integral(BINMIN,BINMAX)<<endl;

  TLatex* tex;
  TLegend* leg = new TLegend(0.60,0.57,0.85,0.88,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextSize(0.04);
  leg->SetTextFont(42);
  leg->SetFillStyle(0);
  leg->AddEntry((TObject*)0,"D* D^{0}(K#pi#pi#pi)#pi",NULL);
  leg->AddEntry(h,"Data","pl");
  leg->AddEntry(f,"Fit","l");
  leg->AddEntry(mass,"D*^{+}+D*^{-} Signal","f");
  leg->AddEntry(massSwap,"K-#pi swapped","f");
  leg->AddEntry(background,"Combinatorial","l");
  leg->Draw("same");

  tex = new TLatex(0.61,0.52,Form("N_{D} = %.0f #pm %.0f",yield,yieldErr));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  tex = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.65,0.93, "PP #sqrt{s_{NN}} = 5.02 TeV");
  tex->SetNDC();
  tex->SetTextAlign(12);
  tex->SetTextSize(0.04);
  tex->SetTextFont(42);
  tex->Draw();
  tex = new TLatex(0.20,0.79,"|y| < 1.0");
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();
  tex = new TLatex(0.20,0.84,Form("p_{T} > %.1f GeV/c",ptmin));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.04);
  tex->Draw();

  c->SaveAs(Form("plots/pp/fitDstar5p/DMass_%s_%.0f.pdf",texData[isData].Data(),ptmin));

  return mass;
}
void fitDstar5pMinpt(Bool_t genmatchpoint=true)
{
  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* fitDstar(TTree* nt, TTree* ntMC, Float_t ptmin, Bool_t plotgenmatch);

  TFile* infData = new TFile(infnameData5p[isData].Data());
  TFile* infMC = new TFile(infnameMC5p[isData].Data());

  TTree* ntData = (TTree*)infData->Get("ntDD0kpipipipi");
  TTree* ntMC = (TTree*)infMC->Get("ntDD0kpipipipi");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  
  ntData->AddFriend("ntHlt");
  if(isData!=Data_MB&&isData!=Data) ntData->AddFriend("ntHi");
  ntMC->AddFriend("ntHlt");
  ntMC->AddFriend("ntHi");
  ntGen->AddFriend("ntHlt");
  ntGen->AddFriend("ntHi");

  Float_t aZero[nBins];
  for(int i=0;i<nBins;i++) aZero[i]=0;
  Float_t aPt[nBins],aPtErr[nBins],aGen[nBins],aGenErr[nBins];
  TH1F* hPt = new TH1F("hPt","",nBins,ptBinsPlus);
  TH1F* hGen = new TH1F("hGen","",nBins,ptBinsPlus);

  for(int i=0;i<nBins;i++)
    {
      TF1* fData = fitDstar(ntData,ntMC,ptBins[i],genmatchpoint);
      Float_t yieldData = fData->Integral(BINMIN,BINMAX)/BINWID;
      Float_t yieldDataErr = fData->Integral(BINMIN,BINMAX)/BINWID*fData->GetParError(0)/fData->GetParameter(0);      
      aPt[i] = yieldData;
      aPtErr[i] = yieldDataErr;
      hPt->SetBinContent(i+1,aPt[i]);
      hPt->SetBinError(i+1,aPtErr[i]);
      TH1D* hGenFill = new TH1D(Form("hGenFill_%.0f",ptBins[i]),"",1,ptBins[i],1.e+3);
      hGenFill->Sumw2();
      ntGen->Project(Form("hGenFill_%.0f",ptBins[i]),"Gpt",TCut("%s",weightmc[isData].Data())*Form("%s&&%s",selgen5p.Data(),triggerselectionmc[isData].Data()));
      aGen[i] = hGenFill->GetBinContent(1);
      aGenErr[i] = hGenFill->GetBinError(1);
      hGen->SetBinContent(i+1,aGen[i]);
      hGen->SetBinError(i+1,aGenErr[i]);
    }

  TGraphErrors* gPt = new TGraphErrors(nBins,ptBins,aPt,aZero,aPtErr);
  gPt->SetName("gPt");
  TGraphErrors* gGen = new TGraphErrors(nBins,ptBins,aGen,aZero,aGenErr);
  gGen->SetName("gGen");

  TFile* outputfile = new TFile(Form("outputfiles/output_5p_%s_Minpt.root",texData[isData].Data()),"recreate");
  outputfile->cd();
  gPt->Write();
  gGen->Write();
  hPt->Write();
  hGen->Write();
  outputfile->Close();
}
void balanceMetVsAj(TString infname = "dj_HCPR-J50U-hiGoodMergedTracks_OfficialSelv2_Final0_120_50.root",
                    TCut myCut = "cent<30", char *title = "",bool drawLegend = false,
                    bool drawSys = true
		    )
{
   // ===========================================================
   // Get Input
   // ===========================================================
   TFile *inf = new TFile(infname);
   TTree *t = (TTree*)inf->Get("ntjt");


   t->SetAlias("metxMergedAll","(metOutOfConex0+metOutOfConex1+metOutOfConex2+metOutOfConex3+metOutOfConex4+metOutOfConex5)");
   t->SetAlias("metxMerged0","(metOutOfConex0)");
   t->SetAlias("metxMerged1","(metOutOfConex1)");
   t->SetAlias("metxMerged2","(metOutOfConex2)");
   t->SetAlias("metxMerged3","(metOutOfConex3)");
   t->SetAlias("metxMerged4","(metOutOfConex4+metOutOfConex5)");

   // ===========================================================
   // Analysis Setup
   // ===========================================================
   const int nBin = 5;
   double bins[nBin+1] = {0.5,1.0,1.5,4,8,1000};
   int colors[5] = {kBlue-10,kYellow-7, kOrange-2,kGreen-5,kRed-3};
   
   const int nBinAj = 4;
   double ajBins[nBinAj+1] = {0.0001,0.11,0.22,0.33,0.49999};
   // Selection cut
   TCut evtCut = "nljet>120&&abs(nljetacorr)<2&&aljet>50&&abs(aljetacorr)<2&&jdphi>2./3*TMath::Pi()&&!maskEvt";
//   TCut evtCut = "nljet>120&&abs(nljetacorr)<2&&aljet>50&&abs(aljetacorr)<2&&jdphi>3&&!maskEvt";

   cout << "Sel evt: " << t->GetEntries(evtCut&&myCut) << endl;

   // ===========================================================
   // Find Average Weights
   // ===========================================================
   TH1D *hw[nBinAj];
   float meanWt[nBinAj];
   for ( int iaj = 0 ; iaj< nBinAj ; iaj++) {
      hw[iaj] = new TH1D(Form("hw_aj%d",iaj),"",1000,0,100);
      TCut ajCut = Form("Aj>%f && Aj<%f", ajBins[iaj],ajBins[iaj+1]);
      t->Draw(Form("weight>>hw_aj%d",iaj), evtCut&&myCut&&ajCut);
      meanWt[iaj] = hw[iaj]->GetMean();
      cout << " <Weight>: " << meanWt[iaj] << endl;
   }

   // ===========================================================
   // Draw Weighted Averages
   // ===========================================================
   TH1D *ppos[nBin];
   TH1D *pneg[nBin];
   TH1D *pe[nBin];
   for (int i=0;i<nBin;i++)
   {
      TH1D *h1 = new TH1D(Form("h1%d",i),"",nBinAj,ajBins);
      TH1D *h2 = new TH1D(Form("h2%d",i),"",nBinAj,ajBins);
      TH1D *he[nBinAj];
      
      // =================================
      // Get Weighted Mean for each Aj bin
      // =================================
      h1->Sumw2();
      h2->Sumw2();
      t->Draw(Form("Aj>>h1%d",i), "weight"*(evtCut&&myCut));
      t->Draw(Form("Aj>>h2%d",i), Form("((-weight*metxMerged%d))",i)*(evtCut&&myCut));
      
      pe[i]=(TH1D*)h2->Clone();
      pe[i]->SetName(Form("p%d",i));     
      pe[i]->Divide(h1);
      ppos[i] = new TH1D(Form("ppos%d",i),"",nBinAj,ajBins);
      ppos[i]->SetLineColor(1);     
      ppos[i]->SetMarkerColor(colors[i]);
      ppos[i]->SetFillColor(colors[i]);
      ppos[i]->SetFillStyle(1001);
      pneg[i] = new TH1D(Form("pneg%d",i),"",nBinAj,ajBins);
      pneg[i]->SetLineColor(1);     
      pneg[i]->SetMarkerColor(colors[i]);
      pneg[i]->SetFillColor(colors[i]);
      pneg[i]->SetFillStyle(1001);

      // =================================
      // Caculated Stat Error of the Mean
      // =================================
      cout << "Stat Error for pt bin " << i << ": ";
      for ( int iaj = 0 ; iaj< nBinAj ; iaj++) {
         he[iaj] = new TH1D(Form("he%d_aj%d",i,iaj),"",100,-200,200);
         TCut ajCut = Form("Aj>%f && Aj<%f", ajBins[iaj],ajBins[iaj+1]);
         t->Draw(Form("((metxMerged%d))>>he%d_aj%d",i,i,iaj), "weight" * evtCut&&myCut&&ajCut);
         float theError = he[iaj]->GetRMS()/ (sqrt(he[iaj]->GetEntries()));
	 cout << theError << " ";
	 pe[i]->SetBinError(iaj+1, theError);
      }
      cout << endl;
   }

   // Stack
   for (int i=nBin-1;i>=0;i--)
   {
      for(int iaj = 0 ; iaj< nBinAj ; iaj++) {
         double posVal=0, negVal=0;
         double posValErr=0, negValErr=0;
         if (i!=nBin-1) {
            posVal = ppos[i+1]->GetBinContent(iaj+1);
            posValErr = ppos[i+1]->GetBinError(iaj+1);
            negVal = pneg[i+1]->GetBinContent(iaj+1);
            negValErr = pneg[i+1]->GetBinError(iaj+1);
         }
         if (pe[i]->GetBinContent(iaj+1)<0) {
            negVal+=pe[i]->GetBinContent(iaj+1);
            negValErr=pe[i]->GetBinError(iaj+1);
            posValErr=0;
         } else if (pe[i]->GetBinContent(iaj+1)>0) {
            posVal+=pe[i]->GetBinContent(iaj+1);
            posValErr=pe[i]->GetBinError(iaj+1);
            negValErr=0;
         } 
         ppos[i]->SetBinContent(iaj+1,posVal);
         ppos[i]->SetBinError(iaj+1,posValErr);
         pneg[i]->SetBinContent(iaj+1,negVal);
         pneg[i]->SetBinError(iaj+1,negValErr);
      }
   }
   
   TH1D *pall;
   TH1D *pallE;
   TH1D *h1 = new TH1D(Form("hAll1"),"",nBinAj,ajBins);
   TH1D *h2 = new TH1D(Form("hAll2"),"",nBinAj,ajBins);

   h1->Sumw2();
   h2->Sumw2();
   t->Draw(Form("Aj>>hAll1"), "weight"*(evtCut&&myCut));
   t->Draw(Form("Aj>>hAll2"), Form("((-weight*metxMergedAll))")*(evtCut&&myCut));
   pall=(TH1D*)h2->Clone();
   pall->SetName("pall");
   pall->Divide(h1);

   // replace the sys error from pallE to pall 
   TH1D *he[nBinAj];
   cout << "Stat Error for All pt: ";
   for ( int iaj = 0 ; iaj< nBinAj ; iaj++) {
      he[iaj] = new TH1D(Form("heAll_aj%d",iaj),"",100,-200,200);
      TCut ajCut = Form("Aj>%f && Aj<%f", ajBins[iaj],ajBins[iaj+1]);
      t->Draw(Form("((metxMergedAll))>>heAll_aj%d",iaj), "weight" * evtCut&&myCut&&ajCut);
      float theError = he[iaj]->GetRMS()/ (sqrt(he[iaj]->GetEntries()));
      cout << theError << " ";
      pall->SetBinError(iaj+1,  theError);
   }
   cout << endl;

   pall->SetXTitle("A_{J}");
   pall->SetYTitle("<#slash{p}_{T}^{#parallel}> (GeV/c)");
   pall->GetXaxis()->CenterTitle();
   pall->GetYaxis()->CenterTitle();
   pall->GetXaxis()->SetLabelSize(22);
   pall->GetXaxis()->SetLabelFont(43);
   pall->GetXaxis()->SetTitleSize(24);
   pall->GetXaxis()->SetTitleFont(43);
   pall->GetYaxis()->SetLabelSize(22);
   pall->GetYaxis()->SetLabelFont(43);
   pall->GetYaxis()->SetTitleSize(24);
   pall->GetYaxis()->SetTitleFont(43);
   pall->GetXaxis()->SetTitleOffset(1.8);
   pall->GetYaxis()->SetTitleOffset(2.4);
   pall->SetNdivisions(505);
   pall->SetAxisRange(-59.9,59.9,"Y");
   pall->SetMarkerSize(1);
   pall->Draw("E");
   float addSys = 0;
   if ( drawSys==1)   addSys=0; // No sys error at this moment

   // ====================
   // Finally Draw
   // ====================
   for (int i=0;i<nBin;++i) {
      ppos[i]->SetLineWidth(1);
      ppos[i]->Draw("hist same");
      pneg[i]->SetLineWidth(1);
      pneg[i]->Draw("hist same");
   }
   
   // ====================
   // Draw Statistical Error bars
   // ====================
   for (int i=0;i<nBin;++i) {
      if ( i==0 )       drawErrorShift(ppos[i],-0.016, addSys);
      if ( i==1 || i==4)       drawErrorShift(ppos[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(ppos[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(ppos[i],0.016,addSys);
      if ( i==0 )       drawErrorShift(pneg[i],-0.016, addSys);
      if ( i==1 || i==4)       drawErrorShift(pneg[i],-0.008,addSys);
      if ( i==2 )       drawErrorShift(pneg[i],0.008,addSys);
      if ( i==3 )       drawErrorShift(pneg[i],0.016,addSys);
   }
   pall->Draw("E same");
   
   // ====================
   // Draw Systematic Errors
   // ====================
   if (drawSys == 1) {
      for(int i = 0; i < nBinAj; ++i){
        double x = pall->GetBinCenter(i+1);
        double y = pall->GetBinContent(i+1);
        // Quote the difference between GEN and RECO in >8 Bin (20%) before adjusting eff as systematics
        double err = fabs(pe[nBin-1]->GetBinContent(i+1)*0.2);
        DrawTick(y,err,err,x,1,0.02,1);
      }
   }

   // ====================
   // Draw Legend
   // ====================
   TLegend *leg = new TLegend(0.10,0.68,0.70,0.96);
   leg->SetFillStyle(0);
   leg->SetBorderSize(0);
   leg->SetTextFont(63);
   leg->SetTextSize(16);
   leg->AddEntry(pall,Form("> %.1f GeV/c",bins[0]),"pl");
   for (int i=0;i<nBin;++i) {
      if (i!=nBin-1){
         leg->AddEntry(ppos[i],Form("%.1f - %.1f GeV/c",bins[i],bins[i+1]),"f");
      } else {
         leg->AddEntry(ppos[i],Form("> %.1f GeV/c",bins[i]),"f");
      }
   }

   if (drawLegend) leg->Draw();

   TLine * l0 = new TLine(0,0,0.5,0);
   l0->SetLineStyle(2);
   l0->Draw();


   TLine * l1 = new TLine(0.0001,-10,0.0001,10);
   l1->Draw();

   TText *titleText = new TText(0.3,30,title);
   titleText->Draw();
}
Exemple #8
0
void fit(const char *run="428211_429133_5s",
	 int key=1, int bmin=10, bool draw=true, bool pa=false) {
  int minentries=1000;
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  gSystem->Exec( Form("mkdir -p %s/SEN%03d",run,key/128) );
  int state = findstate(key);
  printf("state %d\n",state);
  // data
  TString inname = Form("%s/adc/HI_KEY%05d.root",run,key);
  TString outname = Form("HI_KEY%05d",key);
  TFile *file = new TFile( inname.Data() );
  cout << inname.Data() << endl;

  TH1D *out = (TH1D*) file->Get("out");
  double xfit_min=out->GetBinLowEdge(bmin);
  double xfit_max=122.5;
  int bmax = out->GetXaxis()->FindBin(xfit_max);
  int entries = out->Integral(bmin,bmax);
  if(entries<minentries) {
    cout << "not enough entries: ";
    cout << entries << endl;
    return;
  }

  // fit
  TCanvas *main = new TCanvas("main","main");
  int pkt=0;
  if(pa)
    pkt = (key%(8*4*12*64))/(4*12*64);
  TF1 *fitH = GetFit( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) ,pkt,xfit_min);
  out->Fit(fitH,"MELIR","",xfit_min,xfit_max);
  TF1 *MIPH1 = GetMIP(fitH,1,kCyan-3);
  TF1 *MIPH2 = GetMIP(fitH,2,kGreen-3);
  TF1 *MIPH3 = GetMIP(fitH,3,kOrange-3);
  TF1 *MIPH4 = GetMIP(fitH,4,kMagenta-3);
  TF1 *BGR = GetBGR(fitH,xfit_min);

  double amp = fitH->GetParameter(0);
  double eamp= fitH->GetParError(0);
  double lda = fitH->GetParameter(1);
  double elda= fitH->GetParError(1);
  double sg1 = fitH->GetParameter(2);
  double esg1= fitH->GetParError(2);
  double fr2 = fitH->GetParameter(3);
  double efr2= fitH->GetParError(3);
  double fr3 = fitH->GetParameter(4);
  double efr3= fitH->GetParError(4);
  double fr4 = fitH->GetParameter(5);
  double efr4= fitH->GetParError(5);
  double fr1 = 1 - fr2 - fr3 - fr4;
  double ncs = fitH->GetChisquare()/fitH->GetNDF();
  double ba = fitH->GetParameter(6);
  double eba= fitH->GetParError(6);
  double bsl = fitH->GetParameter(7);
  double ebsl= fitH->GetParError(7);

  // saving fit
  ofstream outfit;
  outfit.open( Form("%s/SEN%03d/%s.dat",run,key/128,outname.Data()) );
  outfit << amp << " " << eamp << endl;
  outfit << lda << " " << elda << endl;
  outfit << sg1 << " " << esg1 << endl;
  outfit << fr2 << " " << efr2 << endl;
  outfit << fr3 << " " << efr3 << endl;
  outfit << fr4 << " " << efr4 << endl;
  outfit << ba  << " " << eba  << endl;
  outfit << bsl << " " << ebsl << endl;
  outfit << ncs << endl;
  outfit.close();
  cout << "Parameters saved to ";
  cout << outname.Data() << ".dat" << endl;

  // draw
  if(!draw) return;

  gStyle->SetOptFit(0);
  gStyle->SetOptStat(0);
  out->Draw("HE");
  double ymax = out->GetBinContent( out->FindBin(xfit_min) )*1.5;
  out->GetYaxis()->SetRangeUser(0.5,ymax);
  out->GetXaxis()->SetRangeUser(-5,125);
  out->Sumw2();
  out->SetLineColor(kBlack);
  out->SetMarkerStyle(20);
  out->SetTitle("");
  out->GetXaxis()->SetTitle("ADC-PED (a.u.)");
  BGR->Draw("SAME");
  MIPH1->Draw("SAME");
  MIPH2->Draw("SAME");
  MIPH3->Draw("SAME");
  MIPH4->Draw("SAME");
  fitH->SetRange(xfit_min,xfit_max);
  fitH->Draw("SAME");
  TLatex *text = new TLatex();
  text->DrawLatex(0, (1.03*(ymax)), inname.Data() );
  text->DrawLatex(30, (0.83*(ymax)), Form("Entries  %d",entries) );
  text->DrawLatex(30, (0.73*(ymax)), Form("State  %d",state) );
  text->DrawLatex(30, (0.53*(ymax)), Form("#lambda  %.1f #pm %.1f",lda,elda) );
  text->DrawLatex(30, (0.43*(ymax)), Form("#sigma  %.1f #pm %.1f",sg1,esg1) );
  text->SetTextColor(kRed-3);
  text->DrawLatex(30, (0.63*(ymax)), Form("#Chi^{2} / NDF  %.2f",ncs) );
  text->SetTextColor(kBlue-3);
  text->DrawLatex(75, (0.73*(ymax)), Form("#Alpha  %.0f #pm %.0f",fitH->GetParameter(0),fitH->GetParError(0)) );
  text->SetTextColor(kCyan-3);
  text->DrawLatex(75, (0.63*(ymax)), Form("f_{1}  %.2f",fr1) );
  text->SetTextColor(kGreen-3);
  text->DrawLatex(75, (0.53*(ymax)), Form("f_{2}  %.2f #pm %.2f",fr2,efr2) );
  text->SetTextColor(kOrange-3);
  text->DrawLatex(75, (0.43*(ymax)), Form("f_{3}  %.2f #pm %.2f",fr3,efr3) );
  text->SetTextColor(kMagenta-3);
  text->DrawLatex(75, (0.33*(ymax)), Form("f_{4}  %.2f #pm %.2f",fr4,efr4) );
  text->SetTextColor(kGray);
  text->DrawLatex(75, (0.83*(ymax)), Form("b  %.2f",bsl) );
  text->SetTextColor(kBlack);
  text->SetTextSize(0.035);
  text->SetTextColor( kRed-3 );
  text->DrawLatex(30, (0.93*(ymax)), "e^{bx} + #Alpha ( f_{1} L_{1}(x) + f_{2} L_{2}(x) + f_{3} L_{3}(x) + f_{4} L_{4}(x))");
  main->SaveAs( Form("%s/SEN%03d/%s.eps",run,key/128,outname.Data()), "eps" );
  return;
}
Exemple #9
0
int purityRandNorm(TH1D* h_template, TString name , TFile * fData, TFile * fZinv, TFile * fDY, int & lastmt2val_hybrid) {

  //cout<<"purityRandNorm for template "<<name<<endl;
  //h_template->Print("all");
  int lastbin_hybrid = 0;
  lastmt2val_hybrid = 200;
  TString name_emu = name + "emu";
  TString name_zinv = name;
  name_zinv.ReplaceAll("crdy", "sr");
  TH1D* hEMU   = (TH1D*) fData->Get(name_emu);    
  TH1D* hDY    = (TH1D*) fDY->Get(name);    
  TH1D* hZinv  = (TH1D*) fZinv->Get(name_zinv); 
  if (h_template == 0) {
    cout<<"ZinvMaker::purityAndRatio  :  could not find input template"<<endl;
    return lastbin_hybrid;
  }
  if (hDY == 0 || hZinv == 0) {
    cout<<"ZinvMaker::purityAndRatio  :  could not find DY or Zinv MC histogram"<<endl;
    return lastbin_hybrid;
  }
  if (hEMU) h_template->Add(hEMU, -1*rSFOF);

  // find the last bin
  for ( int ibin=1; ibin <= hDY->GetNbinsX(); ++ibin ) {
    float integratedYield = 0;
    integratedYield = hDY->Integral(ibin,-1);
    if (integratedYield < hybrid_nevent_threshold) {
      if (ibin == 1) lastbin_hybrid = 1;
      else {
	lastbin_hybrid = ibin-1;
	lastmt2val_hybrid = hDY->GetBinLowEdge(ibin);
      }
      break;
    }
  }

  // multiply R(Znn/Zll)
  TH1D* ratio =   (TH1D*) hZinv->Clone("ratio");
  ratio->Divide(hDY);

  h_template->Multiply(ratio);

  // Get the integrals to normalize the Zinv tails
  // and the uncertainties on the CR yield (dominated by data stats in the last N bins)
  double integratedYieldErrZinv = 0;
  float integratedYieldZinv = hZinv->IntegralAndError(lastbin_hybrid, -1., integratedYieldErrZinv);
  float relativeErrorZinv = integratedYieldErrZinv/integratedYieldZinv;
  double integratedYieldErr = 0;
  float integratedYield = h_template->IntegralAndError(lastbin_hybrid,-1,integratedYieldErr); 
  float relativeError = integratedYieldErr/integratedYield;

  // Hybridize the template: last N bins have a common stat uncertainty, and they follow the Zinv MC shape
  for ( int ibin=1; ibin <= hZinv->GetNbinsX(); ++ibin ) {

    if (ibin < lastbin_hybrid) continue;

    float kMT2 = hZinv->GetBinContent(ibin) / integratedYieldZinv;
    float err = sqrt( relativeError*relativeError + relativeErrorZinv*relativeErrorZinv);
    h_template->SetBinContent(ibin, integratedYield * kMT2);
    h_template->SetBinError(ibin, integratedYield * kMT2 * err );

  }

  // Normalize it: we just need a shape after all
  h_template->Scale(1./h_template->Integral());

  //h_template->Print("all");


  return lastbin_hybrid;
}
void MiniTreeSignalProducerVV13TeV(int samplemin, int samplemax){

 string dir = "/usr/users/dschaefer/CMSSW_7_4_7/src/DijetCombineLimitCode/";
  double mgg, mjj,evWeight, mtot, normWeight;
 int categories;

 evWeight = 1.0;
 normWeight = 1;

 for (int iSample = samplemin; iSample < samplemax; iSample++){
   
   string inFile("WprimeToWZ");
   if (iSample == 1) inFile = string("RS1WW");
   if (iSample == 2) inFile = string("RS1ZZ"); // Fake ZZ signal
   if (iSample == 3) inFile = string("QstarQW");
   if (iSample == 4) inFile = string("QstarQZ");
   if (iSample == 5) inFile = string("BulkWW");
   if (iSample == 6) inFile = string("BulkZZ");
   if (iSample == 7) inFile = string("ZprimeWW");
   if (iSample == 8) inFile = string("WprimeWZ");

   string outFile("dijetVV_13TeV_WZ");
   if (iSample == 1) outFile = string("dijetVV_13TeV_RS1WW");
   if (iSample == 2) outFile = string("dijetVV_13TeV_RS1ZZ");
   if (iSample == 3) outFile = string("dijetVV_13TeV_QstarQW");
   if (iSample == 4) outFile = string("dijetVV_13TeV_QstarQZ");
   if (iSample == 5) outFile = string("dijetVV_13TeV_BulkWW");
   if (iSample == 6) outFile = string("dijetVV_13TeV_BulkZZ");
   if (iSample == 7) outFile = string("dijetVV_13TeV_ZprimeWW");
   if (iSample == 8) outFile = string("dijetVV_13TeV_WZ");
   
   int massrange=36;

   for (int iMass = 0; iMass<massrange; iMass++){

     string sInFile = dir+"input/" + inFile + "_13TeV_" + Form("10k_OUT%dGeV.root", 1000+iMass*100);
     cout << sInFile.c_str() << endl;
     TFile file0(sInFile.c_str(), "read");

     string sOutFile = dir+"MiniTrees/Signal_VV_13TeV/" + outFile + Form("OUT%d_miniTree.root", 1000+iMass*100);
     TFile f1(sOutFile.c_str(), "recreate");
     f1.cd();

     TTree *TCVARS = new TTree("TCVARS", "VV selection");
     TCVARS->Branch("mgg13TeV",&mgg,"mgg/D");

     TCVARS->Branch("evWeight",&evWeight,"evWeight/D");
     TCVARS->Branch("normWeight",&normWeight,"normWeight/D");
     
     TCVARS->Branch("categories",&categories,"categories/I");

  
     double dMass = 1000.+iMass*100.;

     
     for (int iCat = 2; iCat < 8; iCat++){
       TH1D* hMass = (TH1D*) file0.Get("DijetMassHighPuriVV;1");
       if (iCat == 1) hMass = (TH1D*) file0.Get("DijetMassLowPuriVV;1");
       
       if (iCat == 2) hMass = (TH1D*) file0.Get("DijetMassHighPuriWW;1");
       if (iCat == 3) hMass = (TH1D*) file0.Get("DijetMassLowPuriWW;1");
       
       if (iCat == 4) hMass = (TH1D*) file0.Get("DijetMassHighPuriWZ;1");
       if (iCat == 5) hMass = (TH1D*) file0.Get("DijetMassLowPuriWZ;1");
       
       if (iCat == 6) hMass = (TH1D*) file0.Get("DijetMassHighPuriZZ;1");
       if (iCat == 7) hMass = (TH1D*) file0.Get("DijetMassLowPuriZZ;1");
    
       if (iCat == 8) hMass = (TH1D*) file0.Get("DijetMassHighPuriqV;1");
       if (iCat == 9) hMass = (TH1D*) file0.Get("DijetMassLowPuriqV;1");

       if (iCat == 10) hMass = (TH1D*) file0.Get("DijetMassHighPuriqW;1");
       if (iCat == 11) hMass = (TH1D*) file0.Get("DijetMassLowPuriqW;1");

       if (iCat == 12) hMass = (TH1D*) file0.Get("DijetMassHighPuriqZ;1");
       if (iCat == 13) hMass = (TH1D*) file0.Get("DijetMassLowPuriqZ;1");

       if (iCat == 14) hMass = (TH1D*) file0.Get("DijetMassNoPuriVV;1");
       if (iCat == 15) hMass = (TH1D*) file0.Get("DijetMassNoPuriWW;1");
       if (iCat == 16) hMass = (TH1D*) file0.Get("DijetMassNoPuriWZ;1");
       if (iCat == 17) hMass = (TH1D*) file0.Get("DijetMassNoPuriZZ;1");
       if (iCat == 18) hMass = (TH1D*) file0.Get("DijetMassNoPuriqV;1");
       if (iCat == 19) hMass = (TH1D*) file0.Get("DijetMassNoPuriqW;1");
       if (iCat == 20) hMass = (TH1D*) file0.Get("DijetMassNoPuriqZ;1");
       // TH1D* hMass = (TH1D*) file0.Get("DijetMassHighPuriVV"); // WW high purity
//        if (iCat == 1) hMass = (TH1D*) file0.Get("DijetMassLowPuriVV"); // WW low purity
//        if (iCat == 2) hMass = (TH1D*) file0.Get("DijetMassHighPuriWW"); // WW high purity
//        if (iCat == 3) hMass = (TH1D*) file0.Get("DijetMassLowPuriWW"); // WW low purity
//        if (iCat == 4) hMass = (TH1D*) file0.Get("DijetMassHighPuriWZ"); // WZ high purity
//        if (iCat == 5) hMass = (TH1D*) file0.Get("DijetMassLowPuriWZ"); // WZ low purity
//        if (iCat == 6) hMass = (TH1D*) file0.Get("DijetMassHighPuriZZ"); // ZZ high purity
//        if (iCat == 7) hMass = (TH1D*) file0.Get("DijetMassLowPuriZZ"); // ZZ low purity
       
       if(!hMass) continue;
       
       TAxis* Axis =   hMass->GetXaxis();
       for (int i = 1 ; i < hMass->GetNbinsX()+1; i++){
	 //if (hMass->GetBinCenter(i) < dMass*0.75 || hMass->GetBinCenter(i) > dMass*1.25) continue;
	 int N = abs(hMass->GetBinContent(i));
	 if (i%1000 == 0) cout << "i = " << i << " N = " << N << endl;
	 
	 mgg = Axis->GetBinCenter(i);
	 
         categories = iCat;
	 for (int k = 0; k < N; k++) {
	   TCVARS->Fill();
	 }
       }
     }
		 TCVARS->Write();
     f1.Close();
     file0.Close();
     
   }

 }


}
TCanvas *drawRatioPlot(TH1D *prediction, TH1D *sr, TH1D *data, TString xTitle, TString filename, double ecaloCut){

  gStyle -> SetPadLeftMargin(0.20);

  data->SetMarkerStyle(20);
  data->SetMarkerColor(kGreen);
  data->SetLineColor(kGreen);


  
  TCanvas *c = new TCanvas("c"+filename,"c",0,0,500,500);

  float y = 0.3;

  TPad *pad1     = new TPad("pad1", "Control Plots 1", 0.01, y, 0.99, 0.99);
  TPad *padRatio = new TPad("rp1", "Ratio1", 0.01, 0.01, 0.99, y-0.01);

  pad1->SetNumber(100);
  pad1->SetTicks(0,1);
  cout<<"number pad1     = "<<pad1->GetNumber()<<endl;
  cout<<"number padRatio = "<<padRatio->GetNumber()<<endl;

  TH1D *ratio = 0;

  //ratio = (TH1D*) sr->Clone();
  //ratio->Divide(prediction);

  ratio = (TH1D*) prediction->Clone();
  ratio->Divide(data);



  for(int i=1; i<=ratio->GetNbinsX();i++){

    if(ratio->GetBinContent(i) != 0){
      cout<<"N in CR in "<<i<<". bin ="<<prediction->GetBinContent(i)<<endl;
      cout<<"N in SR in "<<i<<". bin ="<<sr->GetBinContent(i)<<endl;
      cout<<"Rel. difference in "<<i<<". bin ="<<(1./ratio->GetBinContent(i)-1.)*100<<"%"<<endl; 
    }
    else if(sr->GetBinContent(i) == 0 && prediction->GetBinContent(i) !=0)    cout<<"Scaling Factor in "<<i<<". bin <"<<prediction->GetBinContent(i)/1.15<<" +/- "<<ratio->GetBinError(i)<<endl;
    else if(sr->GetBinContent(i) != 0 && prediction->GetBinContent(i) ==0)    cout<<"Scaling Factor in "<<i<<". bin <"<<(sr->GetEntries()/prediction->GetEntries())/sr->GetBinContent(i)<<" +/- "<<ratio->GetBinError(i)<<endl;

  }

  ratio->GetYaxis()->SetTitle("#frac{CR (MC)}{CR (data)}");
  ratio->SetTitle("");
  ratio->SetLabelSize(0.1,"X");
  ratio->SetLabelSize(0.1,"Y");
  ratio->SetTitleOffset(0.5,"Y");
  ratio->SetTitleSize(0.15,"Y");


  padRatio->cd();
  //ratio->GetYaxis()->SetRangeUser(0,2);
  ratio->Draw("e");

  // Draw line at one!
  float xmin = ratio->GetXaxis()->GetXmin();
  float xmax = ratio->GetXaxis()->GetXmax();
  TLine *line = new TLine(xmin,1,xmax,1);
  line->SetLineWidth(2);
  line->Draw("same");
  padRatio->Modified();

  TLegend *leg = new TLegend(0.5,0.7,0.9,0.9);
  leg->AddEntry(sr,"SR (MC)","l"); 
  leg->AddEntry(prediction,"lepton CR (MC)","pel"); 
 
  pad1->cd();
  pad1->SetLogy();
  //  pad1->SetLogx();

  sr->SetLineColor(kRed);
  sr->SetMarkerColor(kRed);
  sr->SetMarkerStyle(20);
  sr->SetTitle("");
  prediction->SetMarkerStyle(20);
  prediction->SetTitle("");
  prediction->GetXaxis()->SetTitle(xTitle);
  sr->GetXaxis()->SetTitle(xTitle);

  
  

  prediction->SetTitleSize(0.07,"X");
  prediction->GetXaxis()->SetTitleOffset(0.7);
  sr->SetTitleSize(0.07,"X");
  sr->GetXaxis()->SetTitleOffset(0.7);

  double maximum = 0;
  double minimum = 1000000;
  if(sr->GetMinimum()!=0 && sr->GetMinimum()<minimum){
    minimum=sr->GetMinimum()*0.5;
  }
  if(prediction->GetMinimum()!=0 && prediction->GetMinimum()<minimum){
    minimum=prediction->GetMinimum()*0.5;
  }
  if(data->GetMinimum()!=0 && data->GetMinimum()<minimum){
    minimum=data->GetMinimum()*0.5;
  }
  if(sr->GetMaximum()>maximum){
    maximum=sr->GetMaximum()*2.5;
  }
  if(prediction->GetMaximum()>maximum){
    maximum=prediction->GetMaximum()*2.5;
  }
  if(data->GetMaximum()>maximum){
    maximum=data->GetMaximum()*2.5;
  }

  prediction->GetYaxis()->SetRangeUser(minimum,maximum);
  ratio->GetYaxis()->SetRangeUser(0,2);


  prediction->Draw("e");
  sr->Draw("e same");
  leg->AddEntry(data,"lepton CR (data)","pel"); 
  data->Draw("e same");

  
  leg->Draw("same");


  TLatex*  info1   = new TLatex();
  info1->SetTextFont(132);
  info1-> SetNDC();
  info1->SetTextSize(0.06);
  info1->DrawLatex(0.55,0.62,Form("E_{calo}<%.0fGeV",ecaloCut));

  // Draw both pads to canvas
  c->cd();
  pad1->Draw();
  padRatio->SetGridy();
  padRatio->Draw();

  c->SaveAs(filename);

  return c;

}
int main(int argc, char* argv[]) {

  TH1::SetDefaultSumw2();

  ProgramOptions options(argc, argv);

  double lumi = options.lumi;

  // input datasets
  Datasets datasets(options.iDir);
  datasets.readFile(options.datasetFile);
 
  std::string oDir_Plot = options.oDir+std::string("/ZBackground");

  boost::filesystem::path opath(oDir_Plot);
  if (!exists(opath)) {
    std::cout << "Creating output directory : " << oDir_Plot << std::endl;
    boost::filesystem::create_directory(opath);
  }
 
  if (options.doMCFMWeights) std::cout << "Going to apply MCFM weights" << std::endl;

  // output file
  TFile* ofile = TFile::Open( (options.oDir+std::string("/ZBackground.root")).c_str(), "RECREATE");

  // cuts
  Cuts cuts;
  unsigned nCutsZMuMu = cuts.nCutsZMuMu();

  TCut puWeight("puWeight");
  TCut trigCorr( "(trigCorrWeight>0) ? trigCorrWeight : 1." );
  TCut METNoMuon130("metNoMuon>130.");	// add here later for VBF efficiency when MET>35, MET>70 (QCD estimation)
  TCut METNo2Muon130("metNo2Muon>130.");
  TCut cutLoDPhi = cuts.cut("dPhiJJ");

  // For lepton weights
  TCut lVetoWeight   = cuts.elVetoWeight(options.leptCorr) * cuts.muVetoWeight(options.leptCorr);
  TCut muTightWeight = cuts.muTightWeight(options.leptCorr);

  // histograms
  double dphiEdges[4] = { 0., 1.0, 2.6, TMath::Pi() };
  //double metEdges[13] = { 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., 110., 120. };

  // signal MET>130
  TH1D* hZ_DY_C_DPhi   = new TH1D("hZ_DY_C_DPhi",   "", 3, dphiEdges);  // Z+jets MC ctrl region
  TH1D* hZ_BG_C_DPhi   = new TH1D("hZ_BG_C_DPhi",   "", 3, dphiEdges);  // background MC ctrl region
  TH1D* hZ_Data_C_DPhi = new TH1D("hZ_Data_C_DPhi", "", 3, dphiEdges);  // Data ctrl region

  TH1D* hZ_QCD_EffVBFS_D = new TH1D("hZ_QCD_EffVBFS_D", "", 1, 0., 1.);
  TH1D* hZ_QCD_EffVBFS_N = new TH1D("hZ_QCD_EffVBFS_N", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFS_D = new TH1D("hZ_EWK_EffVBFS_D", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFS_N = new TH1D("hZ_EWK_EffVBFS_N", "", 1, 0., 1.);
 
  // combine eps_VBF_C * eps_mumu which remove canceling term (denominator is Z->uu gen level cut)
  TH1D* hZ_QCD_EffVBFC_D = new TH1D("hZ_QCD_EffVBFC_D", "", 1, 0., 1.);
  TH1D* hZ_QCD_EffVBFC_N = new TH1D("hZ_QCD_EffVBFC_N", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFC_D = new TH1D("hZ_EWK_EffVBFC_D", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFC_N = new TH1D("hZ_EWK_EffVBFC_N", "", 1, 0., 1.);

  // cutflow histograms
  TH1D* hZ_CutFlow_Data       = new TH1D("hZ_CutFlow_Data",       "", nCutsZMuMu, 0., nCutsZMuMu);
  TH1D* hZ_CutFlow_DY         = new TH1D("hZ_CutFlow_DY",         "", nCutsZMuMu, 0., nCutsZMuMu);
  TH1D* hZ_CutFlow_SingleTSum = new TH1D("hZ_CutFlow_SingleTSum", "", nCutsZMuMu, 0., nCutsZMuMu);
  TH1D* hZ_CutFlow_Diboson    = new TH1D("hZ_CutFlow_Diboson",    "", nCutsZMuMu, 0., nCutsZMuMu);

  // Hists to calculate DY normalisation factor
  TH1D* hZ_DY_NoVBFNoWeight = new TH1D("hZ_DY_NoVBFNoWeight","", 1, 0., 1.); // DY MC yield after dimuon and dijet selection without y* and mjj weighting
  TH1D* hZ_DY_NoVBFWeight   = new TH1D("hZ_DY_NoVBFWeight",  "", 1, 0., 1.); // DY MC yield after dimuon and dijet selection with y* and mjj weighting

  // loop over MC datasets
  for (unsigned i=0; i<datasets.size(); ++i) {

    Dataset dataset = datasets.getDataset(i);
    
    TCut cutD = cuts.cutDataset(dataset.name);
    TCut yStarWeight("");
    TCut mjjWeight("");

    // check if it's DYJets
    bool isDY = false;
    if (dataset.name.compare(0,2,"DY")==0) {
      isDY = true;
      std::cout << "Analysing DY->ll MC : " << dataset.name << std::endl; 
      // check if it's QCD
      if ( !(dataset.name.length()>11 && dataset.name.compare(11,14,"EWK")==0) ) {
    	if (options.doMCFMWeights) {
    	  yStarWeight = TCut("(0.849667 + (0.149687*abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))))");
    	  mjjWeight   = TCut("0.392568 + (0.120734*log(genVBFM)) - (0.000255622*genVBFM)");
    	}
    	std::cout << "Analysing QCD DY MC " << std::endl;
      }
    }
    else if (dataset.isData) {
      std::cout << "Analysing Data      : " << dataset.name << std::endl;
    }
    else {
      std::cout << "Analysing BG MC     : " << dataset.name << std::endl;
    }

    TCut otherWeight = puWeight * yStarWeight * mjjWeight;

    // get file & tree
    TFile* file = datasets.getTFile(dataset.name);
    TTree* tree = (TTree*) file->Get("invHiggsInfo/InvHiggsInfo");

    // set up cuts
    TCut cutZMuMu_C           = otherWeight * trigCorr * (cutD + cuts.zMuMuVBF() + METNo2Muon130);
    
    TCut cutEfficiencyMuMu_D  = otherWeight * (cutD + cuts.zMuMuGen());
    //TCut cutEfficiencyMuMu_N  = otherWeight * (cutD + cuts.zMuMuGen() + cuts.zMuMuReco());
 
    TCut cutEfficiencyVBFS_D  = otherWeight * (cutD + cuts.zMuMuGenMass());
    TCut cutEfficiencyVBFS_N  = otherWeight * trigCorr * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGenMass() + cuts.vbf() + METNoMuon130 + cutLoDPhi);
    
    //TCut cutEfficiencyVBFC_D  = otherWeight * (cutD + cuts.zMuMuGen() + cuts.zMuMuReco());
    TCut cutEfficiencyVBFC_N  = otherWeight * trigCorr * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.vbf() + METNo2Muon130 + cutLoDPhi);

    // re-weighting
    TCut cutDYNoVBFNoWeight = puWeight * trigCorr * (cutD  + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.cutZMuMu("dijet"));
    TCut cutDYNoVBFWeight   = otherWeight * trigCorr * (cutD  + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.cutZMuMu("dijet"));

    if(!(dataset.isData)) {
	cutZMuMu_C *= muTightWeight;
	cutEfficiencyVBFC_N *= muTightWeight;
	cutDYNoVBFNoWeight  *= muTightWeight;
	cutDYNoVBFWeight    *= muTightWeight;
    }

    // fill tmp histograms for BG estimation
    TH1D* hZ_C_DPhi  = new TH1D("hZ_C_DPhi", "", 3, dphiEdges);  // this is for the actual BG estimation
    // fill tmp histograms for efficiency calculation
    TH1D* hZ_EffVBFS_D  = new TH1D("hZ_EffVBFS_D", "", 1, 0., 1.);
    TH1D* hZ_EffVBFS_N  = new TH1D("hZ_EffVBFS_N", "", 1, 0., 1.);
    TH1D* hZ_EffVBFC_D  = new TH1D("hZ_EffVBFC_D", "", 1, 0., 1.);
    TH1D* hZ_EffVBFC_N  = new TH1D("hZ_EffVBFC_N", "", 1, 0., 1.);

    TH1D* hZ_DY_NoWeight = new TH1D("hZ_DY_NoWeight", "", 1, 0, 1);
    TH1D* hZ_DY_Weight   = new TH1D("hZ_DY_Weight",   "", 1, 0, 1);
    

    if (isDY) {
      tree->Draw("vbfDPhi>>hZ_C_DPhi", cutZMuMu_C);
      tree->Draw("0.5>>hZ_EffVBFS_D",  cutEfficiencyVBFS_D);
      tree->Draw("0.5>>hZ_EffVBFS_N",  cutEfficiencyVBFS_N);
      tree->Draw("0.5>>hZ_EffVBFC_D",  cutEfficiencyMuMu_D);
      tree->Draw("0.5>>hZ_EffVBFC_N",  cutEfficiencyVBFC_N);

      tree->Draw("0.5>>hZ_DY_NoWeight", cutDYNoVBFNoWeight);
      tree->Draw("0.5>>hZ_DY_Weight",   cutDYNoVBFWeight);

//       tree->Draw("abs((log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/(sqrt(zgenmass*zgenmass + zgenpt*zgenpt)))) - 0.5*(genJet1Eta + genJet2Eta))>>hYStar", cutDYNoVBFNoWeight);
//       tree->Draw("abs((log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/(sqrt(zgenmass*zgenmass + zgenpt*zgenpt)))) - 0.5*(genJet1Eta + genJet2Eta))>>hYStarC", cutZMuMu_C);
    }
    else {
      tree->Draw("vbfDPhi>>hZ_C_DPhi", cutZMuMu_C);
      //tree->Draw("met:vbfDPhi>>hZ_C_METDPhi",  cutZMuMu_MET0_C);
    }

    // weight  to lumi
    double weight = (dataset.isData) ? 1. : lumi * dataset.sigma / dataset.nEvents;
    hZ_C_DPhi->Scale(weight);
    hZ_EffVBFS_D->Scale(weight);
    hZ_EffVBFS_N->Scale(weight);
    hZ_EffVBFC_D->Scale(weight);
    hZ_EffVBFC_N->Scale(weight);

    hZ_DY_NoWeight->Scale(weight);
    hZ_DY_Weight->Scale(weight);
    
    // add to output histograms
    if (dataset.isData) {
      hZ_Data_C_DPhi->Add(hZ_C_DPhi);
    }
    else if (isDY) {
      hZ_DY_C_DPhi->Add(hZ_C_DPhi);

      hZ_DY_NoVBFNoWeight->Add(hZ_DY_NoWeight);
      hZ_DY_NoVBFWeight->Add(hZ_DY_Weight);

      if(dataset.name == "DYJetsToLL_NoTrig" || dataset.name == "DYJetsToLL_PtZ-100_NoTrig") {
        hZ_QCD_EffVBFS_D->Add(hZ_EffVBFS_D);
        hZ_QCD_EffVBFS_N->Add(hZ_EffVBFS_N);
        hZ_QCD_EffVBFC_D->Add(hZ_EffVBFC_D);
        hZ_QCD_EffVBFC_N->Add(hZ_EffVBFC_N);
      }
      if(dataset.name == "DYJetsToLL_EWK_NoTrig") {
        hZ_EWK_EffVBFS_D->Add(hZ_EffVBFS_D);
        hZ_EWK_EffVBFS_N->Add(hZ_EffVBFS_N);
        hZ_EWK_EffVBFC_D->Add(hZ_EffVBFC_D);
        hZ_EWK_EffVBFC_N->Add(hZ_EffVBFC_N);
      }
    }
    else {
      hZ_BG_C_DPhi->Add(hZ_C_DPhi);
    }

    std::cout << "  N ctrl (dphi<1.0) : " << hZ_C_DPhi->GetBinContent(1) << " +/- " << hZ_C_DPhi->GetBinError(1) << std::endl;  
    

    delete hZ_C_DPhi;
    delete hZ_EffVBFS_D;
    delete hZ_EffVBFS_N;
    delete hZ_EffVBFC_D;
    delete hZ_EffVBFC_N;

    delete hZ_DY_NoWeight;
    delete hZ_DY_Weight;

    ofile->cd();

    // cut flow histograms
    std::string hname = std::string("hZ_CutFlow_")+dataset.name;
    TH1D* hZ_CutFlow = new TH1D(hname.c_str(), "", nCutsZMuMu, 0., nCutsZMuMu);

    for (unsigned c=0; c<nCutsZMuMu; ++c) {

      TCut cut;

      if(c == nCutsZMuMu-1) cut = otherWeight * trigCorr * (cutD + cuts.cutflowZMuMu(c));
      else cut = otherWeight * (cutD + cuts.cutflowZMuMu(c));

      if(!(dataset.isData)) cut *= muTightWeight;

      TH1D* h = new TH1D("h","", 1, 0., 1.);
      tree->Draw("0.5>>h", cut);

      hZ_CutFlow->SetBinContent(c+1, h->GetBinContent(1));
      hZ_CutFlow->SetBinError(c+1, h->GetBinError(1));

      delete h;
    }

    hZ_CutFlow->Scale(weight);

    if (dataset.isData) {
      hZ_CutFlow_Data->Add(hZ_CutFlow);
    }
    if (dataset.name.compare(0,2,"DY")==0) {
      hZ_CutFlow_DY->Add(hZ_CutFlow);
    }
    if (dataset.name.compare(0,7,"SingleT")==0) {
      hZ_CutFlow_SingleTSum->Add(hZ_CutFlow);
    }
    if (dataset.name.compare(0,2,"WW")==0 ||
  	dataset.name.compare(0,2,"WZ")==0 ||
  	dataset.name.compare(0,2,"ZZ")==0 || 
	dataset.name.compare(0,2,"WG")==0) {
      hZ_CutFlow_Diboson->Add(hZ_CutFlow);
    }

    hZ_CutFlow->Write("",TObject::kOverwrite);

    delete hZ_CutFlow;


    // Z control plots
    TCut cutPlots = otherWeight * trigCorr * (cutD + cuts.zMuMuVBFLoose());

    if(!(dataset.isData)) cutPlots *= muTightWeight;
 
    TFile* ofile_Plot = TFile::Open( (oDir_Plot+std::string("/")+dataset.name+std::string(".root")).c_str(), "RECREATE");

    TH1D* ZCtrlZMass    = new TH1D("ZCtrlZMass",    "", 30, 60., 120.);
    TH1D* ZCtrlZpT      = new TH1D("ZCtrlZpT",      "", 50, 0.,  1000.);
    TH1D* ZCtrlJet1pT   = new TH1D("ZCtrlJet1pT",   "", 50, 0.,  1000.);
    TH1D* ZCtrlJet1Eta  = new TH1D("ZCtrlJet1Eta",  "", 50, -5., 5.);
    TH1D* ZCtrlJet2pT   = new TH1D("ZCtrlJet2pT",   "", 50, 0.,  1000.);
    TH1D* ZCtrlJet2Eta  = new TH1D("ZCtrlJet2Eta",  "", 50, -5., 5.);
    TH1D* ZCtrlCenJetpT = new TH1D("ZCtrlCenJetpT", "", 50, 0.,  400.);
    TH1D* ZCtrlDEtajj   = new TH1D("ZCtrlDEtajj",   "", 50, 0.,  8.);
    TH1D* ZCtrlMjj      = new TH1D("ZCtrlMjj",      "", 30, 0.,  3000.);
    TH1D* ZCtrlMET      = new TH1D("ZCtrlMET",      "", 25, 10.,  510.);
    TH1D* ZCtrlDPhijj   = new TH1D("ZCtrlDPhijj",   "", 50, 0.,  TMath::Pi());

    TH1D* ZCtrlYStar    = new TH1D("ZCtrlYStar",    "", 50, 0., 5.);
    TH1D* ZCtrlYStarWt  = new TH1D("ZCtrlYStarWt",  "", 50, 0., 2.);
    TH1D* ZCtrlMjjWt    = new TH1D("ZCtrlMjjWt",    "", 50, 0., 2.);
    TH1D* ZCtrlYStarMjjWt    = new TH1D("ZCtrlYStarMjjWt",    "", 50, -1., 5.);    

    tree->Draw("zMass>>ZCtrlZMass"	    , cutPlots);
    tree->Draw("zPt>>ZCtrlZpT"		    , cutPlots);
    tree->Draw("jet1Pt>>ZCtrlJet1pT"	    , cutPlots);
    tree->Draw("jet1Eta>>ZCtrlJet1Eta"	    , cutPlots);
    tree->Draw("jet2Pt>>ZCtrlJet2pT"	    , cutPlots);
    tree->Draw("jet2Eta>>ZCtrlJet2Eta"	    , cutPlots);
    tree->Draw("cenJetEt>>ZCtrlCenJetpT"    , cutPlots);
    tree->Draw("vbfDEta>>ZCtrlDEtajj"	    , cutPlots);
    tree->Draw("vbfM>>ZCtrlMjj"		    , cutPlots);
    tree->Draw("metNo2Muon>>ZCtrlMET"	    , cutPlots);
    tree->Draw("vbfDPhi>>ZCtrlDPhijj"	    , cutPlots);

    if (options.doMCFMWeights) {

    tree->Draw("abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))>>ZCtrlYStar"	  , cutPlots);
    tree->Draw("(0.849667 + (0.149687*abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))))>>ZCtrlYStarWt", cutPlots);
    tree->Draw("(0.392568 + (0.120734*log(genVBFM)) - (0.000255622*genVBFM))>>ZCtrlMjjWt", cutPlots);
    tree->Draw("(0.849667 + (0.149687*abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))))*(0.392568 + (0.120734*log(genVBFM)) - (0.000255622*genVBFM))>>ZCtrlYStarMjjWt", cutPlots);

    }

    if (!dataset.isData) {
      ZCtrlZMass->Scale(weight);
      ZCtrlZpT->Scale(weight);
      ZCtrlJet1pT->Scale(weight);
      ZCtrlJet1Eta->Scale(weight);
      ZCtrlJet2pT->Scale(weight);
      ZCtrlJet2Eta->Scale(weight);
      ZCtrlCenJetpT->Scale(weight);
      ZCtrlDEtajj->Scale(weight);
      ZCtrlMjj->Scale(weight);
      ZCtrlMET->Scale(weight);
      ZCtrlDPhijj->Scale(weight);
      ZCtrlYStar->Scale(weight);
      ZCtrlYStarWt->Scale(weight);
      ZCtrlMjjWt->Scale(weight);
      ZCtrlYStarMjjWt->Scale(weight);
    }

    ofile_Plot->cd();
    ZCtrlZMass->Write("",TObject::kOverwrite);
    ZCtrlZpT->Write("",TObject::kOverwrite);
    ZCtrlJet1pT->Write("",TObject::kOverwrite);
    ZCtrlJet1Eta->Write("",TObject::kOverwrite);
    ZCtrlJet2pT->Write("",TObject::kOverwrite);
    ZCtrlJet2Eta->Write("",TObject::kOverwrite);
    ZCtrlCenJetpT->Write("",TObject::kOverwrite);
    ZCtrlDEtajj->Write("",TObject::kOverwrite);
    ZCtrlMjj->Write("",TObject::kOverwrite);
    ZCtrlMET->Write("",TObject::kOverwrite);
    ZCtrlDPhijj->Write("",TObject::kOverwrite);
    ZCtrlYStar->Write("",TObject::kOverwrite);
    ZCtrlYStarWt->Write("",TObject::kOverwrite);
    ZCtrlMjjWt->Write("",TObject::kOverwrite);
    ZCtrlYStarMjjWt->Write("",TObject::kOverwrite);

    ofile_Plot->Close();

    // clean up
    delete tree;
    file->Close();
   
  }

  // re-weighting : will be 1 if re-weighting is off
  TH1D* hZ_DYNorm = new TH1D("hZ_DYNorm", "", 1, 0, 1); 
  hZ_DYNorm->Add(hZ_DY_NoVBFNoWeight);
  hZ_DYNorm->Divide(hZ_DY_NoVBFWeight);
  
  double dyNorm = hZ_DYNorm->GetBinContent(1);

  // numbers - calculate these from MC in this program later!
  double ratioBF = constants::ratioZToNuNuZToLL;

  // efficiencies (these will all have syst uncertainty only)
  TH1D* hZ_QCD_EffVBFS      = new TH1D("hZ_QCD_EffVBFS",  "", 1, 0., 1.);
  TH1D* hZ_QCD_EffVBFC      = new TH1D("hZ_QCD_EffVBFC",  "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFS      = new TH1D("hZ_EWK_EffVBFS",  "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFC      = new TH1D("hZ_EWK_EffVBFC",  "", 1, 0., 1.);
 
  TH1D* hZ_DY_EffVBFS       = new TH1D("hZ_DY_EffVBFS",  "", 1, 0., 1.);  	// epsilon_s_vbf
  TH1D* hZ_DY_EffVBFC       = new TH1D("hZ_DY_EffVBFC",  "", 1, 0., 1.);        // epsilon_c_vbf
  TH1D* hZ_DY_TotalEff      = new TH1D("hZ_DY_TotalEff", "", 1, 0., 1.); 

  // for stat only calculation
  TH1D* hZ_Eff_S_DPhi       = new TH1D("hZ_Eff_S_DPhi",       "", 3, dphiEdges);
  TH1D* hZ_Est_C_DPhi       = new TH1D("hZ_Est_C_DPhi",       "", 3, dphiEdges);
  TH1D* hZ_Est_S_DPhi       = new TH1D("hZ_Est_S_DPhi",       "", 3, dphiEdges);

  // for syst only calculation
  TH1D* hZ_BG_C_DPhi_Syst   = new TH1D("hZ_BG_C_DPhi_Syst",   "", 3, dphiEdges);
  TH1D* hZ_Data_C_DPhi_Syst = new TH1D("hZ_Data_C_DPhi_Syst", "", 3, dphiEdges);
  TH1D* hZ_Eff_S_DPhi_Syst  = new TH1D("hZ_Eff_S_DPhi_Syst",  "", 3, dphiEdges);
  TH1D* hZ_Est_C_DPhi_Syst  = new TH1D("hZ_Est_C_DPhi_Syst",  "", 3, dphiEdges);
  TH1D* hZ_Est_S_DPhi_Syst  = new TH1D("hZ_Est_S_DPhi_Syst",  "", 3, dphiEdges);

  // calculate efficiencies for QCD and EWK processes
  hZ_QCD_EffVBFS->Add(hZ_QCD_EffVBFS_N);
  hZ_QCD_EffVBFS->Divide(hZ_QCD_EffVBFS_D);
  hZ_EWK_EffVBFS->Add(hZ_EWK_EffVBFS_N);
  hZ_EWK_EffVBFS->Divide(hZ_EWK_EffVBFS_D);

  hZ_QCD_EffVBFC->Add(hZ_QCD_EffVBFC_N);
  hZ_QCD_EffVBFC->Divide(hZ_QCD_EffVBFC_D);
  hZ_EWK_EffVBFC->Add(hZ_EWK_EffVBFC_N);
  hZ_EWK_EffVBFC->Divide(hZ_EWK_EffVBFC_D); 

  // combine QCD Zll and EWK Zll with correct weights
  hZ_DY_EffVBFS->Add(hZ_QCD_EffVBFS,constants::sigma_Zvv_QCD);
  hZ_DY_EffVBFS->Add(hZ_EWK_EffVBFS,constants::sigma_Zvv_EWK);
  hZ_DY_EffVBFC->Add(hZ_QCD_EffVBFC,constants::sigma_Zuu_QCD);
  hZ_DY_EffVBFC->Add(hZ_EWK_EffVBFC,constants::sigma_Zuu_EWK);

  hZ_DY_TotalEff->Add(hZ_DY_EffVBFS);
  hZ_DY_TotalEff->Divide(hZ_DY_EffVBFC);

  for(int ibin = 1; ibin <= hZ_Eff_S_DPhi->GetNbinsX(); ++ibin) {
    hZ_Eff_S_DPhi->SetBinContent(ibin,hZ_DY_TotalEff->GetBinContent(1));
    hZ_Eff_S_DPhi->SetBinError(ibin,0.);
    hZ_Eff_S_DPhi_Syst->SetBinContent(ibin,hZ_DY_TotalEff->GetBinContent(1));
    hZ_Eff_S_DPhi_Syst->SetBinError(ibin,hZ_DY_TotalEff->GetBinError(1));
  }

  // do stat only version
  hZ_BG_C_DPhi_Syst->Add(hZ_BG_C_DPhi, 1.);  // copy MC BG histogram for syst calculation
  for (int i=1; i<=hZ_BG_C_DPhi->GetNbinsX(); ++i) hZ_BG_C_DPhi->SetBinError(i,0.);  // set MC BG errors to zero for stat only
  hZ_Est_C_DPhi->Add(hZ_Data_C_DPhi, hZ_BG_C_DPhi, 1., -1.);
  hZ_Est_S_DPhi->Add(hZ_Est_C_DPhi);
  hZ_Est_S_DPhi->Multiply(hZ_Eff_S_DPhi);

  // do syst only version
  hZ_Data_C_DPhi_Syst->Add(hZ_Data_C_DPhi, 1.);
  for (int i=1; i<=hZ_Data_C_DPhi_Syst->GetNbinsX(); ++i) hZ_Data_C_DPhi_Syst->SetBinError(i,0.);

  hZ_Est_C_DPhi_Syst->Add(hZ_Data_C_DPhi_Syst, hZ_BG_C_DPhi, 1., -1.);
  hZ_Est_S_DPhi_Syst->Add(hZ_Est_C_DPhi_Syst);
  hZ_Est_S_DPhi_Syst->Multiply(hZ_Eff_S_DPhi_Syst);


  std::cout << std::endl;
  std::cout << "##################################### MET > 130 #####################################" << std::endl;
  std::cout << "dphi<1.0" << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_s_vbf : " << hZ_QCD_EffVBFS_N->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFS_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_s_vbf      : " << hZ_QCD_EffVBFS_D->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFS_D->GetBinError(1) << std::endl;
  std::cout << "  eps_s_vbf (QCD) : " << hZ_QCD_EffVBFS->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFS->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_s_vbf : " << hZ_EWK_EffVBFS_N->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFS_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_s_vbf      : " << hZ_EWK_EffVBFS_D->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFS_D->GetBinError(1) << std::endl;
  std::cout << "  eps_s_vbf (EWK) : " << hZ_EWK_EffVBFS->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFS->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_c_vbf : " << hZ_QCD_EffVBFC_N->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFC_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_c_vbf      : " << hZ_QCD_EffVBFC_D->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFC_D->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf (QCD) : " << hZ_QCD_EffVBFC->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFC->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_c_vbf : " << hZ_EWK_EffVBFC_N->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFC_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_c_vbf      : " << hZ_EWK_EffVBFC_D->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFC_D->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf (EWK) : " << hZ_EWK_EffVBFC->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFC->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  eps_s_vbf : " << hZ_DY_EffVBFS->GetBinContent(1) << " +/- " << hZ_DY_EffVBFS->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf : " << hZ_DY_EffVBFC->GetBinContent(1) << " +/- " << hZ_DY_EffVBFC->GetBinError(1) << std::endl;
  std::cout << "  total eff : " << hZ_DY_TotalEff->GetBinContent(1) << " +/- " << hZ_DY_TotalEff->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  DY+jets MC ctrl region : " << hZ_DY_C_DPhi->GetBinContent(1) << " +/- " << hZ_DY_C_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Background ctrl region : " << hZ_BG_C_DPhi->GetBinContent(1) << " +/- " << hZ_BG_C_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Data ctrl region       : " << hZ_Data_C_DPhi->GetBinContent(1) << " +/- " << hZ_Data_C_DPhi->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Z in ctrl region       : " << hZ_Est_C_DPhi->GetBinContent(1) << " +/- " << hZ_Est_C_DPhi->GetBinError(1) << " (stat.) + " << hZ_Est_C_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
  std::cout << "  Z in sgnl region       : " << hZ_Est_S_DPhi->GetBinContent(1) << " +/- " << hZ_Est_S_DPhi->GetBinError(1) << " (stat.) + " << hZ_Est_S_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
  std::cout << std::endl;
  //std::cout << "  N_DY^No VBF (no y* or mjj weight)  : " << hZ_DY_NoVBFNoWeight->GetBinContent(1) << " +/- " << hZ_DY_NoVBFNoWeight->GetBinError(1) << std::endl; 
  //std::cout << "  N_DY^No VBF(with y* and mjj weight): " << hZ_DY_NoVBFWeight->GetBinContent(1) << " +/- " << hZ_DY_NoVBFWeight->GetBinError(1) << std::endl;
  //std::cout << "  norm eff (unweighted DY, no VBF / weighted DY, no VBF): " << dyNorm << std::endl;
  std::cout << std::endl;
  std::cout << "#####################################################################################" << std::endl;
  std::cout << std::endl << std::endl;

  // write the cutflow table
  std::cout << "Writing cut flow TeX file" << std::endl;

  ofstream effFile;
  effFile.open(options.oDir+std::string("/cutflowZMuMu.tex"));

  effFile << "Cut & N(data) & N(DY\\rightarrow\\ell\\ell) & N($t\\bar{t}$) & N(single $t$) & N(diboson) \\\\" << std::endl;

  TH1D* hZ_CutFlow_TTBar = (TH1D*) ofile->Get("hZ_CutFlow_TTBar");

  // cutflow table
  for (unsigned i=0; i<nCutsZMuMu; ++i) {

    effFile << cuts.cutNameZMuMu(i) << " & ";
    effFile << "$" << hZ_CutFlow_Data->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_Data->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_DY->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_DY->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_TTBar->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_TTBar->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_SingleTSum->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_SingleTSum->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_Diboson->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_Diboson->GetBinError(i+1) << "$ & ";
    effFile << std::endl;

  }

  effFile << std::endl << std::endl;
  effFile.close();

  // list histograms for dataset summing
  std::vector<std::string> hists;
  hists.push_back("ZCtrlZMass");
  hists.push_back("ZCtrlZpT");
  hists.push_back("ZCtrlJet1pT");
  hists.push_back("ZCtrlJet1Eta");
  hists.push_back("ZCtrlJet2pT");
  hists.push_back("ZCtrlJet2Eta");
  hists.push_back("ZCtrlCenJetpT");
  hists.push_back("ZCtrlDEtajj");
  hists.push_back("ZCtrlMjj");
  hists.push_back("ZCtrlMET");
  hists.push_back("ZCtrlDPhijj");

  // check whether we have NoTrig histograms or normal
  bool noTrig = false;
  std::string dyJetsName = oDir_Plot+std::string("/DYJetsToLL.root");
  std::string dyJetsPtZName = oDir_Plot+std::string("/DYJetsToLL_PtZ-100.root");
  struct stat buffer; 
  if (stat (dyJetsName.c_str(), &buffer) != 0) {
    noTrig = true;
    dyJetsName = oDir_Plot+std::string("/DYJetsToLL_NoTrig.root");
    dyJetsPtZName = oDir_Plot+std::string("/DYJetsToLL_PtZ-100_NoTrig.root");
  }

  std::cout << "Getting histograms for plots from " << dyJetsName << " and " << dyJetsPtZName << std::endl;

  // re-scale QCD DY histograms
  TFile* qcdDYFile = TFile::Open(dyJetsName.c_str(), "UPDATE");
  for (std::vector<std::string>::const_iterator hname=hists.begin(); hname!=hists.end(); ++hname) {
    TH1D* h = (TH1D*) qcdDYFile->Get(hname->c_str());
    //std::cout << "Integral before : " << h->Integral() << std::endl;
    h->Scale(dyNorm);
    //std::cout << "Integral after : " << h->Integral() << std::endl;
    h->Write("",TObject::kOverwrite);
  }
  qcdDYFile->Close();

  qcdDYFile = TFile::Open(dyJetsPtZName.c_str(), "UPDATE");
  for (std::vector<std::string>::const_iterator hname=hists.begin(); hname!=hists.end(); ++hname) {
    TH1D* h = (TH1D*) qcdDYFile->Get(hname->c_str());
    h->Scale(dyNorm);
    h->Write("",TObject::kOverwrite);
  }
  qcdDYFile->Close();


  // sum DY datasets
  std::vector<std::string> DYDatasets;
  if (noTrig) {
    DYDatasets.push_back(std::string("DYJetsToLL_NoTrig"));
    DYDatasets.push_back(std::string("DYJetsToLL_PtZ-100_NoTrig"));
    DYDatasets.push_back(std::string("DYJetsToLL_EWK_NoTrig"));
  }
  else {
    DYDatasets.push_back(std::string("DYJetsToLL"));
    DYDatasets.push_back(std::string("DYJetsToLL_PtZ-100"));
    DYDatasets.push_back(std::string("DYJetsToLL_EWK"));
  }
  SumDatasets(oDir_Plot, DYDatasets, hists, "DY+jets");

  // sum single top datasets
  std::vector<std::string> topDatasets;
  topDatasets.push_back(std::string("SingleT_t"));
  topDatasets.push_back(std::string("SingleTbar_t"));
  topDatasets.push_back(std::string("SingleT_s"));
  topDatasets.push_back(std::string("SingleTbar_s"));
  topDatasets.push_back(std::string("SingleT_tW"));
  topDatasets.push_back(std::string("SingleTbar_tW"));
  topDatasets.push_back(std::string("TTBar"));
  SumDatasets(oDir_Plot, topDatasets, hists, "SingleT+TTbar"); 

  // sum diboson datasets
  std::vector<std::string> dibDatasets;
  dibDatasets.push_back(std::string("WW"));
  dibDatasets.push_back(std::string("WZ"));
  dibDatasets.push_back(std::string("ZZ"));
  dibDatasets.push_back(std::string("WG"));
  SumDatasets(oDir_Plot, dibDatasets, hists, "DiBoson");

  // sum SM backgrounds
  std::vector<std::string> bgDatasets;
  bgDatasets.push_back(std::string("WW"));
  bgDatasets.push_back(std::string("WZ"));
  bgDatasets.push_back(std::string("ZZ"));
  bgDatasets.push_back(std::string("WG"));
  bgDatasets.push_back(std::string("SingleT_t"));
  bgDatasets.push_back(std::string("SingleTbar_t"));
  bgDatasets.push_back(std::string("SingleT_s"));
  bgDatasets.push_back(std::string("SingleTbar_s"));
  bgDatasets.push_back(std::string("SingleT_tW"));
  bgDatasets.push_back(std::string("SingleTbar_tW"));
  bgDatasets.push_back(std::string("TTBar"));
  SumDatasets(oDir_Plot, bgDatasets, hists, "tt+VV"); 

  // make plots
  std::cout << "Making plots" << std::endl;
  StackPlot plots(oDir_Plot);
  plots.setLegPos(0.70,0.60,0.93,0.89);
  //plots.setLegPos(0.62,0.62,0.89,0.89);

  // Note that here I've used the overloaded method addDataset, which allows you to specify a filename for the input ROOT file
  // *and* also allows you to specify what to put in the TLegend. (By default, it uses the filename as the TLegend entry)
  // This is because the Tlegend entry involves some odd characters, which are best not used in filenames for safety

  //  plots.addDataset("DiBoson", kViolet-6, 0);
  plots.addDataset("tt+VV", "t#bar{t}, tW, VV", kAzure-2, 0);
  plots.addDataset("DY+jets", "DY(ll)+jets", kPink-4, 0);
  plots.addDataset("METABCD", kBlack, 1);
  plots.setScaleMCtoData(true); //rescale MC to data

  plots.draw("ZCtrlZpT",	"Z_p_{T} [GeV]",		"N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet1pT", 	"Leading jet p_{T} [GeV]", 	"N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet1Eta", 	"Leading jet #eta", 		"N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet2pT",     "Sub-leading jet p_{T} [GeV]",  "N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet2Eta",    "Sub-leading jet #eta",         "N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlCenJetpT",	"Central jet p_{T} [GeV]",	"N_{events}"    ,1,"RATIO_Z");
  plots.draw("ZCtrlDEtajj",	"#Delta #eta_{jj}",		"N_{events}"	,1,"RATIO_Z");
  plots.setYMax(5.e2);
  plots.setXMin(1100.);
  plots.setXMax(2600.);
  plots.draw("ZCtrlMjj", 	"M_{jj} [GeV]",			"Events / 100 GeV"	,1,"RATIO_Z");
  plots.setYMax(5.e2);
  plots.setXMin(130.);
  plots.draw("ZCtrlMET", 	"E_{T}^{miss} [GeV]",		"Events / 20 GeV"	,1,"RATIO_Z");
  plots.draw("ZCtrlDPhijj", 	"#Delta #phi_{jj}",		"Events"	,1,"RATIO_Z");
  plots.setYMax(80.);
  plots.setYMin(0.);
  plots.draw("ZCtrlZMass",      "M_{#mu#mu}  [GeV]",      "Events / 5 GeV"    ,0,"RATIO_Z");

  //store histograms
  ofile->cd();
  hZ_DY_C_DPhi->Write("",TObject::kOverwrite);
  hZ_BG_C_DPhi->Write("",TObject::kOverwrite);
  hZ_Data_C_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_C_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_C_DPhi_Syst->Write("",TObject::kOverwrite);
  hZ_Est_S_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_S_DPhi_Syst->Write("",TObject::kOverwrite);

  hZ_Eff_S_DPhi->Write("",TObject::kOverwrite);
  hZ_Eff_S_DPhi_Syst->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFS_D->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFS_N->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFC_D->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFC_N->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFS_D->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFS_N->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFC_D->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFC_N->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFS->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFC->Write("",TObject::kOverwrite);
  hZ_DY_TotalEff->Write("",TObject::kOverwrite);

  hZ_CutFlow_Data->Write("",TObject::kOverwrite);
  hZ_CutFlow_DY->Write("",TObject::kOverwrite);
  hZ_CutFlow_SingleTSum->Write("",TObject::kOverwrite);
  hZ_CutFlow_Diboson->Write("",TObject::kOverwrite);

  ofile->Close();    

}
Exemple #13
0
void plotRBDphi( 
		double dphiCut=3.026,
		// double dphiCut=2.094,
	      double dphiCut2 = 3.026,
		 TString infname = "data.root",
		 TString pythia = "pythia.root",
		 TString mix = "mix.root",
		 bool useWeight = true,
		 bool drawXLabel = false,
		 bool drawLeg = true)
{		
  useWeight = 0;

  int threshold1 = 80;
  int threshold2 = 120;
  gStyle->SetErrorX(0); 
  TString cut1=Form("abs(eta1) < 2 && abs(eta2) < 2 && et1>%d&&et2>50",threshold1);
  TString cut2=Form("abs(eta1) < 2 && abs(eta2) < 2 && et1>%d&&et2>50",threshold2);
  cout <<cut1.Data()<<endl;
  cout <<cut2.Data()<<endl;

  TString trigcut = "";
  TString cstring = "";

  // open the data file
  TFile *inf = new TFile(infname.Data());
  TTree *nt =(TTree*)inf->FindObjectAny("nt");

  // open the pythia (MC) file
  TFile *infPythia = new TFile(pythia.Data());
  TTree *ntPythia = (TTree*) infPythia->FindObjectAny("nt");

  // open the datamix file
  TFile *infMix = new TFile(mix.Data());
  TTree *ntMix =(TTree*)infMix->FindObjectAny("nt");

  // open output
  TFile *outfile = new TFile("output.root","recreate");
  TNtuple *ntOut = new TNtuple("ntOut","","npart");


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

  ntMix->SetAlias("et1","pt1");
  ntMix->SetAlias("et2","pt2");
  ntPythia->SetAlias("et1","pt1");
  ntPythia->SetAlias("et2","pt2");

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

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

  ntPythia->SetAlias("weight","1");
  ntMix->SetAlias("weight","1");

  const int nBin = 6;
  double m[nBin+1] = {-1.5,-0.5,3.5,7.5,11.5,20.5,40.5};
  double npart[nBin] = {2,358.623,232.909,97.9521};
  double npart2[nBin] = {2,358.623,232.909,97.9521};
  
  double npartValue[40];
  npartValue[0] = 393.633;
  npartValue[1] = 368.819;
  npartValue[2] = 343.073;
  npartValue[3] = 317.625;
  npartValue[4] = 292.932;
  npartValue[5] = 271.917;
  npartValue[6] = 249.851;
  npartValue[7] = 230.72;
  npartValue[8] = 212.465;
  npartValue[9] = 194.752;
  npartValue[10] = 178.571;
  npartValue[11] = 163.23;
  npartValue[12] = 149.187;
  npartValue[13] = 136.011;
  npartValue[14] = 123.414;
  npartValue[15] = 111.7;
  npartValue[16] = 100.831;
  npartValue[17] = 90.7831;
  npartValue[18] = 80.9823;
  npartValue[19] = 72.6236;
  npartValue[20] = 64.1508;
  npartValue[21] = 56.6284;
  npartValue[22] = 49.9984;
  npartValue[23] = 43.3034;
  npartValue[24] = 37.8437;
  npartValue[25] = 32.6659;
  npartValue[26] = 27.83;
  npartValue[27] = 23.7892;
  npartValue[28] = 20.1745;
  npartValue[29] = 16.8453;
  npartValue[30] = 14.0322;
  npartValue[31] = 11.602;
  npartValue[32] = 9.52528;
  npartValue[33] = 7.6984;
  npartValue[34] = 6.446;
  npartValue[35] = 4.96683;
  npartValue[36] = 4.23649;
  npartValue[37] = 3.50147;
  npartValue[38] = 3.16107;
  npartValue[39] = 2.7877;

  TH1D *hTmp = new TH1D("hTmp","",100,-10,400);
  TH1D *h = new TH1D("h","",nBin,m);
  TH1D *hCut = new TH1D("hCut","",nBin,m);
  TH1D *h2 = new TH1D("h2","",nBin,m);
  TH1D *h2Cut = new TH1D("h2Cut","",nBin,m);

  TH1D *hStat = new TH1D("hStat","",nBin,m);
  TH1D *hNpartSum = new TH1D("hNpartSum","",nBin,m);
  TH1D *hStat2 = new TH1D("hStat2","",nBin,m);
  TH1D *hNpartSum2 = new TH1D("hNpartSum2","",nBin,m);


  Float_t bin=0;
  Float_t et1=0;
  nt->SetBranchAddress("bin",&bin);
  nt->SetBranchAddress("pt1",&et1);
  
  for (int i=0;i<nt->GetEntries();i++)
  {
     nt->GetEntry(i);
     if (et1<threshold1) continue;
     
     if (et1>threshold2) {
        hNpartSum2->Fill(bin,npartValue[(int)bin]);
        hStat2->Fill(bin); 
        if (et1>threshold1) {
        hNpartSum->Fill(bin,npartValue[(int)bin]);
        hStat->Fill(bin); 
	}
     }	 
  }

  hNpartSum->Divide(hStat);
  hNpartSum2->Divide(hStat2);
  
  for (int i=1;i<nBin;i++)
  {
     cout <<hNpartSum->GetBinContent(i+1)<<endl;
     npart[i]=hNpartSum->GetBinContent(i+1);
     cout <<hNpartSum2->GetBinContent(i+1)<<endl;
     npart2[i]=hNpartSum2->GetBinContent(i+1);
     
  }

  nt->Draw("bin>>h",Form("abs(dphi)>%f&&%s",dphiCut,cut1.Data()));
  nt->Draw("bin>>hCut",Form("%s",cut1.Data()));
  TGraphAsymmErrors *g = calcEff(hCut,h,npart);
  g->SetMarkerSize(1.25);

  cout <<cut2.Data()<<endl;
  nt->Draw("bin>>h2",Form("abs(dphi)>%f&&%s",dphiCut2,cut2.Data()));
  nt->Draw("bin>>h2Cut",Form("%s",cut2.Data()));
  TGraphAsymmErrors *g2 = calcEff(h2Cut,h2,npart2);
  g2->SetMarkerSize(1.25);


  ntPythia->Draw("bin>>h",Form("abs(dphi)>%f&&%s",dphiCut2,cut2.Data()));
  ntPythia->Draw("bin>>hCut",Form("%s",cut2.Data()));
  TGraphAsymmErrors *gPythia = calcEffpythia(hCut,h,npart);
  gPythia->SetMarkerSize(1.7);
  
  if(useWeight){
    ntMix->Draw("bin>>h",Form("weight*(abs(dphi)>%f&&%s)",dphiCut2,cut2.Data()));
    ntMix->Draw("bin>>hCut",Form("weight*(%s)",cut2.Data()));
  }else{
    ntMix->Draw("bin>>h",Form("(abs(dphi)>%f&&%s)",dphiCut2,cut2.Data()));
    ntMix->Draw("bin>>hCut",Form("(%s)",cut2.Data()));
  }
  TGraphAsymmErrors *gMix = calcEff(hCut,h,npart);
  gMix->SetMarkerSize(1.25);

  TCanvas *c = new TCanvas("c","",500,500);
  //  hTmp->SetMaximum(g->GetY()[0]*2.2);
  hTmp->SetMaximum(0.85);
  hTmp->SetMinimum(0.);

  hTmp->SetXTitle("N_{part}");
  hTmp->SetYTitle(Form("R_{B}(#Delta#phi_{12} > %.3f)",dphiCut));
  hTmp->GetXaxis()->CenterTitle();
  hTmp->GetYaxis()->CenterTitle();
  //  hTmp->GetYaxis()->SetTitleOffset(1.2);
  //  hTmp->GetYaxis()->SetTitleSize(0.055);
  hTmp->Draw();

  double errorbar = 0.02;
/*
  for(int i = 0; i < g->GetN(); ++i){
    double *x = g->GetX();
    double *y = g->GetY();
//    DrawTick(y[i],0.18*y[i],0.18*y[i],x[i],0.012,8.1,16);
  }
  g->Draw("p same");
  g2->SetMarkerStyle(4);
  */
  for(int i = 0; i < g2->GetN(); ++i){
    double *x = g2->GetX();
    double *y = g2->GetY();
    double err = 1.5*(0.0001129*x[i]);
    err = sqrt(err * err + 0.012*0.012);
    cout <<err/y[i]<<" "<<1.5*(0.0001129*x[i])/y[i]<<" "<<0.012/y[i]<<endl;
    double tickSize = 0.012;
    if (err<tickSize) tickSize=err;
    DrawTick(y[i],err,err,x[i],tickSize,8.1,dataColor);
  }
  gPythia->SetMarkerColor(4);
  gPythia->SetLineColor(4);
  gPythia->SetMarkerStyle(29);

  gMix->SetMarkerColor(4);
  gMix->SetLineColor(4);
  gMix->SetMarkerStyle(25);
  //  gMix->Draw("p same");
  gPythia->Draw("p same");

  g2->SetLineColor(dataColor);
  g2->SetMarkerColor(dataColor);

  g2->Draw("p same");

  TLine* pline = new TLine(0,gPythia->GetY()[0],400,gPythia->GetY()[0]);
  pline->SetLineColor(4);
  pline->SetLineStyle(4);
  pline->Draw();

  if(drawLeg){
    TLegend *t3=new TLegend(0.5,0.77,0.9,0.93); 
    t3->AddEntry(g2,"PbPb  #sqrt{s}_{_{NN}}=2.76 TeV","p");
    //    t3->AddEntry(gPythia,"PYTHIA","p");  
    //    t3->AddEntry(gMix,"PYTHIA+DATA","p");

    //    t3->AddEntry(g,"2011","p");
    //    t3->AddEntry(gMix,"2010","p");
    t3->AddEntry(gPythia,"pp #sqrt{s}=2.76 TeV","p");

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


  TLatex *cms = new TLatex(0.20,0.88,"CMS Preliminary");
  cms->SetNDC();
  cms->SetTextFont(63);
  cms->SetTextSize(18);
  cms->Draw();                                                                                                                                        
  TLatex tsel;
  tsel.SetNDC();
  tsel.SetTextFont(63);
  tsel.SetTextSize(15);
  tsel.DrawLatex(0.25,0.35,"p_{T,1} > 120 GeV/c");
  tsel.DrawLatex(0.25,0.275,"p_{T,2} > 30 GeV/c");
//  tsel.DrawLatex(0.25,0.20,"#Delta#phi_{12} > #frac{2}{3}#pi rad");

  TLatex *lumi = new TLatex(0.20,0.81,"#intL dt = 6.7 #mub^{-1}");
  lumi->SetNDC();
  lumi->SetTextFont(63);
  lumi->SetTextSize(15);
  lumi->Draw(); 
/*
  TF1 *f = new TF1("f","0.5+[0]*x");
  gMix->Fit("f");
  */
  TCanvas *c2 = new TCanvas("c2","",500,500);

  TGraphAsymmErrors *gRatio = divideGraph(g2,gMix);
  gRatio->Draw("ap");
  gRatio->Fit("pol1");
  //gRatio->Fit("pol0");
  
  c->Print(Form("fig/RB_dphi_%d_vs_Npart.eps",(int)(1000*dphiCut)));
  c->Print(Form("fig/RB_dphi_%d_vs_Npart.C",(int)(1000*dphiCut)));
  c->Print(Form("fig/RB_dphi_%d_vs_Npart.gif",(int)(1000*dphiCut)));
  c->Print(Form("fig/RB_dphi_%d_vs_Npart.pdf",(int)(1000*dphiCut)));


}
Exemple #14
0
void tStudent()
{

   //gSystem->Load("libMathMore");
   // this is the way to force load of MathMore in Cling
   ROOT::Math::MathMoreLibrary::Load();

   int n=100;
   double a=-5.;
   double b=5.;
   //double r  = 3;
   TF1* pdf = new TF1("pdf", "ROOT::Math::tdistribution_pdf(x,3.0)", a,b);
   TF1* cum = new TF1("cum", "ROOT::Math::tdistribution_cdf(x,3.0)", a,b);

   TH1D* quant = new TH1D("quant", "", 9, 0, 0.9);

   for(int i=1; i < 10; i++)
      quant->Fill((i-0.5)/10.0, ROOT::Math::tdistribution_quantile((1.0*i)/10, 3.0 ) );

   double xx[10];
   xx[0] = -1.5;
   for(int i=1; i<9; i++)
      xx[i]= quant->GetBinContent(i);
   xx[9] = 1.5;
   TH1D* pdfq[10];
   //int nbin = n/10.0;
   for(int i=0; i < 9; i++) {
      int nbin = n * (xx[i+1]-xx[i])/3.0 + 1.0;
      TString name = "pdf";
      name += i;
      pdfq[i]= new TH1D(name, "", nbin,xx[i],xx[i+1] );
      for(int j=1; j<nbin; j++) {
         double x= j*(xx[i+1]-xx[i])/nbin + xx[i];
         pdfq[i]->SetBinContent(j, ROOT::Math::tdistribution_pdf(x,3));
      }
   }

   TCanvas *Canvas = new TCanvas("DistCanvas", "Student Distribution graphs", 10, 10, 800, 700);
   pdf->SetTitle("Student t distribution function");
   cum->SetTitle("Cumulative for Student t");
   quant->SetTitle("10-quantiles  for Student t");
   Canvas->Divide(2, 2);
   Canvas->cd(1);
   pdf->SetLineWidth(2);
   pdf->DrawCopy();
   Canvas->cd(2);
   cum->SetLineWidth(2);
   cum->SetLineColor(kRed);
   cum->Draw();
   Canvas->cd(3);
   quant->Draw();
   quant->SetLineWidth(2);
   quant->SetLineColor(kBlue);
   quant->SetStats(0);
   Canvas->cd(4);
   pdfq[0]->SetTitle("Student t & its quantiles");
   pdf->SetTitle("");
   pdf->Draw();
   //pdfq[0]->SetAxisRange(-1.5, 0, 1.5,1.0);
   pdfq[0]->SetTitle("Student t & its quantiles");
   for(int i=0; i < 9; i++) {
      pdfq[i]->SetStats(0);
      pdfq[i]->SetFillColor(i+1);
      pdfq[i]->Draw("same");
   }
   Canvas->Modified();
   Canvas->cd();
}
Exemple #15
0
//_______________________________________________________________________________
void makeZinvFromDY( TFile* fData , TFile* fZinv , TFile* fDY ,TFile* fTop, vector<string> dirs, string output_name ) {

  // Generate histogram file with Zinv prediction based on DYData * R(Zinv/DY)

  TFile * outfile = new TFile(output_name.c_str(),"RECREATE") ; 
  outfile->cd();
  const unsigned int ndirs = dirs.size();

//  // Obtain inclusive templates
//  int lastmt2_VL23J=0, lastmt2_VL2J=0, lastmt2_VL4J=0;
//  int lastmt2_L23J=0,  lastmt2_L26J=0, lastmt2_L46J=0, lastmt2_L7J=0;
//  int lastmt2_M23J=0,  lastmt2_M26J=0, lastmt2_M46J=0, lastmt2_M7J=0;
//  int lastmt2_H23J=0,  lastmt2_H26J=0, lastmt2_H46J=0, lastmt2_H7J=0;
//  int lastmt2_UH=0;
//  TH1D* h_TemplateVL23J      = (TH1D*) fData->Get("crdybaseVL/h_mt2bins23J"); 
//  int lastbin_VL23J = purityRandNorm(h_TemplateVL23J, "crdybaseVL/h_mt2bins23J", fData, fZinv, fDY, lastmt2_VL23J);
//  TH1D* h_TemplateVL2J       = (TH1D*) fData->Get("crdybaseVL/h_mt2bins"); 
//  int lastbin_VL2J  = purityRandNorm(h_TemplateVL2J, "crdybaseVL/h_mt2bins", fData, fZinv, fDY, lastmt2_VL2J);
//  TH1D* h_TemplateVL4J       = (TH1D*) fData->Get("crdybaseVL/h_mt2bins4J");  
//  int lastbin_VL4J  = purityRandNorm(h_TemplateVL4J, "crdybaseVL/h_mt2bins4J", fData, fZinv, fDY, lastmt2_VL4J);  
//  TH1D* h_TemplateL23J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins23J");
//  int lastbin_L23J  = purityRandNorm(h_TemplateL23J, "crdybaseL/h_mt2bins23J", fData, fZinv, fDY, lastmt2_L23J);    
//  TH1D* h_TemplateL26J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins26J");
//  int lastbin_L26J  = purityRandNorm(h_TemplateL26J, "crdybaseL/h_mt2bins26J", fData, fZinv, fDY, lastmt2_L26J);    
//  TH1D* h_TemplateL46J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins46J");   
//  int lastbin_L46J  = purityRandNorm(h_TemplateL46J, "crdybaseL/h_mt2bins46J", fData, fZinv, fDY, lastmt2_L46J); 
//  TH1D* h_TemplateL7J        = (TH1D*) fData->Get("crdybaseL/h_mt2bins7J");    
//  int lastbin_L7J   = purityRandNorm(h_TemplateL7J, "crdybaseL/h_mt2bins7J", fData, fZinv, fDY, lastmt2_L7J);
//  TH1D* h_TemplateM23J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins23J");    
//  int lastbin_M23J  = purityRandNorm(h_TemplateM23J, "crdybaseM/h_mt2bins23J", fData, fZinv, fDY, lastmt2_M23J);
//  TH1D* h_TemplateM26J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins26J");    
//  int lastbin_M26J  = purityRandNorm(h_TemplateM26J, "crdybaseM/h_mt2bins26J", fData, fZinv, fDY, lastmt2_M26J);
//  TH1D* h_TemplateM46J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins46J");    
//  int lastbin_M46J  = purityRandNorm(h_TemplateM46J, "crdybaseM/h_mt2bins46J", fData, fZinv, fDY, lastmt2_M46J);
//  TH1D* h_TemplateM7J        = (TH1D*) fData->Get("crdybaseM/h_mt2bins7J");    
//  int lastbin_M7J   = purityRandNorm(h_TemplateM7J, "crdybaseM/h_mt2bins7J", fData, fZinv, fDY, lastmt2_M7J);
//  TH1D* h_TemplateH23J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins23J");    
//  int lastbin_H23J  = purityRandNorm(h_TemplateH23J, "crdybaseH/h_mt2bins23J", fData, fZinv, fDY, lastmt2_H23J);
//  TH1D* h_TemplateH26J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins26J");    
//  int lastbin_H26J  = purityRandNorm(h_TemplateH26J, "crdybaseH/h_mt2bins26J", fData, fZinv, fDY, lastmt2_H26J);
//  TH1D* h_TemplateH46J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins46J");    
//  int lastbin_H46J  = purityRandNorm(h_TemplateH46J, "crdybaseH/h_mt2bins46J", fData, fZinv, fDY, lastmt2_H46J);
//  TH1D* h_TemplateH7J        = (TH1D*) fData->Get("crdybaseH/h_mt2bins7J");    
//  int lastbin_H7J   = purityRandNorm(h_TemplateH7J, "crdybaseH/h_mt2bins7J", fData, fZinv, fDY, lastmt2_H7J);
//  TH1D* h_TemplateUH        = (TH1D*) fData->Get("crdybaseUH/h_mt2bins");    
//  int lastbin_UH    = purityRandNorm(h_TemplateUH, "crdybaseUH/h_mt2bins", fData, fZinv, fDY, lastmt2_UH);


  for ( unsigned int idir = 0; idir < ndirs; ++idir ) {
    
    TString srname = dirs.at(idir);
    TString directory = "sr"+dirs.at(idir);
    TString directoryDY = "crdy"+dirs.at(idir);

    TString fullhistname = directory + "/h_mt2bins";
    TString fullhistnameDY = directoryDY + "/h_mt2bins";
    TString fullhistnameEM = directoryDY + "/h_mt2binsemu";

    TH1D* hData = (TH1D*) fData->Get(fullhistnameDY);    
    TH1D* hDY   = (TH1D*) fDY->Get(fullhistnameDY);
    TH1D* hDataEM   = (TH1D*) fData->Get(fullhistnameEM);    
    TH1D* hZinv = (TH1D*) fZinv->Get(fullhistname);    
    TH1D* hTop  = (TH1D*) fTop->Get(fullhistnameDY);    

    TH1D* hDY_lepeff_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_lepeff_UP");
    TH1D* hDY_lepeff_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_lepeff_DN");
    TH1D* hDY_trigeff_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_trigeff_UP");
    TH1D* hDY_trigeff_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_trigeff_DN");
    TH1D* hDY_ZNJet_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_ZNJet_UP");
    TH1D* hDY_ZNJet_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_ZNJet_DN");
    TH1D* hZinv_ZNJet_UP   = (TH1D*) fZinv->Get(fullhistname+"_ZNJet_UP");
    TH1D* hZinv_ZNJet_DN   = (TH1D*) fZinv->Get(fullhistname+"_ZNJet_DN");
    TH1D* hDY_renorm_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_renorm_UP");
    TH1D* hDY_renorm_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_renorm_DN");
    TH1D* hZinv_renorm_UP   = (TH1D*) fZinv->Get(fullhistname+"_renorm_UP");
    TH1D* hZinv_renorm_DN   = (TH1D*) fZinv->Get(fullhistname+"_renorm_DN");
    
    // If Zinv or DY histograms are not filled, just leave (shouldn't happen when running on full stat MC)
    if(!hDY || !hZinv || !hData){
      cout<<"could not find histogram "<<fullhistname<<endl;
      continue;
    }
    
    if (hDY->GetNbinsX() != hZinv->GetNbinsX() ) {
      cout<<"different binning for histograms "<<fullhistname<<endl;
      continue;
    }
    
    // Make directory and plot(s) in the output file
    TDirectory* dir = 0;
    dir = (TDirectory*)outfile->Get(directory.Data());
    if (dir == 0) {
      dir = outfile->mkdir(directory.Data());
    } 
    dir->cd();

    cout<<"Looking at histo "<<fullhistname<<endl;

    int lastbin_hybrid = 1;
    int lastmt2val_hybrid = 200;
    int ht_LOW = 0, ht_HI = 0, njets_LOW = 0, njets_HI = 0, nbjets_LOW = 0, nbjets_HI = 0;
    TH1D* h_MT2Template = (TH1D*) hZinv->Clone("h_MT2Template");  
    TString inclusiveTemplateName = "";

    TH1D *h_ht_LOW, *h_ht_HI, *h_njets_LOW, *h_njets_HI, *h_nbjets_LOW, *h_nbjets_HI;
    if (doHybridInclusiveTemplate) {
      //  Inclusive template: use inclusive template corresponding to this region
      
      //Get variable boundaries for signal region.
      h_ht_LOW = (TH1D*) fData->Get(directory+"/h_ht_LOW");
      h_ht_HI  = (TH1D*) fData->Get(directory+"/h_ht_HI");
      if (h_ht_LOW) ht_LOW = h_ht_LOW->GetBinContent(1);
      if (h_ht_HI)  ht_HI = h_ht_HI->GetBinContent(1);
      h_njets_LOW = (TH1D*) fData->Get(directory+"/h_njets_LOW");
      h_njets_HI  = (TH1D*) fData->Get(directory+"/h_njets_HI");
      if (h_njets_LOW) njets_LOW = h_njets_LOW->GetBinContent(1);
      if (h_njets_HI)  njets_HI = h_njets_HI->GetBinContent(1);
      h_nbjets_LOW = (TH1D*) fData->Get(directory+"/h_nbjets_LOW");
      h_nbjets_HI  = (TH1D*) fData->Get(directory+"/h_nbjets_HI");
      if (h_nbjets_LOW) nbjets_LOW = h_nbjets_LOW->GetBinContent(1);
      if (h_nbjets_HI)  nbjets_HI = h_nbjets_HI->GetBinContent(1);
      
      //Determine which inclusive template to use. If none works, this reverts to HybridSimple, taking template from its own TopoRegion 
      // Start from the Aggregate Regions (hardcoded, since they can partially overlap with the standard regions)
      if (srname == "20") inclusiveTemplateName = "crdy20/h_mt2bins";  // self (2j, HT1200)
      else if (srname == "base") inclusiveTemplateName = "crdybase/h_mt2bins";
      else if (srname == "baseVL") inclusiveTemplateName = "crdybaseVL/h_mt2bins";
      else if (srname == "baseL") inclusiveTemplateName = "crdybaseL/h_mt2bins";
      else if (srname == "baseM") inclusiveTemplateName = "crdybaseM/h_mt2bins";
      else if (srname == "baseH") inclusiveTemplateName = "crdybaseH/h_mt2bins";
      else if (srname == "baseUH") inclusiveTemplateName = "crdybaseUH/h_mt2bins";
      else if (srname == "21") inclusiveTemplateName = "crdy21/h_mt2bins"; // self (2j, HT1500)
      else if (srname == "22") inclusiveTemplateName = "crdy22/h_mt2bins"; // self (4j, HT1200)
      else if (srname == "23") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21 
      else if (srname == "24") inclusiveTemplateName = "crdy24/h_mt2bins"; // self (7J, HT1200)
      else if (srname == "25") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "26") inclusiveTemplateName = "crdy20/h_mt2bins"; // from 20
      else if (srname == "27") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "28") inclusiveTemplateName = "crdy20/h_mt2bins3J"; // need a 3J histogram within SR20
      //      else if (srname == "28") inclusiveTemplateName = "crdy20/h_mt2bins"; // test
      else if (srname == "29") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "30") inclusiveTemplateName = "crdy24/h_mt2bins"; // from 24
      else if (srname == "31") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      // Now the standard regions
      else if (ht_LOW == 250) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseVL/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7) inclusiveTemplateName = "crdybaseVL/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseVL/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseVL/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseVL/h_mt2bins7J"; 
      }
      else if (ht_LOW == 450) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseL/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7)  inclusiveTemplateName = "crdybaseL/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseL/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseL/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseL/h_mt2bins7J"; 
      }
      else if (ht_LOW == 575) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseM/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7) inclusiveTemplateName = "crdybaseM/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseM/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseM/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseM/h_mt2bins79J"; 
	else if (njets_LOW == 10)  inclusiveTemplateName = "crdybaseM/h_mt2bins10J"; 
      }
      else if (ht_LOW == 1200) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseH/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7)  inclusiveTemplateName = "crdybaseH/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseH/h_mt2bins23J";
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseH/h_mt2bins46J";
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseH/h_mt2bins79J";
	else if (njets_LOW == 10)  inclusiveTemplateName = "crdybaseH/h_mt2bins10J";
      }
      else if (ht_LOW == 1500) inclusiveTemplateName = "crdybaseUH/h_mt2bins";

      if (inclusiveTemplateName == "") {
	cout<< "Can't find template for region: HT "<<ht_LOW<<"-"<<ht_HI<<" and NJ "<<njets_LOW<<"-"<<njets_HI<<endl;
	lastbin_hybrid = 1;
	h_MT2Template = 0;
	cout<<"h_MT2Template is 0, using hybrid within this region (no external templates)"<<endl;
      }
      else {
	cout<< "Using inclusive template "<<inclusiveTemplateName<<" for region: HT "<<ht_LOW<<"-"<<ht_HI<<" and NJ "<<njets_LOW<<"-"<<njets_HI<<endl; 
	// Get the template
	lastbin_hybrid = makeHybridTemplate(srname, h_MT2Template, inclusiveTemplateName , fData, fZinv, fDY, lastmt2val_hybrid);
	cout<<"lastbin_hybrid "<<lastbin_hybrid<<" and lastmt2val_hybrid "<<lastmt2val_hybrid<<endl;
	if (h_MT2Template!=0) h_MT2Template->Print();
	else cout<<"h_MT2Template is 0, using hybrid within this region (no external templates)"<<endl;
      }

   


    }

  


    // If there is no template for this region, go back to the standard hybrid
    if (doHybridSimple || (doHybridInclusiveTemplate && h_MT2Template == 0)) {
      // hybrid method: use nominal MC CR yield histogram to determine how many MT2 bins to use
      //  by default: use all MT2 bins integrated (no bin-by-bin).
      //  choose the last bin to try to have at least hybrid_nevent_threshold integrated events

      // Calculate last bin on local histogram
      for ( int ibin=1; ibin <= hDY->GetNbinsX(); ++ibin ) {
	float top = 0, integratedYield = 0;
	//if (hDataEM) top = hDataEM->Integral(ibin,-1)*rSFOF;
	integratedYield = hDY->Integral(ibin,-1) - top;
	if (integratedYield < hybrid_nevent_threshold) {
	  if (ibin == 1) lastbin_hybrid = 1;
	  else {
	    lastbin_hybrid = ibin-1;
	    lastmt2val_hybrid = hDY->GetBinLowEdge(ibin);
	  }
	  break;
	}
      }
      cout<<"lastbin_hybrid for doHybridSimple: "<<lastbin_hybrid<<endl;
    }
    
    

    TH1D* ratio = (TH1D*) hZinv->Clone("ratio");
    ratio->Divide(hDY);
    double errNum, errDen;
    float ratioValue = hZinv->IntegralAndError(1,-1,errNum) / hDY->IntegralAndError(1,-1,errDen);
    float ratioErr = ratioValue*sqrt(pow(errNum/hZinv->Integral(), 2) + pow(errDen/hDY->Integral(),2));

    TH1D* CRyield = (TH1D*) hData->Clone("h_mt2binsCRyield");

    TH1D* purityMC = (TH1D*) hDY->Clone("h_mt2binsPurityMC");
    if (hTop) purityMC->Add(hTop, -1);
    purityMC->Divide(hDY);

    TH1D* purityData = (TH1D*) hData->Clone("h_mt2binsPurityData");
    if (hDataEM) purityData->Add(hDataEM, -1*rSFOF); 
    purityData->Divide(purityData, hData, 1, 1, "B");
    
    TH1D* Stat = (TH1D*) CRyield->Clone("h_mt2binsStat");
    Stat->Multiply(purityData);
    Stat->Multiply(ratio);

    TH1D* Syst = (TH1D*) Stat->Clone("h_mt2binsSyst");
    TH1D* pred = (TH1D*) Stat->Clone("h_mt2bins");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      Syst->SetBinError(ibin, (1-purityData->GetBinContent(ibin))*0.2*Stat->GetBinContent(ibin));
      double quadrature = Stat->GetBinError(ibin)*Stat->GetBinError(ibin) + Syst->GetBinError(ibin)*Syst->GetBinError(ibin);
      pred->SetBinError(ibin, sqrt(quadrature));
    }
    //pred->Print("all");

    // Inputs to cardMaker
    TH1D* ratioCard  = (TH1D*) ratio->Clone("ratioCard");
    TH1D* purityCard  = (TH1D*) purityData->Clone("purityCard");   
    TH1D* CRyieldCard  = (TH1D*) CRyield->Clone("CRyieldCard");

    TH1D *CRyieldEM = 0, *CRyieldEMCard = 0;
    if (hDataEM){
        CRyieldEM = (TH1D*) hDataEM->Clone("h_mt2binsCRyieldEM");
        CRyieldEMCard = (TH1D*) CRyieldEM->Clone("CRyieldEMCard");
    }

    if (  doHybridSimple || (doHybridInclusiveTemplate && h_MT2Template==0) ) { 
      // purity needs to describe the integrated purity of the CR
      // ratio needs to be modified so that the last N bins include kMT2
      // CRyield needs to be modified so that the last N bins have the same yield (which is the integral over those N bins)
      if (verbose) cout<<" Implementing simple hybrid "<<endl;

      for ( int ibin=1; ibin <= hZinv->GetNbinsX(); ++ibin ) {

	if (ibin < lastbin_hybrid) continue;
	
	double integratedYieldErr = 0;
	float integratedYield = CRyield->IntegralAndError(lastbin_hybrid,-1,integratedYieldErr);
	CRyieldCard->SetBinContent(ibin, integratedYield);
	CRyieldCard->SetBinError(ibin, integratedYieldErr);
	
	float integratedDen = integratedYield;
	double EM = 0, errEM = 0;
	if (hDataEM) EM =  hDataEM->IntegralAndError(lastbin_hybrid, -1, errEM) * rSFOF;
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, EM);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, errEM);
        float integratedNum = integratedDen - EM;
	if (integratedNum < 0) integratedNum = 0;
	float integratedPurity = integratedNum/integratedDen;
	float integratedPurityErr = sqrt(integratedPurity*(1-integratedPurity)/integratedDen);// sqrt(e(1-e)/N)   
	purityCard->SetBinContent(ibin, integratedPurity);
	purityCard->SetBinError(ibin, integratedPurityErr);

	float integratedZinv = 1;
	float kMT2 = 0;
	integratedZinv = hZinv->Integral(lastbin_hybrid, -1);
	kMT2 = hZinv->GetBinContent(ibin) / integratedZinv;
	ratioCard->SetBinContent(ibin, ratioCard->GetBinContent(ibin) * kMT2);
	ratioCard->SetBinError(ibin, ratioCard->GetBinError(ibin) * kMT2 ); // just rescale the error by the same amount

      }
    } 
    else if (doHybridInclusiveTemplate && h_MT2Template!=0) {
      // For Inclusive template: 
      // CRyield: this is flat, just the integral
      // purity: also flat
      // ratio: this contains the normalized template scaled by the Zinv/DY ratio for this control region
      // Template should be rebinned to match this region. lastbin_hybrid will have to be updated to refer to the new binning
      
      if (verbose) cout<<" Implementing hybrid with template "<<endl;

//      // MT2template needs to be rebinned for this topological region Rebin
//      double *TopoRegionBins = hZinv->GetXaxis()->GetXbins()->fArray;
//      int nTopoRegionBins    = hZinv->GetXaxis()->GetNbins();
//      h_MT2Template->Print("all");
//      TH1D* h_MT2TemplateRebin = (TH1D*) h_MT2Template->Rebin(nTopoRegionBins, "h_MT2TemplateRebin", TopoRegionBins);
//      int newlastbin = h_MT2TemplateRebin->FindBin(lastmt2val_hybrid-1);
//      if (newlastbin == 0) newlastbin = 1; // 1 is the lowest
//      if (verbose) cout<<"Rebinning moved lastbin_hybrid from "<<lastbin_hybrid<<" to "<<newlastbin<<". lastmt2val_hybrid="<<lastmt2val_hybrid<<endl;
//      lastbin_hybrid = newlastbin;
//      if (verbose) h_MT2TemplateRebin->Print("all");
      if (verbose) cout<<"Ratio for this control region is "<<ratioValue<<endl;

      double integratedYieldErr = 0;
      float integratedYield = CRyield->IntegralAndError(0,-1,integratedYieldErr);
      
      float integratedDen = integratedYield;
      double EM = 0, errEM=0;
      if (hDataEM) EM =  hDataEM->IntegralAndError(0, -1, errEM)*rSFOF;
      float integratedNum = integratedDen - EM;
      if (integratedNum < 0) integratedNum = 0;
      float integratedPurity = integratedNum/integratedDen;      
      // float integratedPurityErr = sqrt(integratedPurity*(1-integratedPurity)/integratedDen);// sqrt(e(1-e)/N)
      // this isn't a proportion (OF/SF are statistically independent regions). Makes no sense to do this
      // what we want is the error on (SF - R*OF). Three sources: dSF, OF*dR, and R*dOF
      // first comes from gmN error in the cards on the main CR yield
      // second comes from special RSFOF handling in cardmaker
      // third should be: R*dOF/(SF-R*dOF). Use proper poissonian error on OF yield
      errEM = ROOT::Math::gamma_quantile_c((1-0.6828)/2, int(EM)+1, 1) - EM;
      float integratedPurityErr = rSFOF*errEM / integratedNum * integratedPurity;

      if(integratedDen==0.0){
          // if CR is 0, assume purity of 1.0 and give it a big error (this basically assumes that SF=1 and OF=0)
          integratedPurity = 1.0;
          errEM = ROOT::Math::gamma_quantile_c((1-0.6828)/2, int(0)+1, 1) - 0;
          integratedPurityErr = rSFOF*errEM;
      }
      
      if (verbose) cout<<"Found SF="<<integratedYield<<" and OF="<<EM<<", so purity is "<<integratedPurity<<endl;

      for ( int ibin=1; ibin <= hZinv->GetNbinsX()+1; ++ibin ) {
	CRyieldCard->SetBinContent(ibin, integratedYield);
	CRyieldCard->SetBinError(ibin,   integratedYieldErr);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, EM);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, errEM);
	ratioCard->SetBinContent(ibin, ratioValue * h_MT2Template->GetBinContent(ibin));
        float err = 0.0;
        if(ratioValue>0.0 && h_MT2Template->GetBinContent(ibin)>0.0)
            err = ratioValue * h_MT2Template->GetBinContent(ibin) * sqrt(pow(ratioErr/ratioValue,2) + pow(h_MT2Template->GetBinError(ibin)/h_MT2Template->GetBinContent(ibin),2));
	ratioCard->SetBinError(ibin,   err);
	purityCard->SetBinContent(ibin, integratedPurity);
	purityCard->SetBinError(ibin,   integratedPurityErr);
      }

    }

    TH1D* ratioCard_lepeff_UP = (TH1D*)ratioCard->Clone("ratioCard_lepeff_UP");
    TH1D* ratioCard_lepeff_DN = (TH1D*)ratioCard->Clone("ratioCard_lepeff_DN");
    if(hDY_lepeff_UP) ratioCard_lepeff_UP->Scale(hDY->Integral() / hDY_lepeff_UP->Integral());
    if(hDY_lepeff_DN) ratioCard_lepeff_DN->Scale(hDY->Integral() / hDY_lepeff_DN->Integral());

    TH1D* ratioCard_trigeff_UP = (TH1D*)ratioCard->Clone("ratioCard_trigeff_UP");
    TH1D* ratioCard_trigeff_DN = (TH1D*)ratioCard->Clone("ratioCard_trigeff_DN");
    if(hDY_trigeff_UP) ratioCard_trigeff_UP->Scale(hDY->Integral() / hDY_trigeff_UP->Integral());
    if(hDY_trigeff_DN) ratioCard_trigeff_DN->Scale(hDY->Integral() / hDY_trigeff_DN->Integral());

    TH1D* ratioCard_ZNJet_UP = (TH1D*)ratioCard->Clone("ratioCard_ZNJet_UP");
    TH1D* ratioCard_ZNJet_DN = (TH1D*)ratioCard->Clone("ratioCard_ZNJet_DN");
    if(hDY_ZNJet_UP && hZinv_ZNJet_UP) ratioCard_ZNJet_UP->Scale(hDY->Integral() / hDY_ZNJet_UP->Integral() * hZinv_ZNJet_UP->Integral() / hZinv->Integral());
    if(hDY_ZNJet_DN && hZinv_ZNJet_DN) ratioCard_ZNJet_DN->Scale(hDY->Integral() / hDY_ZNJet_DN->Integral() * hZinv_ZNJet_DN->Integral() / hZinv->Integral());

    TH1D* ratioCard_renorm_UP = (TH1D*)ratioCard->Clone("ratioCard_renorm_UP");
    TH1D* ratioCard_renorm_DN = (TH1D*)ratioCard->Clone("ratioCard_renorm_DN");
    if(hDY_renorm_UP && hZinv_renorm_UP) ratioCard_renorm_UP->Scale(hDY->Integral() / hDY_renorm_UP->Integral() * hZinv_renorm_UP->Integral() / hZinv->Integral());
    if(hDY_renorm_DN && hZinv_renorm_DN) ratioCard_renorm_DN->Scale(hDY->Integral() / hDY_renorm_DN->Integral() * hZinv_renorm_DN->Integral() / hZinv->Integral());


    TH1D* hybridEstimate  = (TH1D*) CRyieldCard->Clone("hybridEstimate");
    hybridEstimate->Multiply(purityCard);
    hybridEstimate->Multiply(ratioCard);
    
    
    TH1D* h_lastbinHybrid = new TH1D("h_lastbinHybrid",";last bin",1,0,1);
    h_lastbinHybrid->SetBinContent(1,lastbin_hybrid);
    TH1D* h_lastmt2Hybrid = new TH1D("h_lastmt2Hybrid",";last M_{T2} value",1,0,1);
    h_lastmt2Hybrid->SetBinContent(1,lastmt2val_hybrid);

    pred->Write();
    Stat->Write();
    Syst->Write();
    purityMC->Write();
    purityData->Write();
    ratio->Write();
    CRyield->Write();

    ratioCard->Write();
    ratioCard_lepeff_UP->Write();
    ratioCard_lepeff_DN->Write();
    ratioCard_trigeff_UP->Write();
    ratioCard_trigeff_DN->Write();
    ratioCard_ZNJet_UP->Write();
    ratioCard_ZNJet_DN->Write();
    ratioCard_renorm_UP->Write();
    ratioCard_renorm_DN->Write();
    purityCard->Write();
    CRyieldCard->Write();
    h_lastbinHybrid->Write();
    hybridEstimate->Write();
    h_lastmt2Hybrid->Write();
    if (hDataEM) CRyieldEM->Write();
    if (hDataEM) CRyieldEMCard->Write();

    hDY->Write("h_mt2binsMCCR");
    hZinv->Write("h_mt2binsMCSR");

    if(!directoryDY.Contains("J")){
        // we want these for crdy (not saved for monojet, but they're the same as SR anyway)
        h_ht_LOW = (TH1D*) fData->Get(directoryDY+"/h_ht_LOW");
        h_ht_HI  = (TH1D*) fData->Get(directoryDY+"/h_ht_HI");
        h_njets_LOW = (TH1D*) fData->Get(directoryDY+"/h_njets_LOW");
        h_njets_HI  = (TH1D*) fData->Get(directoryDY+"/h_njets_HI");
        h_nbjets_LOW = (TH1D*) fData->Get(directoryDY+"/h_nbjets_LOW");
        h_nbjets_HI  = (TH1D*) fData->Get(directoryDY+"/h_nbjets_HI");
    }

    if(h_ht_LOW) h_ht_LOW->Write();
    if(h_ht_HI)  h_ht_HI->Write();
    if(h_njets_LOW) h_njets_LOW->Write();
    if(h_njets_HI)  h_njets_HI->Write();
    if(h_nbjets_LOW) h_nbjets_LOW->Write();
    if(h_nbjets_HI)  h_nbjets_HI->Write();


  } // loop over signal regions


  return;
}
Exemple #16
0
//_______________________________________________________________________________
void makeZinvFromGJets( TFile* fZinv , TFile* fGJet , TFile* fZll , vector<string> dirs, string output_name, float kFactorGJetForRatio = 1.0 ) {

  // Generate histogram file with Zinv prediction based on GJetsData * R(Zinv/GJ)


  TFile * outfile = new TFile(output_name.c_str(),"RECREATE") ; 
  outfile->cd();
  const unsigned int ndirs = dirs.size();

  // Do the inclusive ones
  vector<TString> inclPlots;
  inclPlots.push_back("h_njbins");
  inclPlots.push_back("h_nbjbins");
  inclPlots.push_back("h_htbins");
  inclPlots.push_back("h_htbins2");
  inclPlots.push_back("h_mt2bins");
  inclPlots.push_back("h_bosonptbins");

  for ( unsigned int incl = 0; incl < inclPlots.size(); ++incl ) {

    TH1D* hGJetIncl = (TH1D*) fGJet->Get("crgjbaseIncl/"+inclPlots[incl])->Clone();
    TH1D* hZllIncl  = (TH1D*)  fZll->Get("crdybaseIncl/"+inclPlots[incl])->Clone();

    if(!hGJetIncl || !hZllIncl){
      cout<<"could not find histogram "<<inclPlots[incl]<<endl;
      continue;
    }
    if (hGJetIncl->GetNbinsX() != hZllIncl->GetNbinsX() ) {
      cout<<"different binning for histograms "<<inclPlots[incl]<<endl;
      continue;
    }
    outfile->cd();

    hGJetIncl->Scale(kFactorGJetForRatio); // The goal is LO(Z) / LO(gamma)

    // Since we're working on MC, let's set poissionian errors by hand
    hZllIncl->Sumw2(0); hZllIncl->Sumw2(1);
    hGJetIncl->Sumw2(0); hGJetIncl->Sumw2(1);
    TH1D* ratioIncl = (TH1D*) hZllIncl->Clone(inclPlots[incl]+"Ratio");
    ratioIncl->Divide(hGJetIncl);

    ratioIncl->Write();

  } // end of inclusive plots

  for ( unsigned int idir = 0; idir < ndirs; ++idir ) {

    TString directory = "sr"+dirs.at(idir);
    TString directoryGJ = "crgj"+dirs.at(idir);

    cout<<"Looking at directory "<<directory<<endl;

    TString fullhistname = directory + "/h_mt2bins";
    TString fullhistnameHT = directory + "/h_htbins";
    TString fullhistnameHT2 = directory + "/h_htbins2";
    TString fullhistnameNJ = directory + "/h_njbins";
    TString fullhistnameNB = directory + "/h_nbjbins";
    //    TString fullhistnamePT = directory + "/h_bosonptbins";
    TString fullhistnameGJ = directoryGJ + "/h_mt2bins";
      
    TH1D* hGJet = (TH1D*) fGJet->Get(fullhistnameGJ);    
    TH1D* hZinv = (TH1D*) fZinv->Get(fullhistname);
    TH1D* hZinvHT = (TH1D*) fZinv->Get(fullhistnameHT);
    TH1D* hZinvHT2 = (TH1D*) fZinv->Get(fullhistnameHT2);
    TH1D* hZinvNJ = (TH1D*) fZinv->Get(fullhistnameNJ);
    TH1D* hZinvNB = (TH1D*) fZinv->Get(fullhistnameNB);
    //    TH1D* hZinvPT = (TH1D*) fZinv->Get(fullhistnamePT);
    
    // If Zinv or GJet histograms are not filled, just leave (shouldn't happen when running on full stat MC)
    if(!hGJet ){
      cout<<"could not find histogram "<<fullhistnameGJ<<endl;
      continue;
    }
    if(!hZinv){
      cout<<"could not find histogram "<<fullhistname<<endl;
      continue;
    }
//    if(!hZinvPT){
//      cout<<"could not find histogram "<<fullhistnamePT<<" in file "<<fZinv->GetName()<<endl;
//      continue;
//    }
    cout<<"Looking at histo "<<fullhistname<<endl;      
    if (hGJet->GetNbinsX() != hZinv->GetNbinsX() ) {
      cout<<"different binning for histograms "<<fullhistname<<endl;
      continue;
    }
    //hGJet->Print("all");
    hGJet->Scale(kFactorGJetForRatio); // The goal is LO(Z) / LO(gamma)

    // Make directory and plot(s) in the output file
    TDirectory* dir = 0;
    dir = (TDirectory*)outfile->Get(directory.Data());
    if (dir == 0) {
      dir = outfile->mkdir(directory.Data());
    } 
    dir->cd();
    
    TH1D* Stat = (TH1D*) hZinv->Clone("h_mt2binsStat");
    
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { // "<=" to deal with overflow bin
      if (hGJet->GetBinContent(ibin) > 0)
	Stat->SetBinError(ibin, hZinv->GetBinContent(ibin)/sqrt( hGJet->GetBinContent(ibin) ));
      else Stat->SetBinError(ibin, hZinv->GetBinContent(ibin));
    }
    

    // Zgamma ratio in each MT2bin -> to get MC stat error on ratio
    TH1D* ratio = (TH1D*) hZinv->Clone("h_mt2binsRatio");
    //ratio->Print("all");
    //hGJet->Print("all");
    ratio->Divide(hGJet);
    //ratio->Print("all");

    TH1D* ratioInt = (TH1D*) hZinv->Clone("h_mt2binsRatioInt");
    double nGammaErr = 0;
    double nGamma = hGJet->IntegralAndError(0, -1, nGammaErr);
    for ( int ibin = 0; ibin <= ratioInt->GetNbinsX(); ++ibin) {
      if (nGamma>0) {
        ratioInt->SetBinContent(ibin, ratioInt->GetBinContent(ibin)/nGamma);
        float errOld = ratioInt->GetBinError(ibin)/nGamma;
        float errNew = (nGammaErr/nGamma) * ratioInt->GetBinContent(ibin);
        //cout<<nGamma<<" "<<nGammaErr<<" "<<errOld<<" "<<errNew<<endl;
        ratioInt->SetBinError(ibin, sqrt( errOld*errOld + errNew*errNew ) );
      }
      else {
        ratioInt->SetBinContent(ibin, 0);
        ratioInt->SetBinError(ibin, 0);
      }
    }
    //ratioInt->Print("all");

    // MCStat: use relative bin error from ratio hist, normalized to Zinv MC prediction
    TH1D* MCStat = (TH1D*) hZinv->Clone("h_mt2binsMCStat");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      MCStat->SetBinError(ibin, MCStat->GetBinContent(ibin) * ratio->GetBinError(ibin) / ratio->GetBinContent(ibin) );
    }

    TH1D* Syst = (TH1D*) Stat->Clone("h_mt2binsSyst");
    TH1D* pred = (TH1D*) Stat->Clone("h_mt2bins");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      Syst->SetBinError(ibin, 0.);
      double quadrature = Stat->GetBinError(ibin)*Stat->GetBinError(ibin) + Syst->GetBinError(ibin)*Syst->GetBinError(ibin);
      pred->SetBinError(ibin, sqrt(quadrature));
    }
    //pred->Print("all");
    
    TH1D* CRyield = (TH1D*) hGJet->Clone("h_mt2binsCRyield");

    // Extrapolation to next bin: just a ratio of GJet_i/GJet_i-1, so that we can later obtain bin i prediction from bin i-1 yield
    // Instead of : GJet_i * R(Zinv_i/GJet_i), we will do GJet_i-1 * R(GJet_i/GJet_i-1) * R(Zinv_i/GJet_i)
    TH1D* PreviousBinRatio = (TH1D*) hGJet->Clone("h_mt2binsPreviousBinRatio");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      if (ibin<=1) PreviousBinRatio->SetBinContent(ibin, 1.);
      else {
	PreviousBinRatio->SetBinContent(ibin, hGJet->GetBinContent(ibin)/hGJet->GetBinContent(ibin-1));
	PreviousBinRatio->SetBinContent(ibin, hGJet->GetBinContent(ibin)/hGJet->GetBinContent(ibin-1));
      }
      PreviousBinRatio->SetBinError(ibin, 0.); // Ignore uncertainty (just MC anyway)
    }
    

    pred->Write();
    Stat->Write();
    Syst->Write();
    CRyield->Write();
    MCStat->Write();
    PreviousBinRatio->Write();
    ratio->Write();
    ratioInt->Write();
    if(hZinvHT)  hZinvHT->Write();
    if(hZinvHT2) hZinvHT2->Write();
    if(hZinvNJ)  hZinvNJ->Write();
    if(hZinvNB)  hZinvNB->Write();
    //    hZinvPT->Write();
  } // loop over signal regions

  return;
}
void computeSmearingConstants(TString data, TString nonqcd, TString smeared) {

	//define signal and control regions
	vector<scaleFactor> m_regions;
	/*
	m_regions.push_back(scaleFactor("4jet_meff500_2","4jet_meff500noratio_2_qcdcontrol"));
	m_regions.push_back(scaleFactor("4jet_meff500_2_70","4jet_meff500noratio_2_qcdcontrol_70"));
	m_regions.push_back(scaleFactor("6jet_meff500_2_70","6jet_meff500noratio_2_qcdcontrol_70"));
	m_regions.push_back(scaleFactor("6jet_meff500_2_75","6jet_meff500noratio_2_qcdcontrol_75"));
	
	m_regions.push_back(scaleFactor("4jet_meff500_3","4jet_meff500noratio_3_qcdcontrol"));
	m_regions.push_back(scaleFactor("4jet_meff700_3","4jet_meff500noratio_3_qcdcontrol"));
	m_regions.push_back(scaleFactor("4jet_meff900_3_70","4jet_meff500noratio_3_qcdcontrol_70"));
	m_regions.push_back(scaleFactor("6jet_meff700_3_70","6jet_meff500noratio_3_qcdcontrol_70"));
	m_regions.push_back(scaleFactor("6jet_meff900_3_75","6jet_meff500noratio_3_qcdcontrol_75"));
	*/
	m_regions.push_back(scaleFactor("sr1_mct150","sr1_revertdphi"));
	m_regions.push_back(scaleFactor("sr1_mct200","sr1_revertdphi"));
	m_regions.push_back(scaleFactor("sr1_mct250","sr1_revertdphi"));
	m_regions.push_back(scaleFactor("sr2_50ht2","sr2_revertdphi"));
	m_regions.push_back(scaleFactor("sr3_50ht3","sr3_revertdphi"));
	m_regions.push_back(scaleFactor("sr3_met250_j150","sr3_revertdphi"));
	
	TFile dataf(data,"READ");
	TFile nonqcdf(nonqcd,"READ");
	TFile smearedf(smeared,"READ");
	
	TString prefix("nom/");
	TString suffix("_cutflow");
	
    ofstream afh("scaleFactors_smearing.h");
    if (!afh.is_open()) {
      cout << "ERROR opening scaleFactors_smearing.h" << endl;
      return;
    }

    afh << "map<TString,float> getSmearingSFs() {" << endl;    
    afh << "	map<TString,float> scaleFactors;" << endl;
	
	for(unsigned int i = 0; i< m_regions.size(); ++i) {
		TH1D* datacf = (TH1D*)dataf.Get(prefix+m_regions.at(i).CR()+suffix);
		TH1D* nonqcdcf = (TH1D*)nonqcdf.Get(prefix+m_regions.at(i).CR()+suffix);
		TH1D* smearedcf = (TH1D*)smearedf.Get(prefix+m_regions.at(i).CR()+suffix);
		
		if(!datacf) {
			cout << "Missing histograms for region " << m_regions.at(i).CR() << " in data input file." << endl;
			continue;
		}
		else if(!nonqcdcf) {
			cout << "Missing histograms for region " << m_regions.at(i).CR() << " in nonqcd input file." << endl;
			continue;
		}
		else if(!smearedcf) {
			cout << "Missing histograms for region " << m_regions.at(i).CR() << " in smeared input file." << endl;
			continue;
		}
		
		m_regions.at(i).Data(datacf->GetBinContent(1));
		m_regions.at(i).NonQCD(nonqcdcf->GetBinContent(1));
		m_regions.at(i).Smear(smearedcf->GetBinContent(1));
		
		m_regions.at(i).WriteScaleFactor(afh);
		m_regions.at(i).WriteScaleFactor(cout);
	}
	
	afh << "	return scaleFactors;" << endl;
	afh << "};" << endl;
	afh.close();
	
	dataf.Close();
	nonqcdf.Close();
	smearedf.Close();
}
Exemple #18
0
void doPlotsBtag_Log(bool logPlot){
setTDRStyle();

double lumi = 5800;
//stuff to choose
//bool logPlot = false; //true for log plot
int rebinFact = 1;

//isolation selection
//TString Isolation = "QCD No Iso/";
TString Isolation = "Ref selection/";
//TString Isolation = "QCD mu+jets PFRelIso/";
//TString Isolation = "QCD non iso mu+jets/";

TString Systematic = "central";

// number of btags
TString Nbtags = "2btags";  //standard  "2btags" , qcd "0btag"

//choose object
TString Obj = "";
//TString Obj = "MET/";

//muon variables
const int N = 2;
TString Variable;
TString Variables[N] = {"N_BJets", "N_BJets_reweighted"};
double MinXs[N] = {-0.5,-0.5};
double MaxXs[N] = {7.5,7.5};
TString XTitles[N] = {"B-tag Multiplicity", "B-tag Multiplicity"};



//loop over variables
for(int i = 0; i<2; i++){
double MinX = MinXs[i];
double MaxX = MaxXs[i];
Variable = Variables[i];
TString Xtitle = XTitles[i];

//Data
TH1D* data = getSample("SingleMu", 1, Obj, Variable, Isolation, rebinFact, "central");

//MC
TH1D* tt = getSample("TTJet", lumi*225.2/6920475, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* wjets = getSample("W1Jet", lumi*37509/57708550, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w2jets = getSample("W2Jets", lumi*1750.0/34041404, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w3jets = getSample("W3Jets", lumi*519.0/15536443, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* w4jets = getSample("W4Jets", lumi*214.0/13370904, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* zjets = getSample("DY1JetsToLL", lumi*5745.25/30457954, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z2jets = getSample("DY2JetsToLL", lumi*181.0/21835749, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z3jets = getSample("DY3JetsToLL", lumi*51.1/11010628, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* z4jets = getSample("DY4JetsToLL", lumi*23.04/6391785, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* qcd = getSample("QCD_Pt-15to20_MuEnrichedPt5",     lumi*34679.3/8500505, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd2 = getSample("QCD_Pt-20to30_MuEnrichedPt5",   lumi*2.87e8 * 0.0065/8486893, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd3 = getSample("QCD_Pt-30to50_MuEnrichedPt5",   lumi*6.609e7 * 0.0122/8928999, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd4 = getSample("QCD_Pt-50to80_MuEnrichedPt5",   lumi*8082000.0 * 0.0218/7256011, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd5 = getSample("QCD_Pt-80to120_MuEnrichedPt5",  lumi*1024000.0 * 0.0395/9030624, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd6 = getSample("QCD_Pt-120to170_MuEnrichedPt5", lumi*157800.0 * 0.0473/8500505, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd7 = getSample("QCD_Pt-170to300_MuEnrichedPt5", lumi*34020.0 * 0.0676/7662483, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd8 = getSample("QCD_Pt-300to470_MuEnrichedPt5", lumi*1757.0 * 0.0864/7797481, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd9 = getSample("QCD_Pt-470to600_MuEnrichedPt5", lumi*115.2 * 0.1024/2995767, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd10 = getSample("QCD_Pt-800to1000_MuEnrichedPt5",lumi*3.57 * 0.1033/4047142, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* qcd11 = getSample("QCD_Pt-1000_MuEnrichedPt5",     lumi*0.774 * 0.1097/3807263, Obj, Variable, Isolation, rebinFact, Systematic);

TH1D* top_t = getSample("T_t-channel", lumi*56.4/3757707, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* top_tw = getSample("T_tW-channel", lumi*11.1/497395, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* top_s = getSample("T_s-channel", lumi*3.79/249516, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_t = getSample("Tbar_t-channel", lumi*30.7/1934817, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_tw = getSample("Tbar_tW-channel", lumi*11.1/493239, Obj, Variable, Isolation, rebinFact, Systematic);
TH1D* tbar_s = getSample("Tbar_s-channel", lumi*1.76/139948, Obj, Variable, Isolation, rebinFact, Systematic);

//make combined top and single top template
TH1D* sing_top = (TH1D*)top_t->Clone("top");
sing_top->Add(top_tw);sing_top->Add(top_s); sing_top->Add(tbar_t); sing_top->Add(tbar_tw);sing_top->Add(tbar_s);

zjets->Add(z2jets);
zjets->Add(z3jets);
zjets->Add(z4jets);  

wjets->Add(w2jets);
wjets->Add(w3jets);
wjets->Add(w4jets);

//make combined top and single top template
TH1D* qcd_all = (TH1D*)qcd->Clone("qcd_all");
qcd_all->Add(qcd2);
qcd_all->Add(qcd3);
qcd_all->Add(qcd4);
qcd_all->Add(qcd5);
qcd_all->Add(qcd6);
qcd_all->Add(qcd7);
qcd_all->Add(qcd8);
qcd_all->Add(qcd9);
qcd_all->Add(qcd10);
qcd_all->Add(qcd11);
  
THStack *hs = new THStack("hs","test");

qcd_all->SetLineColor(kBlack);
zjets->SetLineColor(kBlack);
wjets->SetLineColor(kBlack);	
sing_top->SetLineColor(kBlack);
tt->SetLineColor(kBlack);	

  hs->Add(qcd_all);
  hs->Add(zjets);
  hs->Add(wjets);
  hs->Add(sing_top);
  hs->Add(tt);

  //draw histos to files
  TCanvas *c1 = new TCanvas("Plot","Plot",900, 600);
		
  hs->SetMaximum(data->GetBinContent(data->GetMaximumBin())*1.2);
  hs->SetMinimum(1.);
  
  hs->Draw();
  data->Draw("E same");
  data->SetMarkerStyle(20);

//events:
cout << "ttbar: " << tt->Integral() << endl;
cout << "data: " << data->Integral() << endl;
  
  if(logPlot == true){
  hs->GetXaxis()->SetLimits(MinX, MaxX);
  }else{
  hs->GetXaxis()->SetLimits(MinX, 4.5);
  }
  
  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(tt , "t#bar{t}", "f");
	tleg2->AddEntry(sing_top, "single top", "f");
	tleg2->AddEntry(wjets , "w+jets", "f");
	tleg2->AddEntry(zjets , "z+jets", "f");
	tleg2->AddEntry(qcd_all , "QCD", "f");
	
	//tleg2->AddEntry(singtEff, "single-t"      , "l");
	//tleg2->AddEntry(singtwEff, "single-tW"      , "l");
 	tleg2->Draw("same");	
	
	if(logPlot == true){
  	TText* textPrelim = doPrelim(0.12,0.96, "#geq 0 btags");
	textPrelim->Draw();
  	}else{
	TText* textPrelim = doPrelim(0.2,0.96, "");
	textPrelim->Draw();
	}
	
  if(logPlot ==true){
  c1->SetLogy();
  }	
  
  TString plotName("Plots/TTbarPlusVarAnalysis/Nbtags/");
  
  if(logPlot ==true){
    plotName += Variable+"_Log";  
  }else{
    plotName += Variable;  
  }
 
 
  c1->SaveAs(plotName+".pdf");
  c1->SaveAs(plotName+".png");
  delete c1;
  
  }
  	
}
Exemple #19
0
TGraph* GetStat(TString className="CVHMV0M-B-NOPF-CENTNOTRD",Bool_t lumi=1, Bool_t goodOnly=0, TString part="PHYSICS_1"){
  Double_t stat[100000];
  Double_t time_stamp[100000];
  TH1D* hStat      = new TH1D("hStat","",1,0,1);
  TH1D* hTimeStart = new TH1D("hTimeStart","",1,0,1);
  TH1D* hTimeEnd   = new TH1D("hTimeEnd","",1,0,1);
  TString classNameRun;

  for (Int_t r=0;r<t->GetEntries();r++){
    t->GetEntry(r);
    if (!partition->String().Contains(part.Data())) continue;
    if (!lhcState->String().Contains("STABLE")) continue;
    if (!lhcPeriod->String().Contains("LHC15m")) continue;
    if (run<225000) continue;
    hTimeStart->Fill(Form("%i",run),timeStart);
    hTimeEnd->Fill(Form("%i",run),timeEnd);
    classNameRun = TString(className);
    if (className.EqualTo("CEMC7-B-NOPF-CENTNOTRD")                  && run<=236224) classNameRun="CEMC7-ABCE-NOPF-ALLNOTRD";
    if (className.EqualTo("CDMC7-B-NOPF-CENTNOTRD")                  && run<=236224) classNameRun="CDMC7-ABCE-NOPF-ALLNOTRD";
    if (className.EqualTo("CMUL7-B-NOPF-MUFAST")                     && run<=226606) classNameRun="CMUL7-B-NOPF-ALLNOTRD";
    if (className.EqualTo("CVHMV0M-B-NOPF-CENTNOTRD")                && run<=236221) classNameRun="CVHMV0M-B-NOPF-CENT";
    if (className.EqualTo("CVHMSH2-B-NOPF-CENTNOTRD")                && run<=236226) classNameRun="CVHMSH2-B-NOPF-CENT";
    if (className.EqualTo("CVHMV0M-B-NOPF-CENTNOTRD") && run>=238432 && run<=239144) classNameRun="CVHMV0M-B-SPD1-CENTNOTRD"; 
    if (className.EqualTo("CVHMSH2-B-NOPF-CENTNOTRD") && run>=238432               ) classNameRun="CVHMSH2-B-SPD1-CENTNOTRD";
    if (className.EqualTo("CINT7-B-NOPF-CENT")        && run>=225000 && run<=228935) classNameRun="CINT7-B-NOPF-ALLNOTRD";
    if (className.EqualTo("CINT7-B-NOPF-CENT")        && run>=228936 && run<=229893) classNameRun="CINT7-B-NOPF-CENTNOTRD";
    if (className.EqualTo("CINT7-B-NOPF-CENT")        && run>=229894 && run<=229899) classNameRun="CINT7-B-NOPF-ALLNOTRD";
    if (className.EqualTo("CINT7-B-NOPF-CENT")        && run>=229900 && run<=233911) classNameRun="CINT7-B-NOPF-CENT";
    if (className.EqualTo("CINT7-B-NOPF-CENT")        && run>=233912 && run<=234050) classNameRun="CINT7-B-NOPF-ALLNOTRD";
    if (className.EqualTo("CINT7-B-NOPF-CENT")        && run>=238890 && run<=239144) classNameRun="CINT7-I-NOPF-CENTNOTRD";
    if (className.EqualTo("CEMC7-B-NOPF-CENTNOTRD")                  && run<=236224) classNameRun="CEMC7-ABCE-NOPF-ALLNOTRD";
    if (className.EqualTo("CDMC7-B-NOPF-CENTNOTRD")                  && run<=236224) classNameRun="CDMC7-ABCE-NOPF-ALLNOTRD";

    AliTriggerClass* cl = (AliTriggerClass*) classes->FindObject(classNameRun.Data());
    if (!cl) { 
      hStat->Fill(Form("%i",run),0.); 
      continue; 
    }
    
    if (goodOnly){
      if (classNameRun.Contains("CINT7") || classNameRun.Contains("CVHM")){
        Int_t good=0;
        for (Int_t i=0;i<nGoodRuns;i++) good|= (goodRuns[i]==run);
        if (!good) {
          hStat->Fill(Form("%i",run),0.);
          continue;
        }
      }

      if (className.Contains("MC7")){
        if (run<235709 || run==236855 || run==236858 || run==236861 || fill==4440) {
          hStat->Fill(Form("%i",run),0.);
          continue;
        }
      }

      if (classNameRun.Contains("CMUL")){
        if (!activeDetectors->String().Contains("MUONTRK") ||
            !activeDetectors->String().Contains("MUONTRG") ||
            !activeDetectors->String().Contains("T0") ||
            !activeDetectors->String().Contains("VZERO") ||
            !activeDetectors->String().Contains("ITSSPD")
        ){
          hStat->Fill(Form("%i",run),0.);
          continue;
        }
      }
    }
//    printf("%i\n",classes->IndexOf(cl));
    Double_t x = lumi ? class_lumi[classes->IndexOf(cl)] : class_l2a[classes->IndexOf(cl)];
    hStat->Fill(Form("%i",run),x);
  }
  hStat->GetXaxis()->LabelsOption("a");
  hTimeEnd->GetXaxis()->LabelsOption("a");
  hTimeStart->GetXaxis()->LabelsOption("a");
  hStat->LabelsDeflate("x");
  hTimeStart->LabelsDeflate("x");
  hTimeEnd->LabelsDeflate("x");
  
  Int_t n = 2*hStat->GetNbinsX();

  for (Int_t i=0;i<hStat->GetNbinsX();i++){
    time_stamp[2*i  ] = hTimeStart->GetBinContent(i+1);
    time_stamp[2*i+1] = hTimeEnd->GetBinContent(i+1);
    stat[2*i]         = i>0?stat[2*i-1]:0;
    stat[2*i+1]       = stat[2*i]+hStat->GetBinContent(i+1)/1000000.;
  }

  delete hStat;
  delete hTimeStart;
  delete hTimeEnd;
  TGraph* gStat = new TGraph(n,time_stamp,stat);
  gStat->SetLineColor(kBlue);
  gStat->SetLineWidth(2);
  return gStat;
}
Exemple #20
0
void DrawPhi(Int_t step=1,Float_t ptmin=0,Float_t ptmax=10){
  TFile *fcur = TFile::Open(Form("step%i.root",step));
  TFile *fpre = TFile::Open(Form("step%i.root",step-1));

  TH2D *hcurT = (TH2D *) fcur->Get("truePidPhiKaKa");
  TH2D *hcurP = (TH2D *) fcur->Get("priorsPhiKaKa");

  TH2D *hpreT = (TH2D *) fpre->Get("truePidPhiLaKa");
  TH2D *hpreP = (TH2D *) fpre->Get("priorsPhiKaKa");

  TH2D *hPion = (TH2D *) fcur->Get("priorsPhiPiPi");
//   hPion->Add((TH2D *) fcur->Get("priorsPhiPiKa"));
//   hPion->Add((TH2D *) fcur->Get("priorsPhiPiPr"));
//   hPion->Add((TH2D *) fcur->Get("priorsPhiKaPi"));
//   hPion->Add((TH2D *) fcur->Get("priorsPhiPrPi"));


  TH1D *hprior = hcurP->ProjectionX("meas",hcurP->GetYaxis()->FindBin(ptmin+0.001),hcurP->GetYaxis()->FindBin(ptmax-0.001));
  TH1D *htrue = hcurT->ProjectionX("true",hcurT->GetYaxis()->FindBin(ptmin+0.001),hcurT->GetYaxis()->FindBin(ptmax-0.001));

  TH1D *hpriorOld = hpreP->ProjectionX("measOld",hpreP->GetYaxis()->FindBin(ptmin+0.001),hpreP->GetYaxis()->FindBin(ptmax-0.001));

  TH1D *hnorm = hPion->ProjectionX("norm",hPion->GetYaxis()->FindBin(ptmin+0.001),hPion->GetYaxis()->FindBin(ptmax-0.001));


  for(Int_t i=1;i <= hprior->GetNbinsX();i++){
    Float_t err = TMath::Abs(hprior->GetBinContent(i)-hpriorOld->GetBinContent(i));
    if(hprior->GetBinContent(i)){
      err *= hnorm->GetBinContent(i);
      err /= hprior->GetBinContent(i);
    }
    hprior->SetBinError(i,err);
    //htrue->SetBinError(i,0);

  }

  TF1 *bw = new TF1("bw","[0]/((x-[1])*(x-[1]) +([2]*[2]*0.25)) + pol1(3)",1,1.05);
  TF1 *bwsig = new TF1("bw","[0]/((x-[1])*(x-[1]) +([2]*[2]*0.25))",1,1.05);

  bw->SetLineColor(2);
  bw->SetParameter(0,100);
  bw->FixParameter(1,1.02);
  bw->FixParameter(2,0.00426);
  bw->SetParameter(3,0);
  bw->SetParameter(4,0);
  bw->SetParameter(5,0);


  TCanvas *c = new TCanvas();
  c->Divide(1,2);
  c->cd(1);

  hprior->Draw("ERR3");
  htrue->SetLineColor(2);
  htrue->Draw("SAME");
  htrue->Fit(bw,"W","",1,1.05);

  for(Int_t i=0;i < 3;i++) bwsig->SetParameter(i,bw->GetParameter(i));
  
  Float_t truesig = bwsig->Integral(1,1.05) / htrue->GetBinWidth(1);

  hprior->Fit(bw,"W","",1,1.05);

  for(Int_t i=0;i < 3;i++) bwsig->SetParameter(i,bw->GetParameter(i));
  
  Float_t meassig = bwsig->Integral(1,1.05) / htrue->GetBinWidth(1);

  c->cd(2);
  bw->SetParameter(0,100);
  bw->SetParameter(3,0);
  bw->SetParameter(4,0);
  bw->SetParameter(5,0);
  TH1D *hr=new TH1D(*hprior);
  hr->Add(htrue,-1);
  hr->GetYaxis()->SetTitle("(meas-true)/true");
  hr->Divide(htrue);
  hr->Draw();
  hr->GetYaxis()->UnZoom();
  hr->Fit("pol0");
  hr->Fit(bw,"W","",1,1.05);

  for(Int_t i=0;i < 3;i++) bwsig->SetParameter(i,bw->GetParameter(i));

  Float_t deltasig = bwsig->Integral(1,1.05) / hr->GetBinWidth(1);

  printf("signal = %f -- delta = %f (%f) --> Precision = %f(%f)%c\n",truesig,meassig-truesig,deltasig,(meassig-truesig)/truesig,deltasig/truesig*100,'%');

}
Exemple #21
0
void plotAnaMult4(char *infname="ana.root")
{    
   TFile *inf = new TFile(infname);
   
   TTree *tData = (TTree*) inf->Get("Data_tree");
   TTree *tMC   = (TTree*) inf->Get("MC_tree");
   TTree *tPP   = (TTree*) inf->Get("PP_tree");

   TCanvas *c1 = new TCanvas("c","",1200,700);
//   c->Divide(4,1);
   TCut recoCut = "leadingJetPt>120&&subleadingJetPt>50&&dphi>5*3.14159265358979/6.&&abs(leadingJetEta)<1.6&&abs(subleadingJetEta)<1.6";
   TCut genCut = "genleadingJetPt>120&&gensubleadingJetPt>50&&genDphi>5*3.14159265358979/6.&&abs(genleadingJetEta)<1.6&&abs(gensubleadingJetEta)<1.6";

   
   const int nPtBin=5;
   Float_t PtBins[nPtBin+1] = {0.001,0.5,1,1.5,2,3.2};
   
   Int_t centBin[5] = {200,100,60,20,0};
   makeMultiPanelCanvas(c1,4,2,0.0,0.0,0.2,0.2,0.02);
   
   for (int i=0;i<4;i++) {
      c1->cd(i+1);
      TH1D * empty=new TH1D("empty","",100,0,3.19);
//      empty->Fill(0.5,1000); 
      empty->SetMaximum(39.99); 
      empty->SetMinimum(0.001); 
      empty->SetNdivisions(105,"X");
      empty->GetXaxis()->SetTitleSize(28);
      empty->GetXaxis()->SetTitleFont(43); 
      empty->GetXaxis()->SetTitleOffset(1.8);
      empty->GetXaxis()->SetLabelSize(22);
      empty->GetXaxis()->SetLabelFont(43);
      empty->GetYaxis()->SetTitleSize(28);
      empty->GetYaxis()->SetTitleFont(43); 
      empty->GetYaxis()->SetTitleOffset(1.8);
      empty->GetYaxis()->SetLabelSize(22);
      empty->GetYaxis()->SetLabelFont(43);
      empty->GetXaxis()->CenterTitle();
      empty->GetYaxis()->CenterTitle();

      empty->SetXTitle("#Delta#eta_{1,2}");
      empty->SetYTitle("Multiplicity Difference");
   
      TProfile *pData = new TProfile(Form("pData%d",i),"",nPtBin,PtBins);
      TProfile *pMC = new TProfile(Form("pMC%d",i),"",nPtBin,PtBins);
      TProfile *pPP = new TProfile(Form("pPP%d",i),"",nPtBin,PtBins);
      TProfile *pGen = new TProfile(Form("pGen%d",i),"",nPtBin,PtBins);
      TCut centCut = Form("hiBin>=%d&&hiBin<%d",centBin[i+1],centBin[i]);
      tData->Draw(Form("-multDiff:abs(leadingJetEta-subleadingJetEta)>>pData%d",i),recoCut&&centCut);
      tPP->Draw(Form("-multDiff:abs(leadingJetEta-subleadingJetEta)>>pPP%d",i),recoCut);
      tMC->Draw(Form("-multDiff:abs(leadingJetEta-subleadingJetEta)>>pMC%d",i),recoCut&&centCut);  
      tMC->Draw(Form("-genMultDiff:abs(genleadingJetEta-gensubleadingJetEta)>>pGen%d",i),genCut&&centCut);  

      pMC->SetLineColor(2);
      pMC->SetMarkerColor(2);
      pPP->SetLineColor(4);
      pPP->SetMarkerColor(4);
      
//      pData->SetAxisRange(0,50,"Y");
//      pData->SetAxisRange(0,0.49,"X");
      empty->Draw();

      double diff=0;
      if (i==0) diff=0.1;
      drawText(Form("%d-%d %%",(int)(0.5*centBin[i+1]),(int)(0.5*centBin[i])),0.22+diff,0.65);
      if (i==0) drawText("PbPb #sqrt{s_{NN}}=2.76 TeV 150/#mub",0.22+diff,0.85);
      if (i==0) drawText("pp      #sqrt{s_{NN}}=2.76 TeV 5.3/pb",0.22+diff,0.75);
      if (i==3) drawText("CMS Preliminary",0.3+diff,0.85);
            
      Float_t sys[4]={1,1,2.5,3};
      

      for (int j=1;j<=pData->GetNbinsX();j++)
      {
         TBox *b = new TBox(pData->GetBinLowEdge(j),pData->GetBinContent(j)-sys[i],pData->GetBinLowEdge(j+1),pData->GetBinContent(j)+sys[i]);
	 //b->SetFillColor(kGray);
	 b->SetFillStyle(0);
	 b->SetLineColor(1);
	 b->Draw();
         TBox *b2 = new TBox(pPP->GetBinLowEdge(j),pPP->GetBinContent(j)-1,pPP->GetBinLowEdge(j+1),pPP->GetBinContent(j)+1);
	 //b2->SetFillColor(65);
	 b2->SetFillStyle(0);
	 b2->SetLineColor(4);
	 b2->Draw();
      }
      pData->Draw("same");
      pMC->Draw("same");
      pPP->Draw("same");
      pGen->SetMarkerColor(4);
      pGen->SetMarkerStyle(24);
      pData->Draw("same");
      
//      pGen->Draw(" same");

      c1->cd(5+i);
      TH1D *empty2 = (TH1D*)empty->Clone("empty2");
      empty2->SetYTitle("PbPb - pp");
      empty2->SetMinimum(-5);
      empty2->SetMaximum(+29.99);
      empty2->Draw();
//      TProfile *pDiff = (TProfile*)pData->Clone("pDiff");
      TH1D *pDiff = new TH1D("pDiff","",nPtBin,PtBins);
      
      for (int j=1;j<=pData->GetNbinsX();j++)
      {
	 pDiff->SetBinContent(j,pData->GetBinContent(j)-pPP->GetBinContent(j));
  	 pDiff->SetBinError(j,sqrt(pData->GetBinError(j)*pData->GetBinError(j)+pPP->GetBinError(j)*pPP->GetBinError(j)));
         TBox *b = new TBox(pDiff->GetBinLowEdge(j),pDiff->GetBinContent(j)-sys[i],pDiff->GetBinLowEdge(j+1),pDiff->GetBinContent(j)+sys[i]);
         TBox *b2 = new TBox(pDiff->GetBinLowEdge(j),pDiff->GetBinContent(j)-sys[i],pDiff->GetBinLowEdge(j+1),pDiff->GetBinContent(j)+sys[i]);
         b->SetFillColor(TColor::GetColor("#FFEE00"));
	 b2->SetLineColor(1);
	 b2->SetFillStyle(0);
	 b->Draw();
	 b2->Draw();
      }
      
      pDiff->Draw("p same");


      TLegend *leg = new TLegend(0.3,0.6,0.9,0.9);
      leg->SetFillStyle(0);
      leg->SetBorderSize(0);
      leg->AddEntry(pData,"PbPb","pl");
      leg->AddEntry(pPP,"pp","pl");
      leg->AddEntry(pMC,"PYTHIA+HYDJET","pl");
      if (i==0) leg->Draw();

      if (i==1) drawText("p_{T,1} > 120 GeV/c",0.22+diff,0.85);
      if (i==1) drawText("p_{T,2} >  50 GeV/c",0.22+diff,0.75);
      if (i==1) drawText("#Delta#phi_{1,2} > 5#pi/6",0.22+diff,0.65);

   }
/*
   TCanvas *c1 = new TCanvas("c1","",(ncent+1)*300,700);
   makeMultiPanelCanvas(c1,ncent+1,2,0.0,0.0,0.2,0.2,0.02);
   TH1D * empty=new TH1D("empty",Form(";%s;<#slash{p}_{T}^{#parallel}> (GeV)",axistitle[index_var].Data()),nalpha/2+1,frac);
   TH1D * empty2=new TH1D("empty2",Form(";%s;<#slash{p}_{T}^{#parallel}> (GeV)",axistitle[index_var].Data()),nalpha/2+1,frac);
   empty->Fill(0.5,1000); 
   empty2->Fill(0.5,1000);   
   if(doIntegrate){
      if(index_var==0){
         empty->SetMaximum(30); 
         empty->SetMinimum(-70); 
      }else{
         empty->SetMaximum(35); 
         empty->SetMinimum(-45); 
      }
   }else{
      empty->SetMaximum(15); 
      empty->SetMinimum(-10); 
      empty2->SetMaximum(15); 
      empty2->SetMinimum(-10); 
   }
   empty->GetXaxis()->SetTitleSize(28);
   empty->GetXaxis()->SetTitleFont(43); 
   empty->GetXaxis()->SetTitleOffset(2.2);
   empty->GetXaxis()->SetLabelSize(22);
   empty->GetXaxis()->SetLabelFont(43);
   empty->GetYaxis()->SetTitleSize(28);
   empty->GetYaxis()->SetTitleFont(43); 
   empty->GetYaxis()->SetTitleOffset(2.2);
   empty->GetYaxis()->SetLabelSize(22);
   empty->GetYaxis()->SetLabelFont(43);
   empty2->GetXaxis()->SetTitleSize(28);
   empty2->GetXaxis()->SetTitleFont(43); 
   empty2->GetXaxis()->SetTitleOffset(2.2);
   empty2->GetXaxis()->SetLabelSize(22);
   empty2->GetXaxis()->SetLabelFont(43);
   empty2->GetYaxis()->SetTitleSize(28);
   empty2->GetYaxis()->SetTitleFont(43); 
   empty2->GetYaxis()->SetTitleOffset(2.2);
   empty2->GetYaxis()->SetLabelSize(22);
   empty2->GetYaxis()->SetLabelFont(43);
   
   
   c1->cd(ncent+2); 
*/

   c1->SaveAs("results/MultiplicityDifference-DeltaEta.C");
   c1->SaveAs("results/MultiplicityDifference-DeltaEta.gif");
   c1->SaveAs("results/MultiplicityDifference-DeltaEta.eps");
   c1->SaveAs("results/MultiplicityDifference-DeltaEta.pdf");


}
Exemple #22
0
void makeCentralityTable(int nbins = 40, const string label = "hf", const char * tag = "HFhitBins", double MXS = 0.){

   // This macro assumes all inefficiency is in the most peripheral bin.
   double EFF = 1. - MXS;

   // Retrieving data
  int nFiles = 1;
  vector<string> infiles;
  //  TFile* infile = new TFile("/net/hisrv0001/home/yetkin/pstore02/ana/Hydjet_MinBias_d20100222/Hydjet_MinBias_4TeV_runs1to300.root");
  //  fwlite::Event event(infile);
  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs1to10.root");
  //  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs11to20.root");
  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs21to30.root");
  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs31to40.root");
  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs41to50.root");
  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs51to60.root");
  //  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs61to70.root");
  //  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs71to80.root");
  //  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs81to90.root")
  //  infiles.push_back("~/hibat0007/aod/JulyExercise/MinBias0707/MinBias0707_runs91to100.root");

  fwlite::ChainEvent event(infiles);

  vector<int> runnums;

  // Creating output table
  TFile* outFile = new TFile("tables.root","update");
   TDirectory* dir = outFile->mkdir(tag);
   dir->cd();

  TH1D::SetDefaultSumw2();
  CentralityBins* bins = new CentralityBins("noname","Test tag", nbins);
  bins->table_.reserve(nbins);

  // Setting up variables & branches
  double binboundaries[nbinsMax+1];
  vector<float> values;

  // Determining bins of cross section
  // loop over events
  unsigned int events=0;
  for(event.toBegin(); !event.atEnd(); ++event, ++events){
     edm::EventBase const & ev = event;
    if( events % 100 == 0 ) cout<<"Processing event : "<<events<<endl;
    edm::Handle<edm::GenHIEvent> mc;
    ev.getByLabel(edm::InputTag("heavyIon"),mc);
    edm::Handle<reco::Centrality> cent;
    ev.getByLabel(edm::InputTag("hiCentrality"),cent);

    double b = mc->b();
    double npart = mc->Npart();
    double ncoll = mc->Ncoll();
    double nhard = mc->Nhard();

    double hf = cent->EtHFhitSum();
    double hftp = cent->EtHFtowerSumPlus();
    double hftm = cent->EtHFtowerSumMinus();
    double eb = cent->EtEBSum();
    double eep = cent->EtEESumPlus();
    double eem = cent->EtEESumMinus();

    double parameter = 0;
    if(label.compare("npart") == 0) parameter = npart;
    if(label.compare("ncoll") == 0) parameter = ncoll;
    if(label.compare("nhard") == 0) parameter = nhard;
    if(label.compare("b") == 0) parameter = b;
    if(label.compare("hf") == 0) parameter = hf;
    if(label.compare("hft") == 0) parameter = hftp + hftm;
    if(label.compare("eb") == 0) parameter = eb;
    if(label.compare("ee") == 0) parameter = eep+eem;

    values.push_back(parameter);
    
    int run = event.id().run();
    if(runnums.size() == 0 || runnums[runnums.size()-1] != run) runnums.push_back(run);
  }
  
  if(label.compare("b") == 0) sort(values.begin(),values.end(),descend);
  else sort(values.begin(),values.end());

  double max = values[events-1];
  binboundaries[nbins] = max;

  cout<<"-------------------------------------"<<endl;
  cout<<label.data()<<" based cuts are : "<<endl;
  cout<<"(";

  int bin = 0;
  for(int i = 0; i< nbins; ++i){
     // Find the boundary 
     int offset = (int)(MXS*events);
     double xsec = events*(1 + MXS);
     // Below should be replaced with an integral
     // when inefficiency is better parametrized 
     // than a step function.

     int entry = (int)(i*(xsec/nbins)) - offset;
     binboundaries[i] = values[entry];

     cout<<" "<<binboundaries[i];
     if(i < nbins - 1) cout<<",";
     else cout<<")"<<endl;
  }
  cout<<"-------------------------------------"<<endl;

  // Determining Glauber results in various bins
  TH2D* hNpart = new TH2D("hNpart","",nbins,binboundaries,500,0,500);
  TH2D* hNcoll = new TH2D("hNcoll","",nbins,binboundaries,2000,0,2000);
  TH2D* hNhard = new TH2D("hNhard","",nbins,binboundaries,250,0,250);
  TH2D* hb = new TH2D("hb","",nbins,binboundaries,300,0,30);

  for(event.toBegin(); !event.atEnd(); ++event){
     edm::EventBase const & ev = event;
     edm::Handle<edm::GenHIEvent> mc;
     ev.getByLabel(edm::InputTag("heavyIon"),mc);
     edm::Handle<reco::Centrality> cent;
     ev.getByLabel(edm::InputTag("hiCentrality"),cent);

     double b = mc->b();
     double npart = mc->Npart();
     double ncoll = mc->Ncoll();
     double nhard = mc->Nhard();

     double hf = cent->EtHFhitSum();
     double hftp = cent->EtHFtowerSumPlus();
     double hftm = cent->EtHFtowerSumMinus();
     double eb = cent->EtEBSum();
     double eep = cent->EtEESumPlus();
     double eem = cent->EtEESumMinus();

     double parameter = 0;

     if(label.compare("npart") == 0) parameter = npart;
     if(label.compare("ncoll") == 0) parameter = ncoll;
     if(label.compare("nhard") == 0) parameter = nhard;
     if(label.compare("b") == 0) parameter = b;
     if(label.compare("hf") == 0) parameter = hf;
     if(label.compare("hft") == 0) parameter = hftp + hftm;
     if(label.compare("eb") == 0) parameter = eb;
     if(label.compare("ee") == 0) parameter = eep+eem;
    
     hNpart->Fill(parameter,npart);
     hNcoll->Fill(parameter,ncoll);
     hNhard->Fill(parameter,nhard);
     hb->Fill(parameter,b);
  }

  // Fitting Glauber distributions in bins to get mean and sigma values


  TF1* fGaus = new TF1("fb","gaus(0)",0,2); 
  fGaus->SetParameter(0,1);
  fGaus->SetParameter(1,0.04);
  fGaus->SetParameter(2,0.02); 
  
  fitSlices(hNpart,fGaus);
  fitSlices(hNcoll,fGaus);
  fitSlices(hNhard,fGaus);
  fitSlices(hb,fGaus);

 /*
  hNpart->FitSlicesY();
  hNcoll->FitSlicesY();
  hNhard->FitSlicesY();
  hb->FitSlicesY();
 */

  TH1D* hNpartMean = (TH1D*)gDirectory->Get("hNpart_1");
  TH1D* hNpartSigma = (TH1D*)gDirectory->Get("hNpart_2");
  TH1D* hNcollMean = (TH1D*)gDirectory->Get("hNcoll_1");
  TH1D* hNcollSigma = (TH1D*)gDirectory->Get("hNcoll_2");
  TH1D* hNhardMean = (TH1D*)gDirectory->Get("hNhard_1");
  TH1D* hNhardSigma = (TH1D*)gDirectory->Get("hNhard_2");
  TH1D* hbMean = (TH1D*)gDirectory->Get("hb_1");
  TH1D* hbSigma = (TH1D*)gDirectory->Get("hb_2");

  cout<<"-------------------------------------"<<endl;
  cout<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;


  // Enter values in table
  for(int i = 0; i < nbins; ++i){
     bins->table_[nbins-i-1].n_part_mean = hNpartMean->GetBinContent(i);
     bins->table_[nbins-i-1].n_part_var = hNpartSigma->GetBinContent(i);
     bins->table_[nbins-i-1].n_coll_mean = hNcollMean->GetBinContent(i);
     bins->table_[nbins-i-1].n_coll_var = hNcollSigma->GetBinContent(i);
     bins->table_[nbins-i-1].b_mean = hbMean->GetBinContent(i);
     bins->table_[nbins-i-1].b_var = hbSigma->GetBinContent(i);
     bins->table_[nbins-i-1].n_hard_mean = hNhardMean->GetBinContent(i);
     bins->table_[nbins-i-1].n_hard_var = hNhardSigma->GetBinContent(i);
     bins->table_[nbins-i-1].bin_edge = binboundaries[i];

     cout<<i<<" "
	 <<hNpartMean->GetBinContent(i)<<" "
	 <<hNpartSigma->GetBinContent(i)<<" "
	 <<hNcollMean->GetBinContent(i)<<" "
	 <<hNcollSigma->GetBinContent(i)<<" "
	 <<hbMean->GetBinContent(i)<<" "
	 <<hbSigma->GetBinContent(i)<<" "
	 <<binboundaries[i]<<" "
	 <<endl;
  }
  cout<<"-------------------------------------"<<endl;

  // Save the table in output file

  if(onlySaveTable){

     TH1D* hh = (TH1D*)gDirectory->Get("hNpart_0");
     hh->Delete();
     hh = (TH1D*)gDirectory->Get("hNcoll_0");
     hh->Delete();
     hh = (TH1D*)gDirectory->Get("hNhard_0");
     hh->Delete();
     hh = (TH1D*)gDirectory->Get("hb_0");
     hh->Delete();

     hNpart->Delete();
     hNpartMean->Delete();
     hNpartSigma->Delete();
     hNcoll->Delete();
     hNcollMean->Delete();
     hNcollSigma->Delete();
     hNhard->Delete();
     hNhardMean->Delete();
     hNhardSigma->Delete();
     hb->Delete();
     hbMean->Delete();
     hbSigma->Delete();
  }
  
  for(int i = 0; i < runnums.size(); ++i){
     CentralityBins* binsForRun = (CentralityBins*) bins->Clone();
     binsForRun->SetName(Form("run%d",runnums[i]));
     binsForRun->Write();
  }
  
  bins->Delete();
  outFile->Write();
  
}
Exemple #23
0
void L1Emul_macro()
{
  //TH1::SetDefaultSumw2();
  TFile *file[2];
  TTree *HltTree[2];

  TString L1Emul_data = "/net/hidsk0001/d00/scratch/luck/data/HiForest.root";
  TString Minbias_data = "/net/hisrv0001/home/icali/hadoop/HIMinBiasUPC_skimmed/MinBias-reTracking-merged/MinBias_Merged_tracking_all.root";
   
  file[0] = new TFile(L1Emul_data);
  HltTree[0] = (TTree*)file[0]->Get("hltanalysis/HltTree");
  HltTree[0]->AddFriend("t=icPu5JetAnalyzer/t",L1Emul_data);

  file[1] = new TFile(Minbias_data);
  HltTree[1] = (TTree*)file[1]->Get("hltanalysis/HltTree");
  HltTree[1]->AddFriend("t=icPu5JetAnalyzer/t",Minbias_data);

  TString L1_SingleJet = "L1_SingleJet";
  TString thresholds[] = {"16", "36_BptxAND", "52_BptxAND",
			  "68_BptxAND", "80_BptxAND", "92_BptxAND",
			  "128_BptxAND"};
  int thresholdi[] = {16, 36, 52, 68, 80, 92, 128};


  
  // TH1D *hist_bottom = new TH1D("hist_bottom","Denominator", 30, 0, 120);
  // HltTree->Project("hist_bottom","t.jtpt[0]");

  // for(int i = 0; i < 6; i++)
  // {  
  //   TH1D *hist = new TH1D(L1_SingleJet+thresholds[i],
  // 			  L1_SingleJet+thresholds[i],
  // 			  30, 0, 120);
  //   HltTree->Project(L1_SingleJet+thresholds[i],
  // 		     "t.jtpt[0]",
  // 		     L1_SingleJet+thresholds[i]);
  //   hist->Divide(hist, hist_bottom, 1, 1, "b");
  //   TCanvas *co = new TCanvas();
  //   hist->GetYaxis()->SetRangeUser(0,1);
  //   hist->Draw("p,E");
  // }


  Double_t xbins[9] = {-2,2,30,42,62,74,86,98,158};
  TH1D *efficiency_curve[4];
  efficiency_curve[0] = new TH1D("efficiency_curve_0","Efficiency",
				    8,xbins);
  efficiency_curve[1] = new TH1D("efficiency_curve_1","Efficiency",
				    8,xbins);
  for(int i = 0; i < 2; i++)
  {
    efficiency_curve[i]->SetXTitle("L1 Jet Trigger Threshold");
    efficiency_curve[i]->SetYTitle("Fraction of Passing Events");
    efficiency_curve[i]->Fill(0.,1.);

    for(int j = 0; j < 7; j++)
    {
      TH1D *hist = new TH1D(L1_SingleJet+thresholds[j],
			    L1_SingleJet+thresholds[j],
			    2, -0.5, 1.5);
      HltTree[i]->Project(L1_SingleJet+thresholds[j],
			  L1_SingleJet+thresholds[j]);

      efficiency_curve[i]->Fill(thresholdi[j],hist->GetBinContent(2)/hist->GetEntries());
      delete hist;
    }
    efficiency_curve[i]->GetYaxis()->SetRangeUser(0,1);
    efficiency_curve[i]->GetXaxis()->SetRangeUser(0,130);
  }

  TriggerPrimitivesTree_alex *min =
    new TriggerPrimitivesTree_alex(new TFile("minbias.root"));
  int total_events = 5000;
  TH1D *temp[2];
  temp[0] = (TH1D*)min->Loop(total_events, 0,
		     false, false)->Clone();
  temp[1] = (TH1D*)min->Loop(total_events, 0,
		     true, false)->Clone();
  for(int j = 0; j < 2; j++)
  {
    stringstream s;
    s << "efficiency_curve_" << j+2;
    efficiency_curve[j+2] = new TH1D(s.str().c_str(),"efficiency_curve",
				     temp[j]->GetNbinsX(),0,temp[j]->GetXaxis()->GetXmax());
    for(int i = 0; i < temp[j]->GetNbinsX(); i++)
    {
      efficiency_curve[j+2]->Fill(temp[j]->GetBinCenter(i), temp[j]->GetBinContent(i));
    }
  }
  

  TCanvas *c0 = new TCanvas();
  efficiency_curve[0]->SetLineColor(kRed);
  efficiency_curve[1]->SetLineColor(kBlue);
  efficiency_curve[2]->SetLineColor(40);
  efficiency_curve[3]->SetLineColor(30);
  
  efficiency_curve[0]->Draw("L");
  efficiency_curve[1]->Draw("L,same");
  efficiency_curve[2]->Draw("L,same");
  efficiency_curve[3]->Draw("L,same");

  TLegend *leg = new TLegend(0.5,0.5,0.8,0.7);
  leg->SetFillColor(0);
  leg->AddEntry(efficiency_curve[1],"Current L1 System, official","l");
  leg->AddEntry(efficiency_curve[2],"Current L1 System, ntuples","l");
  leg->AddEntry(efficiency_curve[0],"Phi-Ring Subtraction at L1, official","l");
  leg->AddEntry(efficiency_curve[3],"Phi-Ring Subtraction at L1, ntuples","l");
  leg->Draw();
 
  c0->Update();

}
int calculateSignificance(double metCut, double ecaloCut, TString region, TString folder = "NLostOuterGe0") {


    TString nlost = "";
    if(folder.Contains("NLostOuterGe0")) nlost="0";
    else if(folder.Contains("NLostOuterGe1")) nlost="1";
    else if(folder.Contains("NLostOuterGe2")) nlost="2";
    else if(folder.Contains("NLostOuterGe3")) nlost="3";

    gStyle->SetOptStat(0);
    TeresaPlottingStyle2d::init();
    gStyle -> SetTitleSize(0.05,"Z");
    gStyle -> SetTitleOffset(1.2,"Z");
    gStyle -> SetOptTitle(1);
    gStyle -> SetNdivisions(505,"Z");

    gStyle->SetTitleStyle(1);
    gStyle->SetStatStyle(0);
    gROOT->ForceStyle();

    //gStyle->SetTitleBorderSize(0);
    //gStyle -> SetPadRightMargin(0.20);
    //gStyle->SetTitleFont(42,"");

    vector<TString> samples;
    vector<TString> titles;
    TString sig_m100_ct1 = "Madgraph_signal_mass_100_ctau_1cm";
    samples.push_back(sig_m100_ct1);
    titles.push_back("mass=100GeV, c#tau=1cm");
    TString sig_m100_ct5 = "Madgraph_signal_mass_100_ctau_5cm";
    samples.push_back(sig_m100_ct5);
    titles.push_back("mass=100GeV, c#tau=5cm");
    TString sig_m100_ct10 = "Madgraph_signal_mass_100_ctau_10cm";
    samples.push_back(sig_m100_ct10);
    titles.push_back("mass=100GeV, c#tau=10cm");
    TString sig_m100_ct50 = "Madgraph_signal_mass_100_ctau_50cm";
    samples.push_back(sig_m100_ct50);
    titles.push_back("mass=100GeV, c#tau=50cm");
    TString sig_m200_ct1 = "Madgraph_signal_mass_200_ctau_1cm";
    //samples.push_back(sig_m200_ct1);
    TString sig_m200_ct5 = "Madgraph_signal_mass_200_ctau_5cm";
    //samples.push_back(sig_m200_ct5);
    TString sig_m200_ct50 = "Madgraph_signal_mass_200_ctau_50cm";
    //samples.push_back(sig_m200_ct50);
    TString sig_m300_ct5 = "Madgraph_signal_mass_300_ctau_5cm";
    //samples.push_back(sig_m300_ct5);
    TString sig_m300_ct10 = "Madgraph_signal_mass_300_ctau_10cm";
    //samples.push_back(sig_m300_ct10);
    TString sig_m300_ct50 = "Madgraph_signal_mass_300_ctau_50cm";
    //samples.push_back(sig_m300_ct50);
    TString sig_m500_ct1 = "Madgraph_signal_mass_500_ctau_1cm";
    //samples.push_back(sig_m500_ct1);
    //titles.push_back("mass=500GeV, c#tau=1cm");
    TString sig_m500_ct5 = "Madgraph_signal_mass_500_ctau_5cm";
    samples.push_back(sig_m500_ct5);
    titles.push_back("mass=500GeV, c#tau=5cm");
    TString sig_m500_ct10 = "Madgraph_signal_mass_500_ctau_10cm";
    samples.push_back(sig_m500_ct10);
    titles.push_back("mass=500GeV, c#tau=10cm");
    TString sig_m500_ct50 = "Madgraph_signal_mass_500_ctau_50cm";
    samples.push_back(sig_m500_ct50);
    titles.push_back("mass=500GeV, c#tau=50cm");


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


        TH2D* sig1 = new TH2D("significance",samples[i] + ": s/#Delta b_{stat}",9,20,65,9,0.00,0.45);
        sig1->GetXaxis()->SetTitle("p_{T} cut [GeV]");
        sig1->GetYaxis()->SetTitle("I_{as} cut");
        //sig1->GetZaxis()->SetTitle("minimum possible x-sec to discover [pb]");
        sig1->GetZaxis()->SetTitle("minimal discoverable x-sec [pb]");
        sig1->GetZaxis()->CenterTitle();
        sig1->SetTitle(titles[i]);

        //    TH2D* sig2 = new TH2D("significance",samples[i]+ ": s/#sqrt((#Delta b_{stat})^{2} + (#Delta b_{sys}^{fake})^{2} + (10 #upoint #Delta b_{sys}^{lepton})^{2})",7,30,65,9,0.00,0.45);
        TH2D* sig2 = new TH2D("significance",samples[i]+ ": s/#Delta b_{stat + sys}",9,20,65,9,0.00,0.45);
        sig2->GetXaxis()->SetTitle("p_{T} cut [GeV]");
        sig2->GetYaxis()->SetTitle("I_{as} cut");
        sig2->GetZaxis()->SetTitle("minimal discoverable x-sec [pb]");
        sig2->GetZaxis()->CenterTitle();
        //sig2->SetTitle(titles[i] + ", N_{lost}^{outer}#geq" + nlost);
        sig2->SetTitle(titles[i]);
        sig2->GetZaxis()->SetNoExponent(kTRUE);
        //sig2->GetZaxis()->SetRangeUser(0.5,2.5);

        TH2D* hBkgYield = new TH2D("hBkgYield","Bkg Yield",9,20,65,9,0.00,0.45);
        hBkgYield -> GetXaxis()->SetTitle("p_{T} cut [GeV]");
        hBkgYield -> GetYaxis()->SetTitle("I_{as} cut");
        hBkgYield -> GetZaxis()->SetTitle("bkg yield");

        TH2D* hBkgUnc = new TH2D("hBkgUnc","Bkg Unc",9,20,65,9,0.00,0.45);
        hBkgUnc -> GetXaxis()->SetTitle("p_{T} cut [GeV]");
        hBkgUnc -> GetYaxis()->SetTitle("I_{as} cut");
        hBkgUnc -> GetZaxis()->SetTitle("bkg uncertainty [%]");

        TH2D* hSignalYield = new TH2D("hSignalYield",samples[i] + ": Signal Yield",9,20,65,9,0.00,0.45);
        hSignalYield -> GetXaxis()->SetTitle("p_{T} cut [GeV]");
        hSignalYield -> GetYaxis()->SetTitle("I_{as} cut");
        hSignalYield -> GetZaxis()->SetTitle("signal yield");
        hSignalYield -> SetTitle(titles[i]);

        //----------------------------------------------------------------------------------------------------------
        // Get theory cross-section:
        cout<<"######################################################"<<endl;
        cout<<"Get theory cross section:"<<endl;
        ifstream inputFile("xsectionsUpdated.txt");
        int it=0;
        TString name;
        double xsec,err;
        while(inputFile>>name>>xsec>>err) {
            TString aux =  "mass_" + name;
            cout<<"aux = "<<aux<<endl;
            if ( samples[i].Contains(aux) ) {
                cout<<endl<<name<<": "<<xsec<<" pb"<<endl<<endl;
                break;
            }
            it++;
        }
        inputFile.close();
        xsec = xsec/1000.;   // xsection in pb
        cout<<"######################################################"<<endl;
        //----------------------------------------------------------------------------------------------------------

        for(int l=0; l<9; l++) {
            //      for(int l=0; l<9; l++){

            double ptCut = 20 + l*5;

            //for(int j=0; j<9; j++){
            for(int j=0; j<9; j++) {


                double iasCut = 0.00 + j*0.05;

                cout<<"---------------------------------------------"<<""<<endl;
                cout<<"pt cut = "<<ptCut<<", Ias Cut = "<<iasCut<<endl;
                //TFile *fBkg        = new TFile(Form("totalBkg" + folder + "/TotalBkg_metCutEq%.0f_ptCutEq%0.f_ECaloCutEq%.0f_IasCutEq0p%02.0f_",metCut,ptCut,ecaloCut,iasCut*100) + region +".root" ,"READ");
                //TString filename   = "signal" + folder + "/Signal_" + samples[i]  + Form("_metCutEq%.0f_ptCutEq%.0f_ECaloCutEq%.0f_IasCutEq0p%02.0f.root",metCut,ptCut,ecaloCut,iasCut*100);
                TFile *fBkg        = new TFile(Form("totalBkg" + folder + "/TotalBkg_metCutEq%.0f_ptGt%.0f_Le50000_ECaloCutEq%.0f_IasGt0p%02.0f_Le0p99_",metCut,ptCut,ecaloCut,iasCut*100) + region +".root" ,"READ");
                TString filename   = "signal" + folder + "/Signal_" + samples[i]  + Form("_metCutEq%.0f_ptGt%.0f_Le50000_ECaloCutEq%.0f_IasGt0p%02.0f_Le0p99.root",metCut,ptCut,ecaloCut,iasCut*100);
                TFile *fSignal     = new TFile(filename,"READ");
                TH1D  *hBkg        = 0;
                TH1D  *hLepton     = 0;
                TH1D  *hFake       = 0;
                TH1D  *hSignal     = 0;
                fBkg       -> GetObject("totalBkg",hBkg);
                fBkg       -> GetObject("leptonBkg",hLepton);
                fBkg       -> GetObject("fakeBkg",hFake);
                fSignal    -> GetObject(samples[i],hSignal);

                cout.precision(3);
                double nAll         = 0;
                double nAllErrorUp  = 0;
                double nAllErrorLow = 0;
                double n, nErrorUp, nErrorLow;

                TString eq = "=";

                int bin         = hBkg->GetXaxis()->FindBin(region);
                n = hBkg->IntegralAndError(bin,bin,nErrorUp);
                nErrorLow = nErrorUp;
                if(nErrorUp==0) eq = "<";
                else            eq = "=";
                nAll         = n ;
                nAllErrorUp  = nErrorUp;
                nAllErrorLow = nErrorLow;

                cout<<"nAll        = "<<nAll<<endl;
                cout<<"nAllErrorUp = "<<nAllErrorUp<<endl;
                cout<<"One Sided Upper 68% limit of bkg = "<<getOneSidedUpperLimit(nAll,0.6827)-nAll<<endl;

                cout<<"Total bkg                          = "<<nAll<<" + "<<nAllErrorUp<<" - "<<nAllErrorLow<<""<<endl;
                cout<<samples[i]<<" = "<<hSignal->GetBinContent(1)<<" +/- "<<hSignal->GetBinError(1)<<endl;
                cout<<"Statistics of signal = "<<pow(hSignal->GetBinContent(1),2)/pow(hSignal->GetBinError(1),2)<<endl;

                hBkgYield    -> SetBinContent(l+1,j+1,n);
                hBkgUnc      -> SetBinContent(l+1,j+1,nErrorUp/n);
                hSignalYield -> SetBinContent(l+1,j+1,hSignal->GetBinContent(1));

                double sOverDeltabUp    = hSignal->GetBinContent(1)/(getOneSidedUpperLimit(nAll,0.6827)-nAll);
                double sOverDeltabError = 0;
                sig1->SetBinContent(l+1,j+1,sOverDeltabUp);
                sig1->SetBinError(l+1,j+1,sOverDeltabError);


                double leptonStatError = hLepton -> GetBinError(bin);
                double fakeStatError   = hFake   -> GetBinError(bin);
                cout<<"leptonStatError  = "<<leptonStatError<<endl;
                cout<<"fakeStatError    = "<<fakeStatError<<endl;

                double leptonSysError = hLepton -> GetBinContent(bin)*1.0;  // 100% error
                double fakeSysError   = hFake   -> GetBinContent(bin)*0.2;  // 20% error
                cout<<"leptonSysError  = "<<leptonSysError<<endl;
                cout<<"fakeSysError    = "<<fakeSysError<<endl;

                // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                // Vary now signal x-sec and don't take the one given from theory -> model independent optimisation
                double sOverDeltabUpStatPlusSys          = 0;
                double sOverDeltabUpStatPlusSysError     = 0;
                double minExcludedXsec                   = 0;
                for(int k=0; k<1000; k++) {

                    sOverDeltabUpStatPlusSys            = k/sqrt( pow( getOneSidedUpperLimit(nAll,0.6827)-nAll ,2) + pow(fakeStatError ,2) + pow(leptonStatError ,2) + pow(fakeSysError ,2) + pow(leptonSysError ,2));


                    if(sOverDeltabUpStatPlusSys>5) {
                        cout<<"Dicovery possible !!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;

                        minExcludedXsec =1.*k/hSignal->GetBinContent(1)*xsec;
                        cout<<"minimal xsec = "<<minExcludedXsec<<endl;
                        cout<<"theory xsec  = "<<xsec<<endl;
                        break;

                    }



                }

                sig2->SetBinContent(l+1,j+1,minExcludedXsec);
                //	sig2->SetBinError(l+1,j+1,sOverDeltabUpStatPlusSysError);

                cout<<"s/(Delta b_stat)                          = "<<sOverDeltabUp<<" +/- "<<sOverDeltabError<<endl;
                cout<<"s/sqrt(Delta b_stat**2 + (Delta b_sys**2) = "<<sOverDeltabUpStatPlusSys<<" +/- "<<sOverDeltabUpStatPlusSysError<<endl;

                //fBkg->Close();
                //fSignal->Close();

                for(int k=0; k<1000; k++) {

                    sOverDeltabUp                       = k/sqrt( pow( getOneSidedUpperLimit(nAll,0.6827)-nAll ,2));

                    if(sOverDeltabUp>5) {
                        cout<<"Dicovery possible !!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;

                        minExcludedXsec =1.*k/hSignal->GetBinContent(1)*xsec;
                        cout<<"minimal xsec = "<<minExcludedXsec<<endl;
                        cout<<"theory xsec  = "<<xsec<<endl;
                        break;

                    }

                }


                sig1->SetBinContent(l+1,j+1,minExcludedXsec);

                cout<<"s/(Delta b_stat)                          = "<<sOverDeltabUp<<" +/- "<<sOverDeltabError<<endl;
                cout<<"s/sqrt(Delta b_stat**2 + (Delta b_sys**2) = "<<sOverDeltabUpStatPlusSys<<" +/- "<<sOverDeltabUpStatPlusSysError<<endl;

                fBkg->Close();
                fSignal->Close();

            }
        }
        TCanvas *c = new TCanvas(samples[i],samples[i],500,500);
        sig1->Draw("COLZ");
        c->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" +  "_SOverDeltaBStat.pdf", ecaloCut));

        TCanvas *c1 = new TCanvas(samples[i],samples[i],500,500);
        sig2->Draw("COLZ");
        //c1->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" + "_SOverDeltaBStatPlusSys_" + nlost+ ".pdf",ecaloCut));
        c1->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" + "_SOverDeltaBStatPlusSys.pdf",ecaloCut));

        TCanvas *c2 = new TCanvas(samples[i],samples[i],500,500);
        hBkgYield->Draw("COLZ");
        c2->SaveAs(Form("plots" + folder + "/BkgYield" + "_ECaloLe%.0f" + ".pdf",ecaloCut));

        TCanvas *c3 = new TCanvas(samples[i],samples[i],500,500);
        hBkgUnc->Draw("COLZ");
        c3->SaveAs(Form("plots" + folder + "/BkgUncertainty" + "_ECaloLe%.0f" + ".pdf",ecaloCut));

        TCanvas *c4 = new TCanvas(samples[i],samples[i],500,500);
        hSignalYield->Draw("COLZ");
        c4->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" + "_SignalYield.pdf",ecaloCut));



    }

    return 0;

}
void PDFSystCalculator_Powheg12Bin()
{
  typedef std::pair<double,double> pairOfDouble;
  set<pairOfDouble> uniqueEventsTrue;

  typedef std::pair<int,int> pairOfInt;
  set<pairOfInt> uniqueEventsReco;

  double mLow = 60.; // Z mass
  double mHigh = 120.; // Z mass
  double ptLow = 0.;
  double ptHigh = 4000.;

  //variable related PDF systematic uncertainty
  //double weightedSelectedEvents[18][53];
  //double weighted2SelectedEvents[18][53];
  double weightedSelectedEvents[12][53];
  double weighted2SelectedEvents[12][53];
  
  double events_central[nptBins] = {0.0};
  double events2_central[nptBins] = {0.0};
  double wa[nptBins] = {0.0};
  double wb[nptBins] = {0.0};
  double wplus[nptBins] = {0.0};
  double wminus[nptBins] = {0.0};

  char tmpName[30];


 // std::ofstream Fout;
 // TString FoutName = "Zpt_12BinWeightedSelectedEvents.txt";
 // Fout.open(FoutName);
 // Fout << fixed << setprecision(3);



  // read input root file
  TChain* tree = new TChain("tree");
  for(int i(1);i<95;i++)
  {
    //sprintf(tmpName,"DYJetsToLL_%d.root",i);
    //sprintf(tmpName,"/d1/scratch/sangilpark/Zpt/CMSSW_5_3_14_patch1/src/TerraNova/NtupleMaker/test/ZpT_Powheg_LowPU/DYJetsToLL_%d.root",i);
    sprintf(tmpName,"/d2/scratch/Storage_Area/ZpT8TeV_Powheg_LowPU/DYJetsToLL_%d.root",i);
    tree->AddFile(tmpName);  // Powheg Ntuple
  }

  TH1D* hPtMCTot = new TH1D("hPtMCTot", "", nptBins, xbins_pt); // no cut
  TH1D* hPtMCAcc = new TH1D("hPtMCAcc", "", nptBins, xbins_pt); // acc.cuts
  TH1D* hPtMCEff = new TH1D("hPtMCEff", "", nptBins, xbins_pt); // acc + all selection cuts


  //Hammid MC truth information pre FSR
  _TrackInfo true1PreFSR, true2PreFSR;
  tree->SetBranchAddress("true1PreFSR", &true1PreFSR);
  tree->SetBranchAddress("true2PreFSR", &true2PreFSR);

  float trueMassPreFSR, truePtPreFSR;
  tree->SetBranchAddress("trueMassPreFSR",	&trueMassPreFSR);
  tree->SetBranchAddress("truePtPreFSR",	&truePtPreFSR);

  vector<float> *weights_CT10;
  TBranch *b_weights_CT10;
  weights_CT10 = 0;
  tree->SetBranchAddress("weights_CT10", &weights_CT10, &b_weights_CT10);


  // Initialize variable
  for(int iBin(0); iBin<nptBins; iBin++)
  {
    {
      for(int j=0; j<53; j++)
      {
	weightedSelectedEvents[iBin][j] = 0;
	weighted2SelectedEvents[iBin][j] = 0;
//	cout << "initialized weightedSelectedEvents : " << weightedSelectedEvents[iBin][j] << endl;
      }
    }
  }

  // Print # of events
  cout << "Loop over the " << tree->GetEntries() << " entries ...\n";

  // Fill histogram
  for(int iEvt(0); iEvt<tree->GetEntries(); iEvt++)
  //for(int iEvt(0); iEvt<20; iEvt++)
  {
    if ( (iEvt % 100000)==0 ) cout << "event " << iEvt << endl;
    tree -> GetEntry(iEvt);

    //nocut start
    pairOfDouble trueMassPtPreFSR(trueMassPreFSR,truePtPreFSR);
    if( !uniqueEventsTrue.insert( trueMassPtPreFSR ).second ) continue;

    if (trueMassPreFSR <  mLow) continue;
    if (trueMassPreFSR > mHigh) continue;

    hPtMCTot -> Fill( truePtPreFSR );

    // acc cut start
    if (true1PreFSR.charge == -999) continue;
    if (true2PreFSR.charge == -999) continue;
    if (true1PreFSR.charge*true2PreFSR.charge>0) continue;

    if (trueMassPreFSR <  mLow) continue;
    if (trueMassPreFSR > mHigh) continue;
    if (true1PreFSR.pt < 20         || true2PreFSR.pt < 20        ) continue;
    if (fabs(true1PreFSR.eta) > 2.1 || fabs(true2PreFSR.eta) > 2.1) continue;
    hPtMCAcc -> Fill( truePtPreFSR );

    //cout << "trueMassPreFSR : " << trueMassPreFSR << endl;
    //cout << "true1PreFSR : " << true1PreFSR.pt << endl;
    //cout << "truePtPreFSR : " << truePtPreFSR << endl;
    //cout << "weights size : " << weights_CT10->size() << endl;


    // Check weight numbers are normal. 
    //cout << Form("iEvt : %d ============================= ",iEvt) << endl;
    //for(int i(0); i<weights_CT10->size(); i++)
    //{
    //  cout << "weights_CT10 : " << (*weights_CT10)[i] << endl;
    //}


    // Save weights each bin
    for(int iBin(0); iBin<nptBins; iBin++)
    {
      if(truePtPreFSR >= xbins_pt[iBin] && truePtPreFSR < xbins_pt[iBin+1])
      {
	for(int j=0; j<weights_CT10->size(); j++)
	{
	  weightedSelectedEvents[iBin][j] += (*weights_CT10)[j];
	  weighted2SelectedEvents[iBin][j] += (*weights_CT10)[j] * (*weights_CT10)[j];
	  //cout << Form("weightedSelectedEvents[%d][%d] : %f \t weighted2SelectedEvents[%d][%d] : %f \t weights_CT10[%d] : %f ",iBin,j,weightedSelectedEvents[iBin][j],iBin,j,weighted2SelectedEvents[iBin][j], j, (*weights_CT10)[j]) << endl;
	}
      }
    }
  }

  double weightedSelectedEventsCentTot=0;
  for(int iBin(0);iBin<nptBins;iBin++)
  {
     weightedSelectedEventsCentTot += weightedSelectedEvents[iBin][0];

      for (unsigned int j=0; j<weights_CT10->size(); ++j)
      {
	cout << fixed << setprecision(5);
	cout<<iBin<<"\t"<<j<<"\t"<<weightedSelectedEvents[iBin][j]<<endl;
      }
  }
    // Calculate PDF syst
  for(int iBin(0);iBin<nptBins;iBin++)
  {
    unsigned int nmembers = weights_CT10->size();
    unsigned int npairs = (nmembers-1)/2;
 
    events_central[iBin] = weightedSelectedEvents[iBin][0]/weightedSelectedEventsCentTot/(xbins_pt[iBin+1]-xbins_pt[iBin]);
    events2_central[iBin] = weighted2SelectedEvents[iBin][0];
    if(npairs>0){
      for (unsigned int j=0; j<npairs; ++j)
      {
	
	double weightedSelectedEventsXPlusTot=0;
	double weightedSelectedEventsXMinusTot=0;
	for(int iBin(0);iBin<nptBins;iBin++)
	{
	  weightedSelectedEventsXPlusTot += weightedSelectedEvents[iBin][2*j+1];
	  weightedSelectedEventsXMinusTot += weightedSelectedEvents[iBin][2*j+2];
	}

	cout << "events central : " << events_central[iBin] << endl;
	//wa[iBin] = weightedSelectedEvents[iBin][2*j+1]/events_central[iBin]-1.;
	//wb[iBin] = weightedSelectedEvents[iBin][2*j+2]/events_central[iBin]-1.;
	
	wa[iBin] = (weightedSelectedEvents[iBin][2*j+1]/weightedSelectedEventsXPlusTot/(xbins_pt[iBin+1]-xbins_pt[iBin]))/events_central[iBin]-1.;
	wb[iBin] = (weightedSelectedEvents[iBin][2*j+2]/weightedSelectedEventsXMinusTot/(xbins_pt[iBin+1]-xbins_pt[iBin]))/events_central[iBin]-1.;
	
	if (wa[iBin]>wb[iBin]){
	  if (wa[iBin]<0.) wa[iBin] = 0.;
	  if (wb[iBin]>0.) wb[iBin] = 0.;
	  wplus[iBin] += wa[iBin]*wa[iBin];
	  wminus[iBin] += wb[iBin]*wb[iBin];
	}else{
	  if (wb[iBin]<0.) wb[iBin] = 0.;
	  if (wa[iBin]>0.) wa[iBin] = 0.;
	  wplus[iBin] += wb[iBin]*wb[iBin];
	  wminus[iBin] += wa[iBin]*wa[iBin];
	}
      }
      if (wplus[iBin]>0) wplus[iBin] = sqrt(wplus[iBin]);
      if (wminus[iBin]>0) wminus[iBin] = sqrt(wminus[iBin]);
    }else{
      cout << "\tNO eigenvectors for uncertainty estimation" << endl;
    }
    //cout <<iBin+1<<" Bin: Relative uncertainty with respect to central member: +" << 100.*wplus[iBin] << " / -" <<  100.*wminus[iBin] << " [%]" << endl;
    cout <<iBin+1<<" + " << 100.*wplus[iBin] << " / -" <<  100.*wminus[iBin] << " [%]" << endl;
  }

  for(int i(0); i<nptBins; i++)
  {
    cout << i+1 << " bin Events number : " << hPtMCAcc->GetBinContent(i+1) << endl;
  }

  TFile* Hist_out = new TFile("ZptPreFSR_Powheg12Bin.root","recreate");

  hPtMCTot->Write();
  hPtMCAcc->Write();

  //Fout.close();
}
Exemple #26
0
void plot(TString var, TString varlatex, TString varname, Int_t nbins, Double_t vmin, Double_t vmax)
{
  cout<<"---- Processing - "<<var<<endl;
  cout<<"  -- Fill histograms"<<endl;
  TFile* ifBkg = new TFile(infnameBkg[isChannel]);
  TTree* ntBkg = (TTree*)ifBkg->Get(texNtuple[isChannel]);
  ntBkg->AddFriend("ntHlt");
  TFile* ifSgl = new TFile(infnameSgl[isChannel]);
  TTree* ntSgl = (TTree*)ifSgl->Get(texNtuple[isChannel]);
  ntSgl->AddFriend("ntHlt");
  ntSgl->AddFriend("ntHi");

  TH1D* hBkg = new TH1D(Form("hBkg_%s",varname.Data()),"",nbins,vmin,vmax);
  TH1D* hSgl = new TH1D(Form("hSgl_%s",varname.Data()),"",nbins,vmin,vmax);

  ntBkg->Project(Form("hBkg_%s",varname.Data()),var,Form("%s&&%s",selTriggerBkg[isChannel].Data(),selBkg[isChannel].Data()));
  ntSgl->Project(Form("hSgl_%s",varname.Data()),var,TCut(weight[isChannel])*Form("%s&&%s",selTriggerSgl[isChannel].Data(),selSgl[isChannel].Data()));

  cout<<"  -- Calculate normalization"<<endl;
  Double_t normBkg=0,normSgl=0;
  //normBkg = hBkg->GetEntries();
  //normSgl = hSgl->GetEntries();
  normBkg = hBkg->Integral(vmin,vmax);
  normSgl = hSgl->Integral(vmin,vmax);
  cout<<"     normBkg: "<<normBkg<<" ;   normSgl: "<<normSgl<<endl;

  cout<<"  -- Normalize histograms"<<endl;
  hBkg->Scale(1./normBkg);
  hSgl->Scale(1./normSgl); 

  cout<<"  -- Plot"<<endl;
  hBkg->SetXTitle(varlatex);
  hBkg->SetYTitle("#Probability");
  hBkg->SetTitleOffset(1.5,"Y");
  Double_t hisMax = (hBkg->GetMaximum()>hSgl->GetMaximum())?hBkg->GetMaximum():hSgl->GetMaximum();
  hBkg->SetMaximum(hisMax*1.2);

  hBkg->SetLineColor(kBlue+1);
  hBkg->SetFillStyle(1001);
  hBkg->SetFillColor(kBlue-9);
  hBkg->SetLineWidth(3);
  hBkg->SetStats(0);

  TH1D* hSglplot = new TH1D(Form("hSglplot_%s",varname.Data()),"",nbins,vmin,vmax);
  for(int ib=0;ib<nbins;ib++) hSglplot->SetBinContent(ib+1,hSgl->GetBinContent(ib+1));
  hSglplot->SetLineColor(kRed);
  hSglplot->SetFillStyle(3004);
  hSglplot->SetFillColor(kRed);
  hSglplot->SetLineWidth(3);
  hSglplot->SetStats(0);

  TCanvas* c = new TCanvas(Form("c_%s",varname.Data()),"",600,600);
  hBkg->Draw();
  hSglplot->Draw("same");

  cout<<"  -- Plot legends"<<endl;
  TLatex* tex = new TLatex(0.18,0.935,Form("5.02TeV %s",texPP[isChannel].Data()));
  tex->SetNDC();
  tex->SetTextFont(42);
  tex->SetTextSize(0.055);
  tex->Draw();
  TLatex* texp;
  texp = new TLatex(0.68,0.935,texDecay[isChannel]);
  texp->SetNDC();
  texp->SetTextFont(42);
  texp->SetTextSize(0.055);
  texp->Draw();
  TLegend* leg = new TLegend(0.56,0.70,0.86,0.86);
  leg->AddEntry(hBkg,"Background","f");
  leg->AddEntry(hSglplot,"Signal","f");
  leg->SetBorderSize(0);
  leg->SetFillStyle(0);
  leg->Draw("same");

  cout<<"  -- Save plots"<<endl;
  c->SaveAs(Form("plots/%s_%s/c_%s.pdf",texPP[isChannel].Data(),texNtuple[isChannel].Data(),varname.Data()));
  cout<<endl;
}
Exemple #27
0
void compareGen(std::string mcfile1, std::string mcfile2, 
		std::string var1, std::string var2="",
		std::string xtitle, 
		std::string output="test",
		std::string header="Z(#rightarrow ee)+#geq 1 jet",
		std::string mcName1="Data",
		std::string mcName2="Madgraph",
		float xmin=-9999.0, float xmax=-9999.0,
		bool logScale=true
		)
{
  
  setTDRStyle();
  gStyle->SetOptStat(0);

  TH1F* h1;
  TH1F* h2;

  char tempName[300];
  if(var2 ==  "" )var2=var1;
  
  // first get the histogram files
  TFile *fmc1 = TFile::Open(mcfile1.data());
  TFile *fmc2   = TFile::Open(mcfile2.data());

  h1  = (TH1F*)(fmc1->Get(var1.data()));
  h2    = (TH1F*)(fmc2->Get(var2.data()));

  TH1D* hscale =(TH1D*) h1->Clone("hscale");
  hscale->SetYTitle(Form("%s/%s",mcName1.data(),mcName2.data()));

  h1->GetXaxis()->SetNdivisions(5);
  h1->GetYaxis()->SetDecimals();

  h2->GetXaxis()->SetNdivisions(5);
  h2->GetYaxis()->SetDecimals();

  hscale->GetXaxis()->SetNdivisions(5);
  hscale->GetYaxis()->SetDecimals();


  h1->SetLineColor(2);
  h1->SetMarkerColor(2);
  h1->SetMarkerSize(1);
  h1->SetMarkerStyle(24);


  h2->SetLineColor(4);
  h2->SetMarkerColor(4);
  h2->SetMarkerSize(1);
  h2->SetMarkerStyle(21);

  // if normalizing to the same area, set the scale 

  int binLo = -1;
  int binHi = -1;
  int nbins = h1->GetNbinsX();
  if(xmin>-9999.0 && xmax>-9999.0)
    {

      binLo = h1->FindBin(xmin);
      binHi = h1->FindBin(xmax)-1;

    }

  else
    {
      binLo = 1;
      binHi = nbins;
      xmin = h1->GetBinLowEdge(1);
      xmax = h1->GetBinLowEdge(nbins+1);
    }


  float scale_mc = (float)h1->Integral(binLo,binHi)/(float)h2->Integral(binLo,binHi);
//   cout << "binLo = " << binLo << ", binHi = " << binHi << endl;
//    cout << "xmin = " << xmin << "xmax = " << xmax << endl;

//   h2->Sumw2();
// //   scale_mc = 1000.0*4.890*3048.0/2.29809910000000000e+07;
//   h2->Scale(scale_mc);

  cout << "h2 integral = " << h2->Integral() << endl;
  cout << "h1 integral = "   << h1->Integral() << endl;;

  // get the ratio
  double chi2 = 0;
  int realbin = 0;
  for(int i=1;i<= nbins;i++){

    double nmc=h2->GetBinContent(i);
    double ndata=h1->GetBinContent(i); 
    double nmcerr=h2->GetBinError(i);
    double ndataerr=h1->GetBinError(i); 
    
    if(nmc<0 || ndata<0)continue;    
    
    if(nmcerr==0 && ndataerr==0)continue;

    if(nmc==0 && ndata==0)continue;

    double chi2ndef = (nmc-ndata)*(nmc-ndata)/
      ( nmcerr*nmcerr+ ndataerr*ndataerr);
    chi2 += chi2ndef;
    realbin++;

    cout << "Bin " << i << " : " << ndata << ", " << nmc;
    cout << " " << chi2ndef << endl;


    // now calculate the ratio
    if(nmc==0 || nmcerr==0 || ndata==0 || ndataerr==0)
      {
	hscale->SetBinContent(i,-9999);
	hscale->SetBinError(i,1e-4);
	continue;
      }

    cout << "Bin " << i << " ratio = " << ndata/nmc << endl;
    hscale->SetBinContent(i,ndata/nmc);
    double err = 0;
    err=
      (ndata/nmc)*sqrt(pow(nmcerr/nmc,2)+pow(ndataerr/ndata,2));
    hscale->SetBinError(i,err);

  }

  for(int i=1;i<=hscale->GetNbinsX();i++)
    cout << i << ": " << hscale->GetBinContent(i) << endl;

  h1->GetXaxis()->SetRangeUser(xmin,xmax);
  h2->GetXaxis()->SetRangeUser(xmin,xmax);
  hscale->GetXaxis()->SetRangeUser(xmin,xmax);


  TCanvas* c1 = new TCanvas("c1","",700,1000);  
  c1->Divide(1,2,0.01,0);
  c1->cd(1);
  if(logScale)
    gPad->SetLogy(1);
  gPad->SetTopMargin(0.01);
  gPad->SetBottomMargin(0);
  gPad->SetRightMargin(0.04);

  
  float max_data  = h1->GetBinError(h1->GetMaximumBin()) + h1->GetMaximum();
  float max_mc    = h2->GetBinError(h2->GetMaximumBin()) + h2->GetMaximum();

  if(max_data > max_mc)
    {
      h1->Draw("e");
      h2->Draw("hesame");
    }
  else
    { h2->Draw("he");
      h1->Draw("esame");
    }


  float x1NDC = 0.725;
  float y1NDC = 0.615;
  float x2NDC = 0.928;
  float y2NDC = 0.951;

  TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);
  
  leg->SetHeader(header.data());
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.04);
  leg->SetBorderSize(0);
  leg->AddEntry(h1, mcName1.data());
  leg->AddEntry(h2, mcName2.data());
  leg->Draw("same");



  c1->cd(2);
  gStyle->SetStatW       (0.3);
  gStyle->SetStatH       (0.3);
  gStyle->SetStatX       (0.879447);
  gStyle->SetStatY       (0.939033);
  gStyle->SetStatFontSize(0.05);
  gStyle->SetStatBorderSize(0);
  gPad->SetRightMargin(0.04);
  gPad->SetTopMargin(0);
  gPad->SetBottomMargin(0.2);
  gPad->SetTickx();
  gStyle->SetOptFit(1);
  hscale->SetTitle("");
  hscale->GetXaxis()->SetTitle(xtitle.data());
//   hscale->SetMaximum(3.0);
//   hscale->SetMinimum(0.1);
  hscale->SetMaximum(2.0);
  hscale->SetMinimum(0.5);
  hscale->SetTitleOffset(1.2,"Y");
  hscale->Draw("e1");
  TF1* fline = new TF1("fline","pol1");
  TLine* l2 = new TLine(xmin,1.,xmax,1.);
  l2->SetLineColor(4);
  l2->SetLineStyle(3);
  fline->SetLineWidth(3);
  fline->SetLineColor(6);
  fline->SetNpx(2500);
//   hscale->Fit("fline","","");
  l2->Draw("same");


  string dirName = "compareGen";
  gSystem->mkdir(dirName.data());

  std::string filename;
  std::string psname = dirName + "/" + var1;
  if(output !="test")
    psname = dirName+ "/" + output;
  else
    psname = dirName+ "/" + var1;
  filename = psname + ".eps";
  c1->Print(filename.data());
  filename = psname + ".gif";
  c1->Print(filename.data());
  filename = psname + ".pdf";
  c1->Print(filename.data());
  //   c1->Close();
}
Exemple #28
0
void fitWm(const TString  outputDir,   // output directory
           const Double_t lumi,        // integrated luminosity (/fb)
	   const Double_t nsigma=0     // vary MET corrections by n-sigmas (nsigma=0 means nominal correction)
) {
  gBenchmark->Start("fitWm");

  //--------------------------------------------------------------------------------------------------------------
  // 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.1;

  // file format for output plots
  const TString format("png"); 

    
  // recoil correction
  RecoilCorrector recoilCorr("../Recoil/ZmmData/fits.root");//, (!) uncomment to perform corrections to recoil from W-MC/Z-MC
                             //"../Recoil/WmpMC/fits.root",
			     //"../Recoil/WmmMC/fits.root",
			     //"../Recoil/ZmmMC/fits.root");
   
  // NNLO boson pT k-factors
  TFile nnloCorrFile("/data/blue/ksung/EWKAna/8TeV/Utils/Ratio.root");
  TH1D *hNNLOCorr = (TH1D*)nnloCorrFile.Get("RpT_B");
  
  //
  // input ntuple file names
  //
  enum { eData, eWmunu, eEWK, eAntiData, eAntiWmunu, eAntiEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/data_select.root"); typev.push_back(eData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/wm_select.root");   typev.push_back(eWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/ewk_select.root");  typev.push_back(eEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Wmunu/ntuples/top_select.root");  typev.push_back(eEWK);
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/data_select.root"); typev.push_back(eAntiData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/wm_select.root");   typev.push_back(eAntiWmunu);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/ewk_select.root");  typev.push_back(eAntiEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/AntiWmunu/ntuples/top_select.root");  typev.push_back(eAntiEWK);


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  //
  // 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 *hWmunuMet  = new TH1D("hWmunuMet","", NBINS,0,METMAX); hWmunuMet->Sumw2();
  TH1D *hWmunuMetp = new TH1D("hWmunuMetp","",NBINS,0,METMAX); hWmunuMetp->Sumw2();
  TH1D *hWmunuMetm = new TH1D("hWmunuMetm","",NBINS,0,METMAX); hWmunuMetm->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();

  TH1D *hAntiDataMet   = new TH1D("hAntiDataMet","",  NBINS,0,METMAX); hAntiDataMet->Sumw2();
  TH1D *hAntiDataMetm  = new TH1D("hAntiDataMetm","", NBINS,0,METMAX); hAntiDataMetm->Sumw2();  
  TH1D *hAntiDataMetp  = new TH1D("hAntiDataMetp","", NBINS,0,METMAX); hAntiDataMetp->Sumw2();
  TH1D *hAntiWmunuMet  = new TH1D("hAntiWmunuMet","", NBINS,0,METMAX); hAntiWmunuMet->Sumw2();
  TH1D *hAntiWmunuMetp = new TH1D("hAntiWmunuMetp","",NBINS,0,METMAX); hAntiWmunuMetp->Sumw2();
  TH1D *hAntiWmunuMetm = new TH1D("hAntiWmunuMetm","",NBINS,0,METMAX); hAntiWmunuMetm->Sumw2();
  TH1D *hAntiEWKMet    = new TH1D("hAntiEWKMet", "",  NBINS,0,METMAX); hAntiEWKMet->Sumw2();
  TH1D *hAntiEWKMetp   = new TH1D("hAntiEWKMetp", "", NBINS,0,METMAX); hAntiEWKMetp->Sumw2();
  TH1D *hAntiEWKMetm   = new TH1D("hAntiEWKMetm", "", NBINS,0,METMAX); hAntiEWKMetm->Sumw2();

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  Float_t pfChIso, pfGamIso, pfNeuIso;
    
  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",   &genVPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);   // 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("pfChIso",  &pfChIso);
    intree->SetBranchAddress("pfGamIso", &pfGamIso);
    intree->SetBranchAddress("pfNeuIso", &pfNeuIso);
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(lep->Pt()        < PT_CUT)  continue;	
      if(fabs(lep->Eta()) > ETA_CUT) continue;
      
      if( (typev[ifile]==eAntiData || typev[ifile]==eAntiWmunu || typev[ifile]==eAntiEWK) &&
          (pfChIso+pfGamIso+pfNeuIso)>0.5*(lep->Pt()) ) 
	  continue;
      
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else if(typev[ifile]==eAntiData) {
        hAntiDataMet->Fill(met);
	if(q>0) { hAntiDataMetp->Fill(met); } 
	else    { hAntiDataMetm->Fill(met); }      
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
	
	if(typev[ifile]==eWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
	
          Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
	  
          hWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hWmunuMetp->Fill(corrMet,weight); } 
	  else    { hWmunuMetm->Fill(corrMet,weight); }
        }
	if(typev[ifile]==eAntiWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();//gRandom->Gaus(lep->Pt(),0.5);
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
          
	  Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
          
	  hAntiWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hAntiWmunuMetp->Fill(corrMet,weight); } 
	  else    { hAntiWmunuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
        if(typev[ifile]==eAntiEWK) {
          hAntiEWKMet->Fill(met,weight);
	  if(q>0) { hAntiEWKMetp->Fill(met,weight); }
	  else    { hAntiEWKMetm->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()/hWmunuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  RooRealVar nAntiSig("nAntiSig","nAntiSig",0.05*(hAntiDataMet->Integral()),0,hAntiDataMet->Integral());
  RooRealVar nAntiQCD("nAntiQCD","nAntiQCD",0.9*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar dewk("dewk","dewk",0.1,0,5) ;
  dewk.setVal(hAntiEWKMet->Integral()/hAntiWmunuMet->Integral());
  dewk.setConstant(kTRUE);
  RooFormulaVar nAntiEWK("nAntiEWK","nAntiEWK","dewk*nAntiSig",RooArgList(nAntiSig,dewk));
  
  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()/hWmunuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  RooRealVar nAntiSigp("nAntiSigp","nAntiSigp",0.05*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar nAntiQCDp("nAntiQCDp","nAntiQCDp",0.9*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar dewkp("dewkp","dewkp",0.1,0,5) ;
  dewkp.setVal(hAntiEWKMetp->Integral()/hAntiWmunuMetp->Integral());
  dewkp.setConstant(kTRUE);
  RooFormulaVar nAntiEWKp("nAntiEWKp","nAntiEWKp","dewkp*nAntiSigp",RooArgList(nAntiSigp,dewkp));
  
  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()/hWmunuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  RooRealVar nAntiSigm("nAntiSigm","nAntiSigm",0.05*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar nAntiQCDm("nAntiQCDm","nAntiQCDm",0.9*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar dewkm("dewkm","dewkm",0.1,0,5) ;
  dewkm.setVal(hAntiEWKMetm->Integral()/hAntiWmunuMetm->Integral());
  dewkm.setConstant(kTRUE);
  RooFormulaVar nAntiEWKm("nAntiEWKm","nAntiEWKm","dewkm*nAntiSigm",RooArgList(nAntiSigm,dewkm));

  //
  // Construct PDFs for fitting
  //
  RooRealVar pfmet("pfmet","pfmet",0,METMAX);
  pfmet.setBins(NBINS);
   
  // Signal PDFs
  RooDataHist wmunuMet ("wmunuMET", "wmunuMET", RooArgSet(pfmet),hWmunuMet);  RooHistPdf pdfWm ("wm", "wm", pfmet,wmunuMet, 1);
  RooDataHist wmunuMetp("wmunuMETp","wmunuMETp",RooArgSet(pfmet),hWmunuMetp); RooHistPdf pdfWmp("wmp","wmp",pfmet,wmunuMetp,1);
  RooDataHist wmunuMetm("wmunuMETm","wmunuMETm",RooArgSet(pfmet),hWmunuMetm); RooHistPdf pdfWmm("wmm","wmm",pfmet,wmunuMetm,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(pdfWm,pdfEWK,*(qcd.model)),   RooArgList(nSig,nEWK,nQCD));  
  RooAddPdf pdfMetp("pdfMetp","pdfMetp",RooArgList(pdfWmp,pdfEWKp,*(qcdp.model)),RooArgList(nSigp,nEWKp,nQCDp));
  RooAddPdf pdfMetm("pdfMetm","pdfMetm",RooArgList(pdfWmm,pdfEWKm,*(qcdm.model)),RooArgList(nSigm,nEWKm,nQCDm));
    
  
  // Anti-Signal PDFs
  RooDataHist awmunuMet ("awmunuMET", "awmunuMET", RooArgSet(pfmet),hAntiWmunuMet);  RooHistPdf apdfWm ("awm", "awm", pfmet,awmunuMet, 1);
  RooDataHist awmunuMetp("awmunuMETp","awmunuMETp",RooArgSet(pfmet),hAntiWmunuMetp); RooHistPdf apdfWmp("awmp","awmp",pfmet,awmunuMetp,1);
  RooDataHist awmunuMetm("awmunuMETm","awmunuMETm",RooArgSet(pfmet),hAntiWmunuMetm); RooHistPdf apdfWmm("awmm","awmm",pfmet,awmunuMetm,1); 
  
  // Anti-EWK+top PDFs
  RooDataHist aewkMet ("aewkMET", "aewkMET", RooArgSet(pfmet),hAntiEWKMet);  RooHistPdf apdfEWK ("aewk", "aewk", pfmet,aewkMet, 1);
  RooDataHist aewkMetp("aewkMETp","aewkMETp",RooArgSet(pfmet),hAntiEWKMetp); RooHistPdf apdfEWKp("aewkp","aewkp",pfmet,aewkMetp,1); 
  RooDataHist aewkMetm("aewkMETm","aewkMETm",RooArgSet(pfmet),hAntiEWKMetm); RooHistPdf apdfEWKm("aewkm","aewkm",pfmet,aewkMetm,1); 
  
  // Anti-QCD Pdfs
  CPepeModel1 aqcd("aqcd",pfmet,qcd.a1);
  CPepeModel1 aqcdp("aqcdp",pfmet,qcdp.a1);
  CPepeModel1 aqcdm("aqcdm",pfmet,qcdm.a1);
  
  // Anti-selection PDFs
  RooAddPdf apdfMet ("apdfMet", "apdfMet", RooArgList(apdfWm,apdfEWK,*(aqcd.model)),   RooArgList(nAntiSig,nAntiEWK,nAntiQCD));  
  RooAddPdf apdfMetp("apdfMetp","apdfMetp",RooArgList(apdfWmp,apdfEWKp,*(aqcdp.model)),RooArgList(nAntiSigp,nAntiEWKp,nAntiQCDp));
  RooAddPdf apdfMetm("apdfMetm","apdfMetm",RooArgList(apdfWmm,apdfEWKm,*(aqcdm.model)),RooArgList(nAntiSigm,nAntiEWKm,nAntiQCDm));
  
  // PDF for simultaneous fit
  RooCategory rooCat("rooCat","rooCat");
  rooCat.defineType("Select");
  rooCat.defineType("Anti");
  
  RooSimultaneous pdfTotal("pdfTotal","pdfTotal",rooCat);
  pdfTotal.addPdf(pdfMet, "Select");
  pdfTotal.addPdf(apdfMet,"Anti");
  
  RooSimultaneous pdfTotalp("pdfTotalp","pdfTotalp",rooCat);
  pdfTotalp.addPdf(pdfMetp, "Select");
  pdfTotalp.addPdf(apdfMetp,"Anti");
  
  RooSimultaneous pdfTotalm("pdfTotalm","pdfTotalm",rooCat);
  pdfTotalm.addPdf(pdfMetm, "Select");
  pdfTotalm.addPdf(apdfMetm,"Anti");
  
  //
  // Perform fits
  //

  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet), hDataMet);
  RooDataHist antiMet("antiMet", "antiMet", RooArgSet(pfmet), hAntiDataMet);
  RooDataHist dataTotal("dataTotal","dataTotal", RooArgList(pfmet), Index(rooCat),
                        Import("Select", dataMet),
                        Import("Anti",   antiMet));
  RooFitResult *fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp", "dataMetp", RooArgSet(pfmet), hDataMetp);
  RooDataHist antiMetp("antiMetp", "antiMetp", RooArgSet(pfmet), hAntiDataMetp);
  RooDataHist dataTotalp("dataTotalp","dataTotalp", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetp),
                         Import("Anti",   antiMetp));
  RooFitResult *fitResp = pdfTotalp.fitTo(dataTotalp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm", "dataMetm", RooArgSet(pfmet), hDataMetm);
  RooDataHist antiMetm("antiMetm", "antiMetm", RooArgSet(pfmet), hAntiDataMetm);
  RooDataHist dataTotalm("dataTotalm","dataTotalm", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetm),
                         Import("Anti",   antiMetm));
  RooFitResult *fitResm = pdfTotalm.fitTo(dataTotalm,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);
   
  TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram("hPdfAntiMet", pfmet));
  hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral());
  TH1D *hAntiMetDiff = makeDiffHist(hAntiDataMet,hPdfAntiMet,"hAntiMetDiff");
  hAntiMetDiff->SetMarkerStyle(kFullCircle);
  hAntiMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMetp = (TH1D*)(apdfMetp.createHistogram("hPdfAntiMetp", pfmet));
  hPdfAntiMetp->Scale((nAntiSigp.getVal()+nAntiEWKp.getVal()+nAntiQCDp.getVal())/hPdfAntiMetp->Integral());
  TH1D *hAntiMetpDiff = makeDiffHist(hAntiDataMetp,hPdfAntiMetp,"hAntiMetpDiff");
  hAntiMetpDiff->SetMarkerStyle(kFullCircle);
  hAntiMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfAntiMetm = (TH1D*)(apdfMetm.createHistogram("hPdfAntiMetm", pfmet));
  hPdfAntiMetm->Scale((nAntiSigm.getVal()+nAntiEWKm.getVal()+nAntiQCDm.getVal())/hPdfAntiMetm->Integral());
  TH1D *hAntiMetmDiff = makeDiffHist(hAntiDataMetm,hPdfAntiMetm,"hAntiMetmDiff");
  hAntiMetmDiff->SetMarkerStyle(kFullCircle); 
  hAntiMetmDiff->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.15);  
  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.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.100,"Y");
  TGaxis::SetMaxDigits(3);
  
  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} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);
  
  // 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 *wmframe = pfmet.frame(Bins(NBINS)); 
  wmframe->GetYaxis()->SetNdivisions(505);
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(wmframe,LineColor(linecolorW));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfWm)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",wmframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#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);

  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);
    
  RooPlot *awmframe = pfmet.frame(Bins(NBINS));    
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMet.plotOn(awmframe,LineColor(linecolorW));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),LineColor(linecolorEWK));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),LineColor(linecolorQCD));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfWm)),LineColor(linecolorW),LineStyle(2));
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMet->GetBinWidth(1));
  CPlot plotAntiMet("fitantimet",awmframe,"","",ylabel);
  plotAntiMet.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotAntiMet.SetYRange(0.1,1.1*(hAntiDataMet->GetMaximum())); 
  plotAntiMet.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetDiff("fitantimet","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotAntiMetDiff.SetYRange(-8,8);
  plotAntiMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMet.SetName("fitantimetlog");
  plotAntiMet.SetLogy();
  plotAntiMet.SetYRange(1e-3*(hAntiDataMet->GetMaximum()),10*(hAntiDataMet->GetMaximum()));
  plotAntiMet.Draw(c,kTRUE,format,1);
    
  //
  // W+ MET plot
  //
  RooPlot *wmpframe = pfmet.frame(Bins(NBINS));
  wmpframe->GetYaxis()->SetNdivisions(505);
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetp.plotOn(wmpframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,LineColor(linecolorW));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfEWKp,*(qcdp.model))),LineColor(linecolorEWK));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(*(qcdp.model))),LineColor(linecolorQCD));
  pdfMetp.plotOn(wmpframe,Components(RooArgSet(pdfWmp)),LineColor(linecolorW),LineStyle(2));
  dataMetp.plotOn(wmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetp->GetBinWidth(1));
  CPlot plotMetp("fitmetp",wmpframe,"","",ylabel);
  plotMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#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.SetYRange(0.1,4100);
  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);

  RooPlot *awmpframe = pfmet.frame(Bins(NBINS));    
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetp.plotOn(awmpframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,LineColor(linecolorW));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfEWKp,*(aqcdp.model))),LineColor(linecolorEWK));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(*(aqcdp.model))),LineColor(linecolorQCD));
  apdfMetp.plotOn(awmpframe,Components(RooArgSet(apdfWmp)),LineColor(linecolorW),LineStyle(2));
  antiMetp.plotOn(awmpframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMetp->GetBinWidth(1));
  CPlot plotAntiMetp("fitantimetp",awmpframe,"","",ylabel);
  plotAntiMetp.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetp.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetp.GetLegend()->AddEntry(hDummyW,"W^{+}#rightarrow#mu^{+}#nu","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetp.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetp.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetp.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetp.SetYRange(0.1,1.1*(hAntiDataMetp->GetMaximum()));
plotAntiMetp.SetYRange(0.1,1500);
  plotAntiMetp.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetpDiff("fitantimetp","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetpDiff.AddHist1D(hAntiMetpDiff,"EX0",ratioColor);
  plotAntiMetpDiff.SetYRange(-8,8);
  plotAntiMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetpDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetp.SetName("fitantimetplog");
  plotAntiMetp.SetLogy();
  plotAntiMetp.SetYRange(1e-3*(hAntiDataMetp->GetMaximum()),10*(hAntiDataMetp->GetMaximum()));
  plotAntiMetp.Draw(c,kTRUE,format,1);
  
  //
  // W- MET plot
  //
  RooPlot *wmmframe = pfmet.frame(Bins(NBINS)); 
  wmmframe->GetYaxis()->SetNdivisions(505);
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMetm.plotOn(wmmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,LineColor(linecolorW));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfEWKm,*(qcdm.model))),LineColor(linecolorEWK));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(*(qcdm.model))),LineColor(linecolorQCD));
  pdfMetm.plotOn(wmmframe,Components(RooArgSet(pdfWmm)),LineColor(linecolorW),LineStyle(2));
  dataMetm.plotOn(wmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotMetm("fitmetm",wmmframe,"","",ylabel);
  plotMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#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.SetYRange(0.1,4100);
  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);

  RooPlot *awmmframe = pfmet.frame(Bins(NBINS)); 
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMetm.plotOn(awmmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,LineColor(linecolorW));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfEWKm,*(aqcdm.model))),LineColor(linecolorEWK));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(*(aqcdm.model))),LineColor(linecolorQCD));
  apdfMetm.plotOn(awmmframe,Components(RooArgSet(apdfWmm)),LineColor(linecolorW),LineStyle(2));
  antiMetm.plotOn(awmmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMetm->GetBinWidth(1));
  CPlot plotAntiMetm("fitantimetm",awmmframe,"","",ylabel);
  plotAntiMetm.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMetm.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMetm.GetLegend()->AddEntry(hDummyW,"W^{-}#rightarrow#mu^{-}#bar{#nu}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMetm.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMetm.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMetm.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
//  plotAntiMetm.SetYRange(0.1,1.1*(hAntiDataMetm->GetMaximum()));
plotAntiMetm.SetYRange(0.1,1500);
  plotAntiMetm.Draw(c,kFALSE,format,1);

  CPlot plotAntiMetmDiff("fitantimetm","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetmDiff.AddHist1D(hAntiMetmDiff,"EX0",ratioColor);
  plotAntiMetmDiff.SetYRange(-8,8);
  plotAntiMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetmDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetm.SetName("fitantimetmlog");
  plotAntiMetm.SetLogy();
  plotAntiMetm.SetYRange(1e-3*(hAntiDataMetm->GetMaximum()),10*(hAntiDataMetm->GetMaximum()));
  plotAntiMetm.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/fitresWm.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/fitresWmp.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/fitresWmm.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("fitWm");
}
void analysisMacroSingleCanv(){
	TFile *withPDCAFile=new TFile("full_analysis_outputs/withPDCA/AnalysisResults.root","READ");
	TFile *noPDCAFile=new TFile("full_analysis_outputs/noPDCA/AnalysisResults.root","READ");

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


	TList *withPDCAProcessedNumberList;
	withPDCAFile->GetObject("MultSelection/cListMultSelection",withPDCAProcessedNumberList);
	TList *withPDCAList;
	withPDCAFile->GetObject("Upsilonfirst/UpsilonOutfirst",withPDCAList);

	TList *noPDCAProcessedNumberList;
	noPDCAFile->GetObject("MultSelection/cListMultSelection",noPDCAProcessedNumberList);
	TList *noPDCAList;
	noPDCAFile->GetObject("Upsilonfirst/UpsilonOutfirst",noPDCAList);


	TH1D *withPDCAProcessedHisto;
	withPDCAProcessedHisto=(TH1D*)withPDCAProcessedNumberList->FindObject("fHistEventCounter");
	TTree *withPDCATree;
	withPDCATree=(TTree*)withPDCAList->FindObject("MuonData");

	TH1D *noPDCAProcessedHisto;
	noPDCAProcessedHisto=(TH1D*)noPDCAProcessedNumberList->FindObject("fHistEventCounter");
	TTree *noPDCATree;
	noPDCATree=(TTree*)noPDCAList->FindObject("MuonData");

	Double_t processedWithPDCA=withPDCAProcessedHisto->GetBinContent(1);
	Double_t processedNoPDCA=noPDCAProcessedHisto->GetBinContent(1);
	Double_t normalizationFactor=processedWithPDCA/processedNoPDCA;

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

	TCanvas *canvHistos090=new TCanvas("canvHistos090","canvHistos090");
	canvHistos090->SetFrameBorderMode(0);
	TPad *Pad1=canvHistos090->cd();
	Pad1->Divide(1,2,0.01,0.0);
	Pad1->cd(1)->SetLogy();
	TH1D *histoInvariantMassWithPDCA090FullRap=new TH1D("Invariant mass 0%-90% 2.5<eta<4.0 PDCA","Invariant mass 0%-90% 2.5<eta<4.0 PDCA",250,2.5,15.);
	withPDCATree->Project("Invariant mass 0%-90% 2.5<eta<4.0 PDCA","dimuon_mass","enevt_centrality>0 && enevt_centrality<90 && dimuon_rapidity>-4. && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassWithPDCA090FullRap->ShowPeaks();
	histoInvariantMassWithPDCA090FullRap->Draw();
	outputHistoFile->cd();
	histoInvariantMassWithPDCA090FullRap->Write();

	TH1D *histoInvariantMassNoPDCA090FullRap=new TH1D("Invariant mass 0%-90% 2.5<eta<4.0","Invariant mass 0%-90% 2.5<eta<4.0",250,2.5,15.);
	noPDCATree->Project("Invariant mass 0%-90% 2.5<eta<4.0","dimuon_mass","enevt_centrality>0 && enevt_centrality<90 && dimuon_rapidity>-4. && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassNoPDCA090FullRap->ShowPeaks();
	histoInvariantMassNoPDCA090FullRap->SetLineColor(kRed);
	histoInvariantMassNoPDCA090FullRap->Draw("SAME");
	outputHistoFile->cd();
	histoInvariantMassNoPDCA090FullRap->Write();

	Pad1->cd(2);
	TH1D *histoInvariantMass090FullRapRatio=new TH1D("Ratio PDCA/NoPDCA 0%-90% 2.5<eta<4.0","Invariant mass 0%-90% 2.5<eta<4.0 PDCA",250,2.5,15.);
	histoInvariantMass090FullRapRatio->Add(histoInvariantMassWithPDCA090FullRap,histoInvariantMassNoPDCA090FullRap,1.,-1.*normalizationFactor);
	histoInvariantMass090FullRapRatio->Divide(histoInvariantMass090FullRapRatio,histoInvariantMassNoPDCA090FullRap);
	histoInvariantMass090FullRapRatio->SetLineColor(kBlack);
	histoInvariantMass090FullRapRatio->Draw();
	histoInvariantMass090FullRapRatio->Write();

///////////////////////////////////////////////////////////////////
	TCanvas *canvHistosAll=new TCanvas("canvHistosAll","canvHistosAll");
	canvHistosAll->SetFrameBorderMode(0);
	TPad *Pad2=canvHistosAll->cd();
	TH1D *histoInvariantMassWithPDCA=new TH1D("All entries PDCA","All entries PDCA",250,2.5,15.);
	withPDCATree->Project("All entries PDCA","dimuon_mass");
//  histoInvariantMassWithPDCA->ShowPeaks();
	histoInvariantMassWithPDCA->Draw();
	outputHistoFile->cd();
	histoInvariantMassWithPDCA->Write();

	TH1D *histoInvariantMassNoPDCA=new TH1D("All entries","All entries",250,2.5,15.);
	noPDCATree->Project("All entries","dimuon_mass");
//  histoInvariantMassNoPDCA->ShowPeaks();
	histoInvariantMassNoPDCA->SetLineColor(kRed);
	histoInvariantMassNoPDCA->Draw("SAME");  
	outputHistoFile->cd();
	histoInvariantMassNoPDCA->Write();  

///////////////////////////////////////////////////////////////////
	TCanvas *canvHistos020=new TCanvas("canvHistos020","canvHistos020");
	canvHistos020->SetFrameBorderMode(0);
	TPad *Pad3=canvHistos020->cd();
	Pad3->Divide(1,2,0.01,0.0);
	Pad3->cd(1)->SetLogy();
	TH1D *histoInvariantMassWithPDCA020FullRap=new TH1D("Invariant mass 0%-20% 2.5<eta<4.0 PDCA","Invariant mass 0%-20% 2.5<eta<4.0 PDCA",250,2.5,15.);
	withPDCATree->Project("Invariant mass 0%-20% 2.5<eta<4.0 PDCA","dimuon_mass","enevt_centrality>0 && enevt_centrality<20 && dimuon_rapidity>-4. && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassWithPDCA020FullRap->ShowPeaks();
	histoInvariantMassWithPDCA020FullRap->Draw();
	outputHistoFile->cd();
	histoInvariantMassWithPDCA020FullRap->Write();

	TH1D *histoInvariantMassNoPDCA020FullRap=new TH1D("Invariant mass 0%-20% 2.5<eta<4.0","Invariant mass 0%-20% 2.5<eta<4.0",250,2.5,15.);
	noPDCATree->Project("Invariant mass 0%-20% 2.5<eta<4.0","dimuon_mass","enevt_centrality>0 && enevt_centrality<20 && dimuon_rapidity>-4. && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassNoPDCA020FullRap->ShowPeaks();
	histoInvariantMassNoPDCA020FullRap->SetLineColor(kRed);
	histoInvariantMassNoPDCA020FullRap->Draw("SAME");  
	outputHistoFile->cd();
	histoInvariantMassNoPDCA020FullRap->Write();  

	Pad3->cd(2);
	TH1D *histoInvariantMass020FullRapRatio=new TH1D("Ratio PDCA/NoPDCA 0%-20% 2.5<eta<4.0","Invariant mass 0%-20% 2.5<eta<4.0 PDCA",250,2.5,15.);
	histoInvariantMass020FullRapRatio->Add(histoInvariantMassWithPDCA020FullRap,histoInvariantMassNoPDCA020FullRap,1.,-1.*normalizationFactor);
	histoInvariantMass020FullRapRatio->Divide(histoInvariantMass020FullRapRatio,histoInvariantMassNoPDCA020FullRap);
	histoInvariantMass020FullRapRatio->SetLineColor(kBlack);
	histoInvariantMass020FullRapRatio->Draw();
	outputHistoFile->cd();
	histoInvariantMass020FullRapRatio->Write();

///////////////////////////////////////////////////////////////////
	TCanvas *canvHistos2090=new TCanvas("canvHistos2090","canvHistos2090");
	canvHistos2090->SetFrameBorderMode(0);
	TPad *Pad4=canvHistos2090->cd();
	Pad4->Divide(1,2,0.01,0.0);
	Pad4->cd(1)->SetLogy();
	TH1D *histoInvariantMassWithPDCA2090FullRap=new TH1D("20%-90% 2.5<eta<4.0 PDCA","20%-90% 2.5<eta<4.0 PDCA",250,2.5,15.);
	withPDCATree->Project("20%-90% 2.5<eta<4.0 PDCA","dimuon_mass","enevt_centrality>20 && enevt_centrality<90 && dimuon_rapidity>-4. && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassWithPDCA2090FullRap->ShowPeaks();
	histoInvariantMassWithPDCA2090FullRap->Draw();
	outputHistoFile->cd();
	histoInvariantMassWithPDCA2090FullRap->Write();

	TH1D *histoInvariantMassNoPDCA2090FullRap=new TH1D("20%-90% 2.5<eta<4.0","20%-90% 2.5<eta<4.0",250,2.5,15.);
	noPDCATree->Project("20%-90% 2.5<eta<4.0","dimuon_mass","enevt_centrality>20 && enevt_centrality<90 && dimuon_rapidity>-4. && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassNoPDCA2090FullRap->ShowPeaks();
	histoInvariantMassNoPDCA2090FullRap->SetLineColor(kRed);
	histoInvariantMassNoPDCA2090FullRap->Draw("SAME");  
	outputHistoFile->cd();
	histoInvariantMassNoPDCA2090FullRap->Write();  

	Pad4->cd(2);
	TH1D *histoInvariantMass2090FullRapRatio=new TH1D("20%-90% 2.5<eta<4.0","20%-90% 2.5<eta<4.0 PDCA",250,2.5,15.);
	histoInvariantMass2090FullRapRatio->Add(histoInvariantMassWithPDCA2090FullRap,histoInvariantMassNoPDCA2090FullRap,1.,-1.*normalizationFactor);
	histoInvariantMass2090FullRapRatio->Divide(histoInvariantMass2090FullRapRatio,histoInvariantMassNoPDCA2090FullRap);
	histoInvariantMass2090FullRapRatio->SetLineColor(kBlack);
	histoInvariantMass2090FullRapRatio->Draw();
	outputHistoFile->cd();
	histoInvariantMass2090FullRapRatio->Write();

///////////////////////////////////////////////////////////////////
	TCanvas *canvHistos090r1=new TCanvas("canvHistos090r1","canvHistos090r1");
	canvHistos090r1->SetFrameBorderMode(0);
	TPad *Pad5=canvHistos090r1->cd();
	Pad5->Divide(1,2,0.01,0.0);
	Pad5->cd(1)->SetLogy();
	TH1D *histoInvariantMassWithPDCA090SecondRap=new TH1D("Invariant mass 0%-90% 2.5<eta<3.2 PDCA","Invariant mass 0%-90% 2.5<eta<3.2 PDCA",250,2.5,15.);
	withPDCATree->Project("Invariant mass 0%-90% 2.5<eta<3.2 PDCA","dimuon_mass","enevt_centrality>0 && enevt_centrality<90 && dimuon_rapidity>-3.2 && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassWithPDCA090SecondRap->ShowPeaks();
	histoInvariantMassWithPDCA090SecondRap->Draw();
	outputHistoFile->cd();
	histoInvariantMassWithPDCA090SecondRap->Write();

	TH1D *histoInvariantMassNoPDCA090SecondRap=new TH1D("Invariant mass 0%-90% 2.5<eta<3.2","Invariant mass 0%-90% 2.5<eta<3.2",250,2.5,15.);
	noPDCATree->Project("Invariant mass 0%-90% 2.5<eta<3.2","dimuon_mass","enevt_centrality>0 && enevt_centrality<90 && dimuon_rapidity>-3.2 && dimuon_rapidity<-2.5 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassNoPDCA090SecondRap->ShowPeaks();
	histoInvariantMassNoPDCA090SecondRap->SetLineColor(kRed);
	histoInvariantMassNoPDCA090SecondRap->Draw("SAME");
	outputHistoFile->cd();
	histoInvariantMassNoPDCA090SecondRap->Write();

	Pad5->cd(2);
	TH1D *histoInvariantMass090SecondRapRatio=new TH1D("Ratio PDCA/NoPDCA 0%-90% 2.5<eta<3.2","Invariant mass 0%-90% 2.5<eta<3.2 PDCA",250,2.5,15.);
	histoInvariantMass090SecondRapRatio->Add(histoInvariantMassWithPDCA090SecondRap,histoInvariantMassNoPDCA090SecondRap,1.,-1.*normalizationFactor);
	histoInvariantMass090SecondRapRatio->Divide(histoInvariantMass090SecondRapRatio,histoInvariantMassNoPDCA090SecondRap);
	histoInvariantMass090SecondRapRatio->SetLineColor(kBlack);
	histoInvariantMass090SecondRapRatio->Draw();
	outputHistoFile->cd();
	histoInvariantMass090SecondRapRatio->Write();

///////////////////////////////////////////////////////////////////
	TCanvas *canvHistos090r2=new TCanvas("canvHistos090r2","canvHistos090r2");
	canvHistos090r2->SetFrameBorderMode(0);
	TPad *Pad6=canvHistos090r2->cd();
	Pad6->Divide(1,2,0.01,0.0);
	Pad6->cd(1)->SetLogy();
	TH1D *histoInvariantMassWithPDCA090FirstRap=new TH1D("Invariant mass 0%-90% 3.2<eta<4.0 PDCA","Invariant mass 0%-90% 3.2<eta<4.0 PDCA",250,2.5,15.);
	withPDCATree->Project("Invariant mass 0%-90% 3.2<eta<4.0 PDCA","dimuon_mass","enevt_centrality>0 && enevt_centrality<90 && dimuon_rapidity>-4. && dimuon_rapidity<-3.2 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassWithPDCA090FirstRap->ShowPeaks();
	histoInvariantMassWithPDCA090FirstRap->Draw();
	outputHistoFile->cd();
	histoInvariantMassWithPDCA090FirstRap->Write();

	TH1D *histoInvariantMassNoPDCA090FirstRap=new TH1D("Invariant mass 0%-90% 3.2<eta<4.0","Invariant mass 0%-90% 3.2<eta<4.0",250,2.5,15.);
	noPDCATree->Project("Invariant mass 0%-90% 3.2<eta<4.0","dimuon_mass","enevt_centrality>0 && enevt_centrality<90 && dimuon_rapidity>-4. && dimuon_rapidity<-3.2 && highest_muon_transverse_momentum>0. && lowest_muon_transverse_momentum>0.");
//  histoInvariantMassNoPDCA090FirstRap->ShowPeaks();
	histoInvariantMassNoPDCA090FirstRap->SetLineColor(kRed);
	histoInvariantMassNoPDCA090FirstRap->Draw("SAME");
	outputHistoFile->cd();
	histoInvariantMassNoPDCA090FirstRap->Write();

	Pad6->cd(2);
	TH1D *histoInvariantMass090FirstRapRatio=new TH1D("Ratio PDCA/NoPDCA 0%-90% 3.2<eta<4.0","Invariant mass 0%-90% 3.2<eta<4.0 PDCA",250,2.5,15.);
	histoInvariantMass090FirstRapRatio->Add(histoInvariantMassWithPDCA090FirstRap,histoInvariantMassNoPDCA090FirstRap,1.,-1.*normalizationFactor);
	histoInvariantMass090FirstRapRatio->Divide(histoInvariantMass090FirstRapRatio,histoInvariantMassNoPDCA090FirstRap);
	histoInvariantMass090FirstRapRatio->SetLineColor(kBlack);
	histoInvariantMass090FirstRapRatio->Draw();
	outputHistoFile->cd();
	histoInvariantMass090FirstRapRatio->Write();
}
void AxEffSyst(TString modOCDBOutputPath, TString stdOCDBOutputPath){

  gStyle->SetOptStat(0);

  TFile *axEffModOCDBFile = new TFile(modOCDBOutputPath.Data(),"READONLY");
  TFile *axEffStdOCDBFile = new TFile(stdOCDBOutputPath.Data(),"READONLY");

  TH1D *axEffModOCDBHisto = 0x0;
  axEffModOCDBFile->GetObject("ratio1", axEffModOCDBHisto);
  axEffModOCDBHisto->SetLineColor(kBlue);
  axEffModOCDBHisto->SetLineWidth(2);
  axEffModOCDBHisto->SetTitle("A#times#epsilon");
  axEffModOCDBHisto->GetXaxis()->SetTitle("Rapidity");
  axEffModOCDBHisto->GetYaxis()->SetTitle("A#times#epsilon");

  TH1D *axEffStdOCDBHisto = 0x0;
  axEffStdOCDBFile->GetObject("ratio1", axEffStdOCDBHisto);
  axEffStdOCDBHisto->SetLineColor(kRed);
  axEffStdOCDBHisto->SetTitle("A#times#epsilon Std OCDB");
  axEffStdOCDBHisto->GetXaxis()->SetTitle("Rapidity");
  axEffStdOCDBHisto->GetYaxis()->SetTitle("A#times#epsilon");

  axEffModOCDBHisto->Sumw2(kTRUE);
  axEffStdOCDBHisto->Sumw2(kTRUE);

  TH1D *ratio = (TH1D*)axEffStdOCDBHisto->Clone();
  ratio->Sumw2(kTRUE);
  ratio->SetLineWidth(1);
  ratio->Add(axEffModOCDBHisto, -1.);
  ratio->Divide(axEffStdOCDBHisto);
  ratio->SetLineColor(kBlack);
  ratio->SetTitle("#frac{A#times#epsilon_{Std OCDB}-A#times#epsilon_{Mod OCDB}}{A#times#epsilon_{Std OCDB}}");
  ratio->GetXaxis()->SetTitle("Rapidity");
  ratio->GetYaxis()->SetTitle("Ratio (%)");

  for (Int_t iBinsRatio = 0; iBinsRatio <= ratio->GetNbinsX()+1; iBinsRatio++) {
    Double_t binContent = ratio->GetBinContent(iBinsRatio);
    cout<<binContent<<"->";
    if ( binContent<0. ) ratio->SetBinContent(iBinsRatio, -binContent*100.);
    else ratio->SetBinContent(iBinsRatio, binContent*100.);
    binContent = ratio->GetBinContent(iBinsRatio);
    cout<<binContent<<endl;
  }

  TCanvas *canv = new TCanvas("canv");
  canv->Divide(2,1);

  canv->cd(1);
  axEffModOCDBHisto->SetDirectory(0);
  axEffModOCDBHisto->Draw("E");
  axEffStdOCDBHisto->SetDirectory(0);
  axEffStdOCDBHisto->Draw("SAME E");

  canv->cd(2);
  ratio->GetYaxis()->SetRangeUser(-0.5,ratio->GetMaximum()*2);
  ratio->SetDirectory(0);
  ratio->Draw("E");

  axEffModOCDBFile->Close();
  axEffStdOCDBFile->Close();
}