Ejemplo n.º 1
0
	TFile * fPbPb = new TFile("eta3_109_1.root");

	TGraphErrors * gr_pA_eta3[20] = {};
	TGraphErrors * gr_AA_eta3[20] = {};
	TGraphErrors * gr_pA_eta3_de[20] = {};
	TGraphErrors * gr_AA_eta3_de[20] = {};

	TGraphErrors * gr_pA_eta[20] = {};
	TGraphErrors * gr_AA_eta[20] = {};
	TGraphErrors * gr_pA_eta_de[20] = {};
	TGraphErrors * gr_AA_eta_de[20] = {};


	SetStyle();

	TCanvas * cT = MakeCanvas("cTeta3", "cTeta3", 1600, 500);
	makeMultiPanelCanvas(cT, 4, 1, 0.0, 0., 0.15, 0.15, 0.01);

	TH2D * hframe_eta3 = new TH2D("hframe_eta3", "", 1, -2.4, 2.4, 1, 0, 0.16);
	InitHist(hframe_eta3, "#eta", "v_{n}");
	hframe_eta3->SetTitleOffset(1.2);

	gr_pA_eta3[7] = (TGraphErrors*) fpPb->Get("gr_EP_eta3_7");
	gr_pA_eta3[6] = (TGraphErrors*) fpPb->Get("gr_EP_eta3_6");
	gr_pA_eta3[5] = (TGraphErrors*) fpPb->Get("gr_EP_eta3_5");
	gr_pA_eta3[4] = (TGraphErrors*) fpPb->Get("gr_EP_eta3_4");
	gr_pA_eta3[3] = (TGraphErrors*) fpPb->Get("gr_EP_eta3_3");

	gr_pA_eta3_de[7] = (TGraphErrors*) fpPb->Get("gr_EP_eta_de3_7");
	gr_pA_eta3_de[6] = (TGraphErrors*) fpPb->Get("gr_EP_eta_de3_6");
	gr_pA_eta3_de[5] = (TGraphErrors*) fpPb->Get("gr_EP_eta_de3_5");
Ejemplo n.º 2
0
void 
postfit_use(const char* inputfile, const char* analysis = "SM", const char* dataset = "2011+2012", const char* extra="", const char* extra2="", float min=0.1, float max=-1., bool log=true)
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  // switch for MSSM/SM
  bool MSSM = std::string(analysis) == std::string("MSSM");
  // determine label
  if (std::string(dataset) == std::string("2011"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV"; }
  if (std::string(dataset) == std::string("2012"     )){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV"; }
  if (std::string(dataset) == std::string("2011+2012")){ dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV, 19.8 fb^{-1} at 8 TeV"; }
  // determine category tag
  const char* category_extra = "";
  if(std::string(extra2) == std::string("0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("0jet"      )){ category_extra = "0 jet";             }
  if(std::string(extra2) == std::string("1jet_low"  )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(extra2) == std::string("1jet_high" )){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(extra2) == std::string("1jet"      )){ category_extra = "1 jet";             }
  if(std::string(extra2) == std::string("vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(extra2) == std::string("nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(extra2) == std::string("btag"      )){ category_extra = "B-Tag";             }

  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get("Fakes"   ), "Fakes/QCD"); 
  TH1F* EWK    = refill((TH1F*)input->Get("EWK"     ), "EWK"      ); 
  TH1F* ttbar  = refill((TH1F*)input->Get("ttbar"   ), "ttbar"    ); 
  TH1F* Ztt    = refill((TH1F*)input->Get("Ztt"     ), "Ztt"      ); 
  TH1F* Zmm    = refill((TH1F*)input->Get("Zmm"     ), "Zmm"      ); 
  TH1F* Zee    = refill((TH1F*)input->Get("Zee"     ), "Zee"      ); 
  TH1F* ggH    = refill((TH1F*)input->Get("ggH"     ), "ggH"      ); 
  TH1F* data   = (TH1F*)input->Get("data_obs"); 
  // determine channel for etau Z->ee (EWK) will be shown separated from the rest (EWK1)
  TH1F* EWK1   = 0;
  if(std::string(extra) == std::string("e#tau_{h}")){
    EWK1 = refill((TH1F*)input->Get("EWK1"),  "EWK1");
  }
  TH1F* ggH_hww = 0;
  if(std::string(extra) == std::string("e#mu") and HWWBG){
    ggH_hww= refill((TH1F*)input->Get("ggH_hww" ), "ggH_hww"  ); 
  }
  TH1F* errorBand = (TH1F*)input->Get("errorBand");

  /* 
    mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  if(log) canv->SetLogy(1);
  // reduce the axis range if necessary for linea plots and SM
  if(MSSM && !log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
  if(!MSSM){ data->GetXaxis()->SetRange(0, data->FindBin(345)); }
  data->SetNdivisions(505);
  data->SetMinimum(min);
  if(std::string(extra) == std::string("#mu#mu")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zmm, log)));
    data->Draw("e");
    if(log){
      Zmm  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("ee")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Zee, log)));
    data->Draw("e");
    if(log){
      Zee  ->Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      Fakes->Draw("same");
      EWK  ->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      EWK1 ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ggH_hww, log)));
    data->Draw("e");
    if(log){
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      ggH_hww -> Draw("same");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  else{
    data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
    data->Draw("e");
    if(log){
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
      if(ggH) ggH  ->Draw("histsame");
    }
    else{
      if(ggH) ggH  ->Draw("histsame");
      Ztt  ->Draw("same");
      ttbar->Draw("same");
      EWK  ->Draw("same");
      Fakes->Draw("same");
    } 
  }
  if(errorBand){
    errorBand->Draw("e2same");
  }
  data->Draw("esame");
  canv->RedrawAxis();




  //CMSPrelim(dataset, extra, 0.17, 0.835);
  CMSPrelim(dataset, "", 0.18, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(extra);
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  if(MSSM){
    float lower_bound = EWK1 ? 0.45 : 0.50;
    TPaveText* massA      = new TPaveText(0.55, lower_bound+0.061, 0.95, lower_bound+0.161, "NDC");
    massA->SetBorderSize(   0 );
    massA->SetFillStyle(    0 );
    massA->SetTextAlign(   12 );
    massA->SetTextSize ( 0.03 );
    massA->SetTextColor(    1 );
    massA->SetTextFont (   62 );
    massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
    massA->Draw();
  }    
  float lower_bound = EWK1 ? 0.60 : 0.65;
  TLegend* leg = new TLegend(MSSM ? 0.55 : 0.50, lower_bound, 0.93, 0.90);
  SetLegendStyle(leg);
  if(MSSM){
    leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau", "L" );
  }
  else{
    if(ggH){
      if(SIGNAL_SCALE!=1){
	leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
      }
      else{
	leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
      }
    }
  }
  leg->AddEntry(data , "observed"                       , "LP");
  
  if(std::string(extra) == std::string("#mu#mu")){
    leg->AddEntry(Zmm  , "Z#rightarrow#mu#mu"    , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("ee")){
    leg->AddEntry(Zee  , "Z#rightarrowee"        , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
  }
  else if(std::string(extra) == std::string("e#tau_{h}")){
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(EWK  , "Z#rightarrow ee"              , "F" );
    leg->AddEntry(EWK1 , "electroweak"                  , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else if(std::string(extra) == std::string("e#mu") && HWWBG){
    leg->AddEntry(ggH_hww  , "H(125 GeV)#rightarrowWW" , "F" );
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  else{
    leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
    leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
    leg->AddEntry(EWK  , "electroweak"                  , "F" );
    leg->AddEntry(Fakes, "QCD"                 , "F" );
  }
  if(errorBand){
    leg->AddEntry(errorBand, "bkg. uncertainty" , "F" );
  }
  leg->Draw();

  /*
    prepare output
  */
  std::string newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root"));
  canv->Print(TString::Format("%s.png", newName.c_str())); 
  canv->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv->Print(TString::Format("%s.eps", newName.c_str())); 

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd(); 
  TH1F* model;
  if(CONSERVATIVE_CHI2){
    if(std::string(extra) == std::string("#mu#mu")){
      model = (TH1F*)Zmm ->Clone("model");
    }
    else if(std::string(extra) == std::string("ee")){
      model = (TH1F*)Zee ->Clone("model");
    }
    else if(std::string(extra) == std::string("e#mu") && HWWBG){
      model = (TH1F*)ggH_hww ->Clone("model");
    }
    else{  
      model = (TH1F*)Ztt ->Clone("model");
    }
  }
  else{
    model = (TH1F*)errorBand->Clone("model");
  }
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONSERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

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

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

  /*
    prepare output
  */
  newName = std::string(inputfile).substr(0, std::string(inputfile).find(".root")) + "_datamc";
  canv0->Print(TString::Format("%s.png", newName.c_str())); 
  canv0->Print(TString::Format("%s.pdf", newName.c_str())); 
  canv0->Print(TString::Format("%s.eps", newName.c_str())); 
}
Ejemplo n.º 3
0
void 
HTT_MT_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="muTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("muTau_0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(directory) == std::string("muTau_0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(directory) == std::string("muTau_boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(directory) == std::string("muTau_boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(directory) == std::string("muTau_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("muTau_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("muTau_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 12.1 fb^{-1} at 8 TeV";}
#endif
 
  // open example histogram file
  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"   , directory)), "QCD"); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"     , directory)), "W"  ); InitHist(EWK1 , "", "", kRed    + 2, 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"    , directory)), "ZJ" ); InitHist(EWK2 , "", "", kRed    + 2, 1001);
  TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"    , directory)), "ZL" ); InitHist(EWK3 , "", "", kRed    + 2, 1001);
#else
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZLL"   , directory)), "ZLL"); InitHist(EWK2 , "", "", kRed    + 2, 1001);
#endif
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"    , directory)), "VV" ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"    , directory)), "TT" ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"   , directory)), "ZTT"); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  float ggHScale = 1., bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A + H for the time being
  if(std::string(inputfile).find("7TeV")!=std::string::npos){ ggHScale = ( 9157.9*0.119 + 10180.7*0.120)/1000.;
                                                             bbHScale = (23314.3*0.119 + 21999.3*0.120)/1000.; }
  if(std::string(inputfile).find("8TeV")!=std::string::npos){ ggHScale = (11815.3*0.119 + 13124.9*0.120)/1000.;
                                                             bbHScale = (31087.9*0.119 + 29317.8*0.120)/1000.; }
 //  float ggHScale = 1., bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A + H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ ggHScale = (2111.4*0.11 + 4022.9*0.11)/1000.;
//                                                               bbHScale = (6211.6*0.11 + 5147.0*0.11)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ ggHScale = (2729.9*0.11 + 5193.2*0.11)/1000.;
//                                                               bbHScale = (8282.7*0.11 + 6867.8*0.11)/1000.; }
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH160", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(ggHScale);
  TH1F* bbH    = refill((TH1F*)input->Get(TString::Format("%s/bbH160", directory)), "bbH"); InitSignal(bbH); bbH ->Scale(bbHScale);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125", directory)), "qqH"); InitSignal(qqH); qqH ->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125" , directory)), "VH" ); InitSignal(VH ); VH  ->Scale(SIGNAL_SCALE);
#endif
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK3 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK3 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif

  if(scaled){
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
#ifdef EXTRA_SAMPLES
    rescale(EWK3 , 5);
#endif 
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK3 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  EWK3 ->Add(EWK2 );
  EWK  ->Add(EWK3 );
#else
  EWK  ->Add(EWK2 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{#mu}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("#mu#tau_{h}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
  leg->AddEntry(data , "observed"                       , "LP");
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=120, tan#beta=10)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

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

  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(Ztt);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+0.5);
  rat1->SetMinimum(-0.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  InitHist  (scales[1], "", "", kRed    + 2, 1001);
  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
Ejemplo n.º 4
0
void plotZee(const TString  outputDir,   // output directory
             const Double_t lumi         // integrated luminosity (/fb)
) {
  gBenchmark->Start("plotZee");
  gStyle->SetTitleOffset(1.100,"Y");
  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  //
  // input ntuple file names
  //
  enum { eData, eZee, eEWK };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;
  
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/data_select.root"); typev.push_back(eData);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/zee_select.root");  typev.push_back(eZee);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/ewk_select.root");  typev.push_back(eEWK);
  fnamev.push_back("/data/blue/ksung/EWKAna/8TeV/Selection/Zee/ntuples/top_select.root");  typev.push_back(eEWK);

  //
  // Fit options
  //
  const Int_t    NBINS     = 60;
  const Double_t MASS_LOW  = 60;
  const Double_t MASS_HIGH = 120;  
  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.5;
  
  // plot output file format
  const TString format("png");
 
   
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  // event category enumeration
  enum { eEleEle2HLT=1, eEleEle1HLT, eEleEleNoSel, eEleSC };
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
    

  // histograms for full selection (EleEle2HLT + EleEle1HLT)
  TH1D *hData = new TH1D("hData","",NBINS,MASS_LOW,MASS_HIGH); hData->Sumw2();
  TH1D *hZee  = new TH1D("hZee", "",NBINS,MASS_LOW,MASS_HIGH); hZee->Sumw2();
  TH1D *hEWK  = new TH1D("hEWK", "",NBINS,MASS_LOW,MASS_HIGH); hEWK->Sumw2();
  TH1D *hMC   = new TH1D("hMC",  "",NBINS,MASS_LOW,MASS_HIGH); hMC->Sumw2();
    
  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  matchGen;
  UInt_t  category;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, u1, u2;
  Int_t   q1, q2;
  LorentzVector *dilep=0, *lep1=0, *lep2=0;
  LorentzVector *sc1=0, *sc2=0;

  TFile *infile=0;
  TTree *intree=0;

  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
  
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	    assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);     // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);    // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);     // event number
    intree->SetBranchAddress("matchGen", &matchGen);   // event has both leptons matched to MC Z->ll
    intree->SetBranchAddress("category", &category);   // dilepton category
    intree->SetBranchAddress("npv",      &npv);	       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);	       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genVPt);     // GEN Z boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);    // GEN Z boson phi (signal MC)
    intree->SetBranchAddress("scale1fb", &scale1fb);   // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);	       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);     // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);      // Sum ET
    intree->SetBranchAddress("u1",       &u1);	       // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);	       // perpendicular component of recoil
    intree->SetBranchAddress("q1",       &q1);	       // charge of tag lepton
    intree->SetBranchAddress("q2",       &q2);	       // charge of probe lepton
    intree->SetBranchAddress("dilep",    &dilep);      // dilepton 4-vector
    intree->SetBranchAddress("lep1",     &lep1);       // tag lepton 4-vector
    intree->SetBranchAddress("lep2",     &lep2);       // probe lepton 4-vector
    intree->SetBranchAddress("sc1",      &sc1);        // tag Supercluster 4-vector
    intree->SetBranchAddress("sc2",      &sc2);        // probe Supercluster 4-vector 
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);

      if(dilep->M()       < MASS_LOW)  continue;
      if(dilep->M()       > MASS_HIGH) continue;
      if(sc1->Pt()        < PT_CUT)    continue;
      if(sc2->Pt()        < PT_CUT)    continue;
      if(fabs(sc1->Eta()) > ETA_CUT)   continue;      
      if(fabs(sc2->Eta()) > ETA_CUT)   continue;
   
      Float_t mass = dilep->M();
      
      Double_t weight=1;
      if(typev[ifile]!=eData) {
	weight *= scale1fb*lumi;
      }
      
      // fill Z events passing selection (EleEle2HLT + EleEle1HLT)
      if((category==eEleEle2HLT) || (category==eEleEle1HLT)) {
        if(typev[ifile]==eData) { 
	  hData->Fill(mass); 
	
	} else {
          
	  LorentzVector slep1 = (*lep1);
	  slep1 *= gRandom->Gaus(slep1.E(), getResCorr(sc1->Eta()))/slep1.E();
	  
	  LorentzVector slep2 = (*lep2);
	  slep2 *= gRandom->Gaus(slep2.E(), getResCorr(sc2->Eta()))/slep2.E();
	  
	  mass = (slep1+slep2).M();	  
	  
	  hMC->Fill(mass,weight);
	  if(typev[ifile]==eZee) { hZee->Fill(mass,weight); }
	  if(typev[ifile]==eEWK) { hEWK->Fill(mass,weight); }
	}
      }
    }
    
    delete infile;
    infile=0, intree=0;
  }

  TH1D *hZeeDiff = makeDiffHist(hData,hMC,"hZeeDiff");
  hZeeDiff->SetMarkerStyle(kFullCircle); 
  hZeeDiff->SetMarkerSize(0.9);
  

  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  

  char ylabel[100];     // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);  
  
  // plot colors
  Int_t linecolorZ   = kOrange-3;
  Int_t fillcolorZ   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t ratioColor   = kGray+2;
    
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.15);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  TGaxis::SetMaxDigits(3);
  
  //
  // EleEle2HLT + EleEle1HLT categories
  //   
  sprintf(ylabel,"Events / %.1f GeV/c^{2}",hData->GetBinWidth(1));
  CPlot plotZee("zee","","",ylabel);
  plotZee.AddHist1D(hData,"data","E");
  plotZee.AddToStack(hZee,"Z#rightarrowee",fillcolorZ,linecolorZ);
  plotZee.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotZee.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotZee.SetYRange(0.01,1.2*(hData->GetMaximum() + sqrt(hData->GetMaximum())));
  plotZee.TransLegend(-0.35,-0.15);
  plotZee.Draw(c,kFALSE,format,1);

  CPlot plotZeeDiff("zee","","M(e^{+}e^{-}) [GeV/c^{2}]","#chi");
  plotZeeDiff.AddHist1D(hZeeDiff,"EX0",ratioColor);
  plotZeeDiff.SetYRange(-8,8);
  plotZeeDiff.AddLine(MASS_LOW, 0,MASS_HIGH, 0,kBlack,1);
  plotZeeDiff.AddLine(MASS_LOW, 5,MASS_HIGH, 5,kBlack,3);
  plotZeeDiff.AddLine(MASS_LOW,-5,MASS_HIGH,-5,kBlack,3);
  plotZeeDiff.Draw(c,kTRUE,format,2);
  
  CPlot plotZee2("zeelog","","",ylabel);
  plotZee2.AddHist1D(hData,"data","E");
  plotZee2.AddToStack(hEWK,"EWK",fillcolorEWK,linecolorEWK);
  plotZee2.AddToStack(hZee,"Z#rightarrowee",fillcolorZ,linecolorZ);
  plotZee2.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);plotZee2.SetName("zeelog");
  plotZee2.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotZee2.SetLogy();
  plotZee2.SetYRange(1e-4*(hData->GetMaximum()),10*(hData->GetMaximum()));
  plotZee2.TransLegend(-0.35,-0.15);
  plotZee2.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  cout << endl;
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("plotZee");
}
Ejemplo n.º 5
0
void fitWm(const TString  outputDir,   // output directory
           const Double_t lumi,        // integrated luminosity (/fb)
	   const Double_t nsigma=0     // vary MET corrections by n-sigmas (nsigma=0 means nominal correction)
) {
  gBenchmark->Start("fitWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  
  // MET histogram binning and range
  const Int_t    NBINS   = 50;
  const Double_t METMAX  = 100;
  
  const Double_t PT_CUT  = 25;
  const Double_t ETA_CUT = 2.1;

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

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


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  //
  // Declare MET histograms
  //
  TH1D *hDataMet   = new TH1D("hDataMet","",  NBINS,0,METMAX); hDataMet->Sumw2();
  TH1D *hDataMetm  = new TH1D("hDataMetm","", NBINS,0,METMAX); hDataMetm->Sumw2();  
  TH1D *hDataMetp  = new TH1D("hDataMetp","", NBINS,0,METMAX); hDataMetp->Sumw2();
  TH1D *hWmunuMet  = new TH1D("hWmunuMet","", NBINS,0,METMAX); hWmunuMet->Sumw2();
  TH1D *hWmunuMetp = new TH1D("hWmunuMetp","",NBINS,0,METMAX); hWmunuMetp->Sumw2();
  TH1D *hWmunuMetm = new TH1D("hWmunuMetm","",NBINS,0,METMAX); hWmunuMetm->Sumw2();
  TH1D *hEWKMet    = new TH1D("hEWKMet", "",  NBINS,0,METMAX); hEWKMet->Sumw2();
  TH1D *hEWKMetp   = new TH1D("hEWKMetp", "", NBINS,0,METMAX); hEWKMetp->Sumw2();
  TH1D *hEWKMetm   = new TH1D("hEWKMetm", "", NBINS,0,METMAX); hEWKMetm->Sumw2();

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

  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  Float_t pfChIso, pfGamIso, pfNeuIso;
    
  TFile *infile=0;
  TTree *intree=0;

  //
  // Loop over files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	  assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("npv",      &npv);       // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);       // number of in-time PU events (MC)
    intree->SetBranchAddress("genVPt",   &genVPt);    // GEN W boson pT (signal MC)
    intree->SetBranchAddress("genVPhi",  &genVPhi);   // GEN W boson phi (signal MC)   
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight per 1/fb (MC)
    intree->SetBranchAddress("met",      &met);       // MET
    intree->SetBranchAddress("metPhi",   &metPhi);    // phi(MET)
    intree->SetBranchAddress("sumEt",    &sumEt);     // Sum ET
    intree->SetBranchAddress("mt",       &mt);        // transverse mass
    intree->SetBranchAddress("u1",       &u1);        // parallel component of recoil
    intree->SetBranchAddress("u2",       &u2);        // perpendicular component of recoil
    intree->SetBranchAddress("q",        &q);	      // lepton charge
    intree->SetBranchAddress("lep",      &lep);       // lepton 4-vector
    intree->SetBranchAddress("pfChIso",  &pfChIso);
    intree->SetBranchAddress("pfGamIso", &pfGamIso);
    intree->SetBranchAddress("pfNeuIso", &pfNeuIso);
  
    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(lep->Pt()        < PT_CUT)  continue;	
      if(fabs(lep->Eta()) > ETA_CUT) continue;
      
      if( (typev[ifile]==eAntiData || typev[ifile]==eAntiWmunu || typev[ifile]==eAntiEWK) &&
          (pfChIso+pfGamIso+pfNeuIso)>0.5*(lep->Pt()) ) 
	  continue;
      
      if(typev[ifile]==eData) {
        hDataMet->Fill(met);
	if(q>0) { hDataMetp->Fill(met); } 
	else    { hDataMetm->Fill(met); }
      
      } else if(typev[ifile]==eAntiData) {
        hAntiDataMet->Fill(met);
	if(q>0) { hAntiDataMetp->Fill(met); } 
	else    { hAntiDataMetm->Fill(met); }      
      
      } else {
        Double_t weight = 1;
        weight *= scale1fb*lumi;
	
	if(typev[ifile]==eWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
	
          Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
	  
          hWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hWmunuMetp->Fill(corrMet,weight); } 
	  else    { hWmunuMetm->Fill(corrMet,weight); }
        }
	if(typev[ifile]==eAntiWmunu) {
          Double_t corrMet=met, corrMetPhi=metPhi;
        
	  // apply recoil corrections to W MC
	  Double_t lepPt = lep->Pt();//gRandom->Gaus(lep->Pt(),0.5);
	  //Double_t lepPt = gRandom->Gaus(lep->Pt(),0.5);  // (!) uncomment to apply scale/res corrections to MC
	  recoilCorr.Correct(corrMet,corrMetPhi,genVPt,genVPhi,lepPt,lep->Phi(),nsigma,q);
          
	  Double_t nnlocorr=1;
          for(Int_t ibin=1; ibin<=hNNLOCorr->GetNbinsX(); ibin++) {
            if(genVPt >= hNNLOCorr->GetBinLowEdge(ibin) &&
               genVPt < (hNNLOCorr->GetBinLowEdge(ibin)+hNNLOCorr->GetBinWidth(ibin)))
              nnlocorr = hNNLOCorr->GetBinContent(ibin);
          }
	  //weight *= nnlocorr;  // (!) uncomment to apply NNLO corrections
          
	  hAntiWmunuMet->Fill(corrMet,weight);
	  if(q>0) { hAntiWmunuMetp->Fill(corrMet,weight); } 
	  else    { hAntiWmunuMetm->Fill(corrMet,weight); }
        }
        if(typev[ifile]==eEWK) {
          hEWKMet->Fill(met,weight);
	  if(q>0) { hEWKMetp->Fill(met,weight); }
	  else    { hEWKMetm->Fill(met,weight); }
        }
        if(typev[ifile]==eAntiEWK) {
          hAntiEWKMet->Fill(met,weight);
	  if(q>0) { hAntiEWKMetp->Fill(met,weight); }
	  else    { hAntiEWKMetm->Fill(met,weight); }
        }
      }
    }
  }  
  delete infile;
  infile=0, intree=0;   
  
  //
  // Declare fit parameters for signal and background yields
  // Note: W signal and EWK+top PDFs are constrained to the ratio described in MC
  //
  RooRealVar nSig("nSig","nSig",0.7*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar nQCD("nQCD","nQCD",0.3*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar cewk("cewk","cewk",0.1,0,5) ;
  cewk.setVal(hEWKMet->Integral()/hWmunuMet->Integral());
  cewk.setConstant(kTRUE);
  RooFormulaVar nEWK("nEWK","nEWK","cewk*nSig",RooArgList(nSig,cewk));
  RooRealVar nAntiSig("nAntiSig","nAntiSig",0.05*(hAntiDataMet->Integral()),0,hAntiDataMet->Integral());
  RooRealVar nAntiQCD("nAntiQCD","nAntiQCD",0.9*(hDataMet->Integral()),0,hDataMet->Integral());
  RooRealVar dewk("dewk","dewk",0.1,0,5) ;
  dewk.setVal(hAntiEWKMet->Integral()/hAntiWmunuMet->Integral());
  dewk.setConstant(kTRUE);
  RooFormulaVar nAntiEWK("nAntiEWK","nAntiEWK","dewk*nAntiSig",RooArgList(nAntiSig,dewk));
  
  RooRealVar nSigp("nSigp","nSigp",0.7*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar nQCDp("nQCDp","nQCDp",0.3*(hDataMetp->Integral()),0,hDataMetp->Integral());
  RooRealVar cewkp("cewkp","cewkp",0.1,0,5) ;
  cewkp.setVal(hEWKMetp->Integral()/hWmunuMetp->Integral());
  cewkp.setConstant(kTRUE);
  RooFormulaVar nEWKp("nEWKp","nEWKp","cewkp*nSigp",RooArgList(nSigp,cewkp));
  RooRealVar nAntiSigp("nAntiSigp","nAntiSigp",0.05*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar nAntiQCDp("nAntiQCDp","nAntiQCDp",0.9*(hAntiDataMetp->Integral()),0,hAntiDataMetp->Integral());
  RooRealVar dewkp("dewkp","dewkp",0.1,0,5) ;
  dewkp.setVal(hAntiEWKMetp->Integral()/hAntiWmunuMetp->Integral());
  dewkp.setConstant(kTRUE);
  RooFormulaVar nAntiEWKp("nAntiEWKp","nAntiEWKp","dewkp*nAntiSigp",RooArgList(nAntiSigp,dewkp));
  
  RooRealVar nSigm("nSigm","nSigm",0.7*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar nQCDm("nQCDm","nQCDm",0.3*(hDataMetm->Integral()),0,hDataMetm->Integral());
  RooRealVar cewkm("cewkm","cewkm",0.1,0,5) ;
  cewkm.setVal(hEWKMetm->Integral()/hWmunuMetm->Integral());
  cewkm.setConstant(kTRUE);
  RooFormulaVar nEWKm("nEWKm","nEWKm","cewkm*nSigm",RooArgList(nSigm,cewkm));  
  RooRealVar nAntiSigm("nAntiSigm","nAntiSigm",0.05*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar nAntiQCDm("nAntiQCDm","nAntiQCDm",0.9*(hAntiDataMetm->Integral()),0,hAntiDataMetm->Integral());
  RooRealVar dewkm("dewkm","dewkm",0.1,0,5) ;
  dewkm.setVal(hAntiEWKMetm->Integral()/hAntiWmunuMetm->Integral());
  dewkm.setConstant(kTRUE);
  RooFormulaVar nAntiEWKm("nAntiEWKm","nAntiEWKm","dewkm*nAntiSigm",RooArgList(nAntiSigm,dewkm));

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

  RooDataHist dataMet("dataMet", "dataMet", RooArgSet(pfmet), hDataMet);
  RooDataHist antiMet("antiMet", "antiMet", RooArgSet(pfmet), hAntiDataMet);
  RooDataHist dataTotal("dataTotal","dataTotal", RooArgList(pfmet), Index(rooCat),
                        Import("Select", dataMet),
                        Import("Anti",   antiMet));
  RooFitResult *fitRes = pdfTotal.fitTo(dataTotal,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetp("dataMetp", "dataMetp", RooArgSet(pfmet), hDataMetp);
  RooDataHist antiMetp("antiMetp", "antiMetp", RooArgSet(pfmet), hAntiDataMetp);
  RooDataHist dataTotalp("dataTotalp","dataTotalp", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetp),
                         Import("Anti",   antiMetp));
  RooFitResult *fitResp = pdfTotalp.fitTo(dataTotalp,Extended(),Minos(kTRUE),Save(kTRUE));
  
  RooDataHist dataMetm("dataMetm", "dataMetm", RooArgSet(pfmet), hDataMetm);
  RooDataHist antiMetm("antiMetm", "antiMetm", RooArgSet(pfmet), hAntiDataMetm);
  RooDataHist dataTotalm("dataTotalm","dataTotalm", RooArgList(pfmet), Index(rooCat),
                         Import("Select", dataMetm),
                         Import("Anti",   antiMetm));
  RooFitResult *fitResm = pdfTotalm.fitTo(dataTotalm,Extended(),Minos(kTRUE),Save(kTRUE));
    
  //
  // Use histogram version of fitted PDFs to make ratio plots
  // (Will also use PDF histograms later for Chi^2 and KS tests)
  //
  TH1D *hPdfMet = (TH1D*)(pdfMet.createHistogram("hPdfMet", pfmet));
  hPdfMet->Scale((nSig.getVal()+nEWK.getVal()+nQCD.getVal())/hPdfMet->Integral());
  TH1D *hMetDiff = makeDiffHist(hDataMet,hPdfMet,"hMetDiff");
  hMetDiff->SetMarkerStyle(kFullCircle);
  hMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfMetp = (TH1D*)(pdfMetp.createHistogram("hPdfMetp", pfmet));
  hPdfMetp->Scale((nSigp.getVal()+nEWKp.getVal()+nQCDp.getVal())/hPdfMetp->Integral());
  TH1D *hMetpDiff = makeDiffHist(hDataMetp,hPdfMetp,"hMetpDiff");
  hMetpDiff->SetMarkerStyle(kFullCircle);
  hMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfMetm = (TH1D*)(pdfMetm.createHistogram("hPdfMetm", pfmet));
  hPdfMetm->Scale((nSigm.getVal()+nEWKm.getVal()+nQCDm.getVal())/hPdfMetm->Integral());
  TH1D *hMetmDiff = makeDiffHist(hDataMetm,hPdfMetm,"hMetmDiff");
  hMetmDiff->SetMarkerStyle(kFullCircle); 
  hMetmDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMet = (TH1D*)(apdfMet.createHistogram("hPdfAntiMet", pfmet));
  hPdfAntiMet->Scale((nAntiSig.getVal()+nAntiEWK.getVal()+nAntiQCD.getVal())/hPdfAntiMet->Integral());
  TH1D *hAntiMetDiff = makeDiffHist(hAntiDataMet,hPdfAntiMet,"hAntiMetDiff");
  hAntiMetDiff->SetMarkerStyle(kFullCircle);
  hAntiMetDiff->SetMarkerSize(0.9);
   
  TH1D *hPdfAntiMetp = (TH1D*)(apdfMetp.createHistogram("hPdfAntiMetp", pfmet));
  hPdfAntiMetp->Scale((nAntiSigp.getVal()+nAntiEWKp.getVal()+nAntiQCDp.getVal())/hPdfAntiMetp->Integral());
  TH1D *hAntiMetpDiff = makeDiffHist(hAntiDataMetp,hPdfAntiMetp,"hAntiMetpDiff");
  hAntiMetpDiff->SetMarkerStyle(kFullCircle);
  hAntiMetpDiff->SetMarkerSize(0.9);
    
  TH1D *hPdfAntiMetm = (TH1D*)(apdfMetm.createHistogram("hPdfAntiMetm", pfmet));
  hPdfAntiMetm->Scale((nAntiSigm.getVal()+nAntiEWKm.getVal()+nAntiQCDm.getVal())/hPdfAntiMetm->Integral());
  TH1D *hAntiMetmDiff = makeDiffHist(hAntiDataMetm,hPdfAntiMetm,"hAntiMetmDiff");
  hAntiMetmDiff->SetMarkerStyle(kFullCircle); 
  hAntiMetmDiff->SetMarkerSize(0.9);
   
  
  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->Divide(1,2,0,0);
  c->cd(1)->SetPad(0,0.3,1.0,1.0);
  c->cd(1)->SetTopMargin(0.1);
  c->cd(1)->SetBottomMargin(0.01);
  c->cd(1)->SetLeftMargin(0.15);  
  c->cd(1)->SetRightMargin(0.07);  
  c->cd(1)->SetTickx(1);
  c->cd(1)->SetTicky(1);  
  c->cd(2)->SetPad(0,0,1.0,0.3);
  c->cd(2)->SetTopMargin(0.05);
  c->cd(2)->SetBottomMargin(0.45);
  c->cd(2)->SetLeftMargin(0.15);
  c->cd(2)->SetRightMargin(0.07);
  c->cd(2)->SetTickx(1);
  c->cd(2)->SetTicky(1);
  gStyle->SetTitleOffset(1.100,"Y");
  TGaxis::SetMaxDigits(3);
  
  char ylabel[100];  // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  if(lumi<0.1) sprintf(lumitext,"%.1f pb^{-1}  at  #sqrt{s} = 8 TeV",lumi*1000.);
  else         sprintf(lumitext,"%.2f fb^{-1}  at  #sqrt{s} = 8 TeV",lumi);
  
  // plot colors
  Int_t linecolorW   = kOrange-3;
  Int_t fillcolorW   = kOrange-2;
  Int_t linecolorEWK = kOrange+10;
  Int_t fillcolorEWK = kOrange+7;
  Int_t linecolorQCD = kViolet+2;
  Int_t fillcolorQCD = kViolet-5;
  Int_t ratioColor   = kGray+2;
  
  //
  // Dummy histograms for TLegend
  // (I can't figure out how to properly pass RooFit objects...)
  //
  TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
  hDummyData->SetMarkerStyle(kFullCircle);
  hDummyData->SetMarkerSize(0.9);
  
  TH1D *hDummyW = new TH1D("hDummyW","",0,0,10);
  hDummyW->SetLineColor(linecolorW);
  hDummyW->SetFillColor(fillcolorW);
  hDummyW->SetFillStyle(1001);
  
  TH1D *hDummyEWK = new TH1D("hDummyEWK","",0,0,10);
  hDummyEWK->SetLineColor(linecolorEWK);
  hDummyEWK->SetFillColor(fillcolorEWK);
  hDummyEWK->SetFillStyle(1001);
  
  TH1D *hDummyQCD = new TH1D("hDummyQCD","",0,0,10);
  hDummyQCD->SetLineColor(linecolorQCD);
  hDummyQCD->SetFillColor(fillcolorQCD);
  hDummyQCD->SetFillStyle(1001);
   
  //
  // W MET plot
  //
  RooPlot *wmframe = pfmet.frame(Bins(NBINS)); 
  wmframe->GetYaxis()->SetNdivisions(505);
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  pdfMet.plotOn(wmframe,FillColor(fillcolorW),DrawOption("F"));
  pdfMet.plotOn(wmframe,LineColor(linecolorW));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfEWK,*(qcd.model))),LineColor(linecolorEWK));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  pdfMet.plotOn(wmframe,Components(RooArgSet(*(qcd.model))),LineColor(linecolorQCD));
  pdfMet.plotOn(wmframe,Components(RooArgSet(pdfWm)),LineColor(linecolorW),LineStyle(2));
  dataMet.plotOn(wmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hDataMet->GetBinWidth(1));
  CPlot plotMet("fitmet",wmframe,"","",ylabel);
  plotMet.SetLegend(0.68,0.57,0.93,0.77);
  plotMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotMet.SetYRange(0.1,1.1*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kFALSE,format,1);

  CPlot plotMetDiff("fitmet","","#slash{E}_{T} [GeV]","#chi");
  plotMetDiff.AddHist1D(hMetDiff,"EX0",ratioColor);
  plotMetDiff.SetYRange(-8,8);
  plotMetDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetDiff.Draw(c,kTRUE,format,2);
  
  plotMet.SetName("fitmetlog");
  plotMet.SetLogy();
  plotMet.SetYRange(1e-3*(hDataMet->GetMaximum()),10*(hDataMet->GetMaximum()));
  plotMet.Draw(c,kTRUE,format,1);
    
  RooPlot *awmframe = pfmet.frame(Bins(NBINS));    
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));
  apdfMet.plotOn(awmframe,FillColor(fillcolorW),DrawOption("F"));
  apdfMet.plotOn(awmframe,LineColor(linecolorW));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),FillColor(fillcolorEWK),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfEWK,*(aqcd.model))),LineColor(linecolorEWK));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),FillColor(fillcolorQCD),DrawOption("F"));
  apdfMet.plotOn(awmframe,Components(RooArgSet(*(aqcd.model))),LineColor(linecolorQCD));
  apdfMet.plotOn(awmframe,Components(RooArgSet(apdfWm)),LineColor(linecolorW),LineStyle(2));
  antiMet.plotOn(awmframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("ZP"));  
  
  sprintf(ylabel,"Events / %.1f GeV",hAntiDataMet->GetBinWidth(1));
  CPlot plotAntiMet("fitantimet",awmframe,"","",ylabel);
  plotAntiMet.SetLegend(0.68,0.57,0.93,0.77);
  plotAntiMet.GetLegend()->AddEntry(hDummyData,"data","PL");
  plotAntiMet.GetLegend()->AddEntry(hDummyW,"W#rightarrow#mu#nu","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyEWK,"EWK+t#bar{t}","F");
  plotAntiMet.GetLegend()->AddEntry(hDummyQCD,"QCD","F");
  plotAntiMet.AddTextBox(lumitext,0.55,0.80,0.90,0.86,0);
  plotAntiMet.AddTextBox("CMS Preliminary",0.63,0.92,0.95,0.99,0);
  plotAntiMet.SetYRange(0.1,1.1*(hAntiDataMet->GetMaximum())); 
  plotAntiMet.Draw(c,kFALSE,format,1);

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

  CPlot plotMetpDiff("fitmetp","","#slash{E}_{T} [GeV]","#chi");
  plotMetpDiff.AddHist1D(hMetpDiff,"EX0",ratioColor);
  plotMetpDiff.SetYRange(-8,8);
  plotMetpDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetpDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetpDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetpDiff.Draw(c,kTRUE,format,2);
  
  plotMetp.SetName("fitmetplog");
  plotMetp.SetLogy();
  plotMetp.SetYRange(1e-3*(hDataMetp->GetMaximum()),10*(hDataMetp->GetMaximum()));
  plotMetp.Draw(c,kTRUE,format,1);

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

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

  CPlot plotMetmDiff("fitmetm","","#slash{E}_{T} [GeV]","#chi");
  plotMetmDiff.AddHist1D(hMetmDiff,"EX0",ratioColor);
  plotMetmDiff.SetYRange(-8,8);
  plotMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotMetmDiff.Draw(c,kTRUE,format,2);
  
  plotMetm.SetName("fitmetmlog");
  plotMetm.SetLogy();
  plotMetm.SetYRange(1e-3*(hDataMetm->GetMaximum()),10*(hDataMetm->GetMaximum()));
  plotMetm.Draw(c,kTRUE,format,1);

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

  CPlot plotAntiMetmDiff("fitantimetm","","#slash{E}_{T} [GeV]","#chi");
  plotAntiMetmDiff.AddHist1D(hAntiMetmDiff,"EX0",ratioColor);
  plotAntiMetmDiff.SetYRange(-8,8);
  plotAntiMetmDiff.AddLine(0, 0,METMAX, 0,kBlack,1);
  plotAntiMetmDiff.AddLine(0, 5,METMAX, 5,kBlack,3);
  plotAntiMetmDiff.AddLine(0,-5,METMAX,-5,kBlack,3);
  plotAntiMetmDiff.Draw(c,kTRUE,format,2);
  
  plotAntiMetm.SetName("fitantimetmlog");
  plotAntiMetm.SetLogy();
  plotAntiMetm.SetYRange(1e-3*(hAntiDataMetm->GetMaximum()),10*(hAntiDataMetm->GetMaximum()));
  plotAntiMetm.Draw(c,kTRUE,format,1);

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  
  //
  // Write fit results
  //
  ofstream txtfile;
  char txtfname[100];    
  
  ios_base::fmtflags flags;
  
  Double_t chi2prob, chi2ndf;
  Double_t ksprob, ksprobpe;
  
  chi2prob = hDataMet->Chi2Test(hPdfMet,"PUW");
  chi2ndf  = hDataMet->Chi2Test(hPdfMet,"CHI2/NDFUW");
  ksprob   = hDataMet->KolmogorovTest(hPdfMet);
  ksprobpe = hDataMet->KolmogorovTest(hPdfMet,"DX");
  sprintf(txtfname,"%s/fitresWm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMet->Integral() << endl;
  txtfile << "  Signal: " << nSig.getVal() << " +/- " << nSig.getPropagatedError(*fitRes) << endl;
  txtfile << "     QCD: " << nQCD.getVal() << " +/- " << nQCD.getPropagatedError(*fitRes) << endl;
  txtfile << "   Other: " << nEWK.getVal() << " +/- " << nEWK.getPropagatedError(*fitRes) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitRes->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitRes);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();
  
  chi2prob = hDataMetp->Chi2Test(hPdfMetp,"PUW");
  chi2ndf  = hDataMetp->Chi2Test(hPdfMetp,"CHI2/NDFUW");
  ksprob   = hDataMetp->KolmogorovTest(hPdfMetp);
  ksprobpe = hDataMetp->KolmogorovTest(hPdfMetp,"DX");  
  sprintf(txtfname,"%s/fitresWmp.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetp->Integral() << endl;
  txtfile << "  Signal: " << nSigp.getVal() << " +/- " << nSigp.getPropagatedError(*fitResp) << endl;
  txtfile << "     QCD: " << nQCDp.getVal() << " +/- " << nQCDp.getPropagatedError(*fitResp) << endl;
  txtfile << "   Other: " << nEWKp.getVal() << " +/- " << nEWKp.getPropagatedError(*fitResp) << endl;
  txtfile << endl; 
  txtfile.flags(flags);
  
  fitResp->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResp);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  chi2prob = hDataMetm->Chi2Test(hPdfMetm,"PUW");
  chi2ndf  = hDataMetm->Chi2Test(hPdfMetm,"CHI2/NDFUW");
  ksprob   = hDataMetm->KolmogorovTest(hPdfMetm);
  ksprobpe = hDataMetm->KolmogorovTest(hPdfMetm,"DX");  
  sprintf(txtfname,"%s/fitresWmm.txt",CPlot::sOutDir.Data());
  txtfile.open(txtfname);
  assert(txtfile.is_open());
  
  flags = txtfile.flags();
  txtfile << setprecision(10);
  txtfile << " *** Yields *** " << endl;
  txtfile << "Selected: " << hDataMetm->Integral() << endl;
  txtfile << "  Signal: " << nSigm.getVal() << " +/- " << nSigm.getPropagatedError(*fitResm) << endl;
  txtfile << "     QCD: " << nQCDm.getVal() << " +/- " << nQCDm.getPropagatedError(*fitResm) << endl;
  txtfile << "   Other: " << nEWKm.getVal() << " +/- " << nEWKm.getPropagatedError(*fitResm) << endl;
  txtfile << endl;
  txtfile.flags(flags);
  
  fitResm->printStream(txtfile,RooPrintable::kValue,RooPrintable::kVerbose);
  txtfile << endl;
  printCorrelations(txtfile, fitResm);
  txtfile << endl;
  printChi2AndKSResults(txtfile, chi2prob, chi2ndf, ksprob, ksprobpe);
  txtfile.close();

  makeHTML(outputDir);
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     
  
  gBenchmark->Show("fitWm");
}
void 
HTT_EE_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="ee_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_low"             )){ category_extra = "p_{T}(lep1) low";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category = "ee, 0 jet";          }    
  if(std::string(directory) == std::string("ee_0jet_high"            )){ category_extra = "p_{T}(lep1) high";         }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_low"          )){ category_extra = "p_{T}(lep1) low";       }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category = "ee, 1 jet";          }    
  if(std::string(directory) == std::string("ee_1jet_high"          )){ category_extra = "p_{T}(lep1) high";       }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category = "ee, 2 jet";          }    
  if(std::string(directory) == std::string("ee_vbf"            )){ category_extra = "VBF";              }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_nobtag"               )){ category_extra = "No B-Tag";                        }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category = "ee";          }    
  if(std::string(directory) == std::string("ee_btag"                 )){ category_extra = "B-Tag";                           }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.8 fb^{-1} at 8 TeV";}
 
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* ZTT     = refill((TH1F*)input ->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"     ); InitHist(ZTT     , "", "", kOrange  -  4, 1001);
  TH1F* ZEE     = refill((TH1F*)input ->Get(TString::Format("%s/ZEE"     , directory)), "ZEE"     ); InitHist(ZEE     , "", "", kAzure   +  2, 1001);
  TH1F* TTJ     = refill((TH1F*)input ->Get(TString::Format("%s/TTJ"     , directory)), "TTJ"     ); InitHist(TTJ     , "", "", kBlue    -  8, 1001);
  TH1F* QCD     = refill((TH1F*)input ->Get(TString::Format("%s/QCD"     , directory)), "QCD"     ); InitHist(QCD     , "", "", kMagenta - 10, 1001);
  TH1F* Dibosons= refill((TH1F*)input ->Get(TString::Format("%s/Dibosons", directory)), "Dibosons"); InitHist(Dibosons, "", "", kGreen   -  4, 1001);
  TH1F* WJets   = refill((TH1F*)input ->Get(TString::Format("%s/WJets"   , directory)), "WJets"   ); InitHist(WJets   , "", "", kRed     +  2, 1001);
#ifdef MSSM
  TH1F* ggH     = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH     = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"     ); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH     = refill((TH1F*)input ->Get(TString::Format("%s/ggH125"  , directory)), "ggH"     ); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH     = refill((TH1F*)input ->Get(TString::Format("%s/qqH125"  , directory)), "qqH"     ); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH      = refill((TH1F*)input ->Get(TString::Format("%s/VH125"   , directory)), "VH"      ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
#ifdef MSSM
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}" , "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);
#else
  InitHist(data, "#bf{D}", "#bf{dN/dD}"     ); InitData(data);
#endif

  TH1F* ref=(TH1F*)ZTT->Clone("ref");
  ref->Add(ZEE);
  ref->Add(TTJ);
  ref->Add(QCD);
  ref->Add(Dibosons);
  ref->Add(WJets);

  double unscaled[9];
  unscaled[0] = ZTT->Integral();
  unscaled[1] = ZEE->Integral();
  unscaled[2] = TTJ->Integral();
  unscaled[3] = QCD->Integral();
  unscaled[4] = Dibosons->Integral();
  unscaled[5] = WJets->Integral();
#ifdef MSSM
  unscaled[6] = ggH->Integral();
  unscaled[7] = bbH->Integral();
  unscaled[8] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[6] = ggH->Integral();
  unscaled[7] = qqH->Integral();
  unscaled[8] = VH ->Integral();
#endif
#endif
  
  if(scaled){
    rescale(ZTT, 1); 
    rescale(ZEE, 2); 
    rescale(TTJ, 3); 
    rescale(QCD, 4); 
    rescale(Dibosons, 5); 
    rescale(WJets,    6);
#ifdef MSSM 
    rescale(ggH, 7);
    rescale(bbH, 8);
#else
#ifndef DROP_SIGNAL
    rescale(ggH, 7);
    rescale(qqH, 8);
    rescale(VH,  9);
#endif
#endif
  }

  TH1F* scales[9];
  scales[0] = new TH1F("scales-ZTT", "", 9, 0, 9);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZTT->Integral()/unscaled[0]-1.)      : 0.);
  scales[1] = new TH1F("scales-ZEE"  , "", 9, 0, 9);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (ZEE->Integral()/unscaled[1]-1.)      : 0.);
  scales[2] = new TH1F("scales-TTJ", "", 9, 0, 9);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (TTJ->Integral()/unscaled[2]-1.)      : 0.);
  scales[3] = new TH1F("scales-QCD"  , "", 9, 0, 9);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (QCD->Integral()/unscaled[3]-1.)      : 0.);
  scales[4] = new TH1F("scales-Dibosons", "", 9, 0, 9);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Dibosons->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-WJets"  , "", 9, 0, 9);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (WJets->Integral()/unscaled[5]-1.)    : 0.);
#ifdef MSSM
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[6]-1.)      : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH->Integral()/unscaled[7]-1.)      : 0.);
  scales[8] = new TH1F("scales-NONE" , "", 9, 0, 9);
  scales[8]->SetBinContent(9, 0.);
#else
#ifndef DROP_SIGNAL
  scales[6] = new TH1F("scales-ggH"  , "", 9, 0, 9);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggH->Integral()/unscaled[4]-1.)      : 0.);
  scales[7] = new TH1F("scales-qqH"  , "", 9, 0, 9);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (qqH->Integral()/unscaled[5]-1.)      : 0.);
  scales[8] = new TH1F("scales-VH"   , "", 9, 0, 9);
  scales[8]->SetBinContent(9, unscaled[8]>0 ? (VH ->Integral()/unscaled[6]-1.)      : 0.);
#endif
#endif

  WJets->Add(Dibosons);
  QCD->Add(WJets);
  TTJ->Add(QCD);
  ZTT->Add(TTJ);
  ZEE->Add(ZTT);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(WJets);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(WJets);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }


  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(ZTT, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(ZTT, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)ZEE ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH->Draw("histsame");
#endif

  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    ZEE->Draw("histsame");
    ZTT->Draw("histsame");
    TTJ->Draw("histsame");
    QCD->Draw("histsame");
    WJets->Draw("histsame");
    //Dibosons->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{e}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.20, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.32, 0.75+0.161, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
  chan->AddText(category_extra2);
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
*/
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.55, 0.50+0.061, 0.95, 0.50+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
  massA->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"           , "LP");
#else
  leg->AddEntry(data , "observed"                    , "LP");
#endif
  leg->AddEntry(ZEE  , "Z#rightarrowee"              , "F" );
  leg->AddEntry(ZTT  , "Z#rightarrow#tau#tau"        , "F" );
  leg->AddEntry(TTJ  , "t#bar{t}"                    , "F" );
  leg->AddEntry(QCD  , "QCD"                         , "F" );
  leg->AddEntry(WJets, "electroweak"                 , "F" );
  //leg->AddEntry(Dibosons  , "Dibosons"             , "F" );
  $ERROR_LEGEND
  leg->Draw();

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

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

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

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

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) ZEE->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ZEE->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
#if defined MSSM
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}"); 
#else
  rat2->GetXaxis()->SetTitle("#bf{D}");
#endif
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kOrange  -  4, 1001);
  InitHist  (scales[1], "", "", kAzure   +  2, 1001);
  InitHist  (scales[2], "", "", kBlue    -  8, 1001);
  InitHist  (scales[3], "", "", kMagenta - 10, 1001);
  InitHist  (scales[4], "", "", kGreen   -  4, 1001);
  InitHist  (scales[5], "", "", kRed     +  2, 1001);  
#ifndef DROP_SIGNAL
  InitSignal(scales[6]);
  InitSignal(scales[7]);
  InitSignal(scales[8]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{ZTT}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{ZEE}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{TTJ}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{QCD}"  );
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Dibosons}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{WJets}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{NONE}" );
#else
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(9, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#ifndef DROP_SIGNAL
  scales[6]->Draw("same");
  scales[7]->Draw("same");
  scales[8]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
 bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  ZTT->Write("Ztt"  );
  ZEE->Write("Zee"  );
  TTJ->Write("ttbar");
  QCD->Write("Fakes");
  Dibosons->Write("Dibosons");
  WJets->Write("EWK");
#ifdef MSSM
  ggH  ->Write("ggH");
  bbH  ->Write("bbH");
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH");
  qqH  ->Write("qqH");
  VH   ->Write("VH" );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
void 
HBB_HAD_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="bb_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  const char* category_extra = "";
  if(std::string(directory) == std::string("bb_had0"  )){ category_extra = "all-had_{0}";  }
  if(std::string(directory) == std::string("bb_had1"  )){ category_extra = "all-had_{1}";  }
  if(std::string(directory) == std::string("bb_had2"  )){ category_extra = "all-had_{2}";  }
  if(std::string(directory) == std::string("bb_had3"  )){ category_extra = "all-had_{3}";  }
  if(std::string(directory) == std::string("bb_had4"  )){ category_extra = "all-had_{4}";  }
  if(std::string(directory) == std::string("bb_had5"  )){ category_extra = "all-had_{5}";  }
  if(std::string(directory) == std::string("bb_lep"   )){ category_extra = "semi-lep";  }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 7 TeV, L = 2.7 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 8 TeV, L = 19.4 fb^{-1}";}
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Bbb  = refill((TH1F*)input->Get(TString::Format("%s/Bbb"   , directory)), "Bbb"); InitHist(Bbb, "", "", kMagenta-10, 1001);
  TH1F* Cbb  = refill((TH1F*)input->Get(TString::Format("%s/Cbb"   , directory)), "Cbb"); InitHist(Cbb, "", "", kRed    + 2, 1001);
  TH1F* Qbb  = refill((TH1F*)input->Get(TString::Format("%s/Qbb"   , directory)), "Qbb"); InitHist(Qbb, "", "", kBlue   - 8, 1001);
  TH1F* bbB  = refill((TH1F*)input->Get(TString::Format("%s/bbB"   , directory)), "bbB"); InitHist(bbB, "", "", kOrange - 4, 1001);
  TH1F* bbX  = refill((TH1F*)input->Get(TString::Format("%s/bbX"   , directory)), "bbX"); InitHist(bbX, "", "", kViolet - 0, 1001);
#ifdef MSSM
  //float bbHScale = 1.;
  //ggHScale = ($MSSM_SIGNAL_ggH_xseff_A + $MSSM_SIGNAL_ggH_xseff_hH);
  //bbHScale = ($MSSM_SIGNAL_bbH_xseff_A + $MSSM_SIGNAL_bbH_xseff_hH);
  TH1F* bbH  = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale($TANB); //bbH->Scale(bbHScale);
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{b#bar{b}} [GeV]}", "#bf{dN/dm_{b#bar{b}} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Qbb->Clone("ref");
  ref->Add(bbX);
  ref->Add(Cbb);
  ref->Add(bbB);
  ref->Add(Bbb);

  double unscaled[7];
  unscaled[0] = Qbb ->Integral();
  unscaled[1] = bbX ->Integral();
  unscaled[2] = Cbb ->Integral();
  unscaled[3] = bbB ->Integral();
  unscaled[4] = Bbb ->Integral();
#ifdef MSSM
  unscaled[5] = bbH ->Integral();
  unscaled[6] = 0;
#endif

  if(scaled){
    rescale(Bbb,   1); 
    rescale(bbB,   4); 
    rescale(Cbb,   2); 
    rescale(bbX,   5);
    rescale(Qbb,   3);
#ifdef MSSM 
    rescale(bbH,   6);
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Qbb", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Qbb  ->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-bbX"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (bbX  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-Cbb", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (Cbb  ->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-bbB"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (bbB  ->Integral()/unscaled[3]-1.) : 0.);
  scales[4] = new TH1F("scales-Bbb"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (Bbb  ->Integral()/unscaled[4]-1.) : 0.);
#ifdef MSSM
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#endif

  bbX  ->Add(Qbb);
  Cbb  ->Add(bbX);
  bbB  ->Add(Cbb);
  Bbb  ->Add(bbB);
  if(!log){
#ifdef MSSM
    bbH  ->Add(Bbb);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Bbb, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Bbb ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);

  if(log){
    Bbb  ->Draw("histsame");
    bbB  ->Draw("histsame");
    Cbb  ->Draw("histsame");
    bbX  ->Draw("histsame");
    Qbb  ->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    bbH  ->Draw("histsame");
#endif
  }
  else{   
#ifndef DROP_SIGNAL
    bbH  ->Draw("histsame");
#endif 
    Bbb  ->Draw("histsame");
    bbB  ->Draw("histsame");
    Cbb  ->Draw("histsame");
    bbX  ->Draw("histsame");
    Qbb  ->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "b#bar{b}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.17, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("b#bar{b}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=$MA GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=$TANB");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("m^{h}_{max}");
  scen->Draw();
#endif

#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(bbH  , "#phi#rightarrowb#bar{b}" , "L" );
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + SM125 GeV signal"    , "LP");
#else
  leg->AddEntry(data , "observed"                       , "LP");
#endif
  leg->AddEntry(Bbb, "Bbb"                            , "F" );
  leg->AddEntry(bbB, "bbB"                            , "F" );
  leg->AddEntry(Cbb, "Cbb"                            , "F" );
  leg->AddEntry(bbX, "bbX"                            , "F" );
  leg->AddEntry(Qbb, "Qbb"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=250, tan#beta=5)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

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

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(Bbb);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+1.5);
  rat1->SetMinimum(-1.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) Bbb->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[4], "", "", kMagenta-10, 1001);
  InitHist  (scales[2], "", "", kRed    + 2, 1001);
  InitHist  (scales[0], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
  InitHist  (scales[1], "", "", kViolet - 0, 1001);
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Qbb}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{bbX}");
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{Cbb}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{bbB}");
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{Bbb}");
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{NONE}" );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  Qbb  ->Write("Qbb"     );
  bbX  ->Write("bbX"     );
  Cbb  ->Write("Cbb"     );
  bbB  ->Write("bbB"     );
  Bbb  ->Write("Bbb"     );
#ifdef MSSM
  bbH  ->Write("bbH"     );
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
Ejemplo n.º 8
0
void MuScale() {

    //--------------------------------------------------------------------------------------------------------------
    // Settings
    //==============================================================================================================

    // event category enumeration
    enum { eMuMu2HLT=1, eMuMu1HLT1L1, eMuMu1HLT, eMuMuNoSel, eMuSta, eMuTrk };  // event category enum

    TString outputDir = "MuScaleResults";

    vector<TString> infilenamev;
    infilenamev.push_back("/afs/cern.ch/work/c/cmedlock/public/wz-ntuples/Zmumu/ntuples/data_select.trkCuts.root"); // data
    infilenamev.push_back("/afs/cern.ch/work/c/cmedlock/public/wz-ntuples/Zmumu/ntuples/zmm_select.raw.trkCuts.root");  // MC

    const Double_t MASS_LOW  = 60;
    const Double_t MASS_HIGH = 120;
    const Double_t PT_CUT    = 25;
    const Double_t ETA_CUT   = 2.4;
    const Double_t MU_MASS   = 0.105658369;

    vector<pair<Double_t,Double_t> > scEta_limits;
    scEta_limits.push_back(make_pair(0.0,1.2));
    scEta_limits.push_back(make_pair(1.2,2.1));
    scEta_limits.push_back(make_pair(2.1,2.4));

    CPlot::sOutDir = outputDir;

    const TString format("png");

    //--------------------------------------------------------------------------------------------------------------
    // Main analysis code
    //==============================================================================================================

    enum { eData=0, eMC };

    char hname[100];
    vector<TH1D*> hMCv, hDatav;
    for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
        for(UInt_t jbin=ibin; jbin<scEta_limits.size(); jbin++) {
            sprintf(hname,"mc_%i_%i",ibin,jbin);
            hMCv.push_back(new TH1D(hname,"",80,MASS_LOW,MASS_HIGH));
            hMCv.back()->Sumw2();

            sprintf(hname,"data_%i_%i",ibin,jbin);
            hDatav.push_back(new TH1D(hname,"",80,MASS_LOW,MASS_HIGH));
            hDatav.back()->Sumw2();
        }
    }

    //
    // Declare output ntuple variables
    //
    UInt_t  runNum, lumiSec, evtNum;
    Float_t scale1fb, puWeight;
    UInt_t  matchGen;
    UInt_t  category;
    UInt_t  npv, npu;
    Int_t   q1, q2;
    TLorentzVector *dilep=0, *lep1=0, *lep2=0;

    for(UInt_t ifile=0; ifile<infilenamev.size(); ifile++) {
        cout << "Processing " << infilenamev[ifile] << "..." << endl;
        TFile *infile = TFile::Open(infilenamev[ifile]);
        assert(infile);
        TTree *intree = (TTree*)infile->Get("Events");
        assert(intree);

        intree->SetBranchAddress("runNum",   &runNum);    // event run number
        intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
        intree->SetBranchAddress("evtNum",   &evtNum);    // event number
        intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight
        intree->SetBranchAddress("puWeight", &puWeight);  // pileup reweighting
        intree->SetBranchAddress("matchGen", &matchGen);  // event has both leptons matched to MC Z->ll
        intree->SetBranchAddress("category", &category);  // dilepton category
        intree->SetBranchAddress("npv",      &npv);	      // number of primary vertices
        intree->SetBranchAddress("npu",      &npu);	      // number of in-time PU events (MC)
        intree->SetBranchAddress("q1",       &q1);	      // charge of lead lepton
        intree->SetBranchAddress("q2",       &q2);	      // charge of trail lepton
        intree->SetBranchAddress("dilep",    &dilep);     // dilepton 4-vector
        intree->SetBranchAddress("lep1",     &lep1);      // lead lepton 4-vector
        intree->SetBranchAddress("lep2",     &lep2);      // trail lepton 4-vector

        for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
            intree->GetEntry(ientry);

            Double_t weight = 1;
            if(ifile==eMC) {
                //if(!matchGen) continue;
                weight=scale1fb*puWeight*1.1*TMath::Power(10,7)/5610.0;
            }

            if((category!=eMuMu2HLT) && (category!=eMuMu1HLT) && (category!=eMuMu1HLT1L1)) continue;
            if(q1 == q2) continue;
            if(dilep->M()	   < MASS_LOW)  continue;
            if(dilep->M()	   > MASS_HIGH) continue;
            if(lep1->Pt()	   < PT_CUT)    continue;
            if(lep2->Pt()	   < PT_CUT)    continue;
            if(fabs(lep1->Eta()) > ETA_CUT)   continue;
            if(fabs(lep2->Eta()) > ETA_CUT)   continue;

            TLorentzVector vLep1(0,0,0,0);
            TLorentzVector vLep2(0,0,0,0);

            vLep1.SetPtEtaPhiM(lep1->Pt(), lep1->Eta(), lep1->Phi(), MU_MASS);
            vLep2.SetPtEtaPhiM(lep2->Pt(), lep2->Eta(), lep2->Phi(), MU_MASS);

            TLorentzVector vDilep = vLep1 + vLep2;

            Int_t bin1=-1, bin2=-1;
            for(UInt_t i=0; i<scEta_limits.size(); i++) {
                Double_t etalow  = scEta_limits.at(i).first;
                Double_t etahigh = scEta_limits.at(i).second;
                if(fabs(lep1->Eta())>=etalow && fabs(lep1->Eta())<=etahigh) bin1=i;
                if(fabs(lep2->Eta())>=etalow && fabs(lep2->Eta())<=etahigh) bin2=i;
            }
            assert(bin1>=0);
            assert(bin2>=0);
            Int_t ibin= (bin1<=bin2) ? bin1 : bin2;
            Int_t jbin= (bin1<=bin2) ? bin2 : bin1;

            UInt_t n=jbin-ibin;
            for(Int_t k=0; k<ibin; k++)
                n+=(scEta_limits.size()-k);

            if(ifile==eData) hDatav[n]->Fill(vDilep.M(),weight);
            if(ifile==eMC)   hMCv[n]->Fill(vDilep.M(),weight);
        }

        delete infile;
        infile=0, intree=0;
    }

    //
    // Fit for energy scale and resolution corrections
    //
    char vname[100];  // buffer for RooFit object names

    char pname[100];
    char str1[100];
    char str2[100];
    TCanvas *c = MakeCanvas("c","c",800,600);

    // Dummy histograms for TLegend (I can't figure out how to properly pass RooFit objects...)
    TH1D *hDummyData = new TH1D("hDummyData","",0,0,10);
    hDummyData->SetMarkerStyle(kFullCircle);
    hDummyData->SetMarkerSize(0.9);
    TH1D *hDummyMC = new TH1D("hDummyMC","",0,0,10);
    hDummyMC->SetLineColor(kBlue);
    hDummyMC->SetFillColor(kBlue);
    hDummyMC->SetFillStyle(3002);
    TH1D *hDummyFit = new TH1D("hDummyFit","",0,0,10);
    hDummyFit->SetLineColor(kGreen+2);

    RooRealVar mass("mass","M_{#mu#mu}",60.0,120.0,"GeV") ;
    mass.setBins(1600,"cache");

    RooRealVar massmc("massmc","massmc",0.0,150.0,"GeV");  // mass variable for building MC template

    RooCategory zscEta_cat("zscEta_cat","zscEta_cat");
    RooSimultaneous combscalefit("combscalefit","combscalefit",zscEta_cat);

    map<string,TH1*> hmap;  // Mapping of category labels and data histograms

    RooArgList scalebins;   // List of RooRealVars storing per bin energy scale corrections
    RooArgList sigmabins;   // List of RooRealVars storing per bin energy resolution corrections
    Int_t intOrder = 1;     // Interpolation order for
    for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
        sprintf(vname,"scale_%i",ibin);
        RooRealVar *scalebinned = new RooRealVar(vname,vname,1.0,0.5,1.5);
        scalebins.add(*scalebinned);

        sprintf(vname,"sigma_%i",ibin);
        RooRealVar *sigmabinned = new RooRealVar(vname,vname,1.0,0.0,2.0);
        sigmabins.add(*sigmabinned);
    }

    for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
        for(UInt_t jbin=ibin; jbin<scEta_limits.size(); jbin++) {
            UInt_t n=jbin-ibin;
            for(UInt_t k=0; k<ibin; k++)
                n+=(scEta_limits.size()-k);

            sprintf(vname,"masslinearshifted_%i_%i",ibin,jbin);
            RooFormulaVar *masslinearshifted = new RooFormulaVar(vname,vname,"sqrt(@0*@1)",RooArgList(*scalebins.at(ibin),*scalebins.at(jbin)));

            sprintf(vname,"massshiftedscEta_%i_%i",ibin,jbin);
            RooLinearVar *massshiftedscEta = new RooLinearVar(vname,vname,mass,*masslinearshifted,RooConst(0.0));

            // MC-based template
            sprintf(vname,"zmassmcscEta_%i_%i",ibin,jbin);
            RooDataHist *zmassmcscEta = new RooDataHist(vname,vname,RooArgList(massmc),hMCv[n]);
            sprintf(vname,"masstemplatescEta_%i_%i",ibin,jbin);
            RooHistPdf *masstemplatescEta = new RooHistPdf(vname,vname,RooArgList(*massshiftedscEta),RooArgList(massmc),*zmassmcscEta,intOrder);

            // Gaussian smearing function
            sprintf(vname,"sigmascEta_%i_%i",ibin,jbin);
            RooFormulaVar *sigmascEta = new RooFormulaVar(vname,vname,"sqrt(@0*@0+@1*@1)",RooArgList(*sigmabins.at(ibin),*sigmabins.at(jbin)));
            sprintf(vname,"resscEta_%i_%i",ibin,jbin);
            RooGaussian *resscEta = new RooGaussian(vname,vname,mass,RooConst(0.),*sigmascEta);

            // Fit model: MC-template convoluted with Gaussian
            sprintf(vname,"fftscEta_%i_%i",ibin,jbin);
            RooFFTConvPdf *fftscEta = new RooFFTConvPdf(vname,vname,mass,*masstemplatescEta,*resscEta);
            fftscEta->setBufferStrategy(RooFFTConvPdf::Flat);

            // Add bin as a category
            char zscEta_catname[100];
            sprintf(zscEta_catname,"zscEta_cat_%i_%i",ibin,jbin);
            zscEta_cat.defineType(zscEta_catname);
            zscEta_cat.setLabel(zscEta_catname);
            hmap.insert(pair<string,TH1*>(zscEta_catname,hDatav[n]));
            combscalefit.addPdf(*fftscEta,zscEta_catname);
        }
    }

    // perform fit
    RooDataHist zdatascEta_comb("zdatascEta_comb","zdatascEta_comb",RooArgList(mass),zscEta_cat,hmap,1.0);
    combscalefit.fitTo(zdatascEta_comb,PrintEvalErrors(kFALSE),Minos(kFALSE),Strategy(0),Minimizer("Minuit2",""));

    Double_t xval[scEta_limits.size()];
    Double_t xerr[scEta_limits.size()];
    Double_t scaleDatatoMC[scEta_limits.size()];
    Double_t scaleDatatoMCerr[scEta_limits.size()];
    Double_t scaleMCtoData[scEta_limits.size()];
    Double_t scaleMCtoDataerr[scEta_limits.size()];
    Double_t sigmaMCtoData[scEta_limits.size()];
    Double_t sigmaMCtoDataerr[scEta_limits.size()];

    for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
        Double_t etalow  = scEta_limits.at(ibin).first;
        Double_t etahigh = scEta_limits.at(ibin).second;

        xval[ibin] = 0.5*(etahigh+etalow);
        xerr[ibin] = 0.5*(etahigh-etalow);

        scaleDatatoMC[ibin]    = ((RooRealVar*)scalebins.at(ibin))->getVal();
        scaleDatatoMCerr[ibin] = ((RooRealVar*)scalebins.at(ibin))->getError();

        scaleMCtoData[ibin]    = 1.0/scaleDatatoMC[ibin];
        scaleMCtoDataerr[ibin] = scaleDatatoMCerr[ibin]/scaleDatatoMC[ibin]/scaleDatatoMC[ibin];

        sigmaMCtoData[ibin]    = ((RooRealVar*)sigmabins.at(ibin))->getVal();
        sigmaMCtoDataerr[ibin] = ((RooRealVar*)sigmabins.at(ibin))->getError();
    }
    TGraphErrors *grScaleDatatoMC = new TGraphErrors(scEta_limits.size(),xval,scaleDatatoMC,xerr,scaleDatatoMCerr);
    TGraphErrors *grScaleMCtoData = new TGraphErrors(scEta_limits.size(),xval,scaleMCtoData,xerr,scaleMCtoDataerr);
    TGraphErrors *grSigmaMCtoData = new TGraphErrors(scEta_limits.size(),xval,sigmaMCtoData,xerr,sigmaMCtoDataerr);

    CPlot plotScale1("mu_scale_datatomc","","Muon |#eta|","Data scale correction");
    plotScale1.AddGraph(grScaleDatatoMC,"",kBlue);
    plotScale1.SetYRange(0.98,1.02);
    plotScale1.AddLine(0,1,2.5,1,kBlack,7);
    plotScale1.Draw(c,kTRUE,format);

    CPlot plotScale2("mu_scale_mctodata","","Muon |#eta|","MC#rightarrowData scale correction");
    plotScale2.AddGraph(grScaleMCtoData,"",kBlue);
    plotScale2.SetYRange(0.98,1.02);
    plotScale2.AddLine(0,1,2.5,1,kBlack,7);
    plotScale2.Draw(c,kTRUE,format);

    CPlot plotRes("mu_res_mctodata","","Muon |#eta|","MC#rightarrowData additional smear [GeV]");
    plotRes.AddGraph(grSigmaMCtoData,"",kBlue);
    plotRes.SetYRange(0,1.6);
    plotRes.Draw(c,kTRUE,format);

    double nData=0;

    for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
        for(UInt_t jbin=ibin; jbin<scEta_limits.size(); jbin++) {
            UInt_t n=jbin-ibin;
            for(UInt_t k=0; k<ibin; k++)
                n+=(scEta_limits.size()-k);

            // Post-fit plot
            RooPlot *frame = mass.frame();
            char catname[100];
            sprintf(catname,"zscEta_cat_%i_%i",ibin,jbin);
            char cutstr[100];
            sprintf(cutstr,"zscEta_cat==zscEta_cat::%s",catname);
            RooDataHist zmc(catname,catname,RooArgList(mass),hMCv[n]);
            RooHistPdf mctemplate(catname,catname,RooArgList(mass),zmc,intOrder);
            //mctemplate.plotOn(frame,LineColor(kBlue),LineWidth(1),Normalization(hDatav[n]->GetEntries()));
            mctemplate.plotOn(frame,LineColor(kBlue),LineWidth(1),Normalization(hDatav[n]->Integral()));
            //mctemplate.plotOn(frame,LineColor(kBlue),FillColor(kBlue),FillStyle(3002),DrawOption("F"),Normalization(hDatav[n]->GetEntries()));
            mctemplate.plotOn(frame,LineColor(kBlue),FillColor(kBlue),FillStyle(3002),DrawOption("F"),Normalization(hDatav[n]->Integral()));
            zdatascEta_comb.plotOn(frame,Cut(cutstr),MarkerStyle(kFullCircle),MarkerSize(1.0),DrawOption("ZP"));
            combscalefit.plotOn(frame,Slice(zscEta_cat,catname),ProjWData(RooArgSet(mass,catname),zdatascEta_comb),
                                LineColor(kGreen+2));
            sprintf(pname,"postfit_%i_%i",ibin,jbin);
            sprintf(str1,"[%.1f, %.1f]",scEta_limits.at(ibin).first,scEta_limits.at(ibin).second);
            sprintf(str2,"[%.1f, %.1f]",scEta_limits.at(jbin).first,scEta_limits.at(jbin).second);
            CPlot plot(pname,frame,"","m(#mu^{+}#mu^{-}) [GeV/c^{2}]","Events / 0.6 GeV/c^{2}");
            plot.AddTextBox(str1,0.21,0.80,0.45,0.87,0,kBlack,-1);
            plot.AddTextBox(str2,0.21,0.73,0.45,0.80,0,kBlack,-1);
            plot.SetLegend(0.75,0.64,0.93,0.88);
            plot.GetLegend()->AddEntry(hDummyData,"Data","PL");
            plot.GetLegend()->AddEntry(hDummyMC,"Sim","FL");
            plot.GetLegend()->AddEntry(hDummyFit,"Fit","L");
            plot.Draw(c,kTRUE,format);

            nData += hDatav[n]->Integral();
        }
    }

    cout<<"nData = "<<nData<<endl;
    //--------------------------------------------------------------------------------------------------------------
    // Output
    //==============================================================================================================

    cout << "*" << endl;
    cout << "* SUMMARY" << endl;
    cout << "*--------------------------------------------------" << endl;
    cout << endl;

    ofstream txtfile;
    char txtfname[100];
    sprintf(txtfname,"%s/summary.txt",outputDir.Data());
    txtfile.open(txtfname);
    assert(txtfile.is_open());
    txtfile << "  Data->MC scale correction" << endl;
    for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
        Double_t etalow  = scEta_limits.at(ibin).first;
        Double_t etahigh = scEta_limits.at(ibin).second;
        txtfile << "$" << etalow << " < |\\eta| < " << etahigh << "$ & ";
        txtfile << "$" << ((RooRealVar*)scalebins.at(ibin))->getVal() << "$ \\pm $" << ((RooRealVar*)scalebins.at(ibin))->getError() << "$ \\\\" << endl;
    }
    txtfile << endl;
    txtfile << "  MC->Data resolution correction [GeV]" << endl;
    for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
        Double_t etalow  = scEta_limits.at(ibin).first;
        Double_t etahigh = scEta_limits.at(ibin).second;
        txtfile << etalow << " < |\\eta| < " << etahigh << " & ";
        txtfile << "$" << ((RooRealVar*)sigmabins.at(ibin))->getVal() << "$ \\pm $" << ((RooRealVar*)sigmabins.at(ibin))->getError() << "$ \\\\" << endl;
    }
    txtfile.close();

    cout << endl;
    cout << "  <> Output saved in " << outputDir << "/" << endl;
    cout << endl;

}
Ejemplo n.º 9
0
void 
HBB_LEP_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="bb_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("bb_had0"  )){ category_extra = "all-had_{0}";  }
  if(std::string(directory) == std::string("bb_had1"  )){ category_extra = "all-had_{1}";  }
  if(std::string(directory) == std::string("bb_had2"  )){ category_extra = "all-had_{2}";  }
  if(std::string(directory) == std::string("bb_had3"  )){ category_extra = "all-had_{3}";  }
  if(std::string(directory) == std::string("bb_had4"  )){ category_extra = "all-had_{4}";  }
  if(std::string(directory) == std::string("bb_had5"  )){ category_extra = "all-had_{5}";  }
  if(std::string(directory) == std::string("bb_lep"   )){ category_extra = "semi-lep";  }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 7 TeV, L = 4.8 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "Preliminary, #sqrt{s} = 8 TeV, L = 19.4 fb^{-1}";}
  
  TFile* input = new TFile(inputfile);
  TH1F* bkgBBB  = refill((TH1F*)input->Get(TString::Format("%s/bkgBBB"   , directory)), "bkgBBB"); InitHist(bkgBBB, "", "", kMagenta-10, 1001);;
#ifdef MSSM
  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=20, A+H for the time being
  if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (23314.3*0.879 + 21999.3*0.877)/1000.; }
  if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (31087.9*0.879 + 29317.8*0.877)/1000.; }
 //  float bbHScale = 1.; // scenario for MSSM, mhmax, mA=160, tanb=10, A+H for the time being
//   if(std::string(inputfile).find("7TeV")!=std::string::npos){ bbHScale = (6211.6*0.89 + 5145.0*0.85)/1000.; }
//   if(std::string(inputfile).find("8TeV")!=std::string::npos){ bbHScale = (8282.7*0.89 + 6867.8*0.85)/1000.; }
  TH1F* bbH  = refill((TH1F*)input->Get(TString::Format("%s/bbH160"  , directory)), "bbH"  ); InitSignal(bbH); bbH->Scale(bbHScale);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{b#bar{b}} [GeV]}", "#bf{dN/dm_{b#bar{b}} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)bkgBBB->Clone("ref");

  double unscaled[7];
  unscaled[0] = bkgBBB ->Integral();
#ifdef MSSM
  unscaled[1] = bbH ->Integral();
  unscaled[2] = 0;
#endif

  if(scaled){
    rescale(bkgBBB,   1);
#ifdef MSSM 
    rescale(bbH,   2);
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-bkgBBB", "", 3, 0, 3);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (bkgBBB  ->Integral()/unscaled[0]-1.) : 0.);
#ifdef MSSM
  scales[1] = new TH1F("scales-bbH"  , "", 3, 0, 3);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (bbH  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-NONE" , "", 3, 0, 3);
  scales[2]->SetBinContent(3, 0.);
#endif

  if(!log){
#ifdef MSSM
    bbH  ->Add(bkgBBB);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(bkgBBB, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)bkgBBB ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);

  if(log){
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif
  }
  else{  
#ifndef DROP_SIGNAL
    bbH     ->Draw("histsame");
#endif  
    bkgBBB  ->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "b#bar{b}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.17, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText("b#bar{b}");
  chan->Draw();

  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();
 
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m_{A}=160GeV");
  massA->Draw();

  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
  tanb->SetBorderSize(   0 );
  tanb->SetFillStyle(    0 );
  tanb->SetTextAlign(   12 );
  tanb->SetTextSize ( 0.03 );
  tanb->SetTextColor(    1 );
  tanb->SetTextFont (   62 );
  tanb->AddText("tan#beta=20");
  tanb->Draw();

  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
  scen->SetBorderSize(   0 );
  scen->SetFillStyle(    0 );
  scen->SetTextAlign(   12 );
  scen->SetTextSize ( 0.03 );
  scen->SetTextColor(    1 );
  scen->SetTextFont (   62 );
  scen->AddText("mhmax");
  scen->Draw();
#endif


#ifdef MSSM  
  TLegend* leg = new TLegend(0.55, 0.65, 0.94, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(bbH  , "#phi#rightarrowb#bar{b}" , "L" );
#endif
  leg->AddEntry(data,   "observed"                       , "LP");
  leg->AddEntry(bkgBBB, "bkgBBB"                      , "F" );
  $ERROR_LEGEND
  leg->Draw();

//#ifdef MSSM
//  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("(m_{A}=250, tan#beta=5)");
//  mssm->Draw();
//#else
//  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
//  mssm->SetBorderSize(   0 );
//  mssm->SetFillStyle(    0 );
//  mssm->SetTextAlign(   12 );
//  mssm->SetTextSize ( 0.03 );
//  mssm->SetTextColor(    1 );
//  mssm->SetTextFont (   62 );
//  mssm->AddText("m_{H}=125");
//  mssm->Draw();
//#endif

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

  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
  rat1->Divide(bkgBBB);
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
    zero->SetBinContent(ibin+1, 0.);
  }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+1.5);
  rat1->SetMinimum(-1.5);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat1->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv0->RedrawAxis();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  TH1F* rat2 = (TH1F*) bkgBBB->Clone("rat2");
  rat2->Divide(ref);
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  rat2->SetLineColor(kRed+ 3);
  rat2->SetFillColor(kRed-10);
  rat2->SetMaximum(+0.3);
  rat2->SetMinimum(-0.3);
  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{b#bar{b}} [GeV]}");
  rat2->GetXaxis()->SetRange(0, 28);
  rat2->Draw();
  zero->SetLineColor(kBlack);
  zero->Draw("same");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{bkgBBB}");
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{NONE}" );
#endif
  scales[0]->SetMaximum(+1.0);
  scales[0]->SetMinimum(-1.0);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
  zero->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd();
  data ->Write("data_obs");
  bkgBBB  ->Write("bkgBBB"  );
#ifdef MSSM
  bbH  ->Write("bbH"     );
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
Ejemplo n.º 10
0
int newUnfoldBiasStudy
(TString UnfoldFile,TString AcceptFile,TString DataFile,TString BaseName,int idx)
{
  double Bins[NWptBinPlus];
  // Final Bins
  Bins[0] = 0.;
  Bins[1] = 7.5;
  Bins[2] = 12.5;
  Bins[3] = 17.5;
  Bins[4] = 24.;
  Bins[5] = 30.;
  Bins[6] = 40.;
  Bins[7] = 50.;
  Bins[8] = 70.;
  Bins[9] = 110.;
  Bins[10]= 150.;
  Bins[11]= 190.;
  Bins[12]= 250.;
  Bins[13]= 600.;

  double nBins[14]={0,1,2,3,4,5,6,7,8,9,10,11,12,13};

  TString resultDir = "Result"+BaseName;
  gSystem->mkdir(resultDir,kTRUE);
  char tmpName[30];
  TString tmpTStr;
  
  ofstream Fout;
  Fout.open(resultDir+"/Systematics.txt");
  Fout << fixed << setprecision(4);
  
  TFile *f_Unfold    = new TFile(UnfoldFile);
  TFile *f_Accept    = new TFile(AcceptFile);
  TFile *f_Data      = new TFile(DataFile);

  TFile *f_RecoScaleCovMat;
  TFile *f_RecoEffiCovMat;
  TFile *f_RecoSmearCovMat;
  TFile *f_RecoRecoilCovMat;
  TFile *f_RecoQCDRatioCovMat;
  
  TFile *f_RecoAcceptCovMat;
  TFile *f_RecoAcceptFSRCovMat;
  
  if(BaseName == "WpToEleNu" )
  {
    f_RecoScaleCovMat     = new TFile("RecoCovMatrix/Result_WpToEleNu_RecoScaleCovMat.root");
    f_RecoEffiCovMat      = new TFile("RecoCovMatrix/Result_WpToEleNu_RecoEffiCovMat.root");
    f_RecoSmearCovMat     = new TFile("RecoCovMatrix/Result_WpToEleNu_RecoSmearCovMat.root");
    f_RecoRecoilCovMat    = new TFile("RecoCovMatrix/Result_WpToEleNu_RecoRecoilCovMat.root");
    f_RecoAcceptCovMat    = new TFile("RecoCovMatrix/Ele_WpToEleNu_S8_Acceptance.root");
    f_RecoAcceptFSRCovMat = new TFile("RecoCovMatrix/Ele_WpToEleNu_S8_AcceptanceFSR.root");
  }else if(BaseName == "WmToEleNu"){
    f_RecoScaleCovMat     = new TFile("RecoCovMatrix/Result_WmToEleNu_RecoScaleCovMat.root");
    f_RecoEffiCovMat      = new TFile("RecoCovMatrix/Result_WmToEleNu_RecoEffiCovMat.root");
    f_RecoSmearCovMat     = new TFile("RecoCovMatrix/Result_WmToEleNu_RecoSmearCovMat.root");
    f_RecoRecoilCovMat    = new TFile("RecoCovMatrix/Result_WmToEleNu_RecoRecoilCovMat.root");
    f_RecoAcceptCovMat    = new TFile("RecoCovMatrix/Ele_WmToEleNu_S8_Acceptance.root");
    f_RecoAcceptFSRCovMat = new TFile("RecoCovMatrix/Ele_WmToEleNu_S8_AcceptanceFSR.root");
  }else if(BaseName == "WpToMuNu"){
    f_RecoEffiCovMat      = new TFile("RecoCovMatrix/Result_WpToMuNu_RecoEffiCovMat.root");
    f_RecoSmearCovMat     = new TFile("RecoCovMatrix/Result_WpToMuNu_RecoSmearCovMat.root");
    f_RecoRecoilCovMat    = new TFile("RecoCovMatrix/Result_WpToMuNu_RecoRecoilCovMat.root");
    f_RecoAcceptCovMat    = new TFile("RecoCovMatrix/Muon_WpToMuNu_S8_Acceptance.root");
    f_RecoAcceptFSRCovMat = new TFile("RecoCovMatrix/Muon_WpToMuNu_S8_AcceptanceFSR.root");
    f_RecoQCDRatioCovMat  = new TFile("RecoCovMatrix/Result_WpToMuNu_RecoQCDRatioCovMat.root");
  }else if(BaseName == "WmToMuNu"){
    f_RecoEffiCovMat      = new TFile("RecoCovMatrix/Result_WmToMuNu_RecoEffiCovMat.root");
    f_RecoSmearCovMat     = new TFile("RecoCovMatrix/Result_WmToMuNu_RecoSmearCovMat.root");
    f_RecoRecoilCovMat    = new TFile("RecoCovMatrix/Result_WmToMuNu_RecoRecoilCovMat.root");
    f_RecoAcceptCovMat    = new TFile("RecoCovMatrix/Muon_WmToMuNu_S8_Acceptance.root");
    f_RecoAcceptFSRCovMat = new TFile("RecoCovMatrix/Muon_WmToMuNu_S8_AcceptanceFSR.root");
    f_RecoQCDRatioCovMat  = new TFile("RecoCovMatrix/Result_WmToMuNu_RecoQCDRatioCovMat.root");
  }
  
  TFile *f_RecoLumiUpCovMat;
  TFile *f_RecoLumiDownCovMat;
  
  f_RecoLumiUpCovMat   = new TFile("RecoCovMatrix/SigYields_Lumi_Up.root");
  f_RecoLumiDownCovMat = new TFile("RecoCovMatrix/SigYields_Lumi_Down.root");
  
  TH1D* h1_SigWptLumiUp;
  TH1D* h1_SigWptLumiDown;
  TH1D *h1_Post_BothFidAccept;
  TH1D *h1_Post_BothFidAcceptFSR;

  TFile *f_Eff    = new TFile("ResultUnfEff/eff.root");
  tmpTStr = resultDir+"/Result_"+BaseName+".root";
  TFile *f_Out    = new TFile(tmpTStr,"recreate");

  // SVD input
  struct histSVD{
    TH2D *Adet;
    TH2D *uAdetCov[nToy];
    TH1D *xini; // Post True
    TH1D *bini; // Reco Truth
    TH1D *data[nToy];
    TH1D *True;
    TH1D *Gen;
    TH1D *EffCorr[nToy];
    TH2D *statCov;
    TH1D *unfRes[nToy];
    TH1D *dDist[nToy];
    TH1D *svDist[nToy];
    TH1D *DetUnf[nToy];
    TH1D *FSRUnf[nToy];
    TH1D *Corr[nToy];
    TH2D *uTotalCovMat;
    TH2D *uTotalSystCov;
    TH2D *uStatCov;
    TH2D *uTauCov[nToy];
    TH2D *uInvCov;

    TH2D *BstatCorr_uTotal; //Total Correlation Matrix
    TH2D *AbsNormCorrErr; //Absolute Normilazed Correlated Error Matrix
    
    TH2D *RecoEffiCovMat;
    TH2D *RecoScaleCovMat;
    TH2D *RecoSmearCovMat;
    TH2D *RecoRecoilCovMat;
    TH2D *RecoLumiCovMat;
    TH2D *RecoStatisticCovMat;
    TH2D *RecoQCDRatioCovMat;
    TH2D *TotalRecoCovMat;
    TH2D *ToyRecoCovMat[nToy];
    TH2D *ToyStatCovMat[nToy];

    TH2D *InputCovMat; //Input Covariance Matrix for FSR Unfolding
    TH2D *uInputCovMat;//Input Covariance Matrix after FSR Unfolding
    
    TH2D *uRecoEffiCovMat;
    TH2D *uRecoScaleCovMat;
    TH2D *uRecoSmearCovMat;
    TH2D *uRecoRecoilCovMat;
    TH2D *uRecoLumiCovMat;
    TH2D *uRecoStatisticCovMat;
    TH2D *uRecoQCDRatioCovMat;
    TH2D *uRecoRespCovMat;

    TH2D *uTotalRecoCovMat;
    TH2D *AcceptFSRCovMat;
    TH2D *MCEventEffFSRCovMat[nToy]; //Make FSR Covariance Matrix from MC Eff.
    TH2D *uMCEventEffFSRCovMat;

    TH2D *Eff_uRecoEffiCovMat;
    TH2D *Eff_uRecoScaleCovMat;
    TH2D *Eff_uRecoSmearCovMat;
    TH2D *Eff_uRecoRecoilCovMat;
    TH2D *Eff_uRecoLumiCovMat;
    TH2D *Eff_uMCEventEffFSRCovMat;
    TH2D *Eff_uRecoStatisticCovMat;
    TH2D *Eff_DetectUnfStatisticCovMat;
    TH2D *Eff_uRecoQCDRatioCovMat;
    TH2D *Eff_uRecoRespCovMat;

    TH2D *Eff_uTauCov;
    
    TH2D *Eff_uTotalRecoCovMat;
    TH2D *Eff_uTotalRecoCovMatEff;
  };
  histSVD SVD_Post;
  histSVD SVD_Born;

  // Efficiency
  TH1D* h1_Post_BothOvTruth; 
  TH1D* h1_Post_BothOvTruth_eqBin; 
  TH1D* h1_Born_BothOvBorn; 
  TH1D* h1_Born_BothOvBorn_eqBin; 
  TH1D* h1_Post_BothOvTruth_weightFSR; 
  TH1D* h1_Post_BothOvTruth_weightFSR_eqBin; 
  
  // Unfolding to Post
  TH1D *h1_Truth_Rec;
  TH1D *h1_Truth_Rec_Even;
  TH1D *h1_Truth_Rec_Odd;
  TH1D *h1_Truth_Post;
  TH1D *h1_Truth_Post_Lumi;
  TH1D *h1_Truth_Post_Even;
  TH1D *h1_Truth_Post_Odd;
  TH2D *h2_Truth_Rec_AP_Post;
  TH2D *h2_Truth_Rec_AP_Post_Ivs;
  TH2D *h2_Truth_Rec_AP_PostEffCorr;
  TH1D *h1_Unfolded_Post_InvMthd;
  TH1D *EqBin_Truth_Rec_Even;

  // Acceptance
  TH1D*	h1_Born_AP;
  TH1D*	h1_Born_BornFid;
  TH1D*	h1_Born_BornFid_Even;
  TH1D*	h1_Born_BornFid_Lumi;
  TH1D*	h1_Born_BothFid;
  TH1D*	h1_Born_BothFid_Lumi;

  TH1D*	h1_Post_PostFid;
  TH1D*	h1_Post_PostFid_Even;
  TH1D*	h1_Post_PostFid_Lumi; // Lumi weighted
  TH1D*	h1_Post_BothFid;
  TH1D*	h1_Post_BothFid_Lumi;
  TH2D*	h2_PostBorn_BothFid;
  TH1D* EqBin_Post_PostFid_Even;

  // Data
  double TotalStat[NWptBinPlus]={0.};
  double TotalError[NWptBinPlus]={0.};
  double TotalUncertErr[NWptBinPlus]={0.};
  
  double dUnf_SVD[NWptBinPlus-1]={0.};
  double FSRUnf_SVD[NWptBinPlus-1]={0.};
  double Unf_SVD[NWptBinPlus-1]={0.};
  
  TH1D* h1_Data_SigYild;
  
  // Define Histo
  h1_Post_BothOvTruth_eqBin=
    new TH1D("h1_Post_BothOvTruth_eqBin","BothOvTruth",NWptBinPlus-1,0,NWptBinPlus-1);
  h1_Post_BothOvTruth_weightFSR_eqBin=
    new TH1D("h1_Post_BothOvTruth_weightFSR_eqBin","BothOvTruth_weightFSR",NWptBinPlus-1,0,NWptBinPlus-1);
  h1_Born_BothOvBorn_eqBin=
    new TH1D("h1_Born_BothOvBorn_eqBin","BothOvBorn",NWptBinPlus-1,0,NWptBinPlus-1);
  
  SVD_Post.xini = new TH1D("xini_Post","Post true",NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.bini = new TH1D("bini_Post","Reco thruth" ,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.True = new TH1D("SVD_Post.True","SVD_Post.True",NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Gen  = new TH1D("SVD_Post.Gen","SVD_Post.Gen",NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Adet = new TH2D("Adet_Post","detector response"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.statCov = new TH2D("SVD_Post.statCov","Covariance matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.BstatCorr_uTotal = new TH2D("SVD_Post.BstatCorr_uTotal","Total Correlation matrix after D_Unf"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.AbsNormCorrErr = new TH2D("SVD_Post.AbsNormCorrErr","Absolute Normalized Covariance Error Matrix D_Unf"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.AbsNormCorrErr = new TH2D("SVD_Born.AbsNormCorrErr","Absolute Normalized Covariance Error Matrix FSR_Unf"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.RecoEffiCovMat = new TH2D("SVD_Post.RecoEffiCovMat","Reco Stage Effi Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  TH2D* h2_RecoEffiCovMat = new TH2D("h2_RecoEffiCovMat","Reco Stage Effi Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uRecoEffiCovMat = new TH2D("SVD_Post.Eff_uRecoEffiCovMat","Eff applied Effi Covariace matrix Detector unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.uRecoEffiCovMat = new TH2D("SVD_Born.uRecoEffiCovMat","Born Effi Covariace matrix Post to Born"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.RecoScaleCovMat = new TH2D("SVD_Post.RecoScaleCovMat","Reco Stage Scale Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  TH2D* h2_RecoScaleCovMat = new TH2D("h2_RecoScaleCovMat","Reco Stage Scale Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uRecoScaleCovMat = new TH2D("SVD_Post.Eff_uRecoScaleCovMat","Eff applied Scale Covariace matrix Detector unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.RecoSmearCovMat = new TH2D("SVD_Post.RecoSmearCovMat","Reco Stage Smear Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  TH2D* h2_RecoSmearCovMat = new TH2D("h2_RecoSmearCovMat","Reco Stage Smear Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uRecoSmearCovMat = new TH2D("SVD_Post.Eff_uRecoSmearCovMat","Effi applied Smear Covariace matrix Detector unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.RecoRecoilCovMat = new TH2D("SVD_Post.RecoRecoilCovMat","Reco Stage Recoil Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  TH2D* h2_RecoRecoilCovMat = new TH2D("h2_RecoRecoilCovMat","Reco Stage Recoil Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uRecoRecoilCovMat = new TH2D("SVD_Post.Eff_uRecoRecoilCovMat","Eff apllied Recoil Covariace matrix Detector unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.RecoLumiCovMat = new TH2D("SVD_Post.RecoLumiCovMat","Reco Stage Lumi Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  TH2D* h2_RecoQCDRatioCovMat = new TH2D("h2_RecoQCDRatioCovMat","Reco Stage QCD ratio Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.RecoQCDRatioCovMat = new TH2D("SVD_Post.RecoQCDRatioCovMat","Reco QCD ratio Covariace matrix "
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.uRecoQCDRatioCovMat = new TH2D("SVD_Post.uRecoQCDRatioCovMat","Reco QCD ratio Covariace matrix "
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uRecoQCDRatioCovMat = new TH2D("SVD_Post.Eff_uRecoQCDRatioCovMat","Eff applied QCD ratio Covariace matrix Detector unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uRecoRespCovMat = new TH2D("SVD_Post.Eff_uRecoRespCovMat","Eff apllied Response Covariace matrix after Detector unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uMCEventEffFSRCovMat = new TH2D("SVD_Post.Eff_uMCEventEffFSRCovMat","Eff applied FSR Covariace matrix Detector unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.AcceptFSRCovMat = new TH2D("SVD_Post.AcceptFSRCovMat","FSR CovMat from Acceptance h1_Post_BothFid"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.RecoStatisticCovMat = new TH2D("SVD_Post.RecoStatisticCovMat","Reco Stage Statistic Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uRecoStatisticCovMat = new TH2D("SVD_Post.Eff_uRecoStatisticCovMat","Effi applied Statistic Covariace matrix Deterctor unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_DetectUnfStatisticCovMat = new TH2D("SVD_Post.Eff_DetectUnfStatisticCovMat","Effi applied StatCovMat from Detector Unf"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.TotalRecoCovMat = new TH2D("SVD_Post.TotalRecoCovMat","Total Reco Stage Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.uTotalRecoCovMat = new TH2D("SVD_Post.uTotalRecoCovMat","Total Covariace matrix Detector unfilding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uTotalRecoCovMat = new TH2D("SVD_Post.Eff_uTotalRecoCovMat","Effi applied Total Covariace matrix Detector ufolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uTotalRecoCovMatEff = new TH2D("SVD_Post.Eff_uTotalRecoCovMatEff","Effi applied Total Covariace matrix Detector ufolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.uTotalCovMat = new TH2D("SVD_Born.uTotalCovMat","Total Covariace matrix after FSR unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.InputCovMat = new TH2D("SVD_Born.InputCovMat","Input Covariace matrix for FSR unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.uInputCovMat = new TH2D("SVD_Born.uInputCovMat","Input Covariace matrix after FSR unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Post.Eff_uTauCov = new TH2D("SVD_Post.Eff_uTauCov","Effi applied uTauCov Deterctor unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.uRecoRespCovMat =  new TH2D("SVD_Born.uRecoRespCovMat","Eff apllied Response Covariace matrix after FSR unfolding"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.xini = new TH1D("xini_Born","Born xini",NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.bini = new TH1D("bini_Born","Post" ,NWptBinPlus-1,0,NWptBinPlus-1);
  //SVD_Born.data = new TH1D("data_Born","data_Rec"    ,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.True = new TH1D("SVD_Born.True","Born.True",NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.Gen  = new TH1D("SVD_Born.Gen","Born.Gen",NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.Adet = new TH2D("Adet_Born","detector response",NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
  SVD_Born.statCov = new TH2D("SVD_Born.statCov","Covariance matrix",NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);

  // Plot
  CPlot *pltBinByBinCorr;
  CPlot *pltSVD_EffCorr;
  
  CPlot *pltUnfPost;
  CPlot *pltUnfPost_InputCov;

  CPlot *pltUnfPost_uTotalCov;
  CPlot *pltUnfPost_uTotalSystCov;
  CPlot *pltUnfPost_uRespMatrix;
  CPlot *pltUnfPost_AbsNormCorrErr;
  CPlot *pltUnfBorn_AbsNormCorrErr;
  CPlot *pltUnfBorn_uTotalCov;
  CPlot *pltUnfBorn_InputCov;
  
  CPlot *pltRecoStatCov;
  CPlot *pltRecoEffCov;
  CPlot *pltRecoRecoilCov;
  CPlot *pltRecoScaleCov;
  CPlot *pltRecoSmearCov;
  CPlot *pltRecoQCDRatioCov;
  CPlot *pltRecoFSRCov;
  CPlot *pltEffFSRCov;
  
  CPlot *plt_uInputCovMat;

  CPlot *pltReconEffi_cov;
  CPlot *pltReconScale_cov;
  CPlot *pltReconSmear_cov;
  CPlot *pltReconRecoil_cov;
  CPlot *pltReconLumi_cov;
  CPlot *pltReconFSR_cov;
  CPlot *pltReconQCDRatio_cov;
 
  CPlot *pltRecon_corr;
  CPlot *plt_DUnf_RespCov;
  
  CPlot *pltUnfPost_d;
  CPlot *pltUnfBorn;
  CPlot *pltUnfBorn_cov;
  CPlot *pltUnfBorn_d;
  TCanvas *myCan = MakeCanvas("myCan","myCan",900,800);


  char legendName[30];

  //=====================
  // Histo from Unfolding
  //=====================
  sprintf(tmpName,"h1_Truth_Rec");
  h1_Truth_Rec = (TH1D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  h1_Truth_Rec->Sumw2();

  sprintf(tmpName,"h1_Truth_Rec_Even");
  h1_Truth_Rec_Even = (TH1D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  h1_Truth_Rec_Even->Sumw2();

  sprintf(tmpName,"h1_Truth_Rec_Odd");
  h1_Truth_Rec_Odd = (TH1D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  h1_Truth_Rec_Odd->Sumw2();

  sprintf(tmpName,"h1_Truth_Post");
  h1_Truth_Post = (TH1D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  h1_Truth_Post->Sumw2();
  sprintf(tmpName,"h1_Truth_Post_Lumi");
  h1_Truth_Post_Lumi = (TH1D*)h1_Truth_Post->Clone(tmpName);
  h1_Truth_Post_Lumi->Sumw2();
  sprintf(tmpName,"h1_Truth_Post_Even");
  h1_Truth_Post_Even = (TH1D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  h1_Truth_Post_Even->Sumw2();
  sprintf(tmpName,"h1_Truth_Post_Odd");
  h1_Truth_Post_Odd = (TH1D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  h1_Truth_Post_Odd->Sumw2();

  sprintf(tmpName,"h2_Truth_Rec_AP_Post");
  h2_Truth_Rec_AP_Post=(TH2D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  InitHist2D(h2_Truth_Rec_AP_Post);
  h2_Truth_Rec_AP_Post->Sumw2();

  sprintf(tmpName,"h2_Truth_Rec_AP_PostEffCorr");
  h2_Truth_Rec_AP_PostEffCorr=(TH2D*)f_Unfold->Get(tmpName)->Clone(tmpName);
  InitHist2D(h2_Truth_Rec_AP_PostEffCorr);
  h2_Truth_Rec_AP_PostEffCorr->Sumw2();
  
  int nbins = h1_Truth_Rec->GetNbinsX();
  //Fout<<"Nsimul N of bins: "<<nbins<<endl;
  double Nsimul = h1_Truth_Rec->Integral();
  //Fout<<"Total Events: "<<setw(20)<<setprecision(7)<<Nsimul<<endl;
  double NsimulEven = h1_Truth_Rec_Even->Integral();
  //Fout<<"NsimulEven: "<<setw(20)<<setprecision(7)<<NsimulEven<<endl;
  double NsimulOdd = h1_Truth_Rec_Odd->Integral();
  //Fout<<"NsimulOdd: "<<setw(20)<<setprecision(7)<<NsimulOdd<<endl;
  double NdetectorResponse = h2_Truth_Rec_AP_Post->Integral();
  double NdetectorResponseEffCorr = h2_Truth_Rec_AP_Post->Integral();
  //Fout<<"NdetectorResponse: "<<NdetectorResponse<<endl;
  //Fout<<"NdetectorResponseEffCorr: "<<NdetectorResponseEffCorr<<endl;
  //======================
  // Histo from Acceptance 
  //======================
  sprintf(tmpName,"h1_Born_AP");
  h1_Born_AP		=(TH1D*)f_Accept->Get(tmpName)->Clone(tmpName);
  sprintf(tmpName,"h1_Born_BornFid");
  h1_Born_BornFid	=(TH1D*)f_Accept->Get(tmpName)->Clone(tmpName);
  h1_Born_BornFid_Lumi=(TH1D*)h1_Born_BornFid->Clone("h1_Born_BornFid_Lumi");
  h1_Born_BornFid_Lumi->Sumw2();
  sprintf(tmpName,"h1_Born_BornFid_Even");
  h1_Born_BornFid_Even	=(TH1D*)f_Accept->Get(tmpName)->Clone(tmpName);
  sprintf(tmpName,"h1_Born_BothFid");
  h1_Born_BothFid	=(TH1D*)f_Accept->Get(tmpName)->Clone(tmpName);
  sprintf(tmpName,"h1_Born_BothFid_Lumi");
  h1_Born_BothFid_Lumi	=(TH1D*)h1_Born_BothFid->Clone(tmpName);

  sprintf(tmpName,"h1_Post_PostFid");
  h1_Post_PostFid	=(TH1D*)f_Accept->Get(tmpName)->Clone(tmpName);
  h1_Post_PostFid_Lumi	=(TH1D*)h1_Post_PostFid->Clone("h1_Post_PostFid_Lumi");
  h1_Post_PostFid_Lumi->Sumw2();

  sprintf(tmpName,"h1_Post_BothFid");
  h1_Post_BothFid	=(TH1D*)f_Accept->Get(tmpName)->Clone(tmpName);
  sprintf(tmpName,"h1_Post_BothFid_Lumi");
  h1_Post_BothFid_Lumi	=(TH1D*)h1_Post_BothFid->Clone(tmpName);
  h1_Post_BothFid_Lumi->Sumw2();
  sprintf(tmpName,"h2_PostBorn_BothFid");
  h2_PostBorn_BothFid	=(TH2D*)f_Accept->Get(tmpName)->Clone(tmpName);

  if(BaseName == "WpToMuNu")
  {
    h1_Truth_Post_Lumi  ->Scale(LumiWeight_Muon_WpToMuNu_S8);
    h1_Post_PostFid_Lumi->Scale(LumiWeight_Muon_WpToMuNu_S8);
    h1_Post_BothFid_Lumi->Scale(LumiWeight_Muon_WpToMuNu_S8);
    h1_Born_BornFid_Lumi->Scale(LumiWeight_Muon_WpToMuNu_S8);
    h1_Born_BothFid_Lumi->Scale(LumiWeight_Muon_WpToMuNu_S8);
    sprintf(tmpName,"h1_WpMu_BothOvTruth");
    h1_Post_BothOvTruth = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WpMu_BothOvTruth_weightFSR");
    h1_Post_BothOvTruth_weightFSR = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WpMu_BothOvBorn");
    h1_Born_BothOvBorn = (TH1D*)f_Eff->Get(tmpName)->Clone();
  }
  else if(BaseName == "WmToMuNu")
  {
    h1_Truth_Post_Lumi  ->Scale(LumiWeight_Muon_WmToMuNu_S8);
    h1_Post_PostFid_Lumi->Scale(LumiWeight_Muon_WmToMuNu_S8);
    h1_Post_BothFid_Lumi->Scale(LumiWeight_Muon_WmToMuNu_S8);
    h1_Born_BornFid_Lumi->Scale(LumiWeight_Muon_WmToMuNu_S8);
    h1_Born_BothFid_Lumi->Scale(LumiWeight_Muon_WmToMuNu_S8);
    sprintf(tmpName,"h1_WmMu_BothOvTruth");
    h1_Post_BothOvTruth = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WmMu_BothOvTruth_weightFSR");
    h1_Post_BothOvTruth_weightFSR = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WmMu_BothOvBorn");
    h1_Born_BothOvBorn = (TH1D*)f_Eff->Get(tmpName)->Clone();
  }
  else if(BaseName == "WpToEleNu")
  {
    h1_Truth_Post_Lumi->  Scale(LumiWeight_Ele_WpToEleNu_S8);
    h1_Post_PostFid_Lumi->Scale(LumiWeight_Ele_WpToEleNu_S8);
    h1_Post_BothFid_Lumi->Scale(LumiWeight_Ele_WpToEleNu_S8);
    h1_Born_BornFid_Lumi->Scale(LumiWeight_Ele_WpToEleNu_S8);
    h1_Born_BothFid_Lumi->Scale(LumiWeight_Ele_WpToEleNu_S8);
    sprintf(tmpName,"h1_WpEl_BothOvTruth");
    h1_Post_BothOvTruth = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WpEl_BothOvTruth_weightFSR");
    h1_Post_BothOvTruth_weightFSR = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WpEl_BothOvBorn");
    h1_Born_BothOvBorn = (TH1D*)f_Eff->Get(tmpName)->Clone();
  }
  else if(BaseName == "WmToEleNu")
  {
    h1_Truth_Post_Lumi->  Scale(LumiWeight_Ele_WmToEleNu_S8);
    h1_Post_PostFid_Lumi->Scale(LumiWeight_Ele_WmToEleNu_S8);
    h1_Post_BothFid_Lumi->Scale(LumiWeight_Ele_WmToEleNu_S8);
    h1_Born_BornFid_Lumi->Scale(LumiWeight_Ele_WmToEleNu_S8);
    h1_Born_BothFid_Lumi->Scale(LumiWeight_Ele_WmToEleNu_S8);
    sprintf(tmpName,"h1_WmEl_BothOvTruth");
    h1_Post_BothOvTruth = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WmEl_BothOvTruth_weightFSR");
    h1_Post_BothOvTruth_weightFSR = (TH1D*)f_Eff->Get(tmpName)->Clone();
    sprintf(tmpName,"h1_WmEl_BothOvBorn");
    h1_Born_BothOvBorn = (TH1D*)f_Eff->Get(tmpName)->Clone();
  }
  else{
    cout<<"Error: there is no BaseName corresponding to "<<BaseName<<endl;
    exit(-1);
  }

  // Histogram from Data
  if(BaseName == "WpToMuNu" || BaseName == "WpToEleNu")
  {
    sprintf(tmpName,"hSigWPpt");
    h1_Data_SigYild = (TH1D*)f_Data->Get(tmpName)->Clone(tmpName);
  }else if(BaseName == "WmToMuNu" || BaseName == "WmToEleNu")
  {
    sprintf(tmpName,"hSigWMpt");
    h1_Data_SigYild = (TH1D*)f_Data->Get(tmpName)->Clone(tmpName);
  }else{
    cout<<"Error: Check the BaseName !!!!!!!!!!!!!!!!!!!!!!!!"<<endl;
    exit(-1);
  }

  double RDNumb = h1_Data_SigYild->Integral();
  //Fout<<"Real Data: "<<RDNumb<<endl;

   // Histo for SVD
  double checkNumber(0);

  for(int i(1);i<=nbins;i++)
  {
    h1_Post_BothOvTruth_eqBin -> SetBinContent(i,h1_Post_BothOvTruth->GetBinContent(i));
    h1_Post_BothOvTruth_eqBin -> SetBinError(i,h1_Post_BothOvTruth->GetBinError(i));
    h1_Born_BothOvBorn_eqBin -> SetBinContent(i,h1_Born_BothOvBorn->GetBinContent(i));
    h1_Born_BothOvBorn_eqBin -> SetBinError(i,h1_Born_BothOvBorn->GetBinError(i));
  }

  //=================================================================
  //=================================================================
  // Unfolding from Rec to Post           ===========================
  //=================================================================
  //=================================================================
  //
  //=====================
  // TSVD
  //=====================
  TRandom3 R;
  //===============
  // Data Unfolding
  //===============
  
  SVD_Post.RecoEffiCovMat =(TH2D*)f_RecoEffiCovMat->Get("h2_RecoEffiCovMat")->Clone();
  SVD_Post.RecoSmearCovMat =(TH2D*)f_RecoSmearCovMat->Get("h2_RecoSmearCovMat")->Clone();
  SVD_Post.RecoRecoilCovMat =(TH2D*)f_RecoRecoilCovMat->Get("h2_RecoRecoilCovMat")->Clone();
  if(BaseName == "WpToMuNu" || BaseName == "WmToMuNu" )
    SVD_Post.RecoQCDRatioCovMat =(TH2D*)f_RecoQCDRatioCovMat->Get("h2_RecoQCDRatioCovMat")->Clone();
  if(BaseName == "WpToEleNu" || BaseName == "WmToEleNu" )
    SVD_Post.RecoScaleCovMat =(TH2D*)f_RecoScaleCovMat->Get("h2_RecoScaleCovMat")->Clone();
  
  SVD_Post.TotalRecoCovMat->Add(SVD_Post.RecoEffiCovMat );
  SVD_Post.TotalRecoCovMat->Add(SVD_Post.RecoSmearCovMat );
  SVD_Post.TotalRecoCovMat->Add(SVD_Post.RecoRecoilCovMat );
  if(BaseName == "WpToEleNu" || BaseName == "WmToEleNu" )
    SVD_Post.TotalRecoCovMat->Add(SVD_Post.RecoScaleCovMat );

  //=================================================================
  // Poisson distribution
  //=================================================================
  
  CPlot *pltPoisson;

  TSVDUnfold *tsvdData[nToy];
  TSVDUnfold *svdBorn[nToy];
  
  RooRealVar x("x","", 0,600);
  
  RooRealVar c1("c1","",0.1,-1,1);
  RooRealVar c2("c2","",0.1,-1,1);
  RooRealVar c3("c3","",0.1,-1,1);
  RooRealVar c4("c4","",0.1,-1,1);
  
  RooRealVar d1("d1","",0.1,-1,1);
  RooRealVar d2("d2","",0.1,-1,1);
  RooRealVar d3("d3","",0.1,-1,1);
  RooRealVar d4("d4","",0.1,-1,1);


  if(BaseName == "WpToMuNu"){
    c1.setVal(-0.364042 );
    c2.setVal(0.0572473 );
    c3.setVal(-0.0042756 );
    c4.setVal(0.000121166 );
    d1.setVal(-0.366776);
    d2.setVal(0.0578532);
    d3.setVal(-0.00432019);
    d4.setVal(0.000122256);
  }else if (BaseName == "WmToMuNu" ){
    c1.setVal(-0.350896 );
    c2.setVal(0.0540635 );
    c3.setVal(-0.00401806 );
    c4.setVal(0.000114203 );
    d1.setVal(-0.35391);
    d2.setVal(0.0547905);
    d3.setVal(-0.00407681);
    d4.setVal(0.000115792);
  }else if (BaseName == "WpToEleNu" ){
    c1.setVal(-0.351337);
    c2.setVal(0.0544906 );
    c3.setVal(-0.00408053 );
    c4.setVal(0.000116708 );
    d1.setVal(-0.370515);
    d2.setVal(0.0589071);
    d3.setVal(-0.00441764);
    d4.setVal(0.000125221);
  }else if (BaseName == "WmToEleNu" ){
    c1.setVal(-0.338061);
    c2.setVal(0.0512756 );
    c3.setVal(-0.00381884 );
    c4.setVal(0.000109534 );
    d1.setVal(-0.360669);
    d2.setVal(0.0567861);
    d3.setVal(-0.00426745);
    d4.setVal(0.000121726);
  }
  c1.setConstant(kTRUE);
  c2.setConstant(kTRUE);
  c3.setConstant(kTRUE);
  c4.setConstant(kTRUE);
  d1.setConstant(kTRUE);
  d2.setConstant(kTRUE);
  d3.setConstant(kTRUE);
  d4.setConstant(kTRUE);
  
  RooPolynomial DetPoly("DetPoly", "", x, RooArgList(c1,c2,c3,c4));
  RooPolynomial FSRPoly("FSRPoly", "", x, RooArgList(d1,d2,d3,d4));

  TH1D* hGenFSR;
  TH1D* hGenFSRNorm;
  
  //RooBinning myBins(13,Bins);
  RooBinning myBins(13,nBins);
  hGenFSR = (TH1D*)(FSRPoly.createHistogram("hGenFSR",x,Binning(myBins))); //GenLevel

  double Nfsr = hGenFSR->Integral();
  hGenFSR->Scale(h1_Post_BothFid->Integral()/Nfsr);
  hGenFSR->SetTitle("");
  hGenFSR->Write();

  //Response Matrix
  TMatrixD dResponseMatrix(nbins,nbins);
  TMatrixD fsrResponseMatrix(nbins,nbins);
  double temp1[nbins];
  double temp2[nbins];

  for(int i(1);i<=nbins;i++)
  {
    for( int j(1);j<=nbins;j++)
    {
      SVD_Post.Adet->SetBinContent(i,j,h2_Truth_Rec_AP_PostEffCorr->GetBinContent(i,j));
      dResponseMatrix(i-1,j-1) = h2_Truth_Rec_AP_PostEffCorr->GetBinContent(i,j);
      
      SVD_Born.Adet->SetBinContent(i,j,h2_PostBorn_BothFid->GetBinContent(i,j));
      fsrResponseMatrix(i-1,j-1) = h2_PostBorn_BothFid->GetBinContent(i,j);
    }
  }
  
  for(int i(0);i<nbins;i++)
  {
    temp1[i] = 0.;
    temp2[i] = 0.;
    for( int j(0);j<nbins;j++)
    {
      temp1[i] += dResponseMatrix(j,i);
      temp2[i] += fsrResponseMatrix(j,i);
    }
  }

  for(int i(0);i<nbins;i++)
  {
    for( int j(0);j<nbins;j++)
    {
      dResponseMatrix(i,j) /= temp1[j];
      fsrResponseMatrix(i,j) /= temp2[j];
    }
  }

  TH1D* hFSR = new TH1D("hFSR","hFSR",13,0,13);//FSR Distribution
  TH1D* hFSR_Det_Fold = new TH1D("hFSR_Det_Fold","hFSR_Det_Fold",13,0,13);//FSR Distribution
  TH1D* hToy;
  
  TH1D* hDetNRespM;
 
  double tmp;
 
//FSR Folding Gen.Level
  for(int i(1);i<=h1_Data_SigYild->GetNbinsX();i++)
  {
    tmp = 0.0;
    for(int j(1);j<=h1_Data_SigYild->GetNbinsX();j++)
    {
      tmp += fsrResponseMatrix(i-1,j-1)*hGenFSR->GetBinContent(j);
    }
    hFSR->SetBinContent(i,tmp);
    
    SVD_Born.xini->SetBinContent(i,hGenFSR->GetBinContent(i));
    SVD_Born.xini->SetBinError(i,hGenFSR->GetBinError(i));
    
    SVD_Born.bini->SetBinContent(i,hFSR->GetBinContent(i));
    SVD_Born.bini->SetBinError(i,hFSR->GetBinError(i));
  }
  hFSR->Write();
  
  hGenFSRNorm = (TH1D*)hGenFSR->Clone("hGenFSRNorm");
  hGenFSRNorm->Scale(h1_Data_SigYild->Integral()/hGenFSRNorm->Integral());
  hGenFSRNorm->Write();

//Normalize FSR Folded hFSR to the Det.Unf.Resp.Matrix numbers
  hDetNRespM = (TH1D*)hFSR->Clone("hDetNRespM");
  hDetNRespM->Scale(h1_Truth_Rec->Integral()/hDetNRespM->Integral());
  
//Det. Folding "hFSR" - the result of FSR Folding
  for(int i(1);i<=h1_Data_SigYild->GetNbinsX();i++)
  {
    tmp = 0.0;
    for(int j(1);j<=h1_Data_SigYild->GetNbinsX();j++)
    {
      tmp += dResponseMatrix(i-1,j-1)*hDetNRespM->GetBinContent(j);
    }
    hFSR_Det_Fold->SetBinContent(i,tmp);
    
    SVD_Post.xini->SetBinContent(i,hDetNRespM->GetBinContent(i));
    SVD_Post.xini->SetBinError(i,hDetNRespM->GetBinError(i));
    
    SVD_Post.bini->SetBinContent(i,hFSR_Det_Fold->GetBinContent(i));
    SVD_Post.bini->SetBinError(i,hFSR_Det_Fold->GetBinError(i));
  }
  hFSR_Det_Fold->Write();

  hToy = (TH1D*)hFSR_Det_Fold->Clone("hToy");
  hToy->Scale(h1_Data_SigYild->Integral()/hToy->Integral());

  TRandom3 dRandom[13];

  for(int nLoop(0);nLoop<nToy;nLoop++)
  {
    double dBinContent[13] = {0.};

    dRandom[0].SetSeed(1+13*(idx*nToy+nLoop));
    dRandom[1].SetSeed(2+13*(idx*nToy+nLoop));
    dRandom[2].SetSeed(3+13*(idx*nToy+nLoop));
    dRandom[3].SetSeed(4+13*(idx*nToy+nLoop));
    dRandom[4].SetSeed(5+13*(idx*nToy+nLoop));
    dRandom[5].SetSeed(6+13*(idx*nToy+nLoop));
    dRandom[6].SetSeed(7+13*(idx*nToy+nLoop));
    dRandom[7].SetSeed(8+13*(idx*nToy+nLoop));
    dRandom[8].SetSeed(9+13*(idx*nToy+nLoop));
    dRandom[9].SetSeed(10+13*(idx*nToy+nLoop));
    dRandom[10].SetSeed(11+13*(idx*nToy+nLoop));
    dRandom[11].SetSeed(12+13*(idx*nToy+nLoop));
    dRandom[12].SetSeed(13+13*(idx*nToy+nLoop));
    
    for(int i(1);i<=h1_Data_SigYild->GetNbinsX();i++)
    {
      for(int j(0);j<hToy->GetBinContent(i);j++)
      {
	dBinContent[i-1] += dRandom[i-1].Poisson(hToy->GetBinContent(i));
      }
    }

    //TODO data from toy
    sprintf(tmpName,"SVD_Post.data_%d",nLoop);
    SVD_Post.data[nLoop] = new TH1D(tmpName,tmpName,NWptBinPlus-1,0,NWptBinPlus-1);
    
    sprintf(tmpName,"SVD_Post.ToyStatCovMat_%d",nLoop);
    SVD_Post.ToyStatCovMat[nLoop] = new TH2D(tmpName,tmpName
	,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
    
    sprintf(tmpName,"SVD_Post.ToyRecoCovMat_%d",nLoop);
    SVD_Post.ToyRecoCovMat[nLoop] = new TH2D(tmpName,"Total Reco Stage Covariace matrix"
      ,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);
    
    sprintf(tmpName,"SVD_Post.DetUnf_%d",nLoop);
    SVD_Post.DetUnf[nLoop] = new TH1D(tmpName,tmpName,13,Bins);
    
    sprintf(tmpName,"SVD_Born.data_%d",nLoop);
    SVD_Born.data[nLoop] = new TH1D(tmpName,tmpName,NWptBinPlus-1,0,NWptBinPlus-1);
    
    sprintf(tmpName,"SVD_Born.ToyStatCovMat_%d",nLoop);
    SVD_Born.ToyStatCovMat[nLoop] = new TH2D(tmpName,tmpName,NWptBinPlus-1,0,NWptBinPlus-1,NWptBinPlus-1,0,NWptBinPlus-1);

    sprintf(tmpName,"SVD_Born.FSRUnf_%d",nLoop);
    SVD_Born.FSRUnf[nLoop] = new TH1D(tmpName,tmpName,13,Bins);

    for(int i(1);i<=h1_Data_SigYild->GetNbinsX();i++)
    {
      SVD_Post.data[nLoop]->SetBinContent(i,dBinContent[i-1]/hToy->GetBinContent(i));
      for(int j(1); j<=h1_Data_SigYild->GetNbinsX();j++)
      {
	if (i==j)
	{
	  SVD_Post.ToyStatCovMat[nLoop]->SetBinContent(i,i,dBinContent[i-1]/hToy->GetBinContent(i));
	}else{
	  SVD_Post.ToyStatCovMat[nLoop]->SetBinContent(i,j,0.);
	}
      }
    }
    
    SVD_Post.ToyRecoCovMat[nLoop]->Add(SVD_Post.TotalRecoCovMat);
    SVD_Post.ToyRecoCovMat[nLoop]->Add(SVD_Post.ToyStatCovMat[nLoop]);

    //=================================================================
    // Detector Unfolding (Error propagation of Cov matrix) ===========
    //=================================================================

    tsvdData[nLoop] = new TSVDUnfold(
	SVD_Post.data[nLoop],SVD_Post.ToyRecoCovMat[nLoop],SVD_Post.bini,SVD_Post.xini,SVD_Post.Adet);

    tsvdData[nLoop]->SetNormalize(kFALSE);
    //SVD_Post.unfRes[nLoop] = tsvdData[nLoop]->Unfold(3); 
    SVD_Post.unfRes[nLoop] = tsvdData[nLoop]->Unfold(4); 
    SVD_Post.dDist[nLoop] = tsvdData[nLoop]->GetD();
    SVD_Post.svDist[nLoop] = tsvdData[nLoop]->GetSV();
    
    for(int i(1);i<=h1_Data_SigYild->GetNbinsX();i++)
    {
      SVD_Post.DetUnf[nLoop]->SetBinContent(i,SVD_Post.unfRes[nLoop]->GetBinContent(i));
      SVD_Born.data[nLoop]->SetBinContent(i,SVD_Post.unfRes[nLoop]->GetBinContent(i));
      for(int j(1); j<=h1_Data_SigYild->GetNbinsX();j++)
      {
	if (i==j)
	{
	  SVD_Born.ToyStatCovMat[nLoop]->SetBinContent(i,i,SVD_Post.unfRes[nLoop]->GetBinContent(i));
	}else{
	  SVD_Born.ToyStatCovMat[nLoop]->SetBinContent(i,j,0.);
	}
      }
    }

    //=================================================================
    // FSR Unfolding (Error propagation of Cov matrix) ===========
    //=================================================================
    svdBorn[nLoop] = new TSVDUnfold(
	SVD_Born.data[nLoop],SVD_Born.ToyStatCovMat[nLoop],SVD_Born.bini,SVD_Born.xini,SVD_Born.Adet);

    svdBorn[nLoop]->SetNormalize( kFALSE );
    //SVD_Born.unfRes[nLoop] = svdBorn[nLoop]->Unfold(3); 
    if(BaseName == "WpToEleNu" || BaseName == "WmToEleNu" )
      SVD_Born.unfRes[nLoop] = svdBorn[nLoop]->Unfold(3);
    if(BaseName == "WpToMuNu" || BaseName == "WmToMuNu" )
      SVD_Born.unfRes[nLoop] = svdBorn[nLoop]->Unfold(4);
    SVD_Born.dDist[nLoop] = svdBorn[nLoop]->GetD();
    SVD_Born.svDist[nLoop] = svdBorn[nLoop]->GetSV();
    
    Fout<<"Bins\t GenFSRNormRD\t FSR Fold\t Det Fold\t ToyData\t Det.Unf.\t FSR.Unf\t UnfRes/GenFSRNormRD"<<endl;
    for(int i(1);i<=h1_Data_SigYild->GetNbinsX();i++)
    {
      SVD_Born.FSRUnf[nLoop]->SetBinContent(i,SVD_Born.unfRes[nLoop]->GetBinContent(i));
      Fout<<i<<"\t"<<hGenFSRNorm->GetBinContent(i)<<"\t"<<hFSR->GetBinContent(i)<<"\t"<<hFSR_Det_Fold->GetBinContent(i)<<"\t"<<SVD_Post.data[nLoop]->GetBinContent(i)<<"\t"<<SVD_Post.DetUnf[nLoop]->GetBinContent(i)<<"\t"<<SVD_Born.FSRUnf[nLoop]->GetBinContent(i)<<"\t"<<SVD_Born.FSRUnf[nLoop]->GetBinContent(i)/hGenFSRNorm->GetBinContent(i)<<endl;
    }
    
    // Write to root file
    SVD_Post.data[nLoop]->Write();	//Toy data (Input to detector Unfolding)
    SVD_Post.DetUnf[nLoop] -> Write();	//Detector Unfolded toy
    SVD_Born.data[nLoop]->Write();	//Toy data (Input to FSR Unfolding)
    SVD_Born.FSRUnf[nLoop] -> Write();	//FSR Unfolded toy
  }
  
  return 0;
}
Ejemplo n.º 11
0
void EleScaleClosureTest() {

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 
  
  // event category enumeration
  enum { eEleEle2HLT=1, eEleEle1HLT1L1, eEleEle1HLT, eEleEleNoSel, eEleSC };
  
  // Create output directory
  TString outputDir = "EleScaleClosureTestResults";
  TString pufname = "../Tools/pileup_weights_2015B.root";

  gSystem->mkdir(outputDir,kTRUE);
  
  vector<TString> infilenamev;
  infilenamev.push_back("/afs/cern.ch/work/c/cmedlock/public/wz-ntuples/Zee/ntuples/data_select.root");    // data
  infilenamev.push_back("/afs/cern.ch/work/c/cmedlock/public/wz-ntuples/Zee/ntuples/zee_select.raw.root"); // MC (raw)
  infilenamev.push_back("/afs/cern.ch/work/c/cmedlock/public/wz-ntuples/Zee/ntuples/zee_select.raw.root"); // MC2 (corrected)

  enum { eData=0, eMC, eMC2 };

  Float_t lumi=40.0;
  
  const Int_t    NBINS     = 40;
  const Double_t MASS_LOW  = 80;
  const Double_t MASS_HIGH = 100;
  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.5;
  const Double_t ELE_MASS  = 0.000511;  
  
  vector<pair<Double_t,Double_t> > scEta_limits;
  scEta_limits.push_back(make_pair(0.0,0.4));
  scEta_limits.push_back(make_pair(0.4,0.8));
  scEta_limits.push_back(make_pair(0.8,1.4442));
  scEta_limits.push_back(make_pair(1.566,2.5));

  CPlot::sOutDir = outputDir;
  
  const TString format("png");

  TRandom3 *rnd = new TRandom3();  
  
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  TFile *pufile = new TFile(pufname); assert(pufile);
  TH1D  *puWeights = (TH1D*)pufile->Get("npv_rw");
  
  TH1D* hData_Tot = new TH1D("hData_Tot","",NBINS,MASS_LOW,MASS_HIGH); hData_Tot->Sumw2();
  TH1D* hMC_Tot   = new TH1D("hMC_Tot","",NBINS,MASS_LOW,MASS_HIGH);   hMC_Tot->Sumw2();
  TH1D* hMC2_Tot  = new TH1D("hMC2_Tot","",NBINS,MASS_LOW,MASS_HIGH);  hMC2_Tot->Sumw2();
  
  char hname[100];
  vector<TH1D*> hMCv, hDatav, hMC2v;  
  for(UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
    for(UInt_t jbin=ibin; jbin<scEta_limits.size(); jbin++) {
      sprintf(hname,"data_%i_%i",ibin,jbin);
      hDatav.push_back(new TH1D(hname,"",NBINS,MASS_LOW,MASS_HIGH));
      hDatav.back()->Sumw2();

      sprintf(hname,"mc_%i_%i",ibin,jbin);
      hMCv.push_back(new TH1D(hname,"",NBINS,MASS_LOW,MASS_HIGH));
      hMCv.back()->Sumw2();
      
      sprintf(hname,"mc2_%i_%i",ibin,jbin);
      hMC2v.push_back(new TH1D(hname,"",NBINS,MASS_LOW,MASS_HIGH));
      hMC2v.back()->Sumw2();
    }
  }
  
  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  matchGen;
  UInt_t  category;
  UInt_t  npv, npu;
  Int_t   q1, q2;
  Float_t scale1fb, puWeight;
  TLorentzVector *dilep=0, *lep1=0, *lep2=0;
  ///// electron specific /////
  TLorentzVector *sc1=0, *sc2=0;
  
  for(UInt_t ifile=0; ifile<infilenamev.size(); ifile++) {
    cout << "Processing " << infilenamev[ifile] << "..." << endl;
    TFile *infile = TFile::Open(infilenamev[ifile]); assert(infile);
    TTree *intree = (TTree*)infile->Get("Events"); assert(intree);
  
    intree->SetBranchAddress("runNum",   &runNum);    // event run number
    intree->SetBranchAddress("lumiSec",  &lumiSec);   // event lumi section
    intree->SetBranchAddress("evtNum",   &evtNum);    // event number
    intree->SetBranchAddress("scale1fb", &scale1fb);  // event weight
    intree->SetBranchAddress("puWeight", &puWeight);  // pileup reweighting
    intree->SetBranchAddress("matchGen", &matchGen);  // event has both leptons matched to MC Z->ll
    intree->SetBranchAddress("category", &category);  // dilepton category
    intree->SetBranchAddress("npv",      &npv);	      // number of primary vertices
    intree->SetBranchAddress("npu",      &npu);	      // number of in-time PU events (MC)
    intree->SetBranchAddress("q1",       &q1);	      // charge of lead lepton
    intree->SetBranchAddress("q2",       &q2);	      // charge of trail lepton
    intree->SetBranchAddress("dilep",    &dilep);     // dilepton 4-vector
    intree->SetBranchAddress("lep1",     &lep1);      // lead lepton 4-vector
    intree->SetBranchAddress("lep2",     &lep2);      // trail lepton 4-vector
    intree->SetBranchAddress("sc1",      &sc1);	      // lead Supercluster 4-vector
    intree->SetBranchAddress("sc2",      &sc2);	      // trail Supercluster 4-vector 
  
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      Double_t weight = 1;
      if(ifile==eMC || ifile==eMC2)
        weight=scale1fb*lumi*puWeights->GetBinContent(npv+1);
      
      if((category!=eEleEle2HLT) && (category!=eEleEle1HLT) && (category!=eEleEle1HLT1L1)) continue;
      if(q1 == q2) continue;
      if(dilep->M()	  < MASS_LOW)  continue;
      if(dilep->M()	  > MASS_HIGH) continue;
      if(sc1->Pt()	  < PT_CUT)    continue;
      if(sc2->Pt()	  < PT_CUT)    continue;
      if(fabs(sc1->Eta()) > ETA_CUT)   continue;      
      if(fabs(sc2->Eta()) > ETA_CUT)   continue;

      TLorentzVector vLep1(0,0,0,0); 
      TLorentzVector vLep2(0,0,0,0); 
      if (ifile==eData) {
	vLep1.SetPtEtaPhiM(lep1->Pt(), lep1->Eta(), lep1->Phi(), ELE_MASS);
	vLep2.SetPtEtaPhiM(lep2->Pt(), lep2->Eta(), lep2->Phi(), ELE_MASS);
      }
      else if (ifile==eMC) {
	vLep1.SetPtEtaPhiM(lep1->Pt(), lep1->Eta(), lep1->Phi(), ELE_MASS);
	vLep2.SetPtEtaPhiM(lep2->Pt(), lep2->Eta(), lep2->Phi(), ELE_MASS);
      }
      else {
	vLep1.SetPtEtaPhiM(gRandom->Gaus(lep1->Pt()*getEleScaleCorr(lep1->Eta(),0),getEleResCorr(lep1->Eta(),0)), lep1->Eta(), lep1->Phi(), ELE_MASS);
	vLep2.SetPtEtaPhiM(gRandom->Gaus(lep2->Pt()*getEleScaleCorr(lep2->Eta(),0),getEleResCorr(lep2->Eta(),0)), lep2->Eta(), lep2->Phi(), ELE_MASS);
      }
      TLorentzVector vDilep = vLep1 + vLep2;
    
      Int_t bin1=-1, bin2=-1;
      for(UInt_t i=0; i<scEta_limits.size(); i++) {
        Double_t etalow  = scEta_limits.at(i).first;
        Double_t etahigh = scEta_limits.at(i).second;
        if(fabs(sc1->Eta())>=etalow && fabs(sc1->Eta())<=etahigh) bin1=i;
        if(fabs(sc2->Eta())>=etalow && fabs(sc2->Eta())<=etahigh) bin2=i;
      }
      assert(bin1>=0);
      assert(bin2>=0);
      Int_t ibin= (bin1<=bin2) ? bin1 : bin2;
      Int_t jbin= (bin1<=bin2) ? bin2 : bin1;

      if (ifile==eData) hData_Tot->Fill(vDilep.M(),weight);
      else if (ifile==eMC) hMC_Tot->Fill(vDilep.M(),weight);
      else if (ifile==eMC2) hMC2_Tot->Fill(vDilep.M(),weight);

      UInt_t n=jbin-ibin;
      for(Int_t k=0; k<ibin; k++)
        n+=(scEta_limits.size()-k);
      
      if(ifile==eData)
	hDatav[n]->Fill(vDilep.M(),weight);
      else if(ifile==eMC)
	hMCv[n]->Fill(vDilep.M(),weight);
      else if(ifile==eMC2)
	hMC2v[n]->Fill(vDilep.M(),weight);
    }  
    delete infile;
    infile=0, intree=0;
  }

  TCanvas *c1 = MakeCanvas("c1", "", 800, 800);
  char pname[100];

  c1->Divide(1,2,0,0);
  c1->cd(1)->SetPad(0,0.3,1.0,1.0);
  c1->cd(1)->SetTopMargin(0.1);
  c1->cd(1)->SetBottomMargin(0.01); //0.01
  c1->cd(1)->SetLeftMargin(0.15);
  c1->cd(1)->SetRightMargin(0.07);
  c1->cd(1)->SetTickx(1);
  c1->cd(1)->SetTicky(1);

  c1->cd(2)->SetPad(0,0,1.0,0.3);
  c1->cd(2)->SetTopMargin(0.05);
  c1->cd(2)->SetBottomMargin(0.45);//0.25
  c1->cd(2)->SetLeftMargin(0.15);
  c1->cd(2)->SetRightMargin(0.07);
  c1->cd(2)->SetTickx(1);
  c1->cd(2)->SetTicky(0);

  TGaxis::SetMaxDigits(3);

  for (UInt_t ibin=0; ibin<scEta_limits.size(); ibin++) {
    for(UInt_t jbin=ibin; jbin<scEta_limits.size(); jbin++) {
      UInt_t n=jbin-ibin;
      for(UInt_t k=0; k<ibin; k++)
        n+=(scEta_limits.size()-k);

      //hMCv[n]   ->Scale(1.0/hMCv[n]->Integral());
      //hDatav[n] ->Scale(1.0/hDatav[n]->Integral());
      //hMC2v[n]->Scale(1.0/hMC2v[n]->Integral());

      c1->cd(1);

      hMCv[n]->SetLineColor(kRed);
      hMCv[n]->GetYaxis()->SetTitleOffset(1.100);
      hMCv[n]->GetYaxis()->SetTitle("Events");
      hMCv[n]->GetYaxis()->SetRangeUser(0.01, 1.3*TMath::Max(hMCv[n]->GetMaximum(),hDatav[n]->GetMaximum()));
      hMCv[n]->Draw("hist");
      hDatav[n]->Draw("EX0 same");
      hMC2v[n]->SetLineColor(kBlue);
      hMC2v[n]->Draw("histsame");

      c1->cd(2);

      TH1D* hDiffMC = returnRelDiff(hMCv[n],hDatav[n],"foo");
      TH1D* hDiffMC2 = returnRelDiff(hMC2v[n],hDatav[n],"foo2");

      hDiffMC->GetYaxis()->SetRangeUser(-1.0,1.0);
      hDiffMC->GetXaxis()->SetTitle("m_{ee} [GeV]");
      hDiffMC->GetYaxis()->SetTitle("#chi");

      hDiffMC->GetYaxis()->SetTitleOffset(0.42);
      hDiffMC->GetYaxis()->SetTitleSize(0.13);
      hDiffMC->GetXaxis()->SetTitleSize(0.13);
      hDiffMC->GetYaxis()->SetLabelSize(0.12);
      hDiffMC->GetXaxis()->SetLabelSize(0.12);
      hDiffMC->GetYaxis()->SetNdivisions(102);
      hDiffMC->GetYaxis()->CenterTitle();
      hDiffMC->GetXaxis()->SetTitleOffset(1.2);
      hDiffMC->GetXaxis()->CenterTitle();

      hDiffMC->Draw("hist");
      TLine l(80,0.0,100,0.0);
      l.Draw();
      hDiffMC->Draw("histsame");

      hDiffMC2->SetMarkerColor(kBlue);
      hDiffMC2->SetMarkerSize(1);
      hDiffMC2->SetLineColor(kBlue);
      hDiffMC2->Draw("EX0 same");

      c1->cd(1);

      TLegend *leg = new TLegend(0.65, 0.55, 0.90, 0.80);
      leg->SetShadowColor(0); leg->SetLineColor(0);
      leg->AddEntry(hMCv[n],"Raw MC","l");
      leg->AddEntry(hDatav[n],"Data","l");
      leg->AddEntry(hMC2v[n],"Corr. MC","l");
      leg->Draw();

      // CMS label
      TPaveText tb1(0.65,0.92,0.95,0.99,"NDC");
      tb1.SetFillStyle(0);
      tb1.SetBorderSize(0);
      tb1.SetTextAlign(32);
      tb1.AddText("CMS Preliminary");
      tb1.Draw();

      char buffer[200];
      // lumi label
      sprintf(buffer,"%.1f pb^{-1}  at  #sqrt{s} = 13 TeV",lumi);
      TPaveText tb2(0.55,0.82,0.90,0.90,"NDC");
      tb2.SetFillStyle(0);
      tb2.SetBorderSize(0);
      tb2.SetTextAlign(32);
      tb2.AddText(buffer);
      tb2.Draw();

      char str1[200],str2[200];
      sprintf(str1,"[%.1f, %.1f]",scEta_limits.at(ibin).first,scEta_limits.at(ibin).second);
      sprintf(str2,"[%.1f, %.1f]",scEta_limits.at(jbin).first,scEta_limits.at(jbin).second);
      TPaveText *a = new TPaveText(0.16,0.75,0.40,0.82,"NDC");
      a->SetFillColor(0); a->SetShadowColor(0); a->SetLineColor(0);
      a->AddText(str1);
      TPaveText *b = new TPaveText(0.16,0.68,0.40,0.75,"NDC");
      b->SetFillColor(0); b->SetShadowColor(0); b->SetLineColor(0);
      b->AddText(str2);

      a->Draw();
      b->Draw();

      sprintf(pname,"ele_comp_%i_%i.png",ibin,jbin); 
      c1->SaveAs(outputDir+"/"+pname);

      delete hDiffMC; delete hDiffMC2;
    }
  }

  cout << endl;
  cout << hMC_Tot->Integral() << ", " << hData_Tot->Integral() << ", " << hMC2_Tot->Integral() << endl;

  c1->cd(1);

  hMC_Tot->SetLineColor(kRed); hMC_Tot->SetMarkerColor(kRed);
  hMC_Tot->GetYaxis()->SetTitleOffset(1.100);
  hMC_Tot->GetYaxis()->SetTitle("Events");
  hMC_Tot->GetYaxis()->SetRangeUser(0.01, 1.2*hMC_Tot->GetMaximum());
  hMC_Tot->Draw("hist");
  hData_Tot->Draw("EX0 same");
  hMC2_Tot->SetLineColor(kBlue); hMC2_Tot->SetMarkerColor(kBlue);
  hMC2_Tot->Draw("hist same");

  c1->cd(2);
  
  TH1D* hDiffMC = returnRelDiff(hMC_Tot,hData_Tot,"foo");
  TH1D* hDiffMC2 = returnRelDiff(hMC2_Tot,hData_Tot,"foo2");
  
  hDiffMC->GetYaxis()->SetRangeUser(-1.0,1.0);
  hDiffMC->GetXaxis()->SetTitle("m_{ee} [GeV]");
  hDiffMC->GetYaxis()->SetTitle("#chi");

  hDiffMC->GetYaxis()->SetTitleOffset(0.42);
  hDiffMC->GetYaxis()->SetTitleSize(0.13);
  hDiffMC->GetXaxis()->SetTitleSize(0.13);
  hDiffMC->GetYaxis()->SetLabelSize(0.12);
  hDiffMC->GetXaxis()->SetLabelSize(0.12);
  hDiffMC->GetYaxis()->SetNdivisions(102);
  hDiffMC->GetYaxis()->CenterTitle();
  hDiffMC->GetXaxis()->SetTitleOffset(1.2);
  hDiffMC->GetXaxis()->CenterTitle();

  hDiffMC->SetMarkerColor(kRed);
  hDiffMC->SetMarkerSize(1);
  hDiffMC->SetLineColor(kRed);
  hDiffMC->Draw("hist");
  TLine l(80,0.0,100,0.0);
  l.Draw();
  //hDiffMC->Draw("EX0 same");

  hDiffMC2->SetMarkerColor(kBlue);
  hDiffMC2->SetMarkerSize(1);
  hDiffMC2->SetLineColor(kBlue);
  hDiffMC2->Draw("EX0 same");

  c1->cd(1);

  TLegend *leg = new TLegend(0.65, 0.55, 0.90, 0.80);
  leg->SetShadowColor(0); leg->SetLineColor(0);
  leg->AddEntry(hMC_Tot,"Raw MC","l");
  leg->AddEntry(hData_Tot,"Data","l");
  leg->AddEntry(hMC2_Tot,"Corr. MC","l");
  leg->Draw();

  // CMS label
  TPaveText tb1(0.65,0.92,0.95,0.99,"NDC");
  tb1.SetFillStyle(0);
  tb1.SetBorderSize(0);
  tb1.SetTextAlign(32);
  tb1.AddText("CMS Preliminary");
  tb1.Draw();

  char buffer[200];
  // lumi label
  sprintf(buffer,"%.1f pb^{-1}  at  #sqrt{s} = 13 TeV",lumi);
  TPaveText tb2(0.55,0.82,0.90,0.90,"NDC");
  tb2.SetFillStyle(0);
  tb2.SetBorderSize(0);
  tb2.SetTextAlign(32);
  tb2.AddText(buffer);
  tb2.Draw();

  char str1[200],str2[200];
  sprintf(str1,"[%.1f, %.1f]",scEta_limits.at(0).first,scEta_limits.at(scEta_limits.size()-1).second);
  sprintf(str2,"[%.1f, %.1f]",scEta_limits.at(0).first,scEta_limits.at(scEta_limits.size()-1).second);
  TPaveText *a = new TPaveText(0.16,0.75,0.40,0.82,"NDC");
  a->SetFillColor(0); a->SetShadowColor(0); a->SetLineColor(0);
  a->AddText(str1);
  TPaveText *b = new TPaveText(0.16,0.68,0.40,0.75,"NDC");
  b->SetFillColor(0); b->SetShadowColor(0); b->SetLineColor(0);
  b->AddText(str2);
  
  a->Draw();
  b->Draw();

  sprintf(pname,"ele_comp_tot.png");
  c1->SaveAs(outputDir+"/"+pname);


}
Ejemplo n.º 12
0
void 
//HHH_TT_X_notag(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
HHH_TT_X_notag(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="tauTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("tauTau_2jet0tag")){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet0tag")){ category_extra= "2-jet 0 b-tag";           }
  if(std::string(directory) == std::string("tauTau_2jet1tag"  )){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet1tag"  )){ category_extra= "2-jet 1 b-tag";     }
  if(std::string(directory) == std::string("tauTau_2jet2tag"  )){ category = "#tau_{h}#tau_{h}";           }
  if(std::string(directory) == std::string("tauTau_2jet2tag"  )){ category_extra = "2-jet 2 b-tag";              }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){
    if(std::string(directory).find("btag")!=std::string::npos){
      dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                18.3 fb^{-1} (8 TeV)";
    }
    else{
        dataset = "#scale[1.5]{CMS}  H#rightarrow hh#rightarrow#tau#tau bb                         19.7 fb^{-1} (8 TeV)";
    }
  }
#else
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  // open example histogram file
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MH_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZLL"      , directory)), "ZLL" ); InitHist(EWK2 , "", "", TColor::GetColor(222,90,106), 1001);
//TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK3 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK  , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggHTohhTo2Tau2B    = refill((TH1F*)input2->Get(TString::Format("%s/ggHTohhTo2Tau2B$MH" , directory)), "ggHTohhTo2Tau2B"); InitSignal(ggHTohhTo2Tau2B); ggHTohhTo2Tau2B->Scale($TANB*SIGNAL_SCALE);
 // if(std::string(directory)=="tauTau_2jet0tag") ggHTohhTo2Tau2B->Scale(4);
/*  TH1F* ggH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/ggH_SM125",directory)),"ggH_SM125");InitSignal(ggH_SM125);ggH_SM125->Scale(SIGNAL_SCALE);
  TH1F* qqH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/qqH_SM125",directory)),"qqH_SM125");InitSignal(qqH_SM125);qqH_SM125->Scale(SIGNAL_SCALE);
  TH1F* VH_SM125 = refill((TH1F*)input->Get(TString::Format("%s/VH_SM125",directory)),"VH_SM125");InitSignal(VH_SM125);VH_SM125->Scale(SIGNAL_SCALE);
  TH1F* WHToBB_SM125 = refill((TH1F*)input->Get(TString::Format("%s/WHToBB_SM125",directory)),"WHToBB_SM125");InitSignal(WHToBB_SM125);WHToBB_SM125->Scale(SIGNAL_SCALE);
  TH1F* ZHToBB_SM125 = refill((TH1F*)input->Get(TString::Format("%s/ZHToBB_SM125",directory)),"ZHToBB_SM125");InitSignal(ZHToBB_SM125);ZHToBB_SM125->Scale(SIGNAL_SCALE);
*/
/*
  TH1F* ggAToZhToLLTauTau = refill((TH1F*)input2->Get(TString::Format("%s/ggAToZhToLLTauTau$MH",directory)),"ggAToZhToLLTauTau"); InitSignal(ggAToZhToLLTauTau);
  TH1F* ggAToZhToLLBB = refill((TH1F*)input2->Get(TString::Format("%s/ggAToZhToLLBB$MH",directory)),"ggAToZhToLLBB"); InitSignal(ggAToZhToLLBB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MH" , directory)), "bbH"); InitSignal(bbH);
*/
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data",true);
#endif
  InitHist(data, "#bf{m_{H} [GeV]}", "#bf{dN/dm_{H} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
//ref->Add(EWK3 );
  ref->Add(EWK );
  ref->Add(ttbar);
  ref->Add(Ztt  );


  double unscaled[8];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
//unscaled[1]+= EWK3 ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggHTohhTo2Tau2B  ->Integral();
/*  unscaled[5] = ggH_SM125->Integral();
  unscaled[5]+= qqH_SM125->Integral();
  unscaled[5]+= VH_SM125->Integral();
*/
/*
  unscaled[5] = ggAToZhToLLTauTau->Integral();
  unscaled[6] = ggAToZhToLLBB->Integral();
  unscaled[7] = bbH  ->Integral();
*/
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK1  = refill(shape_histos(EWK1, datacard, "W"), "W");
    EWK2  = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK   = refill(shape_histos(EWK, datacard, "VV"), "VV");
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT"); 
    Ztt   = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT"); 
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MH"), "ggH$MH"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MH"), "bbH$MH"); 
#else
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH");
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH");
    VH  = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif
*/
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
  //rescale(EWK3 , 5);
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggHTohhTo2Tau2B  , 8); 
/*
    rescale(ggAToZhToLLTauTau,9);
    rescale(ggAToZhToLLBB,10);
    rescale(bbH  , 11);  
*/
#endif
  }

  TH1F* scales[8];
  scales[0] = new TH1F("scales-Fakes", "", 8, 0, 8);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 8, 0, 8);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
					      //+EWK3 ->Integral()
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 8, 0, 8);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 8, 0, 8);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggHTohhTo2Tau2B"  , "", 8, 0, 8);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggHTohhTo2Tau2B  ->Integral()/unscaled[4]-1.) : 0.);
/*  scales[5] = new TH1F("scales-sm","",8,0,8);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? ((ggH_SM125->Integral()+qqH_SM125->Integral()+VH_SM125->Integral())/unscaled[5]-1.) : 0.);
*/
/*
  scales[5] = new TH1F("scales-ggAToZhToLLTauTau"  , "", 8, 0, 8);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (ggAToZhToLLTauTau  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-ggAToZhToLLBB"  , "", 8, 0, 8);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (ggAToZhToLLBB  ->Integral()/unscaled[6]-1.) : 0.);
  scales[7] = new TH1F("scales-bbH"  , "", 8, 0, 8);
  scales[7]->SetBinContent(8, unscaled[7]>0 ? (bbH  ->Integral()/unscaled[7]-1.) : 0.);
*/
#endif

//#ifdef MSSM
//  qqH_SM125->Add(ggH_SM125);
 // VH_SM125->Add(qqH_SM125);
 // Fakes->Add(VH_SM125);
//#endif
  Fakes->Add(ttbar);
  EWK1 ->Add(Fakes);
  EWK2 ->Add(Fakes );
//EWK3 ->Add(EWK2 );
//EWK  ->Add(EWK3 );
  EWK  ->Add(EWK2 );
//  ttbar->Add(EWK  );
  Ztt  ->Add(EWK);

 /*ggH_SM125->Add(qqH_SM125);
 ggH_SM125->Add(VH_SM125);
 ggH_SM125->Add(ZHToBB_SM125);
 ggH_SM125->Add(WHToBB_SM125);
*/
  //if(log){
//#ifdef MSSM
 //   ggH->Add(bbH);
//#else
 //   qqH->Add(VH );
  //  ggH->Add(qqH);
//#endif
 // }
  //else{
//#ifdef MSSM    
 //   bbH->Add(Ztt);
  //  ggH->Add(bbH);
//#else
 //   VH ->Add(Ztt);
  //  qqH->Add(VH );
   // ggH->Add(qqH);
//#endif
 // }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE)); } else{ data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(200, data->FindBin(UPPER_EDGE));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggHTohhTo2Tau2B, log)));
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    ttbar->Draw("histsame");
//#ifdef MSSM
//    VH_SM125->Draw("histsame");
//#endif
    $DRAW_ERROR
    ggHTohhTo2Tau2B  ->Draw("histsame");
   /* ggH_SM125->SetLineColor(kRed);
    ggH_SM125->Draw("histsame");
*/
  }
  else{
    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    ttbar->Draw("histsame");
#ifdef MSSM
    //VH_SM125->Draw("histsame");
#endif
    $DRAW_ERROR
    ggHTohhTo2Tau2B  ->Draw("histsame");
    /*ggH_SM125->SetLineColor(kRed);
    ggH_SM125->Draw("histsame");
*/
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{h}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);  
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (strcmp(category_extra2,"")!=0) chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (strcmp(category_extra2,"")!=0) chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();
/*
  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{mod+} scenario");
  massA->AddText("m_{H}=$MH GeV, tan#beta=$TANB");
  massA->Draw();
#endif
  
#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggHTohhTo2Tau2B  , TString::Format("%0.f #times H#rightarrowhh#rightarrow#tau#taubb", SIGNAL_SCALE) , "L" );
  //leg->AddEntry(ggH_SM125, TString::Format("%0.f #times SM H(125 GeV) #rightarrow #tau#tau/bb", SIGNAL_SCALE), "L");
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Electroweak"                    , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
/*#ifdef MSSM
  leg->AddEntry(VH_SM125, "SM H(125 GeV) #rightarrow #tau#tau", "F" );
#endif
*/
  $ERROR_LEGEND
  leg->Draw();

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

  TH1F* model = (TH1F*)Ztt ->Clone("model");
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONSERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }

double chi2prob=0.;
double chi2ndof=0.;
double ksprob=0.;
double ksprobpe=0.;

if(!BLIND_DATA){
  chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  
}
  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if(edges.size()>1){
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  else if (edges[edges.size()-2]>0.2) { range = 0.5; }
  else if (edges[edges.size()-2]>0.5) { range = 1.0; }
  else if (edges[edges.size()-2]>1.0) { range = 1.5; }
  else if (edges[edges.size()-2]>1.5) { range = 2.0; }
}
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{H} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

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

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
if(edges.size()>1){
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
}
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE)); } else{ rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(200, rat2->FindBin(UPPER_EDGE));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{H} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
  InitHist(scales[4],"","",kGreen+2,1001);
/*  InitHist(scales[5],"","",kGreen+2,1001);
  InitHist(scales[6],"","",kGreen+2,1001);
  InitHist(scales[7],"","",kGreen+2,1001);
*/

  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggHTohhTo2tau2B}"  );
/*
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{ggAToZhToLLTauTau}");
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{ggAToZhToLLBB}");
  scales[0]->GetXaxis()->SetBinLabel(8, "#bf{bbH}"  );
*/
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
  scales[4]->Draw("same");
 /* scales[5]->Draw("same");
  scales[6]->Draw("same");
*/
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggHTohhTo2Tau2B  ->Write("ggHTohhTo2Tau2B"     );
/*
  ggAToZhToLLTauTau->Write("ggAToZhToLLTauTau");
  ggAToZhToLLBB->Write("ggAToZhToLLBB");
  bbH  ->Write("bbH"     );
*/
#endif
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Ejemplo n.º 13
0
void PlotIsjMean()
{
  gROOT->LoadMacro("$LOCAL/include/TUntilsOpHisto.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsAliFigs.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsPlotStd.h"); SetStyle();
//=============================================================================

  TFile *file = TFile::Open("data/AnalysisOutputs_Isj.root", "READ");
  TList *listPy8R4S1 = (TList*)file->Get("list_py8_JetR04_SjeR01");
  TList *listPy8R4S2 = (TList*)file->Get("list_py8_JetR04_SjeR02");
  TList *listPy8R4S3 = (TList*)file->Get("list_py8_JetR04_SjeR03");
  TList *listPy8R5S1 = (TList*)file->Get("list_py8_JetR05_SjeR01");
  TList *listPy8R5S2 = (TList*)file->Get("list_py8_JetR05_SjeR02");
  TList *listPy8R5S3 = (TList*)file->Get("list_py8_JetR05_SjeR03");
  TList *listPy8R5S4 = (TList*)file->Get("list_py8_JetR05_SjeR04");

  TList *listVacR4S1 = (TList*)file->Get("list_vac_JetR04_SjeR01");
  TList *listVacR4S2 = (TList*)file->Get("list_vac_JetR04_SjeR02");
  TList *listVacR4S3 = (TList*)file->Get("list_vac_JetR04_SjeR03");
  TList *listVacR5S1 = (TList*)file->Get("list_vac_JetR05_SjeR01");
  TList *listVacR5S2 = (TList*)file->Get("list_vac_JetR05_SjeR02");
  TList *listVacR5S3 = (TList*)file->Get("list_vac_JetR05_SjeR03");
  TList *listVacR5S4 = (TList*)file->Get("list_vac_JetR05_SjeR04");

  TList *listMedR4S1 = (TList*)file->Get("list_med_JetR04_SjeR01");
  TList *listMedR4S2 = (TList*)file->Get("list_med_JetR04_SjeR02");
  TList *listMedR4S3 = (TList*)file->Get("list_med_JetR04_SjeR03");
  TList *listMedR5S1 = (TList*)file->Get("list_med_JetR05_SjeR01");
  TList *listMedR5S2 = (TList*)file->Get("list_med_JetR05_SjeR02");
  TList *listMedR5S3 = (TList*)file->Get("list_med_JetR05_SjeR03");
  TList *listMedR5S4 = (TList*)file->Get("list_med_JetR05_SjeR04");
  file->Close();

  TProfile *hPy8R4S1 = (TProfile*)listPy8R4S1->FindObject("hJetIsj_mean"); hPy8R4S1->SetName("hPy8R4S1");
  TProfile *hPy8R4S2 = (TProfile*)listPy8R4S2->FindObject("hJetIsj_mean"); hPy8R4S2->SetName("hPy8R4S2");
  TProfile *hPy8R4S3 = (TProfile*)listPy8R4S3->FindObject("hJetIsj_mean"); hPy8R4S3->SetName("hPy8R4S3");
  TProfile *hPy8R5S1 = (TProfile*)listPy8R5S1->FindObject("hJetIsj_mean"); hPy8R5S1->SetName("hPy8R5S1");
  TProfile *hPy8R5S2 = (TProfile*)listPy8R5S2->FindObject("hJetIsj_mean"); hPy8R5S2->SetName("hPy8R5S2");
  TProfile *hPy8R5S3 = (TProfile*)listPy8R5S3->FindObject("hJetIsj_mean"); hPy8R5S3->SetName("hPy8R5S3");
  TProfile *hPy8R5S4 = (TProfile*)listPy8R5S4->FindObject("hJetIsj_mean"); hPy8R5S4->SetName("hPy8R5S4");

  TProfile *hVacR4S1 = (TProfile*)listVacR4S1->FindObject("hJetIsj_mean"); hVacR4S1->SetName("hVacR4S1");
  TProfile *hVacR4S2 = (TProfile*)listVacR4S2->FindObject("hJetIsj_mean"); hVacR4S2->SetName("hVacR4S2");
  TProfile *hVacR4S3 = (TProfile*)listVacR4S3->FindObject("hJetIsj_mean"); hVacR4S3->SetName("hVacR4S3");
  TProfile *hVacR5S1 = (TProfile*)listVacR5S1->FindObject("hJetIsj_mean"); hVacR5S1->SetName("hVacR5S1");
  TProfile *hVacR5S2 = (TProfile*)listVacR5S2->FindObject("hJetIsj_mean"); hVacR5S2->SetName("hVacR5S2");
  TProfile *hVacR5S3 = (TProfile*)listVacR5S3->FindObject("hJetIsj_mean"); hVacR5S3->SetName("hVacR5S3");
  TProfile *hVacR5S4 = (TProfile*)listVacR5S4->FindObject("hJetIsj_mean"); hVacR5S4->SetName("hVacR5S4");

  TProfile *hMedR4S1 = (TProfile*)listMedR4S1->FindObject("hJetIsj_mean"); hMedR4S1->SetName("hMedR4S1");
  TProfile *hMedR4S2 = (TProfile*)listMedR4S2->FindObject("hJetIsj_mean"); hMedR4S2->SetName("hMedR4S2");
  TProfile *hMedR4S3 = (TProfile*)listMedR4S3->FindObject("hJetIsj_mean"); hMedR4S3->SetName("hMedR4S3");
  TProfile *hMedR5S1 = (TProfile*)listMedR5S1->FindObject("hJetIsj_mean"); hMedR5S1->SetName("hMedR5S1");
  TProfile *hMedR5S2 = (TProfile*)listMedR5S2->FindObject("hJetIsj_mean"); hMedR5S2->SetName("hMedR5S2");
  TProfile *hMedR5S3 = (TProfile*)listMedR5S3->FindObject("hJetIsj_mean"); hMedR5S3->SetName("hMedR5S3");
  TProfile *hMedR5S4 = (TProfile*)listMedR5S4->FindObject("hJetIsj_mean"); hMedR5S4->SetName("hMedR5S4");
//=============================================================================

  TH1F    *hfm = 0;
  TCanvas *can = 0;
  TLegend *leg = 0;
  TLatex  *tex = 0;
  TLine  *line = 0;

  const Float_t dflx = 0., dfux = 500.;
  const Float_t dfly = 0., dfuy = 500.;

  const Float_t dlsx = 0.05, dlsy = 0.05;
  const Float_t dtsx = 0.06, dtsy = 0.06;
  const Float_t dtox = 1.10, dtoy = 1.00;

  const TString stnx = "#it{p}_{T,jet} (GeV/#it{c})";
  const TString stny = "#it{p}_{T,subjet}^{mean} (GeV/#it{c})";

  TH1D *hSE = new TH1D("hSE", "", 10., 0., 10.);
  hSE->SetLineWidth(2);
  hSE->SetLineColor(wcl[0]);
  hSE->SetMarkerStyle(wmk[0]);
  hSE->SetMarkerColor(wcl[0]);

  TH1D *hME = new TH1D("hME", "", 10., 0., 10.);
  hME->SetLineWidth(2);
  hME->SetLineColor(wcl[0]);
  hME->SetMarkerStyle(wmk[2]);
  hME->SetMarkerColor(wcl[0]);
//=============================================================================

  can = MakeCanvas("IsjPy8R04_mean"); can->SetGridx(); can->SetGridy(); //can->SetLogy();
  hfm = can->DrawFrame(dflx,dfly,dfux,dfuy); SetupFrame(hfm,dlsx,dlsy,dtsx,dtsy,dtox,dtoy, stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hPy8R4S1, wcl[1], wmk[0], "SAME");
  DrawHisto(hPy8R4S2, wcl[3], wmk[0], "SAME");
  DrawHisto(hPy8R4S3, wcl[4], wmk[0], "SAME");

  leg = new TLegend(0.68, 0.66, 0.98, 0.90); SetupLegend(leg);
  leg->AddEntry(hPy8R4S1, "#it{R}_{sub}=0.1", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hPy8R4S2, "#it{R}_{sub}=0.2", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hPy8R4S3, "#it{R}_{sub}=0.3", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA 8, tune 4C, pp #sqrt{#it{s}_{NN}}=2.76 TeV");
  tex->DrawLatex(0.16, 0.84, "Jet: anti-#it{k}_{T}, #it{R}=0.4, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.76, "Sub-jet: #it{k}_{T}");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("IsjPy8R05_mean"); can->SetGridx(); can->SetGridy(); //can->SetLogy();
  hfm = can->DrawFrame(dflx,dfly,dfux,dfuy); SetupFrame(hfm,dlsx,dlsy,dtsx,dtsy,dtox,dtoy, stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hPy8R5S1, wcl[1], wmk[0], "SAME");
  DrawHisto(hPy8R5S2, wcl[3], wmk[0], "SAME");
  DrawHisto(hPy8R5S3, wcl[4], wmk[0], "SAME");
  DrawHisto(hPy8R5S4, wcl[2], wmk[0], "SAME");

  leg = new TLegend(0.58, 0.74, 0.98, 0.90); SetupLegend(leg);
  leg->SetNColumns(2);
  leg->AddEntry(hPy8R5S1, "#it{R}_{sub}=0.1", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hPy8R5S2, "#it{R}_{sub}=0.2", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hPy8R5S3, "#it{R}_{sub}=0.3", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hPy8R5S4, "#it{R}_{sub}=0.4", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA 8, tune 4C, pp #sqrt{#it{s}_{NN}}=2.76 TeV");
  tex->DrawLatex(0.16, 0.84, "Jet: anti-#it{k}_{T}, #it{R}=0.5, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.76, "Sub-jet: #it{k}_{T}");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("IsjVacR04_mean"); can->SetGridx(); can->SetGridy(); //can->SetLogy();
  hfm = can->DrawFrame(dflx,dfly,dfux,dfuy); SetupFrame(hfm,dlsx,dlsy,dtsx,dtsy,dtox,dtoy, stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hVacR4S1, wcl[1], wmk[0], "SAME");
  DrawHisto(hVacR4S2, wcl[3], wmk[0], "SAME");
  DrawHisto(hVacR4S3, wcl[4], wmk[0], "SAME");

  leg = new TLegend(0.68, 0.66, 0.98, 0.90); SetupLegend(leg);
  leg->AddEntry(hVacR4S1, "#it{R}_{sub}=0.1", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hVacR4S2, "#it{R}_{sub}=0.2", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hVacR4S3, "#it{R}_{sub}=0.3", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA+JEWEL, vacuum, #sqrt{#it{s}_{NN}}=2.76 TeV");
  tex->DrawLatex(0.16, 0.84, "Jet: anti-#it{k}_{T}, #it{R}=0.4, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.76, "Sub-jet: #it{k}_{T}");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("IsjVacR05_mean"); can->SetGridx(); can->SetGridy(); //can->SetLogy();
  hfm = can->DrawFrame(dflx,dfly,dfux,dfuy); SetupFrame(hfm,dlsx,dlsy,dtsx,dtsy,dtox,dtoy,  stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hVacR5S1, wcl[1], wmk[0], "SAME");
  DrawHisto(hVacR5S2, wcl[3], wmk[0], "SAME");
  DrawHisto(hVacR5S3, wcl[4], wmk[0], "SAME");
  DrawHisto(hVacR5S4, wcl[2], wmk[0], "SAME");

  leg = new TLegend(0.58, 0.74, 0.98, 0.90); SetupLegend(leg);
  leg->SetNColumns(2);
  leg->AddEntry(hVacR5S1, "#it{R}_{sub}=0.1", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hVacR5S2, "#it{R}_{sub}=0.2", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hVacR5S3, "#it{R}_{sub}=0.3", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hVacR5S4, "#it{R}_{sub}=0.4", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA+JEWEL, vacuum, #sqrt{#it{s}_{NN}}=2.76 TeV");
  tex->DrawLatex(0.16, 0.84, "Jet: anti-#it{k}_{T}, #it{R}=0.5, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.76, "Sub-jet: #it{k}_{T}");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("IsjMedR04_mean"); can->SetGridx(); can->SetGridy(); //can->SetLogy();
  hfm = can->DrawFrame(dflx,dfly,dfux,dfuy); SetupFrame(hfm,dlsx,dlsy,dtsx,dtsy,dtox,dtoy,  stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hMedR4S1, wcl[1], wmk[0], "SAME");
  DrawHisto(hMedR4S2, wcl[3], wmk[0], "SAME");
  DrawHisto(hMedR4S3, wcl[4], wmk[0], "SAME");

  leg = new TLegend(0.68, 0.66, 0.98, 0.90); SetupLegend(leg);
  leg->AddEntry(hMedR4S1, "#it{R}_{sub}=0.1", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hMedR4S2, "#it{R}_{sub}=0.2", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hMedR4S3, "#it{R}_{sub}=0.3", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA+JEWEL, medium, #sqrt{#it{s}_{NN}}=2.76 TeV");
  tex->DrawLatex(0.16, 0.84, "Jet: anti-#it{k}_{T}, #it{R}=0.4, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.76, "Sub-jet: #it{k}_{T}");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("IsjMedR05_mean"); can->SetGridx(); can->SetGridy(); //can->SetLogy();
  hfm = can->DrawFrame(dflx,dfly,dfux,dfuy); SetupFrame(hfm,dlsx,dlsy,dtsx,dtsy,dtox,dtoy,  stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(hMedR5S1, wcl[1], wmk[0], "SAME");
  DrawHisto(hMedR5S2, wcl[3], wmk[0], "SAME");
  DrawHisto(hMedR5S3, wcl[4], wmk[0], "SAME");
  DrawHisto(hMedR5S4, wcl[2], wmk[0], "SAME");

  leg = new TLegend(0.58, 0.74, 0.98, 0.90); SetupLegend(leg);
  leg->SetNColumns(2);
  leg->AddEntry(hMedR5S1, "#it{R}_{sub}=0.1", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hMedR5S2, "#it{R}_{sub}=0.2", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hMedR5S3, "#it{R}_{sub}=0.3", "LP")->SetTextSizePixels(24);
  leg->AddEntry(hMedR5S4, "#it{R}_{sub}=0.4", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "PYTHIA+JEWEL, medium, #sqrt{#it{s}_{NN}}=2.76 TeV");
  tex->DrawLatex(0.16, 0.84, "Jet: anti-#it{k}_{T}, #it{R}=0.5, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.76, "Sub-jet: #it{k}_{T}");
  CanvasEnd(can);
//=============================================================================

  return;
}
Ejemplo n.º 14
0
void test_msv(std::string var="m_sv",int nbins=25, double xmin=0, double xmax=250,std::string xtitle="m_sv", std::string ytitle="Events")
{
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");
  TH1::SetDefaultSumw2(1);

  std::string dir = "/afs/cern.ch/work/a/arapyan/public/svfitsamples/";
  double sigscale = 10;
  double sigscale1 = 10; 
  std::stringstream scale; scale << sigscale;
  std::stringstream scale1; scale1 << sigscale1;

  //Cut definitions
  double luminosity = 3000;
  std::stringstream lumi; lumi << luminosity;
  std::string objcut = "(ptTau1>30 && ptTau2>30 && abs(etaTau1) <4.0 && abs(etaTau1)<4.0 )";
  //std::string jetcut = objcut+"*(ptJet1>30 && ptJet2>30 && abs(etaJet1) <4.7 && abs(etaJet2) <4.7 )";
  std::string mthcut = objcut+"*( ( (tauCat1==3 && tauCat2==2) || (tauCat2==3 && tauCat1==2) ) )";

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

  //-------------------------------------------------------------------------
  
  //Get histograms
  TCanvas *canv0 = MakeCanvas("canv", "histograms", 600, 600);
  canv0->cd();
  std::string vardraw;
  TH1F *vbf = new TH1F("VBFH","",nbins,xmin,xmax);
  vardraw = var+">>"+"VBFH";
  tree->Draw(vardraw.c_str(),mthcut.c_str());
  InitSignal(vbf);
  vbf->SetLineColor(kBlack);
  //TH1F *ttbar = new TH1F("TTbar","",nbins,xmin,xmax);
  //vardraw = var+">>"+"TTbar";
  //tree->Draw(vardraw.c_str(),ttbarcut.c_str());
  //InitHist(ttbar, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(155,152,204), 1001);
  TH1F *ztt = new TH1F("Ztt","",nbins,xmin,xmax);
  vardraw = var+">>"+"Ztt";
  tree2->Draw(vardraw.c_str(),mthcut.c_str());
  InitHist(ztt, xtitle.c_str(), ytitle.c_str(), TColor::GetColor(248,206,104), 1001);
  //TH1F *ewk = new TH1F("Ewk","",nbins,xmin,xmax);
  //vardraw = var+">>"+"Ewk";
  //tree->Draw(vardraw.c_str(),ewkcut.c_str());
  //InitHist(ewk, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  TH1F *other = new TH1F("Other","",nbins,xmin,xmax);
  vardraw = var+">>"+"Other";
  tree3->Draw(vardraw.c_str(),mthcut.c_str());
  InitHist(other, xtitle.c_str(), ytitle.c_str(),  TColor::GetColor(222,90,106), 1001);
  
  delete canv0;

  //----------------------------------------------------------------------------
  //Print out the yields
  /*  Double_t error=0.0;
  ofstream outfile;
  outfile.open("yields_test.txt");
  outfile << "Yields for the signal region." << std::endl;
  outfile << "VBF   "  << vbf->IntegralAndError(0,vbf->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "TTbar   "  << ttbar->IntegralAndError(0,ttbar->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(0,ztt->GetNbinsX(),error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "other   "  << other->IntegralAndError(0,other->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << "S/sqrt(B)    "  << vbf->Integral()/(other->Integral()+ztt->Integral()+ttbar->Integral()) << endl;
  //--------------------------------------------------------------------------
  //continue outputing
  //outfile << "Ewk total    "  << ewk->IntegralAndError(0,ewk->GetNbinsX(),error) << "+/-" << error << endl;
  outfile << endl << endl << endl;
  outfile << "In the signal region (100,150GeV)  " <<endl;
  outfile << "VBF   "  << vbf->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "TTbar    "  << ttbar->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "Ztt    "  << ztt->IntegralAndError(5,11,error) << "+/-" << error << endl;
  //outfile << "ewk    "  << ewk->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile << "other    "  << other->IntegralAndError(5,11,error) << "+/-" << error << endl;
  outfile.close();*/
  //-----------------------------------------------------------------------
  //Draw the histograms
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  //ewk->Add(other); ttbar->Add(ewk); 
  //ztt->Add(ttbar); vbf->Add(ztt);
  other->Add(ztt);
  //Error band stat
  TH1F* errorBand = (TH1F*)vbf ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  //  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
  //     if(errorBand->GetBinContent(idx)>0){
  //       std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
  //       break;
  //     }
  //}
  Float_t n=other->GetEntries();
  other->Scale(1.0/n);
  n=vbf->GetEntries();
  vbf->Scale(1.0/n);
  //for (Int_t i=1; i<nbins+1; i++) {
  //cout << "i: " << i << " " <<  other->GetBinCenter(i) << " " << other->Integral(0,i) << " " << other->Integral(i,nbins+1) << endl;
  //}
  cout << " other " << other->Integral(10,15) << endl;
  cout << " htt " << vbf->Integral(10,15) << endl;
  //n=ztt->GetEntries();
  //ztt->Scale(1.0/n);
  other->SetMaximum(1.2*std::max(maximum(vbf, 0), maximum(other, 0)));
  //blind(vbf,75,150);
  //ttbar->Draw("histsame");
  //ewk->Draw("histsame");
  other->Draw("hist");
  //ztt->Draw("histsame");
  vbf->Draw("histsame");
  //errorBand->Draw("e2same");
  canv->RedrawAxis();
  //---------------------------------------------------------------------------
  //Adding a legend
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(vbf , "HH"             , "F");
  //leg->AddEntry(ztt  , "bjj-vbf"  , "F" );
  //leg->AddEntry(ttbar, "t#bar{t}"              , "F" );
  //leg->AddEntry(ewk  , "Electroweak"           , "F" );
  leg->AddEntry(other, "Other"                 , "F" );
  //leg->AddEntry(errorBand,"bkg. uncertainty","F");
  leg->Draw();
  //---------------------------------------------------------------------------

  //CMS preliminary 
  const char* dataset = "CMS Preliminary, H#rightarrow#tau#tau, 3.0 ab^{-1} at 14 TeV";
  const char* category = "";
  CMSPrelim(dataset, "#mu#tau_{h}", 0.17, 0.835);
  //CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->Draw();
  //-------------------------------------------------------------------------
  //Save histograms
  canv->Print((var+"_test.png").c_str());

}
Ejemplo n.º 15
0
int WPtCorrFitDetUnfCalc(const TString BaseName)
{
  TString resultDir = "ResultsFitDetUnf";
  
  gSystem->mkdir(resultDir,kTRUE);

  char tmpName[30];
  
  //double WptLogBins[14] = {1.0,7.5,12.5,17.5,24,30,40,50,70,110,150,190,250,600};
  double WptLogBins[27] = {1.0,3.75,7.5,10,12.5,15,17.5,20.75,24,27,30,35,40,45,50,60,70,90,110,130,150,170,190,220,250,425,600};
  const TString format("png"); 
  
  ofstream Fout;
  Fout.open(resultDir+"/"+BaseName+"_WpMN.txt");

  TFile *fWpMN_MCNom;
  TFile *fWmMN_MCNom;
  TFile *fWpEN_MCNom;
  TFile *fWmEN_MCNom;
  fWpMN_MCNom = new TFile("../Unfolding/Nominal/Muon2012LoPU/WpToMuNu_S8_Unfold.root");
  fWmMN_MCNom = new TFile("../Unfolding/Nominal/Muon2012LoPU/WmToMuNu_S8_Unfold.root");
  fWpEN_MCNom = new TFile("../Unfolding/Nominal/Electron2012LoPU/WpToEleNu_S8_Unfold.root");
  fWmEN_MCNom = new TFile("../Unfolding/Nominal/Electron2012LoPU/WmToEleNu_S8_Unfold.root");

  TFile *fWpMN_RDNom;
  TFile *fWmMN_RDNom;
  TFile *fWpEN_RDNom;
  TFile *fWmEN_RDNom;
  fWpMN_RDNom = new TFile("../Unfolding/WpToMuNuDet/Fit.root");
  fWmMN_RDNom = new TFile("../Unfolding/WmToMuNuDet/Fit.root");
  fWpEN_RDNom = new TFile("../Unfolding/WpToEleNuDet/Fit.root");
  fWmEN_RDNom = new TFile("../Unfolding/WmToEleNuDet/Fit.root");

  TH1D* h1_WpT_WpToMN_MCNom;
  TH1D* h1_WpT_WpToMN_MC_NormToRD;
  TH1D* h1_WpT_WpToMN_RDNom;
  TH1D* h1_WpT_WpToMN_ratio;
  TH1D* h1_WpT_WpToMN_MCNom_Log;

  TH1D* h1_WpT_WmToMN_MCNom;
  TH1D* h1_WpT_WmToMN_MC_NormToRD;
  TH1D* h1_WpT_WmToMN_RDNom;
  TH1D* h1_WpT_WmToMN_ratio;
  TH1D* h1_WpT_WmToMN_MCNom_Log;

  TH1D* h1_WpT_WpToEN_MCNom;
  TH1D* h1_WpT_WpToEN_MC_NormToRD;
  TH1D* h1_WpT_WpToEN_RDNom;
  TH1D* h1_WpT_WpToEN_ratio;
  TH1D* h1_WpT_WpToEN_MCNom_Log;

  TH1D* h1_WpT_WmToEN_MCNom;
  TH1D* h1_WpT_WmToEN_MC_NormToRD;
  TH1D* h1_WpT_WmToEN_RDNom;
  TH1D* h1_WpT_WmToEN_ratio;
  TH1D* h1_WpT_WmToEN_MCNom_Log;
  
  // Plot
  CPlot *pltWpMN, *pltWpMN_ratio;
  CPlot *pltWmMN, *pltWmMN_ratio;
  CPlot *pltWpEN, *pltWpEN_ratio;
  CPlot *pltWmEN, *pltWmEN_ratio;
  TCanvas *myCan;
  myCan = MakeCanvas("myCan","myCan",800,800);
  gStyle->SetEndErrorSize(10);
  gStyle->SetTextFont(132);
  gStyle->SetLegendFont(132);
cout << "check1" << endl;
  //======================
  // Histo from root
  //======================
  h1_WpT_WpToMN_MCNom = (TH1D*)fWpMN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WpToMN_MCNom");
  h1_WpT_WpToMN_MCNom_Log = new TH1D("h1_WpT_WpToMN_MCNom_Log","h1_WpT_WpToMN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WmToMN_MCNom = (TH1D*)fWmMN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WmToMN_MCNom");
  h1_WpT_WmToMN_MCNom_Log = new TH1D("h1_WpT_WmToMN_MCNom_Log","h1_WpT_WmToMN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WpToEN_MCNom = (TH1D*)fWpEN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WpToEN_MCNom");
  h1_WpT_WpToEN_MCNom_Log = new TH1D("h1_WpT_WpToEN_MCNom_Log","h1_WpT_WpToEN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WmToEN_MCNom = (TH1D*)fWmEN_MCNom->Get("h1_Truth_Post")->Clone("h1_WpT_WmToEN_MCNom");
  h1_WpT_WmToEN_MCNom_Log = new TH1D("h1_WpT_WmToEN_MCNom_Log","h1_WpT_WmToEN_MCNom_Log",13,WptLogBins);
  
  //h1_WpT_WpToMN_MCNom = (TH1D*)fWpMN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WpToMN_MCNom");
  //h1_WpT_WpToMN_MCNom_Log = new TH1D("h1_WpT_WpToMN_MCNom_Log","h1_WpT_WpToMN_MCNom_Log",13,WptLogBins);
 

  //h1_WpT_WmToMN_MCNom = (TH1D*)fWmMN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WmToMN_MCNom");
  //h1_WpT_WmToMN_MCNom_Log = new TH1D("h1_WpT_WmToMN_MCNom_Log","h1_WpT_WmToMN_MCNom_Log",13,WptLogBins);
  //
  //h1_WpT_WpToEN_MCNom = (TH1D*)fWpEN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WpToEN_MCNom");
  //h1_WpT_WpToEN_MCNom_Log = new TH1D("h1_WpT_WpToEN_MCNom_Log","h1_WpT_WpToEN_MCNom_Log",13,WptLogBins);
  //
  //h1_WpT_WmToEN_MCNom = (TH1D*)fWmEN_MCNom->Get("h1_Truth_Post_DoubleBin")->Clone("h1_WpT_WmToEN_MCNom");
  //h1_WpT_WmToEN_MCNom_Log = new TH1D("h1_WpT_WmToEN_MCNom_Log","h1_WpT_WmToEN_MCNom_Log",13,WptLogBins);
  
  h1_WpT_WpToMN_MCNom->Sumw2();
  h1_WpT_WmToMN_MCNom->Sumw2();
  h1_WpT_WpToEN_MCNom->Sumw2();
  h1_WpT_WmToEN_MCNom->Sumw2();
 
  h1_WpT_WpToMN_MCNom->Scale(18.429*1*7322.0/935446);
  h1_WpT_WmToMN_MCNom->Scale(18.429*1*5181.0/1.97346e6);
  h1_WpT_WpToEN_MCNom->Scale(18.429*1*7322.0/2401905);
  h1_WpT_WmToEN_MCNom->Scale(18.429*1*5181.0/2127666);
 
  h1_WpT_WpToMN_RDNom = (TH1D*)fWpMN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WpToMN_RDNom");
  h1_WpT_WmToMN_RDNom = (TH1D*)fWmMN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WmToMN_RDNom");
  h1_WpT_WpToEN_RDNom = (TH1D*)fWpEN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WpToEN_RDNom");
  h1_WpT_WmToEN_RDNom = (TH1D*)fWmEN_RDNom->Get("h1_Fit__x")->Clone("h1_WpT_WmToEN_RDNom");
  //h1_WpT_WpToMN_RDNom->Sumw2();
  //h1_WpT_WmToMN_RDNom->Sumw2();
  //h1_WpT_WpToEN_RDNom->Sumw2();
  //h1_WpT_WmToEN_RDNom->Sumw2();

  h1_WpT_WpToMN_RDNom->Scale(h1_WpT_WpToMN_MCNom->Integral()/h1_WpT_WpToMN_RDNom->Integral());
  h1_WpT_WmToMN_RDNom->Scale(h1_WpT_WmToMN_MCNom->Integral()/h1_WpT_WmToMN_RDNom->Integral());
  h1_WpT_WpToEN_RDNom->Scale(h1_WpT_WpToEN_MCNom->Integral()/h1_WpT_WpToEN_RDNom->Integral());
  h1_WpT_WmToEN_RDNom->Scale(h1_WpT_WmToEN_MCNom->Integral()/h1_WpT_WmToEN_RDNom->Integral());

  cout << "===W+ Mu Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WpToMN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WpToMN_RDNom->GetBinContent(i) << endl;
  }
  
  cout << "===W- Mu Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WmToMN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WmToMN_RDNom->GetBinContent(i) << endl;
  }
  
  cout << "===W+ Ele Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WpToEN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WpToEN_RDNom->GetBinContent(i) << endl;
  }
  
  cout << "===W- Ele Yield (Truth_Post) (Fit)===" <<endl;
  for(int i(1);i<14;i++){
    cout<<"bin "<<i<<"\t" << h1_WpT_WmToEN_MCNom->GetBinContent(i) << "\t\t"<< h1_WpT_WmToEN_RDNom->GetBinContent(i) << endl;
  }
  h1_WpT_WpToMN_ratio = (TH1D*)h1_WpT_WpToMN_RDNom->Clone("h1_WpT_WpToMN_ratio");
  h1_WpT_WmToMN_ratio = (TH1D*)h1_WpT_WmToMN_RDNom->Clone("h1_WpT_WmToMN_ratio");
  h1_WpT_WpToEN_ratio = (TH1D*)h1_WpT_WpToEN_RDNom->Clone("h1_WpT_WpToEN_ratio");
  h1_WpT_WmToEN_ratio = (TH1D*)h1_WpT_WmToEN_RDNom->Clone("h1_WpT_WmToEN_ratio");
  //cout<<"number h1_WpT_WpToMN_ratio: "<<h1_WpT_WpToMN_ratio->Integral()<<endl;
  h1_WpT_WpToMN_MC_NormToRD = (TH1D*)h1_WpT_WpToMN_MCNom->Clone("h1_WpT_WpToMN_MC_NormToRD");
  h1_WpT_WmToMN_MC_NormToRD = (TH1D*)h1_WpT_WmToMN_MCNom->Clone("h1_WpT_WmToMN_MC_NormToRD");
  h1_WpT_WpToEN_MC_NormToRD = (TH1D*)h1_WpT_WpToEN_MCNom->Clone("h1_WpT_WpToEN_MC_NormToRD");
  h1_WpT_WmToEN_MC_NormToRD = (TH1D*)h1_WpT_WmToEN_MCNom->Clone("h1_WpT_WmToEN_MC_NormToRD");
  //cout<<"Number h1_WpT_WpToMN_MC: "<<h1_WpT_WpToMN_MC_NormToRD->Integral()<<endl;
  h1_WpT_WpToMN_MC_NormToRD->Scale(h1_WpT_WpToMN_ratio->Integral()/h1_WpT_WpToMN_MC_NormToRD->Integral());
  h1_WpT_WmToMN_MC_NormToRD->Scale(h1_WpT_WmToMN_ratio->Integral()/h1_WpT_WmToMN_MC_NormToRD->Integral());
  h1_WpT_WpToEN_MC_NormToRD->Scale(h1_WpT_WpToEN_ratio->Integral()/h1_WpT_WpToEN_MC_NormToRD->Integral());
  h1_WpT_WmToEN_MC_NormToRD->Scale(h1_WpT_WmToEN_ratio->Integral()/h1_WpT_WmToEN_MC_NormToRD->Integral());
  cout<<"Number h1_WpT_WpToMN_MC_NormToRD: "<<h1_WpT_WpToMN_MC_NormToRD->Integral()<<endl;
  h1_WpT_WpToMN_ratio->Divide(h1_WpT_WpToMN_MC_NormToRD);
  h1_WpT_WmToMN_ratio->Divide(h1_WpT_WmToMN_MC_NormToRD);
  h1_WpT_WpToEN_ratio->Divide(h1_WpT_WpToEN_MC_NormToRD);
  h1_WpT_WmToEN_ratio->Divide(h1_WpT_WmToEN_MC_NormToRD);
  
  for(int i(1);i<=13;i++)
  {
    cout<<"Bin "<<i<<" : " <<"Mu+:  "<< h1_WpT_WpToMN_ratio->GetBinContent(i) <<"\t"<<"Mu-:  "<<h1_WpT_WmToMN_ratio->GetBinContent(i)<< endl;
  } 
  for(int i(1);i<=13;i++)
  {
    cout<<"Bin "<<i<<" : "  <<"Ele+:  "<<h1_WpT_WpToEN_ratio->GetBinContent(i)<<"\t"<<"Ele-:  "<<h1_WpT_WmToEN_ratio->GetBinContent(i)<< endl;
  } 




  for(int ipt(1);ipt<=13;ipt++)
  {
    h1_WpT_WpToMN_MCNom_Log->SetBinContent(ipt,h1_WpT_WpToMN_MCNom->GetBinContent(ipt));
    h1_WpT_WmToMN_MCNom_Log->SetBinContent(ipt,h1_WpT_WmToMN_MCNom->GetBinContent(ipt));
    h1_WpT_WpToEN_MCNom_Log->SetBinContent(ipt,h1_WpT_WpToEN_MCNom->GetBinContent(ipt));
    h1_WpT_WmToEN_MCNom_Log->SetBinContent(ipt,h1_WpT_WmToEN_MCNom->GetBinContent(ipt));
  
  }
  sprintf(tmpName,"WpT_WpMN");
  pltWpMN= new CPlot(tmpName,"",tmpName,"events/bin");
  sprintf(tmpName,"WpT_WmMN");
  pltWmMN= new CPlot(tmpName,"",tmpName,"events/bin");
  sprintf(tmpName,"WpT_WpEN");
  pltWpEN= new CPlot(tmpName,"",tmpName,"events/bin");
  sprintf(tmpName,"WpT_WmEN");
  pltWmEN= new CPlot(tmpName,"",tmpName,"events/bin");
  //h1_WpT_WpToMN_MC->SetFillColor(2);
  //h1_WpT_WpToMN_MC->SetMarkerStyle(2);
  //h1_WpT_WpToMN_MC->SetMarkerSize(2);
  //h1_WpT_WpToMN_MC->SetMarkerColor(0);
  //h1_WpT_WpToMN_MC->Draw("h");
  pltWpMN->setOutDir(resultDir);
  pltWmMN->setOutDir(resultDir);
  pltWpEN->setOutDir(resultDir);
  pltWmEN->setOutDir(resultDir);
  //           // hist, drawopt, color, linesty, fillsty, mkerSty, mkerSize
  //pltWpMN->AddHist1D(h1_WpT_WpToMN_MCNom_Log,"hist",kGreen,1,0,0,0);
  //pltWmMN->AddHist1D(h1_WpT_WmToMN_MCNom_Log,"hist",kGreen,1,0,0,0);
  //pltWpMN->AddHist1D(h1_WpT_WpToMN_RDNom,"elp",kBlack,1,0,20,1);
  //pltWmMN->AddHist1D(h1_WpT_WmToMN_RDNom,"elp",kBlack,1,0,20,1);
  pltWpMN->AddHist1D(h1_WpT_WpToMN_MCNom_Log,"H",kGreen,1,1001,2,0);
  pltWmMN->AddHist1D(h1_WpT_WmToMN_MCNom_Log,"H",kGreen,1,1001,2,0);
  pltWpMN->AddHist1D(h1_WpT_WpToMN_RDNom,"elp",kBlack,1,0,21,1);
  pltWmMN->AddHist1D(h1_WpT_WmToMN_RDNom,"elp",kBlack,1,0,21,1);

  pltWpEN->AddHist1D(h1_WpT_WpToEN_MCNom_Log,"H",3,1,1001,2,0);
  pltWmEN->AddHist1D(h1_WpT_WmToEN_MCNom_Log,"H",3,1,1001,2,0);
  pltWpEN->AddHist1D(h1_WpT_WpToEN_RDNom,"E",kBlack,1,0,21,1);
  pltWmEN->AddHist1D(h1_WpT_WmToEN_RDNom,"E",kBlack,1,0,21,1);

  pltWpMN->SetLegend(0.53,0.7,0.7,0.8);
  pltWmMN->SetLegend(0.53,0.7,0.7,0.8);
  pltWpEN->SetLegend(0.53,0.7,0.7,0.8);
  pltWmEN->SetLegend(0.53,0.7,0.7,0.8);
  //cout << "check4" << endl;

  pltWpMN->GetLegend()->SetTextSize(0.03);
  pltWmMN->GetLegend()->SetTextSize(0.03);
  pltWpEN->GetLegend()->SetTextSize(0.03);
  pltWmEN->GetLegend()->SetTextSize(0.03);

  pltWpMN->GetLegend()->AddEntry(h1_WpT_WpToMN_MCNom_Log,"Nominal Truth Post","l");
  pltWmMN->GetLegend()->AddEntry(h1_WpT_WmToMN_MCNom_Log,"Nominal Truth Post","l");
  pltWpMN->GetLegend()->AddEntry(h1_WpT_WpToMN_RDNom,"DetUnf Fit Data ","p");
  pltWmMN->GetLegend()->AddEntry(h1_WpT_WmToMN_RDNom,"DetUnf Fit Data ","p");

  pltWpEN->GetLegend()->AddEntry(h1_WpT_WpToEN_MCNom_Log,"Nominal Truth Post","l");
  pltWmEN->GetLegend()->AddEntry(h1_WpT_WmToEN_MCNom_Log,"Nominal Truth Post","l");
  pltWpEN->GetLegend()->AddEntry(h1_WpT_WpToEN_RDNom,"DetUnf Fit Data","p");
  pltWmEN->GetLegend()->AddEntry(h1_WpT_WmToEN_RDNom,"DetUnf Fit Data","p");

  pltWpMN->SetLogx();
  pltWmMN->SetLogx();
  pltWpEN->SetLogx();
  pltWmEN->SetLogx();
  
  
  pltWpMN->Draw(myCan,kTRUE,format);
  pltWmMN->Draw(myCan,kTRUE,format);
  pltWpEN->Draw(myCan,kTRUE,format);
  pltWmEN->Draw(myCan,kTRUE,format);

  sprintf(tmpName,"WpT_WpMN_ratio");
  pltWpMN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");
  sprintf(tmpName,"WpT_WmMN_ratio");
  pltWmMN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");

  sprintf(tmpName,"WpT_WpEN_ratio");
  pltWpEN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");
  sprintf(tmpName,"WpT_WmEN_ratio");
  pltWmEN_ratio= new CPlot(tmpName,"",tmpName,"ratio/bin");

  pltWpMN_ratio->setOutDir(resultDir);
  pltWmMN_ratio->setOutDir(resultDir);
  pltWpEN_ratio->setOutDir(resultDir);
  pltWmEN_ratio->setOutDir(resultDir);

  pltWpMN_ratio->AddHist1D(h1_WpT_WpToMN_ratio,"E",1,1,1001,21,1);
  pltWmMN_ratio->AddHist1D(h1_WpT_WmToMN_ratio,"E",1,1,1001,21,1);
  pltWpEN_ratio->AddHist1D(h1_WpT_WpToEN_ratio,"E",1,1,1001,21,1);
  pltWmEN_ratio->AddHist1D(h1_WpT_WmToEN_ratio,"E",1,1,1001,21,1);

  pltWpMN_ratio->SetLegend(0.7,0.8,0.9,0.9);
  pltWmMN_ratio->SetLegend(0.7,0.8,0.9,0.9);
  pltWpEN_ratio->SetLegend(0.7,0.8,0.9,0.9);
  pltWmEN_ratio->SetLegend(0.7,0.8,0.9,0.9);

  pltWpMN_ratio->GetLegend()->SetTextSize(0.03);
  pltWmMN_ratio->GetLegend()->SetTextSize(0.03);
  pltWpEN_ratio->GetLegend()->SetTextSize(0.03);
  pltWmEN_ratio->GetLegend()->SetTextSize(0.03);

  //pltWpMN_ratio->GetLegend()->AddEntry(h1_WpT_WpToMN_ratio,"WpToMN PostFSR Data/MC TruthPost");
  //pltWmMN_ratio->GetLegend()->AddEntry(h1_WpT_WmToMN_ratio,"WmToMN PostFSR Data/MC TruthPost");
  //pltWpEN_ratio->GetLegend()->AddEntry(h1_WpT_WpToEN_ratio,"WpToEN PostFSR Data/MC TruthPost");
  //pltWmEN_ratio->GetLegend()->AddEntry(h1_WpT_WmToEN_ratio,"WmToEN PostFSR Data/MC TruthPost");

  pltWpMN_ratio->GetLegend()->AddEntry(h1_WpT_WpToMN_ratio,"WpToMN DetUnfFit Data/MC TruthPost");
  pltWmMN_ratio->GetLegend()->AddEntry(h1_WpT_WmToMN_ratio,"WmToMN DetUnfFit Data/MC TruthPost");
  pltWpEN_ratio->GetLegend()->AddEntry(h1_WpT_WpToEN_ratio,"WpToEN DetUnfFit Data/MC TruthPost");
  pltWmEN_ratio->GetLegend()->AddEntry(h1_WpT_WmToEN_ratio,"WmToEN DetUnfFit Data/MC TruthPost");
  
  pltWpMN_ratio->SetLogx();
  pltWmMN_ratio->SetLogx();
  pltWpEN_ratio->SetLogx();
  pltWmEN_ratio->SetLogx();
  
  pltWpMN_ratio->Draw(myCan,kTRUE,format);
  pltWmMN_ratio->Draw(myCan,kTRUE,format);
  pltWpEN_ratio->Draw(myCan,kTRUE,format);
  pltWmEN_ratio->Draw(myCan,kTRUE,format);

  //TFile *RootOut= new TFile("./WpT_PostFSRData_MC_ratio.root","recreate");
  TFile *RootOut= new TFile("../RstSelection/WpT_FitDetUnfData_MC_ratio.root","recreate");
  h1_WpT_WpToMN_ratio->Write();
  h1_WpT_WmToMN_ratio->Write();
  h1_WpT_WpToEN_ratio->Write();
  h1_WpT_WmToEN_ratio->Write();
  RootOut->Close();
  
  Fout.close();
  myCan->Clear();

  return 0;
}
Ejemplo n.º 16
0
void njet_mWW_Scale()
{
  //TString OutDir = "mWW_sf_reweighted";
  TString OutDir = "mWW_sf_unweighted";
  gSystem->mkdir(OutDir);
  
  TFile *fname_phantom;
  TFile *fname_powheg;

  fname_phantom  = new TFile("phantom/phantom_CommonCut_VBFnjet.root");
  fname_powheg   = new TFile("POWHEG_VBF_unweighted/POWHEG_VBF_CommonCut_VBFnjet.root");
  //fname_powheg   = new TFile("POWHEG_VBF_reweighted/POWHEG_VBF_CommonCut_VBFnjet.root");

  //Histograms
  TH1D* h1_njet_phantom[12];
  TH1D* h1_njet_powheg[12];
  TH1D* h1_njet_noW_phantom[12];
  TH1D* h1_njet_noW_powheg[12];
  TH1D* h1_reWeightFac[12];
  TH1D* h1_powheg_phantom[4];

  //Inclusive jet bin mWW histograms
  TH1D* h1_mWW_phantom;
  TH1D* h1_mWW_powheg;
  TH1D* h1_mWW_noW_phantom;
  TH1D* h1_mWW_noW_powheg;
  
  //Inclusive Total number
  double nTotalPha;
  double nTotalPow;
  
  double ymax;
  double err_phantom;
  double err_powheg;

  char tmpName[50];
  char histName[50];
  char mWWrange[50];

  double Bins[12] = {130.,200.,300.,400.,500.,600.,700.,800.,900.,1000.,1250.,1500.};
  TH1D *h1_tmp = new TH1D("h1_tmp","",11,Bins); h1_tmp->Sumw2();

  TCanvas *myCan = MakeCanvas("myCan", "myCan", 900, 800);

  //Read Histograms from root file
  for(int i(0);i<12;i++)
  {
    sprintf(tmpName,"h1_njet_OffSh_%d",i);

    sprintf(histName,"h1_njet_phantom_%d",i);
    h1_njet_phantom[i] = (TH1D*)fname_phantom->Get(tmpName)->Clone(histName); h1_njet_phantom[i]->Sumw2();
    
    sprintf(histName,"h1_njet_powheg_%d",i);
    h1_njet_powheg[i] = (TH1D*)fname_powheg->Get(tmpName)->Clone(histName); h1_njet_powheg[i]->Sumw2();
    
    sprintf(tmpName,"h1_njet_OffSh_noWeight_%d",i);

    sprintf(histName,"h1_njet_noW_phantom_%d",i);
    h1_njet_noW_phantom[i] = (TH1D*)fname_phantom->Get(tmpName)->Clone(histName); h1_njet_noW_phantom[i]->Sumw2();
    
    sprintf(histName,"h1_njet_noW_powheg_%d",i);
    h1_njet_noW_powheg[i] = (TH1D*)fname_powheg->Get(tmpName)->Clone(histName); h1_njet_noW_powheg[i]->Sumw2();

    for (int j(1);j<=h1_njet_phantom[i]->GetNbinsX();j++)
    {
      err_phantom = 0.;
      err_powheg  = 0.;
      if(h1_njet_noW_phantom[i]->GetBinContent(j)>0.)
        err_phantom = h1_njet_phantom[i]->GetBinContent(j) * sqrt(h1_njet_noW_phantom[i]->GetBinContent(j))/h1_njet_noW_phantom[i]->GetBinContent(j);
      if(h1_njet_noW_powheg[i]->GetBinContent(j)>0.)
        err_powheg = h1_njet_powheg[i]->GetBinContent(j) * sqrt(h1_njet_noW_powheg[i]->GetBinContent(j))/h1_njet_noW_powheg[i]->GetBinContent(j);
      h1_njet_phantom[i] -> SetBinError(j,err_phantom);
      h1_njet_powheg[i]  -> SetBinError(j,err_powheg);
    }
  }

  //Read inclusive jet bin mWW histograms
  h1_mWW_phantom = (TH1D*)fname_phantom->Get("h1_mww_off_CalcPowRew_4")->Clone("h1_mWW_phantom"); //h1_mWW_phantom->Sumw2();
  h1_mWW_powheg  = (TH1D*)fname_powheg ->Get("h1_mww_off_CalcPowRew_4")->Clone("h1_mWW_powheg"); //h1_mWW_powheg->Sumw2();
  h1_mWW_noW_phantom = (TH1D*)fname_phantom->Get("h1_mww_off_CalcPowRew_noWeight_4")->Clone("h1_mWW_noW_phantom"); //h1_mWW_noW_phantom->Sumw2();
  h1_mWW_noW_powheg  = (TH1D*)fname_powheg ->Get("h1_mww_off_CalcPowRew_noWeight_4")->Clone("h1_mWW_noW_powheg"); //h1_mWW_noW_powheg->Sumw2();
  
  for (int j(1);j<=h1_mWW_phantom->GetNbinsX();j++)
  {
    err_phantom = 0.;
    err_powheg  = 0.;
    if(h1_mWW_noW_phantom->GetBinContent(j)>0.)
      err_phantom = h1_mWW_phantom->GetBinContent(j) * sqrt(h1_mWW_noW_phantom->GetBinContent(j))/h1_mWW_noW_phantom->GetBinContent(j);
    if(h1_mWW_noW_powheg->GetBinContent(j)>0.)
      err_powheg = h1_mWW_powheg->GetBinContent(j) * sqrt(h1_mWW_noW_powheg->GetBinContent(j))/h1_mWW_noW_powheg->GetBinContent(j);
    h1_mWW_phantom -> SetBinError(j,err_phantom);
    h1_mWW_powheg  -> SetBinError(j,err_powheg);
  }
  
  //Inclusive Total number
  nTotalPha = h1_mWW_phantom -> Integral();
  nTotalPow = h1_mWW_powheg  -> Integral();

  //Inclusive Total number
  for(int i(0);i<12;i++)
  {
    h1_njet_phantom[i] -> Scale(1./nTotalPha);
    h1_njet_powheg[i]  -> Scale(1./nTotalPow);
    
    //Scale factors calculation for each jet bin
    sprintf(histName,"h1_reWeightFac_%d",i);
    h1_reWeightFac[i] = (TH1D*)h1_njet_powheg[i] -> Clone(histName); h1_reWeightFac[i]->Sumw2();
    h1_reWeightFac[i] -> Divide(h1_njet_phantom[i]);
    
    //Printout powheg/phantom scale factor for each mWW windows
    if(i==11)
      sprintf(mWWrange,"mWW > 130");
    else
      sprintf(mWWrange,"%.1f < mWW #leq %.1f",Bins[i],Bins[i+1]);
    for (int j(1);j<=h1_reWeightFac[i]->GetNbinsX();j++)
    {
      cout<<mWWrange<<"-bin, "<<j-1<<"=njet: "<<h1_reWeightFac[i]->GetBinContent(j)<<" +/- "<<h1_reWeightFac[i]->GetBinError(j)<<endl;
    }
    
    ymax = 1.15*(h1_njet_phantom[i]->GetMaximum()); 
    if(i==0 || i==11)
      ymax = 1.15*(h1_njet_powheg[i]->GetMaximum()); 
    
    //Save Histograms to file
    sprintf(histName,"Bin_%d",i);
    if(i==11)
      sprintf(histName,"incl_Bin");
    CPlot* plotNjet=new CPlot(histName,"","number of jets","");
    plotNjet->setOutDir(OutDir);
    if(i==11)
    {
      plotNjet->AddHist1D(h1_njet_powheg[i],"E1",kRed);
      plotNjet->AddHist1D(h1_njet_phantom[i],"E1",kBlue);
    }else{
      plotNjet->AddHist1D(h1_njet_powheg[i],"HIST",kRed);
      plotNjet->AddHist1D(h1_njet_phantom[i],"HIST",kBlue);
    }
    plotNjet->SetLegend(0.63,0.84,0.88,0.92);
    plotNjet->GetLegend()->AddEntry(h1_njet_powheg[i],"POWHEG","l");
    plotNjet->GetLegend()->AddEntry(h1_njet_phantom[i],"Phantom Sig.","l");
    plotNjet->AddTextBox(mWWrange,0.6,0.92,0.92,0.95,0);
    plotNjet->SetYRange(-0.001,ymax);
    plotNjet->Draw(myCan,kTRUE,"png");

    h1_njet_powheg[i]->Divide(h1_njet_phantom[i]);
    
    sprintf(histName,"Bin_%d_Ratio",i);
    if(i==11)
    {
      sprintf(histName,"incl_Bin_Ratio");
      cout<<h1_njet_powheg[i]->GetBinContent(3)<<"\t"<<h1_njet_powheg[i]->GetBinContent(4)<<endl;
    }
    CPlot* plotRatio=new CPlot(histName,"","number of jets","POWHEG/Phantom");
    plotRatio->setOutDir(OutDir);
    plotRatio->AddHist1D(h1_njet_powheg[i],"HIST",kRed);
    plotRatio->SetLegend(0.63,0.84,0.88,0.92);
    //plotRatio->GetLegend()->AddEntry(h1_njet_powheg[i],"POWHEG","l");
    plotRatio->AddTextBox(mWWrange,0.6,0.92,0.92,0.95,0);
    plotRatio->SetYRange(-0.001,1.15*(h1_njet_powheg[i]->GetMaximum()));
    plotRatio->Draw(myCan,kTRUE,"png");
  }

  //Write Scale Factors to root file
  TFile f_out(OutDir+"/scaleFactors.root","recreate");
  h1_mWW_phantom -> Scale(1./nTotalPha);
  h1_mWW_powheg  -> Scale(1./nTotalPow);
  h1_mWW_powheg  -> Divide(h1_mWW_phantom);
  for (int i(0);i<5;i++)
  {
    if(i==4)
    {
      h1_powheg_phantom[i] = (TH1D*)h1_mWW_powheg -> Clone("h1_powheg_phantom_4"); h1_powheg_phantom[i]->Sumw2();
    }else{
      sprintf(histName,"h1_powheg_phantom_%d",i);
      h1_powheg_phantom[i] = (TH1D*)h1_tmp -> Clone(histName); h1_powheg_phantom[i]->Sumw2();
      for (int j(1);j<=h1_powheg_phantom[i]->GetNbinsX();j++)
      {
	h1_powheg_phantom[i] -> SetBinContent(j,h1_reWeightFac[j-1]->GetBinContent(i+1));
	h1_powheg_phantom[i] -> SetBinError(j,h1_reWeightFac[j-1]->GetBinError(i+1));
      }
    }
    h1_powheg_phantom[i] -> Write();
  }
}
Ejemplo n.º 17
0
int scaleSmearFit(TString RDFile, TString MCFile, char BaseName[30])
{
  cout<<"Processing "<<BaseName<<endl;
  gStyle->SetPalette(1);
  //Data and histograms
  TFile *f_RD = new TFile(RDFile);
  TFile *f_MC = new TFile(MCFile);
  TH1D *h1_ZmassDaughEtaRD = (TH1D*)f_RD->Get("h1_ZmassDaughEtaRD")->Clone();
  TH1D *h1_ZmassDaughEtaMC[ScaleBins][ScaleBins];
  //Variables
  char histName[30];
  RooRealVar zMass("zMass","zMass",60,120);
  RooRealVar *nMC;
  RooRealVar nBRD("nBRD","nBRD",5,2000);
  RooRealVar nSRD("nSRD","nSRD",1000,0,20000);
  RooRealVar nBMC("nBMC","nBMC",5,2000);
  RooRealVar nSMC("nSMC","nSMC",1000,0,20000);
  RooPlot *zmassframe;
  RooPlot *zmassframeMC;
  CPlot *plotFit;
  CPlot *plotFitMC;
  //zMass.setBins(50);
  RooFitResult* fitRes;
  RooFitResult* fitResMC;
  TCanvas *myCan = MakeCanvas("myCan","myCan",800,600);
  RooDataHist *ZmassMC;
  //RooHistPdf *pdfMC;
  RooAddPdf *pdfMC;
  RooAddPdf* pdfRD;
  //RD fitting
  RooDataHist *ZmassRD =
    new RooDataHist("ZmassRD","ZmassRD", RooArgSet(zMass),h1_ZmassDaughEtaRD);
  //CBreitWignerConvCrystalBall ZsignalPdf("ZsigPdf",zMass);
  //pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsignalPdf.model)),RooArgList(nRD));
  CVoigtian     ZsigRD("ZsigRD",zMass);
  CErfExpo ZbgRD("ZbgRD",zMass);
  //CQuadraticExp ZbgRD("ZbgRD",zMass);
  pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD));
  pdfRD=new RooAddPdf("pdfRD","pdfRD",RooArgList(*(ZsigRD.model),*(ZbgRD.model)),RooArgList(nSRD,nBRD));
  fitRes=pdfRD->fitTo(*ZmassRD,Extended(),Minos(kTRUE),Save(kTRUE));
  //fitRes=ZsignalPdf.model->fitTo(*ZmassRD,Minos(kTRUE),Save(kTRUE));
  zmassframe=zMass.frame(Bins(60));
  ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp"));
  //ZsignalPdf.model->plotOn(zmassframe,LineColor(kBlue),DrawOption("l"));
  pdfRD->plotOn(zmassframe,LineColor(kBlack),DrawOption("l"));
  pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZsigRD.model))),LineColor(kBlue),DrawOption("l"));
  pdfRD->plotOn(zmassframe,Components(RooArgSet(*(ZbgRD.model))),LineColor(kRed),DrawOption("l"));
  sprintf(histName,"ZmassRD_%s",BaseName);
  plotFit = new CPlot(histName,zmassframe,"","","Z mass");
  plotFit->setOutDir("Plot");
  plotFit->Draw(myCan,kTRUE,"png");

  //CErfExpo *pdfZbg;
  //double nLL[41][41];

  //                                 90 0.004
  double ScaleWidth = (ScaleH-ScaleL)/(ScaleBins-1);
  double SmearWidth = (SmearH-SmearL)/(ScaleBins-1);
  sprintf(histName,"h2_NLL_%s",BaseName);
  TH2D *h2_NLL = new TH2D(histName,histName,
      ScaleBins,ScaleL-ScaleWidth/2,ScaleH+ScaleWidth/2,
      ScaleBins,SmearL-SmearWidth/2,SmearH+SmearWidth/2);
  //TH2D *h2_NLL = new TH2D("h2_NLL","NLL",41,0.97,1.05,41,0.5,1.5);
  double x,prob;
  //RooAbsReal *nll;
  double nll;
  double binContent;
  //***
  CVoigtian ZsigMC("ZsigMC",zMass);
  RooArgSet allArgset(zMass);
  RooArgSet anaVar;
  //for(int i(0);i<=0;i++)for(int j(0);j<=0;j++)
  for(int i(0);i<=ScaleBins-1;i++)for(int j(0);j<=ScaleBins-1;j++)
  {
    sprintf(histName,"h1_ZmassDaughEta_%d_%d",i,j);
    h1_ZmassDaughEtaMC[i][j] = (TH1D*)f_MC->Get(histName)->Clone(histName);
    ZmassMC =
      new RooDataHist("ZmassMC","ZmassMC",RooArgSet(zMass),h1_ZmassDaughEtaMC[i][j]);
    //                                               interpolation order
    //pdfMC =new RooHistPdf ("pdfMC", "pdfMC", zMass,*ZmassMC, 1);
    //Using fitting MC
    nSMC.setVal(285);
    ZsigMC.mass->setVal(91.37);
    ZsigMC.sigma->setVal(0.42);
    ZsigMC.width->setVal(4.4);
    pdfMC = new RooAddPdf("pdfMC","pdfMC",RooArgList(*(ZsigMC.model)),RooArgList(nSMC));
    fitResMC = pdfMC->fitTo(*ZmassMC,Extended(),Minos(kTRUE),Save(kTRUE),SumW2Error(kTRUE));//SumW2Error(kTRUE) default

    nll=0;
    //nll= h1_ZmassDaughEtaMC[i][j]->Chi2Test(h1_ZmassDaughEtaRD,"CHI2/NDF");
    // code 1000 dataHist sum
    int intCode = pdfMC->getAnalyticalIntegral(allArgset,anaVar);
    double norm = pdfMC->analyticalIntegral(intCode);
    cout<<"norm: code "<<norm<<" : "<<intCode<<"======================"<<endl;
    //double totalProb(0);
    //****
    for(int k(1);k<=60;k++)
    {
      x=h1_ZmassDaughEtaMC[i][j]->GetBinCenter(k);
    //  binContent = h1_ZmassDaughEtaRD->GetBinContent(k);
      //binContent = h1_ZmassDaughEtaMC[i][j]->GetBinContent(k);
      zMass=x;
      //prob = ZsignalPdf.model->evaluate();
      binContent = ZsigRD.model->evaluate()*(120-60)/60.*nSRD.getVal();
      prob = pdfMC->evaluate()*(120-60)/60.;
      //cout<<"binCont, prob "<<binContent<<" "<<prob<<endl;
      //totalProb +=prob;
      nll+=-binContent*log(prob);
      //cout<<" x: prob "<<x<<"  "<<prob<<endl;
    }
    h2_NLL->SetBinContent(i+1,j+1,nll);
    /***/
    //
    //
    if( j==0 || j==int(ScaleBins/2)|| j==(ScaleBins-1) )
    {
      //RD MCpdf RDpdf Plot
      zmassframe =zMass.frame(Bins(60));
      ZmassRD->plotOn(zmassframe,MarkerStyle(kFullCircle),MarkerSize(0.9),DrawOption("zp"));
      pdfRD->plotOn(zmassframe,LineColor(kBlack));
      pdfMC->plotOn(zmassframe,LineColor(kBlue));
      //pdfRD->plotOn(zmassframe,Components(RooArgSet(*(pdfZbg->model))),LineColor(kRed));
      sprintf(histName,"Zmass_%s_%d_%d",BaseName,i,j);
      plotFit = new CPlot(histName,zmassframe,"","","Z mass");
      plotFit->SetLegend(0.68,0.57,0.93,0.8);
      plotFit->GetLegend()->AddEntry(pdfRD,"RD","f");
      plotFit->GetLegend()->AddEntry(pdfMC,"MC","f");
      plotFit->setOutDir("Plot");
      plotFit->Draw(myCan,kTRUE,"png");
      //MC MCPdf Plot
      zmassframeMC = zMass.frame(Bins(60));
      ZmassMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("p"));
      pdfMC->plotOn(zmassframeMC,LineColor(kBlue),DrawOption("l"));
      sprintf(histName,"ZmassMC_%s_%d_%d",BaseName,i,j);
      plotFitMC = new CPlot(histName,zmassframeMC,"","","Z mass MC");
      plotFitMC->setOutDir("Plot");
      plotFitMC->Draw(myCan,kTRUE,"png");
    }
  }
  //====
  //Plot
  //====
  //Zmass----------
  //CPlot *plotZmassRD=new CPlot("plotZmassRD","","zMass","Event");
  //plotZmassRD->setOutDir("Plot");
  //plotZmassRD->AddHist1D(h1_ZmassDaughEtaRD,"",kBlack);
  //plotZmassRD->SetLegend(0.68,0.57,0.93,0.8);
  //plotZmassRD->GetLegend()->AddEntry(h1_ZmassDaughEtaRD,"RD Ele","l");
  //plotZmassRD->AddTextBox("both lepton at the |Eta|<0.4",0.65,0.80,0.99,0.86,0);
  //plotZmassRD->Draw(myCan,kTRUE,"png");
  //NLL------------
  sprintf(histName,"plotNLL_%s",BaseName);
  CPlot *plotNll=new CPlot(histName,"","Scale","Smear");
  plotNll->setOutDir("Plot");
  //plotNll->AddHist2D(h2_NLL,"COLZ",kWhite,kBlack);
  plotNll->AddHist2D(h2_NLL,"SURF3",kWhite,kBlack);
  plotNll->Draw(myCan,kTRUE,"png");
  //****/
  return 0;
}
Ejemplo n.º 18
0
void getXsecExtended(const TString mc_input, int debugMode=0, bool useFEWZ=true, int fineGrid=0)
{
  // check whether it is a calculation
  if (mc_input.Contains("_DebugRun_")) {
    std::cout << "getXsec: _DebugRun_ detected. Terminating the script\n";
    return;
  }

  if (debugMode==1) std::cout << "\n\n\tDEBUG MODE is ON\n\n";
  if (debugMode==-1) std::cout << "\n\n\tPLOT ONLY MODE is ON\n\n";
  std::cout << "DYTools::analysisTag=" << DYTools::analysisTag << "\n";

  if (DYTools::study2D && fineGrid) {
    std::cout << "fineGrid=1 is allowed only for study2D=0\n";
    return;
  }

  // normal calculation

  gBenchmark->Start("getXsec");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  //Bool_t doSave  = false;    // save plots?
  TString format = "png";   // output file format
  MCInputFileMgr_t inpMgr;
  TString fineGridStr;
  if (fineGrid==1) fineGridStr="fineGrid_";
  else if (fineGrid==2) fineGridStr="summer2011Grid_";
  else if (fineGrid==3) fineGridStr="summer2011specGrid_";
  
  Double_t massLow  = DYTools::massBinLimits[0];
  Double_t massHigh = DYTools::massBinLimits[DYTools::nMassBins];

  // fine grid: 0, 1, 2, ..., (fineGrid_1GeVstop-1), fineGrid_1GeVstop, fineGrid_1GeVstop+fineGridLargerStep, fineGrid_1GeVstop+2*fineGridLargerStep, ..., 1500
  //
  double fineGrid_1GeVstop=200.;
  double fineGrid_LargerStep=20.;

  int locMassBinCount=DYTools::nMassBins;
  double *massRangeEdges=NULL;
  if (!fineGrid) {
    massRangeEdges=new double[locMassBinCount+1];
    for (int i=0; i<=DYTools::nMassBins; ++i) {
      massRangeEdges[i]=DYTools::massBinLimits[i];
    }
  }
  else if (fineGrid==1) {
    // 1GeV grid
    locMassBinCount=int(fineGrid_1GeVstop-massLow+1e-3);
    std::cout << "1GeV grid size=" << locMassBinCount << "\n";
    // fineGrid_LargerStep
    double upperRange= (massHigh-fineGrid_1GeVstop);
    double upperCount= upperRange/fineGrid_LargerStep + 1e-3;
    if (upperCount - trunc(upperCount) > 1e-3) {
      std::cout << "(upperCount -1e-3)=" << (upperCount -1e-3) << "\n";
      std::cout << "should be integer value\n";
      return;
    }
    locMassBinCount += int(upperCount);
    std::cout << "mass grid[" << locMassBinCount << "]\n";

    massRangeEdges=new double[locMassBinCount+1];
    double m=massLow, dm=1;
    int count=0;
    while (m<=massHigh) {
      massRangeEdges[count]=m;
      if (1) {
	if (m<massHigh) std::cout << "count=" << count << ", massRange=" << m << " .. " << (m+dm) << "\n";
	else std::cout << "last edge=" << m << "\n";
      }
      count++;
      m+=dm;
      if (m==fineGrid_1GeVstop) dm=fineGrid_LargerStep;
    }
  }
  else if (fineGrid==2) {
    const int nMassBinTh=518;
    Double_t mxl = 14.0;
    locMassBinCount=nMassBinTh;
    massRangeEdges=new double[nMassBinTh+1];

    for(int iTh=0; iTh<=nMassBinTh; iTh++){
      // mass limits
      if     ( iTh >=   0 && iTh <  11 ) {mxl += 1.0;}
      else if( iTh >=  11 && iTh <  18 ) {mxl += 5.0;}
      else if( iTh >=  18 && iTh < 118 ) {mxl += 1.0;}
      else if( iTh >= 118 && iTh < 340 ) {mxl += 2.0;}
      else if( iTh >= 340 && iTh < nMassBinTh)   {mxl += 5.0; }
      else if( iTh == nMassBinTh)                {mxl = 1500; }
      massRangeEdges[iTh]=mxl;
    }
  }
  else if (fineGrid==3) {
    const int nMassBinTh=518;
    Double_t mxl = 14.0;
    locMassBinCount=nMassBinTh;
    massRangeEdges=new double[nMassBinTh+1];

    int iTh_new=0, tmpCounter=0;
    for(int iTh=0; iTh<=nMassBinTh; iTh++, iTh_new++){
      // mass limits
      if     ( iTh >=   0 && iTh <  11 ) {mxl += 1.0;}
      else if( iTh >=  11 && iTh <  18 ) {mxl += 5.0;}
      else if( iTh >=  18 && iTh < 118 ) {mxl += 1.0;}
      else if( iTh >= 118 && iTh < 340 ) {
	if (iTh>=139) {
	  std::cout << "iTh=" << iTh << ", current mxl=" << mxl << " +2\n";
	  if (iTh==139) tmpCounter=10;
	  tmpCounter--;
	  if (tmpCounter>0) iTh_new--;
	  else if (tmpCounter==0) {
	    tmpCounter=10;
	    std::cout << "iTh=" << iTh << ", iTh_new=" << iTh_new << ", current mxl=" << mxl << " +10\n";
	  }
	}
	mxl += 2.0;
      }
      else if( iTh >= 340 && iTh < nMassBinTh)   {
	std::cout << "iTh=" << iTh << ", current mxl=" << mxl << " +5\n";
	if (iTh<342) iTh_new--;
	else {
	  if ((iTh-342)%4>0) iTh_new--;
	  else std::cout << "iTh=" << iTh << ", iTh_new=" << iTh_new << ", current mxl=" << mxl << " +10\n";
	}
	mxl += 5.0; 
      }
      else if( iTh == nMassBinTh)                {mxl = 1500; }
      massRangeEdges[iTh_new]=mxl;
    }
    massRangeEdges[iTh_new-2]=1500.;
    std::cout << "iTh_new=" << iTh_new << "\n";
    locMassBinCount=iTh_new-2;
  }

  TVectorD massGrid(locMassBinCount+1);
  for (int i=0; i<=locMassBinCount; ++i) massGrid[i]=massRangeEdges[i];
  TH1F hMassIdx("h_massIdx","h_massIdx",locMassBinCount-1,massRangeEdges);
  //delete massRangeEdges;

  if (0) {
    printHisto(&hMassIdx);
    if (0) {
      for (int i=0; i<int(massHigh); ++i) {
	double m=i+0.5;
	std::cout << "i=" << i << ", m=" << m << ", idx=" << (hMassIdx.FindBin(m)-1) << "\n";
      }
    }
    return;
  }

  //std::cout << "massHigh=" << massHigh << "\n";
  //std::cout << "locMassBinCount=" << locMassBinCount << "\n";

  if (!inpMgr.Load(mc_input)) {
    return;
  }
  
  //--------------------------------------------------------------------------------------------------------------
  // Main code 
  //==============================================================================================================
  
  //  
  // Set up histograms
  //

  //vector<TH1D*> hZMassv;
  
  Double_t   nZv = 0;

  TMatrixD nEvents (locMassBinCount,DYTools::nYBinsMax);    // number of weigthed events
  TMatrixD nEventsDET (locMassBinCount,DYTools::nYBinsMax); // number of weighted events in the detector acceptance
  TMatrixD nEventsDETrecoPostIdx (locMassBinCount,DYTools::nYBinsMax);    // number of weigthed events
  TMatrixD w2Events (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD w2EventsDET (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD w2EventsDETrecoPostIdx (locMassBinCount,DYTools::nYBinsMax);
  Double_t nZpeak=0, w2Zpeak=0;
  double nZpeakDET=0, w2ZpeakDET=0;
  double nZpeakDETrecoPostIdx=0, w2ZpeakDETrecoPostIdx=0;

  nEvents = 0;
  w2Events = 0;
  nEventsDET = 0;
  w2EventsDET  = 0;
  nEventsDETrecoPostIdx = 0;
  w2EventsDETrecoPostIdx  = 0;

  //char hname[100];
  //for(UInt_t ifile = 0; ifile<fnamev.size(); ifile++) {
  //  sprintf(hname,"hZMass_%i",ifile); hZMassv.push_back(new TH1F(hname,"",500,0,500)); hZMassv[ifile]->Sumw2();
  //}

  // 
  // Read weights from a file
  //
  const bool useFewzWeights = useFEWZ;
  const bool cutZPT100 = true;
  FEWZ_t fewz(useFewzWeights,cutZPT100);
  if (useFewzWeights && !fewz.isInitialized()) {
    std::cout << "failed to prepare FEWZ correction\n";
    throw 2;
  }

  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
    
  // Data structures to store info from TTrees
  mithep::TGenInfo *gen  = new mithep::TGenInfo();

  // loop over samples  
  double lumi0=0;
  if (debugMode!=-1) {
  for(UInt_t ifile=0; ifile<inpMgr.fileNames().size(); ifile++) {
  
    // Read input file
    cout << "Processing " << inpMgr.fileName(ifile) << "..." << endl;
    infile = new TFile(inpMgr.fileName(ifile));
    assert(infile);

    // Get the TTrees
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);

    // Find weight for events for this file
    // The first file in the list comes with weight 1,
    // all subsequent ones are normalized to xsection and luminosity
    double lumi  = eventTree->GetEntries()/inpMgr.xsec(ifile);
    if (ifile==0) lumi0=lumi;
    double scale = lumi0/lumi;
    std::cout << "       -> sample weight is " << scale << endl;

    // Set branch address to structures that will store the info  
    eventTree->SetBranchAddress("Gen",&gen);
    TBranch *genBr = eventTree->GetBranch("Gen");
 
    // loop over events    
    nZv += scale * eventTree->GetEntries();

    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
      if (debugMode && (ientry>100000)) break;

      genBr->GetEntry(ientry);
      if (ientry%1000000==0) printProgress("ientry=",ientry,eventTree->GetEntriesFast());

      double massPreFsr = gen->vmass;   // pre-FSR
      double yPreFsr = gen->vy;    // pre-FSR
      double massPostFsr = gen->mass;   // post-FSR
      double yPostFsr = gen->y;    // post-FSR

      if ((massPreFsr < massLow) || (massPreFsr > massHigh)) continue;
      if ((fabs(yPreFsr) < DYTools::yRangeMin) || 
	  (fabs(yPreFsr) > DYTools::yRangeMax)) continue;

      int ibinMassPreFsr=-1, ibinYPreFsr=-1;
      int ibinMassPostFsr=-1, ibinYPostFsr=-1;

      if (!fineGrid) {
	ibinMassPreFsr = DYTools::findMassBin(massPreFsr);
	ibinMassPostFsr= DYTools::findMassBin(massPostFsr);
	ibinYPreFsr = DYTools::findAbsYBin(ibinMassPreFsr, yPreFsr);
	ibinYPostFsr= DYTools::findAbsYBin(ibinMassPostFsr, yPostFsr);
      }
      else {
	ibinMassPreFsr=hMassIdx.FindBin(massPreFsr)-1;
	ibinMassPostFsr=hMassIdx.FindBin(massPostFsr)-1;
	ibinYPreFsr=0;
	ibinYPostFsr=0;
	//printf("massPreFsr=%8.4lf, idx=%3d;  massPostFsr=%8.4lf, idx=%3d\n", massPreFsr,ibinMassPreFsr, massPostFsr,ibinMassPostFsr);
      }

      // We are only interested in the events, reconstructed with 
      // good mass and rapidity 
      if (ibinMassPreFsr==-1 || 
	  ibinMassPreFsr>=locMassBinCount || 
	  ibinYPreFsr==-1) {
	printf(".. skipping mass=%6.4lf, y=%6.4lf. ibinMass=%d, ibinY=%d\n",massPreFsr,yPreFsr,ibinMassPreFsr,ibinYPreFsr);
	continue;
      }

      // Find FEWZ-powheg reweighting factor 
      // that depends on pre-FSR Z/gamma* rapidity, pt, and mass
      double fewz_weight = 1.0;

      if(useFewzWeights) {
	fewz_weight=fewz.getWeight(gen->vmass,gen->vpt,gen->vy);
      }

      //std::cout << "weight=scale*gen->weight*fewz: " << scale << " * " << gen->weight << " * " << fewz_weight << "\n";
      double fullWeight = scale * gen->weight * fewz_weight;
      nEvents(ibinMassPreFsr,ibinYPreFsr) += fullWeight;
      w2Events(ibinMassPreFsr,ibinYPreFsr) += fullWeight*fullWeight;

      // Pre-FSR cross section
      if( DYTools::goodEtPair(gen->vpt_1, gen->vpt_2) &&
	  DYTools::goodEtaPair(gen->veta_1, gen->veta_2) ) {
	nEventsDET(ibinMassPreFsr,ibinYPreFsr) += fullWeight;
	w2EventsDET(ibinMassPreFsr,ibinYPreFsr) += fullWeight*fullWeight;
      }

      // Post-FSR cross section
      if(  (ibinMassPostFsr!=-1) && (ibinYPostFsr!=-1) &&
	   DYTools::goodEtPair(gen->pt_1, gen->pt_2) &&
	   DYTools::goodEtaPair(gen->eta_1, gen->eta_2) ) {
	nEventsDETrecoPostIdx(ibinMassPostFsr,ibinYPostFsr) += fullWeight;
	w2EventsDETrecoPostIdx(ibinMassPostFsr,ibinYPostFsr) += fullWeight*fullWeight;
      }
    }
    delete infile;
    infile=0, eventTree=0;
  }
  delete gen;

  // Determine Z-peak event count
  for (int i=0; i<locMassBinCount; i++) {
    int isZpeak=0;
    // bin idx is (i+1)
    if ((hMassIdx.GetBinLowEdge(i+1)>=60-1e-3) 
	&& (hMassIdx.GetBinLowEdge(i+1+1)<=120+1e-3)) isZpeak=1;
    if (isZpeak) {
      int yiMax=(fineGrid) ? 1:DYTools::nYBins[i];
      for (int yi=0; yi<yiMax; ++yi) {
	nZpeak += nEvents(i,yi);
	w2Zpeak += w2Events(i,yi);
	nZpeakDET += nEventsDET(i,yi);
	w2ZpeakDET += w2EventsDET(i,yi);
	nZpeakDETrecoPostIdx += nEventsDETrecoPostIdx(i,yi);
	w2ZpeakDETrecoPostIdx += w2EventsDETrecoPostIdx(i,yi);
      }
    }
  }
  std::cout << "\n";
  std::cout << "nZpeak=" << nZpeak << ", w2Zpeak=" << w2Zpeak << "\n";
  std::cout << "nZpeakDET=" << nZpeakDET << ", w2ZpeakDET=" << w2ZpeakDET << "\n";
  std::cout << "nZpeakDETrecoPostIdx=" << nZpeakDETrecoPostIdx << ", w2ZpeakDETrecoPostIdx=" << w2ZpeakDETrecoPostIdx << "\n";
  std::cout << "\n";


  if (nZpeak==0) {
    std::cout << "no events in the Z-peak region\n";
    return ;
  }
  } // if (debugMode!=-1)


  // Containers of the normalized event counts
  TMatrixD nEventsNorm (locMassBinCount,DYTools::nYBinsMax);    // number of weigthed events, normalized to Z-peak
  TMatrixD nEventsDETNorm (locMassBinCount,DYTools::nYBinsMax); // number of weighted events in the detector acceptance, normalized to Z-peak
  TMatrixD nEventsDETrecoPostIdxNorm (locMassBinCount,DYTools::nYBinsMax); // number of weighted events in the detector acceptance, normalized to Z-peak
  TMatrixD nEventsNormErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETNormErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETrecoPostIdxNormErr (locMassBinCount,DYTools::nYBinsMax);

  TMatrixD nEventsErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETErr (locMassBinCount,DYTools::nYBinsMax);
  TMatrixD nEventsDETrecoPostIdxErr (locMassBinCount,DYTools::nYBinsMax);

  nEventsNorm=0;
  nEventsDETNorm=0;
  nEventsDETrecoPostIdxNorm=0;
  nEventsNormErr=0;
  nEventsDETNormErr=0;
  nEventsDETrecoPostIdxNormErr=0;

  nEventsErr=0;
  nEventsDETErr=0;

  if (debugMode!=-1) {
  for(int i=0; i<locMassBinCount; i++) {
    int yiMax=(fineGrid) ? 1:DYTools::nYBins[i];
    for (int j=0; j<yiMax; j++) {
      nEventsErr(i,j)=sqrt(w2Events(i,j));
      nEventsDETErr(i,j)=sqrt(w2EventsDET(i,j));
      nEventsDETrecoPostIdxErr(i,j)=sqrt(w2EventsDETrecoPostIdx(i,j));

      nEventsNorm(i,j) = nEvents(i,j)/nZpeak;
      nEventsNormErr(i,j) = 
	getErrorOnRatio(nEvents(i,j),nEventsErr(i,j),
			nZpeak, sqrt(w2Zpeak));

      nEventsDETNorm(i,j) = nEventsDET(i,j)/nZpeakDET;
      nEventsDETNormErr(i,j) =
	getErrorOnRatio(nEventsDET(i,j),nEventsDETErr(i,j),
			nZpeakDET, sqrt(w2ZpeakDET));

      nEventsDETrecoPostIdxNorm(i,j) = nEventsDETrecoPostIdx(i,j)/nZpeakDETrecoPostIdx;
      nEventsDETrecoPostIdxNormErr(i,j) =
	getErrorOnRatio(nEventsDETrecoPostIdx(i,j),nEventsDETrecoPostIdxErr(i,j),
			nZpeakDETrecoPostIdx, sqrt(w2ZpeakDETrecoPostIdx));
    }
  }
  }



  TString outFile= TString("../root_files/xSecThExt_");
  //outFile.Append("2MCfiles_");
  if (!useFewzWeights) outFile.Append("noFEWZ_");
  if (fineGridStr.Length()) outFile.Append(fineGridStr);
  if (debugMode==1) outFile.Append("debug_");
  outFile.Append( DYTools::analysisTag + TString("_tmp.root") );


  TVectorD rapidityGrid(massGrid.GetNoElements()-1);
  rapidityGrid=1;

  if (debugMode!=-1) {
    TFile thFile(outFile,"recreate");
    massGrid.Write("massBinEdges");
    if (fineGrid) rapidityGrid.Write("rapidityBinCount");
    nEvents.Write("nGenEvents");
    nEventsErr.Write("nGenEventsErr");
    nEventsDET.Write("nGenEventsDET");
    nEventsDETErr.Write("nGenEventsDETErr");
    nEventsDETrecoPostIdx.Write("nGenEventsDETrecoPostIdx");
    nEventsDETrecoPostIdxErr.Write("nGenEventsDETRecoPostIdxErr");
    nEventsNorm.Write("nGenEventsNorm");
    nEventsNormErr.Write("nGenEventsNormErr");
    nEventsDETNorm.Write("nGenEventsDETNorm");
    nEventsDETNormErr.Write("nGenEventsDETNormErr");
    nEventsDETrecoPostIdxNorm.Write("nGenEventsDETrecoPostIdxNorm");
    nEventsDETrecoPostIdxNormErr.Write("nGenEventsDETrecoPostIdxNormErr");
    TVectorD zPeakInfo(6);
    zPeakInfo(0)=nZpeak; zPeakInfo(1)=sqrt(w2Zpeak);
    zPeakInfo(2)=nZpeakDET; zPeakInfo(3)=sqrt(w2ZpeakDET);
    zPeakInfo(4)=nZpeakDETrecoPostIdx; zPeakInfo(5)=sqrt(w2ZpeakDETrecoPostIdx);
    zPeakInfo.Write("zPeakCountAndErr");
    thFile.Close();
    std::cout << "file <" << outFile << "> created\n";
  }
  else {
    TFile thFile(outFile);
    nEvents.Read("nGenEvents");
    nEventsErr.Read("nGenEventsErr");
    nEventsDET.Read("nGenEventsDET");
    nEventsDETErr.Read("nGenEventsDETErr");
    nEventsDETrecoPostIdx.Read("nGenEventsDETrecoPostIdx");
    nEventsDETrecoPostIdxErr.Read("nGenEventsDETRecoPostIdxErr");
    nEventsNorm.Read("nGenEventsNorm");
    nEventsNormErr.Read("nGenEventsNormErr");
    nEventsDETNorm.Read("nGenEventsDETNorm");
    nEventsDETNormErr.Read("nGenEventsDETNormErr");
    nEventsDETrecoPostIdxNorm.Read("nGenEventsDETrecoPostIdxNorm");
    nEventsDETrecoPostIdxNormErr.Read("nGenEventsDETrecoPostIdxNormErr");
    TVectorD zPeakInfo(6);
    zPeakInfo.Read("zPeakCountAndErr");
    thFile.Close();
    
    nZpeak=zPeakInfo[0]; w2Zpeak=SQR(zPeakInfo[1]);
    nZpeakDET=zPeakInfo[2]; w2ZpeakDET=SQR(zPeakInfo[3]);
    nZpeakDETrecoPostIdx=zPeakInfo[4]; w2ZpeakDETrecoPostIdx=SQR(zPeakInfo[5]);
    std::cout << "file <" << outFile << "> loaded\n";
  }

  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  CPlot::sOutDir="plots" + DYTools::analysisTag;

  TString fileNamePlots=outFile;
  fileNamePlots.ReplaceAll("_tmp.root","_plots_tmp.root");
  TFile *filePlots=new TFile(fileNamePlots,"recreate");
  if (!filePlots) {
    std::cout << "failed to create file <" << fileNamePlots << ">\n";
    throw 2;
  }
  // string buffers
  //char ylabel[50];   // y-axis label


  if (DYTools::study2D) {
    TString c2Dname="canvXsectTh_2D";
    if (useFewzWeights) c2Dname.Append("_FEWZ");
    TCanvas *c2D = MakeCanvas(c2Dname,c2Dname,600,600+300*DYTools::study2D);
    std::vector<TH1F*> hXsecV;
    std::vector<CPlot*> cpV;
    hXsecV.reserve(DYTools::nMassBins);
    cpV.reserve(DYTools::nMassBins);
    for (int iM=0; iM<DYTools::nMassBins; ++iM) {
      double massMin=DYTools::massBinLimits[iM];
      double massMax=DYTools::massBinLimits[iM+1];
      CPlot *cp=new CPlot(Form("cpMass%2.0lf_%2.0lf",massMin,massMax),
			  "","|Y|","counts");
      cpV.push_back(cp);
      hXsecV.push_back( plotXsec2D("xsec",iM,nEvents,nEventsErr,cp,kBlack,1) );
    }
    c2D->Divide(2,3);
    for (int ipad=1; ipad<=6; ++ipad) {
      cpV[ipad]->Draw(c2D,false,"png",ipad);
    }
    c2D->Update();
    SaveCanvas(c2D,c2Dname);
  }

  {
    TString canvName=TString("canvXsectTh_") + fineGridStr + TString("1D");
    if (useFewzWeights) canvName.Append("_FEWZ");
    TCanvas *c1D = MakeCanvas(canvName,canvName,600,600);
    CPlot *cp=new CPlot("cplot_1D","","M_{ee} (GeV)","counts");
    TH1F *hXsec= plotXsec1D("xsec1D",nEvents,nEventsErr,cp,kBlue, fineGrid);
    hXsec->SetDirectory(0);
    cp->SetLogx();
    cp->Draw(c1D,false,"png");
    c1D->Update();
    SaveCanvas(c1D,canvName);
  }
	
  {
    TString canvName=TString("canvXsectThNorm_") + fineGridStr + TString("1D");
    if (useFewzWeights) canvName.Append("_FEWZ");
    TCanvas *c1D = MakeCanvas(canvName,canvName,600,600);
    CPlot *cp=new CPlot("cplotNorm_1D","","M_{ee} (GeV)","normalized counts");
    TH1F *hXsec= plotXsec1D("xsec1D",nEventsNorm,nEventsNormErr,cp,kBlue, fineGrid);
    hXsec->SetDirectory(0);
    cp->SetLogx();
    cp->Draw(c1D,false,"png");
    c1D->Update();
    SaveCanvas(c1D,canvName);
  }
	
  /* 

 // Z mass
  sprintf(ylabel,"a.u. / %.1f GeV/c^{2}",hZMassv[0]->GetBinWidth(1));
  CPlot plotZMass1("zmass1","","m(Z) [GeV/c^{2}]",ylabel);
  for(UInt_t i=0; i<fnamev.size(); i++) { 
    plotZMass1.AddHist1D(hZMassv[i],labelv[i],"hist",colorv[i],linev[i]); 
  }
  plotZMass1.SetLogy();
  plotZMass1.Draw(c);
  SaveCanvas(c, "zmass1");

  PlotMatrixVariousBinning(accv, "acceptance", "LEGO2",filePlots);
  filePlots->Close();
  if (DYTools::study2D==0)
    Plot1D(accv,accErrv,"acceptance1D","acceptance");
  //delete filePlots;
  
  */
  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //==============================================================================================================

  if (!fineGrid) {
    const int printSystErr=0;
    TMatrixD zeroErr=nEventsErr; zeroErr=0;
    printYields("nGenEvents", nEvents,nEventsErr,zeroErr, printSystErr);
    printYields("nGenEventsDET", nEventsDET,nEventsDETErr,zeroErr, printSystErr);
    printYields("nGenEventsDETrecoPostIdx",nEventsDETrecoPostIdx,nEventsDETrecoPostIdxErr, zeroErr,printSystErr);
  }

  gBenchmark->Show("getXsec");
}
void 
//HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
HTT_ET_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_et_1_7TeV", string inputfile="root/$HISTFILE", const char* directory="eleTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_low"             )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_medium"          )){ category_extra = "0-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_0jet_high"            )){ category_extra = "0-jet high p_{T}^{#tau_{h}}";         }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_1jet_medium"          )){ category_extra = "1-jet low p_{T}^{#tau_{h}}";       }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_lowhiggs"   )){ category_extra= "1-jet high p_{T}^{#tau_{h}}";  }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category = "e#tau_{h}";                          }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra= "1-jet high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_1jet_high_mediumhiggs")){ category_extra2= "boosted"; }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf"                  )){ category_extra = "VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_loose"            )){ category_extra = "Loose VBF tag";              }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_vbf_tight"            )){ category_extra = "Tight VBF tag";              }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag"               )){ category_extra = "no b-tag";     }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag"                 )){ category_extra = "b-tag";  }        
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_low"           )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_medium"        )){ category_extra2 = "medium p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra = "no b-tag"; }
  if(std::string(directory) == std::string("eleTau_nobtag_high"          )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_low"             )){ category_extra2 = "low p_{T}^{#tau_{h}}"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category = "e#tau_{h}";          }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra = "b-tag"; }
  if(std::string(directory) == std::string("eleTau_btag_high"            )){ category_extra2 = "high p_{T}^{#tau_{h}}"; }

  const char* dataset;
#ifdef MSSM
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                 4.9 fb^{-1} (7 TeV)";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#scale[1.5]{CMS}  h,H,A#rightarrow#tau#tau                                19.7 fb^{-1} (8 TeV)";}
#else
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS, 19.7 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"     , directory)), "QCD"); InitHist(Fakes, "", "", TColor::GetColor(250,202,255), 1001); 
  TH1F* EWK0   = refill((TH1F*)input->Get(TString::Format("%s/VV"      , directory)), "VV" ); InitHist(EWK0 , "", "", TColor::GetColor(222,90,106), 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"       , directory)), "W"  ); InitHist(EWK1 , "", "", TColor::GetColor(222,90,106), 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"      , directory)), "ZJ" ); InitHist(EWK2 , "", "", TColor::GetColor(100,182,232), 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZL"      , directory)), "ZL" ); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#else
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/ZLL"     , directory)), "ZLL"); InitHist(EWK  , "", "", TColor::GetColor(100,182,232), 1001);
#endif
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"      , directory)), "TT" ); InitHist(ttbar, "", "", TColor::GetColor(155,152,204), 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"     , directory)), "ZTT"); InitHist(Ztt  , "", "", TColor::GetColor(248,206,104), 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA" , directory)), "ggH"); InitSignal(ggH); ggH->Scale($TANB);
  TH1F* bbH    = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA" , directory)), "bbH"); InitSignal(bbH); bbH->Scale($TANB);
#else
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"  , directory)), "ggH"); InitSignal(ggH); ggH->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"  , directory)), "qqH"); InitSignal(qqH); qqH->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"   , directory)), "VH" ); InitSignal(VH ); VH ->Scale(SIGNAL_SCALE);
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK0 );
  ref->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK2 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK0 ->Integral();
  unscaled[1]+= EWK1 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK2 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifndef DROP_SIGNAL
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif
#endif

  if(scaled){

/*    Fakes = refill(shape_histos(Fakes, datacard, "QCD"), "QCD");
    EWK0 = refill(shape_histos(EWK0, datacard, "VV"), "VV"); 
    EWK1 = refill(shape_histos(EWK1, datacard, "W"), "W"); 
#ifdef EXTRA_SAMPLES
    EWK2 = refill(shape_histos(EWK2, datacard, "ZJ"), "ZJ");
    EWK = refill(shape_histos(EWK, datacard, "ZL"), "ZL");
#else
    //    EWK = refill(shape_histos(EWK, datacard, "ZLL"), "ZLL");
#endif
    ttbar = refill(shape_histos(ttbar, datacard, "TT"), "TT");
    Ztt = refill(shape_histos(Ztt, datacard, "ZTT"), "ZTT");
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
*/

    rescale(Fakes, 7); 
    rescale(EWK0 , 6); 
    rescale(EWK1 , 3); 
#ifdef EXTRA_SAMPLES
    rescale(EWK2 , 4); 
    rescale(EWK  , 5);
#else
    rescale(EWK  , 4);
#endif 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
#ifndef DROP_SIGNAL
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);
#endif  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK0 ->Integral()
					       +EWK1 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK2 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
#ifndef DROP_SIGNAL
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif
#endif

  EWK0 ->Add(Fakes);
  EWK1 ->Add(EWK0 );
#ifdef EXTRA_SAMPLES
  EWK2 ->Add(EWK1 );
  EWK  ->Add(EWK2 );
#else
  EWK  ->Add(EWK1 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(13);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    EWK1 ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{h}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
#if defined MSSM
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "tlbrNDC");
  if (category_extra2!="") chan     = new TPaveText(0.20, 0.69+0.061, 0.32, 0.74+0.161, "tlbrNDC");
#else
  TPaveText* chan     = new TPaveText(0.52, 0.35, 0.91, 0.55, "tlbrNDC");
#endif
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
#if defined MSSM
  if (category_extra2!="") chan->AddText(category_extra2);
#else
  chan->AddText(category_extra2);
#endif
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

  TPaveText* cat2      = new TPaveText(0.20, 0.66+0.061, 0.32, 0.66+0.161, "NDC");
  cat2->SetBorderSize(   0 );
  cat2->SetFillStyle(    0 );
  cat2->SetTextAlign(   12 );
  cat2->SetTextSize ( 0.05 );
  cat2->SetTextColor(    1 );
  cat2->SetTextFont (   62 );
  cat2->AddText(category_extra2);
  cat2->Draw();
*/  
#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.44+0.061, 0.95, 0.44+0.151, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("MSSM m^{h}_{max} scenario");
  massA->AddText("m_{A}=$MA GeV, tan#beta=$TANB");
  massA->Draw();
#endif

#ifdef MSSM
  TLegend* leg = new TLegend(0.53, 0.60, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "h,A,H#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.52, 0.58, 0.92, 0.89);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
    leg->AddEntry(ggH  , "SM H(125 GeV)#rightarrow#tau#tau" , "L" );
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "Observed"                       , "LP");
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(EWK  , "Z#rightarrow ee"                , "F" );
  leg->AddEntry(EWK1 , "W+jets"                         , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();

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

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

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

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

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", TColor::GetColor(250,202,255), 1001);
  InitHist  (scales[1], "", "", TColor::GetColor(222,90,106), 1001);
  InitHist  (scales[2], "", "", TColor::GetColor(155,152,204), 1001);
  InitHist  (scales[3], "", "", TColor::GetColor(248,206,104), 1001);
#ifndef DROP_SIGNAL
  InitSignal(scales[4]);
  InitSignal(scales[5]);
  InitSignal(scales[6]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "NONE"      );
#else
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifndef DROP_SIGNAL
  scales[4]->Draw("same");
  scales[5]->Draw("same");
  scales[6]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same"); 
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd();
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
    EWK  ->Write("Zee"     );
    EWK1 ->Write("EWK"    );
  //EWK  ->Write("EWK"     );
  EWK1 ->Write("EWK1"    );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Ejemplo n.º 20
0
void PlotDszR04Reco()
{
  gROOT->LoadMacro("$LOCAL/include/TUntilsOpHisto.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsAliFigs.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsPlotStd.h"); SetStyle();

  const TString sTag = "#it{p}_{T,particle}^{Trigger}>20 GeV/#it{c}";
//=============================================================================

  TFile *file = TFile::Open("data/incl/AnalysisOutputs_Rje_py8_JetR04_SjeR01.root", "READ");
  TH2D *hpy8 = (TH2D*)file->Get("hJetDszt020"); hpy8->SetName("hpy8"); hpy8->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_Rje_qpy_JetR04_SjeR01.root", "READ");
  TH2D *hqpy = (TH2D*)file->Get("hJetDszt020"); hqpy->SetName("hqpy"); hqpy->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_Rje_med_JetR04_SjeR01.root", "READ");
  TH2D *hmed = (TH2D*)file->Get("hJetDszt020"); hmed->SetName("hmed"); hmed->SetDirectory(0);
  file->Close();
//=============================================================================

  TH1D *hpy8020 = hpy8->ProjectionY("hpy8020", hpy8->GetXaxis()->FindBin( 20.+1e-6), hpy8->GetXaxis()->FindBin( 30.-1e-6));
  TH1D *hpy8060 = hpy8->ProjectionY("hpy8060", hpy8->GetXaxis()->FindBin( 60.+1e-6), hpy8->GetXaxis()->FindBin( 80.-1e-6));
  TH1D *hpy8120 = hpy8->ProjectionY("hpy8120", hpy8->GetXaxis()->FindBin(120.+1e-6), hpy8->GetXaxis()->FindBin(150.-1e-6));

  TH1D *hqpy020 = hqpy->ProjectionY("hqpy020", hqpy->GetXaxis()->FindBin( 20.+1e-6), hqpy->GetXaxis()->FindBin( 30.-1e-6));
  TH1D *hqpy060 = hqpy->ProjectionY("hqpy060", hqpy->GetXaxis()->FindBin( 60.+1e-6), hqpy->GetXaxis()->FindBin( 80.-1e-6));
  TH1D *hqpy120 = hqpy->ProjectionY("hqpy120", hqpy->GetXaxis()->FindBin(120.+1e-6), hqpy->GetXaxis()->FindBin(150.-1e-6));

  TH1D *hmed020 = hmed->ProjectionY("hmed020", hmed->GetXaxis()->FindBin( 20.+1e-6), hmed->GetXaxis()->FindBin( 30.-1e-6));
  TH1D *hmed060 = hmed->ProjectionY("hmed060", hmed->GetXaxis()->FindBin( 60.+1e-6), hmed->GetXaxis()->FindBin( 80.-1e-6));
  TH1D *hmed120 = hmed->ProjectionY("hmed120", hmed->GetXaxis()->FindBin(120.+1e-6), hmed->GetXaxis()->FindBin(150.-1e-6));


  hpy8020->Rebin(10.); hpy8020->Scale(1./hpy8020->Integral()); NormBinningHistogram(hpy8020);
  hpy8060->Rebin(10.); hpy8060->Scale(1./hpy8060->Integral()); NormBinningHistogram(hpy8060);
  hpy8120->Rebin(10.); hpy8120->Scale(1./hpy8120->Integral()); NormBinningHistogram(hpy8120);

  hqpy020->Rebin(10.); hqpy020->Scale(1./hqpy020->Integral()); NormBinningHistogram(hqpy020);
  hqpy060->Rebin(10.); hqpy060->Scale(1./hqpy060->Integral()); NormBinningHistogram(hqpy060);
  hqpy120->Rebin(10.); hqpy120->Scale(1./hqpy120->Integral()); NormBinningHistogram(hqpy120);

  hmed020->Rebin(10.); hmed020->Scale(1./hmed020->Integral()); NormBinningHistogram(hmed020);
  hmed060->Rebin(10.); hmed060->Scale(1./hmed060->Integral()); NormBinningHistogram(hmed060);
  hmed120->Rebin(10.); hmed120->Scale(1./hmed120->Integral()); NormBinningHistogram(hmed120);


  TGraph *gpy8020 = new TGraph(hpy8020); TGraph *gpy8060 = new TGraph(hpy8060); TGraph *gpy8120 = new TGraph(hpy8120);
  TGraph *gqpy020 = new TGraph(hqpy020); TGraph *gqpy060 = new TGraph(hqpy060); TGraph *gqpy120 = new TGraph(hqpy120);
  TGraph *gmed020 = new TGraph(hmed020); TGraph *gmed060 = new TGraph(hmed060); TGraph *gmed120 = new TGraph(hmed120);
//=============================================================================

  TH1F    *hfm = 0;
  TCanvas *can = 0;
  TLegend *leg = 0;
  TLatex  *tex = 0;
  TLine  *line = 0;

  const Float_t dflx = -40., dfux = 200.;
  const Float_t dfly = 8e-10, dfuy = 8e3;

  const Float_t dlsx = 0.05, dlsy = 0.05;
  const Float_t dtsx = 0.06, dtsy = 0.06;
  const Float_t dtox = 1.10, dtoy = 1.00;

  const TString stnx = "#Delta#it{z}_{sj}";
  const TString stny = "1/#it{N}_{jet} d#it{N}/d#Delta#it{z}_{sj}";
//=============================================================================

  can = MakeCanvas("Jet4Dsz020"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0., 1., 5.); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy, stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawGraph(gpy8020, wcl[3], "C");
  DrawGraph(gqpy020, wcl[1], "C");
  DrawGraph(gmed020, wcl[5], "C");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(gpy8020, "PYTHIA 8", "L")->SetTextSizePixels(24);
  leg->AddEntry(gqpy020, "Q-PYTHIA", "L")->SetTextSizePixels(24);
  leg->AddEntry(gmed020, "JEWEL+PYTHIA", "L")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jet #it{R}=0.4, anti-#it{k}_{T}, 20<#it{p}_{T,jet}<30 GeV/#it{c}, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.84, sTag.Data());
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("Jet4Dsz060"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0., 1., 5.); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy, stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawGraph(gpy8060, wcl[3], "C");
  DrawGraph(gqpy060, wcl[1], "C");
  DrawGraph(gmed060, wcl[5], "C");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(gpy8060, "PYTHIA 8", "L")->SetTextSizePixels(24);
  leg->AddEntry(gqpy060, "Q-PYTHIA", "L")->SetTextSizePixels(24);
  leg->AddEntry(gmed060, "JEWEL+PYTHIA", "L")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jet #it{R}=0.4, anti-#it{k}_{T}, 60<#it{p}_{T,jet}<80 GeV/#it{c}, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.84, sTag.Data());
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("Jet4Dsz120"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0., 1., 5.); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy, stnx, stny);
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawGraph(gpy8120, wcl[3], "C");
  DrawGraph(gqpy120, wcl[1], "C");
  DrawGraph(gmed120, wcl[5], "C");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(gpy8120, "PYTHIA 8", "L")->SetTextSizePixels(24);
  leg->AddEntry(gqpy120, "Q-PYTHIA", "L")->SetTextSizePixels(24);
  leg->AddEntry(gmed120, "JEWEL+PYTHIA", "L")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.14, 0.92, "2.76 TeV, Jet #it{R}=0.4, anti-#it{k}_{T}, 120<#it{p}_{T,jet}<150 GeV/#it{c}, |#eta_{jet}|<1");
  tex->DrawLatex(0.16, 0.84, sTag.Data());
  CanvasEnd(can);
//=============================================================================

  return;
}
Ejemplo n.º 21
0
void tauStudy(const TString conf="new.conf") {

  // tau decay modes
  enum { hadron=1, electron, muon };

  const Int_t nSamples=1;
  
  vector<TString> sampleNames;
  vector<TString> sampleTitles;
  vector<Int_t> sampleColors;

  confParse(conf, sampleNames, sampleTitles, sampleColors);

  TProfile *hEffPt[nSamples];
  TProfile *hEffEta[nSamples];

  TProfile *hJetResPt[nSamples];
  TProfile *hJetResEta[nSamples];

  TH1D *hPt[nSamples];

  char hname[100];

  // define kinematic/plotting constants
  const Float_t PT_MAX  = 300;
  const Float_t PT_MIN  = 0;
  const Int_t   PT_BIN  = 150;
  const Float_t ETA_MAX = 2.5;
  const Float_t ETA_MIN = -2.5;
  const Int_t   ETA_BIN = 16;

  Double_t jetCorr1Pt, jetCorr2Pt;

  for(UInt_t iSamp=0; iSamp<nSamples; iSamp++) {

    sprintf(hname, "hEffPt_%s", sampleTitles[iSamp].Data()); hEffPt[iSamp]= new TProfile(hname, hname, PT_BIN, PT_MIN, PT_MAX);
    sprintf(hname, "hEffEta_%s", sampleTitles[iSamp].Data()); hEffEta[iSamp]= new TProfile(hname, hname, ETA_BIN, ETA_MIN, ETA_MAX);

    sprintf(hname, "hJetResPt_%s", sampleTitles[iSamp].Data()); hJetResPt[iSamp] = new TProfile(hname, hname, PT_BIN, PT_MIN, PT_MAX);
    sprintf(hname, "hJetResEta_%s", sampleTitles[iSamp].Data()); hJetResEta[iSamp] = new TProfile(hname, hname, ETA_BIN, ETA_MIN, ETA_MAX);

    sprintf(hname, "hPt_%s", sampleTitles[iSamp].Data()); hPt[iSamp] = new TH1D(hname, hname, PT_BIN, PT_MIN, PT_MAX);

  }

  UInt_t eventNum;
  UInt_t bTag1, bTag2;
  UInt_t tauCat1, tauCat2;
  LorentzVector *genB1=0, *genB2=0, *recoB1=0, *recoB2=0;
  LorentzVector *genTau1=0, *genTau2=0, *genDecayTau1=0, *genDecayTau2=0, *recoTau1=0, *recoTau2=0;

  TFile *infile;
  TTree *intree;

  for (UInt_t iSamp=0; iSamp<nSamples; iSamp++) { // sample loop

    TString infilename = sampleNames[iSamp];
    cout << "Processing  " << infilename << " ..." << endl;
    infile = new TFile(infilename); assert(infile);
    intree = (TTree*) infile->Get("Events"); assert(intree);
 
    //intree->SetBranchAddress("eventNum",       &eventNum);
    intree->SetBranchAddress("bTag1",          &bTag1);
    intree->SetBranchAddress("bTag2",          &bTag2);
    intree->SetBranchAddress("genB1",          &genB1);
    intree->SetBranchAddress("genB2",          &genB2);
    intree->SetBranchAddress("recoB1",         &recoB1);
    intree->SetBranchAddress("recoB2",         &recoB2);
    intree->SetBranchAddress("tauCat1",        &tauCat1);
    intree->SetBranchAddress("tauCat2",        &tauCat2);
    intree->SetBranchAddress("genTau1",        &genTau1);
    intree->SetBranchAddress("genTau2",        &genTau2);
    intree->SetBranchAddress("genDecayTau1",   &genDecayTau1);
    intree->SetBranchAddress("genDecayTau2",   &genDecayTau2);
    intree->SetBranchAddress("recoTau1",       &recoTau1);
    intree->SetBranchAddress("recoTau2",       &recoTau2);

    for(UInt_t iEntry=0; iEntry<intree->GetEntries(); iEntry++) { // entry loop
      intree->GetEntry(iEntry);

      // jet resolution
      //cout << tauCat1 << " " << tauCat2 << endl;
      if ((recoTau1->Pt()!=999)) {

	//jetCorr1Pt = recoTau1->Pt()*getJetScaleFactor(recoTau1->Pt(), recoTau1->Eta());
	jetCorr1Pt=recoTau1->Pt();

	hPt[iSamp]->Fill(recoTau1->Pt());

	hJetResPt[iSamp]->Fill(genDecayTau1->Pt(),(recoTau1->Pt()-genDecayTau1->Pt())/genDecayTau1->Pt());
        hJetResEta[iSamp]->Fill(genDecayTau1->Eta(),(recoTau1->Pt()-genDecayTau1->Pt())/genDecayTau1->Pt());

      }

      if ((recoTau2->Pt()!=999)) {

	//jetCorr2Pt = recoTau2->Pt()*getJetScaleFactor(recoTau2->Pt(), recoTau2->Eta());
	jetCorr2Pt=recoTau2->Pt();

	hPt[iSamp]->Fill(recoTau2->Pt());

	hJetResPt[iSamp]->Fill(genDecayTau2->Pt(),(recoTau2->Pt()-genDecayTau2->Pt())/genDecayTau2->Pt());
        hJetResEta[iSamp]->Fill(genDecayTau2->Eta(),(recoTau2->Pt()-genDecayTau2->Pt())/genDecayTau2->Pt());

      }

      //tagging efficiency
      /*
      if ((tauDecayCat1==1) && (recoTau1->Pt()!=999)) {
	hEffPt[iSamp]->Fill(genDecayTau1->Pt(),1);
	hEffEta[iSamp]->Fill(genDecayTau1->Eta(),1);
      }
      else {
	hEffPt[iSamp]->Fill(genDecayTau1->Pt(),0);
	hEffEta[iSamp]->Fill(genDecayTau1->Eta(),0);
      }

      if ((tauDecayCat2==1) && (recoTau2->Pt()!=999)) {
	hEffPt[iSamp]->Fill(genDecayTau2->Pt(),1);
	hEffEta[iSamp]->Fill(genDecayTau2->Eta(),1);
      }
      else {
	hEffPt[iSamp]->Fill(genDecayTau2->Pt(),0);
	hEffEta[iSamp]->Fill(genDecayTau2->Eta(),0);
      }
      */
    } // end entry loop
    delete infile;
    infile=0, intree=0;

  } // end sample loop

  char pname[100];
  char xlabel[100];
  char ylabel[100];
  
  TCanvas *c = MakeCanvas("c", "c", 800, 600);
  TLegend *leg = new TLegend(0.7, 0.7, 0.9, 0.9);
  leg->SetShadowColor(0);
  leg->SetFillColor(0);

  // tau jet resolution as a function of pt (uncorrected)
  sprintf(xlabel, "generator level tau jet P_{T}");
  sprintf(ylabel, "(reco P_{T} - gen P_{T})/gen P_{T}");
  sprintf(pname, "tauJetResPt");

  for (UInt_t iSamp=0; iSamp<nSamples; iSamp++) {

    hJetResPt[iSamp]->SetLineColor(sampleColors[iSamp]);
    hJetResPt[iSamp]->SetMarkerColor(sampleColors[iSamp]);
    hJetResPt[iSamp]->SetMarkerSize(1);
    leg->AddEntry(hJetResPt[iSamp], sampleTitles[iSamp],"l");

    if (iSamp==0) {
      hJetResPt[iSamp]->GetXaxis()->SetTitle(xlabel);
      hJetResPt[iSamp]->GetYaxis()->SetTitle(ylabel);
      hJetResPt[iSamp]->SetTitle("");
      //hJetResPt[iSamp]->GetYaxis()->SetRangeUser(-0.5,3);
      hJetResPt[iSamp]->Draw();

    }
    else {
      hJetResPt[iSamp]->Draw("same");
    }
  }
  //leg->Draw();
  c->SaveAs(TString(pname)+TString(".png"));

  hPt[0]->GetXaxis()->SetTitle("p_{T}");
  hPt[0]->SetTitle("");
  hPt[0]->SetLineColor(sampleColors[0]);
  hPt[0]->SetMarkerColor(sampleColors[0]);
  hPt[0]->Draw("hist");
  c->SaveAs("pt.png");

  sprintf(xlabel, "generator level tau Eta");
  sprintf(ylabel, "(reco P_{T} - gen P_{T})/gen P_{T}");
  sprintf(pname, "tauJetResEta");
  leg->Clear();

  for (UInt_t iSamp=0; iSamp<nSamples; iSamp++) {

    hJetResEta[iSamp]->SetLineColor(sampleColors[iSamp]);
    hJetResEta[iSamp]->SetMarkerColor(sampleColors[iSamp]);
    hJetResEta[iSamp]->SetMarkerSize(1);
    leg->AddEntry(hJetResEta[iSamp], sampleTitles[iSamp],"l");

    if (iSamp==0) {
      hJetResEta[iSamp]->GetXaxis()->SetTitle(xlabel);
      hJetResEta[iSamp]->GetYaxis()->SetTitle(ylabel);
      hJetResEta[iSamp]->SetTitle("");
      //hJetResEta[iSamp]->GetYaxis()->SetRangeUser(-0.3,0.3);
      hJetResEta[iSamp]->Draw();
    }

    else {
      hJetResEta[iSamp]->Draw("same");
    }
  }

  //leg->Draw();
  c->SaveAs(TString(pname)+TString(".png"));
}
Ejemplo n.º 22
0
void tauStudy(const TString inputfile = "/afs/cern.ch/work/k/klawhorn/HHToBBTT/Conf4_10GeV/HHToBBTT_10GeVJets_14TeV.root") {

  // set up input tree

  LorentzVector *genTau1=0, *genTau2=0, *genJetTau1=0, *genJetTau2=0, *jetTau1=0, *jetTau2=0;

  Float_t genTau1pt, genTau2pt, genJetTau1pt, genJetTau2pt, jetTau1pt, jetTau2pt, corrJetTau1pt, corrJetTau2pt;
  Float_t genTau1eta, genTau2eta, genJetTau1eta, genJetTau2eta, jetTau1eta, jetTau2eta;

  TFile *infile = new TFile(inputfile, "READ"); assert(infile);
  TTree *intree = (TTree*) infile->Get("Events"); assert(intree);

  intree->SetBranchAddress("genTau1",        &genTau1);
  intree->SetBranchAddress("genTau2",        &genTau2);
  intree->SetBranchAddress("genJetTau1",     &genJetTau1);
  intree->SetBranchAddress("genJetTau2",     &genJetTau2);
  intree->SetBranchAddress("jetTau1",        &jetTau1);
  intree->SetBranchAddress("jetTau2",        &jetTau2);

  const Float_t PT_MAX = 500;
  const Float_t PT_MIN = 0;
  const Int_t PT_BINS = 50;
  const Float_t ETA_MAX = 2.4;
  const Float_t ETA_MIN = -2.4;
  const Int_t ETA_BINS = 16;
  
  TProfile *tauTagEffWithPT = new TProfile("tauTagEffWithPT", "Tau Tagging Efficiency", PT_BINS, PT_MIN, PT_MAX);
  TProfile *tauTagEffWithEta = new TProfile("tauTagEffWithEta", "Tau Tagging Efficiency", ETA_BINS, ETA_MIN, ETA_MAX);

  //TProfile *ptScaleWithPT = new TProfile("ptScaleWithPT", "P_{T} Scale Factor between gen Tau and reco Jet", PT_BINS, PT_MIN, PT_MAX);
  //TProfile *ptJetScaleWithPT = new TProfile("ptJetScaleWithPT", "P_{T} Scale Factor between gen Jet and reco Jet", PT_BINS, PT_MIN, PT_MAX);

  //TProfile *ptScaleWithEta = new TProfile("ptScaleWithEta", "P_{T} Scale Factor between gen Tau and reco Jet", ETA_BINS, ETA_MIN, ETA_MAX);
  //TProfile *ptJetScaleWithEta = new TProfile("ptJetScaleWithEta", "P_{T} Scale Factor between gen Jet and reco Jet", ETA_BINS, ETA_MIN, ETA_MAX);

  //TProfile *ptResWithPT = new TProfile("ptResWithPT", "P_{T} Resolution between gen Tau and reco Jet", PT_BINS, PT_MIN, PT_MAX);
  TProfile *ptJetResWithPT = new TProfile("ptJetResWithPT", "P_{T} Resolution: (genJet-recoJet)/(genJet)", PT_BINS, PT_MIN, PT_MAX);
  TProfile *ptJetResCorrWithPT = new TProfile("ptJetResCorrWithPT", "P_{T} Resolution: (genJet-recoJet)/(genJet)", PT_BINS, PT_MIN, PT_MAX);

  //TProfile *ptResWithEta = new TProfile("ptResWithEta", "P_{T} Resolution between gen Tau and reco Jet", ETA_BINS, ETA_MIN, ETA_MAX);
  TProfile *ptJetResWithEta = new TProfile("ptJetResWithEta", "P_{T} Resolution: (genJet-recoJet)/(genJet)", ETA_BINS, ETA_MIN, ETA_MAX);
  TProfile *ptJetResCorrWithEta = new TProfile("ptJetResCorrWithEta", "P_{T} Resolution: (genJet-recoJet)/(genJet)", ETA_BINS, ETA_MIN, ETA_MAX);
  
  for (Int_t iEntry=0; iEntry<intree->GetEntries(); iEntry++) {
    intree->GetEntry(iEntry);

    genTau1pt = genTau1->Pt();       genTau1eta = genTau1->Eta();
    genTau2pt = genTau2->Pt();       genTau2eta = genTau2->Eta();
    genJetTau1pt = genJetTau1->Pt(); genJetTau1eta = genJetTau1->Eta();
    genJetTau2pt = genJetTau2->Pt(); genJetTau2eta = genJetTau2->Eta();
    jetTau1pt = jetTau1->Pt();       jetTau1eta = jetTau1->Eta();
    jetTau2pt = jetTau2->Pt();       jetTau2eta = jetTau2->Eta();

    // jet corrections
    //if ( (jetTau1pt != 999) ) cout << "eta " << jetTau1eta << " pt " << jetTau1pt << " scaleCorr " << getJetScaleFactor(jetTau1pt, jetTau1eta) << endl;
    corrJetTau1pt = jetTau1pt*getJetScaleFactor(jetTau1pt, jetTau1eta);
    corrJetTau2pt = jetTau2pt*getJetScaleFactor(jetTau2pt, jetTau2eta);

    if ( (genTau1pt != 999) && (jetTau1pt != 999) ) {
      tauTagEffWithPT->Fill(genTau1pt, 1);
      //ptScaleWithPT->Fill(genTau1pt, jetTau1pt/genTau1pt);
      //ptJetScaleWithPT->Fill(genJetTau1pt, jetTau1pt/genJetTau1pt);
      //ptResWithPT->Fill(genTau1pt, (genTau1pt-jetTau1pt)/genTau1pt);
      ptJetResWithPT->Fill(genJetTau1pt, (genJetTau1pt-jetTau1pt)/genJetTau1pt);
      ptJetResCorrWithPT->Fill(genJetTau1pt, (genJetTau1pt-corrJetTau1pt)/genJetTau1pt);

      tauTagEffWithEta->Fill(genTau1eta, 1);
      //ptScaleWithEta->Fill(genTau1eta, jetTau1pt/genTau1pt);
      //ptJetScaleWithEta->Fill(genJetTau1eta, jetTau1pt/genJetTau1pt);
      //ptResWithEta->Fill(genTau1eta, (genTau1pt-jetTau1pt)/genTau1pt);
      ptJetResWithEta->Fill(genJetTau1eta, (genJetTau1pt-jetTau1pt)/genJetTau1pt);
      ptJetResCorrWithEta->Fill(genJetTau1eta, (genJetTau1pt-corrJetTau1pt)/genJetTau1pt);

    }
    else if ( (genTau1pt != 999) && (jetTau1pt == 999) ) {
      tauTagEffWithPT->Fill(genTau1pt, 0);
      tauTagEffWithEta->Fill(genTau1eta, 0);
    }
    if ( (genTau2pt != 999) && (jetTau2pt != 999) ) {
      tauTagEffWithPT->Fill(genTau2pt, 1);
      //ptScaleWithPT->Fill(genTau2pt, jetTau2pt/genTau2pt);
      //ptJetScaleWithPT->Fill(genJetTau2pt, jetTau2pt/genJetTau2pt);
      //ptResWithPT->Fill(genTau2pt, (genTau2pt-jetTau2pt)/genTau2pt);
      ptJetResWithPT->Fill(genJetTau2pt, (genJetTau2pt-jetTau2pt)/genJetTau2pt);
      ptJetResCorrWithPT->Fill(genJetTau2pt, (genJetTau2pt-corrJetTau2pt)/genJetTau2pt);

      tauTagEffWithEta->Fill(genTau2eta, 1);
      //ptScaleWithEta->Fill(genTau2eta, jetTau2pt/genTau2pt);
      //ptJetScaleWithEta->Fill(genJetTau2eta, jetTau2pt/genJetTau2pt);
      //ptResWithEta->Fill(genTau2eta, (genTau2pt-jetTau2pt)/genTau2pt);
      ptJetResWithEta->Fill(genJetTau2eta, (genJetTau2pt-jetTau2pt)/genJetTau2pt);
      ptJetResCorrWithEta->Fill(genJetTau2eta, (genJetTau2pt-corrJetTau2pt)/genJetTau2pt);

    }
    else if ( (genTau2pt != 999) && (jetTau2pt == 999) ) {
      tauTagEffWithPT->Fill(genTau2pt, 0);
      tauTagEffWithEta->Fill(genTau2eta, 0);
    }

  }

  TCanvas *c1 = MakeCanvas("c1", "Tau Tagging Efficiency", 800, 600);
  tauTagEffWithPT->SetMarkerStyle(1);
  tauTagEffWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau");
  tauTagEffWithPT->GetYaxis()->SetTitle("Efficiency");
  tauTagEffWithPT->Draw();
  
  c1->SaveAs("tauTagEffWithPT.png");

  TCanvas *c2 = MakeCanvas("c2", "Tau Tagging Efficiency", 800, 600);
  tauTagEffWithEta->SetMarkerStyle(1);
  tauTagEffWithEta->GetXaxis()->SetTitle("Eta of Generator Tau");
  tauTagEffWithEta->GetYaxis()->SetTitle("Efficiency");
  tauTagEffWithEta->Draw();

  c2->SaveAs("tauTagEffWithEta.png");
  /*  
  TCanvas *c3 = MakeCanvas("c3", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau P_{T})", 800, 600);
  ptScaleWithPT->SetMarkerStyle(1);
  ptScaleWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau");
  ptScaleWithPT->GetYaxis()->SetTitle("P_{T} Scale");
  ptScaleWithPT->Draw();

  c3->SaveAs("ptScaleWithPT.png");

  TCanvas *c4 = MakeCanvas("c4", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau P_{T})", 800, 600);
  ptScaleWithEta->SetMarkerStyle(1);
  ptScaleWithEta->GetXaxis()->SetTitle("Eta of Generator Tau");
  ptScaleWithEta->GetYaxis()->SetTitle("P_{T} Scale");
  ptScaleWithEta->Draw();

  c4->SaveAs("ptScaleWithEta.png");

  TCanvas *c5 = MakeCanvas("c5", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau Jet P_{T})", 800, 600);
  ptJetScaleWithPT->SetMarkerStyle(1);
  ptJetScaleWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau Jet");
  ptJetScaleWithPT->GetYaxis()->SetTitle("P_{T} Scale");
  ptJetScaleWithPT->Draw();

  c5->SaveAs("ptJetScaleWithPT.png");

  TCanvas *c6 = MakeCanvas("c6", "Tau P_{T} Scale (reco Tau Jet P_{T}/gen Tau Jet P_{T})", 800, 600);
  ptJetScaleWithEta->SetMarkerStyle(1);
  ptJetScaleWithEta->GetXaxis()->SetTitle("Eta of Generator Tau Jet");
  ptJetScaleWithEta->GetYaxis()->SetTitle("P_{T} Scale");
  ptJetScaleWithEta->Draw();

  c6->SaveAs("ptJetScaleWithEta.png");

  TCanvas *c7 = MakeCanvas("c7", "Tau P_{T} Resolution ((reco Tau Jet P_{T} - gen Tau P_{T})/gen Tau P_{T})", 800, 600);
  ptResWithPT->SetMarkerStyle(1);
  ptResWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau");
  ptResWithPT->GetYaxis()->SetTitle("P_{T} Resolution");
  ptResWithPT->Draw();

  c7->SaveAs("ptResWithPT.png");

  TCanvas *c8 = MakeCanvas("c8", "Tau P_{T} Resolution", 800, 600);
  ptResWithEta->SetMarkerStyle(1);
  ptResWithEta->GetXaxis()->SetTitle("Eta of Generator Tau");
  ptResWithEta->GetYaxis()->SetTitle("P_{T} Resolution");
  ptResWithEta->Draw();
  
  c8->SaveAs("ptResWithEta.png");

  TCanvas *c9 = MakeCanvas("c9", "Tau P_{T} Resolution", 800, 600);
  ptJetResWithPT->SetMarkerStyle(1);
  ptJetResWithPT->GetXaxis()->SetTitle("P_{T} of Generator Tau Jet");
  ptJetResWithPT->GetYaxis()->SetTitle("P_{T} Resolution");
  ptJetResWithPT->Draw();
  ptJetResCorrWithPT->SetMarkerStyle(1);
  ptJetResCorrWithPT->SetLineColor(2);
  ptJetResCorrWithPT->Draw("same");

  c9->SaveAs("ptJetResWithPT.png");

  TCanvas *c10 = MakeCanvas("c10", "Tau P_{T} Resolution ((reco Tau Jet P_{T} - gen Tau Jet P_{T})/gen Tau Jet P_{T})", 800, 600);
  ptJetResWithEta->SetMarkerStyle(1);
  ptJetResWithEta->GetXaxis()->SetTitle("Eta of Generator Tau Jet");
  ptJetResWithEta->GetYaxis()->SetTitle("P_{T} Resolution");
  ptJetResWithEta->Draw();
  ptJetResCorrWithEta->SetMarkerStyle(1);
  ptJetResCorrWithEta->SetLineColor(2);
  ptJetResCorrWithEta->Draw("same");

  c10->SaveAs("ptJetResWithEta.png");
  */  
}
Ejemplo n.º 23
0
void plotDataMC(const TString outdir   = "Data/extra",
                const TString mcfname  = "MC/eff.root",
	        const TString datfname = "Data/eff.root"
) {
  gBenchmark->Start("plotDataMC");
  
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  vector<TString> etalabelv;
  vector<TString> ptlabelv;
  
  // eta bins
  etalabelv.push_back("0 < |#eta| < 1.5");
  etalabelv.push_back("1.5 < |#eta| < 2.5");
  
  CPlot::sOutDir = outdir;
  TString format = "png";

  // y-axis ranges
  Double_t efflow   = 0.10, effhigh   = 1.20;
  Double_t scalelow = 0.95, scalehigh = 1.05;
  
  
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================   
  
  TFile mcfile(mcfname);      
  TFile datafile(datfname);
  
  TH2F *hMCEff=0,   *hMCErrl=0,   *hMCErrh=0;
  TH2F *hDataEff=0, *hDataErrl=0, *hDataErrh=0;
  
  TGraphAsymmErrors *grMCEffEta=0, *grDataEffEta=0, *grScaleEta=0;
  TGraphAsymmErrors *grMCEffPt=0,  *grDataEffPt=0,  *grScalePt=0;
  
  vector<TGraphAsymmErrors*> mceff_vs_pt_per_etav;
  vector<TGraphAsymmErrors*> eff_vs_pt_per_etav;
  vector<TGraphAsymmErrors*> mceff_vs_eta_per_ptv;
  vector<TGraphAsymmErrors*> eff_vs_eta_per_ptv;
  vector<TGraphAsymmErrors*> scale_vs_pt_per_etav;
  vector<TGraphAsymmErrors*> scale_vs_eta_per_ptv;
  
  grMCEffEta = (TGraphAsymmErrors*)mcfile.Get("grEffEta");
  grMCEffPt  = (TGraphAsymmErrors*)mcfile.Get("grEffPt");
  if(grMCEffPt) {
    grMCEffPt->SetPoint(grMCEffPt->GetN()-1, 125, grMCEffPt->GetY()[grMCEffPt->GetN()-1]);
    grMCEffPt->SetPointError(grMCEffPt->GetN()-1,25,25, 
                             grMCEffPt->GetErrorYlow(grMCEffPt->GetN()-1),
			     grMCEffPt->GetErrorYhigh(grMCEffPt->GetN()-1));
  }  			               
  hMCEff  = (TH2F*)mcfile.Get("hEffEtaPt");
  hMCErrl = (TH2F*)mcfile.Get("hErrlEtaPt");
  hMCErrh = (TH2F*)mcfile.Get("hErrhEtaPt");  

  grDataEffEta = (TGraphAsymmErrors*)datafile.Get("grEffEta");
  grDataEffPt  = (TGraphAsymmErrors*)datafile.Get("grEffPt");
  if(grDataEffPt) {
    grDataEffPt->SetPoint(grDataEffPt->GetN()-1, 125, grDataEffPt->GetY()[grDataEffPt->GetN()-1]);
    grDataEffPt->SetPointError(grDataEffPt->GetN()-1,25,25, 
                                grDataEffPt->GetErrorYlow(grDataEffPt->GetN()-1),
			        grDataEffPt->GetErrorYhigh(grDataEffPt->GetN()-1));
  }
  
  hDataEff  = (TH2F*)datafile.Get("hEffEtaPt");
  hDataErrl = (TH2F*)datafile.Get("hErrlEtaPt");
  hDataErrh = (TH2F*)datafile.Get("hErrhEtaPt");
    
  if(grMCEffEta && grDataEffEta) {
    grScaleEta = new TGraphAsymmErrors(grMCEffEta->GetN());
    for(Int_t i=0; i<grMCEffEta->GetN(); i++) {
      Double_t mcval   = grMCEffEta->GetY()[i];
      Double_t dataval = grDataEffEta->GetY()[i];
      Double_t scale   = dataval/mcval;
      grScaleEta->SetPoint(i,grMCEffEta->GetX()[i],scale);
      
      Double_t mcerrl   = grMCEffEta->GetErrorYlow(i);
      Double_t mcerrh   = grMCEffEta->GetErrorYhigh(i);
      Double_t dataerrl = grDataEffEta->GetErrorYlow(i);
      Double_t dataerrh = grDataEffEta->GetErrorYhigh(i);
      grScaleEta->SetPointError(i, 0, 0,
	  		        scale*sqrt(mcerrl*mcerrl/mcval/mcval + dataerrl*dataerrl/dataval/dataval),
			        scale*sqrt(mcerrh*mcerrh/mcval/mcval + dataerrh*dataerrh/dataval/dataval));
    }
  }
  
  if(grMCEffPt && grDataEffPt) {
    grScalePt = new TGraphAsymmErrors(grMCEffPt->GetN());
    for(Int_t i=0; i<grMCEffPt->GetN(); i++) {
      Double_t mcval   = grMCEffPt->GetY()[i];
      Double_t dataval = grDataEffPt->GetY()[i];
      Double_t scale   = dataval/mcval;
      grScalePt->SetPoint(i, grMCEffPt->GetX()[i],scale);
      if(i==grMCEffPt->GetN()-1)
        grScalePt->SetPoint(i,165,scale);
    
      Double_t mcerrl   = grMCEffPt->GetErrorYlow(i);
      Double_t mcerrh   = grMCEffPt->GetErrorYhigh(i);
      Double_t dataerrl = grDataEffPt->GetErrorYlow(i);
      Double_t dataerrh = grDataEffPt->GetErrorYhigh(i);
      grScalePt->SetPointError(i, 0, 0,
			        scale*sqrt(mcerrl*mcerrl/mcval/mcval + dataerrl*dataerrl/dataval/dataval),
			        scale*sqrt(mcerrh*mcerrh/mcval/mcval + dataerrh*dataerrh/dataval/dataval));
    }
  }
  
  if(hMCEff->GetEntries()>0 && hDataEff->GetEntries()>0) {
    const Int_t nx = hMCEff->GetNbinsX();
    const Int_t ny = hMCEff->GetNbinsY(); 
/*    
    for(Int_t iy=1; iy<=ny; iy++) {
      Double_t xval[nx], xerr[nx];
      Double_t effval[nx],   efferrl[nx],   efferrh[nx];
      Double_t scaleval[nx], scaleerrl[nx], scaleerrh[nx];
      
      for(Int_t ix=1; ix<=nx; ix++) {
        xval[ix-1] = 0.5*(hMCEff->GetXaxis()->GetBinLowEdge(ix) + hMCEff->GetXaxis()->GetBinLowEdge(ix+1));
        xerr[ix-1] = 0;
        
        Double_t mceff  = hMCEff->GetCellContent(ix,iy);
        Double_t mcerrl = hMCErrl->GetCellContent(ix,iy);
        Double_t mcerrh = hMCErrh->GetCellContent(ix,iy);
        
        Double_t dataeff  = hDataEff->GetCellContent(ix,iy);
        Double_t dataerrl = hDataErrl->GetCellContent(ix,iy);
        Double_t dataerrh = hDataErrh->GetCellContent(ix,iy);
        effval[ix-1]  = dataeff;
        efferrl[ix-1] = dataerrl;
        efferrh[ix-1] = dataerrh;
        
        Double_t scale = dataeff/mceff;
        scaleval[ix-1]  = scale;
        scaleerrl[ix-1] = scale*sqrt(mcerrl*mcerrl/mceff/mceff + dataerrl*dataerrl/dataeff/dataeff);
        scaleerrh[ix-1] = scale*sqrt(mcerrh*mcerrh/mceff/mceff + dataerrh*dataerrh/dataeff/dataeff);
      }
      
      eff_vs_eta_per_ptv.push_back(new TGraphAsymmErrors(nx,xval,effval,xerr,xerr,efferrl,efferrh));
      scale_vs_eta_per_ptv.push_back(new TGraphAsymmErrors(nx,xval,scaleval,xerr,xerr,scaleerrl,scaleerrh));
    }
*/    
    for(Int_t ix=1; ix<=nx; ix++) {
      Double_t xval[ny], xerr[ny];
      Double_t mceffval[ny], mcefferrl[ny], mcefferrh[ny];
      Double_t effval[ny],   efferrl[ny],   efferrh[ny];
      Double_t scaleval[ny], scaleerrl[ny], scaleerrh[ny];
      
      for(Int_t iy=1; iy<=ny; iy++) {
        xval[iy-1] = 0.5*(hMCEff->GetYaxis()->GetBinLowEdge(iy+1) + hMCEff->GetYaxis()->GetBinLowEdge(iy));
        xerr[iy-1] = 0.5*(hMCEff->GetYaxis()->GetBinLowEdge(iy+1) - hMCEff->GetYaxis()->GetBinLowEdge(iy));
	if(iy==ny) {
	  xval[iy-1] = 125;
          xerr[iy-1] = 25;
        }
	
        Double_t mceff  = hMCEff->GetCellContent(ix,iy);
        Double_t mcerrl = hMCErrl->GetCellContent(ix,iy);
        Double_t mcerrh = hMCErrh->GetCellContent(ix,iy);
	mceffval[iy-1]  = mceff;
        mcefferrl[iy-1] = mcerrl;
        mcefferrh[iy-1] = mcerrh;
        
        Double_t dataeff  = hDataEff->GetCellContent(ix,iy);
        Double_t dataerrl = hDataErrl->GetCellContent(ix,iy);
        Double_t dataerrh = hDataErrh->GetCellContent(ix,iy);
        effval[iy-1]  = dataeff;
        efferrl[iy-1] = dataerrl;
        efferrh[iy-1] = dataerrh;
        
        Double_t scale = dataeff/mceff;
        scaleval[iy-1]  = scale;
        scaleerrl[iy-1] = (scale>0) ? scale*sqrt(mcerrl*mcerrl/mceff/mceff + dataerrl*dataerrl/dataeff/dataeff) : 0;
        scaleerrh[iy-1] = (scale>0) ? scale*sqrt(mcerrh*mcerrh/mceff/mceff + dataerrh*dataerrh/dataeff/dataeff) : 0;
      }
      
      mceff_vs_pt_per_etav.push_back(new TGraphAsymmErrors(ny,xval,mceffval,xerr,xerr,mcefferrl,mcefferrh));
      eff_vs_pt_per_etav.push_back(new TGraphAsymmErrors(ny,xval,effval,xerr,xerr,efferrl,efferrh));
      scale_vs_pt_per_etav.push_back(new TGraphAsymmErrors(ny,xval,scaleval,0,0,scaleerrl,scaleerrh));
    }  
  }

    
  //--------------------------------------------------------------------------------------------------------------
  // Make plots
  //==============================================================================================================
  TCanvas *c = MakeCanvas("c","c",800,600);
  
  if(grMCEffEta && grDataEffEta) {
    CPlot plotEffEta("effeta","","|#eta|","#varepsilon");
    plotEffEta.AddGraph(grMCEffEta,   "MC","",  kRed, kOpenSquare);
    plotEffEta.AddGraph(grDataEffEta,"data","",kBlue,kFullDotLarge);
    plotEffEta.SetYRange(efflow,effhigh);
    plotEffEta.TransLegend(0,-0.5);
    plotEffEta.Draw(c,kTRUE,format);
    
    CPlot plotScaleEta("scaleeta","","|#eta|","scale factor");
    plotScaleEta.AddGraph(grScaleEta,"",kBlue,kFullDotLarge);
    plotScaleEta.AddLine(0,1.0,2.7,1.0,kBlack,7);
    plotScaleEta.SetYRange(scalelow,scalehigh);
    plotScaleEta.SetXRange(0,2.7);
    plotScaleEta.Draw(c,kTRUE,format);
  }
  
  if(grMCEffPt && grDataEffPt) {
    CPlot plotEffPt("effpt","","p_{T} [GeV/c]","#varepsilon");
    plotEffPt.AddGraph(grMCEffPt,   "MC","",  kRed, kOpenSquare);
    plotEffPt.AddGraph(grDataEffPt,"data","",kBlue,kFullDotLarge);
    plotEffPt.SetYRange(efflow,effhigh);
    plotEffPt.SetXRange(0,150);
    plotEffPt.TransLegend(0,-0.5);
    plotEffPt.Draw(c,kTRUE,format);
  
    CPlot plotScalePt("scalept","","p_{T} [GeV/c]","scale factor");
    plotScalePt.AddGraph(grScalePt,"",kBlue,kFullDotLarge);
    plotScalePt.AddLine(0,1.0,150,1.0,kBlack,7);
    plotScalePt.SetXRange(0,150);
    plotScalePt.SetYRange(scalelow,scalehigh);
    plotScalePt.Draw(c,kTRUE,format);
  }
      
  if(mceff_vs_pt_per_etav.size()>0 && eff_vs_pt_per_etav.size()>0) {
    for(UInt_t ig=0; ig<mceff_vs_pt_per_etav.size(); ig++) {
      char pname[100];
      sprintf(pname,"effpt_eta%i",ig);
      CPlot plotEffPt_perEta(pname,"","p_{T} [GeV/c]","#varepsilon");
      plotEffPt_perEta.AddGraph(mceff_vs_pt_per_etav[ig],"MC","",   kRed,  kOpenSquare);
      plotEffPt_perEta.AddGraph(eff_vs_pt_per_etav[ig], "data","", kBlue, kFullDotLarge);
      plotEffPt_perEta.AddTextBox(etalabelv[ig],0.2,0.82,0.4,0.88,0);
      plotEffPt_perEta.TransLegend(0,-0.5); 
      plotEffPt_perEta.SetXRange(0,150);
      plotEffPt_perEta.SetYRange(efflow,effhigh);
      plotEffPt_perEta.Draw(c,kTRUE,format);
    }    
    
    for(UInt_t ig=0; ig<scale_vs_pt_per_etav.size(); ig++) {
      char pname[100];
      sprintf(pname,"scalept_eta%i",ig);
      CPlot plotScalePt_perEta(pname,"","p_{T} [GeV/c]","scale factor");
      plotScalePt_perEta.AddGraph(scale_vs_pt_per_etav[ig],"",kBlue,kFullDotLarge);
      plotScalePt_perEta.AddTextBox(etalabelv[ig],0.7,0.82,0.9,0.88,0);
      plotScalePt_perEta.AddLine(0,1,150,1,kBlack,7);
      plotScalePt_perEta.SetXRange(0,150);
      plotScalePt_perEta.SetYRange(scalelow,scalehigh);
      plotScalePt_perEta.Draw(c,kTRUE,format);
    }
  }

  if(mceff_vs_eta_per_ptv.size()>0 && eff_vs_eta_per_ptv.size()>0) {
    for(UInt_t ig=0; ig<mceff_vs_eta_per_ptv.size(); ig++) {
      char pname[100];
      sprintf(pname,"effeta_pt%i",ig);
      CPlot plotEffEta_perPt(pname,"","|#eta|","#varepsilon");
      plotEffEta_perPt.AddGraph(mceff_vs_eta_per_ptv[ig],"MC","",  kRed,  kOpenSquare);
      plotEffEta_perPt.AddGraph(eff_vs_eta_per_ptv[ig], "data","", kBlue, kFullDotLarge);
      plotEffEta_perPt.AddTextBox(ptlabelv[ig],0.2,0.82,0.4,0.88,0);
      plotEffEta_perPt.SetYRange(efflow,effhigh);
      plotEffEta_perPt.Draw(c,kTRUE,format);
    }
    
    for(UInt_t ig=0; ig<scale_vs_eta_per_ptv.size(); ig++) {
      char pname[100];
      sprintf(pname,"scaleeta_pt%i",ig);
      CPlot plotScaleEta_perPt(pname,"","|#eta|","scale factor");
      plotScaleEta_perPt.AddGraph(scale_vs_eta_per_ptv[ig],"", kBlue, kFullDotLarge);
      plotScaleEta_perPt.AddLine(-2.7,1.0,2.7,1.0,kBlack,7);
      plotScaleEta_perPt.AddTextBox(ptlabelv[ig],0.7,0.82,0.9,0.88,0);
      plotScaleEta_perPt.SetYRange(scalelow,scalehigh);
      plotScaleEta_perPt.SetXRange(-2.7,2.7);
      plotScaleEta_perPt.Draw(c,kTRUE,format);
    }
  }
  
  gBenchmark->Show("plotDataMC");
}
Ejemplo n.º 24
0
// examples macro
void 
etauAfterFit_novbf(bool scaled = true, bool log = true)
{
  // defining the common canvas, axes pad styles
  SetStyle();

  // open example histogram file
  TFile* exampleFile = new TFile("eleTau_sm.root");

  //load example histograms
  TH1F* data = (TH1F*)exampleFile->Get("eleTau_SM0/data_obs");
  if(data) {InitHist(data, "#bf{m_{vis} [GeV]}", "#bf{Events}"); InitData(data);} else{std::cout << "can't find hitogram " << "eleTau_SM0/data_obs" << std::endl;}

  TH1F* Fakes =  refill((TH1F*)exampleFile->Get("eleTau_SM0/QCD"))              ; InitHist(Fakes, "", "", kMagenta-10, 1001);                   
  TH1F* EWK1  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/W"  ))              ; InitHist(EWK1 , "", "", kRed    + 2, 1001);
  TH1F* EWK2  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZJ" ))              ; InitHist(EWK2 , "", "", kRed    + 2, 1001);
  TH1F* EWK3  =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZL" ))              ; InitHist(EWK3 , "", "", kRed    + 2, 1001);
  TH1F* EWK   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/VV" ))              ; InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar =  refill((TH1F*)exampleFile->Get("eleTau_SM0/TT" ))              ; InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/ZTT"))              ; InitHist(Ztt  , "", "", kOrange - 4, 1001);
  TH1F* ggH   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/SM120" ))           ; InitSignal(ggH); ggH ->Scale(10*16.63*0.071*16.083/ggH ->Integral());
  TH1F* qqH   =  refill((TH1F*)exampleFile->Get("eleTau_SM0/VBF120"))           ; InitSignal(qqH); qqH ->Scale(10*1.269*0.071* 1.105/qqH ->Integral());
 
  if(scaled){
    rescale(Fakes, 2); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
    rescale(EWK3 , 5); 
    rescale(EWK  , 7); 
    rescale(ttbar, 6); 
    rescale(Ztt  , 1);
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
  }
  if(log){
    qqH  ->Add(ggH  );
    Fakes->Add(qqH  );
    EWK1 ->Add(Fakes);
    EWK2 ->Add(EWK1 );
    EWK3 ->Add(EWK2 );
    EWK  ->Add(EWK3 );
    ttbar->Add(EWK  );
    Ztt  ->Add(ttbar);
  }
  else{
    EWK1 ->Add(Fakes);
    EWK2 ->Add(EWK1 );
    EWK3 ->Add(EWK2 );
    EWK  ->Add(EWK3 );
    ttbar->Add(EWK  );
    Ztt  ->Add(ttbar);
    ggH  ->Add(Ztt  );
    qqH  ->Add(ggH  );
  }
  // define canvas
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){
    canv->SetLogy(1);
    data->SetMinimum(5.0);
    data->SetMaximum(500000.);
  }
  else{
    data->SetMaximum(4000.);
  }
  data->SetNdivisions(505);
  data->Draw("e");

  if(log){
    Ztt->Draw("same");
    ttbar->Draw("same");
    EWK->Draw("same");
    Fakes->Draw("same");
    qqH->Draw("same");
  }
  else{
    qqH->Draw("same");
    Ztt->Draw("same");
    ttbar->Draw("same");
    EWK->Draw("same");
    Fakes->Draw("same");
  }
  data->Draw("esame");
  canv->RedrawAxis();

  CMSPrelim("#tau_{e}#tau_{h}", 0.45, 0.75);
  
  TLegend* leg = new TLegend(0.45, 0.45, 0.9, 0.75);
  SetLegendStyle(leg);
  leg->AddEntry(qqH  , "(10x) H#rightarrow#tau#tau" , "L" );
  leg->AddEntry(data , "Observed"                , "LP");
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"    , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                , "F" );
  leg->AddEntry(EWK  , "Electroweak"             , "F" );
  leg->AddEntry(Fakes, "QCD"                     , "F" );
  leg->Draw();

  TPaveText* mssm  = new TPaveText(0.78, 0.70, 0.90, 0.74, "NDC");
  mssm->SetBorderSize(   0 );
  mssm->SetFillStyle(    0 );
  mssm->SetTextAlign(   12 );
  mssm->SetTextSize ( 0.04 );
  mssm->SetTextColor(    1 );
  mssm->SetTextFont (   62 );
  mssm->AddText("m_{H}=120");
  mssm->Draw();

  if(log){
    if(scaled) canv->Print("etau_rescaled_novbf_LOG.pdf"); else canv->Print("etau_unscaled_novbf_LOG.pdf");
    if(scaled) canv->Print("etau_rescaled_novbf_LOG.png"); else canv->Print("etau_unscaled_novbf_LOG.png");
  }
  else{
    if(scaled) canv->Print("etau_rescaled_novbf.pdf"); else canv->Print("etau_unscaled_novbf.pdf");
    if(scaled) canv->Print("etau_rescaled_novbf.png"); else canv->Print("etau_unscaled_novbf.png");
  }
}
Ejemplo n.º 25
0
void PlotJetScheme()
{
  gROOT->LoadMacro("$LOCAL/include/TUntilsOpHisto.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsAliFigs.h");
  gROOT->LoadMacro("$LOCAL/include/TUntilsPlotStd.h"); SetStyle();
//=============================================================================

  TFile *file = TFile::Open("data/incl/AnalysisOutputs_jet_py8_JetR05_SjeR01.root", "READ");
  TH1D *h5py8I = (TH1D*)file->Get("hJet"); h5py8I->SetName("h5py8I"); h5py8I->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_py6_JetR05_SjeR01.root", "READ");
  TH1D *h5py6I = (TH1D*)file->Get("hJet"); h5py6I->SetName("h5py6I"); h5py6I->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_qpy_JetR05_SjeR01.root", "READ");
  TH1D *h5qpyI = (TH1D*)file->Get("hJet"); h5qpyI->SetName("h5qpyI"); h5qpyI->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_vac_JetR05_SjeR01.root", "READ");
  TH1D *h5vacI = (TH1D*)file->Get("hJet"); h5vacI->SetName("h5vacI"); h5vacI->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_med_JetR05_SjeR01.root", "READ");
  TH1D *h5medI = (TH1D*)file->Get("hJet"); h5medI->SetName("h5medI"); h5medI->SetDirectory(0);
  file->Close();


  file = TFile::Open("data/incl/AnalysisOutputs_jet_py8_JetR04_SjeR01.root", "READ");
  TH1D *h4py8I = (TH1D*)file->Get("hJet"); h4py8I->SetName("h4py8I"); h4py8I->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_py6_JetR04_SjeR01.root", "READ");
  TH1D *h4py6I = (TH1D*)file->Get("hJet"); h4py6I->SetName("h4py6I"); h4py6I->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_qpy_JetR04_SjeR01.root", "READ");
  TH1D *h4qpyI = (TH1D*)file->Get("hJet"); h4qpyI->SetName("h4qpyI"); h4qpyI->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_vac_JetR04_SjeR01.root", "READ");
  TH1D *h4vacI = (TH1D*)file->Get("hJet"); h4vacI->SetName("h4vacI"); h4vacI->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/incl/AnalysisOutputs_jet_med_JetR04_SjeR01.root", "READ");
  TH1D *h4medI = (TH1D*)file->Get("hJet"); h4medI->SetName("h4medI"); h4medI->SetDirectory(0);
  file->Close();


  file = TFile::Open("data/mass/AnalysisOutputs_jet_py8_JetR05_SjeR01.root", "READ");
  TH1D *h5py8M = (TH1D*)file->Get("hJet"); h5py8M->SetName("h5py8M"); h5py8M->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_py6_JetR05_SjeR01.root", "READ");
  TH1D *h5py6M = (TH1D*)file->Get("hJet"); h5py6M->SetName("h5py6M"); h5py6M->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_qpy_JetR05_SjeR01.root", "READ");
  TH1D *h5qpyM = (TH1D*)file->Get("hJet"); h5qpyM->SetName("h5qpyM"); h5qpyM->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_vac_JetR05_SjeR01.root", "READ");
  TH1D *h5vacM = (TH1D*)file->Get("hJet"); h5vacM->SetName("h5vacM"); h5vacM->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_med_JetR05_SjeR01.root", "READ");
  TH1D *h5medM = (TH1D*)file->Get("hJet"); h5medM->SetName("h5medM"); h5medM->SetDirectory(0);
  file->Close();


  file = TFile::Open("data/mass/AnalysisOutputs_jet_py8_JetR04_SjeR01.root", "READ");
  TH1D *h4py8M = (TH1D*)file->Get("hJet"); h4py8M->SetName("h4py8M"); h4py8M->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_py6_JetR04_SjeR01.root", "READ");
  TH1D *h4py6M = (TH1D*)file->Get("hJet"); h4py6M->SetName("h4py6M"); h4py6M->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_qpy_JetR04_SjeR01.root", "READ");
  TH1D *h4qpyM = (TH1D*)file->Get("hJet"); h4qpyM->SetName("h4qpyM"); h4qpyM->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_vac_JetR04_SjeR01.root", "READ");
  TH1D *h4vacM = (TH1D*)file->Get("hJet"); h4vacM->SetName("h4vacM"); h4vacM->SetDirectory(0);
  file->Close();

  file = TFile::Open("data/mass/AnalysisOutputs_jet_med_JetR04_SjeR01.root", "READ");
  TH1D *h4medM = (TH1D*)file->Get("hJet"); h4medM->SetName("h4medM"); h4medM->SetDirectory(0);
  file->Close();
//=============================================================================

  TH1F    *hfm = 0;
  TCanvas *can = 0;
  TLegend *leg = 0;
  TLatex  *tex = 0;
  TLine  *line = 0;

  const Float_t dflx = -40., dfux = 200.;
  const Float_t dfly = 8e-10, dfuy = 8e3;

  const Float_t dlsx = 0.05, dlsy = 0.05;
  const Float_t dtsx = 0.06, dtsy = 0.06;
  const Float_t dtox = 1.10, dtoy = 1.00;

  const TString stnx = "#it{p}_{T,jet}^{ch} (GeV/#it{c})";
  const TString stny = "d#sigma/d#it{p}_{T} (mb/GetV/#it{c})";

  TH1D *hSE = new TH1D("hSE", "", 10., 0., 10.);
  hSE->SetLineWidth(2);
  hSE->SetLineColor(wcl[0]);
  hSE->SetMarkerStyle(wmk[0]);
  hSE->SetMarkerColor(wcl[0]);

  TH1D *hME = new TH1D("hME", "", 10., 0., 10.);
  hME->SetLineWidth(2);
  hME->SetLineColor(wcl[0]);
  hME->SetMarkerStyle(wmk[2]);
  hME->SetMarkerColor(wcl[0]);
//=============================================================================

  const Double_t dBin[] = { 0., 10., 20., 30., 40., 50., 60., 80., 100., 120., 150., 200., 250., 300., 350., 400., 500. };
  const Int_t nBin = sizeof(dBin) / sizeof(Double_t) -1;

  TH1D *h5py8Irb = h5py8I->Rebin(nBin, "h5py8Irb", dBin); TH1D *h4py8Irb = h4py8I->Rebin(nBin, "h4py8Irb", dBin);
  TH1D *h5py6Irb = h5py6I->Rebin(nBin, "h5py6Irb", dBin); TH1D *h4py6Irb = h4py6I->Rebin(nBin, "h4py6Irb", dBin);
  TH1D *h5qpyIrb = h5qpyI->Rebin(nBin, "h5qpyIrb", dBin); TH1D *h4qpyIrb = h4qpyI->Rebin(nBin, "h4qpyIrb", dBin);
  TH1D *h5vacIrb = h5vacI->Rebin(nBin, "h5vacIrb", dBin); TH1D *h4vacIrb = h4vacI->Rebin(nBin, "h4vacIrb", dBin);
  TH1D *h5medIrb = h5medI->Rebin(nBin, "h5medIrb", dBin); TH1D *h4medIrb = h4medI->Rebin(nBin, "h4medIrb", dBin);

  TH1D *h5py8Mrb = h5py8M->Rebin(nBin, "h5py8Mrb", dBin); TH1D *h4py8Mrb = h4py8M->Rebin(nBin, "h4py8Mrb", dBin);
  TH1D *h5py6Mrb = h5py6M->Rebin(nBin, "h5py6Mrb", dBin); TH1D *h4py6Mrb = h4py6M->Rebin(nBin, "h4py6Mrb", dBin);
  TH1D *h5qpyMrb = h5qpyM->Rebin(nBin, "h5qpyMrb", dBin); TH1D *h4qpyMrb = h4qpyM->Rebin(nBin, "h4qpyMrb", dBin);
  TH1D *h5vacMrb = h5vacM->Rebin(nBin, "h5vacMrb", dBin); TH1D *h4vacMrb = h4vacM->Rebin(nBin, "h4vacMrb", dBin);
  TH1D *h5medMrb = h5medM->Rebin(nBin, "h5medMrb", dBin); TH1D *h4medMrb = h4medM->Rebin(nBin, "h4medMrb", dBin);
//=============================================================================

  TH1D *h5py8R = (TH1D*)h5py8Irb->Clone("h5py8R"); h5py8R->Divide(h5py8Mrb);
  TH1D *h5qpyR = (TH1D*)h5qpyIrb->Clone("h5qpyR"); h5qpyR->Divide(h5qpyMrb);
  TH1D *h5medR = (TH1D*)h5medIrb->Clone("h5medR"); h5medR->Divide(h5medMrb);

  TH1D *h4py8R = (TH1D*)h4py8Irb->Clone("h4py8R"); h4py8R->Divide(h4py8Mrb);
  TH1D *h4qpyR = (TH1D*)h4qpyIrb->Clone("h4qpyR"); h4qpyR->Divide(h4qpyMrb);
  TH1D *h4medR = (TH1D*)h4medIrb->Clone("h4medR"); h4medR->Divide(h4medMrb);
//=============================================================================

  can = MakeCanvas("Jet5R"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0.95, 500., 1.2); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                      "#it{p}_{T,jet} (GeV/#it{c})",
                                                      "Ratio: BIpt scheme / E scheme");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(h5py8R, wcl[3], wmk[0], "SAME");
  DrawHisto(h5qpyR, wcl[1], wmk[0], "SAME");
  DrawHisto(h5medR, wcl[5], wmk[0], "SAME");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(h5py8R, "PYTHIA 8", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5qpyR, "Q-PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5medR, "JEWEL+PYTHIA", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jets anti-#it{k}_{T}, #it{R}=0.5, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("Jet4R"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0.95, 500., 1.2); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                      "#it{p}_{T,jet} (GeV/#it{c})",
                                                      "Ratio: BIpt scheme / E scheme");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(h4py8R, wcl[3], wmk[0], "SAME");
  DrawHisto(h4qpyR, wcl[1], wmk[0], "SAME");
  DrawHisto(h4medR, wcl[5], wmk[0], "SAME");

  leg = new TLegend(0.62, 0.64, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(h4py8R, "PYTHIA 8", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4qpyR, "Q-PYTHIA", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4medR, "JEWEL+PYTHIA", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jets anti-#it{k}_{T}, #it{R}=0.4, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  TH1D *h5qpyIAA = (TH1D*)h5qpyIrb->Clone("h5qpyIAA"); h5qpyIAA->Divide(h5py6Irb);
  TH1D *h5medIAA = (TH1D*)h5medIrb->Clone("h5medIAA"); h5medIAA->Divide(h5vacIrb);

  TH1D *h4qpyIAA = (TH1D*)h4qpyIrb->Clone("h4qpyIAA"); h4qpyIAA->Divide(h4py6Irb);
  TH1D *h4medIAA = (TH1D*)h4medIrb->Clone("h4medIAA"); h4medIAA->Divide(h4vacIrb);

  TH1D *h5qpyMAA = (TH1D*)h5qpyMrb->Clone("h5qpyMAA"); h5qpyMAA->Divide(h5py6Mrb);
  TH1D *h5medMAA = (TH1D*)h5medMrb->Clone("h5medMAA"); h5medMAA->Divide(h5vacMrb);

  TH1D *h4qpyMAA = (TH1D*)h4qpyMrb->Clone("h4qpyMAA"); h4qpyMAA->Divide(h4py6Mrb);
  TH1D *h4medMAA = (TH1D*)h4medMrb->Clone("h4medMAA"); h4medMAA->Divide(h4vacMrb);
//=============================================================================

  can = MakeCanvas("Jet5RAA"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0., 500., 1.2); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                        "#it{p}_{T,jet} (GeV/#it{c})",
                                                        "#it{R}_{AA}");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(h5qpyIAA, wcl[1], wmk[0], "SAME");
  DrawHisto(h5medIAA, wcl[5], wmk[0], "SAME");

  DrawHisto(h5qpyMAA, wcl[1], wmk[2], "SAME");
  DrawHisto(h5medMAA, wcl[5], wmk[2], "SAME");

  leg = new TLegend(0.42, 0.56, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(h5qpyIAA, "Q-PYTHIA, BIpt scheme", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5qpyMAA, "Q-PYTHIA, BIpt scheme", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5medIAA, "JEWEL+PYTHIA, E scheme", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h5medMAA, "JEWEL+PYTHIA, E scheme", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jet anti-#it{k}_{T}, #it{R}=0.5, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  can = MakeCanvas("Jet4RAA"); can->SetGridx(); can->SetGridy();
  hfm = can->DrawFrame(0., 0., 500., 1.2); SetupFrame(hfm, dlsx, dlsy, dtsx, dtsy, dtox, dtoy,
                                                        "#it{p}_{T,jet} (GeV/#it{c})",
                                                        "#it{R}_{AA}");
  hfm->GetXaxis()->SetNdivisions(510);
  hfm->GetYaxis()->SetNdivisions(510);

  DrawHisto(h4qpyIAA, wcl[1], wmk[0], "SAME");
  DrawHisto(h4medIAA, wcl[5], wmk[0], "SAME");

  DrawHisto(h4qpyMAA, wcl[1], wmk[2], "SAME");
  DrawHisto(h4medMAA, wcl[5], wmk[2], "SAME");

  leg = new TLegend(0.42, 0.56, 0.98, 0.88); SetupLegend(leg);
  leg->AddEntry(h4qpyIAA, "Q-PYTHIA, BIpt scheme", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4qpyMAA, "Q-PYTHIA, BIpt scheme", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4medIAA, "JEWEL+PYTHIA, E scheme", "LP")->SetTextSizePixels(24);
  leg->AddEntry(h4medMAA, "JEWEL+PYTHIA, E scheme", "LP")->SetTextSizePixels(24);
  leg->Draw();

  tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSizePixels(24);
  tex->DrawLatex(0.16, 0.92, "2.76 TeV, Jet anti-#it{k}_{T}, #it{R}=0.4, |#eta_{jet}|<1");
  CanvasEnd(can);
//=============================================================================

  return;
}
Ejemplo n.º 26
0
void bbtt_upg_em(std::string var,int nbins, double xmin, double xmax,std::string xtitle, std::string ytitle, double sigscale=1)
{

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

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

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

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

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  //stat1->Draw();
  canv1->Print((var+"_ratio.png").c_str());
  */
}
void 
HTT_TT_X(bool scaled=true, bool log=false, float min=0., float max=-1., const char* inputfile="root/$HISTFILE", const char* directory="$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category_extra = "";
  if(std::string(directory) == std::string("emu_0jet_low"  )){ category_extra = "0 jet, low p_{T}";  }
  if(std::string(directory) == std::string("emu_0jet_high" )){ category_extra = "0 jet, high p_{T}"; }
  if(std::string(directory) == std::string("emu_boost_low" )){ category_extra = "1 jet, low p_{T}";  }
  if(std::string(directory) == std::string("emu_boost_high")){ category_extra = "1 jet, high p_{T}"; }
  if(std::string(directory) == std::string("emu_vbf"       )){ category_extra = "2 jet (VBF)";       }
  if(std::string(directory) == std::string("emu_nobtag"    )){ category_extra = "No B-Tag";          }
  if(std::string(directory) == std::string("emu_btag"      )){ category_extra = "B-Tag";             }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  ZH#rightarrow#lltau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  ZH#rightarrowll#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#ifdef MSSM
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.4 fb^{-1} at 8 TeV";}
#endif
  
  TFile* input = new TFile(inputfile);
  TH1F* ZZ  = refill((TH1F*)input->Get(TString::Format("%s/ZZ"   , directory)), "ZZ"); InitHist(ZZ, "", "", kMagenta-10, 1001);
  TH1F* GGToZZ2L2L  = refill((TH1F*)input->Get(TString::Format("%s/GGToZZ2L2L"   , directory)), "GGToZZ2L2L"); InitHist(GGToZZ2L2L, "", "", kMagenta-10, 1001);
  TH1F* Zjets    = refill((TH1F*)input->Get(TString::Format("%s/Zjets"     , directory)), "Zjets"  ); InitHist(Zjets  , "", "", kRed    + 2, 1001);
#ifndef DROP_SIGNAL
  TH1F* ZH_htt    = refill((TH1F*)input->Get(TString::Format("%s/ZH_htt"  , directory)+"125"), "ZH_htt"  ); InitSignal(ZH_htt); ZH_htt->Scale(SIGNAL_SCALE);
  TH1F* ZH_hww    = refill((TH1F*)input->Get(TString::Format("%s/ZH_hww"  , directory)+"125"), "ZH_hww"  ); InitSignal(ZH_hww); ZH_hww->Scale(SIGNAL_SCALE);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)ZZ->Clone("ref");
  ref->Add(GGToZZ2L2L);
  ref->Add(Zjets  );

  double unscaled[5];
  unscaled[0] = ZZ->Integral();
  unscaled[1] = GGToZZ2L2L->Integral();
  unscaled[2] = Zjets  ->Integral();
#ifndef DROP_SIGNAL
  unscaled[3] = ZH_htt  ->Integral();
  unscaled[4] = ZH_hww  ->Integral();
#endif

  if(scaled){
    rescale(ZZ, 1);
    rescale(GGToZZ2L2L, 2);
    rescale(Zjets,   3);
#ifndef DROP_SIGNAL
    rescale(ZH_htt,   4);
    rescale(ZH_hww,   5);
#endif
  }

  TH1F* scales[5];
  scales[0] = new TH1F("scales-ZZ", "", 5, 0, 5);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (ZZ->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-GGToZZ2L2L", "", 5, 0, 5);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (GGToZZ2L2L->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-Zjets"  , "", 5, 0, 5);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (Zjets  ->Integral()/unscaled[2]-1.) : 0.);
#ifndef DROP_SIGNAL
  scales[3] = new TH1F("scales-ZH_htt"  , "", 5, 0, 5);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (ZH_htt  ->Integral()/unscaled[3]-1.) : 0.);
  scales[4] = new TH1F("scales-ZH_hww"  , "", 5, 0, 5);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ZH_hww  ->Integral()/unscaled[4]-1.) : 0.);
#endif

  GGToZZ2L2L->Add(Zjets);
  ZZ  ->Add(GGToZZ2L2L);
  if(log){
#ifndef DROP_SIGNAL
    ZH_htt  ->Add(ZH_hww );
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ZH_htt   ->Add(ZH_hww);
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(350)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(1000)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(350));
#endif

  data->SetNdivisions(505);
  data->SetMinimum(min);
  float maxZZ=ZZ->GetBinContent(ZZ->GetMaximumBin()); float maxdata=data->GetBinContent(data->GetMaximumBin());
  if (maxdata>maxZZ)
     data->SetMaximum(1.8*maxdata);
  else
     data->SetMaximum(1.8*maxZZ);
  data->Draw("e");

//  TH1F* errorBand = (TH1F*)ZZ ->Clone();
  TH1F* errorBand = (TH1F*)Zjets ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  errorBand  ->Scale(0.15);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  //if(log){
    ZZ  ->Draw("histsame");
    Zjets->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ZH_htt  ->Draw("histsame");
#endif
  //}
  //else{
//#ifndef DROP_SIGNAL
//    ggH  ->Draw("histsame");
//#endif
//    Ztt  ->Draw("histsame");
//    ttbar->Draw("histsame");
//    EWK  ->Draw("histsame");
//    Fakes->Draw("histsame");
//    $DRAW_ERROR
//  }
  data->Draw("esame");
  canv->RedrawAxis();

//  //CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);  
  CMSPrelim(dataset, "", 0.16, 0.835);  
  TPaveText* chan     = new TPaveText(0.20, 0.74+0.061, 0.32, 0.74+0.161, "NDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  if (directory=="eett_zh") 
    chan->AddText("#tau#tau");
  else
    chan->AddText("#mu#mu#tau#tau");
  chan->Draw();
//
//  TPaveText* cat      = new TPaveText(0.20, 0.68+0.061, 0.32, 0.68+0.161, "NDC");
//  cat->SetBorderSize(   0 );
//  cat->SetFillStyle(    0 );
//  cat->SetTextAlign(   12 );
//  cat->SetTextSize ( 0.05 );
//  cat->SetTextColor(    1 );
//  cat->SetTextFont (   62 );
//  cat->AddText(category_extra);
//  cat->Draw();
//
//#ifdef MSSM
//  TPaveText* massA      = new TPaveText(0.75, 0.48+0.061, 0.85, 0.48+0.161, "NDC");
//  massA->SetBorderSize(   0 );
//  massA->SetFillStyle(    0 );
//  massA->SetTextAlign(   12 );
//  massA->SetTextSize ( 0.03 );
//  massA->SetTextColor(    1 );
//  massA->SetTextFont (   62 );
//  massA->AddText("m_{A}=$MAGeV");
//  massA->Draw();
//
//  TPaveText* tanb      = new TPaveText(0.75, 0.44+0.061, 0.85, 0.44+0.161, "NDC");
//  tanb->SetBorderSize(   0 );
//  tanb->SetFillStyle(    0 );
//  tanb->SetTextAlign(   12 );
//  tanb->SetTextSize ( 0.03 );
//  tanb->SetTextColor(    1 );
//  tanb->SetTextFont (   62 );
//  tanb->AddText("tan#beta=$TANB");
//  tanb->Draw();
// 
//  TPaveText* scen      = new TPaveText(0.75, 0.40+0.061, 0.85, 0.40+0.161, "NDC");
//  scen->SetBorderSize(   0 );
//  scen->SetFillStyle(    0 );
//  scen->SetTextAlign(   12 );
//  scen->SetTextSize ( 0.03 );
//  scen->SetTextColor(    1 );
//  scen->SetTextFont (   62 );
//  scen->AddText("mhmax");
//  scen->Draw();
//#endif
//
//#ifdef MSSM  
//  TLegend* leg = new TLegend(0.45, 0.65, 0.95, 0.90);
//  SetLegendStyle(leg);
//  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
//#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
//#ifndef DROP_SIGNAL
//  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ZH_htt  , TString::Format("%.0f#timesZH(125 GeV)#rightarrowll#tau#tau", SIGNAL_SCALE) , "L" );
//  }
//  else{
//    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
//  }
//#endif
//#endif
  leg->AddEntry(data , "observed"                       , "LP");
  leg->AddEntry(ZZ  , "ZZ"           , "F" );
  leg->AddEntry(Zjets, "Reducible"                       , "F" );
//  leg->AddEntry(EWK  , "electroweak"                    , "F" );
//  leg->AddEntry(Fakes, "QCD"                            , "F" );
  $ERROR_LEGEND
  leg->Draw();
//
////#ifdef MSSM
////  TPaveText* mssm  = new TPaveText(0.69, 0.85, 0.90, 0.90, "NDC");
////  mssm->SetBorderSize(   0 );
////  mssm->SetFillStyle(    0 );
////  mssm->SetTextAlign(   12 );
////  mssm->SetTextSize ( 0.03 );
////  mssm->SetTextColor(    1 );
////  mssm->SetTextFont (   62 );
////  mssm->AddText("(m_{A}=250, tan#beta=5)");
////  mssm->Draw();
////#else
////  TPaveText* mssm  = new TPaveText(0.83, 0.85, 0.95, 0.90, "NDC");
////  mssm->SetBorderSize(   0 );
////  mssm->SetFillStyle(    0 );
////  mssm->SetTextAlign(   12 );
////  mssm->SetTextSize ( 0.03 );
////  mssm->SetTextColor(    1 );
////  mssm->SetTextFont (   62 );
////  mssm->AddText("m_{H}=125");
////  mssm->Draw();
////#endif
//
//  /*
//    Ratio Data over MC
//  */
//  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
//  canv0->SetGridx();
//  canv0->SetGridy();
//  canv0->cd();
//
//  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
//  TH1F* rat1 = (TH1F*)data->Clone("rat"); 
//  rat1->Divide(Ztt);
//  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
//    if(rat1->GetBinContent(ibin+1)>0){
//      // catch cases of 0 bins, which would lead to 0-alpha*0-1
//      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
//    }
//    zero->SetBinContent(ibin+1, 0.);
//  }
//  rat1->SetLineColor(kBlack);
//  rat1->SetFillColor(kGray );
//  rat1->SetMaximum(+0.5);
//  rat1->SetMinimum(-0.5);
//  rat1->GetYaxis()->CenterTitle();
//  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
//  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
//  rat1->Draw();
//  zero->SetLineColor(kBlack);
//  zero->Draw("same");
//  canv0->RedrawAxis();
//
//  /*
//    Ratio After fit over Prefit
//  */
//  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
//  canv1->SetGridx();
//  canv1->SetGridy();
//  canv1->cd();
//
//  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
//  rat2->Divide(ref);
//  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
//    if(rat2->GetBinContent(ibin+1)>0){
//      // catch cases of 0 bins, which would lead to 0-alpha*0-1
//      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
//    }
//  }
//  rat2->SetLineColor(kRed+ 3);
//  rat2->SetFillColor(kRed-10);
//  rat2->SetMaximum(+0.3);
//  rat2->SetMinimum(-0.3);
//  rat2->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
//  rat2->GetYaxis()->CenterTitle();
//  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
//  rat2->GetXaxis()->SetRange(0, 28);
//  rat2->Draw();
//  zero->SetLineColor(kBlack);
//  zero->Draw("same");
//  canv1->RedrawAxis();
//
//  /*
//    Relative shift per sample
//  */
//  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
//  canv2->SetGridx();
//  canv2->SetGridy();
//  canv2->cd();
//
//  InitHist  (scales[0], "", "", kMagenta-10, 1001);
//  InitHist  (scales[1], "", "", kRed    + 2, 1001);
//  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
//  InitHist  (scales[3], "", "", kOrange - 4, 1001);
//#ifndef DROP_SIGNAL
//  InitSignal(scales[4]);
//  InitSignal(scales[5]);
//  InitSignal(scales[6]);
//#endif
//  scales[0]->Draw();
//  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
//  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
//  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
//  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
//#ifdef MSSM
//  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{NONE}" );
//#else
//  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH}"  );
//  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{VH}"   );
//#endif
//  scales[0]->SetMaximum(+1.0);
//  scales[0]->SetMinimum(-1.0);
//  scales[0]->GetYaxis()->CenterTitle();
//  scales[0]->GetYaxis()->SetTitle("#bf{Fit/Prefit-1}");
//  scales[1]->Draw("same");
//  scales[2]->Draw("same");
//  scales[3]->Draw("same");
//#ifndef DROP_SIGNAL
//  scales[4]->Draw("same");
//  scales[5]->Draw("same");
//  scales[6]->Draw("same");
//#endif
//  zero->Draw("same");
//  canv2->RedrawAxis();
//
//  /*
//    prepare output
//  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.png"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.pdf"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
  canv ->Print(TString::Format("%s_%sscaled_%s_%s.eps"       , directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv0->Print(TString::Format("%s_datamc_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv1->Print(TString::Format("%s_prefit_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.png", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "")); 
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.pdf", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
//  canv2->Print(TString::Format("%s_sample_%sscaled_%s_%s.eps", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""));
  TFile* output = new TFile(TString::Format("%s_%sscaled_%s_%s.root", directory, scaled ? "re" : "un", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : ""), "update");
  output->cd(); 
  data ->Write("data_obs");
  ZZ->Write("ZZ"   );
  Zjets  ->Write("Zjets"     );
  ZH_htt->Write("ZH_htt"   );
  ZH_hww  ->Write("ZH_hww"     );
//#ifdef MSSM
//  ggH  ->Write("ggH"     );
//  bbH  ->Write("bbH"     );
//#else
//#ifndef DROP_SIGNAL
//  ggH  ->Write("ggH"     );
//  qqH  ->Write("qqH"     );
//  VH   ->Write("VH"      );
//#endif
//#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
}
Ejemplo n.º 28
0
void xsecSummary()
{   
  //--------------------------------------------------------------------------------------------------------------
  // input parameter
  const Double_t xsec_wp = 11356;   const Double_t xsec_wp_stat = 9;   const Double_t xsec_wp_sys = 197;   const Double_t xsec_wp_lumi = 307;
  const Double_t xsec_wm = 8284;    const Double_t xsec_wm_stat = 8;   const Double_t xsec_wm_sys = 124;   const Double_t xsec_wm_lumi = 224;
  const Double_t xsec_w  = 19708;   const Double_t xsec_w_stat  = 11;   const Double_t xsec_w_sys  = 265;   const Double_t xsec_w_lumi  = 532;
  const Double_t xsec_z  = 1904;    const Double_t xsec_z_stat  = 1;    const Double_t xsec_z_sys  = 30;    const Double_t xsec_z_lumi  = 51;
  const Double_t xsec_wr = 1.372;   const Double_t xsec_wr_stat = 0.002;   const Double_t xsec_wr_sys = 0.022; 
  const Double_t xsec_wpr= 5.966;   const Double_t xsec_wpr_stat= 0.006;   const Double_t xsec_wpr_sys= 0.100; 
  const Double_t xsec_wmr= 4.351;   const Double_t xsec_wmr_stat= 0.005;   const Double_t xsec_wmr_sys= 0.069; 
  const Double_t xsec_wz = 10.330;  const Double_t xsec_wz_stat = 0.009;   const Double_t xsec_wz_sys = 0.147; 

  const Double_t theo_wp = 11328.8;   const Double_t theo_wp_unc = (268.75+323.94)/2.;
  const Double_t theo_wm = 8369.09;   const Double_t theo_wm_unc = (213.11+244.29)/2.;
  const Double_t theo_w  = 19697.6;   const Double_t theo_w_unc  = (473.95+563.48)/2.;
  const Double_t theo_z  = 1867.66;   const Double_t theo_z_unc  = (43.49+47.36)/2.;
  const Double_t theo_wr = 1.35367;   const Double_t theo_wr_unc = (0.0123+0.01054)/2.;
  const Double_t theo_wpr= 6.06494;   const Double_t theo_wpr_unc= (0.04716+0.04361)/2.;
  const Double_t theo_wmr= 4.48044;   const Double_t theo_wmr_unc= (0.01779+0.02685)/2.;
  const Double_t theo_wz = 10.54538;  const Double_t theo_wz_unc = (0.06495+0.07046)/2.;

  const Double_t ratio_wp     = xsec_wp/theo_wp;   const Double_t ratio_wp_the = theo_wp_unc*xsec_wp/(theo_wp*theo_wp); 
  const Double_t ratio_wp_exp = sqrt(xsec_wp_stat*xsec_wp_stat+xsec_wp_sys*xsec_wp_sys)/(theo_wp);

  const Double_t ratio_wm     = xsec_wm/theo_wm;   const Double_t ratio_wm_the = theo_wm_unc*xsec_wm/(theo_wm*theo_wm); 
  const Double_t ratio_wm_exp = sqrt(xsec_wm_stat*xsec_wm_stat+xsec_wm_sys*xsec_wm_sys)/(theo_wm);

  const Double_t ratio_w      = xsec_w/theo_w;     const Double_t ratio_w_the  = theo_w_unc*xsec_w/(theo_w*theo_w); 
  const Double_t ratio_w_exp  = sqrt(xsec_w_stat*xsec_w_stat+xsec_w_sys*xsec_w_sys)/(theo_w);

  const Double_t ratio_z      = xsec_z/theo_z;     const Double_t ratio_z_the  = theo_z_unc*xsec_z/(theo_z*theo_z); 
  const Double_t ratio_z_exp  = sqrt(xsec_z_stat*xsec_z_stat+xsec_z_sys*xsec_z_sys)/(theo_z);

  const Double_t ratio_wr     = xsec_wr/theo_wr;   const Double_t ratio_wr_the = theo_wr_unc*xsec_wr/(theo_wr*theo_wr); 
  const Double_t ratio_wr_exp = sqrt(xsec_wr_stat*xsec_wr_stat+xsec_wr_sys*xsec_wr_sys)/(theo_wr);

  const Double_t ratio_wpr    = xsec_wpr/theo_wpr; const Double_t ratio_wpr_the= theo_wpr_unc*xsec_wpr/(theo_wpr*theo_wpr); 
  const Double_t ratio_wpr_exp= sqrt(xsec_wpr_stat*xsec_wpr_stat+xsec_wpr_sys*xsec_wpr_sys)/(theo_wpr);

  const Double_t ratio_wmr    = xsec_wmr/theo_wmr;   const Double_t ratio_wmr_the = theo_wmr_unc*xsec_wmr/(theo_wmr*theo_wmr); 
  const Double_t ratio_wmr_exp= sqrt(xsec_wmr_stat*xsec_wmr_stat+xsec_wmr_sys*xsec_wmr_sys)/(theo_wmr);

  const Double_t ratio_wz     = xsec_wz/theo_wz;   const Double_t ratio_wz_the = theo_wz_unc*xsec_wz/(theo_wz*theo_wz); 
  const Double_t ratio_wz_exp = sqrt(xsec_wz_stat*xsec_wz_stat+xsec_wz_sys*xsec_wz_sys)/(theo_wz);

  Double_t test = sqrt(xsec_wp_stat*xsec_wp_stat+xsec_wp_sys*xsec_wp_sys)/(xsec_wp);

  //==============================================================================================================  
  
  //--------------------------------------------------------------------------------------------------------------
  // plotting parameter
  Double_t yshift, ydrift; // used for point and error bar
  yshift = 3.75;
  ydrift = -0.245;

  Double_t td, tp, tw; // used for text 
  td = 0.025;
  tp = 0.708;
  tw = 0.035;

  Double_t range_max, range_min;
  //range_min = 0.82;
  //range_max = 1.27;
  range_min = 0.82;
  range_max = 1.25;

  Int_t expColor, theColor;  // colors used
  Int_t prodColor, decayColor, cmbColor;  // colors used
  expColor  = kBlue;
  theColor  = kGreen+2;
  prodColor = kBlue+2;
  decayColor= kRed+2;
  cmbColor  = kBlack;
  //==============================================================================================================  

  //--------------------------------------------------------------------------------------------------------------
  // make plots
  TCanvas *c = MakeCanvas("c","c",800,600);
  c->SetTickx(1);
  c->SetTicky(0);
  c->SetFrameFillStyle(0);
  c->SetFrameLineWidth(2);
  c->SetFrameBorderMode(0);  
  c->SetLeftMargin(0.07);
  
  gStyle->SetEndErrorSize(8);

  Double_t xval, errl, errh, yval;
  xval = ratio_wp;
  yval = yshift+0*ydrift;
  errl = ratio_wp_exp;
  errh = sqrt(ratio_wp_exp*ratio_wp_exp+ratio_wp_the*ratio_wp_the);
  TGraphAsymmErrors grWP(1,&xval,&yval,&errl,&errl,0,0);
 
  grWP.SetTitle("");
  grWP.GetXaxis()->SetTitle("");
  grWP.GetXaxis()->SetTitleSize(0.05);
  grWP.GetYaxis()->SetTitle("");
  grWP.GetYaxis()->SetRangeUser(0,5);
  grWP.GetXaxis()->SetLimits(range_min,range_max);
  grWP.GetXaxis()->SetNdivisions(506);
  grWP.GetYaxis()->SetNdivisions(0);
  grWP.SetMarkerStyle(kFullCircle);
  grWP.SetMarkerSize(1);
  grWP.SetLineWidth(2);
  grWP.SetMarkerColor(kBlack);
  grWP.SetLineColor(expColor);
  grWP.Draw("AP");

  // lumi uncertainty band
  TBox lumi_box(0.973,yshift+7.*ydrift,1.027,3.98);
  //TBox lumi_box(0.974,yshift+7.*ydrift,1.026,3.98);
  lumi_box.SetLineColor(796);
  lumi_box.SetFillColor(796);
  lumi_box.Draw();
  c->RedrawAxis();

  TLine theory_line(1,0.02,1,3.98);
  theory_line.SetLineColor(kRed);
  theory_line.SetLineStyle(1);
  theory_line.SetLineWidth(3);
  theory_line.Draw();

  TGraphAsymmErrors grWP2(1,&xval,&yval,&errh,&errh,0,0);
  grWP2.SetMarkerStyle(kFullCircle);
  grWP2.SetMarkerSize(1);
  grWP2.SetLineWidth(2);
  grWP2.SetMarkerColor(kBlack);
  grWP2.SetLineColor(theColor);
  grWP2.Draw("EPSAME");
  grWP.Draw("EPSAME");
 
  xval = ratio_wm;
  yval = yshift+2*ydrift;
  errl = ratio_wm_exp;
  errh = sqrt(ratio_wm_exp*ratio_wm_exp+ratio_wm_the*ratio_wm_the);
  TGraphAsymmErrors grWM(1,&xval,&yval,&errl,&errl,0,0);
  grWM.SetMarkerStyle(kFullCircle);
  grWM.SetMarkerSize(1);
  grWM.SetLineWidth(2);
  grWM.SetMarkerColor(kBlack);
  grWM.SetLineColor(expColor);
  TGraphAsymmErrors grWM2(1,&xval,&yval,&errh,&errh,0,0);
  grWM2.SetMarkerStyle(kFullCircle);
  grWM2.SetMarkerSize(1);
  grWM2.SetLineWidth(2);
  grWM2.SetMarkerColor(kBlack);
  grWM2.SetLineColor(theColor);
  grWM2.Draw("EPSAME");
  grWM.Draw("EPSAME");

  xval = ratio_w;
  yval = yshift+4*ydrift;
  errl = ratio_w_exp;
  errh = sqrt(ratio_w_exp*ratio_w_exp+ratio_w_the*ratio_w_the);
  TGraphAsymmErrors grW(1,&xval,&yval,&errl,&errl,0,0);
  grW.SetMarkerStyle(kFullCircle);
  grW.SetMarkerSize(1);
  grW.SetLineWidth(2);
  grW.SetMarkerColor(kBlack);
  grW.SetLineColor(expColor);
  TGraphAsymmErrors grW2(1,&xval,&yval,&errh,&errh,0,0);
  grW2.SetMarkerStyle(kFullCircle);
  grW2.SetMarkerSize(1);
  grW2.SetLineWidth(2);
  grW2.SetMarkerColor(kBlack);
  grW2.SetLineColor(theColor);
  grW2.Draw("EPSAME");
  grW.Draw("EPSAME");

  xval = ratio_z;
  yval = yshift+6*ydrift;
  errl = ratio_z_exp;
  errh = sqrt(ratio_z_exp*ratio_z_exp+ratio_z_the*ratio_z_the);
  TGraphAsymmErrors grZ(1,&xval,&yval,&errl,&errl,0,0);
  grZ.SetMarkerSize(1);
  grZ.SetLineWidth(2);
  grZ.SetMarkerColor(kBlack);
  grZ.SetLineColor(expColor);
  TGraphAsymmErrors grZ2(1,&xval,&yval,&errh,&errh,0,0);
  grZ2.SetMarkerStyle(kFullCircle);
  grZ2.SetMarkerSize(1);
  grZ2.SetLineWidth(2);
  grZ2.SetMarkerColor(kBlack);
  grZ2.SetLineColor(theColor);
  grZ2.Draw("EPSAME");
  grZ.Draw("EPSAME");

  xval = ratio_wr;
  yval = yshift+8*ydrift;
  errl = ratio_wr_exp;
  errh = sqrt(ratio_wr_exp*ratio_wr_exp+ratio_wr_the*ratio_wr_the);
  TGraphAsymmErrors grWR(1,&xval,&yval,&errl,&errl,0,0);
  grWR.SetMarkerStyle(kFullCircle);
  grWR.SetMarkerSize(1);
  grWR.SetLineWidth(2);
  grWR.SetMarkerColor(kBlack);
  grWR.SetLineColor(expColor);
  TGraphAsymmErrors grWR2(1,&xval,&yval,&errh,&errh,0,0);
  grWR2.SetMarkerStyle(kFullCircle);
  grWR2.SetMarkerSize(1);
  grWR2.SetLineWidth(2);
  grWR2.SetMarkerColor(kBlack);
  grWR2.SetLineColor(theColor);
  grWR2.Draw("EPSAME");
  grWR.Draw("EPSAME");

  xval = ratio_wpr;
  yval = yshift+10*ydrift;
  errl = ratio_wpr_exp;
  errh = sqrt(ratio_wpr_exp*ratio_wpr_exp+ratio_wpr_the*ratio_wpr_the);
  TGraphAsymmErrors grWPR(1,&xval,&yval,&errl,&errl,0,0);
  grWPR.SetMarkerStyle(kFullCircle);
  grWPR.SetMarkerSize(1);
  grWPR.SetLineWidth(2);
  grWPR.SetMarkerColor(kBlack);
  grWPR.SetLineColor(expColor);
  TGraphAsymmErrors grWPR2(1,&xval,&yval,&errh,&errh,0,0);
  grWPR2.SetMarkerStyle(kFullCircle);
  grWPR2.SetMarkerSize(1);
  grWPR2.SetLineWidth(2);
  grWPR2.SetMarkerColor(kBlack);
  grWPR2.SetLineColor(theColor);
  grWPR2.Draw("EPSAME");
  grWPR.Draw("EPSAME");

  xval = ratio_wmr;
  yval = yshift+12*ydrift;
  errl = ratio_wmr_exp;
  errh = sqrt(ratio_wmr_exp*ratio_wmr_exp+ratio_wmr_the*ratio_wmr_the);
  TGraphAsymmErrors grWMR(1,&xval,&yval,&errl,&errl,0,0);
  grWMR.SetMarkerStyle(kFullCircle);
  grWMR.SetMarkerSize(1);
  grWMR.SetLineWidth(2);
  grWMR.SetMarkerColor(kBlack);
  grWMR.SetLineColor(expColor);
  TGraphAsymmErrors grWMR2(1,&xval,&yval,&errh,&errh,0,0);
  grWMR2.SetMarkerStyle(kFullCircle);
  grWMR2.SetMarkerSize(1);
  grWMR2.SetLineWidth(2);
  grWMR2.SetMarkerColor(kBlack);
  grWMR2.SetLineColor(theColor);
  grWMR2.Draw("EPSAME");
  grWMR.Draw("EPSAME");

  xval = ratio_wz;
  yval = yshift+14*ydrift;
  errl = ratio_wz_exp;
  errh = sqrt(ratio_wz_exp*ratio_wz_exp+ratio_wz_the*ratio_wz_the);
  TGraphAsymmErrors grWZ(1,&xval,&yval,&errl,&errl,0,0);
  grWZ.SetMarkerStyle(kFullCircle);
  grWZ.SetMarkerSize(1);
  grWZ.SetLineWidth(2);
  grWZ.SetMarkerColor(kBlack);
  grWZ.SetLineColor(expColor);
  TGraphAsymmErrors grWZ2(1,&xval,&yval,&errh,&errh,0,0);
  grWZ2.SetMarkerStyle(kFullCircle);
  grWZ2.SetMarkerSize(1);
  grWZ2.SetLineWidth(2);
  grWZ2.SetMarkerColor(kBlack);
  grWZ2.SetLineColor(theColor);
  grWZ2.Draw("EPSAME");
  grWZ.Draw("EPSAME");


  // legend
  xval = range_min+(0.06*(range_max-range_min));
  yval = 4.6;
  errl = 0.015*(range_max-range_min);
  errh = 0.03*(range_max-range_min);
  TGraphAsymmErrors grLeg(1,&xval,&yval,&errl,&errl,0,0);
  grLeg.SetMarkerStyle(kFullCircle);
  grLeg.SetMarkerSize(1);
  grLeg.SetLineWidth(2);
  grLeg.SetMarkerColor(kBlack);
  grLeg.SetLineColor(expColor);
  TGraphAsymmErrors grLeg2(1,&xval,&yval,&errh,&errh,0,0);
  grLeg2.SetMarkerStyle(kFullCircle);
  grLeg2.SetMarkerSize(1);
  grLeg2.SetLineWidth(2);
  grLeg2.SetMarkerColor(kBlack);
  grLeg2.SetLineColor(theColor);
  grLeg2.Draw("EPSAME");
  grLeg.Draw("EPSAME");

  TPaveText tb4(0.14,0.84,0.6,0.875,"NDC");
  tb4.SetFillStyle(0);
  tb4.SetBorderSize(0);
  tb4.SetTextAlign(12);
  tb4.AddText("Observation, uncertainty (exp., exp. #oplus theory)");
  tb4.Draw(); 

  TPaveText tb6(0.14,0.795,0.6,0.83,"NDC");
  tb6.SetFillStyle(0);
  tb6.SetBorderSize(0);
  tb6.SetTextAlign(12);
  tb6.AddText("Uncertainty (lumi)");
  tb6.Draw(); 

  TBox exp_box_leg2(range_min+(0.04*(range_max-range_min)),4.18,range_min+(0.08*(range_max-range_min)),4.38);
  exp_box_leg2.SetLineColor(796);
  exp_box_leg2.SetFillColor(796);
  exp_box_leg2.Draw();
  
  // split lines

  TLine split_line0(range_min,yshift+1*ydrift,range_max,yshift+1*ydrift);
  split_line0.SetLineColor(kBlack);
  split_line0.SetLineStyle(2);
  split_line0.SetLineWidth(1);
  split_line0.Draw();

  TLine split_line1(range_min,yshift+3*ydrift,range_max,yshift+3*ydrift);
  split_line1.SetLineColor(kBlack);
  split_line1.SetLineStyle(2);
  split_line1.SetLineWidth(1);
  split_line1.Draw();

  TLine split_line2(range_min,yshift+5*ydrift,range_max,yshift+5*ydrift);
  split_line2.SetLineColor(kBlack);
  split_line2.SetLineStyle(2);
  split_line2.SetLineWidth(1);
  split_line2.Draw();

  TLine split_line3(range_min,yshift+7*ydrift,range_max,yshift+7*ydrift);
  split_line3.SetLineColor(kBlack);
  split_line3.SetLineStyle(2);
  split_line3.SetLineWidth(1);
  split_line3.Draw();

  TLine split_line4(range_min,yshift+9*ydrift,range_max,yshift+9*ydrift);
  split_line4.SetLineColor(kBlack);
  split_line4.SetLineStyle(2);
  split_line4.SetLineWidth(1);
  split_line4.Draw();
  
  TLine split_line5(range_min,yshift+11*ydrift,range_max,yshift+11*ydrift);
  split_line5.SetLineColor(kBlack);
  split_line5.SetLineStyle(2);
  split_line5.SetLineWidth(1);
  split_line5.Draw();
  
  TLine split_line6(range_min,yshift+13*ydrift,range_max,yshift+13*ydrift);
  split_line6.SetLineColor(kBlack);
  split_line6.SetLineStyle(2);
  split_line6.SetLineWidth(1);
  split_line6.Draw();
  
  TLine split_line7(range_min,yshift+(-1)*ydrift,range_max,yshift+(-1)*ydrift);
  split_line7.SetLineColor(kBlack);
  split_line7.SetLineStyle(2);
  split_line7.SetLineWidth(1);
  split_line7.Draw();



  TPaveText tb1(0.08,0.93,0.34,0.99,"NDC");
  tb1.SetFillStyle(0);
  tb1.SetBorderSize(0);
  tb1.SetTextAlign(12);
  tb1.AddText("#bf{CMS}");
  tb1.Draw();

  TPaveText tb2(0.75,0.93,0.95,0.99,"NDC");
  tb2.SetFillStyle(0);
  tb2.SetBorderSize(0);
  tb2.SetTextAlign(12);
  tb2.AddText("2.3 fb^{-1} (13 TeV)");
  tb2.Draw(); 

  TPaveText tb3(0.6,0.83,0.95,0.88,"NDC");
  tb3.SetFillStyle(0);
  tb3.SetBorderSize(0);
  tb3.SetTextAlign(12);
  tb3.AddText("Theory: FEWZ (NNLO), NNPDF3.0");
  tb3.Draw(); 

  TPaveText tb7(0.6,0.795,0.95,0.83,"NDC");
  tb7.SetFillStyle(0);
  tb7.SetBorderSize(0);
  tb7.SetTextAlign(12);
  tb7.AddText("Observation: NNPDF3.0");
  tb7.Draw(); 

  TPaveText textwp(0.10,tp-(0*td),0.50,tp+tw-(0*td),"NDC");
  textwp.SetFillStyle(0);
  textwp.SetBorderSize(0);
  textwp.SetTextAlign(12);
  textwp.AddText("#bf{W^{+}#rightarrowl^{+}#nu}");
  textwp.Draw(); 

  char buffer[200]; 
  Double_t tmp[4];
  Double_t tmp2[4];
  roundXsec(xsec_wp, xsec_wp_stat, xsec_wp_sys, xsec_wp_lumi, tmp);
  sprintf(buffer,"%.0f #pm %.0f_{stat} #pm %.0f_{syst}", tmp[0], tmp[1], tmp[2]);
  sprintf(buffer,"%s #pm %.0f_{lum} pb",buffer,tmp[3]);
  TPaveText resultwp(0.60,tp-(-0.5*td),1.00,tp+tw-(-0.5*td),"NDC");
  resultwp.SetFillStyle(0);
  resultwp.SetBorderSize(0);
  resultwp.SetTextAlign(12);
  resultwp.AddText(buffer);
  resultwp.Draw(); 

  roundXsec(theo_wp, theo_wp_unc, tmp2);
  sprintf(buffer,"%.0f #pm %.0f pb", tmp2[0], tmp2[1]);
  TPaveText theorywp(0.60,tp-(0.6*td),1.00,tp+tw-(0.6*td),"NDC");
  theorywp.SetFillStyle(0);
  theorywp.SetBorderSize(0);
  theorywp.SetTextAlign(12);
  theorywp.AddText(buffer);
  theorywp.Draw(); 

  TPaveText textwm(0.10,tp-(3*td),0.50,tp+tw-(3*td),"NDC");
  textwm.SetFillStyle(0);
  textwm.SetBorderSize(0);
  textwm.SetTextAlign(12);
  textwm.AddText("#bf{W^{-}#rightarrowl^{-}#nu}");
  textwm.Draw(); 

  roundXsec(xsec_wm, xsec_wm_stat, xsec_wm_sys,xsec_wm_lumi, tmp);
  sprintf(buffer,"%.0f #pm %.0f_{stat} #pm %.0f_{syst}", tmp[0], tmp[1], tmp[2]);
  sprintf(buffer,"%s #pm %.0f_{lum} pb",buffer,tmp[3]);
  TPaveText resultwm(0.60,tp-(2.5*td),1.00,tp+tw-(2.5*td),"NDC");
  resultwm.SetFillStyle(0);
  resultwm.SetBorderSize(0);
  resultwm.SetTextAlign(12);
  resultwm.AddText(buffer);
  resultwm.Draw(); 

  roundXsec(theo_wm, theo_wm_unc, tmp2);
  sprintf(buffer,"%.0f #pm %.0f pb", tmp2[0], tmp2[1]);
  TPaveText theorywm(0.60,tp-(3.6*td),1.00,tp+tw-(3.6*td),"NDC");
  theorywm.SetFillStyle(0);
  theorywm.SetBorderSize(0);
  theorywm.SetTextAlign(12);
  theorywm.AddText(buffer);
  theorywm.Draw(); 

  TPaveText textw(0.10,tp-(6*td),0.50,tp+tw-(6*td),"NDC");
  textw.SetFillStyle(0);
  textw.SetBorderSize(0);
  textw.SetTextAlign(12);
  textw.AddText("#bf{W#rightarrowl#nu}");
  textw.Draw(); 

  roundXsec(xsec_w, xsec_w_stat, xsec_w_sys, xsec_w_lumi, tmp);
  sprintf(buffer,"%.0f #pm %.0f_{stat} #pm %.0f_{syst}", tmp[0], tmp[1], tmp[2]);
  sprintf(buffer,"%s #pm %.0f_{lum} pb",buffer,tmp[3]);
  TPaveText resultw(0.60,tp-(5.5*td),1.00,tp+tw-(5.5*td),"NDC");
  resultw.SetFillStyle(0);
  resultw.SetBorderSize(0);
  resultw.SetTextAlign(12);
  resultw.AddText(buffer);
  resultw.Draw(); 

  roundXsec(theo_w, theo_w_unc, tmp2);
  sprintf(buffer,"%.0f #pm %.0f pb", tmp2[0], tmp2[1]);
  TPaveText theoryw(0.60,tp-(6.6*td),1.00,tp+tw-(6.6*td),"NDC");
  theoryw.SetFillStyle(0);
  theoryw.SetBorderSize(0);
  theoryw.SetTextAlign(12);
  theoryw.AddText(buffer);
  theoryw.Draw(); 

  TPaveText textz(0.10,tp-(9*td),0.50,tp+tw-(9*td),"NDC");
  textz.SetFillStyle(0);
  textz.SetBorderSize(0);
  textz.SetTextAlign(12);
  textz.AddText("#bf{Z#rightarrowl^{+}l^{-}}");
  textz.Draw(); 

  roundXsec(xsec_z, xsec_z_stat, xsec_z_sys,xsec_z_lumi, tmp);
  sprintf(buffer,"%.0f #pm %.0f_{stat} #pm %.0f_{syst}", tmp[0], tmp[1], tmp[2]);
  sprintf(buffer,"%s #pm %.0f_{lum} pb",buffer,tmp[3]);
  TPaveText resultz(0.60,tp-(8.5*td),1.00,tp+tw-(8.5*td),"NDC");
  resultz.SetFillStyle(0);
  resultz.SetBorderSize(0);
  resultz.SetTextAlign(12);
  resultz.AddText(buffer);
  resultz.Draw(); 

  roundXsec(theo_z, theo_z_unc, tmp2);
  sprintf(buffer,"%.0f #pm %.0f pb", tmp2[0], tmp2[1]);
  TPaveText theoryz(0.60,tp-(9.6*td),1.00,tp+tw-(9.6*td),"NDC");
  theoryz.SetFillStyle(0);
  theoryz.SetBorderSize(0);
  theoryz.SetTextAlign(12);
  theoryz.AddText(buffer);
  theoryz.Draw(); 

  TPaveText textwr(0.10,tp-(12*td),0.50,tp+tw-(12*td),"NDC");
  textwr.SetFillStyle(0);
  textwr.SetBorderSize(0);
  textwr.SetTextAlign(12);
  textwr.AddText("#bf{W^{+}#rightarrowl^{+}#nu / W^{-}#rightarrowl^{-}#nu}");
  textwr.Draw(); 

  sprintf(buffer,"%.3f #pm %.3f_{stat} #pm %.3f_{syst}", xsec_wr, xsec_wr_stat, xsec_wr_sys);
  TPaveText resultwr(0.60,tp-(11.5*td),1.00,tp+tw-(11.5*td),"NDC");
  resultwr.SetFillStyle(0);
  resultwr.SetBorderSize(0);
  resultwr.SetTextAlign(12);
  resultwr.AddText(buffer);
  resultwr.Draw(); 

  sprintf(buffer,"%.3f #pm %.3f", theo_wr, theo_wr_unc);
  TPaveText theorywr(0.60,tp-(12.6*td),1.00,tp+tw-(12.6*td),"NDC");
  theorywr.SetFillStyle(0);
  theorywr.SetBorderSize(0);
  theorywr.SetTextAlign(12);
  theorywr.AddText(buffer);
  theorywr.Draw(); 

  TPaveText textwpr(0.10,tp-(15*td),0.50,tp+tw-(15*td),"NDC");
  textwpr.SetFillStyle(0);
  textwpr.SetBorderSize(0);
  textwpr.SetTextAlign(12);
  textwpr.AddText("#bf{W^{+}#rightarrowl^{+}#nu / Z#rightarrowl^{+}l^{-}}");
  textwpr.Draw(); 

  sprintf(buffer,"%.2f #pm %.2f_{stat} #pm %.2f_{syst}", xsec_wpr, xsec_wpr_stat, xsec_wpr_sys);
  TPaveText resultwpr(0.60,tp-(14.5*td),1.00,tp+tw-(14.5*td),"NDC");
  resultwpr.SetFillStyle(0);
  resultwpr.SetBorderSize(0);
  resultwpr.SetTextAlign(12);
  resultwpr.AddText(buffer);
  resultwpr.Draw(); 

  sprintf(buffer,"%.2f #pm %.2f", theo_wpr, theo_wpr_unc);
  TPaveText theorywpr(0.60,tp-(15.6*td),1.00,tp+tw-(15.6*td),"NDC");
  theorywpr.SetFillStyle(0);
  theorywpr.SetBorderSize(0);
  theorywpr.SetTextAlign(12);
  theorywpr.AddText(buffer);
  theorywpr.Draw(); 

  TPaveText textwmr(0.10,tp-(18*td),0.50,tp+tw-(18*td),"NDC");
  textwmr.SetFillStyle(0);
  textwmr.SetBorderSize(0);
  textwmr.SetTextAlign(12);
  textwmr.AddText("#bf{W^{-}#rightarrowl^{-}#nu / Z#rightarrowl^{+}l^{-}}");
  textwmr.Draw(); 

  sprintf(buffer,"%.2f #pm %.2f_{stat} #pm %.2f_{syst}", xsec_wmr, xsec_wmr_stat, xsec_wmr_sys);
  TPaveText resultwmr(0.60,tp-(17.5*td),1.00,tp+tw-(17.5*td),"NDC");
  resultwmr.SetFillStyle(0);
  resultwmr.SetBorderSize(0);
  resultwmr.SetTextAlign(12);
  resultwmr.AddText(buffer);
  resultwmr.Draw(); 

  sprintf(buffer,"%.2f #pm %.2f", theo_wmr, theo_wmr_unc);
  TPaveText theorywmr(0.60,tp-(18.6*td),1.00,tp+tw-(18.6*td),"NDC");
  theorywmr.SetFillStyle(0);
  theorywmr.SetBorderSize(0);
  theorywmr.SetTextAlign(12);
  theorywmr.AddText(buffer);
  theorywmr.Draw(); 

  TPaveText textwz(0.10,tp-(21*td),0.50,tp+tw-(21*td),"NDC");
  textwz.SetFillStyle(0);
  textwz.SetBorderSize(0);
  textwz.SetTextAlign(12);
  textwz.AddText("#bf{W#rightarrowl#nu / Z#rightarrowl^{+}l^{-}}");
  textwz.Draw(); 

  sprintf(buffer,"%.2f #pm %.2f_{stat} #pm %.2f_{syst}", xsec_wz, xsec_wz_stat, xsec_wz_sys);
  TPaveText resultwz(0.60,tp-(20.5*td),1.00,tp+tw-(20.5*td),"NDC");
  resultwz.SetFillStyle(0);
  resultwz.SetBorderSize(0);
  resultwz.SetTextAlign(12);
  resultwz.AddText(buffer);
  resultwz.Draw(); 

  sprintf(buffer,"%.2f #pm %.2f", theo_wz, theo_wz_unc);
  TPaveText theorywz(0.60,tp-(21.6*td),1.00,tp+tw-(21.6*td),"NDC");
  theorywz.SetFillStyle(0);
  theorywz.SetBorderSize(0);
  theorywz.SetTextAlign(12);
  theorywz.AddText(buffer);
  theorywz.Draw(); 

  TPaveText tb5(0.28,0.02,0.98,0.12,"NDC");
  tb5.SetFillStyle(0);
  tb5.SetBorderSize(0);
  tb5.SetTextAlign(12);
  tb5.AddText("ratio (exp./th.) of total cross sections and ratios");
  tb5.Draw();

  c->SaveAs("xsecSummary13TeV.png");
  c->SaveAs("xsecSummary13TeV.pdf");
}
Ejemplo n.º 29
0
void plotZmmStatCorrelations(const TString  outputDir,   // output directory
             const Double_t lumi         // integrated luminosity (/fb)
) {
  gBenchmark->Start("plotZmmStatCorrelations");
  gStyle->SetTitleOffset(0.75,"Y");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  //
  // input ntuple file names
  //
vector<TFile*> file;
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputZPt.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputPhiStar.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputZRap.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputLep1Pt.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputLep2Pt.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputLep1Eta.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputLep2Eta.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputLepNegPt.root", "OPEN"));
  file.push_back(new TFile("../Unfolding/Zmm/UnfoldingOutputLepPosPt.root", "OPEN"));

  
  // plot output file format
  const TString format("png");

   
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  
   
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  

  //
  // Set up output file
  //
  TString outfilename = outputDir + TString("/") + TString("Zmm_StatCorrelations.root");
  TFile *outFile = new TFile(outfilename,"RECREATE");

  
  // histograms

  TH2D *ZPT_STATCORR_MATRIX=(TH2D*)(file[0]->Get("hCorr_Bayes"));
  TH2D *PHISTAR_STATCORR_MATRIX=(TH2D*)(file[1]->Get("hCorr_Bayes"));
  TH2D *ZRAP_STATCORR_MATRIX=(TH2D*)(file[2]->Get("hCorr_Bayes"));
  TH2D *LEP1PT_STATCORR_MATRIX=(TH2D*)(file[3]->Get("hCorr_Bayes"));
  TH2D *LEP2PT_STATCORR_MATRIX=(TH2D*)(file[4]->Get("hCorr_Bayes"));
  TH2D *LEP1ETA_STATCORR_MATRIX=(TH2D*)(file[5]->Get("hCorr_Bayes"));
  TH2D *LEP2ETA_STATCORR_MATRIX=(TH2D*)(file[6]->Get("hCorr_Bayes"));
  TH2D *LEPNEGPT_STATCORR_MATRIX=(TH2D*)(file[7]->Get("hCorr_Bayes"));
  TH2D *LEPPOSPT_STATCORR_MATRIX=(TH2D*)(file[8]->Get("hCorr_Bayes"));
 


  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  

  char xlabel[100];     // string buffer for x-axis label
  char ylabel[100];     // string buffer for y-axis label
  
  // label for lumi
  char lumitext[100];
  sprintf(lumitext,"%.1f fb^{-1}  (13 TeV)",lumi/1000);  
  
  TCanvas *c = MakeCanvas("c","c",800,800);
  c->cd();
  c->SetTopMargin(0.1);
  c->SetBottomMargin(0.15);
  c->SetLeftMargin(0.15);  
  c->SetRightMargin(0.15);  
  c->SetTickx(1);
  c->SetTicky(1);  
  TGaxis::SetMaxDigits(3);

  gStyle->SetTitleOffset(1.4,"Y");
  gStyle->SetPalette(1);
  gStyle->SetPaintTextFormat("4.2f");

  
  
  //
  // ZPt
  //   

  sprintf(ylabel,"p_{T}^{#mu^{+}#mu^{-}} [GeV]");
  sprintf(xlabel,"p_{T}^{#mu^{+}#mu^{-}} [GeV]");
  ZPT_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  ZPT_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  CPlot plotZmmPt("zmmPtStatCorrelations","",xlabel,ylabel);
  plotZmmPt.AddHist2D(ZPT_STATCORR_MATRIX,"COLZ");
  plotZmmPt.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmPt.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmPt.SetLogx();
  plotZmmPt.SetLogy();
  plotZmmPt.Draw(c,kTRUE,format);

  //
  // PhiStar
  //   

  sprintf(ylabel,"#phi_{#eta}*");
  sprintf(xlabel,"#phi_{#eta}*");
  PHISTAR_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  PHISTAR_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  CPlot plotZmmPhiStar("zmmPhiStarStatCorrelations","",xlabel,ylabel);
  plotZmmPhiStar.AddHist2D(PHISTAR_STATCORR_MATRIX,"COLZ");
  plotZmmPhiStar.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmPhiStar.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmPhiStar.SetLogx();
  plotZmmPhiStar.SetLogy();
  plotZmmPhiStar.Draw(c,kTRUE,format);

  //
  // ZRap
  //   

  sprintf(ylabel,"|y^{#mu^{+}#mu^{-}}|");
  sprintf(xlabel,"|y^{#mu^{+}#mu^{-}}|");
  ZRAP_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  ZRAP_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  CPlot plotZmmRap("zmmRapStatCorrelations","",xlabel,ylabel);
  plotZmmRap.AddHist2D(ZRAP_STATCORR_MATRIX,"COLZ");
  plotZmmRap.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmRap.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmRap.Draw(c,kTRUE,format);

  //
  // Lep1Pt
  //   

  sprintf(ylabel,"p_{T} (leading muon) [GeV]");
  sprintf(xlabel,"p_{T} (leading muon) [GeV]");
  LEP1PT_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  LEP1PT_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  CPlot plotZmmLep1Pt("zmmLep1PtStatCorrelations","",xlabel,ylabel);
  plotZmmLep1Pt.AddHist2D(LEP1PT_STATCORR_MATRIX,"COLZ");
  plotZmmLep1Pt.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmLep1Pt.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmLep1Pt.SetLogx();
  plotZmmLep1Pt.SetLogy();
  plotZmmLep1Pt.Draw(c,kTRUE,format);

  //
  // Lep2Pt
  //   

  sprintf(ylabel,"p_{T} (2nd leading muon) [GeV]");
  sprintf(xlabel,"p_{T} (2nd leading muon) [GeV]");
  LEP2PT_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  LEP2PT_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  CPlot plotZmmLep2Pt("zmmLep2PtStatCorrelations","",xlabel,ylabel);
  plotZmmLep2Pt.AddHist2D(LEP2PT_STATCORR_MATRIX,"COLZ");
  plotZmmLep2Pt.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmLep2Pt.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmLep2Pt.SetLogx();
  plotZmmLep2Pt.SetLogy();
  plotZmmLep2Pt.Draw(c,kTRUE,format);

  //
  // Lep1Eta
  //   

  sprintf(ylabel,"|#eta| (leading muon)");
  sprintf(xlabel,"|#eta| (leading muon)");
  LEP1ETA_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  LEP1ETA_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  CPlot plotZmmLep1Eta("zmmLep1EtaStatCorrelations","",xlabel,ylabel);
  plotZmmLep1Eta.AddHist2D(LEP1ETA_STATCORR_MATRIX,"COLZ");
  plotZmmLep1Eta.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmLep1Eta.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmLep1Eta.Draw(c,kTRUE,format);

  //
  // Lep2Eta
  //   

  sprintf(ylabel,"|#eta| (2nd leading muon)");
  sprintf(xlabel,"|#eta| (2nd leading muon)");
  LEP2ETA_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  LEP2ETA_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  CPlot plotZmmLep2Eta("zmmLep2EtaStatCorrelations","",xlabel,ylabel);
  plotZmmLep2Eta.AddHist2D(LEP2ETA_STATCORR_MATRIX,"COLZ");
  plotZmmLep2Eta.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmLep2Eta.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmLep2Eta.Draw(c,kTRUE,format);

  //
  // LepNegPt
  //   

  sprintf(ylabel,"p_{T}^{#mu^{-}} [GeV]");
  sprintf(xlabel,"p_{T}^{#mu^{-}} [GeV]");
  LEP1PT_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  LEP1PT_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  CPlot plotZmmLepNegPt("zmmLepNegPtStatCorrelations","",xlabel,ylabel);
  plotZmmLepNegPt.AddHist2D(LEP1PT_STATCORR_MATRIX,"COLZ");
  plotZmmLepNegPt.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmLepNegPt.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmLepNegPt.SetLogx();
  plotZmmLepNegPt.SetLogy();
  plotZmmLepNegPt.Draw(c,kTRUE,format);

  //
  // LepPosPt
  //   

  sprintf(ylabel,"p_{T}^{#mu^{+}} [GeV]");
  sprintf(xlabel,"p_{T}^{#mu^{+}} [GeV]");
  LEP1PT_STATCORR_MATRIX->GetZaxis()->SetRangeUser(-1,1);
  LEP1PT_STATCORR_MATRIX->GetYaxis()->SetTitleOffset(1.25);
  CPlot plotZmmLepPosPt("zmmLepPosPtStatCorrelations","",xlabel,ylabel);
  plotZmmLepPosPt.AddHist2D(LEP1PT_STATCORR_MATRIX,"COLZ");
  plotZmmLepPosPt.AddTextBox("#bf{CMS} #scale[0.75]{#it{Preliminary}}",0.15,0.90,0.4,0.95,0);
  plotZmmLepPosPt.AddTextBox("Bayes Correlation Matrix",0.53,0.90,0.86,0.95,0);
  plotZmmLepPosPt.SetLogx();
  plotZmmLepPosPt.SetLogy();
  plotZmmLepPosPt.Draw(c,kTRUE,format);

  
  
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  outFile->cd();
  outFile->Write();
  outFile->Close(); 


  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  cout << endl;
 
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     

  gBenchmark->Show("plotZmmStatCorrelations");
}
void 
HTT_MT_X(bool scaled=true, bool log=true, float min=0.1, float max=2000., const char* inputfile="root/$HISTFILE", const char* directory="muTau_$CATEGORY")
{
  // defining the common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "#sqrt{s} = 7 TeV, L = 4.9 fb^{-1}";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "#sqrt{s} = 8 TeV, L = 5.0 fb^{-1}";}

  // open example histogram file
  TFile* input = new TFile(inputfile);
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/QCD"   , directory)), "QCD"); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK1   = refill((TH1F*)input->Get(TString::Format("%s/W"     , directory)), "W"  ); InitHist(EWK1 , "", "", kRed    + 2, 1001);
#ifdef EXTRA_SAMPLES
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZJ"    , directory)), "ZJ" ); InitHist(EWK2 , "", "", kRed    + 2, 1001);
  TH1F* EWK3   = refill((TH1F*)input->Get(TString::Format("%s/ZL"    , directory)), "ZL" ); InitHist(EWK3 , "", "", kRed    + 2, 1001);
#else
  TH1F* EWK2   = refill((TH1F*)input->Get(TString::Format("%s/ZLL"   , directory)), "ZLL"); InitHist(EWK2 , "", "", kRed    + 2, 1001);
#endif
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/VV"    , directory)), "VV" ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/TT"    , directory)), "TT" ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/ZTT"   , directory)), "ZTT"); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH120", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(5);
  TH1F* bbH    = refill((TH1F*)input->Get(TString::Format("%s/bbH120", directory)), "bbH"); InitSignal(bbH); bbH ->Scale(5);
#else
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125", directory)), "ggH"); InitSignal(ggH); ggH ->Scale(5);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125", directory)), "qqH"); InitSignal(qqH); qqH ->Scale(5);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125" , directory)), "VH" ); InitSignal(VH ); VH  ->Scale(5);
#endif
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK1 );
  ref->Add(EWK2 );
#ifdef EXTRA_SAMPLES
  ref->Add(EWK3 );
#endif
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );

  double unscaled[7];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[1]+= EWK1 ->Integral();
  unscaled[1]+= EWK2 ->Integral();
#ifdef EXTRA_SAMPLES
  unscaled[1]+= EWK3 ->Integral();
#endif
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = qqH  ->Integral();
  unscaled[6] = VH   ->Integral();
#endif

  if(scaled){
    rescale(Fakes, 7); 
    rescale(EWK1 , 3); 
    rescale(EWK2 , 4); 
#ifdef EXTRA_SAMPLES
    rescale(EWK3 , 5);
#endif 
    rescale(EWK  , 6); 
    rescale(ttbar, 2); 
    rescale(Ztt  , 1);
#ifdef MSSM
    rescale(ggH  , 8); 
    rescale(bbH  , 9);  
#else
    rescale(ggH  , 8); 
    rescale(qqH  , 9);  
    rescale(VH   ,10);  
#endif
  }

  TH1F* scales[7];
  scales[0] = new TH1F("scales-Fakes", "", 7, 0, 7);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", 7, 0, 7);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? ((EWK  ->Integral()
					       +EWK1 ->Integral()
					       +EWK2 ->Integral()
#ifdef EXTRA_SAMPLES
					       +EWK3 ->Integral()
#endif
						)/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", 7, 0, 7);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", 7, 0, 7);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-bbH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", 7, 0, 7);
  scales[6]->SetBinContent(7, 0.);
#else
  scales[4] = new TH1F("scales-ggH"  , "", 7, 0, 7);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", 7, 0, 7);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-VH"   , "", 7, 0, 7);
  scales[6]->SetBinContent(7, unscaled[6]>0 ? (VH   ->Integral()/unscaled[6]-1.) : 0.);
#endif

  EWK1 ->Add(Fakes);
  EWK2 ->Add(EWK1 );
#ifdef EXTRA_SAMPLES
  EWK3 ->Add(EWK2 );
  EWK  ->Add(EWK3 );
#else
  EWK  ->Add(EWK2 );
#endif
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }
  else{
#ifdef MSSM    
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
    VH   ->Add(Ztt);
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
  }

  /*
    Mass plot before and after fit
  */
  TCanvas *canv = MakeCanvas("canv", "histograms", 600, 600);

  canv->cd();
  if(log){ canv->SetLogy(1); }
  // reduce the axis range if necessary
  //data->GetXaxis()->SetRange(0, 28);
  data->SetNdivisions(505);
  data->SetMinimum(min);
  data->SetMaximum(max);
  data->Draw("e");

  TH1F* errorBand = (TH1F*)Ztt ->Clone();
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);

  if(log){
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    ggH  ->Draw("histsame");
    $DRAW_ERROR
  }
  else{