Example #1
0
void integrateHist(TH1F* hist) {
   int nentries = hist->GetNbinsX();
   TH1F *historig = (TH1F*) hist->Clone("historig");
   for (int i=1; i<nentries+2; i++) {
      double val, err;
      val = historig->IntegralAndError(0,i,err);
      hist->SetBinContent(i,val);
      hist->SetBinError(i,err);
   }
   delete historig;
}
Example #2
0
void ootpu_fit(TString files, TString comments="") {

  TChain* chain = new TChain("reduced_tree");
  chain->Add(files);

  TH1::SetDefaultSumw2();

  TH1F* hrelIso = new TH1F("hrelIso","", 30, 0, 0.5);
  TH1F* hOOTPU = new TH1F("hOOTPU","", 75, 0, 75);
  TH1F* hOOTPUvsIso = new TH1F("hOOTPUvsIso",";Out-of-time ints.;Isolation cut efficiency", 15, 0, 75);

  hrelIso->StatOverflows(true);
  
  int n1(0), n2(0);
  if (files.Contains("20bx25")) {
    n1=15;
    n2=75;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  int low = 15; 
  for (int bin(1); bin<hOOTPUvsIso->GetNbinsX()+1; bin++) {
    if (bin<4) continue;
    if (bin>4) low=low+5;
    if (low>hOOTPUvsIso->GetBinLowEdge(hOOTPUvsIso->GetNbinsX())) break;
    TString cuts = Form("(%s)&&(oot_pu>=%d&&oot_pu<%d)",mu.Data(),low,low+4);
    cout << "Cuts: " << cuts.Data() << endl;
    chain->Project(hrelIso->GetName(), "muon_relIso", cuts);
    chain->Project(hOOTPU->GetName(), "oot_pu", cuts);
    hrelIso->Scale(1/hrelIso->GetEntries());
    Double_t left(0.), lerror(0.), right(0.), rerror(0.);
    left = hrelIso->IntegralAndError(1,12,lerror);
    right = hrelIso->IntegralAndError(13,31,rerror);
    float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
    printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
    hOOTPUvsIso->SetBinContent(bin,left/(left+right));
    hOOTPUvsIso->SetBinError(bin,rat_error);
  }
  
  hOOTPUvsIso->SetLineColor(1);
  hOOTPUvsIso->SetMarkerColor(1);
  hOOTPUvsIso->SetMarkerStyle(20);

  TCanvas* c1 = new TCanvas();

  hOOTPUvsIso->Draw("e1");

  // do a linear fit
  TF1 *flin = new TF1("flin", "1 ++ x", 15, 75);
  hOOTPUvsIso->Fit(flin);
  flin=hOOTPUvsIso->GetFunction("flin");
  flin->SetLineColor(kBlue);
  flin->SetLineWidth(2);

  TString plotTitle ="OOTPU_fit"+comments+".pdf";
  c1->Print(plotTitle);

  // cout << "Rejection rates" << endl;
  // Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  // left = hA->IntegralAndError(1,12,lerror);
  // right = hA->IntegralAndError(13,31,rerror);
  // float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hB->IntegralAndError(1,12,lerror);
  // right = hB->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hC->IntegralAndError(1,12,lerror);
  // right = hC->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  // left = hD->IntegralAndError(1,12,lerror);
  // right = hD->IntegralAndError(13,31,rerror);
  // rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  // printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
Example #3
0
void ootpu_comparison(TString files, TString var, TString title, int nbins, float low, float high, TString comments="") {

  TChain* chain = new TChain("reduced_tree");
  chain->Add(files);

  TH1::SetDefaultSumw2();

  TH1F* hA = new TH1F("hA",title, nbins, low, high);
  TH1F* hB = new TH1F("hB",title, nbins, low, high);
  TH1F* hC = new TH1F("hC",title, nbins, low, high);
  TH1F* hD = new TH1F("hD",title, nbins, low, high);

  TH1F* hA_l = new TH1F("hA_l",title, nbins, low, high);
  TH1F* hB_l = new TH1F("hB_l",title, nbins, low, high);
  TH1F* hC_l = new TH1F("hC_l",title, nbins, low, high);
  TH1F* hD_l = new TH1F("hD_l",title, nbins, low, high);
  hA->SetStats(0);
  hA->GetYaxis()->SetLabelSize(0.04);
  //hA->GetYaxis()->SetTitleOffset(1.3);
  hA->GetXaxis()->SetTitleOffset(1.1);
  hA->GetXaxis()->SetTitleFont(132);
  hA->GetXaxis()->SetTitleSize(0.042);
  hA->GetXaxis()->SetLabelSize(0.04);
  hA->SetLineWidth(2);

  //  hA->StatOverflows(true);
  //  hB->StatOverflows(true);
  //  hC->StatOverflows(true);
  //  hD->StatOverflows(true);

  int n1(0), n2(0), n3(0), n4(0), n5(0);
  if (files.Contains("20bx25")) {
    n1=5;
    n2=17;
    n3=21;
    n4=25;
    n5=40;
  }
  else if (files.Contains("S14")) {
    n1=0;
    n2=25;
    n3=40;
    n4=55;
    n5=120;
  }
  else { // default: 8 TeV scenario
    n1=0;
    n2=15;
    n3=22;
    n4=32;
    n5=70;
  }


  TString mu("num_gen_muons==1&&muon_reco_match>=0");
  //if (files.Contains("PU_S10")) {
  TString cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n1,n2);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hA", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n1,n2);
  chain->Project("hA_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n2,n3);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hB", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n2,n3);
  chain->Project("hB_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d&&eoot_pu<%d)",mu.Data(),n3,n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hC", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d&&loot_pu<%d)",mu.Data(),n3,n4);
  chain->Project("hC_l", var, cuts);
  cuts = Form("(%s)&&(eoot_pu>=%d)",mu.Data(),n4);
  cout << "Cuts: " << cuts.Data() << endl;
  chain->Project("hD", var, cuts);
  cuts = Form("(%s)&&(loot_pu>=%d)",mu.Data(),n4);
  chain->Project("hD_l", var, cuts);
  // }
  // else {
  //  }
  
  float avg1(hA->GetMean());
  float avg2(hB->GetMean());
  float avg3(hC->GetMean());
  float avg4(hD->GetMean());

  hA->Scale(1/hA->Integral());
  hB->Scale(1/hB->Integral());
  hC->Scale(1/hC->Integral());
  hD->Scale(1/hD->Integral());

  hA->SetLineColor(1);
  hB->SetLineColor(2);
  hC->SetLineColor(3);
  hD->SetLineColor(4);

  hA->SetLineWidth(2);
  hB->SetLineWidth(2);
  hC->SetLineWidth(2);
  hD->SetLineWidth(2);

  float avg1_l(hA_l->GetMean());
  float avg2_l(hB_l->GetMean());
  float avg3_l(hC_l->GetMean());
  float avg4_l(hD_l->GetMean());

  hA_l->Scale(1/hA_l->Integral());
  hB_l->Scale(1/hB_l->Integral());
  hC_l->Scale(1/hC_l->Integral());
  hD_l->Scale(1/hD_l->Integral());

  hA_l->SetLineColor(12);
  hB_l->SetLineColor(46);
  hC_l->SetLineColor(8);
  hD_l->SetLineColor(7);

  hA_l->SetLineWidth(2);
  hB_l->SetLineWidth(2);
  hC_l->SetLineWidth(2);
  hD_l->SetLineWidth(2);

  TCanvas* c1 = new TCanvas();
  float max = TMath::Max(hA->GetMaximum(), hB->GetMaximum());
  if (hC->GetMaximum()>max) max = hC->GetMaximum();
  if (hD->GetMaximum()>max) max = hD->GetMaximum();

  hA->SetMaximum(max*1.1);
  hA->Draw("hist");
  hB->Draw("hist,same");
  hC->Draw("hist,same");
  hD->Draw("hist,same");
  hA_l->Draw("hist,same");
  hB_l->Draw("hist,same");
  hC_l->Draw("hist,same");
  hD_l->Draw("hist,same");

  TLegend* leg = new TLegend(0.42,0.6,0.9,0.9);
  leg->SetFillStyle(0);
  char label[1000];
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n1,n2,avg1);
  leg->AddEntry(hA,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n2,n3,avg2);
  leg->AddEntry(hB,label,"lp");
  sprintf(label,"%d#leqEarly Ints.<%d (#mu=%3.3f)",n3,n4,avg3);
  leg->AddEntry(hC,label,"lp");
  sprintf(label,"Early Ints.>%d (#mu=%3.3f)",n4,avg4);
  leg->AddEntry(hD,label,"lp");
  // leg->Draw();

  TString plotTitle ="relIso_vs_early_and_late_OOTPU_"+var+comments+".pdf";
  c1->Print(plotTitle);

  cout << "Rejection rates" << endl;
  Double_t left(0.), lerror(0.), right(0.), rerror(0.);
  left = hA->IntegralAndError(1,12,lerror);
  right = hA->IntegralAndError(13,31,rerror);
  float rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin1: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hB->IntegralAndError(1,12,lerror);
  right = hB->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin2: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hC->IntegralAndError(1,12,lerror);
  right = hC->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin3: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
  left = hD->IntegralAndError(1,12,lerror);
  right = hD->IntegralAndError(13,31,rerror);
  rat_error=sqrt((left*left*rerror*rerror+right*right*lerror*lerror)/((left+right)*(left+right)));
  printf("bin4: %3.2f +/- %3.3f\n", left/(left+right),rat_error);
}
Example #4
0
void bbtt_upg_em(std::string var,int nbins, double xmin, double xmax,std::string xtitle, std::string ytitle, double sigscale=1)
{

  TFile *outDC = new TFile("hh_em_inputs.root","RECREATE");

  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);
 
  //std::string dir = "/data/blue/Bacon/029a/Upgrade/merged_talk_jun30/";
  std::string dir = "/afs/cern.ch/work/j/jlawhorn/public/ntuples/";
  
  std::stringstream scale; scale << sigscale;
  
  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(tauCat1==3 && tauCat2==2 && ptTau1>20 && ptTau2>20 && tauIso2<0.4 && tauIso1<0.4 && (bTag1==2||bTag1==3||bTag1==6||bTag1==7) && (bTag2==1||bTag2==3||bTag2==6||bTag2==7) && ptB1>20 && ptB2>20 && sqrt( (etaTau1-etaTau2)**2 + (phiTau1-phiTau2)**2 )>0.4)";
  std::string jetcut = objcut+"*(mTT>20 && mTT<90)*(mBB1>70 && mBB1<140)*(mt2pileup>100)*(bdtVal>-0.05)";
  //signal region
  std::string mccut = jetcut+"*eventWeight*"+lumi.str();
  std::string sigcut = jetcut+"*eventWeight*"+lumi.str();
  std::string zjetcut = jetcut+"*eventWeight*(eventType==4)*"+lumi.str();
  std::string wjetcut = jetcut+"*eventWeight*(eventType==3)*"+lumi.str();
  std::string ewkcut = jetcut+"*eventWeight*(eventType!=1)*"+lumi.str();
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *hhtree = load(dir+"HHToTTBB_14TeV.root"); 
  TTree *tttree = load(dir+"tt.root"); 
  //TTree *vbfhtree = load(dir+"VBFToTT_14TeV_phase2.root");
  //TTree *gfhtree = load(dir+"H.root");
  //TTree *vjettree = load(dir+"Vjets.root");
  //TTree *ewktree = load(dir+"diboson.root");
  
  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  /*  TH1F *Ztt = new TH1F("DY","",nbins,xmin,xmax);
  vardraw = var+">>"+"DY";
  vjettree->Draw(vardraw.c_str(),zjetcut.c_str());
  InitHist(Ztt  , xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);*/
  TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  vardraw = var+">>"+"TTbar";
  tttree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  /*  TH1F *wjets = new TH1F("Wjets","",nbins,xmin,xmax);
  vardraw = var+">>"+"Wjets";
  vjettree->Draw(vardraw.c_str(),wjetcut.c_str());
  InitHist(wjets, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(222,90,106), 1001);
  TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ewk";
  ewktree->Draw(vardraw.c_str(),ewkcut.c_str());
  InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *vbfh = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  vbfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(vbfh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);
  TH1F *ggh = new TH1F("GGH","",nbins,xmin,xmax);
  vardraw = var+">>"+"GGH";
  gfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ggh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);*/
  TH1F *smhh = new TH1F("SMhh","",nbins,xmin,xmax);
  vardraw = var+">>"+"SMhh";
  hhtree->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(smhh);
  smhh->SetLineColor(kBlack);
  delete canv0;
  //---------------------------------------------------------------------------
  //Print out the yields
  Double_t error=999;
  //ofstream outfile;
  //outfile.open("yields.txt");
  //outfile << "Yields for the signal region." << std::endl;
  cout << "SM hh   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "SM h   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "Ztt    "  << Ztt->IntegralAndError(0,Ztt->GetNbinsX(),error) << "+/-" << error << endl;*/
  cout << "ttbar    "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  /*  outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
      outfile << "wjets    "  << wjets->IntegralAndError(0,wjets->GetNbinsX(),error) << "+/-" << error << endl;*/
  //--------------------------------------------------------------------------
  //outfile.close();
  outDC->cd();
  TDirectory* lTD = outDC->mkdir("emu");
  outDC->cd(lTD->GetPath());
  ttbar->SetName("data_obs");
  ttbar->SetTitle("data_obs");
  ttbar->Write();
  /*Ztt->SetName("ZTT");
  Ztt->SetTitle("ZTT");
  Ztt->Write();*/
  ttbar->SetName("TT");
  ttbar->SetTitle("TT");
  ttbar->Write();
  /*wjets->SetName("W");
  wjets->SetTitle("W");
  wjets->Write();
  ewk->SetName("VV");
  ewk->SetTitle("VV");
  ewk->Write();
  vbfh->SetName("qqH");
  vbfh->SetTitle("qqH");
  vbfh->Write();
  ggh->SetName("ggH");
  ggh->SetTitle("ggH");
  ggh->Write();*/
  smhh->SetName("ggHH");
  smhh->SetTitle("ggHH");
  smhh->Write();
  outDC->Close();
  //stack some  histtograms together
  //vbfh->Add(ggh); 
  //wjets->Add(ewk); 
  //-----------------------------------------------------------------------
  smhh->Scale(sigscale);
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //wjets->Add(ttbar);  //Ztt->Add(wjets); 
  //vbfh->Add(Ztt);
  //Error band stat
  //TH1F* errorBand = (TH1F*)vbfh ->Clone("errorBand");
  TH1F* errorBand = (TH1F*)ttbar ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  ttbar->SetMaximum(1.1*std::max(maximum(ttbar, 0), maximum(smhh, 0)));
  //blind(data,75,150);
  //data->Draw("e");
  //vbfh->Draw("hist");
  //Ztt->Draw("histsame");
  //wjets->Draw("histsame");
  //ttbar->Draw("histsame");
  ttbar->SetTitle("");
  ttbar->Draw("hist"); 
  //data->Draw("esame");
  errorBand->Draw("e2same");
  smhh->Draw("histsame");
  canv->RedrawAxis();
  //canv->SetLogy(1);
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(smhh  , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale) , "L" );
  //leg->AddEntry(smhh , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale1) , "L" );
  //leg->AddEntry(data , "Observed"                       , "LP");
  //leg->AddEntry(vbfh  , "SM H#rightarrow#tau#tau"   , "F" );
  //leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  //leg->AddEntry(wjets  , "Electroweak"                    , "F" );
  leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
   
  //CMS preliminary 
  const char* dataset = "CMS Simulation, 3000 fb^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_em.png").c_str());
  
  /*
    Ratio Data over MC
  */
  /*
  TCanvas *canv1 = MakeCanvas("canv0", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)vbfh->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    //model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    model->SetBinError  (ibin+1, 0);
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ttbar->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)vbfh->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  //stat1->Draw();
  canv1->Print((var+"_ratio.png").c_str());
  */
}
void computeOSWeights_CR(int erg_tev, int iCR, double m4l_low, double m4l_high){
//  if (iCR>2 || iCR==1) return;
  char TREE_NAME[]="SelectedTree";

  int EnergyIndex=0; if (erg_tev==8)EnergyIndex=1;
  double my_luminosity = luminosity[EnergyIndex];

  TString erg_dir;
  erg_dir.Form("LHC_%iTeV", erg_tev);
  TString comstring;
  comstring.Form("%iTeV", erg_tev);

  TChain* tc = new TChain(TREE_NAME);

  TString cinput_common_noSIP = user_dir_hep + "No_SIP/" + erg_dir + "/CR/";
  if (iCR<2){
    int sampleindex = kAllSamples-1 + iCR;
    TString cinput = cinput_common_noSIP;
    cinput = cinput + sample_FullSim[sampleindex] + ".root";
    tc->Add(cinput);
  }
  else{
    for (int smp=kGGSamples; smp<kQQBZZSamples; smp++){
      TString cinput = cinput_common_noSIP;
      cinput = cinput + sample_FullSim[smp] + "_CRZLLTree.root";
      tc->Add(cinput);
    }
  }

  if (tc->GetEntries() == 0){
    cout << "Could not find any files, aborting..." << endl; return;
  }
  else if (iCR==2) cout << "qqZZ CR: " << tc->GetEntries() << endl;

  TString coutput_common = user_dir_hep + "Analysis/Auxiliary/";

  TFile* frecord;
  TString fname = "OSfakeweights_";
  if (iCR==0) fname.Append("ZLL_");
  else if (iCR==1) fname.Append("ZL_");
  else if (iCR==2) fname.Append("QQBZZ_");
  fname += comstring;
  fname.Append(Form("_m4l_%.1f_%.1f%s", m4l_low, m4l_high, ".root"));
  fname.Prepend(coutput_common);
  frecord = new TFile(fname, "recreate");

  TFile* foutput[3];

  TH1F* hOS[4];
  TFile* fweight[2] ={
    new TFile(Form("./data/Zmu_OS_%iTeV.root", erg_tev)),
    new TFile(Form("./data/Ze_OS_%iTeV.root", erg_tev))
  };
  hOS[0] = (TH1F*)fweight[0]->Get("h1D_FRmu_EB");
  hOS[1] = (TH1F*)fweight[0]->Get("h1D_FRmu_EE");
  hOS[2] = (TH1F*)fweight[1]->Get("h1D_FRel_EB");
  hOS[3] = (TH1F*)fweight[1]->Get("h1D_FRel_EE");

  frecord->cd();

  TString hname = "htemp";

  float GenHMass;
  float ZXfake_weight,MC_weight,MC_weight_QQBZZEWK;
  int CRflag;
  float Lep1combRelIsoPF, Lep2combRelIsoPF, Lep3combRelIsoPF, Lep4combRelIsoPF;
  bool Lep1isID, Lep2isID, Lep3isID, Lep4isID;
  short Z1ids;
  short Z2ids;
  float PFMET;

  float Lep1_Z1SIP, Lep2_Z1SIP, Lep3_Z1SIP, Lep4_Z1SIP;
  float Lep1SIP, Lep2SIP, Lep3SIP, Lep4SIP;
  int Lep1ID, Lep2ID, Lep3ID, Lep4ID;

  float Z1Mass, Z2Mass, ZZMass, ZZPt, ZZEta, ZZPhi;
  float KalmanCandVtx_x, KalmanCandVtx_y, KalmanCandVtx_z, KalmanCandVtx_chi2;
  float OfflinePrimaryVtx_x, OfflinePrimaryVtx_y, OfflinePrimaryVtx_z;

  float Lep1Pt, Lep2Pt, Lep3Pt, Lep4Pt;
  float Lep1Eta, Lep2Eta, Lep3Eta, Lep4Eta;

  tc->SetBranchAddress("ZXfake_weight", &ZXfake_weight);
  tc->SetBranchAddress("CRflag", &CRflag);

  tc->SetBranchAddress("Z1ids", &Z1ids);
  tc->SetBranchAddress("Z2ids", &Z2ids);
  tc->SetBranchAddress("Lep1ID", &Lep1ID);
  tc->SetBranchAddress("Lep1isID", &Lep1isID);
  tc->SetBranchAddress("Lep1combRelIsoPF", &Lep1combRelIsoPF);
  tc->SetBranchAddress("Lep2ID", &Lep2ID);
  tc->SetBranchAddress("Lep2isID", &Lep2isID);
  tc->SetBranchAddress("Lep2combRelIsoPF", &Lep2combRelIsoPF);
  tc->SetBranchAddress("Lep3ID", &Lep3ID);
  tc->SetBranchAddress("Lep3isID", &Lep3isID);
  tc->SetBranchAddress("Lep3combRelIsoPF", &Lep3combRelIsoPF);

  tc->SetBranchAddress("PFMET", &PFMET);
  tc->SetBranchAddress("Z1Mass", &Z1Mass);
  tc->SetBranchAddress("Z2Mass", &Z2Mass);
  tc->SetBranchAddress("ZZMass", &ZZMass);
  tc->SetBranchAddress("ZZPt", &ZZPt);
  tc->SetBranchAddress("ZZEta", &ZZEta);
  tc->SetBranchAddress("ZZPhi", &ZZPhi);
  tc->SetBranchAddress("OfflinePrimaryVtx_x", &OfflinePrimaryVtx_x);
  tc->SetBranchAddress("OfflinePrimaryVtx_y", &OfflinePrimaryVtx_y);
  tc->SetBranchAddress("OfflinePrimaryVtx_z", &OfflinePrimaryVtx_z);
  tc->SetBranchAddress("KalmanCandVtx_x", &KalmanCandVtx_x);
  tc->SetBranchAddress("KalmanCandVtx_y", &KalmanCandVtx_y);
  tc->SetBranchAddress("KalmanCandVtx_z", &KalmanCandVtx_z);

  tc->SetBranchAddress("Lep1Pt", &Lep1Pt);
  tc->SetBranchAddress("Lep2Pt", &Lep2Pt);
  tc->SetBranchAddress("Lep3Pt", &Lep3Pt);
  tc->SetBranchAddress("Lep1Eta", &Lep1Eta);
  tc->SetBranchAddress("Lep2Eta", &Lep2Eta);
  tc->SetBranchAddress("Lep3Eta", &Lep3Eta);


  tc->SetBranchAddress("KalmanCandVtx_chi2", &KalmanCandVtx_chi2);
  tc->SetBranchAddress("Lep1_Z1SIP", &Lep1_Z1SIP);
  tc->SetBranchAddress("Lep2_Z1SIP", &Lep2_Z1SIP);
  tc->SetBranchAddress("Lep3_Z1SIP", &Lep3_Z1SIP);
  tc->SetBranchAddress("Lep1SIP", &Lep1SIP);
  tc->SetBranchAddress("Lep2SIP", &Lep2SIP);
  tc->SetBranchAddress("Lep3SIP", &Lep3SIP);

  if (iCR!=1){
    tc->SetBranchAddress("Lep4ID", &Lep4ID);
    tc->SetBranchAddress("Lep4isID", &Lep4isID);
    tc->SetBranchAddress("Lep4combRelIsoPF", &Lep4combRelIsoPF);
    tc->SetBranchAddress("Lep4_Z1SIP", &Lep4_Z1SIP);
    tc->SetBranchAddress("Lep4SIP", &Lep4SIP);
    tc->SetBranchAddress("Lep4Pt", &Lep4Pt);
    tc->SetBranchAddress("Lep4Eta", &Lep4Eta);
  }
  if (iCR==2){
    tc->SetBranchAddress("MC_weight", &MC_weight);
    tc->SetBranchAddress("GenHMass", &GenHMass);
  }

  for (int iwgt=0; iwgt<2; iwgt++){
    if (iCR==1 && iwgt==1) continue;
    for (int isocut=0; isocut<4; isocut++){
      if (iCR==1 && isocut>=2) continue;
      if (isocut<2) continue;

      for (int iM1cut=0; iM1cut<1; iM1cut++){
        if (iM1cut==2 && iCR!=1) continue;
        if (iwgt==0) cout << "Un-weighted";
        else cout << "Weighted";
        if (isocut>=1) cout << ", " << strLepIsoCut_label[isocut-1];
        cout << ", " << Z1masswidth_label[iM1cut] << endl;
        cout << "\t"; for (int icut=0; icut<nSIPCuts; icut++) cout << cutLabel[icut] << '\t' << cutLabel[icut] << " Error\t";
        cout << endl;
        for (int catZ1=0; catZ1<2; catZ1++){
          for (int catZ2=0; catZ2<(iCR!=1 ? 3 : 2); catZ2++){
//          for (int catZ2=0; catZ2<(iCR!=1 ? 6 : 2); catZ2++){
            cout << strZ1Category_label[catZ1] << " ";
            if (iCR!=1) cout << strZ2Category_label[catZ2];
            else cout << strLep3Category_label[catZ2];
            for (int icut=0; icut<nSIPCuts; icut++){
              gStyle->SetTitleFont(62, "t");
              gROOT->SetStyle(gStyle->GetName());
              gROOT->ForceStyle();

              TH1F* hsip = new TH1F(hname, "", 1, 0, 1000);
              hsip->Sumw2();

              double ptbins[9]={ 0, 5, 7, 10, 20, 30, 40, 50, 80 };
              double etabins[3]={ 0, 1.2, 2.5 };
              if ((iCR==1 && catZ2==1) || (iCR!=1 && (catZ2==2 || catZ2==3))) etabins[1]=1.45;

//              const int nbinsTxy = 60;
//              double Txybins[nbinsTxy+1];
//              for (int bin=0; bin<=nbinsTxy; bin++)Txybins[bin] = -1400.+2800.*bin/nbinsTxy;
              const int nbinsTxy = 7;
              double Txybins[nbinsTxy+1]={-2000,-500,-200,-50,50,200,500,2000};
/*              const int nbinsmZZ = 4;
              double mZZbins[nbinsmZZ+1]={ 100, 140.6, 170, 250, m4l_high };
              const int nbinsmZ1 = 10;
              double mZ1bins[nbinsmZ1+1];
              for (int bin=0; bin<=nbinsmZ1; bin++)mZ1bins[bin] = 0.+120.*bin/nbinsmZ1;
              const int nbinsmZ2 = 6;
              double mZ2bins[nbinsmZ2+1];
              for (int bin=0; bin<=nbinsmZ2; bin++)mZ2bins[bin] = 12.+132.*bin/nbinsmZ2;
*/
              const int nbinsmZZ = 4;
              double mZZbins[nbinsmZZ+1]={ 0, 100, 140, 170, 3000 };
              const int nbinsmZ1 = 5;
              double mZ1bins[nbinsmZ1+1]={ 0, 40, 62.5, 85, 97.5, 120 };
              const int nbinsmZ2 = 3;
              double mZ2bins[nbinsmZ2+1]={ 0, 35, 65, 150 };

              TH2F* hmZZTxyOS;
              TH2F* hmZZTxyOS_extra;
              TH3F* hmZZmZ1mZ2OS;
              TH3F* hmZZmZ1mZ2OS_extra;
              if (iCR!=1 && isocut>1 && catZ2<3){
                hmZZTxyOS = new TH2F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_Txy_OS"), "", nbinsmZZ, mZZbins, nbinsTxy, Txybins);
                hmZZTxyOS->Sumw2();
                hmZZTxyOS->SetXTitle("m_{4l} (GeV)");
                hmZZTxyOS->SetYTitle("T_{xy} (#mum)");
                hmZZTxyOS->SetZTitle("Events / bin");
                hmZZTxyOS->SetOption("colz");

                hmZZmZ1mZ2OS = new TH3F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS"), "", nbinsmZZ, mZZbins, nbinsmZ1, mZ1bins, nbinsmZ2, mZ2bins);
                hmZZmZ1mZ2OS->Sumw2();
                hmZZmZ1mZ2OS->SetXTitle("m_{4l} (GeV)");
                hmZZmZ1mZ2OS->SetYTitle("m_{1} (GeV)");
                hmZZmZ1mZ2OS->SetZTitle("m_{2} (GeV)");
                hmZZmZ1mZ2OS->SetOption("box");
                if (isocut==2 && iwgt>0){
                  hmZZTxyOS_extra = new TH2F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_Txy_OS_2p2fin3p1f"), "", nbinsmZZ, mZZbins, nbinsTxy, Txybins);
                  hmZZTxyOS_extra->Sumw2();
                  hmZZTxyOS_extra->SetXTitle("m_{4l} (GeV)");
                  hmZZTxyOS_extra->SetYTitle("T_{xy} (#mum)");
                  hmZZTxyOS_extra->SetZTitle("Events / bin");
                  hmZZTxyOS_extra->SetOption("colz");

                  hmZZmZ1mZ2OS_extra = new TH3F(produceCRname(iCR, iwgt, isocut, iM1cut, catZ1, catZ2, icut, "mZZ_mZ1mZ2_OS_2p2fin3p1f"), "", nbinsmZZ, mZZbins, nbinsmZ1, mZ1bins, nbinsmZ2, mZ2bins);
                  hmZZmZ1mZ2OS_extra->Sumw2();
                  hmZZmZ1mZ2OS_extra->SetXTitle("m_{4l} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetYTitle("m_{1} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetZTitle("m_{2} (GeV)");
                  hmZZmZ1mZ2OS_extra->SetOption("box");
                }
              }


              for (int ev=0; ev<tc->GetEntries(); ev++){
                MC_weight=1;
                MC_weight_QQBZZEWK=1;
                
                tc->GetEntry(ev);

                if (iCR==2){
                  MC_weight*=my_luminosity;
                  MC_weight_QQBZZEWK = getQQZZEWKCorrection(GenHMass);
                  MC_weight*=MC_weight_QQBZZEWK;
                  ZXfake_weight = ZXfake_weight*MC_weight;
                }

                int option[7]={
                  iCR, icut, catZ1, catZ2, iwgt, isocut, iM1cut
                };
                int LepID[4]={
                  Lep1ID, Lep2ID, Lep3ID, Lep4ID
                };
                float Lep_Z1SIP[4]={
                  Lep1_Z1SIP, Lep2_Z1SIP, Lep3_Z1SIP, Lep4_Z1SIP
                };
                float LepSIP[4]={
                  Lep1SIP, Lep2SIP, Lep3SIP, Lep4SIP
                };

                float wgt = applyCRselection(
                  option,

                  m4l_low, m4l_high,

                  CRflag,
                  Lep1combRelIsoPF, Lep2combRelIsoPF, Lep3combRelIsoPF, Lep4combRelIsoPF,
                  Lep1isID, Lep2isID, Lep3isID, Lep4isID,
                  Z1ids,
                  Z2ids,
                  PFMET,

                  Lep_Z1SIP,
                  KalmanCandVtx_chi2,
                  LepSIP,
                  LepID,

                  Z1Mass, ZZMass,

                  1
//                  ZXfake_weight
                  );
                if (wgt==0) continue;
                float wgterror=0;


                float strdraw = Z1Mass;

                float strdraw_Txy = ((KalmanCandVtx_x - OfflinePrimaryVtx_x)*cos(ZZPhi) + (KalmanCandVtx_x - OfflinePrimaryVtx_x)*sin(ZZPhi))*10000.0*ZZMass / ZZPt;
                float strdraw_mZZ = ZZMass;
                float strdraw_mZ1 = Z1Mass;
                float strdraw_mZ2 = Z2Mass;
                float strdraw_pteta_ld[2] ={
                  fabs(Lep3Eta), Lep3Pt
                };
                float strdraw_pteta_subld[2] ={
                  fabs(Lep4Eta), Lep4Pt
                };
                if (iCR!=1 && Lep3Pt<=Lep4Pt){
                  strdraw_pteta_ld[0] = fabs(Lep4Eta);
                  strdraw_pteta_ld[1] = fabs(Lep4Pt);
                  strdraw_pteta_subld[0] = fabs(Lep3Eta);
                  strdraw_pteta_subld[1] = fabs(Lep3Pt);
                }

                float OSSFweight[2] ={ 0 };
                float OSSFweighterror[2] ={ 0 };
                if (iCR!=1 && isocut>1 && catZ2<3 && wgt>0){

                  OSSFweight[0] = applyOSSFweight(
                    hOS, // Zmu, Zmu, Ze, Ze (B, E)

                    CRflag,
                    Z1ids, Z2ids,
                    Lep3combRelIsoPF,
                    Lep3isID,

                    Lep3ID,
                    Lep3Pt,
                    Lep3Eta,

                    OSSFweighterror[0]
                    );

                  OSSFweight[1] = applyOSSFweight(
                    hOS, // Zmu, Zmu, Ze, Ze (B, E)

                    CRflag,
                    Z1ids, Z2ids,
                    Lep4combRelIsoPF,
                    Lep4isID,

                    Lep4ID,
                    Lep4Pt,
                    Lep4Eta,

                    OSSFweighterror[1]
                    );

                  if (isocut==2 && (OSSFweight[0]==0 || OSSFweight[1]==0)) cout << "WARNING: 2p2f OSSF weights are not all positive!" << endl;
                  if (isocut==3 && (OSSFweight[0]==0 && OSSFweight[1]==0)) cout << "WARNING: 3p1f OSSF weights are all zero!" << endl;
                  if (isocut==3 && (OSSFweight[0]!=0 && OSSFweight[1]!=0)) cout << "WARNING: 3p1f OSSF weights are all non-zero!" << endl;

                  float totalOS = 1;
                  float sumOS = 0;

                  float totalOSerror=0;
                  float sumOSerror=0;

                  if (iwgt>0){
                    if (OSSFweight[0]>0){
                      totalOS *= OSSFweight[0];
                      totalOSerror += pow(OSSFweighterror[0]/OSSFweight[0], 2);
                    }
                    if (OSSFweight[1]>0){
                      totalOS *= OSSFweight[1];
                      totalOSerror += pow(OSSFweighterror[1]/OSSFweight[1], 2);
                    }
                    totalOSerror = sqrt(totalOSerror) * totalOS;
                    if (isocut==2){
                      sumOS = OSSFweight[0] + OSSFweight[1];
                      sumOSerror = sqrt(pow(OSSFweighterror[0], 2) + pow(OSSFweighterror[1], 2));
                    }
                    if (iCR==2){
                      totalOS*=MC_weight;
                      sumOS*=MC_weight;
                      totalOSerror*=MC_weight;
                      sumOSerror*=MC_weight;
                    }
                    wgt = totalOS;
                    wgterror = totalOSerror;
                  }
                  else{
                    if (iCR==2){
                      totalOS*=MC_weight;
                      sumOS*=MC_weight;
                    }
                  }

                  hmZZTxyOS->Fill(strdraw_mZZ, strdraw_Txy, totalOS);
                  hmZZmZ1mZ2OS->Fill(strdraw_mZZ, strdraw_mZ1, strdraw_mZ2, totalOS);

                  if (iwgt>0){
/*
                    int binx = hmZZTxyOS->GetXaxis()->FindBin(strdraw_mZZ);
                    int biny = hmZZTxyOS->GetYaxis()->FindBin(strdraw_Txy);
                    hmZZTxyOS->SetBinError(binx, biny, sqrt(pow(hmZZTxyOS->GetBinError(binx, biny), 2)+pow(totalOSerror, 2)));

                    binx = hmZZmZ1mZ2OS->GetXaxis()->FindBin(strdraw_mZZ);
                    biny = hmZZmZ1mZ2OS->GetYaxis()->FindBin(strdraw_mZ1);
                    int binz = hmZZmZ1mZ2OS->GetZaxis()->FindBin(strdraw_mZ2);
                    hmZZmZ1mZ2OS->SetBinError(binx, biny, binz, sqrt(pow(hmZZmZ1mZ2OS->GetBinError(binx, biny, binz), 2)+pow(totalOSerror, 2)));
*/
                    if (isocut==2){
                      hmZZTxyOS_extra->Fill(strdraw_mZZ, strdraw_Txy, sumOS);
                      hmZZmZ1mZ2OS_extra->Fill(strdraw_mZZ, strdraw_mZ1, strdraw_mZ2, sumOS);
/*
                      int binx = hmZZTxyOS_extra->GetXaxis()->FindBin(strdraw_mZZ);
                      int biny = hmZZTxyOS_extra->GetYaxis()->FindBin(strdraw_Txy);
                      hmZZTxyOS_extra->SetBinError(binx, biny, sqrt(pow(hmZZTxyOS_extra->GetBinError(binx, biny), 2)+pow(sumOSerror, 2)));

                      binx = hmZZmZ1mZ2OS_extra->GetXaxis()->FindBin(strdraw_mZZ);
                      biny = hmZZmZ1mZ2OS_extra->GetYaxis()->FindBin(strdraw_mZ1);
                      int binz = hmZZmZ1mZ2OS_extra->GetZaxis()->FindBin(strdraw_mZ2);
                      hmZZmZ1mZ2OS_extra->SetBinError(binx, biny, binz, sqrt(pow(hmZZmZ1mZ2OS_extra->GetBinError(binx, biny, binz), 2)+pow(sumOSerror, 2)));
*/
                    }
                  }

                }

                hsip->Fill(strdraw, wgt);
                if (iwgt>0){
                  int binx = hsip->GetXaxis()->FindBin(strdraw);
                  hsip->SetBinError(binx, sqrt(pow(hsip->GetBinError(binx), 2)+pow(wgterror, 2)));
                }

              }

              if (iCR!=1 && isocut>1 && catZ2<3){
                frecord->WriteTObject(hmZZTxyOS);
                delete hmZZTxyOS;
                frecord->WriteTObject(hmZZmZ1mZ2OS);
                delete hmZZmZ1mZ2OS;
                if (isocut==2 && iwgt>0){
                  frecord->WriteTObject(hmZZTxyOS_extra);
                  delete hmZZTxyOS_extra;
                  frecord->WriteTObject(hmZZmZ1mZ2OS_extra);
                  delete hmZZmZ1mZ2OS_extra;
                }
              }

              double totalerror = 0;
              double totalintegral = hsip->IntegralAndError(1,hsip->GetNbinsX(),totalerror);

              cout << '\t' << totalintegral << '\t' << totalerror;

              delete hsip;
            }
            cout << endl;
          }
        }
        cout << endl;
      }
      cout << endl;
    }
    cout << endl;
  }
  delete tc;

  for (int ww=0; ww<2; ww++) fweight[ww]->Close();
  frecord->Close();
}
void GenerateInputFile_ge4b( double mgl=-1., double mlsp=-1., double target_susy_all0lep=-1. ) {

  TChain* dyTree = new TChain("treeZ") ;
  int nAdded = dyTree->Add("files15fb_8TeV_old1/DY.root") ;
  if ( nAdded <= 0 ) {
     printf("\n\n\n *** No treeZ in files15fb_8TeV_old1/DY.root\n\n\n") ;
     return ;
  }

  double t1bbbbWeight(0.) ;
  TChain chainT1bbbb("tree") ;
  char susycutstring[1000] ;
  sprintf( susycutstring, "&&mgluino==%.0f&&mlsp==%.0f", mgl, mlsp ) ;
  TString susycut( susycutstring ) ;
  if ( mgl>0. && mlsp>0. ) {
     nAdded = chainT1bbbb.Add("files5fb_MT/T1bbbb.root") ;
     if ( nAdded <= 0 ) {
        printf("\n\n\n *** No tree in files5fb_MT/T1bbbb.root\n\n\n") ;
        return ;
     }
     TFile f("referenceXSecs.root") ;
     TH1F* xsechist = (TH1F*) f.Get("gluino8TeV_NLONLL") ;
     if ( xsechist==0x0 ) { printf("\n\n *** can't find reference Xsec histogram in referenceXSecs.root.\n\n") ; return ; }
     int theBin = xsechist->FindBin( mgl ) ;
     if ( theBin <=0 || theBin > xsechist->GetNbinsX() ) {
        printf("\n\n *** can't find bin for mgl=%g.  Returned %d\n\n", mgl, theBin ) ;
        return ;
     }
     double xsec = xsechist->GetBinContent( theBin ) ;
     printf("\n\n T1bbbb xsec for mgl=%g is %g\n\n", mgl, xsec ) ;
     t1bbbbWeight = 1.5*xsec ;  //in pb. scan has 10k events, so nScan*1.5*xsec = events in 15fb-1
     //////  t1bbbbWeight = 0.1*xsec ;  //in pb. T1tttt scan has 50k events, so nScan*0.1*xsec = events in 5fb-1
     printf("\n\n Susy ttree cut: %s\n\n", susycutstring ) ;
  }


  TChain chainQCD("tree") ;
   //--- these have high weight
//chainQCD.Add("files15fb_8TeV/QCD-50to80.root");
//chainQCD.Add("files15fb_8TeV/QCD-80to120.root");
  chainQCD.Add("files15fb_8TeV/QCD-120to170.root");
  chainQCD.Add("files15fb_8TeV/QCD-170to300.root");
   //--- below here, these have weight less than one.
  chainQCD.Add("files15fb_8TeV/QCD-300to470.root");
  chainQCD.Add("files15fb_8TeV/QCD-470to600.root");
  chainQCD.Add("files15fb_8TeV/QCD-600to800.root");
  chainQCD.Add("files15fb_8TeV/QCD-800to1000.root");
  chainQCD.Add("files15fb_8TeV/QCD-1000to1400.root");
  chainQCD.Add("files15fb_8TeV/QCD-1400to1800.root");
  chainQCD.Add("files15fb_8TeV/QCD-1800.root");

  TChain chainTT("tree") ;
  chainTT.Add("files15fb_8TeV/TT.root") ;

  TChain chainZnn("tree") ;
  chainZnn.Add("files15fb_8TeV/Zinv-100to200.root") ;
  chainZnn.Add("files15fb_8TeV/Zinv-200to400.root") ;
  chainZnn.Add("files15fb_8TeV/Zinv-400.root") ;

  TChain chainWJets("tree") ;
  chainWJets.Add("files15fb_8TeV/WJets-250to300.root") ;
  chainWJets.Add("files15fb_8TeV/WJets-300to400.root") ;
  chainWJets.Add("files15fb_8TeV/WJets-400.root") ;
  chainWJets.Add("files15fb_8TeV/T-s.root") ;
  chainWJets.Add("files15fb_8TeV/T-t.root") ;
  chainWJets.Add("files15fb_8TeV/T-tW.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-s.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-t.root") ;
  chainWJets.Add("files15fb_8TeV/Tbar-tW.root") ;



      char qcdinputfile[9][1000] = {
        "files15fb_8TeV/QCD-120to170.root"
       ,"files15fb_8TeV/QCD-170to300.root"
       ,"files15fb_8TeV/QCD-300to470.root"
       ,"files15fb_8TeV/QCD-470to600.root"
       ,"files15fb_8TeV/QCD-600to800.root"
       ,"files15fb_8TeV/QCD-800to1000.root"
       ,"files15fb_8TeV/QCD-1000to1400.root"
       ,"files15fb_8TeV/QCD-1400to1800.root"
       ,"files15fb_8TeV/QCD-1800.root"
      } ;

      char qcdsamplename[9][100] = {
        "qcd_0120_to_0170"
       ,"qcd_0170_to_0300"
       ,"qcd_0300_to_0470"
       ,"qcd_0470_to_0600"
       ,"qcd_0600_to_0800"
       ,"qcd_0800_to_1000"
       ,"qcd_1000_to_1400"
       ,"qcd_1400_to_1800"
       ,"qcd_1800_to_9999"
      } ;



  gROOT->Reset();

  const int nBinsBjets = 4 ;
  const int nJetsCut = 3 ;     // #jets >= nJetsCut

//be careful because this is hard coded now in SmallTree::Loop
  double minLeadJetPt = 70. ;
  double min3rdJetPt = 50. ;
  
  bool doPUreweighting = false;

  //-- met2-ht1-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 1 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,99999.};

//-- met2-ht2-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};

////-- met2-ht8-v1
//const int nBinsMET   = 2 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

  //-- met3-ht2-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,800.,99999.};

////-- met3-ht3-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met3-ht3-v5
//    const int nBinsMET = 3 ;
//    const int nBinsHT  = 3 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = { 125, 200,  350, 99999. } ;
//    float Hbins[nBinsHT+1]  = { 400, 600, 1000, 99999. } ;

////-- met3-ht3-v2
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

////-- met3-ht4-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

////-- met3-ht5-v1
//const int nBinsMET   = 3 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met4-ht3-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,250.,350.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met4-ht3-v2
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {300.,500.,1000.,99999.};

  //-- met5-ht4-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 4 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

////-- met4-ht4-v1
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 1;
//    float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
//    float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v2
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 2;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,500.,600.,800.,99999.};

  //-- met4-ht4-v3
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 3;
//    float Mbins[nBinsMET+1] = {150.,200.,250.,300.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v4
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 4;
//    float Mbins[nBinsMET+1] = {150.,250.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,99999.};

  //-- met4-ht4-v5
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 5;
//    float Mbins[nBinsMET+1] = {150.,175.,200.,400.,99999.};
//    float Hbins[nBinsHT+1] = {400.,450.,550.,850.,99999.};

  //-- met4-ht4-v6
//    const int nBinsMET   = 4 ;
//    const int nBinsHT    = 4 ;
//    const int version = 6;
//    float Mbins[nBinsMET+1] = {150.,200.,350.,450.,99999.};
//    float Hbins[nBinsHT+1] = {400.,550.,800.,950.,99999.};

////-- met4-ht4-v7
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 4 ;
//    const int version = 7;
//float Mbins[nBinsMET+1] = {125, 150.,250.,350.,99999.};
//float Hbins[nBinsHT+1] = {200, 300.,500.,1000.,99999.};

  //-- met4-ht4-v15
      const int nBinsMET   = 4 ;
      const int nBinsHT    = 4 ;
      const int version = 15;
      float Mbins[nBinsMET+1] = {125.,150.,250.,350.,99999.};
      float Hbins[nBinsHT+1] = {400.,500.,800.,1000.,99999.};

////-- met4-ht5-v1
//const int nBinsMET   = 4 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,300.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,800.,1000.,1200.,99999.};

////-- met5-ht5-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 5 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,800.,1000.,99999.};

////-- met5-ht3-v1
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,1000.,99999.};

////-- met5-ht3-v2
//const int nBinsMET   = 5 ;
//const int nBinsHT    = 3 ;
//    const int version = 2;
//float Mbins[nBinsMET+1] = {150.,175.,200.,350.,450.,99999.};
//float Hbins[nBinsHT+1] = {400.,550.,800.,99999.};

  //-- met6-ht6-v1
//const int nBinsMET   = 6 ;
//const int nBinsHT    = 6 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,99999.};

  //-- met7-ht7-v1
//const int nBinsMET   = 7 ;
//const int nBinsHT    = 7 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,500.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,99999.};

////-- met8-ht8-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 8 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,500.,600.,700.,800.,900.,1000.,1200.,99999.};

////-- met8-ht2-v1
//const int nBinsMET   = 8 ;
//const int nBinsHT    = 2 ;
//    const int version = 1;
//float Mbins[nBinsMET+1] = {150.,200.,250.,300.,350.,400.,450.,600.,99999.};
//float Hbins[nBinsHT+1] = {400.,600.,99999.};



  TString sMbins[nBinsMET];
  TString sHbins[nBinsHT];
  TString sBbins[nBinsBjets] = {"_1b","_2b","_3b","_4b"};

  TString cMbins[nBinsMET];
  TString cHbins[nBinsHT];

  for (int i = 0 ; i < nBinsMET ; i++) {
    TString base = "_M";
    stringstream sbin;
    sbin << i+1;
    base += sbin.str();
    sMbins[i] = base;
    base = "&&MET>";
    stringstream cbin;
    cbin << Mbins[i] << "&&MET<" << Mbins[i+1];
    base += cbin.str();
    cMbins[i] = base;
  }

  for (int j = 0 ; j < nBinsHT ; j++) {
    TString base = "_H";
    stringstream sbin;
    sbin << j+1;
    base += sbin.str();
    sHbins[j] = base;
    base = "&&HT>";
    stringstream cbin;
    cbin << Hbins[j] << "&&HT<" << Hbins[j+1];
    base += cbin.str();
    cHbins[j] = base;
  }

  TString leadJetPtCutString ;
  {
     leadJetPtCutString = "(pt_1st_leadJet>" ;
     stringstream number ;
     number << minLeadJetPt ;
     stringstream number2 ;
     number2 << min3rdJetPt ;
     leadJetPtCutString += number.str() ;
     leadJetPtCutString += "&&pt_2nd_leadJet>" ;
     leadJetPtCutString += number.str() ;
     leadJetPtCutString += "&&pt_3rd_leadJet>" ;
     leadJetPtCutString += number2.str() ;
     leadJetPtCutString += ")" ;
  }

//int dummyInt = 99;
//float dummyFloat = 9.999;
  float dummyZero = 0.;
  float dummyOne = 1.0;
  float dummyPoint999 = 0.999 ;
  float dummyErr = 0.1;

  float sl_frac2b_val[nBinsMET][nBinsHT];
  float sl_frac2b_err[nBinsMET][nBinsHT];
  float sl_frac3b_val[nBinsMET][nBinsHT];
  float sl_frac3b_err[nBinsMET][nBinsHT];
  float sl_frac4b_val[nBinsMET][nBinsHT];
  float sl_frac4b_err[nBinsMET][nBinsHT];


  ofstream inFile;
  char outfile[10000] ;
  if ( mgl > 0. && mlsp > 0. ) {
     if ( target_susy_all0lep > 0. ) {
        sprintf( outfile, "InputWT1bbbb-nb4-mgl%.0f-mlsp%.0f-%.0fevts-met%d-ht%d-v%d.dat", mgl, mlsp, target_susy_all0lep, nBinsMET, nBinsHT, version  ) ;
     } else {
        sprintf( outfile, "InputWT1bbbb-nb4-mgl%.0f-mlsp%.0f-met%d-ht%d-v%d.dat", mgl, mlsp, nBinsMET, nBinsHT, version  ) ;
     }
  } else {
     sprintf( outfile, "Input-nb4-met%d-ht%d-v%d.dat", nBinsMET, nBinsHT, version  ) ;
  }
  inFile.open( outfile );

  // print out header line:

  inFile << "Using HT bins:  " ;
  for (int j = 0 ; j <= nBinsHT ; j++ ) {
    inFile << Hbins[j] ;
    if ( j < nBinsHT ) inFile << "-" ;
  }

  inFile << "\t Using MET bins: " ;
  for (int i = 0 ; i <= nBinsMET ; i++ ) {
    inFile << Mbins[i] ;
    if ( i < nBinsMET ) inFile << "-" ;
  }
  
  inFile << endl ;


   int nSel(3) ;
   char selname[3][100] = { "0lep", "1lep", "ldp" } ;

   char selcuts[3][10000] = {
        "minDelPhiN>4&&nMu==0&&nEl==0&&",
        "minDelPhiN>4&&( (nMu==1&&nEl==0) || (nMu==0&&nEl==1) )&&",
        "minDelPhiN<4&&nMu==0&&nEl==0&&" } ;


  //--- Output histograms.

   TH1F* hmctruth_susy [3][4] ;
   TH1F* hmctruth_ttwj [3][4] ;
   TH1F* hmctruth_ttbar[3][4] ;
   TH1F* hmctruth_wjets[3][4] ;
   TH1F* hmctruth_qcd  [3][4] ;
   TH1F* hmctruth_znn  [3][4] ;
   TH1F* hmctruth_allsm[3][4] ;
   TH1F* hmctruth_all  [3][4] ;

   for ( int si=0; si<nSel; si++ ) {
      for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

         char hname[1000] ;
         char htitle[1000] ;
         sprintf( htitle, "%s, %d btag", selname[si], bbi+1 ) ;

         sprintf( hname, "hmctruth_susy_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_susy[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_ttwj_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_ttwj[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_ttbar_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_ttbar[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_wjets_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_wjets[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_qcd_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_qcd[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_znn_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_znn[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_allsm_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_allsm[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;

         sprintf( hname, "hmctruth_all_%s_%db", selname[si], bbi+1 ) ;
         hmctruth_all[si][bbi] = bookHist( hname, htitle, selname[si], bbi+1, nBinsMET, nBinsHT ) ;


      } // bbi.
   } // si.




     TH1F* hmctruth_fit_zee_1b  = bookHist("hmctruth_fit_zee_1b" , "Zee" , "Zee", 1, nBinsMET, nBinsHT ) ;
     TH1F* hmctruth_fit_zmm_1b  = bookHist("hmctruth_fit_zmm_1b" , "Zmm" , "Zmm", 1, nBinsMET, nBinsHT ) ;






  //--- histograms used in getting the observables.

    TH2F* h_tt[10] ;
    TH2F* h_wjets[10] ;
    TH2F* h_qcd[10] ;
    TH2F* h_znn[10] ;
    TH2F* h_susy[10] ;
    TH2F* h_mc[10] ;

    for ( int bi=0; bi<nBinsBjets; bi++ ) {

       char hname[100] ;

       sprintf( hname, "h_tt_%db", bi+1 ) ;
       h_tt[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_tt[bi] -> Sumw2() ;

       sprintf( hname, "h_wjets_%db", bi+1 ) ;
       h_wjets[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_wjets[bi] -> Sumw2() ;

       sprintf( hname, "h_qcd_%db", bi+1 ) ;
       h_qcd[bi]  = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_qcd[bi] -> Sumw2() ;

       sprintf( hname, "h_znn_%db", bi+1 ) ;
       h_znn[bi]  = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_znn[bi] -> Sumw2() ;

       sprintf( hname, "h_susy_%db", bi+1 ) ;
       h_susy[bi] = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_susy[bi] -> Sumw2() ;

       sprintf( hname, "h_mc_%db", bi+1 ) ;
       h_mc[bi]   = new TH2F( hname, hname , nBinsMET, Mbins, nBinsHT, Hbins ) ;
       h_mc[bi] -> Sumw2() ;

    }

  float nSusyTotal = 0;

  for ( int si=0 ; si<nSel ; si++ ) {


  printf("\n\n-----------------------------------------------------------------\n\n") ;

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

        char allcuts[10000] ;
        char allsusycuts[10000] ;

        if ( k < (nBinsBjets-1) ) {
          sprintf( allcuts, "%snB==%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
          sprintf( allsusycuts, "%snB==%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)%s", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt, susycut.Data() ) ;
        } else {
          sprintf( allcuts, "%snB>=%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
          sprintf( allsusycuts, "%snB>=%d&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)%s", selcuts[si], k+1, nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt, susycut.Data() ) ;
        }


        printf("\n\n N_%s -- nbjet bin (%d): cuts=%s\n\n", selname[si], k, allcuts) ; cout << flush ;

        char hname[100] ;
        sprintf( hname, "h_tt_%db", k+1 ) ;
        if(doPUreweighting) FillHTMET(&chainTT, h_tt[k], si, k);
	else chainTT.Project (hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_tt[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_wjets_%db", k+1 ) ;
        if(doPUreweighting) FillHTMET(&chainWJets, h_wjets[k], si, k);
	else chainWJets.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_wjets[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_qcd_%db", k+1 ) ;
        if (doPUreweighting) FillHTMET(&chainQCD, h_qcd[k], si, k);
	else chainQCD.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_qcd[k]->Integral() ) ; cout << flush ;

        sprintf( hname, "h_znn_%db", k+1 ) ;
        if (doPUreweighting) FillHTMET(&chainZnn, h_znn[k], si, k);
	else chainZnn.Project(hname,"HT:MET",allcuts);
	printf("    %12s %9.1f events\n", hname, h_znn[k]->Integral() ) ; cout << flush ;
        if ( mgl > 0. ) {
           sprintf( hname, "h_susy_%db", k+1 ) ;
           chainT1bbbb.Project(hname,"HT:MET",allsusycuts);
           h_susy[k]->Scale( t1bbbbWeight ) ;
           printf("    %12s %9.1f events\n", hname, h_susy[k]->Integral() ) ; cout << flush ;
	   if (si==0) nSusyTotal += h_susy[k]->Integral();
        }
      } // k
      if (si==0) printf("N_Susy_Total = %9.1f events", nSusyTotal); cout << flush;
      printf("\n\n") ;


      for (int i = 0 ; i < nBinsMET ; i++) {
        for (int j = 0 ; j < nBinsHT ; j++) {
          for (int k = 0 ; k < nBinsBjets ; k++) {


             char obsname[1000] ;
             sprintf( obsname, "N_%s_M%d_H%d_%db", selname[si], i+1, j+1, k+1 ) ;


             double ttval = h_tt[k] -> GetBinContent( i+1, j+1 ) ;
             double tterr = h_tt[k] -> GetBinError(   i+1, j+1 ) ;

             double wjetsval = h_wjets[k] -> GetBinContent( i+1, j+1 ) ;
             double wjetserr = h_wjets[k] -> GetBinError(   i+1, j+1 ) ;

             double qcdval = h_qcd[k] -> GetBinContent( i+1, j+1 ) ;
             double qcderr = h_qcd[k] -> GetBinError(   i+1, j+1 ) ;

             double znnval = h_znn[k] -> GetBinContent( i+1, j+1 ) ;
             double znnerr = h_znn[k] -> GetBinError(   i+1, j+1 ) ;

             double susyval = h_susy[k] -> GetBinContent( i+1, j+1 ) ;
             double susyerr = h_susy[k] -> GetBinError(   i+1, j+1 ) ;

             printf(" N_%s, tt     met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, ttval,tterr) ; cout << flush ;
             printf(" N_%s, wjets  met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, wjetsval,wjetserr) ; cout << flush ;
             printf(" N_%s, qcd    met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, qcdval,qcderr) ; cout << flush ;
             printf(" N_%s, znn    met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, znnval,znnerr) ; cout << flush ;
             if ( mgl>0. ) {
                if ( target_susy_all0lep > 0. ) {
                   susyval = susyval * (target_susy_all0lep/nSusyTotal);
                   susyerr = susyerr * (target_susy_all0lep/nSusyTotal);
                }
                printf(" N_%s, susy   met,ht,nbjet bin (%d,%d,%d)  --  npass=%7.1f +/- %6.1f\n", selname[si], i,j,k, susyval,susyerr) ; cout << flush ;
             }
             printf("\n") ;

             double allval = ttval + wjetsval + qcdval + znnval + susyval ;

             //// inFile << obsname << "  \t" << (int)allval << endl;
             inFile << obsname << "  \t" << allval << endl;

             int histbin = 1 + (nBinsHT+1)*i + j + 1 ;

             hmctruth_ttwj[si][k]  -> SetBinContent( histbin, ttval + wjetsval  ) ;
             hmctruth_ttwj[si][k]  -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) )  ) ;
             hmctruth_ttbar[si][k] -> SetBinContent( histbin, ttval ) ;
             hmctruth_ttbar[si][k] -> SetBinError(   histbin, tterr ) ;
             hmctruth_wjets[si][k] -> SetBinContent( histbin, wjetsval  ) ;
             hmctruth_wjets[si][k] -> SetBinError(   histbin, wjetserr  ) ;
             hmctruth_qcd[si][k]   -> SetBinContent( histbin, qcdval ) ;
             hmctruth_qcd[si][k]   -> SetBinError(   histbin, qcderr ) ;
             hmctruth_znn[si][k]   -> SetBinContent( histbin, znnval ) ;
             hmctruth_znn[si][k]   -> SetBinError(   histbin, znnerr ) ;
             hmctruth_susy[si][k]  -> SetBinContent( histbin, susyval  ) ;
             hmctruth_susy[si][k]  -> SetBinError(   histbin, susyerr  ) ;
             hmctruth_allsm[si][k] -> SetBinContent( histbin, ttval+wjetsval+qcdval+znnval ) ;
             hmctruth_allsm[si][k] -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) + pow(qcderr,2) + pow(znnerr,2) ) ) ;
             hmctruth_all[si][k]   -> SetBinContent( histbin, ttval+wjetsval+qcdval+znnval+susyval ) ;
             hmctruth_all[si][k]   -> SetBinError(   histbin, sqrt( pow(tterr,2) + pow(wjetserr,2) + pow(qcderr,2) + pow(znnerr,2) + pow(susyerr,2) ) ) ;


	     // compute fractions of SL 2b/1b and 3b/1b

	     if ( si == 1 && k > 0 ) {

	       double ttval_1b = h_tt[0] -> GetBinContent( i+1, j+1 ) ;
	       double wjetsval_1b = h_wjets[0] -> GetBinContent( i+1, j+1 ) ;

	       double ttwjval = ttval + wjetsval ;
	       double ttwjval_1b = ttval_1b + wjetsval_1b ;

	       if ( k == 1 ) {
		 sl_frac2b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac2b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	       if ( k == 2 ) {
		 sl_frac3b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac3b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	       if ( k == 3 ) {
		 sl_frac4b_val[i][j] = ( ttwjval ) / ( ttwjval_1b ) ;
		 sl_frac4b_err[i][j] = 0.01 ;   // start with arbitrary errors, first
	       }

	     }

            } // k
          } // j
        } // i



          for (int k = 0 ; k < nBinsBjets ; k++) {
             h_tt[k] -> Reset() ;
             h_wjets[k] -> Reset() ;
             h_qcd[k] -> Reset() ;
             h_znn[k] -> Reset() ;
             h_susy[k] -> Reset() ;
          }


     } // si.




     //--- Insert dummy R_lsb lines for backwards compatibility.
     for ( int hbi=0; hbi<nBinsHT; hbi++ ) {
        for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {
           char dummyline[1000] ;
           sprintf( dummyline, "R_lsb_H%d_%db       0.1", hbi+1, bbi+1 ) ;
           inFile << dummyline << endl ;
           sprintf( dummyline, "R_lsb_H%d_%db_err   0.01", hbi+1, bbi+1 ) ;
           inFile << dummyline << endl ;
        } // bbi.
     } // hbi.





    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;

    { //--- scoping bracket for QCD chunk.

    //--- Fill histograms to be used in QCD analysis (done in mcclosure4.c).

      const int nQcdSamples(9) ;

      TCanvas* cqcd = new TCanvas("cqcd","QCD") ;

      TH2F*   h0lep[nQcdSamples][nBinsBjets] ;
      TH2F*   hldp [nQcdSamples][nBinsBjets] ;

      TChain* qcdch[nQcdSamples] ;

      char hname[1000] ;
      char htitle[1000] ;

      TH2F* hdummy = new TH2F("hdummy","",2, Mbins[0], 1500., 2, Hbins[0], 1500. ) ;

         printf("\n\n") ;
         for ( int si=0; si<nQcdSamples; si++ ) {

            qcdch[si] = new TChain("tree") ;
            printf(" %2d : connecting to %s\n", si, qcdinputfile[si] ) ;
            qcdch[si] -> Add( qcdinputfile[si] ) ;

            for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

               sprintf( hname, "h_0lep_%db_%s", bbi+1, qcdsamplename[si] ) ;
               sprintf( htitle, "QCD 0lep yield, nb=%d, %s", bbi+1, qcdsamplename[si] ) ;
               printf("         booking hist %s : %s\n", hname, htitle ) ;
               h0lep[si][bbi] = new TH2F( hname, htitle, nBinsMET, Mbins, nBinsHT, Hbins ) ;
               h0lep[si][bbi] -> Sumw2() ;
               sprintf( hname, "h_ldp_%db_%s", bbi+1, qcdsamplename[si] ) ;
               sprintf( htitle, "QCD  LDP yield, nb=%d, %s", bbi+1, qcdsamplename[si] ) ;
               printf("         booking hist %s  : %s\n", hname, htitle ) ;
               hldp [si][bbi] = new TH2F( hname, htitle, nBinsMET, Mbins, nBinsHT, Hbins ) ;
               hldp [si][bbi] -> Sumw2() ;

            } // bbi.

         } // si.
         printf("\n\n") ;


         char bcut[4][100] = { "nB==1", "nB==2", "nB==3", "nB>=4" } ;

         for ( int si=0; si<nQcdSamples; si++ ) {

            printf(" %2d : %s : 0lep\n", si, qcdsamplename[si] ) ; cout << flush ;
            for ( int bbi=0; bbi<nBinsBjets; bbi++ ) {

               char arg1[1000] ;

               char cuts0lep[10000] ;
               sprintf( cuts0lep, "%s(%s)&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[0], bcut[bbi], nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
               printf("     %db, 0lep cuts : %s\n", bbi+1, cuts0lep ) ;
               sprintf( arg1, "HT:MET>>h_0lep_%db_%s", bbi+1, qcdsamplename[si] ) ;
               qcdch[si] -> Draw( arg1, cuts0lep ) ;
               hdummy->Draw() ;
               h0lep[si][bbi]->Draw("samecolz") ;
               cqcd->Update() ; cqcd->Draw() ;


               char cutsldp[10000] ;
               sprintf( cutsldp, "%s(%s)&&nJets>=%d&&(pt_1st_leadJet>%.0f&&pt_2nd_leadJet>%.0f&&pt_3rd_leadJet>%.0f)", selcuts[2], bcut[bbi], nJetsCut, minLeadJetPt, minLeadJetPt, min3rdJetPt ) ;
               printf("     %db, ldp  cuts : %s\n", bbi+1, cutsldp  ) ;
               sprintf( arg1, "HT:MET>>h_ldp_%db_%s", bbi+1, qcdsamplename[si] ) ;
               qcdch[si] -> Draw( arg1, cutsldp, "colz" ) ;
               hdummy->Draw() ;
               hldp[si][bbi]->Draw("samecolz") ;
               cqcd->Update() ; cqcd->Draw() ;

            } // bbi.

         } // si.

    } //--- scoping bracket for QCD chunk.

    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // Z -> ee observables 
  
    TH1F* ht = new TH1F("ht","ht",10,0,10000);
  
    ht -> Sumw2() ;

    TString cutszee = "cat==2&&minDelPhiNee>4&&nVLB>=1&&nJets>=";
    stringstream njcut ; njcut << nJetsCut ;
    cutszee += njcut.str();
    cutszee += "&&";

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
  
        TString obs_Zee = "N_Zee" ;
        obs_Zee = obs_Zee+sMbins[i]+sHbins[j] ;
        
        TString cut = "HT>";  
        cut += Hbins[j];
        cut += "&&HT<";
        cut += Hbins[j+1];
        cut += "&&METee>";
        cut += Mbins[i];
        cut += "&&METee<";
        cut += Mbins[i+1];
  
        TString allcutsZ = cutszee+cut ;
        allcutsZ += "&&" ;
        allcutsZ += leadJetPtCutString ;
  
        dyTree->Project("ht","HT",allcutsZ);
        double allerr(0.) ;
        double allval = ht->IntegralAndError(1,10,allerr) ;
        printf(" N_Zee -- HT,MET bins (%d,%d): events=%7.1f +/- %6.1f, cuts=%s\n", j,i,allval,allerr,allcutsZ.Data() ) ; cout << flush ;
          ht->Reset() ;
  
        ////// inFile << obs_Zee << "  \t" << (int)allval << endl;
        inFile << obs_Zee << "  \t" << allval << endl;

        //Z->ee counts, with 1 VLb and sig selection, so so MET>250, HT>400, mindelphi>4, 2e, 0mu, nJets >= 3
  
        int histbin = 1 + (nBinsHT+1)*i + j + 1 ;
  
        hmctruth_fit_zee_1b -> SetBinContent( histbin, allval ) ;
        hmctruth_fit_zee_1b -> SetBinError(   histbin, allerr ) ;
  
      }
    }
  
    
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // Z -> mm observables
  
    TString cutszmm = "cat==1&&minDelPhiNmm>4&&nVLB>=1&&nJets>=";
    cutszmm += njcut.str();
    cutszmm += "&&";

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
  
        TString obs_Zmm = "N_Zmm" ;
        obs_Zmm = obs_Zmm+sMbins[i]+sHbins[j] ;
        
        TString cut = "HT>";  
        cut += Hbins[j];
        cut += "&&HT<";
        cut += Hbins[j+1];
        cut += "&&METmm>";
        cut += Mbins[i];
        cut += "&&METmm<";
        cut += Mbins[i+1];
        
        TString allcutsZ = cutszmm+cut ;
        allcutsZ += "&&" ;
        allcutsZ += leadJetPtCutString ;
  
        dyTree->Project("ht","HT",allcutsZ);
        double allerr(0.) ;
        double allval = ht->IntegralAndError(1,10,allerr) ;
        printf(" N_Zmm -- HT,MET bins (%d,%d): events=%7.1f +/- %6.1f, cuts=%s\n", j,i,allval,allerr,allcutsZ.Data() ) ; cout << flush ;
          ht->Reset() ;
  
        ////// inFile << obs_Zmm << "  \t" << (int)allval << endl;
        inFile << obs_Zmm << "  \t" << allval << endl;

        //Z->mm counts, with 1 VLb and sig selection, so so MET>250, HT>400, mindelphi>4, 2mu, 0e, nJets >= 3
  
        int histbin = 1 + (nBinsHT+1)*i + j + 1 ;
  
        hmctruth_fit_zmm_1b -> SetBinContent( histbin, allval ) ;
        hmctruth_fit_zmm_1b -> SetBinError(   histbin, allerr ) ;
  
  
      }
    }
  
    //inFile << "Why are all three of these MC categories separate? I've just put them together (only QCD, Zinv, tt)" << endl;
    // Nttbarsingletopzjetsmc_ldp
  
  
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;

    //--- Owen : these MC inputs are no longer used.  Insert dummy values for backwards compatibility in format.

    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {

           char obsname[1000] ;
           sprintf( obsname, "N_ttbarsingletopzjetsmc_ldp_M%d_H%d_%db", i+1, j+1, k+1 ) ;

           double val, err ;
           val = 0. ;
           err = 0. ;

           printf(" %s : %7.1f +/- %7.1f\n", obsname, val, err ) ;

           inFile << obsname << "  \t" << val << endl ;

        }
        printf("\n") ;
      }
      printf("\n") ;
    }

    // NWJmc_ldp
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString obs_WJmc_ldp = "N_WJmc_ldp" ;
  	obs_WJmc_ldp = obs_WJmc_ldp+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << obs_WJmc_ldp << "  \t" << dummyZero << endl;
  // signal selection, but ldp, so MET>250, HT>400, >=1 b, mindelphi<4, 0L, nJets >= 3
        }
      }
    }
  
  
    // NZnnmc_ldp
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString obs_Znnmc_ldp = "N_Znnmc_ldp" ;
  	obs_Znnmc_ldp = obs_Znnmc_ldp+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << obs_Znnmc_ldp << "  \t" << dummyZero << endl;
  // signal selection, but ldp, so MET>250, HT>400, >=1 b, mindelphi<4, 0L, nJets >= 3
        }
      }
    }
  
    printf("\n\n-----------------------------------------------------------------\n\n") ; cout << flush ;
  
    // various parameters needed for Z -> invis.
  
    // Z -> ee acceptance
  
    for (int i = 0 ; i < nBinsMET ; i++) {
  
      TString Zee_acc = "acc_Zee";
      Zee_acc = Zee_acc+sMbins[i];
  
      inFile << Zee_acc << "  \t" << dummyPoint999 << endl;
  
      Zee_acc = Zee_acc+"_err";
      inFile << Zee_acc << "  \t" << dummyErr << endl;
  
    }
  
  
    // Z -> mm acceptance
  
    for (int i = 0 ; i < nBinsMET ; i++) {
  
      TString Zmm_acc = "acc_Zmm";
      Zmm_acc = Zmm_acc+sMbins[i];
  
      inFile << Zmm_acc << "  \t" << dummyPoint999 << endl;
  
      Zmm_acc = Zmm_acc+"_err";
      inFile << Zmm_acc << "  \t" << dummyErr << endl;
  
    }
  
  
    // Z -> ll efficiencies
  
  // use 2011 values for now.
    inFile << "Z_ee_eff  \t" << 0.6774 << endl;
    inFile << "Z_ee_eff_err  \t" << 0.0580 << endl;
    inFile << "Z_mm_eff  \t" << 0.7217 << endl;
    inFile << "Z_mm_eff_err  \t" << 0.0506 << endl;
  
  
    // Z -> ee VL to nominal scale factors
  // would it make more sense to count events in only the loosest HT and/or MET bin and
  // use the scale factors to translate between the different HT and MET bins?

   //    for (int k = 0 ; k < nBinsBjets ; k++) {
   //    TString knn_ee = "knn_ee" ;
   //    knn_ee = knn_ee+sBbins[k] ;
   //    inFile << knn_ee << "  \t" << dummyOne << endl;
   //    knn_ee = knn_ee+"_err" ;
   //    inFile << knn_ee << "  \t" << dummyErr << endl;
   //  }
   //
   //
   //  // use 2011 values for now.
   //  inFile << "knn_1b     \t" << 0.401 << endl;
   //  inFile << "knn_1b_err \t" << 0.018 << endl;
   //  inFile << "knn_2b     \t" << 0.067 << endl;
   //  inFile << "knn_2b_err \t" << 0.009 << endl;
   //  inFile << "knn_3b     \t" << 0.009 << endl;
   //  inFile << "knn_3b_err \t" << 0.003 << endl;
   //

    // updated SF's to improve MC closure (the errors are the same as before)
    inFile << "knn_1b     \t" << 0.394  << endl;
    inFile << "knn_1b_err \t" << 0.018  << endl;
    inFile << "knn_2b     \t" << 0.0626 << endl;
    inFile << "knn_2b_err \t" << 0.009  << endl;
    inFile << "knn_3b     \t" << 0.0036 << endl;
    inFile << "knn_3b_err \t" << 0.003  << endl;
    inFile << "knn_4b     \t" << 0.00011 << endl;
    inFile << "knn_4b_err \t" << 0.00011  << endl;

    // Z -> ll purity
  
    // use 2011 values for now.
    inFile << "Z_ee_pur  \t" << 0.911 << endl;
    inFile << "Z_ee_pur_err  \t" << 0.079 << endl;
    inFile << "Z_mm_pur  \t" << 0.866 << endl;
    inFile << "Z_mm_pur_err  \t" << 0.079 << endl;
  
  
    // scale factors:
  
    inFile << "sf_mc  \t" << dummyOne << endl ; 
    inFile << "sf_mc_err  \t" << dummyErr << endl; 
  
  
    // sf_qcd
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString sf_qcd = "sf_qcd" ;
  	sf_qcd = sf_qcd+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << sf_qcd << "  \t" << dummyOne << endl;	
  
  	sf_qcd = sf_qcd+"_err" ;
  	inFile << sf_qcd << "  \t" << dummyErr << endl;	
  
        }
      }
    }
  
  
    // sf_ttwj
  
    for (int i = 0 ; i < nBinsMET ; i++) {
      for (int j = 0 ; j < nBinsHT ; j++) {
        for (int k = 0 ; k < nBinsBjets ; k++) {
  
  	TString sf_ttwj = "sf_ttwj" ;
  	sf_ttwj = sf_ttwj+sMbins[i]+sHbins[j]+sBbins[k] ;
  	
  	inFile << sf_ttwj << "  \t" << dummyOne << endl;	
  
  	sf_ttwj = sf_ttwj+"_err" ;
  	inFile << sf_ttwj << "  \t" << dummyErr << endl;	
  
        }
      }
    }
  
  
    // sf_ee
  
    for (int k = 0 ; k < nBinsBjets ; k++) {
  
      TString sf_ee = "sf_ee" ;
      sf_ee = sf_ee+sBbins[k] ;
  
      inFile << sf_ee << "  \t" << dummyOne << endl;
      
      sf_ee = sf_ee+"_err" ;
      inFile << sf_ee << "  \t" << dummyErr << endl;
  
    }
  
  
    // sf_mm
  
    for (int k = 0 ; k < nBinsBjets ; k++) {
  
      TString sf_mm = "sf_mm" ;
      sf_mm = sf_mm+sBbins[k] ;
  
      inFile << sf_mm << "  \t" << dummyOne << endl;
      
      sf_mm = sf_mm+"_err" ;
      inFile << sf_mm << "  \t" << dummyErr << endl;
  
    }


    // btag eff err (Note: this was missing until Aug 3, 2012, but it's apparently not used.)
    inFile << "btageff_err" << " \t" << dummyErr << endl ;



    //--- Addding ttwj and znn LDP/ZL MC values

    //--- ttwj MC LDP/ZL

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {
        int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;
        for (int bbi = 0 ; bbi < nBinsBjets ; bbi++) {

            float ldpval = hmctruth_ttwj[2][bbi] -> GetBinContent( hbin ) ;
            float ldperr = hmctruth_ttwj[2][bbi] -> GetBinError(   hbin ) ;
            float zlval  = hmctruth_ttwj[0][bbi] -> GetBinContent( hbin ) ;
            float zlerr  = hmctruth_ttwj[0][bbi] -> GetBinError(   hbin ) ;

            float ldpoverzl = 0. ;
            float ldpoverzlerr = 0. ;

            if ( zlval > 0. && ldpval > 0. ) {
               ldpoverzl = ldpval / zlval ;
               ldpoverzlerr = ldpoverzl * sqrt( pow((zlerr/zlval),2) + pow((ldperr/ldpval),2) ) ;
            }

            char parname[1000] ;

            sprintf( parname, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_%db", mbi+1, hbi+1, bbi+1 ) ;
            printf(" %s  :  %6.3f +/- %5.3f\n", parname, ldpoverzl, ldpoverzlerr ) ;
            inFile << parname << "  \t" << ldpoverzl << endl;

            sprintf( parname, "ttwj_mc_ldpover0lep_ratio_M%d_H%d_%db_err", mbi+1, hbi+1, bbi+1 ) ;
            inFile << parname << "  \t" << ldpoverzlerr << endl;

        } // bbi
      } // hbi
    } // mbi


    //--- Znn MC LDP/ZL
    //--- Note: the 2b and >=3b MC stats are too low.  Use 1b values for all 3.

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {
        int hbin = 1 + (nBinsHT+1)*mbi + hbi + 1 ;

        float ldpval = hmctruth_znn[2][0] -> GetBinContent( hbin ) ;
        float ldperr = hmctruth_znn[2][0] -> GetBinError(   hbin ) ;
        float zlval  = hmctruth_znn[0][0] -> GetBinContent( hbin ) ;
        float zlerr  = hmctruth_znn[0][0] -> GetBinError(   hbin ) ;

        float ldpoverzl = 0. ;
        float ldpoverzlerr = 0. ;

        if ( zlval > 0. && ldpval > 0. ) {
           ldpoverzl = ldpval / zlval ;
           ldpoverzlerr = ldpoverzl * sqrt( pow((zlerr/zlval),2) + pow((ldperr/ldpval),2) ) ;
        }

        char parname[1000] ;

        for (int bbi = 0 ; bbi < nBinsBjets ; bbi++) {
            sprintf( parname, "znn_mc_ldpover0lep_ratio_M%d_H%d_%db", mbi+1, hbi+1, bbi+1 ) ;
            printf(" %s  :  %6.3f +/- %5.3f\n", parname, ldpoverzl, ldpoverzlerr ) ;
            inFile << parname << "  \t" << ldpoverzl << endl;

            sprintf( parname, "znn_mc_ldpover0lep_ratio_M%d_H%d_%db_err", mbi+1, hbi+1, bbi+1 ) ;
            inFile << parname << "  \t" << ldpoverzlerr << endl;
        } // bbi
      } // hbi
    } // mbi


    // add here the fractions (bin by bin) of 2b/1b and 3b/1b SL events (just for the MC for now)

    for (int mbi = 0 ; mbi < nBinsMET ; mbi++) {
      for (int hbi = 0 ; hbi < nBinsHT ; hbi++) {

	TString Sl2bstring     = "sl_frac_2b_val";
	TString Sl2bstring_err = "sl_frac_2b_err";
	TString Sl3bstring     = "sl_frac_3b_val";
	TString Sl3bstring_err = "sl_frac_3b_err";
	TString Sl4bstring     = "sl_frac_4b_val";
	TString Sl4bstring_err = "sl_frac_4b_err";

	Sl2bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl2bstring_err += sMbins[mbi]+sHbins[hbi] ;
	Sl3bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl3bstring_err += sMbins[mbi]+sHbins[hbi] ;
	Sl4bstring     += sMbins[mbi]+sHbins[hbi] ;
	Sl4bstring_err += sMbins[mbi]+sHbins[hbi] ;

	inFile << Sl2bstring     << "   \t" << sl_frac2b_val[mbi][hbi] << endl ;
	inFile << Sl2bstring_err << "   \t" << sl_frac2b_err[mbi][hbi] << endl ;
	inFile << Sl3bstring     << "   \t" << sl_frac3b_val[mbi][hbi] << endl ;
	inFile << Sl3bstring_err << "   \t" << sl_frac3b_err[mbi][hbi] << endl ;
	inFile << Sl4bstring     << "   \t" << sl_frac4b_val[mbi][hbi] << endl ;
	inFile << Sl4bstring_err << "   \t" << sl_frac4b_err[mbi][hbi] << endl ;

      }
    }




    gSystem->Exec("mkdir -p rootfiles") ;
    char outHistName[1000] ;
    if ( mgl>0. && mlsp>0. ) {
       if ( target_susy_all0lep > 0 ) {
          sprintf( outHistName, "rootfiles/gi-plots-nb4-wsusy-mgl%.0f-mlsp%.0f-%.0fevts-met%d-ht%d-v%d.root", mgl, mlsp, target_susy_all0lep, nBinsMET, nBinsHT, version ) ;
       } else {
          sprintf( outHistName, "rootfiles/gi-plots-nb4-wsusy-mgl%.0f-mlsp%.0f-met%d-ht%d-v%d.root", mgl, mlsp, nBinsMET, nBinsHT, version ) ;
       }
    } else {
       sprintf( outHistName, "rootfiles/gi-plots-nb4-met%d-ht%d-v%d.root", nBinsMET, nBinsHT, version ) ;
    }
    saveHist( outHistName, "h*" ) ;


    inFile.close();
    return;
  
  }
Example #7
0
void draw_tt(std::string var="mTT",int nbins=10, double xmin=0, double xmax=200,std::string xtitle="m_{#tau#tau}", std::string ytitle="Events")
{
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);

  std::string dir = "/afs/cern.ch/work/j/jlawhorn/public/vbf/ntuples/";
  double sigscale = 10;
  double sigscale1 = 10; 
  std::stringstream scale; scale << sigscale;
  std::stringstream scale1; scale1 << sigscale1;

  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(ptTau1>45 && ptTau2>45 && abs(etaTau1) <4.0 && abs(etaTau1)<4.0 )";
  std::string jetcut = objcut+"*(ptJet1>30 && ptJet2>30 && abs(etaJet1) <4.7 && abs(etaJet2) <4.7 )";
  std::string ththcut = jetcut+"*(tauCat1==1 && tauCat2==1 && mJJ>500 && abs(dEta)>3.5)";

  //signal region
  std::string vbfcut = ththcut+"*eventWeight*(eventType==0)*"+lumi.str();
  std::string zttcut = ththcut+"*eventWeight*(eventType==1)*"+lumi.str();
  std::string ttbarcut = ththcut+"*eventWeight*(eventType==3)*"+lumi.str();
  //std::string ewkcut = ththcut+"*eventWeight*(eventType==2)*"+lumi.str();
  std::string othercut = ththcut+"*eventWeight*(eventType==4 || eventType==2)*"+lumi.str();
  
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *tree = load(dir+"vbf_comb.root"); 

  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  TH1F *vbf = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  tree->Draw(vardraw.c_str(),vbfcut.c_str());
  InitSignal(vbf);
  vbf->SetLineColor(kBlack);
  TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  vardraw = var+">>"+"TTbar";
  tree->Draw(vardraw.c_str(),ttbarcut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  TH1F *ztt = new TH1F("Ztt","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ztt";
  tree->Draw(vardraw.c_str(),zttcut.c_str());
  InitHist(ztt, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);
  //TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  //vardraw = var+">>"+"Ewk";
  //tree->Draw(vardraw.c_str(),ewkcut.c_str());
  //InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *other = new TH1F("Other","",nbins,xmin,xmax);
  vardraw = var+">>"+"Other";
  tree->Draw(vardraw.c_str(),othercut.c_str());
  InitHist(other, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  
  delete canv0;
  //----------------------------------------------------------------------------
  //Print out the yields
  Double_t error=0.0;
  ofstream outfile;
  outfile.open("yields_tt.txt");
  outfile << "Yields for the signal region." << std::endl;
  outfile << "VBF   "  << vbf->IntegralAndError(0,vbf->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "TTbar   "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(0,ztt->GetNbinsX(),error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "other   "  << other->IntegralAndError(0,other->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "S/sqrt(B)    "  << vbf->Integral()/(other->Integral()+ztt->Integral()+ttbar->Integral()/*+ewk->Integral()*/) << endl;
  //--------------------------------------------------------------------------
  //continue outputing
  //outfile << "Ewk total    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << endl << endl << endl;
  outfile << "In the signal region (100,150GeV)  " <<endl;
  outfile << "VBF   "  << vbf->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "TTbar    "  << ttbar->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(5,11,error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "other    "  << other->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile.close();
  //-----------------------------------------------------------------------
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //ewk->Add(other); ttbar->Add(ewk); 
  //ztt->Add(ttbar); vbf->Add(ztt);
  //Error band stat
  TH1F* errorBand = (TH1F*)vbf ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  ztt->SetMaximum(1.2*std::max(maximum(ttbar, 0), maximum(ztt, 0)));
  //blind(vbf,75,150);
  ztt->Draw("hist");
  ttbar->Draw("histsame");
  //ewk->Draw("histsame");
  other->Draw("histsame");
  vbf->Draw("histsame");
  //errorBand->Draw("e2same");
  canv->RedrawAxis();
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(vbf , "VBF Signal"             , "F");
  leg->AddEntry(ztt  , "Z#rightarrow#tau#tau"  , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"              , "F" );
  //leg->AddEntry(ewk  , "Electroweak"           , "F" );
  leg->AddEntry(other, "Other"                 , "F" );
  //leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
  
  //CMS preliminary 
  const char* dataset = "CMS Preliminary, H#rightarrow#tau#tau, 3.0 ab^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_tt.png").c_str());
  
  /*
    Ratio Data over MC
    
    TCanvas *canv1 = MakeCanvas("canv0", "histograms", 600, 400);
    canv1->SetGridx();
    canv1->SetGridy();
    canv1->cd();
  */
  /*   TH1F* model = (TH1F*)ztt ->Clone("model");
       TH1F* test1 = (TH1F*)data->Clone("test1"); 
       for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
       //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
       model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
       //model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
       model->SetBinError  (ibin+1, 0);
     test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
     test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
   }
   double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
   double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
   double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
   double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

   std::vector<double> edges;
   TH1F* zero = (TH1F*)ttbar->Clone("zero"); zero->Clear();
   TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
   for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
     rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
     rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
     zero->SetBinContent(ibin+1, 0.);
     zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
   }
   for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
     if(rat1->GetBinContent(ibin+1)>0){
       edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
       // catch cases of 0 bins, which would lead to 0-alpha*0-1
       rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
     }
   }
   float range = 0.1;
   std::sort(edges.begin(), edges.end());
   if (edges[edges.size()-2]>0.1) { range = 0.2; }
   if (edges[edges.size()-2]>0.2) { range = 0.5; }
   if (edges[edges.size()-2]>0.5) { range = 1.0; }
   if (edges[edges.size()-2]>1.0) { range = 1.5; }
   if (edges[edges.size()-2]>1.5) { range = 2.0; }
   rat1->SetLineColor(kBlack);
   rat1->SetFillColor(kGray );
   rat1->SetMaximum(+range);
   rat1->SetMinimum(-range);
   rat1->GetYaxis()->CenterTitle();
   rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
   rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
   rat1->Draw();
   zero->SetFillStyle(  3013);
   zero->SetFillColor(kBlack);
   zero->SetLineColor(kBlack);
   zero->SetMarkerSize(0.1);
   zero->Draw("e2histsame");
   canv1->RedrawAxis();

   TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
   stat1->SetBorderSize(   0 );
   stat1->SetFillStyle(    0 );
   stat1->SetTextAlign(   12 );
   stat1->SetTextSize ( 0.05 );
   stat1->SetTextColor(    1 );
   stat1->SetTextFont (   62 );
   stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
   //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
   //stat1->Draw();
   canv1->Print((var+"_ratio.png").c_str());*/
}
void MutualInfoSingleVar_reducedBias(TString theFormula = "fjet1MassSDb2",TString histFileName = "fjet1MassSDb2",
                                     int numBins = 320,Double_t histMin = -20,Double_t histMax = 300){

  TFile *signalFile = new TFile("signal_word.root");
  TTree *signalTree = (TTree*) signalFile->FindObjectAny("DMSTree");
  TFile *backgdFile = new TFile("background_word.root");
  TTree *backgdTree = (TTree*) backgdFile->FindObjectAny("DMSTree");

  TH1F *signalHist = new TH1F("Signal","Signal",numBins,histMin,histMax); signalHist->Sumw2();
  TH1F *backgdHist = new TH1F("Backgd","Backgd",numBins,histMin,histMax); backgdHist->Sumw2();
  TH1F *sumHist = new TH1F("Sum","Sum",numBins,histMin,histMax); sumHist->Sumw2();

  signalTree->Draw(theFormula + TString(">>Signal"),"weight*(abs(fjet1PartonId)==24)");
  backgdTree->Draw(theFormula + TString(">>Backgd"),"weight");
  *sumHist = *signalHist + *backgdHist;

  Double_t signalErr = 0.;
  Double_t signalWeights = signalHist->IntegralAndError(1,numBins,signalErr);
  Double_t backgdErr = 0.;
  Double_t backgdWeights = backgdHist->IntegralAndError(1,numBins,backgdErr);
  Double_t sumErr = 0.;
  Double_t sumWeights = sumHist->IntegralAndError(1,numBins,sumErr);

  Double_t signalFrac = signalWeights/sumWeights;
  Double_t signalFracErr = sqrt(TMath::Power(signalErr/sumWeights,2) + TMath::Power(signalWeights*sumErr/(TMath::Power(sumWeights,2)),2));

  Double_t truthEntropy = -1*signalFrac*TMath::Log2(signalFrac) - (1-signalFrac)*TMath::Log2(1-signalFrac);
  Double_t truthErr = (TMath::Abs(1+TMath::Log2(signalFrac)) + TMath::Abs(1+TMath::Log2(1-signalFrac)))*signalFracErr;

  Double_t varErr = 0.;
  Double_t varEntropy = histEntropy(sumHist,numBins,sumWeights,sumErr,varErr);
  Double_t unionErr = 0.;
  Double_t unionEntropy = histEntropy(signalHist,numBins,sumWeights,sumErr,unionErr) +
                          histEntropy(backgdHist,numBins,sumWeights,sumErr,unionErr);

  Double_t MutualInfo = truthEntropy + varEntropy - unionEntropy;
  Double_t MutualErr = sqrt(TMath::Power(truthErr,2) + TMath::Power(varErr,2) + TMath::Power(unionErr,2));

  cout << endl;
  cout << theFormula << endl;
  cout << endl;
  cout << "Old Way" << endl;
  cout << "H(T):   " << truthEntropy << " +- " << truthErr  << endl;
  cout << "H(A):   " << varEntropy   << " +- " << varErr    << endl;
  cout << "H(T,A): " << unionEntropy << " +- " << unionErr  << endl;
  cout << "I(T;A): " << MutualInfo   << " +- " << MutualErr << endl;

  TFile *outFile = new TFile(TString("scratch/") + histFileName + TString(".root"),"RECREATE");

  /////////////////////////////////////////////////////////////////////////////////////////////////////////
  //                            Attempts to reduce bias with A.20                                        //
  /////////////////////////////////////////////////////////////////////////////////////////////////////////

  Double_t signalEntropyErr = 0.;
  Double_t signalEntropy = histEntropy(signalHist,numBins,signalWeights,signalErr,signalEntropyErr);
  Double_t backgdEntropyErr = 0.;
  Double_t backgdEntropy = histEntropy(backgdHist,numBins,backgdWeights,backgdErr,backgdEntropyErr);

  TH1F *signalHist_0 = new TH1F("Signal_0","Signal_0",numBins,histMin,histMax); signalHist_0->Sumw2();
  TH1F *backgdHist_0 = new TH1F("Backgd_0","Backgd_0",numBins,histMin,histMax); backgdHist_0->Sumw2();
  TH1F *sumHist_0 = new TH1F("Sum_0","Sum_0",numBins,histMin,histMax); sumHist_0->Sumw2();

  signalTree->Draw(theFormula + TString(">>Signal_0"),"weight*(abs(fjet1PartonId)==24 && event % 2 == 0)");
  backgdTree->Draw(theFormula + TString(">>Backgd_0"),"weight*(event % 2 == 0)"); // This event % 2 term splits the sample in half
  *sumHist_0 = *signalHist_0 + *backgdHist_0;

  Double_t sumErr_0 = 0.;
  Double_t sumWeights_0 = sumHist_0->IntegralAndError(1,numBins,sumErr);

  Double_t mixedErr_0 = 0.;
  Double_t mixedEntropy_0 = histEntropy(sumHist_0,numBins,sumWeights_0,sumErr_0,mixedErr_0);

  Double_t MutualInfo_0 = mixedEntropy_0 - signalFrac*signalEntropy - (1-signalFrac)*backgdEntropy;
  Double_t MutualErr_0  = sqrt(TMath::Power(mixedErr_0,2) +
                               TMath::Power(signalFracErr*(signalEntropy-backgdEntropy),2) +
                               TMath::Power(signalFrac*signalEntropyErr,2) +
                               TMath::Power((1-signalFrac)*backgdEntropyErr,2));

  cout << endl;
  cout << "Reduced Bias Results (0)" << endl;
  cout << "f:         " << signalFrac     << " +- " << signalFracErr    << endl;
  cout << "H_sig+bck: " << mixedEntropy_0 << " +- " << mixedErr_0       << endl;
  cout << "H_sig:     " << signalEntropy  << " +- " << signalEntropyErr << endl;
  cout << "H_bck:     " << backgdEntropy  << " +- " << backgdEntropyErr << endl;
  cout << "I(T;A):    " << MutualInfo_0   << " +- " << MutualErr_0      << endl;

  TH1F *signalHist_1 = new TH1F("Signal_1","Signal_1",numBins,histMin,histMax); signalHist_1->Sumw2();
  TH1F *backgdHist_1 = new TH1F("Backgd_1","Backgd_1",numBins,histMin,histMax); backgdHist_1->Sumw2();
  TH1F *sumHist_1 = new TH1F("Sum_1","Sum_1",numBins,histMin,histMax); sumHist_1->Sumw2();

  signalTree->Draw(theFormula + TString(">>Signal_1"),"weight*(abs(fjet1PartonId)==24 && event % 2 == 1)");
  backgdTree->Draw(theFormula + TString(">>Backgd_1"),"weight*(event % 2 == 1)"); // This event % 2 term splits the sample in half
  *sumHist_1 = *signalHist_1 + *backgdHist_1;

  Double_t sumErr_1 = 0.;
  Double_t sumWeights_1 = sumHist_1->IntegralAndError(1,numBins,sumErr);

  Double_t mixedErr_1 = 0.;
  Double_t mixedEntropy_1 = histEntropy(sumHist_1,numBins,sumWeights_1,sumErr_1,mixedErr_1);

  Double_t MutualInfo_1 = mixedEntropy_1 - signalFrac*signalEntropy - (1-signalFrac)*backgdEntropy;
  Double_t MutualErr_1  = sqrt(TMath::Power(mixedErr_1,2) +
                               TMath::Power(signalFracErr*(signalEntropy-backgdEntropy),2) +
                               TMath::Power(signalFrac*signalEntropyErr,2) +
                               TMath::Power((1-signalFrac)*backgdEntropyErr,2));

  cout << endl;
  cout << "Reduced Bias Results (1)" << endl;
  cout << "f:         " << signalFrac     << " +- " << signalFracErr    << endl;
  cout << "H_sig+bck: " << mixedEntropy_1 << " +- " << mixedErr_1       << endl;
  cout << "H_sig:     " << signalEntropy  << " +- " << signalEntropyErr << endl;
  cout << "H_bck:     " << backgdEntropy  << " +- " << backgdEntropyErr << endl;
  cout << "I(T;A):    " << MutualInfo_1   << " +- " << MutualErr_1      << endl;

  signalHist->Write();
  backgdHist->Write();
  sumHist->Write();
  signalHist_0->Write();
  backgdHist_0->Write();
  sumHist_0->Write();
  signalHist_1->Write();
  backgdHist_1->Write();
  sumHist_1->Write();

  outFile->Close();

}
Example #9
0
void listyieldsWZ_stat(std::string rootfile, int wzstep, std::string proc,int var,int lhe){
	string WZstepname [7]= {"Three leptons",
	"WZ candidate",
	"Z sel",
	"W sel",
	"M(3l) > 100 GeV",
	"1 or 0 b-jets",
	"0 b-jets"};
	
	string variation [5]= {"Central",
	"Up b-tag",
	"Down b-tag",
	"Up b-mistag",
	"Down b-mistag"};
	
	TH1F::SetDefaultSumw2();
	
	TH1F *histo = nullptr;
	TFile *f = new TFile(rootfile.c_str());
	if (var == 0) histo = (TH1F*)f->Get(Form("MET_WZSMstep%i/%s",wzstep, proc.c_str() ));
	if (var == 1) histo = (TH1F*)f->Get(Form("MET_WZSMstep%iUncBTAGUp/%s",wzstep, proc.c_str() ));
	if (var == 2) histo = (TH1F*)f->Get(Form("MET_WZSMstep%iUncBTAGDo/%s",wzstep, proc.c_str() ));
	if (var == 3) histo = (TH1F*)f->Get(Form("MET_WZSMstep%iUncBMISTAGUp/%s",wzstep, proc.c_str() ));
	if (var == 4) histo = (TH1F*)f->Get(Form("MET_WZSMstep%iUncBMISTAGDo/%s",wzstep, proc.c_str() ));
	
	if (var == 5) histo = (TH1F*)f->Get(Form("mZ1_WZaccden/%s", proc.c_str() ));
	if (var == 6) histo = (TH1F*)f->Get(Form("mZ1_WZaccnum/%s", proc.c_str() ));
	
	Double_t error;
	Int_t yield = histo->GetEntries();
	Double_t integral = histo->Integral(0,100000000);
	
	Double_t normfactor;
	
	if (proc.find("WZTo3LNu") != std::string::npos) normfactor=4.42965/1980800;
	else if (proc.find("DYJetsToLL_M10to50") != std::string::npos) normfactor=18610/2.967885e+07;
	else if (proc.find("DYJetsToLL_M50") != std::string::npos) normfactor=6025.2/2.874797e+07;
	else if (proc.find("_TW_") != std::string::npos) normfactor=35.6/995600;
	else if (proc.find("TbarW") != std::string::npos) normfactor=35.6/988500;
	else if (proc.find("TToLeptons_sch") != std::string::npos) normfactor=3.68064/984400;
	else if (proc.find("TToLeptons_tch") != std::string::npos) normfactor=44.071956/3299800;
	else if (proc.find("TbarToLeptons_tch") != std::string::npos) normfactor=26.2278/1680200;
	else if (proc.find("TTJets") != std::string::npos) normfactor=831.8/8.970451e+07;
	else if (proc.find("TTWToLNu") != std::string::npos) normfactor=0.2043/252908;
	else if (proc.find("TTZToLLNuNu") != std::string::npos) normfactor=0.2529/398000;
	else if (proc.find("TTHnobb") != std::string::npos) normfactor=0.2151/1562609;
	else if (proc.find("TTGJets") != std::string::npos) normfactor=3.697/4832230;
	else if (proc.find("WJetsToLNu") != std::string::npos) normfactor=61526.7/2.239467e+07;
	else if (proc.find("WWTo2L2Nu") != std::string::npos) normfactor=12.178/1965200;
	else if (proc.find("WZTo3LNu") != std::string::npos) normfactor=4.42965/1980800;
	else if (proc.find("_ZZ_") != std::string::npos) normfactor=16.523/996944;
	else if (proc.find("GGHZZ4L") != std::string::npos) normfactor=0.01212/498000;
	else if (proc.find("WGToLNuG") != std::string::npos) normfactor=585.8/6099599;
	else if (proc.find("_WWZ_") != std::string::npos) normfactor=0.1651/250000;
	else if (proc.find("_WZZ_") != std::string::npos) normfactor=0.05565/250000;
	else if (proc.find("_ZZZ_") != std::string::npos) normfactor=0.01398/250000;
	else if (proc.find("_ZGTo2LG_") != std::string::npos) normfactor=117.864/4451319;

	histo->Scale(normfactor*2260);
    //Double_t yield_scaled = integral*normfactor*2260;
    Double_t error_scaled;
    Double_t yield_scaled = histo->IntegralAndError(0,1000000,error_scaled);
    
    /*
    if (rootfile.find("all") != std::string::npos){
      cout << lhe << "\t";
      if (var==5) cout << "Den: " << integral;
      if (var==6) cout << "Num: " << integral << endl;
    }
    */
    
    
	if (rootfile.find("all") != std::string::npos){
		cout << WZstepname[wzstep] <<"\t" << yield_scaled << " $\\pm$ " << error_scaled << endl;
	} else if (rootfile.find("eee") != std::string::npos) {
		cout << "Selection step:	" << WZstepname[wzstep] << "	" << "eee	" << yield << endl;
	} else if (rootfile.find("eem") != std::string::npos) {
		cout << "Selection step:	" << WZstepname[wzstep] << "	" << "eem	" << yield << endl;
	} else if (rootfile.find("mme") != std::string::npos) {
		cout << "Selection step:	" << WZstepname[wzstep] << "	" << "mme	" << yield << endl;
	} else if (rootfile.find("mmm") != std::string::npos) {
		cout << "Selection step:	" << WZstepname[wzstep] << "	" << "mmm	" << yield << endl;
	}
	
}
Example #10
0
void bbtt_upg_mt(std::string var,int nbins, double xmin, double xmax,std::string xtitle, std::string ytitle, double sigscale=1,int hist=1)
{
  double massLEdges[14]    = {-0.5,-0.45,-0.4,-0.35,-0.3,-0.25,-0.2,-0.15,-0.1,-0.05,0.0,0.05,0.1,0.2};
  TFile *outDC = new TFile("hh_mt_inputs.root","RECREATE");

  //SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  setTDRStyle();
  TH1::SetDefaultSumw2(1);

  std::string dir = "/data/blue/Bacon/029a/Upgrade/sep-2-bbtt/";
  
  std::stringstream scale; scale << sigscale;
  
  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(tauCat1==1 && tauCat2==3 && ptTau1>30 && ptTau2>30 && (bTag1==2||bTag1==3||bTag1==6||bTag1==7) && (bTag2==2||bTag2==3||bTag2==6||bTag2==7) && ptB1>30 && ptB2>30)*(abs(etaB1)<2.5 && abs(etaB2)<2.5 && abs(etaTau1)<2.1 && abs(etaTau2)<2.5 && ptTrk1>0)";//*(tauIso2<0.15)";

  std::string jetcut = objcut+"*(m_svpileup>100 && m_svpileup<150 && mBB1>90 && mBB1<130 && mt2pileup>100)";
  //std::string jetcut = objcut+"*(m_svpileup>100 && m_svpileup<150 && mBB1>90 && mBB1<130)";
  //std::string jetcut = objcut+"*(1.0)";

  //signal region
  std::string mccut = jetcut+"*eventWeight*"+lumi.str();
  std::string sigcut = jetcut+"*eventWeight*"+lumi.str();
  std::string zjetcut = jetcut+"*eventWeight*(eventType!=3&&eventType!=1)*"+lumi.str();
  std::string wjetcut = jetcut+"*eventWeight*(eventType==3&&eventType!=1)*"+lumi.str();
  std::string ewkcut = jetcut+"*eventWeight*(eventType!=1)*"+lumi.str();
  std::string vbfcut = jetcut+"*eventWeight*49470*0.0632*"+lumi.str();
  
  //--------------------------------------------------------------------------
  
  //Get the trees
  TTree *hhtree = load(dir+"gFHHTobbtautau.root");
  TTree *hhtree_m1 = load(dir+"gFHHTobbtautaulam1m.root");
  TTree *hhtree_m5 = load(dir+"gFHHTobbtautaulam5m.root");
  TTree *hhtree_0 = load(dir+"gFHHTobbtautaulam0.root");
  TTree *hhtree_p5 = load(dir+"gFHHTobbtautaulam5p.root");
  TTree *hhtree_vbf = load("/data/blue/Bacon/029a/Upgrade/sep-10-bbtt/vbfHHTobbtautau.root");
  TTree *tttree = load(dir+"tt.root");
  TTree *vbfhtree = load(dir+"VBFHToTauTau.root");
  TTree *gfhtree = load(dir+"ggFHToTauTau.root");
  TTree *assohtree = load(dir+"vH_ttH.root");
  TTree *vjettree = load(dir+"Bjets.root");
  TTree *ewktree = load(dir+"ewk.root");
  
  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  TH1F *Ztt;
  if(hist)
    Ztt = new TH1F("DY","",nbins,xmin,xmax);
  else 
    Ztt = new TH1F("DY","",13, massLEdges);
  vardraw = var+">>"+"DY";
  vjettree->Draw(vardraw.c_str(),zjetcut.c_str());
  InitHist(Ztt  , xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);
  TH1F *ttbar;
  if(hist)
    ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  else 
    ttbar = new TH1F("TTbar","",13, massLEdges);
  vardraw = var+">>"+"TTbar";
  tttree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  TH1F *wjets;
  if(hist)
    wjets= new TH1F("Wjets","",nbins,xmin,xmax);
  else
    wjets = new TH1F("Wjets","",13, massLEdges);
  vardraw = var+">>"+"Wjets";
  vjettree->Draw(vardraw.c_str(),wjetcut.c_str());
  InitHist(wjets, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(222,90,106), 1001);
  TH1F *ewk;
  if(hist)
    ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  else
    ewk = new TH1F("Ewk","",13,massLEdges);
  vardraw = var+">>"+"Ewk";
  ewktree->Draw(vardraw.c_str(),ewkcut.c_str());
  InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *vbfh;
  if(hist)
    vbfh = new TH1F("VBFH","",nbins,xmin,xmax);
  else
    vbfh = new TH1F("VBFH","",13,massLEdges);
  vardraw = var+">>"+"VBFH";
  vbfhtree->Draw(vardraw.c_str(),vbfcut.c_str());
  InitHist(vbfh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);
  TH1F *ggh;
  if(hist)
    ggh = new TH1F("GGH","",nbins,xmin,xmax);
  else
    ggh = new TH1F("GGH","",13,massLEdges);
  vardraw = var+">>"+"GGH";
  gfhtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(ggh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);
  TH1F *assoh;
  if(hist)
    assoh = new TH1F("AH","",nbins,xmin,xmax);
  else
    assoh = new TH1F("AH","",13,massLEdges);
  vardraw = var+">>"+"AH";
  assohtree->Draw(vardraw.c_str(),mccut.c_str());
  InitHist(assoh, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(250,202,255), 1001);
  TH1F *smhh;
  if(hist)
    smhh= new TH1F("SMhh","",nbins,xmin,xmax);
  else
    smhh= new TH1F("SMhh","",13,massLEdges);
  vardraw = var+">>"+"SMhh";
  hhtree->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(smhh);
  smhh->SetLineColor(kBlack);
  TH1F *hh_0 = new TH1F("hh_0","",nbins,xmin,xmax);
  vardraw = var+">>"+"hh_0";
  hhtree_0->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(hh_0);
  hh_0->SetLineColor(kBlack);
  TH1F *hh_m1;
  if(hist)
    hh_m1 = new TH1F("hh_m1","",nbins,xmin,xmax);
  else
    hh_m1 = new TH1F("hh_m1","",13,massLEdges);
  vardraw = var+">>"+"hh_m1";
  hhtree_m1->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(hh_m1);
  hh_m1->SetLineColor(kBlack);
  TH1F *hh_m5;
  if(hist)
    hh_m5 = new TH1F("hh_m5","",nbins,xmin,xmax);
  else
    hh_m5 = new TH1F("hh_m5","",13,massLEdges);
  vardraw = var+">>"+"hh_m5";
  hhtree_m5->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(hh_m5);
  hh_m5->SetLineColor(kBlack);
  TH1F *hh_p5;
  if(hist)
    hh_p5= new TH1F("hh_p5","",nbins,xmin,xmax);
  else
    hh_p5= new TH1F("hh_p5","",13,massLEdges);
  vardraw = var+">>"+"hh_p5";
  hhtree_p5->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(hh_p5);
  hh_p5->SetLineColor(kBlack);
  TH1F *hh_vbf;
  if(hist)
    hh_vbf= new TH1F("hh_vbf","",nbins,xmin,xmax);
  else
    hh_vbf= new TH1F("hh_vbf","",13,massLEdges);
  vardraw = var+">>"+"hh_vbf";
  hhtree_vbf->Draw(vardraw.c_str(),sigcut.c_str());
  InitSignal(hh_vbf);
  hh_vbf->SetLineColor(kBlue);
  delete canv0;
  //for(int i0 = 0; i0 < ewk->GetNbinsX()+1; i0++)
  //  if(ewk->GetBinContent(i0) == 0)
  //    ewk->SetBinError(i0,2.8);
  //---------------------------------------------------------------------------
  //Print out the yields
  Double_t error=999;
  Double_t sigN=0;
  Double_t sigSig=0;
  Double_t bgdN=0;
  Double_t bgdSig=0;
  //ofstream outfile;
  //outfile.open("yields.txt");
  //outfile << "Yields for the signal region." << std::endl;
  cout << jetcut << endl;
  cout << "SM hh   "  << smhh->IntegralAndError(0,smhh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  cout << " VBF HH "  << hh_vbf->IntegralAndError(0,hh_vbf->GetNbinsX(),error) << "+/-";
  sigN+=smhh->IntegralAndError(0,smhh->GetNbinsX(),error);
  sigSig+=error;
  cout << error << endl; error=999;
  cout << "ttbar   "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  bgdN+=ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error);bgdSig+=error*error;
  cout << "Ztt     "  << Ztt->IntegralAndError(0,Ztt->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  bgdN+=Ztt->IntegralAndError(0,Ztt->GetNbinsX(),error);bgdSig+=error*error;
  cout << "ewk     "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  bgdN+=ewk->IntegralAndError(0,ewk->GetNbinsX(),error);bgdSig+=error*error;
  cout << "wjets   "  << wjets->IntegralAndError(0,wjets->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  bgdN+=wjets->IntegralAndError(0,wjets->GetNbinsX(),error);bgdSig+=error*error;
  cout << "ggH     "  << ggh->IntegralAndError(0,ggh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  bgdN+=ggh->IntegralAndError(0,ggh->GetNbinsX(),error);bgdSig+=error*error;
  cout << "vbfH    "  << vbfh->IntegralAndError(0,vbfh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  bgdN+=vbfh->IntegralAndError(0,vbfh->GetNbinsX(),error);bgdSig+=error*error;
  cout << "vH/ttH  "  << assoh->IntegralAndError(0,assoh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  bgdN+=assoh->IntegralAndError(0,assoh->GetNbinsX(),error); bgdSig+=error*error;
  cout << "S = " << sigN << "+/-" << sigSig << endl;
  cout << "B = " << bgdN << "+/-" << TMath::Sqrt(bgdSig) << endl;
  cout << "S/sqrt(B) = " << sigN/TMath::Sqrt(bgdN) << endl;

  //--------------------------------------------------------------------------
  //outfile.close();
  outDC->cd();
  TDirectory* lTD = outDC->mkdir("mutau");
  outDC->cd(lTD->GetPath());
  ttbar->SetName("data_obs");
  ttbar->SetTitle("data_obs");
  ttbar->Write();
  Ztt->SetName("ZTT");
  Ztt->SetTitle("ZTT");
  Ztt->Write();
  ttbar->SetName("TT");
  ttbar->SetTitle("TT");
  ttbar->Write();
  wjets->SetName("W");
  wjets->SetTitle("W");
  wjets->Write();
  ewk->SetName("VV");
  ewk->SetTitle("VV");
  ewk->Write();
  vbfh->SetName("qqH");
  vbfh->SetTitle("qqH");
  vbfh->Write();
  ggh->SetName("ggH");
  ggh->SetTitle("ggH");
  ggh->Write();
  assoh->SetName("assoH");
  assoh->SetTitle("assoH");
  assoh->Write();
  smhh->SetName("ggHH");
  smhh->SetTitle("ggHH");
  smhh->Write();
  hh_0->SetName("lam0");
  hh_0->SetTitle("lam0");
  hh_0->Write();
  hh_m5->SetName("lamm5");
  hh_m5->SetTitle("lamm5");
  hh_m5->Write();
  hh_m1->SetName("lamm1");
  hh_m1->SetTitle("lamm1");
  hh_m1->Write();
  hh_p5->SetName("lamp5");
  hh_p5->SetTitle("lamp5");
  hh_p5->Write();
  hh_vbf->SetName("qqHH");
  hh_vbf->SetTitle("qqHH");
  hh_vbf->Write();
  outDC->Close();
  //stack some  histtograms together
  vbfh->Add(ggh);
  vbfh->Add(assoh);
  cout << "Single H    "  << vbfh->IntegralAndError(0,vbfh->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  wjets->Add(ewk); 
  cout << "Total  Electroweak    "  << wjets->IntegralAndError(0,wjets->GetNbinsX(),error) << "+/-";
  cout << error << endl; error=999;
  //-----------------------------------------------------------------------
  smhh->Scale(sigscale);
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 800, 600);
  canv->cd();
  wjets->Add(ttbar);
  Ztt->Add(wjets);
  vbfh->Add(Ztt);
  //Error band stat
  TH1F* errorBand = (TH1F*)vbfh->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  vbfh->SetMaximum(1.0*std::max(maximum(vbfh, 0), maximum(smhh, 0)));
  //blind(data,75,150);
  //data->Draw("e");
  vbfh->Draw("hist");
  Ztt->Draw("histsame");
  wjets->Draw("histsame");
  //ggh->Draw("histsame");
  ttbar->Draw("histsame");
  //qcd->Draw("histsame");
  //data->Draw("esame");
  errorBand->Draw("e2same");
  smhh->Draw("histsame");
  canv->RedrawAxis();
  //canv->SetLogy(1);
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.65, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(smhh  , TString::Format("%.0f#timeshh#rightarrow#tau#tau bb", sigscale) , "L" );
  leg->AddEntry(vbfh  , "SM H#rightarrow#tau#tau"   , "F" );
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(wjets  , "Electroweak"                    , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------
   
  //CMS_lumi_v2( canv, 14, 11 );
  //CMS preliminary 
  //const char* dataset = "CMS Simulation, 3000 fb^{-1} at 14 TeV";
  const char* category = "";
  //CMSPrelim(dataset, "#tau_{#mu}#tau_{h}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  //chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_mt.png").c_str());

  /*
    Ratio Data over MC
  */
  /*
  TCanvas *canv1 = MakeCanvas("canv0", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)vbfh->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    //model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    model->SetBinError  (ibin+1, 0);
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ttbar->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)vbfh->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? vbfh->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  //stat1->Draw();
  canv1->Print((var+"_ratio.png").c_str());
  */
}