void RRootHistRead_v1(){
	
	TFile *inputFile = new TFile("pPb_MBSpectra_Combine_-1_1.root");
	cout << "Is the file Open " << inputFile->IsOpen() << endl;

	//Copy the histogram
	TString hName = "Spectra_NtrkOffline0_inf";
	TH1D *h = (TH1D*)inputFile->Get(hName);

	cout << "Number of bins in the histogram: " << h->GetSize() << "\n";
	h->Draw();

	double nhBins = h->GetSize();
	for (int i=0; i < nhBins; i++) cout << h->GetBinWidth(i) << ", ";
	cout << endl;

	// Fit function
	double nParam = 2, maxValue = 5, minValue = 0;

	TF1 *fitFn = new TF1("fitFn", fitFunction, minValue, maxValue, nParam);

	// Set parameters for Fit
	fitFn->SetParameter(0, 0.008);

	// Get parameters from Fit
	double paramFromFit[2];
	fitFn->GetParameters(paramFromFit);

	// Generate data from fit
	double nBins = 27, pT[27], spectraFromFit[27]; // From the Xi 
	for (int i=0; i < nBins; i++){

		spectraFromFit[i] = paramFromFit[0]*exp(-i) + paramFromFit[1];
		cout << spectraFromFit[i] << ", ";
		pT[i] = i;
			
	}

	// Using Integral for the Fit
	h->Fit(fitFn, "I");

	TGraph *g = new TGraph(nBins, pT, spectraFromFit);
	g->SetMarkerStyle(7);
	g->SetMarkerSize(1.5);
	g->SetMarkerColor(kGreen);
	g->Draw("ALP");
	h->Draw("same");
	
}
Esempio n. 2
0
void plotter::draw_projection(TH1D* proj_, TH1D* compare_, TString file_name ){
  TH1D* proj = (TH1D*) proj_->Clone("proj");
  TH1D* compare = (TH1D*) compare_->Clone("compare");

  // check if distribution agrees with Matrix projection
  // since there are some numerical effects involved in the projection,
  // the warning is only printed if both distributions do not agree within 1%
  int nbins = proj->GetSize() - 2;
  for(int i=1; i<= nbins; i++){
    double nproj = proj->GetBinContent(i);
    double ncomp = compare->GetBinContent(i);
    if(nproj < ncomp * 0.99 && nproj > ncomp * 1.01){
      std::cout << "Projection and Distribution in " << file_name << " do not agree in bin " << i << std::endl;
    }
  }

  TCanvas *c= new TCanvas("Projection Gen","",600,600);
  gPad->SetLeftMargin(0.15);
  proj->SetLineColor(kAzure+7);
  proj->Draw("HIST");
  compare->SetLineColor(kRed);
  compare->SetLineStyle(7);
  compare->Draw("HIST SAME");
  TLegend *l=new TLegend(0.55,0.65,0.85,0.8);
  l->SetBorderSize(0);
  l->SetFillStyle(0);
  l->AddEntry(proj,"Projection from matrix","l");
  l->AddEntry(compare,"MC Gen","pl");
  l->Draw();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
Esempio n. 3
0
void plotter::draw_output_pseudo(TH1* output_, TH1D* pseudotruth_, TH1D* mctruth_, bool norm, TString file_name){

  TH1* output = (TH1*) output_->Clone("output");
  TH1D* pseudotruth = (TH1D*) pseudotruth_->Clone("pseudotruth");
  TH1D* mctruth = (TH1D*) mctruth_->Clone("mctruth");

  double ymax_temp = 0;
  if(pseudotruth->GetMaximum() > ymax_temp) ymax_temp = pseudotruth->GetMaximum();
  if(mctruth->GetMaximum() > ymax_temp) ymax_temp = mctruth->GetMaximum();
  if(output->GetMaximum() > ymax_temp) ymax_temp = output->GetMaximum();
  double ymax = 1.5 * ymax_temp;


  pseudotruth->SetTitle(" ");
  pseudotruth->GetYaxis()->SetRangeUser(0., ymax);
  pseudotruth->GetXaxis()->SetTitle("Leading-jet mass [GeV]");
  if(norm) pseudotruth->GetYaxis()->SetTitle("#frac{1}{#sigma} #frac{d#sigma}{dm_{jet}} [#frac{1}{GeV}]");
  else     pseudotruth->GetYaxis()->SetTitle("events");
  pseudotruth->GetYaxis()->SetTitleOffset(1.1);
  pseudotruth->GetXaxis()->SetTitleOffset(0.9);
  pseudotruth->GetYaxis()->SetTitleSize(0.05);
  pseudotruth->GetXaxis()->SetTitleSize(0.05);
  pseudotruth->GetYaxis()->SetNdivisions(505);

  pseudotruth->SetLineWidth(4);
  pseudotruth->SetLineColor(kRed);
  mctruth->SetLineWidth(3);
  mctruth->SetLineStyle(2);
  mctruth->SetLineColor(kBlue);

  output->SetLineColor(kBlack);
  output->SetMarkerColor(kBlack);
  output->SetMarkerStyle(8);
  output->SetMarkerSize(1);

  TCanvas *c= new TCanvas("Particle Level","",600,600);
  gPad->SetLeftMargin(0.15);
  TGaxis::SetMaxDigits(3);
  pseudotruth->Draw("HIST SAME");
  mctruth->Draw("HIST SAME");
  output->Draw("E1 SAME");
  TLegend *l;
  if(mctruth->GetSize() > 20) l=new TLegend(0.2,0.6,0.4,0.85);
  else                       l=new TLegend(0.55,0.6,0.85,0.85);
  l->SetBorderSize(0);
  l->SetFillStyle(0);
  l->AddEntry(output,"pseudo data","pl");
  l->AddEntry(pseudotruth,"pseudo data truth","pl");
  l->AddEntry(mctruth,"MC truth","pl");
  l->SetTextSize(0.04);

  l->Draw();
  gPad->RedrawAxis();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
Esempio n. 4
0
void plotter::draw_output_smear(std::vector<TH1*> output_, TH1D* truth_, TString file_name){
  // std::vector<double> sys = get_sys_errors();
  // TH1* output_sys = add_error_bar(output, sys);

  std::vector<TH1*> outputs;
  for(int i=0; i<output_.size(); i++){
    TH1* hist = (TH1*) output_[i]->Clone();
    outputs.push_back(hist);
  }
  TH1D* truth = (TH1D*) truth_->Clone("truth");

  TCanvas *c = new TCanvas("c","",600,600);
  double ymax;
  gPad->SetLeftMargin(0.15);

  if(truth->GetMaximum() > outputs[0]->GetMaximum()) ymax = 1.5 * truth->GetMaximum();
  else ymax = 1.5 * outputs[0]->GetMaximum();
  TGaxis::SetMaxDigits(3);
  for(auto output: outputs){
    output->SetTitle(" ");
    output->GetYaxis()->SetRangeUser(0., ymax);
    output->GetXaxis()->SetTitle("Leading-jet mass [GeV]");
    output->GetYaxis()->SetTitle("events");
    output->GetYaxis()->SetTitleOffset(1.1);
    output->GetXaxis()->SetTitleOffset(0.9);
    output->GetYaxis()->SetTitleSize(0.05);
    output->GetXaxis()->SetTitleSize(0.05);
    output->GetYaxis()->SetNdivisions(505);
    output->SetLineColor(kBlack);
    output->SetMarkerColor(kBlack);
    output->SetMarkerStyle(8);
    output->SetMarkerSize(1);
    output->Draw("E1 SAME");
  }
  gStyle->SetEndErrorSize(5);
  truth->SetLineWidth(3);
  truth->SetLineColor(kRed);
  truth->SetLineStyle(2);
  truth->Draw("HIST SAME");
  TLegend *l;
  if(truth->GetSize() > 20) l=new TLegend(0.2,0.6,0.4,0.85);
  else                       l=new TLegend(0.5,0.6,0.85,0.85);
  l->SetBorderSize(0);
  l->SetFillStyle(0);
  l->AddEntry(outputs[0],"data unfolded","pl");
  l->AddEntry(truth,"MC particle level","pl");
  l->SetTextSize(0.04);
  l->Draw();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
Esempio n. 5
0
void plotter::draw_output(TH1* output_, TH1D* truth_, bool norm, TString file_name){
  // std::vector<double> sys = get_sys_errors();
  // TH1* output_sys = add_error_bar(output, sys);

  TH1* output = (TH1*) output_->Clone("output");
  TH1D* truth = (TH1D*) truth_->Clone("truth");

  TCanvas *c = new TCanvas("c","",600,600);
  double ymax;
  gPad->SetLeftMargin(0.15);

  if(truth->GetMaximum() > output->GetMaximum()) ymax = 1.5 * truth->GetMaximum();
  else ymax = 1.5 * output->GetMaximum();
  TGaxis::SetMaxDigits(3);
  output->SetTitle(" ");
  output->GetYaxis()->SetRangeUser(0., ymax);
  output->GetXaxis()->SetTitle("Leading-jet mass [GeV]");
  if(norm) output->GetYaxis()->SetTitle("#frac{1}{#sigma} #frac{d#sigma}{dm_{jet}} [#frac{1}{GeV}]");
  else output->GetYaxis()->SetTitle("events");
  output->GetYaxis()->SetTitleOffset(1.1);
  output->GetXaxis()->SetTitleOffset(0.9);
  output->GetYaxis()->SetTitleSize(0.05);
  output->GetXaxis()->SetTitleSize(0.05);
  output->GetYaxis()->SetNdivisions(505);
  output->SetLineColor(kBlack);
  output->SetMarkerColor(kBlack);
  output->SetMarkerStyle(8);
  output->SetMarkerSize(1);
  output->Draw("E1 SAME");
  gStyle->SetEndErrorSize(5);
  truth->SetLineWidth(3);
  truth->SetLineColor(kRed);
  truth->SetLineStyle(2);
  truth->Draw("HIST SAME");
  TLegend *l;
  if(truth->GetSize() > 20) l=new TLegend(0.2,0.6,0.4,0.85);
  else                       l=new TLegend(0.5,0.6,0.85,0.85);
  l->SetBorderSize(0);
  l->SetFillStyle(0);
  l->AddEntry(output,"data unfolded","pl");
  l->AddEntry(truth,"MC particle level","pl");
  l->SetTextSize(0.04);
  l->Draw();
  c->SaveAs(directory + file_name + ".pdf");
  delete c;
}
double CalcChiSqr(TH1D* hist, Double_t coeff, Double_t expo, Int_t xMin, Int_t xMax)
{
  {
    TH1D* myHist = hist->Clone();
    int bins = myHist->GetSize()-2;
    double chiSqr = 0;
    for(int i = xMin+1; i < xMax+1; i++)
      {
	double x = myHist->GetBinCenter(i);
	double o = myHist->GetBinContent(i);
	double e = coeff*(TMath::Power(x,expo));
	//cout << x << "\t" << o << "\t" << e;
	if(o != 0)
	  chiSqr += ((o-e)*(o-e))/o;
	//cout << "\tchiSqr: " << chiSqr << endl;
      }
    return chiSqr/2;
    
  }
  
  
}
Esempio n. 7
0
void Find_JPsiPt()
{
  double pt_bound[200] = {0.0};
  double PT[200], DelPT[200];
  double YPT[200], DelYPT[200];
  
  int Nptbin = 120;
  //int Nptbin = 70;
  
  double step =0.1;
  
  cout<<" pT Bins "<<endl;
  for (Int_t ih = 0; ih < Nptbin; ih++) {
    pt_bound[ih] = 0 + step*ih;
    pt_bound[ih+1] = 0 + step*(ih+1);
    
    PT[ih] = (pt_bound[ih] + pt_bound[ih+1])/2.0;
    DelPT[ih] = (pt_bound[ih+1] - pt_bound[ih])/2.0;
    
    cout<<PT[ih]<<"    "<<DelPT[ih]<<endl;

  }
  

  char namePt[500];
  
  //TFile *fpT = new TFile("Psi2s5M_pythia.root");
  //TH2D *JPt_BPt = (TH2D*)fpT->Get("Psi2SVsJPsi_Pt");
  //TH2D *JPt_BPt = (TH2D*)fpT->Get("Psi2SVsChic0_Pt");

  TFile *fpT = new TFile("Psi2S1M_pythia.root");
  //TH2D *JPt_BPt = (TH2D*)fpT->Get("Psi2SVsChic1_Pt");
  TH2D *JPt_BPt = (TH2D*)fpT->Get("Psi2SVsChic2_Pt");
  
  new TCanvas;
  JPt_BPt->Draw("colz");

  TH1D *service = (TH1D*)JPt_BPt->ProjectionX("service");
  TAxis *xaxis = service->GetXaxis();

  for(int i=0;i<service->GetSize();i++)
    {
      Double_t binCenter = xaxis->GetBinCenter(i);
      cout<<binCenter<<endl;

    }

  
  //return;

  //service->Draw();
  cout<<" service  "<<service<<endl;

  int pt_bin_bound[200];

  TH1D *ProfY_BPt[200];

  
  for (Int_t ih = 0; ih < Nptbin; ih++) {
  
    pt_bin_bound[ih] = service->FindBin(pt_bound[ih]);
    pt_bin_bound[ih+1] = service->FindBin(pt_bound[ih+1]);
    
    sprintf(namePt,"BPt_%d",ih);
    
    //ProfY_BPt[ih] = (TH1D*)JPt_BPt->ProjectionY(namePt, pt_bin_bound[ih], pt_bin_bound[ih+1]-1,"e");
    
    ProfY_BPt[ih] = (TH1D*)JPt_BPt->ProjectionY(namePt, pt_bin_bound[ih], pt_bin_bound[ih+1],"e");
    YPT[ih] = ProfY_BPt[ih]->GetMean();
    DelYPT[ih] = ProfY_BPt[ih]->GetRMS();
    
    cout<< YPT[ih] <<" /pm "<<  DelYPT[ih]<< endl<<endl;

  }
  
  TGraphErrors *gr_BpTvsJpT = new TGraphErrors(Nptbin, PT, YPT, DelPT, DelYPT);
  TF1 *func_BpTvsJpT = new TF1("pol1", pol1, 0, 20, 2); 
  func_BpTvsJpT->SetLineColor(2);
  gr_BpTvsJpT->Fit("pol1","","",0,20);
  gr_BpTvsJpT->GetXaxis()->SetRangeUser(0,20);
  gr_BpTvsJpT->GetXaxis()->SetTitle("J/#psi p_{T}");
  gr_BpTvsJpT->GetYaxis()->SetTitle("#psi(2S) p_{T}");
  new TCanvas;
  gr_BpTvsJpT->Draw("ap");
  func_BpTvsJpT->Draw("same");
}
Esempio n. 8
0
void comparisonJetMCData(string plot,int rebin){
  string tmp;

  string dir="/gpfs/cms/data/2011/Observables/Approval/";
	
  if (isAngularAnalysis){
    mcfile=dir+"MC_zjets"+version;
    back_w=dir+"MC_wjets"+version;
    back_ttbar=dir+"MC_ttbar"+version;
    WW=dir+"MC_diW"+version;
    ZZ=dir+"MC_siZ"+version;
    WZ=dir+"MC_diWZ"+version;
    datafile=dir+"DATA"+version;
    mcfiletau=dir+"MC_zjetstau"+version;
  }
  // List of files

  TFile *dataf = TFile::Open(datafile.c_str()); //data file
  TFile *mcf = TFile::Open(mcfile.c_str()); //MC file
  TFile *mcftau = TFile::Open(mcfiletau.c_str()); //MC file
  TFile *ttbarf = TFile::Open(back_ttbar.c_str()); //MC background file
  TFile *wf = TFile::Open(back_w.c_str());


  TFile *qcd23emf = TFile::Open(qcd23em.c_str());
  TFile *qcd38emf = TFile::Open(qcd38em.c_str());
  TFile *qcd817emf = TFile::Open(qcd817em.c_str());

  TFile *qcd23bcf = TFile::Open(qcd23bc.c_str());
  TFile *qcd38bcf = TFile::Open(qcd38bc.c_str());
  TFile *qcd817bcf = TFile::Open(qcd817bc.c_str());

  TFile *WZf = TFile::Open(WZ.c_str());
  TFile *ZZf = TFile::Open(ZZ.c_str());
  TFile *WWf = TFile::Open(WW.c_str());


  // Canvas
  if (CanvPlot) delete CanvPlot;
  CanvPlot = new TCanvas("CanvPlot","CanvPlot",0,0,800,600);

  // Getting, defining ...
  dataf->cd("validationJEC");
  if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");
	
  TObject * obj;
  gDirectory->GetObject(plot.c_str(),obj);

  TH1 *data;
  TH2F *data2; 
  TH1D *data3; 

  THStack *hs = new THStack("hs","Total MC");


  int flag=-1;
  if ((data = dynamic_cast<TH1F *>(obj)) ){
    flag=1;
    gROOT->Reset();
    gROOT->ForceStyle();
    gStyle->SetPadRightMargin(0.03);
    gPad->SetLogy(1);
    gPad->Modified();
    gPad->Update();
  }
  if ((data2 = dynamic_cast<TH2F *>(obj)) ){
    flag=2;
    gStyle->SetPalette(1);
    gStyle->SetPadRightMargin(0.15);
    gPad->Modified();
  }



  //===================
  // Dirty jobs :)
  if (flag==1){
    CanvPlot->cd();
    TPad *pad1 = new TPad("pad1","pad1",0.01,0.33,0.99,0.99);
    pad1->Draw();
    pad1->cd();
    pad1->SetTopMargin(0.1);
    pad1->SetBottomMargin(0.01);
    pad1->SetRightMargin(0.1);
    pad1->SetFillStyle(0);
    pad1->SetLogy(1);
    TString str=data->GetTitle();
    if (str.Contains("jet") && !str.Contains("zMass") && !str.Contains("Num") && !str.Contains("Eta") && !str.Contains("Phi") && !str.Contains("eld") && !str.Contains("meanPtZVsNjet")) {
      if (!isAngularAnalysis) rebin=1;
    }

    //======================
    // DATA
    Double_t dataint = data->Integral();
    data->SetLineColor(kBlack);
    data->Rebin(rebin);
    if(str.Contains("nJetVtx")) data->GetXaxis()->SetRangeUser(0,10);	
    if(str.Contains("zMass")) data->GetXaxis()->SetRangeUser(70,110);	
    data->SetMinimum(1.);
    data->Sumw2();

    //Canvas style copied from plotsHistsRatio.C
    data->SetLabelSize(0.0);
    data->GetXaxis()->SetTitleSize(0.00);
    data->GetYaxis()->SetLabelSize(0.07);
    data->GetYaxis()->SetTitleSize(0.08);
    data->GetYaxis()->SetTitleOffset(0.76);
    data->SetTitle("");
    gStyle->SetOptStat(0);

    data->GetYaxis()->SetLabelSize(0.06);
    data->GetYaxis()->SetTitleSize(0.06);
    data->GetYaxis()->SetTitleOffset(0.8);

    data->Draw("E1");


    TLegend* legend = new TLegend(0.725,0.27,0.85,0.72);
    legend->SetFillColor(0);
    legend->SetFillStyle(0);
    legend->SetBorderSize(0);
    legend->SetTextSize(0.060);
    legend->AddEntry(data,"data","p");

    // hack to calculate some yields in restricted regions...
    int num1=0, num2=0, num3=0, num4=0, num5=0;
    if(str.Contains("invMass") && !str.Contains("PF")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z ci sono tra 60 e 120 GeV
	if(j>10&&j<=50) num2 += data->GetBinContent(j); // ... tra 70 e 110
	if(j>15&&j<=45) num3 += data->GetBinContent(j); // ... tra 75 e 105
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the invmass histo\n";
      printf("Number of Z in 60-120 %i --- 70-110 %i --- 75-105 %i \n",num1,num2,num3);
      cout << "\n";
    }
    if(str.Contains("zYieldVsjets") && !str.Contains("Vtx")){
      for(int j=1;j<=data->GetNbinsX();j++){
	num1 += data->GetBinContent(j); 		//conto quante Z
	if(j>1) num2 += data->GetBinContent(j); // ... +1,2,3,4... jets
	if(j>2) num3 += data->GetBinContent(j); // ... +2,3,4... jets
	if(j>3) num4 += data->GetBinContent(j); // ..    if(str=="jet_pT"){
	if(j>4) num5 += data->GetBinContent(j); // ... +4... jets
      }
      cout << "\n";
      cout << data->GetNbinsX() <<" Number of bins of the zYieldVsjets histo\n";
      printf("Number of Z+n jet %i --- >1 %i --- >2 %i --- >3 %i --- >4 %i \n",num1,num2,num3,num4,num5);
      cout << "\n";
    }    

    //======================
    // Z + jets signal
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    TH1F* mc;
    gDirectory->GetObject(plot.c_str(),mc);
    TH1F * hsum;
    if(mc){
      hsum =  (TH1F*) mc->Clone();
      hsum->SetTitle("hsum");
      hsum->SetName("hsum");
      hsum->Reset();

      Double_t mcint = mc->Integral();
      mc->SetFillColor(kRed);
      mc->Sumw2();
      if(lumiweights==0) mc->Scale(dataint/mcint);
		
      // Blocco da propagare negli altri MC
      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) mc->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else mc->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) mc->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else mc->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) mc->Scale(zjetsScale);
      }

      // fin qui
      if(lumiweights==1) mc->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      mc->Rebin(rebin);
      if(lumiweights==0) mc->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(mc);
      legend->AddEntry(mc,"Z+jets","f");
    }

    //======================
    // ttbar
    ttbarf->cd("validationJEC");
    if (isMu) ttbarf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ttbarf->cd("validationJEC/");
      if (isMu) ttbarf->cd("validationJECmu/");
    }

    TH1F* ttbar;
    gDirectory->GetObject(plot.c_str(),ttbar);
	
    if(ttbar){
      ttbar->SetFillColor(kBlue);
      ttbar->Sumw2();

      if(ttNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ttbar->Scale( dataLumi2011pix / (ttNumEvents / ttbarXsect));
	    else ttbar->Scale( dataLumi2011 / (ttNumEvents / ttbarXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Apix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011A / (ttNumEvents / ttbarXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ttbar->Scale( dataLumi2011Bpix / (ttNumEvents / ttbarXsect));
	      else ttbar->Scale( dataLumi2011B / (ttNumEvents / ttbarXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ttbar->Scale(ttwemean);
      }
      // fin qui
		
      if(lumiweights==1) ttbar->Scale(1./ttwemean);  // perche' i Weights non fanno 1...
      ttbar->Rebin(rebin);
      if(lumiweights==0) ttbar->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ttbar);
      if(lumiweights==1)legend->AddEntry(ttbar,"ttbar","f");

      //////////
      //Storing the bckgrounds!
      //////////
      cout<<str<<endl;
      if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ttbar,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ttbar,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ttbar,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ttbar,"jet_pT4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ttbar,"jet_Multiplicity");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ttbar,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ttbar,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ttbar,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ttbar,"jet_eta4");
      if(str=="HT") evaluateAndFillBackgrounds(ttbar,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ttbar,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ttbar,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ttbar,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ttbar,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ttbar,"PhiStar");
      }
    }

    //======================
    // w+jets
    wf->cd("validationJEC");
    if (isMu) wf->cd("validationJECmu/");
    if (isAngularAnalysis) {
      wf->cd("validationJEC/");
      if (isMu) wf->cd("validationJECmu/");      
    }

    TH1F* w;
    gDirectory->GetObject(plot.c_str(),w);
    if(w){

      w->SetFillColor(kViolet+2);
      w->Sumw2();

      if(wNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) w->Scale( dataLumi2011pix / (wNumEvents / wjetsXsect));
	    else w->Scale( dataLumi2011 / (wNumEvents / wjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Apix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011A / (wNumEvents / wjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) w->Scale( dataLumi2011Bpix / (wNumEvents / wjetsXsect));
	      else w->Scale( dataLumi2011B / (wNumEvents / wjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) w->Scale(wwemean);
      }
      // fin qui
		
      if(lumiweights==1) w->Scale(1./wwemean);  // perche' i Weights non fanno 1...
      w->Rebin(rebin);
      if(lumiweights==0) w->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(w);
      if(lumiweights==1)legend->AddEntry(w,"W+jets","f");
    }

    //======================
    // wz+jets
    WZf->cd("validationJEC");
    if (isMu) WZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WZf->cd("validationJEC/");
      if (isMu) WZf->cd("validationJECmu/");
    }

    TH1F* wz;
    gDirectory->GetObject(plot.c_str(),wz);
    if(wz){
      wz->SetFillColor(kYellow+2);
      wz->Sumw2();

      if(wzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) wz->Scale( dataLumi2011pix / (wzEvents / WZXsect));
	    else wz->Scale( dataLumi2011 / (wzEvents / WZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Apix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011A / (wzEvents / WZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) wz->Scale( dataLumi2011Bpix / (wzEvents / WZXsect));
	      else wz->Scale( dataLumi2011B / (wzEvents / WZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) wz->Scale(wzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) wz->Scale(1./wzwemean);  // perche' i Weights non fanno 1...
      wz->Rebin(rebin);
      if(lumiweights==0) wz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(wz);
      legend->AddEntry(wz,"WZ+jets","f");


      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(wz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(wz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(wz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(wz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(wz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(wz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(wz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(wz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(wz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(wz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(wz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(wz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(wz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(wz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(wz,"PhiStar");
     }
    }
    
		
    //======================
    // zz+jets
    ZZf->cd("validationJEC");
    if (isMu) ZZf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      ZZf->cd("validationJEC/");
      if (isMu) ZZf->cd("validationJECmu/");
    }

    TH1F* zz;
    gDirectory->GetObject(plot.c_str(),zz);
    if(zz){
      zz->SetFillColor(kOrange+2);
      zz->Sumw2();

      if(zzEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) zz->Scale( dataLumi2011pix / (zzEvents / ZZXsect));
	    else zz->Scale( dataLumi2011 / (zzEvents / ZZXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Apix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011A / (zzEvents / ZZXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) zz->Scale( dataLumi2011Bpix / (zzEvents / ZZXsect));
	      else zz->Scale( dataLumi2011B / (zzEvents / ZZXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) zz->Scale(zzjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) zz->Scale(1./zzwemean);  // perche' i Weights non fanno 1...
      zz->Rebin(rebin);
      if(lumiweights==0) zz->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(zz);
      legend->AddEntry(zz,"ZZ+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(zz,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(zz,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(zz,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(zz,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(zz,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(zz,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(zz,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(zz,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(zz,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(zz,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(zz,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(zz,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(zz,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(zz,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(zz,"PhiStar");
     }  
    }
    
    //======================
    // ww+jets
    WWf->cd("validationJEC");
    if (isMu) WWf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      WWf->cd("validationJEC/");
      if (isMu) WWf->cd("validationJECmu/");
    }

    TH1F* ww;
    gDirectory->GetObject(plot.c_str(),ww);
    if(ww){
      ww->SetFillColor(kBlack);
      ww->Sumw2();

      if(wwEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) ww->Scale( dataLumi2011pix / (wwEvents / WWXsect));
	    else ww->Scale( dataLumi2011 / (wwEvents / WWXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Apix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011A / (wwEvents / WWXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) ww->Scale( dataLumi2011Bpix / (wwEvents / WWXsect));
	      else ww->Scale( dataLumi2011B / (wwEvents / WWXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) ww->Scale(wwjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) ww->Scale(1./wwwemean);  // perche' i Weights non fanno 1...
      ww->Rebin(rebin);
      if(lumiweights==0) ww->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      hsum->Add(ww);
      legend->AddEntry(ww,"WW+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(ww,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(ww,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(ww,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(ww,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(ww,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(ww,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(ww,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(ww,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(ww,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(ww,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(ww,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(ww,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(ww,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(ww,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(ww,"PhiStar");
     }
    }

    /// Tau 

   //======================

    mcftau->cd("validationJEC");
    if (isMu) mcftau->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcftau->cd("validationJEC/");
      if (isMu) mcftau->cd("validationJECmu/");
    }

    TH1F* tau;
    gDirectory->GetObject(plot.c_str(),tau);
    if(tau){
      tau->SetFillColor(kGreen);
      tau->Sumw2();

      if(zNumEvents>0.){
	if(lumiweights==1) {
	  if (WholeStat){
	    if (lumiPixel) tau->Scale( dataLumi2011pix / (zNumEvents / zjetsXsect));
	    else tau->Scale( dataLumi2011 / (zNumEvents / zjetsXsect));
	  }
	  else{
	    if (RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Apix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011A / (zNumEvents / zjetsXsect));
	    }
	    if (!RunA){
	      if (lumiPixel) tau->Scale( dataLumi2011Bpix / (zNumEvents / zjetsXsect));
	      else tau->Scale( dataLumi2011B / (zNumEvents / zjetsXsect));
	    }
	  }
	}
      }
      else {
	if(lumiweights==1) tau->Scale(zjetsScale);
      }
      // fin qui
		
      if(lumiweights==1) tau->Scale(1./zwemean);  // perche' i Weights non fanno 1...
      tau->Rebin(rebin);
      if(lumiweights==0) tau->Draw("HISTO SAMES");
      hsum->Rebin(rebin);
      tau->Scale(1./1000.); //aaaaaaa
      hsum->Add(tau);
      legend->AddEntry(tau,"#tau#tau+jets","f");

      //////////
      //Storing the bckgrounds!
      //////////
     if (isAngularAnalysis){
      if(str=="jet_pT") evaluateAndFillBackgrounds(tau,"jet_pT");
      if(str=="jet_pT2") evaluateAndFillBackgrounds(tau,"jet_pT2");
      if(str=="jet_pT3") evaluateAndFillBackgrounds(tau,"jet_pT3");
      if(str=="jet_pT4") evaluateAndFillBackgrounds(tau,"jet_pT4");
      if(str=="jet_eta") evaluateAndFillBackgrounds(tau,"jet_eta");
      if(str=="jet_eta2") evaluateAndFillBackgrounds(tau,"jet_eta2");
      if(str=="jet_eta3") evaluateAndFillBackgrounds(tau,"jet_eta3");
      if(str=="jet_eta4") evaluateAndFillBackgrounds(tau,"jet_eta4");
      if(str=="Jet_multi") evaluateAndFillBackgrounds(tau,"jet_Multiplicity");
      if(str=="HT") evaluateAndFillBackgrounds(tau,"HT");
      if(str=="HT_1j") evaluateAndFillBackgrounds(tau,"HT1");
      if(str=="HT_2j") evaluateAndFillBackgrounds(tau,"HT2");
      if(str=="HT_3j") evaluateAndFillBackgrounds(tau,"HT3");
      if(str=="HT_4j") evaluateAndFillBackgrounds(tau,"HT4");
      if(str=="Phi_star") evaluateAndFillBackgrounds(tau,"PhiStar");
     }
    }


    /////////
    // Print the bkg contributions
    ////////

    for(int j=0;j<bckg_leadingJetPt.size();j++){      
      cout<<bckg_leadingJetPt[j]<<endl;
    }	

    //======================
    // QCD EM enriched
    qcd23emf->cd("validationJEC");
    TH1F* qcd23emp;
    gDirectory->GetObject(plot.c_str(),qcd23emp);

    if(qcd23emp){
      TH1D * qcdTotEM =  (TH1D*) qcd23emp->Clone(); 
      qcdTotEM->SetTitle("qcd em");
      qcdTotEM->SetName("qcd em");
      qcdTotEM->Reset();
      qcdTotEM->Rebin(rebin);

      qcd38emf->cd("validationJEC");
      TH1F* qcd38emp;
      gDirectory->GetObject(plot.c_str(),qcd38emp);


      qcd817emf->cd("validationJEC");
      TH1F* qcd817emp;
      gDirectory->GetObject(plot.c_str(),qcd817emp);

      qcd23emp->Rebin(rebin);
      qcd23emp->Sumw2();
      qcd23emp->Scale(qcd23emScale); 
      qcd38emp->Rebin(rebin);
      qcd38emp->Sumw2();
      qcd38emp->Scale(qcd38emScale); 
      qcd817emp->Rebin(rebin);
      qcd817emp->Sumw2();
      qcd817emp->Scale(qcd817emScale); 

      qcdTotEM->SetFillColor(kOrange+1);
      qcdTotEM->Add(qcd23emp);
      qcdTotEM->Add(qcd38emp);
      qcdTotEM->Add(qcd817emp);

      hsum->Add(qcdTotEM);

      //if(lumiweights==1)legend->AddEntry(qcdTotEM,"QCD em","f");
    }

    //======================
    // QCD bc
    qcd23bcf->cd("validationJEC");
    TH1F* qcd23bcp;
    TH1D * qcdTotBC;
    bool  qcdbcempty=true;
    gDirectory->GetObject(plot.c_str(),qcd23bcp);

    if(qcd23bcp){
      qcdTotBC =  (TH1D*) qcd23bcp->Clone(); 
      qcdTotBC->SetTitle("qcd bc");
      qcdTotBC->SetName("qcd bc");
      qcdTotBC->Reset();
      qcdTotBC->Rebin(rebin);

      qcd38bcf->cd("validationJEC");
      TH1F* qcd38bcp;
      gDirectory->GetObject(plot.c_str(),qcd38bcp);

      qcd817bcf->cd("validationJEC");
      TH1F* qcd817bcp;
      gDirectory->GetObject(plot.c_str(),qcd817bcp);

      qcd23bcp->Rebin(rebin);
      qcd23bcp->Sumw2();
      qcd23bcp->Scale(qcd23bcScale); 
      qcd38bcp->Rebin(rebin);
      qcd38bcp->Sumw2();
      qcd38bcp->Scale(qcd38bcScale); 
      qcd817bcp->Rebin(rebin);
      qcd817bcp->Sumw2();
      qcd817bcp->Scale(qcd817bcScale); 

      qcdTotBC->SetFillColor(kGreen+2);
      qcdTotBC->Add(qcd23bcp);
      qcdTotBC->Add(qcd38bcp);
      qcdTotBC->Add(qcd817bcp);

      hsum->Add(qcdTotBC);
      if (qcdTotBC->GetEntries()>0) qcdbcempty=false; 

      //if(lumiweights==1)legend->AddEntry(qcdTotBC,"QCD bc","f");
    }

    //======================
    // Add here other backgrounds


    //======================
    // Stacked Histogram
    //if(qcd23em) 	hs->Add(qcdTotEM);
    if(!qcdbcempty) 	hs->Add(qcdTotBC);
    if(w)  	        hs->Add(w);
    if (ww)         hs->Add(ww);
    if(tau)		hs->Add(tau); //Z+Jets
    if (zz)         hs->Add(zz);
    if (wz)         hs->Add(wz);
    if (ttbar)	hs->Add(ttbar);
    if(mc)		hs->Add(mc); //Z+Jets

    // per avere le statistiche
    if(lumiweights==1) hsum->Draw("HISTO SAME");


    //======================
    // Setting the stats
    //pad1->Update(); // altrimenti non becchi la stat
    
    //TPaveStats *r2;
    //if(lumiweights==0) r2 = (TPaveStats*)mc->FindObject("stats");
    //if(lumiweights==1) r2 = (TPaveStats*)hsum->FindObject("stats");
    //r2->SetY1NDC(0.875);     //Uncomment if you wonna add your statistics in the top right corner
    //r2->SetY2NDC(0.75); 
    //r2->SetTextColor(kRed);
		
    if(lumiweights==1) hs->Draw("HISTO SAME");
    gPad->RedrawAxis();
    data->Draw("E1 SAME");
    //r2->Draw(); //here to reactivate the stats
    legend->Draw();
    TLegend* lumi = new TLegend(0.45,0.3,0.75,0.2);
    lumi->SetFillColor(0);
    lumi->SetFillStyle(0);
    lumi->SetBorderSize(0);
    //lumi->AddEntry((TObject*)0,"#int L dt =4.9 1/fb","");
    lumi->Draw();
    string channel;
    if (isMu) channel="Z#rightarrow#mu#mu";
    if (!isMu) channel="Z#rightarrow ee";
    TLatex *latexLabel=CMSPrel(4.890,channel,0.55,0.85); // make fancy label
    latexLabel->Draw("same");

    CanvPlot->Update();

	


    //===============//
    // RATIO DATA MC //
    //===============//
    CanvPlot->cd();
    TPad *pad2 = new TPad("pad2","pad2",0.01,0.01,0.99,0.32);
    pad2->Draw();
    pad2->cd();
    pad2->SetTopMargin(0.01);
    pad2->SetBottomMargin(0.3);
    pad2->SetRightMargin(0.1);
    pad2->SetFillStyle(0);

    TH1D * ratio =  (TH1D*) data->Clone();
    ratio->SetTitle("");
    ratio->SetName("ratio");
    ratio->Reset();

    ratio->Sumw2();
    //data->Sumw2();
    hsum->Sumw2(); // FIXME controlla che sia corretto questo... 
    ratio->SetMarkerSize(.5);
    ratio->SetLineColor(kBlack);
    ratio->SetMarkerColor(kBlack);
    //gStyle->SetOptStat("m");
    TH1F* sumMC;

    hs->Draw("nostack"); 
 
   sumMC=(TH1F*) hs->GetHistogram();
    cout<<sumMC->GetEntries()<<endl;
    ratio->Divide(data,hsum,1.,1.);
    ratio->GetYaxis()->SetRangeUser(0.5,1.5);
    ratio->SetMarkerSize(0.8);
    //pad2->SetTopMargin(1);

   //Canvas style copied from plotsHistsRatio.C
    ratio->GetYaxis()->SetNdivisions(5);
    ratio->GetXaxis()->SetTitleSize(0.14);
    ratio->GetXaxis()->SetLabelSize(0.14);
    ratio->GetYaxis()->SetLabelSize(0.11);
    ratio->GetYaxis()->SetTitleSize(0.11);
    ratio->GetYaxis()->SetTitleOffset(0.43);
    ratio->GetYaxis()->SetTitle("ratio data/MC");   

    ratio->Draw("E1");
		
    TLine *OLine = new TLine(ratio->GetXaxis()->GetXmin(),1.,ratio->GetXaxis()->GetXmax(),1.);
    OLine->SetLineColor(kBlack);
    OLine->SetLineStyle(2);
    OLine->Draw();
 
    TLegend* label = new TLegend(0.60,0.9,0.50,0.95);
    label->SetFillColor(0);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    //horrible mess
    double binContent = 0;
    double binSum = 0;
    double weightSum = 0;
    double binError = 1;
    double totalbins = ratio->GetSize() -2;
    for(unsigned int bin=1;bin<=totalbins;bin++){
      binContent = ratio->GetBinContent(bin);
      binError = ratio->GetBinError(bin);
      if(binError!=0){
	binSum += binContent/binError;
	weightSum += 1./binError;
      }
    }
    double ymean = binSum / weightSum;
    //double ymean = ratio->GetMean(2);
    stringstream sYmean;
    sYmean << ymean;
    string labeltext=sYmean.str()+" mean Y";
    //label->AddEntry((TObject*)0,labeltext.c_str(),""); // mean on Y
    //label->Draw();
		
    //TPaveStats *r3 = (TPaveStats*)ratio->FindObject("stats");
    //r3->SetX1NDC(0.01);
    //r3->SetX2NDC(0.10); 
    //r3->SetY1NDC(0.20);
    //r3->SetY2NDC(0.50); 
    //gStyle->SetOptStat("mr");
    //r3->SetTextColor(kWhite);
    //r3->SetLineColor(kWhite);
    //r3->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+".png";
    CanvPlot->Print(tmp.c_str());

  }
  else if (flag==2){
    //CanvPlot.Divide(2,1);
    //CanvPlot.cd(1);

    // data
    dataf->cd("validationJEC");
    if (isMu && isAngularAnalysis) dataf->cd("validationJECmu");

    gDirectory->GetObject(plot.c_str(),data2);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    TPaveStats *r1 = (TPaveStats*)data2->FindObject("stats");
    //r1->SetX1NDC(0.70); Uncomment if you wonna draw your stat in the top right corner
    //r1->SetX2NDC(0.85); 
    //r1->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"data.png";
    CanvPlot->Print(tmp.c_str());


    //CanvPlot.cd(2);
    // montecarlo
    mcf->cd("validationJEC");
    if (isMu) mcf->cd("validationJECmu/");

    if (isAngularAnalysis) {
      mcf->cd("validationJEC/");
      if (isMu) mcf->cd("validationJECmu/");
    }

    gDirectory->GetObject(plot.c_str(),data2);

    data2->SetMinimum(1);
    data2->Draw("COLZ");

    gPad->Update(); // altrimenti non becchi la stat
    //TPaveStats *r2 = (TPaveStats*)data2->FindObject("stats");
    //r2->SetX1NDC(0.70);
    //r2->SetX2NDC(0.85); 
    //r2->Draw();
    CanvPlot->Update();

    tmp=plotpath+plot+"mc.png";
    CanvPlot->Print(tmp.c_str());
  }
  //	else { cout << "You're getting an exception! Most likely there's no histogram here... \n"; }

  delete data;
  delete data2;
  delete hs;
  //delete CanvPlot;

  dataf->Close();
  mcf->Close();
  ttbarf->Close();
  wf->Close();
  qcd23emf->Close();
  qcd38emf->Close();
  qcd817emf->Close();
  qcd23bcf->Close();
  qcd38bcf->Close();
  qcd817bcf->Close();
  WZf->Close();
  ZZf->Close();
  
  if (isAngularAnalysis){
    if (bckg_leadingJetPt.size()>0 && bckg_2leadingJetPt.size()>0 && bckg_3leadingJetPt.size()>0 && bckg_4leadingJetPt.size()>0  && bckg_JetMultiplicity.size()>0 && bckg_HT.size()>0 && bckg_leadingJetEta.size()>0 && bckg_PhiStar.size()>0 && cold){
      fzj->cd();
      treeBKG_->Fill();
      treeBKG_->Write();
      TH1F *leadhisto=new TH1F("leadhisto","leading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto2=new TH1F("leadhisto2","subleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto3=new TH1F("leadhisto3","subsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *leadhisto4=new TH1F("leadhisto4","subsubsubleading jet background contribution",bckg_leadingJetPt.size(),0,bckg_leadingJetPt.size());
      TH1F *multiphisto=new TH1F("multiphisto","jet multiplicity background contribution",bckg_JetMultiplicity.size(),0,bckg_JetMultiplicity.size());

      TH1F *HT=new TH1F("HT","HT background contribution",bckg_HT.size(),0,bckg_HT.size());
      TH1F *HT1=new TH1F("HT1","HT background contribution when >= 1 jet",bckg_HT1.size(),0,bckg_HT1.size());
      TH1F *HT2=new TH1F("HT2","HT background contribution when >= 2 jets",bckg_HT2.size(),0,bckg_HT2.size());
      TH1F *HT3=new TH1F("HT3","HT background contribution when >= 3 jets",bckg_HT3.size(),0,bckg_HT3.size());
      TH1F *HT4=new TH1F("HT4","HT background contribution when >= 4 jets",bckg_HT4.size(),0,bckg_HT4.size());

      TH1F *leadhistoeta=new TH1F("leadhistoeta","leading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta2=new TH1F("leadhistoeta2","subleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta3=new TH1F("leadhistoeta3","subsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());
      TH1F *leadhistoeta4=new TH1F("leadhistoeta4","subsubsubleading jet background contribution",bckg_leadingJetEta.size(),0,bckg_leadingJetEta.size());

      TH1F *PhiStar=new TH1F("PhiStar","PhiStar background contribution",bckg_PhiStar.size(),0,bckg_PhiStar.size());

      for (int i=0; i< bckg_leadingJetPt.size(); i++){
	leadhisto->Fill(i,bckg_leadingJetPt[i]);
	leadhisto2->Fill(i,bckg_2leadingJetPt[i]);
	leadhisto3->Fill(i,bckg_3leadingJetPt[i]);
	leadhisto4->Fill(i,bckg_4leadingJetPt[i]);
      }
      leadhisto->Write();
      leadhisto2->Write();
      leadhisto3->Write();
      leadhisto4->Write();

      for (int i=0; i< bckg_leadingJetEta.size(); i++){
	leadhistoeta->Fill(i,bckg_leadingJetEta[i]);
	leadhistoeta2->Fill(i,bckg_2leadingJetEta[i]);
	leadhistoeta3->Fill(i,bckg_3leadingJetEta[i]);
	leadhistoeta4->Fill(i,bckg_4leadingJetEta[i]);
      }
      leadhistoeta->Write();
      leadhistoeta2->Write();
      leadhistoeta3->Write();
      leadhistoeta4->Write();
      //fzj->Close();

      for (int i=0; i< bckg_JetMultiplicity.size(); i++){
	multiphisto->Fill(i,bckg_JetMultiplicity[i]);
      }
      multiphisto->Write();
      
      ///////////////

      for (int i=0; i< bckg_HT.size(); i++){
	HT->Fill(i,bckg_HT[i]);
      }
      HT->Write();
      
      for (int i=0; i< bckg_HT1.size(); i++){
	HT1->Fill(i,bckg_HT1[i]);
      }
      HT1->Write();
      
      for (int i=0; i< bckg_HT2.size(); i++){
	HT2->Fill(i,bckg_HT2[i]);
      }
      HT2->Write();
      
      for (int i=0; i< bckg_HT3.size(); i++){
	HT3->Fill(i,bckg_HT3[i]);
      }
      HT3->Write();
      
      for (int i=0; i< bckg_HT4.size(); i++){
	HT4->Fill(i,bckg_HT4[i]);
      }
      HT4->Write();

      //Phi star
      for (int i=0; i< bckg_PhiStar.size(); i++){
	PhiStar->Fill(i,bckg_PhiStar[i]);
      }
      PhiStar->Write();

    cold=false;
    }
  }
  return;
}
Esempio n. 9
0
//iteration code
void iterate(TrkSettings s,int iter, int stepType, bool doCondor, bool testErrors = false)
{
  float pt, eta, phi, weight, centPU, rmin, maxJetPt,trkStatus,pNRec,mpt,mtrkQual,nEv; 
  
  TFile * histFile;
  std::string ifPP = "";
  if(s.nPb==0) ifPP = "pp_";
  if(iter==0) histFile = TFile::Open(Form("%scorrHists_job%d.root",ifPP.c_str(),s.job),"recreate");
  else        histFile = TFile::Open(Form("%scorrHists_job%d.root",ifPP.c_str(),s.job),"update");

  //make needed gen skim if it hasn't been done yet
  if(iter==0)
  {
    TH1D *genPre[20], *mrecoPre[20];
    TH2D *genPre2[20], *mrecoPre2[20];
    std::cout << "Denominator info not yet calculated; calculating and saving it..." << std::endl;
    for(int i = 0; i<8; i++)
    {
      if(i==6) continue;
      if(i != 1 && i!=7)
      {
        genPre[i] = makeTH1(s,i,"gen");
        mrecoPre[i] = makeTH1(s,i,"mreco");
      }
      else
      {
        genPre2[i] = makeTH2(s,i,"gen");
        mrecoPre2[i]= makeTH2(s,i,"mreco");
      }
    }
   
    TFile * skim;
    if(doCondor)
    {
      if(s.reuseSkim) skim = TFile::Open(Form("/mnt/hadoop/cms/store/user/abaty/tracking_Efficiencies/ntuples/%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
      else skim = TFile::Open(Form("%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
    }
    else skim = TFile::Open(Form("/export/d00/scratch/abaty/trackingEff/ntuples/%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
    //for efficiency
    std::cout << "Doing Efficiency denominator" << std::endl;   
    TNtuple * gen = (TNtuple*)  skim->Get("Gen");
    gen->SetBranchAddress("genPt",&pt);
    gen->SetBranchAddress("genEta",&eta); 
    gen->SetBranchAddress("genPhi",&phi);
    gen->SetBranchAddress("weight",&weight);
    gen->SetBranchAddress("centPU",&centPU);
    gen->SetBranchAddress("rmin",&rmin);
    gen->SetBranchAddress("jtpt",&maxJetPt);
    gen->SetBranchAddress("pNRec",&pNRec); 
    gen->SetBranchAddress("nEv",&nEv); 
	   
    for(int i = 0; i<gen->GetEntries(); i++)
    {
      gen->GetEntry(i);
      if(s.doSplit && nEv==1) continue;
      genPre[0]->Fill(pt,weight);
      genPre2[1]->Fill(eta,phi,weight); 
      genPre[2]->Fill(centPU,weight);
      genPre[3]->Fill(maxJetPt,weight);
      genPre[4]->Fill(eta,weight); 
      genPre[5]->Fill(rmin,weight);
      genPre2[7]->Fill(eta,pt,weight);
    }

    //for fake
    std::cout << "Doing Fake denominator" << std::endl;   
    TNtuple * reco = (TNtuple*)  skim->Get("Reco"); 
    reco->SetBranchAddress("trkPt",&pt);
    reco->SetBranchAddress("trkEta",&eta);
    reco->SetBranchAddress("trkPhi",&phi);
    reco->SetBranchAddress("weight",&weight);
    reco->SetBranchAddress("centPU",&centPU);
    reco->SetBranchAddress("rmin",&rmin);
    reco->SetBranchAddress("jtpt",&maxJetPt);
    reco->SetBranchAddress("trkStatus",&trkStatus);
    reco->SetBranchAddress("nEv",&nEv); 
    for(int i = 0; i<reco->GetEntries(); i++)
    {
      reco->GetEntry(i);
      if(s.doSplit && nEv==1) continue;
      if(trkStatus<-100) continue;
      mrecoPre[0]->Fill(pt,weight);
      mrecoPre2[1]->Fill(eta,phi,weight); 
      mrecoPre[2]->Fill(centPU,weight);
      mrecoPre[3]->Fill(maxJetPt,weight);
      mrecoPre[4]->Fill(eta,weight); 
      mrecoPre[5]->Fill(rmin,weight);
      mrecoPre2[7]->Fill(eta,pt,weight);
    }
  
    //Secondary calculation (no iterations)
    std::cout << "Quickly calculating the Secondary Rate from the reco tree (No further iterations needed)" << std::endl;
    TH2D * Secondary_Matched = new TH2D("Secondary_Matched",";pt;",s.multiRecoBins.at(s.job/s.nPtBinCoarse),s.ptMin,s.ptMax,24,-2.4,2.4); 
    TH2D * Secondary_Secondaries = new TH2D("Secondary_Secondaries",";pt;",s.multiRecoBins.at(s.job/s.nPtBinCoarse),s.ptMin,s.ptMax,24,-2.4,2.4); 
    for(int i = 0; i<reco->GetEntries(); i++)
    {
      reco->GetEntry(i);
      if(s.doSplit && nEv==1) continue;
      if(trkStatus>-100)
      {
        Secondary_Matched->Fill(pt,eta,weight);
        if(trkStatus==-99) Secondary_Secondaries->Fill(pt,eta,weight);
      }
    }
    TH2D * Secondary = (TH2D*)Secondary_Secondaries->Clone("SecondaryRate");
    Secondary->Divide(Secondary_Matched);
    Secondary->SetDirectory(histFile);
    Secondary_Matched->SetDirectory(histFile);
    Secondary_Secondaries->SetDirectory(histFile);
    //end Secondary Reco calculation

    //multiReco calculation (no iterations)
    std::cout << "Quickly calculating the Multiple Reconstruction Rate from the gen tree (No further iterations needed)" << std::endl;
    TH1D * MultiGen = new TH1D("MultiGen",";pt;",s.multiRecoBins.at(s.job/s.nPtBinCoarse),s.ptMin,s.ptMax); 
    TH1D * MultiReco = new TH1D("MultiMatchedReco",";pt;",s.multiRecoBins.at(s.job/s.nPtBinCoarse),s.ptMin,s.ptMax); 
    for(int i = 0; i<gen->GetEntries(); i++)
    {
      gen->GetEntry(i);
      if(s.doSplit && nEv==1) continue;
      if(pNRec>-1)
      {
        MultiGen->Fill(pt,weight);
        if(pNRec>1) MultiReco->Fill(pt,(pNRec-1)*weight);
      }
    }
    TH1D * Multi = (TH1D*)MultiReco->Clone("MultipleRecoRate");
    Multi->Divide(MultiGen);
    Multi->SetDirectory(histFile);
    MultiReco->SetDirectory(histFile);
    MultiGen->SetDirectory(histFile);
    //end Multiple Reco calculation

    skim->Close();
    histFile->Write(); 
  }
	  
  //redundant for first step, but needed if the gen file was made and saved previously 
  std::cout << "Loading appropriate information for denominator (gen for efficiency, reco for fake)..." << std::endl;
  TH1D * genHist[20], *recoHist[20];
  TH2D * genHist2[20], *recoHist2[20];
  genHist[0] = (TH1D*)histFile->Get("gen_pt");
  genHist2[1] = (TH2D*)histFile->Get("gen_accept"); 
  genHist[2] = (TH1D*)histFile->Get("gen_centPU");
  genHist[3] = (TH1D*)histFile->Get("gen_maxJetPt");
  genHist[4] = (TH1D*)histFile->Get("gen_eta"); 
  genHist[5] = (TH1D*)histFile->Get("gen_rmin"); 
  genHist2[7] = (TH2D*)histFile->Get("gen_etaPt");
  std::cout << "Efficiency denominator histogram available now." << std::endl;
  recoHist[0] = (TH1D*)histFile->Get("mreco_pt");
  recoHist2[1] = (TH2D*)histFile->Get("mreco_accept"); 
  recoHist[2] = (TH1D*)histFile->Get("mreco_centPU");
  recoHist[3] = (TH1D*)histFile->Get("mreco_maxJetPt");
  recoHist[4] = (TH1D*)histFile->Get("mreco_eta"); 
  recoHist[5] = (TH1D*)histFile->Get("mreco_rmin");
  recoHist2[7] = (TH2D*)histFile->Get("mreco_etaPt");
  std::cout << "Fake denominator histogram available now." << std::endl;
	   
  //************************************************************************************************************
  std::cout << "Calculating numerator for efficiency/fake calculation..." << std::endl;
  TH1D *mrecoHist, *divHist, *frecoHist, *fdivHist;
  TH2D *mrecoHist2,*divHist2, *frecoHist2, *fdivHist2;
  //getting old eff histograms to calculate the updated efficiency (the number 30 is arbitrary, increase if more are needed)
  TH1D * previousEff[30], *previousFake[30];
  TH2D * previousEff2[30], *previousFake2[30];
  for(int i=0; i<iter; i++)
  {
    int type = s.stepOrder.at(i%s.nStep); 
    if(type==0 || type==2 || type==3 || type==4 || type==5)
    {
      previousEff[i] = (TH1D*)histFile->Get(Form("eff_step%d",i)); 
      previousFake[i] = (TH1D*)histFile->Get(Form("fake_step%d",i));
    }
    if(type==1 || type==7)
    {  
      previousEff2[i] = (TH2D*)histFile->Get(Form("eff_step%d",i)); 
      previousFake2[i] = (TH2D*)histFile->Get(Form("fake_step%d",i));
    }
  }

  //setting up stuff for reading out of skim
  TH1D * mrecoErr;
  TH1D * mrecoW;
  TH2D * mrecoErr2;
  TH2D * mrecoW2;
  if(stepType == 0 || stepType==2 || stepType==3 || stepType==4 || stepType==5)
  {
    mrecoHist = makeTH1(s,stepType,Form("mreco_eff_step%d",iter));
    frecoHist = makeTH1(s,stepType,Form("reco_fake_step%d",iter));
    if(testErrors)
    {
      mrecoErr = (TH1D*)mrecoHist->Clone("mrecoErr");
      mrecoW = (TH1D*)mrecoHist->Clone("mrecoW");
    }
  }
  if(stepType == 1 || stepType == 7)
  {
    mrecoHist2 = makeTH2(s,stepType,Form("mreco_eff_step%d",iter));
    frecoHist2 = makeTH2(s,stepType,Form("reco_fake_step%d",iter));
    if(testErrors)
    {
      mrecoErr2 = (TH2D*)mrecoHist2->Clone("mrecoErr");
      mrecoW2 = (TH2D*)mrecoHist2->Clone("mrecoW");
    }
  }

  TFile * skim;
  if(doCondor)
  {
    if(s.reuseSkim) skim = TFile::Open(Form("/mnt/hadoop/cms/store/user/abaty/tracking_Efficiencies/ntuples/%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
    else skim = TFile::Open(Form("%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
  }
  else skim = TFile::Open(Form("/export/d00/scratch/abaty/trackingEff/ntuples/%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
  TNtuple * reco = (TNtuple*)  skim->Get("Reco"); 
  reco->SetBranchAddress("trkPt",&pt);
  reco->SetBranchAddress("trkEta",&eta);
  reco->SetBranchAddress("trkPhi",&phi);
  reco->SetBranchAddress("weight",&weight);
  reco->SetBranchAddress("centPU",&centPU);
  reco->SetBranchAddress("rmin",&rmin);
  reco->SetBranchAddress("jtpt",&maxJetPt);
  reco->SetBranchAddress("trkStatus",&trkStatus);
  reco->SetBranchAddress("nEv",&nEv); 

  //reading out of skim 
  for(int i = 0; i<reco->GetEntries(); i++)
  {
    //applying efficiencies from all previous steps
    float previousFakeCorr = 1; 
    reco->GetEntry(i);
    if(s.doSplit && nEv==1) continue;
    
    //fake part
    if(iter!=0)
    {
      for(int n = 0; n<iter; n++)
      {
        int type = s.stepOrder.at(n%s.nStep);
        if(type==0) previousFakeCorr *= previousFake[n]->GetBinContent(previousFake[n]->FindBin(pt));
        if(type==1) previousFakeCorr *= previousFake2[n]->GetBinContent(previousFake2[n]->GetXaxis()->FindBin(eta),previousFake2[n]->GetYaxis()->FindBin(phi));
        if(type==2) previousFakeCorr *= previousFake[n]->GetBinContent(previousFake[n]->FindBin(centPU));
        if(type==3) previousFakeCorr *= previousFake[n]->GetBinContent(previousFake[n]->FindBin(maxJetPt));
        if(type==4) previousFakeCorr *= previousFake[n]->GetBinContent(previousFake[n]->FindBin(eta));
        if(type==5) previousFakeCorr *= previousFake[n]->GetBinContent(previousFake[n]->FindBin(rmin));
        if(type==7) previousFakeCorr *= previousFake2[n]->GetBinContent(previousFake2[n]->GetXaxis()->FindBin(eta),previousFake2[n]->GetYaxis()->FindBin(pt));
      } 
    }
    if(previousFakeCorr==0) std::cout <<  "\nWarning!!! A correction is going to infinity.  This usually indicates an empty bin somewhere, try using a coarser binning or more events! \n" << std::endl;
    //filling histograms
    if(stepType==0) frecoHist->Fill(pt,weight/previousFakeCorr);
    if(stepType==1) frecoHist2->Fill(eta,phi,weight/previousFakeCorr); 
    if(stepType==2) frecoHist->Fill(centPU,weight/previousFakeCorr);
    if(stepType==3) frecoHist->Fill(maxJetPt,weight/previousFakeCorr);
    if(stepType==4) frecoHist->Fill(eta,weight/previousFakeCorr); 
    if(stepType==5) frecoHist->Fill(rmin,weight/previousFakeCorr); 
    if(stepType==7) frecoHist2->Fill(eta,pt,weight/previousFakeCorr);
  }
  
  //eff part
  TNtuple * gen = (TNtuple*)  skim->Get("Gen");
  gen->SetBranchAddress("genPt",&pt);
  gen->SetBranchAddress("genEta",&eta); 
  gen->SetBranchAddress("genPhi",&phi);
  gen->SetBranchAddress("weight",&weight);
  gen->SetBranchAddress("centPU",&centPU);
  gen->SetBranchAddress("rmin",&rmin);
  gen->SetBranchAddress("jtpt",&maxJetPt);
  gen->SetBranchAddress("pNRec",&pNRec); 
  gen->SetBranchAddress("mtrkPt",&mpt);
  gen->SetBranchAddress("mtrkQual",&mtrkQual); 
  gen->SetBranchAddress("nEv",&nEv); 

  //reading out of skim 
  for(int i = 0; i<gen->GetEntries(); i++)
  {
    //applying efficiencies from all previous steps
    float previousEffCorr = 1;
    float previousEffCorrErr = 0;
    gen->GetEntry(i);
    if(s.doSplit && nEv==1) continue;
    if(mtrkQual<1||  mpt<=0) continue;
    if(iter!=0)
    {
      for(int n = 0; n<iter; n++)//calculating current efficiency correction
      {
        int type = s.stepOrder.at(n%s.nStep);
        if(type==0){
          previousEffCorr *= previousEff[n]->GetBinContent(previousEff[n]->FindBin(pt));
          if(testErrors) previousEffCorrErr += TMath::Power(previousEff[n]->GetBinError(previousEff[n]->FindBin(pt))/previousEff[n]->GetBinContent(previousEff[n]->FindBin(pt)),2);
        }
        if(type==1){
          previousEffCorr *= previousEff2[n]->GetBinContent(previousEff2[n]->GetXaxis()->FindBin(eta),previousEff2[n]->GetYaxis()->FindBin(phi));
          if(testErrors) previousEffCorrErr += TMath::Power(previousEff2[n]->GetBinError(previousEff2[n]->GetXaxis()->FindBin(eta),previousEff2[n]->GetYaxis()->FindBin(phi))/previousEff2[n]->GetBinContent(previousEff2[n]->GetXaxis()->FindBin(eta),previousEff2[n]->GetYaxis()->FindBin(phi)),2);
        }
        if(type==2){
          previousEffCorr *= previousEff[n]->GetBinContent(previousEff[n]->FindBin(centPU));
          if(testErrors) previousEffCorrErr += TMath::Power(previousEff[n]->GetBinError(previousEff[n]->FindBin(centPU))/previousEff[n]->GetBinContent(previousEff[n]->FindBin(centPU)),2); 
        }
        if(type==3){
          previousEffCorr *= previousEff[n]->GetBinContent(previousEff[n]->FindBin(maxJetPt));
          if(testErrors) previousEffCorrErr += TMath::Power(previousEff[n]->GetBinError(previousEff[n]->FindBin(maxJetPt))/previousEff[n]->GetBinContent(previousEff[n]->FindBin(maxJetPt)),2); 
        }
        if(type==4){
          previousEffCorr *= previousEff[n]->GetBinContent(previousEff[n]->FindBin(eta));
          if(testErrors) previousEffCorrErr += TMath::Power(previousEff[n]->GetBinError(previousEff[n]->FindBin(eta))/previousEff[n]->GetBinContent(previousEff[n]->FindBin(eta)),2);  
        }
        if(type==5){
          previousEffCorr *= previousEff[n]->GetBinContent(previousEff[n]->FindBin(rmin));
          if(testErrors) previousEffCorrErr += TMath::Power(previousEff[n]->GetBinError(previousEff[n]->FindBin(rmin))/previousEff[n]->GetBinContent(previousEff[n]->FindBin(rmin)),2);  
        }
        if(type==7){
          previousEffCorr *= previousEff2[n]->GetBinContent(previousEff2[n]->GetXaxis()->FindBin(eta),previousEff2[n]->GetYaxis()->FindBin(pt));
          if(testErrors) previousEffCorrErr += TMath::Power(previousEff2[n]->GetBinError(previousEff2[n]->GetXaxis()->FindBin(eta),previousEff2[n]->GetYaxis()->FindBin(pt))/previousEff2[n]->GetBinContent(previousEff2[n]->GetXaxis()->FindBin(eta),previousEff2[n]->GetYaxis()->FindBin(pt)),2);
        }
      }
      if(testErrors) previousEffCorrErr = previousEffCorrErr/TMath::Power(previousEffCorr,2);
    }
    if(previousEffCorr==0) std::cout <<  "\nWarning!!! A correction is going to infinity.  This usually indicates an empty bin somewhere, try using a coarser binning or more events! \n" << std::endl; 
    //filling histograms
    float var1, var2;
    if(stepType==0) var1 = pt;
    if(stepType==1){var1 = eta; var2 = phi;}
    if(stepType==2) var1 = centPU;
    if(stepType==3) var1 = maxJetPt;
    if(stepType==4) var1 = eta;
    if(stepType==5) var1 = rmin;
    if(stepType==7){var1 = eta; var2 = pt;}
    if(stepType!=1 && stepType!=7){
      mrecoHist->Fill(var1,weight/previousEffCorr);
      if(testErrors){
        mrecoErr->Fill(var1,weight*weight*previousEffCorrErr);
        mrecoW->Fill(var1,weight);
      }
    }
    else{
      mrecoHist2->Fill(var1,var2,weight/previousEffCorr); 
      if(testErrors){
        mrecoErr2->Fill(var1,var2,weight*weight*previousEffCorrErr);
        mrecoW2->Fill(var1,var2,weight);
      }
    }
  }
  skim->Close();

  //saving reco and efficiencies/fake rates 
  std::cout << "Calculating updated Efficiency/Fake Rate and saving histograms" << std::endl;
  histFile->cd();    
  if(stepType==0 || stepType == 2 || stepType == 3 || stepType==4 || stepType==5)
  {
    if(testErrors)
    {
      mrecoErr->Divide(mrecoW);
      mrecoErr->Divide(mrecoW);
      for(int i = 1 ; i<mrecoErr->GetSize()-1; i++) mrecoHist->SetBinError(i,TMath::Power(mrecoErr->GetBinContent(i),0.5));
    }
    divHist = (TH1D*)mrecoHist->Clone(Form("eff_step%d",iter));
    divHist->Divide(genHist[stepType]);
    mrecoHist->Write();
    divHist->Write();
    
    fdivHist = (TH1D*)frecoHist->Clone(Form("fake_step%d",iter));
    fdivHist->Divide(recoHist[stepType]);
    frecoHist->Write();
    fdivHist->Write(); 
  }
  if(stepType==1 || stepType==7)
  {
    if(testErrors)
    {
      mrecoErr2->Divide(mrecoW2);
      mrecoErr2->Divide(mrecoW2);
      for(int i = 1 ; i<mrecoErr2->GetNbinsX()+1; i++)
        for(int j = 1; j<mrecoErr2->GetNbinsY()+1; j++) mrecoHist2->SetBinError(i,j,TMath::Power(mrecoErr2->GetBinContent(i,j),0.5));
    }
    divHist2 = (TH2D*)mrecoHist2->Clone(Form("eff_step%d",iter));
    divHist2->Divide(genHist2[stepType]);
    mrecoHist2->Write();
    divHist2->Write();
    
    fdivHist2 = (TH2D*)frecoHist2->Clone(Form("fake_step%d",iter));
    fdivHist2->Divide(recoHist2[stepType]);
    frecoHist2->Write();
    fdivHist2->Write();
  }
  
  //*********************************************************************************************
  //*********************************************************************************************
  //Only executed on last step before exiting program
  if(iter>=s.nStep*s.fullIterations && s.terminateStep==stepType)
  {
    //writing final correction tables (consolidating multiple steps of the same variable)
    //once again 10 is an arbitrary number, increase if needed...
    std::cout << "Consolidating into final histograms by multiplying out efficiencies/fake rates per variable" << std::endl;
    TH1D * finalEff[10], *finalFake[10];
    TH2D * finalEff2[10], *finalFake2[10];
    for(int i=0; i<s.nStep; i++)
    {
      int type = s.stepOrder.at(i%s.nStep); 
      if(type == 0 || type==2 || type==3 || type==4 || type==5)
      {
        finalEff[i] = (TH1D*)previousEff[i]->Clone(Form("finalEff_type%d",i));
        finalFake[i] = (TH1D*)previousFake[i]->Clone(Form("finalFake_type%d",i));
      }
      if(type == 1 ||  type==7)
      {
        finalEff2[i] = (TH2D*)previousEff2[i]->Clone(Form("finalEff_type%d",i));
        finalFake2[i] = (TH2D*)previousFake2[i]->Clone(Form("finalFake_type%d",i));
      }
    }
    for(int n = s.nStep; n<iter; n++)
    {
      int type2 = s.stepOrder.at(n%s.nStep);
      if(type2==0 || type2==2 || type2==3 || type2==4 || type2==5)
      {
        finalEff[n%s.nStep]->Multiply(previousEff[n]);
        finalFake[n%s.nStep]->Multiply(previousFake[n]); 
      }
      if(type2==1 || type2==7)
      {
        finalEff2[n%s.nStep]->Multiply(previousEff2[n]);
        finalFake2[n%s.nStep]->Multiply(previousFake2[n]); 
      }
    }  
    if(stepType == 0 || stepType==2 || stepType==3 || stepType==4 || stepType==5)
    {
      finalEff[iter%s.nStep]->Multiply((TH1D*)histFile->Get(Form("eff_step%d",iter)));
      finalFake[iter%s.nStep]->Multiply((TH1D*)histFile->Get(Form("fake_step%d",iter)));
    }
    if(stepType == 1 || stepType == 7)
    {
      finalEff2[iter%s.nStep]->Multiply((TH2D*)histFile->Get(Form("eff_step%d",iter)));
      finalFake2[iter%s.nStep]->Multiply((TH2D*)histFile->Get(Form("fake_step%d",iter)));
    }
    for(int i=0; i<s.nStep; i++)
    {
      int type = s.stepOrder.at(i%s.nStep); 
      if(type == 0 || type==2 || type==3 || type==4 || type == 5){ finalEff[i]->Write(); finalFake[i]->Write();}
      if(type == 1 || type == 7){ finalEff2[i]->Write(); finalFake2[i]->Write();}
    }
   
    //******************************************************************************************************* 
    //writing calculating final closures in each variable checked after applying corrections
    std::cout << "Calculating Final Closures..." << std::endl;
    TH1D * finalEffClosure[10], *finalFakeClosure[10];
    TH2D * finalEffClosure2[10], *finalFakeClosure2[10];
    for(int i=0; i<8; i++)
    {
      int type = i;
      if(type==0 || type==2 || type==3 || type==4 || type==5)
      {
        finalEffClosure[i] = (TH1D*)genHist[i]->Clone(Form("finalEffClosure_var%d",i));
        finalFakeClosure[i] = (TH1D*)recoHist[i]->Clone(Form("finalFakeClosure_var%d",i));
        finalEffClosure[i]->Reset();
        finalFakeClosure[i]->Reset();
      }
      if(type==1 || type==7)
      {  
        finalEffClosure2[i] = (TH2D*)genHist2[i]->Clone(Form("finalEffClosure_var%d",i));
        finalFakeClosure2[i] = (TH2D*)recoHist2[i]->Clone(Form("finalFakeClosure_var%d",i));
        finalEffClosure2[i]->Reset();
        finalFakeClosure2[i]->Reset();
      }
    }
   
    if(doCondor)
    { 
      if(s.reuseSkim) skim = TFile::Open(Form("/mnt/hadoop/cms/store/user/abaty/tracking_Efficiencies/ntuples/%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
      else skim = TFile::Open(Form("%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
    }
    else skim = TFile::Open(Form("/export/d00/scratch/abaty/trackingEff/ntuples/%strackSkim_job%d.root",ifPP.c_str(),s.job),"read");
    reco = (TNtuple*)  skim->Get("Reco"); 
    reco->SetBranchAddress("trkPt",&pt);
    reco->SetBranchAddress("trkEta",&eta);
    reco->SetBranchAddress("trkPhi",&phi);
    reco->SetBranchAddress("weight",&weight);
    reco->SetBranchAddress("centPU",&centPU);
    reco->SetBranchAddress("rmin",&rmin);
    reco->SetBranchAddress("jtpt",&maxJetPt);
    reco->SetBranchAddress("trkStatus",&trkStatus);
    reco->SetBranchAddress("nEv",&nEv); 

    //reading out of skim 
    for(int i = 0; i<reco->GetEntries(); i++)
    {
      //applying efficiencies from all previous steps
      float previousFakeCorr = 1; 
      reco->GetEntry(i);
      if(s.doSplit && nEv==1) continue;
      for(int n=0; n<s.nStep; n++)//getting correction
      {
        int type = s.stepOrder.at(n%s.nStep);
        if(type==0) previousFakeCorr *= finalFake[n]->GetBinContent(finalFake[n]->FindBin(pt));
        if(type==1) previousFakeCorr *= finalFake2[n]->GetBinContent(finalFake2[n]->GetXaxis()->FindBin(eta),finalFake2[n]->GetYaxis()->FindBin(phi));
        if(type==2) previousFakeCorr *= finalFake[n]->GetBinContent(finalFake[n]->FindBin(centPU));
        if(type==3) previousFakeCorr *= finalFake[n]->GetBinContent(finalFake[n]->FindBin(maxJetPt));
        if(type==4) previousFakeCorr *= finalFake[n]->GetBinContent(finalFake[n]->FindBin(eta));
        if(type==5) previousFakeCorr *= finalFake[n]->GetBinContent(finalFake[n]->FindBin(rmin));
        if(type==7) previousFakeCorr *= finalFake2[n]->GetBinContent(finalFake2[n]->GetXaxis()->FindBin(eta),finalFake2[n]->GetYaxis()->FindBin(pt));
      }
      if(previousFakeCorr<1) previousFakeCorr==1;
      finalFakeClosure[0]->Fill(pt,weight/previousFakeCorr);
      finalFakeClosure2[1]->Fill(eta,phi,weight/previousFakeCorr); 
      finalFakeClosure[2]->Fill(centPU,weight/previousFakeCorr);
      finalFakeClosure[3]->Fill(maxJetPt,weight/previousFakeCorr);
      finalFakeClosure[4]->Fill(eta,weight/previousFakeCorr); 
      finalFakeClosure[5]->Fill(rmin,weight/previousFakeCorr); 
      finalFakeClosure2[7]->Fill(eta,pt,weight/previousFakeCorr);  
    }
  
    gen = (TNtuple*)  skim->Get("Gen");
    gen->SetBranchAddress("genPt",&pt);
    gen->SetBranchAddress("genEta",&eta); 
    gen->SetBranchAddress("genPhi",&phi);
    gen->SetBranchAddress("weight",&weight);
    gen->SetBranchAddress("centPU",&centPU);
    gen->SetBranchAddress("rmin",&rmin);
    gen->SetBranchAddress("jtpt",&maxJetPt);
    gen->SetBranchAddress("pNRec",&pNRec); 
    gen->SetBranchAddress("mtrkPt",&mpt);
    gen->SetBranchAddress("mtrkQual",&mtrkQual); 
    gen->SetBranchAddress("nEv",&nEv); 
    //reading out of skim 
    for(int i = 0; i<gen->GetEntries(); i++)
    {
      //applying efficiencies from all previous steps
      float previousEffCorr = 1;
      gen->GetEntry(i);
      if(s.doSplit && nEv==1) continue;
      if(mtrkQual<1 || mpt<=0) continue;
      for(int n=0; n<s.nStep; n++)//getting correction
      {
        int type = s.stepOrder.at(n%s.nStep);
        if(type==0) previousEffCorr *= finalEff[n]->GetBinContent(finalEff[n]->FindBin(pt));
        if(type==1) previousEffCorr *= finalEff2[n]->GetBinContent(finalEff2[n]->GetXaxis()->FindBin(eta),finalEff2[n]->GetYaxis()->FindBin(phi));
        if(type==2) previousEffCorr *= finalEff[n]->GetBinContent(finalEff[n]->FindBin(centPU));
        if(type==3) previousEffCorr *= finalEff[n]->GetBinContent(finalEff[n]->FindBin(maxJetPt));
        if(type==4) previousEffCorr *= finalEff[n]->GetBinContent(finalEff[n]->FindBin(eta));
        if(type==5) previousEffCorr *= finalEff[n]->GetBinContent(finalEff[n]->FindBin(rmin));
        if(type==7) previousEffCorr *= finalEff2[n]->GetBinContent(finalEff2[n]->GetXaxis()->FindBin(eta), finalEff2[n]->GetYaxis()->FindBin(pt));  
      }
      if(previousEffCorr>1) previousEffCorr==1;
      finalEffClosure[0]->Fill(pt,weight/previousEffCorr);
      finalEffClosure2[1]->Fill(eta,phi,weight/previousEffCorr); 
      finalEffClosure[2]->Fill(centPU,weight/previousEffCorr);
      finalEffClosure[3]->Fill(maxJetPt,weight/previousEffCorr);
      finalEffClosure[4]->Fill(eta,weight/previousEffCorr); 
      finalEffClosure[5]->Fill(rmin,weight/previousEffCorr); 
      finalEffClosure2[7]->Fill(eta,pt,weight/previousEffCorr);
    }

    histFile->cd();
    for(int i=0; i<8; i++)
    {
      if(i==6) continue;
      if(i!=1 && i!=7)
      {
        finalFakeClosure[i]->Divide(recoHist[i]);
        finalEffClosure[i]->Divide(genHist[i]);
        finalFakeClosure[i]->Write();
        finalEffClosure[i]->Write();
      }
      else
      {
        finalFakeClosure2[i]->Divide(recoHist2[i]);
        finalEffClosure2[i]->Divide(genHist2[i]);
        finalFakeClosure2[i]->Write();
        finalEffClosure2[i]->Write();
      }
    }
    std::cout << "Calculating Final Closures..." << std::endl;
  }
  histFile->Close();    
 
  std::cout << "Finished with iteration \n" << std::endl;
  return;
}