Esempio n. 1
0
TH1D* GetFinalCorrFunc1D(int itrg, int jass)
{
                    TH1D* hbackground_phi = (TH1D*)GetRawBackground1D(itrg,jass);
		    TH1D* hcorrphi = (TH1D*)GetJetCorrFunc1D_ZYAM(itrg,jass);
                    hcorrphi->Multiply(hbackground_phi);
                    float max = hcorrphi->GetBinContent(hcorrphi->GetMaximumBin());
		    hcorrphi->SetAxisRange(ymin,max*1.5,"Y");
                    hcorrphi->SetYTitle("#frac{1}{N^{trg}}#frac{d^{2}N}{d#Delta#phi}");
                    return hcorrphi;
}
Esempio n. 2
0
void MCefficiencyCent(int isPbPb=0,TString inputmc="/data/wangj/MC2015/Dntuple/pp/revised/ntD_pp_Dzero_kpi_prompt/ntD_EvtBase_20160303_Dfinder_20160302_pp_Pythia8_prompt_D0_dPt0tkPt0p5_pthatweight.root", TString selmcgen="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))",TString selmcgenacceptance="((GisSignal==1||GisSignal==2)&&(Gy>-1&&Gy<1))&&abs(Gtk1eta)<2.0&&abs(Gtk2eta)<2.0&&Gtk1pt>2.0&&Gtk2pt>2.0", TString cut_recoonly="Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>2.0&&Dtrk2Pt>2.0&&Dtrk1PtErr/Dtrk1Pt<0.1&&Dtrk2PtErr/Dtrk2Pt<0.1&&abs(Dtrk1Eta)<2.0&&abs(Dtrk2Eta)<2.0&&Dtrk1Algo>3&&Dtrk1Algo<8&&(Dtrk1PixelHit+Dtrk1StripHit)>=11", TString cut="Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>2.0&&Dtrk2Pt>2.0&&(DsvpvDistance/DsvpvDisErr)>3.5&&(DlxyBS/DlxyBSErr)>1.5&&Dchi2cl>0.05&&Dalpha<0.12&&Dtrk1PtErr/Dtrk1Pt<0.1&&Dtrk2PtErr/Dtrk2Pt<0.1&&abs(Dtrk1Eta)<2.0&&abs(Dtrk2Eta)<2.0&&Dtrk1Algo>3&&Dtrk1Algo<8&&Dtrk2Algo>3&&Dtrk2Algo<8&&(Dtrk1PixelHit+Dtrk1StripHit)>=11&&(Dtrk1Chi2ndf/(Dtrk1nStripLayer+Dtrk1nPixelLayer)<0.15)&&(Dtrk2Chi2ndf/(Dtrk2nStripLayer+Dtrk2nPixelLayer)<0.15)",TString label="PP",TString outputfile="test", int useweight=1,Float_t centmin=0., Float_t centmax=100.)
{ 
 
  hiBinMin = centmin*2;
  hiBinMax = centmax*2;
  centMin = centmin;
  centMax = centmax;
  
  if(isPbPb==1)
    {
      selmcgen = selmcgen+Form("&&hiBin>=%f&&hiBin<=%f",hiBinMin,hiBinMax);
      selmcgenacceptance=selmcgenacceptance+Form("&&hiBin>=%f&&hiBin<=%f",hiBinMin,hiBinMax);
      cut_recoonly=cut_recoonly+Form("&&hiBin>=%f&&hiBin<=%f",hiBinMin,hiBinMax);
      cut=cut+Form("&&hiBin>=%f&&hiBin<=%f",hiBinMin,hiBinMax);
    }

     std::cout<<"selmcgen="<<selmcgen<<std::endl;
     std::cout<<"selmcgenacceptance="<<selmcgenacceptance<<std::endl;
     std::cout<<"cut_recoonly"<<cut_recoonly<<std::endl;
     std::cout<<"cut="<<cut<<std::endl;

   std::cout<<"option="<<useweight<<std::endl;
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetEndErrorSize(0);
  gStyle->SetMarkerStyle(20);
 
  TFile* infMC = new TFile(inputmc.Data());
  TTree* ntMC = (TTree*)infMC->Get("ntKp");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  TTree* ntSkim = (TTree*)infMC->Get("ntSkim");
  TTree* ntmvaTree = (TTree*)infMC->Get("mvaTree");
  TTree* ntHlt = (TTree*)infMC->Get("ntHlt");

  ntMC->AddFriend(ntmvaTree);
  ntMC->AddFriend(ntGen);
  ntMC->AddFriend(ntSkim);
  ntMC->AddFriend(ntHlt);

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

  // optimal weigths
  TCut weighpthat = "1";
  TCut weightGpt = "1";
  TCut weightBgenpt = "1";
  TCut weightHiBin = "1";
  if(useweight==0) {
    weightfunctiongen="1";
    weightfunctionreco="1";
    weighpthat = "pthatweight";
    weightGpt = "(pow(10,-0.094152+0.008102*Gpt+Gpt*Gpt*0.000171+Gpt*Gpt*Gpt*-0.000005+Gpt*Gpt*Gpt*Gpt*-0.000000+Gpt*Gpt*Gpt*Gpt*Gpt*0.000000))";
    weightBgenpt = "(pow(10,-0.094152+0.008102*Bgenpt+Bgenpt*Bgenpt*0.000171+Bgenpt*Bgenpt*Bgenpt*-0.000005+Bgenpt*Bgenpt*Bgenpt*Bgenpt*-0.000000+Bgenpt*Bgenpt*Bgenpt*Bgenpt*Bgenpt*0.000000))";
    }
  
  if(useweight==1) {
    weightfunctiongen="6.08582+hiBin*(-0.155739)+hiBin*hiBin*(0.00149946)+hiBin*hiBin*hiBin*(-6.41629e-06)+hiBin*hiBin*hiBin*hiBin*(1.02726e-08)";
    weightfunctionreco="6.08582+hiBin*(-0.155739)+hiBin*hiBin*(0.00149946)+hiBin*hiBin*hiBin*(-6.41629e-06)+hiBin*hiBin*hiBin*hiBin*(1.02726e-08)";
    weighpthat = "pthatweight";
    weightGpt = "(pow(10,-0.107832+0.010248*Gpt+Gpt*Gpt*0.000079+Gpt*Gpt*Gpt*-0.000003+Gpt*Gpt*Gpt*Gpt*-0.000000+Gpt*Gpt*Gpt*Gpt*Gpt*0.000000))";
    weightBgenpt = "(pow(10,-0.107832+0.010248*Bgenpt+Bgenpt*Bgenpt*0.000079+Bgenpt*Bgenpt*Bgenpt*-0.000003+Bgenpt*Bgenpt*Bgenpt*Bgenpt*-0.000000+Bgenpt*Bgenpt*Bgenpt*Bgenpt*Bgenpt*0.000000))";
    weightHiBin = "(6.08582+hiBin*(-0.155739)+hiBin*hiBin*(0.00149946)+hiBin*hiBin*hiBin*(-6.41629e-06)+hiBin*hiBin*hiBin*hiBin*(1.02726e-08))";
    }

  std::cout<<"fit function parameters="<<weightfunctiongen<<std::endl;

  TH1D* hPtMC = new TH1D("hPtMC","",_nBins,_ptBins);
  TH1D* hPtMCrecoonly = new TH1D("hPtMCrecoonly","",_nBins,_ptBins);
  TH1D* hPtGen = new TH1D("hPtGen","",_nBins,_ptBins);
  TH1D* hPtGenAcc = new TH1D("hPtGenAcc","",_nBins,_ptBins);
  TH1D* hPtGenAccWeighted = new TH1D("hPtGenAccWeighted","",_nBins,_ptBins);
  TH1D* hPthat = new TH1D("hPthat","",100,0,500);
  TH1D* hPthatweight = new TH1D("hPthatweight","",100,0,500);

  //ntMC->Project("hPtMC","hiBin",TCut(weightfunctionreco)*(TCut(cut.Data())&&"(Bgen==23333)"));
  ntMC->Project("hPtMC","hiBin",TCut(weighpthat)*TCut(weightBgenpt)*TCut(weightHiBin)*(TCut(cut.Data())&&"(Bgen==23333)"));
  divideBinWidth(hPtMC);
  //ntMC->Project("hPtMCrecoonly","hiBin",TCut(weightfunctionreco)*(TCut(cut_recoonly.Data())&&"(Bgen==23333)"));
  ntMC->Project("hPtMCrecoonly","hiBin",TCut(weighpthat)*TCut(weightBgenpt)*TCut(weightHiBin)*(TCut(cut_recoonly.Data())&&"(Bgen==23333)"));
  divideBinWidth(hPtMCrecoonly);
  //ntGen->Project("hPtGen","hiBin",(TCut(selmcgen.Data())));
  ntGen->Project("hPtGen","hiBin",TCut(weighpthat)*TCut(weightGpt)*(TCut(selmcgen.Data())));
  divideBinWidth(hPtGen);
  //ntGen->Project("hPtGenAcc","hiBin",(TCut(selmcgenacceptance.Data())));
  ntGen->Project("hPtGenAcc","hiBin",TCut(weighpthat)*TCut(weightGpt)*(TCut(selmcgenacceptance.Data())));
  divideBinWidth(hPtGenAcc);
  //ntGen->Project("hPtGenAccWeighted","hiBin",TCut(weightfunctiongen)*(TCut(selmcgenacceptance.Data())));
  ntGen->Project("hPtGenAccWeighted","hiBin",TCut(weighpthat)*TCut(weightGpt)*TCut(weightHiBin)*(TCut(selmcgenacceptance.Data())));
  divideBinWidth(hPtGenAccWeighted);

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

  hPtMC->Sumw2();
  hPtGenAcc->Sumw2();
  hPtMCrecoonly->Sumw2();
  //Acceptance
  TH1D* hEffAcc = (TH1D*)hPtGenAcc->Clone("hEffAcc");
  hEffAcc->Sumw2();
  hEffAcc->Divide(hEffAcc,hPtGen,1,1,"b");
  //Selection
  TH1D* hEffSelection = (TH1D*)hPtMC->Clone("hEffSelection");
  hEffSelection->Sumw2();
  hEffSelection->Divide(hEffSelection,hPtGenAccWeighted,1,1,"b");
  //Acc * Eff (one shot)
  TH1D* hEffReco = (TH1D*)hPtMCrecoonly->Clone("hEffReco");
  hEffReco->Sumw2();
  hEffReco->Divide(hEffReco,hPtGen,1,1,"b");
  //Acc * Eff
  TH1D* hEff = (TH1D*)hEffSelection->Clone("hEff");
  hEff->Sumw2();
  //hEff->Divide(hPtMC,hPtGen,1,1,"");
  hEff->Multiply(hEff,hEffAcc,1,1);

  TH2F* hemptyEff=new TH2F("hemptyEff","",50,_ptBins[0]-5.,_ptBins[_nBins]+5.,10.,0,1.0);  
  hemptyEff->GetXaxis()->CenterTitle();
  hemptyEff->GetYaxis()->CenterTitle();
  //hemptyEff->GetYaxis()->SetTitle("acceptance x #epsilon_{reco} x #epsilon_{sel} ");
  hemptyEff->GetYaxis()->SetTitle("#alpha x #epsilon");
  hemptyEff->GetXaxis()->SetTitle("Centrality");
  hemptyEff->GetXaxis()->SetTitleOffset(0.9);
  hemptyEff->GetYaxis()->SetTitleOffset(0.95);
  hemptyEff->GetXaxis()->SetTitleSize(0.05);
  hemptyEff->GetYaxis()->SetTitleSize(0.05);
  hemptyEff->GetXaxis()->SetTitleFont(42);
  hemptyEff->GetYaxis()->SetTitleFont(42);
  hemptyEff->GetXaxis()->SetLabelFont(42);
  hemptyEff->GetYaxis()->SetLabelFont(42);
  hemptyEff->GetXaxis()->SetLabelSize(0.035);
  hemptyEff->GetYaxis()->SetLabelSize(0.035);  
  hemptyEff->SetMaximum(2);
  hemptyEff->SetMinimum(0.);
  hemptyEff->Draw();

  TH2F* hemptyEffAcc=(TH2F*)hemptyEff->Clone("hemptyEffAcc");
  TH2F* hemptyEffReco=(TH2F*)hemptyEff->Clone("hemptyEffReco");
  TH2F* hemptyEffSelection=(TH2F*)hemptyEff->Clone("hemptyEffSelection");
 

  TCanvas*canvasEff=new TCanvas("canvasEff","canvasEff",1000.,500);
  canvasEff->Divide(2,1);
  canvasEff->cd(1);
  
  hemptyEffAcc->SetYTitle("#alpha");
  hemptyEffAcc->Draw();
  hEffAcc->Draw("same");
  canvasEff->cd(2);
  hemptyEff->Draw();
  hEff->Draw("same");
  canvasEff->SaveAs(Form("plotEff/canvasEff_study%s_Cent.pdf",Form(label.Data())));
  
  TH2F* hemptyPthat=new TH2F("hemptyPthat","",50,0.,500.,10,1e-5,1e9);  
  hemptyPthat->GetXaxis()->CenterTitle();
  hemptyPthat->GetYaxis()->CenterTitle();
  hemptyPthat->GetYaxis()->SetTitle("Entries");
  hemptyPthat->GetXaxis()->SetTitle("pthat");
  hemptyPthat->GetXaxis()->SetTitleOffset(0.9);
  hemptyPthat->GetYaxis()->SetTitleOffset(0.95);
  hemptyPthat->GetXaxis()->SetTitleSize(0.05);
  hemptyPthat->GetYaxis()->SetTitleSize(0.05);
  hemptyPthat->GetXaxis()->SetTitleFont(42);
  hemptyPthat->GetYaxis()->SetTitleFont(42);
  hemptyPthat->GetXaxis()->SetLabelFont(42);
  hemptyPthat->GetYaxis()->SetLabelFont(42);
  hemptyPthat->GetXaxis()->SetLabelSize(0.035);
  hemptyPthat->GetYaxis()->SetLabelSize(0.035);  
  hemptyPthat->SetMaximum(2);
  hemptyPthat->SetMinimum(0.);


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

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

  //### 1D histogram
  //hEff = hPtMC / hPtGen
  //hEffReco = hPtMCrecoonly / hPtGen
  //hEffAcc = hPtGenAcc / hPtGen
  //hEffSelection = hPtMC / hPtMCrecoonly
 
/*
  ntMC->Project("hPtMC","hiBin",TCut(weightfunctionreco)*(TCut(cut.Data())&&"(Bgen==23333)"));
  ntMC->Project("hPtMCrecoonly","hiBin",TCut(weightfunctionreco)*(TCut(cut_recoonly.Data())&&"(Bgen==23333)"));
  ntGen->Project("hPtGen","hiBin",TCut(weightfunctiongen)*(TCut(selmcgen.Data())));
  ntGen->Project("hPtGenAcc","hiBin",TCut(weightfunctiongen)*(TCut(selmcgenacceptance.Data())));
*/  
  TCanvas*canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  gPad->SetLogy();
  hemptySpectra->SetYTitle("Entries of hPtMC");
  hemptySpectra->Draw(); 
  hPtMC->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhPtMC_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  gPad->SetLogy();
  hemptySpectra->SetYTitle("Entries of hPtMCrecoonly");
  hemptySpectra->Draw(); 
  hPtMCrecoonly->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhPtMCrecoonly_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  gPad->SetLogy();
  hemptySpectra->SetYTitle("Entries of hPtGen");
  hemptySpectra->Draw(); 
  hPtGen->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhPtGen_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  gPad->SetLogy();
  hemptySpectra->SetYTitle("Entries of hPtGenAcc");
  hemptySpectra->Draw(); 
  hPtGenAcc->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhPtGenAcc_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  gPad->SetLogy(0);
  hemptyEff->SetYTitle("hPtMC / hPtGen");
  hemptyEff->Draw(); 
  hEff->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhEff_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  hemptyEff->SetYTitle("hPtMCrecoonly / hPtGen");
  hemptyEff->Draw(); 
  hEffReco->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhEffReco_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  hemptyEff->SetYTitle("hPtGenAcc / hPtGen");
  hemptyEff->Draw(); 
  hEffAcc->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhEffAcc_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  canvas1D=new TCanvas("canvas1D","",600,600);
  canvas1D->cd();
  hemptyEff->SetYTitle("hPtMC / hPtGenAcc");
  hemptyEff->Draw(); 
  hEffSelection->Draw("same");
  canvas1D->SaveAs(Form("plotEff/canvas1DhEffSelection_%s_Cent.pdf",Form(label.Data())));
  canvas1D->Clear();

  gStyle->SetPalette(55);
  TCanvas* canvas2D=new TCanvas("canvas2D","",600,600);

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

}
Esempio n. 3
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;
}
Esempio n. 4
0
int drawProgressivePtCut(std::string fileName) {

  // Create file on which histogram(s) can be saved.
  TFile *inFile = new TFile(fileName.c_str(), "READ");
  TH1D* ptProfile = ((TProfile*) inFile->Get( "pT bins" ))->ProjectionX(""); 
  TH1D* hcalProfile = ((TProfile*) inFile->Get( "hcal bins" ))->ProjectionX("");
  TH1D* gev3Profile = ((TProfile*) inFile->Get( "3gev bins" ))->ProjectionX("");
  TH1D* combProfile = (TH1D*) hcalProfile->Clone("hnew");
  combProfile->Multiply( gev3Profile );
  TH1D* hiEProfile = ((TProfile*) inFile->Get( "hie bins" ))->ProjectionX("");

  TCanvas *canv = new TCanvas("c1","c1",1200,1200);
  setTDRStyle();
  canv->UseCurrentStyle();
  ptProfile->GetYaxis()->SetTitleOffset(1.6);
  canv->SetSelected(canv);
  canv->cd();
  // Show histogram  
  TPad *pad1 = new TPad("pad1","",0,0,1,1);
  TPad *pad2 = new TPad("pad2","",0,0,1,1);
  TPad *pad3 = new TPad("pad3","",0,0,1,1);
  TPad *pad4 = new TPad("pad4","",0,0,1,1);
  TPad *pad5 = new TPad("pad5","",0,0,1,1);

  pad2->SetFillStyle(4000);
  pad3->SetFillStyle(4000);
  pad4->SetFillStyle(4000);
  pad5->SetFillStyle(4000);
  pad1->Draw();
  pad1->cd();
  ptProfile->GetXaxis()->SetTitle("p_{T} (GeV)");
  ptProfile->GetYaxis()->SetTitle("simulation for detected pt/full pt");
  ptProfile->GetYaxis()->SetTitleOffset(1.6);
  ptProfile->SetStats(0);
  ptProfile->GetXaxis()->SetMoreLogLabels();
  ptProfile->GetXaxis()->SetNoExponent();
  ptProfile->Draw();
  TLegend *leg = tdrLeg(0.4,0.73,0.6,0.93);
  leg->AddEntry( ptProfile, "All effects" );
  leg->AddEntry( combProfile, "HCal+3GeV" );
  leg->AddEntry( hcalProfile, "HCal" );
  leg->AddEntry( gev3Profile, "3GeV" );
  leg->AddEntry( hiEProfile, "High pt ineff." );
  leg->Draw();
  pythiaFinal();
  canv->Modified();
  pad1->UseCurrentStyle();
  ptProfile->SetMarkerStyle(kCircle);
  ptProfile->SetMaximum(1.04);
  ptProfile->SetMinimum(0.89);
  ptProfile->SetMarkerColor(7);
  pad1->Update();
  
  canv->cd();
  pad2->Draw();
  pad2->cd();
  combProfile->SetStats(0);
  combProfile->GetXaxis()->SetMoreLogLabels();
  combProfile->GetXaxis()->SetNoExponent();
  combProfile->Draw();
  pad2->UseCurrentStyle();
  combProfile->SetMaximum(1.04);
  combProfile->SetMinimum(0.89);
  combProfile->SetMarkerColor(3);
  pad2->Update();

  canv->cd();
  pad3->Draw();
  pad3->cd();
  hcalProfile->SetStats(0);
  hcalProfile->GetXaxis()->SetMoreLogLabels();
  hcalProfile->GetXaxis()->SetNoExponent();
  hcalProfile->Draw();
  pad3->UseCurrentStyle();
  hcalProfile->SetMaximum(1.04);
  hcalProfile->SetMinimum(0.89);
  hcalProfile->SetMarkerStyle(kStar);
  hcalProfile->SetMarkerColor(5);
  pad3->Update();
  
  canv->cd();
  pad4->Draw();
  pad4->cd();
  gev3Profile->SetStats(0);
  gev3Profile->GetXaxis()->SetMoreLogLabels();
  gev3Profile->GetXaxis()->SetNoExponent();
  gev3Profile->Draw();
  pad4->UseCurrentStyle();
  gev3Profile->SetMaximum(1.04);
  gev3Profile->SetMinimum(0.89);
  gev3Profile->SetMarkerStyle(kMultiply);
  pad4->Update();

  canv->cd();
  pad5->Draw();
  pad5->cd();
  hiEProfile->SetStats(0);
  hiEProfile->GetXaxis()->SetMoreLogLabels();
  hiEProfile->GetXaxis()->SetNoExponent();
  hiEProfile->Draw();
  pad5->UseCurrentStyle();
  hiEProfile->SetMaximum(1.04);
  hiEProfile->SetMinimum(0.89);
  hiEProfile->SetMarkerStyle(kCircle);
  hiEProfile->SetMarkerColor(kRed);
  pad5->Update();

  std::cout << "\nDouble click on the histogram window to quit.\n";
  
  // Done.
  return 0;
}
Esempio n. 5
0
void dataDrivenFromCR(TFile* fdata, TFile* fmc, TFile* fout, TString ddtype, TString gentype) {
  // Additional hists to consider: dataStats, MCstats, impurity

  TList* listOfDirs = fmc->GetListOfKeys();
  for (auto k : *listOfDirs) {
    TString srname = k->GetName();
    if (!srname.Contains("sr")) continue;
    if (srname.Contains("base") || srname.Contains("incl") || srname.Contains("sb")) continue;
    if (ddtype == "cr0b" && (srname.EndsWith("2") || srname.EndsWith("3"))) continue;

    TString crname = srname;
    crname.ReplaceAll("sr", ddtype);

    TString hname_data_CR = crname + "/h_metbins";
    TString hname_MC_SR = srname + "/h_metbins" + gentype;
    TString hname_MC_CR = crname + "/h_metbins";

    auto outdir = (TDirectory*) fout->mkdir(srname);

    auto hist_data_CR = (TH1D*) fdata->Get(hname_data_CR);
    auto hist_MC_CR = (TH1D*) fmc->Get(hname_MC_CR);
    auto hist_MC_SR = (TH1D*) fmc->Get(hname_MC_SR);

    if (!fmc->Get(hname_MC_CR)) {
      cout << "Couldn't find yield hist for " << hist_MC_CR << " in " << fmc->GetName() << "!!" << endl;
      cout << "This should not happend! Can not use data driven on this region! Use MC yields directly use TF from other SR!" << endl;
      continue;  // <-- actions to be added
    }
    if (!fmc->Get(hname_MC_SR)) {
      cout << "Couldn't find yield hist for " << hist_MC_SR << " in " << fmc->GetName() << ". Cannot define TF!" << endl;
      continue;  // <-- actions to be added
    }
    if (!fdata->Get(hname_data_CR)) {
      cout << "Couldn't find yield hist for " << hist_data_CR << " in " << fdata->GetName() << ". Please use yield from MC!" << endl;
      continue;  // <-- actions to be added
    }

    int lastbin = hist_data_CR->GetNbinsX();
    int extr_start_bin = lastbin; // the bin to start extrapolation, if == lastbin means no MET extrapolation is needed

    auto combineYieldsInExtrBins = [&](TH1D* hist) {
      double err = 0;
      double ylds = hist->IntegralAndError(extr_start_bin, -1, err);
      for (int ibin = extr_start_bin; ibin <= lastbin; ++ibin) {
        hist->SetBinContent(ibin, ylds);
        hist->SetBinError(ibin, err);
      }
    };

    if (useMetExtrapolation) {
      double yldCR(0.0), err(0.0);
      for (; extr_start_bin > 1; --extr_start_bin) {
        yldCR = hist_MC_CR->IntegralAndError(extr_start_bin, -1, err);
        double TFval = hist_MC_SR->GetBinContent(extr_start_bin) / yldCR;
        if (yldCR > extr_threshold && (TFval < extr_TFcap)) break;
      }
      // if (gentype == "_2lep" && (srname == "srE2" || srname == "srG2")) extr_start_bin = lastbin; // temporary hack for 2016
      // if (gentype == "_2lep" && (srname == "srH")) extr_start_bin = 1; // temporary hack for 2016
      if (extr_start_bin != lastbin) {
        cout << "Doing MET extrapolation for  " << crname << "  from bin " << lastbin << " (last bin) to bin " << extr_start_bin << "!" << endl;
        hist_data_CR->Clone("h_datayields_CR_raw")->Write();
        combineYieldsInExtrBins(hist_data_CR);
      }
    }

    TH1D* centralHist;

    auto crdir = (TDirectoryFile*) fmc->Get(crname);
    for (auto h : *(crdir->GetListOfKeys())) {
      TString hname = h->GetName();
      if (!hname.BeginsWith("h_metbins")) continue;
      // hardcode genclass skipping for now
      if (hname.Contains("_2lep") || hname.Contains("_1lep") || hname.Contains("_Znunu") || hname.Contains("_unclass")) continue;

      TString hnameSR = hname;
      hnameSR.ReplaceAll("h_metbins", "h_metbins" + gentype);

      // Not using fraction
      auto hist_MC_CR = (TH1D*) crdir->Get(hname)->Clone(hname+"_cr");
      auto hist_MC_SR = (TH1D*) fmc->Get(srname + "/" + hnameSR);

      if (!hist_MC_SR) {
        if (!hnameSR.Contains("cr2lTriggerSF"))
          cout << "Couldn't find yield hist for " << (srname + "/" + hnameSR) << " in " << fmc->GetName() << ". Use centralHist!" << endl;
        hist_MC_SR = (TH1D*) fmc->Get(hname_MC_SR)->Clone(hnameSR);
      }

      auto alphaHist = (TH1D*) hist_MC_SR->Clone(hname+"_alpha");
      if (useMetExtrapolation && extr_start_bin != lastbin) {
        // To take the MET distribution from the CR
        double cerr_SR = 0;
        double cyld_SR = alphaHist->IntegralAndError(extr_start_bin, -1, cerr_SR);
        double cyld_CR = hist_MC_CR->Integral(extr_start_bin, -1);
        for (int ibin = extr_start_bin; ibin <= lastbin; ++ibin) {
          double metfrac = hist_MC_CR->GetBinContent(ibin) / cyld_CR;
          alphaHist->SetBinContent(ibin, metfrac * cyld_SR);
          alphaHist->SetBinError(ibin, metfrac * cerr_SR);
        }
        combineYieldsInExtrBins(hist_MC_CR);
      }
      alphaHist->Divide(hist_MC_CR);

      for (int i = 1; i <= alphaHist->GetNbinsX(); ++i) {
        // zero out negative yields
        if (alphaHist->GetBinContent(i) < 0) {
          alphaHist->SetBinContent(i, 0);
          alphaHist->SetBinError(i, 0);
        }
      }

      outdir->cd();
      TH1D* hout = (TH1D*) alphaHist->Clone(hname);
      hout->Multiply(hist_data_CR);
      hout->Write();

      if (yearSeparateSyst && (hname.EndsWith("Up") || hname.EndsWith("Dn"))) {
        for (int i = 1; i < 4; ++i) {

          auto hcen_MC_CR = (TH1D*) fbkgs[i]->Get(crname+"/h_metbins");
          auto hcen_MC_SR = (TH1D*) fbkgs[i]->Get(srname+"/h_metbins"+gentype);
          auto hsys_MC_CR = (TH1D*) fbkgs[i]->Get(crname+"/"+hname);
          auto hsys_MC_SR = (TH1D*) fbkgs[i]->Get(srname+"/"+hnameSR);

          if (!hist_MC_SR) {
            if (!hnameSR.Contains("cr2lTriggerSF"))
              cout << "Couldn't find yield hist for " << (srname + "/" + hnameSR) << " in " << fmc->GetName() << ". Use centralHist!" << endl;
            hist_MC_SR = (TH1D*) fmc->Get(hname_MC_SR)->Clone(hnameSR);
          }

          auto alphaHist_yi = (TH1D*) fmc->Get(hname_MC_SR)->Clone(TString(hname).Insert(hname.Length()-2, Form("%d", 15+i)));
          auto h_MC_CR_yi = (TH1D*) fmc->Get(hname_MC_CR)->Clone(Form("%s_den_%d", hname.Data(), 15+i));
          if (hcen_MC_SR) alphaHist_yi->Add(hcen_MC_SR, -1);
          if (hsys_MC_SR) alphaHist_yi->Add(hsys_MC_SR);
          if (hcen_MC_CR) h_MC_CR_yi->Add(hcen_MC_CR, -1);
          if (hsys_MC_CR) h_MC_CR_yi->Add(hsys_MC_CR);

          if (useMetExtrapolation && extr_start_bin != lastbin) {
            // To take the MET distribution from the CR
            double cerr_SR = 0;
            double cyld_SR = alphaHist_yi->IntegralAndError(extr_start_bin, -1, cerr_SR);
            double cyld_CR = h_MC_CR_yi->Integral(extr_start_bin, -1);
            for (int ibin = extr_start_bin; ibin <= lastbin; ++ibin) {
              double metfrac = h_MC_CR_yi->GetBinContent(ibin) / cyld_CR;
              alphaHist_yi->SetBinContent(ibin, metfrac * cyld_SR);
              alphaHist_yi->SetBinError(ibin, metfrac * cerr_SR);
            }
            combineYieldsInExtrBins(h_MC_CR_yi);
          }
          alphaHist_yi->Divide(h_MC_CR_yi);

          for (int i = 1; i <= alphaHist_yi->GetNbinsX(); ++i) {
            // zero out negative yields
            if (alphaHist_yi->GetBinContent(i) < 0) {
              alphaHist_yi->SetBinContent(i, 0);
              alphaHist_yi->SetBinError(i, 0);
            }
          }
          outdir->cd();
          alphaHist_yi->Multiply(hist_data_CR);
          alphaHist_yi->Write();
        }
      }

      if (hname.EndsWith("h_metbins")) {
        centralHist = hout;
        // Store the central alpha hist and extr_start_bin for signal contamination
        alphaHist->Write("h_alphaHist");
        if (useMetExtrapolation && extr_start_bin < lastbin) {
          TH1D* h_extrstart = new TH1D("h_extrstart", "MET extrapolation start bin", 1, 0, 1);
          h_extrstart->SetBinContent(1, extr_start_bin);
          h_extrstart->Write();
        }
        if (doCRPurityError) {
          auto hist_MC_CR_pure = (TH1D*) fmc->Get(hname_MC_CR + gentype);
          auto hout_purityUp = (TH1D*) hout->Clone(hname+"_CRpurityUp");
          auto hout_purityDn = (TH1D*) hout->Clone(hname+"_CRpurityDn");
          if (useMetExtrapolation && extr_start_bin < lastbin)
            combineYieldsInExtrBins(hist_MC_CR_pure);
          for (int ibin = 1; ibin <= lastbin; ++ibin) {
            double crpurityerr = 0.5 * (hist_MC_CR->GetBinContent(ibin) - hist_MC_CR_pure->GetBinContent(ibin)) / hist_MC_CR->GetBinContent(ibin);
            hout_purityUp->SetBinContent(ibin, hout->GetBinContent(ibin) / ( 1 - crpurityerr));
            hout_purityDn->SetBinContent(ibin, hout->GetBinContent(ibin) / ( 1 + crpurityerr));
          }
          hout_purityUp->Write();
          hout_purityDn->Write();

          auto purityHist = (TH1D*) hist_MC_CR_pure->Clone("h_CRpurity");
          purityHist->Divide(hist_MC_CR_pure, hist_MC_CR, 1, 1, "B");
          purityHist->Write();
        }
      }
    }

    // Create alphaHist for dataStats
    auto h_dataStats = (TH1D*) centralHist->Clone("h_metbins_dataStats");
    auto h_MCStats = (TH1D*) centralHist->Clone("h_metbins_MCStats");
    for (int ibin = 1; ibin <= extr_start_bin; ++ibin) {
      // If not doing met extrapolation, extr_start_bin will equal to lastbin
      double data_error_thisbin = (hist_data_CR->GetBinContent(ibin) < 0.01)? 0 : hist_data_CR->GetBinError(ibin) / hist_data_CR->GetBinContent(ibin);
      h_dataStats->SetBinError(ibin, data_error_thisbin * h_dataStats->GetBinContent(ibin));

      double MC_SR_error_thisbin = (hist_MC_SR->GetBinContent(ibin) < 1e-5)? 0 : hist_MC_SR->GetBinError(ibin) / hist_MC_SR->GetBinContent(ibin);
      double MC_CR_error_thisbin = (hist_MC_CR->GetBinContent(ibin) < 1e-5)? 0 : hist_MC_CR->GetBinError(ibin) / hist_MC_CR->GetBinContent(ibin);
      double MC_error_thisbin = sqrt(MC_SR_error_thisbin*MC_SR_error_thisbin + MC_CR_error_thisbin*MC_CR_error_thisbin);

      h_MCStats->SetBinError(ibin, MC_error_thisbin * h_MCStats->GetBinContent(ibin));
    }
    for (int ibin = extr_start_bin+1; ibin <= lastbin; ++ibin) {
      // If doing met extrapolation, the bins following extr_start_bin for data and MC CR will be set to have 0 stat error
      // TODO: verify that this is the right thing to do
      h_dataStats->SetBinError(ibin, 0);
      double MC_SR_error_thisbin = (hist_MC_SR->GetBinContent(ibin) < 1e-5)? 0 : hist_MC_SR->GetBinError(ibin) / hist_MC_SR->GetBinContent(ibin);
      h_MCStats->SetBinError(ibin, MC_SR_error_thisbin * h_MCStats->GetBinContent(ibin));
    }

    h_dataStats->Write();
    h_MCStats->Write();

    hist_data_CR->Clone("h_datayields_CR")->Write();
    hist_MC_CR->Clone("h_MCyields_CR")->Write();
    hist_MC_SR->Clone("h_MCyields_SR")->Write();
  }
}
Esempio n. 6
0
TH1D *H1DConvolution( TH1D *htf , TH1D *htct , Double_t Cend , int tid) { 
      
   //------------>Both input histograms should have the same bin width<-----------------
   
   //Here you can apply an extra LPFiltering
   //if (Cend!=0) htct = LPFilter( htct , Cend ); 

   //Convolute (commutative)
   //C(t) = Int[ tct(x) transferfunction(t-x) dx ]
   Double_t bw = htct->GetBinCenter(2) - htct->GetBinCenter(1);
   //Double_t bw = htct->GetXaxis()->GetBinCenter(2) - htct->GetXaxis()->GetBinCenter(1);
   //TF1 *f1 = new TF1("f1","abs(sin(x)/x)*sqrt(x)",0,10);
   //   float r = f1->GetRandom();
    TString tftit, tfname;
    tftit.Form("hConv_%d_%d", tid, count);
    tfname.Form("conv_%d_%d", tid, count);
   TH1D *hConv = new TH1D(tftit,tfname,2*htct->GetNbinsX(),-htct->GetNbinsX()*bw,htct->GetNbinsX()*bw);
   
   
   //The convoluted response to the TCT signal is going to be another histogram sized similar to htct
   Int_t Ntf = htf->GetNbinsX() , Ntct = htct->GetNbinsX();
   
   //Create the reverse histogram of the transfer function
   TH1D *hinv = (TH1D *) htf->Clone(); hinv->Reset();
   for (Int_t j=1; j<= Ntf ; j++) hinv->SetBinContent( j , htf->GetBinContent(Ntf-j+1) );  
  // std::basic_string<char> t= std::to_string(tid);
   TH1D *hg = (TH1D *) htct->Clone(); 
   
   hinv->Draw();
   #if CTRLPLOT == 1
   gPad->Print( "hgcontrol.pdf[" ) ; gPad->Print( "hgcontrol.pdf" );
   #endif
   
   for ( Int_t i=1 ; i<=2*Ntct ; i++ ) { 
          
     //Create a shifted histogram version of the inverse
     hg->Reset();
     //for (Int_t j=TMath::Nint(-0.5*Ntf); j<= TMath::Nint(0.5*Ntf) ; j++) hg->SetBinContent( i-j , hinv->GetBinContent( j+TMath::Nint(0.5*Ntf) ) );  
     if ( i<=Ntf ) {
       //Histogram is shifting in from the left
       for (Int_t j=1; j<=i ; j++) hg->SetBinContent( j , hinv->GetBinContent( Ntf-i+j ) );
     } else {
       //Histogram is shifting out. Leaving from the right
       Int_t cont=1 ;
       for (Int_t j=i-Ntf+1; j<=2*Ntf ; j++) {
         hg->SetBinContent( j , hinv->GetBinContent( cont ) );
	 cont++;
       }
  
     }
     
     
     //Multiply f(tau)*g(t-tau)
     hg->Multiply( htct );
     
     //Double_t fxg = hg->Integral("width");
     Double_t fxg = hg->Integral();
     
     hConv->SetBinContent(i,fxg);
     
     #if CTRLPLOT==1
       THStack *hst=new THStack("hst","conv");
       hConv->SetLineColor(2);hConv->SetLineWidth(2);
       hst->Add(hg) ; hst->Add(hConv);
       hst->Draw("nostack");
       if   (i==2*Ntct) { 
         gPad->Print( "hgcontrol.pdf" )  ; gPad->Print( "hgcontrol.pdf]" ) ; 
       } else if (i%10==0)  gPad->Print( "hgcontrol.pdf" )  ;
     #endif

   }

   gStyle->SetOptStat(0);
   gStyle->SetHistLineWidth(2);
   //hConv->SetLineColor(kRed) ;htct->SetLineColor(kBlack) ;htf->SetLineColor(kBlue) ;
   
   THStack *hs = new THStack();
   //hs->Add(htf);
   hs->Add(htct);
   hs->Add(hConv);
   TCanvas *c1=new TCanvas(); c1->cd();
   hs->Draw("nostack");
   //hs->GetXaxis()->SetRangeUser(-2.,10.);
   hs->GetXaxis()->SetTitle("Time [ns]") ;

   c1->SetGrid(1);

   TLegend* legend = c1->BuildLegend();
   legend->Draw();
   c1->Update();
   //   NOPDF for the moment
//   c1->Print( "convolution.pdf" );
 //too many files...
/*
    tftit.Form("conv_%d_%d.root", tid, count);
   TFile *f=new TFile(tftit,"UPDATE");
   hConv->Write();
   //f->Close();
   delete f;

   #if EXE==1
      tftit.Form("convolution_%d_%d.root", tid, count);
      TFile *fout=new TFile(tftit,"UPDATE");
      htct->Write();
      hConv->Write();
      //fout->Close();
      delete fout;
   #endif
  count++; //for naming purposes
*/

   return hConv;  

}
Esempio n. 7
0
void recurseFile(TDirectory *indir, TDirectory *outdir,
                 double etawid, double etamid) {

  TDirectory *curdir = gDirectory;

  // Automatically go through the list of keys (directories)
  TList *keys = indir->GetListOfKeys();
  TListIter itkey(keys);
  TObject *key, *obj;
  TDirectory *dir;

  while ( (key = itkey.Next()) ) {

    if (_debug) cout << key->GetName() << endl << flush;
    obj = ((TKey*)key)->ReadObj(); assert(obj);
    dir = indir;

    // Found a subdirectory: copy it to output and go deeper
    if (obj->InheritsFrom("TDirectory")) {

      //assert(outdir->mkdir(obj->GetName()));
      outdir->mkdir(obj->GetName());
      assert(outdir->cd(obj->GetName()));
      TDirectory *outdir2 = outdir->GetDirectory(obj->GetName()); assert(outdir2);
      outdir2->cd();

      assert(indir->cd(obj->GetName()));
      TDirectory *indir2 = indir->GetDirectory(obj->GetName());
      indir2->cd();

      // Check if directory name contains information on eta bin width
      float etamin, etamax;
      if ( (sscanf(indir->GetName(),"Eta_%f-%f",&etamin,&etamax)==2)
           && (etamax>etamin) ) {
        etawid = 2.*(etamax-etamin);
        etamid = 0.5*(etamax+etamin);
        //cout << "Eta bin width: " << etawid << flush << endl;
      }

      recurseFile(indir2, outdir2, etawid, etamid);
      //outdir2->Write(); // does this speedup or slow down?
    } // inherits from TDirectory

    // Found a plot: normalize if hpt, then copy to output
    if (obj->InheritsFrom("TH1")) {

      outdir->cd();
      TObject *obj2 = obj->Clone(obj->GetName());

      // Normalize hpt and hselpt histograms
      // Same for hbpt
      if (string(obj2->GetName())=="hpt" ||
          string(obj2->GetName())=="hpt_evt" ||
          string(obj2->GetName())=="hpt_jet" ||
          string(obj2->GetName())=="hpt_pre" ||
          string(obj2->GetName())=="hpt0" ||
          string(obj2->GetName())=="hpt1" ||
          string(obj2->GetName())=="hpt2" ||
          string(obj2->GetName())=="hpt3" ||
          string(obj2->GetName())=="hpt_jk1" ||
          string(obj2->GetName())=="hpt_jk2" ||
          string(obj2->GetName())=="hpt_jk3" ||
          string(obj2->GetName())=="hpt_jk4" ||
          string(obj2->GetName())=="hpt_jk5" ||
          string(obj2->GetName())=="hpt_jk6" ||
          string(obj2->GetName())=="hpt_jk7" ||
          string(obj2->GetName())=="hpt_jk8" ||
          string(obj2->GetName())=="hpt_jk9" ||
          string(obj2->GetName())=="hpt_jk10" ||
          string(obj2->GetName())=="hpt_l1off" ||
          string(obj2->GetName())=="hpt_l1fast" ||
          string(obj2->GetName())=="hpt_plus" ||
          string(obj2->GetName())=="hpt_minus" ||
          string(obj2->GetName())=="hpt0_plus" ||
          string(obj2->GetName())=="hpt0_minus" ||
          string(obj2->GetName())=="hpt_noid" ||
          string(obj2->GetName())=="hpt_noevtid" ||
          string(obj2->GetName())=="hpt_nojetid" ||
          string(obj2->GetName())=="hpt_ak5calo" ||
          string(obj2->GetName())=="hpt_ak5pf" ||
          string(obj2->GetName())=="hpt_evt_ak5pf" ||
          string(obj2->GetName())=="hpt_jet_ak5pf" ||
          string(obj2->GetName())=="hselpt" ||
          string(obj2->GetName())=="hpt_r" ||
          string(obj2->GetName())=="hpt_g" ||
          string(obj2->GetName())=="hpt_gg" ||
          string(obj2->GetName())=="hpt_g0" ||
          string(obj2->GetName())=="hpt_g0tw" ||
          string(obj2->GetName())=="hdjmass" ||
          string(obj2->GetName())=="hdjmass0" ||
          string(obj2->GetName())=="hdjmass0_hgg") {

          cout << "." << flush;

        TH1D *hpt = (TH1D*)obj2;
        bool isgen = TString(obj2->GetName()).Contains("pt_g");
        bool isoth = (TString(obj2->GetName()).Contains("pt_no") ||
                      TString(obj2->GetName()).Contains("djmass") ||
                      TString(obj2->GetName()).Contains("hpt0") ||
                      TString(obj2->GetName()).Contains("l1off") ||
                      TString(obj2->GetName()).Contains("l1fast"));
        bool iscalo = (TString(obj2->GetName()).Contains("_ak5calo"));
        bool ispf5 = (TString(obj2->GetName()).Contains("_ak5pf"));
        bool ispre = (TString(obj2->GetName()).Contains("_pre"));
        bool isjk = (TString(obj2->GetName()).Contains("hpt_jk"));
        bool isjet = (TString(obj2->GetName()).Contains("hpt_jet"));

        TProfile *peff = (TProfile*)dir->Get("peff"); assert(peff);

        TH1D *hlumi = (TH1D*)dir->Get("hlumi"); assert(hlumi);
        TH1D *hlumi0 = (TH1D*)dir->Get("../jt450/hlumi"); assert(hlumi0);
        if (_jp_usetriglumi) {

          TH1D *hlumi_orig = (TH1D*)outdir->FindObject("hlumi_orig");
          if (!hlumi_orig) hlumi_orig = (TH1D*)hlumi->Clone("hlumi_orig");

          // regular prescaled luminosity
          TH1D *hlumi_new = (TH1D*)outdir->FindObject("hlumi");
          if (hlumi_new) hlumi = hlumi_new;
          string strg = dir->GetName();
          double lumi = triglumi[strg];
          for (int i = 1; i != hlumi->GetNbinsX()+1; ++i) {
            hlumi->SetBinContent(i, lumi);
          }

          // unprescaled luminosity
          double lumi0 = triglumi["jt450"];
          for (int i = 1; i != hlumi0->GetNbinsX()+1; ++i) {
            hlumi0->SetBinContent(i, lumi0);
          }
        } // _jp_usetriglumi

        // Test MC-based normalization for trigger efficiency
        bool dotrigeff = ((string(obj2->GetName())=="hpt") || isjk || isjet);
        TH1D *htrigeff = (TH1D*)outdir->FindObject("htrigeff");
        TH1D *htrigeffmc = (TH1D*)outdir->FindObject("htrigeffmc");
        TH1D *htrigeffsf = (TH1D*)outdir->FindObject("htrigeffsf");
        TH1D *hpt_notrigeff = 0;

        if (!htrigeff && _jp_dotrigeff) {

          TFile *fmc = new TFile("output-MC-1.root","READ");
          assert(fmc && !fmc->IsZombie());
          assert(fmc->cd("Standard"));
          fmc->cd("Standard");
          TDirectory *dmc0 = fmc->GetDirectory("Standard");
          //assert(gDirectory->cd(Form("Eta_%1.1f-%1.1f",
          //                 etamid-0.25*etawid,etamid+0.25*etawid)));
          //TDirectory *dmc = gDirectory;
          TDirectory *dmc = dmc0->GetDirectory(Form("Eta_%1.1f-%1.1f",
                                                    etamid-0.25*etawid,etamid+0.25*etawid));
          assert(dmc);
          dmc->cd();

          // Add MC truth based trigger efficiency
          if(!htrigeffmc && dmc->cd(dir->GetName())) {

            TDirectory *dir1 = dmc->GetDirectory(dir->GetName()); assert(dir1);
            TH1D *hpty = (TH1D*)dir1->Get("hpt"); assert(hpty);
            assert(dmc->cd("mc"));
            dmc->cd("mc");
            TDirectory *dir2 = dmc->GetDirectory("mc"); assert(dir2);
            TH1D *hptx = (TH1D*)dir2->Get(Form("hpt_%s",dir->GetName()));

            outdir->cd();
            if (hpty && hptx) htrigeffmc = (TH1D*)hpty->Clone("htrigeffmc");
            if (hpty && hptx) htrigeffmc->Divide(hpty,hptx,1,1,"B");
          }

          // Add data/MC scale factor for trigger efficiency
          if (_nh_dt && !htrigeffsf) {

            assert(dmc->cd(dir->GetName()));
            dmc->cd(dir->GetName());
            TDirectory *dirmc = dmc->GetDirectory(dir->GetName()); assert(dirmc);
            TProfile *pm = (TProfile*)dirmc->Get("ptrigefftp");
            TProfile *pd = (TProfile*)dir->Get("ptrigefftp");

            outdir->cd();
            if (pm && pd) htrigeffsf = pm->ProjectionX("htrigeffsf");
            if (pm && pd) htrigeffsf->Divide(pd,pm,1);
          }

          // Combine MC trigger efficiency and scalefactor
          if (htrigeffmc) { // not available for 'mc' directory
            outdir->cd();
            htrigeff = (TH1D*)htrigeffmc->Clone("htrigeff");
            assert(!_nh_dt || htrigeffsf);
            if (_nh_dt) htrigeff->Multiply(htrigeffsf);

            TH1D *h = (TH1D*)dir->Get("hpt");
            assert(outdir->FindObject("hpt_notrigeff")==0);
            outdir->cd();
            hpt_notrigeff = (TH1D*)h->Clone("hpt_notrigeff");
          }

          fmc->Close();
        } // dotrigeff


        // Scale data to account for time dependence
        bool dotimedep = ((string(obj2->GetName())=="hpt") || isjk || isjet);
        TH1D *htimedep = (TH1D*)outdir->FindObject("htimedep");
        TH1D *htimefit = (TH1D*)outdir->FindObject("htimefit");
        TH1D *hpt_notimedep = 0, *hpt_withtimedep = 0;
        double ktime = 1.;

        if (!htimedep) {

          TH1D *h = (TH1D*)dir->Get("hpt");
          TH1D *hsel = (TH1D*)dir->Get("hselpt");
          TH1D *hpre = (TH1D*)dir->Get("hpt_pre");
          //TH1D *hlumi0 = (TH1D*)dir->Get("../jt450/hlumi");

          // Fix luminosity for unprescaled trigger
          //string strg = dir->GetName();
          //double lum0 = triglumi["jt450"];
          //for (int i = 1; i != hlumi0->GetNbinsX()+1; ++i) {
          //hlumi0->SetBinContent(i, lum0);
          //}

          outdir->cd();
          if (h) hpt_notimedep = (TH1D*)h->Clone("hpt_notimedep");
          if (hpre && h) htimedep = (TH1D*)hpre->Clone("htimedep");
          if (hpre && h) htimedep->Divide(hpre,h);//,1,1,"B");

          // Figure out trigger luminosities
          double lumi = 0;
          if (hlumi) lumi = hlumi->GetBinContent(1);
          double lumi0 = 0;
          if (hlumi0) lumi0 = hlumi0->GetBinContent(1);
          if (htimedep && lumi && lumi0) {
            htimedep->Scale(lumi / lumi0);
          }

          // Find proper pT range and fit
          double minpt = 0.;
          double maxpt = 6500.;
          if (hsel) {
            for (int i = 1; i != hsel->GetNbinsX()+1; ++i) {
              if (hsel->GetBinContent(i)!=0 &&
                  hsel->GetBinLowEdge(i)>=_jp_xmin57) {
                if (minpt<20) minpt = hsel->GetBinLowEdge(i);
                maxpt = hsel->GetBinLowEdge(i+1);
              }
            }
          }
          TF1 *ftmp = new TF1("ftmp","[0]",minpt,maxpt);
          ftmp->SetParameter(0,1);
          if (htimedep && htimedep->Integral()>0) htimedep->Fit(ftmp,"QRN");

          if (htimedep && ftmp->GetParameter(0)>0)
            ktime = 1./ftmp->GetParameter(0);

          if (htimedep) {
            outdir->cd();
            htimefit = (TH1D*)hsel->Clone("htimefit");
            hpt_withtimedep = (TH1D*)h->Clone("hpt_withtimedep");

            for (int i = 1; i != htimefit->GetNbinsX()+1; ++i) {

              if (hsel->GetBinContent(i)!=0) {
                htimefit->SetBinContent(i, ftmp->GetParameter(0));
                htimefit->SetBinError(i, ftmp->GetParError(0));
              }

              // Calculate with time dependence here to add ktime fit error
              hpt_withtimedep->SetBinContent(i, hpt_notimedep->GetBinContent(i)
                                             * htimefit->GetBinContent(i));
              double err1 = hpt_notimedep->GetBinError(i)
                / hpt_notimedep->GetBinContent(i);
              double err2 = htimefit->GetBinError(i)
                / htimefit->GetBinContent(i);
              hpt_withtimedep->SetBinError(i, hpt_notimedep->GetBinContent(i)
                                           * sqrt(pow(err1,2) + pow(err2,2)));
            }
          }
        } // dotimedep


        if (!(hpt->GetNbinsX()==peff->GetNbinsX() || isoth || isgen) ||
            !(hpt->GetNbinsX()==hlumi->GetNbinsX() || isoth || isgen)) {
          cerr << "Hist " << hpt->GetName() << " " << dir->GetName()
               << " Nbins=" << hpt->GetNbinsX() << endl << flush;
          assert(hpt->GetNbinsX()==peff->GetNbinsX() || isoth);
          assert(hpt->GetNbinsX()==hlumi->GetNbinsX() || isoth);
        }

        for (int i = 1; i != hpt->GetNbinsX()+1; ++i) {

          // Normalization for bin width in y, pT
          double norm = hpt->GetBinWidth(i) * etawid;
          double trigeff = 1.;
          double pt = hpt->GetBinCenter(i);
          // Normalization for all the common efficiencies
          if (peff->GetBinContent(i)!=0 && !isgen)
            norm *= peff->GetBinContent(i);
          // Test MC-based normalization for trigger efficiency
          if (dotrigeff && htrigeff && _jp_dotrigeff) {
            if (htrigeff->GetBinContent(i)!=0) {
              trigeff = min(1.,max(0.,htrigeff->GetBinContent(i)));
              if (_jp_dotrigefflowptonly && pt>=114) trigeff = 1;
              norm *= trigeff;
            }
          }

          // Normalization for luminosity
          if (hlumi->GetBinContent(i)!=0 && !isoth && !isgen && !ispre)
            norm *= hlumi->GetBinContent(i);
          if (hlumi->GetBinContent(1)!=0 && isoth && !isgen && !ispre)
            norm *= hlumi->GetBinContent(1);
          if (hlumi0->GetBinContent(1)!=0 && !isoth && !isgen && ispre)
            norm *= hlumi0->GetBinContent(1);

          // Fix luminosity from .csv VTX to lumiCalc vdM
          if (!_nh_mc) norm *= _lumiscale;
          // Scale normalization for jackknife
          if (isjk) norm *= 0.9;

          if (_nh_mc && _jp_pthatbins) norm *= 1.;
          if (_nh_mc && !_jp_pthatbins) {
            norm /= 2500.; //(xsecw / (sumw * adhocw) ); // equals 2551.;
          }

          // Correct data for time-dependence
          double norm_notime = norm;
          if (dotimedep && htimedep && _jp_dotimedep) {
            norm *= ktime;
          }

          if (!(peff->GetBinContent(i)!=0||hpt->GetBinContent(i)==0 || isgen ||
                iscalo || ispf5 || isoth || hpt->GetBinCenter(i)<_jp_recopt
                || hpt->GetBinCenter(i)*cosh(etamid)>3500.)) {
            cerr << "Hist " << hpt->GetName() << " " << dir->GetName()
                 << " pt=" << hpt->GetBinCenter(i)
                 << " etamid = " << etamid << endl << flush;
            assert(peff->GetBinContent(i)!=0||hpt->GetBinContent(i)==0||isgen||
                   hpt->GetBinCenter(i)<_jp_recopt);
          }
          /*
          if (!(hlumi->GetBinContent(i)!=0 || hpt->GetBinContent(i)==0
                || isoth || isgen || hpt->GetBinCenter(i)<_jp_recopt)) {
            cerr << "Hist " << hpt->GetName() << " " << dir->GetName()
                 << " pt=" << hpt->GetBinCenter(i) << endl << flush;
            assert(hlumi->GetBinContent(i)!=0 || hpt->GetBinContent(i)==0
                   || isoth || hpt->GetBinCenter(i)<_jp_recopt);
          }
          */

          assert(norm!=0);
          hpt->SetBinContent(i, hpt->GetBinContent(i) / norm);
          hpt->SetBinError(i, hpt->GetBinError(i) / norm);
          if (hpt_notrigeff) {
            hpt_notrigeff->SetBinContent(i, hpt_notrigeff->GetBinContent(i)
                                         / norm * trigeff);
            hpt_notrigeff->SetBinError(i, hpt_notrigeff->GetBinError(i)
                                       / norm * trigeff);
          }
          if (hpt_notimedep) {
            hpt_notimedep->SetBinContent(i, hpt_notimedep->GetBinContent(i)
                                         / norm_notime);
            hpt_notimedep->SetBinError(i, hpt_notimedep->GetBinError(i)
                                       / norm_notime);
          }
          if (hpt_withtimedep) { // ktime already applied => use norm_notime
            hpt_withtimedep->SetBinContent(i, hpt_withtimedep->GetBinContent(i)
                                           / norm_notime);
            hpt_withtimedep->SetBinError(i, hpt_withtimedep->GetBinError(i)
                                         / norm_notime);
          }
        } // for i

      } // hpt

      dir->cd();
    } // inherits from TH1

  } // while key

  curdir->cd();
} // recurseFile
int CompareAllHistos(TString input1 = "../../QCD_ref.root", TString input2 = "../../QCD_filter.root", TString outdir="../plots/QCD/", TString leg1="no cut", TString leg2="jet filter", TString name="RelValQCD", bool MakeTotal=false) {
	
	gROOT->Reset();             
  //SetAtlasStyle();
  setTDRStyle();
  gStyle->SetPalette(1);
  gStyle->SetErrorX(0.5);
  gROOT->ProcessLine(".!mkdir -p "+outdir);
  gROOT->ProcessLine(".!mkdir -p "+outdir+"/pdf");
  gROOT->ProcessLine(".!mkdir -p "+outdir+"/png");

  
  TString Names[2] = { input1, input2};
  
//  TString outdir = "../plots/QCD/";
  const uint nFiles = 2;
  TFile * f[nFiles];  	

  
  std::stringstream indexes;
  for(uint iFile = 0; iFile < nFiles; iFile++)
  {
	indexes.str("");
  	indexes << Names[iFile];
  	
	std::string input_file=indexes.str();
	f[iFile] = TFile::Open(input_file.c_str());
	if(!f[iFile]) {
		std::cerr << "Error: file " << input_file << " could not be opened." << std::endl; 
    return 1;
	}
	else std::cout << "File " << input_file << " succesfully opened!" << std::endl;
  
  }
 // const uint nProfile12=8;
  const uint nProfile=4;
 // const uint nWP=3;
 // const uint n123=3;
  const uint n12=5;
  
  TString dirNames[1] = { "tauDifferenceAnalyzer"}; //"mmet_zh","mmmt_zh","mmme_zh","eett_zh","eemt_zh","eeet_zh","eeem_zh"};
 // TString profileNames_12[nProfile12] = {"pt_DM","eta_DM","vx_DM","phi_DM","pt_DMall","eta_DMall","vx_DMall","phi_DMall"};
  TString prefix_12 = "h_eff_id_";
  TString suffix_12[n12] = {"_DM","_DMall","_loose","_medium","_tight"};
  
  TString profileX[nProfile] = {"pt","eta","vx","phi"};
  const uint nTotal=nProfile*n12;
  //~ TString profile123_prefix="h_eff_id_";
  //~ TString profile123_WP[nWP]={"_loose","_medium","_tight"};
  //~ TString profile123_suffix[n123]={"","_2","_3"};
  //~ 
  TProfile* profileHist1[nTotal][nFiles];
// TProfile* profileHist2[nTotal][nFiles];
  
  //TProfile* profileHist[n123][nProfile*nWP][nFiles];
  //~ TProfile* profileHistB[nProfile*nWP][nFiles];
  //~ TProfile* profileHistC[nProfile*nWP][nFiles];
  //~ 
  
  
 // std::stringstream name;
 for(uint iFile = 0; iFile < nFiles; iFile++)
  {
	for(uint iSuff=0; iSuff < n12; iSuff++)
	{		
		for(uint iProf12=0; iProf12< nProfile; iProf12++)
		{
			profileHist1[iProf12+iSuff*nProfile][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+prefix_12+profileX[iProf12]+suffix_12[iSuff]));
		//	profileHist2[iProf12+iSuff*nProfile][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+prefix_12+profileX[iProf12]+suffix_12[iSuff]));
		}
	}
  }
  
  //~ for(uint iFile = 0; iFile < nFiles; iFile++)
  //~ {
	//~ for(uint iWP=0; iWP<nWP; iWP++)
		//~ {
			//~ for(uint iProf123=0; iProf123< nProfile; iProf123++)
			//~ {
				//~ for(uint i123=0; i123 < n123; i123++)
				//~ {
					//~ std::cout << dirNames[0]+"/"+profile123_prefix+profileX[iProf123]+profile123_WP[iWP]+profile123_suffix[i123] << std::endl;
					//~ profileHist[i123][iWP*nProfile+iProf123][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+profile123_prefix+profileX[iProf123]+profile123_WP[iWP]+profile123_suffix[i123]));
				//~ }
			//~ }
		//~ }
  //~ }
  
  
  
  
  TCanvas *c1 = new TCanvas("c1","",5,30,1024,1024);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);
  
  TPad* histPad = new TPad("histPad","histPad",0.01,0.25,0.99,0.99);
  histPad->SetBottomMargin(0.02);
  histPad->Draw();
  
  TPad* diffPad = new TPad("diffPad","diffPad",0.01,0.01,0.99,0.25);
  diffPad->SetBottomMargin(0.3);
  diffPad->SetTopMargin(0.0);
  diffPad->Draw();
  
  // plotting
  
	TString XTitle[4] = {"True P_{T} [GeV]","True #eta", "nVx","True #phi"};
   // c1->SetLogy();
	std::cout << "hej hola " << std::endl;
	for(uint iProf12=0; iProf12< nTotal; iProf12++)
	{
		 int title_id=iProf12%4;
		
		 if(title_id!=2){
			 profileHist1[iProf12][0]->Rebin(5);
			 profileHist1[iProf12][1]->Rebin(5);
		 }
	
		 TH1D* baseHist = (TH1D*)profileHist1[iProf12][0]->Clone();
		 TH1D* overHist = (TH1D*)profileHist1[iProf12][1]->Clone();
		 
		 if(MakeTotal && iProf12>7){ 
			 double binLow = baseHist->GetXaxis()->GetBinLowEdge(baseHist->GetXaxis()->GetFirst());
			 double binUp = baseHist->GetXaxis()->GetBinUpEdge(baseHist->GetXaxis()->GetLast());
			 int nBins = baseHist->GetXaxis()->GetNbins();
			 
			 TH1D* newBaseHist = new TH1D(TString(baseHist->GetName())+"TOT",baseHist->GetTitle(),nBins,binLow,binUp);
			 TH1D* newDMHist = new TH1D("newDMHist","",nBins,binLow,binUp);
			 TH1D* newOverHist = new TH1D(TString(overHist->GetName())+"TOTover",baseHist->GetTitle(),nBins,binLow,binUp);
			 TH1D* newDMHist2 = new TH1D("newDMHist2","",nBins,binLow,binUp);
			 
			 
			 for(int iBin=0; iBin <= baseHist->GetNbinsX(); iBin++)
			 {
				newBaseHist->SetBinContent(iBin,baseHist->GetBinContent(iBin));
				newBaseHist->SetBinError(iBin,baseHist->GetBinError(iBin));
				newDMHist->SetBinContent(iBin,profileHist1[title_id][0]->GetBinContent(iBin));
				newDMHist->SetBinError(iBin,profileHist1[title_id][0]->GetBinError(iBin));
				newOverHist->SetBinContent(iBin,overHist->GetBinContent(iBin));
				newOverHist->SetBinError(iBin,overHist->GetBinError(iBin));
				newDMHist2->SetBinContent(iBin,profileHist1[title_id][1]->GetBinContent(iBin));
				newDMHist2->SetBinError(iBin,profileHist1[title_id][1]->GetBinError(iBin));	
				
			 }
			 newBaseHist->Multiply(newDMHist);
			 newOverHist->Multiply(newDMHist2);
			 baseHist=newBaseHist;
			 overHist=newOverHist;
			 delete newDMHist;
			 delete newDMHist2;
		 }
	
		 if(title_id==0) baseHist->GetXaxis()->SetRangeUser(0,100);
		 baseHist->GetXaxis()->SetLabelOffset(0.1);		
		 baseHist->GetXaxis()->SetTitle(XTitle[title_id]);
		 baseHist->GetYaxis()->SetTitle("Fake rate");
		 baseHist->SetMarkerStyle(20);
		 baseHist->SetMarkerSize(2);
		 baseHist->SetLineWidth(2);
		 
		 overHist->SetMarkerColor(kRed);
		 overHist->SetMarkerStyle(25);
		 overHist->SetMarkerSize(2);
		 overHist->SetLineWidth(2);
		 overHist->SetLineStyle(2);
		 overHist->SetLineColor(kRed);
		
		 int binmax = baseHist->GetMaximumBin();
	     double max = 1.2*(baseHist->GetBinContent(binmax)+baseHist->GetBinError(binmax));
	     int binmax2 = overHist->GetMaximumBin();
	     double max2 = 1.2*(overHist->GetBinContent(binmax2)+overHist->GetBinError(binmax2));
	     max = max2 > max ? max2 : max;
	 
	     baseHist->SetMaximum(10.0);
	     baseHist->SetMinimum(1e-3);
	     
		 
		 histPad->cd();	
			 histPad->SetLogy();
		 baseHist->Draw();
		 overHist->Draw("same");	
		 
		TLegend* leg = new TLegend(0.8,0.80,0.9,0.9,NULL,"brNDC");
		leg->SetFillColor(0);
		leg->SetTextSize(0.035);
		leg->SetBorderSize(0);
		
		leg->AddEntry(baseHist, leg1, "lp");
		leg->AddEntry(overHist, leg2, "lp");
		
		leg->Draw();
		 //~ 
		 
    TString lumist="";
	TPaveText *ll = new TPaveText(0.15, 0.95, 0.95, 0.99, "NDC");
	ll->SetTextSize(0.03);
	ll->SetTextFont(62);
	ll->SetFillColor(0);
	ll->SetBorderSize(0);
	ll->SetMargin(0.01);
	ll->SetTextAlign(12); // align left
	TString text = name;
	ll->AddText(0.01,0.7,text);
	text = "#sqrt{s} = 13 TeV";
	text = text + lumist;
	//  ll->SetTextAlign(32); // align right
	ll->AddText(0.7, 0.5, text);
	ll->Draw("same");
	  
	
	c1->Update();
	
	TH1D* h_diff=(TH1D*)baseHist->Clone();
	h_diff->Divide(overHist);
	diffPad->cd();
	diffPad->SetGridy();
	diffPad->SetGridx();
	
	h_diff->GetYaxis()->SetLabelSize(0.1);
    h_diff->GetYaxis()->SetTitleOffset(0.55);
    h_diff->GetYaxis()->SetTitleSize(0.12);
    h_diff->GetYaxis()->SetTitle("Ratio");
    h_diff->GetXaxis()->SetLabelSize(0.12);
    h_diff->GetXaxis()->SetLabelOffset(0.01);
    h_diff->GetXaxis()->SetTitleSize(0.15);
	h_diff->GetYaxis()->SetNdivisions(509);
	h_diff->SetMinimum(0.9);
	h_diff->SetMaximum(1.1);
	
	h_diff->Draw("hist");
	c1->Print(outdir+"/pdf/"+profileHist1[iProf12][0]->GetName()+".pdf");
	c1->Print(outdir+"/png/"+profileHist1[iProf12][0]->GetName()+".png");
	
	
	}
  
  
	return 0;
}
Esempio n. 9
0
int CR5(){
  TH1::SetDefaultSumw2(true);
  if(pcp)cout<<"going to set inputs"<<endl;

  TFile* srFile = new TFile( "../SearchRegions/SearchRegions.root", "READ"); 
  TTree* srTree;  
  srFile->GetObject( "SearchRegions", srTree);
  
  Int_t ID = 0;
  Float_t nJetCut = 0.;
  Float_t mtCut = 0.;
  Float_t dphiCut = 0.;
  Float_t centralityCut = 0.;
  Float_t metCut = 0.;
  Float_t yCut = 0.;
  Float_t mlbCut = 0.;
  Float_t m3Cut = 0.;
  Float_t mt2wCut = 0.;
  Float_t drlblCut = 10.;

  srTree->SetBranchAddress( "ID", &ID);
  srTree->SetBranchAddress( "nJetCut", &nJetCut);
  srTree->SetBranchAddress( "mtCut", &mtCut);
  srTree->SetBranchAddress( "dphiCut", &dphiCut);
  srTree->SetBranchAddress( "centralityCut", &centralityCut);
  srTree->SetBranchAddress( "metCut", &metCut);
  srTree->SetBranchAddress( "yCut", &yCut);
  srTree->SetBranchAddress( "mlbCut", &mlbCut);
  srTree->SetBranchAddress( "m3Cut", &m3Cut);
  srTree->SetBranchAddress( "mt2wCut", &mt2wCut);

  const int NSamples = 5;  
  const int NLep = 3;

  TString sample[NSamples];
  sample[0] = "Data";
  sample[1] = "DiLep";
  sample[2] = "OneLep";
  sample[3] = "WJets";
  sample[4] = "Rare";

  bool lepFlag[NLep];
  TString lep[NLep];
  lep[0] = "El";
  lep[1] = "Mu";
  lep[2] = "ElAndMu";

  Int_t n1 = 0;
  Int_t n2 = 0;
  Int_t n3 = 0;
  Int_t n4 = 0;
    	
  Double_t integral = 0.;
  Double_t error = 0.;

  TString outFileName = "./CR5.root";
  TFile* outFile = new TFile( outFileName, "RECREATE");
  outFile->cd();

  Float_t SFLep[NLep] = {};

  Float_t SFLepErr[NLep] = {};

  Float_t peakSFPre = 0.; Float_t peakSFPreErr = 0.;
  Float_t peakSFPost = 0.; Float_t peakSFPostErr = 0.;
  
  Float_t tailData = 0.; Float_t tailDataErr = 0.;
  Float_t tailMC = 0.; Float_t tailMCErr = 0.;
  Float_t tailDiLep = 0.; Float_t tailDiLepErr = 0.;

  Float_t SF = 0.; Float_t SFErr = 0.;
  
  TTree* tree[3];  
  for(int ilep = 0; ilep < NLep; ilep++){
    tree[ilep] = new TTree( lep[ilep], lep[ilep]);

    tree[ilep]->Branch( "peakSFPre", &peakSFPre);
    tree[ilep]->Branch( "peakSFPreErr", &peakSFPreErr);
    tree[ilep]->Branch( "peakSFPost", &peakSFPost);
    tree[ilep]->Branch( "peakSFPostErr", &peakSFPostErr);

    tree[ilep]->Branch( "tailData", &tailData); 
    tree[ilep]->Branch( "tailDataErr", &tailDataErr);
    tree[ilep]->Branch( "tailMC", &tailMC);
    tree[ilep]->Branch( "tailMCErr", &tailMCErr);
    tree[ilep]->Branch( "tailDiLep", &tailDiLep);
    tree[ilep]->Branch( "tailDiLepErr", &tailDiLepErr);
    
    tree[ilep]->Branch( "SF", &SF);
    tree[ilep]->Branch( "SFErr", &SFErr);
  }

  TString histoName = "";

  TH1D* peakPreh[NSamples];
  TH1D* peakSFPreh[NSamples];

  TH1D* peakPosth[NSamples];
  TH1D* peakSFPosth[NSamples];

  TH1D* tailh[NSamples];

  TH1D* SFh = new TH1D( "SF", "SF", 1, 0., 1.);

  for ( int iSample = 0; iSample < NSamples; iSample++){
    peakPreh[iSample] = new TH1D( TString("peakPre") + sample[iSample], TString("peakPre") + sample[iSample], 1, 0., 1.);
    peakSFPreh[iSample] = new TH1D( TString("peakSFPre") + sample[iSample], TString("peakSFPre") + sample[iSample], 1, 0., 1.);

    peakPosth[iSample] = new TH1D( TString("peakPost") + sample[iSample], TString("peakPost") + sample[iSample], 1, 0., 1.);
    peakSFPosth[iSample] = new TH1D( TString("peakSFPost") + sample[iSample], TString("peakSFPost") + sample[iSample], 1, 0., 1.);

    tailh[iSample] = new TH1D( TString("tail") + sample[iSample], TString("tail") + sample[iSample], 1, 0., 1.);
  }

  int N = srTree->GetEntries();

  TFile* inFile[NSamples];
  TDirectory* inBaseDir[NSamples];
  TH1D* mth[NSamples];
  for (int iSample = 0; iSample < NSamples; iSample++){
    TString inFileName = "./MakeHistos/"+sample[iSample]+".root";
    inFile[iSample]= new TFile( inFileName,"READ");
  }

  TH1D* numh = new TH1D( "num", "num", 1, 0., 1.);      
  TH1D* denh = new TH1D( "den", "den", 1, 0., 1.);
  TH1D* tmph = new TH1D( "tmp", "tmp", 1, 0., 1.);

  for (int ilep = 0; ilep < NLep; ilep++){
    for ( int iSR = 0; iSR < N; iSR++){      
      srTree->GetEntry(iSR);
      
      TString baseDirName = ""; baseDirName += iSR;
      for (int iSample = 0; iSample < NSamples; iSample++)
	inBaseDir[iSample] =  inFile[iSample]->GetDirectory(baseDirName);
      
      ////////////////////
      // Cleaning
      ////////////////////
      
      numh->Clear(); numh->Reset();
      denh->Clear(); denh->Reset();
      tmph->Clear(); tmph->Reset();

      SFh->Clear(); SFh->Reset();
      for ( int iSample = 0; iSample < NSamples; iSample++){
	peakPreh[iSample]->Clear();   peakPreh[iSample]->Reset();
	peakSFPreh[iSample]->Clear(); peakSFPreh[iSample]->Reset();
	
	peakPosth[iSample]->Clear();   peakPosth[iSample]->Reset();
	peakSFPosth[iSample]->Clear(); peakSFPosth[iSample]->Reset();
	
	tailh[iSample]->Clear(); tailh[iSample]->Reset();
      }

      ////////////////////
      // Reading input
      ////////////////////

      for (int iSample = 0; iSample < NSamples; iSample++){
	TString histoName = lep[ilep]; histoName += "-SearchRegionPreIsoTrackVeto/Mt";
	inBaseDir[iSample]->GetObject(histoName, mth[iSample]);

	n1 = mth[0]->FindBin(50.);
	n2 = mth[0]->FindBin(79.99); 
	n3 = mth[0]->FindBin(mtCut);
	n4 = mth[0]->GetNbinsX() + 1;

	integral = mth[iSample]->IntegralAndError( n1, n2, error);
	peakPreh[iSample]->SetBinContent(1, integral);
	peakPreh[iSample]->SetBinError(1, error);
      }

      for (int iSample = 0; iSample < NSamples; iSample++){
	TString histoName = lep[ilep]; histoName += "-CR5/Mt";
	inBaseDir[iSample]->GetObject(histoName, mth[iSample]);

	n1 = mth[0]->FindBin(50.);
	n2 = mth[0]->FindBin(79.99); 
	n3 = mth[0]->FindBin(mtCut);
	n4 = mth[0]->GetNbinsX() + 1;

	integral = mth[iSample]->IntegralAndError( n1, n2, error);
	peakPosth[iSample]->SetBinContent(1, integral);
	peakPosth[iSample]->SetBinError(1, error);
	
	integral = mth[iSample]->IntegralAndError( n3, n4, error);
	tailh[iSample]->SetBinContent(1, integral);
	tailh[iSample]->SetBinError(1, error);
      }

      ///////////////////////////////////////////
      // Mt peak weight
      ///////////////////////////////////////////

      // peak SF Pre

      peakSFPreh[1]->Add(peakPreh[0]);
      peakSFPreh[1]->Add(peakPreh[3], -1.); 
      peakSFPreh[1]->Add(peakPreh[4], -1.);

      denh->Clear(); denh->Reset();
      denh->Add(peakPreh[1]);
      denh->Add(peakPreh[2]);

      peakSFPreh[1]->Divide(denh);

      peakSFPre = peakSFPreh[1]->GetBinContent(1);
      peakSFPreErr = peakSFPreh[1]->GetBinError(1);

      peakSFPreh[2]->SetBinContent( 1, peakSFPre);
      peakSFPreh[2]->SetBinError( 1, peakSFPreErr);

      // peak SF Post

      peakSFPosth[2]->Add(peakPosth[0]);
      tmph->Clear(); tmph->Reset();
      peakSFPosth[2]->Add(peakPosth[3], -1.);
      peakSFPosth[2]->Add(peakPosth[4], -1.);

      
      tmph->Add(peakPosth[1]);
      tmph->Multiply(peakSFPreh[1]);
      tmph->Add(peakPosth[2]);
      peakSFPosth[2]->Divide(tmph);
      
      peakSFPost = peakSFPosth[2]->GetBinContent(1);
      peakSFPostErr = peakSFPosth[2]->GetBinError(1);

      ///////////////////////////////////////////
      // Tail and SF
      ///////////////////////////////////////////

      tailData = tailh[0]->GetBinContent(1);
      tailDataErr = tailh[0]->GetBinError(1);
      
      tmph->Clear(); tmph->Reset();
      denh->Clear(); denh->Reset();
      denh->Add(tailh[1]);
      denh->Multiply(peakSFPreh[1]);
      tmph->Add(tailh[2]);
      tmph->Multiply(peakSFPosth[2]);
      denh->Add(tmph);
      denh->Add(tailh[3]);
      denh->Add(tailh[4]);
      tailMC = denh->GetBinContent(1);
      tailMCErr = denh->GetBinError(1);
      
      tailDiLep = tailh[2]->GetBinContent(1);
      tailDiLepErr = tailh[2]->GetBinError(1);

      SFh->Add(tailh[0]);
      SFh->Divide(denh);
      SF = SFh->GetBinContent(1);
      SFErr = SFh->GetBinError(1);

      ///////////////////////////////////////////////
      // Fill outTree
      ///////////////////////////////////////////////

      tree[ilep]->Fill();
      
      //////////////////////////////////
      // Pritn some output
      //////////////////////////////////

      cout<<ID<<"\t";
      cout<<iSR<<" "<<ilep<<"\t";
      cout<<peakSFPre<<"+-"<<peakSFPreErr<<"\t";
      cout<<peakSFPost<<"+-"<<peakSFPostErr<<"\t";
      cout<<SF<<"+-"<<SFErr<<endl;      
    }      
  }

  for (int iSample = 0; iSample < NSamples; iSample++)
    inFile[iSample]->Close();

  for (int ilep = 0; ilep < NLep; ilep++){
    outFile->cd();
    tree[ilep]->Write();
  }

  return 0;
}