double Prediction::GetLimitedRatio(TH1D* h1, TH1D* h2, float min, float max, bool binomial, float &relerror){
	if(h1->GetNbinsX() != h2->GetNbinsX()){cout << "GetIntegral ERROR! " << endl; exit(-1);}
	TH1D* h1cp = h1->Clone("h1cp");
	TH1D* h2cp = h2->Clone("h2cp");
	for(int i=1; i<=h1cp->GetNbinsX(); ++i){
		if(h1cp->GetBinLowEdge(i) <min || h1cp->GetBinLowEdge(i)+h1cp->GetBinWidth(i) >max){
			h1cp->SetBinContent(i, 0);
			h1cp->SetBinError(i, 0);
			h2cp->SetBinContent(i, 0);
			h2cp->SetBinError(i, 0);
		}
	}
	TH1D* h1cp_2 = GetScaledHisto(h1cp, 1, 0, h1cp->GetNbinsX());
	TH1D* h2cp_2 = GetScaledHisto(h2cp, 1, 0, h1cp->GetNbinsX());

	TH1D* r      = h1cp_2->Clone("r");
	r->Divide(h1cp_2, h2cp_2, 1, 1, binomial? "B":"");

	*fLogStream << "Getting Limited Ratio for " << h1->GetName()  << " " << h2->GetName() << endl;
	*fLogStream << ">>> ratio = " << r->GetBinContent(1)  << " pm " << r->GetBinError(1) << endl;
	if(fDoRatioStatErr){
		relerror = r->GetBinError(1)/r->GetBinContent(1);
	}
	double  ratio = r->GetBinContent(1);
	delete h1cp;
	delete h2cp;
	delete h1cp_2;
	delete h2cp_2;
	delete r;
	return ratio;
}
TH1D* Prediction::GetScaledHisto(TH1D* histo, float scale_fact, float scale_fact_err){
	// takes histo, scale factor and uncertainty on scale factor
	// and returns scaled and rebinned histo with 1 bin with uncertainty on scale factor propagated.
	TH1D *h        = (TH1D*) histo->Clone(histo->GetName());
	h->Rebin(h->GetNbinsX());
	h->SetBinError(1, sqrt(h->GetBinError(1)*  h->GetBinError(1)   *scale_fact    *scale_fact + 
			  h->GetBinContent(1)*h->GetBinContent(1) *scale_fact_err*scale_fact_err));
	h->SetBinContent(1, h->GetBinContent(1)*scale_fact);
	return h;
}
TH1D* Prediction::GetScaledHisto(TH1D* histo, float scale_fact, float scale_fact_err, int ngroup){
	// takes histo, scale factor and uncertainty on scale factor
	// and returns scaled and rebinned histo with ngroup bins merged into 1 with uncertainty on scale factor propagated.
	if(ngroup>=histo->GetNbinsX()) ngroup=histo->GetNbinsX();
	TH1D *h        = (TH1D*) histo->Clone(histo->GetName());
	h->Rebin(ngroup);
	for(int i=1; i<=h->GetNbinsX(); ++i){
		h->SetBinError(i, sqrt(h->GetBinError(i)*  h->GetBinError(i)   *scale_fact    *scale_fact + 
				  h->GetBinContent(i)*h->GetBinContent(i) *scale_fact_err*scale_fact_err));
		h->SetBinContent(i, h->GetBinContent(i)*scale_fact);
	}
	return h;
}
Exemplo n.º 4
0
TH1D *
GetITSTPCSpectrum(TFile *file, Int_t part, Int_t charge, Int_t cent)
{
  TList *list = (TList *)file->Get("output");
  TH1D *hin = (TH1D *)list->FindObject(Form("h_%s_%s_cen_%d", ITSTPCPartName[part], ITSTPCChargeName[charge], cent + 1));
  if (!hin) return NULL;

  TH1D *h = new TH1D(Form("hITSTPC_cent%d_%s_%s", cent, AliPID::ParticleName(part), chargeName[charge]), "ITSTPC", NptBins, ptBin);
  Double_t pt, width, value, error;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }
  
#if 0
  /* add systematic error */
  Double_t sys;
  if (part == 2) sys = 0.5;
  else sys = 0.1;
  Double_t cont, conte;
  for (Int_t ipt = 0; ipt < h->GetNbinsX(); ipt++) {
    cont = h->GetBinContent(ipt + 1);
    conte = h->GetBinError(ipt + 1);
    conte = TMath::Sqrt(conte * conte + sys * sys * cont * cont);
    h->SetBinError(ipt + 1, conte);
  }
#endif
  
  h->SetTitle("ITSTPC");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(21);
  h->SetMarkerColor(2);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  return h;
}
Exemplo n.º 5
0
void MergeOverflow(TH1D &h, bool merge_underflow, bool merge_overflow) {
    if(merge_underflow) {
        h.SetBinContent(1, h.GetBinContent(0)+h.GetBinContent(1));
        h.SetBinContent(0, 0.);
        h.SetBinError(1, hypot(h.GetBinError(0), h.GetBinError(1)));
        h.SetBinError(0, 0.);
    }
    int nbins = h.GetNbinsX();
    if(merge_overflow) {
        h.SetBinContent(nbins, h.GetBinContent(nbins)+h.GetBinContent(nbins+1));
        h.SetBinContent(nbins+1, 0.);
        h.SetBinError(nbins, hypot(h.GetBinError(nbins), h.GetBinError(nbins+1)));
        h.SetBinError(nbins+1, 0.);
    }
}
Exemplo n.º 6
0
TH1D* ratio_hist_to_func(TH1D* num, double par0, double par1, double par2) {
    cout<<"[Ratio to fit used]"<<endl;

    TH1D *hRatio = (TH1D*) num->Clone("hRatio");

    TF1 *f3 = new TF1("f3","[0]*(1+(sqrt(0.1396**2+x**2)-0.1396)/([1]*[2]))**(-[2])",0,6.5);
    f3->SetParameters(par0,par1,par2);
    //f3->SetLineColor(2);

    int nbin = num->GetEntries();
    for(int i=0; i<nbin; i++) {

        double cms_value = (double) f3->Eval(hRatio->GetBinCenter(i+1));

        if(hRatio->GetBinCenter(i+1)>0.4 && hRatio->GetBinCenter(i+1)<6.0) {
            //double ratio = cms_value/hRatio->GetBinContent(i+1);
            //double ratio_err = cms_value/hRatio->GetBinError(i+1);
            double ratio = hRatio->GetBinContent(i+1)/cms_value;
            double ratio_err = hRatio->GetBinError(i+1)/cms_value;
        } else {
            double ratio = -999;
            double ratio_err = 0.0;
        }
        //double ratio = hRatio->GetBinContent(i+1)/cms_value;
        //double ratio_err = hRatio->GetBinError(i+1)/cms_value;
        hRatio->SetBinContent(i+1,ratio);
        hRatio->SetBinError(i+1,ratio_err);
    }

    return hRatio;

}
void createSysStatErrorHist(TH1D *hist_pre){

  TH1D *histErr = (TH1D*) hist_pre->Clone("histErr");
  hsyserr = (TH1D*) hist_pre->Clone("hsyserr"), hsyserr->Reset();
  hsyserr->Sumw2();

  cout<<""<<endl;
  for(int i=0;i<histErr->GetNbinsX();i++){ // last bin is meaningless
    double pt = histErr->GetBinCenter(i+1);
    double statferr = histErr->GetBinError(i+1)/histErr->GetBinContent(i+1);
    if(i==(histErr->GetNbinsX()-1)) statferr = 0.9;
    //double sysferr = fsyserr->Eval(pt);
    double sysferr = returnCombinedSysError(pt);
    double sumferr = sqrt(statferr*statferr + sysferr*sysferr);
    //double sumerr = 1.*(sumferr/100);
    double sumerr = 1.*sumferr;
    hsyserr->SetBinContent(i+1,1);
    hsyserr->SetBinError(i+1,sumerr);
    //hsyserr->SetBinError(i+1,0.5); 
    cout<<"[setSysStatError] stat err (frac): "<<statferr<<" syst err (fac): "<<sysferr<<" combined (frac): "<<sumferr<<endl;
  }

  //tsyserr = (TGraphErrors*) TgraphIt(hsyserr);

}
Exemplo n.º 8
0
void QinvKstar (const char* filename, const char* histname) {

	TFile*  fileIn = new TFile(filename,"update");
	TH1D* hist = (TH1D*)fileIn->Get(histname);
	TH1D* histnew = new TH1D(Form("kstar_%s",histname),"",hist->GetNbinsX(),0,0.25);//(TH1D*)fileIn->Get(histname);

//   for (int ibins = 1; ibins <= hist->GetNbinsX()*2; ibins++ ) {
//     hist->SetBinContent(ibins, hist->GetBinContent(ibins));
//     //    hist->SetBinContent(ibins, hist->GetBinContent(ibins));
//   }

	int bin=2;//1

	for (double kstar = 0.00375; kstar <= 0.25; kstar += 0.0025 ) {

//	for (double kstar = 0.00375; kstar <= 0.25; kstar += 0.0025 ) {
		//  for (double kstar = 0.005; kstar <= 0.25; kstar += 0.01 ) {
		//        hist->Fill(kstar,hist->GetBinContent(hist->FindBin(kstar*2)));

		histnew->SetBinContent(bin,hist->GetBinContent(hist->FindFixBin(kstar*2)));
		histnew->SetBinError(bin++,hist->GetBinError(hist->FindFixBin(kstar*2)));

		//    hist->SetBinContent(ibins, hist->GetBinContent(ibins));
		//    hist->SetBinContent(ibins, hist->GetBinContent(ibins));
	}

	TFile* fileOut = new TFile(Form("kstar_%s",filename), "update");
	hist->Write();
	histnew->Write();
}
Exemplo n.º 9
0
CombineSpectra(TH1D *h, TObjArray *oa)
{

  /* combine with weighted mean */
  Double_t ptcen, w, sumw, mean, meane, cont, conte, syse, tote, minvalue, maxvalue, maxerror, maxmindiff;
  Int_t ptbin;
  TH1D *hin;
  for (Int_t ipt = 0; ipt < h->GetNbinsX(); ipt++) {
    mean = 0.;
    sumw = 0.;
    minvalue = kMaxInt;
    maxvalue = 0.;
    maxerror = 0.;
    ptcen = h->GetBinCenter(ipt + 1);
    TProfile prof(Form("prof_%d", ipt), "", 1, 0., 1.); /* to get RMS */
    for (Int_t ih = 0; ih < oa->GetEntries(); ih++) {
      hin = (TH1D *)oa->At(ih);
      ptbin = hin->FindBin(ptcen);
      if (ptbin <= 0.) continue;
      cont = hin->GetBinContent(ptbin);
      conte = hin->GetBinError(ptbin);
      if (cont == 0. || conte == 0.)
	continue;
      w = 1. / (conte * conte);
      mean += cont * w;
      sumw += w;
      if (cont < minvalue)
	minvalue = cont;
      if (cont > maxvalue)
	maxvalue = cont;
      if (conte > maxerror)
	maxerror = conte;
      prof.Fill(0., cont);
    }
    if (sumw == 0.) {
      mean = 0.;
      meane = 0.;	
      syse = 0.;
      tote = 0.;
    }
    else {
      mean /= sumw;
      meane = TMath::Sqrt(1. / sumw);
      syse = 0.5 * (maxvalue -  minvalue);
      tote = TMath::Sqrt(meane * meane + syse * syse);
      //      if (tote < maxerror)
      //	tote = maxerror;
    }

    //    printf("pt = %f, mean = %f, meane = %f, syse = %f, tote = %f\n", ptcen, mean, meane, syse, tote);
    
    //    syse = prof.GetBinError(1);
    h->SetBinContent(ipt + 1, mean);
    h->SetBinError(ipt + 1, tote);
    //    h->SetBinError(ipt + 1, TMath::Sqrt(meane * meane + syse * syse + mean * mean * 0.1 * 0.1)); /* add extra 10% systematics */
  }

}
Exemplo n.º 10
0
void XS1S_Rap(){
  
  TFile *f = new TFile("XSection.root");
  TH1D *H;
  H = (TH1D*)gFile->Get("S1YieldEta");
  double tot(0.); double totE(0.); 
  
  ofstream OUT("XS_1S_rap.tex");
  OUT << "% ----------------------------------------------------------------------" << endl;
  OUT << "% -- Yields" << endl;
  for ( int x = 1; x <= H->GetNbinsX(); ++x ){
    OUT << Form("\\vdef{XS_rap%iS_bin%iContent} {\\ensuremath{ {%.3f } } }",1, x, H->GetBinContent(x)*H->GetBinWidth(x) ) << endl;
    OUT << Form("\\vdef{XS_rap%iS_bin%iError} {\\ensuremath{ {%.3f } } }",1, x, H->GetBinError(x)*H->GetBinWidth(x) ) << endl;
    tot += H->GetBinContent(x)*H->GetBinWidth(x);
    totE += (H->GetBinError(x)*H->GetBinWidth(x)*H->GetBinWidth(x)*H->GetBinError(x));
  }
		
  OUT << Form("\\vdef{sum%iS} {\\ensuremath{ {%.4f } } }",1, tot) << endl;
  OUT << Form("\\vdef{sum%iSError} {\\ensuremath{ {%.4f } } }",1 , TMath::Sqrt(totE) ) << endl;
  OUT.close();
  
}
Exemplo n.º 11
0
TH1D *
GetITSsaSpectrum(TFile *file, Int_t part, Int_t charge, Int_t cent, Bool_t cutSpectrum = kTRUE, Bool_t addSystematicError = kTRUE)
{
  /* pt limits for combined spectra */
  Double_t ptMin[AliPID::kSPECIES] = {0., 0., 0.1, 0.2, 0.3};
  Double_t ptMax[AliPID::kSPECIES] = {0., 0., 0.6, 0.5, 0.6};

  TList *list = (TList *)file->Get("output");
  TH1D *hin = (TH1D *)list->FindObject(Form("h_%s_%s_cen_%d", ITSsaPartName[part], ITSsaChargeName[charge], cent));
  if (!hin) return NULL;  

  /* get systematics */
  TFile *fsys = TFile::Open("SPECTRASYS_ITSsa.root");
  TH1 *hsys = fsys->Get(Form("hSystTot%s%s", ITSsaChargeName[charge], ITSsaPartName[part]));
			
  TH1D *h = new TH1D(Form("hITSsa_cent%d_%s_%s", cent, AliPID::ParticleName(part), chargeName[charge]), "ITSsa", NptBins, ptBin);
  Double_t pt, width, value, error, sys;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin[part] || pt > ptMax[part])) continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    /*** TEMP ADD SYS ***/
    if (addSystematicError) {
      sys = hsys->GetBinContent(bin) * value;
      error = TMath::Sqrt(error * error + sys * sys);
    }
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }

  h->SetTitle("ITSsa");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(20);
  h->SetMarkerColor(1);
  h->SetFillStyle(0);
  h->SetFillColor(0);

  return h;
}
Exemplo n.º 12
0
UpsilonYields getValFromTH1D(TString kineLabel) {
  
  UpsilonYields yields;
  TString fname = Form("fitResults/fixParam1MuPt4_Feb02/fitresults_upsilon_singleCB_%s.root",kineLabel.Data());
  cout << "opening " << fname << " ....." <<endl;
  TFile* f1 = new TFile(fname.Data() );
  if ( f1->IsZombie() )  {
    cout << " no such a file exists..." << endl << endl;
    yields.yield1s = -1 ;     yields.err1s = -1 ; 
    yields.yield2s = -1 ;     yields.err2s = -1 ; 
    yields.yield3s = -1 ;     yields.err3s = -1 ; 
  }
  else { 
    TH1D* h = (TH1D*)f1->Get("fitResults");
    
    yields.yield1s =    h->GetBinContent(1);
    yields.err1s = h->GetBinError (1);
    yields.yield2s =    h->GetBinContent(2);
    yields.err2s = h->GetBinError (2);
    yields.yield3s =    h->GetBinContent(3);
    yields.err3s = h->GetBinError (3);
    yields.r23o123 = h->GetBinContent(4);
    yields.err23o123 = h->GetBinError(4);
    yields.r23o1 = h->GetBinContent(5);
    yields.err23o1 = h->GetBinError(5);

    cout << " 1s = " << yields.yield1s << " +/- " << yields.err1s << endl;
    cout << " 2s = " << yields.yield2s << " +/- " << yields.err2s << endl;
    cout << " 3s = " << yields.yield3s << " +/- " << yields.err3s << endl;
    cout << " (2S+3S)/(1S+2S+3S) = " << yields.r23o123 << " +/- " <<  yields.err23o123 << endl;
    cout << " (2S+3S)/1S = " << yields.r23o1 << " +/- " <<  yields.err23o1 << endl;
    f1->Close();
  }
  cout << "*===*===*===*===*===*===*===*===*===*===*===*===*===*===*"<<endl;
  return yields;
    
}
Exemplo n.º 13
0
void Yield1S_1D(){
  
  TFile *f = new TFile("SigmaDATA_RapInt_3SBin.root");
  TH1D *H;
  H = (TH1D*)gFile->Get("hYield1S");
  double tot(0.); double totE(0.); 
  
  ofstream OUT("Yield_1S_1D.tex");
  OUT << "% ----------------------------------------------------------------------" << endl;
  OUT << "% -- Yields" << endl;
  for ( int x = 1; x <= H->GetNbinsX(); ++x ){
    OUT << Form("\\vdef{%iS_bin%iLowEdge} {\\ensuremath{ {%.2f } } }",1, x, H->GetXaxis()->GetBinLowEdge(x) ) << endl;
    if ( x == H->GetNbinsX() ) OUT << Form("\\vdef{%iS_bin%iHighEdge} {\\ensuremath{ {%.2f } } }",1 , x, H->GetXaxis()->GetBinUpEdge(x) ) << endl;
    OUT << Form("\\vdef{%iS_bin%iContent} {\\ensuremath{ {%.0f } } }",1, x, H->GetBinContent(x) ) << endl;
    OUT << Form("\\vdef{%iS_bin%iError} {\\ensuremath{ {%.0f } } }",1, x, H->GetBinError(x) ) << endl;
    tot += H->GetBinContent(x);
    totE += (H->GetBinError(x)*H->GetBinError(x));
  }
		
  OUT << Form("\\vdef{sum%iS} {\\ensuremath{ {%.0f } } }",1, tot) << endl;
  OUT << Form("\\vdef{sum%iSError} {\\ensuremath{ {%.0f } } }",1 , TMath::Sqrt(totE) ) << endl;
  OUT.close();
  
}
Exemplo n.º 14
0
double countDataError(TChain* chain, TCut cut)
{
  // Create temporary histogram
  TH1D* tmp = new TH1D("tmp", "tmp", 30, 0, 1000);

  double DataError = 0;
  tmp->Sumw2();
  chain->Draw("Njet>>tmp", cut, "goff");

  for(int i=0; i<=(tmp->GetNbinsX()+1); i++)
    DataError += tmp->GetBinError(i);

  delete tmp;
  return DataError;
}
Exemplo n.º 15
0
void AdjustDensityForBinWidth(TH1D &h) {
    double entries = h.GetEntries();
    int nbins = h.GetNbinsX();
    double low = h.GetBinLowEdge(1);
    double high = h.GetBinLowEdge(nbins+1);
    double width = (high-low)/nbins;
    for(int bin = 1; bin <= nbins; ++bin) {
        double content = h.GetBinContent(bin);
        double error = h.GetBinError(bin);
        double this_width = h.GetBinWidth(bin);
        double scale = width/this_width;
        h.SetBinContent(bin, content*scale);
        h.SetBinError(bin, error*scale);
    }
    h.SetEntries(entries);
}
Exemplo n.º 16
0
/** Personalized
build a TGraphError starting from a TH1F
*/
TGraphErrors buildGEfromH_Personalized (const TH1D & histo) 
{
 TVectorF xV(histo.GetNbinsX());
 TVectorF yV(histo.GetNbinsX());
 TVectorF errxV(histo.GetNbinsX());
 TVectorF erryV(histo.GetNbinsX());
 for (int iBin = 0; iBin<histo.GetNbinsX(); iBin++){
  xV[iBin] = histo.GetBinCenter(iBin);
  yV[iBin] = histo.GetBinContent(iBin);
  errxV[iBin] = 0;
//   histo.GetBinWidth(iBin);
  erryV[iBin] = histo.GetBinError(iBin);
 }  
 TGraphErrors g (xV, yV, errxV, erryV) ;
 return g ;
}
Exemplo n.º 17
0
// Rebin first histogram to match the second
TH1D *tools::Rebin(const TH1D *h, const TH1D* href) {

  //assert(href->GetNbinsX()<=h->GetNbinsX());
  if (!(href->GetNbinsX()<=h->GetNbinsX())) {
    cout << "Histo has less bins than ref: "
	 << h->GetNbinsX() << " vs " << href->GetNbinsX()
	 << " for " << h->GetName() << endl;
  }
  
  // First, we need to rebin inclusive jets to match b-tagged jets
  TH1D *hre = (TH1D*)href->Clone(Form("%s_rebin",h->GetName()));
  hre->Reset();

  for (int i = 1; i != h->GetNbinsX()+1; ++i) {

    double x = h->GetBinLowEdge(i);
    int j = hre->FindBin(x);
    // Check that h is fully contained within href bin
    if (h->GetBinContent(i)!=0) {

      if (!(h->GetBinLowEdge(i)>=hre->GetBinLowEdge(j) - 1e-5 &&
	    h->GetBinLowEdge(i+1)<=hre->GetBinLowEdge(j+1) + 1e-5)) {
	cerr << Form("Warning, bin edges overlapping: h=[%1.0f,%1.0f],"
		     " hre=[%1.0f,%1.0f] (%s)",
		     h->GetBinLowEdge(i), h->GetBinLowEdge(i+1),
		     hre->GetBinLowEdge(j), hre->GetBinLowEdge(j+1),
		     h->GetName()) << endl;
      }

      double y = ( hre->GetBinContent(j)*hre->GetBinWidth(j)
		   + h->GetBinContent(i)*h->GetBinWidth(i) )
	/ hre->GetBinWidth(j);
      //double ey = ( hre->GetBinError(j)*hre->GetBinWidth(j)
      //	    + h->GetBinError(i)*h->GetBinWidth(i) )
      // / hre->GetBinWidth(j);
      double ey = sqrt( pow(hre->GetBinError(j)*hre->GetBinWidth(j),2)
			+ pow(h->GetBinError(i)*h->GetBinWidth(i),2) )
	/ hre->GetBinWidth(j);
      hre->SetBinContent(j, y);
      hre->SetBinError(j, ey);
    }
  } // for i

  return hre;
} // Rebin
Exemplo n.º 18
0
// A function to make a new histogram by combining the contents of selected
// consecutive bins in an input histogram.  Useful to produce variable-bin-size
// histograms from fixed-bin-size ones, particularly for regions of phase space
// which lack statistics.
TH1D* CombineBins(TH1D inhisto, float xmin, float xmax)
{
  int startbin = inhisto.FindBin(xmin);
  int endbin = inhisto.FindBin(xmax);

  if (startbin >= endbin) return 0;

  const int newNbins = inhisto.GetNbinsX() - endbin + startbin;

  Double_t edgeArr[newNbins+1];

  for (int i=0; i<=newNbins; ++i) {
    int skipbin = 0;
    if (i>=startbin) skipbin = endbin - startbin;
    edgeArr[i] = inhisto.GetBinLowEdge(i+1+skipbin);
  }

  TH1D *newhist = new TH1D("newhist",inhisto.GetTitle(),newNbins,edgeArr);
  newhist->GetYaxis()->SetTitle(inhisto.GetYaxis()->GetTitle());
  newhist->GetXaxis()->SetTitle(inhisto.GetXaxis()->GetTitle());
  bool sw2 = ( inhisto.GetSumw2N() != 0 );

  // Starting from the new underflow bin, up to the new overflow bin,
  // copy contents for the "untouched" bins. For the new "combination"
  // bin, copy only the startbin
  for (int i=0; i<=newNbins+1; ++i) {
    int skipbin = 0;
    if (i>startbin) skipbin = endbin - startbin;
    newhist->SetBinContent(i, inhisto.GetBinContent(i+skipbin));
    if ( sw2 ) newhist->SetBinError(i, inhisto.GetBinError(i+skipbin));
  }

  // Now we have to handle the "combination" bin. We need to add
  // everything from startbin+1 to endbin. 
  for (int i=startbin+1; i<=endbin; ++i) {
    newhist->SetBinContent(startbin, newhist->GetBinContent(startbin)
			   +inhisto.GetBinContent(i));
    if ( sw2 ) newhist->SetBinError(startbin, sqrt(pow(newhist->GetBinError(startbin),2)+
						   pow(inhisto.GetBinError(i),2)));
  }

  return newhist;
}
Exemplo n.º 19
0
TH1D *
GetTPCTOFSpectrum(TFile *file, Int_t part, Int_t charge, Int_t cent, Bool_t cutSpectrum = kTRUE)
{
  /* pt limits for combined spectra */
  Double_t ptMin[AliPID::kSPECIES] = {0., 0., 0., 0., 0.};
  Double_t ptMax[AliPID::kSPECIES] = {0., 0., 1.2, 1.2, 1.8};

  TH1D *hin = (TH1D *)file->Get(Form("%sFinal%s%d", TPCTOFPartName[part], TPCTOFChargeName[charge], cent));
  if (!hin) return NULL;

  TH1D *h = new TH1D(Form("hTPCTOF_cent%d_%s_%s", cent, AliPID::ParticleName(part), chargeName[charge]), "TPCTOF", NptBins, ptBin);
  Double_t pt, width, value, error;
  Int_t bin;
  for (Int_t ipt = 0; ipt < NptBins; ipt++) {
    /* get input bin */
    pt = h->GetBinCenter(ipt + 1);
    width = h->GetBinWidth(ipt + 1);
    bin = hin->FindBin(pt);
    /* sanity check */
    if (TMath::Abs(hin->GetBinCenter(bin) - pt) > 0.001 ||
	TMath::Abs(hin->GetBinWidth(bin) - width) > 0.001)
      continue;
    /* check pt limits */
    if (cutSpectrum && (pt < ptMin[part] || pt > ptMax[part])) continue;
    /* copy bin */
    value = hin->GetBinContent(bin);
    error = hin->GetBinError(bin);
    h->SetBinContent(ipt + 1, value);
    h->SetBinError(ipt + 1, error);
  }
  
  h->SetTitle("TPCTOF");
  h->SetLineWidth(1);
  h->SetLineColor(1);
  h->SetMarkerStyle(22);
  h->SetMarkerColor(8);
  h->SetFillStyle(0);
  h->SetFillColor(0);
  
  return h;
}
Exemplo n.º 20
0
Spectrum roothist_to_spectrum(const TH1D & hist, const TH2D * cov, bool use_hist_uncertainties){
    const int n = hist.GetNbinsX();
    if(cov){
        if(cov->GetDimension() != 2 || cov->GetNbinsX() != n || cov->GetNbinsY() != n){
            throw runtime_error(string("covariance histogram '") + cov->GetName() + "' has wrong dimension");
        }
    }
    Spectrum s(n);
    for(int i=0; i<n; ++i){
        double c = hist.GetBinContent(i+1);
        if(!isfinite(c)){
            throw runtime_error(string("non-finite entry in histogram '") + hist.GetName() + "'");
        }
        s[i] = c;
        if(use_hist_uncertainties){
            double e = hist.GetBinError(i+1);
            if(!isfinite(e)){
                throw runtime_error(string("non-finite error in histogram '") + hist.GetName() + "'");
            }
            s.cov()(i,i) += e*e;
        }
    }
    if(cov){
        for(int i=0; i<n; ++i){
            for(int j=0; j<n; ++j){
                double c_ij = cov->GetBinContent(i+1, j+1);
                double c_ji = cov->GetBinContent(j+1, i+1);
                if(!isfinite(c_ij)){
                    throw runtime_error(string("covariance histogram '") + cov->GetName() + "' does have non-finite entry");
                }
                if(fabs(c_ij - c_ji) > 1e-8 * max(fabs(c_ij), 1.0)){
                    cerr << "covariance histogram '" << cov->GetName() <<  "' is not symmetric: C(" << i << ","<< j << ") = " << c_ij << "; transposed: " << c_ji << "; diff = " << (c_ij - c_ji) << endl;
                }
                s.cov()(i,j) += c_ij;
            }
        }
    }
    return s;
}
Exemplo n.º 21
0
void fitpapvar(const char* infilename, const char* histname) {
  TFile* infile = new TFile(Form("%s",infilename),"read");
  TH1D* hcf = (TH1D*)infile->Get(histname);
  hcf->GetXaxis()->SetRangeUser(0,2);

   TF1 *fc2 = new TF1("fc2","[3]+[2]*TMath::Gaus(x,[0],[1])",0.4,1);
   fc2->SetParameters(1.5,0.3,-0.2,1);

  // TF1 *fc2 = new TF1("fc2","[1]+[0]*x*x",0,1);
  // fc2->SetParameters(-0.01,1.0);

  // TF1 *fc2 = new TF1("fc2","[2]+[1]*x*x*x*x*x",0,1);
  // fc2->SetParameters(-0.01,0.01,1.0);

  // TF1 *fc2 = new TF1("fc2","[3]+[2]*x*x+[1]*x*x*x+[0]*x*x*x*x",0.,1);
  // fc2->SetParameters(-0.01,0.01,1.0,1.0);

  hcf->Fit("fc2","r","",0.3,1);
  TH1D* hnew = new TH1D("hnew","hnew",hcf->GetNbinsX(),0,1);
  for(int i=1;i<=hcf->GetNbinsX();++i){
    // cout << i << endl;
    // cout << hcf->GetBinContent(i)/fc2->Eval(2.*i/hcf->GetNbinsX()) << endl;
    // cout << hcf->GetBinContent(i) << endl;
    // cout << fc2->Eval(2.*i/hcf->GetNbinsX()) << endl << endl;
    hnew->SetBinContent(i, hcf->GetBinContent(i)/fc2->Eval(1.*i/hcf->GetNbinsX()));
    hnew->SetBinError(i, hcf->GetBinError(i));

  }
  hnew->Draw("same");
  fc2->Draw("same");
  hnew->SetName(Form("divp4%s",histname));
  TFile* ofile = new TFile(Form("divp4%s",infilename),"update");
  hnew->Write();
  hcf->Write();
  ofile->Close();
}
TCanvas *drawRatioPlot(TH1D *prediction, TH1D *sr, TH1D *data, TString xTitle, TString filename, double ecaloCut){

  gStyle -> SetPadLeftMargin(0.20);

  data->SetMarkerStyle(20);
  data->SetMarkerColor(kGreen);
  data->SetLineColor(kGreen);


  
  TCanvas *c = new TCanvas("c"+filename,"c",0,0,500,500);

  float y = 0.3;

  TPad *pad1     = new TPad("pad1", "Control Plots 1", 0.01, y, 0.99, 0.99);
  TPad *padRatio = new TPad("rp1", "Ratio1", 0.01, 0.01, 0.99, y-0.01);

  pad1->SetNumber(100);
  pad1->SetTicks(0,1);
  cout<<"number pad1     = "<<pad1->GetNumber()<<endl;
  cout<<"number padRatio = "<<padRatio->GetNumber()<<endl;

  TH1D *ratio = 0;

  //ratio = (TH1D*) sr->Clone();
  //ratio->Divide(prediction);

  ratio = (TH1D*) prediction->Clone();
  ratio->Divide(data);



  for(int i=1; i<=ratio->GetNbinsX();i++){

    if(ratio->GetBinContent(i) != 0){
      cout<<"N in CR in "<<i<<". bin ="<<prediction->GetBinContent(i)<<endl;
      cout<<"N in SR in "<<i<<". bin ="<<sr->GetBinContent(i)<<endl;
      cout<<"Rel. difference in "<<i<<". bin ="<<(1./ratio->GetBinContent(i)-1.)*100<<"%"<<endl; 
    }
    else if(sr->GetBinContent(i) == 0 && prediction->GetBinContent(i) !=0)    cout<<"Scaling Factor in "<<i<<". bin <"<<prediction->GetBinContent(i)/1.15<<" +/- "<<ratio->GetBinError(i)<<endl;
    else if(sr->GetBinContent(i) != 0 && prediction->GetBinContent(i) ==0)    cout<<"Scaling Factor in "<<i<<". bin <"<<(sr->GetEntries()/prediction->GetEntries())/sr->GetBinContent(i)<<" +/- "<<ratio->GetBinError(i)<<endl;

  }

  ratio->GetYaxis()->SetTitle("#frac{CR (MC)}{CR (data)}");
  ratio->SetTitle("");
  ratio->SetLabelSize(0.1,"X");
  ratio->SetLabelSize(0.1,"Y");
  ratio->SetTitleOffset(0.5,"Y");
  ratio->SetTitleSize(0.15,"Y");


  padRatio->cd();
  //ratio->GetYaxis()->SetRangeUser(0,2);
  ratio->Draw("e");

  // Draw line at one!
  float xmin = ratio->GetXaxis()->GetXmin();
  float xmax = ratio->GetXaxis()->GetXmax();
  TLine *line = new TLine(xmin,1,xmax,1);
  line->SetLineWidth(2);
  line->Draw("same");
  padRatio->Modified();

  TLegend *leg = new TLegend(0.5,0.7,0.9,0.9);
  leg->AddEntry(sr,"SR (MC)","l"); 
  leg->AddEntry(prediction,"lepton CR (MC)","pel"); 
 
  pad1->cd();
  pad1->SetLogy();
  //  pad1->SetLogx();

  sr->SetLineColor(kRed);
  sr->SetMarkerColor(kRed);
  sr->SetMarkerStyle(20);
  sr->SetTitle("");
  prediction->SetMarkerStyle(20);
  prediction->SetTitle("");
  prediction->GetXaxis()->SetTitle(xTitle);
  sr->GetXaxis()->SetTitle(xTitle);

  
  

  prediction->SetTitleSize(0.07,"X");
  prediction->GetXaxis()->SetTitleOffset(0.7);
  sr->SetTitleSize(0.07,"X");
  sr->GetXaxis()->SetTitleOffset(0.7);

  double maximum = 0;
  double minimum = 1000000;
  if(sr->GetMinimum()!=0 && sr->GetMinimum()<minimum){
    minimum=sr->GetMinimum()*0.5;
  }
  if(prediction->GetMinimum()!=0 && prediction->GetMinimum()<minimum){
    minimum=prediction->GetMinimum()*0.5;
  }
  if(data->GetMinimum()!=0 && data->GetMinimum()<minimum){
    minimum=data->GetMinimum()*0.5;
  }
  if(sr->GetMaximum()>maximum){
    maximum=sr->GetMaximum()*2.5;
  }
  if(prediction->GetMaximum()>maximum){
    maximum=prediction->GetMaximum()*2.5;
  }
  if(data->GetMaximum()>maximum){
    maximum=data->GetMaximum()*2.5;
  }

  prediction->GetYaxis()->SetRangeUser(minimum,maximum);
  ratio->GetYaxis()->SetRangeUser(0,2);


  prediction->Draw("e");
  sr->Draw("e same");
  leg->AddEntry(data,"lepton CR (data)","pel"); 
  data->Draw("e same");

  
  leg->Draw("same");


  TLatex*  info1   = new TLatex();
  info1->SetTextFont(132);
  info1-> SetNDC();
  info1->SetTextSize(0.06);
  info1->DrawLatex(0.55,0.62,Form("E_{calo}<%.0fGeV",ecaloCut));

  // Draw both pads to canvas
  c->cd();
  pad1->Draw();
  padRatio->SetGridy();
  padRatio->Draw();

  c->SaveAs(filename);

  return c;

}
Exemplo n.º 23
0
void fitDstar5pMinpt(Bool_t genmatchpoint=true)
{
  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);

  void clean0(TH1D* h);  
  TF1* fitDstar(TTree* nt, TTree* ntMC, Float_t ptmin, Bool_t plotgenmatch);

  TFile* infData = new TFile(infnameData5p[isData].Data());
  TFile* infMC = new TFile(infnameMC5p[isData].Data());

  TTree* ntData = (TTree*)infData->Get("ntDD0kpipipipi");
  TTree* ntMC = (TTree*)infMC->Get("ntDD0kpipipipi");
  TTree* ntGen = (TTree*)infMC->Get("ntGen");
  
  ntData->AddFriend("ntHlt");
  if(isData!=Data_MB&&isData!=Data) ntData->AddFriend("ntHi");
  ntMC->AddFriend("ntHlt");
  ntMC->AddFriend("ntHi");
  ntGen->AddFriend("ntHlt");
  ntGen->AddFriend("ntHi");

  Float_t aZero[nBins];
  for(int i=0;i<nBins;i++) aZero[i]=0;
  Float_t aPt[nBins],aPtErr[nBins],aGen[nBins],aGenErr[nBins];
  TH1F* hPt = new TH1F("hPt","",nBins,ptBinsPlus);
  TH1F* hGen = new TH1F("hGen","",nBins,ptBinsPlus);

  for(int i=0;i<nBins;i++)
    {
      TF1* fData = fitDstar(ntData,ntMC,ptBins[i],genmatchpoint);
      Float_t yieldData = fData->Integral(BINMIN,BINMAX)/BINWID;
      Float_t yieldDataErr = fData->Integral(BINMIN,BINMAX)/BINWID*fData->GetParError(0)/fData->GetParameter(0);      
      aPt[i] = yieldData;
      aPtErr[i] = yieldDataErr;
      hPt->SetBinContent(i+1,aPt[i]);
      hPt->SetBinError(i+1,aPtErr[i]);
      TH1D* hGenFill = new TH1D(Form("hGenFill_%.0f",ptBins[i]),"",1,ptBins[i],1.e+3);
      hGenFill->Sumw2();
      ntGen->Project(Form("hGenFill_%.0f",ptBins[i]),"Gpt",TCut("%s",weightmc[isData].Data())*Form("%s&&%s",selgen5p.Data(),triggerselectionmc[isData].Data()));
      aGen[i] = hGenFill->GetBinContent(1);
      aGenErr[i] = hGenFill->GetBinError(1);
      hGen->SetBinContent(i+1,aGen[i]);
      hGen->SetBinError(i+1,aGenErr[i]);
    }

  TGraphErrors* gPt = new TGraphErrors(nBins,ptBins,aPt,aZero,aPtErr);
  gPt->SetName("gPt");
  TGraphErrors* gGen = new TGraphErrors(nBins,ptBins,aGen,aZero,aGenErr);
  gGen->SetName("gGen");

  TFile* outputfile = new TFile(Form("outputfiles/output_5p_%s_Minpt.root",texData[isData].Data()),"recreate");
  outputfile->cd();
  gPt->Write();
  gGen->Write();
  hPt->Write();
  hGen->Write();
  outputfile->Close();
}
Exemplo n.º 24
0
int main(int argc, char* argv[]) {

  TH1::SetDefaultSumw2();

  ProgramOptions options(argc, argv);

  double lumi = options.lumi;

  // input datasets
  Datasets datasets(options.iDir);
  datasets.readFile(options.datasetFile);
 
  std::string oDir_Plot = options.oDir+std::string("/ZBackground");

  boost::filesystem::path opath(oDir_Plot);
  if (!exists(opath)) {
    std::cout << "Creating output directory : " << oDir_Plot << std::endl;
    boost::filesystem::create_directory(opath);
  }
 
  if (options.doMCFMWeights) std::cout << "Going to apply MCFM weights" << std::endl;

  // output file
  TFile* ofile = TFile::Open( (options.oDir+std::string("/ZBackground.root")).c_str(), "RECREATE");

  // cuts
  Cuts cuts;
  unsigned nCutsZMuMu = cuts.nCutsZMuMu();

  TCut puWeight("puWeight");
  TCut trigCorr( "(trigCorrWeight>0) ? trigCorrWeight : 1." );
  TCut METNoMuon130("metNoMuon>130.");	// add here later for VBF efficiency when MET>35, MET>70 (QCD estimation)
  TCut METNo2Muon130("metNo2Muon>130.");
  TCut cutLoDPhi = cuts.cut("dPhiJJ");

  // For lepton weights
  TCut lVetoWeight   = cuts.elVetoWeight(options.leptCorr) * cuts.muVetoWeight(options.leptCorr);
  TCut muTightWeight = cuts.muTightWeight(options.leptCorr);

  // histograms
  double dphiEdges[4] = { 0., 1.0, 2.6, TMath::Pi() };
  //double metEdges[13] = { 0., 10., 20., 30., 40., 50., 60., 70., 80., 90., 100., 110., 120. };

  // signal MET>130
  TH1D* hZ_DY_C_DPhi   = new TH1D("hZ_DY_C_DPhi",   "", 3, dphiEdges);  // Z+jets MC ctrl region
  TH1D* hZ_BG_C_DPhi   = new TH1D("hZ_BG_C_DPhi",   "", 3, dphiEdges);  // background MC ctrl region
  TH1D* hZ_Data_C_DPhi = new TH1D("hZ_Data_C_DPhi", "", 3, dphiEdges);  // Data ctrl region

  TH1D* hZ_QCD_EffVBFS_D = new TH1D("hZ_QCD_EffVBFS_D", "", 1, 0., 1.);
  TH1D* hZ_QCD_EffVBFS_N = new TH1D("hZ_QCD_EffVBFS_N", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFS_D = new TH1D("hZ_EWK_EffVBFS_D", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFS_N = new TH1D("hZ_EWK_EffVBFS_N", "", 1, 0., 1.);
 
  // combine eps_VBF_C * eps_mumu which remove canceling term (denominator is Z->uu gen level cut)
  TH1D* hZ_QCD_EffVBFC_D = new TH1D("hZ_QCD_EffVBFC_D", "", 1, 0., 1.);
  TH1D* hZ_QCD_EffVBFC_N = new TH1D("hZ_QCD_EffVBFC_N", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFC_D = new TH1D("hZ_EWK_EffVBFC_D", "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFC_N = new TH1D("hZ_EWK_EffVBFC_N", "", 1, 0., 1.);

  // cutflow histograms
  TH1D* hZ_CutFlow_Data       = new TH1D("hZ_CutFlow_Data",       "", nCutsZMuMu, 0., nCutsZMuMu);
  TH1D* hZ_CutFlow_DY         = new TH1D("hZ_CutFlow_DY",         "", nCutsZMuMu, 0., nCutsZMuMu);
  TH1D* hZ_CutFlow_SingleTSum = new TH1D("hZ_CutFlow_SingleTSum", "", nCutsZMuMu, 0., nCutsZMuMu);
  TH1D* hZ_CutFlow_Diboson    = new TH1D("hZ_CutFlow_Diboson",    "", nCutsZMuMu, 0., nCutsZMuMu);

  // Hists to calculate DY normalisation factor
  TH1D* hZ_DY_NoVBFNoWeight = new TH1D("hZ_DY_NoVBFNoWeight","", 1, 0., 1.); // DY MC yield after dimuon and dijet selection without y* and mjj weighting
  TH1D* hZ_DY_NoVBFWeight   = new TH1D("hZ_DY_NoVBFWeight",  "", 1, 0., 1.); // DY MC yield after dimuon and dijet selection with y* and mjj weighting

  // loop over MC datasets
  for (unsigned i=0; i<datasets.size(); ++i) {

    Dataset dataset = datasets.getDataset(i);
    
    TCut cutD = cuts.cutDataset(dataset.name);
    TCut yStarWeight("");
    TCut mjjWeight("");

    // check if it's DYJets
    bool isDY = false;
    if (dataset.name.compare(0,2,"DY")==0) {
      isDY = true;
      std::cout << "Analysing DY->ll MC : " << dataset.name << std::endl; 
      // check if it's QCD
      if ( !(dataset.name.length()>11 && dataset.name.compare(11,14,"EWK")==0) ) {
    	if (options.doMCFMWeights) {
    	  yStarWeight = TCut("(0.849667 + (0.149687*abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))))");
    	  mjjWeight   = TCut("0.392568 + (0.120734*log(genVBFM)) - (0.000255622*genVBFM)");
    	}
    	std::cout << "Analysing QCD DY MC " << std::endl;
      }
    }
    else if (dataset.isData) {
      std::cout << "Analysing Data      : " << dataset.name << std::endl;
    }
    else {
      std::cout << "Analysing BG MC     : " << dataset.name << std::endl;
    }

    TCut otherWeight = puWeight * yStarWeight * mjjWeight;

    // get file & tree
    TFile* file = datasets.getTFile(dataset.name);
    TTree* tree = (TTree*) file->Get("invHiggsInfo/InvHiggsInfo");

    // set up cuts
    TCut cutZMuMu_C           = otherWeight * trigCorr * (cutD + cuts.zMuMuVBF() + METNo2Muon130);
    
    TCut cutEfficiencyMuMu_D  = otherWeight * (cutD + cuts.zMuMuGen());
    //TCut cutEfficiencyMuMu_N  = otherWeight * (cutD + cuts.zMuMuGen() + cuts.zMuMuReco());
 
    TCut cutEfficiencyVBFS_D  = otherWeight * (cutD + cuts.zMuMuGenMass());
    TCut cutEfficiencyVBFS_N  = otherWeight * trigCorr * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGenMass() + cuts.vbf() + METNoMuon130 + cutLoDPhi);
    
    //TCut cutEfficiencyVBFC_D  = otherWeight * (cutD + cuts.zMuMuGen() + cuts.zMuMuReco());
    TCut cutEfficiencyVBFC_N  = otherWeight * trigCorr * (cutD + cuts.HLTandMETFilters() + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.vbf() + METNo2Muon130 + cutLoDPhi);

    // re-weighting
    TCut cutDYNoVBFNoWeight = puWeight * trigCorr * (cutD  + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.cutZMuMu("dijet"));
    TCut cutDYNoVBFWeight   = otherWeight * trigCorr * (cutD  + cuts.zMuMuGen() + cuts.zMuMuReco() + cuts.cutZMuMu("dijet"));

    if(!(dataset.isData)) {
	cutZMuMu_C *= muTightWeight;
	cutEfficiencyVBFC_N *= muTightWeight;
	cutDYNoVBFNoWeight  *= muTightWeight;
	cutDYNoVBFWeight    *= muTightWeight;
    }

    // fill tmp histograms for BG estimation
    TH1D* hZ_C_DPhi  = new TH1D("hZ_C_DPhi", "", 3, dphiEdges);  // this is for the actual BG estimation
    // fill tmp histograms for efficiency calculation
    TH1D* hZ_EffVBFS_D  = new TH1D("hZ_EffVBFS_D", "", 1, 0., 1.);
    TH1D* hZ_EffVBFS_N  = new TH1D("hZ_EffVBFS_N", "", 1, 0., 1.);
    TH1D* hZ_EffVBFC_D  = new TH1D("hZ_EffVBFC_D", "", 1, 0., 1.);
    TH1D* hZ_EffVBFC_N  = new TH1D("hZ_EffVBFC_N", "", 1, 0., 1.);

    TH1D* hZ_DY_NoWeight = new TH1D("hZ_DY_NoWeight", "", 1, 0, 1);
    TH1D* hZ_DY_Weight   = new TH1D("hZ_DY_Weight",   "", 1, 0, 1);
    

    if (isDY) {
      tree->Draw("vbfDPhi>>hZ_C_DPhi", cutZMuMu_C);
      tree->Draw("0.5>>hZ_EffVBFS_D",  cutEfficiencyVBFS_D);
      tree->Draw("0.5>>hZ_EffVBFS_N",  cutEfficiencyVBFS_N);
      tree->Draw("0.5>>hZ_EffVBFC_D",  cutEfficiencyMuMu_D);
      tree->Draw("0.5>>hZ_EffVBFC_N",  cutEfficiencyVBFC_N);

      tree->Draw("0.5>>hZ_DY_NoWeight", cutDYNoVBFNoWeight);
      tree->Draw("0.5>>hZ_DY_Weight",   cutDYNoVBFWeight);

//       tree->Draw("abs((log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/(sqrt(zgenmass*zgenmass + zgenpt*zgenpt)))) - 0.5*(genJet1Eta + genJet2Eta))>>hYStar", cutDYNoVBFNoWeight);
//       tree->Draw("abs((log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/(sqrt(zgenmass*zgenmass + zgenpt*zgenpt)))) - 0.5*(genJet1Eta + genJet2Eta))>>hYStarC", cutZMuMu_C);
    }
    else {
      tree->Draw("vbfDPhi>>hZ_C_DPhi", cutZMuMu_C);
      //tree->Draw("met:vbfDPhi>>hZ_C_METDPhi",  cutZMuMu_MET0_C);
    }

    // weight  to lumi
    double weight = (dataset.isData) ? 1. : lumi * dataset.sigma / dataset.nEvents;
    hZ_C_DPhi->Scale(weight);
    hZ_EffVBFS_D->Scale(weight);
    hZ_EffVBFS_N->Scale(weight);
    hZ_EffVBFC_D->Scale(weight);
    hZ_EffVBFC_N->Scale(weight);

    hZ_DY_NoWeight->Scale(weight);
    hZ_DY_Weight->Scale(weight);
    
    // add to output histograms
    if (dataset.isData) {
      hZ_Data_C_DPhi->Add(hZ_C_DPhi);
    }
    else if (isDY) {
      hZ_DY_C_DPhi->Add(hZ_C_DPhi);

      hZ_DY_NoVBFNoWeight->Add(hZ_DY_NoWeight);
      hZ_DY_NoVBFWeight->Add(hZ_DY_Weight);

      if(dataset.name == "DYJetsToLL_NoTrig" || dataset.name == "DYJetsToLL_PtZ-100_NoTrig") {
        hZ_QCD_EffVBFS_D->Add(hZ_EffVBFS_D);
        hZ_QCD_EffVBFS_N->Add(hZ_EffVBFS_N);
        hZ_QCD_EffVBFC_D->Add(hZ_EffVBFC_D);
        hZ_QCD_EffVBFC_N->Add(hZ_EffVBFC_N);
      }
      if(dataset.name == "DYJetsToLL_EWK_NoTrig") {
        hZ_EWK_EffVBFS_D->Add(hZ_EffVBFS_D);
        hZ_EWK_EffVBFS_N->Add(hZ_EffVBFS_N);
        hZ_EWK_EffVBFC_D->Add(hZ_EffVBFC_D);
        hZ_EWK_EffVBFC_N->Add(hZ_EffVBFC_N);
      }
    }
    else {
      hZ_BG_C_DPhi->Add(hZ_C_DPhi);
    }

    std::cout << "  N ctrl (dphi<1.0) : " << hZ_C_DPhi->GetBinContent(1) << " +/- " << hZ_C_DPhi->GetBinError(1) << std::endl;  
    

    delete hZ_C_DPhi;
    delete hZ_EffVBFS_D;
    delete hZ_EffVBFS_N;
    delete hZ_EffVBFC_D;
    delete hZ_EffVBFC_N;

    delete hZ_DY_NoWeight;
    delete hZ_DY_Weight;

    ofile->cd();

    // cut flow histograms
    std::string hname = std::string("hZ_CutFlow_")+dataset.name;
    TH1D* hZ_CutFlow = new TH1D(hname.c_str(), "", nCutsZMuMu, 0., nCutsZMuMu);

    for (unsigned c=0; c<nCutsZMuMu; ++c) {

      TCut cut;

      if(c == nCutsZMuMu-1) cut = otherWeight * trigCorr * (cutD + cuts.cutflowZMuMu(c));
      else cut = otherWeight * (cutD + cuts.cutflowZMuMu(c));

      if(!(dataset.isData)) cut *= muTightWeight;

      TH1D* h = new TH1D("h","", 1, 0., 1.);
      tree->Draw("0.5>>h", cut);

      hZ_CutFlow->SetBinContent(c+1, h->GetBinContent(1));
      hZ_CutFlow->SetBinError(c+1, h->GetBinError(1));

      delete h;
    }

    hZ_CutFlow->Scale(weight);

    if (dataset.isData) {
      hZ_CutFlow_Data->Add(hZ_CutFlow);
    }
    if (dataset.name.compare(0,2,"DY")==0) {
      hZ_CutFlow_DY->Add(hZ_CutFlow);
    }
    if (dataset.name.compare(0,7,"SingleT")==0) {
      hZ_CutFlow_SingleTSum->Add(hZ_CutFlow);
    }
    if (dataset.name.compare(0,2,"WW")==0 ||
  	dataset.name.compare(0,2,"WZ")==0 ||
  	dataset.name.compare(0,2,"ZZ")==0 || 
	dataset.name.compare(0,2,"WG")==0) {
      hZ_CutFlow_Diboson->Add(hZ_CutFlow);
    }

    hZ_CutFlow->Write("",TObject::kOverwrite);

    delete hZ_CutFlow;


    // Z control plots
    TCut cutPlots = otherWeight * trigCorr * (cutD + cuts.zMuMuVBFLoose());

    if(!(dataset.isData)) cutPlots *= muTightWeight;
 
    TFile* ofile_Plot = TFile::Open( (oDir_Plot+std::string("/")+dataset.name+std::string(".root")).c_str(), "RECREATE");

    TH1D* ZCtrlZMass    = new TH1D("ZCtrlZMass",    "", 30, 60., 120.);
    TH1D* ZCtrlZpT      = new TH1D("ZCtrlZpT",      "", 50, 0.,  1000.);
    TH1D* ZCtrlJet1pT   = new TH1D("ZCtrlJet1pT",   "", 50, 0.,  1000.);
    TH1D* ZCtrlJet1Eta  = new TH1D("ZCtrlJet1Eta",  "", 50, -5., 5.);
    TH1D* ZCtrlJet2pT   = new TH1D("ZCtrlJet2pT",   "", 50, 0.,  1000.);
    TH1D* ZCtrlJet2Eta  = new TH1D("ZCtrlJet2Eta",  "", 50, -5., 5.);
    TH1D* ZCtrlCenJetpT = new TH1D("ZCtrlCenJetpT", "", 50, 0.,  400.);
    TH1D* ZCtrlDEtajj   = new TH1D("ZCtrlDEtajj",   "", 50, 0.,  8.);
    TH1D* ZCtrlMjj      = new TH1D("ZCtrlMjj",      "", 30, 0.,  3000.);
    TH1D* ZCtrlMET      = new TH1D("ZCtrlMET",      "", 25, 10.,  510.);
    TH1D* ZCtrlDPhijj   = new TH1D("ZCtrlDPhijj",   "", 50, 0.,  TMath::Pi());

    TH1D* ZCtrlYStar    = new TH1D("ZCtrlYStar",    "", 50, 0., 5.);
    TH1D* ZCtrlYStarWt  = new TH1D("ZCtrlYStarWt",  "", 50, 0., 2.);
    TH1D* ZCtrlMjjWt    = new TH1D("ZCtrlMjjWt",    "", 50, 0., 2.);
    TH1D* ZCtrlYStarMjjWt    = new TH1D("ZCtrlYStarMjjWt",    "", 50, -1., 5.);    

    tree->Draw("zMass>>ZCtrlZMass"	    , cutPlots);
    tree->Draw("zPt>>ZCtrlZpT"		    , cutPlots);
    tree->Draw("jet1Pt>>ZCtrlJet1pT"	    , cutPlots);
    tree->Draw("jet1Eta>>ZCtrlJet1Eta"	    , cutPlots);
    tree->Draw("jet2Pt>>ZCtrlJet2pT"	    , cutPlots);
    tree->Draw("jet2Eta>>ZCtrlJet2Eta"	    , cutPlots);
    tree->Draw("cenJetEt>>ZCtrlCenJetpT"    , cutPlots);
    tree->Draw("vbfDEta>>ZCtrlDEtajj"	    , cutPlots);
    tree->Draw("vbfM>>ZCtrlMjj"		    , cutPlots);
    tree->Draw("metNo2Muon>>ZCtrlMET"	    , cutPlots);
    tree->Draw("vbfDPhi>>ZCtrlDPhijj"	    , cutPlots);

    if (options.doMCFMWeights) {

    tree->Draw("abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))>>ZCtrlYStar"	  , cutPlots);
    tree->Draw("(0.849667 + (0.149687*abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))))>>ZCtrlYStarWt", cutPlots);
    tree->Draw("(0.392568 + (0.120734*log(genVBFM)) - (0.000255622*genVBFM))>>ZCtrlMjjWt", cutPlots);
    tree->Draw("(0.849667 + (0.149687*abs(log((sqrt(zgenmass*zgenmass + zgenpt*zgenpt*cosh(zgeneta)*cosh(zgeneta)) + zgenpt*sinh(zgeneta))/sqrt(zgenmass*zgenmass + zgenpt*zgenpt)) - 0.5*(genJet1Eta + genJet2Eta))))*(0.392568 + (0.120734*log(genVBFM)) - (0.000255622*genVBFM))>>ZCtrlYStarMjjWt", cutPlots);

    }

    if (!dataset.isData) {
      ZCtrlZMass->Scale(weight);
      ZCtrlZpT->Scale(weight);
      ZCtrlJet1pT->Scale(weight);
      ZCtrlJet1Eta->Scale(weight);
      ZCtrlJet2pT->Scale(weight);
      ZCtrlJet2Eta->Scale(weight);
      ZCtrlCenJetpT->Scale(weight);
      ZCtrlDEtajj->Scale(weight);
      ZCtrlMjj->Scale(weight);
      ZCtrlMET->Scale(weight);
      ZCtrlDPhijj->Scale(weight);
      ZCtrlYStar->Scale(weight);
      ZCtrlYStarWt->Scale(weight);
      ZCtrlMjjWt->Scale(weight);
      ZCtrlYStarMjjWt->Scale(weight);
    }

    ofile_Plot->cd();
    ZCtrlZMass->Write("",TObject::kOverwrite);
    ZCtrlZpT->Write("",TObject::kOverwrite);
    ZCtrlJet1pT->Write("",TObject::kOverwrite);
    ZCtrlJet1Eta->Write("",TObject::kOverwrite);
    ZCtrlJet2pT->Write("",TObject::kOverwrite);
    ZCtrlJet2Eta->Write("",TObject::kOverwrite);
    ZCtrlCenJetpT->Write("",TObject::kOverwrite);
    ZCtrlDEtajj->Write("",TObject::kOverwrite);
    ZCtrlMjj->Write("",TObject::kOverwrite);
    ZCtrlMET->Write("",TObject::kOverwrite);
    ZCtrlDPhijj->Write("",TObject::kOverwrite);
    ZCtrlYStar->Write("",TObject::kOverwrite);
    ZCtrlYStarWt->Write("",TObject::kOverwrite);
    ZCtrlMjjWt->Write("",TObject::kOverwrite);
    ZCtrlYStarMjjWt->Write("",TObject::kOverwrite);

    ofile_Plot->Close();

    // clean up
    delete tree;
    file->Close();
   
  }

  // re-weighting : will be 1 if re-weighting is off
  TH1D* hZ_DYNorm = new TH1D("hZ_DYNorm", "", 1, 0, 1); 
  hZ_DYNorm->Add(hZ_DY_NoVBFNoWeight);
  hZ_DYNorm->Divide(hZ_DY_NoVBFWeight);
  
  double dyNorm = hZ_DYNorm->GetBinContent(1);

  // numbers - calculate these from MC in this program later!
  double ratioBF = constants::ratioZToNuNuZToLL;

  // efficiencies (these will all have syst uncertainty only)
  TH1D* hZ_QCD_EffVBFS      = new TH1D("hZ_QCD_EffVBFS",  "", 1, 0., 1.);
  TH1D* hZ_QCD_EffVBFC      = new TH1D("hZ_QCD_EffVBFC",  "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFS      = new TH1D("hZ_EWK_EffVBFS",  "", 1, 0., 1.);
  TH1D* hZ_EWK_EffVBFC      = new TH1D("hZ_EWK_EffVBFC",  "", 1, 0., 1.);
 
  TH1D* hZ_DY_EffVBFS       = new TH1D("hZ_DY_EffVBFS",  "", 1, 0., 1.);  	// epsilon_s_vbf
  TH1D* hZ_DY_EffVBFC       = new TH1D("hZ_DY_EffVBFC",  "", 1, 0., 1.);        // epsilon_c_vbf
  TH1D* hZ_DY_TotalEff      = new TH1D("hZ_DY_TotalEff", "", 1, 0., 1.); 

  // for stat only calculation
  TH1D* hZ_Eff_S_DPhi       = new TH1D("hZ_Eff_S_DPhi",       "", 3, dphiEdges);
  TH1D* hZ_Est_C_DPhi       = new TH1D("hZ_Est_C_DPhi",       "", 3, dphiEdges);
  TH1D* hZ_Est_S_DPhi       = new TH1D("hZ_Est_S_DPhi",       "", 3, dphiEdges);

  // for syst only calculation
  TH1D* hZ_BG_C_DPhi_Syst   = new TH1D("hZ_BG_C_DPhi_Syst",   "", 3, dphiEdges);
  TH1D* hZ_Data_C_DPhi_Syst = new TH1D("hZ_Data_C_DPhi_Syst", "", 3, dphiEdges);
  TH1D* hZ_Eff_S_DPhi_Syst  = new TH1D("hZ_Eff_S_DPhi_Syst",  "", 3, dphiEdges);
  TH1D* hZ_Est_C_DPhi_Syst  = new TH1D("hZ_Est_C_DPhi_Syst",  "", 3, dphiEdges);
  TH1D* hZ_Est_S_DPhi_Syst  = new TH1D("hZ_Est_S_DPhi_Syst",  "", 3, dphiEdges);

  // calculate efficiencies for QCD and EWK processes
  hZ_QCD_EffVBFS->Add(hZ_QCD_EffVBFS_N);
  hZ_QCD_EffVBFS->Divide(hZ_QCD_EffVBFS_D);
  hZ_EWK_EffVBFS->Add(hZ_EWK_EffVBFS_N);
  hZ_EWK_EffVBFS->Divide(hZ_EWK_EffVBFS_D);

  hZ_QCD_EffVBFC->Add(hZ_QCD_EffVBFC_N);
  hZ_QCD_EffVBFC->Divide(hZ_QCD_EffVBFC_D);
  hZ_EWK_EffVBFC->Add(hZ_EWK_EffVBFC_N);
  hZ_EWK_EffVBFC->Divide(hZ_EWK_EffVBFC_D); 

  // combine QCD Zll and EWK Zll with correct weights
  hZ_DY_EffVBFS->Add(hZ_QCD_EffVBFS,constants::sigma_Zvv_QCD);
  hZ_DY_EffVBFS->Add(hZ_EWK_EffVBFS,constants::sigma_Zvv_EWK);
  hZ_DY_EffVBFC->Add(hZ_QCD_EffVBFC,constants::sigma_Zuu_QCD);
  hZ_DY_EffVBFC->Add(hZ_EWK_EffVBFC,constants::sigma_Zuu_EWK);

  hZ_DY_TotalEff->Add(hZ_DY_EffVBFS);
  hZ_DY_TotalEff->Divide(hZ_DY_EffVBFC);

  for(int ibin = 1; ibin <= hZ_Eff_S_DPhi->GetNbinsX(); ++ibin) {
    hZ_Eff_S_DPhi->SetBinContent(ibin,hZ_DY_TotalEff->GetBinContent(1));
    hZ_Eff_S_DPhi->SetBinError(ibin,0.);
    hZ_Eff_S_DPhi_Syst->SetBinContent(ibin,hZ_DY_TotalEff->GetBinContent(1));
    hZ_Eff_S_DPhi_Syst->SetBinError(ibin,hZ_DY_TotalEff->GetBinError(1));
  }

  // do stat only version
  hZ_BG_C_DPhi_Syst->Add(hZ_BG_C_DPhi, 1.);  // copy MC BG histogram for syst calculation
  for (int i=1; i<=hZ_BG_C_DPhi->GetNbinsX(); ++i) hZ_BG_C_DPhi->SetBinError(i,0.);  // set MC BG errors to zero for stat only
  hZ_Est_C_DPhi->Add(hZ_Data_C_DPhi, hZ_BG_C_DPhi, 1., -1.);
  hZ_Est_S_DPhi->Add(hZ_Est_C_DPhi);
  hZ_Est_S_DPhi->Multiply(hZ_Eff_S_DPhi);

  // do syst only version
  hZ_Data_C_DPhi_Syst->Add(hZ_Data_C_DPhi, 1.);
  for (int i=1; i<=hZ_Data_C_DPhi_Syst->GetNbinsX(); ++i) hZ_Data_C_DPhi_Syst->SetBinError(i,0.);

  hZ_Est_C_DPhi_Syst->Add(hZ_Data_C_DPhi_Syst, hZ_BG_C_DPhi, 1., -1.);
  hZ_Est_S_DPhi_Syst->Add(hZ_Est_C_DPhi_Syst);
  hZ_Est_S_DPhi_Syst->Multiply(hZ_Eff_S_DPhi_Syst);


  std::cout << std::endl;
  std::cout << "##################################### MET > 130 #####################################" << std::endl;
  std::cout << "dphi<1.0" << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_s_vbf : " << hZ_QCD_EffVBFS_N->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFS_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_s_vbf      : " << hZ_QCD_EffVBFS_D->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFS_D->GetBinError(1) << std::endl;
  std::cout << "  eps_s_vbf (QCD) : " << hZ_QCD_EffVBFS->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFS->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_s_vbf : " << hZ_EWK_EffVBFS_N->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFS_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_s_vbf      : " << hZ_EWK_EffVBFS_D->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFS_D->GetBinError(1) << std::endl;
  std::cout << "  eps_s_vbf (EWK) : " << hZ_EWK_EffVBFS->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFS->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_c_vbf : " << hZ_QCD_EffVBFC_N->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFC_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_c_vbf      : " << hZ_QCD_EffVBFC_D->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFC_D->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf (QCD) : " << hZ_QCD_EffVBFC->GetBinContent(1) << " +/- " << hZ_QCD_EffVBFC->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Numerator_c_vbf : " << hZ_EWK_EffVBFC_N->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFC_N->GetBinError(1) << std::endl;
  std::cout << "  Deno_c_vbf      : " << hZ_EWK_EffVBFC_D->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFC_D->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf (EWK) : " << hZ_EWK_EffVBFC->GetBinContent(1) << " +/- " << hZ_EWK_EffVBFC->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  eps_s_vbf : " << hZ_DY_EffVBFS->GetBinContent(1) << " +/- " << hZ_DY_EffVBFS->GetBinError(1) << std::endl;
  std::cout << "  eps_c_vbf : " << hZ_DY_EffVBFC->GetBinContent(1) << " +/- " << hZ_DY_EffVBFC->GetBinError(1) << std::endl;
  std::cout << "  total eff : " << hZ_DY_TotalEff->GetBinContent(1) << " +/- " << hZ_DY_TotalEff->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  DY+jets MC ctrl region : " << hZ_DY_C_DPhi->GetBinContent(1) << " +/- " << hZ_DY_C_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Background ctrl region : " << hZ_BG_C_DPhi->GetBinContent(1) << " +/- " << hZ_BG_C_DPhi->GetBinError(1) << std::endl;
  std::cout << "  Data ctrl region       : " << hZ_Data_C_DPhi->GetBinContent(1) << " +/- " << hZ_Data_C_DPhi->GetBinError(1) << std::endl;
  std::cout << std::endl;
  std::cout << "  Z in ctrl region       : " << hZ_Est_C_DPhi->GetBinContent(1) << " +/- " << hZ_Est_C_DPhi->GetBinError(1) << " (stat.) + " << hZ_Est_C_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
  std::cout << "  Z in sgnl region       : " << hZ_Est_S_DPhi->GetBinContent(1) << " +/- " << hZ_Est_S_DPhi->GetBinError(1) << " (stat.) + " << hZ_Est_S_DPhi_Syst->GetBinError(1) << " (syst)" << std::endl;
  std::cout << std::endl;
  //std::cout << "  N_DY^No VBF (no y* or mjj weight)  : " << hZ_DY_NoVBFNoWeight->GetBinContent(1) << " +/- " << hZ_DY_NoVBFNoWeight->GetBinError(1) << std::endl; 
  //std::cout << "  N_DY^No VBF(with y* and mjj weight): " << hZ_DY_NoVBFWeight->GetBinContent(1) << " +/- " << hZ_DY_NoVBFWeight->GetBinError(1) << std::endl;
  //std::cout << "  norm eff (unweighted DY, no VBF / weighted DY, no VBF): " << dyNorm << std::endl;
  std::cout << std::endl;
  std::cout << "#####################################################################################" << std::endl;
  std::cout << std::endl << std::endl;

  // write the cutflow table
  std::cout << "Writing cut flow TeX file" << std::endl;

  ofstream effFile;
  effFile.open(options.oDir+std::string("/cutflowZMuMu.tex"));

  effFile << "Cut & N(data) & N(DY\\rightarrow\\ell\\ell) & N($t\\bar{t}$) & N(single $t$) & N(diboson) \\\\" << std::endl;

  TH1D* hZ_CutFlow_TTBar = (TH1D*) ofile->Get("hZ_CutFlow_TTBar");

  // cutflow table
  for (unsigned i=0; i<nCutsZMuMu; ++i) {

    effFile << cuts.cutNameZMuMu(i) << " & ";
    effFile << "$" << hZ_CutFlow_Data->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_Data->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_DY->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_DY->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_TTBar->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_TTBar->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_SingleTSum->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_SingleTSum->GetBinError(i+1) << "$ & ";
    effFile << "$" << hZ_CutFlow_Diboson->GetBinContent(i+1) << " \\pm " << hZ_CutFlow_Diboson->GetBinError(i+1) << "$ & ";
    effFile << std::endl;

  }

  effFile << std::endl << std::endl;
  effFile.close();

  // list histograms for dataset summing
  std::vector<std::string> hists;
  hists.push_back("ZCtrlZMass");
  hists.push_back("ZCtrlZpT");
  hists.push_back("ZCtrlJet1pT");
  hists.push_back("ZCtrlJet1Eta");
  hists.push_back("ZCtrlJet2pT");
  hists.push_back("ZCtrlJet2Eta");
  hists.push_back("ZCtrlCenJetpT");
  hists.push_back("ZCtrlDEtajj");
  hists.push_back("ZCtrlMjj");
  hists.push_back("ZCtrlMET");
  hists.push_back("ZCtrlDPhijj");

  // check whether we have NoTrig histograms or normal
  bool noTrig = false;
  std::string dyJetsName = oDir_Plot+std::string("/DYJetsToLL.root");
  std::string dyJetsPtZName = oDir_Plot+std::string("/DYJetsToLL_PtZ-100.root");
  struct stat buffer; 
  if (stat (dyJetsName.c_str(), &buffer) != 0) {
    noTrig = true;
    dyJetsName = oDir_Plot+std::string("/DYJetsToLL_NoTrig.root");
    dyJetsPtZName = oDir_Plot+std::string("/DYJetsToLL_PtZ-100_NoTrig.root");
  }

  std::cout << "Getting histograms for plots from " << dyJetsName << " and " << dyJetsPtZName << std::endl;

  // re-scale QCD DY histograms
  TFile* qcdDYFile = TFile::Open(dyJetsName.c_str(), "UPDATE");
  for (std::vector<std::string>::const_iterator hname=hists.begin(); hname!=hists.end(); ++hname) {
    TH1D* h = (TH1D*) qcdDYFile->Get(hname->c_str());
    //std::cout << "Integral before : " << h->Integral() << std::endl;
    h->Scale(dyNorm);
    //std::cout << "Integral after : " << h->Integral() << std::endl;
    h->Write("",TObject::kOverwrite);
  }
  qcdDYFile->Close();

  qcdDYFile = TFile::Open(dyJetsPtZName.c_str(), "UPDATE");
  for (std::vector<std::string>::const_iterator hname=hists.begin(); hname!=hists.end(); ++hname) {
    TH1D* h = (TH1D*) qcdDYFile->Get(hname->c_str());
    h->Scale(dyNorm);
    h->Write("",TObject::kOverwrite);
  }
  qcdDYFile->Close();


  // sum DY datasets
  std::vector<std::string> DYDatasets;
  if (noTrig) {
    DYDatasets.push_back(std::string("DYJetsToLL_NoTrig"));
    DYDatasets.push_back(std::string("DYJetsToLL_PtZ-100_NoTrig"));
    DYDatasets.push_back(std::string("DYJetsToLL_EWK_NoTrig"));
  }
  else {
    DYDatasets.push_back(std::string("DYJetsToLL"));
    DYDatasets.push_back(std::string("DYJetsToLL_PtZ-100"));
    DYDatasets.push_back(std::string("DYJetsToLL_EWK"));
  }
  SumDatasets(oDir_Plot, DYDatasets, hists, "DY+jets");

  // sum single top datasets
  std::vector<std::string> topDatasets;
  topDatasets.push_back(std::string("SingleT_t"));
  topDatasets.push_back(std::string("SingleTbar_t"));
  topDatasets.push_back(std::string("SingleT_s"));
  topDatasets.push_back(std::string("SingleTbar_s"));
  topDatasets.push_back(std::string("SingleT_tW"));
  topDatasets.push_back(std::string("SingleTbar_tW"));
  topDatasets.push_back(std::string("TTBar"));
  SumDatasets(oDir_Plot, topDatasets, hists, "SingleT+TTbar"); 

  // sum diboson datasets
  std::vector<std::string> dibDatasets;
  dibDatasets.push_back(std::string("WW"));
  dibDatasets.push_back(std::string("WZ"));
  dibDatasets.push_back(std::string("ZZ"));
  dibDatasets.push_back(std::string("WG"));
  SumDatasets(oDir_Plot, dibDatasets, hists, "DiBoson");

  // sum SM backgrounds
  std::vector<std::string> bgDatasets;
  bgDatasets.push_back(std::string("WW"));
  bgDatasets.push_back(std::string("WZ"));
  bgDatasets.push_back(std::string("ZZ"));
  bgDatasets.push_back(std::string("WG"));
  bgDatasets.push_back(std::string("SingleT_t"));
  bgDatasets.push_back(std::string("SingleTbar_t"));
  bgDatasets.push_back(std::string("SingleT_s"));
  bgDatasets.push_back(std::string("SingleTbar_s"));
  bgDatasets.push_back(std::string("SingleT_tW"));
  bgDatasets.push_back(std::string("SingleTbar_tW"));
  bgDatasets.push_back(std::string("TTBar"));
  SumDatasets(oDir_Plot, bgDatasets, hists, "tt+VV"); 

  // make plots
  std::cout << "Making plots" << std::endl;
  StackPlot plots(oDir_Plot);
  plots.setLegPos(0.70,0.60,0.93,0.89);
  //plots.setLegPos(0.62,0.62,0.89,0.89);

  // Note that here I've used the overloaded method addDataset, which allows you to specify a filename for the input ROOT file
  // *and* also allows you to specify what to put in the TLegend. (By default, it uses the filename as the TLegend entry)
  // This is because the Tlegend entry involves some odd characters, which are best not used in filenames for safety

  //  plots.addDataset("DiBoson", kViolet-6, 0);
  plots.addDataset("tt+VV", "t#bar{t}, tW, VV", kAzure-2, 0);
  plots.addDataset("DY+jets", "DY(ll)+jets", kPink-4, 0);
  plots.addDataset("METABCD", kBlack, 1);
  plots.setScaleMCtoData(true); //rescale MC to data

  plots.draw("ZCtrlZpT",	"Z_p_{T} [GeV]",		"N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet1pT", 	"Leading jet p_{T} [GeV]", 	"N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet1Eta", 	"Leading jet #eta", 		"N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet2pT",     "Sub-leading jet p_{T} [GeV]",  "N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlJet2Eta",    "Sub-leading jet #eta",         "N_{events}"	,1,"RATIO_Z");
  plots.draw("ZCtrlCenJetpT",	"Central jet p_{T} [GeV]",	"N_{events}"    ,1,"RATIO_Z");
  plots.draw("ZCtrlDEtajj",	"#Delta #eta_{jj}",		"N_{events}"	,1,"RATIO_Z");
  plots.setYMax(5.e2);
  plots.setXMin(1100.);
  plots.setXMax(2600.);
  plots.draw("ZCtrlMjj", 	"M_{jj} [GeV]",			"Events / 100 GeV"	,1,"RATIO_Z");
  plots.setYMax(5.e2);
  plots.setXMin(130.);
  plots.draw("ZCtrlMET", 	"E_{T}^{miss} [GeV]",		"Events / 20 GeV"	,1,"RATIO_Z");
  plots.draw("ZCtrlDPhijj", 	"#Delta #phi_{jj}",		"Events"	,1,"RATIO_Z");
  plots.setYMax(80.);
  plots.setYMin(0.);
  plots.draw("ZCtrlZMass",      "M_{#mu#mu}  [GeV]",      "Events / 5 GeV"    ,0,"RATIO_Z");

  //store histograms
  ofile->cd();
  hZ_DY_C_DPhi->Write("",TObject::kOverwrite);
  hZ_BG_C_DPhi->Write("",TObject::kOverwrite);
  hZ_Data_C_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_C_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_C_DPhi_Syst->Write("",TObject::kOverwrite);
  hZ_Est_S_DPhi->Write("",TObject::kOverwrite);
  hZ_Est_S_DPhi_Syst->Write("",TObject::kOverwrite);

  hZ_Eff_S_DPhi->Write("",TObject::kOverwrite);
  hZ_Eff_S_DPhi_Syst->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFS_D->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFS_N->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFC_D->Write("",TObject::kOverwrite);
  hZ_QCD_EffVBFC_N->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFS_D->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFS_N->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFC_D->Write("",TObject::kOverwrite);
  hZ_EWK_EffVBFC_N->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFS->Write("",TObject::kOverwrite);
  hZ_DY_EffVBFC->Write("",TObject::kOverwrite);
  hZ_DY_TotalEff->Write("",TObject::kOverwrite);

  hZ_CutFlow_Data->Write("",TObject::kOverwrite);
  hZ_CutFlow_DY->Write("",TObject::kOverwrite);
  hZ_CutFlow_SingleTSum->Write("",TObject::kOverwrite);
  hZ_CutFlow_Diboson->Write("",TObject::kOverwrite);

  ofile->Close();    

}
Exemplo n.º 25
0
//_______________________________________________________________________________
void makeZinvFromDY( TFile* fData , TFile* fZinv , TFile* fDY ,TFile* fTop, vector<string> dirs, string output_name ) {

  // Generate histogram file with Zinv prediction based on DYData * R(Zinv/DY)

  TFile * outfile = new TFile(output_name.c_str(),"RECREATE") ; 
  outfile->cd();
  const unsigned int ndirs = dirs.size();

//  // Obtain inclusive templates
//  int lastmt2_VL23J=0, lastmt2_VL2J=0, lastmt2_VL4J=0;
//  int lastmt2_L23J=0,  lastmt2_L26J=0, lastmt2_L46J=0, lastmt2_L7J=0;
//  int lastmt2_M23J=0,  lastmt2_M26J=0, lastmt2_M46J=0, lastmt2_M7J=0;
//  int lastmt2_H23J=0,  lastmt2_H26J=0, lastmt2_H46J=0, lastmt2_H7J=0;
//  int lastmt2_UH=0;
//  TH1D* h_TemplateVL23J      = (TH1D*) fData->Get("crdybaseVL/h_mt2bins23J"); 
//  int lastbin_VL23J = purityRandNorm(h_TemplateVL23J, "crdybaseVL/h_mt2bins23J", fData, fZinv, fDY, lastmt2_VL23J);
//  TH1D* h_TemplateVL2J       = (TH1D*) fData->Get("crdybaseVL/h_mt2bins"); 
//  int lastbin_VL2J  = purityRandNorm(h_TemplateVL2J, "crdybaseVL/h_mt2bins", fData, fZinv, fDY, lastmt2_VL2J);
//  TH1D* h_TemplateVL4J       = (TH1D*) fData->Get("crdybaseVL/h_mt2bins4J");  
//  int lastbin_VL4J  = purityRandNorm(h_TemplateVL4J, "crdybaseVL/h_mt2bins4J", fData, fZinv, fDY, lastmt2_VL4J);  
//  TH1D* h_TemplateL23J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins23J");
//  int lastbin_L23J  = purityRandNorm(h_TemplateL23J, "crdybaseL/h_mt2bins23J", fData, fZinv, fDY, lastmt2_L23J);    
//  TH1D* h_TemplateL26J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins26J");
//  int lastbin_L26J  = purityRandNorm(h_TemplateL26J, "crdybaseL/h_mt2bins26J", fData, fZinv, fDY, lastmt2_L26J);    
//  TH1D* h_TemplateL46J       = (TH1D*) fData->Get("crdybaseL/h_mt2bins46J");   
//  int lastbin_L46J  = purityRandNorm(h_TemplateL46J, "crdybaseL/h_mt2bins46J", fData, fZinv, fDY, lastmt2_L46J); 
//  TH1D* h_TemplateL7J        = (TH1D*) fData->Get("crdybaseL/h_mt2bins7J");    
//  int lastbin_L7J   = purityRandNorm(h_TemplateL7J, "crdybaseL/h_mt2bins7J", fData, fZinv, fDY, lastmt2_L7J);
//  TH1D* h_TemplateM23J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins23J");    
//  int lastbin_M23J  = purityRandNorm(h_TemplateM23J, "crdybaseM/h_mt2bins23J", fData, fZinv, fDY, lastmt2_M23J);
//  TH1D* h_TemplateM26J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins26J");    
//  int lastbin_M26J  = purityRandNorm(h_TemplateM26J, "crdybaseM/h_mt2bins26J", fData, fZinv, fDY, lastmt2_M26J);
//  TH1D* h_TemplateM46J       = (TH1D*) fData->Get("crdybaseM/h_mt2bins46J");    
//  int lastbin_M46J  = purityRandNorm(h_TemplateM46J, "crdybaseM/h_mt2bins46J", fData, fZinv, fDY, lastmt2_M46J);
//  TH1D* h_TemplateM7J        = (TH1D*) fData->Get("crdybaseM/h_mt2bins7J");    
//  int lastbin_M7J   = purityRandNorm(h_TemplateM7J, "crdybaseM/h_mt2bins7J", fData, fZinv, fDY, lastmt2_M7J);
//  TH1D* h_TemplateH23J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins23J");    
//  int lastbin_H23J  = purityRandNorm(h_TemplateH23J, "crdybaseH/h_mt2bins23J", fData, fZinv, fDY, lastmt2_H23J);
//  TH1D* h_TemplateH26J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins26J");    
//  int lastbin_H26J  = purityRandNorm(h_TemplateH26J, "crdybaseH/h_mt2bins26J", fData, fZinv, fDY, lastmt2_H26J);
//  TH1D* h_TemplateH46J       = (TH1D*) fData->Get("crdybaseH/h_mt2bins46J");    
//  int lastbin_H46J  = purityRandNorm(h_TemplateH46J, "crdybaseH/h_mt2bins46J", fData, fZinv, fDY, lastmt2_H46J);
//  TH1D* h_TemplateH7J        = (TH1D*) fData->Get("crdybaseH/h_mt2bins7J");    
//  int lastbin_H7J   = purityRandNorm(h_TemplateH7J, "crdybaseH/h_mt2bins7J", fData, fZinv, fDY, lastmt2_H7J);
//  TH1D* h_TemplateUH        = (TH1D*) fData->Get("crdybaseUH/h_mt2bins");    
//  int lastbin_UH    = purityRandNorm(h_TemplateUH, "crdybaseUH/h_mt2bins", fData, fZinv, fDY, lastmt2_UH);


  for ( unsigned int idir = 0; idir < ndirs; ++idir ) {
    
    TString srname = dirs.at(idir);
    TString directory = "sr"+dirs.at(idir);
    TString directoryDY = "crdy"+dirs.at(idir);

    TString fullhistname = directory + "/h_mt2bins";
    TString fullhistnameDY = directoryDY + "/h_mt2bins";
    TString fullhistnameEM = directoryDY + "/h_mt2binsemu";

    TH1D* hData = (TH1D*) fData->Get(fullhistnameDY);    
    TH1D* hDY   = (TH1D*) fDY->Get(fullhistnameDY);
    TH1D* hDataEM   = (TH1D*) fData->Get(fullhistnameEM);    
    TH1D* hZinv = (TH1D*) fZinv->Get(fullhistname);    
    TH1D* hTop  = (TH1D*) fTop->Get(fullhistnameDY);    

    TH1D* hDY_lepeff_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_lepeff_UP");
    TH1D* hDY_lepeff_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_lepeff_DN");
    TH1D* hDY_trigeff_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_trigeff_UP");
    TH1D* hDY_trigeff_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_trigeff_DN");
    TH1D* hDY_ZNJet_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_ZNJet_UP");
    TH1D* hDY_ZNJet_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_ZNJet_DN");
    TH1D* hZinv_ZNJet_UP   = (TH1D*) fZinv->Get(fullhistname+"_ZNJet_UP");
    TH1D* hZinv_ZNJet_DN   = (TH1D*) fZinv->Get(fullhistname+"_ZNJet_DN");
    TH1D* hDY_renorm_UP   = (TH1D*) fDY->Get(fullhistnameDY+"_renorm_UP");
    TH1D* hDY_renorm_DN   = (TH1D*) fDY->Get(fullhistnameDY+"_renorm_DN");
    TH1D* hZinv_renorm_UP   = (TH1D*) fZinv->Get(fullhistname+"_renorm_UP");
    TH1D* hZinv_renorm_DN   = (TH1D*) fZinv->Get(fullhistname+"_renorm_DN");
    
    // If Zinv or DY histograms are not filled, just leave (shouldn't happen when running on full stat MC)
    if(!hDY || !hZinv || !hData){
      cout<<"could not find histogram "<<fullhistname<<endl;
      continue;
    }
    
    if (hDY->GetNbinsX() != hZinv->GetNbinsX() ) {
      cout<<"different binning for histograms "<<fullhistname<<endl;
      continue;
    }
    
    // Make directory and plot(s) in the output file
    TDirectory* dir = 0;
    dir = (TDirectory*)outfile->Get(directory.Data());
    if (dir == 0) {
      dir = outfile->mkdir(directory.Data());
    } 
    dir->cd();

    cout<<"Looking at histo "<<fullhistname<<endl;

    int lastbin_hybrid = 1;
    int lastmt2val_hybrid = 200;
    int ht_LOW = 0, ht_HI = 0, njets_LOW = 0, njets_HI = 0, nbjets_LOW = 0, nbjets_HI = 0;
    TH1D* h_MT2Template = (TH1D*) hZinv->Clone("h_MT2Template");  
    TString inclusiveTemplateName = "";

    TH1D *h_ht_LOW, *h_ht_HI, *h_njets_LOW, *h_njets_HI, *h_nbjets_LOW, *h_nbjets_HI;
    if (doHybridInclusiveTemplate) {
      //  Inclusive template: use inclusive template corresponding to this region
      
      //Get variable boundaries for signal region.
      h_ht_LOW = (TH1D*) fData->Get(directory+"/h_ht_LOW");
      h_ht_HI  = (TH1D*) fData->Get(directory+"/h_ht_HI");
      if (h_ht_LOW) ht_LOW = h_ht_LOW->GetBinContent(1);
      if (h_ht_HI)  ht_HI = h_ht_HI->GetBinContent(1);
      h_njets_LOW = (TH1D*) fData->Get(directory+"/h_njets_LOW");
      h_njets_HI  = (TH1D*) fData->Get(directory+"/h_njets_HI");
      if (h_njets_LOW) njets_LOW = h_njets_LOW->GetBinContent(1);
      if (h_njets_HI)  njets_HI = h_njets_HI->GetBinContent(1);
      h_nbjets_LOW = (TH1D*) fData->Get(directory+"/h_nbjets_LOW");
      h_nbjets_HI  = (TH1D*) fData->Get(directory+"/h_nbjets_HI");
      if (h_nbjets_LOW) nbjets_LOW = h_nbjets_LOW->GetBinContent(1);
      if (h_nbjets_HI)  nbjets_HI = h_nbjets_HI->GetBinContent(1);
      
      //Determine which inclusive template to use. If none works, this reverts to HybridSimple, taking template from its own TopoRegion 
      // Start from the Aggregate Regions (hardcoded, since they can partially overlap with the standard regions)
      if (srname == "20") inclusiveTemplateName = "crdy20/h_mt2bins";  // self (2j, HT1200)
      else if (srname == "base") inclusiveTemplateName = "crdybase/h_mt2bins";
      else if (srname == "baseVL") inclusiveTemplateName = "crdybaseVL/h_mt2bins";
      else if (srname == "baseL") inclusiveTemplateName = "crdybaseL/h_mt2bins";
      else if (srname == "baseM") inclusiveTemplateName = "crdybaseM/h_mt2bins";
      else if (srname == "baseH") inclusiveTemplateName = "crdybaseH/h_mt2bins";
      else if (srname == "baseUH") inclusiveTemplateName = "crdybaseUH/h_mt2bins";
      else if (srname == "21") inclusiveTemplateName = "crdy21/h_mt2bins"; // self (2j, HT1500)
      else if (srname == "22") inclusiveTemplateName = "crdy22/h_mt2bins"; // self (4j, HT1200)
      else if (srname == "23") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21 
      else if (srname == "24") inclusiveTemplateName = "crdy24/h_mt2bins"; // self (7J, HT1200)
      else if (srname == "25") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "26") inclusiveTemplateName = "crdy20/h_mt2bins"; // from 20
      else if (srname == "27") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "28") inclusiveTemplateName = "crdy20/h_mt2bins3J"; // need a 3J histogram within SR20
      //      else if (srname == "28") inclusiveTemplateName = "crdy20/h_mt2bins"; // test
      else if (srname == "29") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      else if (srname == "30") inclusiveTemplateName = "crdy24/h_mt2bins"; // from 24
      else if (srname == "31") inclusiveTemplateName = "crdy21/h_mt2bins"; // from 21
      // Now the standard regions
      else if (ht_LOW == 250) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseVL/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7) inclusiveTemplateName = "crdybaseVL/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseVL/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseVL/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseVL/h_mt2bins7J"; 
      }
      else if (ht_LOW == 450) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseL/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7)  inclusiveTemplateName = "crdybaseL/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseL/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseL/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseL/h_mt2bins7J"; 
      }
      else if (ht_LOW == 575) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseM/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7) inclusiveTemplateName = "crdybaseM/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseM/h_mt2bins23J"; 
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseM/h_mt2bins46J"; 
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseM/h_mt2bins79J"; 
	else if (njets_LOW == 10)  inclusiveTemplateName = "crdybaseM/h_mt2bins10J"; 
      }
      else if (ht_LOW == 1200) {
	if (njets_LOW == 2 && nbjets_LOW==3) inclusiveTemplateName = "crdybaseH/h_mt2bins36J"; 
	else if (njets_LOW == 2 && njets_HI==7)  inclusiveTemplateName = "crdybaseH/h_mt2bins26J"; 
	else if (njets_LOW == 2)  inclusiveTemplateName = "crdybaseH/h_mt2bins23J";
	else if (njets_LOW == 4)  inclusiveTemplateName = "crdybaseH/h_mt2bins46J";
	else if (njets_LOW == 7)  inclusiveTemplateName = "crdybaseH/h_mt2bins79J";
	else if (njets_LOW == 10)  inclusiveTemplateName = "crdybaseH/h_mt2bins10J";
      }
      else if (ht_LOW == 1500) inclusiveTemplateName = "crdybaseUH/h_mt2bins";

      if (inclusiveTemplateName == "") {
	cout<< "Can't find template for region: HT "<<ht_LOW<<"-"<<ht_HI<<" and NJ "<<njets_LOW<<"-"<<njets_HI<<endl;
	lastbin_hybrid = 1;
	h_MT2Template = 0;
	cout<<"h_MT2Template is 0, using hybrid within this region (no external templates)"<<endl;
      }
      else {
	cout<< "Using inclusive template "<<inclusiveTemplateName<<" for region: HT "<<ht_LOW<<"-"<<ht_HI<<" and NJ "<<njets_LOW<<"-"<<njets_HI<<endl; 
	// Get the template
	lastbin_hybrid = makeHybridTemplate(srname, h_MT2Template, inclusiveTemplateName , fData, fZinv, fDY, lastmt2val_hybrid);
	cout<<"lastbin_hybrid "<<lastbin_hybrid<<" and lastmt2val_hybrid "<<lastmt2val_hybrid<<endl;
	if (h_MT2Template!=0) h_MT2Template->Print();
	else cout<<"h_MT2Template is 0, using hybrid within this region (no external templates)"<<endl;
      }

   


    }

  


    // If there is no template for this region, go back to the standard hybrid
    if (doHybridSimple || (doHybridInclusiveTemplate && h_MT2Template == 0)) {
      // hybrid method: use nominal MC CR yield histogram to determine how many MT2 bins to use
      //  by default: use all MT2 bins integrated (no bin-by-bin).
      //  choose the last bin to try to have at least hybrid_nevent_threshold integrated events

      // Calculate last bin on local histogram
      for ( int ibin=1; ibin <= hDY->GetNbinsX(); ++ibin ) {
	float top = 0, integratedYield = 0;
	//if (hDataEM) top = hDataEM->Integral(ibin,-1)*rSFOF;
	integratedYield = hDY->Integral(ibin,-1) - top;
	if (integratedYield < hybrid_nevent_threshold) {
	  if (ibin == 1) lastbin_hybrid = 1;
	  else {
	    lastbin_hybrid = ibin-1;
	    lastmt2val_hybrid = hDY->GetBinLowEdge(ibin);
	  }
	  break;
	}
      }
      cout<<"lastbin_hybrid for doHybridSimple: "<<lastbin_hybrid<<endl;
    }
    
    

    TH1D* ratio = (TH1D*) hZinv->Clone("ratio");
    ratio->Divide(hDY);
    double errNum, errDen;
    float ratioValue = hZinv->IntegralAndError(1,-1,errNum) / hDY->IntegralAndError(1,-1,errDen);
    float ratioErr = ratioValue*sqrt(pow(errNum/hZinv->Integral(), 2) + pow(errDen/hDY->Integral(),2));

    TH1D* CRyield = (TH1D*) hData->Clone("h_mt2binsCRyield");

    TH1D* purityMC = (TH1D*) hDY->Clone("h_mt2binsPurityMC");
    if (hTop) purityMC->Add(hTop, -1);
    purityMC->Divide(hDY);

    TH1D* purityData = (TH1D*) hData->Clone("h_mt2binsPurityData");
    if (hDataEM) purityData->Add(hDataEM, -1*rSFOF); 
    purityData->Divide(purityData, hData, 1, 1, "B");
    
    TH1D* Stat = (TH1D*) CRyield->Clone("h_mt2binsStat");
    Stat->Multiply(purityData);
    Stat->Multiply(ratio);

    TH1D* Syst = (TH1D*) Stat->Clone("h_mt2binsSyst");
    TH1D* pred = (TH1D*) Stat->Clone("h_mt2bins");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      Syst->SetBinError(ibin, (1-purityData->GetBinContent(ibin))*0.2*Stat->GetBinContent(ibin));
      double quadrature = Stat->GetBinError(ibin)*Stat->GetBinError(ibin) + Syst->GetBinError(ibin)*Syst->GetBinError(ibin);
      pred->SetBinError(ibin, sqrt(quadrature));
    }
    //pred->Print("all");

    // Inputs to cardMaker
    TH1D* ratioCard  = (TH1D*) ratio->Clone("ratioCard");
    TH1D* purityCard  = (TH1D*) purityData->Clone("purityCard");   
    TH1D* CRyieldCard  = (TH1D*) CRyield->Clone("CRyieldCard");

    TH1D *CRyieldEM = 0, *CRyieldEMCard = 0;
    if (hDataEM){
        CRyieldEM = (TH1D*) hDataEM->Clone("h_mt2binsCRyieldEM");
        CRyieldEMCard = (TH1D*) CRyieldEM->Clone("CRyieldEMCard");
    }

    if (  doHybridSimple || (doHybridInclusiveTemplate && h_MT2Template==0) ) { 
      // purity needs to describe the integrated purity of the CR
      // ratio needs to be modified so that the last N bins include kMT2
      // CRyield needs to be modified so that the last N bins have the same yield (which is the integral over those N bins)
      if (verbose) cout<<" Implementing simple hybrid "<<endl;

      for ( int ibin=1; ibin <= hZinv->GetNbinsX(); ++ibin ) {

	if (ibin < lastbin_hybrid) continue;
	
	double integratedYieldErr = 0;
	float integratedYield = CRyield->IntegralAndError(lastbin_hybrid,-1,integratedYieldErr);
	CRyieldCard->SetBinContent(ibin, integratedYield);
	CRyieldCard->SetBinError(ibin, integratedYieldErr);
	
	float integratedDen = integratedYield;
	double EM = 0, errEM = 0;
	if (hDataEM) EM =  hDataEM->IntegralAndError(lastbin_hybrid, -1, errEM) * rSFOF;
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, EM);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, errEM);
        float integratedNum = integratedDen - EM;
	if (integratedNum < 0) integratedNum = 0;
	float integratedPurity = integratedNum/integratedDen;
	float integratedPurityErr = sqrt(integratedPurity*(1-integratedPurity)/integratedDen);// sqrt(e(1-e)/N)   
	purityCard->SetBinContent(ibin, integratedPurity);
	purityCard->SetBinError(ibin, integratedPurityErr);

	float integratedZinv = 1;
	float kMT2 = 0;
	integratedZinv = hZinv->Integral(lastbin_hybrid, -1);
	kMT2 = hZinv->GetBinContent(ibin) / integratedZinv;
	ratioCard->SetBinContent(ibin, ratioCard->GetBinContent(ibin) * kMT2);
	ratioCard->SetBinError(ibin, ratioCard->GetBinError(ibin) * kMT2 ); // just rescale the error by the same amount

      }
    } 
    else if (doHybridInclusiveTemplate && h_MT2Template!=0) {
      // For Inclusive template: 
      // CRyield: this is flat, just the integral
      // purity: also flat
      // ratio: this contains the normalized template scaled by the Zinv/DY ratio for this control region
      // Template should be rebinned to match this region. lastbin_hybrid will have to be updated to refer to the new binning
      
      if (verbose) cout<<" Implementing hybrid with template "<<endl;

//      // MT2template needs to be rebinned for this topological region Rebin
//      double *TopoRegionBins = hZinv->GetXaxis()->GetXbins()->fArray;
//      int nTopoRegionBins    = hZinv->GetXaxis()->GetNbins();
//      h_MT2Template->Print("all");
//      TH1D* h_MT2TemplateRebin = (TH1D*) h_MT2Template->Rebin(nTopoRegionBins, "h_MT2TemplateRebin", TopoRegionBins);
//      int newlastbin = h_MT2TemplateRebin->FindBin(lastmt2val_hybrid-1);
//      if (newlastbin == 0) newlastbin = 1; // 1 is the lowest
//      if (verbose) cout<<"Rebinning moved lastbin_hybrid from "<<lastbin_hybrid<<" to "<<newlastbin<<". lastmt2val_hybrid="<<lastmt2val_hybrid<<endl;
//      lastbin_hybrid = newlastbin;
//      if (verbose) h_MT2TemplateRebin->Print("all");
      if (verbose) cout<<"Ratio for this control region is "<<ratioValue<<endl;

      double integratedYieldErr = 0;
      float integratedYield = CRyield->IntegralAndError(0,-1,integratedYieldErr);
      
      float integratedDen = integratedYield;
      double EM = 0, errEM=0;
      if (hDataEM) EM =  hDataEM->IntegralAndError(0, -1, errEM)*rSFOF;
      float integratedNum = integratedDen - EM;
      if (integratedNum < 0) integratedNum = 0;
      float integratedPurity = integratedNum/integratedDen;      
      // float integratedPurityErr = sqrt(integratedPurity*(1-integratedPurity)/integratedDen);// sqrt(e(1-e)/N)
      // this isn't a proportion (OF/SF are statistically independent regions). Makes no sense to do this
      // what we want is the error on (SF - R*OF). Three sources: dSF, OF*dR, and R*dOF
      // first comes from gmN error in the cards on the main CR yield
      // second comes from special RSFOF handling in cardmaker
      // third should be: R*dOF/(SF-R*dOF). Use proper poissonian error on OF yield
      errEM = ROOT::Math::gamma_quantile_c((1-0.6828)/2, int(EM)+1, 1) - EM;
      float integratedPurityErr = rSFOF*errEM / integratedNum * integratedPurity;

      if(integratedDen==0.0){
          // if CR is 0, assume purity of 1.0 and give it a big error (this basically assumes that SF=1 and OF=0)
          integratedPurity = 1.0;
          errEM = ROOT::Math::gamma_quantile_c((1-0.6828)/2, int(0)+1, 1) - 0;
          integratedPurityErr = rSFOF*errEM;
      }
      
      if (verbose) cout<<"Found SF="<<integratedYield<<" and OF="<<EM<<", so purity is "<<integratedPurity<<endl;

      for ( int ibin=1; ibin <= hZinv->GetNbinsX()+1; ++ibin ) {
	CRyieldCard->SetBinContent(ibin, integratedYield);
	CRyieldCard->SetBinError(ibin,   integratedYieldErr);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, EM);
        if (hDataEM) CRyieldEMCard->SetBinContent(ibin, errEM);
	ratioCard->SetBinContent(ibin, ratioValue * h_MT2Template->GetBinContent(ibin));
        float err = 0.0;
        if(ratioValue>0.0 && h_MT2Template->GetBinContent(ibin)>0.0)
            err = ratioValue * h_MT2Template->GetBinContent(ibin) * sqrt(pow(ratioErr/ratioValue,2) + pow(h_MT2Template->GetBinError(ibin)/h_MT2Template->GetBinContent(ibin),2));
	ratioCard->SetBinError(ibin,   err);
	purityCard->SetBinContent(ibin, integratedPurity);
	purityCard->SetBinError(ibin,   integratedPurityErr);
      }

    }

    TH1D* ratioCard_lepeff_UP = (TH1D*)ratioCard->Clone("ratioCard_lepeff_UP");
    TH1D* ratioCard_lepeff_DN = (TH1D*)ratioCard->Clone("ratioCard_lepeff_DN");
    if(hDY_lepeff_UP) ratioCard_lepeff_UP->Scale(hDY->Integral() / hDY_lepeff_UP->Integral());
    if(hDY_lepeff_DN) ratioCard_lepeff_DN->Scale(hDY->Integral() / hDY_lepeff_DN->Integral());

    TH1D* ratioCard_trigeff_UP = (TH1D*)ratioCard->Clone("ratioCard_trigeff_UP");
    TH1D* ratioCard_trigeff_DN = (TH1D*)ratioCard->Clone("ratioCard_trigeff_DN");
    if(hDY_trigeff_UP) ratioCard_trigeff_UP->Scale(hDY->Integral() / hDY_trigeff_UP->Integral());
    if(hDY_trigeff_DN) ratioCard_trigeff_DN->Scale(hDY->Integral() / hDY_trigeff_DN->Integral());

    TH1D* ratioCard_ZNJet_UP = (TH1D*)ratioCard->Clone("ratioCard_ZNJet_UP");
    TH1D* ratioCard_ZNJet_DN = (TH1D*)ratioCard->Clone("ratioCard_ZNJet_DN");
    if(hDY_ZNJet_UP && hZinv_ZNJet_UP) ratioCard_ZNJet_UP->Scale(hDY->Integral() / hDY_ZNJet_UP->Integral() * hZinv_ZNJet_UP->Integral() / hZinv->Integral());
    if(hDY_ZNJet_DN && hZinv_ZNJet_DN) ratioCard_ZNJet_DN->Scale(hDY->Integral() / hDY_ZNJet_DN->Integral() * hZinv_ZNJet_DN->Integral() / hZinv->Integral());

    TH1D* ratioCard_renorm_UP = (TH1D*)ratioCard->Clone("ratioCard_renorm_UP");
    TH1D* ratioCard_renorm_DN = (TH1D*)ratioCard->Clone("ratioCard_renorm_DN");
    if(hDY_renorm_UP && hZinv_renorm_UP) ratioCard_renorm_UP->Scale(hDY->Integral() / hDY_renorm_UP->Integral() * hZinv_renorm_UP->Integral() / hZinv->Integral());
    if(hDY_renorm_DN && hZinv_renorm_DN) ratioCard_renorm_DN->Scale(hDY->Integral() / hDY_renorm_DN->Integral() * hZinv_renorm_DN->Integral() / hZinv->Integral());


    TH1D* hybridEstimate  = (TH1D*) CRyieldCard->Clone("hybridEstimate");
    hybridEstimate->Multiply(purityCard);
    hybridEstimate->Multiply(ratioCard);
    
    
    TH1D* h_lastbinHybrid = new TH1D("h_lastbinHybrid",";last bin",1,0,1);
    h_lastbinHybrid->SetBinContent(1,lastbin_hybrid);
    TH1D* h_lastmt2Hybrid = new TH1D("h_lastmt2Hybrid",";last M_{T2} value",1,0,1);
    h_lastmt2Hybrid->SetBinContent(1,lastmt2val_hybrid);

    pred->Write();
    Stat->Write();
    Syst->Write();
    purityMC->Write();
    purityData->Write();
    ratio->Write();
    CRyield->Write();

    ratioCard->Write();
    ratioCard_lepeff_UP->Write();
    ratioCard_lepeff_DN->Write();
    ratioCard_trigeff_UP->Write();
    ratioCard_trigeff_DN->Write();
    ratioCard_ZNJet_UP->Write();
    ratioCard_ZNJet_DN->Write();
    ratioCard_renorm_UP->Write();
    ratioCard_renorm_DN->Write();
    purityCard->Write();
    CRyieldCard->Write();
    h_lastbinHybrid->Write();
    hybridEstimate->Write();
    h_lastmt2Hybrid->Write();
    if (hDataEM) CRyieldEM->Write();
    if (hDataEM) CRyieldEMCard->Write();

    hDY->Write("h_mt2binsMCCR");
    hZinv->Write("h_mt2binsMCSR");

    if(!directoryDY.Contains("J")){
        // we want these for crdy (not saved for monojet, but they're the same as SR anyway)
        h_ht_LOW = (TH1D*) fData->Get(directoryDY+"/h_ht_LOW");
        h_ht_HI  = (TH1D*) fData->Get(directoryDY+"/h_ht_HI");
        h_njets_LOW = (TH1D*) fData->Get(directoryDY+"/h_njets_LOW");
        h_njets_HI  = (TH1D*) fData->Get(directoryDY+"/h_njets_HI");
        h_nbjets_LOW = (TH1D*) fData->Get(directoryDY+"/h_nbjets_LOW");
        h_nbjets_HI  = (TH1D*) fData->Get(directoryDY+"/h_nbjets_HI");
    }

    if(h_ht_LOW) h_ht_LOW->Write();
    if(h_ht_HI)  h_ht_HI->Write();
    if(h_njets_LOW) h_njets_LOW->Write();
    if(h_njets_HI)  h_njets_HI->Write();
    if(h_nbjets_LOW) h_nbjets_LOW->Write();
    if(h_nbjets_HI)  h_nbjets_HI->Write();


  } // loop over signal regions


  return;
}
Exemplo n.º 26
0
//_______________________________________________________________________________
void makeZinvFromGJets( TFile* fZinv , TFile* fGJet , TFile* fZll , vector<string> dirs, string output_name, float kFactorGJetForRatio = 1.0 ) {

  // Generate histogram file with Zinv prediction based on GJetsData * R(Zinv/GJ)


  TFile * outfile = new TFile(output_name.c_str(),"RECREATE") ; 
  outfile->cd();
  const unsigned int ndirs = dirs.size();

  // Do the inclusive ones
  vector<TString> inclPlots;
  inclPlots.push_back("h_njbins");
  inclPlots.push_back("h_nbjbins");
  inclPlots.push_back("h_htbins");
  inclPlots.push_back("h_htbins2");
  inclPlots.push_back("h_mt2bins");
  inclPlots.push_back("h_bosonptbins");

  for ( unsigned int incl = 0; incl < inclPlots.size(); ++incl ) {

    TH1D* hGJetIncl = (TH1D*) fGJet->Get("crgjbaseIncl/"+inclPlots[incl])->Clone();
    TH1D* hZllIncl  = (TH1D*)  fZll->Get("crdybaseIncl/"+inclPlots[incl])->Clone();

    if(!hGJetIncl || !hZllIncl){
      cout<<"could not find histogram "<<inclPlots[incl]<<endl;
      continue;
    }
    if (hGJetIncl->GetNbinsX() != hZllIncl->GetNbinsX() ) {
      cout<<"different binning for histograms "<<inclPlots[incl]<<endl;
      continue;
    }
    outfile->cd();

    hGJetIncl->Scale(kFactorGJetForRatio); // The goal is LO(Z) / LO(gamma)

    // Since we're working on MC, let's set poissionian errors by hand
    hZllIncl->Sumw2(0); hZllIncl->Sumw2(1);
    hGJetIncl->Sumw2(0); hGJetIncl->Sumw2(1);
    TH1D* ratioIncl = (TH1D*) hZllIncl->Clone(inclPlots[incl]+"Ratio");
    ratioIncl->Divide(hGJetIncl);

    ratioIncl->Write();

  } // end of inclusive plots

  for ( unsigned int idir = 0; idir < ndirs; ++idir ) {

    TString directory = "sr"+dirs.at(idir);
    TString directoryGJ = "crgj"+dirs.at(idir);

    cout<<"Looking at directory "<<directory<<endl;

    TString fullhistname = directory + "/h_mt2bins";
    TString fullhistnameHT = directory + "/h_htbins";
    TString fullhistnameHT2 = directory + "/h_htbins2";
    TString fullhistnameNJ = directory + "/h_njbins";
    TString fullhistnameNB = directory + "/h_nbjbins";
    //    TString fullhistnamePT = directory + "/h_bosonptbins";
    TString fullhistnameGJ = directoryGJ + "/h_mt2bins";
      
    TH1D* hGJet = (TH1D*) fGJet->Get(fullhistnameGJ);    
    TH1D* hZinv = (TH1D*) fZinv->Get(fullhistname);
    TH1D* hZinvHT = (TH1D*) fZinv->Get(fullhistnameHT);
    TH1D* hZinvHT2 = (TH1D*) fZinv->Get(fullhistnameHT2);
    TH1D* hZinvNJ = (TH1D*) fZinv->Get(fullhistnameNJ);
    TH1D* hZinvNB = (TH1D*) fZinv->Get(fullhistnameNB);
    //    TH1D* hZinvPT = (TH1D*) fZinv->Get(fullhistnamePT);
    
    // If Zinv or GJet histograms are not filled, just leave (shouldn't happen when running on full stat MC)
    if(!hGJet ){
      cout<<"could not find histogram "<<fullhistnameGJ<<endl;
      continue;
    }
    if(!hZinv){
      cout<<"could not find histogram "<<fullhistname<<endl;
      continue;
    }
//    if(!hZinvPT){
//      cout<<"could not find histogram "<<fullhistnamePT<<" in file "<<fZinv->GetName()<<endl;
//      continue;
//    }
    cout<<"Looking at histo "<<fullhistname<<endl;      
    if (hGJet->GetNbinsX() != hZinv->GetNbinsX() ) {
      cout<<"different binning for histograms "<<fullhistname<<endl;
      continue;
    }
    //hGJet->Print("all");
    hGJet->Scale(kFactorGJetForRatio); // The goal is LO(Z) / LO(gamma)

    // Make directory and plot(s) in the output file
    TDirectory* dir = 0;
    dir = (TDirectory*)outfile->Get(directory.Data());
    if (dir == 0) {
      dir = outfile->mkdir(directory.Data());
    } 
    dir->cd();
    
    TH1D* Stat = (TH1D*) hZinv->Clone("h_mt2binsStat");
    
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { // "<=" to deal with overflow bin
      if (hGJet->GetBinContent(ibin) > 0)
	Stat->SetBinError(ibin, hZinv->GetBinContent(ibin)/sqrt( hGJet->GetBinContent(ibin) ));
      else Stat->SetBinError(ibin, hZinv->GetBinContent(ibin));
    }
    

    // Zgamma ratio in each MT2bin -> to get MC stat error on ratio
    TH1D* ratio = (TH1D*) hZinv->Clone("h_mt2binsRatio");
    //ratio->Print("all");
    //hGJet->Print("all");
    ratio->Divide(hGJet);
    //ratio->Print("all");

    TH1D* ratioInt = (TH1D*) hZinv->Clone("h_mt2binsRatioInt");
    double nGammaErr = 0;
    double nGamma = hGJet->IntegralAndError(0, -1, nGammaErr);
    for ( int ibin = 0; ibin <= ratioInt->GetNbinsX(); ++ibin) {
      if (nGamma>0) {
        ratioInt->SetBinContent(ibin, ratioInt->GetBinContent(ibin)/nGamma);
        float errOld = ratioInt->GetBinError(ibin)/nGamma;
        float errNew = (nGammaErr/nGamma) * ratioInt->GetBinContent(ibin);
        //cout<<nGamma<<" "<<nGammaErr<<" "<<errOld<<" "<<errNew<<endl;
        ratioInt->SetBinError(ibin, sqrt( errOld*errOld + errNew*errNew ) );
      }
      else {
        ratioInt->SetBinContent(ibin, 0);
        ratioInt->SetBinError(ibin, 0);
      }
    }
    //ratioInt->Print("all");

    // MCStat: use relative bin error from ratio hist, normalized to Zinv MC prediction
    TH1D* MCStat = (TH1D*) hZinv->Clone("h_mt2binsMCStat");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      MCStat->SetBinError(ibin, MCStat->GetBinContent(ibin) * ratio->GetBinError(ibin) / ratio->GetBinContent(ibin) );
    }

    TH1D* Syst = (TH1D*) Stat->Clone("h_mt2binsSyst");
    TH1D* pred = (TH1D*) Stat->Clone("h_mt2bins");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      Syst->SetBinError(ibin, 0.);
      double quadrature = Stat->GetBinError(ibin)*Stat->GetBinError(ibin) + Syst->GetBinError(ibin)*Syst->GetBinError(ibin);
      pred->SetBinError(ibin, sqrt(quadrature));
    }
    //pred->Print("all");
    
    TH1D* CRyield = (TH1D*) hGJet->Clone("h_mt2binsCRyield");

    // Extrapolation to next bin: just a ratio of GJet_i/GJet_i-1, so that we can later obtain bin i prediction from bin i-1 yield
    // Instead of : GJet_i * R(Zinv_i/GJet_i), we will do GJet_i-1 * R(GJet_i/GJet_i-1) * R(Zinv_i/GJet_i)
    TH1D* PreviousBinRatio = (TH1D*) hGJet->Clone("h_mt2binsPreviousBinRatio");
    for ( int ibin = 0; ibin <= Stat->GetNbinsX(); ++ibin) { 
      if (ibin<=1) PreviousBinRatio->SetBinContent(ibin, 1.);
      else {
	PreviousBinRatio->SetBinContent(ibin, hGJet->GetBinContent(ibin)/hGJet->GetBinContent(ibin-1));
	PreviousBinRatio->SetBinContent(ibin, hGJet->GetBinContent(ibin)/hGJet->GetBinContent(ibin-1));
      }
      PreviousBinRatio->SetBinError(ibin, 0.); // Ignore uncertainty (just MC anyway)
    }
    

    pred->Write();
    Stat->Write();
    Syst->Write();
    CRyield->Write();
    MCStat->Write();
    PreviousBinRatio->Write();
    ratio->Write();
    ratioInt->Write();
    if(hZinvHT)  hZinvHT->Write();
    if(hZinvHT2) hZinvHT2->Write();
    if(hZinvNJ)  hZinvNJ->Write();
    if(hZinvNB)  hZinvNB->Write();
    //    hZinvPT->Write();
  } // loop over signal regions

  return;
}
int calculateSignificance(double metCut, double ecaloCut, TString region, TString folder = "NLostOuterGe0") {


    TString nlost = "";
    if(folder.Contains("NLostOuterGe0")) nlost="0";
    else if(folder.Contains("NLostOuterGe1")) nlost="1";
    else if(folder.Contains("NLostOuterGe2")) nlost="2";
    else if(folder.Contains("NLostOuterGe3")) nlost="3";

    gStyle->SetOptStat(0);
    TeresaPlottingStyle2d::init();
    gStyle -> SetTitleSize(0.05,"Z");
    gStyle -> SetTitleOffset(1.2,"Z");
    gStyle -> SetOptTitle(1);
    gStyle -> SetNdivisions(505,"Z");

    gStyle->SetTitleStyle(1);
    gStyle->SetStatStyle(0);
    gROOT->ForceStyle();

    //gStyle->SetTitleBorderSize(0);
    //gStyle -> SetPadRightMargin(0.20);
    //gStyle->SetTitleFont(42,"");

    vector<TString> samples;
    vector<TString> titles;
    TString sig_m100_ct1 = "Madgraph_signal_mass_100_ctau_1cm";
    samples.push_back(sig_m100_ct1);
    titles.push_back("mass=100GeV, c#tau=1cm");
    TString sig_m100_ct5 = "Madgraph_signal_mass_100_ctau_5cm";
    samples.push_back(sig_m100_ct5);
    titles.push_back("mass=100GeV, c#tau=5cm");
    TString sig_m100_ct10 = "Madgraph_signal_mass_100_ctau_10cm";
    samples.push_back(sig_m100_ct10);
    titles.push_back("mass=100GeV, c#tau=10cm");
    TString sig_m100_ct50 = "Madgraph_signal_mass_100_ctau_50cm";
    samples.push_back(sig_m100_ct50);
    titles.push_back("mass=100GeV, c#tau=50cm");
    TString sig_m200_ct1 = "Madgraph_signal_mass_200_ctau_1cm";
    //samples.push_back(sig_m200_ct1);
    TString sig_m200_ct5 = "Madgraph_signal_mass_200_ctau_5cm";
    //samples.push_back(sig_m200_ct5);
    TString sig_m200_ct50 = "Madgraph_signal_mass_200_ctau_50cm";
    //samples.push_back(sig_m200_ct50);
    TString sig_m300_ct5 = "Madgraph_signal_mass_300_ctau_5cm";
    //samples.push_back(sig_m300_ct5);
    TString sig_m300_ct10 = "Madgraph_signal_mass_300_ctau_10cm";
    //samples.push_back(sig_m300_ct10);
    TString sig_m300_ct50 = "Madgraph_signal_mass_300_ctau_50cm";
    //samples.push_back(sig_m300_ct50);
    TString sig_m500_ct1 = "Madgraph_signal_mass_500_ctau_1cm";
    //samples.push_back(sig_m500_ct1);
    //titles.push_back("mass=500GeV, c#tau=1cm");
    TString sig_m500_ct5 = "Madgraph_signal_mass_500_ctau_5cm";
    samples.push_back(sig_m500_ct5);
    titles.push_back("mass=500GeV, c#tau=5cm");
    TString sig_m500_ct10 = "Madgraph_signal_mass_500_ctau_10cm";
    samples.push_back(sig_m500_ct10);
    titles.push_back("mass=500GeV, c#tau=10cm");
    TString sig_m500_ct50 = "Madgraph_signal_mass_500_ctau_50cm";
    samples.push_back(sig_m500_ct50);
    titles.push_back("mass=500GeV, c#tau=50cm");


    for(unsigned int i=0; i<samples.size(); i++) {


        TH2D* sig1 = new TH2D("significance",samples[i] + ": s/#Delta b_{stat}",9,20,65,9,0.00,0.45);
        sig1->GetXaxis()->SetTitle("p_{T} cut [GeV]");
        sig1->GetYaxis()->SetTitle("I_{as} cut");
        //sig1->GetZaxis()->SetTitle("minimum possible x-sec to discover [pb]");
        sig1->GetZaxis()->SetTitle("minimal discoverable x-sec [pb]");
        sig1->GetZaxis()->CenterTitle();
        sig1->SetTitle(titles[i]);

        //    TH2D* sig2 = new TH2D("significance",samples[i]+ ": s/#sqrt((#Delta b_{stat})^{2} + (#Delta b_{sys}^{fake})^{2} + (10 #upoint #Delta b_{sys}^{lepton})^{2})",7,30,65,9,0.00,0.45);
        TH2D* sig2 = new TH2D("significance",samples[i]+ ": s/#Delta b_{stat + sys}",9,20,65,9,0.00,0.45);
        sig2->GetXaxis()->SetTitle("p_{T} cut [GeV]");
        sig2->GetYaxis()->SetTitle("I_{as} cut");
        sig2->GetZaxis()->SetTitle("minimal discoverable x-sec [pb]");
        sig2->GetZaxis()->CenterTitle();
        //sig2->SetTitle(titles[i] + ", N_{lost}^{outer}#geq" + nlost);
        sig2->SetTitle(titles[i]);
        sig2->GetZaxis()->SetNoExponent(kTRUE);
        //sig2->GetZaxis()->SetRangeUser(0.5,2.5);

        TH2D* hBkgYield = new TH2D("hBkgYield","Bkg Yield",9,20,65,9,0.00,0.45);
        hBkgYield -> GetXaxis()->SetTitle("p_{T} cut [GeV]");
        hBkgYield -> GetYaxis()->SetTitle("I_{as} cut");
        hBkgYield -> GetZaxis()->SetTitle("bkg yield");

        TH2D* hBkgUnc = new TH2D("hBkgUnc","Bkg Unc",9,20,65,9,0.00,0.45);
        hBkgUnc -> GetXaxis()->SetTitle("p_{T} cut [GeV]");
        hBkgUnc -> GetYaxis()->SetTitle("I_{as} cut");
        hBkgUnc -> GetZaxis()->SetTitle("bkg uncertainty [%]");

        TH2D* hSignalYield = new TH2D("hSignalYield",samples[i] + ": Signal Yield",9,20,65,9,0.00,0.45);
        hSignalYield -> GetXaxis()->SetTitle("p_{T} cut [GeV]");
        hSignalYield -> GetYaxis()->SetTitle("I_{as} cut");
        hSignalYield -> GetZaxis()->SetTitle("signal yield");
        hSignalYield -> SetTitle(titles[i]);

        //----------------------------------------------------------------------------------------------------------
        // Get theory cross-section:
        cout<<"######################################################"<<endl;
        cout<<"Get theory cross section:"<<endl;
        ifstream inputFile("xsectionsUpdated.txt");
        int it=0;
        TString name;
        double xsec,err;
        while(inputFile>>name>>xsec>>err) {
            TString aux =  "mass_" + name;
            cout<<"aux = "<<aux<<endl;
            if ( samples[i].Contains(aux) ) {
                cout<<endl<<name<<": "<<xsec<<" pb"<<endl<<endl;
                break;
            }
            it++;
        }
        inputFile.close();
        xsec = xsec/1000.;   // xsection in pb
        cout<<"######################################################"<<endl;
        //----------------------------------------------------------------------------------------------------------

        for(int l=0; l<9; l++) {
            //      for(int l=0; l<9; l++){

            double ptCut = 20 + l*5;

            //for(int j=0; j<9; j++){
            for(int j=0; j<9; j++) {


                double iasCut = 0.00 + j*0.05;

                cout<<"---------------------------------------------"<<""<<endl;
                cout<<"pt cut = "<<ptCut<<", Ias Cut = "<<iasCut<<endl;
                //TFile *fBkg        = new TFile(Form("totalBkg" + folder + "/TotalBkg_metCutEq%.0f_ptCutEq%0.f_ECaloCutEq%.0f_IasCutEq0p%02.0f_",metCut,ptCut,ecaloCut,iasCut*100) + region +".root" ,"READ");
                //TString filename   = "signal" + folder + "/Signal_" + samples[i]  + Form("_metCutEq%.0f_ptCutEq%.0f_ECaloCutEq%.0f_IasCutEq0p%02.0f.root",metCut,ptCut,ecaloCut,iasCut*100);
                TFile *fBkg        = new TFile(Form("totalBkg" + folder + "/TotalBkg_metCutEq%.0f_ptGt%.0f_Le50000_ECaloCutEq%.0f_IasGt0p%02.0f_Le0p99_",metCut,ptCut,ecaloCut,iasCut*100) + region +".root" ,"READ");
                TString filename   = "signal" + folder + "/Signal_" + samples[i]  + Form("_metCutEq%.0f_ptGt%.0f_Le50000_ECaloCutEq%.0f_IasGt0p%02.0f_Le0p99.root",metCut,ptCut,ecaloCut,iasCut*100);
                TFile *fSignal     = new TFile(filename,"READ");
                TH1D  *hBkg        = 0;
                TH1D  *hLepton     = 0;
                TH1D  *hFake       = 0;
                TH1D  *hSignal     = 0;
                fBkg       -> GetObject("totalBkg",hBkg);
                fBkg       -> GetObject("leptonBkg",hLepton);
                fBkg       -> GetObject("fakeBkg",hFake);
                fSignal    -> GetObject(samples[i],hSignal);

                cout.precision(3);
                double nAll         = 0;
                double nAllErrorUp  = 0;
                double nAllErrorLow = 0;
                double n, nErrorUp, nErrorLow;

                TString eq = "=";

                int bin         = hBkg->GetXaxis()->FindBin(region);
                n = hBkg->IntegralAndError(bin,bin,nErrorUp);
                nErrorLow = nErrorUp;
                if(nErrorUp==0) eq = "<";
                else            eq = "=";
                nAll         = n ;
                nAllErrorUp  = nErrorUp;
                nAllErrorLow = nErrorLow;

                cout<<"nAll        = "<<nAll<<endl;
                cout<<"nAllErrorUp = "<<nAllErrorUp<<endl;
                cout<<"One Sided Upper 68% limit of bkg = "<<getOneSidedUpperLimit(nAll,0.6827)-nAll<<endl;

                cout<<"Total bkg                          = "<<nAll<<" + "<<nAllErrorUp<<" - "<<nAllErrorLow<<""<<endl;
                cout<<samples[i]<<" = "<<hSignal->GetBinContent(1)<<" +/- "<<hSignal->GetBinError(1)<<endl;
                cout<<"Statistics of signal = "<<pow(hSignal->GetBinContent(1),2)/pow(hSignal->GetBinError(1),2)<<endl;

                hBkgYield    -> SetBinContent(l+1,j+1,n);
                hBkgUnc      -> SetBinContent(l+1,j+1,nErrorUp/n);
                hSignalYield -> SetBinContent(l+1,j+1,hSignal->GetBinContent(1));

                double sOverDeltabUp    = hSignal->GetBinContent(1)/(getOneSidedUpperLimit(nAll,0.6827)-nAll);
                double sOverDeltabError = 0;
                sig1->SetBinContent(l+1,j+1,sOverDeltabUp);
                sig1->SetBinError(l+1,j+1,sOverDeltabError);


                double leptonStatError = hLepton -> GetBinError(bin);
                double fakeStatError   = hFake   -> GetBinError(bin);
                cout<<"leptonStatError  = "<<leptonStatError<<endl;
                cout<<"fakeStatError    = "<<fakeStatError<<endl;

                double leptonSysError = hLepton -> GetBinContent(bin)*1.0;  // 100% error
                double fakeSysError   = hFake   -> GetBinContent(bin)*0.2;  // 20% error
                cout<<"leptonSysError  = "<<leptonSysError<<endl;
                cout<<"fakeSysError    = "<<fakeSysError<<endl;

                // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                // Vary now signal x-sec and don't take the one given from theory -> model independent optimisation
                double sOverDeltabUpStatPlusSys          = 0;
                double sOverDeltabUpStatPlusSysError     = 0;
                double minExcludedXsec                   = 0;
                for(int k=0; k<1000; k++) {

                    sOverDeltabUpStatPlusSys            = k/sqrt( pow( getOneSidedUpperLimit(nAll,0.6827)-nAll ,2) + pow(fakeStatError ,2) + pow(leptonStatError ,2) + pow(fakeSysError ,2) + pow(leptonSysError ,2));


                    if(sOverDeltabUpStatPlusSys>5) {
                        cout<<"Dicovery possible !!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;

                        minExcludedXsec =1.*k/hSignal->GetBinContent(1)*xsec;
                        cout<<"minimal xsec = "<<minExcludedXsec<<endl;
                        cout<<"theory xsec  = "<<xsec<<endl;
                        break;

                    }



                }

                sig2->SetBinContent(l+1,j+1,minExcludedXsec);
                //	sig2->SetBinError(l+1,j+1,sOverDeltabUpStatPlusSysError);

                cout<<"s/(Delta b_stat)                          = "<<sOverDeltabUp<<" +/- "<<sOverDeltabError<<endl;
                cout<<"s/sqrt(Delta b_stat**2 + (Delta b_sys**2) = "<<sOverDeltabUpStatPlusSys<<" +/- "<<sOverDeltabUpStatPlusSysError<<endl;

                //fBkg->Close();
                //fSignal->Close();

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

                    sOverDeltabUp                       = k/sqrt( pow( getOneSidedUpperLimit(nAll,0.6827)-nAll ,2));

                    if(sOverDeltabUp>5) {
                        cout<<"Dicovery possible !!!!!!!!!!!!!!!!!!!!!!!!!!"<<endl;

                        minExcludedXsec =1.*k/hSignal->GetBinContent(1)*xsec;
                        cout<<"minimal xsec = "<<minExcludedXsec<<endl;
                        cout<<"theory xsec  = "<<xsec<<endl;
                        break;

                    }

                }


                sig1->SetBinContent(l+1,j+1,minExcludedXsec);

                cout<<"s/(Delta b_stat)                          = "<<sOverDeltabUp<<" +/- "<<sOverDeltabError<<endl;
                cout<<"s/sqrt(Delta b_stat**2 + (Delta b_sys**2) = "<<sOverDeltabUpStatPlusSys<<" +/- "<<sOverDeltabUpStatPlusSysError<<endl;

                fBkg->Close();
                fSignal->Close();

            }
        }
        TCanvas *c = new TCanvas(samples[i],samples[i],500,500);
        sig1->Draw("COLZ");
        c->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" +  "_SOverDeltaBStat.pdf", ecaloCut));

        TCanvas *c1 = new TCanvas(samples[i],samples[i],500,500);
        sig2->Draw("COLZ");
        //c1->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" + "_SOverDeltaBStatPlusSys_" + nlost+ ".pdf",ecaloCut));
        c1->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" + "_SOverDeltaBStatPlusSys.pdf",ecaloCut));

        TCanvas *c2 = new TCanvas(samples[i],samples[i],500,500);
        hBkgYield->Draw("COLZ");
        c2->SaveAs(Form("plots" + folder + "/BkgYield" + "_ECaloLe%.0f" + ".pdf",ecaloCut));

        TCanvas *c3 = new TCanvas(samples[i],samples[i],500,500);
        hBkgUnc->Draw("COLZ");
        c3->SaveAs(Form("plots" + folder + "/BkgUncertainty" + "_ECaloLe%.0f" + ".pdf",ecaloCut));

        TCanvas *c4 = new TCanvas(samples[i],samples[i],500,500);
        hSignalYield->Draw("COLZ");
        c4->SaveAs(Form("plots" + folder + "/" + samples[i] + "_ECaloLe%.0f" + "_SignalYield.pdf",ecaloCut));



    }

    return 0;

}
Exemplo n.º 28
0
void produceROOT_stat(std::string var, bool update=false)
{
  TH1D* hraw;
  std::string rawName;
  std::string anilName;
  std::string xtitle;

  if(var=="h_ystar")
    {
      rawName  = "Ydiff_Z1Jet";
      anilName = "EfficienyVsYdif";
      xtitle = "0.5|Y_{Z}-Y_{jet}|";	    
    }
  else if(var=="h_yB")
    {
      rawName  = "Ysum_Z1Jet";
      anilName = "EfficienyVsYsum";
      xtitle = "0.5|Y_{Z}+Y_{jet}|";
    }
  else if(var=="h_jety")
    {
      rawName  = "FirstJetY_1jet";
      anilName = "EfficienyVsYjet";
      xtitle = "|Y_{jet}|";
    }
  else if(var=="h_zy")
    {
      rawName  ="ZRap_1jet";
      anilName ="EfficienyVsYz";
      xtitle = "|Y_{Z}|";
    }
 
  // first get the histogram files
  std::string var1=var;
  std::string remword1 ="h_";
  size_t pos1  = var1.find(remword1);
  if(pos1!= std::string::npos)
    var1.replace(pos1,remword1.length(),"");



  TFile *fraw   = TFile::Open("/afs/cern.ch/work/s/syu/anil_rootfile/"
			      "VJets_Analysed_ElecData_ZCut_Jes0.root");
  cout << "Opening " << fraw->GetName() << endl;

  hraw    = (TH1D*)(fraw->Get(rawName.data()));
  hraw    -> SetName(Form("hraw_%s",var1.data()));
  hraw    -> SetXTitle(xtitle.data());
  hraw    -> Sumw2();


  int binLo = -1;
  int binHi = -1;
  int nbins = hraw->GetNbinsX();
  binLo = 1;
  binHi = nbins;



  TH1D* r_corr =(TH1D*) hraw->Clone(Form("stat_%s_corr",var1.data()));
  r_corr->Reset();
  r_corr->SetYTitle("statistical");
  r_corr->SetXTitle(xtitle.data());
  r_corr->SetTitle("");

  for(int i=binLo;i<= binHi; i++){
    
    if(hraw->GetBinContent(i)<1e-6)continue;
    r_corr->SetBinContent(i,1.0);

    double relative_error = hraw->GetBinError(i)/hraw->GetBinContent(i);

    r_corr->SetBinError(i,relative_error);


  }

  
  std::string command = "recreate";
  if(update)command = "update";
  TFile* outFile = new TFile(Form("electron_forSteve.root"),
			     command.data());       
  r_corr->Write();

  outFile->Close();

}
Exemplo n.º 29
0
void compareSysts(){

 setTDRStyle();
 
double width[6] = {25, 20, 25, 30, 50, 100};
 
TString Syst[22] = {"JES_up_dir/JES_up","JES_down_dir/JES_down", "BJet_up_dir/BJet_up", "BJet_down_dir/BJet_down", "PU_up_dir/PU_up", "PU_down_dir/PU_down", "Scale_up_tt_dir/Scale_up_tt", "Scale_down_tt_dir/Scale_down_tt","Scale_up_dir/Scale_up","Scale_down_dir/Scale_down", "Match_up_tt_dir/Match_up_tt", "Match_down_tt_dir/Match_down_tt" , "Match_up_dir/Match_up", "Match_down_dir/Match_down", "UnclusteredEnUp_dir/UnclusteredEnUp", "UnclusteredEnDown_dir/UnclusteredEnDown", "TauEnUp_dir/TauEnUp", "TauEnDown_dir/TauEnDown", "MuonEnUp_dir/MuonEnUp", "MuonEnDown_dir/MuonEnDown", "ElectronEnUp_dir/ElectronEnUp", "ElectronEnDown_dir/ElectronEnDown"};

    std::cout.setf(std::ios::fixed);
    std::cout.precision(1);

for(int sys = 0; sys < 22; sys++){

 TH1D * central = getSysts("central_dir/central");
 TH1D * syst_up = getSysts(Syst[sys]);//up_tt for ttbar
// TH1D * syst_down = getSysts("Scale_down_dir/Scale_down"); 
 
 
cout <<  Syst[sys] << " & " ;
 
 for(int i=1; i <= 6; i++){ //loops over met bins
 

 
 central->SetBinContent(i,central->GetBinContent(i)/width[i-1]); 
 central->SetBinError(i,central->GetBinError(i)/width[i-1]);
 syst_up->SetBinContent(i,syst_up->GetBinContent(i)/width[i-1]); 
// syst_down->SetBinContent(i,syst_down->GetBinContent(i)/width[i-1]);
   
 syst_up->SetBinError(i,0.);
 //syst_down->SetBinError(i,0.);
 
 cout << 100*(central->GetBinContent(i)-syst_up->GetBinContent(i))/central->GetBinContent(i) << " & " ;
 
 }
  
cout << " " << endl;


if(sys==21){ 
cout << "Stat: & " ;
for(int i=1; i <= 6; i++){
cout << 100*central->GetBinError(i)/central->GetBinContent(i) << " & " ;
}
}


delete syst_up, central;


}//end systs loop

//   	//do the plots  
//  	TCanvas *c= new TCanvas("c","c",10,10,800,600);
//   
//   	central->SetMarkerStyle(20);	 
//   	central->Draw("E");
// 	central->SetMaximum(central->GetBinContent(central->GetMaximumBin())*1.3);
// 	central->SetMinimum(0.);
// 	
// 	syst_up->SetLineColor(kRed);
// 	syst_down->SetLineColor(kBlue);
// 	
// 	syst_up->Draw("same");
// 	syst_down->Draw("same");
// 
// 	TLegend *tleg;
// 	tleg = new TLegend(0.6,0.75,0.85,0.9);
// 	tleg->SetTextSize(0.03);
// 	tleg->SetBorderSize(0);
// 	tleg->SetFillColor(10);
// 
// 	tleg->AddEntry(central  , "nominal"      , "lep"); 
// 	//tleg->AddEntry(syst_up  , "JES up"      , "l");
// 	//tleg->AddEntry(syst_down  , "JES down"      , "l");
// 	tleg->AddEntry(syst_up  , "Q^{2} up"      , "l");
// 	tleg->AddEntry(syst_down  , "Q^{2} down"      , "l");
// 	
// 	tleg->Draw();
//   	//titles
// 	central->GetYaxis()->SetTitle("#frac{1}{#sigma} #frac{#partial #sigma}{#partial MET} 				[GeV^{-1}]"); central->GetYaxis()->SetTitleSize(0.05);
// 	//central->GetYaxis()->SetTitle("N t#bar{t} fit"); central->GetYaxis()->SetTitleSize(0.05);
// 	
// 	
// 	central->GetXaxis()->SetTitle("MET [GeV]"); central->GetXaxis()->SetTitleSize(0.05);
//       
//        
//        //c->SaveAs("plots/compare/JEScompare.png");
//        c->SaveAs("plots/compare/Scalecompare.png");
// 
// 	delete c;


  
}  
Exemplo n.º 30
0
void PostFitCombine(TString Plots = "fit_s", TString InpDir = "FitResults_DataCardFixbtagSysVisPhSp_hSF-PreApp-v0_Tree_LepJets_NewJEC-OldKinFit_v8-0-6_Spring16-80X_36814pb-1_2btag", TString FitDir = "OBSERVED"){

  TString PlotsFileName;
  if(FitDir == "OBSERVED") PlotsFileName = "obs";
  if(FitDir == "EXPECTED") PlotsFileName = "exp";
 
  TString inputfile = "CombineResults/" + InpDir + "/" + FitDir + "/fitDiagnostics" + PlotsFileName + "MLF.root";
  
 
  setTDRStyle();

  gROOT->SetStyle("Plain");
  gStyle->SetOptFit(1000);
  gStyle->SetOptStat("emruo");
  gStyle->SetOptStat(kFALSE);
  gStyle->SetPadTickY(1);
  gStyle->SetPadTickX(1);
  
  int col_ttbb = TColor::GetColor("#660000");
  int col_ttb  = TColor::GetColor("#ffcc00");
  int col_ttcc = TColor::GetColor("#cc6600");
  int col_ttc  = TColor::GetColor("#cc6600");
  int col_ttLF = TColor::GetColor("#ff0000");
  int col_tt   = TColor::GetColor("#FF7F7F");

  int col_ttbarBkg  = TColor::GetColor("#ff6565");
  int col_SingleTop = TColor::GetColor("#ff00ff");
  int col_WJets     = TColor::GetColor("#33cc33");
  int col_ZJets     = TColor::GetColor("#3366ff");
  int col_QCD       = TColor::GetColor("#ffff00");
  int col_ttbarV    = TColor::GetColor("#e75c8d");
  int col_ttbarH    = TColor::GetColor("#e5c4f4");
  int col_VV        = TColor::GetColor("#ffffff");
 
  TFile *hfile = NULL;
  hfile = TFile::Open(inputfile);
  cout << "file loaded: " << inputfile << endl;

  std::vector<TString> hNamefile;
  std::vector<int> hColor;
  hNamefile.push_back("ttbar_LepJetsPowhegPythiattbb"); // 0
  hColor.push_back(TColor::GetColor("#660000"));
  hNamefile.push_back("ttbar_LepJetsPowhegPythiattbj"); // 1 
  hColor.push_back(TColor::GetColor("#ffcc00"));
  hNamefile.push_back("ttbar_LepJetsPowhegPythiattcc"); // 2
  hColor.push_back(TColor::GetColor("#cc6600"));
  hNamefile.push_back("ttbar_LepJetsPowhegPythiattLF"); // 3
  hColor.push_back(TColor::GetColor("#ff0000"));
  hNamefile.push_back("ttbar_PowhegPythiaBkgtt");
  hColor.push_back(TColor::GetColor("#FF7F7F"));
  hNamefile.push_back("ttHbb_PowhegPythia");
  hColor.push_back(TColor::GetColor("#e5c4f4"));
  hNamefile.push_back("ttV_Madgraph");
  hColor.push_back(TColor::GetColor("#e75c8d"));
  hNamefile.push_back("WJets_aMCatNLO");
  hColor.push_back(TColor::GetColor("#33cc33"));
  hNamefile.push_back("QCD");
  hColor.push_back(TColor::GetColor("#ffff00"));
  hNamefile.push_back("SingleTop");
  hColor.push_back(TColor::GetColor("#ff00ff"));
  hNamefile.push_back("VV");
  hColor.push_back(TColor::GetColor("#ffffff"));
  hNamefile.push_back("ZJets_aMCatNLO");
  hColor.push_back(TColor::GetColor("#3366ff"));
  hNamefile.push_back("total");
  hColor.push_back(1);
  hNamefile.push_back("total_signal");
  hColor.push_back(1);
  hNamefile.push_back("total_background");
  hColor.push_back(1);



  //TString dirname[2]     = {"Name1","Name2"};     //{mu,e}
  TString dirname[2]     = {"ch1","ch2"};     //{mu,e}
  TString titlechname[2] = {"#mu+Jets","e+Jets"}; 
  TString chname[2]      = {"mujets","ejets"};    

  std::vector<TH1D*> hInput[2];
  TH1D    *hData[2], *hData_reg[2][20];
  THStack *AllMC[2], *AllMC_reg[2][20];
  
  THStack *AllMC_CSV1[2], *AllMC_CSV2[2];

  // THStack Initialization
  for(int ich=0;ich<2;ich++){
    AllMC[ich] = new THStack("PostFit_"+chname[ich], "CSV Distribution Post-Fit ("+titlechname[ich]+")");  
    for(int ireg=0;ireg<20;ireg++){
      TString RegNum;
      RegNum.Form("%i",ireg); 
      AllMC_reg[ich][ireg] = new THStack("PostFit_"+chname[ich]+RegNum, "CSV Distribution Post-Fit ("+titlechname[ich]+") for "+RegNum);        
    } // for(ireg)
  } // for(ich)
 
  cout << "Loading histograms... " << endl;

  // MC Profiles
  for(int ich=0;ich<2;ich++){

    for(int ih=0;ih<hNamefile.size();ih++){      
      cout << "shapes_"+Plots+"/"+dirname[ich]+"/" + hNamefile.at(ih) << endl;
      TH1D *htemp = (TH1D*) hfile->Get("shapes_"+Plots+"/"+dirname[ich]+"/" + hNamefile.at(ih))->Clone("c" + hNamefile.at(ih));
      htemp->SetFillColor(hColor.at(ih));
      htemp->SetLineColor(1);
      hInput[ich].push_back(htemp);
      cout << hNamefile.at(ih) << " = " << htemp->Integral()  << endl;
      if(ih==0) AllMC[ich]->SetHistogram((TH1D*)htemp->Clone("FirstStack"));
      if (!hNamefile.at(ih).Contains("total")) AllMC[ich] -> Add(htemp);
      // Data
      // Clone Histo Structure only once
      if(ih==0){
	hData[ich] = (TH1D *) htemp->Clone("data_"+dirname[ich]);
	hData[ich]->Reset();
      }
    } // for(ih)

    // Data TGraph
    TGraphAsymmErrors *DataFull = (TGraphAsymmErrors *) hfile->Get("shapes_"+Plots+"/"+dirname[ich]+"/data")->Clone("data_"+dirname[ich]);
    for(int ibin=1;ibin<=hData[ich]->GetNbinsX();ibin++){ 
      double igb, EvtBinData, EvtErrBinData;
      DataFull->GetPoint((ibin-1),igb,EvtBinData); 
      hData[ich]->SetBinContent(ibin,EvtBinData);
      EvtErrBinData = DataFull->GetErrorY((ibin-1));
      hData[ich]->SetBinError(ibin,EvtErrBinData);
    }
    
    // Histograms for each region
    for(int ih=0;ih<hNamefile.size();ih++){

      TH1D *htemp = (TH1D*) hfile->Get("shapes_"+Plots+"/"+dirname[ich]+"/" + hNamefile.at(ih))->Clone("c_reg" + hNamefile.at(ih));
      
      for(int ireg=0;ireg<20;ireg++){
	TH1D *htempreg = new TH1D ("","",20,0,20);       
    	for(int ibin=1;ibin<=20;ibin++){
	  //if ( (ibin+20*ireg) == 181) cout << hNamefile.at(ih) << " " << ibin+20*ireg << " : " << htemp->GetBinContent(ibin+20*ireg) << " ; " << htemp->GetBinError(ibin+20*ireg) << endl;
    	  htempreg->SetBinContent(ibin,htemp->GetBinContent(ibin+20*ireg));	  
    	  htempreg->SetBinError(ibin,htemp->GetBinError(ibin+20*ireg));	  
	  htempreg->SetFillColor(hColor.at(ih));
    	} // for(ibin)
	if(ih==0) AllMC_reg[ich][ireg]->SetHistogram((TH1D*)htempreg->Clone("FirstStack"));
	if (!hNamefile.at(ih).Contains("total")) AllMC_reg[ich][ireg] -> Add(htempreg);
      } // for(ireg)
    } // for(ih)

    // Data
    for(int ireg=0;ireg<20;ireg++){
      TString RegNum;
      RegNum.Form("%i",ireg);
      hData_reg[ich][ireg] = new TH1D ("hData_"+chname[ich]+RegNum,"Data Histogram "+titlechname[ich]+" for "+RegNum,20,0,20);       

      // Data
      for(int ibin=1;ibin<=20;ibin++){ 
	double igb, EvtBinData, EvtErrBinData;
	DataFull->GetPoint(((ibin-1)+(20*ireg)),igb,EvtBinData); 
	hData_reg[ich][ireg]->SetBinContent(ibin,EvtBinData);	  
	EvtErrBinData = DataFull->GetErrorY((ibin-1));
	hData_reg[ich][ireg]->SetBinError(ibin,EvtErrBinData);

	hData_reg[ich][ireg]->SetMarkerStyle(20);
	hData_reg[ich][ireg]->SetMarkerSize(0.5);
      } // for(ibin)
    } // for(ireg)


    // Recover basic CSV plots
    // -- MC
    TH1D *GlobalCSVJet[12][2]; // 12 components
    AllMC_CSV1[ich] = new THStack("CSV1_"+chname[ich], "CSV-AddJet1 Distribution Post-Fit ("+titlechname[ich]+")");
    AllMC_CSV2[ich] = new THStack("CSV2_"+chname[ich], "CSV-AddJet2 Distribution Post-Fit ("+titlechname[ich]+")");

    for(int ih=0;ih<12;ih++){
      GlobalCSVJet[ih][0] = new TH1D("GlobalCSVJet1_" + hNamefile.at(ih), "CSV distribution for AddJet-1", 20, 0.0, 1.0);
      GlobalCSVJet[ih][1] = new TH1D("GlobalCSVJet2_" + hNamefile.at(ih), "CSV distribution for AddJet-2", 20, 0.0, 1.0);
      RecoverCSVHisto (hInput[ich].at(ih), GlobalCSVJet[ih][0], GlobalCSVJet[ih][1]);
      GlobalCSVJet[ih][0]->SetFillColor(hColor.at(ih));
      GlobalCSVJet[ih][1]->SetFillColor(hColor.at(ih));
      
      if(ih==0) AllMC_CSV1[ich]->SetHistogram((TH1D*)GlobalCSVJet[ih][0]->Clone("FirstStack"));
      if(ih==0) AllMC_CSV2[ich]->SetHistogram((TH1D*)GlobalCSVJet[ih][1]->Clone("FirstStack"));
      AllMC_CSV1[ich] -> Add(GlobalCSVJet[ih][0]);
      AllMC_CSV2[ich] -> Add(GlobalCSVJet[ih][1]);
    }

    // -- Data
    TH1D *GlobalCSVJet_Data[2]; // 12 components
    GlobalCSVJet_Data[0] = new TH1D("GlobalCSVJet1_Data", "CSV distribution for AddJet-1", 20, 0.0, 1.0);
    GlobalCSVJet_Data[1] = new TH1D("GlobalCSVJet2_Data", "CSV distribution for AddJet-2", 20, 0.0, 1.0);
    RecoverCSVHisto (hData[ich], GlobalCSVJet_Data[0], GlobalCSVJet_Data[1]);
    
    // -----------
    // Plotting
    // -----------

    TH1D *hstyle = new TH1D ("","",
			     hData[ich]->GetNbinsX(),
			     hData[ich]->GetBinLowEdge (1),
			     hData[ich]->GetBinLowEdge (hData[ich]->GetNbinsX()+1));
    
    hstyle -> SetMaximum(1.1*hInput[ich].at(12)->GetMaximum());
    hstyle -> GetYaxis()->SetTitleFont(42);
    hstyle -> GetYaxis()->SetTitleOffset(0.7);
    hstyle -> GetYaxis()->SetTitleSize(0.05);
    hstyle -> GetYaxis()->SetLabelFont(42);
    hstyle -> GetYaxis()->SetLabelSize(0.045);
    hstyle -> GetYaxis()->SetNdivisions(607);
    hstyle -> GetYaxis()->SetTitle("Events / unit"); 
    
    
    hData[ich] -> SetMarkerStyle(20); 
    hData[ich] -> SetMarkerSize(0.4); 
    hData[ich] -> SetLineWidth(1); 
    hData[ich] -> SetTitle(""); 
    
    
    TCanvas *cPlots;//histos
    cPlots = new TCanvas("cPlots"+dirname[ich] ,"Plots");
    cPlots->Divide(1,2);
    TPad    *pad[4], *glpad[2];
    // Global Pad
    glpad[0] = (TPad*)cPlots->GetPad(1);
    glpad[0]->Divide(1,2);
    glpad[1] = (TPad*)cPlots->GetPad(2);
    glpad[1]->Divide(1,2);

    //Plot Pad
    pad[0] = (TPad*)glpad[0]->GetPad(1);
    pad[0]->SetPad(0.01, 0.23, 0.99, 0.99);
    pad[0]->SetTopMargin(0.1);
    pad[0]->SetRightMargin(0.04);
    
    //Ratio Pad
    pad[1] = (TPad*)glpad[0]->GetPad(2);
    pad[1]->SetPad(0.01, 0.02, 0.99, 0.3);
    gStyle->SetGridWidth(1);
    gStyle->SetGridColor(14);
    pad[1]->SetGridx();
    pad[1]->SetGridy();
    pad[1]->SetTopMargin(0.05);
    pad[1]->SetBottomMargin(0.4);
    pad[1]->SetRightMargin(0.04);

    //Plot Pad
    pad[2] = (TPad*)glpad[1]->GetPad(1);
    pad[2]->SetPad(0.01, 0.23, 0.99, 0.99);
    pad[2]->SetTopMargin(0.1);
    pad[2]->SetRightMargin(0.04);
    
    //Ratio Pad
    pad[3] = (TPad*)glpad[1]->GetPad(2);
    pad[3]->SetPad(0.01, 0.02, 0.99, 0.3);
    gStyle->SetGridWidth(1);
    gStyle->SetGridColor(14);
    pad[3]->SetGridx();
    pad[3]->SetGridy();
    pad[3]->SetTopMargin(0.05);
    pad[3]->SetBottomMargin(0.4);
    pad[3]->SetRightMargin(0.04);
    
    pad[0]->cd();

    hstyle->Draw();
    AllMC[ich] -> Draw("HISTSAME"); 
    hData[ich] -> Draw("PSAME"); 
    
    TH1D *RatioFull = HistoRatio (hData[ich] , (TH1D*) AllMC[ich]->GetStack()->Last());
    TGraphErrors *gRatioFull = new TGraphErrors(RatioFull);
    gRatioFull->SetFillStyle(1001);
    gRatioFull->SetFillColor(chatch);
    gRatioFull->SetName("gRatioFull");


    TLegend *leg;
    float legPos[4] = {0.70,  // x_o
		       0.40,  // y_o
		       0.94,  // x_f
		       0.87}; // y_f
 
    leg = new TLegend(legPos[0],legPos[1],legPos[2],legPos[3]);
    leg->SetFillColor(0);
    leg->SetLineColor(0);
    leg->SetLineWidth(0.0);
    leg->SetTextFont(62);
    leg->SetTextSize(0.03);
    leg->SetNColumns(2);
  
    leg->AddEntry(hData[ich],         "Data","PL");
    leg->AddEntry(hInput[ich].at(11), "Z+Jets","F");
    leg->AddEntry(hInput[ich].at(10), "VV","F");
    leg->AddEntry(hInput[ich].at(9),  "Single t","F");
    leg->AddEntry(hInput[ich].at(8),  "QCD","F");
    leg->AddEntry(hInput[ich].at(7),  "W+Jets","F");
    leg->AddEntry(hInput[ich].at(6),  "t#bar{t}+V","F");
    leg->AddEntry(hInput[ich].at(5),  "t#bar{t}+H","F");
    leg->AddEntry(hInput[ich].at(4),  "t#bar{t}+other","F");
    leg->AddEntry(hInput[ich].at(3),  "t#bar{t}+LF","F");
    leg->AddEntry(hInput[ich].at(2),  "t#bar{t}+cc","F");
    leg->AddEntry(hInput[ich].at(1),  "t#bar{t}+bj","F");
    leg->AddEntry(hInput[ich].at(0),  "t#bar{t}+bb","F");
    leg->AddEntry(gRatioFull,         "Stat. Unc.","F");

    leg->Draw("SAME");
    
    TLatex *titlePr;      
    titlePr  = new TLatex(-20.,50.,"35.9 fb^{-1} (13TeV)");
    titlePr->SetNDC();
    titlePr->SetTextAlign(12);
    titlePr->SetX(0.78);
    titlePr->SetY(0.935);
    titlePr->SetTextFont(42);
    titlePr->SetTextSize(0.05);
    titlePr->SetTextSizePixels(24);
    titlePr->Draw("SAME");
    
    TLatex *title;
    //title  = new TLatex(-20.,50.,"CMS(2016) #sqrt{s} = 13TeV, L = 35.9 fb^{-1}");
    title  = new TLatex(-20.,50.,"CMS");
    title->SetNDC();
    title->SetTextAlign(12);
    title->SetX(0.13);
    title->SetY(0.84);
    title->SetTextFont(61);
    title->SetTextSize(0.06);
    title->SetTextSizePixels(24);
    title->Draw("SAME");
  
    TLatex *chtitle;
    chtitle  = new TLatex(-20.,50.,titlechname[ich]+"");
    chtitle->SetNDC();
    chtitle->SetTextAlign(12);
    chtitle->SetX(0.14);
    chtitle->SetY(0.74);
    chtitle->SetTextFont(42);
    chtitle->SetTextSize(0.05);
    chtitle->SetTextSizePixels(24);
    chtitle->Draw("SAME");

    pad[2]->cd();
    pad[2]->cd()->SetLogy();
    
    TH1D *hstyleLog = (TH1D *)hstyle->Clone();
    hstyleLog -> SetMaximum(10.0*hInput[ich].at(12)->GetMaximum());
    hstyleLog -> SetMinimum(0.8);
    hstyleLog -> Draw();
    
    AllMC[ich] -> Draw("HISTSAME"); 
    hData[ich] -> Draw("PSAME"); 
    titlePr->Draw("SAME");
    title->Draw("SAME");
    chtitle->Draw("SAME");

    pad[1]->cd();
    RatioFull ->Draw("HIST");
    gRatioFull->Draw("e2");
    RatioFull ->Draw("HISTSAME");

    pad[3]->cd();
    RatioFull ->Draw("HIST");
    gRatioFull->Draw("e2");
    RatioFull ->Draw("HISTSAME");

    TString dirfigname_pdf = "CombineResults/Figures_" + InpDir + Plots + FitDir + "/";
    // make a dir if it does not exist!!
    gSystem->mkdir(dirfigname_pdf, kTRUE);

    cPlots->SaveAs(dirfigname_pdf + "FullHisto_" + dirname[ich] + "_NormLog.pdf");

    // -----------------------------------------------------------------------------
    // Only Log Plots
    // -----------------------------------------------------------------------------

    TCanvas *cPlotsLog;//histos                                                                                                                                                                   
    cPlotsLog = new TCanvas("cPlotsLog"+dirname[ich] ,"Plots");
    cPlotsLog->Divide(1,2);
    TPad    *padLog[2];

    //Plot Pad
    padLog[0] = (TPad*)cPlotsLog->GetPad(1);
    padLog[0]->SetPad(0.01, 0.23, 0.99, 0.99);
    padLog[0]->SetTopMargin(0.1);
    padLog[0]->SetRightMargin(0.04);
    
    //Ratio Pad
    padLog[1] = (TPad*)cPlotsLog->GetPad(2);;
    padLog[1]->SetPad(0.01, 0.02, 0.99, 0.3);
    gStyle->SetGridWidth(1);
    gStyle->SetGridColor(14);
    padLog[1]->SetGridx();
    padLog[1]->SetGridy();
    padLog[1]->SetTopMargin(0.05);
    padLog[1]->SetBottomMargin(0.4);
    padLog[1]->SetRightMargin(0.04);

    padLog[0]->cd();
    padLog[0]->cd()->SetLogy();
    
    hstyleLog -> Draw();
    
    AllMC[ich] -> Draw("HISTSAME"); 
    hData[ich] -> Draw("PSAME"); 
    titlePr->Draw("SAME");
    title->Draw("SAME");
    chtitle->Draw("SAME");

    TLegend *legLog;
    legLog = new TLegend(0.70,0.60,0.94,0.87);
    legLog->SetFillColor(0);
    legLog->SetLineColor(0);
    legLog->SetLineWidth(0.0);
    legLog->SetTextFont(62);
    legLog->SetTextSize(0.03);
    legLog->SetNColumns(2);
  
    legLog->AddEntry(hData[ich],         "Data","PL");
    legLog->AddEntry(hInput[ich].at(11), "Z+Jets","F");
    legLog->AddEntry(hInput[ich].at(10), "VV","F");
    legLog->AddEntry(hInput[ich].at(9),  "Single t","F");
    legLog->AddEntry(hInput[ich].at(8),  "QCD","F");
    legLog->AddEntry(hInput[ich].at(7),  "W+Jets","F");
    legLog->AddEntry(hInput[ich].at(6),  "t#bar{t}+V","F");
    legLog->AddEntry(hInput[ich].at(5),  "t#bar{t}+H","F");
    legLog->AddEntry(hInput[ich].at(4),  "t#bar{t}+other","F");
    legLog->AddEntry(hInput[ich].at(3),  "t#bar{t}+LF","F");
    legLog->AddEntry(hInput[ich].at(2),  "t#bar{t}+cc","F");
    legLog->AddEntry(hInput[ich].at(1),  "t#bar{t}+bj","F");
    legLog->AddEntry(hInput[ich].at(0),  "t#bar{t}+bb","F");
    legLog->AddEntry(gRatioFull,         "Stat. Unc.","F");
    legLog->Draw("SAME");

    padLog[1]->cd();
    RatioFull ->Draw("HIST");
    gRatioFull->Draw("e2");
    RatioFull ->Draw("HISTSAME");

    cPlotsLog->SaveAs(dirfigname_pdf + "FullHisto_" + dirname[ich] + "_OnlyLog.pdf");
    
    // -----------------------------------------------------------------------------
    // -----------------------------------------------------------------------------
    // -----------------------------------------------------------------------------
    // Plots by Regions
    // -----------------------------------------------------------------------------
    // -----------------------------------------------------------------------------
    // -----------------------------------------------------------------------------
    int ireg = 0;
    for(int ican=0;ican<5;ican++){

      TString CanNum;
      CanNum.Form("%i",ican); 
      TCanvas *cPlots_reg;//histos
      cPlots_reg = new TCanvas("cPlots_reg" + CanNum + dirname[ich] ,"Plots By regions");
      cPlots_reg->Divide(2,2);
      
      for(int icr=1;icr<=4;icr++){

        //cPlots_reg->cd(icr);

	TPad *glpad_reg = (TPad*)cPlots_reg->cd(icr);
	glpad_reg->Divide(2,1);
	TPad *pad_reg[2];
	//Plot Pad
	pad_reg[0] = (TPad*)glpad_reg->GetPad(1);
	pad_reg[0]->SetPad(0.01, 0.23, 0.99, 0.99);
	pad_reg[0]->SetTopMargin(0.1);
	pad_reg[0]->SetRightMargin(0.04);	
	//Ratio Pad
	pad_reg[1] = (TPad*)glpad_reg->GetPad(2);
	pad_reg[1]->SetPad(0.01, 0.02, 0.99, 0.3);
	gStyle->SetGridWidth(1);
	gStyle->SetGridColor(14);
	pad_reg[1]->SetGridx();
	pad_reg[1]->SetGridy();
	pad_reg[1]->SetTopMargin(0.05);
	pad_reg[1]->SetBottomMargin(0.4);
	pad_reg[1]->SetRightMargin(0.04);

	pad_reg[0]->cd();
	pad_reg[0]->SetLogy();
	TH1D *hstyle_reg = (TH1D*)AllMC_reg[ich][ireg]->GetHistogram(); 
	hstyle_reg -> Reset();
	hstyle_reg -> SetMaximum(10.0*hData_reg[ich][ireg]->GetMaximum());
	hstyle_reg -> SetMinimum(0.7);
	hstyle_reg -> GetYaxis()->SetTitleOffset(0.9);
	hstyle_reg -> GetYaxis()->SetTitleSize(0.05);
	hstyle_reg -> GetYaxis()->SetLabelSize(0.05);
	hstyle_reg -> GetYaxis()->SetTitle("Events"); 

	pad_reg[0]->cd();
	hstyle_reg->Draw();
	AllMC_reg[ich][ireg] -> Draw("HISTSAME"); 
	hData_reg[ich][ireg] -> Draw("E1SAME"); 
	titlePr->Draw("SAME");
	title->Draw("SAME");
	chtitle->Draw("SAME");	

	TH1D *RatioFull_reg = HistoRatio (hData_reg[ich][ireg] , (TH1D*) AllMC_reg[ich][ireg]->GetStack()->Last());
	TGraphErrors *gRatioFull_reg = new TGraphErrors(RatioFull_reg);
	gRatioFull_reg->SetFillStyle(1001);
	gRatioFull_reg->SetFillColor(chatch);
	gRatioFull_reg->SetName("gRatioFull");
	
	pad_reg[1]->cd();
	RatioFull_reg->GetYaxis()->SetTitleOffset(0.25);	
	RatioFull_reg->Draw("HIST");
	gRatioFull_reg->Draw("e2");
	RatioFull_reg->Draw("HISTSAME");
	
	ireg++;
      } // for(ireg) 

      cPlots_reg->SaveAs(dirfigname_pdf + "RegionHisto_" + CanNum + "_" + dirname[ich] + "_NormLog.pdf");
    } // for(ican) 


    TCanvas *cPlotsI;
    cPlotsI = new TCanvas("cPlotsI"+dirname[ich] ,"Plots");
    cPlotsI->Divide(1,2);

    TPad    *padI[4];
    //Plot Pad
    padI[0] = (TPad*)cPlotsI->GetPad(1);
    padI[0]->SetPad(0.01, 0.23, 0.99, 0.99);
    padI[0]->SetTopMargin(0.1);
    padI[0]->SetRightMargin(0.04);
    
    //Ratio Pad
    padI[1] = (TPad*)cPlotsI->GetPad(2);
    padI[1]->SetPad(0.01, 0.02, 0.99, 0.3);
    gStyle->SetGridWidth(1);
    gStyle->SetGridColor(14);
    padI[1]->SetGridx();
    padI[1]->SetGridy();
    padI[1]->SetTopMargin(0.05);
    padI[1]->SetBottomMargin(0.4);
    padI[1]->SetRightMargin(0.04);

    TCanvas *cPlotsII;
    cPlotsII = new TCanvas("cPlotsII"+dirname[ich] ,"Plots");
    cPlotsII->Divide(1,2);
    //Plot Pad
    padI[2] = (TPad*)cPlotsII->GetPad(1);
    padI[2]->SetPad(0.01, 0.23, 0.99, 0.99);
    padI[2]->SetTopMargin(0.1);
    padI[2]->SetRightMargin(0.04);
    
    //Ratio Pad
    padI[3] = (TPad*)cPlotsII->GetPad(2);
    padI[3]->SetPad(0.01, 0.02, 0.99, 0.3);
    gStyle->SetGridWidth(1);
    gStyle->SetGridColor(14);
    padI[3]->SetGridx();
    padI[3]->SetGridy();
    padI[3]->SetTopMargin(0.05);
    padI[3]->SetBottomMargin(0.4);
    padI[3]->SetRightMargin(0.04);
    


    TH1D *hstyleI = new TH1D ("hstyleI","",
			      GlobalCSVJet_Data[1]->GetNbinsX(),
			      GlobalCSVJet_Data[1]->GetBinLowEdge (1),
			      GlobalCSVJet_Data[1]->GetBinLowEdge (GlobalCSVJet_Data[1]->GetNbinsX()+1));
    
    hstyleI -> SetMaximum(1.1*GlobalCSVJet_Data[1]->GetMaximum());
    hstyleI -> GetYaxis()->SetTitleOffset(0.8);
    hstyleI -> GetYaxis()->SetTitleSize(0.05);
    hstyleI -> GetYaxis()->SetLabelSize(0.05);
    hstyleI -> GetYaxis()->SetTitle("Events"); 
    
    GlobalCSVJet_Data[0] -> SetMarkerStyle(20); 
    GlobalCSVJet_Data[0] -> SetMarkerSize(0.4); 
    GlobalCSVJet_Data[0] -> SetLineWidth(1); 
    GlobalCSVJet_Data[0] -> SetTitle(""); 


    padI[0]->cd();
    padI[0]->cd()->SetLogy();
    
    hstyleI -> SetMaximum(100.0*GlobalCSVJet_Data[0]->GetMaximum());
    hstyleI -> SetMinimum(0.7);
    hstyleI -> Draw();

    AllMC_CSV1[ich] -> Draw("HISTSAME");

    GlobalCSVJet_Data[0] -> SetMarkerStyle(20); 
    GlobalCSVJet_Data[0] -> SetMarkerSize(0.6); 
    GlobalCSVJet_Data[0] -> SetLineWidth(1); 
    GlobalCSVJet_Data[0] -> SetTitle(""); 
    GlobalCSVJet_Data[0] -> Draw("SAME");

    titlePr->Draw("SAME");
    title->Draw("SAME");
    chtitle->Draw("SAME");	

    TLegend *legI;
    legI = new TLegend(0.70,0.64,0.93,0.87);
    legI->SetFillColor(0);
    legI->SetLineColor(0);
    legI->SetLineWidth(0.0);
    legI->SetTextFont(62);
    legI->SetTextSize(0.03);
    legI->SetNColumns(2);
  
    legI->AddEntry(hData[ich],         "Data","PL");
    legI->AddEntry(hInput[ich].at(11), "Z+Jets","F");
    legI->AddEntry(hInput[ich].at(10), "VV","F");
    legI->AddEntry(hInput[ich].at(9),  "Single t","F");
    legI->AddEntry(hInput[ich].at(8),  "QCD","F");
    legI->AddEntry(hInput[ich].at(7),  "W+Jets","F");
    legI->AddEntry(hInput[ich].at(6),  "t#bar{t}+V","F");
    legI->AddEntry(hInput[ich].at(5),  "t#bar{t}+H","F");
    legI->AddEntry(hInput[ich].at(4),  "t#bar{t}+other","F");
    legI->AddEntry(hInput[ich].at(3),  "t#bar{t}+LF","F");
    legI->AddEntry(hInput[ich].at(2),  "t#bar{t}+cc","F");
    legI->AddEntry(hInput[ich].at(1),  "t#bar{t}+bj","F");
    legI->AddEntry(hInput[ich].at(0),  "t#bar{t}+bb","F");
    legI->AddEntry(gRatioFull,         "Stat. Unc.","F");

    legI->Draw("SAME");

    TH1D *RatioFullJet1 = HistoRatio (GlobalCSVJet_Data[0] , (TH1D*) AllMC_CSV1[ich]->GetStack()->Last());
    TGraphErrors *gRatioFullJet1 = new TGraphErrors(RatioFullJet1);
    gRatioFullJet1->SetFillStyle(1001);
    gRatioFullJet1->SetFillColor(chatch);
    gRatioFullJet1->SetName("gRatioFullJet2");

    padI[1]->cd();
    RatioFullJet1 ->GetYaxis()->SetTitleOffset(0.25);
    RatioFullJet1 ->GetXaxis()->SetTitle("CSVv2");
    RatioFullJet1 ->Draw("HIST");
    gRatioFullJet1->Draw("e2");
    RatioFullJet1 ->Draw("HISTSAME");

    padI[2]->cd();
    padI[2]->cd()->SetLogy();
    // No Log
    TH1D *hstyleII = (TH1D *)hstyleI -> Clone("StyleII"); 
    hstyleII -> SetMaximum(100.0*GlobalCSVJet_Data[1]->GetMaximum());
    hstyleII -> SetMinimum(0.7);

    hstyleII -> Draw();
    AllMC_CSV2[ich] -> Draw("HISTSAME");

    GlobalCSVJet_Data[1] -> SetMarkerStyle(20); 
    GlobalCSVJet_Data[1] -> SetMarkerSize(0.5); 
    GlobalCSVJet_Data[1] -> SetLineWidth(1); 
    GlobalCSVJet_Data[1] -> SetTitle(""); 
    GlobalCSVJet_Data[1] -> Draw("SAME");

    titlePr->Draw("SAME");
    title->Draw("SAME");
    chtitle->Draw("SAME");	

    legI->Draw("SAME");

    TH1D *RatioFullJet2 = HistoRatio (GlobalCSVJet_Data[1] , (TH1D*) AllMC_CSV2[ich]->GetStack()->Last());
    TGraphErrors *gRatioFullJet2 = new TGraphErrors(RatioFullJet2);
    gRatioFullJet2->SetFillStyle(1001);
    gRatioFullJet2->SetFillColor(chatch);
    gRatioFullJet2->SetName("gRatioFullJet2");

    padI[3]->cd();
    RatioFullJet2 ->GetYaxis()->SetTitleOffset(0.25);
    RatioFullJet2 ->GetXaxis()->SetTitle("CSVv2");
    RatioFullJet2 ->Draw("HIST");
    gRatioFullJet2->Draw("e2");
    RatioFullJet2 ->Draw("HISTSAME");


    cPlotsI ->SaveAs(dirfigname_pdf + "CSVHistosJet1_" + dirname[ich] + "_Log.pdf");
    cPlotsII->SaveAs(dirfigname_pdf + "CSVHistosJet2_" + dirname[ich] + "_Log.pdf");

    // ttbb Shape

    


  }// for(ich)
  

}