Пример #1
1
void ratioPlots( TCanvas* c1, TH1* h_r, TH1* h_i, 
		 string xTitle, string yTitle, 	string savePath, 
		 double fitMin=-100000, double fitMax=100000, bool doubleColFit=0 ){

	double xMaximum = h_r->GetXaxis()->GetBinUpEdge(h_r->GetXaxis()->GetLast());
	double xMinimum = h_r->GetXaxis()->GetBinLowEdge(h_r->GetXaxis()->GetFirst());
	double yMaximum;
	double yMinimum;

	h_i->Sumw2();
	h_r->Sumw2();

	TLine* line1 = new TLine(xMinimum,1,xMaximum,1);
	line1->SetLineColor(1);
	line1->SetLineWidth(2);
	line1->SetLineStyle(7);
	
	TF1* fpol1  = new TF1("fpol1", "pol1", fitMin, fitMax);	
	fpol1->SetLineColor(2);
	fpol1->SetLineWidth(3);
	fpol1->SetLineStyle(7);
	
	TH1* hRatio = (TH1*)h_r->Clone("clone_record");
	hRatio->Divide(h_i);
	yMaximum = hRatio->GetMaximum();
	yMinimum = hRatio->GetMinimum(0);
	hRatio->GetYaxis()->SetRangeUser(yMinimum/2.5,yMaximum+yMaximum/5);
	hRatio->SetXTitle(xTitle.c_str());
	hRatio->SetYTitle(yTitle.c_str());
	hRatio->SetLineColor(9); 
	hRatio->SetLineWidth(2); 
	hRatio->SetMarkerStyle(8); 
	hRatio->Draw("e");
	hRatio->Fit("fpol1", "L");
	line1->Draw("SAME");
	
	if(doubleColFit){
		double p0=fpol1->GetParameter(0);
		double p1=fpol1->GetParameter(1);
		double endPoint=double(fitMax*p1)+p0;
		double p1new=(endPoint-1)/(fitMax-fitMin);
		char fun[100], text[100];
		sprintf(fun,"x*(%f)+1",p1new);	
		sprintf(text,"Tangent: %f",p1new);	
		TF1* fnew = new TF1("fnew", fun, fitMin, fitMax);
		fnew->SetLineColor(2);
		fnew->SetLineWidth(3);
		fnew->Draw("SAME");
	
			
		TText* Title = new TText( fitMax/12, yMinimum, text);
		Title->SetTextColor(2);
		Title->SetTextSize(0.035);
		Title->Draw("SAME");
	}

	c1->SaveAs(savePath.c_str());
	c1->cd();
}
Пример #2
0
void test2bMBcorr(const Char_t *datatag, const Char_t *mctag, Bool_t bayes = kFALSE)
{

  TCanvas *c = new TCanvas("c", "c");
  c->Divide(4, 3);
  for (Int_t i = 0; i < 10; i++) {
    TH1 *hnomb = UnfoldMe_TAG(datatag, mctag, "clist", i, kFALSE, kFALSE, kFALSE, 1., 4, AliUnfolding::kPowerLaw, 5000., bayes);
    TH1 *hmb = UnfoldMe_TAG(datatag, mctag, "clist", i, kTRUE, kFALSE, kFALSE, 1., 4, AliUnfolding::kPowerLaw, 5000., bayes);
    hnomb->Divide(hmb);
    c->cd(i+1)->DrawFrame(1., 0.9, 100., 1.1);
    c->cd(i+1)->SetLogx();
    hnomb->Draw("same");
    c->Update();
  }

}
Пример #3
0
  //____________________________________________________________________
  TH1* One(TDirectory* newDir, TDirectory* oldDir, Double_t c1, Double_t c2)
  {
    TString name;
    name.Form("cent%03dd%02d_%03dd%02d",
	      Int_t(c1), Int_t(c1*100)%100,
	      Int_t(c2), Int_t(c2*100)%100);
    TDirectory* newSubDir = GetD(newDir, name);
    TDirectory* oldSubDir = GetD(oldDir, name);
    if (!newSubDir || !oldSubDir) return 0;
    Int_t newDim = 0;
    if      (TString(newDir->GetName()).Contains("etaipz")) newDim = 3;
    else if (TString(newDir->GetName()).Contains("eta"))    newDim = 2;
    else if (TString(newDir->GetName()).Contains("const"))  newDim = 1;
    Int_t oldDim = 0;
    if      (TString(oldDir->GetName()).Contains("etaipz")) oldDim = 3;
    else if (TString(oldDir->GetName()).Contains("eta"))    oldDim = 2;
    else if (TString(oldDir->GetName()).Contains("const"))  oldDim = 1;

    TDirectory* newSubSubDir = GetD(newSubDir, Form("results%dd",newDim));
    TDirectory* oldSubSubDir = GetD(oldSubDir, Form("results%dd",oldDim));
    if (!newSubSubDir || !oldSubSubDir) return 0;

    TH1* newRes = GetH1(newSubSubDir, "result");
    TH1* oldRes = GetH1(oldSubSubDir, "result");
    if (!newRes || !oldRes) return 0;

    TH1* ratio = static_cast<TH1*>(newRes->Clone(name));
    ratio->SetDirectory(0);
    ratio->SetTitle(Form("%5.1f - %5.1f%%", c1, c2));
    ratio->SetYTitle("New / Old");
    ratio->Divide(oldRes);
    fMin = TMath::Min(fMin, ratio->GetMinimum());
    fMax = TMath::Max(fMax, ratio->GetMaximum());

    Printf("Calculated %s/%s", newDir->GetName(), oldDir->GetName());
    if (!fLegend) return ratio;

    
    TLegendEntry* e =
      fLegend->AddEntry("", Form("%3.0f - %3.0f%%", c1, c2), "f");
    e->SetFillStyle(1001);
    e->SetFillColor(ratio->GetMarkerColor());
  
    return ratio;
  }
Пример #4
0
void plotter::draw_delta_rel(TH1* hist_, TH1* result_, TString file_name){
  TH1* hist = (TH1*) hist_->Clone("hist");
  TH1* result = (TH1*) result_->Clone("result");
  hist->Divide(result);
  hist->Scale(100);
  TCanvas *c= new TCanvas("Particle Level","",600,600);
  gPad->SetLeftMargin(0.15);
  hist->SetTitle(file_name);
  hist->GetXaxis()->SetTitle("Leading-jet mass [GeV]");
  hist->GetYaxis()->SetTitle("relative uncertainty [%]");
  hist->GetYaxis()->SetTitleOffset(1.5);
  hist->GetYaxis()->SetNdivisions(505);
  hist->SetFillColor(810);
  hist->SetLineColor(810);
  hist->Draw("HIST");
  gPad->RedrawAxis();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
Пример #5
0
TH1* compRatioHistogram(const std::string& ratioHistogramName, const TH1* numerator, const TH1* denominator)
{
  TH1* histogramRatio = 0;
  
  if ( numerator->GetDimension() == denominator->GetDimension() &&
       numerator->GetNbinsX() == denominator->GetNbinsX() ) {
    histogramRatio = (TH1*)numerator->Clone(ratioHistogramName.data());
    histogramRatio->Divide(denominator);
    
    int nBins = histogramRatio->GetNbinsX();
    for ( int iBin = 1; iBin <= nBins; ++iBin ){
      double binContent = histogramRatio->GetBinContent(iBin);
      histogramRatio->SetBinContent(iBin, binContent - 1.);
    }
    
    histogramRatio->SetLineColor(numerator->GetLineColor());
    histogramRatio->SetLineWidth(numerator->GetLineWidth());
    histogramRatio->SetMarkerColor(numerator->GetMarkerColor());
    histogramRatio->SetMarkerStyle(numerator->GetMarkerStyle());
    histogramRatio->SetMarkerSize(numerator->GetMarkerSize());
  }

  return histogramRatio;
}
Пример #6
0
void playsmoothiter(const Char_t *datatag, const Char_t *mctag, const Char_t *anatag, Int_t bin, Bool_t ismc = kFALSE)
{

  TCanvas *c = new TCanvas("cs", "cs");
  c->DrawFrame(0., 0.5, 100., 1.5);

  TH1 *href = UnfoldMe_TAG(datatag, mctag, anatag, bin, kTRUE, kFALSE, ismc, 1., 4);
  TH1 *hout = NULL;
  TH1 *heff_ev = new TH1F("heff_ev", "", 12, 0, 12);
  TH1 *heff_ch = new TH1F("heff_ch", "", 12, 0, 12);
  for (Int_t j = 2; j < 10; j+=2) {
  for (Int_t i = 5; i < 16; i+=2) {
    printf("%d %d\n", j, i);
    hout = UnfoldMe_TAG(datatag, mctag, anatag, bin, kTRUE, kFALSE, ismc, 0.1 * i, j);
    heff_ev->Fill(integr_eff);
    heff_ch->Fill(dndeta_eff);

    hout->Divide(href);
    c->cd();
    hout->Draw("same");
    c->Update();
  }}

}
Пример #7
0
void DrawTwoInPad(TVirtualPad* p,
                  Int_t        sub,
                  TH1*         h1,
                  TH1*         h2,
		  Bool_t       ratio,
		  Bool_t       logy=false,
		  Bool_t       legend=false)
{
  TVirtualPad* pp = p->cd(sub);
  pp->SetRightMargin(0.02);
  pp->SetLeftMargin(0.10);
  TVirtualPad* ppp = pp;
  if (ratio) {
    pp->Divide(1,2,0,0);
    ppp = pp->cd(1);				
    ppp->SetRightMargin(0.02);
  }
  if (logy) ppp->SetLogy();
  TH1* hs[] = { h1, h2, 0 };
  if (h1->GetMaximum() < h2->GetMaximum()) {
    hs[0] = h2;
    hs[1] = h1;
  }
  TH1** ph = hs;
  Double_t size = (ratio ? 0.1 : 0.05);
  Double_t off  = (ratio ? 0.6 : 0.5);
  h1->SetFillStyle(3004);
  h2->SetFillStyle(3005);
  while (*ph) {
    TString opt("hist");
    if (ph != hs) opt.Append(" same");

    TH1* copy = (*ph)->DrawCopy(opt);
    copy->GetXaxis()->SetLabelSize(2*size);
    copy->GetYaxis()->SetLabelSize(size);
    copy->GetYaxis()->SetTitleSize(size);
    copy->GetYaxis()->SetTitleOffset(off);
    copy->SetYTitle(copy->GetTitle());
    copy->SetTitle("");
    copy->SetDirectory(0);
    ph++;
  }
  TString s1 = h1->GetYaxis()->GetTitle();
  TString s2 = h2->GetYaxis()->GetTitle();
  
  if (legend) { 
    TLegend* l = new TLegend(0.6, 0.1, 0.9, 0.9);
    l->SetBorderSize(0);
    TLegendEntry* e = l->AddEntry("dummy", s1, "lf");
    l->SetFillColor(kWhite);
    e->SetFillColor(kBlack);
    e->SetFillStyle(h1->GetFillStyle());
    e = l->AddEntry("dummy", s2, "lf");
    e->SetFillColor(kBlack);
    e->SetFillStyle(h2->GetFillStyle());
    l->Draw();
  }
  if (!ratio) return;
  ppp = pp->cd(2);
  ppp->SetRightMargin(0.02);
  TH1* r = static_cast<TH1*>(h1->Clone(Form("ratio%s", h1->GetName())));
  r->SetDirectory(0);
  r->SetTitle("");
  r->GetXaxis()->SetLabelSize(size);
  r->GetYaxis()->SetLabelSize(size);
  r->GetYaxis()->SetTitleSize(0.9*size);
  r->GetYaxis()->SetTitleOffset(0.9*off);
  r->SetMarkerStyle(20);
  r->SetMarkerColor(h1->GetFillColor()+1);
  r->SetFillStyle(3007);
  r->SetYTitle(Form("#frac{%s}{%s}", s1.Data(), s2.Data()));

  // r->Add(h2, -1);
  // r->Divide(h1);
  if (!r->IsA()->InheritsFrom(TProfile::Class())) {
    r->GetSumw2()->Set(0); // r->Sumw2(false);
    h2->GetSumw2()->Set(0); // h2->Sumw2(false);
  }
  r->Divide(h2);
  Printf("%s", r->GetName());
  for (UShort_t bin = 1; bin <= r->GetNbinsX(); bin++) {
    Printf("  bin # %2d: Diff=%g+/-%g", bin, r->GetBinContent(bin),
	   r->GetBinError(bin));
    r->SetBinError(bin, 0);
  }
  r->GetSumw2()->Set(0); //r->Sumw2(false);
  r->SetMarkerSize(4);
  r->SetMaximum(r->GetMaximum()*1.2);
  r->SetMinimum(r->GetMinimum()*0.8);
  r->Draw("hist text30");  
  p->Modified();
  p->Update();
  p->cd();
}
Пример #8
0
TH1 *
UnfoldMe_MB2(const Char_t *data, const Char_t *mc, const Char_t *anatag, Int_t bin, Bool_t useMBcorr , Bool_t usecorrfit , Bool_t ismc , Float_t smooth , Int_t iter , Int_t regul , Float_t weight , Bool_t bayesian , Int_t nloop )
{

  // MF comments:
  // usedMBcorr: changes the matrix used for unfonding, from effMatrix to bin matrix (I think this is just to use mult dependent v s mb correction_)
  // usecorrfit: if I understand correctly, fits the response matrix and uses fit to extrapolate it

  
  TFile *fdt =0;
  if (ismc)
    fdt =  TFile::Open(data);
  else
    fdt = TFile::Open(data);
  TFile *fmc = TFile::Open(mc);

  TList *ldt = (TList *)fdt->Get(Form("%s", anatag));
  TList *lmc = (TList *)fmc->Get(Form("%s", anatag));
  
  TH2 *hmatdt = (TH2 *)ldt->FindObject(Form(responseMatrix, bin));
  TH2 *hmatmc = 0;
  if (useMBcorr){
     hmatmc = (TH2 *)lmc->FindObject("effMatrix");
     std::cout << "USING MB" << std::endl;
     
  }
  else {
    hmatmc = (TH2 *)lmc->FindObject(Form(responseMatrix, bin));
  }

  TH1 *hdata = hmatdt->ProjectionY("hdata");
//  TH1 *hdata = hmatdt->ProjectionY("htrue");  // For truth Only Calculations

  hdata->Sumw2();
  hdata->SetBinContent(1, 0.);
  hdata->SetBinError(1, 0.);
  //  hdata->Scale(1. / hdata->Integral());
  hdata->SetMarkerStyle(25);
  TH1 *htrue = hmatdt->ProjectionX("htrue");
  htrue->Sumw2();
  //  htrue->Scale(1. / htrue->Integral());
  htrue->SetMarkerStyle(7);
  htrue->SetMarkerColor(2);
  htrue->SetBinContent(1, 0.);
  htrue->SetBinError(1, 0.);

  TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr");
  TH1 *hinit = (TH1 *)hdata->Clone("hinit");
  TH1 *hresu = (TH1 *)hdata->Clone("hresu");
  TH1 *hbias = (TH1 *)hdata->Clone("hbias");
  hresu->SetMarkerStyle(20);
  hresu->SetMarkerColor(4);
  hresu->Reset();

  TH1 *hnum = hcorr->ProjectionY("hnum");
  TH1 *hden = hcorr->ProjectionY("hden");
  TH1 *heff = hcorr->ProjectionY("heff");
  hnum->Reset();
  hnum->Sumw2();
  hden->Reset();
  hden->Sumw2();
  heff->Reset();
  for (Int_t i = 0; i < heff->GetNbinsX(); i++) {
    Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1);
    if (int1 <= 0.) continue;
    Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1);
    hnum->SetBinContent(i + 1, int2);
    hnum->SetBinError(i + 1, TMath::Sqrt(int2));
    hden->SetBinContent(i + 1, int1);
    hden->SetBinError(i + 1, TMath::Sqrt(int1));
  }
  TCanvas *cEfficiency = new TCanvas("cEfficiency", "cEfficiency");
  cEfficiency->SetLogx();
  cEfficiency->SetLogy();

  heff->Divide(hnum, hden, 1., 1., "B");
  heff->Draw();
#if 0
  for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) {
    heff->SetBinContent(ii + 1, 1.);
    heff->SetBinError(ii + 1, 0.);
  }
#endif

  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    hcorr->SetBinContent(i + 1, 1, 0.);
    hcorr->SetBinError(i + 1, 1, 0.);
  }
  for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) {
    hcorr->SetBinContent(1, i + 1, 0.);
    hcorr->SetBinError(1, i + 1, 0.);
  }
  TH2 *hcorrfit = ReturnCorrFromFit(hcorr);
  // Docs from AliUnfolding
  //Int_t AliUnfolding::Unfold(TH2* correlation, TH1* efficiency, TH1* measured, TH1* initialConditions, TH1* result, Bool_t check)
  // unfolds with unfolding method fgMethodType
  //
  // parameters:
  //  correlation: response matrix as measured vs. generated
  //  efficiency:  (optional) efficiency that is applied on the unfolded spectrum, i.e. it has to be in unfolded variables. If 0 no efficiency is applied.
  //  measured:    the measured spectrum
  //  initialConditions: (optional) initial conditions for the unfolding. if 0 the measured spectrum is used as initial conditions.
  //  result:      target for the unfolded result
  //  check:       depends on the unfolding method, see comments in specific functions

  for (Int_t iloop = 0; iloop < nloop; iloop++) {
    if (bayesian) {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian);
      AliUnfolding::SetBayesianParameters(smooth, iter);
    } else {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization);
      AliUnfolding::SetChi2Regularization(AliUnfolding::RegularizationType(regul), weight);
    }
    AliUnfolding::SetSkip0BinInChi2(kTRUE);
    AliUnfolding::SetSkipBinsBegin(1);
    AliUnfolding::SetNbins(150, 150);
    AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu);
    hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop));
  }

  printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1));
  printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1));


  TCanvas *cUnfolded = new TCanvas ("cUnfolded", "cUnfolded", 400, 800);
  cUnfolded->Divide(1, 2);
  cUnfolded->cd(1)->SetLogx();
  cUnfolded->cd(1)->SetLogy();
  hdata->Draw();
  hresu->Draw("same");
  htrue->Draw("same");
  cUnfolded->cd(2)->SetLogx();
  cUnfolded->cd(2)->DrawFrame(1., 0, 300., 10);
  TH1 *hrat = (TH1 *)hresu->Clone("hrat");
  hrat->Divide(htrue);
  hrat->Draw("same");

  TH1 *htrig = (TH1 *)hresu->Clone("htrig");
  htrig->Multiply(heff); 
  

  Float_t dndeta_resu = 0.;
  Float_t integr_resu = 0.;
  Float_t dndeta_trig = 0.;
  Float_t integr_trig = 0.;
  for (Int_t i = 1; i < hresu->GetNbinsX(); i++) {
    dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1);
    integr_resu += hresu->GetBinContent(i + 1);
    dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1);
    integr_trig += htrig->GetBinContent(i + 1);
  }

  cUnfolded->SaveAs("unfold_efficiency.pdf");

  integr_eff = integr_trig / integr_resu;
  integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu);
  dndeta_eff = dndeta_trig / dndeta_resu;
  dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu);

  printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err);
  printf("dN/dEta correction:  %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err);

  return hresu;
}
Пример #9
0
TH1 *
UnfoldMe(Char_t *data, Char_t *mc, Char_t *anatag, Int_t bin, Bool_t useMBcorr = kTRUE, Bool_t usecorrfit = kFALSE, Bool_t ismc = kFALSE, Float_t smooth = 0.001, Int_t iter = 50, Int_t regul = AliUnfolding::kPowerLaw, Float_t weight = 100., Bool_t bayesian = kTRUE, Int_t nloop = 1)
{

  if (ismc)
    TFile *fdt = TFile::Open(data);
  else
    TFile *fdt = TFile::Open(data);
  TFile *fmc = TFile::Open(mc);
  
  TList *ldt = (TList *)fdt->Get(Form("clist_%s", anatag));
  TList *lmc = (TList *)fmc->Get(Form("clist_%s", anatag));
  
  TH2 *hmatdt = (TH2 *)ldt->FindObject(Form("b%d_corrMatrix", bin));
  if (useMBcorr)
    TH2 *hmatmc = (TH2 *)lmc->FindObject("effMatrix");
  else
    TH2 *hmatmc = (TH2 *)lmc->FindObject(Form("b%d_corrMatrix", bin));
 
  TH1 *hdata = hmatdt->ProjectionY("hdata");
  hdata->Sumw2();
  hdata->SetBinContent(1, 0.);
  hdata->SetBinError(1, 0.);
  //  hdata->Scale(1. / hdata->Integral());
  hdata->SetMarkerStyle(25);
  TH1 *htrue = hmatdt->ProjectionX("htrue");
  htrue->Sumw2();
  //  htrue->Scale(1. / htrue->Integral());
  htrue->SetMarkerStyle(7);
  htrue->SetMarkerColor(2);
  htrue->SetBinContent(1, 0.);
  htrue->SetBinError(1, 0.);
  TH2 *hcorr = (TH2 *)hmatmc->Clone("hcorr");
  TH1 *hinit = (TH1 *)hdata->Clone("hinit");
  TH1 *hresu = (TH1 *)hdata->Clone("hresu");
  TH1 *hbias = (TH1 *)hdata->Clone("hbias");
  hresu->SetMarkerStyle(20);
  hresu->SetMarkerColor(4);
  hresu->Reset();

  TH1 *hnum = hcorr->ProjectionY("hnum");
  TH1 *hden = hcorr->ProjectionY("hden");
  TH1 *heff = hcorr->ProjectionY("heff");
  hnum->Reset();
  hnum->Sumw2();
  hden->Reset();
  hden->Sumw2();
  heff->Reset();
  for (Int_t i = 0; i < heff->GetNbinsX(); i++) {
    Float_t int1 = hcorr->Integral(i + 1, i + 1, 0, -1);
    if (int1 <= 0.) continue;
    Float_t int2 = hcorr->Integral(i + 1, i + 1, 2, -1);
    hnum->SetBinContent(i + 1, int2);
    hnum->SetBinError(i + 1, TMath::Sqrt(int2));
    hden->SetBinContent(i + 1, int1);
    hden->SetBinError(i + 1, TMath::Sqrt(int1));
  }
  new TCanvas("cEfficiency");
  heff->Divide(hnum, hden, 1., 1., "B");
  heff->Draw();
#if 0
  for (Int_t ii = 0; ii < heff->GetNbinsX(); ii++) {
    heff->SetBinContent(ii + 1, 1.);
    heff->SetBinError(ii + 1, 0.);
  }
#endif
  
  for (Int_t i = 0; i < hcorr->GetNbinsX(); i++) {
    hcorr->SetBinContent(i + 1, 1, 0.);
    hcorr->SetBinError(i + 1, 1, 0.);
  }
  for (Int_t i = 0; i < hcorr->GetNbinsY(); i++) {
    hcorr->SetBinContent(1, i + 1, 0.);
    hcorr->SetBinError(1, i + 1, 0.);
  }
  TH2 *hcorrfit = ReturnCorrFromFit(hcorr);

  for (Int_t iloop = 0; iloop < nloop; iloop++) {
    if (bayesian) {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kBayesian);
      AliUnfolding::SetBayesianParameters(smooth, iter);
    } else {
      AliUnfolding::SetUnfoldingMethod(AliUnfolding::kChi2Minimization);
      AliUnfolding::SetChi2Regularization(regul, weight);
    }
    AliUnfolding::SetSkip0BinInChi2(kTRUE);
    AliUnfolding::SetSkipBinsBegin(1);
    AliUnfolding::SetNbins(150, 150);
    AliUnfolding::Unfold(usecorrfit ? hcorrfit : hcorr, heff, hdata, hinit, hresu);
    hinit = (TH1 *)hresu->Clone(Form("hinit_%d", iloop));
  }

  printf("hdata->Integral(2, -1) = %f\n", hdata->Integral(2, -1));
  printf("hresu->Integral(2, -1) = %f\n", hresu->Integral(2, -1));
  
  
  TCanvas *cUnfolded = new TCanvas ("cUnfolded", "", 400, 800);
  cUnfolded->Divide(1, 2);
  cUnfolded->cd(1)->SetLogx();
  cUnfolded->cd(1)->SetLogy();
  hdata->Draw();
  hresu->Draw("same");
  htrue->Draw("same");
  cUnfolded->cd(2)->SetLogx();
  cUnfolded->cd(2)->DrawFrame(1., 0.75, 300., 1.25);
  TH1 *hrat = (TH1 *)hresu->Clone("hrat");
  hrat->Divide(htrue);
  hrat->Draw("same");

  TH1 *htrig = (TH1 *)hresu->Clone("htrig");
  htrig->Multiply(heff);

  Float_t dndeta_resu = 0.;
  Float_t integr_resu = 0.;
  Float_t dndeta_trig = 0.;
  Float_t integr_trig = 0.;
  for (Int_t i = 1; i < hresu->GetNbinsX(); i++) {
    dndeta_resu += hresu->GetBinContent(i + 1) * hresu->GetBinLowEdge(i + 1);
    integr_resu += hresu->GetBinContent(i + 1);
    dndeta_trig += htrig->GetBinContent(i + 1) * htrig->GetBinLowEdge(i + 1);
    integr_trig += htrig->GetBinContent(i + 1);
  }
  //  dndeta_resu /= integr_resu;
  //  dndeta_trig /= integr_trig;

  integr_eff = integr_trig / integr_resu;
  integr_eff_err = TMath::Sqrt(integr_eff * (1. - integr_eff) / integr_resu);
  dndeta_eff = dndeta_trig / dndeta_resu;
  dndeta_eff_err = TMath::Sqrt(dndeta_eff * (1. - dndeta_eff) / dndeta_resu);
  
  printf("INEL > 0 efficiency: %.3f +- %.3f\n", integr_eff, integr_eff_err);
  printf("dN/dEta correction:  %.3f +- %.3f\n", dndeta_eff, dndeta_eff_err);

  return hresu;
}
Пример #10
0
void QAtracklets(const Char_t *fdata, const Char_t *fmc)
{

  style();
  
  TFile *fdtin = TFile::Open(fdata);
  TList *ldtin = (TList *)fdtin->Get("clist");
  TH2 *hdtin = (TH2 *)ldtin->FindObject("etaphiTracklets");
  TH1 *pdtin = (TH1 *)hdtin->ProjectionY("pdtin_tracklets");
  pdtin->SetMarkerStyle(20);
  pdtin->SetMarkerSize(1.);
  pdtin->SetMarkerColor(kAzure-3);
  hdtin->Scale(1. / hdtin->GetEntries());
  pdtin->Scale(1. / hdtin->GetEntries());
  
  TFile *fmcin = TFile::Open(fmc);
  TList *lmcin = (TList *)fmcin->Get("clist");

  if(!lmcin) {
      std::cout << "NOLIST" << std::endl;

  }
  lmcin->ls();
  TH2 *hmcin = (TH2 *)lmcin->FindObject("etaphiTracklets");
  if(!hmcin) {
    std::cout << "NO H!! etaphiTracklets" << std::endl;
    
  }
  TH1 *pmcin = (TH1 *)hmcin->ProjectionY("pmcin_tracklets");
  pmcin->SetLineColor(kRed+1);
  pmcin->SetFillStyle(1001);
  pmcin->SetFillColorAlpha(kRed+1, 0.1);
  hmcin->Scale(1. / hmcin->GetEntries());
  pmcin->Scale(1. / hmcin->GetEntries());
  

  /*  
  pdtin->Scale(pmcin->Integral(pmcin->FindBin(0. + 0.001),
			       pmcin->FindBin(1. - 0.001))
	       / pdtin->Integral(pdtin->FindBin(0. + 0.001),
				 pdtin->FindBin(1. - 0.001)));
  */  
  
  TCanvas *cData = new TCanvas("cTrackletData", "cTrackletData", 800, 800);
  //  cData->SetLogz();
  TH1 * hfr = cData->DrawFrame(-2.5, 0., 2.5, 2. * TMath::Pi());
  hfr->SetTitle(";#eta;#varphi");
  hdtin->Draw("same,col");
  cData->SaveAs(canvasPrefix+"trackletData.pdf");

  TCanvas *cMC = new TCanvas("cTrackletMC", "cTrackletMC", 800, 800);
  //  cMC->SetLogz();
  hfr = cMC->DrawFrame(-2.5, 0., 2.5, 2. * TMath::Pi());
  hfr->SetTitle(";#eta;#varphi");
  hmcin->Draw("same,col");
  cMC->SaveAs(canvasPrefix+"trackletMC.pdf");
  
  TCanvas *cPhi = new TCanvas("cTrackletPhi", "cTrackletPhi", 800, 800);
  //  cPhi->SetLogy();
  hfr = cPhi->DrawFrame(0., 0., 2. * TMath::Pi(), 0.01);
  hfr->SetTitle(";#varphi;");
  pdtin->DrawCopy("same");
  pmcin->DrawCopy("same,histo");
  TLegend *legend = new TLegend(0.20, 0.18+0.63, 0.50, 0.30+0.63);
  legend->SetFillColor(0);
  legend->SetBorderSize(0);
  legend->SetTextFont(42);
  legend->SetTextSize(0.04);
  legend->AddEntry(pdtin, "data", "pl");
  legend->AddEntry(pmcin, "Monte Carlo", "l");
  legend->Draw("same");
  cPhi->SaveAs(canvasPrefix+"trackletPhi.pdf");
  
  TCanvas *cPhir = new TCanvas("cTrackletPhir", "cTrackletPhir", 800, 800);
  //  cPhi->SetLogy();
  hfr = cPhir->DrawFrame(0., 0.5, 2. * TMath::Pi(), 1.5);
  hfr->SetTitle(";#varphi;data / Monte Carlo");
  pdtin->Divide(pmcin);
  pdtin->Draw("same");
  cPhir->SaveAs(canvasPrefix+"trackletPhir.pdf");

  
  
}
void makePlot(TCanvas* canvas, const std::string& outputFileName, TTree* testTree, const std::string& varName, 
	      unsigned numBinsX, double xMin, double xMax)
{
  std::cout << "creating histogramTauIdPassed..." << std::endl;
  TString histogramTauIdPassedName = TString("histogramTauIdPassed").Append("_").Append(varName.data());
  TH1* histogramTauIdPassed = fillHistogram(testTree, varName, "type==1", "",
					    histogramTauIdPassedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdPassed = " << histogramTauIdPassed << ":" 
	    << " integral = " << histogramTauIdPassed->Integral() << std::endl;

  std::cout << "creating histogramTauIdFailed..." << std::endl;
  TString histogramTauIdFailedName = TString("histogramTauIdFailed").Append("_").Append(varName.data());
  TH1* histogramTauIdFailed = fillHistogram(testTree, varName, "type==0", "",
					    histogramTauIdFailedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdFailed = " << histogramTauIdFailed 
	    << " integral = " << histogramTauIdFailed->Integral() << std::endl;

  std::cout << "creating histogramTauIdDenominator..." << std::endl;
  TString histogramTauIdDenominatorName = TString("histogramTauIdDenominator").Append("_").Append(varName.data());
  TH1* histogramTauIdDenominator = new TH1F(histogramTauIdDenominatorName.Data(), 
					    histogramTauIdDenominatorName.Data(), numBinsX, xMin, xMax);
  histogramTauIdDenominator->Add(histogramTauIdPassed);
  histogramTauIdDenominator->Add(histogramTauIdFailed);
  std::cout << "--> histogramTauIdDenominator = " << histogramTauIdDenominator 
	    << " integral = " << histogramTauIdDenominator->Integral() << std::endl;

  std::cout << "creating histogramFakeRate..." << std::endl;
  TString histogramFakeRateName = TString("histogramFakeRate").Append("_").Append(varName.data());
  TH1* histogramFakeRate = new TH1F(histogramFakeRateName.Data(), 
				    histogramFakeRateName.Data(), numBinsX, xMin, xMax);
  histogramFakeRate->Add(histogramTauIdPassed);
  histogramFakeRate->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRate = " << histogramFakeRate 
	    << " integral = " << histogramFakeRate->Integral() << std::endl;

  std::cout << "creating histogramFakeRateWeighted..." << std::endl;
  TString histogramFakeRateWeightedName = TString("histogramFakeRateWeighted").Append("_").Append(varName.data());
  TH1* histogramFakeRateWeighted = fillHistogram(testTree, varName, "", "MVA_KNN", 
						 histogramFakeRateWeightedName.Data(), numBinsX, xMin, xMax);
  histogramFakeRateWeighted->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRateWeighted = " << histogramFakeRateWeighted 
	    << " entries = " << histogramFakeRateWeighted->GetEntries() << ","
	    << " integral = " << histogramFakeRateWeighted->Integral() << std::endl;
  // Scale the weighted fake rate histogram

  histogramFakeRate->SetTitle(varName.data());
  histogramFakeRate->SetStats(false);
  histogramFakeRate->SetMinimum(1.e-4);
  histogramFakeRate->SetMaximum(1.e+1);
  histogramFakeRate->SetLineColor(2);
  histogramFakeRate->SetLineWidth(2);
  histogramFakeRate->SetMarkerStyle(20);
  histogramFakeRate->SetMarkerColor(2);
  histogramFakeRate->SetMarkerSize(1);
  histogramFakeRate->Draw("e1p");

  histogramFakeRateWeighted->SetLineColor(4);
  histogramFakeRateWeighted->SetLineWidth(2);
  histogramFakeRateWeighted->SetMarkerStyle(24);
  histogramFakeRateWeighted->SetMarkerColor(4);
  histogramFakeRateWeighted->SetMarkerSize(1);
  histogramFakeRateWeighted->Draw("e1psame");

  TLegend legend(0.11, 0.73, 0.31, 0.89);
  legend.SetBorderSize(0);
  legend.SetFillColor(0);
  legend.AddEntry(histogramFakeRate, "Tau id. discr.", "p");
  legend.AddEntry(histogramFakeRateWeighted, "Fake-Rate weight", "p");
  legend.Draw();

  canvas->Update();
  canvas->Print(outputFileName.data());
}
Пример #12
0
  int main(int argc, char *argv[]){
    /////////////////////////////////////
    if (argc != 6)
    {
      std::cout << "Please enter something like: ./run \"filelist_WJets_PU20bx25_100_200.txt\" \"WJets_PU20bx25_100_200\" \"Results\" \"00\" \"0\" " << std::endl;
      return EXIT_FAILURE;
    }
    //get the inputs from user
    const string InRootList = argv[1];
    const string subSampleKey = argv[2];
    const string Outdir = argv[3];
    const string inputnumber = argv[4];
    const string verbosity = argv[5];
    //////////////////////////////////////
    int verbose = atoi(verbosity.c_str());

     //some varaibles
    char filenames[500];
    vector<string> filesVec;
    ifstream fin(InRootList.c_str());
    TChain *sample_AUX = new TChain("TreeMaker2/PreSelection");
    char tempname[200];
    char histname[200];
    const double deltaRMax = 0.1;
    const double deltaPtMax = 0.2;

    map<string,int> binMap = utils2::BinMap_NoB();
    int totNbins=binMap.size();
    map<string,int> binMap_mht_nj = utils2::BinMap_mht_nj();
    int totNbins_mht_nj=binMap_mht_nj.size();
    TH1* hAccAll = new TH1D("hAccAll","Acceptance -- All",totNbins_mht_nj,1,totNbins_mht_nj+1);
    TH1* hIsoRecoAll = new TH1D("hIsoRecoAll","Efficiency -- All",totNbins,1,totNbins+1);
    TH1* hAccPass = new TH1D("hAccPass","Acceptance -- Pass",totNbins_mht_nj,1,totNbins_mht_nj+1);
    TH1* hIsoRecoPass = new TH1D("hIsoRecoPass","Efficiency -- Pass",totNbins,1,totNbins+1);
    hAccAll->Sumw2();
    hIsoRecoAll->Sumw2();
    hAccPass->Sumw2();
    hIsoRecoPass->Sumw2();

    int TauResponse_nBins=4;
    vector<TH1*> vec_resp;
        TFile * resp_file = new TFile("TauHad/HadTau_TauResponseTemplates_TTbar_Elog195WithDirectionalTemplates.root","R");
    for(int i=0; i<TauResponse_nBins; i++){
      sprintf(histname,"hTauResp_%d",i);
      vec_resp.push_back( (TH1D*) resp_file->Get( histname )->Clone() );
    }

    ///read the file names from the .txt files and load them to a vector.
    while(fin.getline(filenames, 500) ){filesVec.push_back(filenames);}
    cout<< "\nProcessing " << subSampleKey << " ... " << endl;
    for(unsigned int in=0; in<filesVec.size(); in++){ sample_AUX->Add(filesVec.at(in).c_str()); }


    // --- Analyse the events --------------------------------------------
    Selection * sel = new Selection();
    Utils * utils = new Utils();

    // Interface to the event content
    Events * evt = new Events(sample_AUX, subSampleKey,verbose);

    // Loop over the events (tree entries)
    int eventN=0;
    while( evt->loadNext() ){
//      if(eventN>10000)break;
      eventN++;

      // Through out an event that contains HTjets with bad id
      if(evt->JetId()==0)continue;

//printf("\n@@@@@@@@@@@@@@@@@@@@@@@@@@  \n event: %d \n Njet: %d HT: %g MHT: %g dphi1: %g dphi2: %g dphi3: %g  \n ",eventN-1,evt->nJets(),evt->ht(),evt->mht(),evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3()); //Ahmad3

      // Apply the NJets baseline-cut
      if( !sel->Njet_4(evt->nJets()) ) continue;
      // Apply the HT and MHT baseline-cuts
      if( !sel->ht_500(evt->ht()) ) continue;
      if( !sel->mht_200(evt->mht()) ) continue;
      // Apply the delta-phi cuts
//      if( !sel->dphi(evt->nJets(),evt->minDeltaPhiN()) ) continue;
      if( !sel->dphi(evt->nJets(),evt->deltaPhi1(),evt->deltaPhi2(),evt->deltaPhi3(),evt->deltaPhi4()) ) continue;

      if(verbose!=0)printf("\n############ \n event: %d \n ",eventN-1);

      double genMuPt=0.;
      double genMuEta=-99.;
      double genMuPhi=-99.;
      int firstMuId=0;
      vector<TVector3> genMuonVec;
      TVector3 temp3vec;
      genMuonVec.clear();
      bool isMuon = false;

      for(int i=0; i< evt->GenMuPtVec_().size(); i++){
        if(evt->GenMuFromTauVec_()[i]==0){
          genMuPt = evt->GenMuPtVec_().at(i);
          genMuEta = evt->GenMuEtaVec_().at(i);
          genMuPhi = evt->GenMuPhiVec_().at(i);
          isMuon=true;
          temp3vec.SetPtEtaPhi(genMuPt,genMuEta,genMuPhi);
          genMuonVec.push_back(temp3vec);
        }
        
        if(verbose!=0){
          printf("Muon # %d, pt: %g, eta: %g, phi: %g \n ",i,genMuPt,genMuEta,genMuPhi);
        }

        break; // if more than one muon exist, pick the energetic one. 
      }

      // ask for exactly one muon
      if( evt->GenMuPtVec_().size() > 1 ) continue;

      if( !( isMuon ) ) continue;

      // recompute ht mht njet
      double scale;
      if(genMuPt >=20.)scale = utils->getRandom(genMuPt,vec_resp );
      else scale = utils->getRandom(20.,vec_resp );
      double simTauJetPt = scale * genMuPt;
      double simTauJetEta = genMuEta;
      double simTauJetPhi = genMuPhi;

        // 3Vec of muon and scaledMu
        TVector3 SimTauJet3Vec,NewTauJet3Vec,Muon3Vec;
        SimTauJet3Vec.SetPtEtaPhi(simTauJetPt,simTauJetEta,simTauJetPhi);
        Muon3Vec.SetPtEtaPhi(genMuPt,genMuEta,genMuPhi);

        // New ht and mht
        vector<TVector3> HT3JetVec,MHT3JetVec;
        HT3JetVec.clear();
        MHT3JetVec.clear();
        TVector3 temp3Vec;
        int slimJetIdx=-1;
        utils->findMatchedObject(slimJetIdx,genMuEta,genMuPhi,evt->slimJetPtVec_(),evt->slimJetEtaVec_(), evt->slimJetPhiVec_(),deltaRMax,verbose);
        // If there is no match, add the tau jet as a new one
        if(slimJetIdx==-1){
          NewTauJet3Vec=SimTauJet3Vec;
          if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<2.4)HT3JetVec.push_back(NewTauJet3Vec);
          if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<5.)MHT3JetVec.push_back(NewTauJet3Vec);
        }
        for(int i=0;i<evt->slimJetPtVec_().size();i++){
          if(i!=slimJetIdx){
            temp3Vec.SetPtEtaPhi(evt->slimJetPtVec_()[i],evt->slimJetEtaVec_()[i],evt->slimJetPhiVec_()[i]);
            if(evt->slimJetPtVec_()[i]>30. && fabs(evt->slimJetEtaVec_()[i])<2.4)HT3JetVec.push_back(temp3Vec);
            if(evt->slimJetPtVec_()[i]>30. && fabs(evt->slimJetEtaVec_()[i])<5.)MHT3JetVec.push_back(temp3Vec);
          }
          else if(i==slimJetIdx){
            temp3Vec.SetPtEtaPhi(evt->slimJetPtVec_()[i],evt->slimJetEtaVec_()[i],evt->slimJetPhiVec_()[i]);
            NewTauJet3Vec=temp3Vec-Muon3Vec+SimTauJet3Vec;
            if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<2.4)HT3JetVec.push_back(NewTauJet3Vec);
            if(NewTauJet3Vec.Pt()>30. && fabs(NewTauJet3Vec.Eta())<5.)MHT3JetVec.push_back(NewTauJet3Vec);
          }

        }

        // Order the HT3JetVec and MHT3JetVec based on their pT
        HT3JetVec = utils->Order_the_Vec(HT3JetVec);
        MHT3JetVec = utils->Order_the_Vec(MHT3JetVec);


        double newHT=0,newMHT=0,newMHTPhi=-1;
        TVector3 newMHT3Vec;
        for(int i=0;i<HT3JetVec.size();i++){
          newHT+=HT3JetVec[i].Pt();
        }
        for(int i=0;i<MHT3JetVec.size();i++){
          newMHT3Vec-=MHT3JetVec[i];
        }
        newMHT=newMHT3Vec.Pt();
        newMHTPhi=newMHT3Vec.Phi();

        //New #Jet
        int newNJet = HT3JetVec.size();
        if(verbose==1)printf("newNJet: %d \n ",newNJet);



      // Acceptance determination 1: Counter for all events
      // with muons at generator level
      hAccAll->Fill( binMap_mht_nj[utils2::findBin_mht_nj(evt->nJets(),evt->mht()).c_str()] );
//      hAccAll->Fill( binMap_mht_nj[utils2::findBin_mht_nj(newNJet,newMHT).c_str()] ); // this doesn't work good

      // Check if generator-level muon is in acceptance
      if( genMuPt > LeptonAcceptance::muonPtMin() && std::abs(genMuEta) < LeptonAcceptance::muonEtaMax() ) {
        if(verbose!=0)printf("Muon is in acceptance \n ");
        // Acceptance determination 2: Counter for only those events
        // with generator-level muons inside acceptance
        // hAccPass->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()] );
        hAccPass->Fill( binMap_mht_nj[utils2::findBin_mht_nj(evt->nJets(),evt->mht()).c_str()] );
//        hAccPass->Fill( binMap_mht_nj[utils2::findBin_mht_nj(newNJet,newMHT).c_str()] );

        // Reconstruction-efficiency determination 1: Counter for all events
        // with generator-level muons inside acceptance, regardless of whether
        // the muon has also been reconstructed or not.
        // hIsoRecoAll->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()]);
        hIsoRecoAll->Fill( binMap[utils2::findBin_NoB(evt->nJets(),evt->ht(),evt->mht()).c_str()]);

        // Check if the muon has been reconstructed: check if a reconstructed
        // muon is present in the event that matches the generator-level muon
        // Isolation-efficiency determination 1: Counter for all events with a
        // reconstructed muon that has a generator-level muon match inside the
        // the acceptance, regardless of whether the reconstructed muon is also
        // isolated or not.

//if( evt->MuPtVec_().size()>0 )printf(" RecoMu--> Pt: %g eta: %g phi: %g deltaRMax: %g ",evt->MuPtVec_()[0],evt->MuEtaVec_()[0],evt->MuPhiVec_()[0],deltaRMax); // Ahmad3
//else cout << " Muon size is 0 \n " ;
        // in R and in pt
        int matchedMuonIdx = -1;
        if(evt->MuPtVec_().size()>0 && utils->findMatchedObject(matchedMuonIdx,genMuEta,genMuPhi,evt->MuPtVec_(),evt->MuEtaVec_(),evt->MuPhiVec_(),deltaRMax,verbose) ) {
          // Muon is reconstructed
          const double relDeltaPtMu = std::abs(genMuPt - evt->MuPtVec_().at(matchedMuonIdx) ) / evt->MuPtVec_().at(matchedMuonIdx) ;
          if(verbose!=0)printf(" relDeltaPtMu: %g \n ",relDeltaPtMu);
          if( relDeltaPtMu < deltaPtMax ) {
            // and matches generated pt
            if(verbose!=0)printf("Muon is reconstructed \n ");
            // Check if the muon is also isolated: check if an isolated muon is present
            // in the event that matches the reconstructed muon in R
            if( /*muonsRelIso->at(matchedMuonIdx) <= Selection::muIso()*/ true ){
                //.................//.................//
                // Currently muons are picked if they are isolated.
                // So we don't need to put a cut here.     
                //.................//.................//
              // Muon is isolated
              if(verbose!=0)printf("Muon is isolated \n ");
              // Reconstruction-efficiency determination 2: Counter for those events
              // with generator-level muons inside acceptance where the muon has also
              // been reconstructed.
              // Isolation-efficiency determination 2: Counter for those events where
              // the muon is also isolated.
              // hIsoRecoPass->Fill( binMap[utils2::findBin(cntNJetsPt30Eta24,nbtag,HT,template_mht).c_str()] );
              hIsoRecoPass->Fill( binMap[utils2::findBin_NoB(evt->nJets(),evt->ht(),evt->mht()).c_str()] );
            } // End of muon is isolated
          } // End of pt matching
        } // End of reconstructed muon
      } // End of muon in acceptance



    } // end of loop over events


     // Compute acceptance
    TH1* hAcc = static_cast<TH1*>(hAccPass->Clone("hAcc"));
    hAcc->Divide(hAccPass,hAccAll,1,1,"B");// we use B option here because the two histograms are correlated. see TH1 page in the root manual.

    // Compute efficiencies
    TH1* hEff = static_cast<TH1*>(hIsoRecoPass->Clone("hEff"));
    hEff->Divide(hIsoRecoPass,hIsoRecoAll,1,1,"B");

    if(verbose!=0){
      for(int j=1; j<= totNbins; j++){
        printf("hAccAll: %g hAccPass: %g hAcc: %g hIsoRecoAll: %g hIsoRecoPass: %g hEff: %g \n ",hAccAll->GetBinContent(j),hAccPass->GetBinContent(j),hAcc->GetBinContent(j),hIsoRecoAll->GetBinContent(j),hIsoRecoPass->GetBinContent(j),hEff->GetBinContent(j));
      }
    }


    // --- Save the Histograms to File -----------------------------------
    sprintf(tempname,"LostLepton/LostLepton2_MuonEfficienciesFrom%s_%s.root",subSampleKey.c_str(),inputnumber.c_str());
    TFile outFile(tempname,"RECREATE");
    hAcc->Write();
    hEff->Write();
    hAccAll->Write();
    hAccPass->Write();
    hIsoRecoAll->Write();
    hIsoRecoPass->Write();
    outFile.Close();




  } // end of main
void makePlot(double canvasSizeX, double canvasSizeY,
	      TH1* histogramTTH, 
	      TH1* histogramData, 
	      TH1* histogramTT,
	      TH1* histogramTTV,
	      TH1* histogramEWK,
	      TH1* histogramRares,
	      TH1* histogramBgrSum,
	      TH1* histogramBgrUncertainty,		
	      const std::string& xAxisTitle, double xAxisOffset,
	      bool useLogScale, double yMin, double yMax, const std::string& yAxisTitle, double yAxisOffset,
	      const std::string& outputFileName)
{
  TH1* histogramTTH_density = 0;
  if ( histogramTTH ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTH, histogramData);
    histogramTTH_density = divideHistogramByBinWidth(histogramTTH);
  }
  TH1* histogramData_density = 0;
  if ( histogramData ) {
    histogramData_density = divideHistogramByBinWidth(histogramData);      
  }
  TH1* histogramTT_density = 0;
  if ( histogramTT ) {
    if ( histogramData ) checkCompatibleBinning(histogramTT, histogramData);
    histogramTT_density = divideHistogramByBinWidth(histogramTT);
  } 
  TH1* histogramTTV_density = 0;
  if ( histogramTTV ) {
    if ( histogramData ) checkCompatibleBinning(histogramTTV, histogramData);
    histogramTTV_density = divideHistogramByBinWidth(histogramTTV);
  }    
  TH1* histogramEWK_density = 0;
  if ( histogramEWK ) {
    if ( histogramData ) checkCompatibleBinning(histogramEWK, histogramData);
    histogramEWK_density = divideHistogramByBinWidth(histogramEWK);
  }
  TH1* histogramRares_density = 0;
  if ( histogramRares ) {
    if ( histogramData ) checkCompatibleBinning(histogramRares, histogramData);
    histogramRares_density = divideHistogramByBinWidth(histogramRares);
  }    
  TH1* histogramBgrSum_density = 0;
  if ( histogramBgrSum ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrSum, histogramData);
    histogramBgrSum_density = divideHistogramByBinWidth(histogramBgrSum); 
  }
  TH1* histogramBgrUncertainty_density = 0;
  if ( histogramBgrUncertainty ) {
    if ( histogramData ) checkCompatibleBinning(histogramBgrUncertainty, histogramData);
    histogramBgrUncertainty_density = divideHistogramByBinWidth(histogramBgrUncertainty);
  }
  
  TCanvas* canvas = new TCanvas("canvas", "", canvasSizeX, canvasSizeY);
  canvas->SetFillColor(10);
  canvas->SetFillStyle(4000);
  canvas->SetFillColor(10);
  canvas->SetTicky();
  canvas->SetBorderSize(2);  
  canvas->SetLeftMargin(0.12);
  canvas->SetBottomMargin(0.12);
  
  TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.35, 1.00, 1.00);
  topPad->SetFillColor(10);
  topPad->SetTopMargin(0.065);
  topPad->SetLeftMargin(0.15);
  topPad->SetBottomMargin(0.03);
  topPad->SetRightMargin(0.05);
  topPad->SetLogy(useLogScale);
  
  TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.00, 1.00, 0.35);
  bottomPad->SetFillColor(10);
  bottomPad->SetTopMargin(0.02);
  bottomPad->SetLeftMargin(0.15);
  bottomPad->SetBottomMargin(0.31);
  bottomPad->SetRightMargin(0.05);
  bottomPad->SetLogy(false);
  
  canvas->cd();
  topPad->Draw();
  topPad->cd();
  
  TAxis* xAxis_top = histogramData_density->GetXaxis();
  xAxis_top->SetTitle(xAxisTitle.data());
  xAxis_top->SetTitleOffset(xAxisOffset);
  xAxis_top->SetLabelColor(10);
  xAxis_top->SetTitleColor(10);
    
  TAxis* yAxis_top = histogramData_density->GetYaxis();
  yAxis_top->SetTitle(yAxisTitle.data());
  yAxis_top->SetTitleOffset(yAxisOffset);
  yAxis_top->SetTitleSize(0.085);
  yAxis_top->SetLabelSize(0.05);
  yAxis_top->SetTickLength(0.04);  
  
  TLegend* legend = new TLegend(0.66, 0.45, 0.94, 0.92, NULL, "brNDC");
  legend->SetFillStyle(0);
  legend->SetBorderSize(0);
  legend->SetFillColor(10);
  legend->SetTextSize(0.055);
  
  histogramData_density->SetTitle("");
  histogramData_density->SetStats(false);
  histogramData_density->SetMaximum(yMax);
  histogramData_density->SetMinimum(yMin);
  histogramData_density->SetMarkerStyle(20);
  histogramData_density->SetMarkerSize(2);
  histogramData_density->SetMarkerColor(kBlack);
  histogramData_density->SetLineColor(kBlack);
  legend->AddEntry(histogramData_density, "Observed", "p");    
  
  histogramData_density->Draw("ep");
  
  legend->AddEntry(histogramTTH_density, "t#bar{t}H", "l");

  histogramTT_density->SetTitle("");
  histogramTT_density->SetStats(false);
  histogramTT_density->SetMaximum(yMax);
  histogramTT_density->SetMinimum(yMin);
  histogramTT_density->SetFillColor(kMagenta - 10); 
  legend->AddEntry(histogramTT_density, "t#bar{t}+jets", "f");

  histogramTTV_density->SetFillColor(kOrange - 4);
  legend->AddEntry(histogramTTV_density, "t#bar{t}+V", "f");

  histogramEWK_density->SetFillColor(kRed + 2); 
  legend->AddEntry(histogramEWK_density, "EWK", "f");

  histogramRares_density->SetFillColor(kBlue - 8); 
  legend->AddEntry(histogramRares_density, "Rares", "f");

  THStack* histogramStack_density = new THStack("stack", "");
  histogramStack_density->Add(histogramRares_density);
  histogramStack_density->Add(histogramEWK_density);
  histogramStack_density->Add(histogramTTV_density);
  histogramStack_density->Add(histogramTT_density);
  histogramStack_density->Draw("histsame");
  
  histogramBgrUncertainty_density->SetFillColor(kBlack);
  histogramBgrUncertainty_density->SetFillStyle(3344);    
  histogramBgrUncertainty_density->Draw("e2same");
  legend->AddEntry(histogramBgrUncertainty_density, "Uncertainty", "f");

  histogramTTH_density->SetLineWidth(2);
  histogramTTH_density->SetLineStyle(1);
  histogramTTH_density->SetLineColor(kBlue);
  histogramTTH_density->Draw("histsame");
  
  histogramData_density->Draw("epsame");
  histogramData_density->Draw("axissame");
  
  legend->Draw();
  
  addLabel_CMS_luminosity(0.2050, 0.9225, 0.6850);
  
  canvas->cd();
  bottomPad->Draw();
  bottomPad->cd();
  
  TH1* histogramRatio = (TH1*)histogramData->Clone("histogramRatio");
  histogramRatio->Reset();
  if ( !histogramRatio->GetSumw2N() ) histogramRatio->Sumw2();
  checkCompatibleBinning(histogramRatio, histogramBgrSum);
  histogramRatio->Divide(histogramData, histogramBgrSum);
  int numBins_bottom = histogramRatio->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins_bottom; ++iBin ) {
    double binContent = histogramRatio->GetBinContent(iBin);
    if ( histogramData && histogramData->GetBinContent(iBin) >= 0. ) histogramRatio->SetBinContent(iBin, binContent - 1.0);
    else histogramRatio->SetBinContent(iBin, -10.);
  }
  histogramRatio->SetTitle("");
  histogramRatio->SetStats(false);
  histogramRatio->SetMinimum(-0.50);
  histogramRatio->SetMaximum(+0.50);
  histogramRatio->SetMarkerStyle(histogramData_density->GetMarkerStyle());
  histogramRatio->SetMarkerSize(histogramData_density->GetMarkerSize());
  histogramRatio->SetMarkerColor(histogramData_density->GetMarkerColor());
  histogramRatio->SetLineColor(histogramData_density->GetLineColor());
  histogramRatio->Draw("ep");
  
  TAxis* xAxis_bottom = histogramRatio->GetXaxis();
  xAxis_bottom->SetTitle(xAxis_top->GetTitle());
  xAxis_bottom->SetLabelColor(1);
  xAxis_bottom->SetTitleColor(1);
  xAxis_bottom->SetTitleOffset(1.20);
  xAxis_bottom->SetTitleSize(0.13);
  xAxis_bottom->SetLabelOffset(0.02);
  xAxis_bottom->SetLabelSize(0.10);
  xAxis_bottom->SetTickLength(0.055);
  
  TAxis* yAxis_bottom = histogramRatio->GetYaxis();
  yAxis_bottom->SetTitle("#frac{Data - Simulation}{Simulation}");
  yAxis_bottom->SetTitleOffset(0.80);
  yAxis_bottom->SetNdivisions(505);
  yAxis_bottom->CenterTitle();
  yAxis_bottom->SetTitleSize(0.09);
  yAxis_bottom->SetLabelSize(0.10);
  yAxis_bottom->SetTickLength(0.04);  
  
  TH1* histogramRatioUncertainty = (TH1*)histogramBgrUncertainty->Clone("histogramRatioUncertainty");
  if ( !histogramRatioUncertainty->GetSumw2N() ) histogramRatioUncertainty->Sumw2();
  checkCompatibleBinning(histogramRatioUncertainty, histogramBgrUncertainty);
  histogramRatioUncertainty->Divide(histogramBgrSum);
  int numBins = histogramRatioUncertainty->GetNbinsX();
  for ( int iBin = 1; iBin <= numBins; ++iBin ) {
    double binContent = histogramRatioUncertainty->GetBinContent(iBin);
    histogramRatioUncertainty->SetBinContent(iBin, binContent - 1.0);
  }
  histogramRatioUncertainty->SetFillColor(histogramBgrUncertainty_density->GetFillColor());
  //histogramRatioUncertainty->SetFillStyle(histogramBgrUncertainty_density->GetFillStyle());    
  histogramRatioUncertainty->SetFillStyle(3644);    
  
  TF1* line = new TF1("line","0", xAxis_bottom->GetXmin(), xAxis_bottom->GetXmax());
  line->SetLineStyle(3);
  line->SetLineWidth(1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  
  histogramRatioUncertainty->Draw("e2same");
  
  histogramRatio->Draw("epsame");
  
  canvas->Update();
  size_t idx = outputFileName.find(".");
  std::string outputFileName_plot(outputFileName, 0, idx);
  if ( useLogScale ) outputFileName_plot.append("_log");
  else outputFileName_plot.append("_linear");
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName, idx)).data());
  canvas->Print(std::string(outputFileName_plot).append(".png").data());
  canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  canvas->Print(std::string(outputFileName_plot).append(".root").data());
  
  delete histogramTTH_density;
  delete histogramData_density;
  delete histogramTT_density;
  delete histogramTTV_density;
  delete histogramEWK_density;
  delete histogramRares_density;
  delete histogramBgrSum_density;
  //delete histogramBgrUncertainty_density;
  delete histogramStack_density;
  delete legend;
  delete topPad;
  delete histogramRatio;
  delete histogramRatioUncertainty;
  delete line;
  delete bottomPad;    
  delete canvas;
}
Пример #14
0
// === Main Function ===================================================
void hadTau1(unsigned int id = 11, int nEvts = -1) {

  // --- Declare the Output Histograms ---------------------------------

  // The tau response templates
  // They are filled for different bins in generated tau-lepton pt.
  // The binning is encapsulated in ../Utils/TauResponse.h
  std::vector<TH1*> hTauResp(TauResponse::nBins());
  for(unsigned int i = 0; i < TauResponse::nBins(); ++i) {
    hTauResp.at(i) = new TH1D(TauResponse::name(i),";p_{T}(visible) / p_{T}(generated);Probability",50,0.,2.5);
    hTauResp.at(i)->Sumw2();
  }

  // Control histograms for the jet-tau matching efficiency
  TH1* hNJetAll = new TH1D("hNJetAll",";N(jets)",10,0,10);
  hNJetAll->Sumw2();
  TH1* hNJetPass = static_cast<TH1*>(hNJetAll->Clone("hNJetPass"));

  TH1* hHtAll = new TH1D("hHtAll",";H_{T} [GeV]",30,0,3000);
  hHtAll->Sumw2();
  TH1* hHtPass = static_cast<TH1*>(hHtAll->Clone("hHtPass"));

  TH1* hMhtAll = new TH1D("hMhtAll",";#slash{H}_{T} [GeV]",20,0,2000);
  hMhtAll->Sumw2();
  TH1* hMhtPass = static_cast<TH1*>(hMhtAll->Clone("hMhtPass"));



  // --- Analyse the events --------------------------------------------

  // Interface to the event content
  Event* evt = new Event(Sample::fileNameFullSample(id),nEvts);

  // Loop over the events (tree entries)
  while( evt->loadNext() ) {

    // Select only events where the W decayed into a hadronically
    // decaying tau
    if( !(evt->flgW() == 15 && evt->flgTau() == 1) ) continue;

    // Kinematic variables of generator-level tau
    const float genTauPt = evt->genLeptonPt();
    const float genTauEta = evt->genLeptonEta();
    const float genTauPhi = evt->genLeptonPhi();

    // Use only events where the tau is inside the muon acceptance
    // because lateron we will apply the response to muon+jet events
    if( genTauPt < TauResponse::ptMin() ) continue;
    if( std::abs(genTauEta) > TauResponse::etaMax() ) continue;


    // "Cross cleaning": find the jet that originates in the
    // hadronic tau-decay. Associate the jet that is closest in
    // deltaR to the tau. The distance has to be smaller than deltaRMax.

    // First, fill counters before jet-tau matching
    hNJetAll->Fill(evt->nJets());
    hHtAll->Fill(evt->ht());
    hMhtAll->Fill(evt->mht());

    // Do the matching
    int tauJetIdx = -1;		// Will store the index of the jet matched to the tau
    const float deltaRMax = genTauPt < 50. ? 0.2 : 0.1; // Increase deltaRMax at low pt to maintain high-enought matching efficiency
    if( !utils::findMatchedObject(tauJetIdx,genTauEta,genTauPhi,evt->jetsEta(),evt->jetsPhi(),evt->jetsN(),deltaRMax) ) continue;

    // Then, fill counters after matching
    hNJetPass->Fill(evt->nJets());
    hHtPass->Fill(evt->ht());
    hMhtPass->Fill(evt->mht());


    // Calculate RA2 selection-variables from "cleaned" jets,
    // i.e. jets withouth the tau-jet
    int selNJet = 0; // Number of HT jets (jets pt > 50 GeV and |eta| < 2.5)

    for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
      // Skip this jet if it is the tau
      if( jetIdx == tauJetIdx ) continue;

      // Calculate NJet 
      if( evt->jetsPt()[jetIdx] > Selection::htJetPtMin() && std::abs(evt->jetsEta()[jetIdx]) < Selection::htJetEtaMax() ) selNJet++;
    } // End of loop over reco jets
    
    
    // Select only events with at least 2 HT jets
    if( selNJet < 2 ) continue;
    

    // Fill histogram with relative visible energy of the tau
    // ("tau response template") for hadronically decaying taus
    for(int jetIdx = 0; jetIdx < evt->jetsN(); ++jetIdx) {	// Loop over reco jets
      // Select tau jet
      if( jetIdx == tauJetIdx ) {
	// Get the response pt bin for the tau
	const unsigned int ptBin = TauResponse::ptBin(genTauPt);
	// Fill the corresponding response template
	const double tauJetPt = evt->jetsPt()[jetIdx];
	hTauResp.at(ptBin)->Fill( tauJetPt / genTauPt );
	break;		// End the jet loop once the tau jet has been found
      }
    }	// End of loop over reco jets
  } // End of loop over tree entries


  // Normalize the response distributions to get the probability density
  for(unsigned int i = 0; i < hTauResp.size(); ++i) {
    if( hTauResp.at(i)->Integral("width") > 0. ) {
      hTauResp.at(i)->Scale(1./hTauResp.at(i)->Integral("width"));
    }
  }

  // Get the jet-tau matching efficiency
  TH1* hMatchEffNJet = static_cast<TH1*>(hNJetPass->Clone("hMatchEffNJet"));
  hMatchEffNJet->Divide(hNJetAll);
  TH1* hMatchEffHt = static_cast<TH1*>(hHtPass->Clone("hMatchEffHt"));
  hMatchEffHt->Divide(hHtAll);
  TH1* hMatchEffMht = static_cast<TH1*>(hMhtPass->Clone("hMatchEffMht"));
  hMatchEffMht->Divide(hMhtAll);


  // --- Save the Histograms to File -----------------------------------
  TFile outFile("../data/HadTau_TauResponseTemplates.root","RECREATE");
  for(unsigned int i = 0; i < hTauResp.size(); ++i) {
    hTauResp.at(i)->Write();
  }
  hMatchEffNJet->Write();
  hMatchEffHt->Write();
  hMatchEffMht->Write();
  outFile.Close();
}
Пример #15
0
void makeMuEff(const string filename="") 
{
	if (filename.length()<1)
	{
		cout << "Need input root file!" << endl;
		return;
	}

	vector< pair<double,double> >  vJetBins, vHtBins;
	vJetBins.push_back(make_pair(2,2));
	vJetBins.push_back(make_pair(3,5));
	vJetBins.push_back(make_pair(6,7));
	vJetBins.push_back(make_pair(8,1000));
	vHtBins.push_back(make_pair(500,8000));

	TFile f(filename.c_str());
	if (f.IsZombie())
	{
		cout << "File with name " << filename << " cannot be opened or does not exist!" << endl;
		return;
	}

	const string numname("muEff_num");
	const string denname("muEff_den");

	TCanvas *c = new TCanvas();
	size_t dotpos = filename.find(".");
	string substr = filename.substr(0,dotpos);
	stringstream epsname_o, epsname, epsname_c;
	epsname_o << substr << ".eps[";
	epsname << substr << ".eps";
	epsname_c << substr << ".eps]";
	c->Print(epsname_o.str().c_str());
	gStyle->SetOptStat(0);
	gStyle->SetPaintTextFormat("1.1f");
	for (unsigned jetbin=0; jetbin < vJetBins.size(); ++jetbin)
	{
		double minjet= vJetBins.at(jetbin).first;
		double maxjet= vJetBins.at(jetbin).second;
		for (unsigned htbin=0; htbin < vHtBins.size(); ++htbin)
		{
			double minht= vHtBins.at(htbin).first;
			double maxht= vHtBins.at(htbin).second;
			stringstream folder, numhistname, denhistname;
			folder << "muoneff/Hist/Njet" << minjet << "to" << maxjet << "Ht" << minht << "to" << maxht << "/";
			numhistname << folder.str() << numname;
			denhistname << folder.str() << denname;
			TH1* numhist = dynamic_cast<TH1*>( f.Get(numhistname.str().c_str()));
			TH1* denhist = dynamic_cast<TH1*> (f.Get(denhistname.str().c_str()));

			if (numhist == NULL) 
			{
				cout << "Numerator hist " << numhistname.str() << " is not found in file " << f.GetName() << endl;
				return;
			}

			if (denhist == NULL) 
			{
				cout << "Denominator hist " << denhistname.str() << " is not found in file " << f.GetName() << endl;
				return;
			}
			numhist->Draw("colz");
			c->Print(epsname.str().c_str());
			denhist->Draw("colz");
			c->Print(epsname.str().c_str());
			numhist->Sumw2();
			numhist->Divide(denhist);
			stringstream title;
			title << "Jets " << minjet << "-" << maxjet << ", HT>" << minht <<  ": Muon Reco+ID efficiency from " << substr << endl;
			numhist->SetTitle(title.str().c_str());
			//numhist->GetXaxis()->SetRangeUser(0,500);
			numhist->SetAxisRange(0,500,"X");
			numhist->SetAxisRange(0,3.5,"Y");
			//numhist->GetYaxis()->SetRangeUser(0,3.5);
			numhist->Draw("colzTEXT90E");
			c->Print(epsname.str().c_str());
		}
	}
	c->Print(epsname_c.str().c_str());

}
Пример #16
0
int ratio5() {

  // Constants and arrays

  Int_t multi = 2;

  const Int_t n_at = 3;
  Int_t at[n_at] = { 500, 510, 550 };
  //for ( int ii = 0; ii < n_at; ++ii ) { at[ii] = 500 + ii * 10; }

  TString eq = "Gt";

  const Int_t n = 4;
  float pt[n]     = { 50., 40., 30., 20. };
  Int_t colour[n] = { 1, 2, 3, 4 };

  const Int_t m = 2;
  Int_t style[m]  = { kOpenSquare, kFullSquare };
  
  const Int_t ngr = 1000;
  double x3[ngr];
  double r[ngr];

  int count = 0;

  // General style

  gStyle->SetOptStat(0);
  
//   // Canvas for RECO curves 
//   TCanvas* reco_canvas = new TCanvas("Reco");
//   reco_canvas->SetFillColor(0);
//   reco_canvas->SetLineColor(0); 
//   reco_canvas->SetLogy();
//   TLegend* reco_legend = new TLegend( 0.5, 0.7, 0.88, 0.88, NULL, "brNDC" );
//   reco_legend->SetFillColor(0);
//   reco_legend->SetLineColor(0); 
//   bool empty = true;
//   double reco_max = 1.e-15.;
//   double reco_min = 1.e15;
  
  // Loop through pt bins

  for ( Int_t i = 0; i < 1; ++i ) {

    std::stringstream pt_can;
    pt_can << "PtBin" << pt[i];
    
    // Canvas for Pt bin
    TCanvas* pt_canvas = new TCanvas(TString(pt_can.str()),"");
    pt_canvas->SetFillColor(0);
    pt_canvas->SetLineColor(0); 
    pt_canvas->SetLogy();
    TLegend* pt_legend = new TLegend( 0.82, 0.5, 0.98, 0.9, NULL, "brNDC" );

    pt_legend->SetFillColor(0);
    pt_legend->SetLineColor(0); 
    bool empty = true;
    double pt_max = 1.e-15.;
    double pt_min = 1.e15;
    std::vector<TH1*> pt_ratio;

    pt_canvas->SetRightMargin(0.2);

    // Open files
    std::stringstream ss;
    ss << "results/4/Reco" << pt[i] << "_QCDPythia6.root";
    TString name(ss.str());
    TFile* file = new TFile(name);
    if ( file->IsZombie() || !(file->IsOpen()) ) { continue; }
    file->cd();
    
    // Loop through AlphaT thresolds
    for ( Int_t iat = 0; iat < n_at; ++iat ) {
    
      // Loop through RECO and GEN
      for ( Int_t j = 0; j < m; ++j ) {
	
	// Define names of histos to open 
	std::stringstream pre;
	std::stringstream post;
	if ( j == 0 ) {
	  pre << "Ratio" << at[iat] << "/GenHt" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/GenHt" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	} else if ( j == 1 ) {
	  pre << "Ratio" << at[iat] << "/Ht" << eq << "PreAlphaT" << at[iat] << "_" << multi;
	  post << "Ratio" << at[iat] << "/Ht" << eq << "PostAlphaT" << at[iat] << "_" << multi;
	  std::cout << pre.str() << std::endl;
	  std::cout << post.str() << std::endl;
	}
	
	// Create ratio histo
	TH1* denominator = his( (TH1*)file->Get(TString(pre.str())), 45, 200., 650. );
	TH1* numerator = his( (TH1*)file->Get(TString(post.str())), 45, 200., 650. );
	int rebin = 5;
	numerator->Rebin(rebin);
	denominator->Rebin(rebin);
	TH1* ratio = (TH1*)numerator->Clone();
	ratio->Divide(denominator);
	//ratio->Divide(numerator,denominator,1.,1.,"b"); //@@ poisson errors
	ratio->SetMarkerStyle(style[j]);
	ratio->SetMarkerSize(1.2);
	ratio->SetMarkerColor(iat+1);//colour[iat]);
	ratio->SetBarOffset(0.1*i);
	//ratio->GetXaxis()->SetRangeUser(100.,550.);
	ratio->GetYaxis()->SetRangeUser(1.e-7,1.e-1);

	ratio->GetXaxis()->SetTitle("HT_{reco} [GeV]");
	ratio->GetYaxis()->SetTitle("R(#alpha_{T})");
	
 	if ( ratio->GetMaximum() > 0. &&
 	     ratio->GetMaximum() > pt_max ) {
 	  pt_max = ratio->GetMaximum();
 	}
 	if ( ratio->GetMinimum() > 0. && 
 	     ratio->GetMinimum() < pt_min ) {
 	  pt_min = ratio->GetMinimum();
 	}

	pt_ratio.push_back(ratio);

	if ( empty ) { ratio->Draw(""); empty = false; }
        else { ratio->Draw("same"); }

	//ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);


	// Text for legend
	std::stringstream pt_leg;
	if ( j == 0 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", GEN"; }
	else if ( j == 1 ) { pt_leg << "#alpha_{T} = " << at[iat]/1000. << ", RECO"; }
	pt_legend->AddEntry( ratio, TString(pt_leg.str()), "lep" );
	
// 	// Draw histos on canvas for RECO only
// 	if ( j == 1 ) {
// 	  reco_canvas->cd();
// 	  if ( i == 0 ) ratio->Draw("");
// 	  else ratio->Draw("same");
// 	  std::stringstream reco_leg;
// 	  reco_leg << "p_{T}^{min} = " << pt[i];
// 	reco_legend->AddEntry( ratio, TString(reco_leg.str()), "lep" );
// 	}
	
      }
    }

//       if (0) {

// 	int nbins = ratio->GetNbinsX();
// 	int bin_width = ratio->GetBinWidth(1);
      
// 	double lower = 0.;
// 	double upper = 1400.;
      
// 	int bin_lower = int( ( lower - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_lower; ii < ratio->GetNbinsX()-1; ++ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    lower = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	int bin_upper = int( ( upper - ratio->GetBinLowEdge(1) ) / bin_width );
// 	for ( Int_t ii = bin_upper; ii > 0; --ii ) {
// 	  if ( ratio->GetBinContent(ii) > 0. ) { 
// 	    upper = ratio->GetBinCenter(ii);
// 	    break;
// 	  }
// 	}
// 	if (0) {
// 	  std::cout << " bin_width: " << bin_width
// 		    << " bin_lower: " << bin_lower
// 		    << " bin_upper: " << bin_upper
// 		    << " lower: " << lower
// 		    << " upper: " << upper
// 		    << std::endl;
// 	}

// 	TF1* fit = new TF1(sample[i],"expo",lower,upper); 
// 	fit->SetLineColor(colour[i]);
// 	fit->SetLineWidth(1);
// 	ratio->Fit(sample[i],"QR","same");

//       }
      
     pt_canvas->cd();
//      for ( Int_t iii = 0; iii < pt_ratio.size(); ++iii ) {
//        TH1* ratio = pt_ratio[iii];
//        if ( !ratio ) { continue; }
//        if ( ii == 0 ) { ratio->Draw(""); }
//        else { ratio->Draw("same"); }
//        ratio->GetYaxis()->SetRangeUser(pt_min/1.1,pt_max*1.1);
//      }
     pt_legend->Draw("same");
     pt_canvas->Update();
     pt_canvas->SaveAs(TString(pt_can.str()+".png"));
//       pt_canvas->SaveAs(TString(pt_can.str()+".C"));
      
    }

//   reco_canvas->cd();
//   reco_legend->Draw("same");
//   reco_canvas->Update();
//   reco_canvas->SaveAs(TString("Reco.png"));
//   reco_canvas->SaveAs(TString("Reco.C"));
  
//   TCanvas* c2 = new TCanvas("C2");
//   c2->SetLogy();
//   c2->SetFillColor(0);
//   gStyle->SetOptStat(0);
//   if ( count > 0 ) {
//     TGraph* graph = new TGraph(count,x3,r); 
//     graph->Draw("a*");
//   }

  
}
Пример #17
0
void FakeLeptonPlotter::writeFakeRate(string extension)
{        
    for( unsigned int iVar = 0; iVar < nHistograms; ++iVar )
    {           
        if( configContainer.addOverflow ) 
        {
            histogramContainers[iVar].addOverflow();
        }
        if( configContainer.addUnderflow ) 
        {
            histogramContainers[iVar].addUnderflow();
        }
        
        
        HistogramContainer fakeHistCont("fake_rate_" + histogramContainers[iVar].containerName, 1);
        vector<TH1*> hMC;
        bool hasEwkCorrection = false;
        
        for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
        {
            if( histogramContainers[iVar].sampleType[iSample] == SampleType::DATA )
            {
                fakeHistCont.add(histogramContainers[iVar], iSample);
            }
            else if( configContainer.sampleContainer.sampleType[iSample] == SampleType::MC  )
            {
                hMC.push_back(histogramContainers[iVar].histograms[iSample]);
                hasEwkCorrection = true;
            }
        }
        
        // Add QCD signal
        for( unsigned int iSample = 0; iSample < nSamples; ++iSample )
        {
            if( histogramContainers[iVar].sampleType[iSample] == SampleType::SIGNAL )
            {
                fakeHistCont.add(histogramContainers[iVar], iSample);
            }
        }
        
        // EKW MC correction
        if( hasEwkCorrection )
        {
            // Add data without ewk correction
            fakeHistCont.add(fakeHistCont, 0);
            fakeHistCont.color.back() += 3;
            fakeHistCont.reducedNames.back() += "_before_ewk_correction";
            fakeHistCont.histograms.back() = (TH1*) fakeHistCont.histograms[0]->Clone();
        }
        for( TH1* h : hMC )
        {
            fakeHistCont.histograms[0]->Add(h, -1.);           
        }
        
        // Seperate Numerator and Denominator
        if( histogramContainers[iVar].containerName.find("lepton") != string::npos ) 
        {
            if( histogramContainers[iVar].containerName.find("loose") != string::npos ) 
            {
                hDenomVector.push_back(fakeHistCont.histograms);
            }
            else
            {
                fakeHistogramContainers.push_back(fakeHistCont);
            }
        }
    }
        
    for( unsigned int iFake = 0; iFake < fakeHistogramContainers.size(); ++iFake )
    {
        for( unsigned int iHist = 0; iHist < fakeHistogramContainers[iFake].histograms.size(); ++iHist )
        {
            // remove underflow in numerator, important for TGraphAsymmErrors to work!
            fakeHistogramContainers[iFake].histograms[iHist]->ClearUnderflowAndOverflow();
            
            // fill empty/negative bins
            unsigned int nBins = fakeHistogramContainers[iFake].histograms[iHist]->GetNcells();
            for( unsigned int i = 0; i < (nBins+2); ++i )
            {
                if( hDenomVector[iFake][iHist]->GetBinContent(i) <= 0)
                {
                    hDenomVector[iFake][iHist]->SetBinContent(i,1.);
                    fakeHistogramContainers[iFake].histograms[iHist]->SetBinContent(i,0.);
                }
                if( fakeHistogramContainers[iFake].histograms[iHist]->GetBinContent(i) < 0.)
                {
                    fakeHistogramContainers[iFake].histograms[iHist]->SetBinContent(i,0);
                }
                if( fakeHistogramContainers[iFake].histograms[iHist]->GetBinContent(i) > hDenomVector[iFake][iHist]->GetBinContent(i) )
                {
                    fakeHistogramContainers[iFake].histograms[iHist]->SetBinContent(i,hDenomVector[iFake][iHist]->GetBinContent(i));
                }
            }
        }
        // Make plots
        BasePlotter::writeEfficiency(fakeHistogramContainers[iFake], hDenomVector[iFake], extension);
    }
    
    // Write histrograms
    system(("mkdir -p " + configContainer.outputDir).c_str());   
    TFile* f = new TFile((configContainer.outputDir + "Fakerate.root").c_str(), "RECREATE");
        
    for( unsigned int iFake = 0; iFake < fakeHistogramContainers.size(); ++iFake )
    {
        if( fakeHistogramContainers[iFake].histograms[0]->GetDimension() == 1 )
        {
            // Write Data FR
            TGraphAsymmErrors* tgraph = new TGraphAsymmErrors(fakeHistogramContainers[iFake].histograms[0], hDenomVector[iFake][0], "cl=0.683 b(1,1) mode");
            tgraph->Write();
            
            // Write MC signal FR
            for( unsigned int iHist = 0; iHist < fakeHistogramContainers[iFake].histograms.size(); ++iHist )
            {
                if( fakeHistogramContainers[iFake].sampleType[iHist] == SampleType::SIGNAL )
                {
                    TGraphAsymmErrors* tgraph = new TGraphAsymmErrors(fakeHistogramContainers[iFake].histograms[iHist], hDenomVector[iFake][iHist], "cl=0.683 b(1,1) mode");
                    tgraph->Write();;
                }
            }
        }
        else
        {
            // Write Data FR
            TH1* hTemp = (TH1*) fakeHistogramContainers[iFake].histograms[0]->Clone();
            hTemp->Divide(hDenomVector[iFake][0]);
            hTemp->Write();
            
            // Write MC signal FR
            for( unsigned int iHist = 0; iHist < fakeHistogramContainers[iFake].histograms.size(); ++iHist )
            {
                if( fakeHistogramContainers[iFake].sampleType[iHist] == SampleType::SIGNAL )
                {
                    TH1* hTemp = (TH1*) fakeHistogramContainers[iFake].histograms[iHist]->Clone();
                    hTemp->Divide(hDenomVector[iFake][iHist]);
                    hTemp->Write();
                }
            }
        }
    }  
    f->Close();
    
    // verbose output
    for( unsigned int iVar = 0; iVar < fakeHistogramContainers.size(); ++iVar )
    {  
        
        if( iVar == 0 )
            BasePlotter::writeHist("fake_lepton_intermediate.root", fakeHistogramContainers[iVar].histograms, "RECREATE");
        else
            BasePlotter::writeHist("fake_lepton_intermediate.root", fakeHistogramContainers[iVar].histograms, "UPDATE");
        
        BasePlotter::writeHist("fake_lepton_intermediate.root", hDenomVector[iVar], "UPDATE");
    }   
}
Пример #18
0
int main(int argc, char* argv[]) {

  TFile* dataFile=TFile::Open("pu_truth_data2015_50bins.root"); 
  TFile* mcFile = TFile::Open("computed_mc_GJET_plus_QCD_pu_truth_50bins.root");

  TH1* dataHisto = static_cast<TH1*>(dataFile->Get("pileup"));
  TH1* mcHisto = static_cast<TH1*>(mcFile->Get("pileup"));

  TFile f1("/cmshome/fpreiato/GammaJet/CMSSW_7_4_14/src/JetMETCorrections/GammaJetFilter/analysis/tuples/GJET_MC/PhotonJet_2ndLevel_GJet_Pt-15To6000_TuneCUETP8M1-Flat_13TeV_pythia8_25ns_ReReco.root");                                       
  TTree* AnalysisTree_mc = (TTree*) f1.Get("gammaJet/analysis");                                                        
  uint64_t totalEvents_mc = AnalysisTree_mc->GetEntries();  

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

    // Normalize
    dataHisto->Scale(1.0 / dataHisto->Integral());
    mcHisto->Scale(1.0 / mcHisto->Integral());
    
    TCanvas *c1 = new TCanvas("c1","c1",800,800);
    dataHisto-> SetLineColor(kBlue);
    mcHisto -> SetLineColor(kRed);
    dataHisto -> Draw();
    mcHisto -> Draw("same");
    c1-> SaveAs("Plot/pileup_truth.png");
    //   c1-> SaveAs("pileup_truth.root");
        
    // MC * data / MC = data, so the weights are data/MC:
    TH1* ratioHisto = static_cast<TH1*>(dataHisto->Clone());
    ratioHisto->Divide(mcHisto);

    int NBins = ratioHisto->GetNbinsX();

    for (int ibin = 1; ibin < NBins + 1; ++ibin) {
      std::cout << "   " << ibin - 1 << " " << ratioHisto->GetBinContent(ibin) << std::endl;
    }
        
    TCanvas *c2 = new TCanvas("c2","c2",800,800);
    ratioHisto -> Draw();
    c2-> SaveAs("Plot/ratioHisto.png");
    //    c2-> SaveAs("ratioHisto.root");
    
    TH1D* mcHisto_reweighted = new TH1D("mcHisto_reweighted", "mc Reweighted", 50, 0, 50);
    
    for (uint64_t i = 0; i < totalEvents_mc; i++) {      
      if(i == 0 || i % 5000 == 0) cout<< "Events processed "<< i <<endl;
      AnalysisTree_mc->GetEntry(i);
      Float_t interaction;
      AnalysisTree_mc->SetBranchAddress("ntrue_interactions", &interaction);
      //cout<< ptPhot << endl;
      
	int bin = ratioHisto ->GetXaxis()-> FindBin(interaction);
	float PUweight = ratioHisto -> GetBinContent(bin);
	
	double generator_weight;
	AnalysisTree_mc->SetBranchAddress("generator_weight", &generator_weight);   
	if(generator_weight == 0) generator_weight = 1;
	float event_weight;
	AnalysisTree_mc->SetBranchAddress("evtWeightTot", &event_weight);   
	
	double Weight = PUweight* generator_weight * event_weight;
	
	//      cout<< "nvertex "<< nvertex_mc<<endl;
	//      cout<< "PUWeight "<< PUweight<<endl;	
	mcHisto_reweighted -> Fill(interaction, Weight);     
    }
    
    mcHisto_reweighted ->Scale(1.0 / mcHisto_reweighted->Integral());
    
    TCanvas *c3 = new TCanvas("c3","c3",800,800);
    dataHisto -> SetLineColor(kBlue);
    mcHisto_reweighted -> SetLineColor(kRed);
    dataHisto -> Draw();
    mcHisto_reweighted -> Draw("same");
    c3-> SaveAs("Plot/Histo_reweighted.png");
    //    c3-> SaveAs("Histo_reweighted.root");


        
}//main
Пример #19
0
void
GetEccenNpart_new(char* xname = "ile")
{
  gStyle->SetOptStat(0);
  gStyle->SetTitle(0);

  char name[100];

  TChain* ch = new TChain("t");
  int n;

  //you need a file list of root ntuple: fxxxx.lis
  //
  sprintf(name,"f%s.lis",xname);
  cout << "open the filelist : " << name << endl;
  ifstream fin(name);

  string filename;
  while(!fin.eof()){
    fin >> filename;
    if(filename.empty()) continue;
    cout << filename << endl;

    ch->AddFile(filename.c_str());
  }
  fin.close();

  double b;
  int ncoll;
  int npart;
  int nHitBbc_n, nHitBbc_s;
  double qBBC_n, qBBC_s;
  double vertex, ecc_std, ecc_rp, ecc_part,e4;
  double r_oll,r_geo,r_arith;
  ch->SetBranchAddress("b",            &b        );
  ch->SetBranchAddress("vertex",       &vertex   );
  ch->SetBranchAddress("ncoll",        &ncoll    );
  ch->SetBranchAddress("npart",        &npart    );
  ch->SetBranchAddress("ecc_std",      &ecc_std  );
  ch->SetBranchAddress("ecc_rp",       &ecc_rp  );
  ch->SetBranchAddress("ecc_part",     &ecc_part );
  ch->SetBranchAddress("r_ollitra",    &r_oll );
  ch->SetBranchAddress("r_geo",        &r_geo );
  ch->SetBranchAddress("r_arith",      &r_arith );
  ch->SetBranchAddress("e4",           &e4       );
  ch->SetBranchAddress("qBBC_n",       &qBBC_n   );
  ch->SetBranchAddress("qBBC_s",       &qBBC_s   );
  ch->SetBranchAddress("nHitBbc_n",    &nHitBbc_n);
  ch->SetBranchAddress("nHitBbc_s",    &nHitBbc_s);

  char fname[100];
  sprintf(fname,"rootfile/g%s_cent.root",xname);
  TFile* fout = new TFile(fname,"recreate");//rootfile to save distributions

  TH1* hbbcq    = new TH1D("hbbcq","hbbcq",12000,-0.5,2999.5);      hbbcq->Sumw2();
  TH1* hbbcqall = new TH1D("hbbcqall","hbbcqall",12000,-0.5,2999.5);hbbcqall->Sumw2();
  TH1* hbbcqeff = new TH1D("hbbcqeff","hbbcqeff",12000,-0.5,2999.5);hbbcqeff->Sumw2();

  n = ch->GetEntries();
  cout << "events: "<< n << endl;

  //First loop determines the BBC trigger efficiency
  //as function of bbcq;
  for(int i=0; i<n; i++){
    ch->GetEntry(i);

    if(nHitBbc_n>=2&&nHitBbc_s>=2){
      hbbcq->Fill( (qBBC_n+qBBC_s)/100. );//divide by 100 to fit in 0-3000 range
    }

    hbbcqall->Fill( (qBBC_n+qBBC_s)/100. );
  }
  hbbcqeff->Divide(hbbcq,hbbcqall);

  efficiency = hbbcq->Integral()/hbbcqall->Integral();
  cout << "efficiency : " << efficiency << endl;

  //hbin contains the integrated fraction starting from 0 bbc charge, including the BBC trigger efficiency
  TH1* hbin = new TH1D("hbin","hbin",hbbcq->GetNbinsX(),-0.5,2999.5);
  TH1* hbbcqscale = (TH1*)hbbcq->Clone("hbbcqscale");
  hbbcqscale->Scale(1.0/hbbcq->Integral());
  for(int i=1; i<=hbbcqscale->GetNbinsX(); i++){
    hbin->SetBinContent(i,hbbcqscale->Integral(1,i));
  }
  //Following two lines defines the array of cuts and average bbc charge
  //for centrality percentitle in 5%, 10% and 20% steps
  double bbcq5[21],bbcq10[11],bbcq20[6];
  double abbcq5[20],abbcq10[10],abbcq20[5];

  //calculate the various variables for 5% step
  GetCentrality(hbin,20,bbcq5,hbbcq,abbcq5);
  cout << endl << endl;

  //calculate the various variables for 10% step
  GetCentrality(hbin,10,bbcq10,hbbcq,abbcq10);
  cout << endl << endl;

  //calculate the various variables for 20% step
  GetCentrality(hbin,5,bbcq20,hbbcq,abbcq20);
  cout << endl << endl;

  cout << " Find cuts for all the centralities " << endl << endl;

  const int nval=9;//number of variables to fill
  char* centname[3] = {"5pStep","10pStep","20pStep"};
  char* varname[nval] = {"npart","ncoll","b","standard_ecc","reactionplane_ecc","participant_ecc","R_Ollitraut","R_Geo", "R_arith"};
  double vup[nval] = {499.5,2999.5,19.995,1,1,1,4,4,4};
  double vlo[nval] = {-0.5,-0.5,-0.005,-1,-1,-1,0,0,0};
  int vNb[nval] = {500,3000,2000,200,200,200,400,400,400};

  //initialize the histograms which are used to fill the distribution of variables for each centrality
  TH1* hvar[3][nval][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int ivar=0; ivar<nval; ivar++){
      for(int icen=0; icen<NC; icen++){
	sprintf(name,"hvar_%s_%s_cent%d",centname[i],varname[ivar],icen);
	hvar[i][ivar][icen] = new TH1D(name,name,vNb[ivar],vlo[ivar],vup[ivar]);
      }
    }
  }

  double qbbcsum;
  for(int i=0; i<n; i++){
    if(i%1000000==0) cout << i << endl;
    ch->GetEntry(i);

    if(!(nHitBbc_n>=2&&nHitBbc_s>=2)) continue;//BBC trigger condition

    qbbcsum = (qBBC_n+qBBC_s)/100.;

    int centbin5  = FindBin(20,bbcq5,qbbcsum);
    int centbin10 = FindBin(10,bbcq10,qbbcsum);
    int centbin20 = FindBin(5,bbcq20,qbbcsum);

    if(centbin5==-1) continue;
    if(centbin10==-1) continue;
    if(centbin20==-1) continue;

    //find the weight according to the corresponding average efficiency.
    double weight = hbbcqeff->GetBinContent(hbbcqeff->FindBin(qbbcsum));
    //5 percent step
    //
    hvar[0][0][centbin5]->Fill(npart,weight);
    hvar[0][1][centbin5]->Fill(ncoll,weight);
    hvar[0][2][centbin5]->Fill(b,weight);
    hvar[0][3][centbin5]->Fill(ecc_std,weight);
    hvar[0][4][centbin5]->Fill(ecc_rp,weight);
    hvar[0][5][centbin5]->Fill(ecc_part,weight);
    hvar[0][6][centbin5]->Fill(r_oll,weight);
    hvar[0][7][centbin5]->Fill(r_geo,weight);
    hvar[0][8][centbin5]->Fill(r_arith,weight);

    //10 percent step
    //
    hvar[1][0][centbin10]->Fill(npart,weight);
    hvar[1][1][centbin10]->Fill(ncoll,weight);
    hvar[1][2][centbin10]->Fill(b,weight);
    hvar[1][3][centbin10]->Fill(ecc_std,weight);
    hvar[1][4][centbin10]->Fill(ecc_rp,weight);
    hvar[1][5][centbin10]->Fill(ecc_part,weight);
    hvar[1][6][centbin10]->Fill(r_oll,weight);
    hvar[1][7][centbin10]->Fill(r_geo,weight);
    hvar[1][8][centbin10]->Fill(r_arith,weight);


    //20 percent step
    //
    hvar[2][0][centbin20]->Fill(npart,weight);
    hvar[2][1][centbin20]->Fill(ncoll,weight);
    hvar[2][2][centbin20]->Fill(b,weight);
    hvar[2][3][centbin20]->Fill(ecc_std,weight);
    hvar[2][4][centbin20]->Fill(ecc_rp,weight);
    hvar[2][5][centbin20]->Fill(ecc_part,weight);
    hvar[2][6][centbin20]->Fill(r_oll,weight);
    hvar[2][7][centbin20]->Fill(r_geo,weight);
    hvar[2][8][centbin20]->Fill(r_arith,weight);
  }

  //get mean and RMS values for the variables
  float var[3][nval+1][20];
  float rms[3][nval+1][20];
  for(int i=0; i<3; i++){
    int NC = 0;
    if(i==0) NC = 20;
    else if(i==1) NC = 10;
    else if(i==2) NC = 5;
    for(int icen=0; icen<NC; icen++){
      for(int ivar=0; ivar<nval; ivar++){
	var[i][ivar][icen] = hvar[i][ivar][icen]->GetMean();
	rms[i][ivar][icen] = hvar[i][ivar][icen]->GetRMS();
      }
      var[i][nval][icen] = var[i][1][icen]/sigmann;
      rms[i][nval][icen] = rms[i][1][icen]/sigmann;
    }
  }
  //save to file
  for(int ivar=0; ivar<4; ivar++){
    for(int icen=0; icen<16; icen++){
      cout<<var[0][ivar][icen]<<",";
    }
    cout<<var[2][ivar][4]<<",";
    cout<<endl;
  }

  cout.precision(4);

  sprintf(name,"5pstepresults/t%s.txt",xname);
  ofstream f5(name);
  cout << " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<19; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f5 << var[0][ivar][icen] << " ";
    }
    f5 << var[0][nval][icen] << " ";
    f5 <<endl<<  " (";
    /* for(int ivar=0; ivar<7; ivar++){
      f5 << rms[0][ivar][icen] << " ";
    }
    f5 << rms[0][nval][icen] << " ";
    f5 <<  ")"<< endl;
    */
    cout << icen*5 << "-" << icen*5+5;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[0][ivar][icen] ;
    }
    cout <<" & " <<var[0][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[0][ivar][icen];
      else cout <<" & "<<rms[0][ivar][icen];
    }
    cout <<" & "<<rms[0][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    // printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //	   var[0][0][icen],var[0][1][icen],var[0][2][icen],var[0][3][icen],var[0][4][icen],var[0][5][icen],var[0][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[0][0][icen],rms[0][1][icen],rms[0][2][icen],rms[0][3][icen],rms[0][4][icen],rms[0][5][icen],rms[0][6][icen]);
  }
  f5.close();

  cout << endl << endl;
  sprintf(name,"10pstepresults/t%s.txt",xname);
  ofstream f10(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<10; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f10 << var[1][ivar][icen] << " ";
    }
    f10 << var[1][nval][icen] << " ";
    f10 <<endl<<" (";
    /*for(int ivar=0; ivar<7; ivar++){
      f10 << rms[1][ivar][icen] << " ";
    }
    f10 << rms[1][nval][icen] << " ";
    f10 <<  ")" << endl;
    */
    cout << icen*10 << "-" << icen*10+10;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[1][ivar][icen] ;
    }
    cout <<" & " <<var[1][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[1][ivar][icen];
      else cout <<" & "<<rms[1][ivar][icen];
    }
    cout <<" & "<<rms[1][nval][icen];
    cout <<  ")\\\\\\hline" << endl;

    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[1][0][icen],var[1][1][icen],var[1][2][icen],var[1][3][icen],var[1][4][icen],var[1][5][icen],var[1][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[1][0][icen],rms[1][1][icen],rms[1][2][icen],rms[1][3][icen],rms[1][4][icen],rms[1][5][icen],rms[1][6][icen]);

  }
  f10.close();

  cout << endl << endl;
  sprintf(name,"20pstepresults/t%s.txt",xname);
  ofstream f20(name);
  cout <<endl<< " Bin % &  npart &  ncoll &  b & ecc_std & ecc_rp & ecc_part & r_ollitrau & T_{AB}\\\\\\hline" << endl;
  for(int icen=0; icen<5; icen++){
    for(int ivar=0; ivar<7; ivar++){
      f20 << var[2][ivar][icen] << " ";
    }
    f20 << var[2][nval][icen] << " ";
    f20 << endl<<  " (";

    /*for(int ivar=0; ivar<7; ivar++){
      f20 << rms[2][ivar][icen] << " ";
    }
    f20 << rms[2][nval][icen] << " ";
    f20 <<  ")"<< endl;
    */
    cout << icen*20 << "-" << icen*20+20;
    for(int ivar=0; ivar<7; ivar++){
      cout <<" & " <<var[2][ivar][icen] ;
    }
    cout <<" & " <<var[2][nval][icen] ;
    cout <<"\\\\"<<endl;
    for(int ivar=0; ivar<7; ivar++){
      if(ivar==0)cout <<" & ("<<rms[2][ivar][icen];
      else cout <<" & "<<rms[2][ivar][icen];
    }
    cout <<" & "<<rms[2][nval][icen];
    cout <<  ")\\\\\\hline" << endl;
    //printf(" & %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f \\\\\n",
    //       var[2][0][icen],var[2][1][icen],var[2][2][icen],var[2][3][icen],var[2][4][icen],var[2][5][icen],var[2][6][icen]);
    //printf(" (& %3.1f & %4.1f & %2.2f & %1.3f & %1.3f & %1.3f & %1.3f) \\\\\\hline\n",
    //       rms[2][0][icen],rms[2][1][icen],rms[2][2][icen],rms[2][3][icen],rms[2][4][icen],rms[2][5][icen],rms[2][6][icen]);

  }
  f20.close();

  fout->Write();
  fout->Close();

  return;
}
TCanvas* overlay_Merged_RecoSmeared(const vector<string>& folders, 
								const hist_t& h
								)
{

	TLegend *leg  = new TLegend(0.6,0.65,0.9,0.9);
	leg->SetTextFont(42);
	vector<TH1*> hists;
	
	vector<string> jetcoll;
	jetcoll.push_back("reco");
	jetcoll.push_back("gen");
	jetcoll.push_back("smeared");

	stringstream title;
	const string njets("3-5");
	//const string eta("2.5");
	const string eta("5.0");
	title << njets
			<< " Jets, MHT from Jets with P_{T}>30 GeV, |#eta |<" 
			<< eta << ", L = 10 fb^{-1}" << ";" << h.title ;

	for (unsigned j=0; j< jetcoll.size(); ++j)
	{
		TH1* Hist = 0;
		for (unsigned i = 0; i < folders.size(); ++i)
		{
			stringstream histname;
			histname << folders.at(i) << "/" << jetcoll.at(j) << h.name;
			cout << __LINE__ << ": Looking for hist: " << histname.str().c_str() << endl;
			TH1* htemp = GetHist(histname.str());
			
			if (Hist == 0) Hist = htemp;
			else Hist->Add(htemp);
		}
		
		Hist->Rebin(h.rebin);
		Hist->SetTitle(title.str().c_str());
		Hist->SetMarkerStyle(20+j);
		Hist->SetLineWidth(2);
		Hist->SetStats(0);

		stringstream legname;
		if (j==0) 
		{
			legname << "Reco"; 
		} else if (j==1) 
		{
			legname << "Gen"; 
			Hist->SetLineColor(kBlue);
			Hist->SetMarkerColor(kBlue);
		} else if (j==2)
		{
			legname << "Smeared"; 
			Hist->SetLineColor(kRed);
			Hist->SetMarkerColor(kRed);
		}

		const double sum = Hist->Integral(); 
		legname << " (" << sum << ")";
		if (j!=1) leg->AddEntry(Hist, legname.str().c_str());

		hists.push_back(Hist);

	} //end jetcoll
	
	TH1* ratio = dynamic_cast<TH1*> (hists.at(2)->Clone("ratio"));
	ratio->GetYaxis()->SetTitle("Smeared/Reco");
	ratio->SetTitle("");
	ratio->Divide(hists.at(0));
	ratio->GetYaxis()->SetRangeUser(-0.01,2.01);
	//ratio->SetTickLength (+0.01,"Y");

   //TCanvas *c1 = new TCanvas("c1", "c1",15,60,550,600);
   TCanvas *c1 = new TCanvas("c1");
   c1->Range(0,0,1,1);
   c1->SetBorderSize(2);
   c1->SetFrameFillColor(0);
  
// ------------>Primitives in pad: c1_1
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.30,0.99,0.99);
   c1_1->Draw();
   c1_1->cd();
   c1_1->SetBorderSize(2);
   c1_1->SetTickx(1);
   c1_1->SetTicky(1);
   c1_1->SetTopMargin(0.1);
   c1_1->SetBottomMargin(0.0);
   //c1_1->SetFrameFillColor(3);
	c1_1->SetLogy();
   
	hists.at(0)->GetYaxis()->CenterTitle(1);
	hists.at(0)->SetLabelFont(42,"XYZ");
	hists.at(0)->SetTitleFont(42,"XYZ");
	hists.at(0)->GetYaxis()->SetTitleOffset(0.8);
	hists.at(0)->SetLabelSize(0.05,"XYZ");
	hists.at(0)->SetTitleSize(0.06,"XYZ");
   hists.at(0)->Draw("P");
   hists.at(2)->Draw("same P");
	leg->Draw();

   c1_1->Modified();
   c1->cd();
  
// ------------>Primitives in pad: c1_2
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.01,0.01,0.99,0.30);
   c1_2->Draw();
   c1_2->cd();
   c1_2->SetBorderSize(2);
   c1_2->SetTickx(1);
   c1_2->SetTicky(1);
   c1_2->SetTopMargin(0.0);
   c1_2->SetBottomMargin(0.24);
   c1_2->SetFrameFillColor(0);
	c1_2->SetGridx();
	c1_2->SetGridy();
   
	ratio->GetYaxis()->SetTitleOffset(0.4);
	ratio->GetXaxis()->SetTitleOffset(0.9);
	ratio->GetYaxis()->CenterTitle(1);
	ratio->GetXaxis()->CenterTitle(1);
	ratio->SetLabelSize(0.125,"XYZ");
	ratio->SetTitleSize(0.125,"XYZ");
//	ratio->SetLabelFont(labelfont,"XYZ");
//	ratio->SetTitleFont(titlefont,"XYZ");
   ratio->GetXaxis()->SetTickLength(0.07);
   ratio->Draw("");
   
   c1_2->Modified();
   c1->cd();
   //c1->Modified();
   //c1->cd();
   //c1->SetSelected(c1);
	return c1;

}
Пример #21
0
  /** 
   * Process a single eta bin 
   * 
   * @param measured     Input collection of measured data
   * @param corrections  Input collection of correction data
   * @param method       Unfolding method to use 
   * @param regParam     Regularisation parameter
   * @param out          Output directory. 
   *
   * @return Stack of histograms or null 
   */
  THStack* ProcessBin(TCollection* measured, 
		      TCollection* corrections, 
		      UInt_t       method,
		      Double_t     regParam, 
		      TDirectory*  out)
  {
    Printf("   Processing %s ...", measured->GetName());
    // Try to get the data 
    TH1* inRaw    = GetH1(measured,    "rawDist");
    TH1* inTruth  = GetH1(corrections, "truth");
    TH1* inTruthA = GetH1(corrections, "truthAccepted");
    TH1* inTrgVtx = GetH1(corrections, "triggerVertex");
    TH2* inResp   = GetH2(corrections, "response");
    if (!inRaw || !inTruth || !inTruthA || !inTrgVtx || !inResp) 
      return 0;
    
    // Make output directory
    TDirectory* dir = out->mkdir(measured->GetName());
    dir->cd();

    // Copy the input to the output 
    TH1* outRaw    = static_cast<TH1*>(inRaw    ->Clone("measured"));
    TH1* outTruth  = static_cast<TH1*>(inTruth  ->Clone("truth"));
    TH1* outTruthA = static_cast<TH1*>(inTruthA ->Clone("truthAccepted"));
    TH1* outTrgVtx = static_cast<TH1*>(inTrgVtx ->Clone("triggerVertex"));
    TH2* outResp   = static_cast<TH2*>(inResp   ->Clone("response"));

    // Make our response matrix 
    RooUnfoldResponse matrix(0, 0, inResp);
    
    // Store regularization parameter 
    Double_t             r        = regParam;
    RooUnfold::Algorithm algo     = (RooUnfold::Algorithm)method;
    RooUnfold*           unfolder = RooUnfold::New(algo, &matrix, inRaw, r);
    unfolder->SetVerbose(0);

    // Do the unfolding and get the result
    TH1* res = unfolder->Hreco();
    res->SetDirectory(0);

    // Make a copy to store on the output 
    TH1* outUnfold = static_cast<TH1*>(res->Clone("unfolded"));
    TString tit(outUnfold->GetTitle());
    tit.ReplaceAll("Unfold Reponse matrix", "Unfolded P(#it{N}_{ch})");
    outUnfold->SetTitle(tit);

    // Clone the unfolded results and divide by the trigger/vertex
    // bias correction
    TH1* outCorr   = static_cast<TH1*>(outUnfold->Clone("corrected"));
    outCorr->Divide(inTrgVtx);
    tit.ReplaceAll("Unfolded", "Corrected");
    outCorr->SetTitle(tit);

    // Now normalize the output to integral=1 
    TH1*  hists[] = { outRaw, outUnfold, outCorr, 0 };
    TH1** phist   = hists;
    while (*phist) { 
      TH1* h = *phist;
      if (h) { 
	Double_t intg = h->Integral(1, h->GetXaxis()->GetXmax());
	h->Scale(1. / intg, "width");
      }
      phist++;
    }
    
    // And make ratios
    TH1* ratioTrue = static_cast<TH1*>(outCorr->Clone("ratioCorrTruth"));
    tit = ratioTrue->GetTitle();
    tit.ReplaceAll("Corrected", "Corrected/MC 'truth'");
    ratioTrue->SetTitle(tit);
    ratioTrue->Divide(outTruth);
    ratioTrue->SetYTitle("P_{corrected}(#it{N}_{ch})/P_{truth}(#it{N}_{ch})");

    TH1* ratioAcc  = static_cast<TH1*>(outUnfold->Clone("ratioUnfAcc"));
    tit = ratioAcc->GetTitle();
    tit.ReplaceAll("Unfolded", "Unfolded/MC selected");
    ratioAcc->SetTitle(tit);
    ratioAcc->Divide(outTruthA);
    ratioAcc->SetYTitle("P_{unfolded}(#it{N}_{ch})/P_{MC}(#it{N}_{ch})");
    

    // Make a stack 
    tit = measured->GetName();
    tit.ReplaceAll("m", "-");
    tit.ReplaceAll("p", "+");
    tit.ReplaceAll("d", ".");
    tit.ReplaceAll("_", "<#it{#eta}<");
    THStack* stack = new THStack("all", tit);
    stack->Add(outTruth,  "E2");
    stack->Add(outTruthA, "E2");
    stack->Add(outRaw,    "E1");
    stack->Add(outUnfold, "E1");
    stack->Add(outCorr,   "E1");
    dir->Add(stack);

    // Rest of the function is devoted to making the output look nice 
    outRaw   ->SetDirectory(dir); 
    outTruth ->SetDirectory(dir);  
    outTruthA->SetDirectory(dir);  
    outTrgVtx->SetDirectory(dir);  
    outResp  ->SetDirectory(dir);  
    outUnfold->SetDirectory(dir);   
    outCorr  ->SetDirectory(dir); 

    outRaw   ->SetMarkerStyle(20);  // Measured is closed
    outTruth ->SetMarkerStyle(24);  // MC is open
    outTruthA->SetMarkerStyle(24);  // MC is open
    outTrgVtx->SetMarkerStyle(20);  // Derived is closed
    outUnfold->SetMarkerStyle(20);  // Derived is closed   
    outCorr  ->SetMarkerStyle(20);  // Derived is closed 

    outRaw   ->SetMarkerSize(0.9); 
    outTruth ->SetMarkerSize(1.6);  
    outTruthA->SetMarkerSize(1.4);  
    outTrgVtx->SetMarkerSize(1.0);  
    outUnfold->SetMarkerSize(0.9);   
    outCorr  ->SetMarkerSize(1.0);
 
    outRaw   ->SetMarkerColor(kColorMeasured); 
    outTruth ->SetMarkerColor(kColorTruth);  
    outTruthA->SetMarkerColor(kColorAccepted);  
    outTrgVtx->SetMarkerColor(kColorTrgVtx);  
    outUnfold->SetMarkerColor(kColorUnfolded);   
    outCorr  ->SetMarkerColor(kColorCorrected); 

    outRaw   ->SetFillColor(kColorError);     
    outTruth ->SetFillColor(kColorError);  
    outTruthA->SetFillColor(kColorError);  
    outTrgVtx->SetFillColor(kColorError);  
    outUnfold->SetFillColor(kColorError);   
    outCorr  ->SetFillColor(kColorError); 

    outRaw   ->SetFillStyle(0); 
    outTruth ->SetFillStyle(1001);  
    outTruthA->SetFillStyle(1001);  
    outTrgVtx->SetFillStyle(0);  
    outUnfold->SetFillStyle(0);   
    outCorr  ->SetFillStyle(0);

    outRaw   ->SetLineColor(kBlack); 
    outTruth ->SetLineColor(kBlack);  
    outTruthA->SetLineColor(kBlack);  
    outTrgVtx->SetLineColor(kBlack);  
    outUnfold->SetLineColor(kBlack);   
    outCorr  ->SetLineColor(kBlack); 

    // Legend 
    TLegend* l = StackLegend(stack);
    l->AddEntry(outRaw,     "Raw",                 "lp");
    l->AddEntry(outTruth,   "MC 'truth'",          "fp");
    l->AddEntry(outTruthA,  "MC 'truth' accepted", "fp");
    l->AddEntry(outUnfold,  "Unfolded",            "lp");
    l->AddEntry(outCorr,    "Corrected",           "lp");

    return stack;
  }
Пример #22
0
void plot(int mass) {
  double myQCDRelUncert = 0.038;
  double myEWKRelUncert = 0.131;
  double myFakesRelUncert = 0.238;
  double delta = 1.4;
  double br = 0.05;
  bool debug = false;
  bool log = false;
  double ymin = 0.001;
  double ymax = 48;
  
  static bool bMessage = false;
  if (!bMessage) {
    cout << "Values used as relative uncertainty (please check):" << endl;
    cout << "  QCD: " << myQCDRelUncert << endl;
    cout << "  EWK genuine tau: " << myEWKRelUncert << endl;
    cout << "  EWK fake tau: " << myFakesRelUncert << endl << endl;
    bMessage = true;
  }
  cout << "Processing mass point: " << mass << " GeV/c2" << endl;
  
  gStyle->SetOptFit(1);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gStyle->SetTitleFont(43, "xyz");
  gStyle->SetTitleSize(33, "xyz");
  gStyle->SetLabelFont(43, "xyz");
  gStyle->SetLabelSize(27, "xyz");
  
  //std::string infile = "EPS_data_nodeltaphi/hplus_100.root";
  //std::string infile = "EPS_data_deltaphi160/hplus_100.root";
  std::stringstream s;
  s << "lands_histograms_hplushadronic_m" << mass << ".root";

  std::string infile = s.str();
  
 // Canvas
  TCanvas *myCanvas = new TCanvas("myCanvas", "",0,0,600,600);
  myCanvas->SetHighLightColor(2);
  myCanvas->Range(0,0,1,1);
  myCanvas->SetFillColor(0);
  myCanvas->SetBorderMode(0);
  myCanvas->SetBorderSize(2);
  if (log)
    myCanvas->SetLogy();
  myCanvas->SetTickx(1);
  myCanvas->SetTicky(1);
  myCanvas->SetLeftMargin(0.16);
  myCanvas->SetRightMargin(0.05);
  myCanvas->SetTopMargin(0.05);
  myCanvas->SetBottomMargin(0.08);
  myCanvas->SetFrameFillStyle(0);
  myCanvas->SetFrameBorderMode(0);
  myCanvas->SetFrameFillStyle(0);
  myCanvas->SetFrameBorderMode(0);
  myCanvas->cd();

  Int_t ci;

  TFile* f = TFile::Open(infile.c_str());
  s.str("");
  s << "HW" << mass << "_1";
  TH1* hw = (TH1*)f->Get(s.str().c_str());
  s.str("");
  s << "HH" << mass << "_1";
  TH1* hh = (TH1*)f->Get(s.str().c_str());
  TH1* data = (TH1*)f->Get("data_obs");
  data->SetLineWidth(2);
  data->SetMarkerStyle(20);
  data->SetMarkerSize(1.2);

  TH1* ewktau = (TH1*)f->Get("EWK_Tau");
  ci = TColor::GetColor("#993399");
  ewktau->SetFillColor(ci);
  ewktau->SetLineWidth(0);
  TH1* ewkDY = (TH1*)f->Get("EWK_DYx");
  TH1* ewkVV = (TH1*)f->Get("EWK_VVx");
  ewktau->Add(ewkDY);
  ewktau->Add(ewkVV);
  
  //TH1* qcd = (TH1*)f->Get("QCDInv");
  TH1* qcd = (TH1*)f->Get("QCD");
  ci = TColor::GetColor("#ffcc33");
  qcd->SetFillColor(ci);
  qcd->SetLineWidth(0);
  TH1* fakett = (TH1*)f->Get("fake_tt");
  ci = TColor::GetColor("#669900");
  fakett->SetFillColor(ci);
  fakett->SetLineWidth(0);
  TH1* fakeW = (TH1*)f->Get("fake_W");
  ci = TColor::GetColor("#cc3300");
  fakeW->SetFillColor(ci);
  fakeW->SetLineWidth(0);
  TH1* faket = (TH1*)f->Get("fake_t");

  TH1F *hFrame = new TH1F("hFrame","",20,0,400);
  hFrame->SetMinimum(ymin);
  if (log)
    hFrame->SetMaximum(ymax*1.5);
  else
    hFrame->SetMaximum(ymax);
  hFrame->SetDirectory(0);
  hFrame->SetStats(0);
  hFrame->SetLineStyle(0);
  hFrame->SetMarkerStyle(20);
  hFrame->SetXTitle("Transverse mass (#tau jet, E_{T}^{miss}), (GeV/c^{2})");
  if (paperStatus)
    hFrame->SetXTitle("Transverse mass (#tau_{h}, E_{T}^{miss}), (GeV/c^{2})");
  hFrame->SetYTitle("Events / 20 GeV/c^{2}");
  hFrame->GetXaxis()->SetTitleSize(0);
  hFrame->GetXaxis()->SetLabelSize(0);
  hFrame->GetYaxis()->SetTitleFont(43);
  hFrame->GetYaxis()->SetTitleSize(27);
  hFrame->GetYaxis()->SetTitleOffset(1.3);
  

  // signal
  hh->Scale(br*br);
  hw->Scale(2*br*(1.0-br));
  TH1* signal = (TH1*)hh->Clone();
  signal->Add(hw);

  ci = TColor::GetColor("#ff3399");
  signal->SetLineColor(ci);
  signal->SetLineStyle(2);
  signal->SetLineWidth(2);

  // Fakes
  TH1* fakes = (TH1*)(fakett->Clone());
  fakes->Add(fakeW);
  fakes->Add(faket);

  // stacked backgrounds
  THStack *exp = new THStack();
  exp->SetName("exp");
  exp->SetTitle("exp");
  exp->Add(fakes);
  exp->Add(ewktau);
  exp->Add(qcd);
  exp->Add(signal);
  
  TH1* hExpBkg = (TH1*)fakes->Clone();
  hExpBkg->Add(ewktau);
  hExpBkg->Add(qcd);
  
  // uncertainty
  TH1* uncert = (TH1*)fakeW->Clone();
  uncert->Add(fakett);
  uncert->Add(ewktau);
  uncert->Add(qcd);
  uncert->SetFillColor(1);
  uncert->SetFillStyle(3344);
  uncert->SetLineColor(0);
  uncert->SetLineStyle(0);
  uncert->SetLineWidth(0);

  TH1* hExpBkgTotalUncert = (TH1*)uncert->Clone();
  hExpBkgTotalUncert->SetFillStyle(3354);

  TH1* hAgreement = (TH1*)data->Clone();
  hAgreement->Divide(hExpBkg);
  TGraphErrors* hAgreementRelUncert = new TGraphErrors(hAgreement->GetNbinsX());
  hAgreementRelUncert->SetLineWidth(2);
  hAgreementRelUncert->SetLineColor(kBlack);
  for (int i = 1; i <= hFrame->GetNbinsX(); ++i) {
    double myQCDTotalUncert = TMath::Power(qcd->GetBinError(i), 2)
      + TMath::Power(qcd->GetBinContent(i)*myQCDRelUncert, 2);
    double myEWKTotalUncert = TMath::Power(ewktau->GetBinError(i), 2)
      + TMath::Power(ewktau->GetBinContent(i)*myEWKRelUncert, 2);
    double myFakesTotalUncert = TMath::Power(fakes->GetBinError(i), 2)
      + TMath::Power(fakes->GetBinContent(i)*myFakesRelUncert, 2);
    hExpBkgTotalUncert->SetBinError(i, TMath::Sqrt(myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert));

    if (hExpBkg->GetBinContent(i) > 0) {
      hAgreementRelUncert->SetPoint(i-1, hExpBkg->GetBinCenter(i), data->GetBinContent(i) / hExpBkg->GetBinContent(i));
      double myUncertData = 0;
      if (data->GetBinContent(i) > 0)
        myUncertData = TMath::Power(data->GetBinError(i) / data->GetBinContent(i), 2);
      double myUncertBkg = (myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert) / TMath::Power(hExpBkg->GetBinContent(i), 2);
      hAgreementRelUncert->SetPointError(i-1, 0,  data->GetBinContent(i) / hExpBkg->GetBinContent(i) * TMath::Sqrt(myUncertData + myUncertBkg));
    } else {
      hAgreementRelUncert->SetPoint(i-1, hExpBkg->GetBinCenter(i), 0);
      hAgreementRelUncert->SetPointError(i-1, 0, 0);
    }
    if (debug) {
      cout << "Point: " << hAgreementRelUncert->GetX()[i-1]-10 << "-" << hAgreementRelUncert->GetX()[i-1]+10
          << " GeV/c2, agreement: " << hAgreementRelUncert->GetY()[i-1] << ", uncert: " << hAgreement->GetBinError(i) << ", " << hAgreementRelUncert->GetErrorY(i-1) << endl;
      cout << "  bkg. stat. uncert. " << hExpBkg->GetBinError(i) << " (i.e. " << hExpBkg->GetBinError(i) / hExpBkg->GetBinContent(i) * 100.0 << " %)"
          << ", stat+syst uncert. " << TMath::Sqrt(myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert) 
          << " (i.e. " << TMath::Sqrt(myQCDTotalUncert + myEWKTotalUncert + myFakesTotalUncert) / hExpBkg->GetBinContent(i) * 100.0 << " %)" << endl;
    }
  }

  // Agreement pad
  TPad* pad = new TPad("ratiopad","ratiopad",0.,0.,1.,.3);
  pad->Draw();
  pad->cd();
  pad->Range(0,0,1,1);
  pad->SetFillColor(0);
  pad->SetFillStyle(4000);
  pad->SetBorderMode(0);
  pad->SetBorderSize(2);
  pad->SetTickx(1);
  pad->SetTicky(1);
  pad->SetLeftMargin(0.16);
  pad->SetRightMargin(0.05);
  pad->SetTopMargin(0);
  pad->SetBottomMargin(0.34);
  pad->SetFrameFillStyle(0);
  pad->SetFrameBorderMode(0);
  // Plot here ratio
  if (1.0-delta > 0)
    hAgreement->SetMinimum(1.0-delta);
  else
    hAgreement->SetMinimum(0.);
  hAgreement->SetMaximum(1.0+delta);
  hAgreement->GetXaxis()->SetLabelOffset(0.007);
  hAgreement->GetXaxis()->SetLabelFont(43);
  hAgreement->GetXaxis()->SetLabelSize(27);
  hAgreement->GetYaxis()->SetLabelFont(43);
  hAgreement->GetYaxis()->SetLabelSize(27);
  hAgreement->GetYaxis()->SetLabelOffset(0.007);
  hAgreement->GetYaxis()->SetNdivisions(505);
  hAgreement->GetXaxis()->SetTitleFont(43);
  hAgreement->GetYaxis()->SetTitleFont(43);
  hAgreement->GetXaxis()->SetTitleSize(33);
  hAgreement->GetYaxis()->SetTitleSize(33);
  hAgreement->SetTitleSize(27, "xyz");
  hAgreement->GetXaxis()->SetTitleOffset(3.2);
  hAgreement->GetYaxis()->SetTitleOffset(1.3);
  hAgreement->SetXTitle(hFrame->GetXaxis()->GetTitle());
  hAgreement->SetYTitle("Data/#Sigmabkg");
  hAgreement->Draw("e2");
  // Plot line at zero
  TH1* hAgreementLine = dynamic_cast<TH1*>(hAgreement->Clone());
  for (int i = 1; i <= hAgreementLine->GetNbinsX(); ++i) {
    hAgreementLine->SetBinContent(i,1.0);
    hAgreementLine->SetBinError(i,0.0);
  }
  hAgreementLine->SetLineColor(kRed);
  hAgreementLine->SetLineWidth(2);
  hAgreementLine->SetLineStyle(3);
  hAgreementLine->Draw("hist same");
  hAgreement->Draw("same");
  hAgreementRelUncert->Draw("[]");
  pad->RedrawAxis();

  myCanvas->cd();
  
  TPad* plotpad = new TPad("plotpad", "plotpad",0,0.3,1.,1.);
  plotpad->Draw();
  plotpad->cd();
  plotpad->Range(0,0,1,1);
  plotpad->SetFillColor(0);
  plotpad->SetFillStyle(4000);
  plotpad->SetBorderMode(0);
  plotpad->SetBorderSize(2);
  //if (logy)
  //  plotpad->SetLogy();
  plotpad->SetTickx(1);
  plotpad->SetTicky(1);
  plotpad->SetLeftMargin(0.16);
  plotpad->SetRightMargin(0.05);
  plotpad->SetTopMargin(0.065);
  plotpad->SetBottomMargin(0.0);
  plotpad->SetFrameFillStyle(0);
  plotpad->SetFrameBorderMode(0);
  
  hFrame->GetXaxis()->SetTitleSize(0);
  hFrame->GetXaxis()->SetLabelSize(0);
  hFrame->GetYaxis()->SetTitleFont(43);
  hFrame->GetYaxis()->SetTitleSize(33);
  hFrame->GetYaxis()->SetTitleOffset(1.3);
  
  // Draw objects
  hFrame->Draw();
  exp->Draw("hist same");
  uncert->Draw("E2 same");
  hExpBkgTotalUncert->Draw("E2 same");
  // Data
  data->Draw("same");
  
  //signal->Draw("same");
  TLegend *leg = new TLegend(0.53,0.6,0.87,0.91,NULL,"brNDC");
  leg->SetBorderSize(0);
  leg->SetTextFont(63);
  leg->SetTextSize(18);
  leg->SetLineColor(1);
  leg->SetLineStyle(1);
  leg->SetLineWidth(1);
  leg->SetFillColor(kWhite);
  //leg->SetFillStyle(4000); // enabling this will cause the plot to be erased from the pad
  TLegendEntry* entry = leg->AddEntry(data, "Data", "P");
  s.str("");
  s << "with H^{#pm}#rightarrow#tau^{#pm}#nu";
  entry = leg->AddEntry(signal, s.str().c_str(), "L");
  entry = leg->AddEntry(qcd, "QCD (meas.)", "F");
  entry = leg->AddEntry(ewktau, "EWK genuine #tau (meas.)", "F");
  entry = leg->AddEntry(fakes, "EWK fake #tau (MC)", "F");
  entry = leg->AddEntry(uncert, "stat. uncert.", "F");
  entry = leg->AddEntry(hExpBkgTotalUncert, "stat. #oplus syst. uncert.", "F");
  leg->Draw();
  
  string myTitle = "CMS Preliminary";
  if (paperStatus)
    myTitle = "CMS";

  TLatex *tex = new TLatex(0.62,0.945,myTitle.c_str());
  tex->SetNDC();
  tex->SetTextFont(43);
  tex->SetTextSize(27);
  tex->SetLineWidth(2);
  tex->Draw();
  tex = new TLatex(0.2,0.945,"#sqrt{s} = 7 TeV");
  tex->SetNDC();
  tex->SetTextFont(43);
  tex->SetTextSize(27);
  tex->SetLineWidth(2);
  tex->Draw();
  tex = new TLatex(0.43,0.945,"2.2 fb^{-1}");
  tex->SetNDC();
  tex->SetTextFont(43);
  tex->SetTextSize(27);
  tex->SetLineWidth(2);
  tex->Draw();

  s.str("");
  s << "m_{H^{#pm}} = " << mass << " GeV/c^{2}";
  tex = new TLatex(0.28,0.865,s.str().c_str());
  tex->SetNDC();
  tex->SetTextFont(63);
  tex->SetTextSize(20);
  tex->SetLineWidth(2);
  tex->Draw();
  s.str("");
  s << "BR(t#rightarrowbH^{#pm})=" << setprecision(2) << br;
  tex = new TLatex(0.28,0.805,s.str().c_str());
  tex->SetNDC();
  tex->SetTextFont(63);
  tex->SetTextSize(20);
  tex->SetLineWidth(2);
  tex->Draw();

  
  plotpad->RedrawAxis();
  plotpad->Modified();

  s.str("");
  s << "mT_datadriven_m" << mass << ".png";
  myCanvas->Print(s.str().c_str());
  s.str("");
  s << "mT_datadriven_m" << mass << ".C";
  myCanvas->Print(s.str().c_str());
  s.str("");
  s << "mT_datadriven_m" << mass << ".eps";
  myCanvas->Print(s.str().c_str());
   

}