Exemplo n.º 1
0
/** 
 * Draw the Poisson estimate of the occupancy in a given ring.
 * 
 * @param p            List 
 * @param d            Detector
 * @param r            Ring
 * 
 * @return The occupancy (in percent)
 *
 * @deprecated Use QATrender instead
 * @ingroup pwglf_forward_scripts_qa
 */
Double_t
DrawRingOccupancy(TList* p, UShort_t d, Char_t r)
{
  if (!p) return 0;

  TList* ring = static_cast<TList*>(p->FindObject(Form("FMD%d%c",d,r)));
  if (!ring) { 
    Error("DrawOccupancy", "List FMD%d%c not found in %s",d,r,p->GetName());
    return 0;
  }
  
  TH1* corr = static_cast<TH1*>(ring->FindObject("occupancy"));
  if (!corr) { 
    Error("DrawRingOccupancy", "Histogram occupancy not found in FMD%d%c",
	  d, r);
    return 0;
  }
  corr->Rebin(4);

  TPad* pad = static_cast<TPad*>(gPad);
  pad->SetGridy();
  pad->SetGridx();
  pad->SetLogy();
  pad->SetFillColor(0);
    pad->SetRightMargin(0.01);
#if 0
  if (d == 3) { 
    pad->SetPad(pad->GetXlowNDC(), pad->GetYlowNDC(), .99, 
		 pad->GetYlowNDC()+pad->GetHNDC());
    pad->SetRightMargin(0.15);
  }
#endif

  corr->Draw("hist");

  TLatex* ltx = new TLatex(.95, .95, Form("FMD%d%c", d, r));
  ltx->SetNDC();
  ltx->SetTextAlign(33);
  ltx->SetTextSize(.08);
  ltx->Draw();

  return corr->GetMean();
}
void EMCDistribution(TString gain = "CALIB", bool log_scale = false)
{
  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      "EMCDistribution_" + gain + TString(log_scale ? "_Log" : "") + cuts, 1800,
      1000);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      p->SetLogy();
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(log_scale ? "_Log" : "");

      TH1 *h = NULL;

      if (log_scale)
        h = new TH1F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 300,
                     5e-3, 3096);
      else
        //            h = new TH1F(hname,
        //                Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 196,
        //                1900, 2096);
        h = new TH1F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 596,
                     -96, 500);

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);
      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);

      if (log_scale)
        QAHistManagerDef::useLogBins(h->GetXaxis());

      T->Draw(
          "TOWER_" + gain + "_CEMC[].get_energy_power_law_exp()>>" + hname,
          Form(
              "TOWER_%s_CEMC[].get_bineta()==%d && TOWER_%s_CEMC[].get_binphi()==%d",
              gain.Data(), ieta, gain.Data(), iphi),
          "");

      TText *t = new TText(.9, .9, Form("Col%d Row%d", ieta, iphi));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();

      //          return;
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
int CompareAllHistos(TString input1 = "../../QCD_ref.root", TString input2 = "../../QCD_filter.root", TString outdir="../plots/QCD/", TString leg1="no cut", TString leg2="jet filter", TString name="RelValQCD", bool MakeTotal=false) {
	
	gROOT->Reset();             
  //SetAtlasStyle();
  setTDRStyle();
  gStyle->SetPalette(1);
  gStyle->SetErrorX(0.5);
  gROOT->ProcessLine(".!mkdir -p "+outdir);
  gROOT->ProcessLine(".!mkdir -p "+outdir+"/pdf");
  gROOT->ProcessLine(".!mkdir -p "+outdir+"/png");

  
  TString Names[2] = { input1, input2};
  
//  TString outdir = "../plots/QCD/";
  const uint nFiles = 2;
  TFile * f[nFiles];  	

  
  std::stringstream indexes;
  for(uint iFile = 0; iFile < nFiles; iFile++)
  {
	indexes.str("");
  	indexes << Names[iFile];
  	
	std::string input_file=indexes.str();
	f[iFile] = TFile::Open(input_file.c_str());
	if(!f[iFile]) {
		std::cerr << "Error: file " << input_file << " could not be opened." << std::endl; 
    return 1;
	}
	else std::cout << "File " << input_file << " succesfully opened!" << std::endl;
  
  }
 // const uint nProfile12=8;
  const uint nProfile=4;
 // const uint nWP=3;
 // const uint n123=3;
  const uint n12=5;
  
  TString dirNames[1] = { "tauDifferenceAnalyzer"}; //"mmet_zh","mmmt_zh","mmme_zh","eett_zh","eemt_zh","eeet_zh","eeem_zh"};
 // TString profileNames_12[nProfile12] = {"pt_DM","eta_DM","vx_DM","phi_DM","pt_DMall","eta_DMall","vx_DMall","phi_DMall"};
  TString prefix_12 = "h_eff_id_";
  TString suffix_12[n12] = {"_DM","_DMall","_loose","_medium","_tight"};
  
  TString profileX[nProfile] = {"pt","eta","vx","phi"};
  const uint nTotal=nProfile*n12;
  //~ TString profile123_prefix="h_eff_id_";
  //~ TString profile123_WP[nWP]={"_loose","_medium","_tight"};
  //~ TString profile123_suffix[n123]={"","_2","_3"};
  //~ 
  TProfile* profileHist1[nTotal][nFiles];
// TProfile* profileHist2[nTotal][nFiles];
  
  //TProfile* profileHist[n123][nProfile*nWP][nFiles];
  //~ TProfile* profileHistB[nProfile*nWP][nFiles];
  //~ TProfile* profileHistC[nProfile*nWP][nFiles];
  //~ 
  
  
 // std::stringstream name;
 for(uint iFile = 0; iFile < nFiles; iFile++)
  {
	for(uint iSuff=0; iSuff < n12; iSuff++)
	{		
		for(uint iProf12=0; iProf12< nProfile; iProf12++)
		{
			profileHist1[iProf12+iSuff*nProfile][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+prefix_12+profileX[iProf12]+suffix_12[iSuff]));
		//	profileHist2[iProf12+iSuff*nProfile][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+prefix_12+profileX[iProf12]+suffix_12[iSuff]));
		}
	}
  }
  
  //~ for(uint iFile = 0; iFile < nFiles; iFile++)
  //~ {
	//~ for(uint iWP=0; iWP<nWP; iWP++)
		//~ {
			//~ for(uint iProf123=0; iProf123< nProfile; iProf123++)
			//~ {
				//~ for(uint i123=0; i123 < n123; i123++)
				//~ {
					//~ std::cout << dirNames[0]+"/"+profile123_prefix+profileX[iProf123]+profile123_WP[iWP]+profile123_suffix[i123] << std::endl;
					//~ profileHist[i123][iWP*nProfile+iProf123][iFile]=(TProfile*)f[iFile]->Get(TString(dirNames[0]+"/"+profile123_prefix+profileX[iProf123]+profile123_WP[iWP]+profile123_suffix[i123]));
				//~ }
			//~ }
		//~ }
  //~ }
  
  
  
  
  TCanvas *c1 = new TCanvas("c1","",5,30,1024,1024);
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);
  
  TPad* histPad = new TPad("histPad","histPad",0.01,0.25,0.99,0.99);
  histPad->SetBottomMargin(0.02);
  histPad->Draw();
  
  TPad* diffPad = new TPad("diffPad","diffPad",0.01,0.01,0.99,0.25);
  diffPad->SetBottomMargin(0.3);
  diffPad->SetTopMargin(0.0);
  diffPad->Draw();
  
  // plotting
  
	TString XTitle[4] = {"True P_{T} [GeV]","True #eta", "nVx","True #phi"};
   // c1->SetLogy();
	std::cout << "hej hola " << std::endl;
	for(uint iProf12=0; iProf12< nTotal; iProf12++)
	{
		 int title_id=iProf12%4;
		
		 if(title_id!=2){
			 profileHist1[iProf12][0]->Rebin(5);
			 profileHist1[iProf12][1]->Rebin(5);
		 }
	
		 TH1D* baseHist = (TH1D*)profileHist1[iProf12][0]->Clone();
		 TH1D* overHist = (TH1D*)profileHist1[iProf12][1]->Clone();
		 
		 if(MakeTotal && iProf12>7){ 
			 double binLow = baseHist->GetXaxis()->GetBinLowEdge(baseHist->GetXaxis()->GetFirst());
			 double binUp = baseHist->GetXaxis()->GetBinUpEdge(baseHist->GetXaxis()->GetLast());
			 int nBins = baseHist->GetXaxis()->GetNbins();
			 
			 TH1D* newBaseHist = new TH1D(TString(baseHist->GetName())+"TOT",baseHist->GetTitle(),nBins,binLow,binUp);
			 TH1D* newDMHist = new TH1D("newDMHist","",nBins,binLow,binUp);
			 TH1D* newOverHist = new TH1D(TString(overHist->GetName())+"TOTover",baseHist->GetTitle(),nBins,binLow,binUp);
			 TH1D* newDMHist2 = new TH1D("newDMHist2","",nBins,binLow,binUp);
			 
			 
			 for(int iBin=0; iBin <= baseHist->GetNbinsX(); iBin++)
			 {
				newBaseHist->SetBinContent(iBin,baseHist->GetBinContent(iBin));
				newBaseHist->SetBinError(iBin,baseHist->GetBinError(iBin));
				newDMHist->SetBinContent(iBin,profileHist1[title_id][0]->GetBinContent(iBin));
				newDMHist->SetBinError(iBin,profileHist1[title_id][0]->GetBinError(iBin));
				newOverHist->SetBinContent(iBin,overHist->GetBinContent(iBin));
				newOverHist->SetBinError(iBin,overHist->GetBinError(iBin));
				newDMHist2->SetBinContent(iBin,profileHist1[title_id][1]->GetBinContent(iBin));
				newDMHist2->SetBinError(iBin,profileHist1[title_id][1]->GetBinError(iBin));	
				
			 }
			 newBaseHist->Multiply(newDMHist);
			 newOverHist->Multiply(newDMHist2);
			 baseHist=newBaseHist;
			 overHist=newOverHist;
			 delete newDMHist;
			 delete newDMHist2;
		 }
	
		 if(title_id==0) baseHist->GetXaxis()->SetRangeUser(0,100);
		 baseHist->GetXaxis()->SetLabelOffset(0.1);		
		 baseHist->GetXaxis()->SetTitle(XTitle[title_id]);
		 baseHist->GetYaxis()->SetTitle("Fake rate");
		 baseHist->SetMarkerStyle(20);
		 baseHist->SetMarkerSize(2);
		 baseHist->SetLineWidth(2);
		 
		 overHist->SetMarkerColor(kRed);
		 overHist->SetMarkerStyle(25);
		 overHist->SetMarkerSize(2);
		 overHist->SetLineWidth(2);
		 overHist->SetLineStyle(2);
		 overHist->SetLineColor(kRed);
		
		 int binmax = baseHist->GetMaximumBin();
	     double max = 1.2*(baseHist->GetBinContent(binmax)+baseHist->GetBinError(binmax));
	     int binmax2 = overHist->GetMaximumBin();
	     double max2 = 1.2*(overHist->GetBinContent(binmax2)+overHist->GetBinError(binmax2));
	     max = max2 > max ? max2 : max;
	 
	     baseHist->SetMaximum(10.0);
	     baseHist->SetMinimum(1e-3);
	     
		 
		 histPad->cd();	
			 histPad->SetLogy();
		 baseHist->Draw();
		 overHist->Draw("same");	
		 
		TLegend* leg = new TLegend(0.8,0.80,0.9,0.9,NULL,"brNDC");
		leg->SetFillColor(0);
		leg->SetTextSize(0.035);
		leg->SetBorderSize(0);
		
		leg->AddEntry(baseHist, leg1, "lp");
		leg->AddEntry(overHist, leg2, "lp");
		
		leg->Draw();
		 //~ 
		 
    TString lumist="";
	TPaveText *ll = new TPaveText(0.15, 0.95, 0.95, 0.99, "NDC");
	ll->SetTextSize(0.03);
	ll->SetTextFont(62);
	ll->SetFillColor(0);
	ll->SetBorderSize(0);
	ll->SetMargin(0.01);
	ll->SetTextAlign(12); // align left
	TString text = name;
	ll->AddText(0.01,0.7,text);
	text = "#sqrt{s} = 13 TeV";
	text = text + lumist;
	//  ll->SetTextAlign(32); // align right
	ll->AddText(0.7, 0.5, text);
	ll->Draw("same");
	  
	
	c1->Update();
	
	TH1D* h_diff=(TH1D*)baseHist->Clone();
	h_diff->Divide(overHist);
	diffPad->cd();
	diffPad->SetGridy();
	diffPad->SetGridx();
	
	h_diff->GetYaxis()->SetLabelSize(0.1);
    h_diff->GetYaxis()->SetTitleOffset(0.55);
    h_diff->GetYaxis()->SetTitleSize(0.12);
    h_diff->GetYaxis()->SetTitle("Ratio");
    h_diff->GetXaxis()->SetLabelSize(0.12);
    h_diff->GetXaxis()->SetLabelOffset(0.01);
    h_diff->GetXaxis()->SetTitleSize(0.15);
	h_diff->GetYaxis()->SetNdivisions(509);
	h_diff->SetMinimum(0.9);
	h_diff->SetMaximum(1.1);
	
	h_diff->Draw("hist");
	c1->Print(outdir+"/pdf/"+profileHist1[iProf12][0]->GetName()+".pdf");
	c1->Print(outdir+"/png/"+profileHist1[iProf12][0]->GetName()+".png");
	
	
	}
  
  
	return 0;
}
Exemplo n.º 4
0
void plotDistribution( TChain* data , TChain *mc , TCut sel , TCut vtxweight , char* var , int nbins , float xmin , float xmax , char* xtitle , char* plottitle = "" , bool printplot = false , bool residual = false , bool log = false ){

  //--------------------------------------
  // define histograms and TGraphs
  //--------------------------------------

  TH1F* hdata      = new TH1F(Form("hdata_%i"     , iplot),Form("hdata_%i"    , iplot),nbins,xmin,xmax);
  TH1F* hmc        = new TH1F(Form("hmc_%i"       , iplot),Form("hmc_%i"      , iplot),nbins,xmin,xmax);
  TH1F* hmc_novtx  = new TH1F(Form("hmc_novtx_%i" , iplot),Form("hmc_novtx%i" , iplot),nbins,xmin,xmax);

  hdata->Sumw2();
  hmc->Sumw2();

  TGraphAsymmErrors* grdata = new TGraphAsymmErrors();
  TGraphAsymmErrors* grmc   = new TGraphAsymmErrors();

  TH1F* hdata_denom = new TH1F(Form("hdata_denom_%i",iplot),"",nbins,xmin,xmax);
  TH1F* hmc_denom   = new TH1F(Form("hmc_denom_%i"  ,iplot),"",nbins,xmin,xmax);

  //--------------------------------------
  // set up canvas and pads
  //--------------------------------------

  TCanvas *can = new TCanvas(Form("can_%i",iplot),Form("can_%i",iplot),600,600);
  can->cd();
  if( log ) gPad->SetLogy();

  TPad *mainpad = new TPad("mainpad","mainpad",0.0,0.0,1.0,0.8);

  if( residual ){
    mainpad->Draw();
    mainpad->cd();
    if( log ) mainpad->SetLogy();
  }

  //--------------------------------------
  // fill histos and TGraphs
  //--------------------------------------

  data->Draw(Form("min(%s,%f)>>hdata_%i"     , var,xmax-0.0001,iplot),sel);
  mc  ->Draw(Form("min(%s,%f)>>hmc_%i"       , var,xmax-0.0001,iplot),sel*vtxweight);
  mc  ->Draw(Form("min(%s,%f)>>hmc_novtx_%i" , var,xmax-0.0001,iplot),sel);

  for( int ibin = 1 ; ibin <= nbins ; ibin++ ){
    hdata_denom->SetBinContent(ibin,hdata->Integral());
    hmc_denom->SetBinContent(ibin,hmc->Integral());
  }

  grdata->BayesDivide(hdata,hdata_denom);
  grmc->BayesDivide(hmc_novtx,hmc_denom);

  //--------------------------------------
  // get efficiencies and errors
  //--------------------------------------

  /*
  float ndata1     = (float) hdata->GetBinContent(1);
  float ndata      = (float) hdata->Integral();
  float effdata    = 1-ndata1 / ndata;

  // TGraphAsymmErrors* grdata_temp = new TGraphAsymmErrors();
  // TH1F* hdata_num_temp = new TH1F(Form("hdata_num_temp_%i",iplot),"",1,0,1);
  // TH1F* hdata_den_temp = new TH1F(Form("hdata_den_temp_%i",iplot),"",1,0,1);
  // hdata_num_temp->SetBinContent(1,ndata-ndata1);
  // hdata_den_temp->SetBinContent(1,ndata);
  // grdata_temp->BayesDivide(hdata_num_temp,hdata_den_temp);

  //float effdataerr = sqrt(ndata1) / ndata;
  float effdataerr = 0.5 * ( grdata->GetErrorYlow(0) + grdata->GetErrorYhigh(0) );
  //float effdataerr = 0.5 * ( grdata_temp->GetErrorYlow(0) + grdata_temp->GetErrorYhigh(0) );

  float nmc1       = (float) hmc->GetBinContent(1);
  float nmc        = (float) hmc->Integral();
  float effmc      = 1-nmc1 / nmc;
  //float effmcerr   = hmc->GetBinError(1) / nmc;
  float effmcerr   = 0.5 * ( grmc->GetErrorYlow(0) + grmc->GetErrorYhigh(0) );


  float datatot = hdata->Integral();
  float mctot   = hmc->Integral();
  
  cout << endl;
  cout << plottitle << endl;

  cout << "Data eff  " << Form("%.2f +/- %.3f",effdata,effdataerr) << endl;
  cout << "MC   eff  " << Form("%.2f +/- %.3f",effmc  ,effmcerr)   << endl;
  cout << "Data/MC   " << Form("%.2f +/- %.2f",ratio  ,ratioerr)   << endl;
  */

  float ndata    = hdata->Integral();
  float ndata1   = hdata->Integral(2,20);
  float ndata2   = hdata->Integral(3,20);
  float ndata3   = hdata->Integral(4,20);
  float ndata4   = hdata->Integral(5,20);
  float ndata5   = hdata->Integral(6,20);

  float nmc      = hmc->Integral();
  float nmc1     = hmc->Integral(2,20);
  float nmc2     = hmc->Integral(3,20);
  float nmc3     = hmc->Integral(4,20);
  float nmc4     = hmc->Integral(5,20);
  float nmc5     = hmc->Integral(6,20);

  float effdata1 = ndata1/ndata;
  float effdata2 = ndata2/ndata;
  float effdata3 = ndata3/ndata;
  float effdata4 = ndata4/ndata;
  float effdata5 = ndata5/ndata;

  float effmc1   = nmc1/nmc;
  float effmc2   = nmc2/nmc;
  float effmc3   = nmc3/nmc;
  float effmc4   = nmc4/nmc;
  float effmc5   = nmc5/nmc;

  float effdata1err = getBinomialError(ndata1,ndata);
  float effdata2err = getBinomialError(ndata2,ndata);
  float effdata3err = getBinomialError(ndata3,ndata);
  float effdata4err = getBinomialError(ndata4,ndata);
  float effdata5err = getBinomialError(ndata5,ndata);

  float effmc1err   = getBinomialError(nmc1,nmc);
  float effmc2err   = getBinomialError(nmc2,nmc);
  float effmc3err   = getBinomialError(nmc3,nmc);
  float effmc4err   = getBinomialError(nmc4,nmc);
  float effmc5err   = getBinomialError(nmc5,nmc);

  float ratio1      = effdata1/effmc1;
  float ratio2      = effdata2/effmc2;
  float ratio3      = effdata3/effmc3;
  float ratio4      = effdata4/effmc4;
  float ratio5      = effdata5/effmc5;

  float ratio1err   = ratio1 * sqrt(pow(effdata1err/effdata1,2)+pow(effmc1err/effmc1,2));
  float ratio2err   = ratio2 * sqrt(pow(effdata2err/effdata2,2)+pow(effmc2err/effmc2,2));
  float ratio3err   = ratio3 * sqrt(pow(effdata3err/effdata3,2)+pow(effmc3err/effmc3,2));
  float ratio4err   = ratio4 * sqrt(pow(effdata4err/effdata4,2)+pow(effmc4err/effmc4,2));
  float ratio5err   = ratio5 * sqrt(pow(effdata5err/effdata5,2)+pow(effmc5err/effmc5,2));

  cout << endl << endl << plottitle << endl;

  int left = 20;


  // char* delimstart = "|";
  // char* delim      = "|";
  // char* delimend   = "|";
  // char* pm         = "+/-";

  char* delimstart = "";
  char* delim      = "&";
  char* delimend   = "\\\\";
  char* pm         = "$\\pm$";

  cout << delimstart << setw(10) << "" << setw(4)
       << delim << setw(left) << "$>$ 1 GeV" << setw(4)
       << delim << setw(left) << "$>$ 2 GeV" << setw(4)
       << delim << setw(left) << "$>$ 3 GeV" << setw(4) 
       << delim << setw(left) << "$>$ 4 GeV" << setw(4)
       << delim << setw(left) << "$>$ 5 GeV" << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "data" << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata1,pm,effdata1err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata2,pm,effdata2err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata3,pm,effdata3err) << setw(4) 
       << delim << setw(left) << Form("%.3f %s %.4f",effdata4,pm,effdata4err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effdata5,pm,effdata5err) << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "mc" << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc1,pm,effmc1err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc2,pm,effmc2err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc3,pm,effmc3err) << setw(4) 
       << delim << setw(left) << Form("%.3f %s %.4f",effmc4,pm,effmc4err) << setw(4)
       << delim << setw(left) << Form("%.3f %s %.4f",effmc5,pm,effmc5err) << setw(4) 
       << delimend << endl;

  cout << delimstart << setw(10) << "data/mc" << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio1,pm,ratio1err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio2,pm,ratio2err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio3,pm,ratio3err) << setw(4) 
       << delim << setw(left) << Form("%.2f %s %.2f",ratio4,pm,ratio4err) << setw(4)
       << delim << setw(left) << Form("%.2f %s %.2f",ratio5,pm,ratio5err) << setw(4) 
       << delimend << endl;

  //--------------------------------------
  // draw stuff
  //--------------------------------------

  hdata->Scale(1.0/hdata->Integral());
  hmc->Scale(1.0/hmc->Integral());

  if( log ) hmc->GetYaxis()->SetRangeUser(0.0001,5);  
  else      hmc->GetYaxis()->SetRangeUser(0.0,1);  

  hmc->GetXaxis()->SetTitle(xtitle);
  hmc->SetLineColor(2);
  hmc->SetMarkerColor(2);
  hmc->DrawNormalized("hist");
  hmc->DrawNormalized("sameE1");
  hdata->SetLineColor(4);
  hdata->SetMarkerColor(4);
  hdata->Draw("sameE1");

  grdata->SetLineColor(6);
  grmc->SetLineColor(7);
  //grdata->Draw("sameP");
  //grmc->Draw("sameP");

  TLegend *leg = new TLegend(0.6,0.7,0.8,0.9);
  leg->AddEntry(hdata , "data" , "lp");
  leg->AddEntry(hmc   , "MC"   , "lp");
  leg->SetBorderSize(0);
  leg->SetFillColor(0);			       
  leg->Draw();

  TLatex *t = new TLatex();
  t->SetNDC();

  if( TString(plottitle).Contains("el") ) t->DrawLatex(0.6,0.6,"electrons");
  if( TString(plottitle).Contains("mu") ) t->DrawLatex(0.6,0.6,"muons");

  if( TString(plottitle).Contains("0j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 0");
  if( TString(plottitle).Contains("1j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 1");
  if( TString(plottitle).Contains("2j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 2");
  if( TString(plottitle).Contains("3j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 3");
  if( TString(plottitle).Contains("4j") ) t->DrawLatex(0.6,0.5,"n_{jets} #geq 4");

  //--------------------------------------
  // draw residual plots
  //--------------------------------------

  if( residual ){
    can->cd();
  
    TPad *respad = new TPad("respad","respad",0.0,0.8,1.0,1.0);
    respad->Draw();
    respad->cd();
    respad->SetGridy();

    TH1F* hratio = (TH1F*) hdata->Clone(Form("hratio_%i",iplot));
    hratio->Divide(hmc);

    hratio->SetMarkerColor(1);
    hratio->SetLineColor(1);
    hratio->Draw();
    hratio->GetYaxis()->SetRangeUser(0.5,1.5);
    hratio->GetYaxis()->SetNdivisions(5);
    hratio->GetYaxis()->SetLabelSize(0.2);
    hratio->GetXaxis()->SetLabelSize(0.0);
  
    TLine line;
    line.DrawLine(xmin,1.0,xmax,1.0);
  }
  
  //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel+"tkisonew>20");
  //data->Scan("run:lumi:event:probe->pt():probe->eta():tkisonew:met:mt:njets:nbl:nbm",sel);

  if( printplot ) can->Print(Form("plots/%s.pdf",plottitle));

  iplot++;

  // TCanvas *c2 = new TCanvas();
  // c2->cd();
  // grdata->Draw("AP");

}
void makePlot(const TString& title, 
	      TGraphAsymmErrors* graph_Data_passed, TF1* fit_Data_passed, const TString& legendEntry_Data_passed,
	      TGraphAsymmErrors* graph_mcSum_passed, TF1* fit_mcSum_passed, const TString& legendEntry_mcSum_passed,
	      TGraphAsymmErrors* graph_Data_failed, TF1* fit_Data_failed, const TString& legendEntry_Data_failed,
	      TGraphAsymmErrors* graph_mcSum_failed, TF1* fit_mcSum_failed, const TString& legendEntry_mcSum_failed,
	      const TString& outputFileName)
{
  TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 900);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);
  canvas->SetLeftMargin(0.12);
  canvas->SetBottomMargin(0.12);

  //TPad* topPad = new TPad("topPad", "topPad", 0.00, 0.35, 1.00, 1.00);
  TPad* topPad = new TPad("topPad", "topPad", 0.00, 1.00 - 0.65*(0.93/0.84), 1.00, 1.00);
  topPad->SetFillColor(10);
  topPad->SetTopMargin(0.04);
  topPad->SetLeftMargin(0.15);
  //topPad->SetBottomMargin(0.03);
  topPad->SetBottomMargin(0.12);
  topPad->SetRightMargin(0.05);
  topPad->SetGridx();
  topPad->SetGridy();

  canvas->cd();
  topPad->Draw();
  topPad->cd();

  TH1* dummyHistogram_top = new TH1D("dummyHistogram_top", "dummyHistogram_top", 10, 0., 100.);
  dummyHistogram_top->SetTitle("");
  dummyHistogram_top->SetStats(false);
  dummyHistogram_top->SetMaximum(1.2);
  dummyHistogram_top->SetMinimum(0.);
  
  TAxis* xAxis_top = dummyHistogram_top->GetXaxis();
  xAxis_top->SetTitle("calo-E_{T}^{miss} / GeV");
  xAxis_top->SetTitleOffset(1.15);
  //xAxis_top->SetLabelColor(10);
  //xAxis_top->SetTitleColor(10);

  TAxis* yAxis_top = dummyHistogram_top->GetYaxis();
  yAxis_top->SetTitle("#varepsilon");
  yAxis_top->SetTitleOffset(1.2);

  dummyHistogram_top->Draw();
  //dummyHistogram_top->Draw("axis");

  //graph_Data_passed->SetLineColor(4);
  //graph_Data_passed->SetMarkerColor(4);
  //graph_Data_passed->SetMarkerStyle(20);
  //graph_Data_passed->Draw("p");

  //fit_Data_passed->SetLineColor(graph_Data_passed->GetLineColor());
  //fit_Data_passed->SetLineWidth(2);
  //fit_Data_passed->Draw("same");

  graph_mcSum_passed->SetLineColor(7);
  graph_mcSum_passed->SetMarkerColor(7);
  graph_mcSum_passed->SetMarkerStyle(24);
  graph_mcSum_passed->Draw("p");

  fit_mcSum_passed->SetLineColor(graph_mcSum_passed->GetLineColor());
  fit_mcSum_passed->SetLineWidth(2);
  fit_mcSum_passed->Draw("same");

  graph_Data_failed->SetLineColor(2);
  graph_Data_failed->SetMarkerColor(2);
  graph_Data_failed->SetMarkerStyle(21);
  //graph_Data_failed->Draw("p");

  fit_Data_failed->SetLineColor(graph_Data_failed->GetLineColor());
  fit_Data_failed->SetLineWidth(2);
  //fit_Data_failed->Draw("same");
 
  graph_mcSum_failed->SetLineColor(6);
  graph_mcSum_failed->SetMarkerColor(6);
  graph_mcSum_failed->SetMarkerStyle(25);
  graph_mcSum_failed->Draw("p");

  fit_mcSum_failed->SetLineColor(graph_mcSum_failed->GetLineColor());
  fit_mcSum_failed->SetLineWidth(2);
  fit_mcSum_failed->Draw("same");
 
  TLegend* legend = new TLegend(0.61, 0.16, 0.89, 0.47, "", "brNDC"); 
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  //legend->AddEntry(graph_Data_passed,  legendEntry_Data_passed.Data(),  "p");
  legend->AddEntry(graph_mcSum_passed, legendEntry_mcSum_passed.Data(), "p");
  //legend->AddEntry(graph_Data_failed,  legendEntry_Data_failed.Data(),  "p");
  legend->AddEntry(graph_mcSum_failed, legendEntry_mcSum_failed.Data(), "p");
  legend->Draw();

  TPaveText* label = 0;
  if ( title.Length() > 0 ) {
    label = new TPaveText(0.175, 0.89, 0.48, 0.94, "NDC");
    label->AddText(title.Data());
    label->SetTextAlign(13);
    label->SetTextSize(0.045);
    label->SetFillStyle(0);
    label->SetBorderSize(0);
    label->Draw();
  }

  TPad* bottomPad = new TPad("bottomPad", "bottomPad", 0.00, 0.00, 1.00, 0.35);
  bottomPad->SetFillColor(10);
  bottomPad->SetTopMargin(0.02);
  bottomPad->SetLeftMargin(0.15);
  bottomPad->SetBottomMargin(0.24);
  bottomPad->SetRightMargin(0.05);
  bottomPad->SetGridx();
  bottomPad->SetGridy();

  canvas->cd();
  bottomPad->Draw();
  bottomPad->cd();

  TH1* dummyHistogram_bottom = new TH1D("dummyHistogram_bottom", "dummyHistogram_bottom", 10, 0., 100.);
  
  dummyHistogram_bottom->SetMinimum(-1.0);
  dummyHistogram_bottom->SetMaximum(+1.0);

  TAxis* xAxis_bottom = dummyHistogram_bottom->GetXaxis();
  xAxis_bottom->SetTitle("calo-E_{T}^{miss} / GeV");
  xAxis_bottom->SetTitleOffset(1.20);
  xAxis_bottom->SetLabelColor(1);
  xAxis_bottom->SetTitleColor(1);
  xAxis_bottom->SetTitleSize(0.08);
  xAxis_bottom->SetLabelOffset(0.02);
  xAxis_bottom->SetLabelSize(0.08);
  xAxis_bottom->SetTickLength(0.055);

  TAxis* yAxis_bottom = dummyHistogram_bottom->GetYaxis();
  yAxis_bottom->SetTitle("#frac{Data-Simulation}{Simulation}");
  yAxis_bottom->SetTitleOffset(0.85);
  yAxis_bottom->SetNdivisions(505);
  yAxis_bottom->CenterTitle();
  yAxis_bottom->SetTitleSize(0.08);
  yAxis_bottom->SetLabelSize(0.08);
  yAxis_bottom->SetTickLength(0.04);

  dummyHistogram_bottom->SetTitle("");
  dummyHistogram_bottom->SetStats(false);
  dummyHistogram_bottom->Draw("axis");
 
  TGraphAsymmErrors* graph_Data_div_mc_passed = makeGraph_data_div_mc(graph_Data_passed, graph_mcSum_passed);
  graph_Data_div_mc_passed->SetLineColor(graph_Data_passed->GetLineColor());
  graph_Data_div_mc_passed->SetMarkerColor(graph_Data_passed->GetMarkerColor());
  graph_Data_div_mc_passed->SetMarkerStyle(graph_Data_passed->GetMarkerStyle());
  graph_Data_div_mc_passed->Draw("p");
  
  TF1* fit_Data_div_mc_passed = 
    new TF1("fit_Data_div_mc_passed", &integralCrystalBall_f_div_f, 
	    fit_mcSum_passed->GetMinimumX(), fit_mcSum_passed->GetMaximumX(), 2*fit_mcSum_passed->GetNpar());
  for ( int iPar = 0; iPar < fit_mcSum_passed->GetNpar(); ++iPar ) {
    fit_Data_div_mc_passed->SetParameter(iPar, fit_Data_passed->GetParameter(iPar));
    fit_Data_div_mc_passed->SetParameter(iPar + fit_mcSum_passed->GetNpar(), fit_mcSum_passed->GetParameter(iPar));
  }
  fit_Data_div_mc_passed->SetLineColor(graph_Data_div_mc_passed->GetLineColor());
  fit_Data_div_mc_passed->SetLineWidth(2);
  fit_Data_div_mc_passed->Draw("same");

  TGraphAsymmErrors* graph_Data_div_mc_failed = makeGraph_data_div_mc(graph_Data_failed, graph_mcSum_failed);
  graph_Data_div_mc_failed->SetLineColor(graph_Data_failed->GetLineColor());
  graph_Data_div_mc_failed->SetMarkerColor(graph_Data_failed->GetMarkerColor());
  graph_Data_div_mc_failed->SetMarkerStyle(graph_Data_failed->GetMarkerStyle());
  graph_Data_div_mc_failed->Draw("p");
  
  TF1* fit_Data_div_mc_failed = 
    new TF1("fit_Data_div_mc_failed", &integralCrystalBall_f_div_f, 
	    fit_mcSum_failed->GetMinimumX(), fit_mcSum_failed->GetMaximumX(), 2*fit_mcSum_failed->GetNpar());
  for ( int iPar = 0; iPar < fit_mcSum_failed->GetNpar(); ++iPar ) {
    fit_Data_div_mc_failed->SetParameter(iPar, fit_Data_failed->GetParameter(iPar));
    fit_Data_div_mc_failed->SetParameter(iPar + fit_mcSum_failed->GetNpar(), fit_mcSum_failed->GetParameter(iPar));
  }
  fit_Data_div_mc_failed->SetLineColor(graph_Data_div_mc_failed->GetLineColor());
  fit_Data_div_mc_failed->SetLineWidth(2);
  fit_Data_div_mc_failed->Draw("same");

  topPad->RedrawAxis();
  bottomPad->RedrawAxis();

  canvas->Update();
  size_t idx = outputFileName.Last('.');
  std::string outputFileName_plot = std::string(outputFileName.Data(), 0, idx);
  if ( idx != std::string::npos ) canvas->Print(std::string(outputFileName_plot).append(std::string(outputFileName.Data(), idx)).data());
  //canvas->Print(std::string(outputFileName_plot).append(".png").data());
  //canvas->Print(std::string(outputFileName_plot).append(".pdf").data());
  topPad->Print(std::string(outputFileName_plot).append(".png").data());
  topPad->Print(std::string(outputFileName_plot).append(".pdf").data());

  delete legend;
  delete label;
  delete dummyHistogram_top;
  delete topPad;
  delete dummyHistogram_bottom;
  delete bottomPad;
  delete canvas;
}
//################################################################################################################################
TCanvas *drawRatioPlotWithPurity(TH1D *prediction, TH1D *sr, TString xTitle, TString filename, double purity, bool LowECaloRegion){
  
  TCanvas *c = new TCanvas("c"+filename,"c",0,0,500,500);
  c->cd();
  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);

  TH1D *ratio = 0;

  ratio = (TH1D*) sr->Clone();
  ratio->Divide(prediction);
  ratio->GetYaxis()->SetTitle((TString) sr->GetName() + "/" + (TString) prediction->GetName());
  ratio->SetTitle("");
  ratio->SetLabelSize(0.1,"X");
  ratio->SetLabelSize(0.1,"Y");
  ratio->SetTitleOffset(0.5,"Y");
  ratio->SetTitleSize(0.11,"Y");
  ratio->SetLineColor(kBlack);
  ratio->SetMarkerColor(kBlack);


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

  // 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.8,0.85,0.9);
  leg->AddEntry(sr,sr->GetName(),"l"); 
  leg->AddEntry(prediction,prediction->GetName(),"pel"); 
  pad1->cd();
  //pad1->SetLogy();

  sr->SetLineColor(kRed);
  sr->SetMarkerColor(kRed);
  prediction->SetLineColor(kBlack);
  prediction->SetMarkerColor(kBlack);
  sr->SetTitle("");
  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);

  prediction->Draw("e");
  sr->Draw("e same");

  double maximum =prediction->GetMaximum()*1.2;
  double minimum = 0.00001;
  if(sr->GetMinimum()!=0) minimum=sr->GetMinimum()*0.9;
  if(prediction->GetMinimum()!=0) minimum=prediction->GetMinimum()*0.9;
  if(sr->GetMaximum()>prediction->GetMaximum()){

    maximum=sr->GetMaximum()*1.2;
  }



  //leg->Draw("same");


  //***********************
  TLatex*  info   = new TLatex();
  info->SetTextFont(132);
  info-> SetNDC();
  info->SetTextSize(0.06);
  TString AuxString = Form("Purity of fakes in CR = %4.1f ",purity*100);
  //info->DrawLatex(0.4,0.7,AuxString);

  TLatex*  info1   = new TLatex();
  info1->SetTextFont(132);
  info1-> SetNDC();
  info1->SetTextSize(0.06);
  if(LowECaloRegion) AuxString = "E_{calo}<10GeV";
  else               AuxString = "E_{calo}>10GeV"; 
  //info1->DrawLatex(0.2,0.82,AuxString);
  //***********************

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

  c->SaveAs(filename);

  return c;

}
Exemplo n.º 7
0
makeLTauStack(TString name,TString file,TString dir,int s,TString labelX,TString units = "GeV",bool left=false,TString channel = "",bool log = false,bool dndm=false,bool doRatio = false)
{
  setStyle();

  float xR=0.45;
  if(left)
    xR=0.2;


  if(doRatio){
  	TCanvas * c = new TCanvas(name,name,600,600);
  }
  else{
  	TCanvas * c = new TCanvas(name,name,600,600);
    c->SetLeftMargin     (0.18);
    c->SetRightMargin    (0.05);
    c->SetTopMargin      (0.08);
    c->SetBottomMargin   (0.15);
  }



  c->cd();
  
  if(doRatio){
  	TPad * plotPad = new TPad("pad1","",0.0,0.3,1.0,1.0);
  	plotPad->SetLeftMargin  (0.18);
    plotPad->SetTopMargin   (0.10);
    plotPad->SetRightMargin (0.07);
    plotPad->SetBottomMargin(0.03); 
    TPad * ratioPad = new TPad("pad2","",0.0,0.0,1.0,0.3);
    ratioPad->SetLeftMargin  (0.18);
    ratioPad->SetTopMargin   (0.00);
    ratioPad->SetRightMargin (0.07);
    ratioPad->SetBottomMargin(0.30);
    ratioPad->SetGridy(1);
  }
  else{
  	TPad * plotPad = new TPad("pad1","",0.0,0.0,1.0,1.0);
  	plotPad->SetLeftMargin     (0.18);
    plotPad->SetRightMargin    (0.05);
    plotPad->SetTopMargin      (0.08);
    plotPad->SetBottomMargin   (0.15);
  }
  
  plotPad->Draw();
  plotPad->cd();
  
  
  TFile *f = new TFile(file);


  TH1F * data = (TH1F*)(f->Get(dir+"/data_obs"));
  if (dndm) convertToDNDM(data);

  applyDATAStyle(data);

  TH1F * QCD = (TH1F*)(f->Get(dir+"/QCD"));
  if (dndm) convertToDNDM(QCD);

  applyStyle(QCD,kMagenta-10,1,1001);

  TH1F * ttbar = (TH1F*)(f->Get(dir+"/TT"));
  if (dndm) convertToDNDM(ttbar);
  applyStyle(ttbar,kBlue-8,1,1001);

	if(channel == "#tau_{e}#tau_{h}"){
	
	  TH1F * EWK = (TH1F*)(f->Get(dir+"/W"));
	  EWK->Add((TH1F*)(f->Get(dir+"/VV")));
	  if (dndm) convertToDNDM(EWK);
	  applyStyle(EWK,kRed+2,1,1001);
	  	
	  if(f->Get(dir+"/ZL")!=0)
		TH1F * ZEE = (TH1F*)(f->Get(dir+"/ZL"));
	  if(f->Get(dir+"/ZJ")!=0)
		ZEE->Add((TH1F*)(f->Get(dir+"/ZJ")));
	  if(f->Get(dir+"/ZLL")!=0)
		TH1F * ZEE = (TH1F*)(f->Get(dir+"/ZLL")));
	  if (dndm) convertToDNDM(ZEE);
	  applyStyle(ZEE,kAzure+2,1,1001);	
	  
	}
void trisCheckCorrection_unbinnedfit(Char_t* EBEE = 0,
                         Int_t evtsPerPoint = 0,
                         float laserCorrMin = -1.,
                         float laserCorrMax = -1.)
{
  // Set style options
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(1); 
  
  
  
  // Check qualifiers
  if ( strcmp(EBEE,"EB")!=0 && strcmp(EBEE,"EE")!=0 )
  {
    std::cout << "CHK-STB Error: unknown partition " << EBEE << std::endl;
    std::cout << "CHK-STB Select either EB or EE ! " << std::endl;
    return;
  }
  
  if ( strcmp(EBEE,"EB") == 0 )
  {
    lcMin = 0.99;
    lcMax = 1.05;
  }
  else
  {
    lcMin = 0.99;
    lcMax = 1.11;
  }
  
  if( (laserCorrMin != -1.) && (laserCorrMax != -1.) )
  {
    lcMin = laserCorrMin;
    lcMax = laserCorrMax;
  }
  
  
  
  // Get trees
  std::cout << std::endl;
  
  TChain* ntu_DA = new TChain("ntu");
  FillChain(ntu_DA,"inputDATA.txt");
  std::cout << "     DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_MC = new TChain("ntu");
  FillChain(ntu_MC,"inputMC.txt");
  std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  if (ntu_DA->GetEntries() == 0 || ntu_MC->GetEntries() == 0 )
  {
    std::cout << "CHK-STB Error: At least one file is empty" << std::endl; 
    return;
  }  
  
  
  
  // Set branch addresses
  int runId;
  int isW, isZ;
  int timeStampHigh;
  float seedLaserAlpha;
  float avgLaserCorrection, scCrackCorrection;
  float EoP;
  float scE, scERaw, scEta, scEtaWidth, scPhiWidth;
  int seedIeta,seedIphi;
  int seedIx,seedIy,seedZside;
  float esE;
  float seedLaserCorrection;
  int iPhi,iEta;
  
  ntu_DA->SetBranchAddress("runId", &runId);  
  ntu_DA->SetBranchAddress("isW", &isW);
  //ntu_DA->SetBranchAddress("isZ", &isZ);
  ntu_DA->SetBranchAddress("timeStampHigh", &timeStampHigh);
  ntu_DA->SetBranchAddress("ele1_scCrackCorr", &scCrackCorrection);
  ntu_DA->SetBranchAddress("ele1_scLaserCorr", &avgLaserCorrection);
  ntu_DA->SetBranchAddress("ele1_seedLaserCorr", &seedLaserCorrection);
  ntu_DA->SetBranchAddress("ele1_seedLaserAlpha", &seedLaserAlpha);
  ntu_DA->SetBranchAddress("ele1_es", &esE);
  ntu_DA->SetBranchAddress("ele1_scE", &scE);
  ntu_DA->SetBranchAddress("ele1_scERaw", &scERaw);
  ntu_DA->SetBranchAddress("ele1_scEta", &scEta);
  ntu_DA->SetBranchAddress("ele1_scEtaWidth", &scEtaWidth);
  ntu_DA->SetBranchAddress("ele1_scPhiWidth", &scPhiWidth);
  ntu_DA->SetBranchAddress("ele1_EOverP", &EoP);
  ntu_DA->SetBranchAddress("ele1_seedIphi", &iPhi);
  ntu_DA->SetBranchAddress("ele1_seedIeta", &iEta);
  ntu_DA->SetBranchAddress("ele1_seedIeta",       &seedIeta);
  ntu_DA->SetBranchAddress("ele1_seedIphi",       &seedIphi);
  ntu_DA->SetBranchAddress("ele1_seedIx",         &seedIx);
  ntu_DA->SetBranchAddress("ele1_seedIy",         &seedIy);
  ntu_DA->SetBranchAddress("ele1_seedZside",      &seedZside);
  
  ntu_MC->SetBranchAddress("isW", &isW);
  ntu_MC->SetBranchAddress("isZ", &isZ);
  ntu_MC->SetBranchAddress("ele1_scEta", &scEta);
  ntu_MC->SetBranchAddress("ele1_EOverP", &EoP);
  
  

  float params[42];
  InitializeParams(params);
  
  
  // Build the reference from 'infile2'
  std::cout << std::endl;
  std::cout << "***** Build reference for " << EBEE << " *****" << std::endl;
  
  templateHisto = new TH1F("templateHisto", "", 1200, 0., 5.);

  for(int ientry = 0; ientry < ntu_MC->GetEntries(); ++ientry)
  {
    if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << std::endl;
    ntu_MC->GetEntry(ientry);
    
    if (strcmp(EBEE,"EB")==0 && fabs(scEta) > 1.4442) continue;                       // barrel
    if (strcmp(EBEE,"EE")==0 && (fabs(scEta) < 1.56 || fabs(scEta) > 2.5 )) continue; // endcap
    
    //if( seedLaserAlpha > 1.5 ) continue;
        
    //if( fabs(scEta) > 0.44 ) continue;
    //if( fabs(scEta) < 0.44 || fabs(scEta) > 0.77 ) continue;
    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.10 ) continue;
    //if( fabs(scEta) < 1.10 || fabs(scEta) > 1.56 ) continue;
    //if( fabs(scEta) < 1.56 || fabs(scEta) > 2.00 ) continue;
    //if( fabs(scEta) < 2.00 ) continue;
        
    templateHisto -> Fill(EoP);
  }

  int rebin = 4;
  if (strcmp(EBEE,"EB")==0) rebin = 2;
  templateHisto -> Rebin(rebin);  
  FitTemplate();
  
  std::cout << "Reference built for " << EBEE << " - " << templateHisto->GetEntries() << " events" << std::endl;
  
  
  
  // Loop and sort events
  std::cout << std::endl;
  std::cout << "***** Sort events and define bins *****" << std::endl;
  
  int nEntries = ntu_DA -> GetEntriesFast(); 
  int nSavePts = 0; 
  std::vector<bool> isSavedEntries(nEntries);
  std::vector<SorterLC> sortedEntries;
  
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    ntu_DA -> GetEntry(ientry); 
    isSavedEntries.at(ientry) = false;
    
    // save only what is needed for the analysis!!!
    if (strcmp(EBEE,"EB")==0 && fabs(scEta) > 1.4442) continue;                       // barrel
    if (strcmp(EBEE,"EE")==0 && (fabs(scEta) < 1.56 || fabs(scEta) > 2.5 )) continue; // endcap
    
    //if( fabs(scEta) > 0.44 ) continue;
    //if( fabs(scEta) < 0.44 || fabs(scEta) > 0.77 ) continue;
    //if( fabs(scEta) < 0.77 || fabs(scEta) > 1.10 ) continue;
    //if( fabs(scEta) < 1.10 || fabs(scEta) > 1.56 ) continue;
    //if( fabs(scEta) < 1.56 || fabs(scEta) > 2.00 ) continue;
    //if( fabs(scEta) < 2.00 ) continue;
    
        
    if( seedLaserCorrection <= 1.) continue;   
    if( seedLaserAlpha < 1.5 ) continue;
    //if( timeStampHigh > 1303862400 ) continue;
    
    if( seedZside < 0 )
      if( (seedIx > 20 ) && (seedIx < 50) && (seedIy > 85) && (seedIy < 92) ) continue;
    if( seedZside == -1 )
      if( (seedIx > 35 ) && (seedIx < 55) && (seedIy > 80) && (seedIy < 87) ) continue;
    if( seedZside > 0 )
      if( (seedIx > 65 ) && (seedIx < 77) && (seedIy > 33) && (seedIy < 57) ) continue;
    if( seedZside > 0 )
      if( (seedIx > 75 ) && (seedIx < 93) && (seedIy > 18) && (seedIy < 37) ) continue;    
    
    //if ( runId < 163045 ) continue;
    //if ( runId >= 163232 ) continue;
    //if ( runId < 163232 ) continue;
    
    
    //*********************** CLUSTER CORR *****************************
    //if( (ientry%1 == 0) ) std::cout << "\n\n\nreading entry " << ientry << std::endl;    
    //Ediff -> Fill( ( (scCrackCorrection*fClusterCorrections(scERaw+esE,scEta,scPhiWidth/scEtaWidth,params))-scE)/scE );
    //Ediff_vsEta -> Fill( scEta, ( (esE+scCrackCorrection*fClusterCorrections(scERaw,scEta,scPhiWidth/scEtaWidth,params))-scE)/scE );
    //if( fabs(fClusterCorrections(scERaw,scEta,scPhiWidth/scEtaWidth,params)-scE) > 0.001 )
    //{
    //  std::cout << "\n\n" << std::endl;
    //  std::cout << "scEta = " << scEta << "   scE = " << scE << "   scERaw = " << scERaw << std::endl;
    //  std::cout << "scERaw_corr = " << fClusterCorrections(scERaw,scEta,scPhiWidth/scEtaWidth,params) << std::endl;
    //}
    //*********************** CLUSTER CORR *****************************
        
    isSavedEntries.at(ientry) = true;
    
    SorterLC dummy;
    dummy.laserCorr = avgLaserCorrection;
    dummy.entry = ientry;
    sortedEntries.push_back(dummy);
    
    nSavePts++; 
  }
  std::sort(sortedEntries.begin(),sortedEntries.end(),SorterLC());
  std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl;
  
  //TCanvas* c_diff = new TCanvas("c_diff","c_diff");
  //c_diff -> cd();
  //Ediff -> Draw();
  //
  //TCanvas* c_diff_vsEta = new TCanvas("c_diff_vsEta","c_diff");
  //c_diff_vsEta -> cd();
  //Ediff_vsEta -> Draw("colz");
  
  // bins with evtsPerPoint events per bin
  int nBins = std::max(1,int(nSavePts/evtsPerPoint));
  int nBinPts = int( nSavePts/nBins );
  int nBinTempPts = 0;
  
  std::vector<int> binEntryMax;
  binEntryMax.push_back(0);
  for(int iSaved = 0; iSaved < nSavePts; ++iSaved)
  {
    ++nBinTempPts;
    
    if( nBinTempPts == nBinPts )
    {
      binEntryMax.push_back( iSaved );      
      nBinTempPts = 0;
    }
  }
  binEntryMax.at(nBins) = nSavePts;
  
  std::cout << "nBins = " << nBins << std::endl;
  for(int bin = 0; bin < nBins; ++bin)
    std::cout << "bin: " << bin
              << "   entry min: " << setw(6) << binEntryMax.at(bin)
              << "   entry max: " << setw(6) << binEntryMax.at(bin+1)
              << "   events: "    << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin)
              << std::endl;
  TVirtualFitter::SetDefaultFitter("Fumili2");
  
  
  
  // histogram definition
  
  TH1F* h_EoP_spread;
  TH1F* h_EoC_spread;
  TH2F* h_LC_map = new TH2F("h_LC_map","",360,0.,360,170,-85,85);
  
  if ( strcmp(EBEE,"EB")==0 )
  {  
    h_EoP_spread = new TH1F("h_EoP_spread","",100,0.95,1.01);
    h_EoC_spread = new TH1F("h_EoC_spread","",100,0.95,1.01);    
  }
  else 
  {  
    h_EoP_spread = new TH1F("h_EoP_spread","",100,0.91,1.03);
    h_EoC_spread = new TH1F("h_EoC_spread","",100,0.91,1.03);    
  }
  
  h_EoP_spread -> SetLineColor(kRed+2);
  h_EoP_spread -> SetLineWidth(2);
  h_EoP_spread -> GetXaxis() -> SetTitle("Relative E/p scale");

  h_EoC_spread -> SetLineColor(kGreen+2);
  h_EoC_spread -> SetLineWidth(2);
  h_EoC_spread -> GetXaxis() -> SetTitle("Relative E/p scale");  
  
  
  TH1F** h_EoP = new TH1F*[nBins];
  TH1F** h_EoC = new TH1F*[nBins];
  TH1F** h_Las = new TH1F*[nBins];

  for(int i = 0; i < nBins; ++i)
  {
    char histoName[80];
    
    sprintf(histoName, "EoP_%d", i);
    h_EoP[i] = new TH1F(histoName, histoName, 1200, 0., 3.);
    h_EoP[i] -> SetFillColor(kRed+2);
    h_EoP[i] -> SetFillStyle(3004);
    h_EoP[i] -> SetMarkerStyle(7);
    h_EoP[i] -> SetMarkerColor(kRed+2); 
    h_EoP[i] -> SetLineColor(kRed+2); 
    
    sprintf(histoName, "EoC_%d", i);
    h_EoC[i] = new TH1F(histoName, histoName, 1200, 0., 3.);
    h_EoC[i] -> SetFillColor(kGreen+2);
    h_EoC[i] -> SetFillStyle(3004);
    h_EoC[i] -> SetMarkerStyle(7);
    h_EoC[i] -> SetMarkerColor(kGreen+2);
    h_EoC[i] -> SetLineColor(kGreen+2);
    
    sprintf(histoName, "Las_%d", i);
    h_Las[i] = new TH1F(histoName, histoName, 100, 0.5, 1.5);
  }
  
  
  // data definition
  std::vector< std::vector<double>* > dataEoP;
  std::vector< std::vector<double>* > dataEoC;
  
  for (int jbin = 0; jbin< nBins; jbin++){
    dataEoP.push_back(new std::vector<double>);
    dataEoC.push_back(new std::vector<double>);
  }


  // function definition
  TF1** f_EoP = new TF1*[nBins];
  TF1** f_EoC = new TF1*[nBins];
  
  
    
  // loop on the saved and sorted events
  std::cout << std::endl;
  std::cout << "***** Fill and fit histograms *****" << std::endl;

  
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    if( (ientry%10000 == 0) ) std::cout << "reading entry " << ientry << std::endl;
    
    if( isSavedEntries.at(ientry) == false ) continue;
    
    int iSaved = -1;
    for(iSaved = 0; iSaved < nSavePts; ++iSaved)
      if( ientry == sortedEntries[iSaved].entry ) break;
    
    int bin = -1;
    for(bin = 0; bin < nBins; ++bin)
      if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) )
        break;
    
    //std::cout << "ientry = " << ientry << "   iSaved: " << iSaved << "   bin: " << bin << std::endl;
    
    ntu_DA->GetEntry(ientry);
    
    float scale = 1.;
    //scale = sqrt( pow(avgLaserCorrection,((1.52-0.7843)/1.52)-1.) );
    //scale = 1. / (0.1811 + 0.7843*avgLaserCorrection);
    
        
    //// fill the bins 
    (h_Las[bin]) -> Fill(avgLaserCorrection);
    (h_EoP[bin]) -> Fill(EoP/avgLaserCorrection);
    (h_EoC[bin]) -> Fill(EoP * scale);
    h_LC_map->Fill(iPhi,iEta,seedLaserCorrection);

    // fill te vectors data E/p 
    dataEoP[bin]->push_back(EoP/avgLaserCorrection);
    dataEoC[bin]->push_back(EoP);

  }
  

  // Define graph and histograms
  TGraphAsymmErrors* g_fit   = new TGraphAsymmErrors();
  TGraphAsymmErrors* g_c_fit   = new TGraphAsymmErrors();
  
  
  
  // define the fitting function
  // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )
  histoFunc* templateHistoFunc = new histoFunc(templateHisto);
   
  //templateFunc = new TF1("templateFunc", templateHistoFunc, 0., 5., 3, "histoFunc");
  //templateFunc -> SetParName(0,"Norm"); 
  //templateFunc -> SetParName(1,"Scale factor"); 
  //templateFunc -> SetLineWidth(1); 
  //templateFunc -> SetNpx(10000);
  //templateFunc -> SetParameter(0, 1 );
  //templateFunc -> SetParameter(1, 1);
  //templateFunc -> FixParameter(2, 0.);
  //templateFunc -> FixParameter(0, 1./templateFunc ->Integral(0.,5.) ); // normalized to 1. BUT will be renormalized to 1 at each iteration!
  
  TFitterMinuit* myfit = new TFitterMinuit(1);
  myfit->SetFCN(mylike);
  myfit->SetPrintLevel(-1);
  
  
  
  for(int i = 0; i < nBins; ++i)
  {
    h_EoP[i] -> Rebin(rebin*4);    
    h_EoC[i] -> Rebin(rebin*4);    
    
    
    //------------------------------------
    // Fill the graph for uncorrected data
    
    // fit uncorrected data
    mydata = dataEoP.at(i);
    
    myfit->Clear();
    myfit->SetParameter(0, "scale", 1.,0.0005,0.50,1.50);
    
    double arglist[2];
    arglist[0] = 10000; // Max number of function calls
    arglist[1] = 1e-5;  // Tolerance on likelihood ?????????

    int fStatus = myfit->ExecuteCommand("MIGRAD",arglist,2); 
    
    double amin,edm,errdef;
    int nvpar,nparx;
    myfit->GetStats(amin, edm, errdef, nvpar, nparx);
    double bestScale = myfit->GetParameter(0);
    double eee       = myfit->GetParError(0);
    
    char funcName[50];
    sprintf(funcName,"f_EoP_%d",i);
    f_EoP[i] = (TF1*)(templateFunc->Clone());
    f_EoP[i] -> SetParameter(0,h_EoP[i]->GetEntries());
    f_EoP[i] -> SetParameter(7,1.5);
    f_EoP[i] -> SetParName(0,"Norm"); 
    f_EoP[i] -> SetParName(1,"Scale factor"); 
    f_EoP[i] -> SetLineWidth(1); 
    f_EoP[i] -> SetNpx(10000);
    
    double xNorm = h_EoP[i]->GetEntries()/templateHisto->GetEntries() *
                   h_EoP[i]->GetBinWidth(1)/templateHisto->GetBinWidth(1); 
    
    //f_EoP[i] -> FixParameter(0, xNorm);
    //f_EoP[i] -> SetParameter(1, bestScale);
    //f_EoP[i] -> FixParameter(2, 0.);
    f_EoP[i] -> SetLineColor(kRed+2); 
    
    // Fill the graph
    if( fStatus == 0 && eee > 0. )
    {
      g_fit -> SetPoint(i,  h_Las[i]->GetMean() , 1./bestScale);
      g_fit -> SetPointError(i, h_Las[i]->GetRMS(), h_Las[i]->GetRMS(), eee, eee);
      h_EoP_spread -> Fill(1./bestScale);
    }
    else
      std::cout << "Fitting uncorrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << endl;
    
    
    
    //----------------------------------
    // Fill the graph for corrected data

    // fit uncorrected data
    
    mydata = dataEoC.at(i);
    
    myfit->Clear();
    myfit->SetParameter(0, "scale", 1.,0.0005,0.50,1.50);
    
    arglist[0] = 10000; // Max number of function calls
    arglist[1] = 1e-5;  // Tolerance on likelihood ?????????

    fStatus = myfit->ExecuteCommand("MIGRAD",arglist,2); 
    
    myfit->GetStats(amin, edm, errdef, nvpar, nparx);
    bestScale = myfit->GetParameter(0);
    eee       = myfit->GetParError(0);    
    
    
    sprintf(funcName,"f_EoC_%d",i);
    f_EoC[i] = (TF1*)(templateFunc->Clone());
    f_EoC[i] -> SetParameter(0,h_EoC[i]->GetEntries());
    f_EoC[i] -> SetParameter(7,bestScale);
    f_EoC[i] -> SetParName(0,"Norm"); 
    f_EoC[i] -> SetParName(1,"Scale factor"); 
    f_EoC[i] -> SetLineWidth(1); 
    f_EoC[i] -> SetNpx(10000);

    xNorm = h_EoC[i]->GetEntries()/templateHisto->GetEntries() *
            h_EoC[i]->GetBinWidth(1)/templateHisto->GetBinWidth(1); 
    //
    //f_EoC[i] -> SetParameter(1, bestScale);
    //f_EoC[i] -> FixParameter(2, 0.);
    f_EoC[i] -> SetLineColor(kGreen+2); 

    // fill the graph
    if( fStatus == 0 && eee > 0. )
    {        
      g_c_fit -> SetPoint(i,  h_Las[i]->GetMean() , 1./bestScale);
      g_c_fit -> SetPointError(i, h_Las[i]->GetRMS() , h_Las[i]->GetRMS() , eee, eee);
      h_EoC_spread -> Fill(1./bestScale);
    }
    else 
      std::cout << "Fitting corrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << endl;
    
    
    
  }
  
  TF1* pol0 = new TF1("pol0","pol0");
  pol0 -> SetLineColor(kGreen+2);
  pol0 -> SetLineWidth(3);
  pol0 -> SetLineStyle(2);
  g_c_fit -> Fit("pol0","Q+");
  
  
  // Drawings
  TPaveStats** s_EoP = new TPaveStats*[nBins];
  TPaveStats** s_EoC = new TPaveStats*[nBins];
  
  TCanvas *c1[100]; 
  for(int i = 0; i < nBins; ++i)
  {
    char canvasName[50];
    if (i%2==0) {
      sprintf(canvasName, "Fits-%0d", i/2); 
      c1[i/2] = new TCanvas(canvasName, canvasName);
      c1[i/2] -> Divide(2,1);
    }
    c1[i/2] -> cd (i%2+1);

    h_EoP[i] -> GetXaxis() -> SetTitle("E/p");  
    h_EoP[i] -> GetXaxis() -> SetRangeUser(0.5,1.5); 
    h_EoP[i] -> Draw("e");
    gPad->Update();
    s_EoP[i]= (TPaveStats*)(h_EoP[i]->GetListOfFunctions()->FindObject("stats"));
    s_EoP[i]->SetTextColor(kRed+2);

    h_EoC[i] -> Draw("esames");
    gPad->Update(); 
    s_EoC[i]= (TPaveStats*)(h_EoC[i]->GetListOfFunctions()->FindObject("stats"));
    s_EoC[i]->SetY1NDC(0.59); //new x start position
    s_EoC[i]->SetY2NDC(0.79); //new x end position
    s_EoC[i]->SetTextColor(kGreen+2);
    s_EoC[i]->Draw();
    
    f_EoP[i]->Draw("same");
    f_EoC[i]->Draw("same");    
  }

  /*  
  TCanvas *c2[100]; 
  for(int i = 0; i < nBins; ++i)
  {
    char canvasName[50];
    if (i%6==0) {
      sprintf(canvasName, "LaserCorr-%0d", i/6); 
      c2[i/6] = new TCanvas(canvasName, canvasName);
      c2[i/6] -> Divide(3,2);
    }
        
    c2[i/6] -> cd (i%6+1);
    h_Las[i] -> GetXaxis() -> SetTitle("laser correction");
    h_Las[i] -> GetXaxis() -> SetRangeUser(0.5,1.5); 
    h_Las[i] -> Draw("");
    gPad->Update();
    s_Las[i]= (TPaveStats*)(h_Las[i]->GetListOfFunctions()->FindObject("stats"));
    s_Las[i]->SetTextColor(kBlack);
  }
  */

  /*  
  TCanvas *cmap = new TCanvas("cmap","cmap");
  cmap->cd();
  gStyle->SetPalette(1);
  h_LC_map->Draw("colz");
  */
  
  // Final plots
  TCanvas* cplot = new TCanvas("gplot", "gplot",100,100,725,500);
  cplot->cd();

  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,0.64,1.00);
  TPad *cRight = new TPad("pad_1","pad_1",0.64,0.00,1.00,1.00);

  cLeft->SetLeftMargin(0.15); 
  cLeft->SetRightMargin(0.025); 
  cRight->SetLeftMargin(0.025); 

  cLeft->Draw();
  cRight->Draw();

  float tYoffset = 1.5; 
  float labSize = 0.04;
  float labSize2 = 0.07;

  cLeft->cd(); 

  cLeft->SetGridx();
  cLeft->SetGridy();
  
  // pad settings
  TH1F *hPad = (TH1F*)gPad->DrawFrame(lcMin,0.9,lcMax,1.05);
  hPad->GetXaxis()->SetTitle("Laser correction");
  hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize);
  if ( strcmp(EBEE,"EB")==0 )
  {  
    hPad -> SetMinimum(0.950);
    hPad -> SetMaximum(1.010);
  }
  else 
  {  
    hPad -> SetMinimum(0.910);
    hPad -> SetMaximum(1.030);
  }
    
  // draw trend plot
  g_fit -> SetMarkerStyle(20);
  g_fit -> SetMarkerSize(0.75);
  g_fit -> SetMarkerColor(kRed+2);
  g_fit -> SetLineColor(kRed+2);
  g_fit -> Draw("P");
  g_c_fit -> SetMarkerStyle(20);
  g_c_fit -> SetMarkerColor(kGreen+2);
  g_c_fit -> SetLineColor(kGreen+2);
  g_c_fit -> SetMarkerSize(0.75);
  g_c_fit -> Draw("P,same");
  
  
  cRight -> cd();

  TPaveStats* s_EoP_spread = new TPaveStats();
  TPaveStats* s_EoC_spread = new TPaveStats();
  
  h_EoC_spread -> SetFillStyle(3001);
  h_EoC_spread -> SetFillColor(kGreen+2);
  h_EoC_spread->GetYaxis()->SetLabelSize(labSize2);
  h_EoC_spread->GetYaxis()->SetTitleSize(labSize2);
  h_EoC_spread->GetYaxis()->SetNdivisions(505);
  h_EoC_spread->GetYaxis()->SetLabelOffset(-0.02);
  h_EoC_spread->GetXaxis()->SetLabelOffset(1000);

  h_EoC_spread -> Draw("hbar");
  gPad -> Update();
  s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoC_spread ->SetTextColor(kGreen+2);
  s_EoC_spread ->SetTextSize(0.06);
  s_EoC_spread->SetX1NDC(0.49); //new x start position
  s_EoC_spread->SetX2NDC(0.99); //new x end position
  s_EoC_spread->SetY1NDC(0.875); //new x start position
  s_EoC_spread->SetY2NDC(0.990); //new x end position
  s_EoC_spread -> SetOptStat(1100);
  s_EoC_spread -> Draw("sames");

  h_EoP_spread -> SetFillStyle(3001);
  h_EoP_spread -> SetFillColor(kRed+2);
  h_EoP_spread -> Draw("hbarsames");
  gPad -> Update();
  s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoP_spread->SetX1NDC(0.49); //new x start position
  s_EoP_spread->SetX2NDC(0.99); //new x end position
  s_EoP_spread->SetY1NDC(0.750); //new x start position
  s_EoP_spread->SetY2NDC(0.875); //new x end position
  s_EoP_spread ->SetOptStat(1100);
  s_EoP_spread ->SetTextColor(kRed+2);
  s_EoP_spread ->SetTextSize(0.06);
  s_EoP_spread -> Draw("sames");
}
Exemplo n.º 9
0
RooSimultaneous *SignalPDFs(TString url="EventSummaries.root",TString chSelector="")
{
  gStyle->SetOptStat(0);
  TCanvas *c = new TCanvas("signalpdfs","Signal PDFs");

  //the mass points
  typedef std::pair<TString,Float_t> MassPoint_t;
  std::vector<MassPoint_t> MassPointCollection;
  MassPointCollection.push_back( MassPoint_t("TTJets_mass_161v5",161.5) );
  MassPointCollection.push_back( MassPoint_t("TTJets_mass_163v5",163.5) );
  //  MassPointCollection.push_back( MassPoint_t("TTJets_mass_166v5",166.5) );
  MassPointCollection.push_back( MassPoint_t("TTJets_mass_169v5",169.5) ); 
  MassPointCollection.push_back( MassPoint_t("TTJets",           172.5) );
  MassPointCollection.push_back( MassPoint_t("TTJets_mass_175v5",175.5) );
  MassPointCollection.push_back( MassPoint_t("TTJets_mass_178v5",178.5) );
  MassPointCollection.push_back( MassPoint_t("TTJets_mass181v5", 181.5) );
  MassPointCollection.push_back( MassPoint_t("TTJets_mass184v5", 184.5) );

  std::map<std::string,TH1*> hmap;
  
  //get pdfs from file
  RooCategory sample("signal","") ;
  TFile *f = TFile::Open(url);
  for(size_t ipt=0; ipt<MassPointCollection.size(); ipt++)
    {
      TString sName("m"); sName += (ipt+1);      

      TString tname=MassPointCollection[ipt].first + "/data";
      TTree *t = (TTree *) f->Get(tname);
      if(t==0) continue;

      t->Draw("evmeasurements[0]>>hmass(80,100,500)","evmeasurements[0]>0" + chSelector);
      TH1D *h = (TH1D*) gDirectory->Get("hmass");
      if(h==0) continue;
      
      h = (TH1D *) h->Clone(sName);
      h->SetDirectory(0);
      h->GetYaxis()->SetTitle("Events / (5 GeV/c^{2})");
      h->GetXaxis()->SetTitle("Mass [GeV/c^{2}]");
      h->GetXaxis()->SetTitleOffset(0.8);
      h->GetYaxis()->SetTitleOffset(0.8);
      char titbuf[20];
      sprintf(titbuf,"m=%3.1lf",MassPointCollection[ipt].second);
      h->SetTitle(titbuf);

      sample.defineType(TString(sName));
      hmap[sName.Data()] = h;
    }    
  f->Close();
  delete c;

  // divide the binned data in categories according to the generated top quark mass
  RooRealVar mass("m","Mass", 100, 500);
  RooDataHist combData("combData", "combined data",mass, sample, hmap );

  //the parameters to fit and the variable
  RooRealVar g_mean_slope("#mu_{G}(slope)","g_mean_slope",0.01,0.,1.);    
  RooRealVar g_mean_shift("#mu_{G}(intercept)","g_mean_shift",162,100,180); 
  RooRealVar g_sigma_slope("#sigma_{G}(slope)","g_sigma_slope",0.01,0.,1.);
  RooRealVar g_sigma_shift("#sigma_{G}(intercept)","g_sigma_shift",10,0.,25);
  RooRealVar l_mean_slope("mpv_{L}(slope)","l_mean_slope",0.,0.,1.);//1,0,10);
  RooRealVar l_mean_shift("mpv_{L}(intercept)","l_mean_shift",212,150,250); 
  RooRealVar l_sigma_slope("#sigma_{L}(slope)","l_sigma_slope",0.,0.,1.);//1,0,10);
  RooRealVar l_sigma_shift("#sigma_{L}(intercept)","l_sigma_shift",10,0,25);
  RooRealVar massfrac_slope("#alpha(slope)","massfrac_slope",0,0,0.01);
  RooRealVar massfrac_shift("#alpha(intercept)","massfrac_shift",0.38,0.,1.);

  //build the prototype pdf
  RooRealVar    topmass( "mtop","mtop",100,300);
  RooFormulaVar g_mean(  "g_mean",  "(@0-172)*@1+@2",   RooArgSet(topmass,g_mean_slope,g_mean_shift));
  RooFormulaVar g_sigma( "g_sigma", "(@0-172)*@1+@2", RooArgSet(topmass,g_sigma_slope,g_sigma_shift)); 
  RooGaussian gaus("gaus", "Mass component 1", mass, g_mean, g_sigma);
  RooFormulaVar l_mean(  "l_mean",  "(@0-172)*@1+@2",   RooArgSet(topmass,l_mean_slope,l_mean_shift));
  RooFormulaVar l_sigma( "l_sigma", "(@0-172)*@1+@2", RooArgSet(topmass,l_sigma_slope,l_sigma_shift)); 
  RooLandau lan("lan", "Mass component 2", mass, l_mean, l_sigma);  
  RooFormulaVar massfrac( "#alpha", "(@0-172)*@1+@2", RooArgSet(topmass,massfrac_slope,massfrac_shift)); 
  RooAddPdf massmodel("model","Model",RooArgList(lan,gaus),massfrac);
  //RooNumConvPdf massmodel("model","Model",topmass,lan,gaus);

  //now split per categories
  RooSimPdfBuilder builder(massmodel) ;
  RooArgSet* config = builder.createProtoBuildConfig() ;
  config->setStringValue("physModels","model");     // Name of the PDF we are going to work with
  config->setStringValue("splitCats","signal");     // Category used to differentiate sub-datasets
  config->setStringValue("model","signal : mtop");  // Prescription to taylor PDF parameters mtop for each subset in signal
  RooSimultaneous* simPdf = builder.buildPdf(*config,&combData) ;
  config = simPdf->getParameters(combData);
  for(size_t ipt=0; ipt<MassPointCollection.size(); ipt++)
    {
      TString sName("m"); sName+=(ipt+1);
      Float_t imass=MassPointCollection[ipt].second;
      (((RooRealVar &)(*config)["mtop_"+sName])).setRange(imass,imass);
      (((RooRealVar &)(*config)["mtop_"+sName])).setVal(imass);
    }
  
  //fit to data
  simPdf->fitTo(combData,Range(100.,400.));
 
  //display
  for(size_t ipt=0; ipt<MassPointCollection.size(); ipt++)
    {
      if(ipt%5==0)
	{
	  TString name("SignalPDFs_");  name+=ipt;
	  c = new TCanvas(name,name);
	  c->SetBorderSize(0);
	  c->SetFillStyle(0);
	  c->SetFillColor(0);
	  c->SetWindowSize(1750,350);
	  c->Clear();
	  c->Divide(5,1);	  
	}
      
      TPad *p = (TPad *)c->cd(ipt%5+1);
      p->SetGridx();
      p->SetGridy();
      TString procName("m"); procName += (ipt+1);
      char buf[100];
      sprintf(buf,"m_{t}=%3.1lf GeV/c^{2}",MassPointCollection[ipt].second);
      RooPlot* frame = mass.frame(Title(buf));
      RooDataSet* dataslice = (RooDataSet *)combData.reduce("signal==signal::"+procName);
      dataslice->plotOn(frame,DataError(RooAbsData::SumW2));
      RooCategory newCat(procName,procName);
      simPdf->plotOn(frame,Slice(newCat),ProjWData(mass,*dataslice));
      frame->GetYaxis()->SetTitleOffset(1.0);
      frame->GetYaxis()->SetTitle("Events");
      frame->GetXaxis()->SetTitleOffset(0.8);
      frame->GetXaxis()->SetTitle("Reconstructed Mass [GeV/c^{2}]");
      frame->Draw();
             
      TPaveText *pt = new TPaveText(0.75,0.85,0.97,0.95,"brNDC");
      pt->SetBorderSize(0);
      pt->SetFillColor(0);
      pt->SetFillStyle(0);
      char buf2[50];
      sprintf(buf2,"%3.1lf GeV/c^{2}",MassPointCollection[ipt].second);
      pt->AddText(buf2);
      pt->Draw();
    }


  return simPdf;
}
Exemplo n.º 10
0
int main(int argc, char** argv)
{
  // Set style options
  setTDRStyle();
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
  gStyle->SetOptTitle(0); 
  gStyle->SetOptStat(1110); 
  gStyle->SetOptFit(1); 
  
  // Set fitting options
  TVirtualFitter::SetDefaultFitter("Fumili2");
  
  
  
  
  
  
  //-----------------
  // Input parameters
  
  std::cout << "\n***************************************************************************************************************************" << std::endl;
  std::cout << "arcg: " << argc << std::endl;
  char* EBEE = argv[1];
  int evtsPerPoint = atoi(argv[2]);
  int useRegression = atoi(argv[3]);
  std::string dayMin = "";
  std::string dayMax = "";
  std::string dayMinLabel = "";
  std::string dayMaxLabel = "";
  float absEtaMin = -1.;
  float absEtaMax = -1.;
  int IetaMin = -1;
  int IetaMax = -1;
  int IphiMin = -1;
  int IphiMax = -1;
  if(argc >= 5)
  {
    dayMin = std::string(argv[4])+" "+std::string(argv[5])+" "+std::string(argv[6]);
    dayMax = std::string(argv[7])+" "+std::string(argv[8])+" "+std::string(argv[9]);
    dayMinLabel = std::string(argv[4])+"_"+std::string(argv[5])+"_"+std::string(argv[6]);
    dayMaxLabel = std::string(argv[7])+"_"+std::string(argv[8])+"_"+std::string(argv[9]);
    
    t1 = dateToInt(dayMin);
    t2 = dateToInt(dayMax);
  }
  if(argc >= 11)
  {
    yMIN = atof(argv[10]);
    yMAX = atof(argv[11]);
  }
  if(argc >= 13)
  {
    absEtaMin = atof(argv[12]);
    absEtaMax = atof(argv[13]);
  }
  if(argc >= 15)
  {
    IetaMin = atoi(argv[14]);
    IetaMax = atoi(argv[15]);
    IphiMin = atoi(argv[16]);
    IphiMax = atoi(argv[17]);
  }
  
  std::cout << "EBEE: "          << EBEE          << std::endl;
  std::cout << "evtsPerPoint: "  << evtsPerPoint  << std::endl;
  std::cout << "useRegression: " << useRegression << std::endl;
  std::cout << "dayMin: "        << dayMin        << std::endl;
  std::cout << "dayMax: "        << dayMax        << std::endl;
  std::cout << "yMin: "          << yMIN          << std::endl;
  std::cout << "yMax: "          << yMAX          << std::endl;
  std::cout << "absEtaMin: "     << absEtaMin     << std::endl;
  std::cout << "absEtaMax: "     << absEtaMax     << std::endl;
  std::cout << "IetaMin: "       << IetaMin       << std::endl;
  std::cout << "IetaMax: "       << IetaMax       << std::endl;
  std::cout << "IphiMin: "       << IphiMin       << std::endl;
  std::cout << "IphiMax: "       << IphiMax       << std::endl;
  
  
  
  
  
  
  //-------------------
  // Define in/outfiles
  
  std::string folderName = std::string(EBEE) + "_" + dayMinLabel + "_" + dayMaxLabel;
  if( (absEtaMin != -1.) && (absEtaMax != -1.) )
  {
    char absEtaBuffer[50];
    sprintf(absEtaBuffer,"_%.2f-%.2f",absEtaMin,absEtaMax);
    folderName += std::string(absEtaBuffer);
  } 
  
  if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) )
  {
    char absEtaBuffer[50];
    sprintf(absEtaBuffer,"_Ieta_%d-%d_Iphi_%d-%d",IetaMin,IetaMax,IphiMin,IphiMax);
    folderName += std::string(absEtaBuffer);
  } 
  
  gSystem->mkdir(folderName.c_str());
  TFile* o = new TFile((folderName+"/"+folderName+"_histos.root").c_str(),"RECREATE");
  
  
  
  // Get trees
  std::cout << std::endl;
  
  TChain* ntu_DA = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP");
  FillChain(ntu_DA,"inputDATA.txt");
  std::cout << "     DATA: " << std::setw(8) << ntu_DA->GetEntries() << " entries" << std::endl;
  
  TChain* ntu_MC = new TChain("simpleNtupleEoverP/SimpleNtupleEoverP");
  FillChain(ntu_MC,"inputMC.txt");
  std::cout << "REFERENCE: " << std::setw(8) << ntu_MC->GetEntries() << " entries" << std::endl;
  
  if (ntu_DA->GetEntries() == 0 || ntu_MC->GetEntries() == 0 )
  {
    std::cout << "Error: At least one file is empty" << std::endl; 
    return -1;
  }
  
  
  
  // Set branch addresses
  int runId;
  int timeStampHigh;
  int PV_n;
  float scLaserCorr, seedLaserAlpha, EoP, scEta, scPhi, scE, ES, P;
  int seedIeta, seedIphi, seedIx, seedIy, seedZside;
  
  ntu_DA->SetBranchStatus("*",0);
  ntu_DA->SetBranchStatus("runId",1);  
  ntu_DA->SetBranchStatus("timeStampHigh",1);
  ntu_DA->SetBranchStatus("PV_n",1);
  ntu_DA->SetBranchStatus("ele1_scLaserCorr",1);
  ntu_DA->SetBranchStatus("ele1_seedLaserAlpha",1);
  ntu_DA->SetBranchStatus("ele1_EOverP",1);
  ntu_DA->SetBranchStatus("ele1_scEta",1);
  ntu_DA->SetBranchStatus("ele1_scPhi",1);
  ntu_DA->SetBranchStatus("ele1_scE",1);
  ntu_DA->SetBranchStatus("ele1_scE_regression",1);
  ntu_DA->SetBranchStatus("ele1_scE",1);
  ntu_DA->SetBranchStatus("ele1_es",1);
  ntu_DA->SetBranchStatus("ele1_tkP",1);
  ntu_DA->SetBranchStatus("ele1_seedIeta",1);
  ntu_DA->SetBranchStatus("ele1_seedIphi",1);
  ntu_DA->SetBranchStatus("ele1_seedIx",1);
  ntu_DA->SetBranchStatus("ele1_seedIy",1);
  ntu_DA->SetBranchStatus("ele1_seedZside",1);
    
  ntu_DA->SetBranchAddress("runId", &runId);  
  ntu_DA->SetBranchAddress("timeStampHigh", &timeStampHigh);
  ntu_DA->SetBranchAddress("PV_n", &PV_n);
  ntu_DA->SetBranchAddress("ele1_scLaserCorr", &scLaserCorr);
  ntu_DA->SetBranchAddress("ele1_seedLaserAlpha", &seedLaserAlpha);
  ntu_DA->SetBranchAddress("ele1_EOverP", &EoP);
  ntu_DA->SetBranchAddress("ele1_scEta", &scEta);
  ntu_DA->SetBranchAddress("ele1_scPhi", &scPhi);
  if( useRegression < 1 )
    ntu_DA->SetBranchAddress("ele1_scE", &scE);
  else
    ntu_DA->SetBranchAddress("ele1_scE_regression", &scE);
  ntu_DA->SetBranchAddress("ele1_scE", &scE);
  ntu_DA->SetBranchAddress("ele1_es", &ES);
  ntu_DA->SetBranchAddress("ele1_tkP", &P);
  ntu_DA->SetBranchAddress("ele1_seedIeta", &seedIeta);
  ntu_DA->SetBranchAddress("ele1_seedIphi", &seedIphi);
  ntu_DA->SetBranchAddress("ele1_seedIx", &seedIx);
  ntu_DA->SetBranchAddress("ele1_seedIy", &seedIy);
  ntu_DA->SetBranchAddress("ele1_seedZside", &seedZside);
  
  
  ntu_MC->SetBranchStatus("*",0);
  ntu_MC->SetBranchStatus("runId",1);
  ntu_MC->SetBranchStatus("PV_n",1);
  ntu_MC->SetBranchStatus("ele1_scEta",1);
  ntu_MC->SetBranchStatus("ele1_EOverP",1);
  ntu_MC->SetBranchStatus("ele1_scE",1);
  ntu_MC->SetBranchStatus("ele1_scE_regression",1);
  ntu_MC->SetBranchStatus("ele1_es",1);
  ntu_MC->SetBranchStatus("ele1_tkP",1);
  ntu_MC->SetBranchStatus("ele1_seedIeta",1);
  ntu_MC->SetBranchStatus("ele1_seedIphi",1);
  ntu_MC->SetBranchStatus("ele1_seedIx",1);
  ntu_MC->SetBranchStatus("ele1_seedIy",1);
  ntu_MC->SetBranchStatus("ele1_seedZside",1);
  
  ntu_MC->SetBranchAddress("runId", &runId);  
  ntu_MC->SetBranchAddress("PV_n", &PV_n);
  ntu_MC->SetBranchAddress("ele1_scEta", &scEta);
  ntu_MC->SetBranchAddress("ele1_EOverP", &EoP);
  if( useRegression < 1 )
    ntu_MC->SetBranchAddress("ele1_scE", &scE);
  else
    ntu_MC->SetBranchAddress("ele1_scE_regression", &scE);
  ntu_MC->SetBranchAddress("ele1_es", &ES);
  ntu_MC->SetBranchAddress("ele1_tkP", &P);
  ntu_MC->SetBranchAddress("ele1_seedIeta", &seedIeta);
  ntu_MC->SetBranchAddress("ele1_seedIphi", &seedIphi);
  ntu_MC->SetBranchAddress("ele1_seedIx", &seedIx);
  ntu_MC->SetBranchAddress("ele1_seedIy", &seedIy);
  ntu_MC->SetBranchAddress("ele1_seedZside", &seedZside);
  
  
  
  
  
  
  //--------------------------------------------------------
  // Define PU correction (to be used if useRegression == 0)
  
  // corr = p0 + p1 * PV_n
  float p0_EB;
  float p1_EB;
  float p0_EE;
  float p1_EE;
  
  if( useRegression == 0 )
  {
    //2012 EB
    p0_EB = 0.9991;
    p1_EB = 0.0001635;
    //2012 EE
    p0_EE = 0.9968;
    p1_EE = 0.001046;
  }
  else
  {
    //2012 EB
    p0_EB = 1.001;
    p1_EB = -0.000143;
    //2012 EE
    p0_EE = 1.00327;
    p1_EE = -0.000432;
  }
  
  float p0 = -1.;
  float p1 = -1.;
  
  if( strcmp(EBEE,"EB") == 0 )
  {
    p0 = p0_EB;
    p1 = p1_EB;
  }
  else
  {
    p0 = p0_EE;
    p1 = p1_EE;
  }
  
  
  
  
  
  
  //---------------------------------
  // Build the reference distribution
  
  std::cout << std::endl;
  std::cout << "***** Build reference for " << EBEE << " *****" << std::endl;
  
  TH1F* h_template = new TH1F("template", "", 2000, 0., 5.);
  
  for(int ientry = 0; ientry < ntu_MC->GetEntries(); ++ientry)
  {
    if( (ientry%100000 == 0) ) std::cout << "reading MC entry " << ientry << "\r" << std::flush;
    ntu_MC->GetEntry(ientry);
    
    // selections
    if( (strcmp(EBEE,"EB") == 0) && (fabs(scEta) > 1.45) )                    continue; // barrel
    if( (strcmp(EBEE,"EE") == 0) && (fabs(scEta) < 1.47 || fabs(scEta)>2.7) ) continue; // endcap

    if( (absEtaMin != -1.) && (absEtaMax != -1.) )
    {
      if( (fabs(scEta) < absEtaMin) || (fabs(scEta) > absEtaMax) ) continue;
    }
    
    if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) )
    {
      if( (seedIeta < IetaMin) || (seedIeta > IetaMax) ) continue;
      if( (seedIphi < IphiMin) || (seedIphi > IphiMax) ) continue;
    }
    
    // PU correction
    float PUCorr = (p0 + p1*PV_n);
    //std::cout << "p0: " << p0  << "   p1: " << p1 << "   PV_n: " << PV_n << std::endl;
    
    // fill the template histogram
    h_template -> Fill( (scE-ES)/(P-ES) / PUCorr );
  }
  
  std::cout << "Reference built for " << EBEE << " - " << h_template->GetEntries() << " events" << std::endl;
  
  
  
  
  
  
  //---------------------
  // Loop and sort events
  
  std::cout << std::endl;
  std::cout << "***** Sort events and define bins *****" << std::endl;
  
  int nEntries = ntu_DA -> GetEntriesFast(); 
  int nSavePts = 0; 
  std::vector<bool> isSavedEntries(nEntries);
  std::vector<Sorter> sortedEntries;
  std::vector<int> timeStampFirst;
  
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    ntu_DA -> GetEntry(ientry);
    isSavedEntries.at(ientry) = false;
    
    // selections
    if( (strcmp(EBEE,"EB") == 0) && (fabs(scEta) > 1.45) )                    continue; // barrel
    if( (strcmp(EBEE,"EE") == 0) && (fabs(scEta) < 1.47 || fabs(scEta)>2.7) ) continue; // endcap
    
    if( (absEtaMin != -1.) && (absEtaMax != -1.) )
    {
      if( (fabs(scEta) < absEtaMin) || (fabs(scEta) > absEtaMax) ) continue;
    }
    
    if( (IetaMin != -1.) && (IetaMax != -1.) && (IphiMin != -1.) && (IphiMax != -1.) )
    {
      if( (seedIeta < IetaMin) || (seedIeta > IetaMax) ) continue;
      if( (seedIphi < IphiMin) || (seedIphi > IphiMax) ) continue;
    }
    
    if( timeStampHigh < t1 ) continue;
    if( timeStampHigh > t2 ) continue;
    
    if( scLaserCorr <= 0. ) continue;
    
    isSavedEntries.at(ientry) = true;
    
    
    // fill sorter
    Sorter dummy;
    dummy.time = timeStampHigh;
    dummy.entry = ientry;
    sortedEntries.push_back(dummy);
    
    ++nSavePts;
  }
  
  // sort events
  std::sort(sortedEntries.begin(),sortedEntries.end(),Sorter());
  std::cout << "Data sorted in " << EBEE << " - " << nSavePts << " events" << std::endl;
  
  std::map<int,int> antiMap;
  for(unsigned int iSaved = 0; iSaved < sortedEntries.size(); ++iSaved)
    antiMap[sortedEntries.at(iSaved).entry] = iSaved;
  
  
  //---------------------
  // Loop and define bins
  
  // "wide" bins - find events with time separation bigger than 1 day
  int nWideBins = 1;
  std::vector<int> wideBinEntryMax;
  int timeStampOld = -1;
  
  wideBinEntryMax.push_back(0);  
  for(int iSaved = 0; iSaved < nSavePts; ++iSaved)
  {
    if( iSaved%100000 == 0 ) std::cout << "reading saved entry " << iSaved << "\r" << std::flush;
    ntu_DA->GetEntry(sortedEntries[iSaved].entry);  
    
    if( iSaved == 0 )
    {
      timeStampOld = timeStampHigh;
      continue;
    }
    
    if( (timeStampHigh-timeStampOld)/3600. > timeLapse )
    {
      ++nWideBins;
      wideBinEntryMax.push_back(iSaved-1);
    }
    
    timeStampOld = timeStampHigh;
  }
  std::cout << std::endl;
  wideBinEntryMax.push_back(nSavePts);
  
  
  // bins with approximatively evtsPerPoint events per bin
  int nBins = 0;
  std::vector<int> binEntryMax;
  
  binEntryMax.push_back(0);
  for(int wideBin = 0; wideBin < nWideBins; ++wideBin)
  {
    int nTempBins = std::max(1,int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/evtsPerPoint ));
    int nTempBinEntries = int( (wideBinEntryMax.at(wideBin+1)-wideBinEntryMax.at(wideBin))/nTempBins );
    
    for(int tempBin = 0; tempBin < nTempBins; ++tempBin)
    {
      ++nBins;
      if( tempBin < nTempBins - 1 )
        binEntryMax.push_back( wideBinEntryMax.at(wideBin) + (tempBin+1)*nTempBinEntries );
      else
        binEntryMax.push_back( wideBinEntryMax.at(wideBin+1) );
    }
  }
  
  std::cout << "nBins = " << nBins << std::endl;
  //for(int bin = 0; bin < nBins; ++bin)
  //  std::cout << "bin: " << bin
  //            << "   entry min: " << setw(6) << binEntryMax.at(bin)
  //            << "   entry max: " << setw(6) << binEntryMax.at(bin+1)
  //            << "   events: "    << setw(6) << binEntryMax.at(bin+1)-binEntryMax.at(bin)
  //            << std::endl;
  
  
  
  
  
  
  //---------------------
  // histogram definition
  
  TH1F* h_scOccupancy_eta  = new TH1F("h_scOccupancy_eta","", 298, -2.6, 2.6);
  TH1F* h_scOccupancy_phi  = new TH1F("h_scOccupancy_phi","", 363, -3.1765, 3.159);
  SetHistoStyle(h_scOccupancy_eta);
  SetHistoStyle(h_scOccupancy_phi);
  
  TH2F* h_seedOccupancy_EB  = new TH2F("h_seedOccupancy_EB","",  171, -85., 86., 361,   0.,361.);
  TH2F* h_seedOccupancy_EEp = new TH2F("h_seedOccupancy_EEp","", 101,   0.,101., 100,   0.,101.);
  TH2F* h_seedOccupancy_EEm = new TH2F("h_seedOccupancy_EEm","", 101,   0.,101., 100,   0.,101.);
  SetHistoStyle(h_seedOccupancy_EB);
  SetHistoStyle(h_seedOccupancy_EEp);
  SetHistoStyle(h_seedOccupancy_EEm);
  
  TH1F* h_EoP_spread = new TH1F("h_EoP_spread","",100,yMIN,yMAX);
  TH1F* h_EoC_spread = new TH1F("h_EoC_spread","",100,yMIN,yMAX);
  TH1F* h_EoP_spread_run = new TH1F("h_EoP_spread_run","",100,yMIN,yMAX);
  TH1F* h_EoC_spread_run = new TH1F("h_EoC_spread_run","",100,yMIN,yMAX);
  SetHistoStyle(h_EoP_spread,"EoP");
  SetHistoStyle(h_EoC_spread,"EoC");
  SetHistoStyle(h_EoP_spread_run,"EoP");
  SetHistoStyle(h_EoC_spread_run,"EoC");
  
  TH1F* h_EoP_chi2 = new TH1F("h_EoP_chi2","",50,0.,5.);
  TH1F* h_EoC_chi2 = new TH1F("h_EoC_chi2","",50,0.,5.);
  SetHistoStyle(h_EoP_chi2,"EoP");
  SetHistoStyle(h_EoC_chi2,"EoC");  
  
  TH1F** h_EoP = new TH1F*[nBins];
  TH1F** h_EoC = new TH1F*[nBins];
  TH1F** h_Las = new TH1F*[nBins];
  TH1F** h_Tsp = new TH1F*[nBins];
  TH1F** h_Cvl = new TH1F*[nBins];
  
  for(int i = 0; i < nBins; ++i)
  {
    char histoName[80];
    
    sprintf(histoName, "EoP_%d", i);
    h_EoP[i] = new TH1F(histoName, histoName, 2000, 0., 5.);
    SetHistoStyle(h_EoP[i],"EoP");
    
    sprintf(histoName, "EoC_%d", i);
    h_EoC[i] = new TH1F(histoName, histoName, 2000, 0., 5.);
    SetHistoStyle(h_EoC[i],"EoC");
    
    sprintf(histoName, "Las_%d", i);
    h_Las[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5);
    
    sprintf(histoName, "Tsp_%d", i);
    h_Tsp[i] = new TH1F(histoName, histoName, 500, 0.5, 1.5);
  }
  
  
  // function definition
  TF1** f_EoP = new TF1*[nBins];
  TF1** f_EoC = new TF1*[nBins];
  
  
  // graphs definition
  TGraphAsymmErrors* g_fit   = new TGraphAsymmErrors();
  TGraphAsymmErrors* g_c_fit = new TGraphAsymmErrors();
  
  TGraphAsymmErrors* g_fit_run   = new TGraphAsymmErrors();
  TGraphAsymmErrors* g_c_fit_run = new TGraphAsymmErrors();  
  
  TGraph* g_las = new TGraph();
  
  TGraphErrors* g_LT = new TGraphErrors();
  
  g_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_fit->GetXaxis()->SetTimeDisplay(1);
  g_c_fit->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_c_fit->GetXaxis()->SetTimeDisplay(1);
  g_las->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_las->GetXaxis()->SetTimeDisplay(1);
  g_LT->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  g_LT->GetXaxis()->SetTimeDisplay(1);
    
  
  
  
  
  
  //------------------------------------
  // loop on the saved and sorted events
  
  std::cout << std::endl;
  std::cout << "***** Fill and fit histograms *****" << std::endl;

  std::vector<int> Entries(nBins);  
  std::vector<double> AveTime(nBins);
  std::vector<int> MinTime(nBins);
  std::vector<int> MaxTime(nBins);
  std::vector<double> AveRun(nBins);    
  std::vector<int> MinRun(nBins);
  std::vector<int> MaxRun(nBins);
  std::vector<double> AveLT(nBins);
  std::vector<double> AveLT2(nBins);
    
  int iSaved = -1;
  for(int ientry = 0; ientry < nEntries; ++ientry)
  {
    if( (ientry%100000 == 0) ) std::cout << "reading entry " << ientry << "\r" << std::flush;
    
    if( isSavedEntries.at(ientry) == false ) continue;
    
    ++iSaved;
    
    int iSaved = antiMap[ientry];
    int bin = -1;
    for(bin = 0; bin < nBins; ++bin)
      if( iSaved >= binEntryMax.at(bin) && iSaved < binEntryMax.at(bin+1) )
	break;
    
    //std::cout << "bin = " << bin << "   iSaved = "<< iSaved << std::endl;
    ntu_DA->GetEntry(ientry);
    
    
    
    Entries[bin] += 1;
    
    if( iSaved == binEntryMax.at(bin)+1 )   MinTime[bin] = timeStampHigh;
    if( iSaved == binEntryMax.at(bin+1)-1 ) MaxTime[bin] = timeStampHigh;
    AveTime[bin] += timeStampHigh;
    
    if( iSaved == binEntryMax.at(bin)+1 )   MinRun[bin] = runId;
    if( iSaved == binEntryMax.at(bin+1)-1 ) MaxRun[bin] = runId;
    AveRun[bin] += runId;
    
    float LT = (-1. / seedLaserAlpha * log(scLaserCorr));
    AveLT[bin] += LT;
    AveLT2[bin] += LT*LT;
    
    // PU correction
    float PUCorr = (p0 + p1*PV_n);
    
    // fill the histograms
    (h_EoP[bin]) -> Fill( (scE-ES)/(P-ES) / scLaserCorr / PUCorr);
    (h_EoC[bin]) -> Fill( (scE-ES)/(P-ES) / PUCorr );
    
    (h_Las[bin]) -> Fill(scLaserCorr);
    (h_Tsp[bin]) -> Fill(1./scLaserCorr);
    
    h_scOccupancy_eta -> Fill(scEta);
    h_scOccupancy_phi -> Fill(scPhi);
    if(seedZside == 0)
      h_seedOccupancy_EB -> Fill(seedIeta,seedIphi);
    if(seedZside > 0)
      h_seedOccupancy_EEp -> Fill(seedIx,seedIy);
    if(seedZside < 0)
      h_seedOccupancy_EEm -> Fill(seedIx,seedIy);
  }
  
  for(int bin = 0; bin < nBins; ++bin)
  {
    AveTime[bin] = 1. * AveTime[bin] / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    AveRun[bin]  = 1. * AveRun[bin]  / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    AveLT[bin]   = 1. * AveLT[bin]   / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    AveLT2[bin]  = 1. * AveLT2[bin]  / (binEntryMax.at(bin+1)-binEntryMax.at(bin));
    //std::cout << date << " " << AveTime[i] << " " << MinTime[i] << " " << MaxTime[i] << std::endl;
  }
  
  
  
  
  
  
  int rebin = 2;
  if( strcmp(EBEE,"EE") == 0 ) rebin *= 2;
  
  h_template -> Rebin(rebin);
  
  
  
  float EoP_scale = 0.;
  float EoP_err = 0.;
  int   EoP_nActiveBins = 0;
  
  float EoC_scale = 0.;
  float EoC_err = 0.;
  int   EoC_nActiveBins = 0;
  
  float LCInv_scale = 0;
  
  std::vector<int> validBins;
  for(int i = 0; i < nBins; ++i)
  {
    bool isValid = true;
    
    h_EoP[i] -> Rebin(rebin);
    h_EoC[i] -> Rebin(rebin);
    
    
    
    //------------------------------------
    // Fill the graph for uncorrected data
    
    // define the fitting function
    // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )
    
    //o -> cd();
    char convolutionName[50];
    sprintf(convolutionName,"h_convolution_%d",i);
    //h_Cvl[i] = ConvoluteTemplate(std::string(convolutionName),h_template,h_Las[i],32768,-5.,5.);
    h_Cvl[i] = MellinConvolution(std::string(convolutionName),h_template,h_Tsp[i]);
    
    histoFunc* templateHistoFunc = new histoFunc(h_template);
    histoFunc* templateConvolutedHistoFunc = new histoFunc(h_Cvl[i]);
    char funcName[50];

    sprintf(funcName,"f_EoP_%d",i);
    
    if( strcmp(EBEE,"EB") == 0 )
      f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.8*(h_Tsp[i]->GetMean()), 1.4*(h_Tsp[i]->GetMean()), 3, "histoFunc");
    else
      f_EoP[i] = new TF1(funcName, templateConvolutedHistoFunc, 0.75*(h_Tsp[i]->GetMean()), 1.5*(h_Tsp[i]->GetMean()), 3, "histoFunc");
    
    f_EoP[i] -> SetParName(0,"Norm"); 
    f_EoP[i] -> SetParName(1,"Scale factor"); 
    f_EoP[i] -> SetLineWidth(1); 
    f_EoP[i] -> SetNpx(10000);
    
    double xNorm = h_EoP[i]->GetEntries()/h_template->GetEntries() *
      h_EoP[i]->GetBinWidth(1)/h_template->GetBinWidth(1); 
    
    f_EoP[i] -> FixParameter(0, xNorm);
    f_EoP[i] -> SetParameter(1, 1.);
    f_EoP[i] -> FixParameter(2, 0.);
    f_EoP[i] -> SetLineColor(kRed+2); 
    
    int fStatus = 0;
    int nTrials = 0;
    TFitResultPtr rp;
    
    rp = h_EoP[i] -> Fit(funcName, "QERLS+");
    while( (fStatus != 0) && (nTrials < 10) )
    {
      rp = h_EoP[i] -> Fit(funcName, "QERLS+");
      fStatus = rp;
      if(fStatus == 0) break;
      ++nTrials;
    }
    
    // fill the graph
    double eee = f_EoP[i]->GetParError(1);
    //float k    = f_EoP[i]->GetParameter(1);
    float k    = f_EoP[i]->GetParameter(1) / h_Tsp[i]->GetMean(); //needed when using mellin's convolution 
    
    if( (h_EoP[i]->GetEntries() > 3) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) )
    {
      float date = (float)AveTime[i];
      float dLow = (float)(AveTime[i]-MinTime[i]); 
      float dHig = (float)(MaxTime[i]-AveTime[i]);
      float run = (float)AveRun[i];
      float rLow = (float)(AveRun[i]-MinRun[i]); 
      float rHig = (float)(MaxRun[i]-AveRun[i]);
      
      g_fit -> SetPoint(i,  date , 1./k);
      g_fit -> SetPointError(i, dLow , dHig, eee/k/k, eee/k/k);
      
      g_fit_run -> SetPoint(i,  run , 1./k);
      g_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k);
      
      h_EoP_chi2 -> Fill(f_EoP[i]->GetChisquare()/f_EoP[i]->GetNDF());
      
      EoP_scale += 1./k;
      EoP_err += eee/k/k;
      ++EoP_nActiveBins;
    }
    else
    {
      std::cout << "Fitting uncorrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << std::endl;
      isValid = false;
    }  
    
    //----------------------------------
    // Fill the graph for corrected data
    
    // define the fitting function
    // N.B. [0] * ( [1] * f( [1]*(x-[2]) ) )

    sprintf(funcName,"f_EoC_%d",i);
    if( strcmp(EBEE,"EB") == 0 )
      f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.8, 1.4, 3, "histoFunc");
    else
      f_EoC[i] = new TF1(funcName, templateHistoFunc, 0.75, 1.5, 3, "histoFunc");
    f_EoC[i] -> SetParName(0,"Norm"); 
    f_EoC[i] -> SetParName(1,"Scale factor"); 
    f_EoC[i] -> SetLineWidth(1); 
    f_EoC[i] -> SetNpx(10000);
    
    xNorm = h_EoC[i]->GetEntries()/h_template->GetEntries() *
            h_EoC[i]->GetBinWidth(1)/h_template->GetBinWidth(1); 

    f_EoC[i] -> FixParameter(0, xNorm);
    f_EoC[i] -> SetParameter(1, 0.99);
    f_EoC[i] -> FixParameter(2, 0.);
    f_EoC[i] -> SetLineColor(kGreen+2); 
    
    
    rp = h_EoC[i] -> Fit(funcName, "QERLS+");
    fStatus = rp;
    nTrials = 0;
    while( (fStatus != 0) && (nTrials < 10) )
    {
      rp = h_EoC[i] -> Fit(funcName, "QERLS+");
      fStatus = rp;
      if(fStatus == 0) break;
      ++nTrials;
    }
    
    // fill the graph
    k   = f_EoC[i]->GetParameter(1);
    eee = f_EoC[i]->GetParError(1); 
    
    if( (h_EoC[i]->GetEntries() > 10) && (fStatus == 0) && (eee > 0.05*h_template->GetRMS()/sqrt(evtsPerPoint)) )
    {
      float date = (float)AveTime[i]; 
      float dLow = (float)(AveTime[i]-MinTime[i]); 
      float dHig = (float)(MaxTime[i]-AveTime[i]);
      float run = (float)AveRun[i];
      float rLow = (float)(AveRun[i]-MinRun[i]); 
      float rHig = (float)(MaxRun[i]-AveRun[i]);
      
      g_c_fit -> SetPoint(i,  date , 1./k);
      g_c_fit -> SetPointError(i, dLow , dHig , eee/k/k, eee/k/k);
      
      g_c_fit_run -> SetPoint(i,  run , 1./k);
      g_c_fit_run -> SetPointError(i, rLow , rHig, eee/k/k, eee/k/k);
      
      h_EoC_chi2 -> Fill(f_EoC[i]->GetChisquare()/f_EoP[i]->GetNDF());
      
      EoC_scale += 1./k;
      EoC_err += eee/k/k;
      ++EoC_nActiveBins;
    }
    else
    {
      std::cout << "Fitting corrected time bin: " << i << "   Fail status: " << fStatus << "   sigma: " << eee << std::endl;
      isValid = false;
    }
    
    if( isValid == true ) validBins.push_back(i);
  }
  
  EoP_scale /= EoP_nActiveBins;
  EoP_err   /= EoP_nActiveBins;
  
  EoC_scale /= EoC_nActiveBins;
  EoC_err   /= EoC_nActiveBins;
  
  
  
  
  
  
  //----------------------------------------
  // Fill the graph for avg laser correction
  
  //fede
  for(unsigned int itr = 0; itr < validBins.size(); ++itr)
  {  
    int i = validBins.at(itr);
    g_las -> SetPoint(itr, (float)AveTime[i], h_Tsp[i]->GetMean() );
    g_LT  -> SetPoint(itr, (float)AveTime[i], AveLT[i] );
    g_LT  -> SetPointError(itr, 0., sqrt(AveLT2[i]-AveLT[i]*AveLT[i]) / sqrt(Entries[i]) );
        
    LCInv_scale += h_Tsp[i]->GetMean();
  }  
  
  LCInv_scale /= validBins.size();
  
  
  
  
  
  
  //---------------
  // Rescale graphs
  
  float yscale = 1.;
  //float yscale = 1./EoC_scale;
  
  for(unsigned int itr = 0; itr < validBins.size(); ++itr)
  {
    double x,y; 
    g_fit -> GetPoint(itr,x,y); 
    g_fit -> SetPoint(itr,x,y*yscale);
    if ( (x > t1) && (x < t2) ) h_EoP_spread -> Fill(y*yscale);
    
    g_c_fit -> GetPoint(itr,x,y); 
    g_c_fit -> SetPoint(itr,x,y*yscale);
    if ( (x > t1) && (x < t2) ) h_EoC_spread -> Fill(y*yscale);
    
    g_fit_run -> GetPoint(itr,x,y); 
    g_fit_run -> SetPoint(itr,x,y*yscale); 
    if ( (x > t1) && (x < t2) ) h_EoP_spread_run -> Fill(y*yscale);
    
    g_c_fit_run -> GetPoint(itr,x,y); 
    g_c_fit_run -> SetPoint(itr,x,y*yscale);
    if ( (x > t1) && (x < t2) ) h_EoC_spread_run -> Fill(y*yscale);
    
    g_las -> GetPoint(itr,x,y);
    g_las -> SetPoint(itr,x,y*yscale*EoP_scale/LCInv_scale);
  }
  
  TF1 EoC_pol0("EoC_pol0","pol0",t1,t2);
  EoC_pol0.SetLineColor(kGreen+2);
  EoC_pol0.SetLineWidth(2);
  EoC_pol0.SetLineStyle(2);
  g_c_fit -> Fit("EoC_pol0","QNR");
  
  
  
  
  
  
  
  
  //----------------------------
  // Print out global quantities
  
  std::cout << std::endl;
  std::cout << "***** Mean scales and errors *****" << std::endl; 
  std::cout << std::fixed;
  std::cout << std::setprecision(4);
  std::cout << "Mean EoP scale: "  << std::setw(6) << EoP_scale   << "   mean EoP error: " << std::setw(8) << EoP_err << std::endl;
  std::cout << "Mean EoC scale: "  << std::setw(6) << EoC_scale   << "   mean EoC error: " << std::setw(8) << EoC_err << std::endl;
  std::cout << "Mean 1/LC scale: " << std::setw(6) << LCInv_scale << std::endl;
  
  
  
  
  
  
  //-----------------
  // Occupancy plots
  //-----------------
  
  TCanvas* c_scOccupancy = new TCanvas("c_scOccupancy","SC occupancy",0,0,1000,500);
  c_scOccupancy -> Divide(2,1);
  
  c_scOccupancy -> cd(1);
  h_scOccupancy_eta -> GetXaxis() -> SetTitle("sc #eta");
  h_scOccupancy_eta -> GetYaxis() -> SetTitle("events");
  h_scOccupancy_eta -> Draw();
  
  c_scOccupancy -> cd(2);
  h_scOccupancy_phi -> GetXaxis() -> SetTitle("sc #phi");
  h_scOccupancy_phi -> GetYaxis() -> SetTitle("events");
  h_scOccupancy_phi -> Draw();
  
  TCanvas* c_seedOccupancy = new TCanvas("c_seedOccupancy","seed occupancy",0,0,1500,500);
  c_seedOccupancy -> Divide(3,1);
  
  c_seedOccupancy -> cd(1);
  h_seedOccupancy_EB -> GetXaxis() -> SetTitle("seed i#eta");
  h_seedOccupancy_EB -> GetYaxis() -> SetTitle("seed i#phi");
  h_seedOccupancy_EB -> Draw("COLZ");
  
  c_seedOccupancy -> cd(2);
  h_seedOccupancy_EEp -> GetXaxis() -> SetTitle("seed ix");
  h_seedOccupancy_EEp -> GetYaxis() -> SetTitle("seed iy");
  h_seedOccupancy_EEp -> Draw("COLZ");
  
  c_seedOccupancy -> cd(3);
  h_seedOccupancy_EEm -> GetXaxis() -> SetTitle("seed ix");
  h_seedOccupancy_EEm -> GetYaxis() -> SetTitle("seed iy");
  h_seedOccupancy_EEm -> Draw("COLZ");
  
  
  
  //-----------
  // Chi2 plots
  //-----------
  
  TCanvas* c_chi2 = new TCanvas("c_chi2","fit chi2",0,0,500,500);
  c_chi2 -> cd();
  
  h_EoC_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}");
  h_EoC_chi2 -> Draw("");
  gPad -> Update();
    
  TPaveStats* s_EoC = new TPaveStats;
  s_EoC = (TPaveStats*)(h_EoC_chi2->GetListOfFunctions()->FindObject("stats"));
  s_EoC -> SetStatFormat("1.4g");
  s_EoC -> SetTextColor(kGreen+2);
  s_EoC->SetY1NDC(0.59);
  s_EoC->SetY2NDC(0.79);
  s_EoC -> Draw("sames");
  gPad -> Update();
  
  h_EoP_chi2 -> GetXaxis() -> SetTitle("#chi^{2}/N_{dof}");
  h_EoP_chi2 -> Draw("sames");
  gPad -> Update();
  
  TPaveStats* s_EoP = new TPaveStats;
  s_EoP = (TPaveStats*)(h_EoP_chi2->GetListOfFunctions()->FindObject("stats"));
  s_EoP -> SetStatFormat("1.4g");
  s_EoP -> SetTextColor(kRed+2);
  s_EoP->SetY1NDC(0.79);
  s_EoP->SetY2NDC(0.99);
  s_EoP -> Draw("sames");
  gPad -> Update();
  
  
  
  
  
  
  //-------------------
  // Final plot vs date
  //-------------------
  
  TCanvas* cplot = new TCanvas("cplot", "history plot vs date",100,100,1000,500);
  cplot->cd();

  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,0.75,1.00);
  TPad *cRight = new TPad("pad_1","pad_1",0.75,0.00,1.00,1.00);

  cLeft->SetLeftMargin(0.15); 
  cLeft->SetRightMargin(0.025); 
  cRight->SetLeftMargin(0.025); 

  cLeft->Draw();
  cRight->Draw();

  float tYoffset = 1.0; 
  float labSize = 0.05;
  float labSize2 = 0.06;

  cLeft->cd(); 
  
  cLeft->SetGridx();
  cLeft->SetGridy();
  
  TH1F *hPad = (TH1F*)gPad->DrawFrame(t1,0.9,t2,1.05);
  hPad->GetXaxis()->SetTimeFormat("%d/%m%F1970-01-01 00:00:00");
  hPad->GetXaxis()->SetTimeDisplay(1);
  hPad->GetXaxis() -> SetRangeUser(MinTime[0]-43200,MaxTime[nBins-1]+43200);
  hPad->GetXaxis()->SetTitle("date (day/month)");
  if( strcmp(EBEE,"EB") == 0 )
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  else
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize2);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize2);
  hPad -> SetMinimum(yMIN);
  hPad -> SetMaximum(yMAX);
  
  // draw history plot
  g_fit -> SetMarkerStyle(24);
  g_fit -> SetMarkerSize(0.7);
  g_fit -> SetMarkerColor(kRed+2);
  g_fit -> SetLineColor(kRed+2);
  g_fit -> Draw("P");
  g_c_fit -> SetMarkerStyle(20);
  g_c_fit -> SetMarkerColor(kGreen+2);
  g_c_fit -> SetLineColor(kGreen+2);
  g_c_fit -> SetMarkerSize(0.7);
  g_c_fit -> Draw("P,same");
  g_las -> SetLineColor(kAzure-2);
  g_las -> SetLineWidth(2);
  g_las -> Draw("L,same");
  
  TLegend* legend = new TLegend(0.60,0.78,0.90,0.94);
  legend -> SetLineColor(kWhite);
  legend -> SetLineWidth(0);
  legend -> SetFillColor(kWhite);
  legend -> SetFillStyle(0);
  legend -> SetTextFont(42);
  legend -> SetTextSize(0.04);
  legend -> AddEntry(g_c_fit,"with LM correction","PL");
  legend -> AddEntry(g_fit,  "without LM correction","PL");
  legend -> AddEntry(g_las,  "1 / LM correction","L");
  legend -> Draw("same");
  
  char latexBuffer[250];
  
  sprintf(latexBuffer,"CMS 2012 Preliminary");
  TLatex* latex = new TLatex(0.18,0.89,latexBuffer);  
  latex -> SetNDC();
  latex -> SetTextFont(62);
  latex -> SetTextSize(0.05);
  latex -> Draw("same");
  
  //sprintf(latexBuffer,"#sqrt{s} = 8 TeV   L = 3.95 fb^{-1}");
  sprintf(latexBuffer,"#sqrt{s} = 8 TeV");
  TLatex* latex2 = new TLatex(0.18,0.84,latexBuffer);  
  latex2 -> SetNDC();
  latex2 -> SetTextFont(42);
  latex2 -> SetTextSize(0.05);
  latex2 -> Draw("same");
  
  if( strcmp(EBEE,"EB") == 0 )
    sprintf(latexBuffer,"ECAL Barrel");
  else
    sprintf(latexBuffer,"ECAL Endcap");
  TLatex* latex3 = new TLatex(0.18,0.19,latexBuffer);
  latex3 -> SetNDC();
  latex3 -> SetTextFont(42);
  latex3 -> SetTextSize(0.05);
  latex3 -> Draw("same");
  
  //sprintf(latexBuffer,"%.2E events",1.*nSavePts);
  //TLatex* latex4 = new TLatex(0.18,0.24,latexBuffer);  
  //latex4 -> SetNDC();
  //latex4 -> SetTextFont(42);
  //latex4 -> SetTextSize(0.04);
  //latex4 -> Draw("same");
  //
  //sprintf(latexBuffer,"%d events/bin - %d bins",evtsPerPoint,nBins);
  //TLatex* latex5 = new TLatex(0.18,0.19,latexBuffer);  
  //latex5 -> SetNDC();
  //latex5 -> SetTextFont(42);
  //latex5 -> SetTextSize(0.04);
  //latex5 -> Draw("same");
  
  
  cRight -> cd();
  
  TPaveStats* s_EoP_spread = new TPaveStats();
  TPaveStats* s_EoC_spread = new TPaveStats();
  
  
  h_EoC_spread -> SetFillStyle(3001);
  h_EoC_spread -> SetFillColor(kGreen+2);
  h_EoC_spread->GetYaxis()->SetLabelSize(0.09);
  h_EoC_spread->GetYaxis()->SetLabelOffset(-0.03);
  h_EoC_spread->GetYaxis()->SetTitleSize(0.08);
  h_EoC_spread->GetYaxis()->SetNdivisions(505);
  h_EoC_spread->GetXaxis()->SetLabelOffset(1000);
  
  h_EoC_spread -> Draw("hbar");
  gPad -> Update();
  
  s_EoC_spread = (TPaveStats*)(h_EoC_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoC_spread -> SetStatFormat("1.4g");
  s_EoC_spread->SetX1NDC(0.06); //new x start position
  s_EoC_spread->SetX2NDC(0.71); //new x end position
  s_EoC_spread->SetY1NDC(0.93); //new x start position
  s_EoC_spread->SetY2NDC(0.84); //new x end position
  s_EoC_spread -> SetOptStat(1100);
  s_EoC_spread ->SetTextColor(kGreen+2);
  s_EoC_spread ->SetTextSize(0.08);
  s_EoC_spread -> Draw("sames");
  
  
  h_EoP_spread -> SetFillStyle(3001);
  h_EoP_spread -> SetFillColor(kRed+2);
  h_EoP_spread -> Draw("hbarsames");
  gPad -> Update();
  s_EoP_spread = (TPaveStats*)(h_EoP_spread->GetListOfFunctions()->FindObject("stats"));
  s_EoP_spread -> SetStatFormat("1.4g");
  s_EoP_spread->SetX1NDC(0.06); //new x start position
  s_EoP_spread->SetX2NDC(0.71); //new x end position
  s_EoP_spread->SetY1NDC(0.83); //new x start position
  s_EoP_spread->SetY2NDC(0.74); //new x end position
  s_EoP_spread ->SetOptStat(1100);
  s_EoP_spread ->SetTextColor(kRed+2);
  s_EoP_spread ->SetTextSize(0.08);
  s_EoP_spread -> Draw("sames");
  
  /*
  h_EoP_spread -> SetFillStyle(3001);
  h_EoP_spread -> SetFillColor(kRed+2);
  h_EoP_spread -> Draw("hbarsame");
  gPad -> Update();
  */
  
  
  
  //------------------
  // Final plot vs run
  //------------------
  
  TCanvas* cplot_run = new TCanvas("cplot_run", "history plot vs run",100,100,1000,500);
  cplot_run->cd();
  
  cLeft  = new TPad("pad_0_run","pad_0_run",0.00,0.00,0.75,1.00);
  cRight = new TPad("pad_1_run","pad_1_run",0.75,0.00,1.00,1.00);

  cLeft->SetLeftMargin(0.15); 
  cLeft->SetRightMargin(0.025); 
  cRight->SetLeftMargin(0.025); 

  cLeft->Draw();
  cRight->Draw();

  tYoffset = 1.5; 
  labSize = 0.04;
  labSize2 = 0.07;

  cLeft->cd(); 

  cLeft->SetGridx();
  cLeft->SetGridy();
  
  hPad = (TH1F*)gPad->DrawFrame(MinRun[0]-1000,0.9,MaxRun[nBins-1]+1000,1.05);
  hPad->GetXaxis()->SetTitle("run");
  if( strcmp(EBEE,"EB") == 0 )
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  else
    hPad->GetYaxis()->SetTitle("Relative E/p scale"); 
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize);
  hPad -> SetMinimum(yMIN);
  hPad -> SetMaximum(yMAX);
  
  // draw history plot
  g_fit_run -> SetMarkerStyle(20);
  g_fit_run -> SetMarkerSize(0.7);
  g_fit_run -> SetMarkerColor(kRed+2);
  g_fit_run -> SetLineColor(kRed+2);
  g_fit_run -> Draw("P");
  g_c_fit_run -> SetMarkerStyle(20);
  g_c_fit_run -> SetMarkerColor(kGreen+2);
  g_c_fit_run -> SetLineColor(kGreen+2);
  g_c_fit_run -> SetMarkerSize(0.7);
  g_c_fit_run -> Draw("P,same");
  
  
  cRight -> cd();
  
  s_EoP_spread = new TPaveStats();
  s_EoC_spread = new TPaveStats();
  
  
  h_EoC_spread_run -> SetFillStyle(3001);
  h_EoC_spread_run -> SetFillColor(kGreen+2);
  h_EoC_spread_run->GetYaxis()->SetLabelSize(labSize2);
  h_EoC_spread_run->GetYaxis()->SetTitleSize(labSize2);
  h_EoC_spread_run->GetYaxis()->SetNdivisions(505);
  h_EoC_spread_run->GetYaxis()->SetLabelOffset(-0.02);
  h_EoC_spread_run->GetXaxis()->SetLabelOffset(1000);

  h_EoC_spread_run -> Draw("hbar");
  gPad -> Update();
  
  s_EoC_spread = (TPaveStats*)(h_EoC_spread_run->GetListOfFunctions()->FindObject("stats"));
  s_EoC_spread ->SetTextColor(kGreen+2);
  s_EoC_spread ->SetTextSize(0.06);
  s_EoC_spread->SetX1NDC(0.49); //new x start position
  s_EoC_spread->SetX2NDC(0.99); //new x end position
  s_EoC_spread->SetY1NDC(0.875); //new x start position
  s_EoC_spread->SetY2NDC(0.990); //new x end position
  s_EoC_spread -> SetOptStat(1100);
  s_EoC_spread -> Draw("sames");

  h_EoP_spread_run -> SetFillStyle(3001);
  h_EoP_spread_run -> SetFillColor(kRed+2);
  h_EoP_spread_run -> Draw("hbarsames");
  gPad -> Update();
  
  s_EoP_spread = (TPaveStats*)(h_EoP_spread_run->GetListOfFunctions()->FindObject("stats"));
  s_EoP_spread->SetX1NDC(0.49); //new x start position
  s_EoP_spread->SetX2NDC(0.99); //new x end position
  s_EoP_spread->SetY1NDC(0.750); //new x start position
  s_EoP_spread->SetY2NDC(0.875); //new x end position
  s_EoP_spread ->SetOptStat(1100);
  s_EoP_spread ->SetTextColor(kRed+2);
  s_EoP_spread ->SetTextSize(0.06);
  s_EoP_spread -> Draw("sames");
  
  
  
  
  
  
  c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.png").c_str(),"png");
  c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.png").c_str(),"png");
  c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.png").c_str(),"png");
  cplot -> Print((folderName+"/"+folderName+"_history_vsTime.png").c_str(),"png");
  cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.png").c_str(),"png");
  
  c_chi2 -> Print((folderName+"/"+folderName+"_fitChi2.pdf").c_str(),"pdf");
  c_scOccupancy -> Print((folderName+"/"+folderName+"_scOccupancy.pdf").c_str(),"pdf");
  c_seedOccupancy -> Print((folderName+"/"+folderName+"_seedOccupancy.pdf").c_str(),"pdf");
  cplot -> Print((folderName+"/"+folderName+"_history_vsTime.pdf").c_str(),"pdf");
  cplot_run -> Print((folderName+"/"+folderName+"_history_vsRun.pdf").c_str(),"pdf");
  
  cplot -> SaveAs((folderName+"/"+folderName+"_history_vsTime.C").c_str());
  cplot_run -> SaveAs((folderName+"/"+folderName+"_history_vsRun.C").c_str());
  
  
  
   o -> cd();
  
   h_template -> Write();

   h_scOccupancy_eta   -> Write();
   h_scOccupancy_phi   -> Write();
   h_seedOccupancy_EB  -> Write(); 
   h_seedOccupancy_EEp -> Write();
   h_seedOccupancy_EEm -> Write();

   g_fit   -> Write("g_fit");
   g_c_fit -> Write("g_c_fit");
   g_fit_run   -> Write("g_fit_run");
   g_c_fit_run -> Write("g_c_fit_run");
   g_las -> Write("g_las");
   g_LT -> Write("g_LT");
   
   h_EoP_chi2 -> Write();
   h_EoC_chi2 -> Write();
  
   //for(int i = 0; i < nBins; ++i)
   //{
   //  h_EoP[i] -> GetXaxis() -> SetTitle("E/p");
   //  h_EoP[i] -> Write();
   //
   //  h_EoC[i] -> GetXaxis() -> SetTitle("E/p");
   //  h_EoC[i] -> Write();
   //
   //  h_Tsp[i] -> Write();
   //
   //  h_Cvl[i] -> Write();
   //}

  o -> Close();
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
int main (int argc, char ** argv) {

  // check number of inpt parameters
  if(argc < 2){
    cerr<<"Forgot to parse the cfg file --> exit "<<endl;
    return -1;
  }

  // Set Root style from global enviroment path                                                                                                                               
  string ROOTStyle;
  if(getenv ("ROOTStyle")!=NULL){
    ROOTStyle = getenv ("ROOTStyle");
    gROOT->ProcessLine((".x "+ROOTStyle+"/setTDRStyle.C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetPadTopMargin(0.09);
  gStyle->SetPadLeftMargin(0.13);
  gStyle->SetErrorX(0.5);


  // parse config file parameter
  if (gConfigParser) return 1 ;
  gConfigParser = new ConfigParser();

  TString config ; 
  config.Form("%s",argv[1]);

  if(!(gConfigParser->init(config))){
      cout << ">>> parseConfigFile::Could not open configuration file " << config << endl;
      return -1;
  }

  // import base directory where samples are located and txt file with the directory name + other info
  string InputBaseDirectory  = gConfigParser -> readStringOption("Input::InputBaseDirectory");

  // import from cfg file the cross section value for this sample
  float CrossSection   = gConfigParser -> readFloatOption("Input::CrossSection");

  // total number of events
  int maxEventNumber   = gConfigParser -> readFloatOption("Input::EventsNumber");

  // treeName
  string treeName      = gConfigParser -> readStringOption("Input::TreeName");

  // take the cut list
  string InputCutList  = gConfigParser -> readStringOption("Input::InputCutList");

  // Read the cut file
  vector <cutContainer> CutList;
  if(ReadInputCutFile(InputCutList,CutList) <= 0){
    cerr<<" Empty Cut List File or not Exisisting --> Exit "<<endl; return -1;}

  // take the variable list to be plotted
  string InputVariableList  = gConfigParser -> readStringOption("Input::InputVariableList");
  vector<variableContainer> variableList;

  if(ReadInputVariableFile(InputVariableList,variableList) <= 0 ){
    cerr<<" Empty Variable List File or not Exisisting --> Exit "<<endl; return -1;}

  // take lumi and other parameters
  float lumi  =  gConfigParser -> readFloatOption("Option::Lumi"); // fb^(-1)
  lumi *= 1000. ;   // transform into pb^(-1)

  finalStateString    = gConfigParser -> readStringOption("Option::finalStateString");

  matchingCone        = gConfigParser -> readFloatOption("Option::matchingCone"); 
  minLeptonCleaningPt = gConfigParser -> readFloatOption("Option::minLeptonCleaningPt"); 
  minLeptonCutPt      = gConfigParser -> readFloatOption("Option::minLeptonCutPt");
  minJetCutPt         = gConfigParser -> readFloatOption("Option::minJetCutPt");
  usePuppiAsDefault   = gConfigParser -> readBoolOption("Option::usePuppiAsDefault");
  leptonIsoCut_mu     = gConfigParser -> readFloatOption("Option::leptonIsoCutMu");
  leptonIsoCut_el     = gConfigParser -> readFloatOption("Option::leptonIsoCutEl");
  leptonIsoCutLoose   = gConfigParser -> readFloatOption("Option::leptonIsoCutLoose");

  // output directory
  string outputPlotDirectory = gConfigParser -> readStringOption("Output::outputPlotDirectory");
  system(("mkdir -p output/"+outputPlotDirectory).c_str());
  system(("rm -r output/"+outputPlotDirectory+"/*").c_str());
  system(("mkdir -p output/"+outputPlotDirectory+"/xs").c_str());
  system(("mkdir -p output/"+outputPlotDirectory+"/norm").c_str());


  ///// Start the analysis  
  map<string,TH1F*> histoCutEff ;

  TChain* chain = new TChain (treeName.c_str()) ;  
  chain->Add ((InputBaseDirectory+"/*.root").c_str()) ;
  int totEvent = chain->GetEntries();

  readTree* reader  = new readTree((TTree*)(chain));

  cout<<"Lumi (fb-1) "<<lumi/1000<<" entries before "<<totEvent<<" cross section "<<CrossSection<<" Nevents before selections "<<lumi*CrossSection<<" weight "<<lumi*CrossSection/float(totEvent)<<endl;

  float weight = 1.0*lumi*CrossSection/float(totEvent) ;

  // make the plot container 
  vector<histoContainer> plotVector;

  for(size_t iCut = 0; iCut < CutList.size(); iCut++){
    histoCutEff["WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName] = new TH1F(("WW_EWK_pos_"+to_string(iCut)+"_"+CutList.at(iCut).cutLayerName).c_str(),"",15,0,15);
    for(size_t iVar = 0; iVar < variableList.size(); iVar++){
      plotVector.push_back(histoContainer(CutList.at(iCut).cutLayerName,variableList.at(iVar)));
    }
  }

  int passingLHEFilter = 0 ;
  
  int maximumEvents = chain->GetEntries () ;
  if (maxEventNumber > 0 && maxEventNumber < maximumEvents) 
    maximumEvents = maxEventNumber ;
  
  // Loop on the events
  for(int iEvent = 0; iEvent < maximumEvents ; iEvent++){

    reader->fChain->GetEntry(iEvent) ;

    if (iEvent % 100000 == 0) cout << "reading event " << iEvent << "\n" ;

    // filter LHE level leptons
    if(TString(finalStateString).Contains("UU")){
      if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) != 13)
        continue;
    }
    else if(TString(finalStateString).Contains("EE")){
      if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) != 11) continue;
    }
    else if(TString(finalStateString).Contains("EU")){
      if(fabs(reader->leptonLHEpid1) != 11 or fabs(reader->leptonLHEpid2) !=13) continue ;
    }
    else if(TString(finalStateString).Contains("UE")){
      if(fabs(reader->leptonLHEpid1) != 13 or fabs(reader->leptonLHEpid2) !=11) continue ;
    }
    else{
      cerr<<"problem with lhe level filter definition --> skip event"<<endl;
      continue;
    }

    passingLHEFilter++;

    // if an event pass the cut, fill the associated map                                                              
    leptonContainer lepton1,lepton2,parton1,parton2,neutrino1,neutrino2,vboson1,vboson2;

    lepton1.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt1,reader->leptonLHEeta1,reader->leptonLHEphi1,reader->leptonLHEm1);
    lepton1.charge_  = reader->leptonLHEch1;
    lepton1.flavour_ = reader->leptonLHEpid1;  

    lepton2.lepton4V_.SetPtEtaPhiM(reader->leptonLHEpt2,reader->leptonLHEeta2,reader->leptonLHEphi2,reader->leptonLHEm2);
    lepton2.charge_  = reader->leptonLHEch2;
    lepton2.flavour_ = reader->leptonLHEpid2;  

    parton1.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt1,reader->jetLHEPartoneta1,reader->jetLHEPartonphi1,0.);
    parton2.lepton4V_.SetPtEtaPhiM(reader->jetLHEPartonpt2,reader->jetLHEPartoneta2,reader->jetLHEPartonphi2,0.);

    neutrino1.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt1,reader->neutrinoLHEeta1,reader->neutrinoLHEphi1,0.);
    neutrino1.charge_  = 0.;
    neutrino1.flavour_ = reader->neutrinoLHEpid1;  

    neutrino2.lepton4V_.SetPtEtaPhiM(reader->neutrinoLHEpt2,reader->neutrinoLHEeta2,reader->neutrinoLHEphi2,0.);
    neutrino2.charge_  = 0.;
    neutrino2.flavour_ = reader->neutrinoLHEpid2;  

    vboson1.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt1,reader->vbosonLHEeta1,reader->vbosonLHEphi1,reader->vbosonLHEm1);
    vboson1.charge_  = reader->vbosonLHEch1;
    vboson1.flavour_ = reader->vbosonLHEpid1;  
    
    vboson2.lepton4V_.SetPtEtaPhiM(reader->vbosonLHEpt2,reader->vbosonLHEeta2,reader->vbosonLHEphi2,reader->vbosonLHEm2);
    vboson2.charge_  = reader->vbosonLHEch2;
    vboson2.flavour_ = reader->vbosonLHEpid2;  

    float minDR_1 = 999;
    float minDR_2 = 999;

    vector<leptonContainer> lepton, neutrino;
    lepton.push_back(lepton1);
    lepton.push_back(lepton2);
    neutrino.push_back(neutrino1);
    neutrino.push_back(neutrino2);

    leptonContainer leptFromV1, leptFromV2, neuFromV1, neuFromV2;

    for(size_t iLep= 0; iLep < lepton.size(); iLep++){
      for(size_t iNeu = 0; iNeu < neutrino.size(); iNeu++){
	if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_) < minDR_1 ){
	  minDR_1    = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson1.lepton4V_);
	  leptFromV1 = lepton.at(iLep);
	  neuFromV1  = neutrino.at(iNeu);
	}

	if((lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_) < minDR_2){
	  minDR_2    = (lepton.at(iLep).lepton4V_+neutrino.at(iNeu).lepton4V_).DeltaR(vboson2.lepton4V_);
	  leptFromV2 = lepton.at(iLep);
	  neuFromV2  = neutrino.at(iNeu);
	}	

      }
    }

    if(leptFromV1.lepton4V_ == leptFromV2.lepton4V_ or neuFromV1.lepton4V_ == neuFromV2.lepton4V_){
      cerr<<" bad matching with gen W "<<endl;
      continue;
    }
		       

    double costheta1 = 0;
    double costheta2 = 0;
    double Phi  = 0;
    double costhetastar  = 0;
    double Phi1  = 0;

    double costheta1_vbf = 0;
    double costheta2_vbf = 0;
    double Phi_vbf = 0;
    double costhetastar_vbf = 0;
    double Phi1_vbf = 0;


    TLorentzVector VV = vboson1.lepton4V_ + vboson2.lepton4V_;

    if(leptFromV1.charge_ > 0  and leptFromV2.charge_ > 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);
    }
    else if(leptFromV1.charge_ < 0  and leptFromV2.charge_ < 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);

    }

    else if(leptFromV1.charge_ < 0  and leptFromV2.charge_ > 0){
      computeAnglesResonance(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,leptFromV1.lepton4V_,neuFromV1.lepton4V_,vboson2.lepton4V_,neuFromV2.lepton4V_,leptFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);
    }
    else if(leptFromV1.charge_ > 0  and leptFromV2.charge_ < 0){

      computeAnglesResonance(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,
			     costheta1,costheta2,Phi,costhetastar,Phi1);

      computeAnglesVBF(VV,vboson1.lepton4V_,neuFromV1.lepton4V_,leptFromV1.lepton4V_,vboson2.lepton4V_,leptFromV2.lepton4V_,neuFromV2.lepton4V_,parton1.lepton4V_,
		       parton2.lepton4V_,costheta1_vbf,costheta2_vbf,Phi_vbf,costhetastar_vbf,Phi1_vbf);

    }
    else{ cerr<<" wrong charge composition "<<endl;
      continue;
    }
    
    float mTR = 0;
    float mR  = 0;

    TLorentzVector L_met ,L_dijet, L_dilepton, L_LLmet; 

    L_met      = neutrino1.lepton4V_ + neutrino2.lepton4V_;
    L_dijet    = parton1.lepton4V_   + parton2.lepton4V_;
    L_dilepton = lepton1.lepton4V_   + lepton2.lepton4V_;
    L_LLmet    = L_dilepton + L_met ;

    computeRazor(lepton1.lepton4V_,lepton2.lepton4V_,L_met,mTR,mR);

    if(lepton1.lepton4V_.Pt() < minLeptonCutPt or lepton2.lepton4V_.Pt() < minLeptonCutPt) continue;

    // Loop  on the cut list --> one cut for each polarization
    for(size_t iCut = 0; iCut < CutList.size(); iCut++){

      // cut the events
      string name = "WW_EWK";
      if(!passCutContainerSelection(reader,
                                    CutList.at(iCut),
                                    name,
				    int(iCut),
                                    usePuppiAsDefault,
                                    minLeptonCutPt,
                                    minLeptonCleaningPt,
                                    leptonIsoCut_mu,
                                    leptonIsoCut_el,
                                    leptonIsoCutLoose,
                                    matchingCone,
                                    minJetCutPt,
                                    histoCutEff,
				    finalStateString)) continue;

      
      float asimL = (lepton1.lepton4V_.Pt()-lepton2.lepton4V_.Pt())/(lepton1.lepton4V_.Pt()+lepton2.lepton4V_.Pt()) ;


      float asimJ    = (parton1.lepton4V_.Pt()-parton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()+parton2.lepton4V_.Pt()) ;
      float Rvar     = (lepton1.lepton4V_.Pt()*lepton2.lepton4V_.Pt())/(parton1.lepton4V_.Pt()*parton2.lepton4V_.Pt()) ;

      // loop on variables
      for(size_t iVar = 0; iVar < variableList.size(); iVar++){
        histoContainer tmpPlot;
        tmpPlot.cutName = CutList.at(iCut).cutLayerName;
        tmpPlot.varName = variableList.at(iVar).variableName;
        vector<histoContainer>::iterator itVec ;
        itVec = find(plotVector.begin(),plotVector.end(),tmpPlot);
        if(itVec == plotVector.end()){
          cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<"  "<<variableList.at(iVar).variableName<<endl;
          continue ;
        }
	
	// vector boson info
	if(variableList.at(iVar).variableName == "ptV1"){
          itVec->histogram->Fill(vboson1.lepton4V_.Pt(),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "ptV2"){
          itVec->histogram->Fill(vboson2.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaV1"){
          itVec->histogram->Fill(vboson1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaV2"){
          itVec->histogram->Fill(vboson2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptVV"){
          itVec->histogram->Fill(L_dijet.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mVV"){
          itVec->histogram->Fill(L_dijet.M(),weight) ;
        }

	// decay information
	if(variableList.at(iVar).variableName == "costheta1"){
          itVec->histogram->Fill(fabs(costheta1),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "costheta2"){
          itVec->histogram->Fill(fabs(costheta2),weight) ;
        }
	if(variableList.at(iVar).variableName == "costheta1_vbf"){
          itVec->histogram->Fill(fabs(costheta1_vbf),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "costheta2_vbf"){
          itVec->histogram->Fill(fabs(costheta2_vbf),weight) ;
        }

	if(variableList.at(iVar).variableName == "Phi"){
          itVec->histogram->Fill(fabs(Phi),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "Phi1"){
          itVec->histogram->Fill(fabs(Phi1),weight) ;
        }
	if(variableList.at(iVar).variableName == "Phi_vbf"){
          itVec->histogram->Fill(fabs(Phi_vbf),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "Phi1_vbf"){
          itVec->histogram->Fill(fabs(Phi1_vbf),weight) ;
        }

	else if(variableList.at(iVar).variableName == "costhetastar"){
          itVec->histogram->Fill(fabs(costhetastar),weight) ;
        }
	else if(variableList.at(iVar).variableName == "costhetastar_vbf"){
          itVec->histogram->Fill(fabs(costhetastar_vbf),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mTR"){
          itVec->histogram->Fill(mTR,weight) ;
	}

	else if(variableList.at(iVar).variableName == "mR"){
          itVec->histogram->Fill(mR,weight) ;
	}

	// jet info

	if(variableList.at(iVar).variableName == "ptj1"){
          itVec->histogram->Fill(parton1.lepton4V_.Pt(),1.*weight) ; 
        }
	else if(variableList.at(iVar).variableName == "ptj2"){
          itVec->histogram->Fill(parton2.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaj1"){
          itVec->histogram->Fill(parton1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etaj2"){
          itVec->histogram->Fill(parton2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "detajj"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.Eta()-parton2.lepton4V_.Eta()),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptjj"){
          itVec->histogram->Fill(L_dijet.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mjj"){
          itVec->histogram->Fill(L_dijet.M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "Asim_j"){
          itVec->histogram->Fill(asimJ,weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_JJ"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptl1"){
          itVec->histogram->Fill(lepton1.lepton4V_.Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptl2"){
          itVec->histogram->Fill(lepton2.lepton4V_.Pt(),weight) ;
        }
 
	else if(variableList.at(iVar).variableName == "etal1"){
          itVec->histogram->Fill(lepton1.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "etal2"){
          itVec->histogram->Fill(lepton2.lepton4V_.Eta(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "mll"){
          itVec->histogram->Fill(L_dilepton.M(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptll"){
          itVec->histogram->Fill(L_dilepton.Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(lepton2.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "Asim_l"){
          itVec->histogram->Fill(asimL,weight) ;
        }

	else if(variableList.at(iVar).variableName == "met"){
          itVec->histogram->Fill(L_met.Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "R"){
          itVec->histogram->Fill(Rvar,weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LMet"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLMet"){
          itVec->histogram->Fill((lepton1.lepton4V_ + L_met).Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_TLMet"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTLMet"){
          itVec->histogram->Fill((lepton2.lepton4V_ + L_met).Pt(),weight) ;
        }
	else if(variableList.at(iVar).variableName == "DeltaPhi_LLMet"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLLMet"){
          itVec->histogram->Fill((L_dilepton + L_met).Pt(),weight) ;
        }
	///
	else if(variableList.at(iVar).variableName == "DeltaPhi_LJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJL"){
          itVec->histogram->Fill(fabs(lepton1.lepton4V_.DeltaPhi(L_dijet)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptJJL"){
          itVec->histogram->Fill((lepton1.lepton4V_+L_dijet).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton1.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJTL"){
          itVec->histogram->Fill(fabs(lepton2.lepton4V_.DeltaPhi(L_dijet)),weight) ;
        }


	else if(variableList.at(iVar).variableName == "ptLJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptTJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptJJTL"){
          itVec->histogram->Fill((lepton2.lepton4V_+L_dijet).Pt(),weight) ;
        }

 
	else if(variableList.at(iVar).variableName == "DeltaPhi_LJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton1.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(parton2.lepton4V_)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_JJLL"){
          itVec->histogram->Fill(fabs(L_dilepton.DeltaPhi(L_dijet)),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptLJLL"){
          itVec->histogram->Fill((L_dilepton+parton1.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptTJLL"){
          itVec->histogram->Fill((L_dilepton+parton2.lepton4V_).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "ptJJLL"){
          itVec->histogram->Fill((L_dilepton+L_dijet).Pt(),weight) ;
        }

	///
	else if(variableList.at(iVar).variableName == "DeltaPhi_JJMet"){
          itVec->histogram->Fill(fabs(L_dijet.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptJJMet"){
          itVec->histogram->Fill((L_dijet+L_met).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_LJMet"){
          itVec->histogram->Fill(fabs(parton1.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptLJMet"){
          itVec->histogram->Fill((parton1.lepton4V_+L_met).Pt(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "DeltaPhi_TJMet"){
          itVec->histogram->Fill(fabs(parton2.lepton4V_.DeltaPhi(L_met)),weight) ;
        }
	else if(variableList.at(iVar).variableName == "ptTJMet"){
          itVec->histogram->Fill((parton2.lepton4V_+L_met).Pt(),weight) ;
        }
 
	else if(variableList.at(iVar).variableName == "mlljj"){
          itVec->histogram->Fill((L_dilepton+L_dijet).M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mlljjmet"){
          itVec->histogram->Fill((L_dilepton+L_dijet+L_met).M(),weight) ;
        }

	else if(variableList.at(iVar).variableName == "mTH"){
          itVec->histogram->Fill(sqrt(2*L_dilepton.Pt()*L_met.Pt()*(1-TMath::Cos(L_dilepton.DeltaPhi(L_met)))),weight) ;
        } 
      } // loop on variables
      
    } // Loop  on the cut list

  } // Loop on the events

  
  TFile* outputEfficiency = new TFile(("output/"+outputPlotDirectory+"/outputEfficiency.root").c_str(),"RECREATE");

  for(map<string,TH1F*>::const_iterator itMap = histoCutEff.begin(); itMap !=  histoCutEff.end(); itMap++){
    itMap->second->Scale(1./itMap->second->GetBinContent(1));
    itMap->second->Write();
  }

  outputEfficiency->Close();    

  
  // make the canvas and basic banners                                                                                                                                         
  TCanvas *cCanvas = new TCanvas("cCanvas","",1,52,550,550);
  cCanvas->SetTicks();
  cCanvas->SetFillColor(0);
  cCanvas->SetBorderMode(0);
  cCanvas->SetBorderSize(2);
  cCanvas->SetTickx(1);
  cCanvas->SetTicky(1);
  cCanvas->SetRightMargin(0.05);
  cCanvas->SetBottomMargin(0.12);
  cCanvas->SetFrameBorderMode(0);

  cCanvas->cd();

  TPad* upperPad = new TPad("upperPad", "upperPad", .005, .180, .995, .980);
  TPad* lowerPad = new TPad("lowerPad", "lowerPad", .005, .005, .995, .18);
  lowerPad->SetGridx();
  lowerPad->SetGridy();
  upperPad->SetLeftMargin(0.12);
  upperPad->SetRightMargin(0.1);
  lowerPad->SetLeftMargin(0.12);
  lowerPad->SetRightMargin(0.1);
  lowerPad->SetTopMargin(0.002);

  lowerPad->Draw();
  upperPad->Draw();

  TCanvas *cCanvasNorm = new TCanvas("cCanvasNorm","",1,52,550,550);
  cCanvasNorm->SetTicks();
  cCanvasNorm->SetFillColor(0);
  cCanvasNorm->SetBorderMode(0);
  cCanvasNorm->SetBorderSize(2);
  cCanvasNorm->SetTickx(1);
  cCanvasNorm->SetTicky(1);
  cCanvasNorm->SetRightMargin(0.05);
  cCanvasNorm->SetBottomMargin(0.12);
  cCanvasNorm->SetFrameBorderMode(0);

  TLatex * tex = new TLatex(0.88,0.92," 14 TeV");
  tex->SetNDC();
  tex->SetTextAlign(31);
  tex->SetTextFont(42);
  tex->SetTextSize(0.045);
  tex->SetLineWidth(2);
  TLatex * tex2 = new TLatex(0.14,0.92,"Delphes");
  tex2->SetNDC();
  tex2->SetTextFont(61);
  tex2->SetTextSize(0.045);
  tex2->SetLineWidth(2);
  TLatex * tex3 = new TLatex(0.295,0.92,"Simulation Preliminary");
  tex3->SetNDC();
  tex3->SetTextFont(52);
  tex3->SetTextSize(0.04);
  tex3->SetLineWidth(2);

  TLegend* legend = new TLegend(0.55,0.75,0.85,0.89);
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.04);
  legend->SetTextFont(42);
  legend->SetNColumns (3) ;
 
  // make the plot on the same canvas for each variable (legend entry is the cut layer name)  
  vector<TH1F*>  numerator ;
  vector<TH1F*>  denominator ;
  for(size_t iVar = 0; iVar < variableList.size(); iVar++){ // loop on var
   
    numerator.clear();
    denominator.clear();

    for(size_t iCut = 0; iCut < CutList.size(); iCut++){ // loop on cuts
        histoContainer tmpPlot;
        tmpPlot.cutName = CutList.at(iCut).cutLayerName;
        tmpPlot.varName = variableList.at(iVar).variableName;
        vector<histoContainer>::iterator itVec ;
        itVec = find(plotVector.begin(),plotVector.end(),tmpPlot);
        if(itVec == plotVector.end()){
          cerr<<"Problem -->plot not found for "<<CutList.at(iCut).cutLayerName<<"  "<<variableList.at(iVar).variableName<<endl;
        }

       
        itVec->histogram->GetXaxis()->SetTitleSize(0.04);
        itVec->histogram->GetXaxis()->SetTitleOffset(1.16);
        itVec->histogram->GetXaxis()->SetLabelSize(0.04);

        itVec->histogram->GetYaxis()->SetRangeUser(0.001,itVec->histogram->GetMaximum()*1.25);
        itVec->histogram->GetYaxis()->SetTitleSize(0.05);
        itVec->histogram->GetYaxis()->SetTitleOffset(1.20);
        itVec->histogram->GetYaxis()->SetLabelSize(0.04);

        itVec->histogram->SetLineColor(iCut+1);

        if(iCut %2 == 0)
          itVec->histogram->SetLineStyle(1);
        else
          itVec->histogram->SetLineStyle(2);

        itVec->histogram->SetLineWidth(2);
        itVec->histogram->GetYaxis()->SetTitle("#sigma x lumi");

        upperPad->cd();

        if(iCut == 0) 
          itVec->histogram->Draw("hist");
        else
          itVec->histogram->Draw("hist same");

        legend->AddEntry(itVec->histogram,CutList.at(iCut).cutLayerName.c_str(),"l");

        if(itVec->findCutByLabel("LL")) numerator.push_back(itVec->histogram);
        denominator.push_back(itVec->histogram);

	cCanvasNorm->cd();

	TH1F* htempNorm = (TH1F*) itVec->histogram->Clone((string(itVec->histogram->GetName())+"_norm").c_str());
	htempNorm->Scale(1./itVec->histogram->Integral());

	htempNorm->GetYaxis()->SetRangeUser(0.,htempNorm->GetMaximum()*1.5);

        if(iCut == 0)
          htempNorm->Draw("hist");
        else
          htempNorm->Draw("hist same");
    }
    
    // make ratio plot
    lowerPad->cd();
    
    TH1F* numTotal = 0;
    TH1F* denTotal = 0;
    TH1F* ratio    = 0;
    TH1F* ratioW   = 0;

    for(size_t itNum = 0; itNum < numerator.size(); itNum ++){
      if(itNum == 0 and ratio == 0) 
        numTotal = (TH1F*) numerator.at(itNum)->Clone(("Num_"+string(numerator.at(itNum)->GetName())).c_str());
      else if(ratio !=0) 
        numTotal->Add(numerator.at(itNum));
    }

    for(size_t itDen = 0; itDen < denominator.size(); itDen ++){
      if(itDen == 0 and denTotal == 0 ) {
        denTotal = (TH1F*) denominator.at(itDen)->Clone(("Den_"+string(denominator.at(itDen)->GetName())).c_str());
      }
      else if(denTotal !=0){  
        denTotal->Add(denominator.at(itDen));
      }
    }
    
    ratio = new TH1F(("Ratio_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1));
    ratio->GetYaxis()->SetTitle("S/(#sqrt{S+B})");
    ratio->SetMarkerSize(1.1);

    ratioW = new TH1F(("ratioW_"+string(denominator.at(0)->GetName())).c_str(),"",numTotal->GetNbinsX(),numTotal->GetBinLowEdge(1),numTotal->GetBinLowEdge(numTotal->GetNbinsX()+1));
    ratioW->GetYaxis()->SetTitle("weighted S/(#sqrt{S+B})");
    ratioW->SetMarkerSize(1.1);

    TString name = "norm_" ;
    name += denTotal->GetName () ;
    TH1F * norm_denTotal = (TH1F *) denTotal->Clone (name) ;
    norm_denTotal->Scale (1. / norm_denTotal->GetMaximum ()) ; 
    // weight the S/sqrt (B) by the shape of the total, 
    // so that only bins with a lot of stats become visibly significant
    for(int iBin = 0; iBin < ratio->GetNbinsX()+1; iBin++){
      if(denTotal->GetBinContent(iBin) !=0){ 
        ratioW->SetBinContent(iBin,
			      norm_denTotal->GetBinContent (iBin) * numTotal->GetBinContent(iBin) / 
			      sqrt(denTotal->GetBinContent(iBin)));
        ratio->SetBinContent(iBin,
			     numTotal->GetBinContent(iBin) / sqrt(denTotal->GetBinContent(iBin)));
      }
      else 
	ratio->SetBinContent(iBin,0.);
    }
 
    ratio->GetXaxis()->SetTitle("");
    ratio->SetLineColor(kBlue);
    ratio->SetLineStyle(2);
    ratio->SetLineWidth(2);
    ratio->GetXaxis()->SetLabelOffset(999);
    ratio->GetXaxis()->SetLabelSize(0);
    ratio->GetYaxis()->SetLabelSize(0.15);
    ratio->GetYaxis()->SetTitleSize(0.15);
    ratio->GetYaxis()->SetTitleOffset(0.30);
    ratio->GetYaxis()->SetNdivisions(504);

    ratioW->GetXaxis()->SetTitle("");
    ratioW->SetLineColor(kBlack);
    ratioW->SetLineWidth(2);
    ratioW->GetXaxis()->SetLabelOffset(999);
    ratioW->GetXaxis()->SetLabelSize(0);
    ratioW->GetYaxis()->SetLabelSize(0.15);
    ratioW->GetYaxis()->SetTitleSize(0.15);
    ratioW->GetYaxis()->SetTitleOffset(0.30);
    ratioW->GetYaxis()->SetNdivisions(504);

    ratio->GetYaxis()->SetRange(min(ratio->GetMinimum(),ratioW->GetMinimum())*0.9,max(ratio->GetMaximum(),ratioW->GetMaximum())*1.1);    


    TH1F * frame = lowerPad->DrawFrame (ratio->GetXaxis ()->GetXmin (), 0., 
                                        ratio->GetXaxis ()->GetXmax (), 2.) ;
    frame->GetXaxis()->SetTitle (ratio->GetXaxis ()->GetTitle ()) ;
    frame->GetYaxis()->SetTitle (ratio->GetYaxis ()->GetTitle ()) ;
    frame->GetXaxis()->SetLabelOffset(999);
    frame->GetXaxis()->SetLabelSize(0);
    frame->GetYaxis()->SetLabelSize(0.15);
    frame->GetYaxis()->SetTitleSize(0.15);
    frame->GetYaxis()->SetTitleOffset(0.30);
    frame->GetYaxis()->SetNdivisions(504);

    ratio->Draw("P");    
    ratioW->Draw("Lsame");    
    
    upperPad->cd();
    
    tex->Draw("same");
    tex2->Draw("same");
    tex3->Draw("same");
    legend->Draw("same");

    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".png").c_str(),"png");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/xs/"+variableList.at(iVar).variableName+".root").c_str(),"root");

    cCanvasNorm->cd();

    tex->Draw("same");
    tex2->Draw("same");
    tex3->Draw("same");
    legend->Draw("same");

    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".pdf").c_str(),"pdf");
    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".png").c_str(),"png");
    cCanvasNorm->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+".root").c_str(),"root");

    
    legend->Clear();
    
  } // loop on var

  cout<<"LHE filter efficiency : "<<passingLHEFilter<<" totEvent "<<totEvent<<" efficiency "<<float(passingLHEFilter)/float(totEvent)*100<<" % "<<endl;
  
  //Normalize histograms
  for(size_t ihisto = 0; ihisto < plotVector.size(); ihisto++){
    if(plotVector.at(ihisto).varName == "DeltaPhi_LL")
      cout<<"Events Histo "<<plotVector.at(ihisto).histogram->GetName()<<" unweighted "<<plotVector.at(ihisto).histogram->GetEntries()<<" weighted "<<plotVector.at(ihisto).histogram->Integral(0,plotVector.at(ihisto).histogram->GetNbinsX()+1)<<endl;
  }	          

  return 0 ;
}  
TCanvas *drawRatioPlot(TH1D *prediction, TH1D *sr, TString xTitle, TString filename){

  
  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);

  TH1D *ratio = 0;

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

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


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

    cout<<"Scaling Factor in "<<i<<". bin ="<<ratio->GetBinContent(i)<<" +/- "<<ratio->GetBinError(i)<<endl; 

  }

  ratio->GetYaxis()->SetTitle("Pred/Bkg");
  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();

  // 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.6,0.8,0.9,0.9);
  leg->AddEntry(sr,"bkg","l"); 
  leg->AddEntry(prediction,"bkg prediction","pel"); 
  pad1->cd();
  pad1->SetLogy();

  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);

  prediction->Draw("e");
  sr->Draw("e same");

  double maximum =prediction->GetMaximum()*2.5;
  double minimum = 0.00001;
  if(sr->GetMinimum()!=0) minimum=sr->GetMinimum()*0.5;
  if(prediction->GetMinimum()!=0) minimum=prediction->GetMinimum()*0.5;
  if(sr->GetMaximum()>prediction->GetMaximum()){

    maximum=sr->GetMaximum()*2.5;
  }

  prediction->GetYaxis()->SetRangeUser(minimum,maximum);

  leg->Draw("same");




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

  c->SaveAs(filename);

  return c;

}
Exemplo n.º 13
0
void compareplots(){
  vector<TFile*> files; 
  files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_100/ttbar2JetLO8TeVMECut50GeVCTEQ6M-extracted.root"));   
  files.push_back(new TFile("/storage/9/schweiger/analyseFxFx/pythia8/100kEvents/mergingscale_100/ttbarMergedMS100GeVMCCut50GeV8TeVCTEQ6M-extracted.root"));

  



  vector<TString> names;
  names.push_back("ttbar+2 Jets, in LO");
  names.push_back("ttbar+1 Jet, FxFx-Merged");

  
  vector<TString> titles;
  titles.push_back("Gen-Jet p_{T}  with pos weights (GeV)");
  titles.push_back("Gen-Jet p_{T} with neg weights (GeV)");
  titles.push_back("Gen-Jet p_{T} (GeV)");
  titles.push_back("Gen_Jet #phi with pos. weights");
  titles.push_back("Gen_Jet #phi with neg. weights");
  titles.push_back("Gen_Jet #phi");
  titles.push_back("Gen Jet #theta with pos weights");
  titles.push_back("Gen Jet #theta with neg weights");
  titles.push_back("Gen Jet #theta");
  titles.push_back("Gen Jet Energy with pos weights (GeV) ");
  titles.push_back("Gen Jet Energy with neg weights (GeV)");
  titles.push_back("Gen Jet Energy (GeV)");
  titles.push_back("p_{T} of hardest Gen-Jet with pos weights (GeV)");
  titles.push_back("p_{T} of hardest Gen-Jet with neg weights (GeV)");
  titles.push_back("p_{T} of hardest Gen-Jet (GeV)");
  titles.push_back("p_{T} of 2nd hardest Gen-Jet with pos weights (GeV)");
  titles.push_back("p_{T} of 2nd hardest Gen-Jet with neg weights (GeV)");
  titles.push_back("p_{T} of 2nd hardest Gen-Jet (GeV)");
  titles.push_back("#eta of hardest Gen-Jets with pos weights");
  titles.push_back("#eta of hardest Gen-Jets with neg weights");
  titles.push_back("#eta of hardest Gen-Jets");
  titles.push_back("Number of Gen-Jets with pos. weights");
  titles.push_back("Number of Gen-Jets with neg. weights");
  titles.push_back("Number of Gen-Jets");


  TFile *vergleich = new TFile("vergleich_ttbar_Fx_vs_noFx.root","RECREATE");


// Show no statistics box
gStyle->SetOptStat(0);

TH1::SetDefaultSumw2();

// Main program part
  TIter nextkey(files.at(0)->GetListOfKeys());
  TKey *key;
  bool first=true;
  TCanvas* c = new TCanvas();
  c->Print("plots.pdf[");

  // Save also as pictures
  int pictureNumber = 0;

  int run = 0;
  while (key = (TKey*)nextkey()) {
    pictureNumber++;
    TString pictureName = TString::Format("%d.png",pictureNumber);


    vector<TH1F*> histos;
    histos.push_back((TH1F*)key->ReadObj());
    for(size_t i=1;i<files.size();i++){
      histos.push_back((TH1F*)files.at(i)->Get(histos.at(0)->GetName()));
    }
		       
    for(size_t i=0;i<histos.size();i++){
      if(i == 0){
	histos.at(i)->SetLineColor(kBlack);
      }
      if(i == 1){
	histos.at(i)->SetLineColor(kRed);
      }
      if(i == 2){
	histos.at(i)->SetLineColor(kBlue);
      }
      if(i == 3){
	histos.at(i)->SetLineColor(kGreen+2);
      }
      if(i == 4){
	histos.at(i)->SetLineColor(kMagenta-7);
      }
      if(i == 5){
	histos.at(i)->SetLineColor(kOrange+7);
      }
    }
    
    for(size_t i=0;i<histos.size();i++){
      histos.at(i)->Sumw2();
      histos.at(i)->Scale(1./histos.at(i)->Integral(),"width");
    }

// Set axis title
histos.at(0)->GetYaxis()->SetTitle("Normalized units"); 
std::string const histogramName = histos.at(0)->GetName();
histos.at(0)->GetXaxis()->SetLabelSize(0.06);
histos.at(0)->GetXaxis()->SetLabelOffset(0.006);
histos.at(0)->GetYaxis()->SetLabelSize(0.06);
histos.at(0)->GetYaxis()->SetLabelOffset(0.006);
histos.at(0)->GetXaxis()->SetTitleSize(0.06);
histos.at(0)->GetXaxis()->SetTitleOffset(1.1);
histos.at(0)->GetYaxis()->SetTitleSize(0.06);
histos.at(0)->GetYaxis()->SetTitleOffset(1.08);



histos.at(0)->GetXaxis()->SetTitle(titles.at(run));
run = run+1;
 if(run == (3*8)){
   run = 0;
 }
// If only two histograms per plot make a ratio plot
if(histos.size() == 2)
{

//create main pad  
                                                                                                                                                          
           TPad *mainPad = new TPad("","",0.0,0.3,1.0,1.0);
           mainPad->SetNumber(1);
           mainPad->SetBottomMargin(0.0);
           mainPad->SetRightMargin(0.04);
	   mainPad->SetLeftMargin(0.13);
           mainPad->Draw();

           //create ratio pad                                                                                                                                                           
           TPad *ratioPad = new TPad("","",0.0,0.0,1.0,0.3);
           ratioPad->SetTopMargin(0.0);
           ratioPad->SetBottomMargin(0.4);
           ratioPad->SetLeftMargin(0.13);                                                                                                                                             
           ratioPad->SetRightMargin(0.04);
           gStyle->SetOptTitle(0);
           ratioPad->SetFillColor(0);
           ratioPad->SetNumber(2);
           ratioPad->SetGridy();                                                                                                                                                      
           ratioPad->Draw();

// Draw both histograms first
c->cd(1);

histos.at(0)->Draw("histo E");
histos.at(1)->Draw("histo same E");

// Show legend and statistical tests in first pad
    for(size_t i=0;i<histos.size()-1;i=i+2){

      double ksresult = histos.at(i)->KolmogorovTest(histos.at(i+1));
      ksresult=floor(ksresult*1000+0.5)/1000;
      double chi2result =histos.at(i)->Chi2Test(histos.at(i+1),"WW");
      chi2result=floor(chi2result*1000+0.5)/1000;

      stringstream ss;
      ss << "     KS: " <<std::setprecision(3) << ksresult << " chi2: " <<std::setprecision(3) << chi2result << " Private Work"; 
      const char * ch = & ss.str().c_str();;
      TLatex * ks = new TLatex(0.1, 0.9-0.03*i, ch );
      ks->SetTextColor(histos.at(i)->GetLineColor());
      ks->SetNDC();
      ks->Draw("");      

    }

    TLegend* l = new TLegend(0.55,0.9,0.69,0.99);
    // Options for legend
    l->SetBorderSize(0);
    l->SetLineStyle(0);
    l->SetTextSize(0.049);
    l->SetFillStyle(0);
    for(size_t i=0;i<names.size();i++){
      l->AddEntry(histos.at(i),names.at(i),"L");
    }
    l->Draw("same");


// Clone histograms and draw ratio plot
c->cd(2);
 TH1F* ratioHisto = (TH1F*)histos.at(0)->Clone();
ratioHisto->Divide(histos.at(1));
ratioHisto->SetLineColor(kBlue);
ratioHisto->SetStats(false);
ratioHisto->GetYaxis()->SetTitle("Ratio #frac{noFxFx}{FxFx}");
// Same Size like in histogram
ratioHisto->SetLabelSize(histos.at(0)->GetLabelSize() * 0.7 / 0.3);
ratioHisto->SetTitleOffset((histos.at(0)->GetTitleOffset("Y") * 0.3 / 0.7), "Y");
ratioHisto->SetTitleSize((histos.at(0)->GetTitleSize("Y") * 0.7 / 0.3), "Y");
ratioHisto->SetTitleOffset((histos.at(0)->GetTitleOffset("X")), "X");
ratioHisto->SetTitleSize((histos.at(0)->GetTitleSize("X") * 0.7 / 0.3), "X");
// Use nicer range
ratioHisto->GetYaxis()->SetRangeUser(0, 2.2);
ratioHisto->GetYaxis()->SetNdivisions(503);
ratioHisto->GetYaxis()->SetLabelSize(0.06 * 0.7 / 0.3);
ratioHisto->Draw();
}
else
{

    histos.at(0)->Draw("histo E");
    for(size_t i=0;i<histos.size();i++){
      histos.at(i)->Draw("histo same E");
    }


    for(size_t i=0;i<histos.size()-1;i=i+2){

      double ksresult = histos.at(i)->KolmogorovTest(histos.at(i+1));
      ksresult=floor(ksresult*1000+0.5)/1000;
      double chi2result =histos.at(i)->Chi2Test(histos.at(i+1),"WW");
      chi2result=floor(chi2result*1000+0.5)/1000;

      stringstream ss;
      ss << "KS: " <<std::setprecision(3) << ksresult << " chi2: " <<std::setprecision(3) << chi2result; 
      const char * ch = & ss.str().c_str();;
      TText * ks = new TText(0.1, 0.9-0.03*i, ch );
      ks->SetTextColor(histos.at(i)->GetLineColor());
      ks->SetNDC();
      ks->Draw("");      

    }

    TLegend* l = new TLegend(0.65,0.5,0.9,0.7);
    l->SetBorderSize(0);
    l->SetLineStyle(0);
    //    l->SetTextSize(0.039);
    l->SetFillStyle(0);
    for(size_t i=0;i<names.size();i++){
      l->AddEntry(histos.at(i),names.at(i),"L");
    }
    l->Draw("same");
}

    c->Print("plots.pdf");
    c->SaveAs(pictureName);
    vergleich->WriteTObject(c);

}
  c->Print("plots.pdf]");


}
void QA_Draw_Jet_Summary(const char *jet_family = "AntiKt_Tower",
                         const char *qa_file_name_new =
                             "data/G4sPHENIXCells_2000jets25GeV.root_qa.root",
                         const char *qa_file_name_ref =
                             "data/G4sPHENIXCells_250jets25GeV.root_qa.root")
{
  //! drawing energy range
  const double min_Et = 10;
  const double max_Et = 80;

  SetsPhenixStyle();
  TVirtualFitter::SetDefaultFitter("Minuit2");

  // file IO
  TFile *qa_file_new = new TFile(qa_file_name_new);
  assert(qa_file_new->IsOpen());

  // buffer for results
  vector<float> vec_radius;
  vector<TGraphErrors *> vec_phi_res;
  vector<TGraphErrors *> vec_eta_res;
  vector<TGraphErrors *> vec_e_res;
  vector<TGraphErrors *> vec_et_res;
  vector<TGraphErrors *> vec_reco_eff;
  vector<TGraphErrors *> vec_purity;

  // list and process all jets
  TList *hist_key_list = qa_file_new->GetListOfKeys();
  for (int i = 0; i < hist_key_list->GetSize(); ++i)
  {
    TString key_name = hist_key_list->At(i)->GetName();

    TString s_re_fullname = Form(
        "h_QAG4SimJet_.*_r[0-9]*_%s_r[0-9]*_Matching_Count_Truth_Et",
        jet_family);  // regular expression for search
    TRegexp re_fullname(s_re_fullname, false);
    if (key_name.Index(re_fullname) == kNPOS)
      continue;

    //      cout << " key_name = " << key_name << endl;
    TString jet_pair_name = key_name(0,
                                     key_name.Length() - TString("_Matching_Count_Truth_Et").Length());  // remove suffix

    //      cout << " jet_pair_name = " << jet_pair_name << endl;

    //get jet radius
    TRegexp re_jetradius("_r[0-9]*", false);
    Ssiz_t index_radius = key_name.Index(re_jetradius);             // first radius
    index_radius = key_name.Index(re_jetradius, index_radius + 1);  // second radius
    assert(index_radius != kNPOS);
    float radius = 0;
    sscanf(key_name(index_radius, 100).Data(), "_r%f", &radius);
    //      cout << " index_radius = " << index_radius << endl;
    assert(radius != 0);
    radius /= 10;  // jet radius convention in DST names

    cout << "QA_Draw_Jet_Summary - process jet pair " << jet_pair_name
         << " with radius = " << radius << endl;

    vector<TGraphErrors *> resolution_efficiency_summary(
        QA_Draw_Jet_TruthMatching(jet_pair_name, qa_file_name_new,
                                  qa_file_name_ref));

    //save results
    vec_radius.push_back(radius);
    vec_phi_res.push_back(resolution_efficiency_summary[0]);
    vec_eta_res.push_back(resolution_efficiency_summary[1]);
    vec_e_res.push_back(resolution_efficiency_summary[2]);
    vec_et_res.push_back(resolution_efficiency_summary[3]);
    vec_reco_eff.push_back(resolution_efficiency_summary[4]);
    vec_purity.push_back(resolution_efficiency_summary[5]);

    //      break;
  }

  // plot
  TCanvas *c1 = new TCanvas(
      TString("QA_Draw_Jet_Summary_") + TString(jet_family),
      TString("QA_Draw_Jet_Summary_") + TString(jet_family), 1800, 900);
  c1->Divide(3, 2);
  int idx = 1;
  TPad *p;

  // ------------------------------------
  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogz();

  TH1 *h_frame =
      p->DrawFrame(min_Et, -.1, max_Et, .1,
                   TString(jet_family) + " #phi Reconstruction;E_{T, Truth} (GeV);#phi_{Reco} - #phi_{Truth} (rad)");
  //  h_frame->GetYaxis()->SetTitleOffset(1.01);
  TLine *l = new TLine(min_Et, 0, max_Et, 0);
  l->Draw();
  p->SetGridx(0);
  p->SetGridy(0);
  TLegend *legend = new TLegend(0.7, 0.2, .95, 0.5);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(1001);
  legend->SetLineWidth(2);
  legend->SetLineColor(kBlack);
  legend->SetLineStyle(kSolid);
  for (int i = 0; i < vec_radius.size(); ++i)
  {
    const float radius = vec_radius[i];

    TGraphErrors *ge = vec_phi_res[i];
    assert(ge);
    ge = new TGraphErrors(*ge);  // make a copy

    ge->SetLineColor(i + 2);    // automatic color scheme from ROOT
    ge->SetMarkerColor(i + 2);  // automatic color scheme from ROOT
    for (int idata = 0; idata < ge->GetN(); ++idata)
    {
      (ge->GetX())[idata] += i * 0.5;  // shift x a little bit
      (ge->GetEX())[idata] = 0;        // no x error bar
    }
    ge->Draw("p E l");
    legend->AddEntry(ge, Form("r = %.1f", radius), "elp");
  }
  legend->Draw();

  // ------------------------------------
  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogz();

  h_frame =
      p->DrawFrame(min_Et, -.1, max_Et, .1,
                   TString(jet_family) + " #eta Reconstruction;E_{T, Truth} (GeV);#eta_{Reco} - #eta_{Truth}");
  //  h_frame->GetYaxis()->SetTitleOffset(1.01);
  l = new TLine(min_Et, 0, max_Et, 0);
  l->Draw();
  p->SetGridx(0);
  p->SetGridy(0);
  legend = new TLegend(0.7, 0.2, .95, 0.5);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(1001);
  legend->SetLineWidth(2);
  legend->SetLineColor(kBlack);
  legend->SetLineStyle(kSolid);
  for (int i = 0; i < vec_radius.size(); ++i)
  {
    const float radius = vec_radius[i];

    TGraphErrors *ge = vec_eta_res[i];
    assert(ge);
    ge = new TGraphErrors(*ge);  // make a copy

    ge->SetLineColor(i + 2);    // automatic color scheme from ROOT
    ge->SetMarkerColor(i + 2);  // automatic color scheme from ROOT
    for (int idata = 0; idata < ge->GetN(); ++idata)
    {
      (ge->GetX())[idata] += i * 0.5;  // shift x a little bit
      (ge->GetEX())[idata] = 0;        // no x error bar
    }
    ge->Draw("p E l");
    legend->AddEntry(ge, Form("r = %.1f", radius), "elp");
  }
  legend->Draw();

  // ------------------------------------
  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogz();

  h_frame = p->DrawFrame(min_Et, 0, max_Et, 2,
                         TString(jet_family) + " Jet Energy Reconstruction;E_{Truth} (GeV);E_{Reco} / E_{Truth}");
  //  h_frame->GetYaxis()->SetTitleOffset(1.01);
  l = new TLine(min_Et, 1, max_Et, 1);
  l->Draw();
  p->SetGridx(0);
  p->SetGridy(0);
  legend = new TLegend(0.7, 0.2, .95, 0.5);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(1001);
  legend->SetLineWidth(2);
  legend->SetLineColor(kBlack);
  legend->SetLineStyle(kSolid);
  for (int i = 0; i < vec_radius.size(); ++i)
  {
    const float radius = vec_radius[i];

    TGraphErrors *ge = vec_e_res[i];
    assert(ge);
    ge = new TGraphErrors(*ge);  // make a copy

    ge->SetLineColor(i + 2);    // automatic color scheme from ROOT
    ge->SetMarkerColor(i + 2);  // automatic color scheme from ROOT
    for (int idata = 0; idata < ge->GetN(); ++idata)
    {
      (ge->GetX())[idata] += i * 0.5;  // shift x a little bit
      (ge->GetEX())[idata] = 0;        // no x error bar
    }
    ge->Draw("p E l");
    legend->AddEntry(ge, Form("r = %.1f", radius), "elp");
  }
  legend->Draw();

  // ------------------------------------
  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogz();

  h_frame =
      p->DrawFrame(min_Et, 0, max_Et, 2,
                   TString(jet_family) + " Jet E_{T} Reconstruction;E_{T, Truth} (GeV);E_{T, Reco} / E_{T, Truth}");
  //  h_frame->GetYaxis()->SetTitleOffset(1.01);
  l = new TLine(min_Et, 1, max_Et, 1);
  l->Draw();
  p->SetGridx(0);
  p->SetGridy(0);
  legend = new TLegend(0.7, 0.2, .95, 0.5);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(1001);
  legend->SetLineWidth(2);
  legend->SetLineColor(kBlack);
  legend->SetLineStyle(kSolid);
  for (int i = 0; i < vec_radius.size(); ++i)
  {
    const float radius = vec_radius[i];

    TGraphErrors *ge = vec_et_res[i];
    assert(ge);
    ge = new TGraphErrors(*ge);  // make a copy

    ge->SetLineColor(i + 2);    // automatic color scheme from ROOT
    ge->SetMarkerColor(i + 2);  // automatic color scheme from ROOT
    for (int idata = 0; idata < ge->GetN(); ++idata)
    {
      (ge->GetX())[idata] += i * 0.5;  // shift x a little bit
      (ge->GetEX())[idata] = 0;        // no x error bar
    }
    ge->Draw("p E l");
    legend->AddEntry(ge, Form("r = %.1f", radius), "elp");
  }
  legend->Draw();

  // ------------------------------------
  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogz();

  h_frame = p->DrawFrame(min_Et, 0, max_Et, 1.2,
                         TString(jet_family) + " Reco Efficiency;E_{T, Truth} (GeV);Reco efficiency");
  //  h_frame->GetYaxis()->SetTitleOffset(1.01);
  l = new TLine(min_Et, 1, max_Et, 1);
  l->Draw();
  p->SetGridx(0);
  p->SetGridy(0);
  legend = new TLegend(0.7, 0.2, .95, 0.5);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(1001);
  legend->SetLineWidth(2);
  legend->SetLineColor(kBlack);
  legend->SetLineStyle(kSolid);
  for (int i = 0; i < vec_radius.size(); ++i)
  {
    const float radius = vec_radius[i];

    TGraphErrors *ge = vec_reco_eff[i];
    assert(ge);
    ge = new TGraphErrors(*ge);  // make a copy

    ge->SetLineColor(i + 2);    // automatic color scheme from ROOT
    ge->SetMarkerColor(i + 2);  // automatic color scheme from ROOT
    for (int idata = 0; idata < ge->GetN(); ++idata)
    {
      (ge->GetX())[idata] += i * 0.5;  // shift x a little bit
      (ge->GetEX())[idata] = 0;        // no x error bar
    }
    ge->Draw("p E l");
    legend->AddEntry(ge, Form("r = %.1f", radius), "elp");
  }
  legend->Draw();

  // ------------------------------------
  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogz();

  h_frame = p->DrawFrame(min_Et, 0, max_Et, 1.2,
                         TString(jet_family) + " Reconstruction Purity;E_{T, Reco} (GeV);Reconstruction Purity");
  //  h_frame->GetYaxis()->SetTitleOffset(1.01);
  l = new TLine(min_Et, 1, max_Et, 1);
  l->Draw();
  p->SetGridx(0);
  p->SetGridy(0);
  legend = new TLegend(0.7, 0.2, .95, 0.5);
  legend->SetFillColor(kWhite);
  legend->SetFillStyle(1001);
  legend->SetLineWidth(2);
  legend->SetLineColor(kBlack);
  legend->SetLineStyle(kSolid);
  for (int i = 0; i < vec_radius.size(); ++i)
  {
    const float radius = vec_radius[i];

    TGraphErrors *ge = vec_purity[i];
    assert(ge);
    ge = new TGraphErrors(*ge);  // make a copy

    ge->SetLineColor(i + 2);    // automatic color scheme from ROOT
    ge->SetMarkerColor(i + 2);  // automatic color scheme from ROOT
    for (int idata = 0; idata < ge->GetN(); ++idata)
    {
      (ge->GetX())[idata] += i * 0.5;  // shift x a little bit
      (ge->GetEX())[idata] = 0;        // no x error bar
    }
    ge->Draw("p E l");
    legend->AddEntry(ge, Form("r = %.1f", radius), "elp");
  }
  legend->Draw();

  //  PutInputFileName(c1, .03, qa_file_name_new, qa_file_name_ref);
  SaveCanvas(c1, TString(qa_file_name_new) + TString(c1->GetName()), true);
}
Exemplo n.º 15
0
void FastVsSlowSimEff(Int_t id=0,Int_t PbPb=0) {

  Int_t mult = 2400; // 2800  // deducted from "Frackable"
  if (PbPb) mult=2800;


  Int_t plusTPC =0;

  gROOT->LoadMacro("~/fig_template.C"); // figure style
  myOptions(0);
  gROOT->ForceStyle();

  TCanvas *myCan = new TCanvas("myCan");
  myCan->Draw();
  myCan->cd();
  
  TPad *myPad = new TPad("myPad", "The pad",0,0,1,1);
  myPadSetUp(myPad,0.15,0.04,0.04,0.15);
  myPad->Draw();   myPad->cd();
  myPad->SetGridx();   myPad->SetGridy();//  myPad->SetLogx();


  TLegend *leg = new TLegend(0.9,30,1.7,70,"","brCDN"); 
  leg->SetFillColor(0);

  TGraph *c[6];
  if (id!=2) {
  
  
    // Current ITS +++++++++++++++++++++++++++++++++++++++++
    Int_t color=1; Int_t linewidth=2;

    Int_t pi =0;
 
    DetectorK its("ALICE","ITS");
    its.MakeAliceCurrent(0,plusTPC);
    its.SetMaxRadiusOfSlowDetectors(0.01);
    its.SetAtLeastCorr(atLeastcorr);
    if (PbPb) its.SetdNdEtaCent(mult);
    its.SolveViaBilloir(0);
    Int_t color=1; Int_t linewidth=2;

    if (id==0)
      c[pi] = its.GetGraphRecoEfficiency(0,color,linewidth);
    else if (id==1)
      c[pi] = its.GetGraphRecoPurity(0,color,linewidth);
    else 
      c[pi] = its.GetGraphRecoFakes(0,color,linewidth);

    c[pi]->Draw("AC");

    leg->AddEntry(c[pi],"FastTool: Current ITS","l");


    // NEW SPD  +++++++++++++++++++++++++++++++++++++++++

    Int_t color=3; Int_t linewidth=2;
    Int_t pi =2;

    DetectorK its("ALICE","ITS");
    its.MakeAliceCurrent(0,plusTPC);
    its.SetAtLeastCorr(atLeastcorr);
    if (PbPb) its.SetdNdEtaCent(mult);
    its.SetRadius("bpipe",2.0);
    its.AddLayer("spd0", 2.2,1,1,1);  

    its.SetRadius("spd0",2.2); its.SetRadiationLength("spd0",X0); its.SetResolution("spd0",resRPhi,resZ);
    its.SetRadius("spd1",4.8);   its.SetRadiationLength("spd1",X0); its.SetResolution("spd1",resRPhi,resZ);
    its.SetRadius("spd2",9.1);   its.SetRadiationLength("spd2",X0); its.SetResolution("spd2",resRPhi,resZ);

    its.SetMaxRadiusOfSlowDetectors(0.1);
    its.SolveViaBilloir(0);

    if (id==0)
      c[pi] = its.GetGraphRecoEfficiency(0,color,linewidth);
    else if (id==1)
      c[pi] = its.GetGraphRecoPurity(0,color,linewidth);
    else 
      c[pi] = its.GetGraphRecoFakes(0,color,linewidth);
   
    c[pi]->Draw("C");

    leg->AddEntry(c[pi],"FastTool: \"New SPDs\"","l");


    // ALL NEW +++++++++++++++++++++++++++++++++++++++++++

    color=4; Int_t linewidth=2;
    Int_t pi =1; 


    // for a 0.8,0.2 weight configuration
  
    DetectorK *itsU = new DetectorK((char*)"ALICE",(char*)"ITS");
    itsU->SetAtLeastCorr(atLeastcorr);
    itsU->AddLayer((char*)"bpipe", 2.0,0.0022); // beam pipe
    itsU->AddLayer((char*)"vertex",  0,     0); // dummy vertex for matrix calculation
  
    itsU->AddLayer("ddd1",  2.2 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd2",  3.8 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd3",  6.8 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd4", 12.4 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd5", 23.5 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd6", 39.6 ,  X0, resRPhi, resZ); 
    //    itsU->AddLayer("ddd6", 42.6 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd7", 43.0 ,  X0, resRPhi, resZ); 
    //    itsU->AddLayer("ddd8", 43.4 ,  X0, resRPhi, resZ); 


    if (PbPb) itsU->SetdNdEtaCent(mult);
    if(plusTPC) itsU->AddTPC(0.1,0.1);
    itsU->SetMaxRadiusOfSlowDetectors(0.1);
    itsU->SolveViaBilloir(0);
    itsU->PrintLayout();

    if (id==0)
      c[pi] = itsU->GetGraphRecoEfficiency(0,color,linewidth);
    else if (id==1)
      c[pi] = itsU->GetGraphRecoPurity(0,color,linewidth);
    else 
      c[pi] = itsU->GetGraphRecoFakes(0,color,linewidth);
    c[pi]->Draw("C");

    leg->AddEntry(c[pi],"FastTool: \"All New\" ","l");

    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

 // ALL NEW - double outer layer +++++++++++++++++++++++++++++++++++++

    color=2; Int_t linewidth=2;
    Int_t pi =3; 


    // for a 0.8,0.2 weight configuration
  
    DetectorK *itsU = new DetectorK((char*)"ALICE",(char*)"ITS");
    itsU->SetAtLeastCorr(atLeastcorr);
    itsU->AddLayer((char*)"bpipe", 2.0,0.0022); // beam pipe
    itsU->AddLayer((char*)"vertex",  0,     0); // dummy vertex for matrix calculation
  
    itsU->AddLayer("ddd1",  2.2 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd2",  3.8 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd3",  6.8 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd4", 12.4 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd5", 23.5 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd6", 39.6 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd8", 40.0 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd7", 43.0 ,  X0, resRPhi, resZ); 
    itsU->AddLayer("ddd9", 43.4 ,  X0, resRPhi, resZ); 


    if (PbPb) itsU->SetdNdEtaCent(mult);
    if(plusTPC) itsU->AddTPC(0.1,0.1);
    itsU->SetMaxRadiusOfSlowDetectors(0.1);
    itsU->SolveViaBilloir(0);
    itsU->PrintLayout();

    if (id==0)
      c[pi] = itsU->GetGraphRecoEfficiency(0,color,linewidth);
    else if (id==1)
      c[pi] = itsU->GetGraphRecoPurity(0,color,linewidth);
    else 
      c[pi] = itsU->GetGraphRecoFakes(0,color,linewidth);
    c[pi]->Draw("C");

    leg->AddEntry(c[pi],"FastTool: \"All New\" (2x double layer)","l");

    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


  }

  char h[100];
  if (PbPb==0) 
    sprintf(h,"-fran");
  else 
    sprintf(h,"-Anna");

  TFile f1(Form("root/FastVsSlow_CurrentITS-PbPb%s.root",h));
  TFile f2(Form("root/FastVsSlow_NewSPDs-PbPb%s.root",h));
  TFile f3(Form("root/FastVsSlow_AllNew-PbPb%s.root",h));
  TFile f4(Form("root/FastVsSlow_AllNew-9-PbPb%s.root",h));

  //  TFile f1(Form("root/FastVsSlow_CurrentITS%s-fran.root",h));
  //  TFile f2(Form("root/FastVsSlow_NewSPDs%s-fran.root",h));
  //  TFile f3(Form("root/FastVsSlow_AllNew%s-fran.root",h));

  TH1F *eff1 = 0;
  TH1F *eff2 = 0;
  TH1F *eff3 = 0;
  TH1F *eff4 = 0;
  if (id==0) {
    eff1 = (TH1F*)f1.Get("efficiency");
    eff2 = (TH1F*)f2.Get("efficiency");
    eff3 = (TH1F*)f3.Get("efficiency");
    eff4 = (TH1F*)f4.Get("efficiency");
    eff1->GetYaxis()->SetTitle("efficiency (%)");
  } else if (id==1) {
    eff1 = (TH1F*)f1.Get("purity");
    eff2 = (TH1F*)f2.Get("purity");
    eff3 = (TH1F*)f3.Get("purity");
    eff4 = (TH1F*)f4.Get("purity");
      eff1->GetYaxis()->SetTitle("purity (%)");
  } else if (id==2) {
    eff1 = (TH1F*)f1.Get("annaEff");
    eff2 = (TH1F*)f2.Get("annaEff");
    eff3 = (TH1F*)f3.Get("annaEff");
    eff4 = (TH1F*)f4.Get("annaEff");
    eff1->GetYaxis()->SetTitle("Overall efficiency (%)");
  } else if (id==3) {
    eff1 = (TH1F*)f1.Get("fake");
    eff2 = (TH1F*)f2.Get("fake");
    eff3 = (TH1F*)f3.Get("fake");
    eff4 = (TH1F*)f4.Get("fake");
    eff1->GetYaxis()->SetTitle("Fake ratio (%)");
  }

  eff1->SetMarkerStyle(21); eff1->SetMarkerColor(1);
  eff2->SetMarkerStyle(21); eff2->SetMarkerColor(3);
  eff3->SetMarkerStyle(21); eff3->SetMarkerColor(4);
  eff4->SetMarkerStyle(21); eff4->SetMarkerColor(2);

  leg->AddEntry(eff1,"FullMC: Current ITS","PE");
  leg->AddEntry(eff2,"FullMC: \"New SPDs\"","PE");
  leg->AddEntry(eff3,"FullMC: \"All New\" ","PE");
  leg->AddEntry(eff4,"FullMC: \"All New\" (2x double layer)","PE");

  eff1->SetMinimum(0.4); eff1->SetMaximum(100);
  eff1->DrawCopy("E");
  eff2->DrawCopy("sameE");
  eff4->DrawCopy("sameE");
  eff3->DrawCopy("sameE");
  if (id!=2) {
    c[0]->Draw("C");
    c[1]->Draw("C");
    c[2]->Draw("C");
    c[3]->Draw("C");
  }
  eff2->DrawCopy("sameE");
  eff4->DrawCopy("sameE");
  eff3->DrawCopy("sameE");

  
  leg->Draw();
 



  TPaveText *pt = 0;
  if (id!=3) 
   pt = new TPaveText(0.4,0.1,1.76,30);
  else
   pt = new TPaveText(0.4,70,1.76,100);
    
  pt->SetBorderSize(1); // no shadow
  pt->SetTextFont(12);
  TText *t1 = pt->AddText("FastTool settings: "); t1->SetTextFont(32); // bold

  pt->AddText(Form("   Tracked particles: Pions;   Average rapidity: 0.45; dN_{ch}/d#eta = %d ",mult));

  //  pt->AddText("\"New SPDs\": layer radii: r = {2.2,4.8,9.1} cm");
  //  pt->AddText("\"All New\: layer radii: r = {2.2,3.8,6.8,...} cm");
  //  pt->AddText(Form("    New layer prop.: X/X_{0}=%1.1lf%%;  #sigma_{r#phi,z}=%1.0lf#mum",X0*100,resZ*1e4));
  
  TText *t2 = pt->AddText("FullMC settings: "); t2->SetTextFont(32); // bold
  if (PbPb==0) {
    pt->AddText("   Generator: AliGenHIJINGpara (parametrized PbPb event)");
    pt->AddText("   dN_{ch.pr.}/d#eta = 2070");
    pt->AddText("   Track selection: Pions, |#eta|<0.9");
  } else {
    pt->AddText("   Generator: AliGenHijing (modified);  #sqrt{s_{NN}} = 5.5 TeV");
    pt->AddText("   dN_{ch.pr.}/d#eta = 2410; Impactparameter range: b#in(0,5)  #rightarrow central PbPb ");
    pt->AddText("   Track selection: Pions, |#eta|<0.9");
  }
  //  pt->SetLabel("Settings");
  pt->SetTextAlign(12);
  pt->SetFillColor(0);
  pt->Draw();





  if (PbPb==0) {    
    myCan->SaveAs(Form("FastVsSlowSim-Eff-%d.pdf",id));
    myCan->SaveAs(Form("FastVsSlowSim-Eff-%d.eps",id));
  }else{
    myCan->SaveAs(Form("FastVsSlowSim-Eff-PbPb-%d.pdf",id));
    myCan->SaveAs(Form("FastVsSlowSim-Eff-PbPb-%d.eps",id));
  }




}
Exemplo n.º 16
0
void Plot_muons(){
  
 
  gStyle->SetOptStat(0);
  gStyle->SetOptDate(0);
  gStyle->SetOptFit(0111);
  
  int ChComb=1;// 0=Same-charge, 1=Mixed-charge
  int kTbin_L=5, kTbin_H=6;
  int binKT3=1;//1-2

  //TFile *_file0= new TFile("Results/PDC_12a17a_muons_R6.root","READ");
  //TFile *_file0= new TFile("Results/PDC_13b2_efix_p1_muons_R2.root","READ");
  TFile *_file0= new TFile("Results/PDC_12a17e_muons_R4.root","READ");
  
  TList *MyList=(TList*)_file0->Get("MyList");
  _file0->Close();

  TH1D *PionCandidates=(TH1D*)MyList->FindObject("fPionCandidates");
  PionCandidates->GetXaxis()->SetTitle("PDG code");
  //PionCandidates->Draw();
  //
  TH1D *MuonParentsPrimary=(TH1D*)MyList->FindObject("fMuonParents");
  MuonParentsPrimary->GetXaxis()->SetTitle("PDG code");
  MuonParentsPrimary->SetFillColor(1);
  //MuonParentsPrimary->Draw();
  //
  TH1D *MuonParentsSecondary=(TH1D*)MyList->FindObject("fSecondaryMuonParents");
  MuonParentsSecondary->GetXaxis()->SetTitle("PDG code");
  MuonParentsSecondary->SetFillColor(1);
  //MuonParentsSecondary->Draw();
  //
  // M0 R10-R6, M6 for R4, M17 for R2
  TH3D *PurityNum_3D = (TH3D*)MyList->FindObject("Explicit2_Charge1_1_Charge2_1_SC_0_M_6_ED_0_Term_1_PIDpurityNum");
  TH2D *PurityDen_2D = (TH2D*)MyList->FindObject("Explicit2_Charge1_1_Charge2_1_SC_0_M_6_ED_0_Term_1_PIDpurityDen");
  TH1D *PurityNum=PurityNum_3D->ProjectionX("PurityNum",kTbin_L,kTbin_H,1,20);
  double PurityNorm=PurityDen_2D->Integral(kTbin_L,kTbin_H,1,20);
  PurityNum->Scale(1/PurityNorm);
  char *namesAxis[15]={"e-e","e-mu","e-pi","e-k","e-p","mu-mu","mu-pi","mu-k","mu-p","pi-pi","pi-k","pi-p","k-k","k-p","p-p"};
  for(int i=1; i<=15; i++) PurityNum->GetXaxis()->SetBinLabel(i, namesAxis[i-1]);
  PurityNum->GetXaxis()->SetRange(1,15);
  PurityNum->GetYaxis()->SetTitle("Probability");
  PurityNum->Draw();
  //
  //
  TCanvas *can = new TCanvas("can", "can",800,0,800,800);// 11,53,700,500
  can->SetHighLightColor(2);
  gStyle->SetOptFit(0111);
  can->SetFillColor(10);//10
  can->SetBorderMode(0);
  can->SetBorderSize(2);
  can->SetFrameFillColor(0);
  can->SetFrameBorderMode(0);
  can->SetFrameBorderMode(0);
  can->cd();
  TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
  gPad->SetTickx();
  gPad->SetTicky();
  pad->SetGridx();
  pad->SetGridy();
  pad->SetTopMargin(0.02);//0.05
  pad->SetRightMargin(0.02);//3e-2
  pad->SetBottomMargin(0.1);//0.12
  pad->SetLeftMargin(0.1);
  pad->Draw();
  pad->cd();
  TLegend *legend = new TLegend(.5,.65, .9,.95,NULL,"brNDC");//.45 or .4 for x1
  legend->SetBorderSize(0);
  legend->SetFillColor(0);
  legend->SetTextFont(42);
  legend->SetTextSize(0.03);
  //
  TH3D *MuonSmearedNum2_3=(TH3D*)MyList->FindObject("fMuonContamSmearedNum2");
  TH3D *MuonSmearedDen2_3=(TH3D*)MyList->FindObject("fMuonContamSmearedDen2");
  TH3D *PionNum2_3=(TH3D*)MyList->FindObject("fMuonContamIdealNum2");
  TH3D *PionDen2_3=(TH3D*)MyList->FindObject("fMuonContamIdealDen2");
  TH3D *PionPionK2_3=(TH3D*)MyList->FindObject("fPionPionK2");
  //
  TH3D *MuonSmearedNum3_3=(TH3D*)MyList->FindObject("fMuonContamSmearedNum3");
  TH3D *MuonSmearedDen3_3=(TH3D*)MyList->FindObject("fMuonContamSmearedDen3");
  TH3D *PionNum3_3=(TH3D*)MyList->FindObject("fMuonContamIdealNum3");
  TH3D *PionDen3_3=(TH3D*)MyList->FindObject("fMuonContamIdealDen3");
  TH3D *PionPionK3_3=(TH3D*)MyList->FindObject("fPionPionK3");
  TH3D *MuonPionK3_3=(TH3D*)MyList->FindObject("fMuonPionK3");
  
  
  TH1D *MuonSmearedNum2[2];// SC/MC  
  TH1D *MuonSmearedDen2[2];
  TH1D *PionNum2[2];
  TH1D *PionDen2[2];
  TH1D *PionPionK2[2];
  //
  TH1D *MuonSmearedNum3[2];// SC/MC  
  TH1D *MuonSmearedDen3[2];
  TH1D *PionNum3[2];
  TH1D *PionDen3[2];
  TH1D *PionPionK3[2];
  //
  TH1D *C2muonSmeared[2];
  TH1D *C2pion[2];
  TH1D *C3muonSmeared[2];
  TH1D *C3pion[2];
  //
  for(int chtype=0; chtype<2; chtype++){
    TString *names[10];
    for(int i=0; i<10; i++) {names[i]=new TString("name_"); *names[i] += i; *names[i] += chtype;}

    MuonSmearedNum2[chtype]=(TH1D*)MuonSmearedNum2_3->ProjectionZ(names[0]->Data(),chtype+1,chtype+1,kTbin_L,kTbin_H);
    MuonSmearedDen2[chtype]=(TH1D*)MuonSmearedDen2_3->ProjectionZ(names[1]->Data(),chtype+1,chtype+1,kTbin_L,kTbin_H);
    PionNum2[chtype]=(TH1D*)PionNum2_3->ProjectionZ(names[2]->Data(),chtype+1,chtype+1,kTbin_L,kTbin_H);
    PionDen2[chtype]=(TH1D*)PionDen2_3->ProjectionZ(names[3]->Data(),chtype+1,chtype+1,kTbin_L,kTbin_H);
    PionPionK2[chtype]=(TH1D*)PionPionK2_3->ProjectionZ(names[4]->Data(),chtype+1,chtype+1,kTbin_L,kTbin_H);
    PionPionK2[chtype]->Divide(PionDen2[chtype]);
    ////////////////
    MuonSmearedNum3[chtype]=(TH1D*)MuonSmearedNum3_3->ProjectionZ(names[5]->Data(),chtype+1,chtype+1,binKT3,binKT3);
    MuonSmearedDen3[chtype]=(TH1D*)MuonSmearedDen3_3->ProjectionZ(names[6]->Data(),chtype+1,chtype+1,binKT3,binKT3);
    PionNum3[chtype]=(TH1D*)PionNum3_3->ProjectionZ(names[7]->Data(),chtype+1,chtype+1,binKT3,binKT3);
    PionDen3[chtype]=(TH1D*)PionDen3_3->ProjectionZ(names[8]->Data(),chtype+1,chtype+1,binKT3,binKT3);
    PionPionK3[chtype]=(TH1D*)PionPionK3_3->ProjectionZ(names[9]->Data(),chtype+1,chtype+1,binKT3,binKT3);
    PionPionK3[chtype]->Divide(PionDen3[chtype]);
    //
    C2muonSmeared[chtype]=(TH1D*)MuonSmearedNum2[chtype]->Clone();
    C2pion[chtype]=(TH1D*)PionNum2[chtype]->Clone();
    C2muonSmeared[chtype]->Divide(MuonSmearedDen2[chtype]);
    C2pion[chtype]->Divide(PionDen2[chtype]);
    //
    C3muonSmeared[chtype]=(TH1D*)MuonSmearedNum3[chtype]->Clone();
    C3pion[chtype]=(TH1D*)PionNum3[chtype]->Clone();
    C3muonSmeared[chtype]->Divide(MuonSmearedDen3[chtype]);
    C3pion[chtype]->Divide(PionDen3[chtype]);
    //
    //
    C2pion[chtype]->SetLineColor(4);
    C2muonSmeared[chtype]->SetLineColor(2);
    C2pion[chtype]->GetXaxis()->SetRangeUser(0,0.15);
    C2pion[chtype]->SetMinimum(0.98); C2pion[chtype]->SetMaximum(1.35);
    C2pion[chtype]->GetYaxis()->SetTitleOffset(1.5);
    C2pion[chtype]->GetXaxis()->SetTitle("q_{inv} (GeV/c)");
    C2pion[chtype]->GetYaxis()->SetTitle("C_{2}K_{2}");
    //
    C3pion[chtype]->SetLineColor(4);
    C3muonSmeared[chtype]->SetLineColor(2);
    C3pion[chtype]->GetXaxis()->SetRangeUser(0,0.15);
    C3pion[chtype]->SetMinimum(0.90); C3pion[chtype]->SetMaximum(2.0);
    C3pion[chtype]->GetYaxis()->SetTitleOffset(1.5);
    C3pion[chtype]->GetXaxis()->SetTitle("Q_{3} (GeV/c)");
    C3pion[chtype]->GetYaxis()->SetTitle("C_{3}K_{3}");
  }
  //
  //
  
  C2pion[ChComb]->Draw();
  C2muonSmeared[ChComb]->Draw("same");
  legend->AddEntry(C2pion[ChComb],"Input Pion-Pion, C_{2}^{#pi-#pi,QS}K_{2}^{#pi-#pi,QS}","l");
  legend->AddEntry(C2muonSmeared[ChComb],"Pion-Muon residual, C_{2}^{#mu-#pi,QS}K_{2}^{#mu-#pi,QS}","l");
  legend->Draw("same");
  //PionPionK2->Draw("same");
  //
  //
  
  //
  //C3pion[ChComb]->Draw();
  //C3muonSmeared[ChComb]->Draw("same");
  //PionPionK3[0]->Draw("same");
  //legend->AddEntry(C3pion[ChComb],"Input Pion-Pion-Pion, C_{3}^{#pi-#pi-#pi,QS}K_{3}^{#pi-#pi-#pi,QS}","l");
  //legend->AddEntry(C3muonSmeared[ChComb],"Muon-Pion-Pion residual, C_{3}^{#mu-#pi-#pi,QS}K_{3}^{#mu-#pi-#pi,QS}","l");
  //legend->Draw("same");
    
  
  // corrections
  TFile *fout=new TFile("MuonCorrection_temp.root","RECREATE");
  TH1D *C2muonCorrection[2]; 
  C2muonCorrection[0] = new TH1D("C2muonCorrection_SC","",100,0,0.5);
  C2muonCorrection[1] = new TH1D("C2muonCorrection_MC","",100,0,0.5);
  TH1D *WeightmuonCorrection = new TH1D("WeightmuonCorrection","",100,0,0.5);
  TH1D *C3muonCorrection[2]; 
  C3muonCorrection[0] = new TH1D("C3muonCorrection_SC","",50,0,0.5);
  C3muonCorrection[1] = new TH1D("C3muonCorrection_MC","",50,0,0.5);
  //
  C2muonCorrection[0]->GetXaxis()->SetTitle("q_{inv} (GeV/c)"); C2muonCorrection[0]->GetYaxis()->SetTitle("x_{2}"); 
  C2muonCorrection[1]->GetXaxis()->SetTitle("q_{inv} (GeV/c)"); C2muonCorrection[1]->GetYaxis()->SetTitle("x_{2}"); 
  C3muonCorrection[0]->GetXaxis()->SetTitle("Q_{3} (GeV/c)"); C3muonCorrection[0]->GetYaxis()->SetTitle("x_{3}"); 
  C3muonCorrection[1]->GetXaxis()->SetTitle("Q_{3} (GeV/c)"); C3muonCorrection[1]->GetYaxis()->SetTitle("x_{3}"); 
  WeightmuonCorrection->GetXaxis()->SetTitle("q_{inv} (GeV/c)"); WeightmuonCorrection->GetYaxis()->SetTitle("x_{2}^{w}"); 
  
  // 0.944 and 0.959
  float GoodPairFraction=1-0.93*(1-PurityNum->GetBinContent(10));
  cout<<"Pion Pair Purity = "<<PurityNum->GetBinContent(10)<<endl;
  cout<<"Effective Pion Pair Purity = "<<GoodPairFraction<<endl;
  float pionPurity=pow(GoodPairFraction,0.5);
  float muonPurity=1-pionPurity;
  for(int chtype=0; chtype<2; chtype++){
    for(int bin=1; bin<=100; bin++){
      
      bool emptybin2=kFALSE, emptybin3=kFALSE;
      if(PionPionK2[chtype]->GetBinContent(bin)==0) {PionPionK2[chtype]->SetBinContent(bin, 1.00001);}
      if(PionPionK3[chtype]->GetBinContent(bin)==0) {PionPionK3[chtype]->SetBinContent(bin, 1.00001);}
      if(bin > C2pion[chtype]->GetNbinsX()) emptybin2=kTRUE;
      if(bin > C3pion[chtype]->GetNbinsX()) emptybin3=kTRUE;
 
      double value = C2pion[chtype]->GetBinContent(bin)/PionPionK2[chtype]->GetBinContent(bin);
      double den = (GoodPairFraction*C2pion[chtype]->GetBinContent(bin) + (1-GoodPairFraction)*C2muonSmeared[chtype]->GetBinContent(bin))/PionPionK2[chtype]->GetBinContent(bin);
      if(den > 0 && !emptybin2) C2muonCorrection[chtype]->SetBinContent(bin,value/den);
      else C2muonCorrection[chtype]->SetBinContent(bin, 1);
      //
      if(chtype==0){
	value = C2pion[chtype]->GetBinContent(bin)/PionPionK2[chtype]->GetBinContent(bin) - 1.0;
	den = ((GoodPairFraction*C2pion[chtype]->GetBinContent(bin) + (1-GoodPairFraction)*C2muonSmeared[chtype]->GetBinContent(bin))/PionPionK2[chtype]->GetBinContent(bin)) - 1.0;
	if(den > 0 && !emptybin2) WeightmuonCorrection->SetBinContent(bin,value/den);
      }
      //
      value = C3pion[chtype]->GetBinContent(bin)/PionPionK3[chtype]->GetBinContent(bin);
      den = (pow(pionPurity,3)*C3pion[chtype]->GetBinContent(bin) + (3*pow(pionPurity,2)*muonPurity)*C3muonSmeared[chtype]->GetBinContent(bin))/PionPionK3[chtype]->GetBinContent(bin);
      if(den > 0 && !emptybin3) C3muonCorrection[chtype]->SetBinContent(bin,value/den);
      else C3muonCorrection[chtype]->SetBinContent(bin, 1);
    }
    //C2muonCorrection[chtype]->SetBinContent(1, C2muonCorrection[chtype]->GetBinContent(2));
    //C3muonCorrection[chtype]->SetBinContent(1, C3muonCorrection[chtype]->GetBinContent(2));
    C2muonCorrection[chtype]->Write();
    C3muonCorrection[chtype]->Write();
    if(chtype==0) {
      //WeightmuonCorrection->SetBinContent(1, WeightmuonCorrection->GetBinContent(2));
      WeightmuonCorrection->Write();
    }
  }
  
  //
  //C3muonCorrection[0]->SetMinimum(0.99); 
  //C3muonCorrection[0]->SetMaximum(1.05); 
  //C3muonCorrection[0]->GetYaxis()->SetTitleOffset(1.3);
  //C3muonCorrection[0]->Draw();
  //WeightmuonCorrection->GetYaxis()->SetTitleOffset(1.3);
  //WeightmuonCorrection->Draw();
  fout->Close();
  
  
}
Exemplo n.º 17
0
void FastVsSlowSimRes() {

  Int_t plusTPC =0;

  gROOT->LoadMacro("~/fig_template.C"); // figure style
  myOptions(0);
  gROOT->ForceStyle();

  TCanvas *myCan = new TCanvas("myCan");
  myCan->Draw();
  myCan->cd();
  
  TPad *myPad = new TPad("myPad", "The pad",0,0,1,1);
  myPadSetUp(myPad,0.15,0.04,0.04,0.15);
  myPad->Draw();   myPad->cd();
  myPad->SetGridx();   myPad->SetGridy();  myPad->SetLogx(); 

  //  TLegend *leg = new TLegend(0.7,160,20,290,"","brCDN"); 
  TLegend *leg = new TLegend(0.44,160,1.7,290,"","brCDN"); 
 
  leg->SetFillColor(0);

  
  // Current ITS +++++++++++++++++++++++++++++++++++++++++

  DetectorK its("ALICE","ITS");
  its.MakeAliceCurrent(0,plusTPC);
  its.SetMaxRadiusOfSlowDetectors(0.1);
  its.SolveViaBilloir(0);
  Int_t color=1; Int_t linewidth=2;

  TGraph *c[6];
  TGraph *d[6];

  Int_t pi =0;
  d[pi] = its.GetGraphPointingResolution(1,color,linewidth);
  d[pi]->SetLineStyle(2);
  //  d[pi]->GetYaxis()->SetTitle("Pointing resolution #sigma [#mum]");
  //  d[pi]->SetTitle("Pointing resolution .vs. Pt");
  //  d[pi]->Draw("AC");
  
  c[pi] = its.GetGraphPointingResolution(0,color,linewidth);
  c[pi]->SetMinimum(-1);
  c[pi]->Draw("AC");

  leg->AddEntry(c[pi],"FastTool:  Current ITS","l");
  //  leg->AddEntry(d[pi],"in z  - Current ITS","l");

 

 
  // Current ITS +++++++++++++++++++++++++++++++++++++++++

  Int_t color=3; Int_t linewidth=2;
  Int_t pi =2;

  DetectorK its("ALICE","ITS");
  its.MakeAliceCurrent(0,plusTPC);
  
  its.SetRadius("bpipe",2.0);
  its.AddLayer("spd0", 2.2,1,1,1);  

  its.SetRadius("spd0",2.2); its.SetRadiationLength("spd0",X0); its.SetResolution("spd0",resRPhi,resZ);
  its.SetRadius("spd1",4.8);   its.SetRadiationLength("spd1",X0); its.SetResolution("spd1",resRPhi,resZ);
  its.SetRadius("spd2",9.1);   its.SetRadiationLength("spd2",X0); its.SetResolution("spd2",resRPhi,resZ);

  its.SetMaxRadiusOfSlowDetectors(0.1);
  its.SolveViaBilloir(0);

  d[pi] = its.GetGraphPointingResolution(1,color,linewidth);
  d[pi]->SetLineStyle(2);
  //  d[pi]->Draw("C");

  c[pi] = its.GetGraphPointingResolution(0,color,linewidth);
  c[pi]->Draw("C");

  leg->AddEntry(c[pi],"FastTool: \"New SPDs\"","l");
  //  leg->AddEntry(d[pi],"in z  - \"New SPDs\"","l");



  // ALL NEW +++++++++++++++++++++++++++++++++++++++++++

  color=2; Int_t linewidth=2;
  Int_t pi =1; 


  // for a 0.8,0.2 weight configuration
  
  DetectorK *itsU = new DetectorK((char*)"ALICE",(char*)"ITS");
  
  itsU->AddLayer((char*)"bpipe", 2.0,0.0022); // beam pipe
  itsU->AddLayer((char*)"vertex",  0,     0); // dummy vertex for matrix calculation
  
  itsU->AddLayer("ddd1",  2.2 ,  X0, resRPhi, resZ); 
  itsU->AddLayer("ddd2",  3.8 ,  X0, resRPhi, resZ); 
  itsU->AddLayer("ddd3",  6.8 ,  X0, resRPhi, resZ); 
  itsU->AddLayer("ddd4", 12.4 ,  X0, resRPhi, resZ); 
  itsU->AddLayer("ddd5", 23.5 ,  X0, resRPhi, resZ); 
  itsU->AddLayer("ddd6", 39.6 ,  X0, resRPhi, resZ); 
  itsU->AddLayer("ddd7", 43.0 ,  X0, resRPhi, resZ); 
 
  if(plusTPC) itsU->AddTPC(0.1,0.1);
  itsU->SetMaxRadiusOfSlowDetectors(0.1);
  itsU->SolveViaBilloir(0);
  itsU->PrintLayout();

  
  d[pi] = itsU->GetGraphPointingResolution(1,color,linewidth);
  d[pi]->SetLineStyle(2);
  //  d[pi]->Draw("C");

  c[pi] = itsU->GetGraphPointingResolution(0,color,linewidth);
  c[pi]->SetMaximum(150);
  c[pi]->Draw("C");

  leg->AddEntry(c[pi],"FastTool: \"All New\" ","l");
  //  leg->AddEntry(d[pi],"in z  - \"All New\" ","l");


  // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


 
  TFile f1("root/FastVsSlow_CurrentITS-PbPb-fran.root");
  TFile f2("root/FastVsSlow_NewSPDs-PbPb-fran.root");
  TFile f3("root/FastVsSlow_AllNew-PbPb-fran.root");
  TGraphErrors *dca1 = (TGraphErrors*)f1.Get("dca");
  TGraphErrors *dca2 = (TGraphErrors*)f2.Get("dca");
  TGraphErrors *dca3 = (TGraphErrors*)f3.Get("dca");
  
  dca1->SetMarkerStyle(21); dca1->SetMarkerColor(1);
  dca2->SetMarkerStyle(21); dca2->SetMarkerColor(3);
  dca3->SetMarkerStyle(21); dca3->SetMarkerColor(2);

  leg->AddEntry(dca1,"FullMC: Current ITS","PE");
  leg->AddEntry(dca2,"FullMC: \"New SPDs\"","PE");
  leg->AddEntry(dca3,"FullMC: \"All New\" ","PE");

  dca1->Draw("APE"); dca1->SetMinimum(-1); dca1->SetMaximum(300);
  dca2->Draw("PE");
  dca3->Draw("PE");
  c[0]->Draw("C");
  c[1]->Draw("C");
  c[2]->Draw("C");

  leg->Draw();

  myCan->SaveAs(Form("FastVsSlowSim-Res-%d.pdf",plusTPC));
  myCan->SaveAs(Form("FastVsSlowSim-Res-%d.eps",plusTPC));


}
Exemplo n.º 18
0
void DrawVariable(TString DIR,TString VAR,float LUMI,bool LOG,int REBIN,float XMIN,float XMAX,TString XTITLE,bool isINT,int XNDIV,bool PRINT)
{
  gROOT->ForceStyle();
  const int N = 14;

  TString SAMPLE[N] = {
    "JetHT",
    "TT_TuneCUETP8M1_13TeV-powheg-pythia8",
    "WJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "DYJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8"
  };
  float XSEC[N] = {1.0,0.5*832,3539,1460.,136.02,80.95,35.6,35.6,3.67e+5,2.94e+4,6.524e+03,1.064e+03,121.5,2.542e+01};

  TFile *inf[N];
  TH1F  *h[N];

  TCanvas *can = new TCanvas("DataVsMC_"+DIR+"_"+VAR,"DataVsMC_"+DIR+"_"+VAR,900,600);
  can->SetRightMargin(0.15);

  for(int i=0;i<N;i++) {
    inf[i] = TFile::Open("Histo_"+SAMPLE[i]+".root");
    h[i] = (TH1F*)inf[i]->Get(DIR+"/hWt_"+VAR);
    if (!h[i]) {
      cout<<"Histogram "<<"hWt_"+VAR<<" does not exist !!!"<<endl;
      break;
    } 
    h[i]->SetDirectory(0);
    h[i]->Sumw2();
    h[i]->Rebin(REBIN);
    h[i]->SetLineWidth(1);
    h[i]->SetLineColor(kBlack);
    if (i>0) {
      float norm = ((TH1F*)inf[i]->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();   
      //cout<<SAMPLE[i]<<" "<<norm<<endl;
      h[i]->Scale(LUMI*XSEC[i]/norm);
    }
    inf[i]->Close();
  }

  TH1F *hQCD = (TH1F*)h[8]->Clone("hQCD");
  for(int i=9;i<N;i++) {
    hQCD->Add(h[i]);
  }
 
  TH1F *hST = (TH1F*)h[4]->Clone("hST");
  hST->Add(h[5]);
  hST->Add(h[6]);
  hST->Add(h[7]);
  h[0]->SetLineWidth(2);//data
  hQCD->SetFillColor(kBlue-10);//QCD
  h[1]->SetFillColor(kOrange);//ttbar
  h[2]->SetFillColor(kGreen-10);//WJets
  h[3]->SetFillColor(kGreen-8);//ZJets
  hST->SetFillColor(kOrange-1);//ST

  float kfactor = 1.0;
  if (hQCD->Integral() > 0) { 
    kfactor = (h[0]->Integral()-h[1]->Integral()-h[2]->Integral()-h[3]->Integral()-hST->Integral())/hQCD->Integral();
  }  
  hQCD->Scale(kfactor);

  TH1F *hBkg = (TH1F*)hQCD->Clone("hBkg");
  hBkg->Add(h[1]);
  hBkg->Add(h[2]);
  hBkg->Add(h[3]);
  hBkg->Add(h[4]);
  hBkg->Add(hST);
  //hBkg->SetFillColor(kGray);

  cout<<"======== "<<VAR<<"====================="<<endl;
  cout<<"Data events:  "<<h[0]->Integral()<<endl;
  cout<<"QCD events:   "<<hQCD->Integral()<<endl;
  cout<<"WJets events: "<<h[2]->Integral()<<endl;
  cout<<"ZJets events: "<<h[3]->Integral()<<endl;
  cout<<"ST events:    "<<hST->Integral()<<endl;
  cout<<"TTbar events: "<<h[1]->Integral()<<endl;
  cout<<"kfactor:      "<<kfactor<<endl;

  THStack *hs = new THStack("hs","hs");
  if (LOG) {   
    hs->Add(h[2]);
    hs->Add(h[3]);
    hs->Add(hST); 
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  else {
    hs->Add(h[3]);
    hs->Add(hST);
    hs->Add(h[2]);
    hs->Add(hQCD);
    hs->Add(h[1]);
  }
  TH1F *hRatio = (TH1F*)h[0]->Clone("Ratio");
  hRatio->SetLineWidth(2);
  hRatio->Divide(hBkg);

  TLegend *leg = new TLegend(0.86,0.7,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"QCD","F");
  leg->AddEntry(h[1],"TTbar","F"); 
  leg->AddEntry(hST,"ST","F"); 
  leg->AddEntry(h[2],"WJets","F");
  leg->AddEntry(h[3],"ZJets","F"); 
  
  can->SetBottomMargin(0.25);
  TH1F *hAux = (TH1F*)h[0]->Clone("aux");
  hAux->Reset();
  hAux->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hAux->GetXaxis()->CenterLabels();
  } 
  hAux->GetYaxis()->SetRangeUser(0.5,1.1*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));  
  if (LOG) {
    gPad->SetLogy(); 
    hAux->GetYaxis()->SetRangeUser(0.5,2*TMath::Max(hBkg->GetBinContent(hBkg->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin())));
  }
  hAux->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hAux->GetYaxis()->SetTitle(TString::Format("Number of events / %1.2f fb^{-1}",LUMI/1000));
  hAux->GetXaxis()->SetTitle("");
  hAux->GetXaxis()->SetLabelSize(0.0);
  hAux->Draw();
  hs->Draw("hist same");
  //hBkg->Draw("sames hist"); 
  h[0]->Draw("sames E");
  
  leg->Draw();
  gPad->RedrawAxis();

  TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
  pad->SetTopMargin(0.77);
  pad->SetRightMargin(0.15);
  pad->SetFillColor(0);
  pad->SetFillStyle(0);
  pad->Draw();
  pad->cd(0);
  pad->SetGridy();
  hRatio->GetXaxis()->SetTitleOffset(0.95);
  hRatio->GetYaxis()->SetTitleOffset(1.5);
  hRatio->GetYaxis()->SetTickLength(0.06);
  hRatio->GetYaxis()->SetTitleSize(0.03);
  hRatio->GetYaxis()->SetLabelSize(0.03);
  hRatio->GetYaxis()->SetTitle("Data/MC");
  hRatio->GetXaxis()->SetTitle(XTITLE);
  hRatio->GetXaxis()->SetRangeUser(XMIN,XMAX);
  hRatio->GetYaxis()->SetRangeUser(0.5,1.5);
  hRatio->GetYaxis()->SetNdivisions(505);
  hRatio->GetXaxis()->SetNdivisions(XNDIV);
  if (isINT) {
    hRatio->GetXaxis()->CenterLabels();
  }
  hRatio->Draw();
  if (PRINT) {
    can->Print("plots/"+TString(can->GetName())+".pdf"); 
    can->Print("plots/"+TString(can->GetName())+".png");
  }
}
Exemplo n.º 19
0
void DrawVariable(TString VAR,bool SHAPE,int REBIN,float XMIN,float XMAX,TString XTITLE,bool PRINT,bool BLIND=false,float BLIND_MIN=0,float BLIND_MAX=0)
{
  gROOT->ForceStyle();
  const int N = 20;

  TString SAMPLE[N] = {
    "JetHT",
    "ttHJetTobb_M125_13TeV_amcatnloFXFX_madspin_pythia8",
    "ttHJetToNonbb_M125_13TeV_amcatnloFXFX_madspin_pythia8_mWCutfix",
    "QCD_HT300to500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT500to700_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT700to1000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1000to1500_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT1500to2000_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "QCD_HT2000toInf_TuneCUETP8M1_13TeV-madgraphMLM-pythia8",
    "DYJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "WJetsToQQ_HT180_13TeV-madgraphMLM-pythia8",
    "TT_TuneCUETP8M1_13TeV-powheg-pythia8",
    "ST_t-channel_antitop_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1",
    "ST_tW_top_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "ST_tW_antitop_5f_inclusiveDecays_13TeV-powheg-pythia8_TuneCUETP8M1",
    "TTWJetsToQQ_TuneCUETP8M1_13TeV-amcatnloFXFX-madspin-pythia8",
    "TTZToQQ_TuneCUETP8M1_13TeV-amcatnlo-pythia8",
    "WZ_TuneCUETP8M1_13TeV-pythia8",
    "WWTo4Q_13TeV-powheg",
    "ZZTo4Q_13TeV_amcatnloFXFX_madspin_pythia8"
  };

  float XSEC[N] = {
    1.0,
    0.2934,
    0.2151,
    347700, 
    32100,
    6831,
    1207,
    119.9,
    25.24,
    1460,
    3539,
    832,
    217,
    35.6,
    35.6,
    0.4062,
    0.5297,
    47.13,
    51.723,
    22.29
  }; 
 
  float LUMI(5760);
  TFile *inf[N];
  TH1F  *h[N];

  TCanvas *can = new TCanvas("can_"+VAR,"can_"+VAR,900,600);
  can->SetRightMargin(0.15);

  for(int i=0;i<N;i++) {
    inf[i] = TFile::Open("Histo_"+SAMPLE[i]+".root");
    //cout<<inf[i]->GetName()<<" "<<VAR<<endl;
    h[i]   = (TH1F*)inf[i]->Get("ttH/h_"+VAR);
    h[i]->SetDirectory(0);
    h[i]->Rebin(REBIN);
    h[i]->Sumw2();
    h[i]->SetLineWidth(1);
    h[i]->SetLineColor(kBlack);
    if (i>0) {
      float norm = ((TH1F*)inf[i]->Get("eventCounter/GenEventWeight"))->GetSumOfWeights();
      //cout<<inf[i]->GetName()<<" "<<norm<<endl; 
      h[i]->Scale(LUMI*XSEC[i]/norm);
    }
    else {
      h[i]->SetLineWidth(2);
    }
    inf[i]->Close();
  }

  TH1F *hQCD = (TH1F*)h[3]->Clone("hQCD");
  hQCD->Add(h[4]);
  hQCD->Add(h[5]);
  hQCD->Add(h[6]); 
  hQCD->Add(h[7]);
  hQCD->Add(h[8]);

  TH1F *hVV = (TH1F*)h[17]->Clone("hVV");
  hVV->Add(h[18]);
  hVV->Add(h[19]);

  TH1F *hST = (TH1F*)h[12]->Clone("hST");
  hST->Add(h[13]);
  hST->Add(h[14]);

  h[1]->SetLineColor(kRed);//ttHbb
  h[1]->SetFillColor(kRed-9);
  h[1]->SetLineWidth(2);
  h[2]->SetLineColor(kRed);//ttHNobb
  h[2]->SetFillColor(kRed-10);
  h[2]->SetLineWidth(2);

  TH1F *hTT     = (TH1F*)h[11]->Clone("TTbar");
  TH1F *hTTZ    = (TH1F*)h[16]->Clone("TTZ");
  TH1F *hTTW    = (TH1F*)h[15]->Clone("TTW");
  TH1F *hWJets  = (TH1F*)h[10]->Clone("WJets");
  TH1F *hDYJets = (TH1F*)h[9]->Clone("DYJets");
 
  hQCD->SetFillColor(kBlue-10);//QCD
  hTT->SetFillColor(kOrange);
  hST->SetFillColor(kOrange-1);//ST
  hVV->SetFillColor(kMagenta-10);//VV
  hTTZ->SetFillColor(kYellow-10);//ttZ
  hTTW->SetFillColor(kYellow-9);//ttW
  hWJets->SetFillColor(kGreen-10);//WJets
  hDYJets->SetFillColor(kGreen-8);//ZJets
 
 

  float kfactor = 1.0;
  if (hQCD->Integral() > 0) { 
    kfactor = (h[0]->Integral()-hTT->Integral()-hWJets->Integral()-hDYJets->Integral()-hST->Integral())/hQCD->Integral();
  }  
  hQCD->Scale(kfactor);

  TH1F *hBkg = (TH1F*)hQCD->Clone("hBkg");
  hBkg->Add(hTT);
  hBkg->Add(hST);
  hBkg->Add(hTTW);
  hBkg->Add(hTTZ);
  hBkg->Add(hWJets);
  hBkg->Add(hDYJets);
  hBkg->Add(hVV);
  hBkg->SetFillColor(kGray);

  cout<<"Data events:  "<<h[0]->Integral()<<endl;
  cout<<"ttHJetTobb:   "<<h[1]->Integral()<<endl;
  cout<<"ttHJetToNonbb:"<<h[2]->Integral()<<endl;
  cout<<"QCD events:   "<<hQCD->Integral()<<endl;
  cout<<"TTbar events: "<<hTT->Integral()<<endl;
  cout<<"ST events:    "<<hST->Integral()<<endl;
  cout<<"TTZ events:   "<<hTTZ->Integral()<<endl;  
  cout<<"TTW events:   "<<hTTW->Integral()<<endl;
  cout<<"WJets events: "<<hWJets->Integral()<<endl;
  cout<<"DYJets events:"<<hDYJets->Integral()<<endl;
  cout<<"VV events:    "<<hVV->Integral()<<endl;
  cout<<"kfactor:      "<<kfactor<<endl;

  THStack *hs = new THStack("hs","hs");
  hs->Add(hVV);
  hs->Add(hTTW);
  hs->Add(hTTZ);
  hs->Add(hWJets);
  hs->Add(hDYJets);
  hs->Add(hST);
  hs->Add(hTT);
  hs->Add(hQCD);

  if (BLIND) {
    for(int i=0;i<h[0]->GetNbinsX();i++) {
      if (h[0]->GetBinCenter(i+1) > BLIND_MIN && h[0]->GetBinCenter(i+1) < BLIND_MAX) {
        h[0]->SetBinContent(i+1,0);
        h[0]->SetBinError(i+1,0);
      } 
    }
  }

  TH1F *hRatio = (TH1F*)h[0]->Clone("Ratio");
  hRatio->SetLineWidth(2);
  hRatio->Divide(hBkg);

  TLegend *leg = new TLegend(0.86,0.55,0.99,0.9);
  leg->SetFillColor(0);
  leg->SetTextFont(42);
  leg->SetTextSize(0.03);
  leg->AddEntry(hQCD,"QCD","F");
  leg->AddEntry(hTT,"TTbar","F");
  leg->AddEntry(hST,"ST","F");
  leg->AddEntry(hTTZ,"ttZ","F");
  leg->AddEntry(hTTW,"ttW","F");
  leg->AddEntry(hWJets,"WJets","F");
  leg->AddEntry(hDYJets,"ZJets","F");
  leg->AddEntry(hVV,"Diboson","F");
  leg->AddEntry(h[1],"ttHbb","L");
  leg->AddEntry(h[2],"ttHNonbb","L");
  
  if (SHAPE) {
    h[1]->SetFillStyle(3001);
    h[2]->SetFillStyle(3001);
    h[0]->Scale(1./h[0]->Integral());
    h[1]->Scale(1./h[1]->Integral());
    h[2]->Scale(1./h[2]->Integral());
    hQCD->Scale(1./hQCD->Integral());
    hBkg->Scale(1./hBkg->Integral());
    double max = TMath::Max(h[0]->GetBinContent(h[0]->GetMaximumBin()),hBkg->GetBinContent(hBkg->GetMaximumBin()));
    hBkg->SetMaximum(1.1*max);
    hBkg->GetXaxis()->SetTitle(XTITLE);
    hBkg->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hBkg->Draw("hist");
    h[0]->Draw("same E"); 
    //h[1]->Draw("same hist"); 
    leg->Draw();
    gPad->RedrawAxis();
    can->Print("can_"+VAR+"_norm.pdf"); 
  }
  else {
    can->SetBottomMargin(0.25);
    gPad->SetLogy(); 
    //h[1]->Scale(h[0]->Integral()/h[1]->Integral());
    h[1]->SetFillColor(0);
    TH1F *hAux = (TH1F*)h[0]->Clone("aux");
    hAux->Reset();
    hAux->GetYaxis()->SetRangeUser(0.5,1.1*TMath::Max(h[1]->GetBinContent(h[1]->GetMaximumBin()),h[0]->GetBinContent(h[0]->GetMaximumBin()))); 
    
    hAux->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hAux->GetYaxis()->SetTitle(TString::Format("Number of events / %1.2f fb^{-1}",LUMI/1000));
    hAux->GetXaxis()->SetTitle("");
    hAux->GetXaxis()->SetLabelSize(0.0);
    hAux->Draw();
    hs->Draw("hist same"); 
    h[0]->Draw("same E");
    h[1]->Draw("same hist");
    h[2]->Draw("same hist");
    leg->Draw();
    gPad->RedrawAxis();

    TPad *pad = new TPad("pad","pad",0.,0.,1.,1.);
    pad->SetTopMargin(0.77);
    pad->SetRightMargin(0.15);
    pad->SetFillColor(0);
    pad->SetFillStyle(0);
    pad->Draw();
    pad->cd(0);
    pad->SetGridy();
    hRatio->GetXaxis()->SetTitleOffset(0.95);
    hRatio->GetYaxis()->SetTitleOffset(1.5);
    hRatio->GetYaxis()->SetTickLength(0.06);
    hRatio->GetYaxis()->SetTitleSize(0.03);
    hRatio->GetYaxis()->SetLabelSize(0.03);
    hRatio->GetYaxis()->SetTitle("Data/MC");
    hRatio->GetXaxis()->SetTitle(XTITLE);
    hRatio->GetXaxis()->SetRangeUser(XMIN,XMAX);
    hRatio->GetYaxis()->SetRangeUser(0.5,1.5);
    hRatio->GetYaxis()->SetNdivisions(505);
    hRatio->Draw();
    if (PRINT) {
      can->Print("plots/can_"+VAR+"_abs.pdf"); 
      can->Print("plots/can_"+VAR+"_abs.png");
    }
  }
}
void EMCDistribution_ADC(bool log_scale = true)
{
  TString gain = "RAW";

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_ADC_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      "EMCDistribution_ADC_" + gain + TString(log_scale ? "_Log" : "") + cuts,
      1800, 1000);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      if (log_scale)
      {
        p->SetLogz();
      }
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(log_scale ? "_Log" : "");

      TH1 *h = NULL;

      if (log_scale)
        h = new TH2F(hname,
                     Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 24, -.5,
                     23.5,
                     //                128+64, 0, 3096);
                     4098, -1, 4097);
      //          else
      //            h = new TH2F(hname,
      //                Form(";Calibrated Tower Energy Sum (GeV);Count / bin"), 100,
      //                -.050, .5,128,0,2048);

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);
      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetRangeUser(0, 4096);

      //          if (log_scale)
      //            QAHistManagerDef::useLogBins(h->GetYaxis());

      TString sdraw = "TOWER_" + gain + "_CEMC[].signal_samples[]:fmod(Iteration$,24)>>" + hname;
      TString scut =
          Form(
              "TOWER_%s_CEMC[].get_bineta()==%d && TOWER_%s_CEMC[].get_binphi()==%d",
              gain.Data(), ieta, gain.Data(), iphi);

      cout << "T->Draw(\"" << sdraw << "\",\"" << scut << "\");" << endl;

      T->Draw(sdraw, scut, "colz");

      TText *t = new TText(.9, .9, Form("Col%d Row%d", ieta, iphi));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();

      //          return;
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
//################################################################################################################################
//################################################################################################################################
//################################################################################################################################
TCanvas *drawRatioPlot(TH1D *prediction, TH1D *sr, TString xTitle, TString filename){

  
  TCanvas *c = new TCanvas("c"+filename,"c",0,0,500,500);
  c->cd();
  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);

  TH1D *ratio = 0;

  ratio = (TH1D*) sr->Clone();
  ratio->Divide(prediction);
  ratio->GetYaxis()->SetTitle((TString) sr->GetName() + "/" + (TString) prediction->GetName());
  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();

  // 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.6,0.8,0.9,0.9);
  leg->AddEntry(sr,"bkg","l"); 
  leg->AddEntry(prediction,prediction->GetName(),"pel"); 
  pad1->cd();
  //pad1->SetLogy();

  sr->SetLineColor(kRed);
  sr->SetMarkerColor(kRed);
  sr->SetTitle("");
  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);

  prediction->Draw("e");
  sr->Draw("e same");

  if(sr->GetMaximum()>prediction->GetMaximum()){

    sr->Draw("e");
    prediction->Draw("e same");

    }

  leg->Draw("same");




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

  c->SaveAs(filename);

  return c;

}
void EMCDistribution_ShowShape(TString CherenkovSignal = "C2_Inner",
                               const double che_cut = 10)
{
  TString cut_pass = CherenkovSignal + Form(">%.1f", che_cut);
  TString cut_rej = CherenkovSignal + Form("<%.1f", che_cut);

  const double event_pass = T->GetEntries(cut_pass);
  const double event_rej = T->GetEntries(cut_rej);

  TH2 *EnergyDist_pass = new TH2F("EnergyDist_pass",
                                  cut_pass + ";Column;Row;<Energy> / Event / Tower", 8, -.5, 7.5, 8, -.5,
                                  7.5);
  TH2 *EnergyDist_rej = new TH2F("EnergyDist_rej",
                                 cut_rej + ";Column;Row;<Energy> / Event / Tower", 8, -.5, 7.5, 8, -.5,
                                 7.5);
  TH2 *Hodoscope_dist = new TH2F("Hodoscope_dist",
                                 cut_rej + ";7 - Horizontal Hodoscope (5 mm);7 - Vertical Hodoscope (5 mm); Event / finger^2", 8, -.5, 7.5, 8, -.5,
                                 7.5);

  TH1 *Che_full = new TH1F("Che_full",
                           ";" + CherenkovSignal + " Signal (ADC);Count / bin", 200, 0, 2000);
  TH1 *Che_pass = new TH1F("Che_pass",
                           ";" + CherenkovSignal + " Signal (ADC);Count / bin", 200, 0, 2000);
  TH1 *Che_rej = new TH1F("Che_rej",
                          ";" + CherenkovSignal + " Signal (ADC);Count / bin", 200, 0, 2000);

  Che_full->SetLineColor(kBlue + 3);
  Che_full->SetLineWidth(2);
  Che_pass->SetLineColor(kGreen + 3);
  Che_pass->SetLineWidth(2);
  Che_pass->SetFillColor(kGreen + 3);
  Che_pass->SetFillStyle(1);
  Che_rej->SetLineColor(kBlue + 3);
  Che_rej->SetLineWidth(2);
  Che_rej->SetFillColor(kBlue + 3);
  Che_rej->SetFillStyle(1);

  T->Draw(
      "TOWER_CALIB_CEMC[].get_binphi():TOWER_CALIB_CEMC[].get_bineta()>>EnergyDist_pass",
      Form("(%s) * (TOWER_CALIB_CEMC[].get_energy())", cut_pass.Data()),
      "goff");
  T->Draw(
      "TOWER_CALIB_CEMC[].get_binphi():TOWER_CALIB_CEMC[].get_bineta()>>EnergyDist_rej",
      Form("(%s) * (TOWER_CALIB_CEMC[].get_energy())", cut_rej.Data()), "goff");
  T->Draw(
      "7 - Average_HODO_VERTICAL:7 - Average_HODO_HORIZONTAL>>Hodoscope_dist", "1", "goff");

  T->Draw(CherenkovSignal + ">>Che_full", NULL, "goff");
  T->Draw(CherenkovSignal + ">>Che_pass", cut_pass, "goff");
  T->Draw(CherenkovSignal + ">>Che_rej", cut_rej, "goff");

  EnergyDist_pass->Scale(1. / event_pass);
  EnergyDist_rej->Scale(1. / event_rej);

  TText *t;
  TCanvas *c1 = new TCanvas("EMCDistribution_ShowShape" + cuts,
                            "EMCDistribution_ShowShape" + cuts, 1100, 950);
  c1->Divide(2, 2);
  int idx = 1;
  TPad *p;

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  Che_full->DrawClone();
  Che_pass->DrawClone("same");
  Che_rej->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();

  EnergyDist_pass->DrawClone("colz");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);

  EnergyDist_rej->DrawClone("colz");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);

  Hodoscope_dist->DrawClone("colz");

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
Exemplo n.º 23
0
void doComparisonPlots_Et(){

  //  gROOT->ProcessLine(".x /Users/Arabella/Public/style.C");

  std::string plotDir = "../../NonGlobe/PLOTS_vsEt";
  std::string plotDirOut = "2011vs2012_vsEt";

  std::cout << " ci sono " << std::endl;

//       std::string plotDir = "PLOTS_false_Sh";
//       std::string plotDirOut = "2011vs2012_false_Sh";



  for(int ii=0; ii<4; ++ii){
    std::string category;     
    if(ii == 0)  category = "EB_HIGH_scE_reg";
    if(ii == 1)  category = "EB_LOW_scE_reg";
    if(ii == 2)  category = "EE_HIGH_scE_reg";
    if(ii == 3)  category = "EE_LOW_scE_reg";

    std::string file2011 = plotDir+"/results_"+category+"_2011.root";
    std::string file2012 = plotDir+"/results_"+category+"_2012.root";

    TFile f2012(file2012.c_str(),"read");
    TFile f2011(file2011.c_str(),"read");

   TGraphErrors* graph2012 = (TGraphErrors*)f2012.Get("finalGraph");
   TGraphErrors* graph2011 = (TGraphErrors*)f2011.Get("finalGraph");


   graph2012->SetMarkerColor(kGreen+2);
   graph2011->SetMarkerColor(kRed+2);

   if(ii == 0 || ii == 2){
     graph2012->SetMarkerStyle(20);
     graph2011->SetMarkerStyle(20);
   }
   if(ii == 1 || ii == 3){
     graph2012->SetMarkerStyle(21);
     graph2011->SetMarkerStyle(21);
   }

  TCanvas* cplot = new TCanvas("gplot", "gplot",100,100,725,500);
  cplot->cd();
  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,1.00,1.00);
  cLeft->SetLeftMargin(0.17);
  cLeft->SetRightMargin(0.025);
  cLeft->SetBottomMargin(0.17);
  cLeft->Draw();
  float tYoffset = 1.75;
  float tXoffset = 1.6;
  float labSize = 0.04;
  float labSize2 = 0.07;
  cLeft->cd();
  cLeft->SetGridx();
  cLeft->SetGridy();

  // pad settings                                                                     
  TH1F *hPad = (TH1F*)gPad->DrawFrame(20.,-0.02,120.,0.02);
  hPad->GetXaxis()->SetTitle("E_{T}");
  hPad->GetYaxis()->SetTitle("E/p_{data}-E/p_{mc}");
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetTitleOffset(tXoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize);
  TLegend *tspec = new TLegend(0.64,0.80,0.99,0.99);
  tspec->SetFillColor(0);
  tspec->SetTextFont(42);
  if(ii == 0){
  tspec->AddEntry(graph2012,"2012 EB hR9","PL");
  tspec->AddEntry(graph2011,"2011 EB hR9","PL");
  }
  if(ii == 1){
  tspec->AddEntry(graph2012,"2012 EB lR9","PL");
  tspec->AddEntry(graph2011,"2011 EB lR9","PL");
  }
  if(ii == 2){
  tspec->AddEntry(graph2012,"2012 EE hR9","PL");
  tspec->AddEntry(graph2011,"2011 EE hR9","PL");
  }
  if(ii == 3){
  tspec->AddEntry(graph2012,"2012 EE lR9","PL");
  tspec->AddEntry(graph2011,"2011 EE lR9","PL");
  }

  graph2012->Draw("P");
  graph2011->Draw("P,same");

  tspec->Draw("same");
  cplot->Print( (plotDirOut+"/EoP_vs_Et_"+category+".png").c_str(),".png");

  //  cplot->Print( (plotDirOut+"/"+histoName+".png").c_str(),".png");

  }

  // tutto EB in 1 plot
  std::string f11_h = plotDir+"/results_EB_HIGH_scE_reg_2011.root";
  std::string f12_h = plotDir+"/results_EB_HIGH_scE_reg_2012.root";
  std::string f11_l = plotDir+"/results_EB_LOW_scE_reg_2011.root";
  std::string f12_l = plotDir+"/results_EB_LOW_scE_reg_2012.root";

  TFile F12_h(f12_h.c_str(),"read");
  TFile F11_h(f11_h.c_str(),"read");

  TFile F12_l(f12_l.c_str(),"read");
  TFile F11_l(f11_l.c_str(),"read");

  TGraphErrors* g2012_h = (TGraphErrors*)F12_h.Get("finalGraph");
  TGraphErrors* g2011_h = (TGraphErrors*)F11_h.Get("finalGraph");
  TGraphErrors* g2012_l = (TGraphErrors*)F12_l.Get("finalGraph");
  TGraphErrors* g2011_l = (TGraphErrors*)F11_l.Get("finalGraph");

    g2012_h->SetMarkerColor(kGreen+2);
    g2012_l->SetMarkerColor(kGreen+2);
    g2011_h->SetMarkerColor(kRed+2);
    g2011_l->SetMarkerColor(kRed+2);

    g2012_h->SetMarkerStyle(20);
    g2011_h->SetMarkerStyle(20);
    g2012_l->SetMarkerStyle(21);
    g2011_l->SetMarkerStyle(21);

  TCanvas* c = new TCanvas("g", "g",100,100,725,500);
  c->cd();
  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,1.00,1.00);
  cLeft->SetLeftMargin(0.17);
  cLeft->SetRightMargin(0.025);
  cLeft->SetBottomMargin(0.17);
  cLeft->Draw();
  float tYoffset = 1.75;
  float tXoffset = 1.6;
  float labSize = 0.04;
  float labSize2 = 0.07;
  cLeft->cd();
  cLeft->SetGridx();
  cLeft->SetGridy();
    
  // pad settings                                                                     
  TH1F *hPad = (TH1F*)gPad->DrawFrame(20,-0.02,100,0.02);
  hPad->GetXaxis()->SetTitle("E_{T}");
  hPad->GetYaxis()->SetTitle("E/p_{data}-E/p_{mc}");
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetTitleOffset(tXoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize);

  TLegend *tspec = new TLegend(0.64,0.80,0.99,0.99);
  tspec->SetFillColor(0);
  tspec->SetTextFont(42);

  tspec->AddEntry(g2012_h,"2012 EB hR9","PL");
  tspec->AddEntry(g2011_h,"2011 EB hR9","PL");
  tspec->AddEntry(g2012_l,"2012 EB lR9","PL");
  tspec->AddEntry(g2011_l,"2011 EB lR9","PL");

  g2012_h->Draw("p");
  g2011_h->Draw("p, same");
  g2012_l->Draw("p, same");
  g2011_l->Draw("p, same");
    
  tspec->Draw("same");
  c->Print( (plotDirOut+"/EoP_vs_Et_EB.png").c_str(),".png");

  ///////////////////////////////////////////////////////
  // tutto EE in 1 plot
  std::string f11_hE = plotDir+"/results_EE_HIGH_scE_reg_2011.root";
  std::string f12_hE = plotDir+"/results_EE_HIGH_scE_reg_2012.root";
  std::string f11_lE = plotDir+"/results_EE_LOW_scE_reg_2011.root";
  std::string f12_lE = plotDir+"/results_EE_LOW_scE_reg_2012.root";

  TFile F12_hE(f12_hE.c_str(),"read");
  TFile F11_hE(f11_hE.c_str(),"read");

  TFile F12_lE(f12_lE.c_str(),"read");
  TFile F11_lE(f11_lE.c_str(),"read");

  TGraphErrors* g2012_hE = (TGraphErrors*)F12_hE.Get("finalGraph");
  TGraphErrors* g2011_hE = (TGraphErrors*)F11_hE.Get("finalGraph");
  TGraphErrors* g2012_lE = (TGraphErrors*)F12_lE.Get("finalGraph");
  TGraphErrors* g2011_lE = (TGraphErrors*)F11_lE.Get("finalGraph");

    g2012_hE->SetMarkerColor(kGreen+2);
    g2012_lE->SetMarkerColor(kGreen+2);
    g2011_hE->SetMarkerColor(kRed+2);
    g2011_lE->SetMarkerColor(kRed+2);

    g2012_hE->SetMarkerStyle(20);
    g2011_hE->SetMarkerStyle(20);
    g2012_lE->SetMarkerStyle(21);
    g2011_lE->SetMarkerStyle(21);

  TCanvas* cE = new TCanvas("gE", "gE",100,100,725,500);
  cE->cd();
  TPad *cLeft  = new TPad("pad_0","pad_0",0.00,0.00,1.00,1.00);
  cLeft->SetLeftMargin(0.17);
  cLeft->SetRightMargin(0.025);
  cLeft->SetBottomMargin(0.17);
  cLeft->Draw();
  float tYoffset = 1.75;
  float tXoffset = 1.6;
  float labSize = 0.04;
  float labSize2 = 0.07;
  cLeft->cd();
  cLeft->SetGridx();
  cLeft->SetGridy();
    
  // pad settings                                                                     
  TH1F *hPad = (TH1F*)gPad->DrawFrame(20,-0.02,100,0.02);
  hPad->GetXaxis()->SetTitle("E_{T}");
  hPad->GetYaxis()->SetTitle("E/p_{data}-E/p_{mc}");
  hPad->GetYaxis()->SetTitleOffset(tYoffset);
  hPad->GetXaxis()->SetTitleOffset(tXoffset);
  hPad->GetXaxis()->SetLabelSize(labSize);
  hPad->GetXaxis()->SetTitleSize(labSize);
  hPad->GetYaxis()->SetLabelSize(labSize);
  hPad->GetYaxis()->SetTitleSize(labSize);

  TLegend *tspecE = new TLegend(0.64,0.80,0.99,0.99);
  tspecE->SetFillColor(0);
  tspecE->SetTextFont(42);

  tspecE->AddEntry(g2012_hE,"2012 EE hR9","PL");
  tspecE->AddEntry(g2011_hE,"2011 EE hR9","PL");
  tspecE->AddEntry(g2012_lE,"2012 EE lR9","PL");
  tspecE->AddEntry(g2011_lE,"2011 EE lR9","PL");

  g2012_hE->Draw("p");
  g2011_hE->Draw("p, same");
  g2012_lE->Draw("p, same");
  g2011_lE->Draw("p, same");
    
  tspecE->Draw("same");
  cE->Print( (plotDirOut+"/EoP_vs_Et_EE.png").c_str(),".png");

}
void EMCDistribution_SUM_RawADC(TString sTOWER = "Energy_Sum_col1_row2_5x5",
                                TString CherenkovSignal = "C2_Inner")
{
  TH1 *EnergySum_LG_full = new TH1F("EnergySum_LG_full",
                                    ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  TH1 *EnergySum_LG = new TH1F("EnergySum_LG",
                               ";Tower Energy Sum (ADC);Count / bin", 260, -100, 2500);
  //  TH1 * EnergySum_HG = new TH1F("EnergySum_HG",
  //      ";Low range Tower Energy Sum (ADC);Count / bin", 50, 0, 500);

  TH1 *C2_Inner_full = new TH1F("C2_Inner_full",
                                CherenkovSignal + ";Cherenkov Signal (ADC);Count / bin", 1000, 0, 2000);
  TH1 *C2_Inner = new TH1F("C2_Inner",
                           CherenkovSignal + ";Cherenkov Inner Signal (ADC);Count / bin", 1000, 0, 2000);

  EnergySum_LG_full->SetLineColor(kBlue + 3);
  EnergySum_LG_full->SetLineWidth(2);

  EnergySum_LG->SetLineColor(kGreen + 3);
  EnergySum_LG->SetLineWidth(3);
  EnergySum_LG->SetMarkerColor(kGreen + 3);

  C2_Inner_full->SetLineColor(kBlue + 3);
  C2_Inner_full->SetLineWidth(2);

  C2_Inner->SetLineColor(kGreen + 3);
  C2_Inner->SetLineWidth(3);
  C2_Inner->SetMarkerColor(kGreen + 3);

  TCut c2 = CherenkovSignal + ">240";

  T->Draw(sTOWER + ">>EnergySum_LG_full", "", "goff");
  T->Draw(sTOWER + ">>EnergySum_LG", c2, "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner_full", "", "goff");
  T->Draw(CherenkovSignal + ">>C2_Inner", c2, "goff");

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts,
      "EMCDistribution_SUM_RawADC_" + sTOWER + "_" + CherenkovSignal + cuts, 1800,
      600);
  c1->Divide(3, 1);
  int idx = 1;
  TPad *p;

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  C2_Inner_full->DrawClone();
  C2_Inner->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h = (TH1 *) EnergySum_LG_full->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  (TH1 *) EnergySum_LG->DrawClone("same");

  p = (TPad *) c1->cd(idx++);
  c1->Update();
  //  p->SetLogy();
  p->SetGridx(0);
  p->SetGridy(0);

  TH1 *h_full = (TH1 *) EnergySum_LG_full->DrawClone();
  TH1 *h = (TH1 *) EnergySum_LG->DrawClone("same");

  TF1 *fgaus_g = new TF1("fgaus_LG_g", "gaus", h->GetMean() - 1 * h->GetRMS(),
                         h->GetMean() + 4 * h->GetRMS());
  fgaus_g->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
                         h->GetMean() + 2 * h->GetRMS());
  h->Fit(fgaus_g, "MR0N");

  TF1 *fgaus = new TF1("fgaus_LG", "gaus",
                       fgaus_g->GetParameter(1) - 1 * fgaus_g->GetParameter(2),
                       fgaus_g->GetParameter(1) + 4 * fgaus_g->GetParameter(2));
  fgaus->SetParameters(fgaus_g->GetParameter(0), fgaus_g->GetParameter(1),
                       fgaus_g->GetParameter(2));
  h->Fit(fgaus, "MR");

  h->Sumw2();
  h_full->Sumw2();
  h_full->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
                                   h->GetMean() + 4 * h->GetRMS());

  h->SetLineWidth(2);
  h->SetMarkerStyle(kFullCircle);

  h_full->SetTitle(
      Form("#DeltaE/<E> = %.1f%%",
           100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  //  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //  h->SetLineWidth(2);
  //  h->SetLineColor(kBlue + 3);
  ////  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(0, h->GetMean() + 5 * h->GetRMS());
  //
  //  p = (TPad *) c1->cd(idx++);
  //  c1->Update();
  ////  p->SetLogy();
  //  p->SetGridx(0);
  //  p->SetGridy(0);
  //
  //  TH1 * h = (TH1 *) EnergySum_LG->DrawClone();
  //  h->GetXaxis()->SetRangeUser(0,500);
  //
  //  TF1 * fgaus = new TF1("fgaus_HG", "gaus", 0, 100);
  //  fgaus->SetParameters(1, h->GetMean() - 2 * h->GetRMS(),
  //      h->GetMean() + 2 * h->GetRMS());
  //  h->Fit(fgaus, "M");
  //
  //  h->Sumw2();
  //  h->GetXaxis()->SetRangeUser(h->GetMean() - 4 * h->GetRMS(),
  //      h->GetMean() + 4 * h->GetRMS());
  //
  //  h->SetLineWidth(2);
  //  h->SetMarkerStyle(kFullCircle);
  //
  //  h->SetTitle(
  //      Form("#DeltaE/<E> = %.1f%%",
  //          100 * fgaus->GetParameter(2) / fgaus->GetParameter(1)));

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
Exemplo n.º 25
0
void printHisto( TCanvas *can , TChain *data , TChain *mc , TCut num , TCut denom , char* var , int nbins , float xmin , float xmax , char* xtitle , char* ytitle){

  can->cd();

  TPad *plotpad = new TPad("plotpad","plotpad",0.0,0.0,1.0,0.8);
  plotpad->Draw();
  plotpad->cd();

  float ptbin[] = {30., 40., 60. , 80. , 100. , 120. , 150. , 200 , 300 };
  int   nptbin  = 8;

  //TH1F* hpass   = new TH1F(Form("hpass_%i",iplot),Form("hpass_%i",iplot),nptbin,ptbin);
  //TH1F* hall    = new TH1F(Form("hall_%i" ,iplot),Form("hall_%i" ,iplot),nptbin,ptbin);

  // TH1F* hpass_data = new TH1F(Form("hpass_data_%i",iplot),Form("hpass_data_%i",iplot),nbins,xmin,xmax);
  // TH1F* hall_data  = new TH1F(Form("hall_data_%i" ,iplot),Form("hall_data_%i" ,iplot),nbins,xmin,xmax);
  // TH1F* hpass_mc   = new TH1F(Form("hpass_mc_%i"  ,iplot),Form("hpass_mc_%i"  ,iplot),nbins,xmin,xmax);
  // TH1F* hall_mc    = new TH1F(Form("hall_mc_%i"   ,iplot),Form("hall_mc_%i"   ,iplot),nbins,xmin,xmax);

  TH1F* hpass_data   = new TH1F(Form("hpass_data_%i"  ,iplot),Form("hpass_data_%i"  ,iplot),nptbin,ptbin);
  TH1F* hall_data    = new TH1F(Form("hall_data_%i"   ,iplot),Form("hall_data_%i"   ,iplot),nptbin,ptbin);
  TH1F* hratio_data  = new TH1F(Form("hratio_data_%i" ,iplot),Form("hratio_data_%i" ,iplot),nptbin,ptbin);
  TH1F* hpass_mc     = new TH1F(Form("hpass_mc_%i"    ,iplot),Form("hpass_mc_%i"    ,iplot),nptbin,ptbin);
  TH1F* hall_mc      = new TH1F(Form("hall_mc_%i"     ,iplot),Form("hall_mc_%i"     ,iplot),nptbin,ptbin);
  TH1F* hratio_mc    = new TH1F(Form("hratio_mc_%i"   ,iplot),Form("hratio_mc_%i"   ,iplot),nptbin,ptbin);
  TH1F* hsf          = new TH1F(Form("hsf_%i"         ,iplot),Form("hsf_%i"         ,iplot),nptbin,ptbin);

  hpass_data->Sumw2();
  hall_data->Sumw2();
  hratio_data->Sumw2();
  hpass_mc->Sumw2();
  hall_mc->Sumw2();
  hratio_mc->Sumw2();
  hsf->Sumw2();

  //TCanvas *can = new TCanvas(Form("can_%i",iplot),Form("can_%i",iplot),600,600);
  //can->cd();
  
  data->Draw(Form("min(%s,%f)>>hpass_data_%i"  , var,xmax-0.0001,iplot),denom+num);
  data->Draw(Form("min(%s,%f)>>hall_data_%i"   , var,xmax-0.0001,iplot),denom);
  mc->Draw  (Form("min(%s,%f)>>hpass_mc_%i"    , var,xmax-0.0001,iplot),denom+num);
  mc->Draw  (Form("min(%s,%f)>>hall_mc_%i"     , var,xmax-0.0001,iplot),denom);

  TGraphAsymmErrors *grdata = new TGraphAsymmErrors();
  grdata->BayesDivide(hpass_data,hall_data);

  TGraphAsymmErrors *grmc = new TGraphAsymmErrors();
  grmc->BayesDivide(hpass_mc,hall_mc);

  // cout << "data all  " << hall_data->GetBinContent(8) << endl;
  // cout << "data pass " << hpass_data->GetBinContent(8) << endl;
  // cout << "data eff  " << hpass_data->GetBinContent(8) / hall_data->GetBinContent(8) << endl;

  // Double_t x;
  // Double_t y;
  // grdata->GetPoint(7,x,y);
  // cout << "data eff2 " << y << endl;

  gPad->SetGridx();
  gPad->SetGridy();

  grdata->SetMarkerColor(2);
  grdata->SetLineColor(2);
  grmc->SetMarkerColor(4);
  grmc->SetLineColor(4);
  grmc->SetMarkerStyle(25);

  grdata->GetXaxis()->SetRangeUser(30,300);
  grdata->GetYaxis()->SetRangeUser(0.6,1.0);
  grdata->GetXaxis()->SetTitle(xtitle);
  grdata->GetYaxis()->SetTitle(ytitle);
  grdata->Draw("AP");
  grmc->Draw("sameP");

  TLegend *leg = new TLegend(0.5,0.2,0.7,0.4);
  leg->AddEntry(grdata ,"data","lp");
  leg->AddEntry(grmc   ,"mc"  ,"lp");
  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  //leg->Draw();

  TLatex *t = new TLatex();
  t->SetNDC();

  if( TString(denom.GetTitle()).Contains("njets==0") ) t->DrawLatex(0.2,0.2,"n_{jets}=0");
  if( TString(denom.GetTitle()).Contains("njets==1") ) t->DrawLatex(0.2,0.2,"n_{jets}=1");
  if( TString(denom.GetTitle()).Contains("njets==2") ) t->DrawLatex(0.2,0.2,"n_{jets}=2");
  if( TString(denom.GetTitle()).Contains("njets==3") ) t->DrawLatex(0.2,0.2,"n_{jets}=3");
  if( TString(denom.GetTitle()).Contains("njets>=4") ) t->DrawLatex(0.2,0.2,"n_{jets}#geq4");

  can->cd();

  TPad *respad = new TPad("respad","respad",0.0,0.8,1.0,1.0);
  respad->Draw();
  respad->cd();
  respad->SetGridy();

  // TGraphAsymmErrors* gr_ratio = (TGraphAsymmErrors*) grdata->Clone("gr_ratio");
  // gr_ratio->Divide(grmc);
  // gr_ratio->Draw();

  hratio_data->Divide(hpass_data,hall_data,1,1,"B");
  hratio_mc  ->Divide(hpass_mc  ,hall_mc,1,1,"B");
  hsf        ->Divide(hratio_data,hratio_mc,1,1);

  hsf->GetYaxis()->SetRangeUser(0.8,1.2);
  hsf->GetYaxis()->SetNdivisions(5);
  hsf->GetYaxis()->SetLabelSize(0.2);
  hsf->GetXaxis()->SetLabelSize(0.0);
    
  hsf->Draw("E1");

  iplot ++;
}
void EMCDistribution_PeakSample_Fast(bool full_gain = false)
{
  const TString gain = "RAW";

  TString hname = "EMCDistribution_" + gain + TString(full_gain ? "_FullGain" : "") + cuts;

  TH2 *h2 = NULL;
  {
    if (full_gain)
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 100,
                    .05 * 100, 25 * 100, 64, -.5, 63.5);
      QAHistManagerDef::useLogBins(h2->GetXaxis());
    }
    else
    {
      h2 = new TH2F(hname,
                    Form(";Calibrated Tower Energy Sum (ADC);Count / bin"), 260,
                    -.2 * 100, 5 * 100, 64, -.5, 63.5);
    }
    T->Draw(
        "TOWER_" + gain + "_CEMC[].get_bineta() + 8* TOWER_" + gain + "_CEMC[].get_binphi():(TOWER_RAW_CEMC[].signal_samples[10] - TOWER_RAW_CEMC[].signal_samples[0])*(-1)>>" + hname, "", "goff");
  }

  TText *t;
  TCanvas *c1 = new TCanvas(
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts,
      "EMCDistribution_PeakSample_Fast_" + TString(full_gain ? "_FullGain" : "") + cuts, 1800, 950);
  c1->Divide(8, 8, 0., 0.01);
  int idx = 1;
  TPad *p;

  for (int iphi = 8 - 1; iphi >= 0; iphi--)
  {
    for (int ieta = 0; ieta < 8; ieta++)
    {
      p = (TPad *) c1->cd(idx++);
      c1->Update();

      p->SetLogy();
      if (full_gain)
      {
        p->SetLogx();
      }
      p->SetGridx(0);
      p->SetGridy(0);

      TString hname = Form("hEnergy_ieta%d_iphi%d", ieta, iphi) + TString(full_gain ? "_FullGain" : "");

      TH1 *h = h2->ProjectionX(hname, ieta + 8 * iphi + 1,
                               ieta + 8 * iphi + 1);  // axis bin number is encoded as ieta+8*iphi+1

      h->SetLineWidth(0);
      h->SetLineColor(kBlue + 3);
      h->SetFillColor(kBlue + 3);

      h->GetXaxis()->SetTitleSize(.09);
      h->GetXaxis()->SetLabelSize(.08);
      h->GetYaxis()->SetLabelSize(.08);

      h->Draw();

      if (full_gain)
        h->Fit("x*gaus", "M");
      else
        h->Fit("landau", "M");

      double peak = -1;

      TF1 *fit = ((TF1 *) (h->GetListOfFunctions()->At(0)));
      if (fit)
      {
        fit->SetLineColor(kRed);
        peak = fit->GetParameter(1);
      }

      cout << Form("Finished <Col%d Row%d> = %.1f", ieta, iphi, peak)
           << endl;

      TText *t = new TText(.9, .9,
                           Form("<Col%d Row%d> = %.1f", ieta, iphi, peak));
      t->SetTextAlign(33);
      t->SetTextSize(.15);
      t->SetNDC();
      t->Draw();
    }
  }

  SaveCanvas(c1,
             TString(_file0->GetName()) + TString("_DrawPrototype3EMCalTower_") + TString(c1->GetName()), false);
}
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.º 28
0
// Make main selection plots
// n-1, control type plots and plots after all cuts
void makePlot(const TString & histoName, TFile * outputFile, TString anaType,
    const TString & xTitle,  const double & xMin, const double & xMax,
    const double & yMin = 0., const double & yMax = 0., bool logY=false,
    const float lumi = 0, const bool plotData=false, bool drawRatioPlot=false )
{
  std::cout << "----> Making plots for : " << histoName.Data() << std::endl;
  std::cout << "Plotting data ? " << plotData << std::endl;
  TH1::SetDefaultSumw2();
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

  // Keep track of integrals of background & data
  double totalBkgMCIntegral = 0;
  //  double totalDataIntegral = 0;

  //
  // DATA
  //

  TH1F * histoData=0;

  if (plotData) {

    TFile * inputFile= new TFile ("CombinedFiles/Data_combined_"+anaType+".root", "READ");
    histoData = (TH1F*)inputFile->Get(histoName);
    //    totalDataIntegral = histoData->Integral();

    histoData->SetStats(0);
    histoData->SetMarkerStyle(21);
    histoData->SetMarkerSize(1);
  }

  //
  // SIGNAL MC
  //


  // Not good at the moment - just taking one or two examples to plot and hard coded the names of the files here
  TFile * signalInputFile1= new TFile (signal1+anaType+".root", "READ");
  TH1F * histoSignal1 = (TH1F*)signalInputFile1->Get(histoName);
  histoSignal1->SetStats(0);
  histoSignal1->Scale(lumi);

  TFile * signalInputFile2= new TFile (signal2+anaType+".root", "READ");
  TH1F * histoSignal2 = (TH1F*)signalInputFile2->Get(histoName);
  histoSignal2->SetStats(0);
  histoSignal2->Scale(lumi);

  int minIntegral=0;
  int maxIntegral=histoSignal1->GetNbinsX();

//  if ( histoName=="nMinus1_isolationLeptonH_removedLifetimeCuts" || histoName=="nMinus1_relIsolationLeptonH_removedLifetimeCuts" ) {
//    //    std::cout << find90Cut( histoSignal1 ) << std::endl;
//    //    std::cout << find90Cut( histoSignal2 ) << std::endl;
//
//    minIntegral=histoSignal1->FindBin( find90Cut(histoSignal1) );
//
//    // Check integral below specific cut
//    if ( histoName=="nMinus1_relIsolationLeptonH_removedLifetimeCuts" ) {
//      std::cout << "Signal 1" << std::endl;
//      std::cout << "Efficiency with rel iso cut at 0.1 : " << histoSignal1->Integral( 1, histoSignal1->FindBin(0.1) ) / histoSignal1->Integral() << std::endl;
//      std::cout << "Efficiency with rel iso cut at 0.05 : " << histoSignal1->Integral( 1, histoSignal1->FindBin(0.05) ) / histoSignal1->Integral() << std::endl;
//      std::cout << "Signal 2" << std::endl;
//      std::cout << "Efficiency with rel iso cut at 0.1 : " << histoSignal2->Integral( 1, histoSignal2->FindBin(0.1) ) / histoSignal2->Integral() << std::endl;
//      std::cout << "Efficiency with rel iso cut at 0.05 : " << histoSignal2->Integral( 1, histoSignal2->FindBin(0.05) ) / histoSignal2->Integral() << std::endl;
//    }
//  }

  TFile * signalInputFile3= new TFile (signal3+anaType+".root", "READ");
  TH1F * histoSignal3 = (TH1F*)signalInputFile3->Get(histoName);
  histoSignal3->SetStats(0);
  histoSignal3->Scale(lumi);

  //
  // BACKGROUND MC
  //

  THStack stack("Background MC","");
  setPlotTitle(stack, lumi);

  // Add all different background MC to this stack
  TLegend *legend= new TLegend(0.5,0.6,0.85,0.85);

  totalBkgMCIntegral = addBackgroundHistos(anaType, histoName, stack, legend, lumi, minIntegral, maxIntegral);


//  if ( histoName=="nMinus1_isolationLeptonH_removedLifetimeCuts" || histoName=="nMinus1_relIsolationLeptonH_removedLifetimeCuts" ) {
//    std::cout << "Integral of background between " << minIntegral << " and " << maxIntegral << " : " << totalBkgMCIntegral << std::endl;
//  }

  // Output histograms to file
  outputFile->cd();

  // Setup canvas
  TCanvas canvas(histoName);
  canvas.cd();
  // Draw one or two pads
  TPad * up = new TPad("u","u",0.01,0.25,0.99,0.99);
  up->SetNumber(1);
  up->Draw();
  TPad * dp = new TPad("d","d",0.01,0.01,0.99,0.25);

  if ( drawRatioPlot ) {
    dp->SetNumber(2);
    dp->UseCurrentStyle();
    dp->Draw();
  }
  else {
    up->SetPad(0.01,0.01,0.99,0.99);
    up->Draw();
  }

  if ( logY ) up->SetLogy();
  canvas.Draw();
  canvas.cd(1);
  up->cd();
  canvas.SetFillColor(kWhite);
  canvas.SetBorderMode(0);


  // Draw background MC
  // There may be zero entries, which will mess up drawing options
  // Not a good fix at the moment
  bool axesExist=false;
  if (totalBkgMCIntegral>0) {
    axesExist=true;

    stack.Draw("HISTE");

    stack.GetXaxis()->SetRangeUser(xMin, xMax);
    stack.SetMaximum(yMax);
    stack.SetMinimum(yMin);
    stack.GetXaxis()->SetTitle(xTitle);
    stack.GetYaxis()->SetTitle("Entries");
  }

  std::cout << "Drawing signal histos" << std::endl;
  // Draw signal MC
  histoSignal1->SetLineStyle(2);
  histoSignal1->SetLineColor(kMagenta+2);
  histoSignal1->SetLineWidth(2);
  if(axesExist) histoSignal1->Draw("same,HIST");
  else histoSignal1->Draw("HIST");

  histoSignal2->SetLineStyle(2);
  histoSignal2->SetLineColor(kGreen+2);
  histoSignal2->SetLineWidth(2);
  if(axesExist) histoSignal2->Draw("same,HIST");
  else histoSignal2->Draw("HIST");

  //  histoSignal3->SetLineStyle(2);
  //  histoSignal3->SetLineColor(4);
  //  histoSignal3->SetLineWidth(2);
  //  histoSignal3->Draw("same,HIST");

  // Draw data
  if ( plotData ) {
    if (axesExist) histoData->Draw("same,P,E,X0");
    else histoData->Draw("P,E,X0");
  }

  // Draw legend
  legend->SetBorderSize(0);
  legend->SetFillStyle(0);
  if ( plotData ) legend->AddEntry(histoData,"data","p");
  legend->AddEntry(histoSignal1,"m_{H}=1000 GeV/c^{2} m_{X}=350 GeV/c^{2}","l");
  legend->AddEntry(histoSignal2,"m_{H}=400 GeV/c^{2} m_{X}=50 GeV/c^{2}","l");
  //  legend->AddEntry(histoSignal3,"m_{squark}=350 GeV/c^{2} m_{#Chi}=148 GeV/c^{2}","l");

  legend->Draw();

  canvas.Update();

  // Draw mc/data ratio
  if ( drawRatioPlot ) {
    dp->cd();
    TH1F ratioHist( drawMCDataRatio( ((TH1*)stack.GetStack()->Last()), histoData ) );

    // Check content of ratioHist
    ratioHist.GetXaxis()->SetRangeUser(xMin, xMax);
    ratioHist.SetMarkerStyle(20);
    ratioHist.GetYaxis()->SetNdivisions(5,0,0);
    ratioHist.GetYaxis()->SetTickLength(0.01);
    dp->SetGridy();
    ratioHist.Draw("P");
    canvas.Update();
    canvas.Write();
  }
  else canvas.Write();

  // Draw systematic errors for reco PV plot
  // FIXME For some reason, old canvas can't handle this!
  if ( histoName=="nRecoPV" ) {
    TGraphAsymmErrors gr( makePUPlot( stack, anaType, lumi ) );

    // Move back to output file (as other files have been opened and closed in makePUPlot
    outputFile->cd();

    gr.SetFillColor(1);
    gr.SetFillStyle(3001);
    gr.Draw("2P0");
    canvas.Update();

    // Test
    TCanvas can("puSystematic");
    can.cd();
//    can.SetLogy();
    can.Draw();
    gr.SetTitle("TGraphAsymmErrors Example");

    stack.Draw("HISTE");
    gr.Draw("2P0");
    histoData->Draw("P,E,X0SAME");
    legend->Draw();

    can.Update();
    can.Write();
  }
}