Пример #1
0
Double_t calc_asymmetry_syst(TString syst)
{
	TFile *f1 = new TFile("histos/unfolded_syst_"+syst+".root");
	TFile *f3 = new TFile("histos/"+sample+"/efficiency.root");

	TH1F *hunf = (TH1F*)f1->Get("unfolded");
	TH1F *hgen_presel = (TH1F*)f3->Get("hgen_presel");
	//TH1F *hgen_presel_rebin = (TH1F*)f3->Get("hgen_presel_rebin");
	
	TH1F *hasy= (TH1F*)f1->Get("asymmetry");
	//TH1F *hStatErr = (TH1F*)f1->Get("staterr");
	
	// unfolded in bins of generated
	TH1F *hunf_rebin_width = new TH1F(var_y+"_unf",var_y+"_unf",bin_x,list_x);
	for(Int_t i = 1; i <= bin_x; i++) {
		hunf_rebin_width->SetBinContent(i,hunf->GetBinContent(i));
		hunf_rebin_width->SetBinError(i,hunf->GetBinError(i));
	}

	Double_t asy_gen = asymmetry(hgen_presel);
	Double_t asy_unf = hasy->GetMean();

	//cout << endl << asy_gen << " " << asy_unf << endl;

	Double_t diff = asy_gen - asy_unf;
	//Double_t uncertainty = diff/asy_gen;
	Double_t uncertainty = diff;
	cout << uncertainty << endl;
	//cout << hStatErr->GetMean() << endl;

	return uncertainty;
}
TH1F* shape_histos(TH1F* hin, const TString datacard, const TString name)
/*
  use the proper histograms and errors including shpae uncertainties as provided by combine
*/
{
  TH1F* hout = (TH1F*)hin->Clone(); hout->Clear();
  TFile* mlfit = new TFile("fitresults/mlfit.root", "READ");
  TH1F* shape = (TH1F*)mlfit->Get(TString("shapes_fit_s/").Append(datacard).Append("/").Append(name)); // currently problems with data and hioggsprocesses -> different name

  if(shape==0) std::cout << " No histogram found for " << name << std::endl;

  //  for(int i=0; i<hout->GetNbinsX(); ++i)
  for(int i=1; i<hout->GetNbinsX()+1; i++)
  {

    Float_t Norig = hin->GetBinContent(i)*hin->GetBinWidth(i);
    Float_t Nshape = shape->GetBinContent(i);
    Float_t scale_err = (Nshape==0) ? 1 : Norig/Nshape;

    //    hout->SetBinContent(i,shape->GetBinContent(i));
    hout->SetBinContent(i,hin->GetBinContent(i)*hin->GetBinWidth(i));
    hout->SetBinError(i,shape->GetBinError(i)*scale_err);
  }
  mlfit->Close();
  return hout;
}
Пример #3
0
TH1F * divideHistosForRatio(TH1F * sig, TH1F * bkg) {

  TH1F * cloneS = (TH1F *) sig->Clone( sig->GetTitle() );
  TH1F * cloneB = (TH1F *) bkg->Clone( bkg->GetTitle() );

  /*
  for( Int_t bin = 1; bin <= cloneB->GetNbinsX(); bin++ )
    cloneB->SetBinError( bin, 0. );    
  
  cloneS->Divide( cloneS, cloneB, 1, 1, "" );
  */

  for( Int_t bin = 1; bin <= cloneS->GetNbinsX(); bin++ ){

    Double_t sv = cloneS->GetBinContent(bin);
    Double_t se = cloneS->GetBinError(bin);

    Double_t bv = cloneB->GetBinContent(bin);

    Double_t rat = -1.;
    Double_t err =  0.;

    if( sv != 0. && bv != 0. ) {
      rat = sv / bv;
      // err = sqrt( sv / (bv*bv) );
      err = sqrt( se / (bv*bv) );
    }

    cloneS->SetBinContent( bin, rat );
    cloneS->SetBinError( bin, err );
  }

  return cloneS;
}
//Make a histogram from a TF1
TH1F* makeHist(TF1 *iFit,TH1F *iH,std::string iName) { 
  TH1F *lH = (TH1F*) iH->Clone(iName.c_str());
  for(int i0 = 0; i0 < lH->GetNbinsX()+1; i0++) lH->SetBinContent(i0,iFit->Eval(lH->GetXaxis()->GetBinCenter(i0)));
  for(int i0 = 0; i0 < lH->GetNbinsX()+1; i0++) lH->SetBinContent(i0,lH->GetBinContent(i0)*lH->GetXaxis()->GetBinWidth(i0));
  for(int i0 = 0; i0 < lH->GetNbinsX()+1; i0++) lH->SetBinError (i0,lH->GetBinError   (i0)*lH->GetXaxis()->GetBinWidth(i0));
  return lH;
}
Пример #5
0
void DYjets_WeightedYield(TTree* tr, TCut cut, float& val, float& err)
{
  TH1F* h = new TH1F("h","h",1,-3.0,3.0);
//  std::cout<<"tr->GetEntries()="<<tr->GetEntries(cut)<<std::endl;
  tr->Draw("phoSCEta>>h",cut,"goff");
  val = h->GetBinContent(1);
  err = h->GetBinError(1);
  delete h;
}// end of DYjets_WeightedYield
Пример #6
0
TH1F* fixrange(TH1F* old, int numB) {

  float x1, x2;
  string name = old->GetName();

  if (name.find("Ht")!=string::npos) {
    x1 = 30.;
    x2 = 500.;
    if (numB==2) x2 = 400.;
  } else if (name.find("jet_pt")!=string::npos) {
    x1 = 30.;
    x2 = 300.;
    if (numB==2) {
      if (name.find("first")!=string::npos) x2 = 200.;
      if (name.find("second")!=string::npos) x2 = 120.;
    }
  } else if (name.find("pt_Z")!=string::npos) {
    x1 = 0.;
    x2 = 300.;
    if (numB==2) x2 = 230.;
  } else {
    x1 = old->GetXaxis()->GetBinCenter(1);
    x2 = old->GetXaxis()->GetBinCenter(old->GetNbinsX());
  }

  int nx = old->GetXaxis()->FindBin(x2)-old->GetXaxis()->FindBin(x1)+1;

  x1 = old->GetXaxis()->GetBinLowEdge(old->GetXaxis()->FindBin(x1));
  x2 = old->GetXaxis()->GetBinUpEdge(old->GetXaxis()->FindBin(x2));

  TH1F* tmp = new TH1F("tmp",old->GetTitle(),nx,x1,x2);
  tmp->Sumw2();

  tmp->GetXaxis()->SetTitle(old->GetXaxis()->GetTitle());
  tmp->GetYaxis()->SetTitle(old->GetYaxis()->GetTitle());

  for (int i=0;i<=old->GetNbinsX()+1;i++) {
    int ii = tmp->GetXaxis()->FindBin(old->GetXaxis()->GetBinCenter(i));
    float c1 = tmp->GetBinContent(ii);
    float e1 = tmp->GetBinError(ii);
    float c2 = old->GetBinContent(i);
    float e2 = old->GetBinError(i);

    tmp->SetBinContent(ii,c1+c2);
    tmp->SetBinError(ii,TMath::Sqrt(e1*e1+e2*e2));
  }

  tmp->SetEntries(old->GetEntries());

  old->Delete();
  tmp->SetName(name.c_str());

  return tmp;
}
Пример #7
0
float stat(TString mass){
  TString samplename = "TTbar_Powheg";
  if (mass == "1725") samplename += ".root";
  else samplename += "_mtop" + mass + ".root"; 
  TFile *f = TFile::Open(path + samplename);
  TH1F* h;
  f->GetObject("H_Yields_ElMu", h);
  float y = h->GetBinError(5); 
  delete f;
  return y*Lumi;
}
Пример #8
0
/**
 * Saving Histogram Data
 */
void ExportHistogram(TFile* f,const char* histKey,const char* outputfile){
  // Root Setup
  TH1F* h = (TH1F*) f->Get(histKey);

  // File Setup
  ofstream out;
  out.open(outputfile);
  out<<"Bin,Value,Error"<<endl;
  for (int i = 1; i < h->GetNbinsX()-1; i++){
    out<<h->GetBinCenter(i)<<","<<h->GetBinContent(i)<<","<<h->GetBinError(i)<<endl;
  }
  out.close();
}
Пример #9
0
TH1F * getSystErrForRatio(TH1F * bkg) {

  TH1F * cloneB = (TH1F *) bkg->Clone( bkg->GetTitle() );

  for ( Int_t bin = 1; bin <= cloneB->GetNbinsX(); bin++ ) {
    Double_t relError = ( cloneB->GetBinError(bin) / cloneB->GetBinContent(bin) );

    cloneB->SetBinContent( bin, 1. );
    cloneB->SetBinError( bin, relError );
  }

  return cloneB;
}
Пример #10
0
//*************************************************************************************************
//Normalize Hist
//*************************************************************************************************
TH1F* NormalizeHist(TH1F *originalHist) {
  TH1F* hist = (TH1F*)originalHist->Clone((string(originalHist->GetName())+"_normalized").c_str());
  Double_t norm = 0;
  hist->SetTitle("");
  for (UInt_t b=0; int(b)<hist->GetXaxis()->GetNbins()+2; ++b) {
    norm += hist->GetBinContent(b);
  }
  for (UInt_t b=0; int(b)<hist->GetXaxis()->GetNbins()+2; ++b) {
    hist->SetBinContent(b,hist->GetBinContent(b) / norm);
    hist->SetBinError(b,hist->GetBinError(b) / norm);
  }

  return hist;
}
RooHistPdf* GetRooHistPdf(TFile* fin, string region, string process, string varname, RooRealVar* var, float& norm, TH1F*& histo, bool do_mcstat, bool do_norm, float input_norm){
    TH1F* h  =  GetHisto(fin,region,process,varname, norm, do_norm, input_norm);
    histo = h;
    if(do_mcstat)
    {
        //randomisation of the histo ...
        for(int i=1;i<=h->GetNbinsX();i++)
        {
            h->SetBinContent(i,randomnessGenerator->Gaus(h->GetBinContent(i),h->GetBinError(i)));
        }
    }
    string rdhname = "rdh_"+region+"_"+process;
    RooDataHist *rdh  = new RooDataHist(rdhname.c_str(),rdhname.c_str(),RooArgList(*var),Import(*h));
    string pdfname = "pdf_"+region+"_"+process;
    RooHistPdf *pdf  = new  RooHistPdf(pdfname.c_str(),pdfname.c_str(),RooArgSet(*var),*rdh);
    return pdf;
}
Пример #12
0
// rebin the spectra
TH1F *rebin_yaxian(TH1F *h, char *histName)
{
  TH1F *hRebin = new TH1F(Form("%s_rebin",h->GetName()),Form("rebin %s",h->GetTitle()),nbins_jetPtBin,boundaries_jetPtBin);
  for (int i=1;i<=h->GetNbinsX();i++)
    {
      double val=h->GetBinContent(i);
      double valErr=h->GetBinError(i);
      int binNum = hRebin->FindBin(h->GetBinCenter(i));
      double val1 = hRebin->GetBinContent(binNum);
      double valErr1 = hRebin->GetBinError(binNum);
      hRebin->SetBinContent(binNum,val+val1);
      hRebin->SetBinError(binNum,sqrt(valErr1*valErr1+valErr*valErr));
    }
  cleanup(hRebin);
  hRebin->SetName(histName);
  return hRebin;
}
//Rebin the histogram
TH1F* rebin(TH1F* iH,int iNBins,double *iAxis) { 
  std::string lTmp = "tmp"; //Added to avoid Root output errors
  TH1F *lH = new TH1F(lTmp.c_str(),lTmp.c_str(),iNBins,iAxis);
  for(int i0 = 0; i0 < iH->GetNbinsX()+1; i0++) {
    int    lNBin = lH->GetXaxis()->FindBin(iH->GetXaxis()->GetBinCenter(i0));
    double lVal  = iH->GetBinContent(i0);
    double lErr  = iH->GetBinError  (i0);
    double lOldV = lH->GetBinContent(lNBin);
    double lOldE = lH->GetBinError  (lNBin);
    lH->SetBinContent(lNBin,lVal+lOldV);
    lH->SetBinError  (lNBin,sqrt(lOldE*lOldE+lErr*lErr));
  }
  std::string lName2 = iH->GetName();
  std::string fine_binning = "_fine_binning";
  lName2.replace(lName2.find(fine_binning),fine_binning.length(),"");
  lH->SetName (lName2.c_str());
  lH->SetTitle(lName2.c_str());
  delete iH;
  return lH;
}
Пример #14
0
void Fit(TString SIGNAL,TString HISTO,double scaleSGN)
{
  gROOT->ForceStyle();
  TFile *fDat = TFile::Open("Histo_flatTree_data_tmva"+SIGNAL+".root");
  TFile *fBkg = TFile::Open("Histo_flatTree_qcd_weights_tmva"+SIGNAL+".root");
  TFile *fSgn = TFile::Open("Histo_flatTree_"+SIGNAL+"_weights_tmva"+SIGNAL+".root");
  
  TH1 *hDat = (TH1*)fDat->Get(HISTO);
  TH1 *hBkgRaw = (TH1*)fBkg->Get(HISTO);
  TH1 *hSgn = (TH1*)fSgn->Get(HISTO);
  TH1 *hDat_JESlo = (TH1*)fDat->Get(HISTO+"_JESlo");
  TH1 *hBkgRaw_JESlo = (TH1*)fBkg->Get(HISTO+"_JESlo");
  TH1 *hSgn_JESlo = (TH1*)fSgn->Get(HISTO+"_JESlo");
  TH1 *hDat_JESup = (TH1*)fDat->Get(HISTO+"_JESup");
  TH1 *hBkgRaw_JESup = (TH1*)fBkg->Get(HISTO+"_JESup");
  TH1 *hSgn_JESup = (TH1*)fSgn->Get(HISTO+"_JESup");
  
  TH1F *hBkg = (TH1F*)hBkgRaw->Clone("Bkg");
  TH1F *hBkg_JESlo = (TH1F*)hBkgRaw_JESlo->Clone("Bkg_JESlo");
  TH1F *hBkg_JESup = (TH1F*)hBkgRaw_JESup->Clone("Bkg_JESup");
  
  hBkg->Smooth(2);
  hBkg_JESlo->Smooth(2);
  hBkg_JESup->Smooth(2);
  hSgn->Smooth(2);
  hSgn_JESlo->Smooth(2);
  hSgn_JESup->Smooth(2);
  
  double lumi = 4967;
  hBkg->Scale(lumi);
  hBkg_JESlo->Scale(lumi);
  hBkg_JESup->Scale(lumi);
  double k_factor = hDat->Integral()/hBkg->Integral();
  double k_factor_JESlo = hDat->Integral()/hBkg_JESlo->Integral();
  double k_factor_JESup = hDat->Integral()/hBkg_JESup->Integral();
  hBkg->Scale(k_factor);
  cout<<"Signal entries = "<<hSgn->GetEntries()<<endl;
  hSgn->Scale(lumi/scaleSGN);
  hBkg_JESlo->Scale(k_factor_JESlo);
  hSgn_JESlo->Scale(lumi/scaleSGN);
  hBkg_JESup->Scale(k_factor_JESup);
  hSgn_JESup->Scale(lumi/scaleSGN);
  hSgn_JESlo->Scale(hSgn->Integral()/hSgn_JESlo->Integral());
  hSgn_JESup->Scale(hSgn->Integral()/hSgn_JESup->Integral());
  
  TH1 *hBkg_STATlo = (TH1*)hBkg->Clone(HISTO+"_STATlo");
  TH1 *hSgn_STATlo = (TH1*)hSgn->Clone(HISTO+"_STATlo");
  TH1 *hBkg_STATup = (TH1*)hBkg->Clone(HISTO+"_STATup");
  TH1 *hSgn_STATup = (TH1*)hSgn->Clone(HISTO+"_STATup");
  
  float y1,e1;
  for(int i=0;i<hBkg->GetNbinsX();i++) {
    y1 = hBkg->GetBinContent(i+1);
    e1 = hBkg->GetBinError(i+1);
    hBkg_STATlo->SetBinContent(i+1,y1-e1);
    hBkg_STATup->SetBinContent(i+1,y1+e1);
    y1 = hSgn->GetBinContent(i+1);
    e1 = hSgn->GetBinError(i+1);
    hSgn_STATlo->SetBinContent(i+1,y1-e1);
    hSgn_STATup->SetBinContent(i+1,y1+e1);
  }
  hBkg_STATlo->Scale(hBkg->Integral()/hBkg_STATlo->Integral());
  hBkg_STATup->Scale(hBkg->Integral()/hBkg_STATup->Integral());
  hSgn_STATlo->Scale(hSgn->Integral()/hSgn_STATlo->Integral());
  hSgn_STATup->Scale(hSgn->Integral()/hSgn_STATup->Integral());
  
  double xMIN = hBkg->GetBinLowEdge(1);
  double xMAX = hBkg->GetBinLowEdge(hBkg->GetNbinsX()+1);
  double xMIN2 = hDat->GetBinLowEdge(hDat->FindFirstBinAbove(0.5));
  double xMAX2 = hDat->GetBinLowEdge(hDat->FindLastBinAbove(0.5)+1);
  RooRealVar x("x","x",xMIN2,xMAX2);
  
  RooDataHist data("data","dataset with x",x,hDat);
  RooDataHist bkg("qcd","bkg with x",x,hBkg);
  RooDataHist sgn("signal","sgn with x",x,hSgn);
  
  RooHistPdf bkgPDF("bkgPDF","bkgPDF",x,bkg,0);
  RooHistPdf sgnPDF("sgnPDF","sgnPDF",x,sgn,0);
  
  RooRealVar f("f","f",0,0.,1.);
  
  RooAddPdf model("model","model",RooArgList(sgnPDF,bkgPDF),RooArgList(f));
  
  RooFitResult* r = model.fitTo(data,Save());
  r->Print("v");
  double N = hDat->Integral();
  double B = hBkg->Integral();
  double S = hSgn->Integral();
  double m = f.getVal();
  double e = f.getError();
  cout<<"k-factor = "<<k_factor<<endl;
  cout<<N<<" "<<B<<" "<<S<<endl;
  cout<<"Total cross section =       "<<N/lumi<<" pb"<<endl;
  cout<<"Model cross section =       "<<S/lumi<<" pb"<<endl;
  cout<<"Fitted signal strength =    "<<m*N/S<<endl;
  cout<<"Fitted signal error =       "<<e*N/S<<endl;
  double p = 0.95;
  double xup = (N/S)*(m+sqrt(2.)*e*TMath::ErfInverse((1-p)*TMath::Erf(m/e)+p));
  cout<<"Bayesian Upper limit =      "<<xup<<endl;
  RooPlot* frame1 = x.frame();  
  data.plotOn(frame1);
  model.plotOn(frame1,Components("sgnPDF*"),LineStyle(1),LineWidth(2),LineColor(kGreen+1));
  model.plotOn(frame1,Components("bkgPDF*"),LineStyle(1),LineWidth(2),LineColor(kRed));
  model.plotOn(frame1,LineStyle(1),LineWidth(2),LineColor(kBlue));
  
  //cout<<frame1->chiSquare()<<endl;
  RooHist* hresid = frame1->residHist();
  RooHist* hpull = frame1->pullHist();
  RooPlot* frame2 = x.frame(Title("Residual Distribution"));
  frame2->addPlotable(hresid,"P") ;
  
  // Create a new frame to draw the pull distribution and add the distribution to the frame
  RooPlot* frame3 = x.frame(Title("Pull Distribution"));
  frame3->addPlotable(hpull,"P");
  
  TCanvas* cFit = new TCanvas("fitANN_"+SIGNAL,"fitANN_"+SIGNAL,900,600);
  gPad->SetLogy();
  frame1->SetMaximum(1e+4);
  frame1->SetMinimum(0.5);
  frame1->GetXaxis()->SetTitle("ANN Output");
  frame1->GetYaxis()->SetTitle("Events");
  frame1->Draw();
  cout<<frame1->nameOf(3)<<endl;
  TLegend *leg = new TLegend(0.7,0.65,0.9,0.9);
  leg->SetHeader(SIGNAL);
  leg->AddEntry(frame1->findObject("h_data"),"data","P");
  leg->AddEntry(frame1->findObject("model_Norm[x]"),"QCD+Signal","L");
  leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[bkgPDF*]"),"QCD","L");
  leg->AddEntry(frame1->findObject("model_Norm[x]_Comp[sgnPDF*]"),"Signal","L");
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.04);
  leg->Draw();

  TCanvas* cPull = new TCanvas("pullANN_"+SIGNAL,"pullANN_"+SIGNAL,900,400); 
  frame3->GetXaxis()->SetTitle("ANN Output");
  frame3->GetYaxis()->SetTitle("Pull");
  frame3->Draw();
  
  cout<<"Creating datacard"<<endl;
  ofstream datacard;
  datacard.open("datacard_"+SIGNAL+"_"+HISTO+".txt");
  datacard.setf(ios::right);
  datacard<<"imax 1"<<"\n";
  datacard<<"jmax 1"<<"\n";
  datacard<<"kmax *"<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"shapes * * "<<SIGNAL+"_"+HISTO+"_input.root $PROCESS $PROCESS_$SYSTEMATIC"<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"bin         1"<<"\n";
  datacard<<"observation "<<N<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"bin         1       1"<<"\n";
  datacard<<"process     signal  background  "<<"\n";
  datacard<<"process     0       1"<<"\n";
  datacard<<"rate       "<<S<<"    "<<B<<"\n";
  datacard<<"----------------"<<"\n";
  datacard<<"lumi        lnN       1.022    1.022"<<"\n";
  datacard<<"jes         shape     1        1"<<"\n";
  datacard<<"mcstat      shape     1        1"<<"\n";
  datacard<<"jer         shape     0        0"<<"\n";
  datacard.close();
  
  TFile *out = new TFile(SIGNAL+"_"+HISTO+"_input.root","RECREATE");
  out->cd();
  hDat->Write("data_obs");
  hBkg->Write("background");
  hSgn->Write("signal");
  hDat_JESlo->Write("data_obs_jesDown");
  hBkg_JESlo->Write("background_jesDown");
  hBkg_STATlo->Write("background_mcstatDown");
  hSgn_STATlo->Write("signal_mcstatDown");
  hSgn_JESlo->Write("signal_jesDown");
  hDat_JESup->Write("data_obs_jesUp");
  hBkg_JESup->Write("background_jesUp");
  hBkg_STATup->Write("background_mcstatUp");
  hSgn_JESup->Write("signal_jesUp");
  hSgn_STATup->Write("signal_mcstatUp");
  //----- JER placeholder ----------------
  hBkg_JESlo->Write("background_jerDown");
  hSgn_JESlo->Write("signal_jerDown"); 
  hBkg_JESup->Write("background_jerUp");
  hSgn_JESup->Write("signal_jerUp");
}
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();
}
Пример #16
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())); 
}
Пример #17
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    int MinPhi = 41;
    int MaxPhi = 53;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  TF1 *fped = new TF1("fped","gaus",0, 80);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	    

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
Пример #18
0
void Analyzer::ComputeMinFast(){
	g2=new TGraph2D(); 
	
	alpha=1.0;beta=0;
	Loop(t_data,1);
	for(int j=0;j<=h_data->GetNbinsX()+1;j++)if(h_data->GetBinError(j)==0)h_data->SetBinError(j,1);
	if(varName=="QGLMLP")
		Loop(t_mc,4);
	//scan
	//reset Fast
	ResetFast();
	
	alpha=1.0;beta=0;
	for(float ai=aMin; ai<=aMax; ai+=0.02)
		{
		Reset(h_mc);	
		alphaFast.push_back(ai);	
		betaFast.push_back(0);	
		h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
		}
	alpha=1.0;beta=0;
	for(float bi=bMin; bi<=bMax; bi+=0.01)
		{
		Reset(h_mc);	
		alphaFast.push_back(1.0);	
		betaFast.push_back(bi);	
		h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
		}

	for(int j=0;j< int(h_mcFast.size());j++) h_mcFast[j]->Sumw2();	
	Loop(t_mc,16);
		for(int i=0 ;i<int(alphaFast.size());i++)
			{
			for(int j=0;j<=h_mcFast[i]->GetNbinsX()+1;j++)if(h_mcFast[i]->GetBinError(j)==0)h_mcFast[i]->SetBinError(j,1);
			h_mcFast[i]->Scale(h_data->Integral()/h_mcFast[i]->Integral());
			g2->SetPoint(g2->GetN(),alphaFast[i],betaFast[i], h_data->Chi2Test(h_mcFast[i],opt.c_str())  );
			}
	//Find min0;min1
	float min0=1,min1=0;
	pair<float,float> R=MinG(g2);
	min0=R.first;min1=R.second;
		
	ResetFast();

	delete g2;
	g2=new TGraph2D();

	for(int i=-nstep;i<=nstep;i++)
	for(int j=-nstep;j<=nstep;j++)
        	{
        	alphaFast.push_back(min0+i*stp0 );
        	betaFast.push_back(min1+j*stp1 );
		h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
		//g2->SetPoint(g2->GetN(),alpha,beta, h_data->Chi2Test(h_mc,opt.c_str())  );
		}
	alphaFast.push_back(min0);
	betaFast.push_back(0);
	h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );

	alphaFast.push_back(min1);
	betaFast.push_back(bMax);
	h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
	
	alphaFast.push_back(1);
	betaFast.push_back(0);
	h_mcFast.push_back(new TH1F( Form("hmc_%d",int(h_mcFast.size())),"hmc",nBins,xMin,xMax) );
	
	for(int j=0;j<int(h_mcFast.size());j++) h_mcFast[j]->Sumw2();	
	Loop(t_mc,16);
		for(int i=0 ;i<int(alphaFast.size());i++)
			{
			for(int j=0;j<=h_mcFast[i]->GetNbinsX()+1;j++)if(h_mcFast[i]->GetBinError(j)==0)h_mcFast[i]->SetBinError(j,1);
			h_mcFast[i]->Scale(h_data->Integral()/h_mcFast[i]->Integral());
			g2->SetPoint(g2->GetN(),alphaFast[i],betaFast[i], h_data->Chi2Test(h_mcFast[i],opt.c_str())  );
			}
	double m0,m1;
	R=MinG(g2,&m0,&m1);
	printf("a=%.3f;b=%.3f;lmin=%.3f;lmax=%.3f;break;//chi2=%.3lf; chi2_0=%.3lf\n",R.first,R.second,lmin,lmax,m0,m1);
	{
	TFile *out=TFile::Open("output.root","UPDATE");out->cd();
	for(int i=0;i<int(h_mcFast.size());i++)
		{
		h_mcFast[i]->SetName(Form("%s_alpha%.2f_beta%.2f_lmin%.3f_lmax%.3f_pt%0f_%.0f_rho%.0f_%.0f_eta%.0f_%.0f",varName.c_str(),alphaFast[i],betaFast[i],lmin,lmax,PtMin,PtMax,RhoMin,RhoMax,EtaMin,EtaMax));
		h_mcFast[i]->Write();
		}
	h_data->SetName(Form("%s_data_pt%0f_%.0f_rho%.0f_%.0f_eta%.0f_%.0f",varName.c_str(),PtMin,PtMax,RhoMin,RhoMax,EtaMin,EtaMax));
	h_data->Write();
	}
	return;
}
Пример #19
0
pair<float,float> Analyzer::SmearDoubleMin(float a0_q,float b0_q , float a0_g,float b0_g,int type){ //type = 0 Q, 1 G
	fprintf(stderr,"SmearDoubleMin\n");
	TGraph2D *g2_q=new TGraph2D(); 
	TGraph2D *g2_g=new TGraph2D(); 
	
	alpha=1.0;beta=0;

	//if(h_data!=NULL)delete h_data;
	//if(h_mc!=NULL)delete h_mc;
	fprintf(stderr,"Creating Histos\n");
	CreateHisto(3);
	
	fprintf(stderr,"Going to do Data Loop\n");
	Loop(t_data,1);

	if(varName=="QGLMLP")
		Loop(t_mc,4);
	//scan
	a_q=a0_q;b_q=b0_q;
	a_g=a0_g;b_g=b0_g;

	alpha=1.0;beta=0;
	fprintf(stderr,"Going to do span ai\n");
	for(float ai=0.7; ai<=1.1; ai+=0.02)
		{
		Reset(h_mc);	
		if(type==0)a_q=ai;
		if(type==1)a_g=ai;
		Loop(t_mc,8);
		for(int j=0;j<=h_mc->GetNbinsX()+1;j++)if(h_mc->GetBinError(j)==0)h_mc->SetBinError(j,1);
		h_mc->Scale(h_data->Integral()/h_mc->Integral());

		if(type==0)g2_q->SetPoint(g2_q->GetN(),a_q,b_q, h_data->Chi2Test(h_mc,opt.c_str())  );	
		if(type==1)g2_g->SetPoint(g2_g->GetN(),a_g,b_g, h_data->Chi2Test(h_mc,opt.c_str())  );	
		}
	alpha=1.0;beta=0;
	a_q=a0_q;b_q=b0_q;
	a_g=a0_g;b_g=b0_g;

	fprintf(stderr,"Going to do span bi\n");
	for(float bi=-0.5; bi<=0.5; bi+=0.01)
		{
		Reset(h_mc);	
		if(type==0)b_q=bi;
		if(type==1)b_g=bi;
		Loop(t_mc,8);
		for(int j=0;j<=h_mc->GetNbinsX()+1;j++)if(h_mc->GetBinError(j)==0)h_mc->SetBinError(j,1);
		h_mc->Scale(h_data->Integral()/h_mc->Integral());
		if(type==0)g2_q->SetPoint(g2_q->GetN(),a_q,b_q, h_data->Chi2Test(h_mc,opt.c_str())  );	
		if(type==1)g2_g->SetPoint(g2_g->GetN(),a_g,b_g, h_data->Chi2Test(h_mc,opt.c_str())  );	
		}
	
	//Find min0;min1
	float min0=1,min1=0;
	pair<float,float> R;
		if(type==0)R=MinG(g2_q);
		if(type==1)R=MinG(g2_g);
	min0=R.first;min1=R.second;

	for(int i=-nstep;i<=nstep;i++)
	for(int j=-nstep;j<=nstep;j++)
        	{
        	if(type==0)a_q=min0+i*stp0;
        	if(type==1)a_g=min0+i*stp0;
        	if(type==0)b_q=min1+j*stp1;
        	if(type==1)b_g=min1+j*stp1;
		Loop(t_mc,8);
		for(int k=0;k<=h_mc->GetNbinsX()+1;k++)if(h_mc->GetBinError(k)==0)h_mc->SetBinError(k,1);
		h_mc->Scale(h_data->Integral()/h_mc->Integral());
		if(type==0)g2_q->SetPoint(g2_q->GetN(),a_q,b_q, h_data->Chi2Test(h_mc,opt.c_str())  );	
		if(type==1)g2_g->SetPoint(g2_g->GetN(),a_g,b_g, h_data->Chi2Test(h_mc,opt.c_str())  );	
		}
	
		if(type==0)R=MinG(g2_q);
		if(type==1)R=MinG(g2_g);
	//SAME ON G,& REDO
	//printf("a=%.3f;b=%.3f;lmin=%.3f;lmax=%.3f;break;\n",R.first,R.second,lmin,lmax);
	return R;
}
Пример #20
0
void makeStack(TString myVar, TString myCut, TString myName, TString myAxisNameX, TString myAxisNameY, 
               vector<const Sample*>& listOfSignals, vector<const Sample*>& listOfSamples, vector<const Sample*> listOfDatasets, 
               TString inFileName,
               bool isBlind, bool isLog, bool drawSignal, bool drawLegend,
               int nBins, float xLow, float xHigh,
               float* xlowVec)
{
  // prepare the input file
  TFile* infile = new TFile(inFileName, "READ"); 
  infile -> cd();
  
  // prepare the stack
  THStack *hs = new THStack("hs","");
  // prepare the histos pointers
  TH1F*   hist[20];
  // prepare the tree pointers
  TTree*  tree[20];
  // prepare the legend
  TLegend* leg = new TLegend(.7485,.7225,.9597,.9604);
  leg->SetFillColor(0);
  // prepare the colors
  Int_t col[20] = {46,2,12,5,3,4,9,7,47,49,49,50,51,52,53,54,55,56,57,58};
  // prepare the cut
  if (isBlind) myCut += "*(phoMetDeltaPhi < 2.9)";        
  // prepare the Y axis lable
  if (xlowVec != 0) myAxisNameY = "Events/" + myAxisNameY;
  else {
    float binWidth = (xHigh-xLow)/nBins;
    TString tempString;
    tempString.Form("%.2f ",binWidth); 
    myAxisNameY = "Events/" + tempString + myAxisNameY;
  }
  // prepare the legend strings
  vector<TString> theLegends;
  
  // loop through the datasets and produce the plots
  TH1F* hdata;
  TH1F* hsignal;
  //prepare data and signal histos
  if (xlowVec != 0) hdata   = new TH1F("hdata","",nBins,xlowVec);
  else hdata = new TH1F("hdata","",nBins,xLow,xHigh);
  if (xlowVec != 0) hsignal = new TH1F("hsignal","",nBins,xlowVec);
  else hsignal = new TH1F("hsignal","",nBins,xLow,xHigh);

  TTree*  treedata[20];
  for (UInt_t iDatas=0; iDatas < listOfDatasets.size(); iDatas++) {
    //get the tree
    treedata[iDatas] = (TTree*) infile -> Get(listOfDatasets.at(iDatas)->Name()->Data());

    //fill the histogram
    if ( iDatas == 0 ) treedata[iDatas] -> Draw(myVar + " >> hdata","evt_weight*kf_weight*pu_weight" + myCut);
    else treedata[iDatas] -> Draw(myVar + " >>+ hdata","evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( isBlind && iDatas == 0 ) leg -> AddEntry(hdata, "DATA (19.8 fb^{-1})", "pl");    
    
  }//end loop on datasets
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinError  (iBin,hdata->GetBinError(iBin)/hdata->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hdata->SetBinContent(iBin,hdata->GetBinContent(iBin)/hdata->GetBinWidth(iBin));
  }

  TTree*  treesignal[20];
  for (UInt_t iSignal=0; iSignal < listOfSignals.size(); iSignal++) {
    //get the tree
    treesignal[iSignal] = (TTree*) infile -> Get(listOfSignals.at(iSignal)->Name()->Data());

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSignals.at(iSignal)->Scale()));
    if ( iSignal == 0 ) treesignal[iSignal] -> Draw(myVar + " >> hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else treesignal[iSignal] -> Draw(myVar + " >>+ hsignal",thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    if ( drawSignal && iSignal == 0 ) leg -> AddEntry(hsignal, "Signal", "l");    
    
  }//end loop on signals
  if (xlowVec != 0) {
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinError  (iBin,hsignal->GetBinError(iBin)/hsignal->GetBinWidth(iBin));
    for (int iBin = 1; iBin <= nBins; iBin++) hsignal->SetBinContent(iBin,hsignal->GetBinContent(iBin)/hsignal->GetBinWidth(iBin));
  }
  hsignal -> SetLineColor(49);
  hsignal -> SetLineWidth(4.0);
       
  int theHistCounter = 0;
  // loop through the samples and produce the plots
  for (UInt_t iSample=0; iSample < listOfSamples.size(); iSample++) {

    //determine if the histo is first of the series
    bool isFirstOfSerie = (*listOfSamples.at(iSample)->Legend()).CompareTo(" ");
    bool isLastOfSerie = false;
    if (iSample == listOfSamples.size() - 1) isLastOfSerie = true;
    if (iSample < listOfSamples.size() - 1 && (*listOfSamples.at(iSample+1)->Legend()).CompareTo(" ") != 0) isLastOfSerie = true;
    
    //get the tree
    tree[iSample] = (TTree*) infile -> Get(listOfSamples.at(iSample)->Name()->Data());
    //if sample first of the list create a new histogram
    if (isFirstOfSerie) {
       TString thisHistName = "h_" + *(listOfSamples.at(iSample)->Name());
       //variable bin histo
       if (xlowVec != 0) hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xlowVec);
       //fixed bin histo
       else hist[theHistCounter] = new TH1F(thisHistName,thisHistName,nBins,xLow,xHigh);
       hist[theHistCounter] -> Sumw2();
       hist[theHistCounter] -> SetFillColor(col[theHistCounter]);
       hist[theHistCounter] -> SetFillStyle(1001);
       theLegends.push_back(*listOfSamples.at(iSample)->Legend());
    }

    //fill the histogram
    TString thisScale = Form("%f *", *(listOfSamples.at(iSample)->Scale()));
    if (isFirstOfSerie) tree[iSample] -> Draw(myVar + " >> " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    else tree[iSample] -> Draw(myVar + " >>+ " + TString(hist[theHistCounter] -> GetName()),thisScale + "evt_weight*kf_weight*pu_weight" + myCut);
    
    //add the histogram to the stack if the last of the series:
    //either last sample or ~ sample followed by non ~ sample
    if (isLastOfSerie) {
       if (xlowVec != 0) {
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinError  (iBin,hist[theHistCounter]->GetBinError(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
         for (int iBin = 1; iBin <= nBins; iBin++) hist[theHistCounter]->SetBinContent(iBin,hist[theHistCounter]->GetBinContent(iBin)/hist[theHistCounter]->GetBinWidth(iBin));
       }
       hs -> Add(hist[theHistCounter]);
       theHistCounter++;
    }
    
  }//end loop on samples

  //Fix the legend
  for (int iHisto = theHistCounter-1; iHisto >= 0; iHisto--) {
    leg -> AddEntry(hist[iHisto], theLegends[iHisto], "f");   
  }
  
  //get the maximum to properly set the frame
  float theMax = hdata -> GetBinContent(hdata -> GetMaximumBin()) + hdata -> GetBinError(hdata -> GetMaximumBin());
  TH1* theMCSum = (TH1*) hs->GetStack()->Last();
  float theMaxMC = theMCSum->GetBinContent(theMCSum->GetMaximumBin()) + theMCSum->GetBinError(theMCSum->GetMaximumBin());
  if (theMaxMC > theMax) theMax = theMaxMC;
  
  //prepare the ratio band and plot
  TH1* theMCRatioBand = makeRatioBand(theMCSum);
  TH1* theRatioPlot = makeRatioPlot(hdata,theMCSum);
    
  TCanvas* can = new TCanvas();
  can -> SetLogy(isLog);
  
  TPad *pad1 = new TPad("pad1","top pad",0,0.30,1,1);
  pad1->SetBottomMargin(0.02);
  pad1->SetLeftMargin(0.13);
  pad1->Draw();
  TPad *pad2 = new TPad("pad2","bottom pad",0,0.0,1,0.30);
  pad2->SetTopMargin(0.02);
  pad2->SetLeftMargin(0.13);
  pad2->SetBottomMargin(0.4);
  pad2->SetGridy();
  pad2->Draw();
  
  pad1->cd();
  hs->Draw("hist");
  hdata->Draw("same,pe");
  if (drawSignal) hsignal->Draw("same,hist");
  if (drawLegend) leg->Draw("same");
  //hs->GetXaxis()->SetTitle(myAxisNameX);
  hs->GetYaxis()->SetTitle(myAxisNameY);
  hs->GetXaxis()->SetLabelSize(0.04);
  hs->GetYaxis()->SetLabelSize(0.04);
  hs->GetXaxis()->SetLabelOffset(0.025);
  hs->GetYaxis()->SetLabelOffset(0.035);
  //hs->GetXaxis()->SetTitleOffset(1.1);
  hs->GetYaxis()->SetTitleOffset(1.1);
  hs->SetMaximum(theMax);
  if (isLog) hs->SetMinimum(0.01);
  
  pad2->cd();
  theMCRatioBand->GetXaxis()->SetTitle(myAxisNameX);
  theMCRatioBand->GetXaxis()->SetTitleSize(0.16);
  theMCRatioBand->GetXaxis()->SetTitleOffset(1.1);
  theMCRatioBand->GetXaxis()->SetLabelSize(0.12);
  theMCRatioBand->GetXaxis()->SetLabelOffset(0.07);
  theMCRatioBand->GetYaxis()->SetTitle("Data/MC");
  theMCRatioBand->GetYaxis()->SetTitleSize(0.10);
  theMCRatioBand->GetYaxis()->SetTitleOffset(0.6);
  theMCRatioBand->GetYaxis()->SetLabelSize(0.06);
  theMCRatioBand->GetYaxis()->SetLabelOffset(0.03);
  theMCRatioBand->SetFillStyle(3001);
  theMCRatioBand->SetFillColor(kBlue);
  theMCRatioBand->SetLineWidth(1);
  theMCRatioBand->SetLineColor(kBlack);
  theMCRatioBand->SetMarkerSize(0.1);
  theMCRatioBand->SetMaximum(4.);
  theMCRatioBand->SetMinimum(0.);
  theMCRatioBand->Draw("E2");
  TLine *line = new TLine(xLow,1,xHigh,1);
  line->SetLineColor(kBlack);
  line->Draw("same");
  theRatioPlot->Draw("same,pe");
  
  can->cd();
  can->Modified();
  can -> SaveAs(myName + ".pdf","pdf");
  
  //cleanup the memory allocation
  delete theMCSum;
  delete hs;
  delete leg;
  delete hdata;
  delete pad1;
  delete pad2;
  delete can;
  delete theMCRatioBand;
  delete theRatioPlot;
  infile -> Close();
  delete infile;
  
  return;
}
Пример #21
0
void printBfraction(char *tagger="discr_ssvHighEff", Double_t workingPoint=2, char *taggerName="ssvHighEff", int doCent=2, int do3bin=1) {

  gROOT->ForceStyle(1);

  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);


  gStyle->SetTextFont(42);
  gStyle->SetLabelFont(42,"XYZ");
  gStyle->SetTitleFont(42,"XYZ");

  // hack
  if(doCent)gStyle->SetErrorX(0);
  gStyle->SetLabelSize(0.05,"xy");
  gStyle->SetTitleSize(0.05,"xy");
  gStyle->SetTitleOffset(1.5,"xy");
  gStyle->SetPadLeftMargin(0.15);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetNdivisions(408,"y");


  TFile *fin1, *fin2;
  if(doCent){
    if(doCent==1){
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_centDep_80_100.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_centDep_80_100.root");
    }
    if(doCent==2){
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_centDep_100_120.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_centDep_100_120.root");
    }
    // broken
    //fin1 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL1_centDep_80_100.root");
    //fin2 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL0_centDep_80_100.root");
  }
  else{
    // try to smear by 2 sigma
    //fin1 = new TFile("output/bFractionMerged_Smear2Sigma_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_Smear2Sigma_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    // with reg tracks in reco jets
    //fin1 = new TFile("output/bFractionMerged_regPFJets_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_regPFJets_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    if(do3bin){
      fin1 = new TFile("output/bFractionMerged_3bins_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
      fin2 = new TFile("output/bFractionMerged_3bins_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
    }
    else{
      fin1 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL1_bin_0_40_eta_0_2.root");
      fin2 = new TFile("output/bFractionMerged_SSVHEat2.0FixCL0_bin_0_40_eta_0_2.root");
      // old naming convention
    //fin1 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL1_bin_0_40_eta_0_2.root");
    //fin2 = new TFile("output/bFractionMerged_ssvHighEffat2.0FixCL0_bin_0_40_eta_0_2.root");

    }
  }

  TH1F *hBFractionMC = (TH1F*) fin1->Get("hBFractionMC");

  TH1F *hBFractionData = (TH1F*) fin1->Get("hBFractionData");
  TH1F *hBFractionDataLTJP = (TH1F*) fin1->Get("hBFractionDataLTJP");
  TH1F *hBFractionJPdirect = (TH1F*) fin1->Get("hBFractionJPdirect");

  TH1F *hBFractionDataFixC = (TH1F*) fin2->Get("hBFractionData");
  TH1F *hBFractionDataLTJPFixC = (TH1F*) fin2->Get("hBFractionDataLTJP");
  TH1F *hBFractionJPdirectFixC = (TH1F*) fin2->Get("hBFractionJPdirect");

  


  /*  --- correction due to Jet Energy Scale (calcul) ---
  correct(hBFractionMC);
  correct(hBFractionData);
  correct(hBFractionDataMoreC);
  correct(hBFractionDataLessC);
  correct(hBFractionDataLTJP);
  correct(hBFractionDataLTJPMoreC);
  correct(hBFractionDataLTJPLessC);
  correct(hBFractionJPdirect);
  correct(hBFractionJPdirectMoreC);
  correct(hBFractionJPdirectLessC);
  //*/

  //*  --- correction due to Jet Energy Scale (by hand) ---
  if(doCent){
    correctByCent(hBFractionMC,doCent);
    correctByCent(hBFractionData,doCent);
    correctByCent(hBFractionDataFixC,doCent);
    correctByCent(hBFractionDataLTJP,doCent);
    correctByCent(hBFractionDataLTJPFixC,doCent);
    correctByCent(hBFractionJPdirect,doCent);
    correctByCent(hBFractionJPdirectFixC,doCent);
  }
  else{
    //*
    correct2(hBFractionMC,do3bin);
    correct2(hBFractionData,do3bin);
    correct2(hBFractionDataFixC,do3bin);
    correct2(hBFractionDataLTJP,do3bin);
    correct2(hBFractionDataLTJPFixC,do3bin);
    correct2(hBFractionJPdirect,do3bin);
    correct2(hBFractionJPdirectFixC,do3bin);
    //*/
  }
  //*/

  //  --- plots with variation of charm ---


  TCanvas *cBFraction1 = new TCanvas("cBFraction1","b-jet fraction",600,600);
  hBFractionMC->SetLineColor(2);
  hBFractionMC->SetLineWidth(2);
  hBFractionMC->SetMarkerColor(2);
  //hBFractionMC->SetMarkerStyle(4);
  if(!doCent)hBFractionMC->SetAxisRange(80,200,"X");
  hBFractionMC->SetAxisRange(0,0.06,"Y");
  hBFractionMC->SetTitleOffset(1,"X");  
  hBFractionMC->GetYaxis()->SetTitle("b-jet fraction");;
  //hBFractionMC->Draw("e1"); 
  
  //hBFractionMC->GetYaxis()->SetNdivisions(505);
  
  TH1F *hBFractionMC_dummy= (TH1F*)hBFractionMC->Clone("hBFractionMC_dummy");
  hBFractionMC_dummy->SetLineWidth(0);
  hBFractionMC_dummy->SetLineColor(0);
  hBFractionMC_dummy->SetMarkerSize(0);
  hBFractionMC_dummy->Draw(); 
  //  hBFractionMC->Draw("hist"); 

  hBFractionData->SetMarkerStyle(8);
  hBFractionData->Draw("e1,same");  
  hBFractionDataLTJP->SetLineColor(kGreen-2); 
  hBFractionDataLTJP->SetMarkerColor(kGreen-2); 
  hBFractionDataLTJP->SetMarkerStyle(8); 
  hBFractionDataLTJP->Draw("e1,same");
  hBFractionJPdirect->SetMarkerStyle(8); 
  hBFractionJPdirect->SetMarkerColor(kBlue);
  hBFractionJPdirect->SetLineColor(kBlue);
  hBFractionJPdirect->Draw("e1,same");

  
  hBFractionDataFixC->SetLineStyle(2);
  //hBFractionDataFixC->Draw("e1same");   
  hBFractionDataLTJPFixC->SetLineColor(kGreen-2);
  hBFractionDataLTJPFixC->SetMarkerColor(kGreen-2);
  hBFractionDataLTJPFixC->SetMarkerStyle(4);
  hBFractionDataLTJPFixC->SetLineStyle(2);
  hBFractionDataLTJPFixC->Draw("e1same");
  hBFractionJPdirectFixC->SetLineStyle(2);
  //hBFractionJPdirectFixC->Draw("e1same");

  
  TLegend *legFrac1 = new TLegend(0.15,0.65,0.87,0.95);

  legFrac1->SetBorderSize(0);
  legFrac1->SetFillStyle(0);
  legFrac1->SetHeader("PbPb, #sqrt{s_{NN}} = 2.76 TeV");
  legFrac1->AddEntry(hBFractionDataLTJP,Form("SSVHE, LT method",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionDataLTJPFixC,Form("SSVHE, LT method, Floating Charm Norm.",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionData,Form("SSVHE, MC eff.",taggerName,workingPoint),"pl");
  legFrac1->AddEntry(hBFractionJPdirect,"Jet Probability","pl");
  //legFrac1->AddEntry(hBFractionMC,"MC Input (reconstructed)","l");

  legFrac1->Draw();




  //  --- plots of LT method with syst. uncertainty ---

  TCanvas *cBFraction2 = new TCanvas("cBFraction2","b-jet fraction",600,600);

  TH1F *hBFractionMC2 = hBFractionMC->Clone("hBFractionMC2");
  if(!doCent)hBFractionMC2->GetXaxis()->SetRangeUser(80,200);
  hBFractionMC2->SetMarkerSize(0);
  hBFractionMC2->SetMaximum(0.06);
  hBFractionMC2->SetMinimum(0.0);
  hBFractionMC2->Draw("hist");


  TGraphAsymmErrors *gBFractionMC2 = new TGraphAsymmErrors(hBFractionMC);
  if(!doCent){
    setMeanPt(gBFractionMC2,hBFractionMC,0,do3bin);
    gBFractionMC2->GetXaxis()->SetRangeUser(80,200);
  }



  TLatex *prel;
  if(doCent)prel= new TLatex(10,0.0615,"CMS preliminary");
  else prel= new TLatex(85,0.0615,"CMS preliminary");
  prel->Draw();

  TLatex *roots = new TLatex(147,0.0615,"#sqrt{s_{NN}} = 2.76 TeV");
  roots->Draw();

  if(!doCent){
    TLatex *csel = new TLatex(90,0.05,"Centrality 0-100%");
    csel->Draw();
  }
  TLatex *ptlabel;
  if(doCent==1) ptlabel= new TLatex(20,0.005,"80 < Jet p_{T} < 100 GeV/c");
  if(doCent==2) ptlabel= new TLatex(20,0.005,"100 < Jet p_{T} < 120 GeV/c");
  if(doCent)ptlabel->Draw();

  // to be precise we should evaluate mcStatErr for 3 bins seperately
  float mcStatErr[4] = {0.03,0.06,0.07,0.15};

  
  //TGraphAsymmErrors *gSyst = new TGraphAsymmErrors(3);
  TGraphErrors *gSyst;
  if(do3bin) gSyst= new TGraphErrors(3);
  else gSyst= new TGraphErrors(4);
  Double_t errCLratio, errMethod, totalSystErr;

  for(Int_t i=1;i<=hBFractionDataLTJP->GetNbinsX();i++) {
    gSyst->SetPoint(i-1,hBFractionDataLTJP->GetBinCenter(i),hBFractionDataLTJP->GetBinContent(i));
    cout<<" central value "<<hBFractionDataLTJP->GetBinContent(i)<<endl;
    errCLratio = abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionDataLTJPFixC->GetBinContent(i));
    errMethod = max(abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionData->GetBinContent(i)),abs(hBFractionDataLTJP->GetBinContent(i)-hBFractionJPdirect->GetBinContent(i)));
    double errJES = 0.14*hBFractionDataLTJP->GetBinContent(i);
    
    totalSystErr = norm(errCLratio,errMethod,errJES);
    gSyst->SetPointError(i-1,hBFractionDataLTJP->GetBinWidth(i)/2,totalSystErr);
    cout<<" sys error "<<totalSystErr<<endl;
    // add in MC template uncertainties
    float origStatErr = hBFractionDataLTJP->GetBinError(i);
    int statBin=i-1;
    if(doCent==1) statBin=0;
    if(doCent==2) statBin=1;
    float extraStatErr = mcStatErr[statBin]*hBFractionDataLTJP->GetBinContent(i);
    float totalStatErr = sqrt(origStatErr*origStatErr + extraStatErr*extraStatErr);
    hBFractionDataLTJP->SetBinError(i,totalStatErr);
    cout<<" total error "<<sqrt(totalSystErr*totalSystErr+totalStatErr*totalStatErr)<<endl;

  }

  gSyst->SetFillColor(5);
  gSyst->Draw("2");


  gBFractionMC2->Draw("Z,p,same");
  hBFractionMC2->Draw("hist,same");


  TGraphAsymmErrors *gBFractionDataLTJP2 = new TGraphAsymmErrors(hBFractionDataLTJP);
  if(!doCent)setMeanPt(gBFractionDataLTJP2,hBFractionDataLTJP,1,do3bin);
  gBFractionDataLTJP2->SetLineColor(1);
  gBFractionDataLTJP2->SetMarkerColor(1);
  gBFractionDataLTJP2->SetMarkerSize(1.5);
  gBFractionDataLTJP2->Draw("p,e1,same");


  TLegend *legFrac2 = new TLegend(0.2,0.15,0.8,0.34);
  if(doCent){
    legFrac2->SetX1(0.365);
    legFrac2->SetY1(0.657);
    legFrac2->SetX2(0.965);
    legFrac2->SetY2(0.848);
  }

  legFrac2->SetHeader("#int L dt = 150 #mub^{-1}");
  legFrac2->SetBorderSize(0);
  legFrac2->SetFillStyle(0);
  legFrac2->AddEntry(gBFractionDataLTJP2,"PbPb data","p");
  legFrac2->AddEntry(gBFractionMC2,"PYTHIA+HYDJET 1.8","lp");
  legFrac2->AddEntry(gSyst,"Exp. uncertainty","f");
  legFrac2->Draw();

 
  cBFraction2->RedrawAxis();

}
Пример #22
0
//void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfile="ROOTfiles/NPFitPP.root", TString outputfile="outfMasshisto/mass")
void fitD(TString collsyst="PbPb",TString nominalcut="", TString varname_="", Int_t varbins=10, Float_t varmin=0.5, Float_t varmax=2,TString vartex_="", Int_t isLarger_=1, TString npfit="0", TString outputfile="outfMasshisto/mass")
{
  _nominalcut = nominalcut;
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);
  gStyle->SetOptStat(0);
  gStyle->SetMarkerStyle(20);
  gStyle->SetMarkerSize(0.8);

  collisionsystem = collsyst;
  infname = outputfile;
  varname=varname_;
  vartex=vartex_;
  isLarger=isLarger_;

  //TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, float NPpar[]);
  TF1* fit(Float_t varval, Float_t ibin, Int_t isMC, TString npfit);
  //void getNPFnPar(TString npfname, float par[]);
  //float NPpar[2];
  //getNPFnPar(npfile, NPpar);
  //std::cout<<"NP parameter 0: "<<NPpar[0]<<std::endl;
  //std::cout<<"NP parameter 1: "<<NPpar[1]<<std::endl;
  
  Float_t varstep;
  if(varbins==1) varstep = 0.5;
  else varstep = (varmax-varmin)/(varbins-1);
  TH1F* hMCCut = new TH1F("hMCCut","",varbins,varmin,varmax+varstep);
  TH1F* hMCNoCut = new TH1F("hMCNoCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaCut = new TH1F("hDaCut","",varbins,varmin,varmax+varstep);
  TH1F* hDaNoCut = new TH1F("hDaNoCut","",varbins,varmin,varmax+varstep);
  for(float i=0;i<varbins+1;i++)
    {
      Float_t yield,yieldErr;
      Float_t ivar = varmin+(i-1)*varstep;
      //TF1* fMC = fit(ivar,i,1, NPpar);
      TF1* fMC = fit(ivar,i,1, npfit);
      yield = fMC->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fMC->Integral(minhisto,maxhisto)/binwidthmass*fMC->GetParError(0)/fMC->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hMCNoCut->SetBinContent(j+1,yield);
              hMCNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hMCCut->SetBinContent(i,yield);
          hMCCut->SetBinError(i,yieldErr);
        }
      //TF1* fDa = fit(ivar,i,0, NPpar);
      TF1* fDa = fit(ivar,i,0, npfit);
      yield = fDa->Integral(minhisto,maxhisto)/binwidthmass;
      yieldErr = fDa->Integral(minhisto,maxhisto)/binwidthmass*fDa->GetParError(0)/fDa->GetParameter(0);
      if(i==0)
        {
          for(int j=0;j<varbins;j++)
            {
              hDaNoCut->SetBinContent(j+1,yield);
              hDaNoCut->SetBinError(j+1,yieldErr);
            }
        }
      else
        {
          hDaCut->SetBinContent(i,yield);
          hDaCut->SetBinError(i,yieldErr);
        }
    }

  TCanvas* cMCRatio = new TCanvas("cMCRatio","",600,600);
  TH1F* hMCRatio = (TH1F*)hMCCut->Clone("hMCRatio");
  hMCRatio->SetTitle(Form(";%s;hMCRatio",vartex.Data()));
  hMCRatio->Divide(hMCNoCut);
  hMCRatio->Draw();

  TCanvas* cDaRatio = new TCanvas("cDaRatio","",600,600);
  TH1F* hDaRatio = (TH1F*)hDaCut->Clone("hDaRatio");
  hDaRatio->SetTitle(Form(";%s;hDaRatio",vartex.Data()));
  hDaRatio->Divide(hDaNoCut);
  hDaRatio->Draw();

  TCanvas* chDoubleRatio = new TCanvas("chDoubleRatio","",600,600);
  TH1F* hDoubleRatio = (TH1F*)hDaRatio->Clone("hDoubleRatio");
  hDoubleRatio->SetTitle(Form(";%s;hDoubleRatio",vartex.Data()));
  hDoubleRatio->Divide(hMCRatio);
  hDoubleRatio->Draw();

  Float_t aDoubleRatio[varbins],aDoubleRatioErr[varbins],aX[varbins],aZero[varbins];
  Float_t AbsMax = max(fabs(hDoubleRatio->GetMaximum()-1), fabs(hDoubleRatio->GetMinimum()-1));
  for(int i=0;i<varbins;i++)
    {
      aDoubleRatio[i] = hDoubleRatio->GetBinContent(i+1);
      aDoubleRatioErr[i] = hDoubleRatio->GetBinError(i+1);
      aX[i] = varmin+i*varstep;
      aZero[i] = 0;
    }
  TGraphErrors* gDoubleRatio = new TGraphErrors(varbins,aX,aDoubleRatio,aZero,aDoubleRatioErr);
  TH2F* hemptyDoubleRatio = new TH2F("hemptyDoubleRatio","",20,varmin-0.5*varstep,varmax+0.5*varstep,10.,0.,2.);
  hemptyDoubleRatio->GetXaxis()->SetTitle(Form("%s",vartex.Data()));
  hemptyDoubleRatio->GetYaxis()->SetTitle("(Yield^{Data}_{Cuts}/Yield^{Data}_{NoCuts})/(Yield^{MC}_{Cuts}/Yield^{MC}_{NoCuts})");
  hemptyDoubleRatio->GetXaxis()->SetTitleOffset(1.);
  hemptyDoubleRatio->GetYaxis()->SetTitleOffset(1.4);
  hemptyDoubleRatio->GetXaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetYaxis()->SetTitleSize(0.045);
  hemptyDoubleRatio->GetXaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetYaxis()->SetTitleFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetYaxis()->SetLabelFont(42);
  hemptyDoubleRatio->GetXaxis()->SetLabelSize(0.04);
  hemptyDoubleRatio->GetYaxis()->SetLabelSize(0.04);
  TLine* lDoubleRatio = new TLine(varmin-0.5*varstep, 1., varmax+0.5*varstep, 1.);
  lDoubleRatio->SetLineWidth(1);
  lDoubleRatio->SetLineStyle(7);
  lDoubleRatio->SetLineColor(1);
  TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
  texCms->SetNDC();
  texCms->SetTextAlign(12);
  texCms->SetTextSize(0.04);
  texCms->SetTextFont(42);
  TLatex* texCol = new TLatex(0.96,0.93, Form("%s #sqrt{s_{NN}} = 5.02 TeV",collisionsystem.Data()));
  texCol->SetNDC();
  texCol->SetTextAlign(32);
  texCol->SetTextSize(0.04);
  texCol->SetTextFont(42);
  TCanvas* cDoubleRatio = new TCanvas("cDoubleRatio","",600,600);
  hemptyDoubleRatio->Draw();
  gDoubleRatio->Draw("psame");
  lDoubleRatio->Draw();
  texCms->Draw();
  texCol->Draw();
  TLatex* texAbsMax = new TLatex(0.88,0.85, Form("max diff: %.3f",AbsMax));
  texAbsMax->SetNDC();
  texAbsMax->SetTextAlign(32);
  texAbsMax->SetTextSize(0.04);
  texAbsMax->SetTextFont(42);
  texAbsMax->Draw();
	
  cDoubleRatio->SaveAs(Form("plotRatios/%s_%s_DoubleRatio.pdf",collisionsystem.Data(),varname.Data()));

  TFile* outf = new TFile(Form("outfDoubleratio/f%s_%s_DoubleRatio.root",collisionsystem.Data(),varname.Data()),"recreate");
  outf->cd();
  hDoubleRatio->Write();
  outf->Close();
}
Пример #23
0
// --------------------------------- //
void ClosureTest()
{
   setTDRStyle();
   gROOT->ForceStyle();

   // input files
   // TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureSecondHalf_v2.root", "READ");

   /* TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneEE3C_Flat_herwigpp_final_nominal_v2.root", "READ");
      TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureFirstHalf_v2.root", "READ");*/

   /*TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneEE3C_Flat_herwigpp_final_nominal_v4.root", "READ");
     TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_nominal_v4.root", "READ");*/

   //TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final.root", "READ");

   TFile* mc_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureFirstHalf_NotSmeared_v4.root", "READ");
     TFile* mc_smeared_file = new TFile("/afs/desy.de/user/k/kheine/zunzuncito/zz-out/MC_QCD_Pt-15to3000_TuneZ2_Flat_final_ClosureSecondHalf_Smeared_v4.root", "READ");

   TString suffix = "_PythiaSmearedVsPythia_v4";
   // TString suffix = "_HerwigVsPythia";
   // TString suffix = "_PythiaVsHerwig_v4";

 
   // define helper histos
   TH1F *tmp_mcsmeared = new TH1F();
   TH1F *tmp_mc = new TH1F();
   TH1F *tmp_gensmeared = new TH1F();
   TH1F *tmp_gen = new TH1F();
   tmp_mcsmeared->Sumw2();
   tmp_mc->Sumw2();
   tmp_gensmeared->Sumw2();
   tmp_gen->Sumw2();
 
   std::vector<float> alpha;
   alpha.push_back(0.1); 
   alpha.push_back(0.125); 
   alpha.push_back(0.15); 
   alpha.push_back(0.175); 
   alpha.push_back(0.20); 
   alpha.push_back(0.225);
   alpha.push_back(0.25); 
      
   float pt_bins[14] = {62, 107, 175, 205, 242, 270, 310, 335, 379, 410, 467, 600, 1000, 2000};
   // float eta_bins[6] = {0, 0.5, 1.1, 1.7, 2.3, 5.0};
   float eta_bins[8] = {0, 0.5, 1.1, 1.7, 2.3, 2.8, 3.2, 5.0};
   TH1F *extrapolated_mcsmeared = new TH1F("extrapolated_mcsmeared", "extrapolated_mcsmeared", 13, pt_bins);
   TH1F *extrapolated_mc = new TH1F("extrapolated_mc", "extrapolated_mc", 13, pt_bins);
   TH1F *extrapolated_gen = new TH1F("extrapolated_gen", "extrapolated_gen", 13, pt_bins);
   TH1F *extrapolated_mcsmeared_with_pli = new TH1F("extrapolated_mcsmeared_with_pli", "extrapolated_mcsmeared", 13, pt_bins);
   TH1F *extrapolated_mc_with_pli = new TH1F("extrapolated_mc_with_pli", "extrapolated_mc", 13, pt_bins);

   TH1F* RatioVsEta = new TH1F("RatioVsEta", "", 7, eta_bins);
   TH1F* RatioVsEta_with_pli = new TH1F("RatioVsEta_with_pli", "", 7, eta_bins);
   extrapolated_mcsmeared->Sumw2();
   extrapolated_mc->Sumw2();
   extrapolated_gen->Sumw2();
   extrapolated_mcsmeared_with_pli->Sumw2();
   extrapolated_mc_with_pli->Sumw2();
 
   RatioVsEta->Sumw2();
   RatioVsEta_with_pli->Sumw2();

   // how much should be truncated?
   double yq_IQW[2],xq_IQW[2];
   xq_IQW[0] = 0.0;
   xq_IQW[1] = 0.985;
   
   //// get asymmetry histos
   for(int ieta=0; ieta < 5; ++ieta){
      //  cout << "eta Bin: " << ieta << endl;

      extrapolated_mcsmeared->Reset();
      extrapolated_mc->Reset();
      extrapolated_gen->Reset();
      extrapolated_mcsmeared_with_pli->Reset();
      extrapolated_mc_with_pli->Reset();
    
      for(int ipt=0; ipt < 13; ++ipt){     
         //  cout << "pt Bin: " << ipt << endl;
         std::vector<double> x,x_e,MCy,MCy_e,Datay,Datay_e,Geny,Geny_e;

         for(int ialpha=0; ialpha < 7; ++ialpha){
         //for(int ialpha=0; ialpha < 3; ++ialpha){
            //  cout << "alpha Bin: " << ialpha << endl;
            TString hname = Form("Pt%i_eta%i_alpha%i", ipt, ieta, ialpha);
            TString hname_gen = Form("GenAsymm_Pt%i_eta%i_alpha%i", ipt, ieta, ialpha);

            //  cout << "hname: " << hname << endl;

            mc_file->cd();
            tmp_mc = 0;
            tmp_gen = 0;
            tmp_mc = (TH1F*) gDirectory->FindObjectAny(hname);
            tmp_gen = (TH1F*) gDirectory->FindObjectAny(hname_gen);

            mc_smeared_file->cd();
            tmp_mcsmeared = 0;
            tmp_gensmeared = 0;
            tmp_mcsmeared = (TH1F*) gDirectory->FindObjectAny(hname);
            tmp_gensmeared = (TH1F*) gDirectory->FindObjectAny(hname_gen);
                               
            x.push_back(alpha.at(ialpha));
            x_e.push_back(0.);

            double mc_width = GetAsymmWidth(tmp_mc, xq_IQW, yq_IQW);
            double mc_width_err = GetAsymmWidth(tmp_mc, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_mc->GetEffectiveEntries()));
            double data_width = GetAsymmWidth(tmp_mcsmeared, xq_IQW, yq_IQW);
            double data_width_err = GetAsymmWidth(tmp_mcsmeared, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_mcsmeared->GetEffectiveEntries()));
            double gen_width = GetAsymmWidth(tmp_gen, xq_IQW, yq_IQW);
            double gen_width_err = GetAsymmWidth(tmp_gen, xq_IQW, yq_IQW)/(TMath::Sqrt(2*tmp_gen->GetEffectiveEntries()));

            MCy.push_back( mc_width );
            MCy_e.push_back( mc_width_err );
            Datay.push_back( data_width );
            Datay_e.push_back( data_width_err );
            Geny.push_back( gen_width );
            Geny_e.push_back( gen_width_err );

            tmp_mc->Scale(tmp_mcsmeared->Integral()/tmp_mc->Integral());
            tmp_gen->Scale(tmp_gensmeared->Integral()/tmp_gen->Integral());

            // draw asymmetry histos
            TCanvas *c5 = new TCanvas("c5", "", 600, 600);
            c5->SetLogy();
            //  tmp_mc->GetYaxis()->SetRangeUser(0.1, 100.*tmp_mc->GetMaximum());
            // tmp_mc->GetXaxis()->SetTitle("(p_{T,1} - p_{T,2})/(p_{T,1} + p_{T,2})");
            tmp_mc->GetXaxis()->SetTitle("|A|");
            tmp_mc->GetYaxis()->SetTitle("Events");
            tmp_mc->SetLineColor(30);
            //  tmp_mc->SetFillColor(30);
            tmp_mc->Rebin(10);
            tmp_mc->Draw("hist");
            //   gauss_mc->Draw("same");
            tmp_mcsmeared->Rebin(10);
            tmp_mcsmeared->SetMarkerStyle(20);
            tmp_mcsmeared->Draw("histsame");
          
            TPaveText *label = util::LabelFactory::createPaveTextWithOffset(3,0.8,0.01);
            label->AddText("Anti-k_{T} (R=0.5) PFCHS Jets");
            label->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq  p_{T}^{ave} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
            label->AddText( Form("#alpha #leq %0.3f", alpha.at(ialpha)) );
            label->Draw("same");
            
            TLegend* leg1 = util::LabelFactory::createLegendColWithOffset(2,0.65,0.2);
            leg1->AddEntry(tmp_mcsmeared,"Herwig","L");
            leg1->AddEntry(tmp_mc,"Pythia","L");
            leg1->Draw();

            if(ieta == 0 && ipt == 0 && ialpha == 0 ) c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps(");
            else if(ieta == 4 && ipt == 12 && ialpha == 6) c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps)");
            else c5->Print("ClosureTest/AsymmHistos" + suffix + ".eps"); 

            // draw gen-asymmetry histos
            TCanvas *c5b = new TCanvas("c5b", "", 600, 600);
            c5b->SetLogy();
            //  tmp_gen->GetYaxis()->SetRangeUser(0.1, 100.*tmp_gen->GetMaximum());
            // tmp_gen->GetXaxis()->SetTitle("(p_{T,1} - p_{T,2})/(p_{T,1} + p_{T,2})");
            tmp_gen->GetXaxis()->SetTitle("|A_{gen}|");
            tmp_gen->GetYaxis()->SetTitle("Events");
            tmp_gen->SetLineColor(30);
            //  tmp_gen->SetFillColor(30);
            tmp_gen->Rebin(10);
            tmp_gen->Draw("hist");
            //   gauss_gen->Draw("same");
            tmp_gensmeared->Rebin(10);
            tmp_gensmeared->SetMarkerStyle(20);
            tmp_gensmeared->Draw("histsame");
          
            TPaveText *label2 = util::LabelFactory::createPaveTextWithOffset(3,0.8,0.01);
            label2->AddText("Anti-k_{T} (R=0.5) PFCHS Jets");
            label2->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq  p_{T}^{ave} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
            label2->AddText( Form("#alpha #leq %0.3f", alpha.at(ialpha)) );
            label2->Draw("same");
            
            TLegend* leg2 = util::LabelFactory::createLegendColWithOffset(2,0.65,0.2);
            leg2->AddEntry(tmp_gensmeared,"Herwig","L");
            leg2->AddEntry(tmp_gen,"Pythia","L");
            leg2->Draw();

            if(ieta == 0 && ipt == 0 && ialpha == 0 ) c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps(");
            else if(ieta == 4 && ipt == 12 && ialpha == 6) c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps)");
            else c5b->Print("ClosureTest/GenAsymmHistos" + suffix + ".eps"); 
         }

         // Covariance matrices needed for fitting 
         TMatrixD y_cov_mc;
         TMatrixD y_cov_data;
         TMatrixD y_cov_gen;
         y_cov_mc.ResizeTo(alpha.size(), alpha.size());
         y_cov_data.ResizeTo(alpha.size(), alpha.size());
         y_cov_gen.ResizeTo(alpha.size(), alpha.size());

         // fill covariance matrix for data and mc
         for(int ialpha=0; ialpha < alpha.size(); ++ialpha){
            for (Int_t jalpha =0; jalpha < alpha.size(); jalpha++){
               if( ialpha <= jalpha ) {
                  double n1_mc = pow(MCy.at(ialpha),2)/(2*pow(MCy_e.at(ialpha),2));
                  double n2_mc = pow(MCy.at(jalpha),2)/(2*pow(MCy_e.at(jalpha),2));
          
                  double n1_data = pow(Datay.at(ialpha),2)/(2*pow(Datay_e.at(ialpha),2));
                  double n2_data = pow(Datay.at(jalpha),2)/(2*pow(Datay_e.at(jalpha),2));

                  double n1_gen = pow(Geny.at(ialpha),2)/(2*pow(Geny_e.at(ialpha),2));
                  double n2_gen = pow(Geny.at(jalpha),2)/(2*pow(Geny_e.at(jalpha),2));

                  y_cov_mc(ialpha, jalpha) = pow(MCy_e.at(ialpha),2) * pow((n1_mc/n2_mc),2)*
                     (MCy.at(ialpha)/MCy.at(jalpha));
                  y_cov_data(ialpha, jalpha) = pow(Datay_e.at(ialpha),2) * pow((n1_data/n2_data),2)*
                     (Datay.at(ialpha)/Datay.at(jalpha));  
                  y_cov_gen(ialpha, jalpha) = pow(Geny_e.at(ialpha),2) * pow((n1_gen/n2_gen),2)*
                     (Geny.at(ialpha)/Geny.at(jalpha));  
               }
               else {
                  double n1_mc = pow(MCy.at(jalpha),2)/(2*pow(MCy_e.at(jalpha),2));
                  double n2_mc = pow(MCy.at(ialpha),2)/(2*pow(MCy_e.at(ialpha),2));

                  double n1_data = pow(Datay.at(jalpha),2)/(2*pow(Datay_e.at(jalpha),2));
                  double n2_data = pow(Datay.at(ialpha),2)/(2*pow(Datay_e.at(ialpha),2));

                  double n1_gen = pow(Geny.at(jalpha),2)/(2*pow(Geny_e.at(jalpha),2));
                  double n2_gen = pow(Geny.at(ialpha),2)/(2*pow(Geny_e.at(ialpha),2));

                  y_cov_mc(ialpha, jalpha) = pow(MCy_e.at(jalpha),2) * pow((n1_mc/n2_mc),2)*
                     (MCy.at(jalpha)/MCy.at(ialpha));
                  y_cov_data(ialpha, jalpha) = pow(Datay_e.at(jalpha),2) * pow((n1_data/n2_data),2)*
                     (Datay.at(jalpha)/Datay.at(ialpha));
                  y_cov_gen(ialpha, jalpha) = pow(Geny_e.at(jalpha),2) * pow((n1_gen/n2_gen),2)*
                     (Geny.at(jalpha)/Geny.at(ialpha));
               }
            }
         }        
  
         //create TGraphErrors from previously defined vectors
         TGraphErrors *extrapol_MC = new TGraphErrors(alpha.size(),&x[0],&MCy[0],&x_e[0],&MCy_e[0]);
         TGraphErrors *extrapol_Data = new TGraphErrors(alpha.size(),&x[0],&Datay[0],&x_e[0],&Datay_e[0]);
         TGraphErrors *extrapol_Gen = new TGraphErrors(alpha.size(),&x[0],&Geny[0],&x_e[0],&Geny_e[0]);
 
         // fit linear extrapolation function
         TF1 *lin_extrapol_mc = new TF1("lin_extrapol_mc","[0]+[1]*x",0,alpha.back()+0.05); 
         TF1 *lin_extrapol_data = new TF1("lin_extrapol_data","[0]+[1]*x",0,alpha.back()+0.05);
         TF1 *lin_extrapol_gen = new TF1("lin_extrapol_gen","[0]+[1]*x",0,alpha.back()+0.05);
                  
         //fit extrapolation function to the TGraphErrors for data and MC  
         // extrapol_MC->Fit("lin_extrapol_mc","Q","same",0,alpha.back()+0.05);
         //  extrapol_Data->Fit("lin_extrapol_data","Q","same",0,alpha.back()+0.05);
                 
         // fit mc
         data.reset();
         data.x_val = x;
         data.y_val = MCy;
         data.y_cov.ResizeTo(alpha.size(), alpha.size());
         data.y_cov = y_cov_mc;
         data.CheckPoints();
         
         // choose start values for MC fit
         double slope = (MCy.at(MCy.size()-1) - MCy.at(MCy.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4));
         double d_slope = slope;
         double offset = MCy.at(MCy.size()-1) - (slope*x.at(x.size()-1));
         double d_offset = offset;
             
         std::cout << "MC start values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         make_lin_fit(slope, d_slope, offset, d_offset);
         std::cout << "MC fit values: " << "slope: " << slope << " offset: " << offset << std::endl; 

         lin_extrapol_mc->SetParameter(0, offset);
         lin_extrapol_mc->SetParError(0, d_offset);
         lin_extrapol_mc->SetParameter(1, slope);
         lin_extrapol_mc->SetParError(1, d_slope);
         extrapol_MC->GetListOfFunctions()->Add(lin_extrapol_mc);
         
         data.reset();
         
         // fit data
         data.x_val = x;
         data.y_val = Datay;
         data.y_cov.ResizeTo(alpha.size(), alpha.size());
         data.y_cov = y_cov_data;
         data.CheckPoints();
         
         // choose start values for data fit
         slope = (Datay.at(Datay.size()-1) - Datay.at(Datay.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4));
         d_slope = slope;
         offset = Datay.at(Datay.size()-1) - (slope*x.at(x.size()-1));
         d_offset = offset;
            
         std::cout << "Data start values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         make_lin_fit(slope, d_slope, offset, d_offset);
         std::cout << "Data fit values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         
         lin_extrapol_data->SetParameter(0, offset);
         lin_extrapol_data->SetParError(0, d_offset);
         lin_extrapol_data->SetParameter(1, slope);
         lin_extrapol_data->SetParError(1, d_slope);
         extrapol_Data->GetListOfFunctions()->Add(lin_extrapol_data);
         
         data.reset();

         // fit gen
         data.x_val = x;
         data.y_val = Geny;
         data.y_cov.ResizeTo(alpha.size(), alpha.size());
         data.y_cov = y_cov_gen;
         data.CheckPoints();
         
         // choose start values for gen fit
         slope = (Geny.at(Geny.size()-1) - Geny.at(Geny.size()-4))/(x.at(x.size()-1) - x.at(x.size()-4));
         d_slope = slope;
         offset = Geny.at(Geny.size()-1) - (slope*x.at(x.size()-1));
         d_offset = offset;
            
         std::cout << "Gen start values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         make_lin_fit(slope, d_slope, offset, d_offset);
         std::cout << "Gen fit values: " << "slope: " << slope << " offset: " << offset << std::endl; 
         
         lin_extrapol_gen->SetParameter(0, offset);
         lin_extrapol_gen->SetParError(0, d_offset);
         lin_extrapol_gen->SetParameter(1, slope);
         lin_extrapol_gen->SetParError(1, d_slope);
         extrapol_Gen->GetListOfFunctions()->Add(lin_extrapol_gen);
         
         data.reset();

         // draw extrapolations data + mc
         TCanvas *c = new TCanvas("c","",600,600);
         std::pair <float,float> minMaxPair = determineMinMax(extrapol_Data);
         c->DrawFrame(0,minMaxPair.first*0.5-0.05,alpha.back()+0.05,minMaxPair.second*1.47,(";Threshold #alpha_{max};#sigma_{A}"));
         extrapol_MC->SetMarkerStyle(20);
         extrapol_MC->SetMarkerColor(kRed+1);
         extrapol_MC->SetLineColor(kRed+1);
         extrapol_MC->Draw("P");
         extrapol_Data->SetMarkerStyle(20);
         extrapol_Data->SetMarkerColor(kBlack);
         extrapol_Data->SetLineColor(kBlack);
         extrapol_Data->Draw("Psame");
         TF1* MCTemp = new TF1();
         TF1* DataTemp = new TF1();
         extrapol_MC->GetFunction("lin_extrapol_mc")->SetLineColor(kRed+1);
         extrapol_MC->GetFunction("lin_extrapol_mc")->SetLineStyle(2);
         extrapol_Data->GetFunction("lin_extrapol_data")->SetLineColor(kBlack);
         extrapol_Data->GetFunction("lin_extrapol_data")->SetLineStyle(2);
         MCTemp=(TF1*) extrapol_MC->GetFunction("lin_extrapol_mc")->Clone();
         DataTemp=(TF1*) extrapol_Data->GetFunction("lin_extrapol_data")->Clone();
         MCTemp->SetRange(0.1,1);
         MCTemp->SetLineStyle(1);
         MCTemp->Draw("same");
         DataTemp->SetRange(0.1,1);
         DataTemp->SetLineStyle(1);
         DataTemp->Draw("same");
       
         TPaveText *label = util::LabelFactory::createPaveTextWithOffset(2,1.0,0.5);
         label->AddText("Anti-k_{T} (R=0.5) PFchs Jets");
         label->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq #bar{ p}_{T} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
         label->Draw("same");
  
         TLegend* leg1 = util::LabelFactory::createLegendWithOffset(2,0.6);
         leg1->AddEntry(extrapol_Data,"Extrapolation (MC smeared)","LP");
         leg1->AddEntry(extrapol_MC,"Extrapolation (MC)","LP");

         leg1->Draw();
         cmsPrel(-1, false , 8);

         TString name;
         name = Form("ClosureTest/Extrapol_Eta%i_pt%i" + suffix + ".eps", ieta, ipt);
         c->Print(name);

         TCanvas *cb = new TCanvas("c","",600,600);
         std::pair <float,float> minMaxPair2 = determineMinMax(extrapol_Data);
         cb->DrawFrame(0,minMaxPair2.first*0.5-0.05,alpha.back()+0.05,minMaxPair2.second*1.47,(";Threshold #alpha_{max, gen};#sigma_{A, gen}"));
         extrapol_Gen->SetMarkerStyle(20);
         extrapol_Gen->SetMarkerColor(kBlue+1);
         extrapol_Gen->SetLineColor(kBlue+1);
         extrapol_Gen->Draw("P");
         TF1* GenTemp = new TF1();
         extrapol_Gen->GetFunction("lin_extrapol_gen")->SetLineColor(kBlue+1);
         extrapol_Gen->GetFunction("lin_extrapol_gen")->SetLineStyle(2);
         GenTemp=(TF1*) extrapol_Gen->GetFunction("lin_extrapol_gen")->Clone();
         GenTemp->SetRange(0.1,1);
         GenTemp->SetLineStyle(1);
         GenTemp->Draw("same");

         TPaveText *label2 = util::LabelFactory::createPaveTextWithOffset(2,1.0,0.05);
         label2->AddText("Anti-k_{T} (R=0.5) PFchs Jets");
         label2->AddText( Form("%0.1f #leq |#eta| #leq %0.1f, %3.0f #leq #bar{ p}_{T} [GeV] #leq %3.0f", eta_bins[ieta], eta_bins[ieta+1], pt_bins[ipt], pt_bins[ipt+1]) );
         label2->Draw("same");
  
         TLegend* leg2 = util::LabelFactory::createLegendWithOffset(2,0.15);
         leg2->AddEntry(extrapol_Gen,"Extrapolation (PLI)","LP");

         leg2->Draw();
         cmsPrel(-1, false , 8);

         TString name2;
         name2 = Form("ClosureTest/Extrapol_Eta%i_pt%i_gen" + suffix + ".eps", ieta, ipt);
         cb->Print(name2);

         float par_data = lin_extrapol_data->GetParameter(0);
         float par_data_err = lin_extrapol_data->GetParError(0);
         float par_mc = lin_extrapol_mc->GetParameter(0);
         float par_mc_err = lin_extrapol_mc->GetParError(0);
         float par_gen = lin_extrapol_gen->GetParameter(0);
         float par_gen_err = lin_extrapol_gen->GetParError(0);
       
         cout << "ieta : " << ieta << "  ipt : " << ipt << endl;
         cout << "Parameter data: " << par_data << endl;
         cout << "Parameter error data: " << par_data_err << endl;
         cout << "Parameter mc: " << par_mc << endl;
         cout << "Parameter error mc: " << par_mc_err << endl;
         cout << "Parameter gen: " << par_gen << endl;
         cout << "Parameter error gen: " << par_gen_err << endl;

         extrapolated_mcsmeared->SetBinContent(ipt+1, par_data);
         extrapolated_mcsmeared->SetBinError(ipt+1, par_data_err);
         extrapolated_mc->SetBinContent(ipt+1, par_mc);
         extrapolated_mc->SetBinError(ipt+1, par_mc_err);   
         extrapolated_gen->SetBinContent(ipt+1, par_gen);
         extrapolated_gen->SetBinError(ipt+1, par_gen_err);    

         float par_data_pli_corr = 0;
         float par_data_pli_corr_err = 0;
         float par_mc_pli_corr = 0;
         float par_mc_pli_corr_err = 0;

         if(par_gen > 0 && par_data > 0 && par_mc > 0 && par_data > par_gen && par_mc > par_gen) {
            par_data_pli_corr = TMath::Sqrt(pow(par_data,2) - pow(par_gen,2));
            par_data_pli_corr_err = TMath::Sqrt( pow(par_data,2)/(pow(par_data,2) - pow(par_gen,2)) * pow(par_data_err,2) +  pow(par_gen,2)/(pow(par_data,2) - pow(par_gen,2)) * pow(par_gen_err,2));
            par_mc_pli_corr = TMath::Sqrt(pow(par_mc,2) - pow(par_gen,2));
            par_mc_pli_corr_err = TMath::Sqrt( pow(par_mc,2)/(pow(par_mc,2) - pow(par_gen,2)) * pow(par_mc_err,2) +  pow(par_gen,2)/(pow(par_mc,2) - pow(par_gen,2)) * pow(par_gen_err,2));
         }
            
         extrapolated_mcsmeared_with_pli->SetBinContent(ipt+1, par_data_pli_corr);
         extrapolated_mcsmeared_with_pli->SetBinError(ipt+1, par_data_pli_corr_err);
         extrapolated_mc_with_pli->SetBinContent(ipt+1, par_mc_pli_corr);
         extrapolated_mc_with_pli->SetBinError(ipt+1, par_mc_pli_corr_err);

         cout << "Parameter data after pli: " << par_data_pli_corr << endl;
         cout << "Parameter error data after pli: " << par_data_pli_corr_err << endl;
         cout << "Parameter mc after pli: " << par_mc_pli_corr << endl;
         cout << "Parameter error mc after pli: " << par_mc_pli_corr_err << endl;
      }

      // --------------------------------------- //
      // calc data/mc ratio and fit with constant
      TH1F* ratio = new TH1F(*extrapolated_mc);
      TH1F* ratio_with_pli = new TH1F(*extrapolated_mc);
      ratio->Divide(extrapolated_mcsmeared, extrapolated_mc, 1, 1);
      ratio_with_pli->Divide(extrapolated_mcsmeared_with_pli, extrapolated_mc_with_pli, 1, 1);
    
      TF1 *fit_const = new TF1("fit_const", "[0]", ratio->GetXaxis()->GetXmin(), ratio->GetXaxis()->GetXmax());
      fit_const->SetParameters(0, 1.1);
      fit_const->SetParName(0, "const");
      ratio->Fit("fit_const", "", "same");
      ratio->GetXaxis()->SetTitle("#bar{ p}_{T} [GeV]");
      ratio->GetYaxis()->SetRangeUser(0.7, 1.4);
      ratio->GetYaxis()->SetTitle("MC_{smeared}/MC ratio (const fit)");

      RatioVsEta->SetBinContent(ieta+1, ratio->GetFunction("fit_const")->GetParameter(0));
      RatioVsEta->SetBinError(ieta+1, ratio->GetFunction("fit_const")->GetParError(0));

      TCanvas *c3 = new TCanvas("c3","",600,600);
      c3->SetLogx();
      ratio->Draw();
      TString name3;
      name3 = Form("ClosureTest/ExtrapolRatio_Eta%i" + suffix + ".eps", ieta);
      c3->Print(name3);

      ratio_with_pli->Fit("fit_const", "", "same");
      ratio_with_pli->GetXaxis()->SetTitle("#bar{ p}_{T} [GeV]");
      ratio_with_pli->GetYaxis()->SetRangeUser(0.7, 1.4);
      ratio_with_pli->GetYaxis()->SetTitle("MC_{smeared}/MC ratio (const fit)");
    
      TCanvas *c3b = new TCanvas("c3","",600,600);
      c3b->SetLogx();
      ratio_with_pli->Draw();
      TString name4;
      name4 = Form("ClosureTest/ExtrapolRatio_Eta%i_with_pli" + suffix + ".eps", ieta);
      c3b->Print(name4);

      RatioVsEta_with_pli->SetBinContent(ieta+1, ratio_with_pli->GetFunction("fit_const")->GetParameter(0));
      RatioVsEta_with_pli->SetBinError(ieta+1, ratio_with_pli->GetFunction("fit_const")->GetParError(0));

   }

   // draw data/mc scaling factors vs. eta
   TCanvas *c4 = new TCanvas();
   RatioVsEta->GetYaxis()->SetRangeUser(0.7, 1.3);
   RatioVsEta->GetXaxis()->SetTitle("|#eta|");
   RatioVsEta->GetYaxis()->SetTitle("MC_{smeared} /MC ratio (const fit)");
   RatioVsEta->Draw();
   c4->Print("ClosureTest/ScalingFactorsVsEta" + suffix + ".eps");

   cout << "//----------------------------------------------//" << endl;
   cout << "Scaling factors without PLI: " << endl;
   cout << "Ratio eta1: " << RatioVsEta->GetBinContent(1) << " +- " << RatioVsEta->GetBinError(1) << endl;
   cout << "Ratio eta2: " << RatioVsEta->GetBinContent(2) << " +- " << RatioVsEta->GetBinError(2) << endl;
   cout << "Ratio eta3: " << RatioVsEta->GetBinContent(3) << " +- " << RatioVsEta->GetBinError(3) << endl;
   cout << "Ratio eta4: " << RatioVsEta->GetBinContent(4) << " +- " << RatioVsEta->GetBinError(4) << endl;
   cout << "Ratio eta5: " << RatioVsEta->GetBinContent(5) << " +- " << RatioVsEta->GetBinError(5) << endl;
   cout << "Ratio eta6: " << RatioVsEta->GetBinContent(6) << " +- " << RatioVsEta->GetBinError(6) << endl;
   cout << "Ratio eta7: " << RatioVsEta->GetBinContent(7) << " +- " << RatioVsEta->GetBinError(7) << endl;
   cout << "//----------------------------------------------//" << endl;

   TCanvas *c4b = new TCanvas();
   RatioVsEta_with_pli->GetYaxis()->SetRangeUser(0.7, 1.4);
   RatioVsEta_with_pli->GetXaxis()->SetTitle("|#eta|");
   RatioVsEta_with_pli->GetYaxis()->SetTitle("MC_{smeared} /MC ratio (const fit)");
   RatioVsEta_with_pli->Draw();
   c4b->Print("ClosureTest/ScalingFactorsVsEta_with_pli" + suffix + ".eps");

   cout << "//----------------------------------------------//" << endl;
   cout << "Scaling factors with PLI: " << endl;
   cout << "Ratio eta1: " << RatioVsEta_with_pli->GetBinContent(1) << " +- " << RatioVsEta_with_pli->GetBinError(1) << endl;
   cout << "Ratio eta2: " << RatioVsEta_with_pli->GetBinContent(2) << " +- " << RatioVsEta_with_pli->GetBinError(2) << endl;
   cout << "Ratio eta3: " << RatioVsEta_with_pli->GetBinContent(3) << " +- " << RatioVsEta_with_pli->GetBinError(3) << endl;
   cout << "Ratio eta4: " << RatioVsEta_with_pli->GetBinContent(4) << " +- " << RatioVsEta_with_pli->GetBinError(4) << endl;
   cout << "Ratio eta5: " << RatioVsEta_with_pli->GetBinContent(5) << " +- " << RatioVsEta_with_pli->GetBinError(5) << endl;
   cout << "Ratio eta6: " << RatioVsEta_with_pli->GetBinContent(6) << " +- " << RatioVsEta_with_pli->GetBinError(6) << endl;
   cout << "Ratio eta7: " << RatioVsEta_with_pli->GetBinContent(7) << " +- " << RatioVsEta_with_pli->GetBinError(7) << endl;
   cout << "//----------------------------------------------//" << endl;

}
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;
}
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;
}
Пример #26
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();
}
Пример #27
0
void drawFigure4a(TString var="Njets") 
{
  gInterpreter->ExecuteMacro("GoodStyle.C");
  gROOT->LoadMacro("tdrstyle.C");                                                                                                                           
  setTDRStyle();    

  TString variable = "p_{T,max}^{#font[12]{l}}";
  std::ostringstream filename, madname;
  filename<<"rootfiles/all_unfolding_"<<var<<".root";
  TFile* file = new TFile(filename.str().c_str(), "read");
  madname<<"hGenXs"<<var<<"_1";
  std::cout<<madname.str().c_str()<<std::endl;
  TH1F* xsValue          = (TH1F*)(file->Get("hComb_diff")->Clone("xsValue"));
  TH1F* xsValue_Madgraph = (TH1F*)(file->Get(madname.str().c_str())->Clone("xsValue_Madgraph"));
  TH1F* xsValue_MCnlo    = (TH1F*)(file->Get("mcfm_tot")->Clone("xsValue_MCnlo"));

  // Set the data errors- I don't need this because I already have complete error in my plot
  //----------------------------------------------------------------------------
  
  // Data cosmetics
  //----------------------------------------------------------------------------
  xsValue->SetLineWidth(1);
  xsValue->SetMarkerSize(_msize);
  xsValue->SetMarkerStyle(kFullCircle);
  xsValue->SetMarkerColor(kBlack);
  xsValue->SetLineColor(kBlack);
  xsValue->SetFillStyle(1001);
  xsValue->SetFillColor(kWhite);
  // Madgraph cosmetics
  //----------------------------------------------------------------------------
  xsValue_Madgraph->SetFillColor(kOrange);
  //xsValue_Madgraph->SetFillColor(kWhite);
  xsValue_Madgraph->SetFillStyle(1001);
  xsValue_Madgraph->SetLineColor(kOrange+7);
  xsValue_Madgraph->SetLineWidth(1);
  xsValue_Madgraph->SetMarkerColor(kOrange+7);
  xsValue_Madgraph->SetMarkerSize(_msize);
  xsValue_Madgraph->SetMarkerStyle(21);


  // MCNLO cosmetics
  //----------------------------------------------------------------------------
  xsValue_MCnlo->SetFillColor(kAzure-9);
   //xsValue_MCnlo->SetFillColor(kWhite);
  xsValue_MCnlo->SetFillStyle(1001);
  xsValue_MCnlo->SetLineColor(kAzure);
  xsValue_MCnlo->SetLineWidth(1);
  xsValue_MCnlo->SetMarkerColor(kAzure);
  xsValue_MCnlo->SetMarkerSize(_msize);
  //  xsValue_MCnlo->SetMarkerStyle(21);
  xsValue_MCnlo->SetMarkerStyle(24);

  //  TCanvas * c1=new TCanvas("c1", "c1");
  
//xsValue_MCnlo->Draw("pey0");
   

  // Set the canvas and pads
  //----------------------------------------------------------------------------
  TCanvas* canvas = new TCanvas("wwxs", "wwxs", 600, 600);
  //  TCanvas* canvas = new TCanvas("wwxs", "wwxs"); 

  //defalut
  //TCanvas* canvas = new TCanvas("wwxs", "wwxs", 600, 850);
  //  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.55, 1, 1.000);
  //TPad* pad2 = new TPad("pad2", "pad2", 0, 0.39, 1, 0.552);
  //TPad* pad3 = new TPad("pad3", "pad3", 0, 0.23, 1, 0.392);

  TPad* pad1 = new TPad("pad1", "pad1", 0, 0.49, 1, 1.000);
  TPad* pad2 = new TPad("pad2", "pad2", 0, 0.33, 1, 0.492);
  TPad* pad3 = new TPad("pad3", "pad3", 0, 0, 1, 0.332);
  
  pad1->SetTopMargin(0.09);
  pad2->SetTopMargin(0);
  pad3->SetTopMargin(0);

  pad1->SetBottomMargin(0);
  pad2->SetBottomMargin(0);
  //  pad3->SetBottomMargin(0.15);
  pad3->SetBottomMargin(0.45);

  pad1->SetLeftMargin(0.16);
  pad2->SetLeftMargin(0.16);
  pad3->SetLeftMargin(0.16);

  pad1->SetRightMargin(0.06);
  pad2->SetRightMargin(0.06);
  pad3->SetRightMargin(0.06);



  // pad1
  //----------------------------------------------------------------------------
  pad1->Draw();
  pad1->cd();
  pad1->SetLogy();


  // Draw
  //----------------------------------------------------------------------------
  AxisFonts(xsValue->GetXaxis(), variable + " (GeV)");
  if (var=="Zpt")
    AxisFonts(xsValue->GetYaxis(), "d#sigma(WZ#rightarrow3l#nu)/dp_{T}^{Z}");
  if (var=="LeadingJetPt")
    AxisFonts(xsValue->GetYaxis(), "d#sigma(WZ#rightarrow3l#nu)/dp_{T}^{LeadingJet}");
  
  //TH1F* hpowError = (TH1F*)xsValue_Powheg->Clone();
  //  TH1F* hmadError = (TH1F*)xsValue_Madgraph->Clone();
  //TH1F* hmcError  = (TH1F*)xsValue_MCnlo->Clone();

  xsValue         ->Draw("pe");
  xsValue_Madgraph->Draw("p,same");
  xsValue_MCnlo   ->Draw("p,same");

  xsValue->SetMinimum(1.1e-4);

 
  // Legend
  //----------------------------------------------------------------------------
  DrawLegend(0.718, 0.80, xsValue,   " Data",     "lp");
  DrawLegend(0.718, 0.74, xsValue_Madgraph, " Madgraph", "flp");  
  DrawLegend(0.718, 0.68, xsValue_MCnlo,  " MCFM",   "flp");


  // Draw text 
  //----------------------------------------------------------------------------
  DrawLatex(_cmsTextFont,   0.173, 0.935, 0.065, 11, "CMS");
  DrawLatex(_extraTextFont, 0.268, 0.935, 0.035, 11, "Preliminary");
  DrawLatex(_lumiTextFont,  0.940, 0.935, 0.050, 31, "19.6 fb^{-1} (8 TeV)");


  // Prepare the ratios
  //----------------------------------------------------------------------------
  TH1F* ratio_mad    = xsValue_Madgraph->Clone("ratio");
  TH1F* ratio_mcnlo  = xsValue_Madgraph->Clone("ratio");
  //  TH1F* ratio_mcnlo  = xsValue_MCnlo->Clone("ratio");
  TH1F* hratio_mad   = xsValue_Madgraph->Clone("ratio");
  TH1F* hratio_mcnlo = xsValue_MCnlo->Clone("ratio");
  TH1F* ratioErr     = xsValue->Clone("ratio");


  ratioErr->SetFillColor  (kGray+2);
  ratioErr->SetFillStyle  (   3004);
  ratioErr->SetLineColor  (kGray+2);
  ratioErr->SetMarkerColor(kGray+2);
  ratioErr->SetMarkerSize (      0);


  // Set the bin content
  //----------------------------------------------------------------------------
  for (UInt_t ibin=1; ibin<=ratio->GetNbinsX(); ibin++) {
   
    Double_t madValue = xsValue_Madgraph->GetBinContent(ibin);
    //Double_t madError = xsValue_Madgraph->GetBinError  (ibin);
   
    Double_t mcnloValue = xsValue_MCnlo->GetBinContent(ibin);
    //Double_t mcnloError = xsValue_MCnlo->GetBinError  (ibin);
   
    Double_t dataValue = xsValue->GetBinContent(ibin);
    
    Double_t dataError = xsValue->GetBinError(ibin);
   
    Double_t ratioValue_mad = (madValue > 0) ? madValue / dataValue : 0.0;
    //Double_t ratioError_mad = (madValue > 0) ? madError / dataValue : 0.0;
    Double_t ratioError_mad = madValue/pow(dataValue,2)*dataError;
    Double_t ratioValue_mcnlo = (mcnloValue > 0) ? mcnloValue / dataValue : 0.0;
    // Double_t ratioError_mcnlo = (mcnloValue > 0) ? mcnloError / dataValue : 0.0;
    Double_t ratioError_mcnlo = mcnloValue/pow(dataValue,2)*dataError;
   
    Double_t uncertaintyError = (dataValue > 0) ? dataError / dataValue : 0.0;
   
    ratio_mad ->SetBinContent(ibin, ratioValue_mad);
    hratio_mad->SetBinContent(ibin, ratioValue_mad);
    hratio_mad->SetBinError  (ibin, ratioError_mad);
   
    ratio_mcnlo ->SetBinContent(ibin, ratioValue_mcnlo);
    hratio_mcnlo->SetBinContent(ibin, ratioValue_mcnlo);
    hratio_mcnlo->SetBinError  (ibin, ratioError_mcnlo);
   
    ratioErr->SetBinContent(ibin, 1.0);
    ratioErr->SetBinError  (ibin, uncertaintyError);  //??? ovo nije bas jasno sto je
  }


  //  AxisFontsRatio(ratioErr->GetYaxis(), "y", "Theory / Data");
  //AxisFontsRatio(ratioErr->GetXaxis(), "x", variable + " (GeV)");
  AxisFontsRatio(ratio_mad->GetYaxis(), "y", "Theory / Data");
  //AxisFontsRatio(ratio_mad->GetXaxis(), "x", variable + " (GeV)");

  AxisFontsRatio(ratio_mcnlo->GetYaxis(), "y", "Theory / Data");

  if (var=="Zpt")
    AxisFontsRatio(ratio_mcnlo->GetXaxis(), "x", "p_{T}^{Z} (GeV)");
  if (var=="LeadingJetPt")
    AxisFontsRatio(ratio_mcnlo->GetXaxis(), "x", "p_{T}^{LeadingJet} (GeV)");
  ratio_mcnlo->SetFillColor(kAzure-9);
   //xsValue_MCnlo->SetFillColor(kWhite);
  ratio_mcnlo->SetFillStyle(1001);
  ratio_mcnlo->SetLineColor(kAzure);
  ratio_mcnlo->SetLineWidth(1);
  ratio_mcnlo->SetMarkerColor(kAzure);
  ratio_mcnlo->SetMarkerSize(_msize);
  //  xsValue_MCnlo->SetMarkerStyle(21);
  ratio_mcnlo->SetMarkerStyle(24);

  // Draw pad2
  //----------------------------------------------------------------------------
  canvas->cd();
  pad2->Draw();
  pad2->cd();
  
  //ratioErr  ->Draw("e2");
  
  ratio_mad ->Draw("pz");
  hratio_mad->Draw("e2,same");
  ratio_mad ->Draw("p, same");
  ratio_mad->GetYaxis()->SetRangeUser(0.1, 2.3);  

  pad2->Modified();
  
  DrawLatex(43, 0.2, 0.79, 15.0, 11, "Madgraph+Pythia normalized to #sigma_{NLO}");
  

  // Draw pad3
  //----------------------------------------------------------------------------
  canvas->cd();
  pad3->Draw();
  pad3->cd();
  std::cout<<"Default option: "<<ratio_mcnlo->GetOption()<<std::endl;
  
  //ratioErr    ->Draw("e2");
  ratio_mcnlo->Draw("pz");
  hratio_mcnlo->Draw("e2,same");

  ratio_mcnlo ->Draw("pz, same");
  ratio_mcnlo->GetYaxis()->SetRangeUser(0.1, 2.3);  
  //ratio_mcnlo->GetYaxis()->SetRangeUser(0.0, 0.5);  
  
  pad3->Modified();

  DrawLatex(43, 0.2, 0.89, 15.0, 11, "MCFM");
  
    

  // Save
  //----------------------------------------------------------------------------
  pad1->cd(); pad1->GetFrame()->DrawClone();
  pad2->cd(); pad2->GetFrame()->DrawClone();
  pad3->cd(); pad3->GetFrame()->DrawClone();

  canvas->cd();

  std::ostringstream saveName, saveName2;
  saveName  << "pdf/unfolded_"<<var<<".pdf";
  saveName2 << "png/unfolded_"<<var<<".png";
  canvas->SaveAs(saveName.str().c_str());
  canvas->SaveAs(saveName2.str().c_str());
}
Пример #28
0
//............................................
// Constructor for accpetance from a ROOT Tfile
SlicedAcceptance::SlicedAcceptance( string type, string fileName,string histName, bool fluctuate, bool quiet ) :
	slices(), nullSlice(new AcceptanceSlice(0.,0.,0.)), tlow(), thigh(), beta(), _sortedSlices(false), maxminset(false), t_min(0.), t_max(0.), _hasChecked(false), _storedDecision(false)
{
	if(!quiet) cout << "Root file being used for acceptance" << endl;
	(void)type;
	if( type != "RootFile" ) {   }//do nothing for now

	string fullFileName = StringProcessing::FindFileName( fileName, quiet );

	if( !quiet ) cout << "Opening: " << fullFileName << endl;

	TFile* file = TFile::Open(TString(fullFileName));
 	if(!quiet) cout << "File " << fullFileName << " opened!" << endl;
	TH1F* histo = (TH1F*)file->Get(TString(histName));
	if(!quiet) cout << "Histo " << histName << " opened!" << endl;
	histo->Draw();
	if(!quiet) cout << "Histo " << histName << " drawn!" << endl;
//	histo->Sumw2();

	if(fluctuate){
	cout << "WARNING! You have fluctuated the acceptance." << endl;
	cout << "WARNING! This is for systematic studies only. " << endl;
	cout << "WARNING! Projections and pull fits will have a different fluctuated acceptance to the PDF you fit with." << endl;
	cout << "WARNING! ONLY USE FluctuateAcceptance:True FOR SYSTEMATIC STUDIES" << endl;
	TRandom3 * rng = new TRandom3(0);	
	//Randomly fluctuate bin contents within error: 
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
	if(!quiet)	cout << "Bin content and error before: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l);
		histo->SetBinContent(l,rng->Gaus(histo->GetBinContent(l),histo->GetBinError(l)));
	if(!quiet)	cout <<  " and after: " << histo->GetBinContent(l) << "+/-" << histo->GetBinError(l) << endl;
	}
	delete rng;
	}

	histo->Scale(1./(histo->GetBinContent(histo->GetMaximumBin())));
	histo->SetMinimum(0);


	double maxend = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double height;
	double start;
	double end  = histo->GetBinLowEdge(histo->GetNbinsX()) + histo->GetBinWidth(histo->GetNbinsX());
	double dheight;
	for (int l = 1; l <= histo->GetNbinsX(); ++l){
		height = histo->GetBinContent(l);
		dheight = height;
		for (int n = l; n>0; n--){
			if(histo->GetBinContent(n)<height){
				dheight = height - histo->GetBinContent(n);
				cout << l << " " << n << " " << dheight << endl;
				break;
			}
		}
		start = histo->GetBinLowEdge(l);
		end = maxend;
		for (int m = l; m <= histo->GetNbinsX(); ++m){
			double thisbinheight = histo->GetBinContent(m);
			if(thisbinheight<height){
				end = histo->GetBinLowEdge(m);
				break;
			}
		}
		slices.push_back( new AcceptanceSlice( start, end, dheight ) );
	if(!quiet)	cout << start << "	" << end << "      " << dheight << endl;
	}
	histo->Delete();
//	delete histo;
	file->Close();
	delete file;

	if( !quiet ) cout << "Time Acc Slices: " << slices.size() << endl;
	if( slices.size() == 1 )
	{
		cout << "SlicedAcceptance: SERIOUS ERROR" << endl;
		exit(0);
	}
	//....done.....


	_sortedSlices = this->isSorted();

	if( _sortedSlices )
	{
		if( !quiet ) cout << "Sliced Acceptance is using sorted horizontal slices" << endl;
	}
	else
	{
		if( !quiet ) cout << "Sliced Acceptance is NOT using sorted horizontal slices" << endl;
	}
}
Пример #29
0
void RAA_dataDrivenUnfoldingErrorCheck(int radius = 4, int radiusPP = 4, char* algo = (char*) "Pu", char *jet_type = (char*) "PF", int unfoldingCut = 30, char* etaWidth = (char*) "n20_eta_p20", double deltaEta = 4.0){

  TStopwatch timer; 
  timer.Start();
  
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();
  
  bool printDebug = true;

  // get the data and mc histograms from the output of the read macro. 
  
  TDatime date;//this is just here to get them to run optimized. 

  // Raghav's files: 
  //TFile * fPbPb_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/PbPb_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  //  //TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pp_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  //TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pp_CutEfficiency_noJetID_exclusionhighertriggers_A_R0p%d.root",radius));

  // Pawan's files:
  TFile * fPbPb_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pawan_ntuplehistograms/PbPb_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  //TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pp_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));
  TFile * fPP_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/Pawan_ntuplehistograms/Pp_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));

  TFile * fPbPb_MB_in = TFile::Open(Form("/afs/cern.ch/work/r/rkunnawa/WORK/RAA/CMSSW_5_3_18/src/Output/PbPb_MinBiasUPC_CutEfficiency_YetkinCuts_matched_slantedlinecalopfpt_addingunmatched_exclusionhighertriggers_eMaxSumcand_A_R0p%d.root",radius));


  
  //TH1F * htest = new TH1F("htest","",nbins_pt, boundaries_pt);
  //Int_t unfoldingCutBin = htest->FindBin(unfoldingCut);
  
  cout<<"after input file declaration"<<endl;
  // need to make sure that the file names are in prefect order so that i can run them one after another. 
  // for the above condition, i might have to play with the date stamp. 
  
  const int nbins_cent = 6;
  double boundaries_cent[nbins_cent+1] = {0,2,4,12,20,28,36};
  double ncoll[nbins_cent+1] = {1660,1310,745,251,62.8,10.8,362.24};
  
  // histogram declarations with the following initial appendage: d - Data, m - MC, u- Unfolded
  // for the MC closure test, ive kept separate 

  // setup the radius and the eta bin loop here later. not for the time being. Aug 20th. only run the -2 < eta < 2 with the differenent centrality bins 

  TH1F *dPbPb_TrgComb[nbins_cent+1], *dPbPb_Comb[nbins_cent+1], *dPbPb_Trg80[nbins_cent+1], *dPbPb_Trg65[nbins_cent+1], *dPbPb_Trg55[nbins_cent+1], *dPbPb_1[nbins_cent+1], *dPbPb_2[nbins_cent+1], *dPbPb_3[nbins_cent+1], *dPbPb_80[nbins_cent+1], *dPbPb_65[nbins_cent+1], *dPbPb_55[nbins_cent+1];
  
  TH1F *mPbPb_Gen[nbins_cent+1], *mPbPb_Reco[nbins_cent+1];
  TH2F *mPbPb_Matrix[nbins_cent+1], *mPbPb_Response[nbins_cent+1], *mPbPb_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_data[nbins_cent+1];
  TH2F *mPbPb_mcclosure_Matrix[nbins_cent+1],*mPbPb_mcclosure_Response[nbins_cent+1], *mPbPb_mcclosure_ResponseNorm[nbins_cent+1];
  TH1F *mPbPb_mcclosure_gen[nbins_cent+1];
  const int Iterations = 20; //for unfolding systematics. 
  const int BayesIter = 4;
  TH1F *uPbPb_Bayes[nbins_cent+1], *uPbPb_BinByBin[nbins_cent+1], *uPbPb_SVD[nbins_cent+1]; 
  TH1F *uPbPb_BayesianIter[nbins_cent+1][Iterations];
  TH1F *dPbPb_MinBias[nbins_cent];
  
  TH1F *dPP_1, *dPP_2, *dPP_3, *dPP_Comb;
  TH1F *mPP_Gen, *mPP_Reco;
  TH2F *mPP_Matrix, *mPP_Response,*mPP_ResponseNorm;
  TH1F *mPP_mcclosure_data;
  TH2F *mPP_mcclosure_Matrix, *mPP_mcclosure_Response,*mPP_mcclosure_ResponseNorm;
  TH1F *mPP_mcclosure_Gen;
  TH1F *uPP_Bayes, *uPP_BinByBin, *uPP_SVD;
  TH1F *uPP_BayesianIter[Iterations];

  // would be better to read in the histograms and rebin them. come to think of it, it would be better to have them already rebinned (and properly scaled - to the level of differential cross section in what ever barns (inverse micro barns) but keep it consistent) from the read macro. 

  // get PbPb data
  for(int i = 0;i<nbins_cent;i++){
    if(printDebug) cout<<"cent_"<<i<<endl;
    dPbPb_TrgComb[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLTComb_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_TrgComb[i]->Scale(4*145.156*1e6);
    dPbPb_TrgComb[i]->Print("base");
    dPbPb_Trg80[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT80_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_Trg80[i]->Scale(4*145.156*1e6);
    dPbPb_Trg80[i]->Print("base");
    dPbPb_Trg65[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT65_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_Trg65[i]->Scale(4*145.156*1e6);
    dPbPb_Trg65[i]->Print("base");
    dPbPb_Trg55[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_HLT55_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_Trg55[i]->Scale(4*145.156*1e6);
    dPbPb_Trg55[i]->Print("base");
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_Trg80[i]->Clone(Form("Jet_80_triggered_spectra_data_PbPb_cent%d",i));
    
    //dPbPb_MinBias[i] = (TH1F*)fPbPb_MB_in->Get(Form("hpbpb_HLTComb_R%d_n20_eta_p20_cent%d",radius,i));
    //dPbPb_MinBias[i]->Print("base");
    dPbPb_TrgComb[i]->Scale(1./(145.156 * 1e9));
    //dPbPb_MinBias[i]->Scale(1./(161.939 * 1e9));
    
    //dPbPb_TrgComb[i]->Add(dPbPb_MinBias[i]);
    
    for(int k = 1;k<=unfoldingCut;k++) {
      dPbPb_TrgComb[i]->SetBinContent(k,0);
      dPbPb_Trg80[i]->SetBinContent(k,0);
      dPbPb_Trg65[i]->SetBinContent(k,0);
      dPbPb_Trg55[i]->SetBinContent(k,0);
    }
    
  }
  
  //Int_t nSVDIter = 4;
  
  if(printDebug)cout<<"loaded the data histograms PbPb"<<endl;
  // get PbPb MC
  for(int i = 0;i<nbins_cent;i++){
    
    mPbPb_Gen[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_JetComb_gen_R%d_n20_eta_p20_cent%d",radius,i));
    //mPbPb_Gen[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_gen_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_Gen[i]->Print("base");
    mPbPb_Reco[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_JetComb_reco_R%d_n20_eta_p20_cent%d",radius,i));
    //mPbPb_Reco[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_reco_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_Reco[i]->Print("base");
    mPbPb_Matrix[i] = (TH2F*)fPbPb_in->Get(Form("hpbpb_matrix_HLT_R%d_n20_eta_p20_cent%d",radius,i));
    //mPbPb_Matrix[i] = (TH2F*)fPbPb_in->Get(Form("hpbpb_matrix_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_Matrix[i]->Print("base");
    mPbPb_mcclosure_data[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_mcclosure_JetComb_data_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_mcclosure_data[i]->Print("base");
    mPbPb_mcclosure_gen[i] = (TH1F*)fPbPb_in->Get(Form("hpbpb_mcclosure_gen_JetComb_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_mcclosure_gen[i]->Print("base");
    mPbPb_mcclosure_Matrix[i] = (TH2F*)fPbPb_in->Get(Form("hpbpb_mcclosure_matrix_HLT_R%d_n20_eta_p20_cent%d",radius,i));
    mPbPb_mcclosure_Matrix[i]->Print("base");
    
    //since SVD is very straight forward, lets do it rignt here:
    //get the SVD response matrix:
    //RooUnfoldResponse ruResponse(mPbPb_Matrix[i]->ProjectionY(),mPbPb_Matrix[i]->ProjectionX(), mPbPb_Matrix[i],"","");
    //regularization parameter definition: 
    //RooUnfoldSvd unfoldSvd(&ruResponse, dPbPb_TrgComb[i], nSVDIter);
    //uPbPb_SVD[i] = (TH1F*)unfoldSvd.Hreco();
  
    
    // for(int k = 1;k<=unfoldingCut;k++){

    //   mPbPb_Gen[i]->SetBinContent(k,0);
    //   mPbPb_Reco[i]->SetBinContent(k,0);
    //   mPbPb_mcclosure_data[i]->SetBinContent(k,0);
    //   mPbPb_mcclosure_gen[i]->SetBinContent(k,0);
    //   for(int l = 1;l<=1000;l++){
    // 	mPbPb_Matrix[i]->SetBinContent(k,l,0);
    // 	mPbPb_mcclosure_Matrix[i]->SetBinContent(k,l,0);
    // 	mPbPb_Matrix[i]->SetBinContent(l,k,0);
    // 	mPbPb_mcclosure_Matrix[i]->SetBinContent(l,k,0);	
    //   }
    // }
    
    //mPbPb_Response[i] = new TH2F(Form("mPbPb_Response_cent%d",i),"Response Matrix",nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
    //mPbPb_ResponseNorm[i] = new TH2F(Form("mPbPb_ResponseNorm_cent%d",i),"Normalized Response Matrix",nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
  }
  
  if(printDebug) cout<<"loaded the data and mc PbPb histograms from the files"<<endl;

  // get PP data
  if(printDebug) cout<<"Getting PP data and MC"<<endl;
  dPP_1 = (TH1F*)fPP_in->Get(Form("hpp_HLT80_R%d_%s",radiusPP,etaWidth)); 
  dPP_1->Print("base");
  dPP_2 = (TH1F*)fPP_in->Get(Form("hpp_HLT60_R%d_%s",radiusPP,etaWidth));
  dPP_2->Print("base");
  dPP_3 = (TH1F*)fPP_in->Get(Form("hpp_HLT40_R%d_%s",radiusPP,etaWidth));
  dPP_3->Print("base");
  dPP_Comb = (TH1F*)fPP_in->Get(Form("hpp_HLTComb_R%d_%s",radiusPP,etaWidth));   
  //dPP_Comb = (TH1F*)dPP_1->Clone(Form("hpp_TrgComb_R%d_n20_eta_p20",radiusPP,etaWidth));   
  dPP_Comb->Print("base");

  dPP_Comb->Scale(1./(5.3 * 1e9));
  
  for(int k = 1;k<=unfoldingCut;k++) {
    dPP_Comb->SetBinContent(k,0);
    dPP_1->SetBinContent(k,0);
    dPP_2->SetBinContent(k,0);
    dPP_3->SetBinContent(k,0);
  }
  
  // get PP MC
  mPP_Gen = (TH1F*)fPP_in->Get(Form("hpp_JetComb_gen_R%d_%s",radiusPP,etaWidth));
  mPP_Gen->Print("base");
  mPP_Reco = (TH1F*)fPP_in->Get(Form("hpp_JetComb_reco_R%d_%s",radiusPP,etaWidth));
  mPP_Reco->Print("base");
  mPP_Matrix = (TH2F*)fPP_in->Get(Form("hpp_matrix_HLT_R%d_%s",radiusPP,etaWidth));
  mPP_Matrix->Print("base");
  mPP_mcclosure_data = (TH1F*)fPP_in->Get(Form("hpp_mcclosure_JetComb_data_R%d_%s",radiusPP,etaWidth));
  mPP_mcclosure_data->Print("base");
  mPP_mcclosure_Matrix = (TH2F*)fPP_in->Get(Form("hpp_mcclosure_matrix_HLT_R%d_%s",radiusPP,etaWidth));
  mPP_mcclosure_Matrix->Print("base");

  //RooUnfoldResponse ruResponsePP(mPP_Matrix->ProjectionY(),mPP_Matrix->ProjectionX(), mPP_Matrix,"","");
  //regularization parameter definition: 
  //RooUnfoldSvd unfoldSvdPP(&ruResponsePP, dPP_Comb, nSVDIter);
  //uPP_SVD = (TH1F*)unfoldSvdPP.Hreco();

  
  // for(int k = 1;k<=unfoldingCut;k++){
  //   mPP_Gen->SetBinContent(k,0);
  //   mPP_Reco->SetBinContent(k,0);
  //   mPP_mcclosure_data->SetBinContent(k,0);
  //   for(int l = 1;l<=1000;l++){
  //     mPP_Matrix->SetBinContent(k,l,0);
  //     mPP_mcclosure_Matrix->SetBinContent(k,l,0);
  //     mPP_Matrix->SetBinContent(l,k,0);
  //     mPP_mcclosure_Matrix->SetBinContent(l,k,0);
  //   }
  // }

  
  if(printDebug) cout<<"Filling the PbPb response Matrix"<<endl;

  // response matrix and unfolding for PbPb 
  // going to try it the way kurt has it. 

  for(int i = 0;i<nbins_cent;i++){
    if(printDebug) cout<<"centrality bin iteration = "<<i<<endl;
    TF1 *f = new TF1("f","[0]*pow(x+[2],[1])");
    f->SetParameters(1e10,-8.8,40);
    // TH1F *hGenSpectraCorr = (TH1F*)mPbPb_Matrix[i]->ProjectionX()->Clone(Form("hGenSpectraCorr_cent%d",i));
    // hGenSpectraCorr->Fit("f"," ");
    // hGenSpectraCorr->Fit("f","","");
    // hGenSpectraCorr->Fit("f","LL");
    // TH1F *fHist = functionHist(f,hGenSpectraCorr,Form("fHist_cent%d",i));// function that you get from the fitting 
    // hGenSpectraCorr->Divide(fHist);
    for (int y=1;y<=mPbPb_Matrix[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {
	if (mPbPb_Matrix[i]->GetBinContent(x,y)<=1*mPbPb_Matrix[i]->GetBinError(x,y)) {
	  //in the above line mine had 0*getbinerror while Kurt's had 1*. 
	  mPbPb_Matrix[i]->SetBinContent(x,y,0);
	  mPbPb_Matrix[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Matrix[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Matrix[i]->GetNbinsX();x++) {	   
	double ratio = 1;
	// if (hGenSpectraCorr->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorr->GetBinContent(x);
	mPbPb_Matrix[i]->SetBinContent(x,y,mPbPb_Matrix[i]->GetBinContent(x,y)*ratio);
	mPbPb_Matrix[i]->SetBinError(x,y,mPbPb_Matrix[i]->GetBinError(x,y)*ratio);
      }
    }
    //mPbPb_Matrix[i]->Smooth(0);
    // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  
    
    mPbPb_Response[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_Response_cent%d",i));
    TH1F *hProj = (TH1F*)mPbPb_Response[i]->ProjectionY()->Clone(Form("hProj_cent%d",i));

    for (int y=1;y<=mPbPb_Response[i]->GetNbinsY();y++) {
      double sum=0;
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {
	if (mPbPb_Response[i]->GetBinContent(x,y)<=1*mPbPb_Response[i]->GetBinError(x,y)) {
	  // in the above if loop, kurt has 1*error and my old had 0*error
	  mPbPb_Response[i]->SetBinContent(x,y,0);
	  mPbPb_Response[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_Response[i]->GetBinContent(x,y);
      }
      
      for (int x=1;x<=mPbPb_Response[i]->GetNbinsX();x++) {  	
	if (sum==0) continue;
	double ratio = 1;
	//if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
	// else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
	ratio = 1./sum;
	if (hProj->GetBinContent(y)==0) ratio = 1e-100/sum;
	else ratio = hProj->GetBinContent(y)/sum;
	mPbPb_Response[i]->SetBinContent(x,y,mPbPb_Response[i]->GetBinContent(x,y)*ratio);
	mPbPb_Response[i]->SetBinError(x,y,mPbPb_Response[i]->GetBinError(x,y)*ratio);
      }
    }
    
    mPbPb_ResponseNorm[i] = (TH2F*)mPbPb_Matrix[i]->Clone(Form("mPbPb_ResponseNorm_cent%d",i));
    for (int x=1;x<=mPbPb_ResponseNorm[i]->GetNbinsX();x++) {
      double sum=0;
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {
	if (mPbPb_ResponseNorm[i]->GetBinContent(x,y)<=1*mPbPb_ResponseNorm[i]->GetBinError(x,y)) {
	  mPbPb_ResponseNorm[i]->SetBinContent(x,y,0);
	  mPbPb_ResponseNorm[i]->SetBinError(x,y,0);
	}
	sum+=mPbPb_ResponseNorm[i]->GetBinContent(x,y);
      }
      
      for (int y=1;y<=mPbPb_ResponseNorm[i]->GetNbinsY();y++) {  	
	if (sum==0) continue;
	double ratio = 1./sum;
	mPbPb_ResponseNorm[i]->SetBinContent(x,y,mPbPb_ResponseNorm[i]->GetBinContent(x,y)*ratio);
	mPbPb_ResponseNorm[i]->SetBinError(x,y,mPbPb_ResponseNorm[i]->GetBinError(x,y)*ratio);
      }
      
    }
    
    
  }

  
  if(printDebug) cout<<"Filling PP response Matrix"<<endl;

  // response matrix for pp.  
  // Kurt doesnt have this whole hGenSpectraCorr thing in his macro. need to check why the difference exists between out codes
  
  TF1 *fpp = new TF1("fpp","[0]*pow(x+[2],[1])");
  fpp->SetParameters(1e10,-8.8,40);
  // if(printDebug) cout<<"before getting the gen spectra corr matrix"<<endl;
  // TH1F *hGenSpectraCorrPP = (TH1F*)mPP_Matrix->ProjectionX()->Clone("hGenSpectraCorrPP");
  // if(printDebug) cout<<"after gettign the gen spectra corr matrix"<<endl;
  // hGenSpectraCorrPP->Fit("f"," ");
  // hGenSpectraCorrPP->Fit("f","","");
  // hGenSpectraCorrPP->Fit("f","LL");
  // TH1F *fHistPP = functionHist(fpp,hGenSpectraCorrPP,"fHistPP");// that the function that you get from the fitting 
  // hGenSpectraCorrPP->Divide(fHistPP);
  
  for (int y=1;y<=mPP_Matrix->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {
      if (mPP_Matrix->GetBinContent(x,y)<=1*mPP_Matrix->GetBinError(x,y)) {
	mPP_Matrix->SetBinContent(x,y,0);
	mPP_Matrix->SetBinError(x,y,0);
      }
      sum+=mPP_Matrix->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Matrix->GetNbinsX();x++) {	   
      double ratio = 1;
      // if (hGenSpectraCorrPP->GetBinContent(x)!=0) ratio = 1e5/hGenSpectraCorrPP->GetBinContent(x);
      mPP_Matrix->SetBinContent(x,y,mPP_Matrix->GetBinContent(x,y)*ratio);
      mPP_Matrix->SetBinError(x,y,mPP_Matrix->GetBinError(x,y)*ratio);
    }
  }
  // mPbPb_Matrix[i]->Smooth(0);
  
  // Ok major differences here between my code and Kurt in b-jet Tools under Unfold - lines 469 and above.  

  if(printDebug) cout<<"getting the response matrix"<<endl;

  mPP_Response = (TH2F*)mPP_Matrix->Clone("mPP_Response");
  TH1F *hProjPP = (TH1F*)mPP_Response->ProjectionY()->Clone("hProjPP");
  
  
  for (int y=1;y<=mPP_Response->GetNbinsY();y++) {
    double sum=0;
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {
      if (mPP_Response->GetBinContent(x,y)<=1*mPP_Response->GetBinError(x,y)) {
	// in the above if statement, kurt has 1*error and my old has 0*error
	mPP_Response->SetBinContent(x,y,0);
	mPP_Response->SetBinError(x,y,0);
      }
      sum+=mPP_Response->GetBinContent(x,y);
    }
    
    for (int x=1;x<=mPP_Response->GetNbinsX();x++) {  	
      if (sum==0) continue;
      double ratio = 1;
      //if(dPbPb_TrgComb[i]->GetBinContent(y)==0) ratio = 1e-100/sum;
      // else ratio = dPbPb_TrgComb[i]->GetBinContent(y)/sum
      ratio = 1./sum;
      if (hProjPP->GetBinContent(y)==0) ratio = 1e-100/sum;
      else ratio = hProjPP->GetBinContent(y)/sum;
      mPP_Response->SetBinContent(x,y,mPP_Response->GetBinContent(x,y)*ratio);
      mPP_Response->SetBinError(x,y,mPP_Response->GetBinError(x,y)*ratio);
    }
  }
  if(printDebug) cout<<"getting the normalized response matrix"<<endl;
  mPP_ResponseNorm = (TH2F*)mPP_Matrix->Clone("mPP_ResponseNorm");
  for (int x=1;x<=mPP_ResponseNorm->GetNbinsX();x++) {
    double sum=0;
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {
      if (mPP_ResponseNorm->GetBinContent(x,y)<=1*mPP_ResponseNorm->GetBinError(x,y)) {
	mPP_ResponseNorm->SetBinContent(x,y,0);
	mPP_ResponseNorm->SetBinError(x,y,0);
      }
      sum+=mPP_ResponseNorm->GetBinContent(x,y);
    }
    
    for (int y=1;y<=mPP_ResponseNorm->GetNbinsY();y++) {  	
      if (sum==0) continue;
      double ratio = 1./sum;
      mPP_ResponseNorm->SetBinContent(x,y,mPP_ResponseNorm->GetBinContent(x,y)*ratio);
      mPP_ResponseNorm->SetBinError(x,y,mPP_ResponseNorm->GetBinError(x,y)*ratio);
    }
    
    
  }
  
  // scale the spectra to the respective units

  // for(int i = 0;i<nbins_cent;++i){
  //   dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins_pt,Form("PbPb_measured_spectra_combined_cent%d",i),boundaries_pt);
  //   divideBinWidth(dPbPb_TrgComb[i]);
  // }

  // dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins_pt,"pp_measured_spectra_combined",boundaries_pt);
  // divideBinWidth(dPP_Comb);
  // dPP_Comb->Scale(1./ dPP_Comb->GetBinContent(nbins_pt));
  
  // Now that we have all the response matrix for the 6 centralities in PbPb and one pp spectra lets start doing the steps:
  // we have 39 pt bins, so we need 1000 gaussian functions for each pt bin.
  
  Int_t unfoldingTrials = 200;
  Double_t meanMeasPbPb[nbins_pt][nbins_cent], sigmaMeasPbPb[nbins_pt][nbins_cent];
  Double_t meanMeasPP[nbins_pt], sigmaMeasPP[nbins_pt];
  Double_t meanUnfoldPbPb[nbins_pt][nbins_cent][unfoldingTrials], sigmaUnfoldPbPb[nbins_pt][nbins_cent][unfoldingTrials];
  Double_t meanUnfoldPP[nbins_pt][unfoldingTrials], sigmaUnfoldPP[nbins_pt][unfoldingTrials]; 
  
  TRandom3 *random = new TRandom3(0);

  for(int u = 0;u<unfoldingTrials;++u){
    cout<<"unfolding trial no = "<<u+1<<endl;
  
    for(int j = 0;j<nbins_pt;++j){
      for(int i = 0;i<nbins_cent;++i){
      
	meanMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinContent(j+1);
	sigmaMeasPbPb[j][i] = dPbPb_TrgComb[i]->GetBinError(j+1);

      }// centrality loop

      meanMeasPP[j] = dPP_Comb->GetBinContent(j+1);
      sigmaMeasPP[j] = dPP_Comb->GetBinContent(j+1);
      
    }// nbins_pt loop

    // now proceed to unfolding for each trial.

    for(int i = 0;i<nbins_cent;++i){
      //cout<<"centrality = "<<i<<endl;

      TH1F * hPreUnfoldingSpectra = new TH1F("hPreUnfoldingSpectra","",nbins_pt,0,nbins_pt);
      TH1F * hAfterUnfoldingSpectra;

      for(int j = 0;j<nbins_pt;++j){
	
	hPreUnfoldingSpectra->SetBinContent(j+1, random->Gaus(meanMeasPbPb[j][i], sigmaMeasPbPb[j][i]));
	hPreUnfoldingSpectra->SetBinError(j+1, sigmaMeasPbPb[j][i]/sqrt(unfoldingTrials));
        //if(j==100)cout << " before unfolding bin " << j << " value = " << hPreUnfoldingSpectra->GetBinContent(j+1)<<endl;
        //if(j==100)cout << " before unfolding bin " << j << " error = " << hPreUnfoldingSpectra->GetBinError(j+1)<<endl;
	
      }// nbins_pt loop

      TH1F* hMCGen          = (TH1F*)mPbPb_Response[i]->ProjectionX();
      removeZero(hMCGen);
      //cout << " MC bin " << 100 << " value = " << hMCGen->GetBinContent(100)<<endl;
      bayesianUnfold myUnfoldingMulti(mPbPb_Matrix[i], hMCGen, 0);
      myUnfoldingMulti.unfold(hPreUnfoldingSpectra, BayesIter);

      hAfterUnfoldingSpectra = (TH1F*) myUnfoldingMulti.hPrior->Clone("hAfterUnfoldingSpectra");

      for(int j = 0;j<nbins_pt;++j){
	
	//if(j==100)cout << " before unfolding bin " << j << " value = " << hPreUnfoldingSpectra->GetBinContent(j+1)<<endl;
	//if(j==100)cout << " after  unfolding bin " << j << " value = " << hAfterUnfoldingSpectra->GetBinContent(j+1)<<endl;
	
	meanUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinContent(j+1);
	sigmaUnfoldPbPb[j][i][u] = hAfterUnfoldingSpectra->GetBinError(j+1);

	// cout << "after unfolding meanUnfoldPbPb[" << j << "][" << i << "][" << u<< "] = " <<meanUnfoldPbPb[j][i][u]<<"    ";
	// cout << "after unfolding meanUnfoldPbPb[" << j << "][" << i << "][" << u<< "] = " <<sigmaUnfoldPbPb[j][i][u]<<endl;
	
      }// nbins_pt loop
      
      //hPreUnfoldingSpectra->Print("base");
      //hAfterUnfoldingSpectra->Print("base");
      
      delete hPreUnfoldingSpectra;
      delete hAfterUnfoldingSpectra;
      delete hMCGen; 
      
    }// centrality loop

    cout<<"pp "<<endl;

    // now do it for the pp:
    TH1F * hPreUnfoldingSpectraPP = new TH1F("hPreUnfoldingSpectraPP","",nbins_pt,0,nbins_pt);
    TH1F * hAfterUnfoldingSpectraPP;
    
    for(int j = 0;j<nbins_pt;++j){
	
      hPreUnfoldingSpectraPP->SetBinContent(j+1, random->Gaus(meanMeasPP[j], sigmaMeasPP[j]));
      hPreUnfoldingSpectraPP->SetBinError(j+1, sigmaMeasPP[j]/sqrt(unfoldingTrials));
        
    }// nbins_pt loop
    TH1F* hMCGenPP          = (TH1F*)mPP_Response->ProjectionX();
    removeZero(hMCGenPP);
    bayesianUnfold myUnfoldingMultiPP(mPP_Matrix, hMCGenPP, 0);
    myUnfoldingMultiPP.unfold(hPreUnfoldingSpectraPP, BayesIter);

    hAfterUnfoldingSpectraPP = (TH1F*) myUnfoldingMultiPP.hPrior->Clone("hAfterUnfoldingSpectraPP");

    for(int j = 0;j<nbins_pt;++j){

      meanUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinContent(j+1);
      sigmaUnfoldPP[j][u] = hAfterUnfoldingSpectraPP->GetBinError(j+1);

    }// nbins_pt loop

    delete hPreUnfoldingSpectraPP;
    delete hAfterUnfoldingSpectraPP;
    delete hMCGenPP; 
    
  }// unfolding trials loop


  // Now that we have all the necesary values we need, lets proceed to fill a histogram with the mean values for each ptbin and get the corrected values.
  TH1F * hAfterUnfoldingptBinDistribution[nbins_pt];
  TH1F * hCorrUnfoldingPbPb[nbins_cent];
  
  for(int i = 0;i<nbins_cent;++i){

    hCorrUnfoldingPbPb[i] = new TH1F(Form("PbPb_BayesianUnfolded_cent%d",i),"Spectra after correction", nbins_pt, 0, nbins_pt);

    for(int j = 0;j<nbins_pt;++j){
      
      //hAfterUnfoldingptBinDistribution[j] = new TH1F(Form("hAfterUnfoldingptBinDistribution_ptBin%d",j),"",100,	(meanMeasPbPb[j][i]-10) * sigmaMeasPbPb[j][i], (meanMeasPbPb[j][i]+10) * sigmaMeasPbPb[j][i]);
      hAfterUnfoldingptBinDistribution[j] = new TH1F(Form("hAfterUnfoldingptBinDistribution_ptBin%d",j),"",100,	0, 1);
      for(int u = 0;u<unfoldingTrials;++u){

	hAfterUnfoldingptBinDistribution[j]->Fill(meanUnfoldPbPb[j][i][u]);

	//if(j==100) cout<< "unfolding_trial = " << u+1 << " mean unfold value = "<< meanUnfoldPbPb[j][i][u] <<endl;

      }// unfolding trials loop

      //if(j==100) cout<<"Mean of that value for pt=100 = "<< (Float_t)hAfterUnfoldingptBinDistribution[j]->GetMean() <<endl;      
      hCorrUnfoldingPbPb[i]->SetBinContent(j+1, hAfterUnfoldingptBinDistribution[j]->GetMean());
      //cout<<"centrality bin "<<i<<", pT bin "<<j<<" bin Content = "<<hCorrUnfoldingPbPb[i]->GetBinContent(j+1)<<endl;
      hCorrUnfoldingPbPb[i]->SetBinError(j+1, hAfterUnfoldingptBinDistribution[j]->GetRMS());
      //cout<<"centrality bin "<<i<<", pT bin "<<j<<" bin Error   = "<<hCorrUnfoldingPbPb[i]->GetBinError(j+1)<<endl;

      delete hAfterUnfoldingptBinDistribution[j];
      
    }// nbins_pt loop

  }// centrality loop

  // similar for the pp:
  TH1F * hAfterUnfoldingptBinDistributionPP[nbins_pt];
  TH1F * hCorrUnfoldingPP;
  
  hCorrUnfoldingPP = new TH1F("PP_BayesianUnfolded","Spectra after unfolding error correction",nbins_pt, 0, nbins_pt);
  
  for(int j = 0;j<nbins_pt;++j){
    
    //hAfterUnfoldingptBinDistributionPP[j] = new TH1F(Form("hAfterUnfoldingptBinDistributionPP_ptBin%d",j),"",1000,(meanMeasPP[j]-10) * sigmaMeasPP[j], (meanMeasPP[j]+10) * sigmaMeasPP[j]);
    hAfterUnfoldingptBinDistributionPP[j] = new TH1F(Form("hAfterUnfoldingptBinDistributionPP_ptBin%d",j),"",100, 0, 1);
    for(int u = 0;u<unfoldingTrials;++u){
      
      hAfterUnfoldingptBinDistributionPP[j]->Fill(meanUnfoldPP[j][u]);
      
    }// unfolding trials loop
    
    hCorrUnfoldingPP->SetBinContent(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetMean());
    //cout<<"PP pT bin "<<j<<" bin Content = "<<hCorrUnfoldingPP->GetBinContent(j+1)<<endl;
    hCorrUnfoldingPP->SetBinError(j+1, hAfterUnfoldingptBinDistributionPP[j]->GetRMS());
    //cout<<"PP pT bin "<<j<<" bin Error   = "<<hCorrUnfoldingPP->GetBinError(j+1)<<endl;
    
    delete hAfterUnfoldingptBinDistributionPP[j];
    
  }// nbins_pt loop
    
  TFile f(Form("../../Output/Pawan_ntuple_PbPb_R%d_pp_R%d_%s_unfoldingCut_%d_data_driven_correction_ak%s%s_%d.root",radius, radiusPP, etaWidth ,unfoldingCut,algo,jet_type,date.GetDate()),"RECREATE");
  f.cd();

  for(int i = 0;i<nbins_cent;i++) {

    hCorrUnfoldingPbPb[i]->Scale(145.156 * 1e9);
    //hCorrUnfoldingPbPb[i] = (TH1F*)hCorrUnfoldingPbPb[i]->Rebin(nbins_pt_coarse, Form("PbPb_BayesianUnfolded_cent%d",i), boundaries_pt_coarse);
    hCorrUnfoldingPbPb[i]->Write();
    hCorrUnfoldingPbPb[i]->Print("base");

    dPbPb_TrgComb[i]->Scale(145.156 * 1e9);
    //dPbPb_TrgComb[i] = (TH1F*)dPbPb_TrgComb[i]->Rebin(nbins_pt_coarse, Form("PbPb_measured_cent%d",i), boundaries_pt_coarse);
    dPbPb_TrgComb[i]->Write();
    dPbPb_TrgComb[i]->Print("base");
    
  }

  hCorrUnfoldingPP->Scale(5.3 * 1e9);
  //hCorrUnfoldingPP = (TH1F*)hCorrUnfoldingPP->Rebin(nbins_pt_coarse, "PP_BayesianUnfolded", boundaries_pt_coarse);
  hCorrUnfoldingPP->Write();
  hCorrUnfoldingPP->Print("base");
  dPP_Comb->Scale(5.3 * 1e9);
  //dPP_Comb = (TH1F*)dPP_Comb->Rebin(nbins_pt_coarse, "PP_measured", boundaries_pt_coarse);  
  dPP_Comb->Write();
  dPP_Comb->Print("base");
  
  f.Write();
  f.Close();

  timer.Stop();
  if(printDebug) cout<<"CPU time (mins) = "<<(Float_t)timer.CpuTime()/60<<endl;
  if(printDebug) cout<<"Real tile (mins) = "<<(Float_t)timer.RealTime()/60<<endl;
  

}
Пример #30
0
int main(int argc, char* argv[]){
    UImanager uimanager(argc, argv, "dndt_fit");
//work directory    
    TString workdir(getenv("WORKDIR"));
//***************************set constant ****************************************
    Double_t acdntl_corr = 1., respf_corr = 1.;
	Double_t eff_corr = uimanager.get_adcerr() * uimanager.get_br_corr() * uimanager.get_ta_corr() * acdntl_corr * respf_corr;//	adcerr x tdiff_cut_eff x veto_eff x pi0 decay products abs. (set to 1, since included in current rmat) x bkg_in_fit (not in current rmat)
    if(uimanager.best_tdiff()) eff_corr *= uimanager.get_bit_corr();
    if(uimanager.ismc()) eff_corr = uimanager.get_ta_corr(); 

    cout << eff_corr << " " << uimanager.flux() << " " << uimanager.get_tgt_lumi() << endl;
	Double_t f_l = uimanager.flux() * uimanager.get_tgt_lumi() * eff_corr;

//************ start reading files *******************************
//read tables/eflux.dat [tables/effcor.dat] tables/dfp1_xx.dat or current_foler/dfp1_xx.dat
//get echn flux
	Double_t flw[180];
	ifstream eflux(workdir+"tables/eflux.dat");
	if (!eflux.is_open()) {
		cout << "eflux doesn't exist" << endl;
		exit(1);
 	}
	for(int i=0;i<180;i++)eflux>>flw[i];
//get efficiency table
    TString dfp;
    if (!uimanager.target()) dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_si.dat";
    else dfp = Form("dfp%d", int(uimanager.isouter())) + uimanager.input_filename("mc") + "_c12.dat";

	ifstream profile;
    profile.open(dfp);
    if (profile.is_open()) {
        cout << "use local efficiency table: " << dfp << endl;
    } else {
        //profile.open(workdir+"efficiency2/tables/"+dfp);
        profile.open(workdir+"/tables/"+dfp);
        if(!profile.is_open()) cout << " can't open table " << dfp << endl;
        cout << " use efficiency table in tables: " << dfp << endl;
    }
	
    const int phy = 5;
	const int ech = 180;
	Double_t dfprob[phy][nangle][ech];
	Double_t coulm[nangle], ncohe[nangle], cosfiint[nangle], sinfiint[nangle], ninco[nangle];
	for(int i=0;i<nangle;i++){
		coulm[i]=0;
        ncohe[i]=0;
		cosfiint[i]=0;
		sinfiint[i]=0;
		ninco[i]=0;
	}

	for(int i = 0;i < 180;i++)
		for(int j = 0;j < nangle;j++)
			for(int k = 0;k < 5;k++){
				Double_t f_l_j=f_l;
				int ic = 0;
				int jc = 0;
				int kc = 0;
				profile>>ic>>jc>>kc>>dfprob[k][j][i];
                if(ic!=i+1||jc!=j+1||kc!=k+1){
					cout << i << " " << j << " " << k << endl;
					cout << ic << " " << jc << " " << kc << " " << dfprob[k][j][i] << endl;
					cout<<"Bad data given for dfprob"<<endl;
					exit(1);
				}
				if(kc==1)coulm[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==2)cosfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==3)ncohe[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else if(kc==4)ninco[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
				else sinfiint[j]+=flw[i]*dfprob[k][j][i]*f_l_j;
            }

	for(int i=1;i<=nangle;i++){
		hcoulm->SetBinContent(i,coulm[i-1]);
		hcosfiint->SetBinContent(i,cosfiint[i-1]);
		hncohe->SetBinContent(i,ncohe[i-1]);
		hninco->SetBinContent(i,ninco[i-1]);
		hsinfiint->SetBinContent(i,sinfiint[i-1]);
    }
//read yield
    TString inrootname("pi0alt" + uimanager.input_filename("fit") + ".root");

	TFile *yield = new TFile(inrootname);
    if (!yield->IsOpen()) exit(open_err(inrootname));
	TH1F *yieldhist = (TH1F*)yield->Get("hyield");
	//TH1F *yieldhist = (TH1F*)yield->Get("hyield_mc_nocut");
	yieldhist->SetDirectory(0);
	if (!uimanager.target() && !uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/o tran.)");
    else if (!uimanager.target()) yieldhist->SetTitle("#pi^{0} yield (Si, crystal w/ tran.)");
    else if (!uimanager.isouter()) yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/o tran.)");
    else yieldhist->SetTitle("#pi^{0} yield (C12, crystal w/ tran.)");
    
    double nyield = 0, nyield_err = 0;
    for(int i = 1; i<=125; i++) {
        nyield += yieldhist->GetBinContent(i);
        nyield_err += yieldhist->GetBinError(i)*yieldhist->GetBinError(i);
    }
    nyield_err = sqrt(nyield_err);
//***************** end reading files **************************************
    
	gStyle->SetOptFit(1);
	gStyle->SetOptStat(0);
	gStyle->SetPaperSize(12,24);
	//Double_t parameter[4] = {7.9, 1.0, 1.0, 0.8};
	Double_t parameter[4] = {7.7, 1.0, 0.8, 0.5};

	TF1 *ftot = new TF1("ftot", dndt, 0., dndt_fit_range, 4);
	ftot->SetParNames("#Gamma","C1","#phi","C2");

	ftot->SetParameter(0,parameter[0]);
	ftot->SetParameter(1,parameter[1]);
	ftot->SetParameter(2,parameter[2]);
	ftot->SetParameter(3,parameter[3]);
/*
	ftot->FixParameter(0,parameter[0]);
	ftot->FixParameter(1,parameter[1]);
	ftot->FixParameter(2,parameter[2]);
	ftot->FixParameter(3,parameter[3]);
*/
    ftot->SetParLimits(0, 3, 10);
    ftot->SetParLimits(1, 0.3, 1.5);
    ftot->SetParLimits(2, 0, 3.1415936/2);
    ftot->SetParLimits(3, 0., 10.0);

	yieldhist->Fit("ftot", "RMBE0");

	Double_t chi2 = ftot->GetChisquare()/ftot->GetNDF();
	parameter[0]=ftot->GetParameter(0);
	parameter[1]=ftot->GetParameter(1);
	parameter[2]=ftot->GetParameter(2);
	parameter[3]=ftot->GetParameter(3);
	
    Double_t e1 = ftot->GetParError(0);
    Double_t e2 = ftot->GetParError(1);
    Double_t e3 = ftot->GetParError(2);
    Double_t e4 = ftot->GetParError(3);

	//cout<<chi2<<" "<<parameter[0]<<" "<<parameter[1]<<" "<<parameter[2]<<" "<<parameter[3]<<endl;
    TString fname = "fitresult" + uimanager.input_filename("fit") + ".dat";
    ofstream output(fname);
    output<<nyield<<" "<<nyield_err<<" "<<chi2<<" "<<parameter[0]<<" "<<e1<<" "<<parameter[1]<<" "<<e2<<" "<<parameter[2]<<" "<<e3<<" "<<parameter[3]<<" "<<e4<<endl;

	TH1F *fithist = new TH1F("fithist", "fithist", fit_nangle, 0, dndt_fit_range);
	TH1F *fitcoulm = new TH1F("fitcolum", "fitcolum", fit_nangle, 0, dndt_fit_range);
	TH1F *fitncohe = new TH1F("fitncohe", "fitncohe", fit_nangle, 0, dndt_fit_range);
	TH1F *fitit = new TH1F("fitit", "fitit", fit_nangle, 0, dndt_fit_range);
	TH1F *fitninco = new TH1F("fitninco", "fitninco", fit_nangle, 0, dndt_fit_range);

	yieldhist->SetLineWidth(2);
	fithist->SetLineWidth(2);
	fitcoulm->SetLineWidth(2);
	fitncohe->SetLineWidth(2);
	fitit->SetLineWidth(2);
	fitninco->SetLineWidth(2);

	float accfit[fit_nangle], acchist[fit_nangle], acchisterr[fit_nangle], diff[fit_nangle];

	for(int i=1;i<=fit_nangle;i++){
		fithist->SetBinContent(i,ftot->Eval(max_angle/nangle*(i-0.5)));
		fitcoulm->SetBinContent(i,parameter[0]*hcoulm->GetBinContent(i));
		fitncohe->SetBinContent(i,parameter[1]*hncohe->GetBinContent(i));
		fitit->SetBinContent(i,TMath::Sqrt(parameter[0]*parameter[1])*(TMath::Cos(parameter[2])*hcosfiint->GetBinContent(i)+TMath::Sin(parameter[2])*hsinfiint->GetBinContent(i)));
		fitninco->SetBinContent(i,parameter[3]*hninco->GetBinContent(i));
		if (i == 1) {
			accfit[0] = fithist->GetBinContent(1);
			acchist[0] = yieldhist->GetBinContent(1);
			acchisterr[0] = yieldhist->GetBinError(1) * yieldhist->GetBinError(1);
		}
		if (i != fit_nangle) {
			acchist[i] = yieldhist->GetBinContent(i) + acchist[i - 1];
			accfit[i] = fithist->GetBinContent(i) + accfit[i - 1];
			acchisterr[i] = acchisterr[i - 1] + yieldhist->GetBinError(i) * yieldhist->GetBinError(i);
		}
	}

	for(int i = 0; i < fit_nangle; ++i) {
		
		diff[i] = acchist[i] - accfit[i];
		acchisterr[i] = sqrt(acchisterr[i]);
	}

	TString outfilename("fyield" + uimanager.input_filename("fit"));

	float angles[fit_nangle], ex[fit_nangle];
	for(int i=0;i<fit_nangle;i++) {
		angles[i] = 0.02*(i+0.5);
        ex[i] = 0;
    }

	TGraphErrors ge(fit_nangle, angles, diff, ex, acchisterr);
	TGraphErrors ge1(fit_nangle, angles, acchist, ex, acchisterr);
	TGraph ge2(fit_nangle, angles, accfit);

	TCanvas *c1 = new TCanvas("c1","c1",1600,1200);
	c1->SaveAs(outfilename+".pdf[");
	yieldhist->SetMinimum(0);
	yieldhist->SetMaximum(yieldhist->GetMaximum()*1.05);
	yieldhist->Draw("e1");
	fitcoulm->SetLineColor(kBlue);
	fitcoulm->Draw("sameC");
	fitncohe->SetLineColor(32);
	fitncohe->Draw("sameC");
	fitit->SetLineColor(kBlack);
	fitit->Draw("sameC");
	fitninco->SetLineColor(kYellow);
	fitninco->Draw("sameC");
	fithist->SetLineColor(kRed);
	fithist->Draw("sameC");

	TLegend *leg = new TLegend(0.1,0.7,0.45,0.9);
	leg->SetFillColor(0);
	leg->SetTextSize(0.03);
	leg->AddEntry(fitcoulm,"Primakoff","L");
	leg->AddEntry(fitncohe,"Nuclear Coherent","L");
	leg->AddEntry(fitit,"Interference","L");
	leg->AddEntry(fitninco,"Nuclear Incoherent","L");
	//leg->Draw();

	c1->SaveAs(outfilename+".pdf");

	ge.SetMarkerStyle(20);
	ge.SetMarkerColor(kBlue);
	ge.SetTitle("accumulated yield - fit vs. #theta");
	ge.Draw("ap");
	c1->SaveAs(outfilename + ".pdf");

	ge1.SetMarkerStyle(20);
	ge1.SetMarkerColor(kBlue);
	ge1.SetTitle("accumulated yield and fitting vs. #theta");
	ge1.Draw("ap");
	ge2.SetLineColor(kRed);
	ge2.Draw("sameC");
	c1->SaveAs(outfilename + ".pdf");

	c1->SaveAs(outfilename+".pdf]");

	TFile *ftyd = new TFile(outfilename+".root", "RECREATE");
	yieldhist->Write();
	fithist->Write();
	fitcoulm->Write();
	fitncohe->Write();
	fitit->Write();
	fitninco->Write();
    hcoulm->Write();
    hncohe->Write();
    hninco->Write();
	hcosfiint->Write();
    hsinfiint->Write();
    ftyd->Close();
    
	return 0;
}