Exemplo n.º 1
0
void RecoverCSVHisto (TH1D *his, TH1D *CSV1, TH1D *CSV2){

  for(int ireg=0;ireg<20;ireg++){
    TH1D *htempreg = new TH1D ("","",20,0.,1.);       
    for(int ibin=1;ibin<=20;ibin++){
      htempreg->SetBinContent(ibin,his->GetBinContent(ibin+20*ireg));	  
      htempreg->SetBinError(ibin,his->GetBinError(ibin+20*ireg));	  
    } // for(ibin)
    CSV2 -> Add(htempreg);
    double bYields, bError;
    bYields = htempreg->IntegralAndError(1,20,bError);
    CSV1 -> SetBinContent((ireg+1),bYields);
    CSV1 -> SetBinError((ireg+1),bError);
  } // for(ireg)  

}
Exemplo n.º 2
0
void draw_from_trees(TString var, TCut other_cuts,
		     TString weights, TString title, int nbinsx, 
		     double xlow, double xup,
		     TString options="plotSig:plotLog:plotData",
		     double cut_low=-1, double cut_high=-1,
		     TString plot_title="default")
{

  bool plotSig = options.Contains("plotSig") && (!options.Contains("!plotSig"));
  bool plotLog = options.Contains("plotLog") && (!options.Contains("!plotLog"));
  bool plotData = options.Contains("plotData") && (!options.Contains("!plotData"));
  bool sigStack = options.Contains("sigStack") && (!options.Contains("!sigStack"));

  // Book histograms
  TH1D * httbar = new TH1D("ttbar" , title, nbinsx, xlow, xup);
  TH1D * hqcd = new TH1D("qcd" , title, nbinsx, xlow, xup);
  TH1D * hznn = new TH1D("znn" , title, nbinsx, xlow, xup);
  TH1D * hwjets = new TH1D("wjets" , title, nbinsx, xlow, xup);
  TH1D * hother = new TH1D("other" , title, nbinsx, xlow, xup);
  TH1D * hmc_exp = new TH1D("mc_exp" , title, nbinsx, xlow, xup);
  TH1D * hsingle_top = new TH1D("single_top" , title, nbinsx, xlow, xup);  
  TH1D * ht1bbbb_1500_100 = new TH1D("t1bbbb_1500_100" , title, nbinsx, xlow, xup);
  TH1D * ht1bbbb_1000_900 = new TH1D("t1bbbb_1000_900" , title, nbinsx, xlow, xup);
  TH1D * ht1tttt_1500_100 = new TH1D("t1tttt_1500_100" , title, nbinsx, xlow, xup);
  TH1D * ht1tttt_1200_800 = new TH1D("t1tttt_1200_800" , title, nbinsx, xlow, xup);
  TH1D * ht1qqqq_1400_100 = new TH1D("t1qqqq_1400_100" , title, nbinsx, xlow, xup);
  TH1D * ht1qqqq_1000_800 = new TH1D("t1qqqq_1000_800" , title, nbinsx, xlow, xup);

  // Format cuts
  TCut cut(other_cuts);

  // TCut ttbar_weight("(weightppb*4000)/top_pt_weight_official");

  TCut ttbar_weight("(3.17760399999999981e-05*4000)");

  cout << "Filling histograms for " << var.Data() << endl;
  ttbar_ch->Project("ttbar",var,(cut)*ttbar_weight);
  qcd_ch->Project("qcd",var,cut*weights);
  znn_ch->Project("znn",var,cut*weights);
  wjets_ch->Project("wjets",var,(cut)*weights);
  other_ch->Project("other",var,cut*weights);
  single_top_ch->Project("single_top",var,cut*weights);
  t1bbbb_1500_100_ch->Project("t1bbbb_1500_100",var,(cut)*weights);
  t1bbbb_1000_900_ch->Project("t1bbbb_1000_900",var,(cut)*weights);
  t1tttt_1500_100_ch->Project("t1tttt_1500_100",var,(cut)*weights);
  t1tttt_1200_800_ch->Project("t1tttt_1200_800",var,(cut)*weights);
  t1qqqq_1400_100_ch->Project("t1qqqq_1400_100",var,(cut)*weights);
  t1qqqq_1000_800_ch->Project("t1qqqq_1000_800",var,(cut)*weights);


  bool addOverflow(true);
  Double_t e_overflow(0.), i_overflow(0.);
  if (addOverflow) {
    i_overflow=httbar->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    httbar->SetBinContent(nbinsx, i_overflow);
    httbar->SetBinError(nbinsx, e_overflow);
    i_overflow=hqcd->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hqcd->SetBinContent(nbinsx, i_overflow);
    hqcd->SetBinError(nbinsx, e_overflow);
    i_overflow=hznn->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hznn->SetBinContent(nbinsx, i_overflow);
    hznn->SetBinError(nbinsx, e_overflow);
    i_overflow=hwjets->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hwjets->SetBinContent(nbinsx, i_overflow);
    hwjets->SetBinError(nbinsx, e_overflow);
    i_overflow=hsingle_top->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hsingle_top->SetBinContent(nbinsx, i_overflow);
    hsingle_top->SetBinError(nbinsx, e_overflow);
    i_overflow=hother->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    hother->SetBinContent(nbinsx, i_overflow);
    hother->SetBinError(nbinsx, e_overflow);
    i_overflow=ht1bbbb_1500_100->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    ht1bbbb_1500_100->SetBinContent(nbinsx, i_overflow);
    ht1bbbb_1500_100->SetBinError(nbinsx, e_overflow);
    i_overflow=ht1bbbb_1000_900->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    ht1bbbb_1000_900->SetBinContent(nbinsx, i_overflow);
    ht1bbbb_1000_900->SetBinError(nbinsx, e_overflow);
    i_overflow=ht1tttt_1500_100->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    ht1tttt_1500_100->SetBinContent(nbinsx, i_overflow);
    ht1tttt_1500_100->SetBinError(nbinsx, e_overflow);
    i_overflow=ht1tttt_1200_800->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    ht1tttt_1200_800->SetBinContent(nbinsx, i_overflow);
    ht1tttt_1200_800->SetBinError(nbinsx, e_overflow);
    i_overflow=ht1qqqq_1400_100->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    ht1qqqq_1400_100->SetBinContent(nbinsx, i_overflow);
    ht1qqqq_1400_100->SetBinError(nbinsx, e_overflow);
    i_overflow=ht1qqqq_1000_800->IntegralAndError(nbinsx,nbinsx+1,e_overflow);
    ht1qqqq_1000_800->SetBinContent(nbinsx, i_overflow);
    ht1qqqq_1000_800->SetBinError(nbinsx, e_overflow);
  }

  
  // Add up MC histograms
  hmc_exp->Add(httbar);
  hmc_exp->Add(hqcd);
  hmc_exp->Add(hznn);
  hmc_exp->Add(hwjets);
  hmc_exp->Add(hsingle_top);
  hmc_exp->Add(hother);


  double binwidth = (xup - xlow) / nbinsx;
  TString ytitle = Form("Events / %.3f", binwidth);
  hmc_exp->GetXaxis()->SetTitle(httbar->GetXaxis()->GetTitle());
  hmc_exp->GetYaxis()->SetTitle(ytitle);
  cout << "... DONE: add all backgrounds to mc_exp." << endl;
  
  Double_t ttbar_e(0.), qcd_e(0.), znn_e(0.), wjets_e(0.), other_e(0.), single_top_e(0.), bg_tot_e(0.), t1tttt_1500_100_e(0.);
  double ttbar_n(httbar->IntegralAndError(0,nbinsx+1, ttbar_e));
  double qcd_n(hqcd->IntegralAndError(0,nbinsx+1, qcd_e));
  double znn_n(hznn->IntegralAndError(0,nbinsx+1, znn_e));
  double wjets_n(hwjets->IntegralAndError(0,nbinsx+1, wjets_e));
  double other_n(hother->IntegralAndError(0,nbinsx+1, other_e));
  double single_top_n(hsingle_top->IntegralAndError(0,nbinsx+1, single_top_e));
  double bg_tot(hmc_exp->IntegralAndError(0,nbinsx+1, bg_tot_e));
  double t1tttt_1500_100_n(ht1tttt_1500_100->IntegralAndError(0,nbinsx+1, t1tttt_1500_100_e));


  printf("Counts before cut: %s\n",var.Data());
  printf("&ttbar&qcd&znn&wjets&single top&other&t1bbbb_1500_100\\\\ \n");
  printf("%s & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f & %3.2f+-%3.2f \\\\\n",
	 var.Data(),
	 ttbar_n,ttbar_e,
	 qcd_n,qcd_e,
	 znn_n,znn_e,
	 wjets_n,wjets_e,
	 single_top_n,single_top_e,
	 other_n,other_e,
	 //	 hmc_exp->GetBinContent(1), hmc_exp->GetBinError(1),
	 bg_tot,bg_tot_e,
	 t1tttt_1500_100_n,t1tttt_1500_100_e);


  cout << "... DONE: filled histograms." << endl;
 
  if (sigStack) {
    for (int bin(0); bin<nbinsx; bin++) {
      ht1bbbb_1500_100->SetBinContent(bin+1, hmc_exp->GetBinContent(bin+1));
      ht1bbbb_1000_900->SetBinContent(bin+1, hmc_exp->GetBinContent(bin+1));
      ht1tttt_1500_100->SetBinContent(bin+1, hmc_exp->GetBinContent(bin+1));
      ht1tttt_1200_800->SetBinContent(bin+1, hmc_exp->GetBinContent(bin+1));
    }
  }
 
  THStack * hs = new THStack("hs", "");
  hs->Add(hother); 
  hs->Add(hsingle_top);
  hs->Add(hwjets);
  hs->Add(hznn);
  if (httbar->Integral()>hqcd->Integral()) {
    hs->Add(hqcd);
    hs->Add(httbar);
  } else {
    hs->Add(httbar);
    hs->Add(hqcd);
  }


  //hs->GetYaxis()->SetTitle("Events / 5 fb^{-1}");
  //hs->GetXaxis()->SetTitle(httbar->GetXaxis()->GetTitle());

  // Setup histogram styles
  set_style(httbar, "ttbar");
  set_style(hqcd, "qcd");
  set_style(hznn, "znn");
  set_style(hwjets, "wjets");
  set_style(hother, "other");
  set_style(hsingle_top, "single_top");

  // Setup auxiliary histograms (ratios, errors, etc)
  TH1D * staterr = (TH1D *) hmc_exp->Clone("staterr");
  staterr->Sumw2();
  //staterr->SetFillColor(kRed);
  staterr->SetFillColor(kGray+3);
  staterr->SetMarkerSize(0);
  staterr->SetFillStyle(3013);

 
  // Setup legends
  TLegend * leg1 = new TLegend(0.48, 0.6, 0.72, 0.92);
  set_style(leg1,0.025);
  if (plotData) leg1->AddEntry(hsingle_top, "Data", "pel");
  if (plotSig) {
    leg1->AddEntry(ht1bbbb_1500_100, "#splitline{T1bbbb}{(1500,100) GeV}", "l");
    leg1->AddEntry(ht1bbbb_1000_900, "#splitline{T1bbbb}{(1000,900) GeV}", "l");
    leg1->AddEntry(ht1tttt_1500_100, "#splitline{T1tttt}{(1500,100) GeV}", "l");
    leg1->AddEntry(ht1tttt_1200_800, "#splitline{T1tttt}{(1200,800) GeV}", "l");
    leg1->AddEntry(ht1qqqq_1400_100, "#splitline{T1qqqq}{(1400,100) GeV}", "l");
    leg1->AddEntry(ht1qqqq_1000_800, "#splitline{T1qqqq}{(1000,800) GeV}", "l");
  }
 

  TLegend * leg2 = new TLegend(0.72, 0.6, 0.94, 0.92);
  set_style(leg2,0.025);
  if (httbar->Integral()>hqcd->Integral()) {
    leg2->AddEntry(httbar, "t#bar{t}", "f");
    leg2->AddEntry(hqcd, "QCD", "f");
  } else {
    leg2->AddEntry(hqcd, "QCD", "f");
    leg2->AddEntry(httbar, "t#bar{t}", "f");
  }
  leg2->AddEntry(hznn, "Z+jets", "f");
  leg2->AddEntry(hwjets, "W+jets", "f");
  leg2->AddEntry(hsingle_top, "Single Top", "f");
  leg2->AddEntry(hother, "Other", "f");
  leg2->AddEntry(staterr, "MC uncert.", "f");
    
  double ymax = hs->GetMaximum();
  if (ht1tttt_1500_100->GetMaximum()>ymax) ymax=ht1tttt_1500_100->GetMaximum();
  if (ht1bbbb_1500_100->GetMaximum()>ymax) ymax=ht1bbbb_1500_100->GetMaximum();
  if (ht1qqqq_1400_100->GetMaximum()>ymax) ymax=ht1qqqq_1400_100->GetMaximum();


  if(plotLog) {
    hs->SetMaximum(200*ymax);
    hs->SetMinimum(0.1);
  }
  else {
    hs->SetMaximum(2*ymax);
    if (plot_title.Contains("baseline")) hs->SetMaximum(1.3*ymax);
  }
  // Vertical lines for cuts
  TLine* line_low = new TLine(cut_low,0,cut_low,1.5*ymax);
  TLine* line_high = new TLine(cut_high,0,cut_high,1.5*ymax);
  set_style(line_low);
  set_style(line_high);

  // Setup canvas and pads  
  TCanvas * c1 = new TCanvas("c1", "c1", 700, 700);
  TPad * pad1 = new TPad("pad1", "top pad" , 0.0, 0.3, 1.0, 1.0);
  TPad * pad2 = new TPad("pad2", "bottom pad", 0.0, 0.0, 1.0, 0.3);
  if(plotData) {
    pad1->SetBottomMargin(0.0);
    pad1->Draw();
    pad2->SetTopMargin(0.0);
    pad2->SetBottomMargin(0.35);
    pad2->Draw();
    pad1->cd();
    pad1->SetLogy(plotLog);
  }
  else {
    c1->cd();
    c1->SetLogy(plotLog);
  }
  // Draw hists
  hs->Draw("hist");
  hs->SetTitle(hmc_exp->GetTitle());
  hs->GetXaxis()->SetTitle(httbar->GetXaxis()->GetTitle());
  hs->GetYaxis()->SetTitle(ytitle);
  hs->GetXaxis()->SetLabelSize(0.03);
  hs->GetYaxis()->SetLabelSize(0.03);
  if (plotData) 
    {
      //  hsingle_top->Draw("e1 same");
      hs->GetXaxis()->SetLabelSize(0);
    }
  staterr->Draw("e2 same");
  if (plotSig) {
    ht1bbbb_1500_100->SetLineColor(2);
    ht1bbbb_1500_100->SetLineWidth(4);
    ht1bbbb_1500_100->SetFillColor(0);
    ht1bbbb_1000_900->SetLineColor(2);
    ht1bbbb_1000_900->SetLineWidth(4);
    ht1bbbb_1000_900->SetLineStyle(7);
    ht1bbbb_1000_900->SetFillColor(0);
    ht1tttt_1500_100->SetLineColor(kGreen);
    ht1tttt_1500_100->SetLineWidth(4);
    ht1tttt_1500_100->SetFillColor(0);
    ht1tttt_1200_800->SetLineColor(kGreen);
    ht1tttt_1200_800->SetLineStyle(7);
    ht1tttt_1200_800->SetLineWidth(4);
    ht1tttt_1200_800->SetFillColor(0);
    ht1qqqq_1400_100->SetLineColor(1006);
    ht1qqqq_1400_100->SetLineWidth(4);
    ht1qqqq_1400_100->SetFillColor(0);
    ht1qqqq_1000_800->SetLineColor(1006);
    ht1qqqq_1000_800->SetLineWidth(4);
    ht1qqqq_1000_800->SetLineStyle(7);
    ht1qqqq_1000_800->SetFillColor(0);
    ht1bbbb_1500_100->Draw("hist same");
    ht1bbbb_1000_900->Draw("hist same");
    ht1tttt_1500_100->Draw("hist same");
    ht1tttt_1200_800->Draw("hist same");
    ht1qqqq_1400_100->Draw("hist same");
    ht1qqqq_1000_800->Draw("hist same");
  }
  if (cut_low>0) line_low->Draw("same");
  if (cut_high>0) line_high->Draw("same");


  // Draw legends
  leg1->Draw();
  leg2->Draw();
  TLatex * latex = new TLatex();
  latex->SetNDC();
  latex->SetTextAlign(12);
  latex->SetTextFont(62);
  latex->SetTextSize(0.042);
  latex->DrawLatex(0.19, 0.89, "CMS Simulation");
  latex->SetTextSize(0.03);
  latex->DrawLatex(0.19, 0.84, "#sqrt{s} = 13 TeV, L = 4 fb^{-1}");
  
  // Print
  cout << "MakePlots(): Printing..." << endl;

  c1->cd();
  if (plot_title.EqualTo("default")) plot_title=plotdir+var;
  gPad->Print(plotdir+plot_title+".pdf");


  // Clean up
  delete staterr;
  delete leg1;
  delete leg2;
  delete latex;
  // delete pave;
  delete hs;
  delete pad1;
  delete pad2;
  delete c1;

  delete httbar;
  delete hqcd;
  delete hznn;
  delete hwjets;
  delete hsingle_top;
  delete hother;
  delete hmc_exp;

  delete ht1bbbb_1500_100;
  delete ht1bbbb_1000_900;
  delete ht1tttt_1500_100;
  delete ht1tttt_1200_800;
  delete ht1qqqq_1400_100;
  delete ht1qqqq_1000_800;

  cout << "MakePlots(): DONE!" << endl;

  return;
}
Exemplo 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;
}
Exemplo n.º 4
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;
}
Exemplo n.º 5
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;
}
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;

}
Exemplo n.º 7
0
void Z0AccEff(int isData = 2, int yieldInt = 1, int iSpec = 3, int Weight =1)
{
  ////////  definitions of Switches   ///////////
  //  isData = 1 for Data
  //  isData = 2 for Simulation
  
    
  // iSpec = 1  pT spectra
  // iSpec = 2  Y spectra
  // iSpec = 3  Centrality Spectra
  
  //Weight = 1 for weighted histo
  //weight = 0  for non weighted histo



  ////////////////////////////////////////////////////////////
  gStyle->SetOptStat(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0000); 

  // Fit ranges
  float mass_low, mass_high, mlow, mhigh;
  int nrebin;
  bool isLog, isFit;
  double MassZ0, WidthZ0;

  // High Mass range
  MassZ0 = 91.1876; WidthZ0 = 2.4952;
  mass_low = 60; mass_high = 120;  // Fit ranges Glb Glb
  //mass_low = 40; mass_high = 140;  // Fit ranges STA
  mlow = 0.0; mhigh = 200.0; nrebin = 80; isLog =0; isFit = 0; // draw ranges
  
  int whis = 1; // 1 for full all eta, 2 for barrel  //4 for trigger matched PAT
  
  //file one is good file

  TFile *fil1, *fil2;

  if (isData == 2) fil2 = new TFile("Z0_DataMixPt50_PatDiMuonPlots_All11Dec.root");
  //if (isData == 2) fil2 = new TFile("ReReco_DM_DiMuonPlot_All16Dec.root");
  if (isData == 2)  fil1 = new TFile("Z0HydPt50_PatDiMuonPlots_AllWOSel12Dec.root");

  // Pt bin sizes
  int Nptbin=1;
  double pt_bound[100] = {0};
  
  if(iSpec == 1) { 
    Nptbin = 3;
    pt_bound[0] = 0.0; pt_bound[1] = 6.0;
    pt_bound[2] = 12.0; pt_bound[3] = 100.0;
    
    if(isData == 2) {
      Nptbin = 25;
      // pt_bound[100] = {0.0,100.0,12.0,100.0};
      pt_bound[0] = 0;
      pt_bound[1] = 2;
      pt_bound[2] = 4;
      pt_bound[3] = 6;
      pt_bound[4] = 8;
      pt_bound[5] = 10;
      pt_bound[6] = 12;
      pt_bound[7] = 14;
      pt_bound[8] = 16;
      pt_bound[9] = 18;
      pt_bound[10] = 20;
      pt_bound[11] = 22;
      pt_bound[12] = 24;
      pt_bound[13] = 26;
      pt_bound[14] = 28;
      pt_bound[15] = 30;
      pt_bound[16] = 32;
      pt_bound[17] = 34;
      pt_bound[18] = 36;
      pt_bound[19] = 38;
      pt_bound[20] = 40;
      pt_bound[21] = 42;
      pt_bound[22] = 44;
      pt_bound[23] = 46;
      pt_bound[24] = 48;
      pt_bound[25] = 50;
    }
  }
  
  // Y bin sizes
  if(iSpec == 2) {
    Nptbin = 10;
    // pt_bound[100] = {-2.4,-1.0,-0.5,0.5,1.0,2.4}; 
    // pt_bound[100] = {-2.4,-1.0,-0.5,0.5,1.0,2.4}; 
    // pt_bound[100] = {-2.4,-2.1,-1.6,-1.1,-0.6,0,0.6,1.1,1.6,2.1,2.4}; 
    pt_bound[0] = -2.4; 
    pt_bound[1] = -2.1; 
    pt_bound[2] = -1.6; 
    pt_bound[3] = -1.1; 
    pt_bound[4] = -0.6; 
    pt_bound[5] =  0.0; 
    pt_bound[6] = 0.6; 
    pt_bound[7] = 1.1; 
    pt_bound[8] = 1.6; 
    pt_bound[9] = 2.1; 
    pt_bound[10] = 2.4; 

  }
  
  if(iSpec == 3) {
    if(isData == 2) { 
      Nptbin = 9;
      pt_bound[0] = 0.0;
      pt_bound[1] = 4.0;
      pt_bound[2] = 8.0;
      pt_bound[3] = 12.0;
      pt_bound[4] = 16.0;
      pt_bound[5] = 20.0;
      pt_bound[6] = 24.0;
      pt_bound[7] = 28.0;
      pt_bound[8] = 32.0;
      pt_bound[9] = 40.0;
    }
  }
  
  double PT[100], DelPT[100], mom_err[100];
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = pt_bound[ih+1] - pt_bound[ih];
    mom_err[ih] = DelPT[ih]/2.0;
  }
  
  float gen_pt[100], gen_ptError[100];
  float gen_ptS[100], gen_ptErrorS[100];
  
  if(isData==2){

    TH2D *genMass_1, *genMassS_1;

    if (iSpec == 1 &&  Weight==1 ) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsPtW");
    if (iSpec == 2 &&  Weight==1) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsYW");
    if (iSpec == 3 &&  Weight==1) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsCenW");
    
    if (iSpec == 1 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsPtW");
    if (iSpec == 2 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsYW");
    if (iSpec == 3 &&  Weight==1) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsCenW");
    
    if (iSpec == 1 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsPt");
    if (iSpec == 2 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsY");
    if (iSpec == 3 &&  Weight==0) genMass_1 = (TH2D*)fil1->Get("diMuonsGenInvMassVsCen");


    if (iSpec == 1 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsPt");
    if (iSpec == 2 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsY");
    if (iSpec == 3 &&  Weight==0) genMassS_1 = (TH2D*)fil2->Get("diMuonsGenInvMassVsCen");

    TH1D *ptaxis = (TH1D*)genMass_1->ProjectionY("ptaxis");
    
    for (Int_t ih = 0; ih < Nptbin; ih++) {
      cout<<pt_bound[ih]<<"  "<<pt_bound[ih+1]<<endl;
      int pt_bin1 = ptaxis->FindBin(pt_bound[ih]+0.0000001);
      int pt_bin2 = ptaxis->FindBin(pt_bound[ih+1]+0.0000001);
      
      cout<< pt_bin1<<"  "<< pt_bin2<<endl; 
      TH1D * genMassVsPt = (TH1D*)genMass_1->ProjectionX("genMassVsPt", pt_bin1, pt_bin2-1);
      TH1D * genMassVsPtS = (TH1D*)genMassS_1->ProjectionX("genMassVsPtS", pt_bin1, pt_bin2-1);
      
      //does not work with weight
      //gen_pt[ih] = genMassVsPt->GetEntries();
      
      double genError,genErrorS;
      gen_pt[ih] = genMassVsPt->IntegralAndError(1,8000,genError);
      gen_ptError[ih]= genError;
      
      gen_ptS[ih] = genMassVsPtS->IntegralAndError(1,8000,genErrorS);
      gen_ptErrorS[ih]= genErrorS;
      
      cout<<" gen entries : "<< gen_pt[ih]<<endl;
      cout<<"genErro "<<genError<<"  "<< gen_ptError[ih]<<endl<<endl;
    }
  }
  
  // Efficiency
  float Eff_cat_1[100]; 
  float Eff_catS_1[100]; 
  
  float errEff_cat_1[100];
  float errEff_catS_1[100];
  
  float errEff_cat_S1[100], errEff_cat_S2[100];
  float errEff_catS_S1[100], errEff_catS_S2[100];
  
  char *Xname[100] = {" ", "p_{T}^{Dimuon} (GeV/c)", "rapidity", "centrality"};
  
  double yld_cat_1[100];
  double yld_catS_1[100];
  double cyld_cat_1[100];
  double cyld_catS_1[100];
  double eyld_cat_1[100];
  double eyld_catS_1[100];
  double ceyld_cat_1[100], ceyld_catS_1[100];

  char namePt_1[500];
  char namePt_1S[500];
  //char namePt_1B[500];
  char text[100];
  
  ///// Write the spectra 
  char fspectra[500];
  sprintf(fspectra,"fileSpecta%d.root", yieldInt);
  TFile *fileSpectra = new TFile(fspectra, "recreate");

  ///////////////////////////////////////////////////////////////////////
  // Category _1 
  TLegend *lcat_1;
  lcat_1 = new TLegend(.1, .82, .50, .93);
  lcat_1->SetName("lcat_1");
  lcat_1->SetBorderSize(0);
  lcat_1->SetFillStyle(0);
  lcat_1->SetFillColor(0);
  lcat_1->SetTextSize(0.032);
  //lcat_1->AddEntry(RBWPOL," CMS Preliminary", " ");
  //lcat_1->AddEntry(RBWPOL," PbPb #sqrt{s_{NN}} = 2.76 TeV ", " ");
  
  TLegend *legend_1[100];
  for(int i=0; i<100; i++) { 
    if(isFit) legend_1[i] = new TLegend(.62, .52, .91, 0.93 );
    if(!isFit) legend_1[i] = new TLegend(.62, .68, .91, 0.93 );
    legend_1[i]->SetBorderSize(0);
    legend_1[i]->SetFillStyle(0);
    legend_1[i]->SetFillColor(0);
    legend_1[i]->SetTextSize(0.032);
  }
  
  //for no cut
  //if(whis == 1 && iSpec == 1 ) TH2D *Z0Mass_1 = (TH2D*)fil1->Get("dimu");
  //if(whis == 2 && iSpec == 1) TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPtBRL");
  //if(whis == 4 && iSpec == 1 ) {
    //TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsPATInvMassVsPt");
    //TH2D *Z0Mass_1 = (TH2D*)fil1->Get("diMuonsPATSTAInvMassVsPt");
  //}



  TH2D *Z0Mass_1, *Z0Mass_1S;

  //with weight

  if(iSpec == 1 &&  Weight==1 ) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPtW");
  if(iSpec == 2 &&  Weight==1) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsYW");
  if(iSpec == 3 &&  Weight==1) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsCenW");


  //without weight
  if(iSpec == 1  &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsPt");
  if(iSpec == 2 &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsY");
  if(iSpec == 3 &&  Weight==0) Z0Mass_1 = (TH2D*)fil1->Get("diMuonsGlobalInvMassVsCen");
      
  //with weight fil2
  if(iSpec == 1  &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsPtW");
  if(iSpec == 2 &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsYW");
  if(iSpec == 3 &&  Weight==1) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsCenW");

  //without weight fil2
  if(iSpec == 1 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsPt");
  if(iSpec == 2 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsY");
  if(iSpec == 3 &&  Weight==0  ) Z0Mass_1S = (TH2D*)fil2->Get("diMuonsGlobalInvMassVsCen");
  
  TH1D *service = (TH1D*)Z0Mass_1->ProjectionY("service");
  int pt_bin_bound[100];
  TH1D *dimuonsGlobalInvMassVsPt[100],  *dimuonsGlobalInvMassVsPtS[100];
  
  TCanvas *CanvPt_1 = new TCanvas("CanvPt_1"," Z0 Yield Vs. Pt ", 40,40,1000,700);
  if (Nptbin == 2)  CanvPt_1->Divide(2,1);
  if (Nptbin == 3 || Nptbin == 4)  CanvPt_1->Divide(2,2);
  if (Nptbin == 5 || Nptbin == 6)  CanvPt_1->Divide(3,2);
  if (Nptbin == 9 || Nptbin == 10)  CanvPt_1->Divide(5,2);
  cout << endl << Xname[iSpec] << "    Yield      Mass (GeV)    Width (GeV)    GauWidth    chi2/ndf " << endl << endl; 
  //ih loop
  for (Int_t ih = 0; ih < Nptbin; ih++) 
    {
      CanvPt_1->cd(ih+1);
      gPad->SetTickx();
      gPad->SetTicky();
      
      // Project 1 D 
      pt_bin_bound[ih] = Z0Mass_1->GetYaxis()->FindBin(pt_bound[ih]+0.0000001);
      pt_bin_bound[ih+1] = Z0Mass_1->GetYaxis()->FindBin(pt_bound[ih+1]-0.0000001);
      sprintf(namePt_1,"Z0_1_pt_%d",ih);
      sprintf(namePt_1S,"Z0_1S_pt_%d",ih);
      
      //printf(namePt_1,"Z0_1_pt_%d",ih);
      //cout<<endl<<endl;
      //continue;
      
      dimuonsGlobalInvMassVsPt[ih] = (TH1D*)Z0Mass_1->ProjectionX(namePt_1, pt_bin_bound[ih], pt_bin_bound[ih+1]-1+1, "e");
      dimuonsGlobalInvMassVsPtS[ih] = (TH1D*)Z0Mass_1S->ProjectionX(namePt_1S, pt_bin_bound[ih], pt_bin_bound[ih+1]-1+1,"e");
      if(iSpec == 1 || iSpec == 2) {sprintf(text," %s [%.1f, %.1f]", Xname[iSpec], service->GetBinLowEdge(pt_bin_bound[ih]), 
					    service->GetBinLowEdge(pt_bin_bound[ih+1])+service->GetBinWidth(pt_bin_bound[ih+1]));}
      if(iSpec == 3) {sprintf(text," %s [%.1f, %.1f] %s", Xname[iSpec], 2.5*service->GetBinLowEdge(pt_bin_bound[ih]), 
			      2.5*(service->GetBinLowEdge(pt_bin_bound[ih+1])+service->GetBinWidth(pt_bin_bound[ih+1])), "%");}
      
      dimuonsGlobalInvMassVsPt[ih]->Rebin(nrebin);
      dimuonsGlobalInvMassVsPtS[ih]->Rebin(nrebin);
      
      float m_low = 60.0;
      float m_high = 120.0;
      
      TAxis *axs   = dimuonsGlobalInvMassVsPt[ih]->GetXaxis();
      int binlow = axs->FindBin(m_low);
      int binhi  = axs->FindBin(m_high);
      //      Double_t bin_size = (1.0*dimuonsGlobalInvMassVsPt[ih]->GetNbinsX())/(axs->GetXmax() - axs->GetXmin());
      //    Float_t int_sig = 0.0;
      //for(Int_t bin = binlow; bin<=binhi;bin++) {
      //int_sig+ = dimuonsGlobalInvMassVsPt[ih]->GetBinContent(bin);
      //}   
      double recerror,recerrorS;
      //double yld;
      double yld_1 = dimuonsGlobalInvMassVsPt[ih]->IntegralAndError(binlow, binhi, recerror);
      double yldS_1 = dimuonsGlobalInvMassVsPtS[ih]->IntegralAndError(binlow, binhi, recerrorS); 
      eyld_cat_1[ih] =recerror;
      eyld_catS_1[ih] =recerrorS;
      cout<< "yld " << yld_1 <<"  eyld_cat_1[ih]  "<< eyld_cat_1[ih]<<" rec error "<<recerror<<endl;
      
      yld_cat_1[ih] = yld_1;
      yld_catS_1[ih] = yldS_1;
      
      if(isLog) gPad->SetLogy(1);
      TColor *pal = new TColor();
      Int_t kblue = pal->GetColor(9,0,200);
      //      Int_t korange  = pal->GetColor(101, 42,  0);
      
      dimuonsGlobalInvMassVsPt[ih]->SetMarkerStyle(21);
      dimuonsGlobalInvMassVsPt[ih]->SetMarkerColor(kblue);
      dimuonsGlobalInvMassVsPt[ih]->SetLineColor(kblue);
      dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetTitle("Dimuon mass (GeV/c^{2})");
      dimuonsGlobalInvMassVsPt[ih]->GetYaxis()->SetTitle("Events/(2 GeV/c^{2})");
      dimuonsGlobalInvMassVsPt[ih]->GetXaxis()->SetRangeUser(mlow,mhigh);
      dimuonsGlobalInvMassVsPt[ih]->DrawCopy("EPL");
      // fil2
      dimuonsGlobalInvMassVsPtS[ih]->SetMarkerStyle(8);
      dimuonsGlobalInvMassVsPtS[ih]->SetMarkerColor(46);
      dimuonsGlobalInvMassVsPtS[ih]->SetLineColor(46);
      //****** dimuonsGlobalInvMassVsPtS[ih]->DrawCopy("EPsame");
      //RBWPOL->SetLineColor(kblue);
      //backfun_1->SetLineColor(46);
      //backfun_1->SetLineWidth(1);
      //if(isFit) backfun_1->Draw("same");
      lcat_1->Draw("same"); 
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih],"Global-Global", " ");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," |y| < 2.4 ", "");  
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], text, "");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih]," Opposite Charge ", "LP");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPtS[ih]," Same Charge ", "LP");
      char label_1[512];
      //      char label_2[512], label_3[512], label_4[512];
      sprintf(label_1, "N=%1.2f #pm %1.2f ", yld_cat_1[ih], eyld_cat_1[ih]);
      //    sprintf(label_1, "N_{Z^{0}} = 27");
      legend_1[ih]->AddEntry(dimuonsGlobalInvMassVsPt[ih], label_1, "");
    }//ih loop
  cout << endl << endl;
  CanvPt_1->Print("Pt_Z0MassCat_1.png");
  
  TGraphErrors *Z0pt_cat_1 = new TGraphErrors(Nptbin, PT, yld_cat_1, mom_err, eyld_cat_1);
  Z0pt_cat_1->SetMarkerStyle(20);
  Z0pt_cat_1->SetMarkerColor(2);
  Z0pt_cat_1->GetXaxis()->SetTitle(Xname[iSpec]);
  Z0pt_cat_1->GetYaxis()->SetTitle("counts");

  new TCanvas;
  Z0pt_cat_1->SetMinimum(0.0);
  Z0pt_cat_1->SetName("Z0pt_cat_1");
  Z0pt_cat_1->Draw("AP");
  lcat_1->Draw("same"); 
  gPad->Print("Pt_Z0YieldCat_1.png");
  cout << endl << endl;
  Z0pt_cat_1->Write();
  lcat_1->Write();
  
  // Efficiency correction
  if(isData==2) 
    {
       ofstream fileout("correction.txt");
       cout << Xname[iSpec] << "   Eff_cat_1  " << endl;
       
       for (Int_t ih = 0; ih < Nptbin; ih++) {
      	//cout<<"gen_pt[ih];  "<<gen_pt[ih]<<endl;
	 Eff_cat_1[ih] = yld_cat_1[ih]/gen_pt[ih]; 
	 Eff_catS_1[ih] = yld_catS_1[ih]/gen_ptS[ih]; 
	 //eyld_cat_1[ih];
	 //gen_ptError[ih];
	 //cout<<endl<<endl<<endl;
	//cout<<"Eff_cat_1[ih] "<<Eff_cat_1[ih]<<endl;
	//cout<<"yld_cat_1[ih] "<< yld_cat_1[ih] <<endl;
	//cout<<"eyld_cat_1[ih] "<<eyld_cat_1[ih] <<endl;
	//cout<<"gen_pt[ih]    "<< gen_pt[ih] <<endl;
	//cout<<"gen_ptError[ih] "<< gen_ptError[ih]<<endl;
	 //Error for first graph
	 double errEff_cat_S1_1[100]={0},errEff_cat_S1_2[100]={0};
	 double errEff_cat_S2_1[100]={0},errEff_cat_S2_2[100]={0};
	 errEff_cat_S1_1[ih]= ( (Eff_cat_1[ih] * Eff_cat_1[ih]) /(gen_pt[ih] * gen_pt[ih]) );
	 errEff_cat_S1_2[ih]= (gen_ptError[ih] * gen_ptError[ih] ) - ( eyld_cat_1[ih] * eyld_cat_1[ih] );
	 errEff_cat_S1[ih]= (errEff_cat_S1_1[ih] * errEff_cat_S1_2[ih]);
	 //cout<<" errEff_cat_S1_1[ih] "<<	errEff_cat_S1_1[ih]<< " errEff_cat_S1_2[ih] "<<errEff_cat_S1_2[ih]<<endl;
	 errEff_cat_S2_1[ih]= ( (1 - Eff_cat_1[ih])* (1 - Eff_cat_1[ih]) ) / ( gen_pt[ih] * gen_pt[ih]);
	 errEff_cat_S2_2[ih]= (eyld_cat_1[ih] * eyld_cat_1[ih]);
	 errEff_cat_S2[ih]=errEff_cat_S2_1[ih]*errEff_cat_S2_2[ih];
	 //cout<<" errEff_cat_S2_1[ih] "<<	errEff_cat_S2_1[ih]<< " errEff_cat_S2_2[ih] "<<errEff_cat_S2_2[ih]<<endl;
	 //cout<<"errEff_cat_S1[ih]    "<<errEff_cat_S1[ih]<< " errEff_cat_S2[ih]   "<< errEff_cat_S2[ih]<<endl;	
	 errEff_cat_1[ih]=sqrt(errEff_cat_S1[ih] + errEff_cat_S2[ih]);
	 
	 //Error for second graph
	 double errEff_catS_S1_1[100]={0},errEff_catS_S1_2[100]={0};
	 double errEff_catS_S2_1[100]={0},errEff_catS_S2_2[100]={0};
	 errEff_catS_S1_1[ih]= ( (Eff_catS_1[ih] * Eff_catS_1[ih]) /(gen_ptS[ih] * gen_ptS[ih]) );
	 errEff_catS_S1_2[ih]= (gen_ptErrorS[ih] * gen_ptErrorS[ih] ) - (eyld_catS_1[ih] * eyld_catS_1[ih] );
	 errEff_catS_S1[ih]= (errEff_catS_S1_1[ih] * errEff_catS_S1_2[ih]);
	 errEff_catS_S2_1[ih]= ( (1 - Eff_catS_1[ih])* (1 - Eff_catS_1[ih]) ) / ( gen_ptS[ih] * gen_ptS[ih]);
	 errEff_catS_S2_2[ih]= (eyld_catS_1[ih] * eyld_catS_1[ih]);
	 errEff_catS_S2[ih]= errEff_catS_S2_1[ih]*errEff_catS_S2_2[ih];
	 errEff_catS_1[ih]=sqrt(errEff_catS_S1[ih] + errEff_catS_S2[ih]);
	 //Error for no weight
	 //errEff_cat_1[ih] =((Eff_cat_1[ih]*(1- Eff_cat_1[ih]))/gen_pt[ih]);
	 //Prashant error
	 //errEff_cat_1[ih] = eyld_cat_1[ih]/gen_pt[ih]; 
	 fileout << PT[ih] <<"   "<< Eff_cat_1[ih] << "   " << errEff_cat_1[ih] << endl; 
	 cout <<"    " << PT[ih] <<"    "<< Eff_cat_1[ih] << " +- " << errEff_cat_1[ih] << endl;
	 cyld_cat_1[ih] = Eff_cat_1[ih];
	 ceyld_cat_1[ih] = errEff_cat_1[ih];
	 cyld_catS_1[ih] = Eff_catS_1[ih];
	 ceyld_catS_1[ih] = errEff_catS_1[ih];
       }
    }
  
  TGraphErrors *Z0ptC_cat_1 = new TGraphErrors(Nptbin, PT, cyld_cat_1, mom_err, ceyld_cat_1);
  Z0ptC_cat_1->SetMarkerStyle(20);
  Z0ptC_cat_1->SetMarkerColor(2);
  Z0ptC_cat_1->GetXaxis()->SetTitle(Xname[iSpec]);
  Z0ptC_cat_1->GetYaxis()->SetTitle("Acc #times Eff");
  Z0ptC_cat_1->GetYaxis()->SetRangeUser(0,1.0);

  TGraphErrors *Z0ptC_catS_1 = new TGraphErrors(Nptbin, PT, cyld_catS_1, mom_err, ceyld_catS_1);
  Z0ptC_catS_1->SetMarkerStyle(8);
  Z0ptC_catS_1->SetMarkerColor(1);
  Z0ptC_catS_1->GetYaxis()->SetRangeUser(0,0.8);
  
  TLegend *legend_GP = new TLegend( 0.59,0.79,0.88,0.89);
  legend_GP->SetBorderSize(0);
  legend_GP->SetFillStyle(0);
  legend_GP->SetFillColor(0);
  legend_GP->SetTextSize(0.032);
  //legend_GP->AddEntry(Z0ptC_catS_1,"Pythia Gun in MB HI Data ", "");
  legend_GP->AddEntry(Z0ptC_catS_1,"Pythia Gun in MB Hydjet ", "");
  new TCanvas;
  Z0ptC_cat_1->SetMinimum(0.0);
  Z0ptC_cat_1->Draw("AP");
  //Z0ptC_catS_1->Draw("sameP");
  lcat_1->Draw("same"); 
  legend_GP->Draw("same");
  cout << endl << endl;
  Z0ptC_cat_1->Write();
}
Exemplo n.º 8
0
void PrintLine(TCut cut, string description) {

  TH1::SetDefaultSumw2(1);


  // cout << "Cut: " << description << endl;
 
  TH1D *h = new TH1D("h","",2,0,2);
  TCut weight = Form("weightppb*%f",int_lumi);
  double n_SM(0.), n_t1tttt_1500_100(0.), n_t1tttt_1200_800(0.), n_t1bbbb_1500_100(0.), n_t1bbbb_1000_900(0.);
  double sig_t1tttt_1500_100(0.), sig_t1tttt_1200_800(0.), sig_t1bbbb_1500_100(0.), sig_t1bbbb_1000_900(0.);
  Double_t e_SM(0.), e_t1tttt_1500_100(0.), e_t1tttt_1200_800(0.), e_t1bbbb_1500_100(0.), e_t1bbbb_1000_900(0.);

  // Fill hist to get each weighted yield
  t1bbbb_1500_100_ch->Project("h","1",cut*weight);
  n_t1bbbb_1500_100=h->IntegralAndError(1,3,e_t1bbbb_1500_100);
  t1bbbb_1000_900_ch->Project("h","1",cut*weight);
  n_t1bbbb_1000_900=h->IntegralAndError(1,3,e_t1bbbb_1000_900);
  t1tttt_1500_100_ch->Project("h","1",cut*weight);
  n_t1tttt_1500_100=h->IntegralAndError(1,3,e_t1tttt_1500_100);
  t1tttt_1200_800_ch->Project("h","1",cut*weight);
  n_t1tttt_1200_800=h->IntegralAndError(1,3,e_t1tttt_1200_800);

  SM_ch->Project("h","1",cut*weight);
  n_SM=h->IntegralAndError(1,3,e_SM);

  double fstat_bg = e_SM/n_SM;
  double fsyst_bg=0.2;
  double ferr_bg = TMath::Sqrt(fstat_bg*fstat_bg+fsyst_bg*fsyst_bg);

  sig_t1tttt_1500_100 = RooStats::NumberCountingUtils::BinomialObsZ(n_t1tttt_1500_100+n_SM,n_SM,ferr_bg);
  if (sig_t1tttt_1500_100<0) sig_t1tttt_1500_100=0;
  sig_t1tttt_1200_800 = RooStats::NumberCountingUtils::BinomialObsZ(n_t1tttt_1200_800+n_SM,n_SM,ferr_bg);
  if (sig_t1tttt_1200_800<0) sig_t1tttt_1200_800=0;
  sig_t1bbbb_1500_100 = RooStats::NumberCountingUtils::BinomialObsZ(n_t1bbbb_1500_100+n_SM,n_SM,ferr_bg);
  if (sig_t1bbbb_1500_100<0) sig_t1bbbb_1500_100=0;
  sig_t1bbbb_1000_900 = RooStats::NumberCountingUtils::BinomialObsZ(n_t1bbbb_1000_900+n_SM,n_SM,ferr_bg);
  if (sig_t1bbbb_1000_900<0) sig_t1bbbb_1000_900=0;

  // sig_t1tttt_1500_100 = 2*(TMath::Sqrt(n_t1tttt_1500_100+n_SM)-TMath::Sqrt(n_SM)); 
  // sig_t1tttt_1200_800 = 2*(TMath::Sqrt(n_t1tttt_1200_800+n_SM)-TMath::Sqrt(n_SM)); 
  // sig_t1bbbb_1500_100 = 2*(TMath::Sqrt(n_t1bbbb_1500_100+n_SM)-TMath::Sqrt(n_SM)); 
  // sig_t1bbbb_1000_900 = 2*(TMath::Sqrt(n_t1bbbb_1000_900+n_SM)-TMath::Sqrt(n_SM)); 

  // sig_t1tttt_1500_100 = n_t1tttt_1500_100/TMath::Sqrt(n_SM); 
  // sig_t1tttt_1200_800 = n_t1tttt_1200_800/TMath::Sqrt(n_SM); 
  // sig_t1bbbb_1500_100 = n_t1bbbb_1500_100/TMath::Sqrt(n_SM); 
  // sig_t1bbbb_1000_900 = n_t1bbbb_1000_900/TMath::Sqrt(n_SM); 

  // printf("%s, %3.1f+-%3.1f, %3.1f+-%3.1f, %3.1f+-%3.1f, %3.1f+-%3.1f , %3.1f+-%3.1f\n",
  // 	  description.c_str(), n_t1bbbb_1500_100, e_t1bbbb_1500_100, n_t1bbbb_1000_900, e_t1bbbb_1000_900,
  // 	  n_t1tttt_1500_100, e_t1tttt_1500_100, n_t1tttt_1200_800, e_t1tttt_1200_800, n_SM, e_SM);  
  // if (errors) fprintf(file, "%s, %3.1f+-%3.1f, %3.1f+-%3.1f, %3.1f+-%3.1f, %3.1f+-%3.1f , %3.1f+-%3.1f\n",
  // 		      description.c_str(), n_t1bbbb_1500_100, e_t1bbbb_1500_100, n_t1bbbb_1000_900, e_t1bbbb_1000_900,
  // 		      n_t1tttt_1500_100, e_t1tttt_1500_100, n_t1tttt_1200_800, e_t1tttt_1200_800, n_SM, e_SM);
  // else fprintf(file, "%s, %3.1f, %3.1f, %3.1f, %3.1f , %3.1f\n",
  // 	       description.c_str(), n_t1bbbb_1500_100, n_t1bbbb_1000_900,
  // 		      n_t1tttt_1500_100, n_t1tttt_1200_800, n_SM);

  printf("%s, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f , %3.1f\n",
	 description.c_str(), n_t1bbbb_1500_100, sig_t1bbbb_1500_100, n_t1bbbb_1000_900, sig_t1bbbb_1000_900,
	 n_t1tttt_1500_100, sig_t1tttt_1500_100, n_t1tttt_1200_800, sig_t1tttt_1200_800, n_SM); 
  fprintf(file, "%s, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f, %3.1f , %3.1f\n",
	  description.c_str(), n_t1bbbb_1500_100, sig_t1bbbb_1500_100, n_t1bbbb_1000_900, sig_t1bbbb_1000_900,
	  n_t1tttt_1500_100, sig_t1tttt_1500_100, n_t1tttt_1200_800, sig_t1tttt_1200_800, n_SM); 


  delete h;

}
Exemplo n.º 9
0
// -----------------------------------------------------------------------------
//
TCanvas* createPlot( TString path, 
		     TString canvas_name, 
		     TString name, 
		     TString dirmame, 
		     int rebin, 
		     bool norm, 
		     bool log,
		     TDirectory* file )
{

  // SetSomeStyles();

  float lumi = 250.0;// 15.04;//10.9;//6.8;
 
  // Create legend
  TLegend* legend = new TLegend(0.75, 0.6, 0.99, 0.99, "", "brNDC" );
  legend->SetFillColor(0);
  legend->SetLineColor(0); 
  legend->SetShadowColor(0);
  TLatex* prelim = new TLatex(0.6,0.54,"#scale[0.8]{CMS preliminary 2010}");
  prelim->SetNDC();
  TLatex* alumi = new TLatex(0.6,.45,"#scale[0.8]{#int L dt = 35 pb^{-1}, #sqrt{s} = 7 TeV}");
  alumi->SetNDC();

  // Create canvas 
  TCanvas* aCanvas = createCanvas( canvas_name, file, log );

  // Create histogram
  TString aname("nAll");
  // TH1D* data1    = getHisto( path+"S14datacleaned/Edward_Data_Skim/",name,"data.root",aname,rebin);
  // TH1D* data    = getHisto( path+"S14datacleaned/Edward_Data_Skim/",name,"data.root",dirmame,rebin);
 
  TH1D* data    = getHisto( path+"", name, "tt.root", dirmame, rebin );
  TH1D* qcd     = getHisto( path+"", name, "lm1.root", dirmame, rebin );
  TH1D* w_jets  = getHisto( path+"", name, "w.root", dirmame, rebin );
  TH1D* tt_jets = getHisto( path+"", name, "tt.root", dirmame, rebin );
  TH1D* z_jets  = getHisto( path+"", name, "z.root", dirmame, rebin );
  TH1D* lm3     = getHisto( path+"", name, "lm3.root", dirmame, rebin );
  TH1D* lm1     = getHisto( path+"", name, "lm1.root", dirmame, rebin );
  TH1D* lm6     = getHisto( path+"", name, "data.root", dirmame, rebin );
  TH1D* wm     = getHisto( path+"", name, "w.root", dirmame, rebin );
  data->Scale(lumi/100.);
  qcd->Scale(lumi/100.);
  tt_jets->Scale(lumi/100);
  w_jets->Scale(lumi/100);
  //  w_jets->Scale(10);
  //  z_inv->Scale(lumi/100);
  //  lm6->Scale(lumi/100);
  lm1->Scale(lumi/100);
  lm3->Scale(lumi/100);
  z_jets->Scale(lumi/100);
  wm->Scale(lumi/100);
  // Combine Z+jets and Z->inv
  // TH1D* z_all = z_inv->Clone(); 
  //  z_all->Add(z_jets,1);
  //z_jets->Add(z_inv,1);
  TH1D* total = tt_jets->Clone();
  total->Add(w_jets);
  total->Add(z_jets);

  // total->
 
  Int_t binMax =   total->GetNbinsX();
  Double_t& err = new Double_t(0.);
  total->IntegralAndError(10,binMax ,err);
  Double_t& errW = new Double_t(0.);
  w_jets->IntegralAndError(10,binMax ,errW);
  Double_t& errtt = new Double_t(0.);
  tt_jets->IntegralAndError(10,binMax ,errtt);
  Double_t& errZ = new Double_t(0.);
  z_jets->IntegralAndError(10,binMax ,errZ);
  Double_t& errQCD = new Double_t(0.);
  qcd->IntegralAndError(10,binMax ,errQCD );


  cout  <<endl;
  //  cout << "MC:" <<  total->IntegralAndError(11,binMax ,err) <<" && " <<  w_jets->Integral(11,binMax)<<" && "<<tt_jets->Integral(11,binMax) << "&&  "<<z_jets->Integral(11,binMax)<<" && "<< "\/\ /\hline"<<endl;
  //  cout << total->IntegralAndError(0,binMax ,err) <<" & " << lm1->Integral(0,binMax) <<" & " << lm3->Integral(0,binMax)<<" & " << lm6->Integral(0,binMax)   <<"\\\\ \\hline"<<endl;
  //  cout <<"270: " <<  total->IntegralAndError(27,binMax ,err) <<" & " << lm1->Integral(27,binMax) <<" & " << lm3->Integral(27,binMax)<<" & " << lm6->Integral(27,binMax)   <<"\\\\ \\hline"<<endl;


  cout <<"250& " <<  total->IntegralAndError(6,binMax ,err) <<" & " << lm1->Integral(6,binMax) <<" & " << lm3->Integral(6,binMax)<<" & " << lm6->Integral(6,binMax)   <<"\\\\ \\hline"<<endl;
 
  // cout << "300: " <<  total->IntegralAndError(7,binMax ,err) <<" & " << lm1->Integral(7,binMax) <<" & " << lm3->Integral(7,binMax)<<" &" << lm6->Integral(7,binMax)   <<"\\\\ \\hline"<<endl;

  cout <<"350& " <<  total->IntegralAndError(8,binMax ,err) <<" & " << lm1->Integral(8,binMax) <<" & " << lm3->Integral(8,binMax)<<" & " << lm6->Integral(8,binMax)    <<"\\\\ \\hline"<<endl;

  //   cout << "400: " <<  total->IntegralAndError(9,binMax ,err) <<" & " << lm1->Integral(9,binMax) <<" & " << lm3->Integral(9,binMax)<<" & " << lm6->Integral(9,binMax)    <<"\\\\ \\hline"<<endl;

cout << "450& " <<  total->IntegralAndError(10,binMax ,err) <<" & " << lm1->Integral(10,binMax) <<" & " << lm3->Integral(10,binMax)<<" & " << lm6->Integral(10,binMax)    <<"\\\\ \\hline"<<endl;

//cout << "500: " <<   total->IntegralAndError(11,binMax ,err) <<" & " << lm1->Integral(11,binMax) <<" & " << lm3->Integral(11,binMax)<<" & " << lm6->Integral(11,binMax)    <<"\\\\ \\hline"<<endl;

  cout <<"550& " <<  total->IntegralAndError(12,binMax ,err) <<" & " << lm1->Integral(12,binMax) <<" & " << lm3->Integral(12,binMax)<<" & " << lm6->Integral(12,binMax)    <<"\\\\ \\hline"<<endl;
  /*
 cout << "MC:" <<  total->IntegralAndError(7,binMax ,err) <<" && " << lm1->Integral(7,binMax) <<" && " << lm3->Integral(7,binMax)<<" && " << lm6->Integral(6,binMax)   <<"/\/\ /\hline"<<endl;
  cout << "MC:" <<  total->IntegralAndError(8,binMax ,err) <<" && " << lm1->Integral(8,binMax) <<" && " << lm3->Integral(8,binMax)<<" && " << lm6->Integral(7,binMax)   <<"/\/\ /\hline"<<endl;
  cout << "MC:" <<  total->IntegralAndError(10,binMax ,err) <<" && " << lm1->Integral(10,binMax) <<" && " << lm3->Integral(10,binMax)<<" && " << lm6->Integral(10,binMax)   <<"/\/\ /\hline"<<endl;
 cout << "MC:" <<  total->IntegralAndError(11,binMax ,err) <<" && " << lm1->Integral(11,binMax) <<" && " << lm3->Integral(11,binMax)<<" && " << lm6->Integral(11,binMax)   <<"/\/\ /\hline"<<endl;
 cout << "MC:" <<  total->IntegralAndError(12,binMax ,err) <<" && " << lm1->Integral(12,binMax) <<" && " << lm3->Integral(12,binMax)<<" && " << lm6->Integral(12,binMax)   <<"/\/\ /\hline"<<endl;
  // cout << "MC:" << err  <<", W: " << errW<<", tt: "<<errtt << ", Z: "<<errZ<<", QCD: "<<  errQCD<< endl;
  */

  //  cout << "data:" << data->Integral() << endl;


  TH1D* hcen = total->Clone();
  TH1D* herr = total->Clone();
  
  herr->SetLineColor(kTeal+3);
  herr->SetMarkerColor(kAzure+6);
  herr->SetFillColor(kAzure+6);
  herr->SetLineWidth(3);
  
  total->SetLineWidth(3);
  total->SetFillColor(kAzure+2);
  total->SetLineColor(kAzure+2);
  total->SetFillStyle(3245);
 
  hcen->SetFillStyle(0);
  hcen->SetMarkerColor(kTeal+3);
  hcen->SetLineColor(kTeal+3);
  hcen->SetLineWidth(3);

  // Merge Z+jets and Z->inv
  bool combine = false;
  
  // Line colour and fill
  qcd->SetLineColor(kPink+4);
  qcd->SetLineWidth(3);
  tt_jets->SetLineColor(kBlue+1);
  tt_jets->SetLineWidth(3);
  
  w_jets->SetLineColor(kPink+7);
  w_jets->SetLineWidth(3);

  z_jets->SetLineWidth(3);
  z_jets->SetLineColor(kTeal-7);
  
  if ( combine ) {
    z_all->SetLineColor(kBlack);
    z_all->SetLineStyle(3);
    z_all->SetLineWidth(1);
  } else {
    data->SetLineColor(1);
    data->SetLineStyle(1);
    data->SetLineWidth(3);
    data->SetMarkerStyle(20);
    data->SetFillColor(0);
  }
  //  lm0->SetLineColor(kRed);
  //  lm0->SetLineWidth(3);
  // lm1->SetLineColor(kRed+3);
  // lm1->SetLineWidth(3);

  // Populate legend
  // legend->AddEntry( data, "tt fully leptonic/", "LP" );
   legend->AddEntry( herr, "full SM", "LP" );
    legend->AddEntry( z_jets, " Z+jets ", "LP" );
    legend->AddEntry( w_jets, " W+jets", "LP" );
    legend->AddEntry( tt_jets, " t#bar{t}", "LP" );
    //  legend->AddEntry( lm3, " SUSY LM3", "LP" );
    //   legend->AddEntry( lm1, " SUSY LM1", "LP" );
    legend->AddEntry( lm6, " data", "LP" );
    // legend->AddEntry(wm,"W Mad","lp");
    
  // Calc maximum number of entries
  double aMax = 0.;
  if( data->GetMaximum()     > aMax ) { aMax = data->GetMaximum()+data->GetBinError(data->GetMaximumBin()); }
  if ( qcd->GetMaximum()     > aMax ) { aMax = qcd->GetMaximum(); }
  //  if ( lm0->GetMaximum()     > aMax ) { aMax = lm0->GetMaximum(); }
  //  if ( lm1->GetMaximum()     > aMax ) { aMax = lm1->GetMaximum(); }
  if ( tt_jets->GetMaximum() > aMax ) { aMax = tt_jets->GetMaximum(); }  
  if ( w_jets->GetMaximum()  > aMax ) { aMax = w_jets->GetMaximum(); }  
  if ( combine ) {
    if ( z_all->GetMaximum()  > aMax ) { aMax = z_all->GetMaximum(); }  
  } else {
    //   if ( data->GetMaximum()   > aMax ) { aMax = z_inv->GetMaximum(); }  
    if ( z_jets->GetMaximum()  > aMax ) { aMax = z_jets->GetMaximum(); }  
  }

  // Calc minimum number of entries
  double aMin = 1.e12;
  if ( qcd->GetMinimum(1.e-12)     < aMin ) { aMin = qcd->GetMinimum(1.e-12); }
  //  if ( lm0->GetMinimum(1.e-12)     < aMin ) { aMin = lm0->GetMinimum(1.e-12); }
  //  if ( lm1->GetMinimum(1.e-12)     < aMin ) { aMin = lm1->GetMinimum(1.e-12); }
  if ( tt_jets->GetMinimum(1.e-12) < aMin ) { aMin = tt_jets->GetMinimum(1.e-12); }  
  if ( w_jets->GetMinimum(1.e-12)  < aMin ) { aMin = w_jets->GetMinimum(1.e-12); }  
  if ( combine ) {
    if ( z_all->GetMinimum(1.e-12)   < aMin ) { aMin = z_all->GetMinimum(1.e-12); }  
  } else {
    // if ( data->GetMinimum(1.e-12)   < aMin ) { aMin = z_inv->GetMinimum(1.e-12); }  
    if ( z_jets->GetMinimum(1.e-12)  < aMin ) { aMin = z_jets->GetMinimum(1.e-12); }  
  }

  if ( qcd ) qcd->GetYaxis()->SetTitleOffset(1.43);
  if ( qcd ) qcd->GetYaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleSize(0.06);
  if ( qcd ) qcd->GetXaxis()->SetTitleOffset(0.9);

 
  if ( log ) {
    if ( qcd ) herr->SetMaximum( aMax * 10. );
    //   if ( qcd ) herr->SetMinimum( aMin * 0.1 );
    if ( qcd ) herr->SetMinimum( 0.005);
  } else {
    if ( qcd ) herr->SetMaximum( aMax * 1.1 );
    //   if ( qcd ) herr->SetMinimum( aMin * 0.9 );
  if ( qcd ) herr->SetMinimum( 0.005);

  }

  /*  TPad* mainPad = new TPad("","",0.01,0.25,0.99,0.99);
  mainPad->SetNumber(1);
  mainPad->SetFillColor(0);
  // mainPad->Range(-288.2483,-2.138147,1344.235,6.918939);
  mainPad->SetFillColor(0);
  mainPad->SetBorderMode(0);
  mainPad->SetBorderSize(2);
  if ( log == true)mainPad->SetLogy();
   mainPad->SetLeftMargin(0.1765705);
  mainPad->SetRightMargin(0.05772496);
  mainPad->SetTopMargin(0.04778761);
  mainPad->SetBottomMargin(0.1256637);
  mainPad->SetFrameFillStyle(0);
  mainPad->SetFrameLineWidth(2);
  mainPad->SetFrameBorderMode(0);
  mainPad->SetFrameFillStyle(0);
  mainPad->SetFrameLineWidth(2);
  mainPad->SetFrameBorderMode(0);
  if ( log == true)mainPad->SetLogy();
  mainPad->Draw();
  TPad*  ratioPad = new TPad("","",0.01,0.01,0.99,0.25);
  ratioPad->SetNumber(2);
  ratioPad->SetFillColor(0);
  ratioPad->SetFillColor(0);
  ratioPad->SetBorderMode(0);
  ratioPad->SetBorderSize(2);
  // if ( log == true)ratioPad->SetLogy();
   ratioPad->SetLeftMargin(0.1765705);
  ratioPad->SetRightMargin(0.05772496);
  ratioPad->SetTopMargin(0.04778761);
  ratioPad->SetBottomMargin(0.1256637);
  ratioPad->SetFrameFillStyle(0);
  ratioPad->SetFrameLineWidth(2);
  ratioPad->SetFrameBorderMode(0);
  ratioPad->SetFrameFillStyle(0);
  ratioPad->SetFrameLineWidth(2);
  ratioPad->SetFrameBorderMode(0);
  //  if ( log == true)ratioPad->SetLogy();
  ratioPad->Draw();
 

  aCanvas->cd(1);
  */

  herr->GetYaxis()->SetTitle("events");


  if ( norm ) {
    if ( qcd ) qcd->DrawNormalized("Ehist");
    // if ( lm0->GetEntries() > 0. )     { lm0->DrawNormalized("hsame"); }
    if ( lm1->GetEntries() > 0. )     { lm1->DrawNormalized("hsame"); }
    if ( tt_jets->GetEntries() > 0. ) { tt_jets->DrawNormalized("hsame"); }
    if ( w_jets->GetEntries() > 0. )  { w_jets->DrawNormalized("hsame"); }
    if ( combine ) {
      if ( z_all->GetEntries() > 0. )   { z_all->DrawNormalized("hsame"); }
    } else {
      if ( data->GetEntries() > 0. )   { z_inv->DrawNormalized("hsame"); }
      if ( z_jets->GetEntries() > 0. )  { z_jets->DrawNormalized("hsame"); }
    }
  } else {
     herr->Draw("hist");
   
   
     // qcd->SetFillStyle(3240);
     // qcd->SetFillColor(kPink+4);
    // qcd->Draw("hist");
    w_jets->Draw("hSameh");
    z_jets->Draw("9Sameh");
    w_jets->Draw("9Sameh");
    tt_jets->Draw("9SAMEh");
    //data1->Draw("9SAMEh");
     //lm0->Draw("9SAMEh");
     lm1->SetLineColor(12);
     lm1->SetLineStyle(2);
     lm1->SetLineWidth(2);
     //     lm1->Draw("9SAMEh");
     lm3->SetLineColor(14);
     lm3->SetLineStyle(2);
     lm3->SetLineWidth(2);
     //  lm3->Draw("9SAMEh");
     lm6->Draw("9SAMEh");
     wm->SetLineStyle(2);
     wm->SetLineColor(kPink+7);
     // wm->Draw("9Sameh");

     // total->DrawNormalized("9E2same");
     //      data->Draw("SAMEh");
    //  tt_jets->Divide(data);
    //  tt_jets->Draw("h");
  //  data->SetLineColor(kRed);
  //  data->Draw("sameh");
     //     data1->SetLineColor(kRed);
     //  data1->Draw("9SAMEP");
  }
  
    legend->Draw();
  // prelim->Draw();
  // alumi->Draw();



  /*  TH1D* ratioBottom = total->Clone();
  TH1D* ratioTop = data->Clone();
  ratioTop->GetYaxis()->SetTitle("data / sim");
  ratioTop->Divide(ratioBottom);
  
  aCanvas->cd(1)->Update();
 
  aCanvas->cd(2);

  ratioTop->SetTitleSize(0.1, "XYZ");
  ratioTop->SetTitleOffset(0.55, "X");
  ratioTop->SetTitleOffset(0.3, "Y");
  ratioTop->SetLabelSize(0.06,"XY");
    
  // ratioTop->GetXaxis().SetRangeUser(MinX,MaxX);
  ratioTop->GetYaxis()->SetRangeUser(0.,2.0);
  ratioTop->Draw();*/
  /* TBox* unity = TBox(ratioTop->GetXaxis()->GetBinLowEdge(ratioTop->GetXaxis()->GetFirst()), 0.89,ratioTop->GetXaxis()->GetBinLowEdge(ratioTop->GetXaxis()->GetLast()), 1.11);
  unity->SetLineWidth(2);
   
  unity->SetLineColor(2);
  unity->SetFillColor(2);
  unity->SetFillStyle(3002);
  unity->Draw();

  */
  file->cd();
 
  aCanvas->SaveAs( std::string(canvas_name+".pdf").c_str() );
  aCanvas->Write();



  //   aCanvas->Print(".png");
 return aCanvas;

}
void SignificanceTestDeltaR(){

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

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

TH1D* allMC = (TH1D*)ttgamma->Clone("all MC");
  allMC->Add(tt);
  allMC->Add(wjets);
  allMC->Add(DY1);
  allMC->Add(DY2);
  allMC->Add(T_tW);
  allMC->Add(Tbar_tW);
  allMC->Add(ZZ);
  allMC->Add(WW);
  allMC->Add(WZ);
  allMC->Add(QCD_all); 

 
  	
TH1D* sigTest = new TH1D("sigTest", "#DeltaR(#gamma, jets) Significance Test", 500/RebinFact, 0, 5);
 	sigTest->GetYaxis()->SetTitle("Significance");
 	//sigTest->SetFillColor(kAzure);
 	//sigTest->SetLineColor(kAzure);
	
	if(Variable == "Photon_deltaR_muons_")
 		sigTest->GetXaxis()->SetTitle("#DeltaR(#gamma, #mu)");
	if(Variable == "Photon_deltaR_jets_")
 		sigTest->GetXaxis()->SetTitle("#DeltaR(#gamma, jets)"); 	
	if(Variable == "Photon_deltaR_electrons_")
 		sigTest->GetXaxis()->SetTitle("#DeltaR(#gamma, e)");
			
	for(int i = 1; i<ttgamma->GetNbinsX(); i++){	
 	
	double ttgammaErr, allErr;
	
	double sigVal = ttgamma->IntegralAndError(i,ttgamma->GetNbinsX(),ttgammaErr) / sqrt(ttgamma->IntegralAndError(i,allMC->GetNbinsX(), allErr));
	double sigErr = sigVal*sqrt(pow(ttgammaErr/ttgamma->Integral(i,ttgamma->GetNbinsX()),2)+pow(allErr/allMC->Integral(i,ttgamma->GetNbinsX()),2));
	
	if(sigVal > 0){
	 
 	sigTest->SetBinContent(i, sigVal);
	sigTest->SetBinError(i, sigErr);
	}
	
std::cout << sigVal << " , pm: " << sigErr << std::endl; 
	
 	}

TCanvas *c1 = new TCanvas("Plot");

	

	sigTest->Draw("E");

	TString plotName("plots/Control/" + Obj + Cut + Type + Next + Variable+"ge1b_sig");
	c1->SaveAs(plotName+".pdf");
	c1->SaveAs(plotName+".png");
	delete c1;

}
Exemplo n.º 11
0
void fakerate_systematics(int istart = 0, int iend = 999)
{
  // histogram name to be used for plotting
  const char * hname = "m_smuon";

  // reference values from standard analysis

  // get default values
  setup("../config/plot.cfg");
  TH1D * hReferenceFakes = fake_estimate_1d("fullrun76", hname);
  double N_ref, R_ref; // N and RMS
  N_ref = hReferenceFakes->IntegralAndError(1, hReferenceFakes->GetNbinsX(), R_ref);

  // list of systematics
  const int nMax = 13; // dont forget to set this when you chance the array below!
  const syst_struct sel[nMax] = {
    { "fullrun75_LooseMuonRelIso_0.2", "" },
    { "fullrun75_LooseMuonRelIso_0.4", "" },
    { "fullrun75_LooseMuonRelIso_0.8", "" },
    { "fullrun75_LooseMuonRelIso_1.0", "" },

    { "fullrun75_TL_jetpt_min_40.", "" },
    { "fullrun75_TL_jetpt_min_60.", "" },
    { "fullrun75_TL_jetpt_min_70.", "" },

    { "fullrun75_TL_met_max_40.", "" },
    { "fullrun75_TL_met_max_60.", "" },
    { "fullrun75_TL_met_max_70.", "" },

    { "fullrun75_TL_mt_max_30.", "" },
    { "fullrun75_TL_mt_max_50.", "" },
    { "fullrun75_TL_mt_max_60.", "" } //,

    // { "fullrun75_smoothsys_off", "" }
  };

  // get all numbers
  TH1D * hFakes[nMax] = { 0 };
  for (int i = istart; i < TMath::Min(iend, nMax); i++) {
    setup(Form("../config/plot%s.cfg", sel[i].cfg));
    hFakes[i] = fake_estimate_1d(sel[i].sel, hname);
  }

  // compute differences
  for (int i = istart; i < TMath::Min(iend, nMax); i++) {
    double N = 0, R = 0; // N and RMS
    if (hFakes[i]) {
      N = hFakes[i]->IntegralAndError(1, hFakes[i]->GetNbinsX(), R);
      delete hFakes[i];
    }
    else {
      ERROR("could not get fakes for selection " << sel[i].sel);
      continue;
    }
    N -= N_ref;
    R = TMath::Sqrt(TMath::Abs(q(R_ref)-q(R)));
    // output table line
    cout << sel[i].sel << ": " 
	 << "N = " << 100.*N/N_ref << " +- " << 100*R/N_ref << "%" << endl;
  }
}
Exemplo n.º 12
0
TGraphAsymmErrors* GetCombinedEfficiency(const TString cut = "min_delta_phi_met_N>4.", const TString preselection="")
{ 
  
  TH1::SetDefaultSumw2();

  const int nbins=16;
  const double varbins[nbins+1]={0,20,40,60,80,100,125,150,175,200,250,300,400,500,600,800,1000};


    
  TCut all(preselection);
  TCut ccut(cut);
  TCut pass(all+ccut);


  TFile *fout = new TFile("macros/qcd_control/output.root", "recreate");
  fout->cd();

  cout << "Denom. cuts: " << (string)all << endl;
  cout << "Num. cuts: " << (string)pass << endl;

  TList* pList=new TList();
  vector<TH1D> v_all, v_pass;

  for (unsigned int sample(0); sample<nSamples; sample++) {
      
    TChain * ch = new TChain();
    ch->Add(qcd_files[sample]+"/reduced_tree");


    TH1D* hMETall = new TH1D(Form("hMETall_%d",sample),"hMETall",nbins,varbins);
    TH1D* hMETpass = new TH1D(Form("hMETpass_%d",sample),"hMETpass",nbins,varbins);

    ch->Project(hMETall->GetName(),"met",all);
    ch->Project(hMETpass->GetName(),"met",pass);

    Double_t e_overflow(0.), i_overflow(0.);
    i_overflow=hMETall->IntegralAndError(nbins,nbins+1,e_overflow);
    hMETall->SetBinContent(nbins, i_overflow);
    hMETall->SetBinError(nbins, e_overflow);
    i_overflow=hMETpass->IntegralAndError(nbins,nbins+1,e_overflow);
    hMETpass->SetBinContent(nbins, i_overflow);
    hMETpass->SetBinError(nbins, e_overflow);

    printf("Sample %d: hMETpass/hMETall=%.1f/%.1f\n",sample, hMETpass->Integral(),hMETall->Integral());

      
    delete ch;

    v_all.push_back(*hMETall);
    v_pass.push_back(*hMETpass);

    delete hMETall;
    delete hMETpass;

  }

  for (unsigned int sample(0); sample<nSamples; sample++) {
    cout << "Found hist " << v_all[sample].GetName() << endl;
    v_all[sample].Write();
    v_pass[sample].Write();
    TEfficiency* pEff = new TEfficiency(v_pass[sample],v_all[sample]);
    pList->Add(pEff);
  }

  TGraphAsymmErrors* gr = TEfficiency::Combine(pList,"v,mode",nSamples,weights);
  return gr;
}
Exemplo n.º 13
0
int makeNorms(double mass = 0, string version = "test", bool alt = false, bool interpSigOnly = false)
{
  LOG(logINFO) << "Normalizing systematic histograms";

  setup(mass, alt);

  stringstream massStr;
  massStr << mass;
  string smass = massStr.str();

  stringstream altStr;
  if (alt) altStr << "_alt";
  string salt = altStr.str();

  int nrBasePoints = 43;
  double* baseMassPoints = new double[nrBasePoints];
  double thisMass = 90;
  double step = 5;
  for (int i=0;i<nrBasePoints;i++)
  {
    baseMassPoints[i] = thisMass;
    if (thisMass >= 200) step = 20;

    thisMass += step;
  }

  // int nrBasePoints = 39;
  // int* baseMassPoints = new int[nrBasePoints];
  // int thisMass = 110;
  // int step = 5;
  // for (int i=0;i<nrBasePoints;i++)
  // {
  //   baseMassPoints[i] = thisMass;
  //   if (thisMass >= 200) step = 20;
  //   thisMass += step;
  // }

  // unnecessary
  int nrPoints = 1;
  double* massPoints = new double[nrPoints];
  massPoints[0] = mass;

  int nrSys = fileNames->size();

  // prepare sample and channel names
  vector<string> sampleNames;
  if (!interpSigOnly)
  {
    if (dost)    sampleNames.push_back("st");
    if (dottbar) sampleNames.push_back("ttbar");
    if (doww)
    {
      if (!splitww)
      {
        sampleNames.push_back("ww");
      }
      else
      {
        sampleNames.push_back("ggww");
        sampleNames.push_back("qqww");
      }
    }
    if(!doOSmSS){//Nina
      if (dowwew)  sampleNames.push_back("wwew");
      if (dowzzz)  sampleNames.push_back("wzzz");
      if (dowzzzew)sampleNames.push_back("wzzzew");
      if (doWgs)   sampleNames.push_back("wgs");
      if (doWg)    sampleNames.push_back("wg");
    }
    if (dozjets)
    {
      if (!splitzjets)
      {
        sampleNames.push_back("zjets");
      } else
      {
        sampleNames.push_back("zleplep");
        sampleNames.push_back("ztautau");
      }
    }
    if (dozjetsew)
    {
      if (!splitzjets)
      {
        sampleNames.push_back("zjetsew");
      } else
      {
        sampleNames.push_back("zleplepew");
        sampleNames.push_back("ztautauew");
      }
    }
    if(doOSmSS){//Nina
      sampleNames.push_back("wjetsminusss");
      sampleNames.push_back("ss");
    }else{
      if (doWjets) sampleNames.push_back("wjets"); 
      if (doQCD)   sampleNames.push_back("qcd");
    }

  }
  for (int imass=0;imass<nrPoints;imass++)
  {
    bool found = false;
    for (int ibase=0;ibase<nrBasePoints;ibase++)
    {
      if (baseMassPoints[ibase] == massPoints[imass])
      {
        found = true;
        break;
      }
    }

    if (!found && !interpSigOnly) continue;
    if (found && interpSigOnly) continue;

    stringstream ggfName;
    ggfName << "ggf" << massPoints[imass];
    
    stringstream ggfName0;
    if(useJHUspin0)
    {
      ggfName0 << "ggH" << massPoints[imass] << "spin0p";
      // ggfName << "ggH" << massPoints[imass] << "spin0p";
    }  
    else
    {
      ggfName0 << "ggf" << massPoints[imass];
      // ggfName << "ggf" << massPoints[imass];
    }

    stringstream ggfName2;
    if(doSpin2plus)  ggfName2 << "ggH" << massPoints[imass] << "spin2p";
    else if(doSpin1plus)  ggfName2 << "ggH" << massPoints[imass] << "spin1p";
    else if(doSpin1minus)  ggfName2 << "ggH" << massPoints[imass] << "spin1m";
    else if(doSpin0minus)  ggfName2 << "ggH" << massPoints[imass] << "spin0m";

    stringstream vbfName;
    vbfName << "vbf" << massPoints[imass];

    stringstream whName;
    whName << "wh" << massPoints[imass];

    stringstream zhName;
    zhName << "zh" << massPoints[imass];

    if (include125BG)
    {
      sampleNames.push_back("ggf125bg");
      sampleNames.push_back("vbf125bg");
      sampleNames.push_back("wh125bg");
      sampleNames.push_back("zh125bg");
    }

    if (!doSpin)
    {
      //if (!doFermi && doggf && !doVBF2j) sampleNames.push_back(ggfName.str());
      //else sampleNames.push_back("ggf125");
      if (doggf) sampleNames.push_back(ggfName.str());
    } else
    {
      if (doggf) sampleNames.push_back(ggfName0.str());
      if (doggf) sampleNames.push_back(ggfName2.str());
    }
    if (dovbf) sampleNames.push_back(vbfName.str());
    if (mass <= 300 && doVH)
    {
      if (dowh) sampleNames.push_back(whName.str());
      if (dozh) sampleNames.push_back(zhName.str());
    }
  }
  delete massPoints;
  delete baseMassPoints;
  int nrSamples = sampleNames.size();
  if (nrSamples == 0) return 0;

  //Aaron Comments this out??...why?
  //vector<string> channelNames;
  //if (doee) channelNames.push_back("ee");
  //if (doem) channelNames.push_back("em");
  //if (splitem && dome) channelNames.push_back("me");
  //if (domm) channelNames.push_back("mm");
  //if (combineCRs) channelNames.push_back("OF");
  //if (combineSFCRs) channelNames.push_back("SF");
  //int nrChannels = channelNames.size();

  //vector<string> jetNames;
  //if (do0j) jetNames.push_back("0j");
  //if (do1j) jetNames.push_back("1j");
  //if (do2j) jetNames.push_back("2j");
  //int nrJets = jetNames.size();

  int nrRegions = regions->size(); 

  TFile** files = new TFile*[nrSamples];

  //save nominal values
  LOG(logINFO) << "Saving nominal values";
  map<string, double> nominals_tot;
  map<string, pair<double, double> > nominals;
  for (int isam=0;isam<nrSamples;isam++)
  {
    stringstream fileName;
    fileName << "rev/" << version << "/hists/Nominal/Normal/" << sampleNames[isam] << ".root";
    TFile* f = new TFile(fileName.str().c_str());
    files[isam] = f;


    //Aaron added this
    int nrReg = regions->size();
    for (int ireg = 0; ireg < nrReg; ireg++)
      {
	Region* r = &(*regions)[ireg];
	int nrChannels = r->channels.size();
	
	for (int ichan = 0; ichan < nrChannels; ichan++)
	  {
	    Channel* c = &r->channels[ichan];
	    string jetName = c->jetName;
	    string channelName = c->name;

    //Aaron comments these out, just to make things faster? to stay out of jet loop? Before went into chan->jet->region, now gos into reg->chan
    //    for (int ichan=0;ichan<nrChannels;ichan++)
    //  {
    //      for (int ijet=0;ijet<nrJets;ijet++)
    //     {
    //        for (int ireg=0;ireg<nrRegions;ireg++)
    //        {
	  

          LOG(logINFO) << "ireg = " << ireg << " / " << nrRegions;
	  string regionName = r->name;//Aaron
          //string regionName = (*regions)[ireg].name; //Aaron comments out
          //Region* r = &(*regions)[ireg];// Aaron comments this out? why?

	  bool skipLoop = skipRegion(r, channelName, jetName);
	  //bool skipLoop = skipRegion(r, channelNames[ichan], jetNames[ijet]); //Aaron comments out
          if (skipLoop) continue;

          LOG(logDEBUG) << "Made it through the gauntlet";

          stringstream histName;
	  histName << channelName << "_" << (*regions)[ireg].name << "_" << jetName;//Aaron
          //histName << channelNames[ichan] << "_" << (*regions)[ireg].name << "_" << jetNames[ijet];
          TH1D* hist = (TH1D*)f->Get(histName.str().c_str());
          LOG(logDEBUG) << "hist: " << hist;
          
          if (!hist)
          {
            LOG(logERROR) << "Couldn't find hist: " << fileName.str().c_str() << "/" << histName.str() << " -- " << sampleNames[isam];
            return 1;
          }

          string nomName = sampleNames[isam] + "_" + histName.str();
          double integral, error;
          integral = hist->IntegralAndError(0, hist->GetNbinsX()+1, error);
          nominals[nomName] = make_pair(integral, error);

          if (isam == 0) nominals_tot[histName.str()] = 0;
          nominals_tot[histName.str()] += integral;

          LOG(logINFO) << "Exiting loop";
	  }//end channels loop
      }//end regions loop
  }//end samples loop
  

  //big loop that does the normalization
  LOG(logINFO) << "Normalizing histograms / computing norms";
  vector<SysInfo> removed;
  vector<SysInfo> warn;
  stringstream outFileName;
  system(("mkdir -vp rev/"+version+"/normHists").c_str());
  ofstream outFile(("rev/"+version+"/normHists/norms_"+smass+salt+(interpSigOnly?"_sig":"")+".txt").c_str());
  for (int isys=0;isys<nrSys;isys++)
  {
    Sys* sys = &(*fileNames)[isys];
    bool first = true;
    LOG(logINFO) << "Processing sys: " << sys->folder;

    bool sym = sys->fileUp == sys->fileDown; // are the variations symmetric?
    for (int isam=0;isam<nrSamples;isam++)
    {
      if (sys->sampleNames.find(sampleNames[isam]) == sys->sampleNames.end()) continue;

      string baseFolder = sys->folder+"/";
      system(("mkdir -vp rev/"+version+"/normHists/"+baseFolder+sys->fileUp).c_str());
      if (!sym) system(("mkdir -vp rev/"+version+"/normHists/"+baseFolder+sys->fileDown).c_str());

      bool doHi = 1;
      bool doLo = 1;

      if (!gSystem->AccessPathName(("rev/"+version+"/normHists/"+baseFolder+sys->fileUp+"/"+sampleNames[isam]+".root").c_str(), kFileExists)) {
	while (!gSystem->AccessPathName(("rev/"+version+"/normHists/"+baseFolder+sys->fileUp+"/"+sampleNames[isam]+".root.lock").c_str(), kFileExists))
	  sleep(30);
	doHi = 0;
      }
      else
	if (sys->folder != "Nominal")
	  gSystem->Exec(("touch rev/"+version+"/normHists/"+baseFolder+sys->fileUp+"/"+sampleNames[isam]+".root.lock").c_str());
      if (!gSystem->AccessPathName(("rev/"+version+"/normHists/"+baseFolder+sys->fileDown+"/"+sampleNames[isam]+".root").c_str(), kFileExists)) {
	while (!gSystem->AccessPathName(("rev/"+version+"/normHists/"+baseFolder+sys->fileDown+"/"+sampleNames[isam]+".root.lock").c_str(), kFileExists))
	  sleep(30);
	doLo = 0;
      }
      else
	if (sys->folder != "Nominal")
	  gSystem->Exec(("touch rev/"+version+"/normHists/"+baseFolder+sys->fileDown+"/"+sampleNames[isam]+".root.lock").c_str());
      if (doHi) system(("cp rev/"+version+"/hists/"+baseFolder+sys->fileUp+"/"+sampleNames[isam]+".root rev/"+version+"/normHists/"+baseFolder+sys->fileUp+"/"+sampleNames[isam]+".root").c_str());
      if (!sym && doLo) system(("cp rev/"+version+"/hists/"+baseFolder+sys->fileDown+"/"+sampleNames[isam]+".root rev/"+version+"/normHists/"+baseFolder+sys->fileDown+"/"+sampleNames[isam]+".root").c_str());

      if (sys->folder == "Nominal") continue;

      TFile* f_hi = new TFile(("rev/"+version+string(doHi?"/normHists/":"/hists/")+baseFolder+sys->fileUp+"/"+sampleNames[isam]+".root").c_str(),doHi?"update":"read");
      TFile* f_lo = sym ? NULL : new TFile(("rev/"+version+string(doLo?"/normHists/":"/hists/")+baseFolder+sys->fileDown+"/"+sampleNames[isam]+".root").c_str(),doLo?"update":"read");


      //Aaron commented out, instead of going chan->jet->region like before, he does reg->chan      
      //     for (int ichan=0;ichan<nrChannels;ichan++)
      //     {
      //        for (int ijet=0;ijet<nrJets;ijet++)
      //       {
      //         for (int ireg=0;ireg<nrRegions;ireg++)
      //          {
      //
      //           Region* r = &(*regions)[ireg];

      int nrReg = regions->size();
      for (int ireg = 0; ireg < nrReg; ireg++)
	{
	  Region* r = &(*regions)[ireg];
	  int nrChannels = r->channels.size();
	  
	  for (int ichan = 0; ichan < nrChannels; ichan++)
	    {
	      Channel* c = &r->channels[ichan];
	      string jetName = c->jetName;
	      string channelName = c->name;
	      
	      bool skipLoop = skipRegion(r, channelName, jetName);
         
            if (skipLoop) continue;
	    
	    string histName = channelName+"_"+(*regions)[ireg].name+"_"+jetName;
            TH1D* h_hi = (TH1D*)f_hi->Get(histName.c_str());
            TH1D* h_lo = sym ? NULL : (TH1D*)f_lo->Get(histName.c_str());
	    
            if (!h_hi || (!sym && !h_lo))
            {
              LOG(logWARNING) << "Hist doesn't exist: " << histName << ", for sys " << sys->folder << " on sample " << sampleNames[isam];
              continue;
            }

            double hi_int = h_hi->Integral();
            double lo_int = sym ? 0 : h_lo->Integral();
	    
            double nom = nominals[sampleNames[isam]+"_"+histName].first;
	    
            LOG(logDEBUG) << "Testing nominal for " << sampleNames[isam] << "_" << histName << ": " << nom;
            if (nom < 0.0001)
	      {
		sys->veto.insert(sampleNames[isam]+"_"+histName);
		continue;
	      }
	    
            double var_up = hi_int/nom - 1; // get the variations
            double var_down = sym ? var_up : lo_int/nom - 1;
            //double var_down = sym ? -var_up/(1+var_up) : lo_int/nom - 1;
	    
            string id = sampleNames[isam] + "_" + sys->folder + "_" + histName;
	    
            if (fabs(var_up) < 0.001) var_up = 0;
            if (fabs(var_down) < 0.001) var_down = 0;
	    
            bool remove = false;
	    
            set<string> flagged; //flag spurious systematics that result from low MC stat
            //       flagged.insert("");
            //       flagged.insert("");
            flagged.insert("");
            if (flagged.find(id) != flagged.end()) remove = true;
            if (((id.find("ttbar") != string::npos || id.find("st") != string::npos) &&
                 /*id.find("JES") != string::npos &&*/ id.find("0j") != string::npos)) remove = true;
            if(doABCD2j && (id.find("SF") != string::npos || id.find("mm") != string::npos || id.find("ee") != string::npos) && id.find("signalLike") != string::npos && id.find("2j") != string::npos && (id.find("ztautau") != string::npos || id.find("zjets") != string::npos || id.find("zleplep") != string::npos) && id.find("ew") == string::npos) remove = true;
	    
            //pick up any spurious systematics not otherwise flagged
            //if (var_up <= -0.99 || var_down <= -0.99 || var_up > 2 || var_down > 2) remove = true;
            if (var_up <= -0.8 || var_down <= -0.8 || var_up > 1.5 || var_down > 1.5) remove = true;
	    
	    
            if (remove) // remove by setting to zero
	      {
		SysInfo info;
		info.id=id;
		info.hi=var_up;
		info.lo=var_down;
		removed.push_back(info);
		
		var_up=0;
		var_down=0;
	      }
	    
	    
            if (fabs(var_up) > 0.5 || fabs(var_down) > 0.5)
	      {
		SysInfo info;
		info.id=id;
		info.hi=var_up;
		info.lo=var_down;
		warn.push_back(info);
	      }
	    
	    
            //no need to consider very small systematics. they do nothing but slow down computations
            if ((fabs(var_up) > 0.005 || fabs(var_down) > 0.005) && sys->isNorm )
	      {
		if (first)
		  {
		    
		    outFile << "seed " << sys->folder << "\n"
			    << "range -5 5\n"
			    << "type bifur_gaus\n";
		    first=false;
		  }
		
		outFile << "uncert " << id << " " << var_up << " " << var_down << "\n";
		
	      }
	    
            //normalize
            h_hi->Scale(nom/hi_int);
            if (h_lo) h_lo->Scale(nom/lo_int);
	    
            //determine if it's negligible
            if (sys->isShape)
	      {
		TH1D* nomHist = (TH1D*)files[isam]->Get(histName.c_str());
		bool isNegligible = true;
		int nrBins = h_hi->GetNbinsX();
		for (int ib=0;ib<nrBins;ib++)
		  {
		    double nom_content = nomHist->GetBinContent(ib+1);
		    //                 if (nom_content < 0.00001) continue;
		    double hi_content = h_hi->GetBinContent(ib+1);
		    double lo_content = h_lo ? h_lo->GetBinContent(ib+1) : nom_content;
		    double var_hi = hi_content / nom_content - 1;
		    double var_lo = lo_content / nom_content - 1;

		    if (fabs(var_hi) > 0.01 || fabs(var_lo) > 0.01)
		      {
			isNegligible = false;
			break;
		      }
		  }
		
		if (isNegligible)
		  {
		    LOG(logWARNING) << "Negligible shape systematic : " << sampleNames[isam] << "_" << histName << " for " << sys->folder;
		    sys->veto.insert(sampleNames[isam]+"_"+histName);
		  }
	      }//end of determine if negligible loop
	    }//end of channel loop
        }//end or region loop
      
      
      //write
      if (doHi) {
	f_hi->Write();
	gSystem->Exec(("rm -f rev/"+version+"/normHists/"+baseFolder+sys->fileUp+"/"+sampleNames[isam]+".root.lock").c_str());
      }
      f_hi->Close();
      if (f_lo)
      {
        if (doLo) {
	  f_lo->Write();
	  gSystem->Exec(("rm -f rev/"+version+"/normHists/"+baseFolder+sys->fileDown+"/"+sampleNames[isam]+".root.lock").c_str());
	}
        f_lo->Close();
	delete f_lo;
      }
      delete f_hi;
    }

    outFile << "\n";
  }
  outFile.close();

  for (int isam=0;isam<nrSamples;isam++)
  {
    files[isam]->Close();
  }
  delete files;

  //print warnings of very large systematics
  int nrRemove=removed.size();
  for (int i=0;i<nrRemove;i++)
  {
    SysInfo* info = &removed[i];
    LOG(logWARNING) << "Removing spurious systematic: " << info->id << " " << info->hi << " " << info->lo;
  }

  ofstream warnFile(("rev/"+version+"/normHists/"+"warned_"+smass+salt+".txt").c_str());

  int nrWarn=warn.size();
  for (int i=0;i<nrWarn;i++)
  {
    SysInfo* info = &warn[i];
    LOG(logWARNING) << "WARNING::Spurious systematic remaining: " << info->id << " " << info->hi << " " << info->lo;
    warnFile << "flagged.insert(\"" << info->id << "\");\n";
  }

  if (interpSigOnly) return 0;

  //save statistical uncertainties and wjets systematics
  if (doData) system(("cp rev/"+version+"/hists/Nominal/Normal/data.root rev/"+version+"/normHists/Nominal/Normal/data.root").c_str());

  return 0;
}