Example #1
0
void plotEfficiency(TGraphAsymmErrors *eff1, string legend1, TGraphAsymmErrors *eff2, string legend2,
                    string plotname, 
                    Double_t xmin = -99, Double_t xmax = -99, 
                    Double_t ymin  = -99 , Double_t ymax = -99 ) {

  TCanvas *cv = MakeCanvas("cv", "cv", 800, 600);
  TLegend *leg = new TLegend(0.60,0.80,0.90,0.90);
  leg->SetBorderSize(0);  
  leg->SetTextSize(0.03);
  

  eff1->SetTitle("");
  eff2->SetTitle("");
  eff1->SetLineColor(kRed);
  eff1->SetMarkerColor(kRed);
  eff2->SetLineColor(kBlue);
  eff2->SetMarkerColor(kBlue);

  leg->Clear();
  leg->AddEntry(eff1, legend1.c_str(), "P");
  leg->AddEntry(eff2, legend2.c_str(), "P");

  if (xmin != -99 && xmax != -99) eff1->GetXaxis()->SetRangeUser(xmin,xmax);
  if (ymin != -99) eff1->SetMinimum(ymin);
  if (ymax != -99) eff1->SetMaximum(ymax);

  eff1->Draw("AP");
  eff2->Draw("Psame");
  leg->Draw();
  cv->SaveAs((plotname + ".gif").c_str());
   cv->SaveAs((plotname + ".eps").c_str());

}
Example #2
0
void Limitd() {
    setNCUStyle(true);
    c1 = new TCanvas("c1","",800,600);

    int width [nWidth]= {25,30,35,40};
    int bmin[nBmin]= {100,105,110,115};
    string  masspoint[11]= {"1000","1200","1400","1600","1800","2000","2500","3000","3500","4000","4500"};

    TLegend *leg = new TLegend(0.75, 0.68, 0.96, 0.95);

    leg->SetBorderSize(0);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);
    leg->SetTextSize(0.04);

    string categoryName[7]= {"0a","0c","1a","1c","2a","2b","2d"};

    for(int k=0; k<3; k++) {
        leg->Clear();
        int lower=105,upper=135;
        if(k==1) {
            lower=110;
            upper=140;
        }
        else if (k==2) {
            lower=115;
            upper=145;
        }

        for(int h=0; h<7; h++) {
            TFile* tf1=TFile::Open(Form("%sW/MassPlotFineBins_subtr_Moriond_Silver%dto%d.root",categoryName[h].data(),lower,upper));
            //if(h==2) tf1=TFile::Open(Form("%sW/MassPlotFineBins_subtr_Moriond_Silver110to145.root",categoryName[h].data()));
            //if(h>=3) tf1=TFile::Open(Form("%sW/MassPlotFineBins_subtr_Moriond_Silver115to145.root",categoryName[h].data()));
            if (!tf1 || !tf1->IsOpen())continue;
            TGraphAsymmErrors* tg1=(TGraphAsymmErrors*)tf1->Get("LimitExpectedCLs");
            tg1->GetYaxis()->SetTitle("95% CLs on #sigma(X#rightarrowHH)#timesBR(HH#rightarrowb#bar{b}b#bar{b})[fb]");
            tg1->SetLineStyle(1);
            tg1->SetFillColor(0);
            tg1->SetLineColor(h+1);
            leg->AddEntry(tg1,Form("%s %d-%d",categoryName[h].data(),lower,upper));
            // else if(h==2)leg->AddEntry(tg1,Form("%s 110-145",categoryName[h].data()));
            // else if(h>=3)leg->AddEntry(tg1,Form("%s 115-145",categoryName[h].data()));
            tg1->SetMaximum(12);
            tg1->SetMinimum(0.5);
            // cout<<k<<","<<m<<endl;
            //c1->SetLogy(1);
            if(h==0)tg1->Draw("APL");
            else tg1->Draw("PL same");
        }


        leg->Draw("same");
        c1->Print(Form("limitPlots/%d-%d.pdf",lower,upper));

    }
}
Example #3
0
void PlotFakePredictions() {

    TFile *fileSS = new TFile("WWSelectionPlotsFakePrediction_SS.root", "READ");
    TFile *fileOS = new TFile("WWSelectionPlotsFakePrediction.root", "READ");
    
    TH1F *LeptonPtMin_OS = (TH1F*)fileOS->Get("hLeptonPtMin");
    TH1F *LeptonPtMin_SS = (TH1F*)fileSS->Get("hLeptonPtMin");

    TLegend *legend = new TLegend(0.73,0.75,0.93,0.90);
    legend->SetTextSize(0.03);
    legend->SetBorderSize(1);
    
    legend->Clear();
    legend->AddEntry(LeptonPtMin_OS, "OppSign", "L");
    legend->AddEntry(LeptonPtMin_SS, "SameSign", "LP");

    TCanvas *cv = new TCanvas("cv","cv",800,600);
    LeptonPtMin_OS->SetMaximum(0.4);
    LeptonPtMin_OS->Draw("hist");
    LeptonPtMin_SS->SetLineColor(kRed);
    LeptonPtMin_SS->SetMarkerColor(kRed);
    LeptonPtMin_SS->Draw("same,E1");
    legend->Draw();
    cv->SaveAs("LeptonPtMin_FakePrediction.gif");

//     fileSS->Close();
//     fileOS->Close();



    TH1F *DileptonMass_OS = (TH1F*)fileOS->Get("dileptonMass");
    TH1F *DileptonMass_SS = (TH1F*)fileSS->Get("dileptonMass");
    DileptonMass_OS->SetMaximum(0.25);
    DileptonMass_OS->Draw("hist");
    DileptonMass_SS->SetLineColor(kRed);
    DileptonMass_SS->SetMarkerColor(kRed);
    DileptonMass_SS->Draw("same,E1");
    legend->Draw();
    cv->SaveAs("DileptonMass_FakePrediction.gif");

    TH1F *DeltaPhiLeptons_OS = (TH1F*)fileOS->Get("hDeltaPhiLeptons");
    TH1F *DeltaPhiLeptons_SS = (TH1F*)fileSS->Get("hDeltaPhiLeptons");
    DeltaPhiLeptons_OS->SetMaximum(0.25);
    DeltaPhiLeptons_OS->Draw("hist");
    DeltaPhiLeptons_SS->SetLineColor(kRed);
    DeltaPhiLeptons_SS->SetMarkerColor(kRed);
    DeltaPhiLeptons_SS->Draw("same,E1");
    legend->Draw();
    cv->SaveAs("DeltaPhiLeptons_FakePrediction.gif");


}
bool plot_nhists(vector<TH1F*> histo, TString epsname, TString* type)
{

  set_style();

  TCanvas* can = new TCanvas("can", "can", 600, 600); 
  can->cd();

  can->Print(epsname+"[");
  can->SetLogy();
  
  TLegend * legend = new TLegend(0.7,0.8,.92,0.99);
  legend->SetTextFont(72);
  legend->SetTextSize(0.04);
  legend->SetFillColor(kWhite);
  
  TString  histo_titel = histo[0]->GetTitle();
  int b =0;

  for(unsigned int i = 0; i<histo.size(); ++i){ 
    if(histo_titel==histo[i]->GetTitle()){
      histo[i]->SetMaximum(histo[i]->GetMaximum()<1 ? 1.2 : 1.4*histo[i]->GetMaximum());
      histo[i]->Draw("same");
      histo[i]->SetLineColor(b+2);
      legend->AddEntry(histo[i],type[b]);
      b+=1;
    }
    else{
      
      legend->Draw();
      can->Print(epsname);
      legend->Clear();
      b=0;
      histo[i]->SetMaximum(histo[i]->GetMaximum()<1 ? 1.2 : 1.4*histo[i]->GetMaximum());
      histo[i]->Draw();
      histo[i]->SetLineColor(b+2);
      legend->AddEntry(histo[i],type[b]);
      b+=1;
      histo_titel=histo[i]->GetTitle();
    }
  }

  legend->Draw();
  can->Print(epsname);

  can->Print(epsname+"]");
  can->Close();
  
  return true;


}
Example #5
0
//------------------------------------------//
// Format amplitude plots
//------------------------------------------//
void ampPlot(TFile* file, vector<TString> filters)
{

  // Specify the titles
  TString xtitle = "Amplitude [v]";
  TString ytitle = "Entries";

  // Histogram name
  TString pname = "h_amp";

  // Create canvas
  TCanvas* c = makeCanvas("c");
  c->SetLogx();
  c->SetLogy();

  // Make legend
  TLegend* leg = makeLegend(0.7,0.8,0.8,0.9);

  // Loop and plot
  TH1* hist = NULL;
  for(unsigned int i=0; i<filters.size(); ++i){
    leg->Clear();
    leg->SetHeader("Filter");
    
    TString filter = filters.at(i);
    
    hist = getHist(file,pname+"_"+filter,xtitle,ytitle,
		   m_colors[i], m_markers[i]);
    
    leg->AddEntry(hist,(filter+"%").Data(),"l");
    hist->Draw();

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

    c->SaveAs((savedir+"amp_filter"+filter+".png").Data());

  }// end loop over filters


	       
}
Example #6
0
//------------------------------------------//
// Plotting the maximum time difference
// for the maximum amplitude wave
//------------------------------------------//
void tDiffMaxPlotForMaxV(TFile* file, vector<TString> filters)
{

  // Specify the titles
  TString xtitle = "Max(LEtime - wavetime) [ns]";
  TString ytitle = "Entries";

  // Histogram name
  TString pname = "h_maxTDiff_forMaxV";

  // Create canvas
  TCanvas* c = makeCanvas("c");
  //c->SetLogy();
  
  // Make legend
  TLegend* leg = makeLegend(0.7,0.8,0.8,0.9);

  // Loop and plot
  TH1* hist = NULL;
  for(unsigned int i=0; i<filters.size(); ++i){
    leg->Clear();
    leg->SetHeader("Filter");
    TString filter = filters.at(i);
    
    hist = getHist(file,pname+"_"+filter,xtitle,ytitle,
		   m_colors[i], m_markers[i]);
    
    leg->AddEntry(hist,(filter+"%").Data(),"l");
    hist->Draw();

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

    // Save 
    //c->SaveAs((savedir+"maxTimeDiff_filter"+filter+"_nonlog.png").Data());
    //c->SaveAs((savedir+"maxTimeDiff_cutOnCounter_filter"+filter+"_nonlog.png").Data());

  }// end loop over filters

	       
}
Example #7
0
void plotEfficiency(vector<TGraphAsymmErrors*> efficiencyGraphs, vector<string> efficiencyGraphLabels, 
                    string plotname, 
                    Double_t xmin = -99, Double_t xmax = -99, 
                    Double_t ymin  = -99 , Double_t ymax = -99 ) {

  assert(efficiencyGraphs.size() > 0);
  assert(efficiencyGraphs.size() == efficiencyGraphLabels.size());

  TCanvas *cv = MakeCanvas("cv", "cv", 800, 600);
  TLegend *leg = new TLegend(0.60,0.80,0.90,0.90);
  leg->SetBorderSize(0);  
  leg->SetTextSize(0.03);

  leg->Clear();
  for (int i=0; i<efficiencyGraphs.size() ; ++i) {
    efficiencyGraphs[i]->SetTitle("");
    efficiencyGraphs[i]->SetLineColor(COLORS[i]);
    efficiencyGraphs[i]->SetMarkerColor(COLORS[i]);
    efficiencyGraphs[i]->SetMarkerStyle(MARKERS[i]);
    efficiencyGraphs[i]->GetYaxis()->SetTitle("Fake Rate");
    leg->AddEntry(efficiencyGraphs[i], efficiencyGraphLabels[i].c_str(), "P");
  }

  if (xmin != -99 && xmax != -99) efficiencyGraphs[0]->GetXaxis()->SetRangeUser(xmin,xmax);
  if (ymin != -99) efficiencyGraphs[0]->SetMinimum(ymin);
  if (ymax != -99) efficiencyGraphs[0]->SetMaximum(ymax);

  for (int i=0; i<efficiencyGraphs.size() ; ++i) {
    if (i==0) efficiencyGraphs[i]->Draw("AP");
    else efficiencyGraphs[i]->Draw("Psame");
  }
  leg->Draw();
  cv->SaveAs((plotname + ".gif").c_str());
   cv->SaveAs((plotname + ".eps").c_str());

}
int comp_crossSection_pt_LHCb_each_xErr(bool shifted=false, Int_t runCode=0, bool isScale =false, bool isLog=true, bool isPtCut = false)
{
	//gROOT->Macro("./JpsiStyleForFinalResult.C");
	gROOT->Macro("./tdrstyle_kyo.C");
	gStyle->SetTitleSize(0.046, "XYZ");
  gStyle->SetEndErrorSize(0);
	gStyle->SetOptTitle(0);
	gStyle->SetOptStat(0);
  gStyle->SetPadTopMargin(0.075);
  gStyle->SetPadBottomMargin(0.13); //KYO
  gStyle->SetPadLeftMargin(0.13); //KYO
  gStyle->SetPadRightMargin(0.075);
	gStyle->SetTitleXOffset(1.15);
	gStyle->SetTitleYOffset(1.22);
  //gStyle->SetTitleFontSize(0.03); // KYO
  gStyle->SetTitleSize(0.05, "XYZ");
	
	
	// set info.
	const Double_t br = 0.0593 ;
	const Double_t brErr = 0.0006;
	Double_t lumi_nb;
	Double_t lumi_nb_err;
	Double_t lumi_mub;
	Double_t lumi_mub_err;
	string runstring;
	string lumistring;
	string cmsstring = "CMS preliminary";
	string beamstring = "pPb #sqrt{s_{NN}} = 5.02 TeV";
	if (runCode ==0) { runstring = "All"; lumi_nb =34.622; lumi_nb_err=1.2; }
	else if (runCode == 1) { runstring = "Pbp"; lumi_nb =20.7; lumi_nb_err=0.7; }//1stRun
	else if (runCode == 2) { runstring = "pPb"; lumi_nb = 14.0; lumi_nb_err=0.5; }//2ndRun
	lumistring = Form("L_{int} = %.1f nb^{-1}", lumi_nb);
	lumi_mub = lumi_nb * 1000; // (nb)^{-1} -> {#mub}^{-1}
	lumi_mub_err = lumi_nb_err * 1000; // (nb)^{-1} -> {#mub}^{-1}
	
	// read our crossSection_pt graph
	TFile *inFile = new TFile("cross_8rap9pt2gev/crossSection_pt_isLog0_isScale0.root");
	TGraphAsymmErrors* gCross_pr_sys_0 = (TGraphAsymmErrors*)inFile->Get("gCross_pr_sys_0"); 	
	TGraphAsymmErrors* gCross_pr_0 = (TGraphAsymmErrors*)inFile->Get("gCross_pr_0"); 	
	TGraphAsymmErrors* gCross_np_sys_0 = (TGraphAsymmErrors*)inFile->Get("gCross_np_sys_0"); 	
	TGraphAsymmErrors* gCross_np_0 = (TGraphAsymmErrors*)inFile->Get("gCross_np_0"); 	
	cout << "gCross_pr_sys_0 = " << gCross_pr_sys_0 << endl;
	cout << "gCross_pr_0 = " << gCross_pr_0 << endl;
	cout << "gCross_np_sys_0 = " << gCross_np_sys_0 << endl;
	cout << "gCross_np_0 = " << gCross_np_0 << endl;

	///////////////////////////////////////////////////
	///////////////////// LHCb ////////////////////////
	///////////////////////////////////////////////////
	Double_t lhcb_px[] = {0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 10.5};
	//Double_t lhcb_ex[] = {0., 0., 0., 0., 0., 0., 0., 0.};
	Double_t lhcb_ex[] = {0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 3.5}; //binW
//	Double_t lhcb_py_pr[] = {69.1, 160.2, 138.5, 85.6, 60.4, 34.2, 17.8, 2.8};
//	Double_t lhcb_py_np[] = {12.5, 15.6, 19.3, 14.9, 10.1, 6.6, 3.9, 0.9};
	Double_t lhcb_py_pr[] = {69.1*br, 160.2*br, 138.5*br, 85.6*br, 60.4*br, 34.2*br, 17.8*br, 2.8*br};
	Double_t lhcb_py_np[] = {12.5*br, 15.6*br, 19.3*br, 14.9*br, 10.1*br, 6.6*br, 3.9*br, 0.9*br};

	Double_t lhcb_ey_pr[] = {7.7*br, 11.9*br, 9.9*br, 7.0*br, 4.5*br, 3.0*br, 1.9*br, 0.2*br};
	Double_t lhcb_ey_np[] = {2.7*br, 2.7*br, 2.9*br, 2.4*br, 1.6*br, 1.2*br, 0.8*br, 0.1*br};
	Double_t lhcb_exsys[] = {0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4};
	//Double_t lhcb_exsys[] = {0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2};
	Double_t lhcb_eysys01_pr[] = {3.7, 12.4, 10.0, 7.6, 4.0, 0.9, 0.6, 0.1};
	Double_t lhcb_eysys02_pr[] = {3.1, 7.3, 6.3, 3.9, 2.7, 1.5, 0.8, 0.1};
	Double_t lhcb_eysys01_np[] = {2.4, 2.7, 1.9, 1.3, 0.8, 0.3, 0.4, 0.0};
	Double_t lhcb_eysys02_np[] = {0.6, 0.7, 0.9, 0.7, 0.5, 0.3, 0.2, 0.0};
	
	const Int_t nBin_lhcb = sizeof(lhcb_px)/sizeof(Double_t);
	cout << "nBin_lhcb : " << nBin_lhcb << endl; 

	Double_t dummy01[]={0,0,0,0,0,0,0,0};
	Double_t dummy02[]={0,0,0,0,0,0,0,0};
	Double_t dummy03[nBin_lhcb];
	Double_t lhcb_eysys_pr[nBin_lhcb];
	Double_t lhcb_eysys_np[nBin_lhcb];

	// total systematic uncertainties = sqrt( (sys01)^2 + (sys02)^2 )
	for (int ipt =0; ipt< nBin_lhcb; ipt ++) {
		AddValue(dummy01[ipt], lhcb_eysys01_pr[ipt], dummy02[ipt], lhcb_eysys02_pr[ipt], &dummy03[ipt], &lhcb_eysys_pr[ipt]);
		lhcb_eysys_pr[ipt]=lhcb_eysys_pr[ipt]*br;
		cout << ipt << "th lhcb_eysys_pr = " << lhcb_eysys_pr[ipt] << endl;
		AddValue(dummy01[ipt], lhcb_eysys01_np[ipt], dummy02[ipt], lhcb_eysys02_np[ipt], &dummy03[ipt], &lhcb_eysys_np[ipt]);
		lhcb_eysys_np[ipt]=lhcb_eysys_np[ipt]*br;
		cout << ipt << "th lhcb_eysys_np = " << lhcb_eysys_np[ipt] << endl;
	}
	//Double_t lhcb_eysys_pr_tmp[] = {4.580392996, 13.86362146, 11.36485812, 8.285529555, 4.614108798, 1.58113883, 0.921954446, 0.141421356};
	//Double_t lhcb_eysys_np_tmp[] = {2.451530134, 2.765863337, 2.024845673, 1.431782106, 0.894427191, 0.424264069, 0.447213595, 0.};

	////////////////////
	////// Draw Plots
	////////////////////

//	TLegend *legUR = new TLegend(0.40, 0.71, 0.83, 0.88); //upper left
	TLegend *legUR = new TLegend(0.50, 0.71, 0.83, 0.85); //upper left
	SetLegendStyle(legUR);
	TLegend *legUL = new TLegend(0.20, 0.73, 0.40, 0.92); //upper left
	SetLegendStyle(legUL);
	legUR->SetTextSize(0.037);
	legUL->SetTextSize(0.037);
  legUR->SetTextFont(42);
  legUL->SetTextFont(42);

	TLatex* latex = new TLatex();
	latex->SetNDC();
	if (isLog) latex->SetTextAlign(12);
	else latex->SetTextAlign(32);
	latex->SetTextSize(0.04);
	
	
	
	//globtex box for beam, rapidity, pT info
	TLatex* globtex = new TLatex();
	globtex->SetNDC();
	//globtex->SetTextAlign(12); //1:left, 2:vertical center
  globtex->SetTextAlign(32); //3:right 2:vertical center
  globtex->SetTextFont(42);
	globtex->SetTextSize(0.04);



	TBox * globalbox = new TBox(0.5, 6.4, 1.5, 13.6);
	globalbox->SetFillColor(kYellow);

	/// LHCb /////
	TGraphAsymmErrors * gCross_lhcb_pr_sys;
	TGraphAsymmErrors * gCross_lhcb_pr;
	TGraphAsymmErrors * gCross_lhcb_np_sys;
	TGraphAsymmErrors * gCross_lhcb_np;

	////// 01 ////////
	// prompt
	TCanvas *c_pr = new TCanvas("c_pr","", 200, 10, 600, 600);
	c_pr->cd();
	if (isLog) gPad->SetLogy(1);
	else gPad->SetLogy(0);
	gCross_pr_sys_0->SetTitle("");
	gCross_pr_sys_0->GetXaxis()->SetTitle("p_{T} [GeV/c]");
	gCross_pr_sys_0->GetXaxis()->CenterTitle();
	if (isPtCut) gCross_pr_sys_0->GetXaxis()->SetLimits(3.0,20.0);
	else gCross_pr_sys_0->GetXaxis()->SetLimits(0.0,20.0);
	gCross_pr_sys_0->GetYaxis()->SetTitle("B x d^{2}#sigma/dp_{T}dy [#mub/(GeV/c)]");
	if (isLog){
		gCross_pr_sys_0->SetMinimum(0.001);
		if (isPtCut) gCross_pr_sys_0->SetMaximum(500.);
		else gCross_pr_sys_0->SetMaximum(100.);
	}
	else {
		gCross_pr_sys_0->SetMinimum(-1.0);
		if(isPtCut) gCross_pr_sys_0->SetMaximum(150.);
//		else gCross_pr_sys_0->SetMaximum(300.);
		else gCross_pr_sys_0->SetMaximum(20.);
	}
	//gCross_pr_sys_0->SetFillColor(kViolet-9);
	gCross_pr_sys_0->SetFillColor(kTeal-9);
	gCross_pr_sys_0->Draw("A2");

	gCross_lhcb_pr_sys = new TGraphAsymmErrors(nBin_lhcb, lhcb_px, lhcb_py_pr, lhcb_exsys, lhcb_exsys, lhcb_eysys_pr, lhcb_eysys_pr);	
	//gCross_lhcb_pr_sys->SetFillColor(kAzure-9);
	gCross_lhcb_pr_sys->SetFillColor(kGray);
	gCross_lhcb_pr_sys->SetFillStyle(3001);

	//SetGraphStyle(gCross_pr_0,8,12);
	SetGraphStyle(gCross_pr_0,0,5);
	gCross_pr_0->SetMarkerSize(2.1);
	gCross_pr_0->Draw("P");


	gCross_lhcb_pr = new TGraphAsymmErrors(nBin_lhcb, lhcb_px, lhcb_py_pr, lhcb_ex, lhcb_ex, lhcb_ey_pr, lhcb_ey_pr);	
	SetGraphStyle(gCross_lhcb_pr,9,10);

	TF1 *expoFunc_pr = new TF1("expoFunc_pr","[0]*exp(-[1]*x)", 4, 14);
	expoFunc_pr->SetParameter(0,10000);
	expoFunc_pr->SetParameter(1,1.5);
	expoFunc_pr->SetLineColor(6);
	//gCross_lhcb_pr->Fit("expoFunc_pr","R LL M");
	gCross_lhcb_pr->Fit("expoFunc_pr","R LL M N");
	double lhcb_px_prShift[nLHCbBin];
	getMeanPtBins( lhcb_px_prShift, expoFunc_pr);
	TGraphAsymmErrors* gCross_lhcb_pr_shifted = new TGraphAsymmErrors(nBin_lhcb, lhcb_px_prShift, lhcb_py_pr, lhcb_ex, lhcb_ex, lhcb_ey_pr, lhcb_ey_pr);
	SetGraphStyle(gCross_lhcb_pr_shifted,9,10);

	TGraphAsymmErrors* gCross_lhcb_pr_sys_shifted = new TGraphAsymmErrors(nBin_lhcb, lhcb_px_prShift, lhcb_py_pr, lhcb_exsys, lhcb_exsys, lhcb_eysys_pr, lhcb_eysys_pr);
//        gCross_lhcb_pr_sys_shifted->SetFillColor(kAzure-9);
        gCross_lhcb_pr_sys_shifted->SetFillColor(kGray);
        gCross_lhcb_pr_sys_shifted->SetFillStyle(3001);
	
	if ( shifted)  {
	  gCross_lhcb_pr_sys_shifted->Draw("2");
	  gCross_lhcb_pr_shifted->Draw("P");
	}
	else {  
	  gCross_lhcb_pr_sys->Draw("2");
	  gCross_lhcb_pr->Draw("P");
	}

	gCross_pr_0->Draw("P");







	if (!isLog) {
		if (isPtCut) dashedLine(3.0,0.0,20.0,0.0,1,1);
		else dashedLine(0.0,0.0,20.0,0.0,1,1);
	}
		
	//legUR -> SetHeader("Prompt J/#psi");
	//legUR -> AddEntry(gCross_pr_0,"CMS Preliminary :1.5 < y_{CM} < 1.93","lp");
	legUR -> AddEntry(gCross_pr_0,"CMS : 1.5 < y_{CM} < 1.93","lp");
	legUR -> AddEntry(gCross_lhcb_pr,"LHCb : 1.5 < y_{CM} < 2","lp");
	legUR -> Draw();
	
	globtex->SetTextSize(0.045);
	globtex->SetTextFont(62);
	globtex->DrawLatex(0.88, 0.88, "Prompt J/#psi");
	
	latex->SetTextSize(0.04);
	if (isLog) {
		latex->DrawLatex(0.19, 0.31, "Preliminary");
		latex->DrawLatex(0.19, 0.25, Form("%s",beamstring.c_str()));
	}
	else {
		latex->DrawLatex(0.89, 0.31, "Preliminary");
		latex->DrawLatex(0.89, 0.25, Form("%s",beamstring.c_str()));
	}	
	

	
//	if (isLog) {
//		latex->DrawLatex(0.20, 0.25, beamstring.c_str());
//	}
//	else {
//		latex->DrawLatex(0.62, 0.25, beamstring.c_str());
//	}
	
	c_pr->Update();
	c_pr->SaveAs(Form("compOtherExp/comp_crossSection_pt_LHCb_pr_isLog%d_isPtCut_%d_shifted_%d_each_xErr.pdf",(int)isLog,(int)isPtCut,(int)shifted));
	c_pr->SaveAs(Form("compOtherExp/comp_crossSection_pt_LHCb_pr_isLog%d_isPtCut_%d_shifted_%d_each_xErr.png",(int)isLog,(int)isPtCut,(int)shifted));
	legUR->Clear();
	//c_pr->Clear();


	////// 02 ////////
	// non-prompt
	TCanvas *c_np = new TCanvas("c_np","", 200, 10, 600, 600);
	c_np->cd();
	if (isLog) gPad->SetLogy(1);
	else gPad->SetLogy(0);
	gCross_np_sys_0->SetTitle("");
	gCross_np_sys_0->GetXaxis()->SetTitle("p_{T} [GeV/c]");
	gCross_np_sys_0->GetXaxis()->CenterTitle();
	if(isPtCut) gCross_np_sys_0->GetXaxis()->SetLimits(3.0,20.0);
	else gCross_np_sys_0->GetXaxis()->SetLimits(0.0,20.0);
	gCross_np_sys_0->GetYaxis()->SetTitle("B x d^{2}#sigma/dp_{T}dy [ #mub/(GeV/c)]");
	if (isLog){
		gCross_np_sys_0->SetMinimum(0.001);
		if (isPtCut) gCross_np_sys_0->SetMaximum(500.);
		//else gCross_np_sys_0->SetMaximum(100.);
		else gCross_np_sys_0->SetMaximum(10.);
	}
	else {
		gCross_np_sys_0->SetMinimum(-0.1);
		if (isPtCut) gCross_np_sys_0->SetMaximum(25.);
		else gCross_np_sys_0->SetMaximum(2.5);
	}
	gCross_np_sys_0->SetFillColor(kTeal-9);
	gCross_np_sys_0->Draw("A2");

	gCross_lhcb_np_sys = new TGraphAsymmErrors(nBin_lhcb, lhcb_px, lhcb_py_np, lhcb_exsys, lhcb_exsys, lhcb_eysys_np, lhcb_eysys_np);	
	gCross_lhcb_np_sys->SetFillColor(kGray);
	gCross_lhcb_np_sys->SetFillStyle(3001);

	SetGraphStyle(gCross_np_0,0,5);
	gCross_np_0->SetMarkerSize(2.1);
	gCross_np_0->Draw("P");

	gCross_lhcb_np = new TGraphAsymmErrors(nBin_lhcb, lhcb_px, lhcb_py_np, lhcb_ex, lhcb_ex, lhcb_ey_np, lhcb_ey_np);	
	SetGraphStyle(gCross_lhcb_np,9,10);
	
	TF1 *expoFunc_np = new TF1("expoFunc_np","[0]*exp(-[1]*x)", 4, 14);
        expoFunc_np->SetParameter(0,10000);
        expoFunc_np->SetParameter(1,1.5);
        expoFunc_np->SetLineColor(6);
        //gCross_lhcb_np->Fit("expoFunc_np","R LL M");
        gCross_lhcb_np->Fit("expoFunc_np","R LL M N");
	double lhcb_px_npShift[nLHCbBin];
        getMeanPtBins( lhcb_px_npShift, expoFunc_np);
        TGraphAsymmErrors* gCross_lhcb_np_shifted = new TGraphAsymmErrors(nBin_lhcb, lhcb_px_npShift, lhcb_py_np, lhcb_ex, lhcb_ex, lhcb_ey_np, lhcb_ey_np);
        SetGraphStyle(gCross_lhcb_np_shifted,9,10);

        TGraphAsymmErrors* gCross_lhcb_np_sys_shifted = new TGraphAsymmErrors(nBin_lhcb, lhcb_px_npShift, lhcb_py_np, lhcb_exsys, lhcb_exsys, lhcb_eysys_np, lhcb_eysys_np);
        gCross_lhcb_np_sys_shifted->SetFillColor(kGray);
        gCross_lhcb_np_sys_shifted->SetFillStyle(3001);

        if ( shifted)  {
          gCross_lhcb_np_sys_shifted->Draw("2");
          gCross_lhcb_np_shifted->Draw("P");
        }
        else {
          gCross_lhcb_np_sys->Draw("2");
          gCross_lhcb_np->Draw("P");
	}
	if (!isLog) {
		if (isPtCut) dashedLine(3.0,0.0,20.0,0.0,1,1);
		else dashedLine(0.0,0.0,20.0,0.0,1,1);
	}
	
	gCross_np_0->Draw("P");

	//legUR -> SetHeader("Non-prompt J/#psi");
	legUR -> AddEntry(gCross_np_0,"CMS :1.5 < y_{CM} < 1.93","lp");
	legUR -> AddEntry(gCross_lhcb_np,"LHCb : 1.5 < y_{CM} < 2","lp");
	legUR -> Draw();
	
	globtex->SetTextSize(0.045);
	globtex->SetTextFont(62);
	globtex->DrawLatex(0.88, 0.88, "Non-prompt J/#psi");
	
	latex->SetTextSize(0.04);
	if (isLog) {
		latex->DrawLatex(0.19, 0.31, "Preliminary");
		latex->DrawLatex(0.19, 0.25, Form("%s",beamstring.c_str()));
	}
	else {
		latex->DrawLatex(0.89, 0.31, "Preliminary");
		latex->DrawLatex(0.89, 0.25, Form("%s",beamstring.c_str()));
	}	
	
	c_np->Update();
	c_np->SaveAs(Form("compOtherExp/comp_crossSection_pt_LHCb_np_isLog%d_isPtCut_%d_shifted_%d_each_xErr.pdf",(int)isLog,(int)isPtCut,(int)shifted));
	c_np->SaveAs(Form("compOtherExp/comp_crossSection_pt_LHCb_np_isLog%d_isPtCut_%d_shifted_%d_each_xErr.png",(int)isLog,(int)isPtCut,(int)shifted));
	//legUR->Clear();
	//c_np->Clear();





	return 0;
}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
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 ;
}  
Example #10
0
int stack_upgrade_42X() {

	//gROOT->ProcessLine(".L ./tdrstyle.C");
	//setTDRStyle();
  gStyle->SetPadColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetPadBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetOptStat(0000000);
  gStyle->SetOptFit(0111);
  gStyle->SetOptTitle(0);
  gStyle->SetTitleStyle(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetPalette(1);


  const int nFiles = 7;

  //Int_t r = 4;
  //DoubleEle + WZ
  //TString fileNames[nFiles] = {"DoubleEle","TT_42X_TruePU","WZ_42X_TruePU","ZZ_42X_TruePU","DY_42X_TruePU","Htt120_42X_TruePU","Hww120_42X_TruePU"};
  //DoubleEle + WZjets 
  TString fileNames[nFiles] = {"DoubleMu","ZZ_42X_TruePU","WZJets_42X_TruePU","TT_42X_TruePU","DY_42X_TruePU","Htt120_42X_TruePU","Hww120_42X_TruePU"};
  //DoubleMu + WZ 
  //TString fileNames[nFiles] = {"DoubleMu","TT_42X_TruePU","WZ_42X_TruePU","ZZ_42X_TruePU","DY_42X_TruePU","Htt120_42X_TruePU","Hww120_42X_TruePU"};
  //DoubleMu + WZjets 
  //TString fileNames[nFiles] = {"DoubleMu","TT_42X_TruePU","WZjets_42X_TruePU","ZZ_42X_TruePU","DY_42X_TruePU","Htt120_42X_TruePU","Hww120_42X_TruePU"};

  //DoubleEle + WZ
  //Double_t weights[nFiles] = {1.00, 0.01054, 0.0392, 0.00047967, 0.44927,0.0009171,0.000136};
  //DoubleEle + WZjets 
  //Double_t weights[nFiles] = {1.00, 0.0004796752, 0.00351, 0.010544, 0.449278,0.00091718,0.000136};
 //DoubleMu + WZ 
  //Double_t weights[nFiles] = {1.00, 0.01054, 0.0392, 0.00047967, 0.44927,0.0009171,0.000136};
  //DoubleMu + WZjets 
  //Double_t weights[nFiles] = {1.00, 0.01054, 0.003525, 0.00047967, 0.44927,0.0009171,0.000136};
  
  TFile * f[nFiles];  	
  std::stringstream indexes;  

  for(int iFile = 0; iFile < nFiles; iFile++)

  {
	  indexes.str("");
	  indexes << fileNames[iFile];
	  std::string input_file="NewCuts/forPlot/"+indexes.str()+".root";

	  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 int nHist1 = 5;
  //const int nHist1 = 44;


TString histNames1[nHist1] = {"h_Zmass_mumu","h_H_mass_type_1","h_H_mass_type_2","h_H_mass_type_3","h_H_mass_type_4"};
  TString histTitles[nHist1] = {"M_{2#mu}[GeV]","M_{#mu#tau}[GeV]","M_{#mue}[GeV]","M_{e#tau}[GeV]","M_{#tau#tau}[GeV]"};
  TString PaveText[nHist1]	= {"Z#mu#mu","MMMT","MMME","MMET","MMTT"};
  //~ 
  //~ TString histNames1[nHist1] = {"h_Zmass","h_Zpt","h_Z_eta","h_PF_MET_selected","h_Tmass","h_nbjets","h_nbjetsVetoed","h_nbjets_afterVeto","h_cut_flow_weight"};//,"h_H_mass_type_5","h_H_mass_type_6","h_H_mass_type_7","h_H_mass_type_8"};
  //~ TString histTitles[nHist1] = {"M_{Z}[GeV]","Z p_{T} [GeV]","Z #eta", "PF MET [GeV]", "M_{T} [GeV]", "# b-jets", "# of b-jets causing veto", "# b-jets after the veto", "Cut flow" };//,"M_{#mu#tau}[GeV]","M_{#mue}[GeV]","M_{e#tau}[GeV]","M_{#tau#tau}[GeV]"};
  //~ TString PaveText[nHist1]	= {"Z all","Z all","Z all","All","All","All","All","All", "All" };//,"EEMT","EEME","EEET","EETT"};
  
  //TString histNames1[nHist1] = {"h_mu1Z_pt", "h_mu2Z_pt", "h_Z_lep1_eta", "h_Z_lep2_eta", "h_Z_lep1_phi", "h_Z_lep2_phi", "h_Zmass_mumu", "h_Zmass_ee","h_Zpt_mumu", "h_Zpt_ee","h_Zmass", "h_Zpt","h_H_mass", "h_H_pt","h_H_eta", "h_H_phi", "h_H_mass_type_1", "h_H_mass_type_2", "h_H_mass_type_3", "h_H_mass_type_4", "h_H_mass_type_5", "h_H_mass_type_6", "h_H_mass_type_7", "h_H_mass_type_8", "h_Tmass","h_H_lep1_eta","h_H_lep2_eta","h_H_lep1_phi","h_H_lep2_phi","h_nbjets","h_nbjets_afterVeto","h_nbjetsVetoed","h_nPU_Info","h_nPU_InfoTrue","h_nPU_Bunch0","h_nPU_Info_W","h_nPU_InfoTrue_W","h_nPU_Bunch0_W","h_Nvertex_NoCut","h_Nvertex_NoCut_W","h_Nvertex_AfterZ","h_Nvertex_AfterZ_W","h_Nvertex_AfterZH","h_Nvertex_AfterZH_W"};

  TH1F * 		h_1d[nHist1][nFiles];
  TH1F *                signal[nHist1];
  
  Double_t weights[nFiles];
  Double_t xsection[nFiles]={1.0, 0.106, 0.868, 17.32, 3048, 0.0184915, 0.0039508088};
  
  
  
  const double total_lumi = 4934.0; //1294.0 +2741.0; // pb-1
  
  for(int iFile = 0; iFile < nFiles; iFile++)
	{
		TH1D * h_pu = (TH1D*)f[iFile]->Get("h_nPU_raw");		
		std::cout << h_pu->Integral() << std::endl;
		double lumi = h_pu->Integral()/xsection[iFile];
		if(iFile > 0) weights[iFile]=total_lumi/lumi;
		else weights[iFile] = 1.0;
		std::cout << weights[iFile] << std::endl;
	}

  for(int iFile = 0; iFile < nFiles; iFile++)
  {
	  for(int iHist = 0; iHist < nHist1; iHist++)
	  {
		  h_1d[iHist][iFile] = (TH1F*)f[iFile]->Get(histNames1[iHist]);
		  h_1d[iHist][iFile]->Scale(weights[iFile]); 
		 if(iHist > 0) h_1d[iHist][iFile]->Rebin(10);
	  }
  }
  
    int ZZ_Color = TColor::GetColor("#99ff99");
    int WZ_Color = TColor::GetColor("#660099");
    int TTbar_Color = TColor::GetColor("#cc66cc");
    int Zjet_Color = TColor::GetColor("#32c3ff");

  TCanvas *c1 = new TCanvas("c1","",5,30,650,600);
  //gPad->SetLogy(); 
  c1->SetGrid(0,0);
  c1->SetFillStyle(4000);
  c1->SetFillColor(10);
  c1->SetTicky();
  c1->SetObjectStat(0);

  for(int iHist = 0; iHist < nHist1; iHist++){
	  signal[iHist] = (TH1F*)h_1d[iHist][5]->Clone();}

  for(int iHist = 0; iHist < nHist1; iHist++)

  {
	  THStack *hs = new THStack("hs","Stacked MC histograms");


	  for(int iFile=1; iFile < nFiles-1; iFile++)

	  {

		  h_1d[iHist][iFile]->SetLineWidth(0);
		  h_1d[iHist][iFile]->SetFillStyle(3244);

		  if(iFile == 1){ h_1d[iHist][iFile]->SetFillColor(ZZ_Color);  }
		  else if(iFile == 2){  h_1d[iHist][iFile]->SetFillColor(WZ_Color); }
		  else if(iFile == 3){  h_1d[iHist][iFile]->SetFillColor(TTbar_Color); }
		  else if(iFile == 4){  h_1d[iHist][iFile]->SetFillColor(Zjet_Color); }
		  else if(iFile == 5){
			  signal[iHist]->Add(h_1d[iHist][iFile+1]);
                          signal[iHist]->SetLineColor(kRed); 
                          signal[iHist]->SetLineWidth(2.0); 
                          
                   }

		  if(iFile < 5) hs->Add(h_1d[iHist][iFile],"hist");		

	  }

		  //hs->Add(signal[iHist],"hist");		
	  
	  h_1d[iHist][0]->SetMarkerStyle(21);
	  h_1d[iHist][0]->SetMarkerSize(0.7);

 TLegend* leg = new TLegend(0.65,0.70,0.88,0.88,NULL,"brNDC");
 leg->SetFillColor(0);
 leg->SetTextSize(0.035);
 leg->SetBorderSize(0);
			
	  leg->AddEntry(h_1d[iHist][0],"data 2011","p");
	  leg->AddEntry(h_1d[iHist][1],"ZZ","f");
	  leg->AddEntry(h_1d[iHist][2],"WZ","f");
	  leg->AddEntry(h_1d[iHist][3],"t#bar{t}","f");
	  leg->AddEntry(h_1d[iHist][4],"Zjet","f");
	  leg->AddEntry(signal[iHist],"ZH(120)#times 5","f");

TString lumist="4.9 fb^{-1}";
  TPaveText *ll = new TPaveText(0.25, 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 = PaveText[iHist];
  ll->AddText(0.01,0.5,text);
  text = "#sqrt{s} = 7 TeV  L = ";
  text = text + lumist;
  //  ll->SetTextAlign(32); // align right
  ll->AddText(0.5, 0.5, text);
   
	  /*double max_dy = h_1d[iHist][4]->GetMaximum();
	  double max_data = h_1d[iHist][0]->GetMaximum();
	  double max = 0;

	  if (max_dy > max_data){
		  max = max_dy;}
	  else {
		  max = max_data;}
	  if (max != 0) hs->SetMaximum(max);

          cout << "max data: " << max_data << endl;
          cout << "max dy: " << max_dy << endl;
	  */

	  h_1d[iHist][0]->Draw("PE01");
	  double max = h_1d[iHist][0]->GetMaximum();
	  h_1d[iHist][0]->GetYaxis()->SetRangeUser(1e-2,200*max);
	// if(iHist > 0 && iHist < 4)  h_1d[iHist][0]->GetXaxis()->SetRangeUser(0,150);
	 
	  h_1d[iHist][0]->GetXaxis()->SetTitle(histTitles[iHist]);
	  hs->Draw("same");
	  signal[iHist]->Scale(10.);
	  signal[iHist]->Draw("histsame");
      h_1d[iHist][0]->Draw("samePE01");
      
	  
	  leg->Draw("same");
	  ll->Draw("same");
	  gPad->RedrawAxis();

	  c1->SetLogy();	
	  c1->Print("NewCuts/Mu_"+histNames1[iHist]+"_all.png");
	  c1->Print("NewCuts/Mu_"+histNames1[iHist]+"_all.eps");
	  c1->SetLogy(0);
	  h_1d[iHist][0]->GetYaxis()->SetRangeUser(0,1.5*max);
	
	  c1->Print("NewCuts/Mu_"+histNames1[iHist]+"_all_normal.png");
	  c1->Print("NewCuts/Mu_"+histNames1[iHist]+"_all_normal.eps");
	  	
	  

	  leg->Clear();
	  hs->Clear();    

  }

  return 0;

}
Example #11
0
void tempSumm()
{

  const Int_t nx = 5;
  char *labels[nx] = {"9/30","10/15","10/31","11/19","12/19"};

  TH1F *probe1summ = new TH1F("probe1summ","",nx,0,nx);
  TH1F *probe2summ = new TH1F("probe2summ","",nx,0,nx);
  TH1F *probe3summ = new TH1F("probe3summ","",nx,0,nx);
  TH1F *probe4summ = new TH1F("probe4summ","",nx,0,nx);

  probe1summ->Fill(labels[0],0.910);//keep track of these from SC elog:36
  probe1summ->SetBinError(1,0.057);
  probe1summ->Fill(labels[1],1.088);
  probe1summ->SetBinError(2,0.018);
  probe1summ->Fill(labels[2],0.64);
  probe1summ->SetBinError(3,0.12);
  probe1summ->Fill(labels[3],0.72);
  probe1summ->SetBinError(4,0.057);
  probe1summ->Fill(labels[4],0.81);
  probe1summ->SetBinError(5,0.043);

  probe2summ->Fill(labels[0],1.280);
  probe2summ->SetBinError(1,0.026);
  probe2summ->Fill(labels[1],1.269);
  probe2summ->SetBinError(2,0.021);
  probe2summ->Fill(labels[2],1.05);
  probe2summ->SetBinError(3,0.08);
  probe2summ->Fill(labels[3],1.67);
  probe2summ->SetBinError(4,0.050);
  probe2summ->Fill(labels[4],1.42);
  probe2summ->SetBinError(5,0.028);

  probe3summ->Fill(labels[0],0.833);
  probe3summ->SetBinError(1,0.026);
  probe3summ->Fill(labels[1],1.423);
  probe3summ->SetBinError(2,0.035);
  probe3summ->Fill(labels[2],1.24);
  probe3summ->SetBinError(3,0.118);
  probe3summ->Fill(labels[3],1.60);
  probe3summ->SetBinError(4,0.055);
  probe3summ->Fill(labels[4],1.34);
  probe3summ->SetBinError(5,0.038);

  probe4summ->Fill(labels[0],-999);
  probe4summ->SetBinError(1,-999);
  probe4summ->Fill(labels[1],0.340);
  probe4summ->SetBinError(2,0.071);
  probe4summ->Fill(labels[2],0.38);
  probe4summ->SetBinError(3,0.082);
  probe4summ->Fill(labels[3],0.59);
  probe4summ->SetBinError(4,0.054);
  probe4summ->Fill(labels[4],0.48);
  probe4summ->SetBinError(5,0.119);

  probe1summ->GetXaxis()->SetTitle("run date");
  probe1summ->GetXaxis()->CenterTitle(1);
  probe1summ->GetYaxis()->SetTitle("temp. (C)");
  probe1summ->GetYaxis()->CenterTitle(1);

  probe1summ->SetMarkerColor(kBlue);
  probe1summ->SetLineColor(kBlue);
  probe2summ->SetMarkerColor(kRed);
  probe2summ->SetLineColor(kRed);
  probe3summ->SetMarkerColor(kGreen);
  probe3summ->SetLineColor(kGreen);
  probe4summ->SetMarkerColor(kCyan);
  probe4summ->SetLineColor(kCyan);

  probe1summ->SetMarkerStyle(20);
  probe2summ->SetMarkerStyle(20);
  probe3summ->SetMarkerStyle(20);
  probe4summ->SetMarkerStyle(20);

  probe1summ->SetMarkerSize(0.5);
  probe2summ->SetMarkerSize(0.5);
  probe3summ->SetMarkerSize(0.5);
  probe4summ->SetMarkerSize(0.5);

  probe1summ->SetMinimum(0);
  probe1summ->SetMaximum(2);

  probe1summ->GetXaxis()->SetLabelSize(0.05);

  TLegend *leg = new TLegend(0.155,0.691,0.344,0.860);
  leg->SetTextSize(0.035);
  leg->SetTextColor(1);
  leg->SetFillColor(0);
  leg->Clear();
  leg->AddEntry(probe1summ, "probe 1", "pl");
  leg->AddEntry(probe2summ, "probe 2", "pl");
  leg->AddEntry(probe3summ, "probe 3", "pl");
  leg->AddEntry(probe4summ, "probe 4", "pl");
  leg->SetFillColor(0);
  leg->SetLineColor(0);
  leg->SetTextFont(22);

  gStyle->SetOptStat(0000);

  TCanvas *tempSumm = new TCanvas();
  probe1summ->Draw("e1p");
  probe2summ->Draw("e1p same");
  probe3summ->Draw("e1p same");
  probe4summ->Draw("e1p same");
  leg->Draw();
  tempSumm->Print("tempSumm.eps");  

}
Example #12
0
void vs_PlotQCDcomp() {

  Bool_t saveC  = false;
  Bool_t diJets = true;
  Bool_t isMC   = false;

  TString vsSave;
  vsSave = "_T07w";

  TString jSave;
  if(diJets) jSave = "2j";
  else       jSave = "3j";

  TString sample;
  if(diJets) sample = "select_1ph_2jets";
  else       sample = "select_1ph_3jets";

  TString FOtag;
  if(isMC) FOtag = "_FO_CorrMC";
  //  else     FOtag = "_FO_Corr";
  else     FOtag = "_FO";

  TString sysu = "SYSTUP_";
  TString sysd = "SYSTDOWN_";

  TString outDir;
  outDir = "Plots_PhotonSusyAnalysis/QCDweights/";


  //  string inputFile1 = "/data/user/vsola/CMSSW_Releases/CMSSW_5_3_9/src/Plots_PhotonSusyAnalysis/Merged_QCD_PhotonJet_T07w_PAT/mergedHistos.root";
  //  string inputFile1 = "/data/user/vsola/CMSSW_Releases/CMSSW_5_3_9/src/Plots_PhotonSusyAnalysis/Merged_Data_V05w_PAT/mergedHistos.root";
  string inputFile1 = "/data/user/vsola/CMSSW_Releases/CMSSW_5_3_9/src/Plots_PhotonSusyAnalysis/PhotonHadReReco_22Jan2013_V05_PAT/mergedHistos.root";
  
  
  setMyTDRStyle();
  gROOT->SetStyle("mytdrStyle");
  
  //  gStyle->SetHistMinimumZero();
  //  gStyle->SetPaintTextFormat("4.2f");

  gStyle->SetHistLineWidth(2);
  gStyle->UseCurrentStyle();

  //  gStyle->SetPadTopMargin(1.0);
  //  gStyle->SetPadLeftMargin(3.2);
  //  gStyle->SetPadRightMargin(4.5);
  //  gStyle->SetPadBottomMargin(3.2);

  gROOT->ForceStyle(1);


  static const Int_t nHt  =  7;
  static const Int_t nPt  = 13;
  static const Int_t nMet = 16;
  static const Int_t nJet = 15;

  Double_t binPt[nPt+1]   = {0.,75.,90.,120.,160.,210.,260.,320.,400.,500.,650.,800.,1000.,1500.};
  Double_t binHt[nHt+1]   = {0.,400.,450.,550.,700.,900.,1200.,1500.};
  Double_t binMet[nMet+1] = {0.,10.,20.,30.,40.,50.,60.,70.,80.,90.,100.,120.,160.,200.,270.,350.,500.};
  Double_t binJet[nJet+1] = {0.,1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.,12.,13.,14.,15};


  TLatex *as = new TLatex();
  as->SetNDC(true);
  as->SetTextColor(12);
  as->SetTextFont(43);
  as->SetTextSize(19);

  TLegend *legend = new TLegend(0.60, 0.70, 0.75, 0.85, "");
  legend->SetFillColor(10);
  legend->SetFillStyle(1001);
  legend->SetTextSize(0.04);
  legend->SetBorderSize(0);
  legend->SetShadowColor(0);

  std::string outLumi  = "CMS Work in Progress - QCD MC #sqrt{s} = 8 TeV - #geq 1 #gamma, #geq 2 j";

  TFile* f1 = TFile::Open( inputFile1.c_str() );

  //photon Pt
  TCanvas * cPt = new TCanvas("cPt","cPt");

  TH1F* hpt   = (TH1F*) f1->Get( sample+"/PreselCut_photonPt" );
  TH1F* hptFO = (TH1F*) f1->Get( sample+FOtag+"/PreselCut_photonPt" );

  TH1F *hptR = (TH1F*) hpt->Rebin(nPt,hpt->GetTitle(),binPt);
  if (hptR->GetSumw2N() == 0)
    hptR->Sumw2();

  TH1F *hptFOR = (TH1F*) hptFO->Rebin(nPt,hptFO->GetTitle(),binPt);
  if (hptFOR->GetSumw2N() == 0)
    hptFOR->Sumw2();

  TH1F* hptSU = (TH1F*) f1->Get( sample+FOtag+"/PreselCut_"+sysu+"photonPt" );
  TH1F* hptSD = (TH1F*) f1->Get( sample+FOtag+"/PreselCut_"+sysd+"photonPt" );

  TH1F *hptSUR = (TH1F*) hptSU->Rebin(nPt,hptSU->GetTitle(),binPt);
  if (hptSUR->GetSumw2N() == 0)
    hptSUR->Sumw2();

  TH1F *hptSDR = (TH1F*) hptSD->Rebin(nPt,hptSD->GetTitle(),binPt);
  if (hptSDR->GetSumw2N() == 0)
    hptSDR->Sumw2();

  if ( hptFOR != 0 ) {
    for (int b = 0; b < hptFOR->GetNbinsX(); b++) {

      Double_t mainHistoContent   = hptFOR->GetBinContent(b);
      Double_t systUpHistoContent = hptSUR->GetBinContent(b);
      Double_t systDnHistoContent = hptSDR->GetBinContent(b);
      Double_t systDiffUp = fabs( (double) systUpHistoContent - mainHistoContent );
      Double_t systDiffDn = fabs( (double) mainHistoContent - systDnHistoContent );

      // use average error for histogram
      Double_t systDiff = ( systDiffUp + systDiffDn ) / 2.;
      
      Double_t statErr   = hptFOR->GetBinError(b);
      Double_t combError = sqrt( systDiff * systDiff + statErr * statErr );
      hptFOR->SetBinError(b, combError);
    } //for
  }//if
    
  cPt->SetLogy(1);
  gPad->Update();
  cPt->Update();

  //  hptR->Scale(1,"width");
  //  hptR->SetMinimum(0.02);
  //  hptR->SetMaximum(1000); 
  hptR->GetXaxis()->SetTitle("1^{st} photon p_{T} [GeV]");
  hptR->GetYaxis()->SetTitle("Number of Events / GeV");

  if(isMC) hptR->SetMarkerSize(0);
  if(isMC) hptR->Draw("histE");
  else     hptR->Draw("E X0");


  hptFOR->SetMarkerSize(0);
  hptFOR->SetLineColor(2);
  hptFOR->SetFillColor(2);
  hptFOR->SetFillStyle(3004);
  hptFOR->Draw("same hist ][ E2");

  legend->Clear();
  if(isMC) legend->SetHeader("#gamma/QCD (Sim)");
  else     legend->SetHeader("#gamma/QCD (Data)");
  if(isMC) legend->AddEntry(hptR, "#gamma", "l");
  else     legend->AddEntry(hptR, "#gamma", "p");
  legend->AddEntry(hptFOR, "Pred (from #gamma_{jet})", "f");
  legend->Draw();

  as->DrawLatex(0.17, 0.93, outLumi.c_str() );
  cPt->Update();
  cPt->SetBottomMargin(0.2 + 0.8 * cPt->GetBottomMargin() - 0.2 * cPt->GetTopMargin());

  TPad *ratioPt = new TPad("BottomPad", "", 0, 0, 1, 1);
  ratioPt->SetTopMargin(0.8 - 0.8 * ratioPt->GetBottomMargin() + 0.2 * ratioPt->GetTopMargin());
  ratioPt->SetFillStyle(0);
  ratioPt->SetFrameFillColor(10);
  ratioPt->SetFrameBorderMode(0);
  ratioPt->Draw();

  ratioPt->cd();
  ratioPt->SetLogy(0);

  TH1F *hptRat = (TH1F*) divideHistosForRatio(hptR,hptFOR);
  hptRat->SetMinimum(0.);
  hptRat->SetMaximum(10.);
  hptRat->GetXaxis()->SetNdivisions(505);
  if(isMC) hptRat->GetYaxis()->SetTitle("Sim/Pred");
  else     hptRat->GetYaxis()->SetTitle("Data/Pred");
  hptRat->GetYaxis()->SetTitleSize(0.04);
  hptRat->GetYaxis()->SetLabelSize(0.03);
  hptRat->GetYaxis()->SetTitleOffset(1.3);
  hptRat->GetYaxis()->SetNdivisions(505);
  hptRat->SetMarkerStyle(20);
  hptRat->SetMarkerSize(1);
  hptRat->SetMarkerColor(1);
  hptRat->SetLineColor(1);
  hptRat->Draw("E X0");

  TH1F *hptFRat = (TH1F*) getSystErrForRatio(hptFOR);
  hptFRat->SetLineColor(2);
  hptFRat->SetFillColor(2);
  hptFRat->SetFillStyle(3004);
  hptFRat->Draw("same hist ][ E2");


  TLine * line = new TLine( hptRat->GetXaxis()->GetXmin(), 1., hptRat->GetXaxis()->GetXmax(), 1. );
  line->SetLineColor(1);
  line->SetLineWidth(0.5);
  line->SetLineStyle(1);
  line->Draw("same");

  hptR->GetXaxis()->SetLabelSize(0);
  hptR->GetXaxis()->SetTitle("");
  cPt->RedrawAxis();
  gPad->Update();
  cPt->Update();


  return;
}
void makeCorrRoofit2(){
	setNCUStyle(true);
	c1 = new TCanvas("c1","",1360,768);
	
	
	
	TFile* tf1[nMasspoint];
	int masspoint[nMasspoint]={700,800,900,1000,1200,1400,1600,1800,2000,2500,3000};
	for(int i=0;i<nMasspoint;i++){
		tf1[i]=TFile::Open(Form("corr/B%d.root",masspoint[i]));
		//f[i+11]=TFile::Open(Form("R%s.root",masspoint[i].data()));
	}
	double xsec[9]={1.90,0.763,0.33,0.155,7.65e-2,1.58e-2,3.73e-3,2.08e-4,4.91e-5};
		
	double ptBins[14]={200,300,400,500,600,700,800,900,1000,1250,1500,1750,2000,2500};
	double ptBinsCenter[16]={350,450,550,650,750,850,950,1125,1375,1625,1875,2250,2750};
	double ptBinsCenterE[16]={350,450,550,650,750,850,950,1125,1375,1625,1875,2250,2750};
	double ptBinsError[16]={0};
	double ptBinsErrorE[16]={0};
	
	double mean[2][16];
	double sigma[2][16];
	
	RooRealVar xpt("x","x",0,3200) ;
	
	for(int i=0;i<nMasspoint;i++){
		TH1D* th1=(TH1D	*)tf1[i]->Get("ptBarrel");
		ptBinsCenter[i]=th1->GetMean();
		ptBinsError[i]=20;
		th1->SetTitle(Form("%d",masspoint[i]));
		th1->Draw("");
		if(i==0)c1->Print("plots/ptBarrel.pdf(");
		else if(i==nMasspoint-1)c1->Print("plots/ptBarrel.pdf)");
		else  c1->Print("plots/ptBarrel.pdf");
		delete th1;
	}

	for(int i=0;i<nMasspoint;i++){
		TH1D* th1=(TH1D	*)tf1[i]->Get("ptEndcap");
		ptBinsCenterE[i]=th1->GetMean();
		ptBinsErrorE[i]=20;
		th1->SetTitle(Form("%d",masspoint[i]));
		th1->Draw("");
		if(i==0)c1->Print("plots/ptEndcap.pdf(");
		else if(i==nMasspoint-1)c1->Print("plots/ptEndcap.pdf)");
		else  c1->Print("plots/ptEndcap.pdf");
		delete th1;
	}
	
	
	RooRealVar x("x","x",40,150) ;
	
	for(int i=0;i<nMasspoint;i++){
		TH1D* th1=(TH1D	*)tf1[i]->Get("recoBarrelMass");
		th1->SetTitle(Form("%d",masspoint[i]));
		th1->SetMaximum(th1->GetMaximum()*1.3);
		cout<<i<<"="<<Form("%d",masspoint[i])<<endl;

		RooDataHist dh("dh","dh",x,Import(*th1)) ;
		/*RooRealVar mean("mean","mean",125,50,150) ;
		RooRealVar sigmaR("sigmaR","sigmaR",4,0.1,9) ;
		RooRealVar sigmaL("sigmaL","sigmaL",10,0.1,18) ;
		RooBifurGauss Bi("bi","bi",x,mean,sigmaL,sigmaR);
		*/
		
		RooRealVar m0("m0","m0",117,50,150);
		RooRealVar sig("sigma","sigma",12,0,100);
		RooRealVar alpha("alpha","alpha",1,0,10);
		RooRealVar n("n","n",1,0,50);
		RooCBShape CB("CB","CB",x,m0,sig,alpha,n);
		RooPlot* frame=x.frame(Title(Form("%d",masspoint[i])));
		dh.plotOn(frame);
		CB.fitTo(dh) ; 
		CB.plotOn(frame,LineColor(kRed)) ;
		CB.paramOn(frame,Layout(0.55)) ;
		mean[0][i]=125/m0.getValV();
		sigma[0][i]=m0.getError()*(125/m0.getValV())/m0.getValV();
		//mean[4][i]=125/th1->GetMean();
		//sigma[4][i]=th1->GetMeanError()/th1->GetMean();
		//th1->Draw();
		frame->SetMaximum(th1->GetMaximum()*1.3);
		frame->Draw() ;
		
		if(i==0)c1->Print("plots/recoBarrel.pdf(");
		else if(i==nMasspoint-1)c1->Print("plots/recoBarrel.pdf)");
		else  c1->Print("plots/recoBarrel.pdf");
		delete th1;
	}
	
	for(int i=0;i<nMasspoint;i++){
		TH1D* th1=(TH1D	*)tf1[i]->Get("recoEndcapMass");
		th1->SetTitle(Form("%d",masspoint[i]));
		th1->SetMaximum(th1->GetMaximum()*1.3);
		
		RooDataHist dh("dh","dh",x,Import(*th1)) ;
		/*RooRealVar mean("mean","mean",125,50,150) ;
		RooRealVar sigmaR("sigmaR","sigmaR",4,0.1,9) ;
		RooRealVar sigmaL("sigmaL","sigmaL",10,0.1,18) ;
		RooBifurGauss Bi("bi","bi",x,mean,sigmaL,sigmaR);
		*/
		
		RooRealVar m0("m0","m0",117,50,150);
		RooRealVar sig("sigma","sigma",12,0,100);
		RooRealVar alpha("alpha","alpha",1,0,10);
		RooRealVar n("n","n",1,0,50);
		RooCBShape CB("CB","CB",x,m0,sig,alpha,n);
		RooPlot* frame=x.frame(Title(Form("%d",masspoint[i])));
		dh.plotOn(frame);
		CB.fitTo(dh) ; 
		CB.plotOn(frame,LineColor(kRed)) ;
		CB.paramOn(frame,Layout(0.55)) ;
		mean[1][i]=125/m0.getValV();
		sigma[1][i]=m0.getError()*(125/m0.getValV())/m0.getValV();
		//mean[4][i]=125/th1->GetMean();
		//sigma[4][i]=th1->GetMeanError()/th1->GetMean();
		//th1->Draw();
		frame->SetMaximum(th1->GetMaximum()*1.3);
		frame->Draw() ;
		//cout<<i<<"="<<mean[5][i]<<endl;
		if(i==0)c1->Print("plots/recoEndcap.pdf(");
		else if(i==nMasspoint-1)c1->Print("plots/recoEndcap.pdf)");
		else  c1->Print("plots/recoEndcap.pdf");
		delete th1;
	}
	
	
	
	
	TGraphErrors* tg1[6];
	
	tg1[4]=new TGraphErrors(nMasspoint,ptBinsCenter,mean[0],ptBinsError,sigma[0]);
	tg1[5]=new TGraphErrors(nMasspoint,ptBinsCenterE,mean[1],ptBinsErrorE,sigma[1]);
	
	for(int i=0;i<14;i++)cout<<i<<"="<<mean[0][i]<<endl;
	for(int i=0;i<14;i++)cout<<i<<"="<<mean[1][i]<<endl;
	for(int i=0;i<14;i++)cout<<i<<","<<ptBinsCenter[i]<<","<<ptBinsError[i]<<endl;
	
	for(int i=0;i<nMasspoint;i++)cout<<ptBinsCenter[i]<<",";
	cout<<endl;
	for(int i=0;i<nMasspoint;i++)cout<<mean[0][i]<<",";
	cout<<endl;
	for(int i=0;i<nMasspoint;i++)cout<<ptBinsCenterE[i]<<",";
	cout<<endl;
	for(int i=0;i<nMasspoint;i++)cout<<mean[1][i]<<",";
	cout<<endl;
	
	TLegend *leg = new TLegend(0.68, 0.65, 0.94, 0.90);
  
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.04);
	
	
	tg1[4]->GetXaxis()->SetTitle("jet Pt");
	tg1[4]->GetYaxis()->SetTitle("M_{PDG}/M_{Reco}");
	tg1[4]->SetTitle("Gen Correction");
	tg1[4]->SetMinimum(1);
	tg1[4]->SetMaximum(1.4);
	tg1[4]->Draw("APL");
	tg1[4]->SetFillColor(0);
	tg1[5]->SetFillColor(0);
	tg1[5]->SetLineColor(2);
	tg1[5]->SetMarkerColor(2);
	tg1[5]->Draw("PLsame");
	
	tg1[4]->SetTitle("Higgs mass correction");
	/*
	TF1* recoOneBarel = new TF1("genBarel","[0]+[1]*pow(x*[2],-[3])");
	  recoOneBarel->SetParameters(
   				 1.00626,
   				 -1.06161,
   				 0.07999,
   				 1.20454
   				 );
	TF1* recoOneEndcap = new TF1("genEndcap","[0]+[1]*pow(x*[2],-[3])");
	  recoOneEndcap->SetParameters(
   				 1.00626,
   				 -1.06161,
   				 0.07999,
   				 1.20454
   				 );
	*/
	
	
leg->Clear();


 TF1* puppisd_corrGEN      = new TF1("puppisd_corrGEN","[0]+[1]*pow(x*[2],-[3])");
  puppisd_corrGEN->SetParameters(
   				 1.00626,
   				 -1.06161,
   				 0.07999,
   				 1.20454
   				 );
  TF1* puppisd_corrRECO_cen = new TF1("puppisd_corrRECO_cen","([0]+[1]*x+[2]*pow(x,2)+[3]*pow(x,3)+[4]*pow(x,4)+[5]*pow(x,5))*([6]+[7]*pow(x*[8],-[9]))",200,2000);
  puppisd_corrRECO_cen->SetParameters(
   				      1.05807,
   				      -5.91971e-05,
   				      2.296e-07,
   				      -1.98795e-10,
   				      6.67382e-14,
   				      -7.80604e-18,
					 1.00626,
   				 -1.06161,
   				 0.07999,
   				 1.20454
   				      );

  TF1* puppisd_corrRECO_for = new TF1("puppisd_corrRECO_for","([0]+[1]*x+[2]*pow(x,2)+[3]*pow(x,3)+[4]*pow(x,4)+[5]*pow(x,5))*([6]+[7]*pow(x*[8],-[9]))",200,2000);
  puppisd_corrRECO_for->SetParameters(
   				      1.26638,
   				      -0.000658496,
   				      9.73779e-07,
   				      -5.93843e-10,
   				      1.61619e-13,
   				      -1.6272e-17,
						 1.00626,
   				 -1.06161,
   				 0.07999,
   				 1.20454);
					
					
  
  leg->AddEntry(tg1[4],"H corr barrel");
  leg->AddEntry(tg1[5],"H corr endcap");
  leg->AddEntry(puppisd_corrRECO_cen,"Thea barrel");
  leg->AddEntry(puppisd_corrRECO_for,"Thea endcap");

	leg->Draw("same");
	//genBarel->Draw("same");
//	genEndcap->Draw("same");
	puppisd_corrRECO_cen->SetLineColor(3);
	puppisd_corrRECO_for->SetLineColor(4);
	//tg1[2]->Draw("APL");
	puppisd_corrRECO_cen->Draw("same");
	puppisd_corrRECO_for->Draw("same");
	
	c1->Print("plots/Correction.pdf");
	
}
Example #14
0
/*
void makeEff(TString fin){

  c1 = new TCanvas("c1","",1360,768);
  f= TFile::Open(fin.Data());
  TH1F * th1 = (TH1F*)f->FindObjectAny("HMass");
  int width [nWidth]={30,35,50,45,50};
  int bmin[nBmin]={91,93,95,97,99,101,103,105,107,109};
  double eff[nWidth][nBmin];
  for(int i=0;i<nWidth;i++){
    for(int j=0;j<nBmin;j++){
      eff[i][j]=getEff(th1,bmin[j],bmin[j]+width[i]);
      cout<<"range={"<<bmin[j]<<","<<bmin[j]+width[i]<<"} and efficiency="<<eff[i][j]<<endl;
    }
  }
}
*/
void makeEffPRN0922() {
    c1 = new TCanvas("c1","",1360,768);
    c2 = new TCanvas("c2","",1360,768);
    c1->cd();
    string output="FATjetATLASmassL2L3Corr";
    int twikiSign[13][nWidth][nBmin];
    int twikiSignNum[13][nWidth][nBmin];
    double twikiSignValue[13][nWidth][nBmin];
    double twikiSignNumValue[13][nWidth][nBmin];
    double twikiEffValue[13][nWidth][nBmin];
    double tgraphMass[13]= {600,800,1000,1200,1400,1600,1800,2000,2500,3000,3500,4000,4500};
    double tgraphMassError[13]= {0};
    double tgraphSigEff[13]= {0};
    double tgraphSigEffError[13]= {0};
    double tgraphBkgEff[13]= {0};
    double tgraphBkgEffError[13]= {0};
    double tgraphSgnEff[13]= {0};
    double tgraphSgnEffError[13]= {0};
    double tgraphSigEff145[13]= {0};
    double tgraphSigEffError145[13]= {0};
    double tgraphBkgEff145[13]= {0};
    double tgraphBkgNum145[13]= {0};
    double tgraphBkgNum[13]= {0};
    double tgraphBkgEffError145[13]= {0};
    double tgraphSgnEff145[13]= {0};
    double tgraphSgnEffError145[13]= {0};
    //double twikiEffNumValue[13][nWidth][nBmin];
    //double twikiWidth[13][nWidth][nBmin];
    //double twikiBmin[13][nWidth][nBmin];
    //string  masspoint[4]={"1000","2000","3000","4500"};
    string  masspoint[13]= {"600","800","1000","1200","1400","1600","1800","2000","2500","3000","3500","4000","4500"};
    int width [nWidth]= {20,25,30,35,40,45,50,55,60};
    int bmin[nBmin]= {90,95,100,105,110};
    for (int massP=0; massP<13; massP++) {
        TString fin =Form("root_files/signal-%s.root",masspoint[massP].data()),
                fin2 = Form("root_files/DY-%s.root",masspoint[massP].data());
        // fin2=Form("root_files/DYHTall-%s.root",masspoint[massP].data());
        f= TFile::Open(fin.Data());
        f2= TFile::Open(fin2.Data());
        TH1F * th1 = (TH1F*)f->FindObjectAny("FATjetPRmassL2L3Corr");
        TH1F * th2 = (TH1F*)f2->FindObjectAny("FATjetPRmassL2L3Corr");

        //TString fin3 = Form("root_files/BulkGravitonZlepZqq-%s.root",masspoint[massP].data());
        //f3= TFile::Open(fin3.Data());
        //TH1F * th3 = (TH1F*)f3->FindObjectAny("HMass");
        //cout<<"before"<<th2->GetEntries()<<endl;
        th2->Sumw2();
        //th2->Add(th3);
        //cout<<"after"<<th2->GetEntries()<<endl;
        double eff[nWidth][nBmin],eff2[nWidth][nBmin],err[nWidth][nBmin],err2[nWidth][nBmin],err2Num[nWidth][nBmin];
        double sign[nWidth][nBmin],signCP[nWidth][nBmin],signErr[nWidth][nBmin];
        double signNum[nWidth][nBmin],signNumCP[nWidth][nBmin],signNumErr[nWidth][nBmin];
        for(int i=0; i<nWidth; i++) {
            for(int j=0; j<nBmin; j++) {
                eff[i][j]=getEff(th1,bmin[j],bmin[j]+width[i]);
                eff2[i][j]=getEff(th2,bmin[j],bmin[j]+width[i]);
                //if(eff2[i][j]==0)cout<<massP<<","<<eff2[i][j]<<endl;
                err[i][j]=getErr(th1,bmin[j],bmin[j]+width[i]);
                err2[i][j]=getErr(th2,bmin[j],bmin[j]+width[i]);
                err2Num[i][j]=getErr2(th2,bmin[j],bmin[j]+width[i]);
                //if(massP==0)cout<<"method1="<<err2[i][j]<<",method2="<<err2Num[i][j]/th2->Integral()<<endl;
                sign[i][j]=getSign(eff[i][j],eff2[i][j]);
                signNum[i][j]=getSign(eff[i][j],eff2[i][j]*th2->Integral());
                signCP[i][j]=sign[i][j];
                signNumCP[i][j]=signNum[i][j];
                signErr[i][j]=(1/(1+sqrt(eff2[i][j])))*sqrt(err[i][j]*err[i][j]+ (eff[i][j]*eff[i][j]*err2[i][j]*err2[i][j])/(4*eff2[i][j]*(1+sqrt(eff2[i][j]))*(1+sqrt(eff2[i][j]))));
                //signNumErr[i][j]=(1/(1+sqrt(eff2[i][j]*th2->Integral())))*sqrt(err[i][j]*err[i][j]+ (eff[i][j]*eff[i][j]*err2[i][j]*err2[i][j]*th2->Integral())/(4*eff2[i][j]*(1+sqrt(eff2[i][j]*th2->Integral()))*(1+sqrt(eff2[i][j]*th2->Integral()))));
                signNumErr[i][j]=(1/(1+sqrt(eff2[i][j]*th2->Integral())))*sqrt(err[i][j]*err[i][j]+ (eff[i][j]*eff[i][j]*err2Num[i][j]*err2Num[i][j])/(4*eff2[i][j]*th2->Integral()*(1+sqrt(eff2[i][j]*th2->Integral()))*(1+sqrt(eff2[i][j]*th2->Integral()))));
                if(eff2[i][j]<1e-7) {
                    signErr[i][j]=err[i][j]/(1+sqrt(eff2[i][j]));
                    signNumErr[i][j]=err[i][j]/(1+sqrt(eff2[i][j]*th2->Integral()));
                }
                if(massP==2 &&i==3 && j==3) {
                    tgraphBkgNum145[massP]=eff2[i][j]*th2->Integral();
                    tgraphSigEff145[massP]=eff[i][j];
                    tgraphSigEffError145[massP]=err[i][j];
                    tgraphBkgEff145[massP]=eff2[i][j];
                    tgraphBkgEffError145[massP]=err2[i][j];
                    tgraphSgnEff145[massP]=signNum[i][j];
                    tgraphSgnEffError145[massP]=signNumErr[i][j];
                }
                else if (massP==7 &&i==2 && j==2) {
                    tgraphBkgNum145[massP]=eff2[i][j]*th2->Integral();
                    tgraphSigEff145[massP]=eff[i][j];
                    tgraphSigEffError145[massP]=err[i][j];
                    tgraphBkgEff145[massP]=eff2[i][j];
                    tgraphBkgEffError145[massP]=err2[i][j];
                    tgraphSgnEff145[massP]=signNum[i][j];
                    tgraphSgnEffError145[massP]=signNumErr[i][j];
                }
                else if (massP==9 &&i==2 && j==2) {
                    tgraphBkgNum145[massP]=eff2[i][j]*th2->Integral();
                    tgraphSigEff145[massP]=eff[i][j];
                    tgraphSigEffError145[massP]=err[i][j];
                    tgraphBkgEff145[massP]=eff2[i][j];
                    tgraphBkgEffError145[massP]=err2[i][j];
                    tgraphSgnEff145[massP]=signNum[i][j];
                    tgraphSgnEffError145[massP]=signNumErr[i][j];

                }
                else if (massP==11 &&i==4 && j==1) {

                    tgraphBkgNum145[massP]=eff2[i][j]*th2->Integral();
                    tgraphSigEff145[massP]=eff[i][j];
                    tgraphSigEffError145[massP]=err[i][j];
                    tgraphBkgEff145[massP]=eff2[i][j];
                    tgraphBkgEffError145[massP]=err2[i][j];
                    tgraphSgnEff145[massP]=signNum[i][j];
                    tgraphSgnEffError145[massP]=signNumErr[i][j];
                }

                else {}

                if(i==4 && j==3) {

                    //cout<<width[i]<<","<<bmin[j];



                }

                //cout<<"range={"<<bmin[j]<<","<<bmin[j]+width[i]<<"} and efficiency="<<eff[i][j]<<endl;
                //cout<<"range=["<<bmin[j]<<","<<bmin[j]+width[i]<<"] and significant="<<sign[i][j]<<endl;
                //if(massP==0)cout<<eff[i][j]<<","<<eff2[i][j]<<endl;
            }
        }

        vector<int> signI,signJ;
        for(int ij=0; ij<nWidth*nBmin; ij++) {
            double tempSign=0;
            int tempI=0,tempJ=0;
            for(int i=0; i<nWidth; i++) {
                for(int j=0; j<nBmin; j++) {
                    if(signCP[i][j]>tempSign) {
                        //cout<<"i="<<i<<",j="<<j<<",signcp="<<signCP[i][j]<<",temp="<<tempSign<<endl;
                        tempSign=signCP[i][j];
                        tempI=i;
                        tempJ=j;
                    }
                }
            }

            //cout<<signCP[tempI][tempJ]<<endl;
            signCP[tempI][tempJ]=0;
            if(width[tempI]+bmin[tempJ]>150) {

                continue;
            }
            //if(massP==0)cout<<"tempI"<<tempI<<",tempJ"<<tempJ<<endl;
            signI.push_back(tempI);
            signJ.push_back(tempJ);
        }

        vector<int> signINum,signJNum;
        for(int ij=0; ij<nWidth*nBmin; ij++) {
            double tempSign=0;
            int tempI=0,tempJ=0;
            for(int i=0; i<nWidth; i++) {
                for(int j=0; j<nBmin; j++) {
                    if(signNumCP[i][j]>tempSign) {
                        //cout<<"i="<<i<<",j="<<j<<",signcp="<<signCP[i][j]<<",temp="<<tempSign<<endl;
                        tempSign=signNumCP[i][j];
                        tempI=i;
                        tempJ=j;
                    }
                }
            }

            //cout<<signCP[tempI][tempJ]<<endl;
            signNumCP[tempI][tempJ]=0;
            if(width[tempI]+bmin[tempJ]>150) {
                //cout<<"!";
                continue;
            }
            signINum.push_back(tempI);
            signJNum.push_back(tempJ);
        }

        int numberBin=15;
        int numberBinFull=35;
        TH1F * th1Sign=new TH1F("Sign","Sign",numberBin,0,numberBin);
        TH1F * th1Eff=new TH1F("th1Eff","th1Eff",numberBin,0,numberBin);
        TH1F * th1Eff2=new TH1F("th1Eff2","th1Eff2",numberBin,0,numberBin);
        TH1F * th1SignFull=new TH1F("SignFull","SignFull",numberBinFull,0,numberBinFull);
        TH1F * th1EffFull=new TH1F("th1EffFull","th1EffFull",numberBinFull,0,numberBinFull);
        TH1F * th1Eff2Full=new TH1F("th1Eff2Full","th1Eff2Full",numberBinFull,0,numberBinFull);
        for(int i=0; i<numberBin; i++) {
            th1Sign->SetBinContent(i+1,sign[signI[i]][signJ[i]]);
            th1Sign->SetBinError(i+1,signErr[signI[i]][signJ[i]]);
            th1Eff->SetBinContent(i+1,eff[signI[i]][signJ[i]]);
            th1Eff2->SetBinContent(i+1,eff2[signI[i]][signJ[i]]);
            th1Eff->SetBinError(i+1,err[signI[i]][signJ[i]]);
            th1Eff2->SetBinError(i+1,err2[signI[i]][signJ[i]]);
            th1Sign->GetXaxis()->SetBinLabel(i+1,Form("%d-%d",bmin[signJ[i]],bmin[signJ[i]]+width[signI[i]]));
            //cout<<"range=["<<bmin[signJ[i]]<<","<<bmin[signJ[i]]+width[signI[i]]<<"] and significant="<<sign[signI[i]][signJ[i]]<<endl;
        }

        //cout<<"signI.size="<<signI.size()<<endl;
        for(unsigned int i=0; i<signI.size(); i++) {
            twikiSign[massP][signI[i]][signJ[i]]=i+1;

            th1SignFull->SetBinContent(i+1,sign[signI[i]][signJ[i]]);
            th1SignFull->SetBinError(i+1,signErr[signI[i]][signJ[i]]);
            th1EffFull->SetBinContent(i+1,eff[signI[i]][signJ[i]]);
            th1Eff2Full->SetBinContent(i+1,eff2[signI[i]][signJ[i]]);
            th1EffFull->SetBinError(i+1,err[signI[i]][signJ[i]]);
            th1Eff2Full->SetBinError(i+1,err2[signI[i]][signJ[i]]);
            //th1SignFull->GetXaxis()->SetBinLabel(i+1,Form("%d-%d",bmin[signJ[i]],bmin[signJ[i]]+width[signI[i]]));
            th1SignFull->GetXaxis()->SetBinLabel(i+1,"");
            twikiSignValue[massP][signI[i]][signJ[i]]=sign[signI[i]][signJ[i]];
            twikiEffValue[massP][signI[i]][signJ[i]]=eff[signI[i]][signJ[i]];
            //cout<<"range=["<<bmin[signJ[i]]<<","<<bmin[signJ[i]]+width[signI[i]]<<"] and significant="<<sign[signI[i]][signJ[i]]<<endl;
        }
        gStyle->SetOptStat(0000000000);


        th1Sign->SetTitle(Form("largest 15 Sign.(eff),%sGev",masspoint[massP].data()));
        th1Sign->SetMinimum(0);
        th1Sign->SetMaximum(1);
        th1Sign->SetLineColor(4);
        th1Sign->Draw();
        th1Eff->SetLineColor(2);
        th1Eff2->SetLineColor(3);
        th1Eff->Draw("same");
        th1Eff2->Draw("same");
        TLegend* leg ;
        leg=new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);
        setLeg(leg);
        leg->AddEntry(th1Sign,"significance");
        leg->AddEntry(th1Eff,"signal efficiency");
        leg->AddEntry(th1Eff2,"Bkg. efficiency");
        leg->Draw("same");

        if(massP==0)c1->Print(Form("pdfPR/%s.pdf(",output.data()));
        //else if(massP==12)c1->Print("pdf/signv2.pdf)");
        else c1->Print(Form("pdfPR/%s.pdf",output.data()));

        th1SignFull->SetTitle(Form("all windows(eff),%sGev",masspoint[massP].data()));
        th1SignFull->SetMinimum(0);
        th1SignFull->SetMaximum(1);
        th1SignFull->SetLineColor(4);
        th1SignFull->Draw("Hist");
        th1EffFull->SetLineColor(2);
        th1Eff2Full->SetLineColor(3);
        th1EffFull->Draw("same");
        th1Eff2Full->Draw("same");
        leg->Draw("same");

        c1->Print(Form("pdfPR/%s.pdf",output.data()));

        for(int i=0; i<numberBin; i++) {
            if(i==0) {
                tgraphSigEff[massP]=eff[signINum[i]][signJNum[i]];
                tgraphSigEffError[massP]=err[signINum[i]][signJNum[i]];
                tgraphBkgEff[massP]=eff2[signINum[i]][signJNum[i]];
                tgraphBkgEffError[massP]=err2[signINum[i]][signJNum[i]];
                tgraphSgnEff[massP]=signNum[signINum[i]][signJNum[i]];
                tgraphSgnEffError[massP]=signNumErr[signINum[i]][signJNum[i]];
                tgraphBkgNum[massP]=eff2[signINum[i]][signJNum[i]]*th2->Integral();


            }
            th1Sign->SetBinContent(i+1,signNum[signINum[i]][signJNum[i]]);
            th1Sign->SetBinError(i+1,signNumErr[signINum[i]][signJNum[i]]);
            th1Eff->SetBinContent(i+1,eff[signINum[i]][signJNum[i]]);
            th1Eff2->SetBinContent(i+1,eff2[signINum[i]][signJNum[i]]);
            th1Eff->SetBinError(i+1,err[signINum[i]][signJNum[i]]);
            th1Eff2->SetBinError(i+1,err2[signINum[i]][signJNum[i]]);
            th1Eff->GetXaxis()->SetBinLabel(i+1,Form("%d-%d",bmin[signJNum[i]],bmin[signJNum[i]]+width[signINum[i]]));
            //cout<<"range=["<<bmin[signJ[i]]<<","<<bmin[signJ[i]]+width[signI[i]]<<"] and significant="<<sign[signI[i]][signJ[i]]<<endl;
        }


        for(unsigned int i=0; i<signINum.size(); i++) {
            twikiSignNum[massP][signINum[i]][signJNum[i]]=i+1;

            th1SignFull->SetBinContent(i+1,signNum[signINum[i]][signJNum[i]]);
            th1SignFull->SetBinError(i+1,signNumErr[signINum[i]][signJNum[i]]);
            th1EffFull->SetBinContent(i+1,eff[signINum[i]][signJNum[i]]);
            th1Eff2Full->SetBinContent(i+1,eff2[signINum[i]][signJNum[i]]);
            th1EffFull->SetBinError(i+1,err[signINum[i]][signJNum[i]]);
            th1Eff2Full->SetBinError(i+1,err2[signINum[i]][signJNum[i]]);
            //th1SignFull->GetXaxis()->SetBinLabel(i+1,Form("%d-%d",bmin[signJ[i]],bmin[signJ[i]]+width[signI[i]]));
            th1SignFull->GetXaxis()->SetBinLabel(i+1,"");
            th1EffFull->GetXaxis()->SetBinLabel(i+1,"");
            th1Eff2Full->GetXaxis()->SetBinLabel(i+1,"");
            twikiSignNumValue[massP][signINum[i]][signJNum[i]]=signNum[signINum[i]][signJNum[i]];
            th1EffFull->GetXaxis()->SetBinLabel(i+1,Form("%d-%d",bmin[signJNum[i]],bmin[signJNum[i]]+width[signINum[i]]));
            //twikiEffNumValue[massP][signINum[i]][signJNum[i]]=effNum[signINum[i]][signJNum[i]];
            //cout<<"range=["<<bmin[signJ[i]]<<","<<bmin[signJ[i]]+width[signI[i]]<<"] and significant="<<sign[signI[i]][signJ[i]]<<endl;
        }



        th1Eff->SetMinimum(0);
        th1Eff->SetMaximum(1);
        th1EffFull->SetMinimum(0);
        th1EffFull->SetMaximum(1);
        th1Eff->SetYTitle("efficiency");
        th1EffFull->SetYTitle("efficiency");
        th1Eff->SetTitle(Form("largest 15 Sign.(Num),%sGev",masspoint[massP].data()));
        th1Eff->Draw();
        th1Eff2->Draw("same");

        Float_t rightmax = 2*th1Sign->GetBinContent(1);
        //cout<<rightmax<<endl;
        Float_t scale = gPad->GetUymax()/rightmax;
        //hint1->SetLineColor(kRed);
        th1Sign->Scale(scale);
        //hint1->Draw("same");
        //draw an axis on the right side
        c1->Update();
        th1Sign->Draw("same");
        //leg->Clear();
        //leg->AddEntry(th1Eff,"signal efficiency");
        //leg->AddEntry(th1Eff2,"Bkg. efficiency");
        //leg->SetY1(0.8335);
        leg->Draw("same");

        TGaxis *axis = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),
                                  gPad->GetUxmax(), gPad->GetUymax(),0,rightmax,510,"+L");
        axis->SetTitle("significance");
        axis->SetTitleColor(4);
        axis->SetLineColor(4);
        axis->SetLabelColor(4);
        axis->Draw();

        c1->Print(Form("pdfPR/%s.pdf",output.data()));




        th1EffFull->SetTitle(Form("all windows(Num),%sGev",masspoint[massP].data()));
        th1EffFull->Draw();
        th1Eff2Full->Draw("same");
        c1->Update();
        rightmax = 1.1*th1SignFull->GetBinContent(1);
        scale = gPad->GetUymax()/rightmax;
        th1SignFull->Scale(scale);

        th1SignFull->Draw("Hist,same");
        leg->Draw("same");

        TGaxis *axis2 = new TGaxis(gPad->GetUxmax(),gPad->GetUymin(),
                                   gPad->GetUxmax(), gPad->GetUymax(),0,rightmax,510,"+L");
        axis2->SetTitle("significance");
        axis2->SetTitleColor(4);
        axis2->SetLineColor(4);
        axis2->SetLabelColor(4);
        axis2->Draw();



        if(massP==12)c1->Print(Form("pdfPR/%s.pdf)",output.data()));
        else c1->Print(Form("pdfPR/%s.pdf",output.data()));

    }


    TLegend* leg ;
    leg=new TLegend(0.1441452,0.742447,0.300645,0.883966);
    setLeg(leg);
    c2->cd();
    TGraphErrors* tg1= new TGraphErrors(13,tgraphMass,tgraphSigEff,tgraphMassError,tgraphSigEffError);
    TGraphErrors* tg2= new TGraphErrors(13,tgraphMass,tgraphBkgEff,tgraphMassError,tgraphBkgEffError);
    TGraphErrors* tg3= new TGraphErrors(13,tgraphMass,tgraphSgnEff,tgraphMassError,tgraphSgnEffError);

    for(int i=0; i<13; i++) {
        //cout<<tgraphSigEff[i]<<","<<tgraphSigEff145[i];
        cout<<"i="<<i<<","<<tgraphSigEff[i]<<","<<tgraphBkgNum[i]<<","<<tgraphSgnEff[i]<<endl;
        cout<<"i="<<i<<","<<tgraphSigEff145[i]<<","<<tgraphBkgNum145[i]<<","<<tgraphSgnEff145[i]<<endl;
        tgraphSigEff[i]=tgraphSigEff[i]/tgraphSigEff145[i];
        //cout<<tgraphSigEff[i]<<endl;
        tgraphSigEffError[i]=sqrt((tgraphSigEffError[i]/tgraphSigEff[i])*(tgraphSigEffError[i]/tgraphSigEff[i])+(tgraphSigEffError145[i]/tgraphSigEff145[i])*(tgraphSigEffError145[i]/tgraphSigEff145[i]));
        tgraphSigEffError[i]*=tgraphSigEff[i];
        tgraphBkgEff[i]=tgraphBkgEff[i]/tgraphBkgEff145[i];
        tgraphBkgEffError[i]=sqrt((tgraphBkgEffError[i]/tgraphBkgEff[i])*(tgraphBkgEffError[i]/tgraphBkgEff[i])+(tgraphBkgEffError145[i]/tgraphBkgEff145[i])*(tgraphBkgEffError145[i]/tgraphBkgEff145[i]));
        tgraphBkgEffError[i]*=tgraphBkgEff[i];
        tgraphSgnEff[i]=tgraphSgnEff[i]/tgraphSgnEff145[i];
        tgraphSgnEffError[i]=sqrt((tgraphSgnEffError[i]/tgraphSgnEff[i])*(tgraphSgnEffError[i]/tgraphSgnEff[i])+(tgraphSgnEffError145[i]/tgraphSgnEff145[i])*(tgraphSgnEffError145[i]/tgraphSgnEff145[i]));
        tgraphSgnEffError[i]*=tgraphSgnEff[i];

    }

    TGraphErrors* tg4= new TGraphErrors(13,tgraphMass,tgraphSigEff,tgraphMassError,tgraphSigEffError);
    TGraphErrors* tg5= new TGraphErrors(13,tgraphMass,tgraphBkgEff,tgraphMassError,tgraphBkgEffError);
    TGraphErrors* tg6= new TGraphErrors(13,tgraphMass,tgraphSgnEff,tgraphMassError,tgraphSgnEffError);


    tg1->SetMaximum(1);
    tg1->SetMinimum(0);
    tg1->SetTitle("");
    tg1->GetXaxis()->SetTitle("Mass of Z' [GeV]");
    tg1->Draw("APL*");
    tg2->SetLineColor(2);
    tg3->SetLineColor(3);
    tg1->SetMarkerStyle(20);
    tg2->SetMarkerStyle(21);
    tg3->SetMarkerStyle(22);
    leg->Clear();
    tg1->SetFillColor(kWhite);
    tg2->SetFillColor(kWhite);
    tg3->SetFillColor(kWhite);
    gStyle->SetFillColor(kWhite) ;
    leg->AddEntry(tg1,"signal eff.");
    leg->AddEntry(tg2,"bkg. eff.");
    leg->AddEntry(tg3,"significance");
    tg2->Draw("PL,same");
    tg3->Draw("PL,same");
    leg->Draw("same");
    c2->Print("png/1.png");


    tg4->GetXaxis()->SetTitle("Mass of Z' [GeV]");
    tg4->SetTitle("most significant window/105-145");
    tg4->SetMaximum(2.2);
    tg4->SetMinimum(0.3);
    tg4->SetMarkerStyle(20);
    tg5->SetMarkerStyle(21);
    tg6->SetMarkerStyle(22);
    tg4->Draw("APL");
    tg5->SetLineColor(2);
    tg6->SetLineColor(3);

    leg->Clear();
    tg4->SetFillColor(kWhite);
    tg5->SetFillColor(kWhite);
    tg6->SetFillColor(kWhite);
    gStyle->SetFillColor(kWhite) ;
    leg->AddEntry(tg4,"signal eff. ratio");
    leg->AddEntry(tg5,"bkg. eff. ratio");
    leg->AddEntry(tg6,"significance ratio");
    tg5->Draw("PL,same");
    tg6->Draw("PL,same");
    leg->Draw("same");
    c2->Print("png/2.png");






    ofstream myfile;
    myfile.open ("txt/twikiOPPRN.txt");
    myfile<<"|*windowRange*|";
    for (int massP=0; massP<4; massP++)myfile<<"*"<<masspoint[massP].data()<<"Num*|";
    //myfile<<"*";
    for (int massP=0; massP<4; massP++)myfile<<"*"<<masspoint[massP].data()<<"Eff*|";
    myfile<<"*avg.rank(eff)*|*avg.rank(Num)*|*avg.rank(total)*|"<<endl;
    for(int j=0; j<nBmin; j++) {
        for(int i=0; i<nWidth; i++) {
            if(width[i]+bmin[j]>150)continue;
            myfile<<"|"<<bmin[j]<<"to"<<bmin[j]+width[i]<<"|";
            double temp1=0,temp2=0;
            for (int massP=0; massP<4; massP++) {
                myfile<<twikiSignNum[massP][i][j]<<"("<<twikiSignNumValue[massP][i][j]<<")|";
                temp1+=twikiSign[massP][i][j];
                temp2+=twikiSignNum[massP][i][j];
            }
            for (int massP=0; massP<4; massP++) {
                myfile<<twikiSign[massP][i][j]<<"("<<twikiSignValue[massP][i][j]<<")|";
            }
            myfile<<temp1/4<<"|"<<temp2/4<<"|"<<(temp1+temp2)/8<<"|"<<endl;
            //<<"to"<<bmin[i]+width[j]<<"|"<<endl;
            //cout<<j<<","<<i<<endl;
        }
    }
    myfile<<endl;



    myfile<<"|*rank(signalEff)*|";
    for (int massP=0; massP<4; massP++)myfile<<"*"<<masspoint[massP].data()<<"Eff*|";
    myfile<<endl;
    vector<int> signINum,signJNum;
//for(int ij=0;ij<nWidth*nBmin;ij++){
    for(int ij=0; ij<15; ij++) {
        myfile<<"|"<<ij+1<<"|";
        for (int massP=0; massP<4; massP++) {
            double tempSign=1000;
            int tempI=0,tempJ=0;
            //for(int i=0;i<nWidth;i++)for(int j=0;j<nBmin;j++)if(width[tempI]+bmin[tempJ]>150)twikiSign[massP][tempI][tempJ]=10000;

            for(int i=0; i<nWidth; i++) {
                for(int j=0; j<nBmin; j++) {
                    if(twikiSign[massP][i][j]<tempSign) {
                        if(width[i]+bmin[j]>150)continue;
                        //cout<<"i="<<i<<",j="<<j<<",signcp="<<signCP[i][j]<<",temp="<<tempSign<<endl;
                        tempSign=twikiSign[massP][i][j];
                        tempI=i;
                        tempJ=j;
                        //cout<<tempI<<","<<tempJ<<","<<tempSign<<endl;
                    }
                }
            }
            //signINum.push_back(tempI);
            //signJNum.push_back(tempJ);
            //cout<<signCP[tempI][tempJ]<<endl;
            //cout<<"twikiSign[massP][tempI][tempJ]="<<twikiSign[massP][tempI][tempJ]<<"|"<<bmin[tempJ]<<"to"<<bmin[tempJ]+width[tempI]<<"|"<<endl;
            twikiSign[massP][tempI][tempJ]=10000;
            //if(width[tempI]+bmin[tempJ]>150)continue;
            myfile<<bmin[tempJ]<<"to"<<bmin[tempJ]+width[tempI]<<"("<<setprecision(3)<<twikiEffValue[massP][tempI][tempJ]<<")|";
            //cout<<twikiSign[massP][tempI][tempJ];

        }
        myfile<<endl;
    }
    myfile<<endl;

    myfile<<"|*rank(signalEff)*|";
    for (int massP=0; massP<4; massP++)myfile<<"*"<<masspoint[massP].data()<<"Num*|";
    myfile<<endl;
    //vector<int> signINum,signJNum;
//for(int ij=0;ij<nWidth*nBmin;ij++){
    for(int ij=0; ij<15; ij++) {
        myfile<<"|"<<ij+1<<"|";
        for (int massP=0; massP<4; massP++) {
            double tempSign=10000;
            int tempI=0,tempJ=0;
            //for(int i=0;i<nWidth;i++)for(int j=0;j<nBmin;j++)if(width[tempI]+bmin[tempJ]>150)twikiSignNum[massP][tempI][tempJ]=10000;

            for(int i=0; i<nWidth; i++) {
                for(int j=0; j<nBmin; j++) {
                    if(twikiSignNum[massP][i][j]<tempSign) {
                        if(width[i]+bmin[j]>150)continue;
                        //cout<<"i="<<i<<",j="<<j<<",signcp="<<signCP[i][j]<<",temp="<<tempSign<<endl;
                        tempSign=twikiSignNum[massP][i][j];
                        tempI=i;
                        tempJ=j;
                        //cout<<tempI<<","<<tempJ<<","<<tempSign<<endl;
                    }
                }
            }
            //signINum.push_back(tempI);
            //signJNum.push_back(tempJ);
            //cout<<signCP[tempI][tempJ]<<endl;
            twikiSignNum[massP][tempI][tempJ]=10000;
            //if(width[tempI]+bmin[tempJ]>150)continue;
            myfile<<bmin[tempJ]<<"to"<<bmin[tempJ]+width[tempI]<<"("<<setprecision(3)<<twikiEffValue[massP][tempI][tempJ]<<")|";
            //cout<<twikiSign[massP][tempI][tempJ];

        }
        myfile<<endl;
    }
    myfile<<endl;
}
Example #15
0
void plotHitEnergy(string inputDir, int hittype=1, float radius=0.4) {
    setNCUStyle(true);

    string decversion;
    if(inputDir.find("rfull009")!=std::string::npos)decversion="rfull009";
    else if(inputDir.find("rfull012")!=std::string::npos)decversion="rfull012";

    TH1F* hecal;
    TH1F* hhcal;
    std::string ecalhitname = hittype==1? "EM_BARREL":"EcalBarrelHits";
    std::string hcalhitname = hittype==1? "HAD_BARREL":"HcalBarrelHits";

    TString energy=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; test2=${test%%mumu*}; echo \"${test2##*tev}\"",inputDir.data()));
    cout << "energy = " << energy.Data() << endl;

    string inputFile = inputDir + "/radius" + Form("%0.1f",radius)+ (hittype==1? "_rawhit.root": "_rawhit_new.root");
    cout << "opening " << inputFile.data() << endl;



    TFile *f = TFile::Open(inputFile.data());
    hecal = (TH1F*)f->FindObjectAny("hecalhit_energy");
    hecal->SetLineWidth(3);
    hecal->SetFillStyle(1001);
    hecal->SetFillColor(4);
    hecal->SetLineColor(4);
    hecal->SetXTitle(Form("%s hit energy [GeV]",ecalhitname.data()));
    hecal->SetYTitle(Form("Number of hits per %.1f GeV",hecal->GetBinWidth(1)));
    hecal->SetTitleOffset(1.2,"X");
    hecal->SetTitleOffset(1.4,"Y");
    hhcal = (TH1F*)f->FindObjectAny("hhcalhit_energy");
    hhcal->SetLineWidth(3);
    hhcal->SetFillStyle(1001);
    hhcal->SetFillColor(2);
    hhcal->SetLineColor(2);
    hhcal->SetXTitle(Form("%s hit energy [GeV]",hcalhitname.data()));
    hhcal->SetYTitle(Form("Number of hits per %.1f GeV",hhcal->GetBinWidth(1)));
    hhcal->SetTitleOffset(1.2,"X");
    hhcal->SetTitleOffset(1.4,"Y");


    TLegend* leg = new TLegend(0.444,0.690,0.990,0.903);
    leg->SetFillColor(0);
    leg->SetFillStyle(0);

    TCanvas* c1 = new TCanvas("c1","",500,500);
    int lastbin=hecal->FindLastBinAbove(0)+20;
    float xmax=hecal->GetBinLowEdge(lastbin);
    hecal->GetXaxis()->SetRangeUser(0,xmax);
    hecal->Draw("hist");
    c1->SetLogy(1);

    leg->SetHeader(decversion.data());
    leg->AddEntry(hecal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f");
    leg->Draw("same");

    std::string outputname = decversion + "/" + decversion + "_" + ecalhitname + "hit_energy_" + Form("%s",energy.Data()) + "TeVZp";
    c1->Print(Form("%s.pdf",outputname.data()));
    c1->Print(Form("%s.eps",outputname.data()));
    leg->Clear();


    lastbin=hhcal->FindLastBinAbove(0)+20;
    xmax=hhcal->GetBinLowEdge(lastbin);
    hhcal->GetXaxis()->SetRangeUser(0,xmax);
    hhcal->Draw("hist");
    c1->SetLogy(1);

    leg->SetHeader(decversion.data());
    leg->AddEntry(hhcal,Form("%s-TeV Z'#rightarrow qq",energy.Data()),"f");
    leg->Draw("same");

    outputname = decversion + "/" + decversion + "_" + hcalhitname + "hit_energy_" + Form("%s",energy.Data()) + "TeVZp";

    c1->Print(Form("%s.pdf",outputname.data()));
    c1->Print(Form("%s.eps",outputname.data()));

}
//Calls treeAnalyzer::applySelection(strInputTextFile) and then for each plot made here it analyzes the raw data that went into making each plot
//The output is stored inside the Plots directory for each Canvas created
void treeAnalyzerTDC::applySelectionTDC(string strOutputROOTFile){
    //Variable Declaration
    bool bExitSuccess = false;
    
    //Apply the Selection
    //------------------------------------------------------
    applySelection(strOutputROOTFile);
    
    //Load the ROOT file that was just created in the UPDATE mode
    //------------------------------------------------------
    //TFile *file_ROOT_Output = new TFile(strOutputROOTFile.c_str(), "UPDATE", "", 1);
    //TFile file_ROOT_Output = getFile(strOutputROOTFile, "UPDATE", bExitSuccess);
    TFile * file_ROOT_Output = getFile(strOutputROOTFile, "UPDATE", bExitSuccess);
    
    if (!bExitSuccess) { //Case: Output File Was Not Created Successfully
        if(bVerbose_IO) {
            cout<< ("treeAnalyzerTDC::applySelectionTDC() - Output ROOT File: " + strOutputROOTFile + " was not successfully created, stopping\n").c_str();
            cout<<"treeAnalyzerTDC::applySelectionTDC() - Please Cross-Check (Maybe you do not have write-permission in working directory or filepath does not exist???)"<<endl;
        }
        
        return;
    } //End Case: Output File Was Not Created Successfully
    
    //Loop Over Selection Input to create the indepth TDC Analysis
    //------------------------------------------------------
    for (auto iterSel = vecSelInfo.begin(); iterSel != vecSelInfo.end(); ++iterSel) { //Loop Over vecSelInfo
        //Get the TDirectory that was made for this SelInfo
        TDirectory *dir_thisSel = file_ROOT_Output->GetDirectory( (*iterSel).strDirectory.c_str(), false, "GetDirectory" );
        
        //Loop over all CanvasInfo's that were requested for this SelInfo
        //------------------------------------------------------
        for (auto iterCanvas = (*iterSel).mapCanvas.begin(); iterCanvas != (*iterSel).mapCanvas.end(); ++iterCanvas) { //Loop Over (*iterSel).mapCanvas
            //Get the TDirectory that was made for this CanvasInfo
            TDirectory *dir_thisCanvas = dir_thisSel->GetDirectory( ((*iterCanvas).second).strDirectory.c_str(), false, "GetDirectory" );
            
            //Loop over all PlotInfo's that were requested for this CanvasInfo
            //------------------------------------------------------
            for (auto iterPlot = ((*iterCanvas).second).mapPlot.begin(); iterPlot != ((*iterCanvas).second).mapPlot.end(); ++iterPlot) { //Loop Over ((*iterCanvas).second).mapPlot
                //Skip this plot if no friend branch was defined by the user
                if ( ((*iterPlot).second).strFriendBranch.length() == 0 ) continue;
                
                //Get the TDirectory that was made for this PlotInfo
                //------------------------------------------------------
                TDirectory *dir_thisPlot = dir_thisCanvas->GetDirectory( ((*iterPlot).second).strDirectory.c_str(), false, "GetDirectory" );
                TDirectory *dir_HistoWithFit = dir_thisPlot->mkdir( ("HistoWithFit_" + ((*iterPlot).second).strVarIndep).c_str() );
                TDirectory *dir_HistoOverFit = dir_thisPlot->mkdir( ("HistoOverFit_" + ((*iterPlot).second).strVarIndep).c_str() );
                
                //Open the Input Data File
                //------------------------------------------------------
                TFile * file_ROOT_Input = getFile( ((*iterPlot).second).strNameROOTFile, "READ", bExitSuccess );
                
                if (!bExitSuccess) { //Case: Input File Failed To Open Successfully
                    if (bVerbose_IO) {
                        std::cout << ("treeAnalyzerTDC::applySelectionTDC(): error while opening file: " + ((*iterPlot).second).strNameROOTFile).c_str() << endl;
                        std::cout << "Skipping Plot: " << ((*iterPlot).second).strName << endl;
                    }
                    
                    continue;
                } //End Case: Input File Failed To Open Successfully
                
                //Load the TTree from file_ROOT_Input
                //------------------------------------------------------
                TTree *treeInput = (TTree*) file_ROOT_Input->Get( ((*iterPlot).second).strNameTree.c_str() );
                
                //Note the Selection is already setup due to calling "applySelection()" of the parent class
                
                //Declaration of TTree's leaf types
                //------------------------------------------------------
                int iRun;                           //value of the run number
                
                float fVarIndep;                    //value of the independent variable for the i^th point
                
                TH1F *hTDC_Histo = new TH1F();      //Histogram from the i^th point
                
                TF1 *func_FriendBranch = new TF1(); //Fit Function from the i^th point
                
                //Set the branch addresses
                //------------------------------------------------------
                treeInput->SetBranchAddress("iRun",&iRun);
                treeInput->SetBranchAddress( ((*iterPlot).second).strVarIndep.c_str(), &fVarIndep);
                treeInput->SetBranchAddress("hTDC_Histo",&hTDC_Histo);
                treeInput->SetBranchAddress( ((*iterPlot).second).strFriendBranch.c_str(), &func_FriendBranch);
                
                //Loop Over the Entries in treeInput that pass the selection
                //------------------------------------------------------
                //Inform the user we have moved to a new SelInfo and then draw the tree
                //cout<< ("Selection = '" + (*iterSel).strSel + "'" ) << endl;
                //treeInput->Draw( ">>listSelEvts", (*iterSel).strSel.c_str(), "entrylist" );
                
                cout<< ("Selection = '" + ((*iterPlot).second).strSelLocal + "'" ) << endl;
                treeInput->Draw( ">>listSelEvts", ((*iterPlot).second).strSelLocal.c_str(), "entrylist" );
                
                //Get the Entry List
                TEntryList *listSelEvts = (TEntryList*) gDirectory->Get("listSelEvts");
                
                //Loop Over the events passing ((*iterPlot).second).strSelLocal stored in eventList
                //cout<<"i\tidx_EvtList\tSigma_Fit\n";
                for (int i=0; i < listSelEvts->GetN(); ++i) { //Loop over events stored in eventList
                    //int iEvtIdx = listSelEvts->Next();  //Should probably use listSelEvts->GetEntry(i) because duplicate calls of Next() per loop iteration cause undesired iteration through the list
                    
                    //treeInput->GetEntry( iEvtIdx );
                    treeInput->GetEntry( listSelEvts->GetEntry(i) );
                    
                    //Skip this Event if the Histogram pointer is a null pointer
                    if (hTDC_Histo == nullptr){
                        continue;
                    }
                    else{ //Otherwise Set the Histogram Style
                        hTDC_Histo = getHistogram( (*iterPlot).second, hTDC_Histo);
                    }
                    
                    //treeInput->Show();
                    //if(i==0) treeInput->Show();
                    
                    //Set the Style
                    
                    //Create the Canvas - Histogram w/Fit
                    //------------------------------------------------------
                    //set the style based on user input
                    //Make a copy of the CanvasInfo, reset the name, and then pass it to treeAnalyzer::getCanvas()
                    CanvasInfo tempCanvasInfo = (*iterCanvas).second;
                    tempCanvasInfo.strName = "canvas_DataHistoWithFit_R" + getString(iRun) + "_" + ((*iterPlot).second).strVarDepend + "_" + ((*iterPlot).second).strVarIndep + getString(fVarIndep);
                    
                    TCanvas *cHistoWithFit = getCanvas(tempCanvasInfo);
                    cHistoWithFit->cd();
                    
                    TLegend *leg = (TLegend *) ((*iterCanvas).second).leg->Clone( ("leg_HistoWithFit_" + getString(fVarIndep) ).c_str() );
                    leg->Clear();   //Wipe all previous entries
                    
                    leg->AddEntry(hTDC_Histo,"Data","LPE");
                    
                    //Plot Histogram on the Canvas
                    cHistoWithFit->cd();
                    hTDC_Histo->Draw("E1");
                    
                    //Check that the fit function exists
                    if ( func_FriendBranch != nullptr) {
                        //Set the style
                        func_FriendBranch->SetLineColor( ((*iterPlot).second).iColor );
                        func_FriendBranch->SetLineStyle( ((*iterPlot).second).iStyleLine );
                        func_FriendBranch->SetLineWidth( ((*iterPlot).second).fSizeLine );
                        
                        //Add to the Legend
                        leg->AddEntry(func_FriendBranch, "Fit", "L");
                        
                        //Draw
                        func_FriendBranch->Draw("same");
                    }
                    
                    //Draw the legend
                    leg->Draw("same");
                    
                    //Store
                    dir_HistoWithFit->cd();
                    cHistoWithFit->Write();
                    hTDC_Histo->Write();
                    func_FriendBranch->Write();
                    //if ( func_FriendBranch != nullptr) func_FriendBranch->Write();
                    
                    //Create the Canvas - Histogram DIVIDED by Fit
                    //------------------------------------------------------
                    //set the style based on user input
                    //Make a copy of the CanvasInfo, reset the name, and then pass it to treeAnalyzer::getCanvas()
                    tempCanvasInfo.strName = "canvas_DataHistoOverFit_R" + getString(iRun) + "_" + ((*iterPlot).second).strVarDepend + "_" + ((*iterPlot).second).strVarIndep + getString(fVarIndep);
                    
                    TCanvas *cHistoOverFit = getCanvas(tempCanvasInfo);
                    cHistoOverFit->cd();
                    
                    TH1F *hTDC_HistoOverFit = (TH1F *) hTDC_Histo->Clone( (hTDC_Histo->GetName() + getString("_OverFit") ).c_str() );
                    
                    hTDC_HistoOverFit->Divide(func_FriendBranch);
                    
                    hTDC_HistoOverFit->GetYaxis()->SetRangeUser(0.,2.);
                    
                    hTDC_HistoOverFit->Draw("E1");
                    
                    //store
                    dir_HistoOverFit->cd();
                    cHistoOverFit->Write();
                    hTDC_HistoOverFit->Write();
                    
                    //Delete pointers
                    delete cHistoWithFit;
                    delete cHistoOverFit;
                    //delete func_FriendBranch; //No this breaks the TTree::GetEntry() Call
                    //delete hTDC_Histo;        //No this breaks the TTree::GetEntry() Call
                    delete leg;
                } //End Loop over events stored in eventList
                
                //Close the Input ROOT File
                //------------------------------------------------------
                file_ROOT_Input->Close();
            } //End Loop Over ((*iterCanvas).second).mapPlot
        } //End Loop Over (*iterSel).mapCanvas
    } //End Loop Over vecSelInfo
    
    //Close the output ROOT file
    //------------------------------------------------------
    file_ROOT_Output->Close();
    
    return;
} //End treeAnalyzerTDC::applySelectionTDC()
Example #17
0
File: plot.C Project: magania/CMS2
void plot(TString fileName, TString det, TString version, TString sampleName)
{

	gROOT->ProcessLine(".L ../tdrStyle.C");
	gROOT->ProcessLine("setTDRStyle()");

	TFile f(fileName, "READ");
	TH1F *h1_numerator = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_ee");
	TH1F *h1_denom_old = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_idold_ee");
	TH1F *h1_denom_new = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_idnew_ee");

	TH1F *h1_denom_iso_old = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_isoold_ee");
	TH1F *h1_denom_iso_new = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_isonew_ee");

	TH1F *h1_denom_iso_new_cand1 = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_isonew_cand1_ee");

	TH1F *h1_denom_id1_iso1_conv = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_id1_iso1_conv_ee");

	TH1F *h1_denom_conv = (TH1F*)f.Get(sampleName+"_hyp_lt_" + det + "_pt_conv_ee");

	//
	// id
	//

	TGraphAsymmErrors *gr_eff_old = new TGraphAsymmErrors();
	gr_eff_old->BayesDivide(h1_denom_old, h1_numerator);
	gr_eff_old->GetYaxis()->SetRangeUser(0, 1.1);
	gr_eff_old->GetYaxis()->SetTitle("Efficiency");
	gr_eff_old->GetXaxis()->SetTitle("LT p_{T} (GeV)");
	gr_eff_old->SetMarkerColor(kRed);
	gr_eff_old->SetLineColor(kRed);

	TGraphAsymmErrors *gr_eff_new = new TGraphAsymmErrors();
	gr_eff_new->BayesDivide(h1_denom_new, h1_numerator);
	gr_eff_new->GetYaxis()->SetRangeUser(0, 1.1);
	gr_eff_new->GetYaxis()->SetTitle("Efficiency");
	gr_eff_new->GetXaxis()->SetTitle("LT p_{T} (GeV)");
	gr_eff_new->SetMarkerColor(kBlue);
	gr_eff_new->SetLineColor(kBlue);

	//
	// iso
	//

	TGraphAsymmErrors *gr_eff_iso_old = new TGraphAsymmErrors();
	gr_eff_iso_old->BayesDivide(h1_denom_iso_old, h1_numerator);
	gr_eff_iso_old->GetYaxis()->SetRangeUser(0, 1.1);
	gr_eff_iso_old->GetYaxis()->SetTitle("Efficiency");
	gr_eff_iso_old->GetXaxis()->SetTitle("LT p_{T} (GeV)");
	gr_eff_iso_old->SetMarkerColor(kRed);
	gr_eff_iso_old->SetLineColor(kRed);

	TGraphAsymmErrors *gr_eff_iso_new = new TGraphAsymmErrors();
	gr_eff_iso_new->BayesDivide(h1_denom_iso_new, h1_numerator);
	gr_eff_iso_new->GetYaxis()->SetRangeUser(0, 1.1);
	gr_eff_iso_new->GetYaxis()->SetTitle("Efficiency");
	gr_eff_iso_new->GetXaxis()->SetTitle("LT p_{T} (GeV)");
	gr_eff_iso_new->SetMarkerColor(kBlue);
	gr_eff_iso_new->SetLineColor(kBlue);

	TGraphAsymmErrors *gr_eff_iso_new_cand1 = new TGraphAsymmErrors();
	gr_eff_iso_new_cand1->BayesDivide(h1_denom_iso_new_cand1, h1_numerator);
	gr_eff_iso_new_cand1->GetYaxis()->SetRangeUser(0, 1.1);
	gr_eff_iso_new_cand1->GetYaxis()->SetTitle("Efficiency");
	gr_eff_iso_new_cand1->GetXaxis()->SetTitle("LT p_{T} (GeV)");
	gr_eff_iso_new_cand1->SetMarkerColor(kBlack);
	gr_eff_iso_new_cand1->SetLineColor(kBlack);

	TGraphAsymmErrors *gr_eff_id1_iso1_conv = new TGraphAsymmErrors();
	gr_eff_id1_iso1_conv->BayesDivide(h1_denom_id1_iso1_conv, h1_numerator);
	gr_eff_id1_iso1_conv->GetYaxis()->SetRangeUser(0, 1.1);
	gr_eff_id1_iso1_conv->GetYaxis()->SetTitle("Efficiency");
	gr_eff_id1_iso1_conv->GetXaxis()->SetTitle("LT p_{T} (GeV)");
	gr_eff_id1_iso1_conv->SetMarkerColor(kMagenta);
	gr_eff_id1_iso1_conv->SetLineColor(kMagenta);
	gr_eff_id1_iso1_conv->SetMarkerStyle(25);

	TGraphAsymmErrors *gr_eff_conv = new TGraphAsymmErrors();
	gr_eff_conv->BayesDivide(h1_denom_conv, h1_numerator);
	gr_eff_conv->GetYaxis()->SetRangeUser(0, 1.1);
	gr_eff_conv->GetYaxis()->SetTitle("Efficiency");
	gr_eff_conv->GetXaxis()->SetTitle("LT p_{T} (GeV)");
	gr_eff_conv->SetMarkerColor(kMagenta);
	gr_eff_conv->SetLineColor(kMagenta);
	gr_eff_conv->SetMarkerStyle(22);


	TLegend *lg = new TLegend(0.5, 0.2, 0.9, 0.4);
	lg->SetFillColor(kWhite);
	lg->SetLineColor(kWhite);
	lg->SetShadowColor(kWhite);
	lg->AddEntry(gr_eff_old, "egamma_looseId", "lp");
	lg->AddEntry(gr_eff_new, "cand01", "lp");

	TCanvas *c1 = new TCanvas();
	c1->cd();
	gr_eff_old->Draw("AP");
	gr_eff_new->Draw("P");
	lg->Draw();
	c1->SaveAs("results/eff_mc" + version + "_" + det + ".png");


	lg->Clear();
	lg->AddEntry(gr_eff_iso_old, "relsusy_iso", "lp");
	lg->AddEntry(gr_eff_iso_new, "relsusy_iso_cand0", "lp");
	lg->AddEntry(gr_eff_iso_new_cand1, "relsusy_iso_cand1", "lp");

	c1->cd();
	gr_eff_iso_old->Draw("AP");
	gr_eff_iso_new->Draw("P");
	gr_eff_iso_new_cand1->Draw("P");
	lg->Draw();
	c1->SaveAs("results/effiso_mc" + version + "_" + det + ".png");

	lg->Clear();
	lg->AddEntry(gr_eff_id1_iso1_conv, "id1_iso1_conv", "lp");

	c1->cd();
	gr_eff_id1_iso1_conv->Draw("AP");
	lg->Draw();
	c1->SaveAs("results/eff_id1_iso1_conv_mc" + version + "_" + det + ".png");

	lg->Clear();
	lg->AddEntry(gr_eff_conv, "conv", "lp");

	c1->cd();
	gr_eff_conv->Draw("AP");
	lg->Draw();
	c1->SaveAs("results/eff_conv_mc" + version + "_" + det + ".png");


}
Example #18
0
void HwwGenJetVetoEfficiency(const string inputFilename,  const string Label) 
{  
  gBenchmark->Start("WWTemplate");

  cout << "here1\n";
  string label = "";
  cout << "here11\n";
  if (Label != "") label = "_" + Label;
  cout << "here12\n";

  TFile *file = new TFile("JetVetoEfficiencySystematics.root", "UPDATE");
  cout << "here13\n";
  assert(file);
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPtFineBinning_ggHww160_PowhegToNNLL");
  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww160_PowhegToNNLL");
  cout << "here14\n";
//    TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww160_MCAtNLOToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww180_PowhegToNNLL");//  
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww200_PowhegToNNLL");
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww220_PowhegToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww250_PowhegToNNLL");
//  TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww300_PowhegToNNLL");
//   TH1D *kFactorHiggsPt = (TH1D*)file->Get("kFactorHiggsPt_ggHww400_PowhegToNNLL");
  assert(kFactorHiggsPt);
  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  Double_t lumi;              // luminosity (pb^-1)
    
  cout << "here2\n";

  //--------------------------------------------------------------------------------------------------------------
  // Histograms
  //==============================================================================================================  
  TH1D *dileptonMass = new TH1D("dileptonMass", "; Mass [GeV/c^{2}]; Number of Events", 50, 0, 200);
  TH1D *genMet = new TH1D("genMet", ";  Met [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonPtMin = new TH1D("leptonPtMin", ";  Lepton p_{T} [GeV/c]; Number of Events", 50, 0, 200);
  TH1D *leptonEta = new TH1D("leptonEta", "; Lepton #eta; Number of Events", 50, -5, 5);
  TH1D *leadingGenJetPt = new TH1D((string("leadingGenJetPt")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *leadingGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *secondGenJetPt_reweighted = new TH1D((string("leadingGenJetPt_reweighted")+ label).c_str() , "; Leading GenJet p_{T} [GeV/c]; Number of Events", 200, 0, 200);
  TH1D *nGenJets = new TH1D("nGenJets", "; Mass [GeV/c^{2}]; Number of Events", 10, -0.5, 9.5);
  TH1D *leptonDeltaPhi = new TH1D("leptonDeltaPhi", "; #Delta #phi (l,l); Number of Events", 50, 0, 180);


  vector<Double_t> NEvents_0Jets;
  vector<Double_t> NEvents_1Jets;
  vector<Double_t> NEvents_2Jets;
  for(UInt_t k=0 ; k < 200; ++k) {
    NEvents_0Jets.push_back(0); 
    NEvents_1Jets.push_back(0); 
    NEvents_2Jets.push_back(0);
  }


  Double_t NEventsGenerated = 0;
  Double_t NEventsAccepted = 0;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  //  
  TFile *infile=0;
  TTree *eventTree=0;  
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info    = new mithep::TEventInfo();
  mithep::TGenInfo *genInfo    = new mithep::TGenInfo();

  cout << "here3\n";

  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); assert(eventTree);
  
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);          TBranch *infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("Gen", &genInfo); TBranch *genInfoBr = eventTree->GetBranch("Gen");
   
  cout << "here4\n";

  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  Double_t nsel=0, nselvar=0;
  for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
    genInfoBr->GetEntry(ientry);
		
    NEventsGenerated++;

   mithep::FourVectorM lepton1;
    mithep::FourVectorM lepton2;
    lepton1.SetCoordinates(genInfo->pt_1, genInfo->eta_1, genInfo->phi_1, 0.51099892e-3 );
    lepton2.SetCoordinates(genInfo->pt_2, genInfo->eta_2, genInfo->phi_2, 0.51099892e-3 );
    mithep::FourVectorM dilepton = lepton1+lepton2;

    if (genInfo->pt_1 > 20.0 && genInfo->pt_2 > 20.0
        && fabs(genInfo->eta_1) < 2.5 && fabs(genInfo->eta_2) < 2.5
        && genInfo->met > 30.0
        && fabs(dilepton.M() - 91.2) > 15.0
      ) {
      Double_t scale = kFactorHiggsPt->GetBinContent(kFactorHiggsPt->GetXaxis()->FindFixBin(genInfo->ptBosonSystem));
      scale = 1;

      if (info->eventweight >= 0) {
        
        //don't use a scale factor for Higgs pt < 1.0, because HQT does negative.
        if (genInfo->ptBosonSystem < 1.25 ) scale = 1.0;

        //powheg
        if (genInfo->ptBosonSystem > 200) scale = 0.6;
        //MC@NLO
//          if (genInfo->ptBosonSystem > 200) scale = 1.5;        

         leadingGenJetPt->Fill(genInfo->jetpt_1,1.0);
         leadingGenJetPt_reweighted->Fill(genInfo->jetpt_1,scale);

         for(UInt_t k=0 ; k < 200; ++k) {
           if (genInfo->jetpt_1 > k && genInfo->jetpt_2 > k) {
             NEvents_2Jets[k] += scale;
           } else if (genInfo->jetpt_1 > k) {
             NEvents_1Jets[k] += scale; 
           } else {
             NEvents_0Jets[k] += scale;
           }                                
         }

      } else {       
        leadingGenJetPt_reweighted->Fill(genInfo->jetpt_1,-1*scale);
        leadingGenJetPt->Fill(genInfo->jetpt_1,-1*scale);
        
        for(UInt_t k=0 ; k < 200; ++k) {
          if (genInfo->jetpt_1 > k && genInfo->jetpt_2 > k) {
            NEvents_2Jets[k] += -1*scale;
          } else if (genInfo->jetpt_1 > k) {
            NEvents_1Jets[k] += -1*scale; 
          } else {
             NEvents_0Jets[k] += -1*scale;
          }                                
        }

      }
    }
  } //end loop over data     

  delete info;
  delete genInfo;

  //--------------------------------------------------------------------------------------------------------------
  // Compute Jet Veto Efficiency
  //==============================================================================================================
  TH1D *jetVetoEfficiency = (TH1D*)leadingGenJetPt->Clone((string("jetVetoEfficiency")+label).c_str()); 
  jetVetoEfficiency->GetYaxis()->SetTitle("Jet Veto Efficiency");
  jetVetoEfficiency->GetYaxis()->SetTitleOffset(1.5);
  for (int i=1; i<jetVetoEfficiency->GetXaxis()->GetNbins()+1; ++i) {
    Int_t n = leadingGenJetPt->Integral(1,i);
    Int_t d = leadingGenJetPt->Integral(1,leadingGenJetPt->GetXaxis()->GetNbins()+1);
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    Int_t errorType = 2;
    mithep::MathUtils::CalcRatio(n , d, ratio, errLow, errHigh, errorType);

    jetVetoEfficiency->SetBinContent(i,ratio);
    jetVetoEfficiency->SetBinError(i,(errLow+errHigh)/2); 
    cout << jetVetoEfficiency->GetXaxis()->GetBinLowEdge(i) << " : " << n << " / " << d << " = " 
         << ratio << " + " << errHigh << " - " << errLow << endl;
  }

  TH1D *jetVetoEfficiency_reweighted = (TH1D*)leadingGenJetPt_reweighted->Clone((string("jetVetoEfficiency_reweighted")+label).c_str()); 
  jetVetoEfficiency_reweighted->GetYaxis()->SetTitle("Jet Veto Efficiency");
  jetVetoEfficiency_reweighted->GetYaxis()->SetTitleOffset(1.5);
  for (int i=1; i<jetVetoEfficiency_reweighted->GetXaxis()->GetNbins()+1; ++i) {
    Int_t n = leadingGenJetPt_reweighted->Integral(1,i);
    Int_t d = leadingGenJetPt_reweighted->Integral(1,leadingGenJetPt_reweighted->GetXaxis()->GetNbins()+1);
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    Int_t errorType = 2;
    mithep::MathUtils::CalcRatio(n , d, ratio, errLow, errHigh, errorType);

    jetVetoEfficiency_reweighted->SetBinContent(i,ratio);
    jetVetoEfficiency_reweighted->SetBinError(i,(errLow+errHigh)/2); 
    cout << jetVetoEfficiency_reweighted->GetXaxis()->GetBinLowEdge(i) << " : " << n << " / " << d << " = " 
         << ratio << " + " << errHigh << " - " << errLow << endl;
  }





  //*****************************************************************************************************
  //0,1,2 - Jet Fractions
  //*****************************************************************************************************
  const int nPoints = 100;
  double jetPtCut[nPoints];
  double jetPtCutError[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    jetPtCut[i] = i;
    jetPtCutError[i] = 0;     
  }

  double ZeroJetFraction[nPoints];
  double ZeroJetFractionErrLow[nPoints];
  double ZeroJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_0Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    ZeroJetFraction[i] = ratio;
    ZeroJetFractionErrLow[i] = errLow;
    ZeroJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *ZeroJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, ZeroJetFraction, jetPtCutError, jetPtCutError, ZeroJetFractionErrLow, ZeroJetFractionErrHigh);
  ZeroJetFractionVsJetPtCut->SetName(("ZeroJetFractionVsJetPtCut"+label).c_str());
  ZeroJetFractionVsJetPtCut->SetMarkerColor(kRed);
  ZeroJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  ZeroJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);



  double OneJetFraction[nPoints];
  double OneJetFractionErrLow[nPoints];
  double OneJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_1Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    OneJetFraction[i] = ratio;
    OneJetFractionErrLow[i] = errLow;
    OneJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *OneJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, OneJetFraction, jetPtCutError, jetPtCutError, OneJetFractionErrLow, OneJetFractionErrHigh);
  OneJetFractionVsJetPtCut->SetName(("OneJetFractionVsJetPtCut"+label).c_str());
  OneJetFractionVsJetPtCut->SetMarkerColor(kBlue);
  OneJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  OneJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);



  double TwoJetFraction[nPoints];
  double TwoJetFractionErrLow[nPoints];
  double TwoJetFractionErrHigh[nPoints];
  for (UInt_t i=0; i<nPoints; ++i) {
    
    Double_t ratio;
    Double_t errLow;
    Double_t errHigh;     
    
    Double_t n1 = TMath::Nint(NEvents_2Jets[i]);
    Double_t n2 = TMath::Nint(NEvents_0Jets[i]+NEvents_1Jets[i]+NEvents_2Jets[i]);
    mithep::MathUtils::CalcRatio(n1 , n2, ratio, errLow, errHigh, 2);
    TwoJetFraction[i] = ratio;
    TwoJetFractionErrLow[i] = errLow;
    TwoJetFractionErrHigh[i] = errHigh;
  }
  TGraphAsymmErrors *TwoJetFractionVsJetPtCut = new TGraphAsymmErrors (nPoints,  jetPtCut, TwoJetFraction, jetPtCutError, jetPtCutError, TwoJetFractionErrLow, TwoJetFractionErrHigh);
  TwoJetFractionVsJetPtCut->SetName(("TwoJetFractionVsJetPtCut"+label).c_str());
  TwoJetFractionVsJetPtCut->SetMarkerColor(kMagenta);
  TwoJetFractionVsJetPtCut->GetXaxis()->SetTitleOffset(1.02);
  TwoJetFractionVsJetPtCut->GetYaxis()->SetTitleOffset(1.05);




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

  TCanvas *cv = new TCanvas("cv","cv", 800,600);
  TLegend *tmpLegend = new TLegend(0.73,0.55,0.93,0.70); 
  

  tmpLegend->SetTextSize(0.03);
  tmpLegend->SetBorderSize(1);
  tmpLegend->AddEntry(leadingGenJetPt, "Powheg", "LP");   
  tmpLegend->AddEntry(leadingGenJetPt_reweighted, "MC@NLO(reweighted)", "LP");   
  cv->SetLogy();
  leadingGenJetPt->Draw();
  leadingGenJetPt->SetLineColor(kRed);
  leadingGenJetPt_reweighted->Draw("same");
  tmpLegend->Draw();
  cv->SaveAs("leadingGenJetPt.gif");

  jetVetoEfficiency->Draw();
  cv->SaveAs("jetVetoEfficiency.gif");
 
  cv->SetLogy(0);
  tmpLegend->Clear();
  tmpLegend->AddEntry(ZeroJetFractionVsJetPtCut, "0Jet Fraction", "LP");   
  tmpLegend->AddEntry(OneJetFractionVsJetPtCut, "1Jet Fraction", "LP");   
  tmpLegend->AddEntry(TwoJetFractionVsJetPtCut, ">2 Jet Fraction", "LP");   
  ZeroJetFractionVsJetPtCut->GetYaxis()->SetRangeUser(0.0,1.0);
  ZeroJetFractionVsJetPtCut->Draw("AP");
  OneJetFractionVsJetPtCut->Draw("Psame");
  TwoJetFractionVsJetPtCut->Draw("Psame");
  cv->SaveAs("NJetFractions.gif");


  file->WriteTObject(leadingGenJetPt, leadingGenJetPt->GetName(), "WriteDelete");
  file->WriteTObject(leadingGenJetPt_reweighted, leadingGenJetPt_reweighted->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency, jetVetoEfficiency->GetName(), "WriteDelete");
  file->WriteTObject(jetVetoEfficiency_reweighted, jetVetoEfficiency_reweighted->GetName(), "WriteDelete");
  file->WriteTObject(ZeroJetFractionVsJetPtCut, ZeroJetFractionVsJetPtCut->GetName(), "WriteDelete");
  file->WriteTObject(OneJetFractionVsJetPtCut, OneJetFractionVsJetPtCut->GetName(), "WriteDelete");
  file->WriteTObject(TwoJetFractionVsJetPtCut, TwoJetFractionVsJetPtCut->GetName(), "WriteDelete");
//   file->Close();

  //--------------------------------------------------------------------------------------------------------------
  // Summary print out
  //============================================================================================================== 
 


        
  gBenchmark->Show("plotZ");       
} 
void myPlot(vector< TH1D*> h_Z,
           vector< TH1D*> v_data,
	    TH1D* h_data, TH1D* h_bkg,int option=0){

  h_data->Reset();
  for(unsigned int i=0;i<v_data.size();i++)h_data->Add(v_data[i]);
  
  TLegend *leg = new TLegend(0.84, 0.68, 0.92, 0.87);
  
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.04);

   h_bkg->Reset();
    THStack *h_stack = new THStack("h_stack", "");
  for(unsigned int i=0;i<h_Z.size();i++){
	  h_Z[i]->SetFillColor(97-4*i);
	  h_Z[i]->SetLineColor(kBlack);
	  h_bkg->Add(h_Z[i]);
	   h_stack->Add(h_Z[i]);
	  
  }
   
   
   if(option==1){
	   leg->Clear();
	   leg->AddEntry(h_Z[3], "udsg", "f");
	leg->AddEntry(h_Z[2], "cc,c", "f");
	leg->AddEntry(h_Z[1], "b", "f");
	leg->AddEntry(h_Z[0], "bb", "f");
	}
	else{
		leg->AddEntry(h_Z[0], "QCD700", "f");
   leg->AddEntry(h_Z[1], "QCD1000", "f");
   leg->AddEntry(h_Z[2], "QCD1500", "f");
   leg->AddEntry(h_Z[3], "QCD2000", "f");
	}
  /*
leg->AddEntry(h_Zjets, "Z+Jets", "f");
  leg->AddEntry(h_TT, "t#bar{t}", "f");
  leg->AddEntry(h_WW, "WW", "f");
  leg->AddEntry(h_WZ, "WZ", "f");
  leg->AddEntry(h_ZZ, "ZZ", "f");
  leg->AddEntry(h_ZH, "ZH", "f");
*/

  h_data->SetLineColor(kBlack);
  h_data->SetMarkerStyle(8);
  h_data->SetMarkerSize(1.5);
  h_data->GetYaxis()->SetTitleOffset(1.3);
  h_data->GetXaxis()->SetTitle("");
  h_data->GetXaxis()->SetLabelOffset(999);
  h_data->GetXaxis()->SetLabelSize(0);
  
  int bmin=0,bmax=0;

		for (int k=1;k<25001;k++){
			bmin=k;
			if (h_data->GetBinContent(k)/h_data->GetMaximum()>0.02) break;
	}

		for (int k=25000;k>0;k--){
			bmax=k;
			if (h_data->GetBinContent(k)/h_data->GetMaximum()>0.02) break;
	}
	double width=h_data->GetBinWidth(1);
	rangeUserUp=(bmax-0.5)*width+h_data->GetBinCenter(1);
	rangeUserDown=(bmin-0.5)*width+h_data->GetBinCenter(1);
	if(isSetRange)h_data->GetXaxis()->SetRangeUser(rangeUserDown,rangeUserUp);
	//if(isSetRange)h_stack->GetXaxis()->SetRangeUser(rangeUserDown,rangeUserUp);
	//h_stack->GetXaxis()->SetRangeUser((bmin-0.5)*width+h_data->GetBinCenter(1),(bmax-0.5)*width+h_data->GetBinCenter(1));

  if( h_data->GetMaximum() < h_stack->GetMaximum() && isSetRange==0 ){
	  h_stack->SetTitle(h_data->GetTitle());
	h_stack->SetMaximum(h_data->GetMaximum()*1.3);
    h_stack->Draw("histe");
   // h_stack->GetHistogram()->GetYaxis()->SetTitle("Event Numbers");
    h_stack->GetHistogram()->GetYaxis()->SetTitle("");
    h_stack->GetHistogram()->GetYaxis()->SetTitleSize(h_data->GetYaxis()->GetTitleSize());
    h_stack->GetHistogram()->GetYaxis()->SetLabelSize(h_data->GetYaxis()->GetLabelSize());
    h_stack->GetHistogram()->GetYaxis()->SetTitleOffset(1.3);
    h_stack->GetHistogram()->GetXaxis()->SetTickLength(0);
    h_stack->GetHistogram()->GetXaxis()->SetLabelOffset(999);
    h_data->Draw("elsame");
  
  }
    
  else{

   // h_data->GetYaxis()->SetTitle("Event Numbers");
    h_data->GetYaxis()->SetTitle("");
    h_data->Draw("el");
    h_stack->Draw("histesame");
    h_data->Draw("elsame");

  }

    
  
  leg->AddEntry(h_data, "Data", "lp");
  leg->Draw();

  TLatex *lar = new TLatex();

  lar->SetNDC(kTRUE);
  lar->SetTextSize(0.04);
  lar->SetLineWidth(5);
  //lar->DrawLatex(0.14, 0.94, "CMS #it{#bf{2015}}");
  lar->DrawLatex(0.60, 0.94, "L = 12.9 fb^{-1} at #sqrt{s} = 13 TeV");
  
  

		lar->SetNDC(kTRUE);
		lar->SetTextSize(0.07);
		lar->SetLineWidth(5);
		lar->SetTextAlign(14);
		//lar->DrawLatex(0.14, 0.94, "CMS #it{#bf{2015}}");
		
		
		TLatex *lar2 = new TLatex();

		lar2->SetNDC(kTRUE);
		lar2->SetTextSize(0.04);
		lar2->SetLineWidth(5);
		lar2->SetTextAlign(12);
		lar->DrawLatex(0.14, 0.94, "CMS");
		lar2->DrawLatex(0.25, 0.94, "#it{#bf{Preliminary}} ");

}
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----                                                                                                
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_PhaseIAged       = gConfigParser -> readStringOption("Input::InputBaseDirectoryPhaseIAged");
  string InputBaseDirectory_PhaseIIShashlik  = gConfigParser -> readStringOption("Input::InputBaseDirectoryPhaseIIShashlik");


  // 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 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;}

  string InputVariableRespList  = gConfigParser -> readStringOption("Input::InputVariableRespList");
  vector<variableContainer> variableRespList;

  if(ReadInputVariableFile(InputVariableRespList,variableRespList) <= 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)                                                                                                                                 

  string finalStateString    = gConfigParser -> readStringOption("Option::finalStateString");
  float  matchingCone        = gConfigParser -> readFloatOption("Option::matchingCone");
  float  minLeptonCutPt      = gConfigParser -> readFloatOption("Option::minLeptonCutPt");
  float  minJetCutPt         = gConfigParser -> readFloatOption("Option::minJetCutPt");
 

  int   nLeptons   = gConfigParser -> readIntOption("Option::nLeptons");
  float metCut     = gConfigParser -> readFloatOption("Option::metCut");
  float mllCut     = gConfigParser -> readFloatOption("Option::mllCut");
  float mjjCut     = gConfigParser -> readFloatOption("Option::mjjCut");
  float detajjCut  = gConfigParser -> readFloatOption("Option::detajjCut");

  // 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+"/norm").c_str());
  system(("mkdir -p output/"+outputPlotDirectory+"/xs").c_str());

  ///// Start the analysis for phaseI aged detector                                                                                                                          
  // make chain and branches for Aged trees

  TChain* chain_PhaseIAged = new TChain (treeName.c_str()) ;
  chain_PhaseIAged->Add ((InputBaseDirectory_PhaseIAged+"/*.root").c_str()) ;
  int totEvent_PhaseIAged = chain_PhaseIAged->GetEntries();

  TEventInfo   *fEventInfo_PhaseIAged = new TEventInfo(); 
  TClonesArray *fElectron_PhaseIAged = new TClonesArray("baconhep::TElectron");
  TClonesArray *fMuon_PhaseIAged     = new TClonesArray("baconhep::TMuon");
  TClonesArray *fJet_PhaseIAged      = new TClonesArray("baconhep::TJet");
  TClonesArray *fGenParticle_PhaseIAged = new TClonesArray("baconhep::TGenParticle");

  chain_PhaseIAged->SetBranchAddress("Info",&fEventInfo_PhaseIAged);
  chain_PhaseIAged->SetBranchAddress("Electron", &fElectron_PhaseIAged);
  chain_PhaseIAged->SetBranchAddress("Muon", &fMuon_PhaseIAged);
  chain_PhaseIAged->SetBranchAddress("Jet04", &fJet_PhaseIAged);
  chain_PhaseIAged->SetBranchAddress("GenParticle", &fGenParticle_PhaseIAged);

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

  float weight_PhaseIAged = 1.0*lumi*CrossSection/float(totEvent_PhaseIAged) ;

  // make chain and branches for Shashlik trees
    
  TChain* chain_PhaseIIShashlik = new TChain (treeName.c_str()) ;
  chain_PhaseIIShashlik->Add ((InputBaseDirectory_PhaseIIShashlik+"/*.root").c_str()) ;
  int totEvent_PhaseIIShashlik = chain_PhaseIIShashlik->GetEntries();

  TClonesArray *fElectron_PhaseIIShashlik  = new TClonesArray("baconhep::TElectron");
  TClonesArray *fMuon_PhaseIIShashlik      = new TClonesArray("baconhep::TMuon");
  TClonesArray *fJet_PhaseIIShashlik       = new TClonesArray("baconhep::TJet");
  TClonesArray *fGenParticle_PhaseIIShashlik  = new TClonesArray("baconhep::TGenParticle");
  TEventInfo   *fEventInfo_PhaseIIShashlik = new TEventInfo(); 

  chain_PhaseIIShashlik ->SetBranchAddress("Electron", &fElectron_PhaseIIShashlik);
  chain_PhaseIIShashlik ->SetBranchAddress("Muon", &fMuon_PhaseIIShashlik);
  chain_PhaseIIShashlik ->SetBranchAddress("Jet04", &fJet_PhaseIIShashlik);
  chain_PhaseIIShashlik ->SetBranchAddress("GenParticle", &fGenParticle_PhaseIIShashlik);
  chain_PhaseIIShashlik->SetBranchAddress("Info",&fEventInfo_PhaseIIShashlik);

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

  float weight_PhaseIIShashlik = 1.0*lumi*CrossSection/float(totEvent_PhaseIIShashlik) ;

  TH1::SetDefaultSumw2();

  // Efficiency histograms
  map<string,TH1F*> histoCutEff_PhaseIAged ;
  map<string,TH1F*> histoCutEff_PhaseIIShashlik ;

  vector<histoContainer> plotVector_PhaseIAged;
  vector<histoContainer> plotVector_PhaseIIShashlik;
  vector<histoContainer> plotVector_Gen;

  vector<histoContainer> plotResponse_PhaseIAged;
  vector<histoContainer> plotResponse_PhaseIIShashlik;

  histoCutEff_PhaseIAged["PhaseIAged"]           = new TH1F("PhaseIAged","",9,0,9);
  histoCutEff_PhaseIIShashlik["PhaseIIShashlik"] = new TH1F("PhaseIIShashlik","",9,0,9);

  for(size_t iVar = 0; iVar < variableList.size(); iVar++){
    plotVector_PhaseIAged.push_back(histoContainer("PhaseIAged",variableList.at(iVar)));
    plotVector_Gen.push_back(histoContainer("Gen",variableList.at(iVar)));
    plotVector_PhaseIIShashlik.push_back(histoContainer("PhaseIIShashlik",variableList.at(iVar)));
  }

  for(size_t iVar = 0; iVar < variableRespList.size(); iVar++){
    plotResponse_PhaseIAged.push_back(histoContainer("PhaseIAgedResponse",variableRespList.at(iVar)));
    plotResponse_PhaseIIShashlik.push_back(histoContainer("PhaseIIShashlikResponse",variableRespList.at(iVar)));
  }

  int maximumEvents_PhaseIAged = chain_PhaseIAged->GetEntries () ;
  if (maxEventNumber > 0 && maxEventNumber < maximumEvents_PhaseIAged)
    maximumEvents_PhaseIAged = maxEventNumber ;

  int maximumEvents_PhaseIIShashlik = chain_PhaseIIShashlik->GetEntries () ;
  if (maxEventNumber > 0 && maxEventNumber < maximumEvents_PhaseIIShashlik)
    maximumEvents_PhaseIIShashlik = maxEventNumber ;


  // Loop on aged events
  for(int iEvent = 0; iEvent < maximumEvents_PhaseIAged ; iEvent++){
    
    if (iEvent % 10000 == 0) cout << "reading event " << iEvent << "\n" ;
    string name = "PhaseIAged";
    
    chain_PhaseIAged->GetEntry(iEvent);

    // TElectron and TMuon are all the reco lepton to be used in the analysis --> apply some basic ID cuts
    vector<TMuon> goodTightMuons ;
    vector<TElectron> goodTightElectrons ;

    if((fMuon_PhaseIAged->GetEntriesFast()+fElectron_PhaseIAged->GetEntriesFast()) < nLeptons) continue;
    if((fJet_PhaseIAged->GetEntriesFast()) < 2) continue;

    // look for tight muons and electrons in the event

    for(int iEle = 0; iEle < fElectron_PhaseIAged->GetEntriesFast(); iEle++){
      TElectron *ele = (TElectron*)((*fElectron_PhaseIAged)[iEle]);
      if(ele->pt < minLeptonCutPt) continue;
      if(fabs(ele->eta) > 2.5) continue;
      if(passEleID(ele,fEventInfo_PhaseIAged->rhoIso))
	 goodTightElectrons.push_back(*ele);
    }

    for(int iMu = 0; iMu < fMuon_PhaseIAged->GetEntriesFast(); iMu++){
      TMuon *mu = (TMuon*)((*fMuon_PhaseIAged)[iMu]);
      if(mu->pt < minLeptonCutPt) continue;
      if(fabs(mu->eta) > 2.5) continue;
      if(passMuonID(mu,fEventInfo_PhaseIAged->rhoIso))
	 goodTightMuons.push_back(*mu);
    }

    // sort in pt
    sort(goodTightMuons.rbegin(),goodTightMuons.rend());
    sort(goodTightElectrons.rbegin(),goodTightElectrons.rend());

    // apply a cut on the number of tight leptons and final state topology
    if(int(goodTightElectrons.size()+goodTightMuons.size()) < nLeptons) continue;

    int iBin = 1;
    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"NLep tight");
      iBin++;
    }

    // select final state topology    
    if(TString(finalStateString).Contains("UU")){
      if(goodTightMuons.size() !=2 or goodTightElectrons.size() != 0) continue;
    }
    else if(TString(finalStateString).Contains("EE")){
      if(goodTightElectrons.size() !=2 or goodTightMuons.size() != 0) continue;
    }
    else continue;

    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"flavour selection");
      iBin++;
    }

    // charge : same sign
    if(TString(finalStateString).Contains("UU")){
      if(goodTightMuons.at(0).q != goodTightMuons.at(1).q) continue;
    }
    else if(TString(finalStateString).Contains("EE")){
      if(goodTightElectrons.at(0).q != goodTightElectrons.at(1).q) continue;
    }
    else continue;

    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"same sign");
      iBin++;
    }

    // met cut
    if(fEventInfo_PhaseIAged->pfMETC < metCut) continue;

    TLorentzVector met ; met.SetPtEtaPhiM(fEventInfo_PhaseIAged->pfMETC,0.,fEventInfo_PhaseIAged->pfMETCphi,0.);

    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"met cut");
      iBin++;
    }

    // mll cut
    TLorentzVector lepton1, lepton2;
    if(TString(finalStateString).Contains("UU")){
      lepton1.SetPtEtaPhiM(goodTightMuons.at(0).pt,goodTightMuons.at(0).eta,goodTightMuons.at(0).phi,0.);
      lepton2.SetPtEtaPhiM(goodTightMuons.at(1).pt,goodTightMuons.at(1).eta,goodTightMuons.at(1).phi,0.);
    }
    else if(TString(finalStateString).Contains("EE")){
      lepton1.SetPtEtaPhiM(goodTightElectrons.at(0).pt,goodTightElectrons.at(0).eta,goodTightElectrons.at(0).phi,0.);
      lepton2.SetPtEtaPhiM(goodTightElectrons.at(1).pt,goodTightElectrons.at(1).eta,goodTightElectrons.at(1).phi,0.);
    }

    if((lepton1+lepton2).M() < mllCut) continue;

    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"mll cut");
      iBin++;
    }


    // matching with generator level leptons : find gen muons and gene ele from W decay
    vector<int> genEleIndex ;
    vector<int> genMuIndex ;
    findGenLeptonsFromW(fGenParticle_PhaseIAged,genEleIndex,genMuIndex);

    vector<TGenParticle> genMatchedMuons;
    vector<TGenParticle> genMatchedElectrons;
    vector<TGenParticle> genNeutrino;
    
    findGenNeutrinoFromW(fGenParticle_PhaseIAged,genNeutrino);

    for(size_t iMu = 0; iMu < goodTightMuons.size(); iMu++){
      TMuon mu = goodTightMuons.at(iMu);
      TLorentzVector mu4V;
      mu4V.SetPtEtaPhiM(mu.pt,mu.eta,mu.phi,0.);
      // Match with genParticle	
      for( vector<int>::iterator iGen = genMuIndex.begin(); iGen != genMuIndex.end(); ++iGen ) {
	TGenParticle *genP = (TGenParticle*)((*fGenParticle_PhaseIAged)[*iGen]); 
	TLorentzVector gen4V;
	gen4V.SetPtEtaPhiM(genP->pt,genP->eta,genP->phi,0.);
	if(mu4V.DeltaR(gen4V) < matchingCone){
	  genMatchedMuons.push_back(*genP);
	  break;
	}
      }
    }
   
    for(size_t iEle = 0; iEle < goodTightElectrons.size(); iEle++){
      TElectron ele = goodTightElectrons.at(iEle);
      TLorentzVector ele4V;
      ele4V.SetPtEtaPhiM(ele.pt,ele.eta,ele.phi,0.);
      // Match with genParticle	
      for( vector<int>::iterator iGen = genEleIndex.begin(); iGen != genEleIndex.end(); ++iGen ) {
	TGenParticle *genP = (TGenParticle*)((*fGenParticle_PhaseIAged)[*iGen]); 
	TLorentzVector gen4V;
	gen4V.SetPtEtaPhiM(genP->pt,genP->eta,genP->phi,0.);
	if(ele4V.DeltaR(gen4V) < matchingCone){
	  genMatchedElectrons.push_back(*genP);
	  break;
	}
      }
    }
   
    if (int(genMatchedElectrons.size() + genMatchedMuons.size()) != nLeptons) continue;

    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"mathcing gen lepton");
      iBin++;
    }

    TLorentzVector genLep1, genLep2;
    if(TString(finalStateString).Contains("UU")){
      genLep1.SetPtEtaPhiM(genMatchedMuons.at(0).pt,genMatchedMuons.at(0).eta,genMatchedMuons.at(0).phi,0.);
      genLep2.SetPtEtaPhiM(genMatchedMuons.at(1).pt,genMatchedMuons.at(1).eta,genMatchedMuons.at(1).phi,0.);
    }
    else if(TString(finalStateString).Contains("EE")){
      genLep1.SetPtEtaPhiM(genMatchedElectrons.at(0).pt,genMatchedElectrons.at(0).eta,genMatchedElectrons.at(0).phi,0.);
      genLep2.SetPtEtaPhiM(genMatchedElectrons.at(1).pt,genMatchedElectrons.at(1).eta,genMatchedElectrons.at(1).phi,0.);
    }


    TLorentzVector genMet ;
    for(size_t iNu = 0; iNu < genNeutrino.size(); iNu++){
      TLorentzVector tmp4V;
      tmp4V.SetPtEtaPhiM(genNeutrino.at(iNu).pt,0.,genNeutrino.at(iNu).phi,0.);
      genMet += tmp4V ;
    }

    // look for jets cleaning leptons
    vector<TJet> cleanedJets;    
    cleanedJetsFromLeptons(cleanedJets,*fJet_PhaseIAged,goodTightMuons,goodTightElectrons,minJetCutPt,matchingCone);
    sort(cleanedJets.rbegin(),cleanedJets.rend());
    if(cleanedJets.size() < 2) continue;
    
    TLorentzVector jet1, jet2, dijet ;
    jet1.SetPtEtaPhiM(cleanedJets.at(0).pt,cleanedJets.at(0).eta,cleanedJets.at(0).phi,cleanedJets.at(0).mass);
    jet2.SetPtEtaPhiM(cleanedJets.at(1).pt,cleanedJets.at(1).eta,cleanedJets.at(1).phi,cleanedJets.at(1).mass);

    dijet = jet1+jet2;

    // matching with gen jets by the flag

    if(cleanedJets.at(0).genpt <= 0 and cleanedJets.at(1).genpt <= 0) continue;

    TLorentzVector genjet1, genjet2;
    genjet1.SetPtEtaPhiM(cleanedJets.at(0).genpt,cleanedJets.at(0).geneta,cleanedJets.at(0).genphi,cleanedJets.at(0).genm);
    genjet2.SetPtEtaPhiM(cleanedJets.at(1).genpt,cleanedJets.at(1).geneta,cleanedJets.at(1).genphi,cleanedJets.at(1).genm);

    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"mathcing gen jets after cleaning");
      iBin++;
    }

    if(dijet.M() < mjjCut) continue;
    
    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"mjj cut");
      iBin++;
    }

    if(fabs(jet1.Eta()-jet2.Eta()) < detajjCut) continue;
    
    if(histoCutEff_PhaseIAged.size()!=0){
      histoCutEff_PhaseIAged[name]->SetBinContent(iBin,histoCutEff_PhaseIAged[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIAged[name]->GetXaxis()->SetBinLabel(iBin,"detajj cut");
      iBin++;
    }
    
    // fill histos
    fillHistos(plotVector_PhaseIAged,variableList,name,weight_PhaseIAged,lepton1,lepton2,jet1,jet2,met);
    // fill response
    fillResponse(plotResponse_PhaseIAged,variableRespList,name+"Response",weight_PhaseIAged,lepton1,genLep1,lepton2,genLep2,jet1,genjet1,jet2,genjet2,met,genMet);

  }

  // Loop on shashlik events
  for(int iEvent = 0; iEvent < maximumEvents_PhaseIIShashlik ; iEvent++){
    
    if (iEvent % 10000 == 0) cout << "reading event " << iEvent << "\n" ;
    string name = "PhaseIIShashlik";
    
    chain_PhaseIIShashlik->GetEntry(iEvent);

    // TElectron and TMuon are all the reco lepton to be used in the analysis --> apply some basic ID cuts
    vector<TMuon> goodTightMuons ;
    vector<TElectron> goodTightElectrons ;

    if((fMuon_PhaseIIShashlik->GetEntriesFast()+fElectron_PhaseIIShashlik->GetEntriesFast()) < nLeptons) continue;
    if((fJet_PhaseIIShashlik->GetEntriesFast()) < 2) continue;

    for(int iEle = 0; iEle < fElectron_PhaseIIShashlik->GetEntriesFast(); iEle++){
      TElectron *ele = (TElectron*)((*fElectron_PhaseIIShashlik)[iEle]);
      if(ele->pt < minLeptonCutPt) continue;
      if(fabs(ele->eta) > 2.5) continue;
      if(passEleID(ele,fEventInfo_PhaseIIShashlik->rhoIso))
	 goodTightElectrons.push_back(*ele);
    }

    for(int iMu = 0; iMu < fMuon_PhaseIIShashlik->GetEntriesFast(); iMu++){
      TMuon *mu = (TMuon*)((*fMuon_PhaseIIShashlik)[iMu]);
      if(mu->pt < minLeptonCutPt) continue;
      if(fabs(mu->eta) > 2.5) continue;
      if(passMuonID(mu,fEventInfo_PhaseIIShashlik->rhoIso))
	 goodTightMuons.push_back(*mu);
    }

    sort(goodTightMuons.rbegin(),goodTightMuons.rend());
    sort(goodTightElectrons.rbegin(),goodTightElectrons.rend());

    // apply a cut on the number of tight leptons and final state topology
    if(int(goodTightElectrons.size()+goodTightMuons.size()) < nLeptons) continue;

    int iBin = 1;

    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"NLep tight");
      iBin++;
    }

    // select final state topology    
    if(TString(finalStateString).Contains("UU")){
      if(goodTightMuons.size() !=2 or goodTightElectrons.size() != 0) continue;
    }
    else if(TString(finalStateString).Contains("EE")){
      if(goodTightElectrons.size() !=2 or goodTightMuons.size() != 0) continue;
    }
    else continue;

    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"flavour selection");
      iBin++;
    }

    // charge : same sign
    if(TString(finalStateString).Contains("UU")){
      if(goodTightMuons.at(0).q != goodTightMuons.at(1).q) continue;
    }
    else if(TString(finalStateString).Contains("EE")){
      if(goodTightElectrons.at(0).q != goodTightElectrons.at(1).q) continue;
    }
    else continue;

    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"same sign");
      iBin++;
    }

    // met cut
    if(fEventInfo_PhaseIIShashlik->pfMETC < metCut) continue;

    TLorentzVector met ; met.SetPtEtaPhiM(fEventInfo_PhaseIIShashlik->pfMETC,0.,fEventInfo_PhaseIIShashlik->pfMETCphi,0.);

    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"met cut");
      iBin++;
    }

    // mll cut
    TLorentzVector lepton1, lepton2;
    if(TString(finalStateString).Contains("UU")){
      lepton1.SetPtEtaPhiM(goodTightMuons.at(0).pt,goodTightMuons.at(0).eta,goodTightMuons.at(0).phi,0.);
      lepton2.SetPtEtaPhiM(goodTightMuons.at(1).pt,goodTightMuons.at(1).eta,goodTightMuons.at(1).phi,0.);
    }
    else if(TString(finalStateString).Contains("EE")){
      lepton1.SetPtEtaPhiM(goodTightElectrons.at(0).pt,goodTightElectrons.at(0).eta,goodTightElectrons.at(0).phi,0.);
      lepton2.SetPtEtaPhiM(goodTightElectrons.at(1).pt,goodTightElectrons.at(1).eta,goodTightElectrons.at(1).phi,0.);
    }

    if((lepton1+lepton2).M() < mllCut) continue;

    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"mll cut");
      iBin++;
    }


    // matching with generator level leptons : find gen muons and gene ele from W decay
    vector<int> genEleIndex ;
    vector<int> genMuIndex ;
    findGenLeptonsFromW(fGenParticle_PhaseIIShashlik,genEleIndex,genMuIndex);

    vector<TGenParticle> genMatchedMuons;
    vector<TGenParticle> genMatchedElectrons;
    vector<TGenParticle> genNeutrino;
    
    findGenNeutrinoFromW(fGenParticle_PhaseIIShashlik,genNeutrino);


    for(size_t iMu = 0; iMu < goodTightMuons.size(); iMu++){
      TMuon mu = goodTightMuons.at(iMu);
      TLorentzVector mu4V;
      mu4V.SetPtEtaPhiM(mu.pt,mu.eta,mu.phi,0.);
      // Match with genParticle	
      for( vector<int>::iterator iGen = genMuIndex.begin(); iGen != genMuIndex.end(); ++iGen ) {
	TGenParticle *genP = (TGenParticle*)((*fGenParticle_PhaseIIShashlik)[*iGen]); 
	TLorentzVector gen4V;
	gen4V.SetPtEtaPhiM(genP->pt,genP->eta,genP->phi,0.);
	if(mu4V.DeltaR(gen4V) < matchingCone){
	  genMatchedMuons.push_back(*genP);
	  break;
	}
      }
    }
   
    for(size_t iEle = 0; iEle < goodTightElectrons.size(); iEle++){
      TElectron ele = goodTightElectrons.at(iEle);
      TLorentzVector ele4V;
      ele4V.SetPtEtaPhiM(ele.pt,ele.eta,ele.phi,0.);
      // Match with genParticle	
      for( vector<int>::iterator iGen = genEleIndex.begin(); iGen != genEleIndex.end(); ++iGen ) {
	TGenParticle *genP = (TGenParticle*)((*fGenParticle_PhaseIIShashlik)[*iGen]); 
	TLorentzVector gen4V;
	gen4V.SetPtEtaPhiM(genP->pt,genP->eta,genP->phi,0.);
	if(ele4V.DeltaR(gen4V) < matchingCone){
	  genMatchedElectrons.push_back(*genP);
	  break;
	}
      }
    }
   
    if (int(genMatchedMuons.size()+genMatchedElectrons.size()) != nLeptons) continue;

    TLorentzVector genLep1, genLep2;
    if(TString(finalStateString).Contains("UU")){
      genLep1.SetPtEtaPhiM(genMatchedMuons.at(0).pt,genMatchedMuons.at(0).eta,genMatchedMuons.at(0).phi,0.);
      genLep2.SetPtEtaPhiM(genMatchedMuons.at(1).pt,genMatchedMuons.at(1).eta,genMatchedMuons.at(1).phi,0.);
    }
    else if(TString(finalStateString).Contains("EE")){
      genLep1.SetPtEtaPhiM(genMatchedElectrons.at(0).pt,genMatchedElectrons.at(0).eta,genMatchedElectrons.at(0).phi,0.);
      genLep2.SetPtEtaPhiM(genMatchedElectrons.at(1).pt,genMatchedElectrons.at(1).eta,genMatchedElectrons.at(1).phi,0.);
    }

    

    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"mathcing gen lepton");
      iBin++;
    }

    // look for jets cleaning leptons
    vector<TJet> cleanedJets;    
    cleanedJetsFromLeptons(cleanedJets,*fJet_PhaseIIShashlik,goodTightMuons,goodTightElectrons,minJetCutPt,matchingCone);
    sort(cleanedJets.rbegin(),cleanedJets.rend());
    if(cleanedJets.size() < 2) continue;
    
    TLorentzVector jet1, jet2, dijet ;
    jet1.SetPtEtaPhiM(cleanedJets.at(0).pt,cleanedJets.at(0).eta,cleanedJets.at(0).phi,cleanedJets.at(0).mass);
    jet2.SetPtEtaPhiM(cleanedJets.at(1).pt,cleanedJets.at(1).eta,cleanedJets.at(1).phi,cleanedJets.at(1).mass);


    dijet = jet1+jet2;

    // matching with gen jets by the flag

    if(cleanedJets.at(0).genpt <= 0 and cleanedJets.at(1).genpt <= 0) continue;

    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"mathcing gen jets after cleaning");
      iBin++;
    }

    if(dijet.M() < mjjCut) continue;
    
    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"mjj cut");
      iBin++;
    }

    if(fabs(jet1.Eta()-jet2.Eta()) < detajjCut) continue;
    
    if(histoCutEff_PhaseIIShashlik.size()!=0){
      histoCutEff_PhaseIIShashlik[name]->SetBinContent(iBin,histoCutEff_PhaseIIShashlik[name]->GetBinContent(iBin)+1);
      histoCutEff_PhaseIIShashlik[name]->GetXaxis()->SetBinLabel(iBin,"detajj cut");
      iBin++;
    }
    
    // fill histos
    fillHistos(plotVector_PhaseIIShashlik,variableList,name,weight_PhaseIIShashlik,lepton1,lepton2,jet1,jet2,met);

    TLorentzVector genMet ;
    for(size_t iNu = 0; iNu < genNeutrino.size(); iNu++){
      TLorentzVector tmp4V;
      tmp4V.SetPtEtaPhiM(genNeutrino.at(iNu).pt,0.,genNeutrino.at(iNu).phi,0.);
      genMet += tmp4V ;
    }

    TLorentzVector genjet1, genjet2;
    genjet1.SetPtEtaPhiM(cleanedJets.at(0).genpt,cleanedJets.at(0).geneta,cleanedJets.at(0).genphi,cleanedJets.at(0).genm);
    genjet2.SetPtEtaPhiM(cleanedJets.at(1).genpt,cleanedJets.at(1).geneta,cleanedJets.at(1).genphi,cleanedJets.at(1).genm);


    fillHistos(plotVector_Gen,variableList,"Gen",1,genLep1,genLep2,genjet1,genjet2,genMet);

    fillResponse(plotResponse_PhaseIIShashlik,variableRespList,name+"Response",weight_PhaseIIShashlik,lepton1,genLep1,lepton2,genLep2,jet1,genjet1,jet2,genjet2,met,genMet);


  }


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

  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,"CMS");
  tex2->SetNDC();
  tex2->SetTextFont(61);
  tex2->SetTextSize(0.045);
  tex2->SetLineWidth(2);
  TLatex * tex3 = new TLatex(0.28,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);

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

  for(map<string,TH1F*>::const_iterator itMap = histoCutEff_PhaseIAged.begin(); itMap !=  histoCutEff_PhaseIAged.end(); itMap++){
    itMap->second->Scale(1./(maximumEvents_PhaseIAged));
    itMap->second->GetYaxis()->SetRangeUser(0.,itMap->second->GetMaximum()*1.3);
    itMap->second->Draw("hist");    
    itMap->second->SetLineColor(kBlue);
    itMap->second->SetLineWidth(2);
    itMap->second->GetYaxis()->SetTitle("Efficiency");
    itMap->second->GetYaxis()->SetTitleOffset(1.15);
    legend->AddEntry(itMap->second,"Aged efficiency","l");
    itMap->second->Write();
  }

  for(map<string,TH1F*>::const_iterator itMap = histoCutEff_PhaseIIShashlik.begin(); itMap !=  histoCutEff_PhaseIIShashlik.end(); itMap++){
    itMap->second->Scale(1./(maximumEvents_PhaseIIShashlik));
    legend->AddEntry(itMap->second,"Shashlik efficiency","l");
    itMap->second->Draw("hist same");
    itMap->second->SetLineColor(kRed);
    itMap->second->SetLineWidth(2);
    itMap->second->SetLineStyle(7);
    itMap->second->Write();
  }

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

  cCanvas->SaveAs(("output/"+outputPlotDirectory+"/efficiency.png").c_str(),"png");  
  cCanvas->SaveAs(("output/"+outputPlotDirectory+"/efficiency.pdf").c_str(),"pdf");  

  cCanvas->SetLogy(1);

  cCanvas->SaveAs(("output/"+outputPlotDirectory+"/efficiency_log.png").c_str(),"png");  
  cCanvas->SaveAs(("output/"+outputPlotDirectory+"/efficiency_log.pdf").c_str(),"pdf");  

  cCanvas->SetLogy(0);

  legend->Clear();

  outputEfficiency->Close();


  // make the plot on the same canvas for each variable (legend entry is the cut layer name)                                                                                   
  for(size_t iVar = 0; iVar < variableList.size(); iVar++){ // loop on var                                                                                                     
    histoContainer tmpPlot_PhaseIAged;
    tmpPlot_PhaseIAged.cutName = "PhaseIAged";
    tmpPlot_PhaseIAged.varName = variableList.at(iVar).variableName;
    vector<histoContainer>::iterator itVec_PhaseIAged ;
    itVec_PhaseIAged = find(plotVector_PhaseIAged.begin(),plotVector_PhaseIAged.end(),tmpPlot_PhaseIAged);
    if(itVec_PhaseIAged == plotVector_PhaseIAged.end()){
      cerr<<"Problem -->plot not found for PhaseI_Aged  "<<variableList.at(iVar).variableName<<endl;
    }

    itVec_PhaseIAged->histogram->GetXaxis()->SetTitleSize(0.04);
    itVec_PhaseIAged->histogram->GetXaxis()->SetTitleOffset(1.25);
    itVec_PhaseIAged->histogram->GetXaxis()->SetLabelSize(0.04);

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

    itVec_PhaseIAged->histogram->SetLineColor(kBlue);

    itVec_PhaseIAged->histogram->SetLineWidth(2);
    itVec_PhaseIAged->histogram->GetYaxis()->SetTitleOffset(1.1);

    itVec_PhaseIAged->histogram->GetYaxis()->SetTitle("#sigma x lumi");

    legend->AddEntry(itVec_PhaseIAged->histogram,"Phase I Aged","l");


    histoContainer tmpPlot_PhaseIIShashlik;
    tmpPlot_PhaseIIShashlik.cutName = "PhaseIIShashlik";
    tmpPlot_PhaseIIShashlik.varName = variableList.at(iVar).variableName;
    vector<histoContainer>::iterator itVec_PhaseIIShashlik ;
    itVec_PhaseIIShashlik = find(plotVector_PhaseIIShashlik.begin(),plotVector_PhaseIIShashlik.end(),tmpPlot_PhaseIIShashlik);
    if(itVec_PhaseIIShashlik == plotVector_PhaseIIShashlik.end()){
      cerr<<"Problem -->plot not found for PhaseII_Shashlik  "<<variableList.at(iVar).variableName<<endl;
    }

    histoContainer tmpPlot_Gen;
    tmpPlot_Gen.cutName = "Gen";
    tmpPlot_Gen.varName = variableList.at(iVar).variableName;
    vector<histoContainer>::iterator itVec_Gen ;
    itVec_Gen = find(plotVector_Gen.begin(),plotVector_Gen.end(),tmpPlot_Gen);
    if(itVec_Gen == plotVector_Gen.end()){
      cerr<<"Problem -->plot not found for Gen  "<<variableList.at(iVar).variableName<<endl;
    }


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

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

    itVec_PhaseIIShashlik->histogram->SetLineColor(kRed);

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

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.001,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*1.3);

    itVec_PhaseIAged->histogram->Draw("hist");
    itVec_PhaseIIShashlik->histogram->Draw("hist same");
    legend->AddEntry(itVec_PhaseIIShashlik->histogram,"Phase II Shashlik","l");

    itVec_Gen->histogram->SetLineColor(kGreen+1);
    itVec_Gen->histogram->SetLineWidth(2);

    legend->Draw("same");
    tex->Draw("same");
    tex2->Draw("same");
    tex3->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->SetLogy(1);

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.1,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*100);

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

    itVec_PhaseIAged->histogram->Scale(1./itVec_PhaseIAged->histogram->Integral());
    itVec_PhaseIIShashlik->histogram->Scale(1./itVec_PhaseIIShashlik->histogram->Integral());
    itVec_Gen->histogram->Scale(1./itVec_Gen->histogram->Integral());

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.001,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*1.3);

    itVec_PhaseIAged->histogram->GetYaxis()->SetTitle("a.u.");

    itVec_PhaseIAged->histogram->Draw("hist");
    itVec_PhaseIIShashlik->histogram->Draw("hist same");
    itVec_Gen->histogram->Draw("hist same");
    

    legend->AddEntry(itVec_Gen->histogram,"gen level","l");

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

    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_norm.pdf").c_str(),"pdf");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_norm.png").c_str(),"png");
    cCanvas->SetLogy(1);

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.01,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*100);

    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_norm_log.pdf").c_str(),"pdf");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_norm_log.png").c_str(),"png");
    cCanvas->SetLogy(0);

    legend->Clear();

  }  




  // make the plot on the same canvas for each variable (legend entry is the cut layer name)                                                                                   
  for(size_t iVar = 0; iVar < variableRespList.size(); iVar++){ // loop on var                                                                                                
    histoContainer tmpPlot_PhaseIAged;
    tmpPlot_PhaseIAged.cutName = "PhaseIAgedResponse";
    tmpPlot_PhaseIAged.varName = variableRespList.at(iVar).variableName;
    vector<histoContainer>::iterator itVec_PhaseIAged ;
    itVec_PhaseIAged = find(plotResponse_PhaseIAged.begin(),plotResponse_PhaseIAged.end(),tmpPlot_PhaseIAged);
    if(itVec_PhaseIAged == plotResponse_PhaseIAged.end()){
      cerr<<"Problem -->plot not found for PhaseI_Aged  "<<variableRespList.at(iVar).variableName<<endl;
    }

    itVec_PhaseIAged->histogram->GetXaxis()->SetTitleSize(0.04);
    itVec_PhaseIAged->histogram->GetXaxis()->SetTitleOffset(1.25);
    itVec_PhaseIAged->histogram->GetXaxis()->SetLabelSize(0.04);

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

    itVec_PhaseIAged->histogram->SetLineColor(kBlue);

    itVec_PhaseIAged->histogram->SetLineWidth(2);
    itVec_PhaseIAged->histogram->GetYaxis()->SetTitleOffset(1.1);

    itVec_PhaseIAged->histogram->GetYaxis()->SetTitle("#sigma x lumi");

    legend->AddEntry(itVec_PhaseIAged->histogram,"Phase I Aged","l");


    histoContainer tmpPlot_PhaseIIShashlik;
    tmpPlot_PhaseIIShashlik.cutName = "PhaseIIShashlikResponse";
    tmpPlot_PhaseIIShashlik.varName = variableRespList.at(iVar).variableName;
    vector<histoContainer>::iterator itVec_PhaseIIShashlik ;
    itVec_PhaseIIShashlik = find(plotResponse_PhaseIIShashlik.begin(),plotResponse_PhaseIIShashlik.end(),tmpPlot_PhaseIIShashlik);
    if(itVec_PhaseIIShashlik == plotResponse_PhaseIIShashlik.end()){
      cerr<<"Problem -->plot not found for PhaseII_Shashlik  "<<variableRespList.at(iVar).variableName<<endl;
    }


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

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

    itVec_PhaseIIShashlik->histogram->SetLineColor(kRed);

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

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.001,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*1.3);

    itVec_PhaseIAged->histogram->Draw("hist");
    itVec_PhaseIIShashlik->histogram->Draw("hist same");
    legend->AddEntry(itVec_PhaseIIShashlik->histogram,"Phase II Shashlik"," l");

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

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

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.1,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*100);

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

    itVec_PhaseIAged->histogram->Scale(1./itVec_PhaseIAged->histogram->Integral());
    itVec_PhaseIIShashlik->histogram->Scale(1./itVec_PhaseIIShashlik->histogram->Integral());

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.001,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*1.3);

    itVec_PhaseIAged->histogram->GetYaxis()->SetTitle("a.u.");

    itVec_PhaseIAged->histogram->Draw("hist");
    itVec_PhaseIIShashlik->histogram->Draw("hist same");
    

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

    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_resp_norm.pdf").c_str(),"pdf");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_resp_norm.png").c_str(),"png");
    cCanvas->SetLogy(1);

    itVec_PhaseIAged->histogram->GetYaxis()->SetRangeUser(0.01,max(itVec_PhaseIAged->histogram->GetMaximum(),itVec_PhaseIIShashlik->histogram->GetMaximum())*100);

    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_resp_norm_log.pdf").c_str(),"pdf");
    cCanvas->SaveAs(string("output/"+outputPlotDirectory+"/norm/"+variableList.at(iVar).variableName+"_resp_norm_log.png").c_str(),"png");
    cCanvas->SetLogy(0);

    legend->Clear();

  }  
  
 return 0 ;

}
Example #21
0
void dumpComparePDF(std::string inputFile1_,std::string inputFile2_,bool normalize=true)
{

  TString endfix1=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; echo \"${test%%.root}\"",inputFile1_.data()));

  cout << endfix1 << endl;

  TString endfix2=gSystem->GetFromPipe(Form("file=%s; test=${file##*/}; echo \"${test%%.root}\"",inputFile2_.data()));


  cout << endfix2 << endl;

  TLegend* leg = new TLegend(0.3333,0.7027,0.8333,0.9023);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.04);
  leg->SetBorderSize(0);

  std::string dirName = "fig";
  gSystem->mkdir(dirName.data());

  std::string outputFileName=Form("%s/%s_%s.pdf",dirName.data(),
				  endfix1.Data(),
				  endfix2.Data());

  TCanvas* c1 = new TCanvas("c1","",500,500);

  TFile *_file1 = TFile::Open(inputFile1_.data());
  TFile *_file2 = TFile::Open(inputFile2_.data());
  _file1->cd();

  TDirectory *current_sourcedir = gDirectory;
  int nPage=0;
  // loop over all keys in this directory
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key;
  while ((key = (TKey*)nextkey()) ) {

    TObject *obj = key->ReadObj();
    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // descendant of TH1 -> scale it

      cout << "outputing histogram " << obj->GetName() << endl;
      TH1 *h1 = (TH1*)_file1->FindObjectAny(obj->GetName());
      h1->SetMarkerStyle(8);
      h1->SetMarkerSize(1);
      h1->SetLineWidth(3);
      h1->SetLineColor(4);

      TH1 *h2 = (TH1*)_file2->FindObjectAny(obj->GetName());
      h2->SetMarkerStyle(25);
      h2->SetMarkerSize(1);
      h2->SetLineWidth(3);
      h2->SetLineColor(2);
			 			 
      gStyle->SetOptStat(0);
      h1->Sumw2();
      h2->Sumw2();
      if(normalize)
	{
	  h1->Scale(1.0/h1->Integral());
	  h2->Scale(1.0/h2->Integral());
	}

      float max = h1->GetMaximum()>h2->GetMaximum()?
	h1->GetMaximum():h2->GetMaximum();

      h1->SetMaximum(1.1*max);
      h2->SetMaximum(1.1*max);

      double chi2=0.;
      int nbins=0;
      chi2NbinsCompare(h1,h2,chi2,nbins,1,h1->GetNbinsX());

      h1->Draw("hist");
      h2->Draw("histsame");

      leg->Clear();
      leg->SetHeader("");
      leg->AddEntry((TObject*)0, Form("#chi^{2}/NDF=%.1f/%d",chi2,nbins), "");
      leg->AddEntry((TObject*)0, Form("#chi^{2} Prob=%.2f",TMath::Prob(chi2,nbins)), "");
      leg->AddEntry((TObject*)0, "", "");
      leg->AddEntry(h1,endfix1.Data(),"l");
      leg->AddEntry(h2,endfix2.Data(),"l");
      leg->Draw("same");

      if(nPage==0)
	c1->Print(Form("%s(",outputFileName.data()),"pdf");
      else 
	c1->Print(Form("%s",outputFileName.data()),"pdf");
      nPage++;
    } // if the object is a histogram


  } // loop over keys

  c1->Print(Form("%s)",outputFileName.data()),"pdf");
    


}
Example #22
0
void PlotKFactor() {

  TFile *EffFile = new TFile("JetVetoEfficiencySystematics.root", "UPDATE");

  TCanvas *cv = 0;
  cv = new TCanvas("cv","cv", 800,600);
  TLegend *tmpLegend = new TLegend(0.23,0.55,0.43,0.70);   
  tmpLegend->SetTextSize(0.03);
  tmpLegend->SetBorderSize(1);


  TH1D* PowhegKFactor160 = (TH1D*)EffFile->Get("kFactorHiggsPt_ggHww160_PowhegToNNLL");
  TH1D* MCAtNLOKFactor160 = (TH1D*)EffFile->Get("kFactorHiggsPt_ggHww160_MCAtNLOToNNLL");
  tmpLegend->Clear();
  tmpLegend->AddEntry(PowhegKFactor160, "Powheg", "LP");   
  tmpLegend->AddEntry(MCAtNLOKFactor160, "MC@NLO", "LP");   


  MCAtNLOKFactor160->SetLineColor(kBlack);
  MCAtNLOKFactor160->Draw("hist");
  MCAtNLOKFactor160->GetYaxis()->SetTitleOffset(1.2);
  MCAtNLOKFactor160->GetYaxis()->SetTitle("KFactor");
  MCAtNLOKFactor160->GetXaxis()->SetTitleOffset(1.05);
  MCAtNLOKFactor160->GetYaxis()->SetRangeUser(0.3,3.2);

  PowhegKFactor160->SetLineColor(kRed);
  PowhegKFactor160->Draw("hist,same");
  tmpLegend->Draw();
  cv->SaveAs("KFactorPowhegVsMCAtNLO.gif");




//   TH1D* KFactor160 = (TH1D*)EffFile->Get("kFactorHiggsPt_ggHww160_PowhegToNNLL");
//   TH1D* KFactor200 = (TH1D*)EffFile->Get("kFactorHiggsPt_ggHww200_PowhegToNNLL");
//   TH1D* KFactor250 = (TH1D*)EffFile->Get("kFactorHiggsPt_ggHww250_PowhegToNNLL");

//   TCanvas *cv = new TCanvas("cv","cv", 800,600);

//   TLegend *tmpLegend = new TLegend(0.73,0.55,0.93,0.70);   
//   tmpLegend->SetTextSize(0.03);
//   tmpLegend->SetBorderSize(1);
//   tmpLegend->AddEntry(KFactor160, "m_{H} = 160", "LP");   
//   tmpLegend->AddEntry(KFactor200, "m_{H} = 200", "LP");   
//   tmpLegend->AddEntry(KFactor250, "m_{H} = 250", "LP");   

//   KFactor160->SetLineColor(kBlack);
//   KFactor160->Draw("hist");
//   KFactor160->GetYaxis()->SetTitleOffset(1.2);
//   KFactor160->GetYaxis()->SetTitle("KFactor");
//   KFactor160->GetXaxis()->SetTitleOffset(1.05);
//   KFactor200->SetLineColor(kRed);
//   KFactor200->Draw("hist,same");
//   KFactor250->SetLineColor(kBlue);
//   KFactor250->Draw("hist,same");
//   tmpLegend->Draw();
//   cv->SaveAs("KFactorVsMass.gif");


 
}
Example #23
0
void tauStudy(const TString conf="new.conf") {

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

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

  confParse(conf, sampleNames, sampleTitles, sampleColors);

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

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

  TH1D *hPt[nSamples];

  char hname[100];

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

  Double_t jetCorr1Pt, jetCorr2Pt;

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

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

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

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

  }

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

  TFile *infile;
  TTree *intree;

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

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

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

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

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

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

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

      }

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

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

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

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

      }

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

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

  } // end sample loop

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

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

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

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

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

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

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

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

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

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

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

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

  //leg->Draw();
  c->SaveAs(TString(pname)+TString(".png"));
}
Example #24
0
//---------------------------------------------------------------------------------------------------
void analyse(const char* directoryName, int chipId)
{
//--- initialize internal data-structures	
  initialize();

//--- read last DAC temperature information used as "training" data
  load(directoryName, chipId);

//--- prepare output graphs

  for ( Int_t itemprange = 0; itemprange < numTempRanges; itemprange++ ){
    TGraph* graph = gADCgraph_Measurement[chipId][itemprange];

    Int_t numPoints = 0;
    for ( Int_t itemperature = 0; itemperature < numTemperatures; itemperature++ ){
      Double_t adcValue   = gADCvalue_Measurement[chipId][itemprange][itemperature];
      Double_t blackLevel = gADCvalue_blackLevel[chipId][itemperature];
//--- only include measurements that correspond to a positive voltage difference
//    (i.e. have an ADC value above the black level)
//    and are within the amplification linear range, below the amplifier saturation
      if ( adcValue > minADCvalue_graph && adcValue < maxADCvalue_graph ){
	graph->SetPoint(numPoints, temperatureValues_target[itemperature], adcValue);
	numPoints++;
      }
    }
  }

  for ( Int_t itemprange = 0; itemprange < numTempRanges; itemprange++ ){
    TGraph* graph = gADCgraph_Calibration[chipId][itemprange];

    Int_t numPoints = 0;
    for ( Int_t itemperature = 0; itemperature < numTemperatures; itemperature++ ){
      Double_t adcValue   = gADCvalue_Calibration[chipId][itemprange][itemperature];
      Double_t blackLevel = gADCvalue_blackLevel[chipId][itemperature];
      //--- only include measurements that correspond to a positive voltage difference
      //    (i.e. have an ADC value above the black level)
      //    and are within the amplification linear range, below the amplifier saturation
      if ( adcValue > minADCvalue_graph && adcValue < maxADCvalue_graph ){
	graph->SetPoint(numPoints, temperatureValues_target[itemperature], adcValue);
	numPoints++;
      }
    }
  }


//--- initialise dummy histogram
//    (neccessary for drawing graphs)
  TH1F* dummyHistogram = new TH1F("dummyHistogram", "dummyHistogram", numTemperatures, temperatureValues_target[0] - 1, temperatureValues_target[numTemperatures - 1] + 1);
  dummyHistogram->SetTitle("");
  dummyHistogram->SetStats(false);
//   dummyHistogram->GetXaxis()->SetTitle("T / degrees");
  dummyHistogram->GetXaxis()->SetTitleOffset(1.2);
//   dummyHistogram->GetYaxis()->SetTitle("ADC");
  dummyHistogram->GetYaxis()->SetTitleOffset(1.3);
  dummyHistogram->SetMaximum(1.25*maxADCvalue_graph);

//--- prepare graph showing range in which the temperature has been measured
//    and the precision of the cooling-box of reaching the temperature setting
    dummyHistogram->GetXaxis()->SetTitle("T/C    ");
    dummyHistogram->GetXaxis()->SetTitleOffset(0.5);
    dummyHistogram->GetXaxis()->SetTitleSize(0.06);
//   dummyHistogram->GetYaxis()->SetTitle("T_{actual} / degrees");
  dummyHistogram->SetMinimum(minADCvalue_graph);
  dummyHistogram->SetMaximum(maxADCvalue_graph);

//--- draw output graphs
  TLegend* legendTempRanges = new TLegend(0.13, 0.47, 0.68, 0.87, NULL, "brNDC");
  legendTempRanges->SetFillColor(10);
  legendTempRanges->SetLineColor(10);

  c1->cd(14);
  //  TString title = Form("ADC Measurement for ROC%i", chipId);
  //  dummyHistogram->SetTitle(title);
  legendTempRanges->Clear();
  Int_t numGraphs = 0;
  for ( Int_t itemprange = 0; itemprange < numTempRanges; itemprange++ ){
    if ( gADCgraph_Measurement[chipId][itemprange]->GetN() >= 2 ){
      if ( numGraphs == 0 ) dummyHistogram->Draw();
      gADCgraph_Measurement[chipId][itemprange]->SetLineColor((itemprange % 8) + 1);
      gADCgraph_Measurement[chipId][itemprange]->SetLineStyle((itemprange / 8) + 1);
      gADCgraph_Measurement[chipId][itemprange]->SetLineWidth(2);
      gADCgraph_Measurement[chipId][itemprange]->Draw("L");
      numGraphs++;
      TString label = Form("Vref = %3.2f", vReference[itemprange]);
      legendTempRanges->AddEntry(gADCgraph_Measurement[chipId][itemprange], label, "l");
    }
  }
   
  tl->DrawLatex(0.12, 0.92, "ADC Measurement"); 
   if ( numGraphs > 0 ){
     legendTempRanges->Draw();
    
//     gCanvas->Update();
//     gPostScript->NewPage();
   }
  
  
  c1->cd(15);
//   TString title = Form("ADC Calibration for ROC%i", chipId);
//   dummyHistogram->SetTitle(title);
  legendTempRanges->Clear();
  Int_t numGraphs = 0;
  for ( Int_t itemprange = 0; itemprange < numTempRanges; itemprange++ ){
    if ( gADCgraph_Calibration[chipId][itemprange]->GetN() >= 2 ){
      if ( numGraphs == 0 ) dummyHistogram->Draw();
      gADCgraph_Calibration[chipId][itemprange]->SetLineColor((itemprange % 8) + 1);
      gADCgraph_Calibration[chipId][itemprange]->SetLineStyle((itemprange / 8) + 1);
      gADCgraph_Calibration[chipId][itemprange]->SetLineWidth(2);
      gADCgraph_Calibration[chipId][itemprange]->Draw("L");
      numGraphs++;
      TString label = Form("Vref = %3.2f", vReference[itemprange]);
      legendTempRanges->AddEntry(gADCgraph_Calibration[chipId][itemprange], label, "l");
    }
  }
 
  tl->DrawLatex(0.12, 0.92, "ADC Calibration");   
   if ( numGraphs > 0 ){
     legendTempRanges->Draw();
    
//     gCanvas->Update();
//     gPostScript->NewPage();
   }
   	
  //  delete gCanvas;
  //  delete gPostScript;
}
Example #25
0
void draw_cross_pt(bool sysByHand=false, bool noPtWeight=false, bool isScale=true, bool isLog=true, int isPA = 1, bool isPrompt=true)
{
	gROOT->Macro("./tdrstyle_kyo.C");
  gStyle->SetTitleYOffset(1.38); //KYO

	//int iPos=0.;//outOfFrame
	int iPos=33;//right corner
  //int iPos=11;//left corner

	//// pileup rejection!!
	Double_t pileReg;
  if (isPA==0) pileReg = 1;
  else pileReg = 128234./123240.;
	//const Double_t pileRegRelErr = 0.23;

	//// zvtx correction!!
	//const Double_t zvtxCor = 1.064; // not used anymore!!

	//// BR and lumi info.
	const Double_t br = 0.0593 ;
	const Double_t brErr = 0.0006;
	const Double_t pp_lumi_pb =27.972; // 28.0/pb
	const Double_t pp_lumi_pb_err = 0.643; // 2.3 %
	const Double_t pPb_lumi_nb = 34.622; // 34.6/nb
	const Double_t pPb_lumi_nb_err = 1.211; // 3.5 %
	Double_t lumi_mub;
	Double_t lumi_mub_err;
  if (isPA==0) {
    lumi_mub = pp_lumi_pb *1000*1000;
    lumi_mub_err = pp_lumi_pb_err *1000*1000;
  }
  else if (isPA==1) {
    lumi_mub = pPb_lumi_nb * 1000;
    lumi_mub_err = pPb_lumi_nb_err * 1000;
  } else {
    cout << "select among isPA = 0 or 1"<< endl; return ;
  }
	cout << "isPA = " << isPA << ", and lumi_mub = " << lumi_mub <<"+-" <<lumi_mub_err <<  endl;
	cout << " *** pileReg = " << pileReg << endl;

	/////////////////////////////////////////////////////////////////////////
	//// bin center & systematic uncertainties by hand  
	const int nRap = 8;	
	const int nPt = 9;
	const int nRapTmp = nRap + 1;
	const int nPtTmp = nPt + 1;
	const int nRapRFB = 3;	
	const int nPtRFB = 3;
	
	Double_t pxtmp[nRap][nPt]; //x point to fill remporarily
	Double_t pytmp[nRap][nPt]; //y point to fill remporarily
	Double_t eytmp[nRap][nPt]; //y point error to fill remporarily

	Double_t px[nRap][nPt];
  /*
  Double_t px_pp[nRap][nPt] = { //x point (mean pT) by JB -- from FW to BW
    {2.54567, 3.50886, 4.48508, 5.69331, 6.97532, 7.97107, 9.17601, 11.5322, 17.4867},
    {0, 0, 4.54938, 5.75633, 6.9727, 7.97359, 9.17558, 11.4729, 17.4391},
    {0, 0, 0, 0, 7.0061, 7.97991, 9.19355, 11.5729, 17.6818},
    {0, 0, 0, 0, 7.08557, 8.01392, 9.2137, 11.6042, 17.9741},
    {0, 0, 0, 0, 7.08944, 8.01343, 9.21616, 11.6091, 17.7608},
    {0, 0, 0, 0, 7.00408, 7.98632, 9.19122, 11.5535, 17.7004},
    {0, 0, 4.54198, 5.76465, 6.97492, 7.96787, 9.18318, 11.5223, 17.4279},
    {2.54164, 3.5085, 4.48298, 5.69705, 6.97263, 7.97372, 9.17313, 11.5032, 17.3023}
	};
	Double_t px_pA[nRap][nPt] = { //x point (mean pT) by JB -- from FW to BW
    {2.525, 3.51255, 4.4772, 5.70327, 6.96635, 7.96061, 9.17243, 11.5938, 18.0681},
    {0, 0, 4.52793, 5.74033, 6.97622, 7.98335, 9.19458, 11.4927, 17.6693},
    {0, 0, 0, 0, 7.018, 8.00224, 9.19714, 11.5483, 17.6577},
    {0, 0, 0, 0, 7.11111, 8.02103, 9.24485, 11.6204, 17.8454},
    {0, 0, 0, 0, 7.05329, 8.00998, 9.20583, 11.5222, 17.4633},
    {0, 0, 0, 5.84477, 6.98466, 7.97917, 9.17551, 11.5322, 17.34},
    {0, 0, 4.52204, 5.72881, 6.97074, 7.95284, 9.14157, 11.4976, 17.3058},
    {2.51699, 3.4959, 4.47636, 5.68624, 6.97338, 7.97824, 9.1805, 11.4841, 16.8762}
	};
	*/
  //// for middle
  Double_t px_pp[nRap][nPt] = {	
		{2.5, 3.5, 4.5, 5.75, 7, 8, 9.25, 12., 22}, 
		{0., 0., 4.5, 5.75, 7, 8, 9.25, 12., 22},
		{0., 0., 0., 0., 7, 8, 9.25, 12., 22},
		{0., 0., 0., 0., 7, 8, 9.25, 12., 22}, 
		{0., 0., 0., 0., 7, 8, 9.25, 12., 22}, 
		{0., 0., 0., 0., 7, 8, 9.25, 12., 22},
		{0., 0., 4.5, 5.75, 7, 8, 9.25, 12., 22}, 
		{2.5, 3.5, 4.5, 5.75, 7, 8, 9.25, 12., 22}
	};
	Double_t px_pA[nRap][nPt] = {	
		{2.5, 3.5, 4.5, 5.75, 7, 8, 9.25, 12., 22}, 
		{0., 0., 4.5, 5.75, 7, 8, 9.25, 12., 22},
		{0., 0., 0., 0., 7, 8, 9.25, 12., 22},
		{0., 0., 0., 0., 7, 8, 9.25, 12., 22}, 
		{0., 0., 0., 0., 7, 8, 9.25, 12., 22}, 
		{0., 0., 0., 5.75, 7, 8, 9.25, 12., 22},
		{0., 0., 4.5, 5.75, 7, 8, 9.25, 12., 22}, 
		{2.5, 3.5, 4.5, 5.75, 7, 8, 9.25, 12., 22}
	};
  
  Double_t ex[nPt] = {0,0,0,0,0,0,0,0,0}; // x stat error
	Double_t exlow[nRap][nPt]; // x binWidth 
	Double_t exhigh[nRap][nPt]; // x binWidth
	Double_t exsys[nPt] = {0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4,0.4}; // x sys error
	Double_t eysysrel[nRap][nPt]; //relative y sys error
	Double_t eysys[nRap][nPt]; //absolute y sys error
	for (Int_t iy=0; iy<nRap; iy++) {
	  for (Int_t ipt=0; ipt<nPt; ipt++) {
      if (isPA==0) { px[iy][ipt] = px_pp[iy][ipt]; }
      else { px[iy][ipt] = px_pA[iy][ipt]; }
    }
  }

	//// scaling for drawing
  double scaleF[nRap];
	double scaleF_pp[nRap] = {1000., 100., 10., 1., 1., 10., 100., 1000.};
	double scaleF_pA[nRap] = {100., 10., 1., 1., 10., 100., 1000., 10000.};
  for (int iy=0; iy<nRap; iy++){
    if (isPA==0) {scaleF[iy] = scaleF_pp[iy]; }
    else {scaleF[iy] = scaleF_pA[iy]; }
	  if (!isScale) { scaleF[iy] = 1.; };
    cout << "scaleF["<<iy<<"] = " << scaleF[iy] << endl;	
	}
  
  //// 1) y_CM array (from forward to backward)
	Double_t rapArrNumFB_pA[nRapTmp] = {1.93, 1.5, 0.9, 0., -0.9, -1.5, -1.93, -2.4, -2.87};// for pt dist.
	//Double_t rapArrNumBF_pA[nRapTmp] = {-2.87, -2.4, -1.93, -1.5, -0.9, 0., 0.9, 1.5, 1.93};// for rap dist.
	Double_t rapArrNumFB_pp[nRapTmp] = {2.4, 1.93, 1.5, 0.9, 0., -0.9, -1.5, -1.93, -2.4};// for pt dist.
	//Double_t rapArrNumBF_pp[nRapTmp] = {-2.4, -1.93, -1.5, -0.9, 0., 0.9, 1.5, 1.93, 2.4};// for rap dist.
	Double_t rapArrNumFB[nRapTmp];
	for (Int_t iy=0; iy<nRapTmp; iy++) {
		if (isPA==0) { rapArrNumFB[iy] = rapArrNumFB_pp[iy]; }
		else { rapArrNumFB[iy] = rapArrNumFB_pA[iy]; }
	}
	Double_t rapBinW[nRap];
	for (Int_t iy=0; iy<nRap; iy++) {
    rapBinW[iy] = rapArrNumFB[iy]-rapArrNumFB[iy+1];
    //rapBinW[iy] = rapArrNumBF[iy+1]-rapArrNumBF[iy];
	}
	//// 2) pt array
	Double_t ptArrNum[nPtTmp] = {2.0, 3.0, 4.0, 5.0, 6.5, 7.5, 8.5, 10., 14., 30.};
	Double_t ptBinW[nPt];
	for (Int_t ipt=0; ipt<nPt; ipt++) {
		ptBinW[ipt] = ptArrNum[ipt+1]-ptArrNum[ipt]; 
	}
	//// array string
	TString rapArr[nRap];
	for (Int_t iy=0; iy<nRap; iy++) {
		formRapArr(rapArrNumFB[iy+1], rapArrNumFB[iy], &rapArr[iy]);
		cout << iy <<"th rapArr = " << rapArr[iy] << endl;
	}
	TString ptArr[nPt];
	for (Int_t ipt=0; ipt<nPt; ipt++) {
		formPtArr(ptArrNum[ipt], ptArrNum[ipt+1], &ptArr[ipt]);
		cout << ipt <<"th ptArr = " << ptArr[ipt] << endl;
	}
  
  //// ex calculation
  for (Int_t iy=0; iy<nRap; iy++) {
    for (Int_t ipt=0; ipt<nPt; ipt++) {
      exlow[iy][ipt] = px[iy][ipt]-ptArrNum[ipt]; 
      exhigh[iy][ipt] = ptArrNum[ipt+1]-px[iy][ipt]; 
    }
  }

	//////////////////////////////////////////////////////////////	
	//// read-in sys. file 
	TFile * fSys;
  if (isPA==0) fSys = new TFile("../TotalSys/TotSys_8rap9pt_pp_etOpt0.root");
  else fSys = new TFile("../TotalSys/TotSys_8rap9pt_pA_etOpt0.root");
	TH2D* h2D_SysErr;
  if (isPrompt) h2D_SysErr = (TH2D*)fSys->Get("hTotalPR");
	else h2D_SysErr = (TH2D*)fSys->Get("hTotalNP");

	//////////////////////////////////////////////////////////////	
	//// read-in corr-yield file
	TFile * f2D;
  if (isPA==0) {
    if (noPtWeight) f2D = new TFile("../FittingResult/totalHist_pp_8rap9pt_newcut_nominal_Zvtx0_SF1_etOpt0_noPtWeight.root");
    else f2D = new TFile("../FittingResult/totalHist_pp_8rap9pt_newcut_nominal_Zvtx0_SF1_etOpt0.root");
  } else {
    if (noPtWeight) f2D = new TFile("../FittingResult/totalHist_pA_8rap9pt_newcut_nominal_Zvtx1_SF1_etOpt0_noPtWeight.root");
    else f2D = new TFile("../FittingResult/totalHist_pA_8rap9pt_newcut_nominal_Zvtx1_SF1_etOpt0.root");

  }
	//// read-in 2D hist for corrected yield
  TH2D* h2D_CorrY;
	if (isPA==0) {
    if (isPrompt) h2D_CorrY = (TH2D*)f2D->Get("h2D_CorrY_PR_pp");
  	else h2D_CorrY = (TH2D*)f2D->Get("h2D_CorrY_NP_pp");
  } else {
    if (isPrompt) h2D_CorrY = (TH2D*)f2D->Get("h2D_CorrY_PR_pA");
  	else h2D_CorrY = (TH2D*)f2D->Get("h2D_CorrY_NP_pA");
  }
	const int nbinsX = h2D_CorrY->GetNbinsX();
	const int nbinsY = h2D_CorrY->GetNbinsY();
	if (nbinsX != nRap) { cout << " *** Error!!! nbinsX != nRap"; return; };
	if (nbinsY != nPt) { cout << " *** Error!!! nbinsY != nPt"; return; };

	////  projection to 1D hist : iy=0 refers to forwards !!! (ordering here)
	TH1D* h1D_CorrY[nRap]; 
	TH1D* h1D_SysErr[nRap];
	for (Int_t iy = 0; iy < nRap; iy++) {
		if ( isPA==0) {
      h1D_CorrY[iy] = h2D_CorrY->ProjectionY(Form("h1D_CorrY_%d",iy),nRap-iy,nRap-iy);
		  h1D_SysErr[iy] = h2D_SysErr->ProjectionY(Form("h1D_SysErr_%d",iy),nRap-iy,nRap-iy);
		} else {
      h1D_CorrY[iy] = h2D_CorrY->ProjectionY(Form("h1D_CorrY_%d",iy),iy+1,iy+1);
		  h1D_SysErr[iy] = h2D_SysErr->ProjectionY(Form("h1D_SysErr_%d",iy),iy+1,iy+1);
		}
	}
  //// read sys values from hist	
	for (Int_t iy = 0; iy < nRap; iy++) {
		for (int ipt=0; ipt <nPt; ipt ++ ){ 
			eysysrel[iy][ipt] = h1D_SysErr[iy]->GetBinContent(ipt+1);
		}
	}
	
  //////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////
	//// calcualte cross-section = corrY/(dPt*dY*lumi)
	TH1D* h1D_cross[nRap]; 
	for (Int_t iy = 0; iy < nRap; iy++) {
		h1D_cross[iy] = (TH1D*)h1D_CorrY[iy]->Clone(Form("h1D_cross_%d",iy));
		//// normalization
		h1D_cross[iy]->Scale(1,"width"); //pT bin 
		h1D_cross[iy]->Scale(1./rapBinW[iy]); //rap bin
		h1D_cross[iy]->Scale(1./lumi_mub); // lumi
		// h1D_cross[iy]->Scale(1./br); //br
    h1D_cross[iy]->Scale(pileReg);	// pileup correction
		h1D_cross[iy]->Scale(scaleF[iy]); // scaling for drawing
	}
		
	//// set values as zero for unused bins
	for (Int_t iy = 0; iy < nRap; iy++) {
		if (iy>=1 && iy<=6) {
			h1D_cross[iy]->SetBinContent(1,-532);
			h1D_cross[iy]->SetBinError(1,0);
			h1D_cross[iy]->SetBinContent(2,-532);
			h1D_cross[iy]->SetBinError(2,0);
      exlow[iy][0]=0; exhigh[iy][0]=0;
      exlow[iy][1]=0; exhigh[iy][1]=0;
		}
		if (iy>=2 && iy<=5) {
			h1D_cross[iy]->SetBinContent(3,-532);
			h1D_cross[iy]->SetBinError(3,0);
      exlow[iy][2]=0; exhigh[iy][2]=0;
		}
    if (isPA==0) {
  		if (iy>=2 && iy<=5) {
	  		h1D_cross[iy]->SetBinContent(4,-532);
	  		h1D_cross[iy]->SetBinError(4,0);
        exlow[iy][3]=0; exhigh[iy][3]=0;
	  	}
    }
    else {
  		if (iy>=2 && iy<=4) {
	  		h1D_cross[iy]->SetBinContent(4,-532);
	  		h1D_cross[iy]->SetBinError(4,0);
        exlow[iy][3]=0; exhigh[iy][3]=0;
	  	}
    }
	}

	//////////////////////////////////////////////////////////////////

	TLegend *legBLFW; 
	TLegend *legBLBW;
  if (isPA==0) {
    //legBLFW = new TLegend(0.19, 0.160, 0.46, 0.320);
    //legBLBW = new TLegend(0.19, 0.160, 0.46, 0.320);
    legBLFW = new TLegend(0.19, 0.160, 0.46, 0.160+0.035*4+0.035*1.2);
    legBLBW = new TLegend(0.19, 0.160, 0.46, 0.160+0.035*4+0.035*1.2);
  } else {
    legBLFW = new TLegend(0.19, 0.160, 0.46, 0.160+0.035*3+0.035*1.2);
    legBLBW = new TLegend(0.19, 0.160, 0.46, 0.160+0.035*5+0.035*1.2);
  }
	SetLegendStyle(legBLFW);
	SetLegendStyle(legBLBW);
	//legBLFW->SetTextSize(0.034); 
	//legBLBW->SetTextSize(0.034); 
	 	
	TLatex* globtex = new TLatex();
	globtex->SetNDC();
	//globtex->SetTextAlign(12); //1:left, 2:vertical center
  globtex->SetTextAlign(32); //3:right 2:vertical center
  globtex->SetTextFont(42);
	globtex->SetTextSize(0.04);

	//////////////////////////////////////////////////////////////////////////////////////
	//// convert to TGraphAsymErrors
	TGraphAsymmErrors* g_cross_sys[nRap];	
	TGraphAsymmErrors* g_cross[nRap];	
	for (Int_t iy = 0; iy < nRap; iy++) {
		g_cross_sys[iy] = new TGraphAsymmErrors(h1D_cross[iy]);
		g_cross[iy] = new TGraphAsymmErrors(h1D_cross[iy]);
		g_cross_sys[iy]->SetName(Form("g_cross_sys_%d",iy));
		g_cross[iy]->SetName(Form("g_cross_%d",iy));
    cout << "::: for excel ::: iy= " << iy << endl;
		for (Int_t ipt=0; ipt<nPt; ipt++ ){
			g_cross_sys[iy]->GetPoint(ipt, pxtmp[iy][ipt], pytmp[iy][ipt]);
			g_cross_sys[iy]->SetPoint(ipt, px[iy][ipt], pytmp[iy][ipt]);
			//// absolute error calculation 
			eysys[iy][ipt]=eysysrel[iy][ipt]*pytmp[iy][ipt];
			//g_cross_sys[iy]->SetPointError(ipt, exsys[ipt], exsys[ipt], eysys[iy][ipt], eysys[iy][ipt]);
			g_cross_sys[iy]->SetPointError(ipt, exlow[iy][ipt], exhigh[iy][ipt], eysys[iy][ipt], eysys[iy][ipt]);
			g_cross[iy]->GetPoint(ipt, pxtmp[iy][ipt], pytmp[iy][ipt]);
			eytmp[iy][ipt] = g_cross[iy]-> GetErrorY(ipt);
			g_cross[iy]->SetPoint(ipt, px[iy][ipt], pytmp[iy][ipt]);
			g_cross[iy]->SetPointEXlow(ipt, ex[ipt]);
			g_cross[iy]->SetPointEXhigh(ipt, ex[ipt]);
			//cout << "" << endl;
      //cout << "cross["<<iy<<"]["<<ipt<<"] = " << pytmp[iy][ipt]<<endl;
			//cout << "stat.["<<iy<<"]["<<ipt<<"] = " << eytmp[iy][ipt]<<endl;
			//cout << "sys.["<<iy<<"]["<<ipt<<"] = " << eysys[iy][ipt]<<endl;
      cout << pytmp[iy][ipt] <<"\t"<<eytmp[iy][ipt] << "\t "<<eysys[iy][ipt]<<endl;
		}
	}

	//////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////
	//// Draw
	//////////////////////////////////////////////////////////////////////////////////////
	//////////////////////////////////////////////////////////////////////////////////////
	
  int fw_init_pp = 0, fw_init_pA = 0;
	int bw_init_pp = 4, bw_init_pA = 3;
  int fw_init, bw_init;
  if (isPA==0) { fw_init=fw_init_pp; bw_init=bw_init_pp; }
  else { fw_init=fw_init_pA; bw_init=bw_init_pA; }

  for (Int_t iy = 0; iy < nRap; iy++) {
	  g_cross_sys[iy]->GetXaxis()->SetTitle("p_{T} (GeV/c)");
	  g_cross_sys[iy]->GetXaxis()->CenterTitle("");
	  g_cross_sys[iy]->GetYaxis()->SetTitle("B d^{2}#sigma/dp_{T}dy (#mub/ GeV/c)");
	  g_cross_sys[iy]->GetYaxis()->CenterTitle("");
	  if (isLog) {
		  if (isPA==0) {
		    g_cross_sys[iy]->SetMinimum(0.0000001);
        g_cross_sys[iy]->SetMaximum(1000.);
		  } else {
		    g_cross_sys[iy]->SetMinimum(0.00001);
        //g_cross_sys[iy]->SetMaximum(1000000.);
        g_cross_sys[iy]->SetMaximum(500000.);
  	  }
  	}
  	else {
  		g_cross_sys[iy]->SetMinimum(0.0);
  		if (isPA==0) {
        if (isPrompt) g_cross_sys[iy]->SetMaximum(0.16);
        else g_cross_sys[iy]->SetMaximum(0.016);
  		} else {
        if (isPrompt) g_cross_sys[iy]->SetMaximum(20);
        else g_cross_sys[iy]->SetMaximum(2);
  	  }
  	}
	  //g_cross_sys[iy]->GetXaxis()->SetLimits(0.0, 20.);
	  g_cross_sys[iy]->GetXaxis()->SetLimits(0.0, 32.);
	}

  //// different color scheme for pp and pA
  if (isPA==0) {
	  g_cross_sys[0]->SetFillColorAlpha(kMagenta-10,0.5);
	  g_cross_sys[1]->SetFillColorAlpha(kGreen-10,0.5);
	  g_cross_sys[2]->SetFillColorAlpha(kBlue-10,0.5);
	  g_cross_sys[3]->SetFillColorAlpha(kRed-10,0.5);
	  g_cross_sys[4]->SetFillColorAlpha(kRed-10,0.5);
	  g_cross_sys[5]->SetFillColorAlpha(kBlue-10,0.5);
	  g_cross_sys[6]->SetFillColorAlpha(kGreen-10,0.5);
	  g_cross_sys[7]->SetFillColorAlpha(kMagenta-10,0.5);
	  
    g_cross_sys[0]->SetLineColor(kViolet-6);
	  g_cross_sys[1]->SetLineColor(kGreen+3);
	  g_cross_sys[2]->SetLineColor(kBlue-2);
	  g_cross_sys[3]->SetLineColor(kPink-6);
	  g_cross_sys[4]->SetLineColor(kPink-6);
	  g_cross_sys[5]->SetLineColor(kBlue-2);
	  g_cross_sys[6]->SetLineColor(kGreen+3);
	  g_cross_sys[7]->SetLineColor(kViolet-6);

	  SetGraphStyleFinal(g_cross[0],	8,6);
	  g_cross[0]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[1],	0,5);
	  g_cross[1]->SetMarkerSize(2.1);
	  SetGraphStyleFinal(g_cross[2],	2,3);
	  g_cross[2]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[3],	1,0);
	  g_cross[3]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[4],	1,0);
	  g_cross[4]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[5],	2,3);
	  g_cross[5]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[6],	0,5);
	  g_cross[6]->SetMarkerSize(2.1);
	  SetGraphStyleFinal(g_cross[7],	8,6);
	  g_cross[7]->SetMarkerSize(1.4);

  } else {
	  g_cross_sys[0]->SetFillColorAlpha(kGreen-10,0.5);
	  g_cross_sys[1]->SetFillColorAlpha(kBlue-10,0.5);
	  g_cross_sys[2]->SetFillColorAlpha(kRed-10,0.5);
	  g_cross_sys[3]->SetFillColorAlpha(kRed-10,0.5);
	  g_cross_sys[4]->SetFillColorAlpha(kBlue-10,0.5);
	  g_cross_sys[5]->SetFillColorAlpha(kGreen-10,0.5);
	  g_cross_sys[6]->SetFillColorAlpha(kMagenta-10,0.5);
	  g_cross_sys[7]->SetFillColorAlpha(kGray+1,0.5);
	  
    g_cross_sys[0]->SetLineColor(kGreen+3);
	  g_cross_sys[1]->SetLineColor(kBlue-2);
	  g_cross_sys[2]->SetLineColor(kPink-6);
	  g_cross_sys[3]->SetLineColor(kPink-6);
	  g_cross_sys[4]->SetLineColor(kBlue-2);
	  g_cross_sys[5]->SetLineColor(kGreen+3);
	  g_cross_sys[6]->SetLineColor(kViolet-6);
	  g_cross_sys[7]->SetLineColor(kBlack);

	  SetGraphStyleFinal(g_cross[0],	0,5);
	  g_cross[0]->SetMarkerSize(2.1);
	  SetGraphStyleFinal(g_cross[1],	2,3);
	  g_cross[1]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[2],	1,0);
	  g_cross[2]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[3],	1,0);
	  g_cross[3]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[4],	2,3);
	  g_cross[4]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[5],	0,5);
	  g_cross[5]->SetMarkerSize(2.1);
	  SetGraphStyleFinal(g_cross[6],	8,6);
	  g_cross[6]->SetMarkerSize(1.4);
	  SetGraphStyleFinal(g_cross[7],	9,4);
	  g_cross[7]->SetMarkerSize(2.1);
  }
	
  ////////  Forward
	TCanvas* c_fw = new TCanvas("c_fw","c_fw",200,10,600,600);
	c_fw->cd();
	if (isLog) gPad->SetLogy(1);
	else gPad->SetLogy(0);
	//// 1) cross_sys
	for (Int_t iy = fw_init; iy < bw_init; iy++) {
    if (iy==fw_init) g_cross_sys[iy]->Draw("A5");
    else g_cross_sys[iy]->Draw("5");
	}
	//// 2) cross
	for (Int_t iy = fw_init; iy < bw_init; iy++) {
	  g_cross[iy]->Draw("P");
	}
	//// leg
	legBLFW->SetTextSize(0.032*1.2); 
  legBLFW -> SetHeader("Forward rapidity");
	legBLFW->SetTextSize(0.032); 
  for (Int_t iy = fw_init; iy < bw_init; iy++) {
		if (isScale && scaleF[bw_init-iy-1]!=1.) legBLFW -> AddEntry(g_cross[bw_init-iy-1],Form("%s (x%.0f)",rapArr[bw_init-iy-1].Data(),scaleF[bw_init-iy-1]),"lp");
		else legBLFW -> AddEntry(g_cross[bw_init-iy-1],Form("%s",rapArr[bw_init-iy-1].Data()),"lp");
		//if (isScale && scaleF[iy]!=1.) legBLFW -> AddEntry(g_cross[iy],Form("%s (x%.0f)",rapArr[iy].Data(),scaleF[iy]),"lp");
		//else legBLFW -> AddEntry(g_cross[iy],Form("%s",rapArr[iy].Data()),"lp");
	}
	if (isLog) legBLFW->Draw();
  
  globtex->SetTextSize(0.048);
	globtex->SetTextFont(42);
	if (isPrompt) globtex->DrawLatex(0.92, 0.77, "Prompt J/#psi");
	else globtex->DrawLatex(0.92, 0.77, "Nonprompt J/#psi");
//	globtex->SetTextSize(0.035);
//	globtex->SetTextFont(42);
//	if (isPA==0) globtex->DrawLatex(0.91, 0.80, "Global uncertainty : 4 \%");
//	else globtex->DrawLatex(0.91, 0.80, "Global uncertainty : 3.5 \%");

	CMS_lumi( c_fw, isPA, iPos );
	c_fw->Update();
  if (isPA==0){
    if (noPtWeight) {
    	c_fw->SaveAs(Form("plot_cross/pp_fw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_fw->SaveAs(Form("plot_cross/pp_fw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.png",(int)isPrompt,(int)isLog,(int)isScale));
	  } else {
    	c_fw->SaveAs(Form("plot_cross/pp_fw_cross_pt_isPrompt%d_isLog%d_isScale%d.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_fw->SaveAs(Form("plot_cross/pp_fw_cross_pt_isPrompt%d_isLog%d_isScale%d.png",(int)isPrompt,(int)isLog,(int)isScale));
    }
  } else {
    if (noPtWeight) {
    	c_fw->SaveAs(Form("plot_cross/pA_fw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_fw->SaveAs(Form("plot_cross/pA_fw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.png",(int)isPrompt,(int)isLog,(int)isScale));
	  } else {
    	c_fw->SaveAs(Form("plot_cross/pA_fw_cross_pt_isPrompt%d_isLog%d_isScale%d.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_fw->SaveAs(Form("plot_cross/pA_fw_cross_pt_isPrompt%d_isLog%d_isScale%d.png",(int)isPrompt,(int)isLog,(int)isScale));
    }
  }
  legBLFW->Clear();
	
  ////////  Backward
	TCanvas* c_bw = new TCanvas("c_bw","c_bw",200,10,600,600);
	c_bw->cd();
	if (isLog) gPad->SetLogy(1);
	else gPad->SetLogy(0);
	//// 1) cross_sys
	for (Int_t iy = bw_init; iy < nRap; iy++) {
    if (iy==bw_init) g_cross_sys[iy]->Draw("A5");
    else g_cross_sys[iy]->Draw("5");
	}
	//// 2) cross
	for (Int_t iy = bw_init; iy < nRap; iy++) {
	  g_cross[iy]->Draw("P");
	}
	//// leg
	legBLBW->SetTextSize(0.032*1.2); 
  legBLBW -> SetHeader("Backward rapidity");
	legBLBW->SetTextSize(0.032); 
  for (Int_t iy = bw_init; iy < nRap; iy++) {
		if (isScale && scaleF[iy]!=1.) legBLBW -> AddEntry(g_cross[iy],Form("%s (x%.0f)",rapArr[iy].Data(),scaleF[iy]),"lp");
		else legBLBW -> AddEntry(g_cross[iy],Form("%s",rapArr[iy].Data()),"lp");
	}
	if (isLog) legBLBW->Draw();
	
  globtex->SetTextSize(0.048);
	globtex->SetTextFont(42);
	if (isPrompt) globtex->DrawLatex(0.92, 0.77, "Prompt J/#psi");
	else globtex->DrawLatex(0.92, 0.77, "Nonprompt J/#psi");
//	globtex->SetTextSize(0.035);
//	globtex->SetTextFont(42);
//	if (isPA==0) globtex->DrawLatex(0.91, 0.80, "Global uncertainty : 4 \%");
//	else globtex->DrawLatex(0.91, 0.80, "Global uncertainty : 3.5 \%");
	CMS_lumi( c_bw, isPA, iPos );
	c_bw->Update();
  if (isPA==0){
    if (noPtWeight) {
    	c_bw->SaveAs(Form("plot_cross/pp_bw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_bw->SaveAs(Form("plot_cross/pp_bw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.png",(int)isPrompt,(int)isLog,(int)isScale));
	  } else {
    	c_bw->SaveAs(Form("plot_cross/pp_bw_cross_pt_isPrompt%d_isLog%d_isScale%d.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_bw->SaveAs(Form("plot_cross/pp_bw_cross_pt_isPrompt%d_isLog%d_isScale%d.png",(int)isPrompt,(int)isLog,(int)isScale));
    }
  } else {
    if (noPtWeight) {
    	c_bw->SaveAs(Form("plot_cross/pA_bw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_bw->SaveAs(Form("plot_cross/pA_bw_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.png",(int)isPrompt,(int)isLog,(int)isScale));
	  } else {
    	c_bw->SaveAs(Form("plot_cross/pA_bw_cross_pt_isPrompt%d_isLog%d_isScale%d.pdf",(int)isPrompt,(int)isLog,(int)isScale));
    	c_bw->SaveAs(Form("plot_cross/pA_bw_cross_pt_isPrompt%d_isLog%d_isScale%d.png",(int)isPrompt,(int)isLog,(int)isScale));
    }
  }
	legBLBW->Clear();
  	
	///////////////////////////////////////////////////////////////////
	//// save as a root file
	TFile *outFile;
  if (isPA==0) {
    if (noPtWeight) {
      outFile = new TFile(Form("plot_cross/pp_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.root",(int)isPrompt,(int)isLog,(int)isScale),"RECREATE");
    } else {
      outFile = new TFile(Form("plot_cross/pp_cross_pt_isPrompt%d_isLog%d_isScale%d.root",(int)isPrompt,(int)isLog,(int)isScale),"RECREATE");
    }
  }else {
    if (noPtWeight) {
      outFile = new TFile(Form("plot_cross/pA_cross_pt_isPrompt%d_isLog%d_isScale%d_noPtWeight.root",(int)isPrompt,(int)isLog,(int)isScale),"RECREATE");
    } else {
      outFile = new TFile(Form("plot_cross/pA_cross_pt_isPrompt%d_isLog%d_isScale%d.root",(int)isPrompt,(int)isLog,(int)isScale),"RECREATE");
    }
  }

	outFile->cd();
	for (Int_t iy = 0; iy < nRap; iy++) {
		g_cross_sys[iy]->Write();	
		g_cross[iy]->Write();	
	}
	outFile->Close();
	
  return;

} // end of main func.
void draw_muonHistos_dmoon(int fileCode=3){

	//gROOT->Macro("./JpsiStyle.c");
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetPadTopMargin(0.05);
  gStyle->SetPadRightMargin(0.05);
  gStyle->SetPadBottomMargin(0.12);
  gStyle->SetPadLeftMargin(0.12);

	TFile* inFile;
	string samplename;
	Double_t massMin;
	Double_t massMax;
	Double_t ptMin;
	Double_t ptMax;
	Double_t diptMin;
	Double_t diptMax;
	const int nPtBin = 40;
	const int nEtaBin = 15;
	const int nPhiBin = 15;
	const int nMassBin = 40;

  //TFile *in = new TFile("HLTrgAna_RelVal_JpsitoMM_20131205.root","READ");

	if (fileCode ==0) {
	  inFile = TFile::Open("root://eoscms//eos/cms/store/user/dmoon/cms538HI/HLTrgAna/RelVal/HLTrgAna_RelVal_JpsitoMM_20131205.root","READ");
		samplename = "53X_Jpsi";
		massMin = 2.6; massMax = 3.5;
		ptMin = 0.0; ptMax = 20.0;
		diptMin = 0.0; diptMax = 20.0;
		
	} else if (fileCode ==1) {
	  inFile = TFile::Open("root://eoscms//eos/cms/store/user/dmoon/cms538HI/HLTrgAna/RelVal/HLTrgAna_RelVal_ZtoMM_20131205.root","READ");
		samplename = "53X_Z";
		massMin = 60; massMax = 120;
		ptMin = 0.0; ptMax =100.0;
		diptMin = 0.0; diptMax = 50.0;
	} else if (fileCode ==2) {
	  inFile = TFile::Open("root://eoscms//eos/cms/store/user/dmoon/cms538HI/HLTrgAna/442patch5/HLTrgAna_RelVal_JpsiMM_442patch5_20131210.root","READ");
		samplename = "44X_Jpsi";
		massMin = 2.6; massMax = 3.5;
		ptMin = 0.0; ptMax = 20.0;
		diptMin = 0.0; diptMax = 20.0;
	} else if (fileCode ==3) {
	  inFile = TFile::Open("root://eoscms//eos/cms/store/user/dmoon/cms538HI/HLTrgAna/442patch5/HLTrgAna_RelVal_ZMM_442patch5_20131210.root","READ");
		samplename = "44X_Z";
		massMin = 60; massMax = 120;
		ptMin = 0.0; ptMax =100.0;
		diptMin = 0.0; diptMax = 50.0;
	} else std::cout << "*** Error *** Specify the input file" << std::endl;

  TTree *Ana = (TTree*)inFile->Get("Ana");

  // single muon (muon, regitmuon -  glb, trk)
	//pt
  TH1F *hRecoMuPtGlb = new TH1F("hRecoMuPtGlb",";p_{T} (GeV/c);", nPtBin, ptMin, ptMax);
  TH1F *hRecoMuPtTrk = new TH1F("hRecoMuPtTrk",";p_{T} (GeV/c);", nPtBin, ptMin, ptMax);
  hRecoMuPtGlb->Sumw2();
  hRecoMuPtTrk->Sumw2();
  TH1F *hRegitMuPtGlb = new TH1F("hRegitMuPtGlb",";p_{T} (GeV/c);",nPtBin, ptMin, ptMax);
  TH1F *hRegitMuPtTrk = new TH1F("hRegitMuPtTrk",";p_{T} (GeV/c);",nPtBin, ptMin, ptMax);
  hRegitMuPtGlb->Sumw2();
  hRegitMuPtTrk->Sumw2();
	//eta
  TH1F *hRecoMuEtaGlb = new TH1F("hRecoMuEtaGlb",";#eta;",nEtaBin, -2.5, 2.5);
  TH1F *hRecoMuEtaTrk = new TH1F("hRecoMuEtaTrk",";#eta;",nEtaBin, -2.5, 2.5);
  hRecoMuEtaGlb->Sumw2();
  hRecoMuEtaTrk->Sumw2();
  TH1F *hRegitMuEtaGlb = new TH1F("hRegitMuEtaGlb",";#eta;",nEtaBin, -2.5, 2.5);
  TH1F *hRegitMuEtaTrk = new TH1F("hRegitMuEtaTrk",";#eta;",nEtaBin, -2.5, 2.5);
  hRegitMuEtaGlb->Sumw2();
  hRegitMuEtaTrk->Sumw2();
	//phi
  TH1F *hRecoMuPhiGlb = new TH1F("hRecoMuPhiGlb",";#phi;",nPhiBin, 0, 3.2);
  TH1F *hRecoMuPhiTrk = new TH1F("hRecoMuPhiTrk",";#phi;",nPhiBin, 0, 3.2);
  hRecoMuPhiGlb->Sumw2();
  hRecoMuPhiTrk->Sumw2();
  TH1F *hRegitMuPhiGlb = new TH1F("hRegitMuPhiGlb",";#phi;",nPhiBin, 0, 3.2);
  TH1F *hRegitMuPhiTrk = new TH1F("hRegitMuPhiTrk",";#phi;",nPhiBin, 0, 3.2);
  hRegitMuPhiGlb->Sumw2();
  hRegitMuPhiTrk->Sumw2();

	// dimuon (muon, regitmuon -  glb, trk)
	// pt
  TH1F *hRecoDiMuPt = new TH1F("hRecoDiMuPt",";p_{T} (GeV/c);",nPtBin, diptMin, diptMax);
  hRecoDiMuPt->Sumw2();
  TH1F *hRegitDiMuPt = new TH1F("hRegitDiMuPt",";p_{T} (GeV/c);",nPtBin, diptMin, diptMax);
  hRegitDiMuPt->Sumw2();
	// mass
  TH1F *hRecoDiMuMass = new TH1F("hRecoDiMuMass",";m_{#mu#mu} (GeV/c^{2});",nMassBin, massMin, massMax);
  hRecoDiMuMass->Sumw2();
  TH1F *hRegitDiMuMass = new TH1F("hRegitDiMuMass",";m_{#mu#mu} (GeV/c^{2});",nMassBin, massMin, massMax);
  hRegitDiMuMass->Sumw2();

	// single muon	
  Ana->Draw("recoMu_pt>>hRecoMuPtGlb","recoMu_Glb==1","E");
  Ana->Draw("recoMu_pt>>hRecoMuPtTrk","recoMu_Trk==1","E");
  Ana->Draw("regrecoMu_pt>>hRegitMuPtGlb","regrecoMu_Glb==1","E");
  Ana->Draw("regrecoMu_pt>>hRegitMuPtTrk","regrecoMu_Trk==1","E");
  Ana->Draw("recoMu_eta>>hRecoMuEtaGlb","recoMu_Glb==1","E");
  Ana->Draw("recoMu_eta>>hRecoMuEtaTrk","recoMu_Trk==1","E");
  Ana->Draw("regrecoMu_eta>>hRegitMuEtaGlb","regrecoMu_Glb==1","E");
  Ana->Draw("regrecoMu_eta>>hRegitMuEtaTrk","regrecoMu_Trk==1","E");
  Ana->Draw("recoMu_phi>>hRecoMuPhiGlb","recoMu_Glb==1","E");
  Ana->Draw("recoMu_phi>>hRecoMuPhiTrk","recoMu_Trk==1","E");
  Ana->Draw("regrecoMu_phi>>hRegitMuPhiGlb","regrecoMu_Glb==1","E");
  Ana->Draw("regrecoMu_phi>>hRegitMuPhiTrk","regrecoMu_Trk==1","E");

	// dimuon
  Ana->Draw("recoDimu_pt>>hRecoDiMuPt","","E");
  Ana->Draw("regrecoDimu_pt>>hRegitDiMuPt","","E");
  Ana->Draw("recoDimu_mass>>hRecoDiMuMass","","E");
  Ana->Draw("regrecoDimu_mass>>hRegitDiMuMass","","E");

	SetHistStyle(hRecoMuPtGlb, 1,0);
	SetHistStyle(hRegitMuPtGlb, 2,0);
	SetHistStyle(hRecoMuPtTrk, 1,0);
	SetHistStyle(hRegitMuPtTrk, 2,0);
	SetHistStyle(hRecoMuEtaGlb, 1,0);
	SetHistStyle(hRegitMuEtaGlb, 2,0);
	SetHistStyle(hRecoMuEtaTrk, 1,0);
	SetHistStyle(hRegitMuEtaTrk, 2,0);
	SetHistStyle(hRecoMuPhiGlb, 1,0);
	SetHistStyle(hRegitMuPhiGlb, 2,0);
	SetHistStyle(hRecoMuPhiTrk, 1,0);
	SetHistStyle(hRegitMuPhiTrk, 2,0);

	SetHistStyle(hRecoDiMuPt, 1,0);
	SetHistStyle(hRegitDiMuPt, 2,0);
	SetHistStyle(hRecoDiMuMass, 1,0);
	SetHistStyle(hRegitDiMuMass, 2,0);

  TLegend *legUR01 = new TLegend(0.68,0.60,0.87,0.77);
  TLegend *legUM = new TLegend(0.42,0.70,0.61,0.88);
  TLegend *legBR = new TLegend(0.64,0.15,0.84,0.33);
	SetLegendStyle(legUR01);
	SetLegendStyle(legUM);
	SetLegendStyle(legBR);

	//draw and save plots
  TCanvas *c1 = new TCanvas("c1","",600,600);
	//single muon
  hRegitMuPtTrk->SetMinimum(0);
  hRegitMuPtTrk->Draw();
  hRecoMuPtTrk->Draw("same");
  legUR01->SetHeader("Tracker Muons");
  legUR01->AddEntry(hRecoMuPtTrk,"reco muon","PL");
  legUR01->AddEntry(hRegitMuPtTrk,"regit muon","PL");
  legUR01->Draw("same");
  c1->SaveAs(Form("%s_MuPtTrk_reco_vs_regit.pdf",samplename.c_str()));
	legUR01->Clear();
	c1->Clear();

  hRegitMuPtGlb->SetMinimum(0);
  hRegitMuPtGlb->Draw();
  hRecoMuPtGlb->Draw("same");
  legUR01->SetHeader("Global Muons");
  legUR01->AddEntry(hRecoMuPtGlb,"reco muon","PL");
  legUR01->AddEntry(hRegitMuPtGlb,"regit muon","PL");
  legUR01->Draw("same");
  c1->SaveAs(Form("%s_MuPtGlb_reco_vs_regit.pdf",samplename.c_str()));
	legUR01->Clear();
	c1->Clear();

  hRegitMuEtaTrk->SetMinimum(0);
  hRegitMuEtaTrk->Draw();
  hRecoMuEtaTrk->Draw("same");
  legUM->SetHeader("Tracker Muons");
  legUM->AddEntry(hRecoMuEtaTrk,"reco muon","PL");
  legUM->AddEntry(hRegitMuEtaTrk,"regit muon","PL");
  legUM->Draw("same");
  c1->SaveAs(Form("%s_MuEtaTrk_reco_vs_regit.pdf",samplename.c_str()));
	legUM->Clear();
	c1->Clear();

  hRegitMuEtaGlb->SetMinimum(0);
  hRegitMuEtaGlb->Draw();
  hRecoMuEtaGlb->Draw("same");
  legUM->SetHeader("Global Muons");
  legUM->AddEntry(hRecoMuEtaGlb,"reco muon","PL");
  legUM->AddEntry(hRegitMuEtaGlb,"regit muon","PL");
  legUM->Draw("same");
  c1->SaveAs(Form("%s_MuEtaGlb_reco_vs_regit.pdf",samplename.c_str()));
	legUM->Clear();
	c1->Clear();

  hRegitMuPhiTrk->SetMinimum(0);
  hRegitMuPhiTrk->Draw();
  hRecoMuPhiTrk->Draw("same");
  legBR->SetHeader("Tracker Muons");
  legBR->AddEntry(hRecoMuPhiTrk,"reco muon","PL");
  legBR->AddEntry(hRegitMuPhiTrk,"regit muon","PL");
  legBR->Draw("same");
  c1->SaveAs(Form("%s_MuPhiTrk_reco_vs_regit.pdf",samplename.c_str()));
	legBR->Clear();
	c1->Clear();

  hRegitMuPhiGlb->SetMinimum(0);
  hRegitMuPhiGlb->Draw();
  hRecoMuPhiGlb->Draw("same");
  legBR->SetHeader("Global Muons");
  legBR->AddEntry(hRecoMuPhiGlb,"reco muon","PL");
  legBR->AddEntry(hRegitMuPhiGlb,"regit muon","PL");
  legBR->Draw("same");
  c1->SaveAs(Form("%s_MuPhiGlb_reco_vs_regit.pdf",samplename.c_str()));
	legBR->Clear();
	c1->Clear();

	//dimu
  hRegitDiMuPt->SetMinimum(0);
  hRegitDiMuPt->Draw();
  hRecoDiMuPt->Draw("same");
  legUR01->SetHeader("Dimuons");
  legUR01->AddEntry(hRecoDiMuPt,"reco muon","PL");
  legUR01->AddEntry(hRegitDiMuPt,"regit muon","PL");
  legUR01->Draw("same");
  c1->SaveAs(Form("%s_DiMuPt_reco_vs_regit.pdf",samplename.c_str()));
	legUR01->Clear();
	c1->Clear();

  hRegitDiMuMass->SetMinimum(0);
  hRegitDiMuMass->Draw();
  hRecoDiMuMass->Draw("same");
  legUR01->SetHeader("Dimuons");
  legUR01->AddEntry(hRecoDiMuMass,"reco muon","PL");
  legUR01->AddEntry(hRegitDiMuMass,"regit muon","PL");
  legUR01->Draw("same");
  c1->SaveAs(Form("%s_DiMuMass_reco_vs_regit.pdf",samplename.c_str()));
	legUR01->Clear();
	c1->Clear();

	return;

}
Example #27
0
void DrawDataDataplot(TTree *Data_miniTree, TTree *OLD_Data_miniTree, string var, string pic, string limits, string cut, string name, string Title, bool inlog, bool drawUnderOverFsubleading, TCanvas *c0){

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

  // Get Histo_Data from eventTree
  TH1F *Histo_Data_temp = new TH1F();
  string variable_Data = var + ">>Histo_Data_temp"+limits;
  Data_miniTree->Draw(variable_Data.c_str(), cut.c_str());
  TH1F *Histo_Data = (TH1F*)gDirectory->Get("Histo_Data_temp");
  //c1->Clear();
/*
  // Get Histo_DYToMuMu from eventTree
  TH1F *Histo_DYToMuMu_temp = new TH1F();
  string variable_DYToMuMu = var + ">>Histo_DYToMuMu_temp";
  DYToMuMu_miniTree->Draw(variable_DYToMuMu.c_str(), cut.c_str());
  TH1F *Histo_DYToMuMu = (TH1F*)gDirectory->Get("Histo_DYToMuMu_temp");
  c1->Clear();


  // Get Histo_OLD_DYToMuMu from eventTree
  TH1F *Histo_OLD_DYToMuMu_temp = new TH1F();
  string variable_OLD_DYToMuMu = var + ">>Histo_OLD_DYToMuMu_temp";
  OLD_DYToMuMu_miniTree->Draw(variable_OLD_DYToMuMu.c_str(), cut.c_str());
  TH1F *Histo_OLD_DYToMuMu = (TH1F*)gDirectory->Get("Histo_OLD_DYToMuMu_temp");
  c1->Clear();
*/

  // Get Histo_OLD_Data from eventTree
  TH1F *Histo_OLD_Data_temp = new TH1F();
  string variable_OLD_Data = var + ">>Histo_OLD_Data_temp"+limits;
  OLD_Data_miniTree->Draw(variable_OLD_Data.c_str(), cut.c_str());
  TH1F *Histo_OLD_Data = (TH1F*)gDirectory->Get("Histo_OLD_Data_temp");
  //c1->Clear();
  // Get Histo_WJetsToLNu from eventTree
//  TH1F *Histo_WJetsToLNu_temp = new TH1F();
//  string variable_WJetsToLNu = var + ">>Histo_WJetsToLNu_temp";
//  WJetsToLNu_miniTree->Draw(variable_WJetsToLNu.c_str(), cut.c_str());
//  TH1F *Histo_WJetsToLNu = (TH1F*)gDirectory->Get("Histo_WJetsToLNu_temp");
//  c1->Clear();

  // Get Histo_QCDMu from eventTree
//  TH1F *Histo_QCDMu_temp = new TH1F();
//  string variable_QCDMu = var + ">>Histo_QCDMu_temp";
//  QCDMu_miniTree->Draw(variable_QCDMu.c_str(), cut.c_str());
//  TH1F *Histo_QCDMu = (TH1F*)gDirectory->Get("Histo_QCDMu_temp");
//  c1->Clear();

  // Get the number of entries for further normalization
//  double a = Histo_Data->Integral();
/*
  double b_DYToMuMu = Histo_DYToMuMu->Integral();
  if( (a==0.0) || (b_DYToMuMu==0.0) ){
    cout << "no entries to plots" <<endl;
    return; 
  }*/
  // Normalize
  Histo_Data->Sumw2(); // In order to have the correct error bars on data after renormalization
  Histo_OLD_Data->Sumw2(); // In order to have the correct error bars on data after renormalization
  // // Normalize MC and Data to 1
  //Histo_Data->Scale((double)((double)1.0/(double)a));
  //Histo_MC->Scale((double)((double)1.0/(double)b));
  // // Normalize MC to Data number of entries
//  double integratedLuminosity = 191.09326;

//  double XSectionDYToMuMu = 1614.0;
//  double XSectionOLD_DYToMuMu = 1614.0;
//  double XSectionOLD_Data = 121.0;
//	double XSectionWJetsToLNu = 24640.0;
//	double XSectionQCDMu = 84679.30;

//  double InitialNumberDYToMuMu = 1995236.0;
//  double InitialNumberOLD_DYToMuMu = 1995236.0;
//  double InitialNumberOLD_Data = 1164208.0;
//	double InitialNumberWJetsToLNu = 15110974.0;
//	double InitialNumberQCDMu = 29434562.0;

// Normalize everything to 1
	double N_Data = Histo_Data->Integral();
	double N_OLD_Data = Histo_OLD_Data->Integral();
//	double N_DYToMuMu = Histo_DYToMuMu->Integral();
//	double N_OLD_DYToMuMu = Histo_OLD_DYToMuMu->Integral();

	Histo_Data->Scale((double)((double)1.0/(double)N_Data));
	Histo_OLD_Data->Scale((double)((double)1.0/(double)N_OLD_Data));
//	Histo_DYToMuMu->Scale((double)((double)1.0/(double)N_DYToMuMu));
//	Histo_OLD_DYToMuMu->Scale((double)((double)1.0/(double)N_OLD_DYToMuMu));


//  Histo_DYToMuMu->Scale((double)(  (double)((double)(XSectionDYToMuMu) / (double)(InitialNumberDYToMuMu)) * (double)integratedLuminosity));
//  Histo_OLD_DYToMuMu->Scale((double)(  (double)((double)(XSectionOLD_DYToMuMu) / (double)(InitialNumberOLD_DYToMuMu)) * (double)integratedLuminosity));
//  Histo_OLD_Data->Scale((double)(  (double)((double)(XSectionOLD_Data) / (double)(InitialNumberOLD_Data)) * (double)integratedLuminosity));
//  Histo_WJetsToLNu->Scale((double)(  (double)((double)(XSectionWJetsToLNu) / (double)(InitialNumberWJetsToLNu)) * (double)integratedLuminosity));
//  Histo_QCDMu->Scale((double)(  (double)((double)(XSectionQCDMu) / (double)(InitialNumberQCDMu)) * (double)integratedLuminosity));
  // Adding histograms for binned samples
//  Histo_QCD_Pt15->Add(Histo_QCD_Pt30);
//  Histo_QCD_Pt15->Add(Histo_QCD_Pt80);
//  Histo_QCD_Pt15->Add(Histo_QCD_Pt170);
//  Histo_QCD_Pt15->Add(Histo_QCD_Pt300);
//  Histo_QCD_Pt15->Add(Histo_QCD_Pt470);

//	Histo_WJetsToLNu->Add(Histo_QCDMu);
//	Histo_OLD_Data->Add(Histo_WJetsToLNu);
//	Histo_OLD_DYToMuMu->Add(Histo_OLD_Data);
//	Histo_DYToMuMu->Add(Histo_OLD_DYToMuMu);

	// Total MC histo for comupting min/max
//	TH1F *Histo_allMC = new TH1F(*Histo_QCD_Mu_Pt20to30);
//	Histo_allMC->Add(Histo_QCD_Pt15);
//	Histo_allMC->Add(Histo_InclusiveMu15);
//	Histo_allMC->Add(Histo_ZmumuJet_Pt0to15);
//	Histo_allMC->Add(Histo_ZJets_7TeV);
//	Histo_allMC->Add(Histo_WJets_7TeV);
//	Histo_allMC->Add(Histo_TTbarJets_Tauola);
//	Histo_allMC->Add(Histo_DYToMuMu);


  // Get the maxs and the mins to further correct the Y-axis
  double dataMax = Histo_Data->GetMaximum();
  double YMax = dataMax;

//  double DYToMuMuMax = Histo_DYToMuMu->GetMaximum();
//  YMax = max(YMax, DYToMuMuMax);

	double OLD_dataMax = Histo_OLD_Data->GetMaximum();
	YMax = max(YMax, OLD_dataMax);

//	double OLD_DYToMuMuMax = Histo_OLD_DYToMuMu->GetMaximum();
//  YMax = max(YMax, OLD_DYToMuMuMax);

//	double allMCMax = Histo_allMC->GetMaximum();
//	YMax = max(YMax, allMCMax);

  double dataMin = YMax;
//  double OLD_DYToMuMuMin = YMax;
//  double DYToMuMuMin = YMax;
  double OLD_DataMin = YMax;
//  double WJetsToLNuMin = YMax;
//  double QCDMuMin = YMax;

	double allMCMin = YMax;

  double YMin = YMax;

  // Gets the actual minimum for each histogram, and not the unfilled bin if any

  for( int ibin=1 ; ibin<Histo_Data->GetNbinsX() ; ibin++ ){
		if( ((Histo_Data->GetBinContent(ibin))!=0) ){
			YMax = max(YMax, (Histo_Data->GetBinContent(ibin) + Histo_Data->GetBinError(ibin)));
//			cout << "YMax= " << YMax << endl;
		}
//		cout << "ibin= " << ibin << "\tcontent= " << Histo_Data->GetBinContent(ibin) << "\terror= " << Histo_Data->GetBinError(ibin) << endl;
    if( ((Histo_Data->GetBinContent(ibin))!=0) && ((Histo_Data->GetBinContent(ibin))<dataMin) ){
      dataMin = Histo_Data->GetBinContent(ibin);
    }
  }
  YMin = min(YMin, dataMin);
/*
  for( int ibin=1 ; ibin<Histo_DYToMuMu->GetNbinsX() ; ibin++ ){
    if( ((Histo_DYToMuMu->GetBinContent(ibin))!=0) && ((Histo_DYToMuMu->GetBinContent(ibin))<DYToMuMuMin) ){
      DYToMuMuMin = Histo_DYToMuMu->GetBinContent(ibin);
    }
  }
  YMin = min(YMin, DYToMuMuMin);

 for( int ibin=1 ; ibin<Histo_OLD_DYToMuMu->GetNbinsX() ; ibin++ ){
    if( ((Histo_OLD_DYToMuMu->GetBinContent(ibin))!=0) && ((Histo_OLD_DYToMuMu->GetBinContent(ibin))<OLD_DYToMuMuMin) ){
      OLD_DYToMuMuMin = Histo_OLD_DYToMuMu->GetBinContent(ibin);
    }
  }
  YMin = min(YMin, OLD_DYToMuMuMin);
*/
  for( int ibin=1 ; ibin<Histo_OLD_Data->GetNbinsX() ; ibin++ ){
    if( ((Histo_OLD_Data->GetBinContent(ibin))!=0) && ((Histo_OLD_Data->GetBinContent(ibin))<OLD_DataMin) ){
      OLD_DataMin = Histo_OLD_Data->GetBinContent(ibin);
    }
  }
  YMin = min(YMin, OLD_DataMin);

//  for( int ibin=1 ; ibin<Histo_WJetsToLNu->GetNbinsX() ; ibin++ ){
//    if( ((Histo_WJetsToLNu->GetBinContent(ibin))!=0) && ((Histo_WJetsToLNu->GetBinContent(ibin))<WJetsToLNuMin) ){
//      WJetsToLNuMin = Histo_WJetsToLNu->GetBinContent(ibin);
//    }
//  }
//  YMin = min(YMin, WJetsToLNuMin);

//  for( int ibin=1 ; ibin<Histo_QCDMu->GetNbinsX() ; ibin++ ){
//    if( ((Histo_QCDMu->GetBinContent(ibin))!=0) && ((Histo_QCDMu->GetBinContent(ibin))<QCDMuMin) ){
//      QCDMuMin = Histo_QCDMu->GetBinContent(ibin);
//    }
//  }
//  YMin = min(YMin, QCDMuMin);


//  cout << "YMax= "<< YMax << "\t\tYMin= " << YMin << endl;
  double YMin_lin = (double)YMin / (double)10.0;
//  double Range_lin = ((double)(YMax - YMin_lin)) / ((double)(0.8));
  double Range_lin = ((double)(YMax - YMin_lin)) / ((double)(1.0));
  double YMax_lin = 0.2*Range_lin + YMax;
/*
  double Range_lin = ((double)(YMax - YMin)) / ((double)(0.77));
  double YMax_lin = 0.2*Range_lin + YMax;
  double YMin_lin = max(YMin - 0.03*Range_lin, (double)YMin / (double)10.0);
*/
  double Range_log = ((double)(log10(YMax) - log10(YMin))) / ((double)(0.77));
//  cout << "Range_lin= " << Range_lin << "\t\tRange_log= " << Range_log << endl;
  double YMax_log = pow(10.0, 0.2*Range_log + log10(YMax));
  double YMin_log = pow(10.0, log10(YMin) - 0.03*Range_log);
//  cout << "YMin_lin= " << YMin_lin << "\t\tYMax_lin= " << YMax_lin << endl;
//  cout << "YMin_log= " << YMin_log << "\t\tYMax_log= " << YMax_log << endl;




	c0->Divide(1,2);
	c0->cd(1);
//	gPad->SetNumber(1);
	gPad->SetPad(0,0.2,1,1);
//	gPad->SetBottomMargin(0);
	gPad->Draw();                                                             

	c0->cd(2);
//	gPad->SetNumber(2);
	gPad->SetPad(0,0.,1,0.2);
//	gPad->SetTopMargin(0);
//	gPad->SetBottomMargin(0.3);
	gPad->Draw();                                                   


	

/*
TPad *pad =new TPad("haut","haut",0,0.4,1,1);
	    pad->SetNumber(1);
//	    cout << pad->GetBottomMargin() << endl;
//	    pad->SetBottomMargin(0);
	    pad->Draw();
	    
	    TPad *pad2 =new TPad("milieu","milieu",0,0.2,1,0.4);
	    pad2->SetNumber(2);
//	    pad2->SetTopMargin(0);
//	   pad2->SetBottomMargin(0.3);
	    pad2->Draw();

		TPad *pad3=new TPad("bas", "bas", 0, 0, 1, 0.2);
		pad3->SetNumber(3);
		pad3->Draw();
*/

  c0->cd(1);
  // Setup the histo and canvas names and title
  string data_name = "Data_" + pic + "_" + name;
  string mc_name = "MC_" + pic + "_" + name;
  string canvas_name = "DataData_" + pic + "_" + name;
  std::ostringstream binWidthOSS;
  binWidthOSS << (double)Histo_Data->GetBinWidth(1);
  string binWidth = binWidthOSS.str();
  string YaxisTitle = "";
  if((Title.rfind("[") < Title.size()) && (Title.rfind("]") < Title.size())){
//    string unit = Title.substr(Title.rfind("[")+1, Title.size()-Title.rfind("]")-2);
    string unit = Title.substr(Title.rfind("[")+1, Title.rfind("]")-Title.rfind("[")-1);
    YaxisTitle = "a.u. / " + binWidth + " " + unit;
  } else {
    YaxisTitle = "a.u. / " + binWidth;
  }
  Histo_Data->SetName(data_name.c_str());
//  Histo_QCDMu->SetName(mc_name.c_str());
//	Histo_DYToMuMu->SetName(mc_name.c_str());
	
  c0->SetName(canvas_name.c_str());
  c0->SetTitle(canvas_name.c_str());

  // Draw the comparison plots
//	// Template empty histo
//	TH1F *Histo_template = new TH1F("Histo_template", "Histo_template", Histo_Data->GetNbinsX(), Histo_Data->GetXaxis()->GetXmin(),  Histo_Data->GetXaxis()->GetXmax());
//	Histo_template->SetAxisRange(Histo_Data->GetXaxis()->GetXmin(),  Histo_Data->GetXaxis()->GetXmax(), "X");
//	Histo_template->SetAxisRange(YMin_lin, YMax_lin,"Y");
//	Histo_template->SetMaximum(YMax_lin);
//	Histo_template->SetMinimum(YMin_lin);
//	Histo_template->Draw();
//	c0->Update();
//	c0->Draw();

  TLegend *legend = new TLegend(0.55, 0.82, 0.8, 0.93, "");
  legend->SetTextSize(0.05);
  legend->SetFillColor(kWhite);
  legend->SetLineColor(kWhite);
  legend->SetShadowColor(kWhite);
  legend->AddEntry(Histo_Data->GetName(), "Data Run2012 52X", "lp");
  legend->AddEntry(Histo_OLD_Data->GetName(), "Data Run2012 53X", "l");
//  legend->AddEntry(Histo_DYToMuMu->GetName(), "Z#mu#muJet 41X", "f");
//  legend->AddEntry(Histo_OLD_DYToMuMu->GetName(), "Z#mu#muJets 39X", "f");
//  legend->AddEntry(Histo_WJetsToLNu->GetName(), "WJets", "f");
//  legend->AddEntry(Histo_QCDMu->GetName(), "QCD #mu", "f");
//  legend->AddEntry(Histo_DYToMuMu->GetName(), "PhotonJet", "f");
//  legend->AddEntry(Histo_QCD_Mu_Pt20to30->GetName(), "QCD Mu", "f");
//  legend->AddEntry(Histo_ZJets_7TeV->GetName(), "ZJets madgraph", "f");



  // // First: draw the data to get correct Y-axis scale
  gPad->Update();
  Histo_Data->GetXaxis()->SetTitle(Title.c_str());
  Histo_Data->GetYaxis()->SetTitle(YaxisTitle.c_str());
  Histo_Data->SetTitleSize(0.05,"XY");;
  Histo_Data->SetLineColor(kBlack);
  Histo_Data->SetMarkerColor(kBlack);
  Histo_Data->SetMarkerSize(0.7);
  Histo_Data->SetMarkerStyle(20);
  Histo_Data->SetMaximum(YMax_lin);
  Histo_Data->SetMinimum(YMin_lin);
//  Histo_Data->GetYaxis()->SetRangeUser(YMin_lin, YMax_lin);
//  Histo_Data->Draw("E1sames");

  // // Second: draw MC on the same canvas
//  Histo_InclusiveMu15->SetLineColor(kBlack);
//  Histo_InclusiveMu15->SetFillColor(kGreen-6);
//  Histo_InclusiveMu15->SetFillStyle(3001);
//  Histo_InclusiveMu15->SetMaximum(YMax_lin);
//  Histo_InclusiveMu15->SetMinimum(YMin_lin);
//  Histo_InclusiveMu15->Draw("same");  
//  OLD_DataAddEntry(Histo_InclusiveMu15->GetName(), "InclusiveMu15", "f");

//  Histo_QCDMu->SetLineColor(kBlack);
//  Histo_QCDMu->SetFillColor(kGreen-6);
//  Histo_QCDMu->SetFillStyle(3001);
//  Histo_QCDMu->SetMaximum(YMax_lin);
//  Histo_QCDMu->SetMinimum(YMin_lin);

//  Histo_WJetsToLNu->SetLineColor(kBlack);
//  Histo_WJetsToLNu->SetFillColor(kMagenta+3);
//  Histo_WJetsToLNu->SetFillStyle(3001);
//  Histo_WJetsToLNu->SetMaximum(YMax_lin);
//  Histo_WJetsToLNu->SetMinimum(YMin_lin);
  Histo_Data->Draw("E1");                                             

  Histo_OLD_Data->SetLineColor(kRed);
  Histo_OLD_Data->SetMarkerColor(kRed);
  Histo_OLD_Data->SetMarkerSize(0.7);
  Histo_OLD_Data->SetMarkerStyle(20);
//  Histo_OLD_Data->SetFillColor(kBlue);
//  Histo_OLD_Data->SetFillStyle(3001);
  Histo_OLD_Data->SetMaximum(YMax_lin);
  Histo_OLD_Data->SetMinimum(YMin_lin);
  Histo_OLD_Data->Draw("same");                                           

//  Histo_DYToMuMu->SetLineColor(kBlack);
//  Histo_DYToMuMu->SetFillColor(kMagenta);
//  Histo_DYToMuMu->SetFillStyle(3001);
//  Histo_DYToMuMu->SetMaximum(YMax_lin);
//  Histo_DYToMuMu->SetMinimum(YMin_lin);

/*
  Histo_DYToMuMu->SetLineColor(kBlack);
  Histo_DYToMuMu->SetFillColor(kRed);
  Histo_DYToMuMu->SetFillStyle(3001);
  Histo_DYToMuMu->SetMaximum(YMax_lin);
  Histo_DYToMuMu->SetMinimum(YMin_lin);
  Histo_DYToMuMu->GetXaxis()->SetTitle(Title.c_str());
  Histo_DYToMuMu->GetYaxis()->SetTitle(YaxisTitle.c_str());
  Histo_DYToMuMu->Draw("HISTsame");

	Histo_OLD_DYToMuMu->SetLineColor(kBlack);
  Histo_OLD_DYToMuMu->SetFillColor(kOrange);
  Histo_OLD_DYToMuMu->SetFillStyle(3001);
  Histo_OLD_DYToMuMu->SetMaximum(YMax_lin);
  Histo_OLD_DYToMuMu->SetMinimum(YMin_lin);
  Histo_OLD_DYToMuMu->Draw("HISTsame");
*/
//	Histo_QCD_Mu_Pt20to30->Draw("same");
//  Histo_WJetsToLNu->Draw("same");
//  Histo_QCDMu->Draw("same");



  // // Third: re-draw Data so that data appears in front of MC
  //Histo_Data->Draw("PE1 same");                                          
  //Histo_OLD_Data->Draw("same");

  // // Fourth: redraw axis so that axis appears in front of everything
  gPad->RedrawAxis();

  // // Fifth: draw legend
  legend->Draw("same");
	c0->Update();

	c0->cd(2);
	TH1F *Histo_DataRatio = (TH1F*) Histo_Data->Clone("Dataratio");
	Histo_DataRatio->Reset();
//	Histo_DataRatio->Sumw2();
	Histo_DataRatio->Divide(Histo_Data, Histo_OLD_Data, 1.0, 1.0);
	Histo_DataRatio->SetMinimum(0.0);
	Histo_DataRatio->SetMaximum(2);
	Histo_DataRatio->GetYaxis()->SetTitle("DATA / OLD DATA");
	Histo_DataRatio->GetXaxis()->SetTitle("");
	Histo_DataRatio->SetTitleOffset(0.35,"Y");
	Histo_DataRatio->SetTitleSize(0.1,"Y");
	Histo_DataRatio->SetLabelSize(0.15,"XY"); 
	Histo_DataRatio->GetYaxis()->CenterTitle();
	Histo_DataRatio->SetNdivisions(509 ,"Y");
	Histo_DataRatio->Draw("EP");                                     
	TLine *l = new TLine(Histo_DataRatio->GetXaxis()->GetXmin(),1.,Histo_DataRatio->GetXaxis()->GetXmax(),1.);
	l->SetLineWidth(1.5); 
	l->Draw("same");
	c0->Update();
/*
	c0->cd(3);
 	TH1F *Histo_DYToMuMuRatio = (TH1F*) Histo_DYToMuMu->Clone("DYToMuMuratio");
	Histo_DYToMuMuRatio->Reset();
//	Histo_DYToMuMuRatio->Sumw2();
	Histo_DYToMuMuRatio->Divide(Histo_DYToMuMu, Histo_OLD_DYToMuMu, 1.0, 1.0);
	Histo_DYToMuMuRatio->SetMinimum(0.0);
	Histo_DYToMuMuRatio->SetMaximum(2);
	Histo_DYToMuMuRatio->GetYaxis()->SetTitle("MC / OLD MC");
	Histo_DYToMuMuRatio->SetTitleOffset(0.35,"Y");
	Histo_DYToMuMuRatio->SetTitleSize(0.11,"Y");
	Histo_DYToMuMuRatio->SetLabelSize(0.1,"Y"); 
	Histo_DYToMuMuRatio->GetYaxis()->CenterTitle();
	Histo_DYToMuMuRatio->SetNdivisions(509 ,"Y");
	Histo_DYToMuMuRatio->Draw("EP");
	TLine *l1 = new TLine(Histo_DYToMuMuRatio->GetXaxis()->GetXmin(),1.,Histo_DYToMuMuRatio->GetXaxis()->GetXmax(),1.);
	l1->SetLineWidth(1.5); 
	l1->Draw("same");
	c0->Update();
*/
	c0->cd(1);
  TLatex latexLabel;
//  std::ostringstream intLumiString;
//  intLumiString << setprecision (2) << fixed << integratedLuminosity;
//  string intLumiText = "#intL= " + intLumiString.str() + " pb^{-1}";
  latexLabel.SetTextSize(0.04);
  latexLabel.SetNDC();
  latexLabel.DrawLatex(0.15, 0.96, "CMS 2012");
  latexLabel.DrawLatex(0.42, 0.96, "#sqrt{s} = 8 TeV");
//  latexLabel.DrawLatex(0.57, 0.96, intLumiText.c_str());

  // // Sixth: update canvas
  c0->Update();
  //c0->Draw();                            

  // Print the canvas
  string PicName="PlotGif/DataData_" + pic + "_" + name + ".gif";
  c0->Print(PicName.c_str());
  PicName="PlotEps/DataData_" + pic + "_" + name + ".eps";
  c0->Print(PicName.c_str());
  string convert = "convert PlotEps/DataData_" + pic + "_" + name + ".eps" + " PlotPdf/DataData_" + pic + "_" + name + ".pdf";
  system(convert.c_str());


  if (inlog==true) {
    c0->cd(1);
    Histo_Data->SetMaximum(YMax_log);
    Histo_Data->SetMinimum(YMin_log);
    Histo_Data->GetYaxis()->SetRangeUser(YMin_log, YMax_log);
//    Histo_DYToMuMu->SetMaximum(YMax_log);
//    Histo_DYToMuMu->SetMinimum(YMin_log);
//    Histo_DYToMuMu->GetYaxis()->SetRangeUser(YMin_log, YMax_log);
//    Histo_QCD_Pt15->SetMaximum(YMax_log);
//    Histo_QCD_Pt15->SetMinimum(YMin_log);
//    Histo_QCD_Pt15->GetYaxis()->SetRangeUser(YMin_log, YMax_log);

    Histo_OLD_Data->SetMaximum(YMax_log);
    Histo_OLD_Data->SetMinimum(YMin_log);
    Histo_OLD_Data->GetYaxis()->SetRangeUser(YMin_log, YMax_log);

//    Histo_WJetsToLNu->SetMaximum(YMax_log);
//    Histo_WJetsToLNu->SetMinimum(YMin_log);
//    Histo_WJetsToLNu->GetYaxis()->SetRangeUser(YMin_log, YMax_log);

//    Histo_QCDMu->SetMaximum(YMax_log);
//    Histo_QCDMu->SetMinimum(YMin_log);
//    Histo_QCDMu->GetYaxis()->SetRangeUser(YMin_log, YMax_log);

//    Histo_InclusiveMu15->SetMaximum(YMax_log);
//    Histo_InclusiveMu15->SetMinimum(YMin_log);
//    Histo_InclusiveMu15->GetYaxis()->SetRangeUser(YMin_log, YMax_log);

//    Histo_OLD_DYToMuMu->SetMaximum(YMax_log);
//    Histo_OLD_DYToMuMu->SetMinimum(YMin_log);
//    Histo_OLD_DYToMuMu->GetYaxis()->SetRangeUser(YMin_log, YMax_log);

    c0->cd(1)->SetLogy(1);
    c0->Update();
    //c0->Draw();                     fan
    string PicName_log="PlotGif/DataData_" + pic + "_" + name + "_log.gif";
    c0->Print(PicName_log.c_str());
    PicName="PlotEps/DataData_" + pic + "_" + name + "_log.eps";
    c0->Print(PicName.c_str());
    string convert = "convert PlotEps/DataData_" + pic + "_" + name + "_log.eps" + " PlotPdf/DataData_" + pic + "_" + name + "_log.pdf";
    system(convert.c_str());
    c0->cd(1)->SetLogy(0);
    c0->Update();
  }


  // Clean the memory
  c0->Clear();       
  legend->Clear();
//	Histo_template->Delete();
    Histo_Data_temp->Delete();    
    Histo_Data->Delete();        
//  Histo_DYToMuMu_temp->Delete();
//  Histo_DYToMuMu->Delete();

//  Histo_OLD_DYToMuMu_temp->Delete();
//  Histo_OLD_DYToMuMu->Delete();

  Histo_OLD_Data_temp->Delete();
  Histo_OLD_Data->Delete();

//  Histo_WJetsToLNu_temp->Delete();
//  Histo_WJetsToLNu->Delete();

//  Histo_QCDMu_temp->Delete();
//  Histo_QCDMu->Delete();

}
Example #28
0
void makeCorr3(){
	setNCUStyle(true);
	c1 = new TCanvas("c1","",1360,768);
	
	TFile *f;
	f=TFile::Open("corr2/corr.root");
	
	TFile *f2;
	f2=TFile::Open("pdgToReco2.root");
	
	TFile* tf1[nMasspoint];
	int masspoint[nMasspoint]={1000,1200,1400,1600,1800,2000,2500,3000};
	for(int i=0;i<nMasspoint;i++){
		tf1[i]=TFile::Open(Form("corr2/B%d.root",masspoint[i]));
		//f[i+11]=TFile::Open(Form("R%s.root",masspoint[i].data()));
	}
	double xsec[nMasspoint]={1.90,0.763,0.33,0.155,7.65e-2,1.58e-2,3.73e-3,2.08e-4,4.91e-5};
		
	double ptBins[14]={300,400,500,600,700,800,900,1000,1250,1500,1750,2000,2500};
	double ptBinsCenter[14]={350,450,550,650,750,850,950,1125,1375,1625,1875,2250,2750};
	double ptBinsCenterE[14]={350,450,550,650,750,850,950,1125,1375,1625,1875,2250,2750};
	double ptBinsError[14]={0};
	double ptBinsErrorE[14]={0};
	
	double mean[6][15];
	double sigma[6][15];
	
	
	TLegend *leg = new TLegend(0.68, 0.45, 0.94, 0.90);
  
  leg->SetBorderSize(0);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.04);
	
	
	TGraphErrors* tg1[nMasspoint];
	
	for(int k=0;k<nMasspoint;k++){
		for(int i=0;i<13;i++){
		TH1D* th1=(TH1D	*)tf1[k]->Get(Form("ptBarel%.0f",ptBins[i]));
		ptBinsCenter[i]=th1->GetMean();
		ptBinsError[i]=th1->GetRMS();
		cout<<i<<","<<ptBinsCenter[i]<<","<<ptBinsError[i]<<endl;
	}
	
	
		
		for(int i=0;i<13;i++){
		TH1D* th1=(TH1D*)tf1[k]->Get(Form("recoBarelMass%.0f",ptBins[i]));
		TF1 *tf1[4];
	if(i<3){
			tf1[0]=new TF1("fa1","gaus(25000)",th1->GetMaximumBin()-30,th1->GetMaximumBin()+30);
		th1->Fit(tf1[0],"","",th1->GetMaximumBin()-30,th1->GetMaximumBin()+30);
		}
		else {
			tf1[0]=new TF1("fa1","gaus(25000)",th1->GetMaximumBin()-20,th1->GetMaximumBin()+20);
		th1->Fit(tf1[0],"","",th1->GetMaximumBin()-20,th1->GetMaximumBin()+20);
		}
		mean[4][i]=125/tf1[0]->GetParameter(1);
		sigma[4][i]=tf1[0]->GetParError(1)*(125/tf1[0]->GetParameter(1))/tf1[0]->GetParameter(1);
		double temp=tf1[0]->GetParError(1)/tf1[0]->GetParameter(1);
		//mean[4][i]=125/th1->GetMean();
		//sigma[4][i]=th1->GetMeanError()/th1->GetMean();
		
		//cout<<i<<"="<<mean[4][i]<<endl;
		//sigma[4][i]=0;
		th1->SetTitle(Form("%.0f",ptBins[i]));
		if(i==0)c1->Print(Form("plots/recoBarel%d.pdf(",masspoint[k]));
		else if(i==12)c1->Print(Form("plots/recoBarel%d.pdf)",masspoint[k]));
		else  c1->Print(Form("plots/recoBarel%d.pdf",masspoint[k]));
		if(th1->GetEntries()<50|| mean[4][i]<0 || mean[4][i]>2.5||temp>0.3){
			mean[4][i]=0;
			sigma[4][i]=0;
		}
	}
	
	
	
	tg1[k]=new TGraphErrors(12,ptBinsCenter,mean[4],ptBinsError,sigma[4]);
	
	
	
	tg1[k]->GetXaxis()->SetTitle("jet Pt");
	tg1[k]->GetXaxis()->SetRangeUser(0,1800);
	tg1[k]->GetYaxis()->SetTitle("M_{PDG}/M_{Reco}");
	tg1[k]->SetTitle("Gen Correction");
	tg1[k]->SetMinimum(0.9);
	tg1[k]->SetMaximum(2.2);
	tg1[k]->SetFillColor(0);
	tg1[k]->SetLineColor(97-5*k);
	tg1[k]->SetMarkerColor(97-5*k);
	tg1[k]->SetMarkerStyle(20+k);
	tg1[k]->SetMarkerSize(2);
	tg1[k]->SetLineWidth(3);
		
		
		leg->AddEntry(tg1[k],Form("M=%d",masspoint[k]));
	
	}
	for(int k=0;k<nMasspoint;k++){
		tg1[k]->GetXaxis()->SetRangeUser(200,2500);
		if(k==0)tg1[k]->Draw("APL");
		else tg1[k]->Draw("samePL");
	
	for(int j=0;j<12;j++){
		double x,y;
		tg1[k]->GetPoint(j,x,y);
		cout<<"k="<<k<<",j="<<j<<","<<x<<","<<y<<endl;
		if(y<0.1){
			tg1[k]->RemovePoint (j);
			//j--;
		}
		tg1[k]->GetPoint(j,x,y);
		cout<<"k="<<k<<",j="<<j<<","<<x<<","<<y<<endl;
	}
	
	for(int j=0;j<12;j++){
		double x,y;
		tg1[k]->GetPoint(j,x,y);
		
		if(y<0.1){
			tg1[k]->RemovePoint (j);
			//j--;
		}
	}
	for(int j=0;j<12;j++){
		double x,y;
		tg1[k]->GetPoint(j,x,y);
		
		if(y<0.1){
			tg1[k]->RemovePoint (j);
			//j--;
		}
	}
	}
	
	
	TGraphErrors* te1=(TGraphErrors*)f2->Get("barel");
	//leg->AddEntry(te1,"avg");
	//te1->Draw("samePL");
	// te1->SetLineColor(1);
	// te1->SetLineWidth(3);
	// te1->SetMarkerColor(1);
	// te1->SetMarkerSize(1.5);
	// te1->SetMarkerStyle(20);
	leg->Draw("same");
	c1->Print("plots/recoOneBarrel.pdf");
	
	
	leg->Clear();
	
		for(int k=0;k<nMasspoint;k++){

	
	for(int i=0;i<11;i++){
		TH1D* th1=(TH1D*)tf1[k]->Get(Form("ptEndcap%.0f",ptBins[i]));
		ptBinsCenterE[i]=th1->GetMean();
		ptBinsErrorE[i]=th1->GetRMS();
		cout<<i<<","<<ptBinsCenterE[i]<<","<<ptBinsErrorE[i]<<endl;
	}
		
		
		for(int i=0;i<13;i++){
		TH1D* th1=(TH1D*)tf1[k]->Get(Form("recoEndcapMass%.0f",ptBins[i]));
		TF1 *tf1[4];
	if(i<3){
			tf1[0]=new TF1("fa1","gaus(25000)",th1->GetMaximumBin()-40,th1->GetMaximumBin()+40);
		th1->Fit(tf1[0],"","",th1->GetMaximumBin()-40,th1->GetMaximumBin()+40);
		}
		else {
			tf1[0]=new TF1("fa1","gaus(25000)",th1->GetMaximumBin()-30,th1->GetMaximumBin()+30);
			tf1[0]->SetParameter(1,100);
		th1->Fit(tf1[0],"","",th1->GetMaximumBin()-30,th1->GetMaximumBin()+30);
		
		}
		mean[4][i]=125/tf1[0]->GetParameter(1);
		sigma[4][i]=tf1[0]->GetParError(1)*(125/tf1[0]->GetParameter(1))/tf1[0]->GetParameter(1);
		double temp=tf1[0]->GetParError(1)/tf1[0]->GetParameter(1);
		//mean[4][i]=125/th1->GetMean();
		//sigma[4][i]=th1->GetMeanError()/th1->GetMean();
		
		//cout<<i<<"="<<mean[4][i]<<endl;
		//sigma[4][i]=0;
		th1->SetTitle(Form("%.0f",ptBins[i]));
		if(i==0)c1->Print(Form("plots/recoEndcap%d.pdf(",masspoint[k]));
		else if(i==12)c1->Print(Form("plots/recoEndcap%d.pdf)",masspoint[k]));
		else  c1->Print(Form("plots/recoEndcap%d.pdf",masspoint[k]));
		if(th1->GetEntries()<50|| mean[4][i]<1 || mean[4][i]>2.5||temp>0.3){
			mean[4][i]=0;
			sigma[4][i]=0;
		}
	}
	
	
	
	tg1[k]=new TGraphErrors(9,ptBinsCenter,mean[4],ptBinsError,sigma[4]);
	
	
	
	tg1[k]->GetXaxis()->SetTitle("jet Pt");
	tg1[k]->GetXaxis()->SetRangeUser(0,1800);
	tg1[k]->GetYaxis()->SetTitle("M_{PDG}/M_{Reco}");
	tg1[k]->SetTitle("Gen Correction");
	tg1[k]->SetMinimum(1);
	tg1[k]->SetMaximum(1.7);
	tg1[k]->SetFillColor(0);
	tg1[k]->SetLineColor(97-5*k);
	tg1[k]->SetMarkerColor(97-5*k);
	tg1[k]->SetMarkerStyle(20+k);
	tg1[k]->SetMarkerSize(2);
	tg1[k]->SetLineWidth(3);
		
		
		leg->AddEntry(tg1[k],Form("M=%d",masspoint[k]));
	
	}
	for(int k=0;k<nMasspoint;k++){
		tg1[k]->GetXaxis()->SetRangeUser(200,2500);
		if(k==0)tg1[k]->Draw("APL");
	else tg1[k]->Draw("samePL");
	
	for(int j=0;j<12;j++){
		double x,y;
		tg1[k]->GetPoint(j,x,y);
		cout<<"k="<<k<<",j="<<j<<","<<x<<","<<y<<endl;
		if(y<0.1){
			tg1[k]->RemovePoint (j);
			//j--;
		}
		tg1[k]->GetPoint(j,x,y);
		cout<<"k="<<k<<",j="<<j<<","<<x<<","<<y<<endl;
	}
	
	for(int j=0;j<12;j++){
		double x,y;
		tg1[k]->GetPoint(j,x,y);
		
		if(y<0.1){
			tg1[k]->RemovePoint (j);
			//j--;
		}
	}
	for(int j=0;j<12;j++){
		double x,y;
		tg1[k]->GetPoint(j,x,y);
		
		if(y<0.1){
			tg1[k]->RemovePoint (j);
			//j--;
		}
	}
	}
	 te1=(TGraphErrors*)f2->Get("endcap");
	//leg->AddEntry(te1,"avg");
	//te1->Draw("samePL");
	// te1->SetLineColor(1);
	// te1->SetLineWidth(3);
	// te1->SetMarkerColor(1);
	// te1->SetMarkerSize(1.5);
	// te1->SetMarkerStyle(20);
	leg->Draw("same");
	c1->Print("plots/recoOneEndcap.pdf");
	
	/*
	
	
	for(int i=0;i<13;i++){
		TH1D* th1=(TH1D*)f->Get(Form("recoEndcapMass%.0f",ptBins[i]));
		TF1 *tf1[4];
		if(i<2){
			tf1[0]=new TF1("fa1","gaus(25000)",th1->GetMaximumBin()-30,th1->GetMaximumBin()+30);
		th1->Fit(tf1[0],"","",th1->GetMaximumBin()-30,th1->GetMaximumBin()+30);
		}
		else {
			tf1[0]=new TF1("fa1","gaus(25000)",th1->GetMaximumBin()-20,th1->GetMaximumBin()+20);
		th1->Fit(tf1[0],"","",th1->GetMaximumBin()-20,th1->GetMaximumBin()+20);
		}
	
		mean[5][i]=125/tf1[0]->GetParameter(1);
		sigma[5][i]=tf1[0]->GetParError(1)*(125/tf1[0]->GetParameter(1)	)/tf1[0]->GetParameter(1);
		//mean[5][i]=125/th1->GetMean();
		//sigma[5][i]=th1->GetMeanError()/th1->GetMean();
			th1->Draw();
			th1->SetTitle(Form("%.0f",ptBins[i]));
		tf1[0]->Draw("same");
	//cout<<i<<"="<<mean[5][i]<<endl;
	
  
	}
	
	
	
	
	TGraphErrors* tg1[6];
	
	tg1[4]=new TGraphErrors(12,ptBinsCenter,mean[4],ptBinsError,sigma[4]);
	tg1[5]=new TGraphErrors(9,ptBinsCenter,mean[5],ptBinsError,sigma[5]);
	
	for(int i=0;i<14;i++)cout<<i<<"="<<mean[4][i]<<endl;
	for(int i=0;i<14;i++)cout<<i<<"="<<mean[5][i]<<endl;
	

	
	
  

	tg1[4]->Draw("APL");
	tg1[4]->SetFillColor(0);
	tg1[5]->SetFillColor(0);
	tg1[5]->SetLineColor(2);
	tg1[5]->SetMarkerColor(2);
	tg1[5]->Draw("PLsame");
	

leg->Clear();


  
  leg->AddEntry(tg1[5],"reco endcap");
  leg->AddEntry(puppisd_corrRECO_cen,"Thea barel");
  leg->AddEntry(puppisd_corrRECO_for,"Thea endcap");

	leg->Draw("same");
	genBarel->Draw("same");
	genEndcap->Draw("same");
	puppisd_corrRECO_cen->SetLineColor(3);
	puppisd_corrRECO_for->SetLineColor(4);
	//tg1[2]->Draw("APL");
	puppisd_corrRECO_cen->Draw("same");
	puppisd_corrRECO_for->Draw("same");
	
	c1->Print("plots/recoOne.pdf");
	*/
}
Example #29
0
void ang3()
{
   gROOT->SetBatch();
   gROOT->SetStyle("Plain");

   gROOT->ProcessLine(".x common.C");

   TCanvas *c1 = new TCanvas("c1","c1",0,0,600,500);

   double minpt = 0.1;
   double maxpt = 3.;
   double pt[10000];
   int npt = 0;
   for(int i=0;i<10000;i++)
     {
	if( minpt+i*0.1 > maxpt ) break;
	pt[i] = minpt+i*0.1;
	npt++;
     }
   int npt =const_cast<int>(npt);

   double B = 4; // T
   double h = 2.8*10E-3;
   double w = 90*10E-6;

   const int nr = 2;
   double r[2] = 
     {0.6,1.1};
   double col[2] =
     {1,632};
   
   TGraph *gr[10000];
   TGraph *grd[10000];

   TLegend *leg = new TLegend(0.75,0.85,0.90,0.70);
   leg->SetFillColor(253);
   leg->SetBorderSize(0);
   
   for(int ir=0;ir<nr;ir++)
     {	
	int idx = 0;
	
	double tran[10000];
	double perp[10000];
	double delta[10000];
	
	for(int i=0;i<npt;i++)
	  {
	     double pp = pt[i];
	     
	     double R = pp/0.3/B;
	     
	     double ag = aimp(r[ir],R);
	
	     if( ag == -666 )
	       {
		  continue;
	       }	 
	     
	     tran[idx] = ag/ANG2PI;
	     perp[idx] = pp;
	     delta[idx] = h/w*ag;
	     
	     idx++;
	  }   
   
	gr[ir] = new TGraph(idx,perp,tran);
	grd[ir] = new TGraph(idx,perp,delta);
     }   

   for(int ir=0;ir<nr;ir++)
     {	
	if( ir == 0 ) gr[ir]->Draw("AL");
	else gr[ir]->Draw("LS");
	gr[ir]->GetYaxis()->SetRangeUser(0.,90.);
	gr[ir]->GetXaxis()->SetLimits(0.2,3.2);
	gr[ir]->GetXaxis()->SetTitle("P_{T} [GeV]");
	gr[ir]->GetYaxis()->SetTitle("#varphi [deg]");
	gr[ir]->SetLineColor(col[ir]);
	gr[ir]->SetLineWidth(2);
	if( ir == 1 ) gr[ir]->SetLineStyle(2);
	std::string pname = std::string(Form("%.1f",r[ir]))+" m";
	leg->AddEntry(gr[ir],pname.c_str(),"l");
     }
   
   leg->Draw();
   c1->Print("pics/ang.eps");
   c1->Clear();
   leg->Clear();

   for(int ir=0;ir<nr;ir++)
     {	
	if( ir == 0 ) grd[ir]->Draw("AL");
	else grd[ir]->Draw("LS");
	grd[ir]->GetYaxis()->SetRangeUser(0.,40.);
	grd[ir]->GetXaxis()->SetLimits(0.2,3.2);
	grd[ir]->GetXaxis()->SetTitle("P_{T} [GeV]");
	grd[ir]->GetYaxis()->SetTitle("W_{size}");
	grd[ir]->SetLineColor(col[ir]);
	grd[ir]->SetLineWidth(2);
	if( ir == 1 ) grd[ir]->SetLineStyle(2);
	std::string pname = std::string(Form("%.1f",r[ir]))+" m";
	leg->AddEntry(grd[ir],pname.c_str(),"l");
     }
   
   leg->Draw();
   
   c1->Print("pics/delta.eps");
   
   gApplication->Terminate();
}
Example #30
0
void doPlotXJ(TString outname, int inc_or_bjet=1, bool useMC = true, bool addppunc = false)
{
  macro m(outname);

  // bool useMC = true;
  // bool addppunc = false;
  
  TFile *fin = new TFile("results_redoana_default/xJdphi.root");

  TFile *fpps1 = new TFile("results_redoana_ppsmear1/xJdphi.root");
  TFile *fpps2 = new TFile("results_redoana_ppsmear2/xJdphi.root");
  TFile *fpps3 = new TFile("results_redoana_ppsmear3/xJdphi.root");


  string species = "inc";
  if(inc_or_bjet) species = "bjt";

  TH1F *hData010 = (TH1F*) fin->Get(Form("xJ_data_%s_0_10",species.c_str()));
  TH1F *hData1030 = (TH1F*) fin->Get(Form("xJ_data_%s_10_30",species.c_str()));
  TH1F *hData30100 = (TH1F*) fin->Get(Form("xJ_data_%s_30_100",species.c_str()));
  TH1F *hDataPP = (TH1F*) fin->Get(Form("xJ_data_%s_pp",species.c_str()));
  
  TH1F *hMC010;
  TH1F *hMC1030;
  TH1F *hMC30100;
  TH1F *hMCPP = (TH1F*) fin->Get(Form("xJ_mc_%s_pp",species.c_str()));  

  if (useMC) {
    hMC010 = (TH1F*) fin->Get(Form("xJ_mc_%s_0_10",species.c_str()));
    hMC1030 = (TH1F*) fin->Get(Form("xJ_mc_%s_10_30",species.c_str()));
    hMC30100 = (TH1F*) fin->Get(Form("xJ_mc_%s_30_100",species.c_str()));
  } else
  {
    hMC010 = (TH1F*) fpps1->Get(Form("xJ_data_%s_pp",species.c_str()));
    hMC1030 = (TH1F*) fpps2->Get(Form("xJ_data_%s_pp",species.c_str()));
    hMC30100 = (TH1F*) fpps3->Get(Form("xJ_data_%s_pp",species.c_str()));
  }

  // if(inc_or_bjet) hMCPP = (TH1F*) fin->Get(Form("xJ_mc_%s_pp;1",species.c_str()));

Normalize({hMC010,hMC1030,hMC30100,hMCPP}); //temporary fix

  vector<float> syserr;
  if (inc_or_bjet) syserr = {0.023,0.018,0.014,0.008}; //0-10%, 10-30%, 30-100%, pp
  else syserr = {0.023,0.016,0.010,0.007};

  int syscolor = inc_or_bjet ? kredLight : kblueLight;
  int color = kblue;
  if(inc_or_bjet) color=kred;

  auto hData010sys =    makesysplot(hData010,syserr[0],syscolor);
  auto hData1030sys =   makesysplot(hData1030,syserr[1],syscolor);
  auto hData30100sys =  makesysplot(hData30100,syserr[2],syscolor);
  auto hDataPPsys =     makesysplot(hDataPP,syserr[3],syscolor);

  auto hSmPP010sys = makesysplot(hMC010,syserr[3],syscolor);
  auto hSmPP1030sys = makesysplot(hMC1030,syserr[3],syscolor);
  auto hSmPP30100sys = makesysplot(hMC30100,syserr[3],syscolor);


  hSmPP30100sys->SetFillStyle(3005);
  hSmPP30100sys->SetFillColor(color);
  hSmPP1030sys->SetFillStyle(3005);
  hSmPP1030sys->SetFillColor(color);
  hSmPP010sys->SetFillStyle(3005);
  hSmPP010sys->SetFillColor(color);

  lumi_sqrtS = lumi_sqrtSPbPb;


  TCanvas *c1=new TCanvas("c1","c1",600,600);



  
  hData010->SetMarkerColor(color);
  hData010->SetLineColor(color);
  hMC010->SetLineColor(color);

  hData010->GetXaxis()->CenterTitle(1);
  hData010->GetYaxis()->CenterTitle(1);
  hData010->SetYTitle("Event fraction");
  hData010->Draw();
  hData010sys->Draw("e2,same");
  if (addppunc) hSmPP010sys->Draw("e2,same");
  hData010->Draw("same"); //b/c systematics should be on the back

  hMC010->SetMarkerSize(0);
  hMC010->Draw("h,same");
  
  CMS_lumi(c1, iPeriod, iPos ); 
    
  TLegend *l =new TLegend(0.43,0.63,0.9,0.81);
l->AddEntry(hData010,"Data","P");
l->AddEntry(hMC010,useMC ? "Pythia6" : "pp-based reference","l");
 if(inc_or_bjet)l->SetHeader("b dijets");
 else l->SetHeader("Inclusive dijets");
 l->SetFillStyle(0);
 l->Draw();



  SavePlot(c1,"xJ010"+species);

  TCanvas *c2=new TCanvas("c2","c2",600,600);


  hData1030->SetMarkerColor(color);
  hData1030->SetLineColor(color);
  hMC1030->SetLineColor(color);

  hData1030->GetXaxis()->CenterTitle(1);
  hData1030->GetYaxis()->CenterTitle(1);
  hData1030->SetYTitle("Event fraction");
  hData1030->Draw();
  hData1030sys->Draw("e2,same");
  if (addppunc) hSmPP1030sys->Draw("e2,same");
  hData1030->Draw("same");
  
  hMC1030->SetMarkerSize(0);
  hMC1030->Draw("h,same");


  
  CMS_lumi(c2, iPeriod, iPos );

  l->Draw();



  SavePlot(c2,"xJ1030"+species);

    TCanvas *c3=new TCanvas("c3","c3",600,600);

  hData30100->SetMarkerColor(color);
  hData30100->SetLineColor(color);
  hMC30100->SetLineColor(color);
  hData30100->GetXaxis()->CenterTitle(1);
  hData30100->GetYaxis()->CenterTitle(1);
  hData30100->SetYTitle("Event fraction");
  hData30100->Draw();
  hData30100sys->Draw("e2,same");
  if (addppunc) hSmPP30100sys->Draw("e2,same");
  hData30100->Draw("same");
  
  hMC30100->SetMarkerSize(0);
  hMC30100->Draw("h,same");

  
  
  CMS_lumi(c3, iPeriod, iPos );

  l->Draw();
  
SavePlot(c3,"xJ30100"+species);



  lumi_sqrtS = lumi_sqrtSpp;
  

   TCanvas *c4=new TCanvas("c4","c4",600,600);


  hDataPP->SetMarkerColor(color);
  hDataPP->SetLineColor(color);
  hMCPP->SetLineColor(color);

  hDataPP->GetXaxis()->CenterTitle(1);
  hDataPP->GetYaxis()->CenterTitle(1);
  hDataPP->SetYTitle("Event fraction");
  hDataPP->Draw();
  hDataPPsys->Draw("e2,same");  
  hDataPP->Draw("same");
  hMCPP->SetMarkerSize(0);
  hMCPP->Draw("h,same");
  
  
  CMS_lumi(c4, iPeriod, iPos );


  l->Clear();
  l->AddEntry(hDataPP,"Data","P");
  l->AddEntry(hMCPP,"Pythia6","l");
  if(inc_or_bjet)l->SetHeader("b dijets");
  else l->SetHeader("Inclusive dijets");

  l->Draw();



SavePlot(c4,"xJpp"+species);
 
}