void Muti_Plot_centScale(std::string mu_title, const char **lineKind_Arr, TCut selectionC , std::string Var ,  const int ngr, const int nVarBins, double * VarBins_array , double **yArr2, double **yErrArr2)
{ 

	char filename[]="JetESR_status.txt";
	fstream myfile;
	myfile.open (filename,ios::out|ios::app);

	double VarBinsCenter[nVarBins];
	double VarBinsErr[nVarBins];
	for (int ibin=0; ibin<nVarBins; ibin++)
	{
		VarBinsCenter[ibin]= (VarBins_array[ibin] + VarBins_array[ibin+1]) /2;
		//		VarBinsErr[ibin]=0;
		VarBinsErr[ibin]=(VarBins_array[ibin+1]- VarBins_array[ibin])/2;
	}

	cout<<"lineKind_Arr 1 = "<<lineKind_Arr[0]<<" ,lineKind_Arr2 = "<<lineKind_Arr[1]<<endl;
	cout<<"mu_title = "<<mu_title<<" selectionC = "<< selectionC<<endl;

	Can_result[counter1] = new TCanvas(Form("Can_result_%i",counter1));
	mutiGR[counter1] = new TMultiGraph("name",Form("%s",mu_title.c_str()));
	TGraphErrors *gr_mean[ngr];
	legend[counter1] = new TLegend(0.68,0.7,0.88,0.85);

	for(int igr=0; igr<ngr; igr++)
	{
		gr_mean[igr] = new TGraphErrors(nVarBins, VarBinsCenter, yArr2[igr], VarBinsErr , yErrArr2[igr]);
		gr_mean[igr]->SetTitle(Form("some title_%i", igr));
		gr_mean[igr]->SetFillStyle(0);
		gr_mean[igr]->SetMarkerStyle(1);
		gr_mean[igr]->SetLineColor(igr+1);	
		gr_mean[igr]->SetMarkerColor(igr+1);
		mutiGR[counter1]->Add(gr_mean[igr]);
		legend[counter1]->AddEntry( gr_mean[igr] ,lineKind_Arr[igr],"l");  // not work for unknow reason

	}

	myfile<<"hello, Var = "<<Var<<"Var.compare(Centrality) = "<<Var.compare("Centrality")<<endl;

	mutiGR[counter1]->Draw("AP");
	mutiGR[counter1]->GetXaxis()->SetTitle("Centrality"); // must after draw to create a vitual histogram like object to set title.
	mutiGR[counter1]->GetYaxis()->SetTitle("#mu_{Reco./Gen.}");
	mutiGR[counter1]->Draw("AP"); // draw again to let all the settting on it.
	//	Can_result[counter1]->BuildLegend(0.7,0.7,0.9,0.9);
	legend[counter1]->SetBorderSize(0);
	legend[counter1]->Draw();

	TLatex *tex = new TLatex(0.25,0.7,"#bf{#color[2]{|#eta_{jet}|<2.0 &75<refpt<120}}");
	tex->SetNDC();
	tex->SetTextFont(43);
	tex->SetTextSize(24);
	tex->SetLineWidth(2);
	tex->Draw();

	Can_result[counter1]->SaveAs(Form("./Plots/result_%s_%s_%s.pdf",mu_title.c_str(),selectionC.GetTitle() , Var.c_str())); 
	Can_result[counter1]->SaveAs(Form("./Plots/result_%s_%s_%s.C",mu_title.c_str(),selectionC.GetTitle() , Var.c_str()));
	counter1++;
	cout<<"finish mutigraph"<<endl;
}
void make_psi2s_mupt(float ptmin=0.0, float ptmax=30.0, float ymin=0.0, float ymax=2.4, bool absRapidity=true, bool saveFile=false)
{
  TCanvas *c1 = new TCanvas("c1","c1");
  c1->SetLogy();
  TCut defaultCut = "Reco_QQ_sign==0&&Reco_QQ_4mom.M()>3.35&&Reco_QQ_4mom.M()<4.0&&Reco_QQ_ctauTrue>-10";
  TCut ptCut = Form("Reco_QQ_4mom.Pt()>%4.1f&&Reco_QQ_4mom.Pt()<%4.1f",ptmin,ptmax);
  TCut rapCut;
  if (absRapidity)
    rapCut = Form("abs(Reco_QQ_4mom.Rapidity())>%3.1f&&abs(Reco_QQ_4mom.Rapidity())<%3.1f",ymin,ymax);
  else
    rapCut = Form("Reco_QQ_4mom.Rapidity()>%3.1f&&Reco_QQ_4mom.Rapidity()<%3.1f",ymin,ymax);

  unsigned int trigBit=2; // DoubleMu0_HighQ
  TCut trigCut = Form("(HLTriggers&%u)==%u&&(Reco_QQ_trig&%u)==%u",trigBit,trigBit,trigBit,trigBit);

  TString fname;
  fname = Form("20140324/MC_psi2s_pp_mupt_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f.root",ymin,ymax,ptmin,ptmax);

  std::cout << fname << std::endl;


  std::cout << "default: " << defaultCut.GetTitle() << std::endl;
  std::cout << "pt cut: " << ptCut.GetTitle() << std::endl;
  std::cout << "rapidity cut: " << rapCut.GetTitle() << std::endl;
  std::cout << "trigger bit: " << trigCut.GetTitle() << std::endl;

  TH1F *hMuPlPtRec = new TH1F("hMuPlPtRec","hMuPlPtRec;p_{T} (#mu^{+}) (GeV/c);Events",200,0,20);
  TH1F *hMuMiPtRec = new TH1F("hMuMiPtRec","hMuMiPtRec;p_{T} (#mu^{-}) (GeV/c);Events",200,0,20);
  TH1F *hMuPtRec = new TH1F("hMuPtRec","hMuPtRec;p_{T} (#mu^{#pm}) (GeV/c);Events",200,0,20);
  hMuPlPtRec->Sumw2();
  hMuMiPtRec->Sumw2();
  hMuPtRec->Sumw2();

  hMuPlPtRec->SetMarkerColor(kRed);
  hMuMiPtRec->SetMarkerColor(kBlue);

  TChain *myTree = new TChain("myTree");
  myTree->Add("../root_files/PRpsi2SMC_Histos_2013pp_GlbGlb_STARTHI53_V28-v1_muLessPV.root");

  myTree->Draw("Reco_QQ_mupl_4mom.Pt()>>hMuPlPtRec",defaultCut&&ptCut&&rapCut&&trigCut,"e");
  myTree->Draw("Reco_QQ_mumi_4mom.Pt()>>hMuMiPtRec",defaultCut&&ptCut&&rapCut&&trigCut,"e");

  hMuPtRec->Add(hMuPlPtRec,hMuMiPtRec);

  hMuPtRec->Draw();
  hMuPlPtRec->Draw("same");
  hMuMiPtRec->Draw("same");

  TFile *outf = NULL;
  if (saveFile) {
    outf = new TFile(fname,"RECREATE");
    hMuPtRec->Write();
    outf->Close();
  }

  return;
}
Exemple #3
0
void HT_RaTPlot(TTree *t1, TString sel, TString set){
gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0);
  SetStyle();



  TH1D *noHT = RaT(t1,kRed,trigMC+numpj,"noHT",sel,set);
   TH1D *HT200 = RaT(t1,kBlack,trigMC+HT200,"HT200",sel,set);
   TH1D *HT300= RaT(t1,kGreen,trigMC+HT300,"HT300",sel,set);
   TH1D *HT350 = RaT(t1,kBlue,trigMC+HT350,"HT350",sel,set);

TCanvas *c7 = new TCanvas ("SAS"+sel+set,"SAS"+sel+set);
 TLegend *leg = new TLegend(0.7,0.7,0.99,0.99);
 leg->AddEntry(noHT,"noHT","LP");
 leg->AddEntry(HT200,"HT > 200","LP");
 leg->AddEntry(HT300,"HT > 300","LP");
 leg->AddEntry(HT350,"HT > 350","LP");
 noHT->Draw("E");
 gPad->SetGridx(); gPad->SetGridy();
 HT200->Draw("ESAME");
 HT300->Draw("ESAME");
 HT350->Draw("ESAME");

 HT200->SetTitle();
 HT200->GetXaxis()->SetTitle("|#eta | leading jet");
 HT200->GetYaxis()->SetTitle("N(above aT "+s_aT+") / N(all)");
 HT200->GetYaxis()->SetTitleOffset(1.2);
 leg->Draw("SAME");
 c7->Update();
 c7->SaveAs(plotting+"RaT_HTbins_"+set+"_"+sel+".png");

}
Exemple #4
0
void makePlot(vector<TTree*> sigTree,vector<double> sigWeight,
	      vector<int> ptHatLo, vector<int> ptHatHi,
              std::string var,TCut cut,TH1F* h,bool norm)
{
   TH1F *hRes = (TH1F*)h->Clone();
   hRes->SetName("hRes");
   hRes->Sumw2();
  
   char tmp[300];
   for (unsigned int i=0; i<sigTree.size(); i++)
     {
       // first determine the pthat cut
       
       sprintf(tmp, "ptHat >= %d && ptHat <= %d",ptHatLo[i], ptHatHi[i]);
       TCut ptHatCut = tmp;
       TCut allCut = cut + ptHatCut;
       cout << "Current cut = " << allCut.GetTitle() << endl;
       TH1F *htmp = (TH1F*)h->Clone();
       htmp->SetName("htmp");
       sigTree[i]->Draw(Form("%s>>htmp",var.data()),allCut);
       htmp->Sumw2();
       htmp->Scale(sigWeight[i]);
       cout << "scale = " << sigWeight[i] << endl;
       cout << "After scaling htmp -> entries() " << htmp->GetEntries() << endl;
       cout << "After scaling htmp -> Integral() " << htmp->Integral() << endl;
       cout << "After scaling htmp -> GetMean()  " << htmp->GetMean() << endl;
       cout << "After scaling htmp -> GetRMS()  " << htmp->GetRMS() << endl;
       hRes->Add(htmp);
       delete htmp;
   }
   h->Sumw2();
   h->Add(hRes);
   if(norm)h->Scale(1.0/(double)h->Integral(0,1000));
   cout << "After scaling h-> entries() " << h->GetEntries() << endl;
   cout << "After scaling h-> Integral() " << h->Integral() << endl;
   cout << "After scaling h -> GetMean()  " << h->GetMean() << endl;
   cout << "After scaling h -> GetRMS()  " << h->GetRMS() << endl;
   
   delete hRes;
}
Exemple #5
0
void zeeAnaDiff(TH1D* hsee, TCut addCut,TH1D* hseeMc) {
  
  TFile *f1=new TFile(fname1.Data());
  TTree *zp = (TTree*)f1->Get("tz");
  zp->AddFriend("yEvt=yongsunHiEvt"       ,fname1.Data());
  zp->AddFriend("ySkim=yongsunSkimTree"   ,fname1.Data());
  zp->AddFriend("yHlt=yongsunHltTree"     ,fname1.Data());
  zp->AddFriend("tgj",                     fname1.Data());
  
  TH1D* hmass = new TH1D("hmass",";inv. mass (GeV);event fraction",34,30,200);
  hmass->Sumw2();

  zp->Draw("invm>>hmass",addCut && "isEle1==1 && isEle2==1");
  TH1D* htemp = (TH1D*)hsee->Clone("htemp");   htemp->Reset();
  zp->Draw("see1>>htemp",addCut && "isEle1==1 && isEle2==1" && "invm>80 && invm<100" );
  hsee->Reset();
  hsee->Add(htemp);
  handsomeTH1(hmass,2);
  scaleInt(hmass);
  
  TH1D* htempMC;
  TFile *f1mc;
  TTree *zpmc ;
  f1mc=new TFile(fname1MC.Data());
  zpmc = (TTree*)f1mc->Get("tz");
  zpmc->AddFriend("yEvt=yongsunHiEvt"       ,fname1MC.Data());
  zpmc->AddFriend("ySkim=yongsunSkimTree"   ,fname1MC.Data());
  zpmc->AddFriend("yHlt=yongsunHltTree"     ,fname1MC.Data());
  zpmc->AddFriend("yPho=yongsunPhotonTree"     ,fname1MC.Data());
  zpmc->AddFriend("tgj",                     fname1MC.Data());
  hseeMc->Sumw2();
  htempMC = (TH1D*)hseeMc->Clone("htempMc");   htempMC->Reset();
  TH1D* hmassMC = new TH1D("hmassMC11",";inv. mass (GeV);event fraction",34,30,200);
  hmassMC->Sumw2();
  zpmc->Draw("invm>>hmassMC11",Form("(%s) *yPho.ncoll",addCut.GetTitle()));
  zpmc->Draw("see1>>htempMc",Form("(%s) *yPho.ncoll", (addCut && "invm>80 && invm<100").GetTitle()) );
  hseeMc->Reset();
  hseeMc->Add(htempMC);
  handsomeTH1(hmassMC,1);
  scaleInt(hmassMC);
  
  
  hmassMC->SetAxisRange(0,0.6,"Y");
  hmassMC->DrawCopy();
  hmass->DrawCopy("same");                                                                                             
  TLegend* leg1 =  new TLegend(0.5580645,0.5381356,0.8923387,0.7648305,NULL,"brNDC");
  easyLeg(leg1,"Z->ee mass");
  leg1->AddEntry(hmass,"DATA","pl");
  leg1->AddEntry(hmassMC,"MC","pl");
  leg1->Draw();
  
}
Exemple #6
0
void getseePhoMC(TH1D* hsee, TCut addCut){

  TFile *f1=new TFile(fPho.Data());
  TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree");
  photon1->AddFriend("yEvt=yongsunHiEvt"       ,fPho.Data());
  photon1->AddFriend("ySkim=yongsunSkimTree"   ,fPho.Data());
  photon1->AddFriend("yHlt=yongsunHltTree"     ,fPho.Data());
  photon1->AddFriend("tgj",                     fPho.Data());
 
  TH1D* htemp = (TH1D*)hsee->Clone("htemp");  htemp->Reset();
  photon1->Draw("sigmaIetaIeta>>htemp",Form("(%s) *ncoll",addCut.GetTitle()));
  hsee->Reset();
  hsee->Add(htemp);
}
double countEvt(process &process, TCut Cut)
{
  // Create temporary histogram
  TH1D* tmp = new TH1D("tmp", "tmp", 30, 0, 1000);

  // Get number of events after a cut
  double Sel = 0;
  process.GetChain()->Draw("Njet>>tmp","XS*5000/Nevt"*Cut, "goff");
  Sel = tmp->Integral();

  delete tmp;
  process.SetSelection(Cut.GetName());
  process.SetNevt_sel(Sel);
  return Sel;
}
Exemple #8
0
// ---------------------------------------------------------------------------------------------
TString weightCut (TCut cut, bool needMCweight, int treeVersion = 2, bool pTweighted = false)
{
  TString sWMC (treeVersion <= 1 ? "xsec" : "w");
  TString sPT (treeVersion <= 2 ? "jtpt" : "jtrawpt");
  TString title( stripStart( stripEnd( cut.GetTitle() ) ) );
  
  TString title_in_parenthesis( title );
  if( ! allInBrackets( title ) ) title_in_parenthesis = "("+title+")";
  if( needMCweight || pTweighted ) { // need some sort of weight
    TString sW;
    if( needMCweight && !pTweighted ) sW = sWMC.Data();
    if( pTweighted && !needMCweight ) sW = sPT.Data();
    if( needMCweight && pTweighted )  sW = Form("(%s*%s)", sWMC.Data(), sPT.Data());
    if( title.IsWhitespace() ) {
      return sW;
    } else {
      return title_in_parenthesis + "*" + sW;
    }
  } else { // no weights needed. 
    // But this is a cut, not a weigh, so add parenthesis and a test to prevent weighting
    if( title.IsWhitespace() ) return "";
    return title_in_parenthesis+">0";
  }
}
int main(int argc, char* argv[]) {

  TH1::SetDefaultSumw2();

  ProgramOptions options(argc, argv);

  double lumi = options.lumi;

  std::cout << "Integrated luminosity : " << lumi << " pb-1" << std::endl;

  Datasets datasets(options.iDir);
  datasets.readFile(options.datasetFile);

  LeptonWeights lw;

  // cuts
  Cuts cuts;
  TCut puWeight("puWeight");
  TCut trigCorr( "(trigCorrWeight>0) ? trigCorrWeight : 1." );

  // For lepton weights
  TCut elTightWeight     = cuts.elTightWeight(options.leptCorr);
  TCut muTightWeight     = cuts.muTightWeight(options.leptCorr);
  TCut leptonTightWeight = elTightWeight * muTightWeight;

  TCut elVetoWeight      = cuts.elVetoWeight(options.leptCorr);
  TCut muVetoWeight      = cuts.muVetoWeight(options.leptCorr);
  TCut leptonVetoWeight  = elVetoWeight * muVetoWeight;

  TCut otherCutsTight = puWeight * trigCorr * leptonTightWeight;
  TCut otherCutsVeto  = puWeight * trigCorr * leptonVetoWeight;

  TCut cutSignalNoMETNoDPhi = cuts.HLTandMETFilters() + cuts.leptonVeto() + cuts.vbf();
  
  // Tau cuts
  // Get puWeight etc added below if necessary
  // standard TightMjj selection - essentially signal selection but no DPhiJJ and no cjv
  TCut cutTightMjj_basic = cuts.HLTandMETFilters() + cuts.cutWTau("lVeto") + cuts.cutWTau("dijet") + cuts.cutWTau("dEtaJJ") + cuts.cutWTau("MET") + cuts.cutWTau("Mjj"); 
  TCut cutwMunoMjj       = cuts.cutWMu("trigger")+ cuts.cutWMu("wMu")+cuts.cutWMu("lVeto")+cuts.cutWMu("dijet")+cuts.cutWMu("dEtaJJ")+cuts.cutWMu("MET") + cuts.cutWMu("dPhiJJ") + cuts.cutWMu("CJV"); //for W->mu regions
  cutwMunoMjj.Print();
  TCut cutTightMjj(""); // used to add in PU, trig corr, wWeight etc
  TCut cutWMuVBFNoCJV = cuts.cutWMu("trigger")  + cuts.cutWMu("wMu")  + cuts.cutWMu("lVeto")  + cuts.cutWMu("dijet")  + cuts.cutWMu("dEtaJJ")  + cuts.cutWMu("Mjj");

  // double dphiEdges[4] = { 0., 1.0, 2.6, TMath::Pi() };
  double dphiEdges[5]     = { 0., 1.0, 1.8, 2.6, TMath::Pi() };
  double MjjEdges[5]      = { 800., 1000., 1200., 1800., 3000. };
  // double MjjEdges[5]      = { 800., 1100., 1400., 1800., 3000. };
  double METEdges[5]      = { 100., 150., 200., 250., 300. };
  //double CenJetEtEdges[5] = { 10., 40., 70., 120. ,200};
  double CenJetEtEdges[5] = { 10., 30., 60., 100., 150.};

  TH1D* hWMu_MCGen_DPhi  = new TH1D("hWMu_MCGen_DPhi", "", 1, 0,1);   // W+jets MC gen level mu
  TH1D* hWTau_MCGen_DPhi = new TH1D("hWTau_MCGen_DPhi", "", 1, 0,1);   // W+jets MC gen level Tau - for ID 

  // DPhiJJ histograms
  // WMu histograms
  TH1D* hWMu_MCC_DPhi    = new TH1D("hWMu_MCC_DPhi", "", 4, dphiEdges);  // W+jets MC mu ctrl region
  
  TH1D* hWMu_BGC_DPhi    = new TH1D("hWMu_BGC_DPhi", "", 4, dphiEdges);  // background MC ctrl region
  TH1D* hWMu_DataC_DPhi  = new TH1D("hWMu_DataC_DPhi", "", 4, dphiEdges);  // Data ctrl region
  
  // WTau histograms
  TH1D* hWTau_MCC_DPhi   = new TH1D("hWTau_MCC_DPhi", "", 4, dphiEdges);  // W+jets MC tau ctrl region - for CJV ratio
  
  TH1D* hWTau_BGC_DPhi   = new TH1D("hWTau_BGC_DPhi", "", 4, dphiEdges);  // background MC ctrl region
  TH1D* hWTau_DataC_DPhi = new TH1D("hWTau_DataC_DPhi", "", 4, dphiEdges);  // Data ctrl region

  // Mjj histograms
  // WMu histograms
  TH1D* hWMu_MCC_Mjj    = new TH1D("hWMu_MCC_Mjj", "", 4, MjjEdges);  // W+jets MC mu ctrl region
  TH1D* hWMu_BGC_Mjj    = new TH1D("hWMu_BGC_Mjj", "", 4, MjjEdges);  // background MC ctrl region
  TH1D* hWMu_DataC_Mjj  = new TH1D("hWMu_DataC_Mjj", "", 4, MjjEdges);  // Data ctrl region
  
  // WTau histograms
  TH1D* hWTau_MCC_Mjj   = new TH1D("hWTau_MCC_Mjj", "", 4, MjjEdges);  // W+jets MC tau ctrl region - for CJV ratio
  TH1D* hWTau_BGC_Mjj   = new TH1D("hWTau_BGC_Mjj", "", 4, MjjEdges);  // background MC ctrl region
  TH1D* hWTau_DataC_Mjj = new TH1D("hWTau_DataC_Mjj", "", 4, MjjEdges);  // Data ctrl region  // Mjj histograms
 

  // MET histograms
  // WMu histograms
  TH1D* hWMu_MCC_MET    = new TH1D("hWMu_MCC_MET", "", 4, METEdges);  // W+jets MC mu ctrl region
  TH1D* hWMu_BGC_MET    = new TH1D("hWMu_BGC_MET", "", 4, METEdges);  // background MC ctrl region
  TH1D* hWMu_DataC_MET  = new TH1D("hWMu_DataC_MET", "", 4, METEdges);  // Data ctrl region
  
  // WTau histograms
  TH1D* hWTau_MCC_MET   = new TH1D("hWTau_MCC_MET", "", 4, METEdges);  // W+jets MC tau ctrl region - for CJV ratio
  TH1D* hWTau_BGC_MET   = new TH1D("hWTau_BGC_MET", "", 4, METEdges);  // background MC ctrl region
  TH1D* hWTau_DataC_MET = new TH1D("hWTau_DataC_MET", "", 4, METEdges);  // Data ctrl region  // MET histograms
 
  // Central Jet Et histograms 
  // WMu histograms
  TH1D* hWMu_MCC_CenJetEt    = new TH1D("hWMu_MCC_CenJetEt", "", 4, CenJetEtEdges);  // W+jets MC mu ctrl region
  TH1D* hWMu_BGC_CenJetEt    = new TH1D("hWMu_BGC_CenJetEt", "", 4, CenJetEtEdges);  // background MC ctrl region
  TH1D* hWMu_DataC_CenJetEt  = new TH1D("hWMu_DataC_CenJetEt", "", 4, CenJetEtEdges);  // Data ctrl region
  
  // WTau histograms
  TH1D* hWTau_MCC_CenJetEt   = new TH1D("hWTau_MCC_CenJetEt", "", 4, CenJetEtEdges);  // W+jets MC tau ctrl region - for CJV ratio
  TH1D* hWTau_BGC_CenJetEt   = new TH1D("hWTau_BGC_CenJetEt", "", 4, CenJetEtEdges);  // background MC ctrl region
  TH1D* hWTau_DataC_CenJetEt = new TH1D("hWTau_DataC_CenJetEt", "", 4, CenJetEtEdges);  // Data ctrl region

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

    Dataset dataset = datasets.getDataset(i);

    TFile* file = datasets.getTFile(dataset.name);
    TTree* tree = (TTree*) file->Get("invHiggsInfo/InvHiggsInfo");
    // TFile* ofile = TFile::Open( (oDir+std::string("/")+dataset.name+std::string(".root")).c_str(), "RECREATE");

    // setup cuts
    TCut wWeight("");

    TCut cutD = cuts.cutDataset(dataset.name);
    TCut cutWMu_Gen           = cuts.wMuGen();
    TCut cutWTau_Gen          = cuts.wTauGen();

    TCut cutWMu_MCC_DPhi      = cuts.wMuGen() + cuts.wMuVBF() + cuts.cutWMu("MET");
    TCut cutWMu_C_DPhi        = cutD + cuts.wMuVBF() + cuts.cutWMu("MET"); // WMu MC control region; WMu MC gen only; control region for data/bg - all for DPhiJJ
    TCut cutWTau_MCC_DPhi     = cuts.wTauGen() + cutTightMjj_basic + cuts.cutWTau("wTau");
    TCut cutWTau_C_DPhi       = cutD + cutTightMjj_basic + cuts.cutWTau("wTau"); // WTau MC control region; WTau MC gen only; control region for data/bg - all for DPhiJJ

    TCut cutWMu_MCC_Mjj       = cuts.wMuGen() + cutwMunoMjj;
    TCut cutWMu_C_Mjj         = cutD + cutwMunoMjj;
    TCut cutWTau_MCC_Mjj      = cuts.wTauGen() + cuts.cutWTau("wTau") + cuts.cutWTau("trigger") + cuts.cutWTau("lVeto") + cuts.cutWTau("dijet") + cuts.cutWTau("dEtaJJ") + cuts.cutWTau("MET") + cuts.cutWTau("dPhiJJ");
    TCut cutWTau_C_Mjj        = cutD + cuts.cutWTau("wTau") + cuts.cutWTau("trigger") + cuts.cutWTau("lVeto") + cuts.cutWTau("dijet") + cuts.cutWTau("dEtaJJ") + cuts.cutWTau("MET") + cuts.cutWTau("dPhiJJ");
    
    TCut cutWMu_MCC_MET       = cuts.wMuGen() + cuts.wMuVBF() + cuts.cutWMu("dPhiJJ");
    TCut cutWMu_C_MET         = cutD + cuts.wMuVBF()+ cuts.cutWMu("dPhiJJ");
    TCut cutWTau_MCC_MET      = cuts.wTauGen() + cuts.cutWTau("wTau") + cuts.cutWTau("trigger") + cuts.cutWTau("lVeto") + cuts.cutWTau("dijet") + cuts.cutWTau("dEtaJJ") + cuts.cutWTau("Mjj") + cuts.cutWTau("dPhiJJ");
    TCut cutWTau_C_MET        = cutD + cuts.cutWTau("wTau") + cuts.cutWTau("trigger") + cuts.cutWTau("lVeto") + cuts.cutWTau("dijet") + cuts.cutWTau("dEtaJJ") + cuts.cutWTau("Mjj") + cuts.cutWTau("dPhiJJ");
    
    TCut cutWMu_MCC_CenJetEt  = cuts.wMuGen() + cuts.cutWMu("trigger") + cuts.cutWMu("lVeto") + cuts.cutWMu("wMu") + cuts.cutWMu("dijet") + cuts.cutWMu("dEtaJJ") + cuts.cutWMu("Mjj") + cuts.cutWMu("MET") + cuts.cutWMu("dPhiJJ");
    TCut cutWMu_C_CenJetEt    = cutD + cuts.cutWMu("trigger") + cuts.cutWMu("lVeto") + cuts.cutWMu("wMu") + cuts.cutWMu("dijet") + cuts.cutWMu("dEtaJJ") + cuts.cutWMu("Mjj") + cuts.cutWMu("MET") + cuts.cutWMu("dPhiJJ");
    TCut cutWTau_MCC_CenJetEt = cuts.wTauGen() + cutTightMjj_basic + cuts.cutWTau("wTau") + cuts.cutWTau("dPhiJJ");
    TCut cutWTau_C_CenJetEt   = cutD + cutTightMjj_basic + cuts.cutWTau("wTau") + cuts.cutWTau("dPhiJJ");

    // TEMP HISTS - DPhiJJ
    TH1D* hWMu_MCGen_DPhi_tmp      = new TH1D("hWMu_MCGen_DPhi_tmp", "",1, 0,1);  // W+jets Mu MC gen
    TH1D* hWTau_MCGen_DPhi_tmp     = new TH1D("hWTau_MCGen_DPhi_tmp", "",1, 0,1);  // W+jets Tau MC gen

    // tmp histograms - WMu
    TH1D* hWMu_MCC_DPhi_tmp        = new TH1D("hWMu_MCC_DPhi_tmp",   "",4,dphiEdges);  // W+jets MC ctrl region
    TH1D* hWMu_DataC_DPhi_tmp      = new TH1D("hWMu_DataC_DPhi_tmp", "",4,dphiEdges); // Data in WMu ctrl region
    TH1D* hWMu_BGC_DPhi_tmp        = new TH1D("hWMu_BGC_DPhi_tmp",   "",4,dphiEdges); //BG in WMu ctrl region
    
    // tmp histograms - wTau
    TH1D* hWTau_MCC_DPhi_tmp       = new TH1D("hWTau_MCC_DPhi_tmp",   "",4,dphiEdges);  // W+jets MC ctrl region
    TH1D* hWTau_DataC_DPhi_tmp     = new TH1D("hWTau_DataC_DPhi_tmp", "",4,dphiEdges); // Data in WTau ctrl region
    TH1D* hWTau_BGC_DPhi_tmp       = new TH1D("hWTau_BGC_DPhi_tmp",   "",4,dphiEdges); // BG in WTau ctrl region

    // TEMP HISTS - Mjj
    // tmp histograms - WMu
    TH1D* hWMu_MCC_Mjj_tmp         = new TH1D("hWMu_MCC_Mjj_tmp",   "",4,MjjEdges);  // W+jets MC ctrl region
    TH1D* hWMu_DataC_Mjj_tmp       = new TH1D("hWMu_DataC_Mjj_tmp", "",4,MjjEdges);
    TH1D* hWMu_BGC_Mjj_tmp         = new TH1D("hWMu_BGC_Mjj_tmp",   "",4,MjjEdges);
    
    // tmp histograms - wTau
    TH1D* hWTau_MCC_Mjj_tmp        = new TH1D("hWTau_MCC_Mjj_tmp",   "",4,MjjEdges);  // W+jets MC ctrl region
    TH1D* hWTau_DataC_Mjj_tmp      = new TH1D("hWTau_DataC_Mjj_tmp", "",4,MjjEdges);
    TH1D* hWTau_BGC_Mjj_tmp        = new TH1D("hWTau_BGC_Mjj_tmp",   "",4,MjjEdges);
    
    // TEMP HISTS - MET
    // tmp histograms - WMu
    TH1D* hWMu_MCC_MET_tmp         = new TH1D("hWMu_MCC_MET_tmp",   "",4,METEdges);  // W+jets MC ctrl region
    TH1D* hWMu_DataC_MET_tmp       = new TH1D("hWMu_DataC_MET_tmp", "",4,METEdges);
    TH1D* hWMu_BGC_MET_tmp         = new TH1D("hWMu_BGC_MET_tmp",   "",4,METEdges);
    
    // tmp histograms - wTau
    TH1D* hWTau_MCC_MET_tmp        = new TH1D("hWTau_MCC_MET_tmp",   "",4,METEdges);  // W+jets MC ctrl region
    TH1D* hWTau_DataC_MET_tmp      = new TH1D("hWTau_DataC_MET_tmp", "",4,METEdges);
    TH1D* hWTau_BGC_MET_tmp        = new TH1D("hWTau_BGC_MET_tmp",   "",4,METEdges);
    
    // TEMP HISTS - CenJetEt
    // tmp histograms - WMu
    TH1D* hWMu_MCC_CenJetEt_tmp    = new TH1D("hWMu_MCC_CenJetEt_tmp",   "",4,CenJetEtEdges);  // W+jets MC ctrl region
    TH1D* hWMu_DataC_CenJetEt_tmp  = new TH1D("hWMu_DataC_CenJetEt_tmp", "",4,CenJetEtEdges);
    TH1D* hWMu_BGC_CenJetEt_tmp    = new TH1D("hWMu_BGC_CenJetEt_tmp",   "",4,CenJetEtEdges);
    
    // tmp histograms - wTau
    TH1D* hWTau_MCC_CenJetEt_tmp   = new TH1D("hWTau_MCC_CenJetEt_tmp",   "",4,CenJetEtEdges);  // W+jets MC ctrl region
    TH1D* hWTau_DataC_CenJetEt_tmp = new TH1D("hWTau_DataC_CenJetEt_tmp", "",4,CenJetEtEdges);
    TH1D* hWTau_BGC_CenJetEt_tmp   = new TH1D("hWTau_BGC_CenJetEt_tmp",   "",4,CenJetEtEdges);

    // Weight to lumi
    double weight = (dataset.isData) ? 1. : (lumi * dataset.sigma / dataset.nEvents);
    if(dataset.name == "EWK_ZvvFake") weight *= constants::ratioZToNuNuZToLL;

    // check it's  W+Jets
    bool isWJets = false;
    bool isEwkW  = false;
    if (dataset.name == "WJets" ||
        dataset.name == "W1Jets" || 
        dataset.name == "W2Jets" || 
        dataset.name == "W3Jets" || 
        dataset.name == "W4Jets" ||
        dataset.name == "EWK_Wp2Jets" ||
        dataset.name == "EWK_Wm2Jets") {

      std::cout << "Analysing W MC     : " << dataset.name << std::endl;
      std::cout << "  weight : " << weight << std::endl;

      if (dataset.name == "EWK_Wp2Jets" || dataset.name == "EWK_Wm2Jets") isEwkW = true;
      else isWJets = true;

      if(isWJets) wWeight =  cuts.wWeight();

      // Mu cuts
      tree->Draw("vbfDPhi>>hWMu_MCC_DPhi_tmp", otherCutsTight * wWeight * cutWMu_MCC_DPhi);
      tree->Draw("0.5>>hWMu_MCGen_DPhi_tmp", otherCutsTight * wWeight * cutWMu_Gen);
      tree->Draw("vbfM>>hWMu_MCC_Mjj_tmp", otherCutsTight * wWeight * cutWMu_MCC_Mjj);
      tree->Draw("metNoWLepton>>hWMu_MCC_MET_tmp", otherCutsTight * wWeight * cutWMu_MCC_MET);
      tree->Draw("cenJetEt>>hWMu_MCC_CenJetEt_tmp", otherCutsTight * wWeight * cutWMu_MCC_CenJetEt);

      hWMu_MCC_DPhi_tmp->Scale(weight);
      hWMu_MCGen_DPhi_tmp->Scale(weight);
      hWMu_MCC_Mjj_tmp->Scale(weight);
      hWMu_MCC_MET_tmp->Scale(weight);
      hWMu_MCC_CenJetEt_tmp->Scale(weight);
      
      // add to final histogram
      hWMu_MCC_DPhi->Add(hWMu_MCC_DPhi_tmp);
      hWMu_MCGen_DPhi->Add(hWMu_MCGen_DPhi_tmp);
      hWMu_MCC_Mjj->Add(hWMu_MCC_Mjj_tmp);
      hWMu_MCC_MET->Add(hWMu_MCC_MET_tmp);
      hWMu_MCC_CenJetEt->Add(hWMu_MCC_CenJetEt_tmp);

      tree->Draw("vbfDPhi>>hWTau_MCC_DPhi_tmp", otherCutsVeto * wWeight * cutWTau_MCC_DPhi);
      tree->Draw("0.5>>hWTau_MCGen_DPhi_tmp", otherCutsVeto * wWeight * cutWTau_Gen);
      tree->Draw("vbfM>>hWTau_MCC_Mjj_tmp", otherCutsVeto * wWeight * cutWTau_MCC_Mjj);
      tree->Draw("met>>hWTau_MCC_MET_tmp", otherCutsVeto * wWeight * cutWTau_MCC_MET);
      tree->Draw("cenJetEt>>hWTau_MCC_CenJetEt_tmp", otherCutsVeto * wWeight * cutWTau_MCC_CenJetEt);

      hWTau_MCC_DPhi_tmp->Scale(weight);
      hWTau_MCGen_DPhi_tmp->Scale(weight);
      hWTau_MCC_Mjj_tmp->Scale(weight);
      hWTau_MCC_MET_tmp->Scale(weight);
      hWTau_MCC_CenJetEt_tmp->Scale(weight);
      
      // add to final histogram
      hWTau_MCC_DPhi->Add(hWTau_MCC_DPhi_tmp);
      hWTau_MCGen_DPhi->Add(hWTau_MCGen_DPhi_tmp);
      hWTau_MCC_Mjj->Add(hWTau_MCC_Mjj_tmp);
      hWTau_MCC_MET->Add(hWTau_MCC_MET_tmp);
      hWTau_MCC_CenJetEt->Add(hWTau_MCC_CenJetEt_tmp);

    } else if (dataset.isData) {
     
      std::cout << "Analysing Data     : " << dataset.name << std::endl;

      // Mu region
      tree->Draw("vbfDPhi>>hWMu_DataC_DPhi_tmp", cutWMu_C_DPhi);
      hWMu_DataC_DPhi->Add(hWMu_DataC_DPhi_tmp);

      tree->Draw("vbfM>>hWMu_DataC_Mjj_tmp", cutWMu_C_Mjj);
      hWMu_DataC_Mjj->Add(hWMu_DataC_Mjj_tmp);

      tree->Draw("metNoWLepton>>hWMu_DataC_MET_tmp", cutWMu_C_MET);
      hWMu_DataC_MET->Add(hWMu_DataC_MET_tmp);

      tree->Draw("cenJetEt>>hWMu_DataC_CenJetEt_tmp", cutWMu_C_CenJetEt);
      hWMu_DataC_CenJetEt->Add(hWMu_DataC_CenJetEt_tmp);

      // Tau region
      tree->Draw("vbfDPhi>>hWTau_DataC_DPhi_tmp", cutWTau_C_DPhi);
      hWTau_DataC_DPhi->Add(hWTau_DataC_DPhi_tmp);

      tree->Draw("vbfM>>hWTau_DataC_Mjj_tmp", cutWTau_C_Mjj);
      hWTau_DataC_Mjj->Add(hWTau_DataC_Mjj_tmp);

      tree->Draw("met>>hWTau_DataC_MET_tmp", cutWTau_C_MET);
      hWTau_DataC_MET->Add(hWTau_DataC_MET_tmp);

      tree->Draw("cenJetEt>>hWTau_DataC_CenJetEt_tmp", cutWTau_C_CenJetEt);
      hWTau_DataC_CenJetEt->Add(hWTau_DataC_CenJetEt_tmp);
    
      std::cout << "  N ctrl region (dphi<1) : " << hWTau_DataC_DPhi_tmp->GetBinContent(1) << " +/- " << hWTau_DataC_DPhi_tmp->GetBinError(1) << std::endl;// debug output

    } else {
    
      std::cout << "Analysing BG MC    : " << dataset.name << std::endl;
      std::cout << "  weight : " << weight << std::endl;

      if (dataset.name.compare(0,17,"SignalM125_POWHEG")== 0 || dataset.name.compare(0,3,"QCD") == 0) continue;

      if(dataset.name.compare(0,3,"Zvv") != 0 && dataset.name != "EWK_ZvvFake"){ // Don't need Zvv in WMu estimates
        tree->Draw("vbfDPhi>>hWMu_BGC_DPhi_tmp", otherCutsTight * cutWMu_C_DPhi);
        tree->Draw("vbfM>>hWMu_BGC_Mjj_tmp", otherCutsTight * cutWMu_C_Mjj);
        tree->Draw("metNoWLepton>>hWMu_BGC_MET_tmp", otherCutsTight * cutWMu_C_MET);
        tree->Draw("cenJetEt>>hWMu_BGC_CenJetEt_tmp", otherCutsTight * cutWMu_C_CenJetEt);
        
        hWMu_BGC_DPhi_tmp->Scale(weight);
      	hWMu_BGC_Mjj_tmp->Scale(weight);
        hWMu_BGC_MET_tmp->Scale(weight);
        hWMu_BGC_CenJetEt_tmp->Scale(weight);
        
        hWMu_BGC_DPhi->Add(hWMu_BGC_DPhi_tmp);
        hWMu_BGC_Mjj->Add(hWMu_BGC_Mjj_tmp);
        hWMu_BGC_MET->Add(hWMu_BGC_MET_tmp);
        hWMu_BGC_CenJetEt->Add(hWMu_BGC_CenJetEt_tmp);
      } 

      // Count number of tau in control region in bg mc
      tree->Draw("vbfDPhi>>hWTau_BGC_DPhi_tmp", otherCutsVeto * cutWTau_C_DPhi);
      tree->Draw("vbfM>>hWTau_BGC_Mjj_tmp", otherCutsVeto * cutWTau_C_Mjj);
      tree->Draw("met>>hWTau_BGC_MET_tmp", otherCutsVeto * cutWTau_C_MET);
      tree->Draw("cenJetEt>>hWTau_BGC_CenJetEt_tmp", otherCutsVeto * cutWTau_C_CenJetEt);

      hWTau_BGC_DPhi_tmp->Scale(weight);
      hWTau_BGC_Mjj_tmp->Scale(weight);
      hWTau_BGC_MET_tmp->Scale(weight);
      hWTau_BGC_CenJetEt_tmp->Scale(weight);

      hWTau_BGC_DPhi->Add(hWTau_BGC_DPhi_tmp);
      hWTau_BGC_Mjj->Add(hWTau_BGC_Mjj_tmp);
      hWTau_BGC_MET->Add(hWTau_BGC_MET_tmp);
      hWTau_BGC_CenJetEt->Add(hWTau_BGC_CenJetEt_tmp);

      // debug output
      std::cout << "  N ctrl region (dphi<1) : " << hWTau_BGC_DPhi_tmp->GetBinContent(1) << " +/- " << hWTau_BGC_DPhi_tmp->GetBinError(1) << std::endl;
      std::cout << "  N ctrl region (MET)    : " << hWTau_BGC_MET_tmp->GetBinContent(1) << " +/- " << hWTau_BGC_MET_tmp->GetBinError(1) << std::endl;

    }

        
    // debug output
    // std::cout << "  N ctrl region (dphi<1) : " << hWMu_C_DPhi->GetBinContent(1) << " +/- " << hWMu_C_DPhi->GetBinError(1) << std::endl;
    
    delete hWMu_MCC_DPhi_tmp;
    delete hWMu_MCGen_DPhi_tmp;
    delete hWMu_DataC_DPhi_tmp;
    delete hWMu_BGC_DPhi_tmp;

    delete hWTau_MCC_DPhi_tmp;
    delete hWTau_MCGen_DPhi_tmp;
    delete hWTau_DataC_DPhi_tmp;
    delete hWTau_BGC_DPhi_tmp;

    delete hWMu_MCC_Mjj_tmp;
    delete hWMu_DataC_Mjj_tmp;
    delete hWMu_BGC_Mjj_tmp;
    
    delete hWTau_MCC_Mjj_tmp;
    delete hWTau_DataC_Mjj_tmp;
    delete hWTau_BGC_Mjj_tmp;

    delete hWMu_MCC_MET_tmp;
    delete hWMu_DataC_MET_tmp;
    delete hWMu_BGC_MET_tmp;
    
    delete hWTau_MCC_MET_tmp;
    delete hWTau_DataC_MET_tmp;
    delete hWTau_BGC_MET_tmp;

    delete hWMu_MCC_CenJetEt_tmp;
    delete hWMu_DataC_CenJetEt_tmp;
    delete hWMu_BGC_CenJetEt_tmp;
    
    delete hWTau_MCC_CenJetEt_tmp;
    delete hWTau_DataC_CenJetEt_tmp;
    delete hWTau_BGC_CenJetEt_tmp;

    file->Close();
    // ofile->Close();
   
  } // end of datasets loop

  //for (int i=1; i<=hWTau_BGC_DPhi->GetNbinsX(); ++i) hWTau_BGC_DPhi->SetBinError(i,0.); // no stat error from mc
  //for (int i=1; i<=hWMu_BGC_DPhi->GetNbinsX(); ++i) hWMu_BGC_DPhi->SetBinError(i,0.); // no stat error from mc

  //for (int i=1; i<=hWTau_BGC_MET->GetNbinsX(); ++i) hWTau_BGC_MET->SetBinError(i,0.); // no stat error from mc
  //for (int i=1; i<=hWMu_BGC_MET->GetNbinsX(); ++i) hWMu_BGC_MET->SetBinError(i,0.); // no stat error from mc

  //for (int i=1; i<=hWTau_BGC_CenJetEt->GetNbinsX(); ++i) hWTau_BGC_CenJetEt->SetBinError(i,0.); // no stat error from mc
  //for (int i=1; i<=hWMu_BGC_CenJetEt->GetNbinsX(); ++i) hWMu_BGC_CenJetEt->SetBinError(i,0.); // no stat error from mc

  // W->mu
  TH1D* hWMu_EstC_DPhi = new TH1D("hWMu_EstC_DPhi", "", 4, dphiEdges); // n_data - n_bg in WMu control
  hWMu_EstC_DPhi->Add(hWMu_DataC_DPhi, hWMu_BGC_DPhi, 1., -1.);
  TH1D* hWMu_EstC_Mjj = new TH1D("hWMu_EstC_Mjj", "", 4, MjjEdges); // n_data - n_bg in WMu control
  hWMu_EstC_Mjj->Add(hWMu_DataC_Mjj, hWMu_BGC_Mjj, 1., -1.);
  TH1D* hWMu_EstC_MET = new TH1D("hWMu_EstC_MET", "", 4, METEdges); // n_data - n_bg in WMu control
  hWMu_EstC_MET->Add(hWMu_DataC_MET, hWMu_BGC_MET, 1., -1.);
  TH1D* hWMu_EstC_CenJetEt = new TH1D("hWMu_EstC_CenJetEt", "", 4, CenJetEtEdges); // n_data - n_bg in WMu control
  hWMu_EstC_CenJetEt->Add(hWMu_DataC_CenJetEt, hWMu_BGC_CenJetEt, 1., -1.);

  // W->Tau
  TH1D* hWTau_EstC_DPhi = new TH1D("hWTau_EstC_DPhi", "", 4, dphiEdges); // n_data - n_bg in WTau control
  hWTau_EstC_DPhi->Add(hWTau_DataC_DPhi, hWTau_BGC_DPhi, 1., -1.);
  TH1D* hWTau_EstC_Mjj = new TH1D("hWTau_EstC_Mjj", "", 4, MjjEdges); // n_data - n_bg in WTau control
  hWTau_EstC_Mjj->Add(hWTau_DataC_Mjj, hWTau_BGC_Mjj, 1., -1.);
  TH1D* hWTau_EstC_MET = new TH1D("hWTau_EstC_MET", "", 4, METEdges); // n_data - n_bg in WTau control
  hWTau_EstC_MET->Add(hWTau_DataC_MET, hWTau_BGC_MET, 1., -1.);
  TH1D* hWTau_EstC_CenJetEt = new TH1D("hWTau_EstC_CenJetEt", "", 4, CenJetEtEdges); // n_data - n_bg in WTau control
  hWTau_EstC_CenJetEt->Add(hWTau_DataC_CenJetEt, hWTau_BGC_CenJetEt, 1., -1.);

  TH1D* h_RGEN = new TH1D("h_RGEN","",1,0,1.);
  h_RGEN->Divide(hWMu_MCGen_DPhi,hWTau_MCGen_DPhi,1.,1.);

  TH1D* h_RVBF_DPhi = new TH1D("h_RVBF_DPhi","",4,dphiEdges);
  h_RVBF_DPhi->Divide(hWTau_MCC_DPhi,hWMu_MCC_DPhi,1.,1.);
  TH1D* h_RVBF_Mjj = new TH1D("h_RVBF_Mjj","",4,MjjEdges);
  h_RVBF_Mjj->Divide(hWTau_MCC_Mjj,hWMu_MCC_Mjj,1.,1.);
  TH1D* h_RVBF_MET = new TH1D("h_RVBF_MET","",4,METEdges);
  h_RVBF_MET->Divide(hWTau_MCC_MET,hWMu_MCC_MET,1.,1.);
  TH1D* h_RVBF_CenJetEt = new TH1D("h_RVBF_CenJetEt","",4,CenJetEtEdges);
  h_RVBF_CenJetEt->Divide(hWTau_MCC_CenJetEt,hWMu_MCC_CenJetEt,1.,1.);

  //for (int i=1; i<=h_RGEN->GetNbinsX(); ++i)h_RGEN->SetBinError(i,0.); // no stat error from mc
  //for (int i=1; i<=h_RVBF_DPhi->GetNbinsX(); ++i) h_RVBF_DPhi->SetBinError(i,0.); // no stat error from mc
  //for (int i=1; i<=h_RVBF_MET->GetNbinsX(); ++i) h_RVBF_MET->SetBinError(i,0.); // no stat error from mc
  //for (int i=1; i<=h_RVBF_CenJetEt->GetNbinsX(); ++i) h_RVBF_CenJetEt->SetBinError(i,0.); // no stat error from mc
  
  TH1D* h_R_DPhi     = new TH1D("h_R_DPhi","",4,dphiEdges);
  TH1D* h_R_Mjj      = new TH1D("h_R_Mjj","",4,MjjEdges);
  TH1D* h_R_MET      = new TH1D("h_R_MET","",4,METEdges);
  TH1D* h_R_CenJetEt = new TH1D("h_R_CenJetEt","",4,CenJetEtEdges);
 
  for (int ibin = 1; ibin <= h_R_DPhi->GetNbinsX(); ++ibin){
    h_R_DPhi->SetBinContent(ibin, h_RVBF_DPhi->GetBinContent(ibin) * h_RGEN->GetBinContent(1));
    h_R_DPhi->SetBinError(ibin, h_R_DPhi->GetBinContent(ibin) * sqrt(pow(h_RVBF_DPhi->GetBinError(ibin)/h_RVBF_DPhi->GetBinContent(ibin),2) + pow(h_RGEN->GetBinError(1)/ h_RGEN->GetBinContent(1),2)));
  }
  for (int ibin = 1; ibin <= h_R_Mjj->GetNbinsX(); ++ibin){
    h_R_Mjj->SetBinContent(ibin, h_RVBF_Mjj->GetBinContent(ibin) * h_RGEN->GetBinContent(1));
    h_R_Mjj->SetBinError(ibin, h_R_Mjj->GetBinContent(ibin) * sqrt(pow(h_RVBF_Mjj->GetBinError(ibin)/h_RVBF_Mjj->GetBinContent(ibin),2) + pow(h_RGEN->GetBinError(1)/ h_RGEN->GetBinContent(1),2)));
  }
  for (int ibin = 1; ibin <= h_R_MET->GetNbinsX(); ++ibin){
    h_R_MET->SetBinContent(ibin, h_RVBF_MET->GetBinContent(ibin) * h_RGEN->GetBinContent(1));
    h_R_MET->SetBinError(ibin, h_R_MET->GetBinContent(ibin) * sqrt(pow(h_RVBF_MET->GetBinError(ibin)/h_RVBF_MET->GetBinContent(ibin),2) + pow(h_RGEN->GetBinError(1)/ h_RGEN->GetBinContent(1),2)));
  }
  for (int ibin = 1; ibin <= h_R_CenJetEt->GetNbinsX(); ++ibin){
    h_R_CenJetEt->SetBinContent(ibin, h_RVBF_CenJetEt->GetBinContent(ibin) * h_RGEN->GetBinContent(1));
    h_R_CenJetEt->SetBinError(ibin, h_R_CenJetEt->GetBinContent(ibin) * sqrt(pow(h_RVBF_CenJetEt->GetBinError(ibin)/h_RVBF_CenJetEt->GetBinContent(ibin),2) + pow(h_RGEN->GetBinError(1)/ h_RGEN->GetBinContent(1),2)));
  }

  // lets calculate some stuff
  TH1D* hWTau_Prediction_DPhi = new TH1D("hWTau_Prediction_DPhi","",4,dphiEdges);
  hWTau_Prediction_DPhi->Add(hWMu_EstC_DPhi,1.);
  hWTau_Prediction_DPhi->Multiply(h_R_DPhi);

  TH1D* hWTau_Prediction_Mjj = new TH1D("hWTau_Prediction_Mjj","",4,MjjEdges);
  hWTau_Prediction_Mjj->Add(hWMu_EstC_Mjj,1.);
  hWTau_Prediction_Mjj->Multiply(h_R_Mjj);

  TH1D* hWTau_Prediction_MET = new TH1D("hWTau_Prediction_MET","",4,METEdges);
  hWTau_Prediction_MET->Add(hWMu_EstC_MET,1.);
  hWTau_Prediction_MET->Multiply(h_R_MET);

  TH1D* hWTau_Prediction_CenJetEt = new TH1D("hWTau_Prediction_CenJetEt","",4,CenJetEtEdges);
  hWTau_Prediction_CenJetEt->Add(hWMu_EstC_CenJetEt,1.);
  hWTau_Prediction_CenJetEt->Multiply(h_R_CenJetEt);

  double xsecRatio = (0.1125*0.6476)/(0.1057+(0.1125*0.1741)); // Ratio of w->Tau cross-section to w-?mu cross section (includes w->mu and w->tau->mu)
  hWTau_Prediction_DPhi->Scale(xsecRatio);
  hWTau_Prediction_Mjj->Scale(xsecRatio);
  hWTau_Prediction_MET->Scale(xsecRatio);
  hWTau_Prediction_CenJetEt->Scale(xsecRatio);

  ///////////////////////////
  // Lots of screen output //
  ///////////////////////////
  std::cout << std::endl;
  std::cout << "***************** W Tau closure test from W Mu *****************" << std::endl;
  std::cout << std::endl;
  std::cout << "--- Binned by DPhiJJ ---" << std::endl;
  for (int a = 0; a < 4; a++){
    std::cout << std::endl;
    std::cout << "Bin: " << dphiEdges[a] << " < dphi < " << dphiEdges[a+1] << "" << std::endl;
    std::cout << "W->mu channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl                                  : " << hWMu_MCC_DPhi->GetBinContent(a+1) << " +/- " << hWMu_MCC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << "  W+jets at gen level                                    : " << hWMu_MCGen_DPhi->GetBinContent(a+1) << " +/- " << hWMu_MCGen_DPhi->GetBinError(a+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWMu_BGC_DPhi->GetBinContent(a+1) << " +/- " << hWMu_BGC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWMu_DataC_DPhi->GetBinContent(a+1) << " +/- " << hWMu_DataC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << "  Data-bg ctrl region                                    : " << hWMu_EstC_DPhi->GetBinContent(a+1) << " +/- " << hWMu_EstC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << std::endl;
    std::cout << "W->tau channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl (MC estimate in ctrl)            : " << hWTau_MCC_DPhi->GetBinContent(a+1) << " +/- " << hWTau_MCC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << "  W+jets at gen level                                    : " << hWTau_MCGen_DPhi->GetBinContent(a+1) << " +/- " << hWTau_MCGen_DPhi->GetBinError(a+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWTau_BGC_DPhi->GetBinContent(a+1) << " +/- " << hWTau_BGC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWTau_DataC_DPhi->GetBinContent(a+1) << " +/- " << hWTau_DataC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  WTau in ctrl region observed                           : " << hWTau_EstC_DPhi->GetBinContent(a+1) << " +/- " << hWTau_EstC_DPhi->GetBinError(a+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  Closure test: WTau from WMu                            : " << hWTau_Prediction_DPhi->GetBinContent(a+1) << " +/- " << hWTau_Prediction_DPhi->GetBinError(a+1) << std::endl;
    std::cout << std::endl;
  }

  std::cout << std::endl;
  std::cout << "--- Binned by Mjj ---" << std::endl;
  for (int b = 0; b < 4; b++) {
    std::cout << std::endl;
    std::cout << "Bin: " << MjjEdges[b] << " < Mjj < " << MjjEdges[b+1] << "" << std::endl;
    std::cout << "W->mu channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl                                  : " << hWMu_MCC_Mjj->GetBinContent(b+1) << " +/- " << hWMu_MCC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWMu_BGC_Mjj->GetBinContent(b+1) << " +/- " << hWMu_BGC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWMu_DataC_Mjj->GetBinContent(b+1) << " +/- " << hWMu_DataC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << "  Data-bg ctrl region                                    : " << hWMu_EstC_Mjj->GetBinContent(b+1) << " +/- " << hWMu_EstC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
    std::cout << "W->tau channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl (MC estimate in ctrl)            : " << hWTau_MCC_Mjj->GetBinContent(b+1) << " +/- " << hWTau_MCC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWTau_BGC_Mjj->GetBinContent(b+1) << " +/- " << hWTau_BGC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWTau_DataC_Mjj->GetBinContent(b+1) << " +/- " << hWTau_DataC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  WTau in ctrl region observed                           : " << hWTau_EstC_Mjj->GetBinContent(b+1) << " +/- " << hWTau_EstC_Mjj->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  Closure test: WTau from WMu                            : " << hWTau_Prediction_Mjj->GetBinContent(b+1) << " +/- " << hWTau_Prediction_Mjj->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
  }

  std::cout << std::endl;
  std::cout << "--- Binned by MET ---" << std::endl;
  for (int b = 0; b < 4; b++) {
    std::cout << std::endl;
    std::cout << "Bin: " << METEdges[b] << " < MET < " << METEdges[b+1] << "" << std::endl;
    std::cout << "W->mu channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl                                  : " << hWMu_MCC_MET->GetBinContent(b+1) << " +/- " << hWMu_MCC_MET->GetBinError(b+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWMu_BGC_MET->GetBinContent(b+1) << " +/- " << hWMu_BGC_MET->GetBinError(b+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWMu_DataC_MET->GetBinContent(b+1) << " +/- " << hWMu_DataC_MET->GetBinError(b+1) << std::endl;
    std::cout << "  Data-bg ctrl region                                    : " << hWMu_EstC_MET->GetBinContent(b+1) << " +/- " << hWMu_EstC_MET->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
    std::cout << "W->tau channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl (MC estimate in ctrl)            : " << hWTau_MCC_MET->GetBinContent(b+1) << " +/- " << hWTau_MCC_MET->GetBinError(b+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWTau_BGC_MET->GetBinContent(b+1) << " +/- " << hWTau_BGC_MET->GetBinError(b+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWTau_DataC_MET->GetBinContent(b+1) << " +/- " << hWTau_DataC_MET->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  WTau in ctrl region observed                           : " << hWTau_EstC_MET->GetBinContent(b+1) << " +/- " << hWTau_EstC_MET->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  Closure test: WTau from WMu                            : " << hWTau_Prediction_MET->GetBinContent(b+1) << " +/- " << hWTau_Prediction_MET->GetBinError(b+1) << std::endl;
    std::cout << std::endl;
  }

  std::cout << std::endl;
  std::cout << "--- Binned by CenJetEt ---" << std::endl;
  for (int c = 0; c<4; c++){
    std::cout << std::endl;
    std::cout << "Bin: " << CenJetEtEdges[c] << " < Central Jet Et < " << CenJetEtEdges[c+1] << "" << std::endl;
    std::cout << "W->mu channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl                                  : " << hWMu_MCC_CenJetEt->GetBinContent(c+1) << " +/- " << hWMu_MCC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWMu_BGC_CenJetEt->GetBinContent(c+1) << " +/- " << hWMu_BGC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWMu_DataC_CenJetEt->GetBinContent(c+1) << " +/- " << hWMu_DataC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << "  Data-bg ctrl region                                    : " << hWMu_EstC_CenJetEt->GetBinContent(c+1) << " +/- " << hWMu_EstC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << std::endl;
    std::cout << "W->tau channel" << std::endl;
    std::cout << "  W+jets reco'd in ctrl (MC estimate in ctrl)            : " << hWTau_MCC_CenJetEt->GetBinContent(c+1) << " +/- " << hWTau_MCC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << "  Background ctrl region                                 : " << hWTau_BGC_CenJetEt->GetBinContent(c+1) << " +/- " << hWTau_BGC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << "  Data ctrl region                                       : " << hWTau_DataC_CenJetEt->GetBinContent(c+1) << " +/- " << hWTau_DataC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  WTau in ctrl region observed                           : " << hWTau_EstC_CenJetEt->GetBinContent(c+1) << " +/- " << hWTau_EstC_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << std::endl;
    std::cout << "  Closure test: WTau from WMu                            : " << hWTau_Prediction_CenJetEt->GetBinContent(c+1) << " +/- " << hWTau_Prediction_CenJetEt->GetBinError(c+1) << std::endl;
    std::cout << std::endl;
  }

  ////////////////////////
  // draw closure plots //
  ////////////////////////
  std::string pdfName;

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(111111111);

  double x_dPhi[4]  = {0.5, 1.4, 2.2, 2.6 + (TMath::Pi()-2.6)/2};
  double ex_dPhi[4] = {0.5, 0.4, 0.4, (TMath::Pi()-2.6)/2};
  double y_dPhi1[4],ey_dPhi1[4],y_dPhi2[4],ey_dPhi2[4],y_dPhi3[4],ey_dPhi3[4]; // For raw numbers - prediceted (data), observed, predicted (MC)
  double frac_dPhi[4],efrac_dPhi[4]; // For Frac diff

  // double MjjEdges[5]      = { 800., 1100., 1400., 1800., 3000. };

  double x_Mjj[4]   = {900., 1100., 1500., 2400.};
  double ex_Mjj[4]  = {100, 100, 300, 600};
  // double x_Mjj[4]   = {950., 1250., 1600., 2400.};
  // double ex_Mjj[4]  = {150, 150, 200, 600};
  double y_Mjj1[4],ey_Mjj1[4],y_Mjj2[4],ey_Mjj2[4],y_Mjj3[4],ey_Mjj3[4]; // For raw numbers - prediceted (data), observed, predicted (MC)
  double frac_Mjj[4],efrac_Mjj[4]; // For Frac diff

  double x_MET[4]   = {125., 175., 225., 275.};
  double ex_MET[4]  = {25, 25, 25, 25};
  double y_MET1[4],ey_MET1[4],y_MET2[4],ey_MET2[4],y_MET3[4],ey_MET3[4]; // For raw numbers - prediceted (data), observed, predicted (MC)
  double frac_MET[4],efrac_MET[4]; // For Frac diff

  //double x_CenJetEt[4]  = {25, 55, 95, 160};
  //double ex_CenJetEt[4] = {15, 15, 25, 40};
  double x_CenJetEt[4]   = {20., 45., 80., 125.};
  double ex_CenJetEt[4]  = {10, 15, 20, 25};  
  double y_CenJetEt1[4],ey_CenJetEt1[4],y_CenJetEt2[4],ey_CenJetEt2[4],y_CenJetEt3[4],ey_CenJetEt3[4]; // For raw numbers - prediceted (data), observed, predicted (MC)
  double frac_CenJetEt[4],efrac_CenJetEt[4]; // For Frac diff

  double y_syst[4],e_syst[4]; // for systematic bands

  for(int i=0; i<4; ++i) {
        y_syst[i] = 0.;
        //e_syst[i] = sqrt( pow(0.2,2) + pow(constants::syst_WTau,2) ); // 20% from MC stats, plus whatever the current value of Tau syst from TAU ID, w-e contamination, JER etc
	e_syst[i] = constants::syst_WTau;

        y_dPhi1[i]  = hWTau_Prediction_DPhi->GetBinContent(i+1);  //Predicted WTau
        ey_dPhi1[i] = hWTau_Prediction_DPhi->GetBinError(i+1);
        y_dPhi2[i]  = hWTau_EstC_DPhi->GetBinContent(i+1);        //Observed WTau
        ey_dPhi2[i] = hWTau_EstC_DPhi->GetBinError(i+1);  
        y_dPhi3[i]  = hWTau_MCC_DPhi->GetBinContent(i+1);         //MC prediction
        ey_dPhi3[i] = hWTau_MCC_DPhi->GetBinError(i+1);
        frac_dPhi[i]  = (y_dPhi1[i]/y_dPhi2[i])-1.;
        efrac_dPhi[i] = (y_dPhi1[i]/y_dPhi2[i])*sqrt(pow(ey_dPhi1[i]/y_dPhi1[i],2) + pow(ey_dPhi2[i]/y_dPhi2[i],2));

        y_Mjj1[i]  = hWTau_Prediction_Mjj->GetBinContent(i+1);  //Predicted WTau
        ey_Mjj1[i] = hWTau_Prediction_Mjj->GetBinError(i+1);
        y_Mjj2[i]  = hWTau_EstC_Mjj->GetBinContent(i+1);        //Observed WTau
        ey_Mjj2[i] = hWTau_EstC_Mjj->GetBinError(i+1);  
        y_Mjj3[i]  = hWTau_MCC_Mjj->GetBinContent(i+1);         //MC prediction
        ey_Mjj3[i] = hWTau_MCC_Mjj->GetBinError(i+1);
        frac_Mjj[i]  = (y_Mjj1[i]/y_Mjj2[i])-1.;
        efrac_Mjj[i] = (y_Mjj1[i]/y_Mjj2[i])*sqrt(pow(ey_Mjj1[i]/y_Mjj1[i],2) + pow(ey_Mjj2[i]/y_Mjj2[i],2));

        y_MET1[i]  = hWTau_Prediction_MET->GetBinContent(i+1);  //Predicted WTau
        ey_MET1[i] = hWTau_Prediction_MET->GetBinError(i+1);
        y_MET2[i]  = hWTau_EstC_MET->GetBinContent(i+1);        //Observed WTau
        ey_MET2[i] = hWTau_EstC_MET->GetBinError(i+1);  
        y_MET3[i]  = hWTau_MCC_MET->GetBinContent(i+1);         //MC prediction
        ey_MET3[i] = hWTau_MCC_MET->GetBinError(i+1);
        frac_MET[i]  = (y_MET1[i]/y_MET2[i])-1.;
        efrac_MET[i] = (y_MET1[i]/y_MET2[i])*sqrt(pow(ey_MET1[i]/y_MET1[i],2) + pow(ey_MET2[i]/y_MET2[i],2));

        y_CenJetEt1[i]  = hWTau_Prediction_CenJetEt->GetBinContent(i+1);  //Predicted WTau
        ey_CenJetEt1[i] = hWTau_Prediction_CenJetEt->GetBinError(i+1);
        y_CenJetEt2[i]  = hWTau_EstC_CenJetEt->GetBinContent(i+1);        //Observed WTau
        ey_CenJetEt2[i] = hWTau_EstC_CenJetEt->GetBinError(i+1);  
        y_CenJetEt3[i]  = hWTau_MCC_CenJetEt->GetBinContent(i+1);         //MC prediction
        ey_CenJetEt3[i] = hWTau_MCC_CenJetEt->GetBinError(i+1);
        frac_CenJetEt[i]  = (y_CenJetEt1[i]/y_CenJetEt2[i])-1.;
        efrac_CenJetEt[i] = (y_CenJetEt1[i]/y_CenJetEt2[i])*sqrt(pow(ey_CenJetEt1[i]/y_CenJetEt1[i],2) + pow(ey_CenJetEt2[i]/y_CenJetEt2[i],2));

  }

  TGraphErrors *gp_dPhi1 = new TGraphErrors(4,x_dPhi,y_dPhi1,ex_dPhi,ey_dPhi1);
  TGraphErrors *gp_dPhi2 = new TGraphErrors(4,x_dPhi,y_dPhi2,ex_dPhi,ey_dPhi2);
  TGraphErrors *gp_dPhi3 = new TGraphErrors(4,x_dPhi,y_dPhi3,ex_dPhi,ey_dPhi3);
  TGraphErrors *gp_dPhiF = new TGraphErrors(4,x_dPhi,frac_dPhi,ex_dPhi,efrac_dPhi);
  TGraphErrors *gp_dPhiS = new TGraphErrors(4,x_dPhi,y_syst,ex_dPhi,e_syst); // systematic error bands

  TGraphErrors *gp_Mjj1 = new TGraphErrors(4,x_Mjj,y_Mjj1,ex_Mjj,ey_Mjj1);
  TGraphErrors *gp_Mjj2 = new TGraphErrors(4,x_Mjj,y_Mjj2,ex_Mjj,ey_Mjj2);
  TGraphErrors *gp_Mjj3 = new TGraphErrors(4,x_Mjj,y_Mjj3,ex_Mjj,ey_Mjj3);
  TGraphErrors *gp_MjjF = new TGraphErrors(4,x_Mjj,frac_Mjj,ex_Mjj,efrac_Mjj);
  TGraphErrors *gp_MjjS = new TGraphErrors(4,x_Mjj,y_syst,ex_Mjj,e_syst); // systematic error bands

  TGraphErrors *gp_MET1 = new TGraphErrors(4,x_MET,y_MET1,ex_MET,ey_MET1);
  TGraphErrors *gp_MET2 = new TGraphErrors(4,x_MET,y_MET2,ex_MET,ey_MET2);
  TGraphErrors *gp_MET3 = new TGraphErrors(4,x_MET,y_MET3,ex_MET,ey_MET3);
  TGraphErrors *gp_METF = new TGraphErrors(4,x_MET,frac_MET,ex_MET,efrac_MET);
  TGraphErrors *gp_METS = new TGraphErrors(4,x_MET,y_syst,ex_MET,e_syst); // systematic error bands

  TGraphErrors *gp_CenJetEt1 = new TGraphErrors(4,x_CenJetEt,y_CenJetEt1,ex_CenJetEt,ey_CenJetEt1);
  TGraphErrors *gp_CenJetEt2 = new TGraphErrors(4,x_CenJetEt,y_CenJetEt2,ex_CenJetEt,ey_CenJetEt2);
  TGraphErrors *gp_CenJetEt3 = new TGraphErrors(4,x_CenJetEt,y_CenJetEt3,ex_CenJetEt,ey_CenJetEt3);
  TGraphErrors *gp_CenJetEtF = new TGraphErrors(4,x_CenJetEt,frac_CenJetEt,ex_CenJetEt,efrac_CenJetEt);
  TGraphErrors *gp_CenJetEtS = new TGraphErrors(4,x_CenJetEt,y_syst,ex_CenJetEt,e_syst); // systematic error bands

  TH1D *h_dPhi     = new TH1D("h_dPhi", "", 1, 0, TMath::Pi()); // For axes
  TH1D *h_Mjj      = new TH1D("h_Mjj", "", 1, 800, 3000); // For axes
  TH1D *h_MET      = new TH1D("h_MET", "", 1, 100, 300); // For axes
  TH1D *h_CenJetEt = new TH1D("h_CenJetEt", "", 1, 10, 150); // For axes

  TPaveText *cms = new TPaveText(0.12, 0.68, 0.58 , 0.88, "NDC");
  cms->SetFillColor(0);
  cms->SetFillStyle(4000);
  cms->SetBorderSize(0);
  cms->SetLineColor(0);
  cms->SetTextAlign(12);
  cms->AddText("CMS Preliminary");
  cms->AddText("");
  cms->AddText("#sqrt{s} = 8 TeV L = 19.6 fb^{-1}");
  cms->AddText("");

  TCanvas canvas; 
  canvas.SetCanvasSize(canvas.GetWindowWidth(), 1.2*canvas.GetWindowHeight());

  ///////////////////
  // DPhiJJ graphs //
  ///////////////////
  // Absolute numbers
  gp_dPhi1->SetTitle("");
  gp_dPhi1->SetMarkerStyle(20);
  gp_dPhi1->SetMarkerSize(0.9);
  gp_dPhi1->SetLineColor(kRed);
  gp_dPhi1->SetMarkerColor(kRed);
  gp_dPhi1->GetXaxis()->SetTitle("#Delta #phi_{jj}");
  gp_dPhi1->GetXaxis()->SetRangeUser(0,TMath::Pi());
  gp_dPhi1->GetYaxis()->SetTitle("N(W#rightarrow #tau#nu)");
  gp_dPhi1->GetYaxis()->SetTitleOffset(1.2);
  gp_dPhi1->GetYaxis()->SetRangeUser(0,80);
  gp_dPhi1->Draw("AP");
  gp_dPhi2->SetMarkerStyle(20);
  gp_dPhi2->SetMarkerSize(0.9);
  gp_dPhi2->SetLineColor(kBlue);
  gp_dPhi2->SetMarkerColor(kBlue);
  gp_dPhi2->Draw("P same");
  gp_dPhi3->SetMarkerStyle(20);
  gp_dPhi3->SetMarkerSize(0.9);
  gp_dPhi3->SetLineColor(kViolet);
  gp_dPhi3->SetMarkerColor(kViolet);
  gp_dPhi3->Draw("P same");

  TLegend leg(0.12,0.67,0.32,0.87);
  leg.SetBorderSize(0);
  leg.SetFillColor(0);
  leg.AddEntry(gp_dPhi1,"predicted (data)","P");
  leg.AddEntry(gp_dPhi2,"observed (data)","P");
  leg.AddEntry(gp_dPhi3,"predicted (MC)","P");
  leg.Draw();

  pdfName= options.oDir + std::string("/Wtaunu_dphi_num.pdf");
  canvas.Print(pdfName.c_str());

   // Fractional diff
  h_dPhi->Draw();
  h_dPhi->GetXaxis()->SetTitle("#Delta #phi_{jj}");
  h_dPhi->GetYaxis()->SetTitle("#frac{Predicted - Observed}{Observed}");
  h_dPhi->GetYaxis()->SetTitleOffset(1.2);
  h_dPhi->GetYaxis()->SetRangeUser(-1.0,2.0);
  h_dPhi->SetLineColor(kBlue);
  h_dPhi->SetLineWidth(2);
  h_dPhi->Draw();
  gp_dPhiS->SetLineColor(kGray);
  gp_dPhiS->SetLineWidth(0);
  gp_dPhiS->SetFillColor(kGray);
  gp_dPhiS->SetFillStyle(3001);
  gp_dPhiF->SetMarkerStyle(20);
  gp_dPhiF->SetMarkerSize(1.4);
  gp_dPhiF->SetMarkerColor(kBlue);
  gp_dPhiF->SetLineWidth(2);
  TF1 *f_dPhi = new TF1("f_dPhi","pol0",0,2.6); //To do a fit in first 3 bins only
  gp_dPhiF->Fit("f_dPhi","R");
  h_dPhi->Draw();
  gp_dPhiS->Draw("2 same");
  gp_dPhiF->Draw("P same");

  TLegend leg2_dphi(0.12,0.67,0.40,0.87);
  leg2_dphi.SetBorderSize(0);
  leg2_dphi.SetFillColor(0);
  leg2_dphi.AddEntry(f_dPhi,"pol0 fit (0 < #Delta #phi_{jj} < 2.6)","l");
  leg2_dphi.AddEntry(gp_dPhiS,"Systematic error","f");
  leg2_dphi.Draw();
  pdfName= options.oDir + std::string("/Wtaunu_dphi_frac.pdf");
  canvas.Print(pdfName.c_str());

  ////////////////
  // Mjj graphs //
  ////////////////
  gp_Mjj1->SetTitle("");
  gp_Mjj1->SetMarkerStyle(20);
  gp_Mjj1->SetMarkerSize(0.9);
  gp_Mjj1->SetLineColor(kRed);
  gp_Mjj1->SetMarkerColor(kRed);
  gp_Mjj1->GetXaxis()->SetTitle("M_{jj} [GeV]");
  gp_Mjj1->GetXaxis()->SetRangeUser(800.,3000.);
  gp_Mjj1->GetYaxis()->SetTitle("N(W#rightarrow #tau#nu)");
  gp_Mjj1->GetYaxis()->SetTitleOffset(1.2);
  gp_Mjj1->GetYaxis()->SetRangeUser(0.,50.);
  gp_Mjj1->Draw("AP");
  gp_Mjj2->SetMarkerStyle(20);
  gp_Mjj2->SetMarkerSize(0.9);
  gp_Mjj2->SetLineColor(kBlue);
  gp_Mjj2->SetMarkerColor(kBlue);
  gp_Mjj2->Draw("P same");
  gp_Mjj3->SetMarkerStyle(20);
  gp_Mjj3->SetMarkerSize(0.9);
  gp_Mjj3->SetLineColor(kViolet);
  gp_Mjj3->SetMarkerColor(kViolet);
  gp_Mjj3->Draw("P same");

  leg.Draw();

  pdfName= options.oDir + std::string("/Wtaunu_mjj_num.pdf");
  canvas.Print(pdfName.c_str());
 
  h_Mjj->Draw();
  h_Mjj->GetXaxis()->SetTitle("M_{jj} [GeV]");
  h_Mjj->GetYaxis()->SetTitle("#frac{Predicted - Observed}{Observed}");
  h_Mjj->GetYaxis()->SetTitleOffset(1.2);
  h_Mjj->GetYaxis()->SetRangeUser(-3.0,10.0);
  h_Mjj->SetLineColor(kBlue);
  h_Mjj->SetLineWidth(2);
  h_Mjj->Draw();
  gp_MjjS->SetLineColor(kGray);
  gp_MjjS->SetLineWidth(0);
  gp_MjjS->SetFillColor(kGray);
  gp_MjjS->SetFillStyle(3001);
  gp_MjjF->SetMarkerStyle(20);
  gp_MjjF->SetMarkerSize(1.4);
  gp_MjjF->SetMarkerColor(kBlue);
  gp_MjjF->SetLineWidth(2);
  TF1 *f_Mjj = new TF1("f_Mjj","pol0",800,3000);
  gp_MjjF->Fit("f_Mjj","R");
  h_Mjj->Draw();
  gp_MjjS->Draw("2 same");
  gp_MjjF->Draw("P same");

  TLegend leg2_mjj(0.12,0.67,0.40,0.87);
  leg2_mjj.SetBorderSize(0);
  leg2_mjj.SetFillColor(0);
  leg2_mjj.AddEntry(f_Mjj,"pol0 fit","l");
  leg2_mjj.AddEntry(gp_MjjS,"Systematic error","f");
  leg2_mjj.Draw();
  pdfName= options.oDir + std::string("/Wtaunu_mjj_frac.pdf");
  canvas.Print(pdfName.c_str());

  ////////////////
  // MET graphs //
  ////////////////
  gp_MET1->SetTitle("");
  gp_MET1->SetMarkerStyle(20);
  gp_MET1->SetMarkerSize(0.9);
  gp_MET1->SetLineColor(kRed);
  gp_MET1->SetMarkerColor(kRed);
  gp_MET1->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]");
  gp_MET1->GetXaxis()->SetRangeUser(100,300);
  gp_MET1->GetYaxis()->SetTitle("N(W#rightarrow #tau#nu)");
  gp_MET1->GetYaxis()->SetTitleOffset(1.2);
  gp_MET1->GetYaxis()->SetRangeUser(0,40);
  gp_MET1->Draw("AP");
  gp_MET2->SetMarkerStyle(20);
  gp_MET2->SetMarkerSize(0.9);
  gp_MET2->SetLineColor(kBlue);
  gp_MET2->SetMarkerColor(kBlue);
  gp_MET2->Draw("P same");
  gp_MET3->SetMarkerStyle(20);
  gp_MET3->SetMarkerSize(0.9);
  gp_MET3->SetLineColor(kViolet);
  gp_MET3->SetMarkerColor(kViolet);
  gp_MET3->Draw("P same");

  leg.Draw();

  pdfName= options.oDir + std::string("/Wtaunu_met_num.pdf");
  canvas.Print(pdfName.c_str());
 
  h_MET->Draw();
  h_MET->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]");
  h_MET->GetYaxis()->SetTitle("#frac{Predicted - Observed}{Observed}");
  h_MET->GetYaxis()->SetTitleOffset(1.2);
  h_MET->GetYaxis()->SetRangeUser(-3.0,5.0);
  h_MET->SetLineColor(kBlue);
  h_MET->SetLineWidth(2);
  h_MET->Draw();
  gp_METS->SetLineColor(kGray);
  gp_METS->SetLineWidth(0);
  gp_METS->SetFillColor(kGray);
  gp_METS->SetFillStyle(3001);
  gp_METF->SetMarkerStyle(20);
  gp_METF->SetMarkerSize(1.4);
  gp_METF->SetMarkerColor(kBlue);
  gp_METF->SetLineWidth(2);
  TF1 *f_MET = new TF1("f_MET","pol0",100,300);
  gp_METF->Fit("f_MET","R");
  h_MET->Draw();
  gp_METS->Draw("2 same");
  gp_METF->Draw("P same");

  TLegend leg2_met(0.12,0.67,0.40,0.87);
  leg2_met.SetBorderSize(0);
  leg2_met.SetFillColor(0);
  leg2_met.AddEntry(f_MET,"pol0 fit","l");
  leg2_met.AddEntry(gp_METS,"Systematic error","f");
  leg2_met.Draw();
  pdfName= options.oDir + std::string("/Wtaunu_met_frac.pdf");
  canvas.Print(pdfName.c_str());

  /////////////////////
  // CenJetEt graphs //
  /////////////////////
  gp_CenJetEt1->SetTitle("");
  gp_CenJetEt1->SetMarkerStyle(20);
  gp_CenJetEt1->SetMarkerSize(0.9);
  gp_CenJetEt1->SetLineColor(kRed);
  gp_CenJetEt1->SetMarkerColor(kRed);
  gp_CenJetEt1->GetXaxis()->SetTitle("Central Jet E_{T} [Gev]");
  gp_CenJetEt1->GetXaxis()->SetRangeUser(10,150);
  gp_CenJetEt1->GetYaxis()->SetTitle("N(W#rightarrow #tau#nu)");
  gp_CenJetEt1->GetYaxis()->SetTitleOffset(1.2);
  gp_CenJetEt1->GetYaxis()->SetRangeUser(0,40);
  gp_CenJetEt1->Draw("AP");
  gp_CenJetEt2->SetMarkerStyle(20);
  gp_CenJetEt2->SetMarkerSize(0.9);
  gp_CenJetEt2->SetLineColor(kBlue);
  gp_CenJetEt2->SetMarkerColor(kBlue);
  gp_CenJetEt2->Draw("P same");
  gp_CenJetEt3->SetMarkerStyle(20);
  gp_CenJetEt3->SetMarkerSize(0.9);
  gp_CenJetEt3->SetLineColor(kViolet);
  gp_CenJetEt3->SetMarkerColor(kViolet);
  gp_CenJetEt3->Draw("P same");

  leg.Draw();

  pdfName= options.oDir + std::string("/Wtaunu_CenJetEt_num.pdf");
  canvas.Print(pdfName.c_str());
 
  h_CenJetEt->Draw();
  h_CenJetEt->GetXaxis()->SetTitle("Central Jet E_{T} [Gev]");
  h_CenJetEt->GetYaxis()->SetTitle("#frac{Predicted - Observed}{Observed}");
  h_CenJetEt->GetYaxis()->SetTitleOffset(1.2);
  h_CenJetEt->GetYaxis()->SetRangeUser(-3.0,5.0);
  h_CenJetEt->SetLineColor(kBlue);
  h_CenJetEt->SetLineWidth(2);
  h_CenJetEt->Draw();
  gp_CenJetEtS->SetLineColor(kGray);
  gp_CenJetEtS->SetLineWidth(0);
  gp_CenJetEtS->SetFillColor(kGray);
  gp_CenJetEtS->SetFillStyle(3001);
  gp_CenJetEtF->SetMarkerStyle(20);
  gp_CenJetEtF->SetMarkerSize(1.4);
  gp_CenJetEtF->SetMarkerColor(kBlue);
  gp_CenJetEtF->SetLineWidth(2);
  TF1 *f_CenJetEt = new TF1("f_CenJetEt","pol0",10,150); 
  gp_CenJetEtF->Fit("f_CenJetEt","R");
  h_CenJetEt->Draw();
  gp_CenJetEtS->Draw("2 same");
  gp_CenJetEtF->Draw("P same");

  TLegend leg2_cenjet(0.12,0.67,0.40,0.87);
  leg2_cenjet.SetBorderSize(0);
  leg2_cenjet.SetFillColor(0);
  leg2_cenjet.AddEntry(f_CenJetEt,"pol0 fit","l");
  leg2_cenjet.AddEntry(gp_CenJetEtS,"Systematic error","f");
  leg2_cenjet.Draw();

  pdfName= options.oDir + std::string("/Wtaunu_CenJetEt_frac.pdf");
  canvas.Print(pdfName.c_str());


}
Exemple #10
0
void tnpScale_trigger( bool printplot = false ) {

  //----------------------------------------
  // Files
  //----------------------------------------

  char* version = (char*) "V00-00-07";

  TChain *chmc   = new TChain("leptons");
  TChain *chdata = new TChain("leptons");

  //char* suffix = "";
  char* suffix = "_2jets";

  //chmc->Add(Form("smurf/%s/dymm_test%s.root" , version , suffix));
  //chmc->Add(Form("smurf/%s/dymm_test%s_INCOMPLETE.root" , version , suffix));
  //chmc->Add(Form("smurf/%s/dymm_testskim%s.root" , version , suffix));
  //chmc->Add(Form("smurf/%s/dymm_test%s.root" , version , suffix));
  
  // chdata->Add(Form("smurf/%s/data_DoubleElectron_May10%s.root"    , version , suffix));
  // chdata->Add(Form("smurf/%s/data_DoubleElectron_PRv4%s.root"     , version , suffix));
  // chdata->Add(Form("smurf/%s/data_DoubleElectron_PRv6%s.root"     , version , suffix));
  // chdata->Add(Form("smurf/%s/data_DoubleElectron_Aug05%s.root"    , version , suffix));
  // chdata->Add(Form("smurf/%s/data_DoubleElectron_B30%s.root"      , version , suffix));
  // chdata->Add(Form("smurf/%s/data_DoubleElectron_B34%s.root"      , version , suffix));

  chdata->Add(Form("smurf/%s/data_SingleMu_May10%s.root"          , version , suffix));
  chdata->Add(Form("smurf/%s/data_SingleMu_PRv4%s.root"           , version , suffix));
  chdata->Add(Form("smurf/%s/data_SingleMu_Aug05%s.root"          , version , suffix));
  chdata->Add(Form("smurf/%s/data_SingleMu_PRv6%s.root"           , version , suffix));
  chdata->Add(Form("smurf/%s/data_SingleMu_B30%s.root"            , version , suffix));
  chdata->Add(Form("smurf/%s/data_SingleMu_B34%s.root"            , version , suffix));

  //----------------------------------------
  // bins 
  //----------------------------------------

  //float ptbin[] = {10., 15., 20., 30., 40., 50., 7000.};
  float ptbin[] = {30., 40., 10000.};
  float etabin[] = {0, 0.8, 1.5, 2.1};
  int nptbin=2;
  int netabin=3;

  TH2F *hdataid_deno 	= new TH2F("hdataid_deno", "hdataid_deno", nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_num 	= new TH2F("hdataid_num" , "hdataid_num" , nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_eff 	= new TH2F("hdataid_eff" , "hdataid_eff" , nptbin, ptbin, netabin, etabin);


  hdataid_deno->Sumw2();
  hdataid_num->Sumw2();
  hdataid_eff->Sumw2();

  //
  // histogram
  //
  //deno
  // TH2F *hmcid_deno 	= new TH2F("hmcid_deno", "hmcid_deno", nptbin, ptbin, netabin, etabin);
  // TH2F *hmciso_deno 	= new TH2F("hmciso_deno", "hmciso_deno", nptbin, ptbin, netabin, etabin);
  // TH2F *hdataid_deno 	= new TH2F("hdataid_deno", "hdataid_deno", nptbin, ptbin, netabin, etabin);
  // TH2F *hdataiso_deno	= new TH2F("hdataiso_deno", "hdataiso_deno", nptbin, ptbin, netabin, etabin);
  // hmcid_deno->Sumw2();
  // hmciso_deno->Sumw2();
  // hdataid_deno->Sumw2();
  // hdataiso_deno->Sumw2();
  // //num
  // TH2F *hmcid_num 	= new TH2F("hmcid_num", "hmcid_num", nptbin, ptbin, netabin, etabin);
  // TH2F *hmciso_num 	= new TH2F("hmciso_num", "hmciso_num", nptbin, ptbin, netabin, etabin);
  // TH2F *hdataid_num 	= new TH2F("hdataid_num", "hdataid_num", nptbin, ptbin, netabin, etabin);
  // TH2F *hdataiso_num 	= new TH2F("hdataiso_num", "hdataiso_num", nptbin, ptbin, netabin, etabin);
  // hmcid_num->Sumw2();
  // hmciso_num->Sumw2();
  // hdataid_num->Sumw2();
  // hdataiso_num->Sumw2();
  // // eff
  // TH2F *hmcid 	= new TH2F("hmcid", "hmcid", nptbin, ptbin, netabin, etabin);
  // TH2F *hmciso 	= new TH2F("hmciso", "hmciso", nptbin, ptbin, netabin, etabin);
  // TH2F *hdataid 	= new TH2F("hdataid", "hdataid", nptbin, ptbin, netabin, etabin);
  // TH2F *hdataiso 	= new TH2F("hdataiso", "hdataiso", nptbin, ptbin, netabin, etabin);
  // hmcid->Sumw2();
  // hmciso->Sumw2();
  // hdataid->Sumw2();
  // hdataiso->Sumw2();
  // // SF
  // TH2F *hsfid 	= new TH2F("hsfid", "hsfid", nptbin, ptbin, netabin, etabin);
  // TH2F *hsfiso 	= new TH2F("hsfiso", "hsfiso", nptbin, ptbin, netabin, etabin);
  // hsfid->Sumw2();
  // hsfiso->Sumw2();


  //---------------------------
  // tag cuts
  //---------------------------

  TCut zmass("abs(tagAndProbeMass-91)<15");
  TCut eltnp("(eventSelection&1)==1");
  TCut mutnp("(eventSelection&2)==2");
  TCut os("qProbe*qTag<0");
  TCut tag_eta21("abs(tag->eta())<2.1");
  TCut probe_eta21("abs(probe->eta())<2.1");
  TCut tag_eta25("abs(tag->eta())<2.5");
  TCut njets1("njets>=1");
  TCut njets2("njets>=2");
  TCut njets3("njets>=3");
  TCut njets4("njets>=4");
  TCut tag_pt30("tag->pt()>30.0");
  TCut met30("met<30");
  TCut met20("met<20");
  TCut nbm0("nbm==0");
  TCut nbl0("nbl==0");
  TCut mt30("mt<30");
  TCut eltnptrig("HLT_TNP_tag > 0 || HLT_TNPel_tag > 0");
  TCut mutnptrig("HLT_IsoMu30_eta2p1_tag > 0");
  TCut tag_trig("HLT_IsoMu30_eta2p1_tag > 0");
  TCut probe_trig("HLT_IsoMu30_eta2p1_probe > 0");

  //---------------------------
  // tag cuts
  //---------------------------

  TCut mufo 	   = "(leptonSelection&32768)==32768";    // mu fo
  TCut muid 	   = "(leptonSelection&65536)==65536";    // mu id 
  TCut muiso 	   = "(leptonSelection&131072)==131072";  // mu iso 
  TCut elfo        = "(leptonSelection&4)==4";            // ele fo 
  TCut elid  	   = "(leptonSelection&8)==8";            // ele id 
  TCut eliso 	   = "(leptonSelection&16)==16";          // ele iso
  TCut probept     = "probe->pt()>30";                    // probe pt
  TCut probe_pt20  = "probe->pt()>20";                    // probe pt
  TCut drprobe     = "drprobe<0.05";                      // dR(probe,pfcandidate)

  TCut eltnpcut;
  eltnpcut += zmass;
  eltnpcut += os;
  eltnpcut += eltnp;
  eltnpcut += tag_eta25;
  //eltnpcut += njets2;
  eltnpcut += tag_pt30;
  eltnpcut += eltnptrig;
  eltnpcut += met30;
  // eltnpcut += mt30;
  eltnpcut += nbl0;
  
  eltnpcut += elid;
  eltnpcut += probept;
  eltnpcut += drprobe;

  TCut mutnpcut;

  mutnpcut += zmass;
  mutnpcut += os;
  mutnpcut += mutnp;
  //mutnpcut += njets2;

  mutnpcut += tag_trig;
  mutnpcut += tag_pt30;
  mutnpcut += tag_eta21;

  mutnpcut += probe_pt20;
  mutnpcut += probe_eta21;

  mutnpcut += met30;
  mutnpcut += nbl0;

  mutnpcut += muid;
  mutnpcut += muiso;

  //mutnpcut += probept;
  //mutnpcut += drprobe;

  // mutnpcut += mt30;

  //
  //eltnpcut += njets3;
  //eltnpcut += nbm0;
  //eltnpcut += mt30;
  //eltnpcut += met20;

  //TCut eltnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&1)==1 && qProbe*qTag<0 && abs(tag->eta())<2.5 && njets>=4 && tag->pt()>30.0 && met<30.0 && nbm==0 && mt<30"; 
  //TCut mutnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && njets>=4 && tag->pt()>30.0"; 

  //TCut vtxweight = "vtxweight";

  // cout << "Electrons:" << endl;
  // cout << "Total MC yields 	: " << chmc->GetEntries(eltnpcut) << endl;
  // cout << "Total DATA yields 	: " << chdata->GetEntries(eltnpcut) << endl;

  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno" , TCut(mutnpcut)            );
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num"  , TCut(mutnpcut+probe_trig) );	

  hdataid_eff->Divide(hdataid_num,hdataid_deno,1,1);

  cout << endl << "Denominator" << endl;
  printline(hdataid_deno);
  cout << endl << "Numerator" << endl;
  printline(hdataid_num);
  cout << endl << "Efficiency" << endl;
  printline(hdataid_eff);
  
  cout << "Muons:" << endl;
  cout << "Selection            : " << mutnpcut.GetTitle() << endl;
  //cout << "Total MC yields 	: " << chmc->GetEntries(mutnpcut) << endl;
  cout << "Total DATA yields 	: " << chdata->GetEntries(mutnpcut) << endl;

  TCut etabin1("abs(probe->eta()) < 0.8");
  TCut etabin2("abs(probe->eta()) > 0.8 && abs(probe->eta())<1.5");
  TCut etabin3("abs(probe->eta()) > 1.5 && abs(probe->eta())<2.1");
  TCut etabin4("abs(probe->eta()) > 2.1 && abs(probe->eta())<2.4");

  TGraphAsymmErrors* gr   = getEfficiencyGraph( chdata , probe_trig , mutnpcut               , "probe->pt()" , 28,20,300,"probe p_{T} [GeV]","trigger efficiency");
  TGraphAsymmErrors* gr1  = getEfficiencyGraph( chdata , probe_trig , TCut(mutnpcut+etabin1) , "probe->pt()" , 28,20,300,"probe p_{T} [GeV]","trigger efficiency");
  TGraphAsymmErrors* gr2  = getEfficiencyGraph( chdata , probe_trig , TCut(mutnpcut+etabin2) , "probe->pt()" , 28,20,300,"probe p_{T} [GeV]","trigger efficiency");
  TGraphAsymmErrors* gr3  = getEfficiencyGraph( chdata , probe_trig , TCut(mutnpcut+etabin3) , "probe->pt()" , 28,20,300,"probe p_{T} [GeV]","trigger efficiency");
  TGraphAsymmErrors* gr4  = getEfficiencyGraph( chdata , probe_trig , TCut(mutnpcut+etabin4) , "probe->pt()" , 28,20,300,"probe p_{T} [GeV]","trigger efficiency");

  TCanvas *c1 = new TCanvas();
  c1->cd();

  //gr->Draw("AP");

  gr1->SetLineColor(1);
  gr2->SetLineColor(2);
  gr3->SetLineColor(4);
  gr4->SetLineColor(6);

  gr1->SetMarkerColor(1);
  gr2->SetMarkerColor(2);
  gr3->SetMarkerColor(4);
  gr4->SetMarkerColor(6);

  gr1->Draw("AP");
  gr2->Draw("sameP");
  gr3->Draw("sameP");
  //gr4->Draw("sameP");

  TLegend *leg = new TLegend(0.5,0.2,0.7,0.4);
  leg->AddEntry(gr1,"|#eta| < 0.8","lp");
  leg->AddEntry(gr2,"|#eta| 0.8 - 1.5","lp");
  leg->AddEntry(gr3,"|#eta| 1.5 - 2.1","lp");
  //leg->AddEntry(gr4,"|#eta| > 2.1");

  leg->SetBorderSize(1);
  leg->SetFillColor(0);
  leg->Draw();

  /*
  //TCut njets    = "njets>=2";
  TCut tkisoold = "tkisoold/probe->pt()>0.1";
  TCut tkisonew = "tkisonew/probe->pt()>0.1";

  //-----------------------------------------
  // check nvtx data vs. MC
  //-----------------------------------------

  TH1F *hnvtx_mc   = new TH1F("hnvtx_mc"  ,"",30,0,30);
  TH1F *hnvtx_data = new TH1F("hnvtx_data","",30,0,30);

  hnvtx_mc->Sumw2();
  hnvtx_data->Sumw2();

  chdata->Draw("nvtx>>hnvtx_data",(eltnpcut||mutnpcut));
  chmc->Draw("nvtx>>hnvtx_mc",(eltnpcut||mutnpcut)*vtxweight);

  TCanvas *c1 = new TCanvas();
  c1->cd();
  
  hnvtx_mc->SetLineColor(2);
  hnvtx_mc->SetMarkerColor(2);
  hnvtx_data->SetLineColor(4);
  hnvtx_data->SetMarkerColor(4);
  
  hnvtx_data->GetXaxis()->SetTitle("N_{VTX}");
  hnvtx_data->DrawNormalized();
  hnvtx_mc->DrawNormalized("same");

  TLegend *leg = new TLegend(0.6,0.6,0.8,0.8);
  leg->AddEntry(hnvtx_data,"data","lp");
  leg->AddEntry(hnvtx_mc,"MC","lp");
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->Draw();

  if( printplot ) c1->Print("plots/nvtx.pdf");
  */

  //--------------------------
  // absolute track isolation
  //--------------------------
  /*  
  bool residual = true;
  bool log      = true;
  
  char* var = "tkisonewnoveto";
  
  plotDistribution( chdata , chmc , TCut(eltnpcut)        , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_0j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut)        , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_0j" , printplot , residual , log );
  
  plotDistribution( chdata , chmc , TCut(eltnpcut+njets1) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_1j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets1) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_1j" , printplot , residual , log );
  
  plotDistribution( chdata , chmc , TCut(eltnpcut+njets2) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_2j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets2) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_2j" , printplot , residual , log );

  plotDistribution( chdata , chmc , TCut(eltnpcut+njets3) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_3j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets3) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_3j" , printplot , residual , log );

  plotDistribution( chdata , chmc , TCut(eltnpcut+njets4) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_4j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets4) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_4j" , printplot , residual , log );
  */
  //--------------------------
  // relative track isolation
  //--------------------------

  // plotDistribution( chdata , chmc , TCut(eltnpcut) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "el_tkrliso_2j" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "mu_tkrliso_2j" , printplot );

  // plotDistribution( chdata , chmc , TCut(eltnpcut+njets3) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "el_tkrliso_3j" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut+njets3) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "mu_tkrliso_3j" , printplot );

  // plotDistribution( chdata , chmc , TCut(eltnpcut+njets4) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "el_tkrliso_4j" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut+njets4) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "mu_tkrliso_4j" , printplot );




  // plotDistribution( chdata , chmc , TCut(eltnpcut) , vtxweight , "tkisoold" , 10 , 0 , 10 , "trkiso (old) [GeV]" , "el_tkiso_old" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut) , vtxweight , "tkisoold" , 10 , 0 , 10 , "trkiso (old) [GeV]" , "mu_tkiso_old" , printplot );

  //printHisto( chdata , chmc , TCut(muiso) , TCut(tnpcut+muid) , "probe.pt()" , 10 , 0.0 , 100.0 , "lepton p_{T} [GeV]" , "iso efficiency" );
  //printHisto( chdata , chmc , tkisoold , TCut(tnpcut+muid+njets) , "probe.pt()" , 10 , 0.0 , 100.0 , "lepton p_{T} [GeV]" , "tkiso(old) efficiency" );
  //printHisto( chdata , chmc , tkisonew , TCut(tnpcut+muid+njets) , "probe.pt()" , 10 , 0.0 , 100.0 , "lepton p_{T} [GeV]" , "tkiso(new) efficiency" );


  /*


  //
  // Fill histograms
  //
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");

  TCut tnpcut   	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && njets>=4 && tag->pt()>30.0"; 

  chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+muiso,	      	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 	tnpcut+muiso+muid,	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+muid,	      	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+muid+muiso,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+muiso,		"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 	tnpcut+muiso+muid,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+muid,	       	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+muid+muiso,	"goff");

  // get efficiencies 
  // hmcid->Divide(hmcid_num,hmcid_deno,1,1,"B");
  // hmciso->Divide(hmciso_num,hmciso_deno,1,1,"B");
  // hdataid->Divide(hdataid_num,hdataid_deno,1,1,"B");
  // hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1,"B");

  hmcid->Divide(hmcid_num,hmcid_deno,1,1);
  hmciso->Divide(hmciso_num,hmciso_deno,1,1);
  hdataid->Divide(hdataid_num,hdataid_deno,1,1);
  hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1);
	
  // get scale factors
  hsfid->Divide(hdataid, hmcid, 1, 1);
  hsfiso->Divide(hdataiso, hmciso, 1, 1);

  // Draw histograms	
  //hmcid->Draw("text");
  */

  /*
  // print table
  cout << " ------ MC ID ----- " << endl;
  printline(hmcid);
  cout << " ------ MC ISO ----- " << endl;
  printline(hmciso);
  cout << " ------ DATA ID ----- " << endl;
  printline(hdataid);
  cout << " ------ DATA ISO ----- " << endl;
  printline(hdataiso);
  cout << " ------ Scale Factor ID ----- " << endl;
  printline(hsfid);
  cout << " ------ Scale Factor ISO ----- " << endl;
  printline(hsfiso);
  */
	
}
void gammaJetHistProducer_jetEnergyScaledMinus2percent(sampleType collision = kPADATA, float photonPtThr=60, float photonPtThrUp=9999, float jetPtThr=30, int icent =1) {
  TH1::SetDefaultSumw2();
  
  TString stringSampleType = getSampleName(collision); "";
  
  TDatime* date = new TDatime();
  TString  outName=  Form("photonTrackCorr_%s_output_photonPtThr%d_to_%d_jetPtThr%d_%d.root",stringSampleType.Data(),(int)photonPtThr, (int)photonPtThrUp, (int)jetPtThr,  date->GetDate());
  delete date;
  
  int lowerCent(0),  upperCent(0); 
  TCut centCut  = "";
  if ( (collision ==kHIDATA) || (collision==kHIMC) )   {
    lowerCent = centBin1[icent-1];
    upperCent = centBin1[icent]-1;
    if ( icent > 9999) {
      lowerCent = ((icent/100)%100)/2.5;
      upperCent =  (icent%100)/2.5 -1;
    }   
    centCut = Form("cBin >= %d && cBin<= %d",lowerCent,upperCent);
  }
  else if (  (collision ==kPPDATA) || (collision==kPPMC)  ){  // if it's pp 
    centCut = "(1==1)";
    //    icent = 7;   // for pp, centrality is set as the smearing 
  }
  else { // pPb
    centCut = Form( "hf4Sum > %f && hf4Sum <= %f", (float)centBinPa[icent-1], (float)centBinPa[icent]);
  }
  
  cout <<" centrality : " << centCut.GetTitle() << endl;
      
  ///////// Photon cut //////////////////////////////////////////////////////////////////////////////
  
  cout <<" photon pt >" << photonPtThr << " GeV" << endl;
  TCut ptPhoCut  = Form("photonEt>%.1f && photonEt<%.1f", (float)photonPtThr, (float)photonPtThrUp  );
  TCut caloIso;
  
  if ( (collision==kPPMC) || (collision==kPPDATA) ) 
    caloIso = "(ecalIso < 4.2  &&  hcalIso < 2.2  &&  trackIso < 2) && hovere<0.1";
  else if ( (collision==kHIMC) || (collision==kHIDATA) )
    caloIso = "(sumIso<1) && hovere<0.1";
  else {
    caloIso = "ecalIso < 4.2  &&  hcalIso < 2.2  &&  trackIso < 2 && hovere<0.1";
  }
  
  TCut sbIso   = "(sumIso>10) && (sumIso<20) && hovere<0.1";
  //  if ( (collision==kPPMC) || (collision==kPPDATA) || (collision==kPAMC) || (collision==kPADATA)  )
  //  sbIso   = "ecalIso < 4.2  &&  hcalIso < 2.2 && trackIso > 2 && trackIso < 5 && hovere<0.1";

  TCut basicPhoCut = centCut && ptPhoCut && caloIso ;
  TCut sbPhoCut    = centCut && ptPhoCut && sbIso   ;
  TCut evtSeltCut = basicPhoCut;
  TCut sbSeltCut  = sbPhoCut;

  TCut phoCandCut   = "sigmaIetaIeta<0.010";
  TCut phoDecayCut  = "(sigmaIetaIeta>0.011) && (sigmaIetaIeta<0.017)";
  if  ( ( collision == kHIMC ) || (collision == kPPMC) || (collision == kPAMC))  
    phoCandCut = phoCandCut && "genIso<5 && abs(genMomId)<=22";
  
  
  TString fname = "";
  if ( collision == kHIDATA)      fname = fnameHIDATA_Minus2percentScaled;
  else if ( collision == kPADATA) fname = fnamePADATA_Minus2percentScaled;
  else if ( collision == kPPDATA) {
    if ( icent == 7 ) fname = fnamePPDATA_Minus2percentScaled;
  }  
  else fname = "";
  
  multiTreeUtil* tgj = new multiTreeUtil();
  multiTreeUtil* tgjMC = new multiTreeUtil();
  if (  ( collision == kHIDATA)   || ( collision==kPADATA) || ( collision == kPPDATA) ) {
    tgj->addFile(fname,  "tgj",  evtSeltCut,  1);
  }
  else if ( collision == kPPMC ) {
    tgj->addFile(fnamePPMC_AllQcdPho30to50,    "tgj", evtSeltCut, wPPMC_AllQcdPho30to50 );
    tgj->addFile(fnamePPMC_AllQcdPho50to80,    "tgj", evtSeltCut, wPPMC_AllQcdPho50to80 );
    tgj->addFile(fnamePPMC_AllQcdPho80to120,   "tgj", evtSeltCut, wPPMC_AllQcdPho80to120 );
    tgj->addFile(fnamePPMC_AllQcdPho120to9999, "tgj", evtSeltCut, wPPMC_AllQcdPho120to9999 );
  }
  else if ( collision == kPAMC ) {
    tgj->addFile(fnamePAMC_AllQcdPho30to50,    "tgj", evtSeltCut, wPAMC_AllQcdPho30to50 );
    tgj->addFile(fnamePAMC_AllQcdPho50to80,    "tgj", evtSeltCut, wPAMC_AllQcdPho50to80 );
    tgj->addFile(fnamePAMC_AllQcdPho80to120,   "tgj", evtSeltCut, wPAMC_AllQcdPho80to120 );
    tgj->addFile(fnamePAMC_AllQcdPho120to9999, "tgj", evtSeltCut, wPAMC_AllQcdPho120to9999 );
  }
  else  {    // kHIMC
    tgj->addFile(fnameHIMC_AllQcdPho30to50,    "tgj", evtSeltCut, wHIMC_AllQcdPho30to50 );
    tgj->addFile(fnameHIMC_AllQcdPho50to80,    "tgj", evtSeltCut, wHIMC_AllQcdPho50to80 );
    tgj->addFile(fnameHIMC_AllQcdPho80to9999,  "tgj", evtSeltCut, wHIMC_AllQcdPho80to9999 );
  }
  tgj->AddFriend("yJet");
 
  // get purity with the current jet cut ! 
  float purity(0);
  
  TString canvasName = Form("gifs/purity_%s_output_icent%d_photonPtThr%d-%d_jetPtThr%d", stringSampleType.Data(),  (int)icent, (int)photonPtThr, (int)photonPtThrUp, (int)jetPtThr);
  
  //  if ( (collision==kPPDATA) && (photonPtThr < 50 ) ) {
  //   purity = 0.86 ;   
  //   cout << " !!!!!!!" << endl << endl << " purity is set as  0.86 for this bin because we don't have pp MC low pt sample " << endl;
  //   cout << endl << endl << endl << " !!!!!!" << endl;
  //  }

  if ( (collision==kHIDATA)||(collision==kPPDATA)||(collision==kPADATA) )  {
    
    fitResult fitr = getPurity(fname, collision, evtSeltCut, sbSeltCut, canvasName, photonPtThr, photonPtThrUp);
    purity = fitr.purity010;

    /*
      float originalP = purity;
      if (collision==kPPDATA)  
      purity = purity - 0.05;
      else if (collision==kHIDATA) {
      if ( icent == 10030)
      purity = purity - 0.08; 
      else if ( icent == 13099) 
      purity = purity - 0.07; 
      }
      cout << "====================================================================================" << endl << endl << endl;
      cout << "====================================================================================" << endl << endl << endl;
      cout << "================================ Purity modified!!! ================================" << endl << endl << endl;
      cout << "=============== "<<originalP<< " --> "<<purity<< "====================================" << endl << endl << endl;
      cout << "====================================================================================" << endl << endl << endl;
    */
  }
  else  {
    purity = 1;  
    cout << " MC purity = 1" << endl;
  }
  

  GjSpectra* gSpec = new GjSpectra();
  gSpec->init(Form("icent%d",(int)icent) );
  tgj->Draw2(gSpec->hPtPhoCand,  "photonEt", phoCandCut, "")  ;
  tgj->Draw2(gSpec->hPtPhoDecay, "photonEt", phoDecayCut, "") ;
  
  // Obtain background subtracted spectra
  
  float candInt = gSpec->hPtPhoCand->Integral();
  float candDecay = gSpec->hPtPhoDecay->Integral();
  gSpec->hPtPhoSig->Reset();
  gSpec->hPtPhoSig->Add(gSpec->hPtPhoCand);
  gSpec->hPtPhoSig->Add(gSpec->hPtPhoDecay, -(1. - purity) * candInt / candDecay);
  gSpec->hPtPhoSig->Scale(1./purity ) ;
  
  TFile outf = TFile(Form("ffFiles/%s",outName.Data()),"update");
  gSpec->hPtPhoCand->Write();
  gSpec->hPtPhoDecay->Write();
  gSpec->hPtPhoSig->Write();
  outf.Close();
  
  
  
  // Objects
  multiTreeUtil* tObj[3];
  tObj[kTrkRaw] = new multiTreeUtil();
  tObj[kTrkBkg] = new multiTreeUtil();
  
  if (  ( collision == kHIDATA)   || ( collision==kPADATA) || ( collision == kPPDATA) ) {
    tObj[kTrkRaw]->addFile(fname,  "yJet",  evtSeltCut,  1);
    tObj[kTrkBkg]->addFile(fname,  "mJet",  evtSeltCut,  1);
  }
  else if ( collision == kHIMC ) {
    tObj[kTrkRaw]->addFile(fnameHIMC_AllQcdPho30to50,   "yJet", evtSeltCut, wHIMC_AllQcdPho30to50 ) ;
    tObj[kTrkRaw]->addFile(fnameHIMC_AllQcdPho50to80,   "yJet", evtSeltCut, wHIMC_AllQcdPho50to80 ) ;
    tObj[kTrkRaw]->addFile(fnameHIMC_AllQcdPho80to9999, "yJet", evtSeltCut, wHIMC_AllQcdPho80to9999 ) ;
 
    tObj[kTrkBkg]->addFile(fnameHIMC_AllQcdPho30to50,   "mJet", evtSeltCut, wHIMC_AllQcdPho30to50 ) ;
    tObj[kTrkBkg]->addFile(fnameHIMC_AllQcdPho50to80,   "mJet", evtSeltCut, wHIMC_AllQcdPho50to80 ) ;
    tObj[kTrkBkg]->addFile(fnameHIMC_AllQcdPho80to9999, "mJet", evtSeltCut, wHIMC_AllQcdPho80to9999 ) ;
  } 
  else if ( collision == kPAMC ) {
    tObj[kTrkRaw]->addFile(fnamePAMC_AllQcdPho30to50,   "yJet", evtSeltCut, wPAMC_AllQcdPho30to50 ) ;
    tObj[kTrkRaw]->addFile(fnamePAMC_AllQcdPho50to80,   "yJet", evtSeltCut, wPAMC_AllQcdPho50to80 ) ;
    tObj[kTrkRaw]->addFile(fnamePAMC_AllQcdPho80to120,  "yJet", evtSeltCut, wPAMC_AllQcdPho80to120 ) ;
    tObj[kTrkRaw]->addFile(fnamePAMC_AllQcdPho120to9999,"yJet", evtSeltCut, wPAMC_AllQcdPho120to9999 ) ;
    
    tObj[kTrkBkg]->addFile(fnamePAMC_AllQcdPho30to50,   "mJet", evtSeltCut, wPAMC_AllQcdPho30to50 ) ;
    tObj[kTrkBkg]->addFile(fnamePAMC_AllQcdPho50to80,   "mJet", evtSeltCut, wPAMC_AllQcdPho50to80 ) ;
    tObj[kTrkBkg]->addFile(fnamePAMC_AllQcdPho80to120,  "mJet", evtSeltCut, wPAMC_AllQcdPho80to120 ) ;
    tObj[kTrkBkg]->addFile(fnamePAMC_AllQcdPho120to9999,"mJet", evtSeltCut, wPAMC_AllQcdPho120to9999 ) ;
  }
  else if ( collision == kPPMC ) {
    tObj[kTrkRaw]->addFile(fnamePPMC_AllQcdPho30to50,   "yJet", evtSeltCut, wPPMC_AllQcdPho30to50 );
    tObj[kTrkRaw]->addFile(fnamePPMC_AllQcdPho50to80,   "yJet", evtSeltCut, wPPMC_AllQcdPho50to80 );
    tObj[kTrkRaw]->addFile(fnamePPMC_AllQcdPho80to120,  "yJet", evtSeltCut, wPPMC_AllQcdPho80to120 );
    tObj[kTrkRaw]->addFile(fnamePPMC_AllQcdPho120to9999,"yJet", evtSeltCut, wPPMC_AllQcdPho120to9999 );

    tObj[kTrkBkg]->addFile(fnamePPMC_AllQcdPho30to50,   "mJet", evtSeltCut, wPPMC_AllQcdPho30to50 );
    tObj[kTrkBkg]->addFile(fnamePPMC_AllQcdPho50to80,   "mJet", evtSeltCut, wPPMC_AllQcdPho50to80 );
    tObj[kTrkBkg]->addFile(fnamePPMC_AllQcdPho80to120,  "mJet", evtSeltCut, wPPMC_AllQcdPho80to120 );
    tObj[kTrkBkg]->addFile(fnamePPMC_AllQcdPho120to9999,"mJet", evtSeltCut, wPPMC_AllQcdPho120to9999 );
  }



  tObj[kTrkRaw]->AddFriend("tgj");
  tObj[kTrkBkg]->AddFriend("tgj");
  TCut jetCut     =  Form("abs(eta)<%f && pt>%f", (float)cutjetEta, (float)jetPtThr );
  TCut jetCutDphi =  jetCut && (TCut)(Form("abs(dphi)>%f",(float)awayRange));
  TCut genJetCut     =  Form("abs(jtEta)<%f && jtPt>%f", (float)cutjetEta, (float)jetPtThr );
  TCut genJetCutDphi =  jetCut && (TCut)(Form("abs(refDphi)>%f",(float)awayRange));
  
  TCut jetCut2   = Form("abs(dphi)>%f && pt>%f", (float)awayRange, (float)jetPtThr ) ;
  
  
  TString jetWeight = "";
  
  TH1D* hJetDphi = new TH1D(Form("jetDphi_icent%d",icent),";#Delta#phi_{Jet,#gamma} ;dN/d#Delta#phi",20,0,3.141592);
  corrFunctionTrk* cJetDphi = new corrFunctionTrk();
  TString varJetDphi         = Form("dphi");

  gammaTrkSingle( gSpec,  tObj, cJetDphi,  purity, 
		  collision, varJetDphi, jetCut, jetWeight,
		  phoCandCut, phoDecayCut,  hJetDphi, outName);
  
  TH1D* hJetPt = new TH1D(Form("jetPt_icent%d",icent),";Jet p_{T} (GeV) ;dN/dp_{T} (GeV^{-1})",280, 20,300);
  corrFunctionTrk* cJetPt = new corrFunctionTrk();
  TString varJetPt         = Form("pt");
  
  gammaTrkSingle( gSpec,  tObj, cJetPt,  purity, 
		  collision, varJetPt, jetCutDphi, jetWeight,
		  phoCandCut, phoDecayCut,  hJetPt, outName);
  
  const int nJetIaaBin = 7;
  double jetIaaBin[nJetIaaBin+1] = {30,40,50,60,80,100,120,200};
  TH1D* hJetPtForIaa = new TH1D(Form("jetPtForIaa_icent%d",icent),";Jet p_{T} (GeV) ;dN/dp_{T} (GeV^{-1})",nJetIaaBin, jetIaaBin);
  corrFunctionTrk* cJetIaaPt = new corrFunctionTrk();
  gammaTrkSingle( gSpec,  tObj, cJetIaaPt,  purity,
                  collision, varJetPt, jetCutDphi, jetWeight,
                  phoCandCut, phoDecayCut,  hJetPtForIaa, outName);
  
  //  TH1D* hDjetPt = new TH1D(Form("dpt_icent%d",icent),";p_{T}^{#gamma} - p_{T}^{Jet} (GeV) ;dN/dp_{T} (GeV^{-1})",30,-150,150);
  //  corrFunctionTrk* cDjetPt = new corrFunctionTrk();
  //  TString varJetDpt         = Form("pt - photonEt");
  // gammaTrkSingle( gSpec,  tObj, cDjetPt,  purity, 
  //		  collision, varJetDpt, jetCutDphi, jetWeight,
  //		  phoCandCut, phoDecayCut,  hDjetPt, outName);
  
  
  TH1D* hJetXjg = new TH1D(Form("xjg_icent%d",icent),";p_{T}^{Jet}/p_{T}^{#gamma}  ; ",400,0,5);
  corrFunctionTrk* cJetXjg = new corrFunctionTrk();
  TString varJetXjg         = Form("pt/photonEt");
  
  gammaTrkSingle( gSpec,  tObj, cJetXjg,  purity, 
		  collision, varJetXjg, jetCutDphi, jetWeight,
		  phoCandCut, phoDecayCut,  hJetXjg, outName);
  

  if ( (collision == kPAMC) || (collision == kPPMC) ||(collision == kHIMC) ) {
    TH1D* hGenJetPt = (TH1D*)hJetPt->Clone(Form("genJetPt_icent%d",icent));
    corrFunctionTrk* cGenJetPt = new corrFunctionTrk();
    TString varGenJetPt         = Form("refPt");
    gammaTrkSingle( gSpec,  tObj, cJetPt,  purity, 
		    collision, varGenJetPt, genJetCutDphi, jetWeight,
		    phoCandCut, phoDecayCut,  hGenJetPt, outName);
    
    TH1D* hGenJetXjg = (TH1D*)hJetXjg->Clone(Form("xjg_genJet_icent%d",icent));
    corrFunctionTrk* cGenJetXjg = new corrFunctionTrk();
    TString varGenJetXjg         = Form("refPt/photonEt");
    gammaTrkSingle( gSpec,  tObj, cGenJetXjg,  purity, 
		    collision, varGenJetXjg, genJetCutDphi , jetWeight,
		    phoCandCut, phoDecayCut,  hGenJetXjg, outName);
    
    TH1D* hGenPhotonXjg = (TH1D*)hJetXjg->Clone(Form("xjg_genPho_icent%d",icent));
    corrFunctionTrk* cGenPhotonXjg = new corrFunctionTrk();
    TString varGenPhotonXjg         = Form("pt/genPhotonEt");
    gammaTrkSingle( gSpec,  tObj, cGenPhotonXjg,  purity, 
		    collision, varGenPhotonXjg, jetCutDphi, jetWeight,
		    phoCandCut, phoDecayCut,  hGenPhotonXjg, outName);
    
    TH1D* hGenPhoGenJetXjg = (TH1D*)hJetXjg->Clone(Form("xjg_genPho_genJet_icent%d",icent));
    corrFunctionTrk* cGenPhoGenJetXjg = new corrFunctionTrk();
    TString varGenPhoGenJetXjg         = Form("refPt/genPhotonEt");
    gammaTrkSingle( gSpec,  tObj, cGenPhoGenJetXjg,  purity, 
		    collision, varGenPhoGenJetXjg, genJetCutDphi, jetWeight,
		    phoCandCut, phoDecayCut,  hGenPhoGenJetXjg, outName);
  }
  
  bool doRapidity= false;
  if ( doRapidity) {
  // Eta distribution
    TH1D* hEtaJg = new TH1D(Form("etaJg_icent%d",icent),";#eta_{J,#gamma} ; ",160,-3,3);
    corrFunctionTrk* cEtaJg = new corrFunctionTrk();
    TString varEtaJg         = Form("(photonEta+eta)/2.");
    
    gammaTrkSingle( gSpec,  tObj, cEtaJg,  purity, 
		    collision, varEtaJg, jetCut2, jetWeight,
		    phoCandCut, phoDecayCut,  hEtaJg, outName);
    
    TH1D* hEtaJet = new TH1D(Form("etaJet_icent%d",icent),";#eta_{Jet} ; ",160,-3,3);
    corrFunctionTrk* cEtaJet = new corrFunctionTrk();
    TString varEtaJet         = Form("eta");
    
    gammaTrkSingle( gSpec,  tObj, cEtaJet,  purity, 
		    collision, varEtaJet, jetCut2, jetWeight,
		    phoCandCut, phoDecayCut,  hEtaJet, outName);
  
    TH1D* hEtaPhoton = new TH1D(Form("etaPhoton_icent%d",icent),";#eta_{#gamma} ; ",160,-3,3);
    corrFunctionTrk* cEtaPhoton = new corrFunctionTrk();
    TString varEtaPhoton         = Form("photonEta");
    
    gammaTrkSingle( gSpec,  tObj, cEtaPhoton,  purity, 
		    collision, varEtaPhoton, jetCut2, jetWeight,
		    phoCandCut, phoDecayCut,  hEtaPhoton, outName);
  }
  
}
Exemple #12
0
void drawSingleVariable(TH1D* theHist, int lowCent, int highCent, TString variable1, TCut addCut1, TString variable2, TCut addCut2, int normChoice,bool overDraw, TH1D* theMCSig) { 
   theHist->Reset();   
   if (addCut2 =="")  
      addCut2 = addCut1;
   if (variable2 =="")
      variable2 = variable1;

   cout << "addCut2 = " << addCut2.GetTitle() << endl;
   cout << "variable2 = "<< variable2 << endl;

   TString fname1 = "rootFiles/barrelHiForestPhoton35_Skim2011-Dec04-withTracks.root";//barrelHiForestPhoton35_Skim2011-v2.root";
   TFile *f1  =new TFile(fname1.Data());
   TTree *photon1 = (TTree*)f1->Get("yongsunPhotonTree");
   photon1->AddFriend("yEvt=yongsunHiEvt"    ,fname1.Data());
   photon1->AddFriend("yskim=yongsunSkimTree"   ,fname1.Data());
   photon1->AddFriend("yhlt=yongsunHltTree"     ,fname1.Data());

   TString fname2 = "rootFiles/barrelHiForestPhoton35_Skim2010.root";
   TFile *f2  =new TFile(fname2.Data());
   TTree *photon2 = (TTree*)f2->Get("yongsunPhotonTree");
   //  photon2->AddFriend("yEvt=yongsunHiEvt"    ,fname2.Data());
   photon2->AddFriend("yskim=yongsunSkimTree"   ,fname2.Data());
   photon2->AddFriend("yhlt=yongsunHltTree"     ,fname2.Data());
   
   TString fnameMC ;
   TFile *fMC;
   TTree *photonSig;
   if ( theMCSig){ 
      fnameMC = "rootFiles/barrelHiForestPhoton35_MCPhoton50_25k.root";
      fMC  =new TFile(fnameMC.Data());
      photonSig = (TTree*)fMC->Get("yongsunPhotonTree");
      photonSig->AddFriend("yEvt=yongsunHiEvt"    ,fnameMC.Data());
      cout << " MC is running " << endl;
   }
   //   photonSig->AddFriend("yskim=yongsunSkimTree"   ,fnameMC.Data());
   //  photonSig->AddFriend("yhlt=yongsunHltTree"     ,fnameMC.Data());
   
   //genMatchCut1 
   TCut collisionCut = "yskim.pcollisionEventSelection==1";
   
   TCut runCut1       = ""; //"yhlt.Run>= 181985 && yhlt.Run <=182099"; 
   
   TCut centCut1     = Form("(yEvt.hiBin >= %d) && (yEvt.hiBin<= %d)",lowCent,highCent);
   TCut centCut2     = Form("(cBin >= %d) && (cBin <= %d)",lowCent,highCent);
   
   TCut spikeCut1     = "abs(seedTime)<4 && swissCrx<0.90 && sigmaIetaIeta>0.002";
   TCut spikeCut2   = "abs(seedTime)<4 && (1 - (eRight+eLeft+eTop+eBottom)/eMax)<0.90 && sigmaIetaIeta>0.002";
   TCut spikeCutSig = "swissCrx<0.90 && sigmaIetaIeta>0.002";

   TCut nonElectron = "!isEle";
   
   TCut hltCut1       = "yhlt.HLT_HISinglePhoton30_v2==1"; // 181695 => H/E cut is removed from L1
   TCut hltCut2       = "yhlt.HLT_HIPhoton30==1";
      
   TCut basicCut1       = collisionCut && nonElectron && etaCut && spikeCut1 && centCut1 && runCut1 && hltCut1;
   TCut basicCut2       = collisionCut && nonElectron && etaCut && spikeCut2 && centCut2; //&& hltCut2;
   TCut basicCutSig     =                 nonElectron && etaCut && spikeCutSig && centCut1;
   
   
   TCut finalCut1     = basicCut1   && addCut1;
   TCut finalCut2     = basicCut2   && addCut2;
   TCut finalCutSig   = basicCutSig && addCut1 && genMatchCut1;
   
   TH1D* tempHist1 = (TH1D*)theHist->Clone("tempHist1");
   TH1D* tempHist2 = (TH1D*)theHist->Clone("tempHist2");
   TH1D* tempHistSig = (TH1D*)theHist->Clone("tempHistSig");
   
   
   photon1->Draw(Form("%s>>%s",variable1.Data(),tempHist1->GetName()),finalCut1);
   photon2->Draw(Form("%s>>%s",variable2.Data(),tempHist2->GetName()),finalCut2);
   if ( theMCSig) {
      photonSig->Draw(Form("%s>>%s",variable1.Data(),tempHistSig->GetName()),  Form("(%s)*ncoll",finalCutSig.GetTitle()));
      cout << " mc cut = " << finalCutSig.GetTitle() << endl;
   }

   tempHist1->Sumw2();
   tempHist2->Sumw2();
   if ( theMCSig)
      tempHistSig->Sumw2();
   
   handsomeTH1(tempHist1,2);
   handsomeTH1(tempHist2,1);
   tempHist2->SetMarkerStyle(24);
   if ( normChoice == 0) {
      scaleInt(tempHist1);
      scaleInt(tempHist2);
   }
   if ( normChoice == 1) {
      double nEvents1 = photon1->GetEntries("leading==1" && basicCut1 && "pt>40 && hadronicOverEm<0.2");
      double nEvents2 = photon2->GetEntries("leading==1" && basicCut2 && "pt>40 && hadronicOverEm<0.2");
      tempHist1->Scale(1./nEvents1);
      tempHist2->Scale(1./nEvents2);
      cout <<" this file is<<" << nEvents1/nEvents2 * 6.7 << "micro barn" << endl;
   }
   if ( normChoice == 2) {
      double nLumi1 = 17.4   ; //microb^-1
      double nLumi2 = 7.0  ;
      tempHist1->Scale(1./nLumi1);
      tempHist2->Scale(1./nLumi2);
   }
   
   cleverRange(tempHist2,1.5);
   if ( overDraw) 
      tempHist2->DrawCopy("same");//hist");
   else 
      tempHist2->DrawCopy("");//hist");                                                                                                  

   tempHist1->DrawCopy("same");
   
   TLegend* leg1 =  new TLegend(0.4012097,0.7584746,1,0.9300847,NULL,"brNDC");
   easyLeg(leg1,"");
   leg1->AddEntry(tempHist2,"2010 PbPb, 6.8 #mub^{-1}","pl");
   leg1->AddEntry(tempHist1,"2011 PbPb, 84  #mub^{-1}","pl");
   leg1->Draw();
   theHist->Reset();
   theHist->Add(tempHist1);
   if ( theMCSig)
      theMCSig->Add(tempHistSig);
   
}
Exemple #13
0
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void DrawPlots(){
    
    

    bool DoProtonsMomenta       = false;
    bool DoProtonsTrackLength   = false;
    bool DoSRCEvents            = false;
    bool DoAngles               = false;
    bool DoHighMomentumTail     = false;
    bool DothetaPPFinalInitial  = false;
    bool DoDrawQ                = true;
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    TPlots  * tracks   = new TPlots("Ana.root","TracksTree");
    TPlots  * events   = new TPlots("Ana.root","EventsTree","events",false);
   
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoProtonsMomenta) {
        TH1F * h = tracks -> H1("StartMomentum.P()","PdgCode==2212","",401,-1,1000
                             ,"proton momentum","p [MeV/c]","",38,38);
        analysis -> NormalizeHistogram(h);
        tracks -> Line(251,0,251,h->GetMaximum(),2,4,2);
        tracks -> Text(260,0.8*h->GetMaximum(),"Fermi momentum 251 MeV/c [e-scat.]");
    }
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoProtonsTrackLength) {
        tracks -> H2("StartMomentum.P()","TrackLength","PdgCode==2212","colz",401,1,1000,401,-1,1000
                  ,"proton momentum","p [MeV/c]","track length [cm]");
    }
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoSRCEvents){
        // identify v (np) -> µ p p events, and ask reconstruct BNL measurement
        // the angle between the two protons in the inital state vs. the recoil momentum
        TCanvas * c = plot -> CreateCanvas("c" , "DivideSquare");
        c -> cd(1);
        TH1F * Prec = events -> H1("Prec.Mag()",SRCcut&& "Prec.Mag()>0","colz",50,0,1000,"","recoil momentum [GeV/c]","",38,38);
        plot -> Line(pThresholdArgoNeuT,0,pThresholdArgoNeuT,Prec->GetMaximum(),2,2);
        c -> cd(2);
        events -> H1(plot->CosTheta("Pmiss","Prec"),SRCcut&& "Prec.Mag()>0","colz",50,-1.1,1.1,"","cos( #theta )","",38,38);
        c -> cd(3);
        events -> H2("Prec.Mag()",plot->CosTheta("Pmiss","Prec"),SRCcut&& "Prec.Mag()>0","colz"
                     ,50,1,1000,50,-1.01,1.01,"","recoil momentum [MeV/c]","#theta (p(miss) , p(recoil))");
        plot -> Line(pThresholdArgoNeuT,-1.01,pThresholdArgoNeuT,1.01,2,2);
    }
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoAngles){
//        plot -> CreateCanvas("Theta_pn_i_Prec");
//        events -> H2("Prec.Mag()",plot->CosTheta("Pmiss","Prec"),cutCC2p,"colz"
//                     ,50,0,1000,50,-1.05,1.05,"","recoil momentum [MeV/c]","cos( #theta_{np}^{i} )");
//        plot -> CreateCanvas("Theta_pn_i_Theta_munu");
//        events -> H2(plot->CosTheta("neutrino.Vect()","muon.Vect()"),plot->CosTheta("Pmiss","Prec"),cutCC2p&&"Prec.Mag()>1","colz"
//                     ,50,-1.01,1.01,50,-1.01,1.01,"","cos( #theta_{#nu#mu} )","cos( #theta_{np}^{i} )");
        plot -> CreateCanvas("Theta_pp_f_Prec");
        events -> H2("Prec.Mag()",plot->CosTheta("protons[0].Vect()","protons[1].Vect()"),cutCC2p,"colz"
                     ,50,1,1000,50,-1.01,1.01,"","recoil momentum [MeV/c]","cos( #theta_{pp}^{f} )");
//        plot -> CreateCanvas("Theta_pp_Theta_numu");
//        events -> H2(plot->CosTheta("neutrino.Vect()","muon.Vect()"),plot->CosTheta("protons[0].Vect()","protons[1].Vect()"),cutCC2p,"colz"
//                     ,50,-1.01,1.01,50,-1.01,1.01,"","cos( #theta_{#nu#mu} )","cos( #theta_{pp}^{f} )");
//        plot -> CreateCanvas("Theta_numu_Prec");
//        events -> H2("Prec.Mag()",plot->CosTheta("neutrino.Vect()","muon.Vect()"),cutCC2p&&"Prec.Mag()>200","colz"
//                     ,50,1,1000,50,-1.01,1.01,"","recoil momentum [MeV/c]","cos( #theta_{#nu#mu} )");
    }
    
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DoHighMomentumTail){
        plot -> CreateCanvas("DoHighMomentumTail");
        float Max = 1300;
        TH1F * Prec = events -> H1("Prec.Mag()",cutCC2p,"",75,0,Max,"","recoil momentum [MeV/c]","",38,38);
        events -> H1("Prec.Mag()",cutCC2p&&"Prec.Mag()>270","same",75,0,Max,"","recoil momentum [MeV/c]","",48,48,3001);
        float Tail      = Prec -> Integral(Prec->GetXaxis()->FindBin(270),Prec->GetXaxis()->FindBin(Max));
        float TailErr   = sqrt(Tail);
        float Tot       = Prec -> Integral(Prec->GetXaxis()->FindBin(0),Prec->GetXaxis()->FindBin(Max));
        float TotErr    = sqrt(Tot);
        float fTail     = Tail / Tot;
        float fTailErr  = fTail * ( 1./Tail + 1./Tot );
        SHOW(Tail);
        SHOW(Tot);
        SHOW(fTail);
        SHOW(fTailErr);
        TString TailPercentage  = plot->PercentStr(fTail);
        TString TailPercenErr   = plot->PercentStr(fTailErr);
        plot -> Text(300,Prec->GetMaximum(),Form("high momentum tail (>270 MeV/c) %.2f(%.0f)%%",100*fTail,100*100*fTailErr));
    }
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if (DothetaPPFinalInitial){
        plot -> CreateCanvas("Theta_numu_Prec");
//        TString var = plot->CosTheta("Pmiss","Prec") , XTitle = "cos( #theta_{pn}^{i} )";
        TString var = plot->CosTheta("protons[0].Vect()","protons[1].Vect()") , XTitle = "cos( #theta_{pp}^{f} )";
        const int N = 5;
        TH1F    * h[N];
        TString Labels[N];
        float   PmissMin[N] = {0 , 100 , 200 , 400 , 600 } , PmissMax[N] = {100 , 200 , 400 , 600 , 1000 } ;
        for (int i = 0; i < N ; i++) {
            TCut cut = cutCC2p && Form("%f > Prec.Mag() && Prec.Mag() > %f",PmissMax[i],PmissMin[i]) ;
            Labels[i] = Form("%.0f > p(rec) > %.0f MeV/c",PmissMax[i],PmissMin[i]);
            cut.Print();
            h[i] = events -> H1(var,cut,"goff",50,-1.05,1.05,"",XTitle,"",(i!=4)?i+1:i+2,(i!=4)?i+1:i+2);
            analysis -> NormalizeHistogram(h[i]);
        }
        for (int i = N-1; i >= 0 ; i--){
            h[i] -> Draw((i==N-1)?"":"same");
        }
        plot -> AddLegend("recoil momentum cut",N,h,Labels,1,"f");
        
     }

    
    
    //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
    if(DoDrawQ){
        plot -> CreateCanvas("q");
        TString var = "TMath::RadToDeg()*q.Theta()";
//        TString var = plot->Theta("neutrino.Vect()","Pmiss"); //"TMath::RadToDeg()*q.Theta()"
        events -> H2("q.Vect().Mag()",var,cutCC2p,"colz"
                     ,50,1,1400,50,0,180,"","momentum transfer [MeV/c]","#theta_{q}");
//        events -> H2("Prec.Mag()",var,cutCC2p,"colz"
//                     ,50,1,1400,50,0,180,"","recoil momentum [MeV/c]","#theta_{q}");
        
    }
}
Exemple #14
0
void fit_combine(TChain *tc, std::string Var, const double * VarBins_array , const int nVarBins , TCut Gcut,  double *mean, double *meanErr, double *sigma, double *sigmaErr ){

	std::string jetTitle=tc->GetTitle();

	cout<<"tc title = "<<tc->GetTitle()<<" ,Var = "<<Var<<" ,nVarBins = "<<nVarBins<<", Gcut = "<<Gcut<<endl;
	Can_Temp[counter] = new TCanvas(Form("Can_Temp_%i",counter));
	if(nVarBins<=9){Can_Temp[counter]->Divide(3,3);}
	else {Can_Temp[counter]->Divide(3,4);}


	TH1D *h_Ratio[nVarBins];
	TF1 *f_Ratio[nVarBins];
	double nRatiobins= 100;
	double minRatio=0;
	double maxRatio=3;


	for(int ibin =0; ibin<nVarBins; ibin++)
	{
		Can_Temp[counter]->cd(ibin+1);
		double VarMin = VarBins_array[ibin];
		double VarMax = VarBins_array[ibin+1];

		h_Ratio[ibin] = new TH1D( Form("h_Ratio[%d]",ibin),Form("%s_%s_%i_%i",jetTitle.c_str(),Var.c_str(),(int)VarMin,(int)VarMax) ,nRatiobins,minRatio,maxRatio);  // h_Ration_%d ??
		h_Ratio[ibin]->Sumw2();

		TCut Varcut = Form("%s>%f && %s<%f", Var.c_str(), VarMin, Var.c_str(), VarMax);
		TCut allcut = Gcut && Varcut;
		cout<<"Varcut = "<<Varcut<<" ,allcut = "<<allcut<<endl;

		tc->Draw( Form("jtpt/refpt>>h_Ratio[%d]",ibin ) , allcut*"weight" );

		h_Ratio[ibin]->GetXaxis()->SetTitle(Form("%s, jtpt/refpt",Gcut.GetTitle()));

		f_Ratio[ibin] = new TF1(Form("f_Ratio_%d",ibin), "gaus",0.5,1.5 );
		f_Ratio[ibin]->SetParameter(0,h_Ratio[ibin]->GetEntries()); // get number for normalization
		if(ibin==0){
		f_Ratio[ibin]->SetParameter(1,h_Ratio[ibin]->GetMean()) ;   // for mean
		f_Ratio[ibin]->SetParameter(2,h_Ratio[ibin]->GetStdDev()) ; // for sigma   
		}
		if(ibin>=1){
    f_Ratio[ibin]->SetParameter(1,mean[ibin-1]) ;   // for mean
    f_Ratio[ibin]->SetParameter(2,sigma[ibin-1]) ; // for sigma   
		} 
		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
    h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MRL");
    h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");


		mean[ibin] = f_Ratio[ibin]->GetParameter(1);
		meanErr[ibin] = f_Ratio[ibin]->GetParError(1);
		sigma[ibin] = f_Ratio[ibin]->GetParameter(2);
		sigmaErr[ibin] = f_Ratio[ibin]->GetParError(2);

	} // end   for(int ibin =0; ibin<nVarBins; ibin++)

	Can_Temp[counter]->SaveAs(Form("./fitPlots/fit_%s_%s_%s.pdf",Var.c_str(),jetTitle.c_str(),Gcut.GetTitle() ));

	counter++; 
}
void printHisto( TCanvas *can , TChain *data , TChain *mc , TCut num , TCut denom , char* var , int nbins , float xmin , float xmax , char* xtitle , char* ytitle){

  can->cd();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  can->cd();

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

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

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

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

  iplot ++;
}
Exemple #16
0
void tnpScale_IDISO( int leptype = 1, bool printplot = false ) {

  cout << endl;
  cout << "-------------------" << endl;
  if     ( leptype == 0 ) cout << "Doing electrons" << endl;
  else if( leptype == 1 ) cout << "Doing muons"      << endl;
  else{
    cout << "ERROR! unrecognized leptype " << leptype << endl;
    exit(0);
  }
  cout << "-------------------" << endl;

  //----------------------------------------
  // Files
  //----------------------------------------

  TChain *chmc   = new TChain("leptons");
  TChain *chdata = new TChain("leptons");

  char* version = (char*) "V00-00-06";
  char* suffix = "";
  //char* suffix = "_2jets";
  //char* suffix = "_probept100";


  chmc->  Add(Form("smurf/ZJetsFull_%s/merged%s.root",version,suffix));

  if( leptype == 1 ){
    chdata->Add(Form("smurf/SingleMu2012AFull_%s/merged_json%s.root",version,suffix));
    chdata->Add(Form("smurf/SingleMu2012BFull_%s/merged_json%s.root",version,suffix));
    chdata->Add(Form("smurf/SingleMu2012CFull_%s/merged_json%s.root",version,suffix));
    chdata->Add(Form("smurf/SingleMu2012DFull_%s/merged_json%s.root",version,suffix));
  }
  else{
    chdata->Add(Form("smurf/SingleEl2012AFull_%s/merged_json%s.root",version,suffix));
    chdata->Add(Form("smurf/SingleEl2012BFull_%s/merged_json%s.root",version,suffix));
    chdata->Add(Form("smurf/SingleEl2012CFull_%s/merged_json%s.root",version,suffix));
    chdata->Add(Form("smurf/SingleEl2012DFull_%s/merged_json%s.root",version,suffix));
  }

  //----------------------------------------
  // bins 
  //----------------------------------------

  // float ptbin[]  = {10., 15., 20., 30., 40., 50., 7000.};
  // float ptbin[]  = { 30. , 40. , 50. , 60. , 80.0 , 100.0 , 120.0 , 150.0 , 7000.};
  // float etabin[] = {0, 0.8, 1.5, 2.1};
  // int nptbin=8;
  // int netabin=3;

  // float ptbin[]  = { 20., 30. , 40. , 50. , 60. , 80.0 , 100.0 , 150.0 , 200.0 , 300.0 , 500.0 , 1000.0 , 10000000.0};
  // int   nptbin   = 12;

  // float etabin[] = {0,2.1};
  // int   netabin  = 1;

  float ptbin[] = { 20., 30. , 40. , 50. , 60. , 80.0 , 100.0 , 150.0 , 200.0 , 300.0, 10000.0};
  int   nptbin  = 10;

  float etabin[4];
  int   netabin = 0;

  if( leptype == 1 ){
    cout << "DOING MUON ETA BINS" << endl;
    netabin=3;
    etabin[0] = 0.0;
    etabin[1] = 0.8;
    etabin[2] = 1.5;
    etabin[3] = 2.1;
  }

  if( leptype == 0 ){
    cout << "DOING ELECTRON ETA BINS" << endl;
    netabin=2;
    etabin[0] = 0.0;
    etabin[1] = 0.8;
    etabin[2] = 1.4442;

    // netabin=1;
    // etabin[0] = 0.0;
    // etabin[1] = 1.4442;
  }


  //deno
  TH2F *hmcid_deno 	= new TH2F("hmcid_deno"   , "hmcid_deno"   , nptbin, ptbin, netabin, etabin);
  TH2F *hmciso_deno 	= new TH2F("hmciso_deno"  , "hmciso_deno"  , nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_deno 	= new TH2F("hdataid_deno" , "hdataid_deno" , nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso_deno	= new TH2F("hdataiso_deno", "hdataiso_deno", nptbin, ptbin, netabin, etabin);
  hmcid_deno->Sumw2();
  hmciso_deno->Sumw2();
  hdataid_deno->Sumw2();
  hdataiso_deno->Sumw2();

  //num
  TH2F *hmcid_num 	= new TH2F("hmcid_num"    , "hmcid_num"    , nptbin, ptbin, netabin, etabin);
  TH2F *hmciso_num 	= new TH2F("hmciso_num"   , "hmciso_num"   , nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_num 	= new TH2F("hdataid_num"  , "hdataid_num"  , nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso_num 	= new TH2F("hdataiso_num" , "hdataiso_num" , nptbin, ptbin, netabin, etabin);
  hmcid_num->Sumw2();
  hmciso_num->Sumw2();
  hdataid_num->Sumw2();
  hdataiso_num->Sumw2();

  // eff
  TH2F *hmcid 	        = new TH2F("hmcid"        , "hmcid"        , nptbin, ptbin, netabin, etabin);
  TH2F *hmciso 	        = new TH2F("hmciso"       , "hmciso"       , nptbin, ptbin, netabin, etabin);
  TH2F *hdataid 	= new TH2F("hdataid"      , "hdataid"      , nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso 	= new TH2F("hdataiso"     , "hdataiso"     , nptbin, ptbin, netabin, etabin);
  hmcid->Sumw2();
  hmciso->Sumw2();
  hdataid->Sumw2();
  hdataiso->Sumw2();

  // SF
  TH2F *hsfid 	= new TH2F("hsfid"  , "hsfid" , nptbin, ptbin, netabin, etabin);
  TH2F *hsfiso 	= new TH2F("hsfiso" , "hsfiso", nptbin, ptbin, netabin, etabin);
  hsfid->Sumw2();
  hsfiso->Sumw2();

  // TCuts
  TCut muid ("(leptonSelection&65536)==65536");     // mu id 
  TCut muiso("(leptonSelection&131072)==131072");   // mu iso 
  TCut elid ("(leptonSelection&8)==8");             // ele id 
  TCut eliso("(leptonSelection&16)==16");           // ele iso

  TCut zmass("abs(tagAndProbeMass-91)<15");
  TCut tightzmass("abs(tagAndProbeMass-91)<5");
  TCut os("qProbe*qTag<0");

  TCut mutnp("(eventSelection&2)==2");
  TCut mutnptrig("HLT_IsoMu24_tag > 0");

  TCut eltnp("(eventSelection&1)==1");
  TCut eltnptrig("HLT_Ele27_WP80_tag > 0");

  TCut tag_eta21("abs(tag->eta())<2.1");
  TCut tag_eta14("abs(tag->eta())<1.4442");
  TCut tag_pt30("tag->pt()>30.0");
  TCut probe_eta21("abs(probe->eta())<2.1");
  TCut probe_eta14("abs(probe->eta())<1.4442");

  TCut mutrk("mutrk==1");

  TCut met30("met<30");
  TCut nbl0("nbl==0");

  TCut njets0("njets>=0");
  TCut njets1("njets>=1");
  TCut njets2("njets>=2");
  TCut njets3("njets>=3");
  TCut njets4("njets>=4");

  TCut mud0("mud0 < 0.02");
  TCut mudz("mudz < 0.5");

  // TCut mud0("mud0 < 0.2");
  // TCut mudz("mudz < 1.0");

  //TCut tnpcut   = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && tag->pt()>30.0"; 

  TCut tnpcut;
  tnpcut += zmass;
  //tnpcut += tightzmass;
  tnpcut += os;
  tnpcut += tag_pt30;

  tnpcut += met30;
  tnpcut += nbl0;

  TCut  lepid;
  TCut  lepiso;
  char* lepchar = "";

  if( leptype == 0 ){
    tnpcut += tag_eta14;
    tnpcut += probe_eta14;
    tnpcut += eltnp;
    tnpcut += eltnptrig;
    lepid   = TCut(elid);
    lepiso  = TCut(eliso);
    lepchar = "el";
  }
  else if( leptype == 1 ){
    tnpcut += tag_eta21;
    tnpcut += probe_eta21;
    //tnpcut += mutrk;
    //tnpcut += mud0;
    //tnpcut += mudz;
    tnpcut += mutnp;
    tnpcut += mutnptrig;
    lepid   = TCut(muid);
    lepiso  = TCut(muiso);
    lepchar = "mu";
  }
  
  //tnpcut += njets2;
  cout << "Selection  : " << tnpcut.GetTitle()          << endl;
  cout << "Ndata      : " << chdata->GetEntries(tnpcut) << endl;
  cout << "NMC        : " << chmc->GetEntries(tnpcut)   << endl;
  cout << "ID cut     : " << lepid.GetTitle()           << endl;
  cout << "iso cut    : " << lepiso.GetTitle()          << endl;

  chmc->  Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+lepiso,	      	"goff");
  chmc->  Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 	tnpcut+lepiso+lepid,	"goff");
  chmc->  Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+lepid,	      	"goff");
  chmc->  Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+lepid+lepiso,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+lepiso,		"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 	tnpcut+lepiso+lepid,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+lepid,	       	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+lepid+lepiso,	"goff");

  // get efficiencies 
  hmcid->Divide(hmcid_num,hmcid_deno,1,1,"B");
  hmciso->Divide(hmciso_num,hmciso_deno,1,1,"B");
  hdataid->Divide(hdataid_num,hdataid_deno,1,1,"B");
  hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1,"B");

  // hmcid->Divide(hmcid_num,hmcid_deno,1,1);
  // hmciso->Divide(hmciso_num,hmciso_deno,1,1);
  // hdataid->Divide(hdataid_num,hdataid_deno,1,1);
  // hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1);
	
  // get scale factors
  hsfid->Divide(hdataid, hmcid, 1, 1);
  hsfiso->Divide(hdataiso, hmciso, 1, 1);

  // Draw histograms	
  //hmcid->Draw("text");


  printHeader( leptype , "MC ID" );
  printline(hmcid);

  printHeader( leptype , "MC ISO" );
  printline(hmciso);

  printHeader( leptype , "DATA ID" );
  printline(hdataid);

  printHeader( leptype , "DATA ISO" );
  printline(hdataiso);

  printHeader( leptype , "Scale Factor ID" );
  printline(hsfid);

  printHeader( leptype , "Scale Factor ISO" );
  printline(hsfiso);

  cout << "\\hline" << endl << "\\hline" << endl;

  TCanvas *c_iso[10];
  TCanvas *c_id[10];

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

    TCut mysel;
    if     ( i==0 ) mysel = TCut(tnpcut+njets0);
    else if( i==1 ) mysel = TCut(tnpcut+njets1);
    else if( i==2 ) mysel = TCut(tnpcut+njets2);
    else if( i==3 ) mysel = TCut(tnpcut+njets3);
    else if( i==4 ) mysel = TCut(tnpcut+njets4);

    c_iso[i] = new TCanvas(Form("c_iso_%i",i),Form("c_iso_%i",i),600,600);
    c_iso[i]->cd();
    printHisto( c_iso[i] , chdata , chmc , TCut(lepiso) , TCut(mysel+lepid) , "probe.pt()" , 10 , 0.0 , 340.0 , "lepton p_{T} [GeV]" , "iso efficiency" );
    if( printplot ) c_iso[i]->Print(Form("plots/%s_iso_njets%i.pdf",lepchar,i));

    c_id[i] = new TCanvas(Form("c_id_%i",i),Form("c_id_%i",i),600,600);
    c_id[i]->cd();
    printHisto( c_id[i] , chdata , chmc , TCut(lepid) , TCut(mysel+lepiso) , "probe.pt()" , 10 , 0.0 , 340.0 , "lepton p_{T} [GeV]" , "ID efficiency" );
    if( printplot ) c_id[i]->Print(Form("plots/%s_id_njets%i.pdf",lepchar,i));

  }

  /*

  //---------------------------
  // tag cuts
  //---------------------------

  TCut zmass("abs(tagAndProbeMass-91)<15");
  TCut eltnp("(eventSelection&1)==1");
  TCut mutnp("(eventSelection&2)==2");
  TCut os("qProbe*qTag<0");
  TCut tag_eta21("abs(tag->eta())<2.1");
  TCut tag_eta25("abs(tag->eta())<2.5");
  TCut njets1("njets>=1");
  TCut njets2("njets>=2");
  TCut njets3("njets>=3");
  TCut njets4("njets>=4");
  TCut tag_pt30("tag->pt()>30.0");
  TCut met30("met<30");
  TCut met20("met<20");
  TCut nbm0("nbm==0");
  TCut nbl0("nbl==0");
  TCut mt30("mt<30");
  TCut eltnptrig("HLT_TNP_tag > 0 || HLT_TNPel_tag > 0");
  TCut mutnptrig("HLT_IsoMu30_eta2p1_tag > 0");

  //---------------------------
  // tag cuts
  //---------------------------

  TCut mufo 	= "(leptonSelection&32768)==32768";    // mu fo
  TCut elfo     = "(leptonSelection&4)==4";            // ele fo 
  TCut elid  	= "(leptonSelection&8)==8";            // ele id 
  TCut eliso 	= "(leptonSelection&16)==16";          // ele iso
  TCut probept  = "probe->pt()>30";                    // probe pt
  TCut drprobe  = "drprobe<0.05";                      // dR(probe,pfcandidate)

  TCut eltnpcut;
  eltnpcut += zmass;
  eltnpcut += os;
  eltnpcut += eltnp;
  eltnpcut += tag_eta25;
  //eltnpcut += njets2;
  eltnpcut += tag_pt30;
  eltnpcut += eltnptrig;
  eltnpcut += met30;
  // eltnpcut += mt30;
  eltnpcut += nbl0;
  
  eltnpcut += elid;
  eltnpcut += probept;
  eltnpcut += drprobe;

  TCut mutnpcut;
  mutnpcut += zmass;
  mutnpcut += os;
  mutnpcut += mutnp;
  mutnpcut += tag_eta21;
  //mutnpcut += njets2;
  mutnpcut += tag_pt30;
  mutnpcut += mutnptrig;
  mutnpcut += met30;
  // mutnpcut += mt30;
  mutnpcut += nbl0;

  mutnpcut += muid;
  mutnpcut += probept;
  mutnpcut += drprobe;


  //eltnpcut += njets2;
  //eltnpcut += njets3;
  //eltnpcut += nbm0;
  //eltnpcut += mt30;
  //eltnpcut += met20;

  //TCut eltnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&1)==1 && qProbe*qTag<0 && abs(tag->eta())<2.5 && njets>=4 && tag->pt()>30.0 && met<30.0 && nbm==0 && mt<30"; 
  //TCut mutnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && njets>=4 && tag->pt()>30.0"; 

  TCut vtxweight = "vtxweight";

  cout << "Electrons:" << endl;
  cout << "Total MC yields 	: " << chmc->GetEntries(eltnpcut) << endl;
  cout << "Total DATA yields 	: " << chdata->GetEntries(eltnpcut) << endl;

  cout << "Muons:" << endl;
  cout << "Total MC yields 	: " << chmc->GetEntries(mutnpcut) << endl;
  cout << "Total DATA yields 	: " << chdata->GetEntries(mutnpcut) << endl;


  //TCut njets    = "njets>=2";
  TCut tkisoold = "tkisoold/probe->pt()>0.1";
  TCut tkisonew = "tkisonew/probe->pt()>0.1";

  //-----------------------------------------
  // check nvtx data vs. MC
  //-----------------------------------------

  TH1F *hnvtx_mc   = new TH1F("hnvtx_mc"  ,"",30,0,30);
  TH1F *hnvtx_data = new TH1F("hnvtx_data","",30,0,30);

  hnvtx_mc->Sumw2();
  hnvtx_data->Sumw2();

  chdata->Draw("nvtx>>hnvtx_data",(eltnpcut||mutnpcut));
  chmc->Draw("nvtx>>hnvtx_mc",(eltnpcut||mutnpcut)*vtxweight);

  TCanvas *c1 = new TCanvas();
  c1->cd();
  
  hnvtx_mc->SetLineColor(2);
  hnvtx_mc->SetMarkerColor(2);
  hnvtx_data->SetLineColor(4);
  hnvtx_data->SetMarkerColor(4);
  
  hnvtx_data->GetXaxis()->SetTitle("N_{VTX}");
  hnvtx_data->DrawNormalized();
  hnvtx_mc->DrawNormalized("same");

  TLegend *leg = new TLegend(0.6,0.6,0.8,0.8);
  leg->AddEntry(hnvtx_data,"data","lp");
  leg->AddEntry(hnvtx_mc,"MC","lp");
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->Draw();

  if( printplot ) c1->Print("plots/nvtx.pdf");



  // Fill histograms
  //
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");

  */
	
}
void Muti_Plot(std::string mu_title,std::string filltype,std::string selection,  const char **lineKind_Arr, TCut selectionC , std::string Var , const int ngr, const int nVarBins, double * VarBins_array , double **yArr2, double **yErrArr2)
{ 

	char filename[]="JetESR_status.txt";
	fstream myfile;
	myfile.open (filename,ios::out|ios::app);

	double VarBinsCenter[nVarBins];
	double VarBinsErr[nVarBins];
	for (int ibin=0; ibin<nVarBins; ibin++)
	{
		VarBinsCenter[ibin]= (VarBins_array[ibin] + VarBins_array[ibin+1]) /2;
		VarBinsErr[ibin]=(VarBins_array[ibin+1]- VarBins_array[ibin])/2;
	}

	cout<<"lineKind_Arr 1 = "<<lineKind_Arr[0]<<" ,lineKind_Arr2 = "<<lineKind_Arr[1]<<endl;
	cout<<"mu_title = "<<mu_title<<" selectionC = "<< selectionC<<endl;

	Can_result[counter1] = new TCanvas(Form("Can_result_%i",counter1));
//	mutiGR[counter1] = new TMultiGraph("name",Form("%s",mu_title.c_str()));
	mutiGR[counter1] = new TMultiGraph(Form("name_%s",mu_title.c_str()),"");
	TGraphErrors *gr_mean[ngr];
	legend[counter1] = new TLegend(0.65,0.75,0.85,0.88);

	double mutiGRYmax =0;
	double mutiGRYmin =999;

	for(int igr=0; igr<ngr; igr++)
	{
		gr_mean[igr] = new TGraphErrors(nVarBins, VarBinsCenter, yArr2[igr], VarBinsErr , yErrArr2[igr]);
		gr_mean[igr]->SetTitle(Form("some title_%i", igr));
		gr_mean[igr]->SetFillStyle(0);
		gr_mean[igr]->SetMarkerStyle(1);
		gr_mean[igr]->SetLineColor(igr+1);	
		gr_mean[igr]->SetMarkerColor(igr+1);
		mutiGR[counter1]->Add(gr_mean[igr]);
		legend[counter1]->AddEntry( gr_mean[igr] ,lineKind_Arr[igr],"l"); 
		double maxTemp = TMath::MaxElement(nVarBins,yArr2[igr]);
		double minTemp = TMath::MinElement(nVarBins,yArr2[igr]);
		if (maxTemp>mutiGRYmax){mutiGRYmax = maxTemp;}
		if (minTemp<mutiGRYmin){mutiGRYmin = minTemp;}

	}

//	mutiGR[counter1]->SetTitle("JES Closure akPu4PF");
	mutiGR[counter1]->Draw("AP");
	mutiGR[counter1]->GetXaxis()->SetTitle(Form("%s",Var.c_str())); // must after draw to create a vitual histogram like object to set title.
	mutiGR[counter1]->GetYaxis()->SetTitle("#mu_{Reco./Gen.} (akPu4PF)");
	if (mu_title.compare("JES") == 0)
		mutiGR[counter1]->GetYaxis()->SetTitle("#mu_{Reco./Gen.} akPu4PF");
	if (mu_title.compare("JER") == 0)
		mutiGR[counter1]->GetYaxis()->SetTitle("#sigma_{Reco./Gen.} akPu4PF");

	cout<<"ymax = "<<mutiGRYmax<<" , ymin = "<<mutiGRYmin<<endl;

	mutiGR[counter1]->Draw("AP"); // draw again to let all the settting on it.
	double ydiff = mutiGRYmax-mutiGRYmin;
	gPad->Modified();
//	mutiGR[counter1]->SetMinimum(mutiGRYmin-ydiff*0.2);
//	mutiGR[counter1]->SetMaximum(mutiGRYmax+ydiff*0.45);
  mutiGR[counter1]->SetMinimum(0.95);
  mutiGR[counter1]->SetMaximum(1.21);

	if ( mu_title.compare("JEC Closure") ==0)
	{
//  mutiGR[counter1]->SetMinimum(0.975);
//  mutiGR[counter1]->SetMaximum(1.06);
	}

	legend[counter1]->SetBorderSize(0);
	/*
		 TProfile *hf_qcd;
		 TProfile *hf_bjt;
		 TProfile *hf_csvbjt;

		 if (mu_title.compare("JES")==0)
		 {
		 TCanvas *c_JES_prof = new TCanvas("c_JES_prof","c_JES_prof");
		 c_JES_prof->Divide(2,2);
		 TCut refpt200 = "refpt<200";
		 hf_qcd = new TProfile("hf_qcd","hf_qcd",16,40,200,0.8,1.2);
		 hf_bjt = new TProfile("hf_bjt","hf_bjt",16,40,200,0.8,1.2)
		 hf_csvbjt =  new TProfile("hf_csvbjt","hf_csvbjt",16,40,200,0.8,1.2)

		 }
		 */

	legend[counter1]->Draw();

	TLegend *legend1 = new TLegend(0.3,0.75,0.6,0.88);
	legend1->AddEntry((TObject*)0,selection.c_str(),"");
	cout<<"Var = "<<Var<<endl;
	if (Var.compare("jteta") == 0){ legend1->AddEntry((TObject*)0,"refpt>50","");}
	if (Var.compare("refpt") == 0){ legend1->AddEntry((TObject*)0,"|#eta_{jet}|<2.0","");}
	legend1->SetBorderSize(0);
	legend1->Draw();

	/*	TLatex *tex = new TLatex(0.35,0.8,"#bf{#color[2]{|#eta_{jet}|<2.0}}");
			tex->SetNDC();
			tex->SetTextFont(43);
			tex->SetTextSize(26);
			tex->SetLineWidth(2);
			tex->Draw();
			*/

	Can_result[counter1]->SaveAs(Form("./Plots/%s/result_%s_%s_%s.pdf",Var.c_str(),mu_title.c_str(),selectionC.GetTitle() , Var.c_str())); 
	counter1++;
	cout<<"finish mutigraph"<<endl;
}
void Muti_Plot_JER_ce30to100(std::string mu_title, const char **lineKind_Arr, TCut selectionC , std::string Var ,  const int ngr, const int nVarBins, double * VarBins_array , double **yArr2, double **yErrArr2)
{ 

	char filename[]="JetESR_status.txt";
	fstream myfile;
	myfile.open (filename,ios::out|ios::app);

	// Double_t Xptbin_chris_mean_ce0to30[20] = {7.999, 9.680157, 11.71464, 14.17672, 17.15625, 20.762, 25.12557, 30.40623, 36.79673, 44.53033, 53.88931, 65.21529, 78.92163, 95.50865, 115.5818, 139.8737, 169.2711, 204.8469, 247.8998, 300.001};
  Double_t Xptbin_chris_mean_ce30to100[21] = {-2,-1.8,-1.6,-1.4,-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1,1.2,1.4,1.6,1.8,2};

	Double_t Xpt_chris_mean_ce30to100[20];
	Double_t XErrpt_chris_mean_ce30to100[20];
	for (int ibin =0; ibin<20;ibin++){
		Xpt_chris_mean_ce30to100[ibin]= (Xptbin_chris_mean_ce30to100[ibin+1] +Xptbin_chris_mean_ce30to100[ibin])/2;
		XErrpt_chris_mean_ce30to100[ibin]= (Xptbin_chris_mean_ce30to100[ibin+1] -Xptbin_chris_mean_ce30to100[ibin])/2;
	}
//	double ypt_chris_mean_ce0to30[19]={2.614117,2.282987,2.04587,1.74664,1.548742,1.396857,1.275476,1.194122,1.140162,1.120749,1.075858,1.05422,1.009865,0.9785294,0.945,0.99,0.9000001,1.163599,1.15};
//	double yerrpt_chris_mean_ce0to30[19]={0.03932904,0.02605798,0.0244768,0.02502056,0.02119035,0.02074938,0.01284258,0.01424918,0.01133906,0.01246782,0.01578119,0.0227899,0.03189043,0.02962023,0.0438062,0.05302978,0.01194279,0.009490237,0.01854081};
  double ypt_chris_mean_ce30to100[20]={0.2311591,0.2477474,0.2655955,0.2576075,0.2220231,0.206768,0.2064983,0.2020811,0.19917,0.2115871,0.1952014,0.1965805,0.2158946,0.2003286,0.213619,0.213695,0.2466632,0.2597152,0.2553281,0.2344014};
  double yerrpt_chris_mean_ce30to100[20]={0.009894431,0.01000488,0.01052403,0.009913006,0.008527985,0.007570562,0.007309829,0.007320613,0.00699798,0.00776784,0.007146697,0.00713059,0.007530691,0.007364154,0.007896077,0.007855752,0.009496669,0.01034782,0.01046585,0.009252961};

	TGraphErrors *gr_chris_JERpt_ce30to100= new TGraphErrors(20,Xpt_chris_mean_ce30to100,ypt_chris_mean_ce30to100,XErrpt_chris_mean_ce30to100,yerrpt_chris_mean_ce30to100);

	gr_chris_JERpt_ce30to100->SetFillStyle(0);
	gr_chris_JERpt_ce30to100->SetMarkerStyle(1);
	gr_chris_JERpt_ce30to100->SetLineColor(ngr+1);
	gr_chris_JERpt_ce30to100->SetMarkerColor(ngr+1);


	double VarBinsCenter[nVarBins];
	double VarBinsErr[nVarBins];
	for (int ibin=0; ibin<nVarBins; ibin++)
	{
		VarBinsCenter[ibin]= (VarBins_array[ibin] + VarBins_array[ibin+1]) /2;
		//		VarBinsErr[ibin]=0;
		VarBinsErr[ibin]=(VarBins_array[ibin+1]- VarBins_array[ibin])/2;
	}

	cout<<"lineKind_Arr 1 = "<<lineKind_Arr[0]<<" ,lineKind_Arr2 = "<<lineKind_Arr[1]<<endl;
	cout<<"mu_title = "<<mu_title<<" selectionC = "<< selectionC<<endl;

	Can_result[counter1] = new TCanvas(Form("Can_result_%i",counter1));
	mutiGR[counter1] = new TMultiGraph("name",Form("%s",mu_title.c_str()));
	TGraphErrors *gr_mean[ngr];
	legend[counter1] = new TLegend(0.62,0.7,0.82,0.85);

	for(int igr=0; igr<ngr; igr++)
	{
		gr_mean[igr] = new TGraphErrors(nVarBins, VarBinsCenter, yArr2[igr], VarBinsErr , yErrArr2[igr]);
		//    char *name_temp = {Form("gr_mean_%i", (int)igr)};
		//		gr_mean[igr]->SetName(Form("gr_mean_%i", (int)igr) );
		//		gr_mean[igr]->SetName(name_temp);
		gr_mean[igr]->SetTitle(Form("some title_%i", igr));
		gr_mean[igr]->SetFillStyle(0);
		gr_mean[igr]->SetMarkerStyle(1);
		gr_mean[igr]->SetLineColor(igr+1);	
		gr_mean[igr]->SetMarkerColor(igr+1);
		mutiGR[counter1]->Add(gr_mean[igr]);
		legend[counter1]->AddEntry( gr_mean[igr] ,lineKind_Arr[igr],"l");  // not work for unknow reason

	}

	mutiGR[counter1]->Add(gr_chris_JERpt_ce30to100);
	legend[counter1]->AddEntry(gr_chris_JERpt_ce30to100,"from chris","l");

	myfile<<"hello, Var = "<<Var<<"Var.compare(Centrality) = "<<Var.compare("Centrality")<<endl;

	mutiGR[counter1]->Draw("AP");
	mutiGR[counter1]->GetXaxis()->SetTitle(Form("%s",Var.c_str())); // must after draw to create a vitual histogram like object to set title.
	mutiGR[counter1]->GetYaxis()->SetTitle("#sigma_{Reco./Gen.}");
	mutiGR[counter1]->Draw("AP"); // draw again to let all the settting on it.
	//	Can_result[counter1]->BuildLegend(0.7,0.7,0.9,0.9);
	legend[counter1]->SetBorderSize(0);
	legend[counter1]->Draw();

	TLatex *tex = new TLatex(0.35,0.8,"#bf{#color[2]{|#eta_{jet}|<2.0} & refpt>30}");
	tex->SetNDC();
	tex->SetTextFont(43);
	tex->SetTextSize(26);
	tex->SetLineWidth(2);
	tex->Draw();
  tex = new TLatex(0.17,0.25,"Centrality:30-100%");
	tex->SetNDC();
  tex->SetTextFont(43);
  tex->SetTextSize(26);
  tex->SetLineWidth(2);
  tex->Draw();


	Can_result[counter1]->SaveAs(Form("./Plots/result_%s_%s_%s.pdf",mu_title.c_str(),selectionC.GetTitle() , Var.c_str())); 
	Can_result[counter1]->SaveAs(Form("./Plots/result_%s_%s_%s.C",mu_title.c_str(),selectionC.GetTitle() , Var.c_str()));
	counter1++;
	cout<<"finish mutigraph"<<endl;
}
Exemple #19
0
 bool isAbs () const {return TString(cut.GetTitle()).Contains("abs(");}
void gammaTrkHistProducer(sampleType collision = kPPDATA, float photonPtThr=20, float photonPtThrUp=9999, int icent =7){
  TH1::SetDefaultSumw2();
  
  TString stringSampleType = getSampleName(collision); "";
  
  TDatime* date = new TDatime();
  TString  outName=  Form("photonTrackCorr_%s_output_photonPtThr%d_to_%d_%d.root",stringSampleType.Data(),(int)photonPtThr, (int)photonPtThrUp,  date->GetDate());
  delete date;
  
 
  int lowerCent(0),  upperCent(0); 
  TCut centCut  = "";
  if ( (collision ==kHIDATA) || (collision ==kHIMC) ) {
     lowerCent = ((icent/100)%100) *2 ;
     upperCent =  (icent%100)*2 -1 ; 
     centCut = Form("cBin >= %d && cBin<= %d",lowerCent,upperCent);
  }
  else if (  (collision ==kPPDATA) || (collision==kPPMC)  ){  // if it's pp 
    centCut = "(1==1)";
    //    icent = 7;   // for pp, centrality is set as the smearing 
  }
  else { // pPb
    centCut = Form( "hf4Sum > %f && hf4Sum <= %f", (float)centBinPa[icent-1], (float)centBinPa[icent]);
  }
  
  cout <<" centrality : " << centCut.GetTitle() << endl;
      
  ///////// Photon cut //////////////////////////////////////////////////////////////////////////////
  
  cout <<" photon pt >" << photonPtThr << " GeV" << endl;
  TCut ptPhoCut  = Form("photonEt>%.1f && photonEt<%.1f", (float)photonPtThr, (float)photonPtThrUp  );
  TCut caloIso;
  
  if ( (collision==kPPMC) || (collision==kPPDATA) ) 
    caloIso = "(ecalIso < 4.2  &&  hcalIso < 2.2  &&  trackIso < 2) && hovere<0.1";
  else if ( (collision==kHIMC) || (collision==kHIDATA) )
    caloIso = "(sumIso<5) && hovere<0.1";
  else {
    caloIso = "ecalIso < 4.2  &&  hcalIso < 2.2  &&  trackIso < 2 && hovere<0.1";
  }
  
  TCut sbIso   = "(sumIso>5) && (sumIso<20) && hovere<0.1";
  //  if ( (collision==kPPMC) || (collision==kPPDATA) || (collision==kPAMC) || (collision==kPADATA)  )
  //  sbIso   = "ecalIso < 4.2  &&  hcalIso < 2.2 && trackIso > 2 && trackIso < 5 && hovere<0.1";

  TCut basicPhoCut = centCut && ptPhoCut && caloIso ;
  TCut sbPhoCut    = centCut && ptPhoCut && sbIso   ;
  TCut evtSeltCut = basicPhoCut;
  TCut sbSeltCut  = sbPhoCut;

  TCut phoCandCut   = "sigmaIetaIeta<0.010";
  TCut phoDecayCut  = "(sigmaIetaIeta>0.011) && (sigmaIetaIeta<0.017)";
  if  ( ( collision == kHIMC ) || (collision == kPPMC) || (collision == kPAMC))  
    phoCandCut = phoCandCut && "genIso<5 && abs(genMomId)<=22";
  
  
  TString fname = "";
  if ( collision == kHIDATA)      fname = fnameHIDATA; //
  else if ( collision == kPADATA) fname = fnamePADATA;
  else if ( collision == kPPDATA) {
    if  ( icent == 7 ) fname = fnamePPDATA;
    else if ( icent == 10010 ) fname = fnamePPDATA0010;
    else if ( icent == 11030 ) fname = fnamePPDATA1030;
    else if ( icent == 13050 ) fname = fnamePPDATA3050;
    else if ( icent == 15099 ) fname = fnamePPDATA5099;
    else if ( icent == 10030 ) fname = fnamePPDATA0030;
    else if ( icent == 13099 ) fname = fnamePPDATA30100;
  }  
  else fname = "";
  
  multiTreeUtil* tgj = new multiTreeUtil();
  tgj->addFile(fname,  "tgj",  evtSeltCut,  1);
  tgj->AddFriend("yTrk");
 
  float purity(0);
  
  TString canvasName = Form("gifs/purity_%s_output_icent%d_photonPtThr%d-%d", stringSampleType.Data(),  (int)icent, (int)photonPtThr, (int)photonPtThrUp);
  
  if ( collision == kPPDATA) {  
    purity = 0.85;
  }
  else {
    fitResult fitr = getPurity(fname, collision, evtSeltCut, sbSeltCut, canvasName, photonPtThr, photonPtThrUp);
    purity = fitr.purity010;
  }
  GjSpectra* gSpec = new GjSpectra();
  gSpec->init(Form("icent%d",(int)icent) );
  tgj->Draw2(gSpec->hPtPhoCand,  "photonEt", phoCandCut, "");
  tgj->Draw2(gSpec->hPtPhoDecay, "photonEt", phoDecayCut, "");
  
  // Obtain background subtracted spectra
  
  float candInt = gSpec->hPtPhoCand->Integral();
  float decayInt = gSpec->hPtPhoDecay->Integral();
  gSpec->hPtPhoSig->Reset();
  gSpec->hPtPhoSig->Add(gSpec->hPtPhoCand);
  gSpec->hPtPhoSig->Add(gSpec->hPtPhoDecay, -(1. - purity) * candInt / decayInt);
  gSpec->hPtPhoSig->Scale(1./purity ) ;
  
  TFile outf = TFile(Form("ffFiles/%s",outName.Data()),"update");
  gSpec->hPtPhoCand->Write();
  gSpec->hPtPhoDecay->Write();
  gSpec->hPtPhoSig->Write();
  outf.Close();
  
  
  // Objects
  multiTreeUtil* tObj[3];
  tObj[kTrkRaw] = new multiTreeUtil();
  tObj[kTrkBkg] = new multiTreeUtil();
  
  tObj[kTrkRaw]->addFile(fname,  "yTrk",  evtSeltCut,  1);
  tObj[kTrkBkg]->addFile(fname,  "mTrk",  evtSeltCut,  1);
  
  tObj[kTrkRaw]->AddFriend("tgj");
  tObj[kTrkBkg]->AddFriend("tgj");
  TCut trkCut     =  Form("abs(eta)<%f && pt>%f", (float)cuttrkEta, (float)cuttrkPt );
  
  TString varTrkDphi         = Form("dphi");

  corrFunctionTrk* cTrkDphi = new corrFunctionTrk();
  TH1D* hTrkDphi = new TH1D(Form("dphi_icent%d",icent),";#Delta#phi_{Jet,#gamma} ;dN/d#Delta#phi",20,0,3.141592);
  gammaTrkSingle( gSpec,  tObj, cTrkDphi,  purity, 
		  collision, varTrkDphi, trkCut, "pt",
		  phoCandCut, phoDecayCut,  hTrkDphi, outName);

  TH1D* hTrkDphi1to2GeV = new TH1D(Form("dphi_icent%d_pt1to2GeV",icent),";#Delta#phi_{Jet,#gamma} ;dN/d#Delta#phi",20,0,3.141592);
  corrFunctionTrk* cTrkDphi1to2GeV = new corrFunctionTrk();
  gammaTrkSingle( gSpec,  tObj, cTrkDphi1to2GeV,  purity, 
		  collision, varTrkDphi, trkCut && "pt > 1 && pt <=2", "pt",
		  phoCandCut, phoDecayCut,  hTrkDphi, outName);

  TH1D* hTrkDphi2to4GeV = new TH1D(Form("dphi_icent%d_pt2to4GeV",icent),";#Delta#phi_{Jet,#gamma} ;dN/d#Delta#phi",20,0,3.141592);
  corrFunctionTrk* cTrkDphi2to4GeV = new corrFunctionTrk();
  gammaTrkSingle( gSpec,  tObj, cTrkDphi2to4GeV,  purity, 
		  collision, varTrkDphi, trkCut && "pt > 2 && pt <=4", "pt",
		  phoCandCut, phoDecayCut,  hTrkDphi, outName);

  TH1D* hTrkDphi4to8GeV = new TH1D(Form("dphi_icent%d_pt4to8GeV",icent),";#Delta#phi_{Jet,#gamma} ;dN/d#Delta#phi",20,0,3.141592);
  corrFunctionTrk* cTrkDphi4to8GeV = new corrFunctionTrk();
  gammaTrkSingle( gSpec,  tObj, cTrkDphi4to8GeV,  purity, 
		  collision, varTrkDphi, trkCut && "pt > 4 && pt <=8", "pt",
		  phoCandCut, phoDecayCut,  hTrkDphi, outName);

  TH1D* hTrkDphi8andHighGeV = new TH1D(Form("dphi_icent%d_pt8andHighGeV",icent),";#Delta#phi_{Jet,#gamma} ;dN/d#Delta#phi",20,0,3.141592);
  corrFunctionTrk* cTrkDphi8andHighGeV = new corrFunctionTrk();
  gammaTrkSingle( gSpec,  tObj, cTrkDphi8andHighGeV,  purity, 
		  collision, varTrkDphi, trkCut && "pt > 8", "pt",
		  phoCandCut, phoDecayCut,  hTrkDphi, outName);


}
void Plotting()
{
  TH1::AddDirectory(kFALSE);
  gStyle->SetCanvasDefH(600);
  gStyle->SetCanvasDefW(600);
  
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetFrameFillColor(0);
  gStyle->SetCanvasColor(0);
  gStyle->SetTitleFillColor(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadBorderSize(0);
  gStyle->SetCanvasBorderSize(0);
  gStyle->SetOptTitle(0); // at least most of the time
  gStyle->SetOptStat("nemr"); // most of the time, sometimes "nemriou" might be useful to display name, 
  //number of entries, mean, rms, integral, overflow and underflow
  gStyle->SetOptFit(0); // set to 1 only if you want to display fit results
  
  //=================================== Histo for all cut variables ==========================================
  using namespace RooFit;
  using namespace RooStats;
 
  void setWSRange(RooWorkspace *ws);
  void defineMassBkg(RooWorkspace *ws);
  void defineMassSig(RooWorkspace *ws);    

  double RError(double,double,double,double);
  double WeightRatioError(double,double,double,double);
  
  bool is3D =1;
  bool significance = 0;
  bool isHI=0; 
  bool Prompt = 0;
  bool nonPrompt = 1;

  bool savePlot=0;
  bool Binning =0;
  bool ctauFit = 1;
  

  float ptmin=3.0; float ptmax=30.0; float ymin=1.6; float ymax=2.4; bool absRapidity=true; 
  double threshold=0.8; double efficiency=0.9; int centmin=0; int centmax=200;

  ymin=1.6; ymax=2.4; ptmin=3.0; ptmax=30.0; 
  //ymin=1.6; ymax=2.4; ptmin=3.0; ptmax=6.5; 
  //ymin=1.6; ymax=2.4; ptmin=6.5; ptmax=12.0; 
  //ymin=1.6; ymax=2.4; ptmin=12.0; ptmax=30.0; 
  
  //ymin=0.0; ymax=1.6; ptmin=6.5; ptmax=30.0;  
  //ymin=0.0; ymax=1.6; ptmin=6.5; ptmax=9.0;  
  //ymin=0.0; ymax=1.6; ptmin=9.0; ptmax=12.0;  
  //ymin=0.0; ymax=1.6; ptmin=12.0; ptmax=15.0;  
  //ymin=0.0; ymax=1.6; ptmin=15.0; ptmax=20.0;  
  //ymin=0.0; ymax=1.6; ptmin=20.0; ptmax=30.0;  
  
  int range1 = 0; int fbin = 0;
  int range2 = 0; int lbin = 0;
  float xVal = 0.0;

  if(significance){
    range1 = -10;
    range2 = 50;
    fbin = -10; lbin = 50;
    xVal = 11.0;
  }else{
    range1 = -1;
    range2 = 3;
    fbin = -5; lbin = 10;
    xVal = 0.5;
  }

  float lCut=-10.0;
  TLegend *leg = new TLegend(0.38,0.5,0.87,0.75);
  if (isHI)
    leg->SetHeader("PYTHIA: PbPb #sqrt{s_{NN}} = 5.02 TeV");
  else
    leg->SetHeader("PYTHIA: pp #sqrt{s} = 5.02 TeV");
  leg->SetFillStyle(0);
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->SetMargin(0.15);
  leg->SetTextSize(0.032);
  leg->SetTextColor(2);

  TCut defaultCut = NULL;
  //  TCut defaultCut = "Reco_QQ_sign==0&&Gen_QQ_4mom.M()>3.09&&Gen_QQ_4mom.M()<3.10&&Reco_QQ_4mom.M()>2.9&&Reco_QQ_4mom.M()<3.2&&Reco_QQ_ctauTrue>-10";
  defaultCut = "Reco_QQ_sign==0&&Reco_QQ_4mom.M()>2.9&&Reco_QQ_4mom.M()<3.2&&Reco_QQ_ctau>-500&&Reco_QQ_ctauTrue>-10";
  if(significance)
    defaultCut = "Reco_QQ_sign==0&&Reco_QQ_4mom.M()>2.85&&Reco_QQ_4mom.M()<3.25&&Reco_QQ_ctau>-500&&Reco_QQ_ctauErr>-500&&Reco_QQ_ctauTrue>-10";
  if(is3D){
    defaultCut = "Reco_QQ_sign==0&&Reco_QQ_4mom.M()>2.85&&Reco_QQ_4mom.M()<3.25&&Reco_QQ_ctau3D>-500&&Reco_QQ_ctauTrue3D>-10";
    if(significance)
      defaultCut = "Reco_QQ_sign==0&&Reco_QQ_4mom.M()>2.85&&Reco_QQ_4mom.M()<3.25&&Reco_QQ_ctau3D>-500&&Reco_QQ_ctauErr3D>-500&&Reco_QQ_ctauTrue3D>-10";
  }
  
  TCut ptCut = Form("Reco_QQ_4mom.Pt()>%3.1f&&Reco_QQ_4mom.Pt()<%3.1f",ptmin,ptmax);
  TCut rapCut;
  if (absRapidity)
    rapCut = Form("abs(Reco_QQ_4mom.Rapidity())>%3.1f&&abs(Reco_QQ_4mom.Rapidity())<%3.1f",ymin,ymax);
  else
    rapCut = Form("Reco_QQ_4mom.Rapidity()>%3.1f&&Reco_QQ_4mom.Rapidity()<%3.1f",ymin,ymax);
  TCut centCut;
  if (isHI)
    centCut = Form("Centrality>=%d&&Centrality<%d",centmin,centmax);
  
  // new Acceptance
  TCut IsPlAccept = "(abs(Reco_QQ_mupl_4mom->Eta()) < 2.4 && ( (abs(Reco_QQ_mupl_4mom->Eta()) < 1.2 && Reco_QQ_mupl_4mom->Pt() >= 3.5 ) || (1.2 <= abs(Reco_QQ_mupl_4mom->Eta()) && abs(Reco_QQ_mupl_4mom->Eta()) < 2.1 && Reco_QQ_mupl_4mom->Pt() >= 5.77-1.89*abs(Reco_QQ_mupl_4mom->Eta() )) || (2.1 <= abs(Reco_QQ_mupl_4mom->Eta()) && Reco_QQ_mupl_4mom->Pt() >= 1.8 )))";
  TCut IsMiAccept = "(abs(Reco_QQ_mumi_4mom->Eta()) < 2.4 && ( (abs(Reco_QQ_mumi_4mom->Eta()) < 1.2 && Reco_QQ_mumi_4mom->Pt() >= 3.5 ) || (1.2 <= abs(Reco_QQ_mumi_4mom->Eta()) && abs(Reco_QQ_mumi_4mom->Eta()) < 2.1 && Reco_QQ_mumi_4mom->Pt() >= 5.77-1.89*abs(Reco_QQ_mumi_4mom->Eta() )) || (2.1 <= abs(Reco_QQ_mumi_4mom->Eta()) && Reco_QQ_mumi_4mom->Pt() >= 1.8 )))";

  TCut MuPlID = "((Reco_QQ_mupl_isGoodMuon==1) && Reco_QQ_mupl_nTrkWMea> 5 &&  Reco_QQ_mupl_nPixWMea > 0 && TMath::Abs(Reco_QQ_mupl_dxy) < 0.3 && TMath::Abs(Reco_QQ_mupl_dz) < 20 && Reco_QQ_VtxProb > 0.01 )";
  TCut MuMiID = "((Reco_QQ_mumi_isGoodMuon==1) && Reco_QQ_mumi_nTrkWMea> 5 &&  Reco_QQ_mumi_nPixWMea > 0 && TMath::Abs(Reco_QQ_mumi_dxy) < 0.3 && TMath::Abs(Reco_QQ_mumi_dz) < 20 && Reco_QQ_VtxProb > 0.01 )";
  
  
  unsigned int trigBit;
  if (isHI)
    trigBit=1; // DoubleMu0_HighQ
  else
    trigBit=1; // DoubleMu0_HighQ
  TCut trigCut = Form("(HLTriggers&%u)==%u&&(Reco_QQ_trig&%u)==%u",trigBit,trigBit,trigBit,trigBit);

  TString fname;
  TString fnamepng;
  TString outfname;
  TString plotDir;
  
  if(!is3D){plotDir = "Plots/2015";}
  if(!is3D && significance){plotDir = "Plots/2015/significance";}
  if(is3D){plotDir = "Plots/2015/3D";}
  if(is3D && Binning){plotDir = "Plots/2015/3D/Binning";}
  if(is3D && ctauFit){plotDir = "Plots/2015/3D/ctauFit";}
  if(is3D && significance){plotDir = "Plots/2015/3D/significance";}
  
  if (isHI) {
    if(Prompt){
      fname = Form("/Jpsi_PbPb_XcheckEff_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f_Cent_%d-%d.pdf",efficiency,ymin,ymax,ptmin,ptmax,int(centmin/2.0),int(centmax/2.0));
      fnamepng = Form("/Jpsi_PbPb_XcheckEff_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f_Cent_%d-%d.png",efficiency,ymin,ymax,ptmin,ptmax,int(centmin/2.0),int(centmax/2.0));
      outfname = Form("/Jpsi_PbPb_XcheckEff_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f_Cent_%d-%d.root",efficiency,ymin,ymax,ptmin,ptmax,int(centmin/2.0),int(centmax/2.0));
    }
    if(nonPrompt){
      fname = Form("/Jpsi_PbPb_XcheckEff_NP_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f_Cent_%d-%d.pdf",efficiency,ymin,ymax,ptmin,ptmax,int(centmin/2.0),int(centmax/2.0));
      fnamepng = Form("/Jpsi_PbPb_XcheckEff_NP_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f_Cent_%d-%d.png",efficiency,ymin,ymax,ptmin,ptmax,int(centmin/2.0),int(centmax/2.0));
      outfname = Form("/Jpsi_PbPb_XcheckEff_NP_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f_Cent_%d-%d.root",efficiency,ymin,ymax,ptmin,ptmax,int(centmin/2.0),int(centmax/2.0));
    }
      
  } 
  else {
    if(Prompt){
      fname = Form("/Jpsi_pp_XcheckEff_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f.pdf",efficiency,ymin,ymax,ptmin,ptmax);
      fnamepng = Form("/Jpsi_pp_XcheckEff_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f.png",efficiency,ymin,ymax,ptmin,ptmax);
      outfname = Form("/Jpsi_pp_XcheckEff_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f.root",efficiency,ymin,ymax,ptmin,ptmax);
    }
    if(nonPrompt){
      fname = Form("/Jpsi_pp_XcheckEff_NP_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f.pdf",efficiency,ymin,ymax,ptmin,ptmax);
      fnamepng = Form("/Jpsi_pp_XcheckEff_NP_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f.png",efficiency,ymin,ymax,ptmin,ptmax);
      outfname = Form("/Jpsi_pp_XcheckEff_NP_%3.1f_Rap_%3.1f-%3.1f_Pt_%3.1f-%3.1f.root",efficiency,ymin,ymax,ptmin,ptmax);
    }
  }
  std::cout << fname << std::endl;

  std::cout << "default: " << defaultCut.GetTitle() << std::endl;
  std::cout << "pt cut: " << ptCut.GetTitle() << std::endl;
  std::cout << "rapidity cut: " << rapCut.GetTitle() << std::endl;
  std::cout << "centrality cut: " << centCut.GetTitle() << std::endl;
  std::cout << "trigger bit: " << trigCut.GetTitle() << std::endl;

  TLatex *lpt;
  if (ptmin==0.0)
    lpt = new TLatex(0.38,0.845,Form("p_{T} < %3.1f GeV/c",ptmax));
  else{
    lpt = new TLatex(0.38,0.845,Form("%3.1f < p_{T} < %3.1f GeV/c",ptmin,ptmax));
    lpt->SetTextSize(0.033);
  }
  TLatex *lrap;
  if (absRapidity){
    if (ymin==0.0){
      lrap = new TLatex(0.38,0.77,Form("|y| < %3.1f",ymax));
      lrap->SetTextSize(0.033);
    }
    else{
      lrap = new TLatex(0.38,0.77,Form("%3.1f < |y| < %3.1f",ymin,ymax));
      lrap->SetTextSize(0.033);
    }
  }
  else {
    if (ymin==0.0)
      lrap = new TLatex(0.38,0.77,Form("y < %3.1f",ymax));
    else
      lrap = new TLatex(0.38,0.77,Form("%3.1f < y < %3.1f",ymin,ymax));
  }

  lpt->SetNDC(kTRUE);
  lrap->SetNDC(kTRUE);
  
  TLatex *lcent = NULL;
  if (isHI) {
    lcent = new TLatex(0.38,0.69,Form("Cent. %d-%d%%",int(centmin/2.0),int(centmax/2.0)));
    lcent->SetTextSize(0.033);
    lcent->SetNDC(kTRUE);
  }
  
  TChain *iTree = NULL;
  iTree = new TChain("hionia/myTree");
  if (isHI) {
    if(Prompt)
      {
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/Jpsi/OniaTree_Pythia8_JpsiMM_ptJpsi_00_03_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/Jpsi/OniaTree_Pythia8_JpsiMM_ptJpsi_03_06_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/Jpsi/OniaTree_Pythia8_JpsiMM_ptJpsi_06_09_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/Jpsi/OniaTree_Pythia8_JpsiMM_ptJpsi_09_12_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/Jpsi/OniaTree_Pythia8_JpsiMM_ptJpsi_12_15_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/Jpsi/OniaTree_Pythia8_JpsiMM_ptJpsi_15_30_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/Jpsi/OniaTree_Pythia8_JpsiMM_ptJpsi_30_Inf_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
      }
    if(nonPrompt)
      {
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/BJpsi/OniaTree_Pythia8_BJpsiMM_ptJpsi_00_03_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/BJpsi/OniaTree_Pythia8_BJpsiMM_ptJpsi_03_06_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/BJpsi/OniaTree_Pythia8_BJpsiMM_ptJpsi_06_09_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/BJpsi/OniaTree_Pythia8_BJpsiMM_ptJpsi_09_12_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/BJpsi/OniaTree_Pythia8_BJpsiMM_ptJpsi_12_15_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/BJpsi/OniaTree_Pythia8_BJpsiMM_ptJpsi_15_30_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
	//iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/PbPb/BJpsi/OniaTree_Pythia8_BJpsiMM_ptJpsi_30_Inf_Hydjet_MB_HINPbPbWinter16DR-75X_mcRun2_HeavyIon_v13-v1.root");
      }
  }
  else{
    if(Prompt)
      iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/pp/OniaTree_JpsiMM_5p02TeV_TuneCUETP8M1_HINppWinter16DR-75X_mcRun2_asymptotic_ppAt5TeV_v3-v1.root");
    if(nonPrompt)
      iTree->Add("/home/abdulla/CMS/quarkoniaData/Charm2015/rootfiles/MC/pp/OniaTree_BJpsiMM_5p02TeV_TuneCUETP8M1_HINppWinter16DR-75X_mcRun2_asymptotic_ppAt5TeV_v3-v1.root");
  }
  
  Float_t         muPlPt;
  Float_t         muMiPt;
  Float_t         muPlEta;
  Float_t         muMiEta;
  Float_t         QQctau3D;
  Float_t         QQctau3DErr;
  
  double invariantMass;
  double JpsiPt;
  double JpsiRap;
  double vProb;

  float muPlDxy;
  float muPlDz;
  int muPlNhits;
  int muPlNPxlLayers;
  int muPlNTrkLayers;
  float muPlInnerChi;
  float muPlGlobalChi;
  int muPlNMuonhits;
  bool muPlGoodMu;
  bool muPlTrkArb;
  bool muPlTMOneStaTight;
  bool muPlHighPurity;

  float muMiDxy;
  float muMiDz;
  int muMiNhits;
  int muMiNPxlLayers;
  int muMiNTrkLayers;
  float muMiInnerChi;
  float muMiGlobalChi;
  int muMiNMuonhits;
  bool muMiGoodMu;
  bool muMiTrkArb;
  bool muMiTMOneStaTight;
  bool muMiHighPurity;
  
  
  int nx = 14, ny = 15000;
  //double xBins[22] = {0.0,1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,30.0}; //19
  double xBins[15] = {3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,15.0,18.0,22.0,30.0}; //19
  
  //double xBins[4] = {3.0,6.5,12.0,30.0}; //19
  //double xBins[6] = {6.5,9.0,12.0,15.0,20.0,30.0}; //19
  
  //double xBins[13] = {6.5,7.0,8.0,9.0,10.0,11.0,12.0,13.0,15.0,18.0,21.0,24.0,30.0}; //13
  //double xBins[8] = {6.0,9.0,12.0,15.0,18.0,21.0,24.0,30.0}; //19
  //TH2D *hPR2D = new TH2D("hPR2D","hPR2D",nx,xBins,ny,-5.0,10.0);
  
  //TH1F *hPR = new TH1F("hPR","hPR;Inv_mass",100,-2.5,3.2);
  TH1F *hPR = new TH1F("hPR","hPR;p_{T}",nx,xBins);
  //TH1F *hPR = new TH1F("hPR","hPR;l_{J/#psi} (mm);counts",1500,-5,10);
  hPR->Sumw2();
  hPR->SetLineColor(1);
  //TH1F *hPRfunc = new TH1F("hPRfunc","hPRfunc;Inv_mass",100,-2.8,3.2);
  TH1F *hPRfunc = new TH1F("hPRfunc","hPRfunc;p_{T}",nx,xBins);
  //TH1F *hPRfunc = new TH1F("hPRfunc","hPRfunc;l_{J/#psi} (mm);counts",1500,-5,10);
  hPRfunc->Sumw2();
  hPRfunc->SetLineColor(2);
  //TH1F* hPRCut = (TH1F*) hPR->Clone("hPRCut");
  
  TFile *Fitfile = new TFile("Plots/2015/3D/ctauFit/Jpsi_pp_eff_0.9_Rap_1.6-2.4_Pt_3.0-30.0.root");
  TGraph *FitGr = (TGraph*)Fitfile->Get("Graph");
  TF1 *func1 = (TF1*)FitGr->GetFunction("FitFn");
  
  new TCanvas;
  TAxis *XaxctauFW = FitGr->GetXaxis();
  XaxctauFW->SetLimits(0.0,30.0);
  TAxis *YaxctauFW = FitGr->GetYaxis();
  YaxctauFW->SetLimits(0.0,0.1);
  FitGr->GetXaxis()->SetRangeUser(0.0,30.0);
  FitGr->GetYaxis()->SetRangeUser(0.0,0.1);
  //FitGr->Draw("AP");
  //FitGr->Draw();
  func1->Draw();

  initOniaTree(iTree);
  Long64_t nentries = iTree->GetEntries();
  nentries = 500000;          
  cout<<"Total Entries in data  Tree  "<<"  "<<nentries<< "====="<<endl;
  Long64_t nbytes = 0, nb = 0;
 
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    nb = iTree->GetEntry(jentry);   
    
    for (int iQQ=0; iQQ<Reco_QQ_size; iQQ++) {
      TLorentzVector *qq4mom = (TLorentzVector*) Reco_QQ_4mom->At(iQQ);
      TLorentzVector *qq4mupl = (TLorentzVector*) Reco_QQ_mupl_4mom->At(iQQ);
      TLorentzVector *qq4mumi = (TLorentzVector*) Reco_QQ_mumi_4mom->At(iQQ);
      
      invariantMass = qq4mom->M();
      JpsiPt = qq4mom->Pt();
      JpsiRap = qq4mom->Rapidity();

      muPlPt = qq4mupl->Pt();
      muMiPt = qq4mumi->Pt();
      muPlEta = qq4mupl->Eta();
      muMiEta = qq4mumi->Eta();

      QQctau3D = Reco_QQ_ctau3D[iQQ];
      //QQctauTrue3D = Reco_QQ_ctauTrue3D[iQQ];
      
      vProb = Reco_QQ_VtxProb[iQQ];
      muPlDxy=Reco_QQ_mupl_dxy[iQQ];
      muPlDz=Reco_QQ_mupl_dz[iQQ];
      muPlNPxlLayers=Reco_QQ_mupl_nPixWMea[iQQ];
      muPlNTrkLayers=Reco_QQ_mupl_nTrkWMea[iQQ];
      muPlTMOneStaTight=Reco_QQ_mupl_TMOneStaTight[iQQ];
      muPlGoodMu = Reco_QQ_mupl_isGoodMuon[iQQ];
      muPlHighPurity = Reco_QQ_mupl_highPurity[iQQ];

      muMiDxy=Reco_QQ_mumi_dxy[iQQ];
      muMiDz=Reco_QQ_mumi_dz[iQQ];
      muMiNPxlLayers=Reco_QQ_mumi_nPixWMea[iQQ];
      muMiNTrkLayers=Reco_QQ_mumi_nTrkWMea[iQQ];
      muMiTMOneStaTight=Reco_QQ_mumi_TMOneStaTight[iQQ];
      muMiGoodMu = Reco_QQ_mumi_isGoodMuon[iQQ];
      muMiHighPurity = Reco_QQ_mumi_highPurity[iQQ];
      
      bool defaultpass =0, ptpass =0, rappass =0, PosPass=0, NegPass=0, AllCut=0 ,PosIn=0, NegIn=0,TriggerPass=0;
      
      //if(Reco_QQ_sign[iQQ]==0 && invariantMass>2.85 && invariantMass<3.25 && Reco_QQ_ctau3D[iQQ]>-500 && Reco_QQ_ctauTrue3D[iQQ]>-10) {defaultpass =1;}
      if(Reco_QQ_sign[iQQ]==0 && invariantMass>2.85 && invariantMass<3.25 ) {defaultpass =1;}
      if(!defaultpass) continue;
      
      if(JpsiPt>ptmin && JpsiPt<ptmax)  {ptpass =1;}
      if( fabs(JpsiRap)>ymin && fabs(JpsiRap) <ymax )   {rappass =1;}

      if(!ptpass) continue;
      if(!rappass) continue; 
      //centCut = Form("Centrality>=%d&&Centrality<%d",centmin,centmax);
      
      if( (HLTriggers&(ULong64_t)pow(2,0))==pow(2,0) && (Reco_QQ_trig[iQQ]&(ULong64_t)pow(2,0))==pow(2,0) )
	{TriggerPass =1;}
      
      if (fabs(muPlEta) < 2.4 && ( (fabs(muPlEta) < 1.2 && muPlPt >= 3.5 ) || (1.2 <= fabs(muPlEta) && fabs(muPlEta) < 2.1 && muPlPt >= 5.77-1.89*fabs(muPlEta )) || (2.1 <= fabs(muPlEta) && muPlPt >= 1.8 )) )  {PosIn =1;}
	
      if(fabs(muMiEta) < 2.4 && ( (fabs(muMiEta) < 1.2 && muMiPt >= 3.5 ) || (1.2 <= fabs(muMiEta) && fabs(muMiEta) < 2.1 && muMiPt >= 5.77-1.89*fabs(muMiEta )) || (2.1 <= fabs(muMiEta) && muMiPt >= 1.8 )) )  {NegIn =1;}

      if( (muPlGoodMu==1) && muPlNTrkLayers> 5 &&  muPlNPxlLayers > 0 && TMath::Abs(muPlDxy) < 0.3 && TMath::Abs(muPlDz) < 20 && vProb > 0.01){PosPass=1;}

      if( (muMiGoodMu==1) && muMiNTrkLayers> 5 &&  muMiNPxlLayers > 0 && TMath::Abs(muMiDxy) < 0.3 && TMath::Abs(muMiDz) < 20 ){NegPass=1;}

      //if((Reco_QQ_mupl_isGoodMuon==1) && Reco_QQ_mupl_nTrkWMea> 5 &&  Reco_QQ_mupl_nPixWMea > 0 && TMath::fabs(Reco_QQ_mupl_dxy) < 0.3 && TMath::fabs(Reco_QQ_mupl_dz) < 20 && Reco_QQ_VtxProb > 0.01 )  {PosPass =1;}
      //if((Reco_QQ_mumi_isGoodMuon==1) && Reco_QQ_mumi_nTrkWMea> 5 &&  Reco_QQ_mumi_nPixWMea > 0 && TMath::fabs(Reco_QQ_mumi_dxy) < 0.3 && TMath::fabs(Reco_QQ_mumi_dz) < 20 && Reco_QQ_VtxProb > 0.01 )  {NegPass =1;}
      
      if(TriggerPass &&PosIn && NegIn && PosPass && NegPass) {AllCut = 1;}
      if(!AllCut) continue;
      
      //hPR->Fill(QQctau3D);
      hPR->Fill(JpsiPt);
      
      //for pp fwdrap:         cut.dMuon.ctauCut = "( ctau < (0.0128 + (0.288/pt)) )";
      //for pbpb fwdrap:     cut.dMuon.ctauCut = "( ctau < (0.0147 + (0.279/pt)) )";
      //for pp midrap:         cut.dMuon.ctauCut = "( ctau < (0.0097 + (0.249/pt)) )";
      //for pbpb midrap:     cut.dMuon.ctauCut = "( ctau < (0.0134 + (0.216/pt)) )";
      if( QQctau3D < (0.0128 + (0.288/JpsiPt) ) ) {hPRfunc->Fill(JpsiPt);}
      
    }
  }
  
  //TH1F* ratio = (TH1F*)hPR->Clone();      
  //ratio->Divide(hPRfunc);

  TH1F* ratio = (TH1F*)hPRfunc->Clone();      
  ratio->Divide(hPR);
  
  ratio->SetStats(0);
  //gStyle->SetFitFormat("1.3f");
  
  TCanvas *rt = new TCanvas();
  gPad->SetTickx();
  gPad->SetTicky();
  gPad->SetGridy();
  ratio->SetMarkerColor(kGreen+3);
  ratio->SetLineColor(0);
  ratio->SetMarkerStyle(29);
  ratio->SetMarkerSize(1.3);
  
  XaxctauFW = ratio->GetXaxis();
  XaxctauFW->SetLimits(0.0,30.0);
  YaxctauFW = ratio->GetYaxis();
  YaxctauFW->SetLimits(0.5,1.5);
  ratio->GetXaxis()->SetRangeUser(0.0,30.0);
  ratio->GetYaxis()->SetRangeUser(0.5,1.5);
  ratio->Draw();
 
  //*/
  
  
  lpt->Draw();
  lrap->Draw();
  leg->Draw();
  
  if (isHI)
    lcent->Draw();

  if (savePlot) {
    rt->SaveAs(plotDir+fname);
    rt->SaveAs(plotDir+fnamepng);
  }

  return;

  /*
  //TH1D *ctauMid_pT = new TH1D("ctauMid_pT","ctauMid_pT",90,0,30);
  //TH1D *ctauFW_pT = new TH1D("ctauFW_pT","ctauFW_pT",90,0,30);
  
  //double ctauFrw[5] = {0.04,0.03,0.02,0.02,0.01};
  double ctauFrw[4] = {0.07,0.04,0.03};
  double ctauMd[6] = {0.04,0.03,0.02,0.02,0.01};
  
  double Fbins[4] = {3,6.5,12.0,30.0};
  double Mbins[6] = {6.5,9.0,12.0,15.0,20.0,30.0};
  double x1bins[4] = {0.0};
  double x2bins[6] = {0.0};
  
  for(int i=0; i<3; i++){
    x1bins[i] = (Fbins[i] + Fbins[i+1])/2.0;
    cout<<x1bins[i]<<endl;
    //ctauFW_pT->SetBinContent(x1bins[i], ctauFrw[i-1]);
  } 

  for(int i=0; i<5; i++){
    x2bins[i] = (Mbins[i] + Mbins[i+1])/2.0;
    //ctauMid_pT->SetBinContent(x2bins[i], ctauMd[i]);
  } 
  
  new TCanvas;
  gPad->SetTickx();
  gPad->SetTicky();
  gPad->SetGridy();

  TGraph *ctauFW_pT = new TGraph(3,x1bins,ctauFrw);
  
  TF1 *FitFn = new TF1("FitFn",Pol2,0.0,30.0,3);
  FitFn->SetParNames("C","a","b");
  FitFn->SetLineWidth(2.0);
  FitFn->SetLineColor(2);
  ctauFW_pT->Fit("FitFn","", "",3.0,30.0);

  ctauFW_pT->SetLineColor(2);    
  ctauFW_pT->SetLineWidth(3); 
  ctauFW_pT->SetMarkerSize(1.5);
  ctauFW_pT->GetYaxis()->SetTitle("c#tau");
  ctauFW_pT->GetXaxis()->SetTitle("p_{T} bin");

  TAxis *XaxctauFW = ctauFW_pT->GetXaxis();
  XaxctauFW->SetLimits(0.0,30.0);
  TAxis *YaxctauFW = ctauFW_pT->GetYaxis();
  YaxctauFW->SetLimits(0.0,0.1);
  ctauFW_pT->GetXaxis()->SetRangeUser(0.0,30.0);
  ctauFW_pT->GetYaxis()->SetRangeUser(0.0,0.1);
  ctauFW_pT->Draw("AP*");

  new TCanvas;
  gPad->SetTickx();
  gPad->SetTicky();
  gPad->SetGridy();
  
  TF1 *FitFn2 = new TF1("FitFn2",Exp,0.0,30.0,2);
  TGraph *ctauMid_pT = new TGraph(5,x2bins,ctauMd);
  ctauMid_pT->SetLineColor(2);    
  ctauMid_pT->SetLineWidth(3); 
  ctauMid_pT->SetMarkerSize(1.5);
  ctauMid_pT->GetYaxis()->SetTitle("c#tau");
  ctauMid_pT->GetXaxis()->SetTitle("p_{T} bin");
  
  ctauMid_pT->Fit("FitFn2","", "",3.0,30.0);
  FitFn2->SetParNames("C1","n");

  TAxis *XaxctauMid = ctauMid_pT->GetXaxis();
  XaxctauMid->SetLimits(0.0,30.0);
  TAxis *YaxctauMid = ctauMid_pT->GetYaxis();
  YaxctauMid->SetLimits(0.0,0.1);
  ctauMid_pT->GetXaxis()->SetRangeUser(0.0,30.0);
  ctauMid_pT->GetYaxis()->SetRangeUser(0.0,0.1);
  ctauMid_pT->Draw("AP*");
  
  TLatex *t = new TLatex();
  t->SetNDC(); t->SetTextAlign(12);t->SetTextColor(1);
  t->SetTextSize(0.03);
  
  //t->DrawLatex(0.135,0.21," 10  pp               6.5-30   0.0-1.6");
  //lh->Draw("same");
  
  TF1 *myfunc1=ctauFW_pT->GetFunction("FitFn");
  TF1 *myfunc2=ctauMid_pT->GetFunction("FitFn2");
  
  TH1F *funHist = new TH1F("funHist","funHist",30,0.0,30.0);
  TH1F *funHist2 = new TH1F("funHist2","funHist2",30,0.0,30.0);
  
  funHist->Eval(myfunc1);
  funHist2->Eval(myfunc2);
  //funHist = myfunc->GetHistogram();
  //root > TH1F h("h","",100,0,10);
  //root > h.Eval(f1);

  cout<<"funHist:Entries "<<funHist->GetEntries()<<endl;
  for(int i=1;i<=funHist->GetNbinsX();++i)
    {
      cout<<"bin:pT "<<i<<"ctau: "<<funHist->GetBinContent(i)<<endl<<endl;
    }

  for(int i=1;i<=funHist2->GetNbinsX();++i)
    {
      cout<<"bin:pT "<<i<<"ctau: "<<funHist2->GetBinContent(i)<<endl<<endl;
    }

  new TCanvas;
  gPad->SetTickx();
  gPad->SetTicky();
  gPad->SetGridy();
  TAxis *XaxHistMid = funHist->GetXaxis();
  XaxHistMid->SetLimits(0.0,30.0);
  TAxis *YaxHistMid = funHist->GetYaxis();
  YaxHistMid->SetLimits(0.0,0.1);
  funHist->GetXaxis()->SetRangeUser(0.0,30.0);
  funHist->GetYaxis()->SetRangeUser(0.0,0.1);
  funHist->Draw();
  funHist2->SetLineColor(2);
  funHist2->Draw("same");
  //gPad->SaveAs("Plots/ctauMid.png");   
  //gPad->SaveAs("plots/ctauMid.pdf");   
  */

}
Exemple #22
0
void tnpScale( bool printplot = false ) {

  //----------------------------------------
  // Files
  //----------------------------------------

  char* version = (char*) "V00-00-00";

  TChain *chmc   = new TChain("leptons");
  TChain *chdata = new TChain("leptons");

  char* suffix = "";
  //char* suffix = "_2jets";

  chmc->  Add(Form("smurf/ZJets_V00-00-01/merged%s.root"        ,suffix));
  chdata->Add(Form("smurf/SingleMu2012A_V00-00-01/merged%s.root",suffix));
  chdata->Add(Form("smurf/SingleMu2012B_V00-00-01/merged%s.root",suffix));
  chdata->Add(Form("smurf/SingleMu2012C_V00-00-01/merged%s.root",suffix));
  chdata->Add(Form("smurf/SingleEl2012A_V00-00-01/merged%s.root",suffix));
  chdata->Add(Form("smurf/SingleEl2012B_V00-00-01/merged%s.root",suffix));
  chdata->Add(Form("smurf/SingleEl2012C_V00-00-01/merged%s.root",suffix));

  //----------------------------------------
  // bins 
  //----------------------------------------

  //float ptbin[] = {10., 15., 20., 30., 40., 50., 7000.};
  float ptbin[] = {10., 15., 20., 30., 40., 50., 60. , 70. , 80.0 , 100.0 , 7000.};
  float etabin[] = {0, 0.8, 1.479, 2.0, 2.5};
  int nptbin=10;
  int netabin=4;

  //
  // histogram
  //
  //deno
  TH2F *hmcid_deno 	= new TH2F("hmcid_deno", "hmcid_deno", nptbin, ptbin, netabin, etabin);
  TH2F *hmciso_deno 	= new TH2F("hmciso_deno", "hmciso_deno", nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_deno 	= new TH2F("hdataid_deno", "hdataid_deno", nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso_deno	= new TH2F("hdataiso_deno", "hdataiso_deno", nptbin, ptbin, netabin, etabin);
  hmcid_deno->Sumw2();
  hmciso_deno->Sumw2();
  hdataid_deno->Sumw2();
  hdataiso_deno->Sumw2();
  //num
  TH2F *hmcid_num 	= new TH2F("hmcid_num", "hmcid_num", nptbin, ptbin, netabin, etabin);
  TH2F *hmciso_num 	= new TH2F("hmciso_num", "hmciso_num", nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_num 	= new TH2F("hdataid_num", "hdataid_num", nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso_num 	= new TH2F("hdataiso_num", "hdataiso_num", nptbin, ptbin, netabin, etabin);
  hmcid_num->Sumw2();
  hmciso_num->Sumw2();
  hdataid_num->Sumw2();
  hdataiso_num->Sumw2();
  // eff
  TH2F *hmcid 	= new TH2F("hmcid", "hmcid", nptbin, ptbin, netabin, etabin);
  TH2F *hmciso 	= new TH2F("hmciso", "hmciso", nptbin, ptbin, netabin, etabin);
  TH2F *hdataid 	= new TH2F("hdataid", "hdataid", nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso 	= new TH2F("hdataiso", "hdataiso", nptbin, ptbin, netabin, etabin);
  hmcid->Sumw2();
  hmciso->Sumw2();
  hdataid->Sumw2();
  hdataiso->Sumw2();
  // SF
  TH2F *hsfid 	= new TH2F("hsfid", "hsfid", nptbin, ptbin, netabin, etabin);
  TH2F *hsfiso 	= new TH2F("hsfiso", "hsfiso", nptbin, ptbin, netabin, etabin);
  hsfid->Sumw2();
  hsfiso->Sumw2();


  //---------------------------
  // tag cuts
  //---------------------------

  TCut zmass("abs(tagAndProbeMass-91)<15");
  TCut eltnp("(eventSelection&1)==1");
  TCut mutnp("(eventSelection&2)==2");
  TCut os("qProbe*qTag<0");
  TCut tag_eta21("abs(tag->eta())<2.1");
  TCut tag_eta25("abs(tag->eta())<2.5");
  TCut njets1("njets>=1");
  TCut njets2("njets>=2");
  TCut njets3("njets>=3");
  TCut njets4("njets>=4");
  TCut tag_pt30("tag->pt()>30.0");
  TCut met30("met<30");
  TCut met20("met<20");
  TCut nbm0("nbm==0");
  TCut nbl0("nbl==0");
  TCut mt30("mt<30");
  TCut eltnptrig("HLT_Ele27_WP80_tag > 0");
  TCut mutnptrig("HLT_IsoMu24_tag > 0");

  //---------------------------
  // tag cuts
  //---------------------------

  TCut mufo 	= "(leptonSelection&32768)==32768";    // mu fo
  TCut muid 	= "(leptonSelection&65536)==65536";    // mu id 
  TCut muiso 	= "(leptonSelection&131072)==131072";  // mu iso 
  TCut elfo     = "(leptonSelection&4)==4";            // ele fo 
  TCut elid  	= "(leptonSelection&8)==8";            // ele id 
  TCut eliso 	= "(leptonSelection&16)==16";          // ele iso
  TCut probept  = "probe->pt()>30";                    // probe pt
  TCut drprobe  = "drprobe<0.05";                      // dR(probe,pfcandidate)

  TCut eltnpcut;
  eltnpcut += zmass;
  eltnpcut += os;
  eltnpcut += eltnp;
  eltnpcut += tag_eta21;
  //eltnpcut += njets2;
  eltnpcut += tag_pt30;
  eltnpcut += eltnptrig;
  eltnpcut += met30;
  // eltnpcut += mt30;
  eltnpcut += nbl0;
  
  eltnpcut += elid;
  eltnpcut += probept;
  eltnpcut += drprobe;

  TCut mutnpcut;
  mutnpcut += zmass;
  mutnpcut += os;
  mutnpcut += mutnp;
  mutnpcut += tag_eta21;
  //mutnpcut += njets2;
  mutnpcut += tag_pt30;
  mutnpcut += mutnptrig;
  mutnpcut += met30;
  // mutnpcut += mt30;
  mutnpcut += nbl0;

  mutnpcut += muid;
  mutnpcut += probept;
  mutnpcut += drprobe;


  //eltnpcut += njets2;
  //eltnpcut += njets3;
  //eltnpcut += nbm0;
  //eltnpcut += mt30;
  //eltnpcut += met20;

  //TCut eltnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&1)==1 && qProbe*qTag<0 && abs(tag->eta())<2.5 && njets>=4 && tag->pt()>30.0 && met<30.0 && nbm==0 && mt<30"; 
  //TCut mutnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && njets>=4 && tag->pt()>30.0"; 

  TCut vtxweight = "vtxweight";

  

  cout << "Electrons:" << endl;
  cout << "Selection            : " << eltnpcut.GetTitle()          << endl;
  cout << "Total MC yields 	: " << chmc->GetEntries(eltnpcut)   << endl;
  cout << "Total DATA yields 	: " << chdata->GetEntries(eltnpcut) << endl;

  cout << "Muons:" << endl;
  cout << "Selection            : " << mutnpcut.GetTitle()          << endl;
  cout << "Total MC yields 	: " << chmc->GetEntries(mutnpcut)   << endl;
  cout << "Total DATA yields 	: " << chdata->GetEntries(mutnpcut) << endl;


  //TCut njets    = "njets>=2";
  TCut tkisoold = "tkisoold/probe->pt()>0.1";
  TCut tkisonew = "tkisonew/probe->pt()>0.1";

  //-----------------------------------------
  // check nvtx data vs. MC
  //-----------------------------------------

  TH1F *hnvtx_mc   = new TH1F("hnvtx_mc"  ,"",30,0,30);
  TH1F *hnvtx_data = new TH1F("hnvtx_data","",30,0,30);

  hnvtx_mc->Sumw2();
  hnvtx_data->Sumw2();

  chdata->Draw("nvtx>>hnvtx_data",(eltnpcut||mutnpcut));
  chmc->Draw("nvtx>>hnvtx_mc",(eltnpcut||mutnpcut)*vtxweight);

  TCanvas *c1 = new TCanvas();
  c1->cd();
  
  hnvtx_mc->SetLineColor(2);
  hnvtx_mc->SetMarkerColor(2);
  hnvtx_data->SetLineColor(4);
  hnvtx_data->SetMarkerColor(4);
  
  hnvtx_data->GetXaxis()->SetTitle("N_{VTX}");
  hnvtx_data->DrawNormalized();
  hnvtx_mc->DrawNormalized("same");

  TLegend *leg = new TLegend(0.6,0.6,0.8,0.8);
  leg->AddEntry(hnvtx_data,"data","lp");
  leg->AddEntry(hnvtx_mc,"MC","lp");
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->Draw();

  if( printplot ) c1->Print("plots/nvtx.pdf");

  //--------------------------
  // absolute track isolation
  //--------------------------
  
  bool residual = true;
  bool log      = true;
  
  char* var = "tkisonewnoveto";
  
  plotDistribution( chdata , chmc , TCut(eltnpcut)        , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_0j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut)        , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_0j" , printplot , residual , log );

  plotDistribution( chdata , chmc , TCut(eltnpcut+njets1) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_1j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets1) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_1j" , printplot , residual , log );
  
  plotDistribution( chdata , chmc , TCut(eltnpcut+njets2) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_2j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets2) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_2j" , printplot , residual , log );

  plotDistribution( chdata , chmc , TCut(eltnpcut+njets3) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_3j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets3) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_3j" , printplot , residual , log );

  plotDistribution( chdata , chmc , TCut(eltnpcut+njets4) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "el_tkiso_4j" , printplot , residual , log );
  plotDistribution( chdata , chmc , TCut(mutnpcut+njets4) , vtxweight , var , 10 , 0 , 10 , "abs tkiso [GeV]"    , "mu_tkiso_4j" , printplot , residual , log );

  //--------------------------
  // relative track isolation
  //--------------------------

  // plotDistribution( chdata , chmc , TCut(eltnpcut) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "el_tkrliso_2j" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "mu_tkrliso_2j" , printplot );

  // plotDistribution( chdata , chmc , TCut(eltnpcut+njets3) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "el_tkrliso_3j" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut+njets3) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "mu_tkrliso_3j" , printplot );

  // plotDistribution( chdata , chmc , TCut(eltnpcut+njets4) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "el_tkrliso_4j" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut+njets4) , vtxweight , "tkisonew/probe->pt()" , 10 , 0 , 1 , "rel tkiso [GeV]"    , "mu_tkrliso_4j" , printplot );




  // plotDistribution( chdata , chmc , TCut(eltnpcut) , vtxweight , "tkisoold" , 10 , 0 , 10 , "trkiso (old) [GeV]" , "el_tkiso_old" , printplot );
  // plotDistribution( chdata , chmc , TCut(mutnpcut) , vtxweight , "tkisoold" , 10 , 0 , 10 , "trkiso (old) [GeV]" , "mu_tkiso_old" , printplot );

  //printHisto( chdata , chmc , TCut(muiso) , TCut(tnpcut+muid) , "probe.pt()" , 10 , 0.0 , 100.0 , "lepton p_{T} [GeV]" , "iso efficiency" );
  //printHisto( chdata , chmc , tkisoold , TCut(tnpcut+muid+njets) , "probe.pt()" , 10 , 0.0 , 100.0 , "lepton p_{T} [GeV]" , "tkiso(old) efficiency" );
  //printHisto( chdata , chmc , tkisonew , TCut(tnpcut+muid+njets) , "probe.pt()" , 10 , 0.0 , 100.0 , "lepton p_{T} [GeV]" , "tkiso(new) efficiency" );


  /*


  //
  // Fill histograms
  //
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");

  TCut tnpcut   	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && njets>=4 && tag->pt()>30.0"; 

  chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+muiso,	      	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 	tnpcut+muiso+muid,	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+muid,	      	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+muid+muiso,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+muiso,		"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 	tnpcut+muiso+muid,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+muid,	       	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+muid+muiso,	"goff");

  // get efficiencies 
  // hmcid->Divide(hmcid_num,hmcid_deno,1,1,"B");
  // hmciso->Divide(hmciso_num,hmciso_deno,1,1,"B");
  // hdataid->Divide(hdataid_num,hdataid_deno,1,1,"B");
  // hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1,"B");

  hmcid->Divide(hmcid_num,hmcid_deno,1,1);
  hmciso->Divide(hmciso_num,hmciso_deno,1,1);
  hdataid->Divide(hdataid_num,hdataid_deno,1,1);
  hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1);
	
  // get scale factors
  hsfid->Divide(hdataid, hmcid, 1, 1);
  hsfiso->Divide(hdataiso, hmciso, 1, 1);

  // Draw histograms	
  //hmcid->Draw("text");
  */

  /*
  // print table
  cout << " ------ MC ID ----- " << endl;
  printline(hmcid);
  cout << " ------ MC ISO ----- " << endl;
  printline(hmciso);
  cout << " ------ DATA ID ----- " << endl;
  printline(hdataid);
  cout << " ------ DATA ISO ----- " << endl;
  printline(hdataiso);
  cout << " ------ Scale Factor ID ----- " << endl;
  printline(hsfid);
  cout << " ------ Scale Factor ISO ----- " << endl;
  printline(hsfiso);
  */
	
}
int printYield(){
  // Open input file(s)
  string basedirectory = "/lstore/cms/cbeiraod/Stop4Body/LepFix/";

  // Create chains
  TChain* wjetsChain = new TChain("bdttree"); //creates a chain to process a Tree called "bdttree"
  wjetsChain->Add((basedirectory + "Wjets_100to200_bdt.root").c_str());
  wjetsChain->Add((basedirectory + "Wjets_200to400_bdt.root").c_str());
  wjetsChain->Add((basedirectory + "Wjets_400to600_bdt.root").c_str());
  wjetsChain->Add((basedirectory + "Wjets_600toInf_bdt.root").c_str());

  TChain* ttbarChain = new TChain("bdttree"); //creates a chain to process a Tree called "bdttree"
  ttbarChain->Add((basedirectory + "TTJets_LO_bdt.root").c_str());

  TChain* stopChain = new TChain("bdttree"); //creates a chain to process a Tree called "bdttree"
  stopChain->Add((basedirectory + "T2DegStop_300_270_bdt.root").c_str());

  TChain* dataChain = new TChain("bdttree"); //creates a chain to process a Tree called "bdttree"
  dataChain->Add((basedirectory + "PseudoData_bdt.root").c_str());

  vector<process> vprocess;

  process pwjets(wjetsChain,"wjets");
  process pttbar(ttbarChain,"ttbar");
  process psignal(stopChain,"signal");

  vprocess.push_back(pwjets);
  vprocess.push_back(pttbar);
  vprocess.push_back(psignal);

  //Create TCuts
  TCut null = "1";
  TCut muon = "(abs(LepID)==13)&&(LepIso03<0.2)";
  TCut electron = "(abs(LepID)==11)&&(LepIso03<0.2)";
  TCut emu = muon||electron;
  TCut ISRjet = "Jet1Pt > 110";
  TCut met = "Met > 300";
  TCut njets = "Njet > 2";
  TCut lepPt = "LepPt < 17";
//  TCut mt = "mt < 135";
  TCut preSel = met && emu && ISRjet;

  TCut selection = preSel;

  TCut Met540 = "Met>540";
  TCut mt100 = "mt > 100";
  TCut jet1Pt550 = "Jet1Pt > 550";
  TCut CosDeltaPhi025 = "CosDeltaPhi < 0.25";
  TCut ht20700 = "HT20 > 700";

  //Set names of TCuts
  emu.SetName("emu");
  ISRjet.SetName("$p_T$(Jet1)$ > 110$");
  electron.SetName("electron");
  preSel.SetName("PreSelection");
  selection.SetName("Selection FOM");

  // Create VCut
  vector<TCut> vcut;
  //vcut.push_back(emu);
  //vcut.push_back(ISRjet*emu);
  //vcut.push_back(met*ISRjet*emu);
  vcut.push_back(preSel);
  vcut.push_back(Met540*preSel);
  vcut.push_back(mt100*Met540*preSel);
  vcut.push_back(jet1Pt550*mt100*Met540*preSel);
//  vcut.push_back(CosDeltaPhi025*Met540*preSel);
//  vcut.push_back(ht20700*CosDeltaPhi025*Met540*preSel);

  vcut[1].SetName("Met $>$ 540");
//  vcut[2].SetName("$Cos(\\Delta \\phi)$ $<$ 0.25");
  vcut[2].SetName("$m_T >$ 100");
//  vcut[3].SetName("$H_T$ (20) $>$ 700");
  vcut[3].SetName("$p_T$ (Jet) $>$ 550");

  // Create matrix
  double** matrix = new double*[vprocess.size()+3];
  for(int i=0; i<int(vprocess.size()+3); i++)
    matrix[i] = new double[vcut.size()+1];

  double** matrixError = new double*[vprocess.size()+3];
  for(int i=0; i<int(vprocess.size()+3); i++)
    matrixError[i] = new double[vcut.size()+1];

  // Total
  for(int i=0;i<int(vprocess.size());i++)
    {
      matrix[i][0] = countTotal(vprocess[i]);
      matrixError[i][0] = countError(vprocess[i].GetChain(), null);
    }

  // Processes
  for(int i=0; i<int(vprocess.size()); i++)
    {
      for(int j=0;j<int(vcut.size());j++)
      {
        matrix[i][j+1] = countEvt(vprocess[i],vcut[j]);
        matrixError[i][j+1] = countError(vprocess[i].GetChain(),vcut[j]);
      }
    }

  // Total Background & Signal + Background
  for(int j=0; j<int(vcut.size()+1); j++)
    {
      matrix[vprocess.size()][j] = 0;
      matrix[vprocess.size()+1][j] = 0;

      matrixError[vprocess.size()][j] = 0;
      matrixError[vprocess.size()+1][j] = 0;

      double tmp=0;

      for(int i=0; i<int(vprocess.size()-1); i++)
      {
        matrix[vprocess.size()][j] += matrix[i][j];
        tmp += matrixError[i][j]*matrixError[i][j];
      }

      matrixError[vprocess.size()][j] = sqrt(tmp);

      double tmp1 = matrixError[vprocess.size()][j];
      double tmp2 = matrixError[vprocess.size()-1][j];

      matrix[vprocess.size()+1][j] = matrix[vprocess.size()][j] + matrix[vprocess.size()-1][j];
      matrixError[vprocess.size()+1][j] = sqrt(tmp1*tmp1 + tmp2*tmp2);
    }

  // Data
  matrix[vprocess.size()+2][0] = countDataTotal(dataChain);
  matrixError[vprocess.size()+2][0] = countDataError(dataChain, null);
  for(int j=0; j<int(vcut.size()); j++)
    {
      matrix[vprocess.size()+2][j+1] = countDataEvt(dataChain, vcut[j]);
      matrixError[vprocess.size()+2][j+1] = countDataError(dataChain, vcut[j]);
    }

  // Print
  Print(vprocess,vcut,matrix,matrixError);

  return 0;
}
void fit_combine(TTree *tc, std::string Var,std::string filltype, const double * VarBins_array , const int nVarBins , TCut Gcut,  double *mean, double *meanErr, double *sigma, double *sigmaErr , int type){

	std::string jetTitle=tc->GetTitle();

	gStyle->SetOptFit(1111);
	cout<<"tc title = "<<tc->GetTitle()<<" ,Var = "<<Var<<" ,nVarBins = "<<nVarBins<<", Gcut = "<<Gcut<<endl;
	Can_Temp[counter] = new TCanvas(Form("Can_Temp_%i",counter));
	if(nVarBins<=9){Can_Temp[counter]->Divide(3,3);}
	else if(nVarBins<=12){Can_Temp[counter]->Divide(3,4);}
	else {Can_Temp[counter]->Divide(4,4);}



	TH1D *h_Ratio[nVarBins];
	TF1 *f_Ratio[nVarBins];
	double nRatiobins= 50;
	double minRatio=0;
	double maxRatio=3;
	if (filltype.compare("residue")==0){
		minRatio= -2;
		maxRatio=2;	
	}

	// TLegend *legendfit[nVarBins]; 

	for(int ibin =0; ibin<nVarBins; ibin++)
	{
		Can_Temp[counter]->cd(ibin+1);
		double VarMin = VarBins_array[ibin];
		double VarMax = VarBins_array[ibin+1];

		h_Ratio[ibin] = new TH1D( Form("h_Ratio[%d]",ibin),Form("%s_%s_%i_%i",jetTitle.c_str(),Var.c_str(),(int)VarMin,(int)VarMax) ,nRatiobins,minRatio,maxRatio);  // h_Ration_%d ??
		h_Ratio[ibin]->Sumw2();

		TCut Varcut = Form("%s>%f && %s<%f", Var.c_str(), VarMin, Var.c_str(), VarMax);
		TCut allcut = Gcut && Varcut;
		cout<<"Varcut = "<<Varcut<<" ,allcut = "<<allcut<<endl;

		if (filltype.compare("residue")==0){
			tc->Draw( Form("(jtpt/refpt -1)>>h_Ratio[%d]",ibin ) , allcut*"weight" );
		}
		if (filltype.compare("ratio")==0){

			if(type==0){tc->Draw( Form("jtptCorr/refpt>>h_Ratio[%d]",ibin ) , allcut*"weight" ); }
			else if(type==1){tc->Draw( Form("jtptCorrB/refpt>>h_Ratio[%d]",ibin ) , allcut*"weight" ); }
			else if(type==2){tc->Draw( Form("jtptCorrcsvB/refpt>>h_Ratio[%d]",ibin ) , allcut*"weight" ); }
			else if(type==3){tc->Draw( Form("jtptCorrFCRB/refpt>>h_Ratio[%d]",ibin ) , allcut*"weight" ); }
			else if(type==4){tc->Draw( Form("jtptCorrFCRcsvB/refpt>>h_Ratio[%d]",ibin ) , allcut*"weight" ); }
			else{cout<<"type worng!!"<<endl;
				tc->Draw( Form("jtpt/refpt>>h_Ratio[%d]",ibin ) , allcut*"weight" );}
		}

		double mean_temp=h_Ratio[ibin]->GetMean();
		double rms_temp=h_Ratio[ibin]->GetRMS();

		h_Ratio[ibin]->GetXaxis()->SetTitle(Form("%s, jtpt/refpt",Gcut.GetTitle()));

		if (filltype.compare("ratio")==0){
			f_Ratio[ibin] = new TF1(Form("f_Ratio_%d",ibin), "gaus",mean_temp-3*rms_temp,mean_temp+3*rms_temp );}
		if (filltype.compare("residue")==0){
			f_Ratio[ibin] = new TF1(Form("f_Ratio_%d",ibin), "gaus",-3*rms_temp,3*rms_temp );}


		f_Ratio[ibin]->SetParameter(0,h_Ratio[ibin]->GetEntries()); // get number for normalization
		if(ibin==0){
			if (filltype.compare("ratio")==0){
				f_Ratio[ibin]->SetParameter(1,h_Ratio[ibin]->GetMean()) ;   // for mean
				f_Ratio[ibin]->SetParameter(2,h_Ratio[ibin]->GetRMS()) ; // for sigma   
			}
			if (filltype.compare("residue")==0){
				f_Ratio[ibin]->SetParameter(1,h_Ratio[ibin]->GetMean()-1) ;   // for mean
				f_Ratio[ibin]->SetParameter(2,h_Ratio[ibin]->GetRMS()) ; // for sigma
			}	
		}
		if(ibin>=1){
			f_Ratio[ibin]->SetParameter(1,mean[ibin-1]) ;   // for mean
			f_Ratio[ibin]->SetParameter(2,sigma[ibin-1]) ; // for sigma   
		} 
		//		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
		//		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MRL");
		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"WL Q MR");
		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
		h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");

		if (f_Ratio[ibin]->GetProb() < .01){cout<<"f1_Ratio[ibin]->GetProb() <0.01"<<endl;}

		if(f_Ratio[ibin]->GetParError(1) > 0.05 || f_Ratio[ibin]->GetProb() < .001){
			f_Ratio[ibin] = new TF1(Form("f_Ratio_%d",ibin), "gaus",mean_temp-2*rms_temp,mean_temp+2*rms_temp );
			f_Ratio[ibin]->SetParameter(1,h_Ratio[ibin]->GetMean());
			f_Ratio[ibin]->SetParameter(2,h_Ratio[ibin]->GetRMS()) ; 	
			h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
			h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MRL");
			h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"WL Q MR");
			h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
			h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
			h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");
			h_Ratio[ibin]->Fit(Form("f_Ratio_%d",ibin),"MR");



		}

		/*
			 legendfit[ibin]= new TLegend(0.2,0.2,0.7,0.4);
			 legendfit[ibin]->AddEntry((TObject*)0,Form("%s",Gcut.GetTitle()),"");
			 legendfit[ibin]->SetBorderSize(0);
			 legendfit[ibin]->Draw();
			 */


		mean[ibin] = f_Ratio[ibin]->GetParameter(1);
		meanErr[ibin] = f_Ratio[ibin]->GetParError(1);
		sigma[ibin] = f_Ratio[ibin]->GetParameter(2);
		sigmaErr[ibin] = f_Ratio[ibin]->GetParError(2);

	} // end   for(int ibin =0; ibin<nVarBins; ibin++)

	Can_Temp[counter]->SaveAs(Form("./Plots/%s/fitPlots/fit_%s_%s_%s.pdf",Var.c_str(),Var.c_str(),jetTitle.c_str(),Gcut.GetTitle() ));

	counter++; 
}
Exemple #25
0
void extractK( bool exclusive , bool printplot , bool bveto ){

  //char* iter = (char*) "V00-01-04";
  char* iter = (char*) "V00-02-00";

  //char* suffix = "";
  char* suffix = "_2jets";

  TChain *data = new TChain("T1");
  //data->Add(Form("../output/%s/data_ALL_53X_baby%s.root",iter,suffix));
  //data->Add(Form("../output/%s/data_53X_baby%s.root",iter,suffix));
  //data->Add(Form("../output/%s/data_2012C_53X_baby%s.root",iter,suffix));

  data->Add(Form("../output/%s/data_53X_2012A_baby%s.root",iter,suffix));
  data->Add(Form("../output/%s/data_53X_2012B_baby%s.root",iter,suffix));
  data->Add(Form("../output/%s/data_53X_2012C_baby%s.root",iter,suffix));
  data->Add(Form("../output/%s/data_53X_2012D_baby%s.root",iter,suffix));

  TChain *mc = new TChain("T1");
  mc->Add(Form("../output/%s/ttbar_53X_baby%s.root"       ,iter,suffix));
  //mc->Add(Form("../output/%s/zjets_full_53X_baby%s.root"  ,iter,suffix));
  mc->Add(Form("../output/%s/zjets_53X_baby%s.root"  ,iter,suffix));
  mc->Add(Form("../output/%s/ww_53X_baby%s.root"          ,iter,suffix));
  mc->Add(Form("../output/%s/wz_53X_baby%s.root"          ,iter,suffix));
  mc->Add(Form("../output/%s/zz_53X_baby%s.root"          ,iter,suffix));
  mc->Add(Form("../output/%s/t_53X_baby%s.root"           ,iter,suffix));
  mc->Add(Form("../output/%s/ttZ_53X_baby%s.root"         ,iter,suffix));
  mc->Add(Form("../output/%s/ttW_53X_baby%s.root"         ,iter,suffix));
  mc->Add(Form("../output/%s/VVV_53X_baby%s.root"         ,iter,suffix));

  //mc->Add(Form("../output/%s/ttbar_baby%s.root",iter,suffix));
  //mc->Add(Form("../output/%s/zjets_baby%s.root",iter,suffix));
  //mc->Add(Form("../output/%s/ww_baby%s.root",iter,suffix));
  //mc->Add(Form("../output/%s/t_baby%s.root",iter,suffix));

  TCut pfleptons("pflep1.pt() > 20 && pflep2.pt() > 20");
  TCut transveto("el1tv==0 && el2tv==0");
  TCut Zmass("dilmasspf>81 && dilmasspf<101");
  TCut njets2("njets>=2");
  TCut em("leptype==2");
  TCut nb0("nbcsvm==0");
  TCut mjj("mjj>70.0 && mjj<110.0");
  TCut nlep2("nlep==2");
  TCut pt40cuts("njets40>=2");
  TCut pt2010("lep1.pt()>20 && lep2.pt()>10");
  TCut pt2020("lep1.pt()>20 && lep2.pt()>20");
  TCut filters("csc==0 && hbhe==1 && hcallaser==1 && ecaltp==1 && trkfail==1 && eebadsc==1 && hbhenew==1");
  TCut runrange("isdata==0 || (run<197556 || run>198913)");

  TCut sel;
  sel += em;
  sel += filters;
  sel += runrange;
  //sel += transveto;
  
  if( pt40 ){
    //sel += pt40cuts;
    sel += "njets40>=3";
    sel += pt2020;
  }

  else{
    sel += njets2;
    //sel += pfleptons;
    sel += pt2020;
  }

  if( bveto ){
    sel += nb0;
    //sel += mjj;
    //sel += nlep2;
  }

  TCut weight("vtxweight * weight");
  //TCut weight("1");

  cout << "Using selection : " << sel.GetTitle() << endl;
  cout << "Using weight    : " << weight.GetTitle() << endl;

  cout << "OF entries (total)  " << data->GetEntries(sel+em) << endl;
  cout << "OF entries (Z mass) " << data->GetEntries(sel+Zmass+em) << endl;
  cout << "K                   " << (float) data->GetEntries(sel+Zmass+em) / (float) data->GetEntries(sel+em) << endl;

  int mynbins = 6;
  if( bveto ) mynbins = 7;

  const unsigned int nbins = mynbins;

  TCut metcuts[nbins];

  if( bveto ){
    if( exclusive ){
      metcuts[0] = TCut("pfmet>0   && pfmet<30" );
      metcuts[1] = TCut("pfmet>30  && pfmet<60" );
      metcuts[2] = TCut("pfmet>60  && pfmet<80" );
      metcuts[3] = TCut("pfmet>80  && pfmet<100");
      metcuts[4] = TCut("pfmet>100 && pfmet<150");
      metcuts[5] = TCut("pfmet>150 && pfmet<200");
      metcuts[6] = TCut("pfmet>200");
    }else{
      metcuts[0] = TCut("pfmet>0");
      metcuts[1] = TCut("pfmet>30");
      metcuts[2] = TCut("pfmet>60");
      metcuts[3] = TCut("pfmet>80");
      metcuts[4] = TCut("pfmet>100");
      metcuts[5] = TCut("pfmet>150");
      metcuts[6] = TCut("pfmet>200");

    }
  }

  else{
    if( exclusive ){
      metcuts[0] = TCut("pfmet>0   && pfmet<30" );
      metcuts[1] = TCut("pfmet>30  && pfmet<60" );
      metcuts[2] = TCut("pfmet>60  && pfmet<100");
      metcuts[3] = TCut("pfmet>100 && pfmet<200");
      metcuts[4] = TCut("pfmet>200 && pfmet<300");
      metcuts[5] = TCut("pfmet>300");
    }else{
      metcuts[0] = TCut("pfmet>0");
      metcuts[1] = TCut("pfmet>30");
      metcuts[2] = TCut("pfmet>60");
      metcuts[3] = TCut("pfmet>100");
      metcuts[4] = TCut("pfmet>200");
      metcuts[5] = TCut("pfmet>300");
    }
  }

  float K[nbins];
  float Kerr[nbins];

  float KMC[nbins];
  float KMCerr[nbins];

  TH1F* htot = new TH1F("htot","",1,0,1);
  TH1F* hZ   = new TH1F("hZ"  ,"",1,0,1);
  htot->Sumw2();
  hZ->Sumw2();

  for( int i = 0 ; i < nbins ; ++i ){
    float tot = (float) data->GetEntries(sel+em+metcuts[i]);
    float   Z = (float) data->GetEntries(sel+em+metcuts[i]+Zmass);
    
    K[i]    = Z/tot;
    Kerr[i] = sqrt(Z)/tot;

    // float totMC = (float) mc->GetEntries(sel+em+metcuts[i]);
    // float   ZMC = (float) mc->GetEntries(sel+em+metcuts[i]+Zmass);
    
    // KMC[i]    = ZMC/totMC;
    // KMCerr[i] = sqrt(ZMC)/totMC;

    mc->Draw("0.5>>htot" , (sel+em+metcuts[i]      ) * weight );
    mc->Draw("0.5>>hZ"   , (sel+em+metcuts[i]+Zmass) * weight );

    float   totMC     = htot->GetBinContent(1);
    float   ZMC       = hZ->GetBinContent(1);
    float   totMCerr  = htot->GetBinError(1);
    float   ZMCerr    = hZ->GetBinError(1);

    KMC[i]    = ZMC    / totMC;
    //KMCerr[i] = ZMCerr / totMC;
    KMCerr[i] = KMC[i] * sqrt(pow( totMCerr/totMC , 2 ) + pow( ZMCerr/ZMC , 2 ) );

    cout << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << metcuts[i].GetTitle() << endl << endl;
    cout << "data  : " << endl;
    cout << "total : " << tot << endl;
    cout << "Z     : " <<   Z << endl;
    cout << "K     : " << Form("%.2f +/- %.3f",K[i],Kerr[i]) << endl << endl;
    cout << "MC    : " << endl;
    cout << "total : " << totMC << endl;
    cout << "Z     : " <<   ZMC << endl;
    cout << "K     : " << Form("%.2f +/- %.3f",KMC[i],KMCerr[i]) << endl;
    cout << "--------------------------------------------------------------" << endl;
    cout << endl;
  }

  float x[nbins];
  float xerr[nbins];
  
  for(int i = 0 ; i < nbins ; ++i ){
    x[i]    = i+1;
    xerr[i] = 0;
  }

  TCanvas *c1 = new TCanvas();
  c1->cd();
  gPad->SetGridy();

  TH2F* hdummy = new TH2F("hdummy","",nbins,0.5,nbins+0.5,10,0,0.2);
  hdummy->Draw();
  hdummy->GetXaxis()->SetTitle("E_{T}^{miss} [GeV]");
  hdummy->GetYaxis()->SetTitle("K");
  if( bveto ){
    if( exclusive ){
      hdummy->GetXaxis()->SetBinLabel(1,"0-30");
      hdummy->GetXaxis()->SetBinLabel(2,"30-60");
      hdummy->GetXaxis()->SetBinLabel(3,"60-80");
      hdummy->GetXaxis()->SetBinLabel(4,"80-100");
      hdummy->GetXaxis()->SetBinLabel(5,"100-150");
      hdummy->GetXaxis()->SetBinLabel(6,"150-200");
      hdummy->GetXaxis()->SetBinLabel(7,">200");
    }
    else{
      hdummy->GetXaxis()->SetBinLabel(1,">0");
      hdummy->GetXaxis()->SetBinLabel(2,">30");
      hdummy->GetXaxis()->SetBinLabel(3,">60");
      hdummy->GetXaxis()->SetBinLabel(4,">80");
      hdummy->GetXaxis()->SetBinLabel(5,">100");
      hdummy->GetXaxis()->SetBinLabel(6,">150");
      hdummy->GetXaxis()->SetBinLabel(7,">200");
    }
  }
  else{
    if( exclusive ){
      hdummy->GetXaxis()->SetBinLabel(1,"0-30");
      hdummy->GetXaxis()->SetBinLabel(2,"30-60");
      hdummy->GetXaxis()->SetBinLabel(3,"60-100");
      hdummy->GetXaxis()->SetBinLabel(4,"100-200");
      hdummy->GetXaxis()->SetBinLabel(5,"200-300");
      hdummy->GetXaxis()->SetBinLabel(6,">300");
    }
    else{
      hdummy->GetXaxis()->SetBinLabel(1,">0");
      hdummy->GetXaxis()->SetBinLabel(2,">30");
      hdummy->GetXaxis()->SetBinLabel(3,">60");
      hdummy->GetXaxis()->SetBinLabel(4,">100");
      hdummy->GetXaxis()->SetBinLabel(5,">200");
      hdummy->GetXaxis()->SetBinLabel(6,">300");
    }
  }

  TGraphErrors *gr   = new TGraphErrors(nbins,x,K,xerr,Kerr);
  TGraphErrors *grMC = new TGraphErrors(nbins,x,KMC,xerr,KMCerr);
  gr->GetXaxis()->SetTitle("E_{T}^{miss} bin");
  gr->GetYaxis()->SetTitle("K");
  gr->SetMaximum(0.2);
  grMC->SetLineColor(2);
  grMC->SetMarkerColor(2);
  grMC->SetMarkerStyle(25);

  gr->Draw("sameP");
  grMC->Draw("sameP");

  TLegend* leg = new TLegend(0.2,0.2,0.4,0.4);
  leg->AddEntry(gr,"data","lp");
  leg->AddEntry(grMC,"MC","lp");
  leg->SetFillColor(0);
  leg->SetBorderSize(1);
  leg->Draw();

  if( printplot ){

    if( bveto ){
      if(exclusive ) c1->Print("../plots/extractK_exclusive_bveto.pdf");
      else           c1->Print("../plots/extractK_inclusive_bveto.pdf");
    }

    else{
      if(exclusive ) c1->Print("../plots/extractK_exclusive.pdf");
      else           c1->Print("../plots/extractK_inclusive.pdf");
    }

  }

}
void drawSpectra2D(const TString configFile, const TString inputFile, const TString outputFile, const TString outputFigureName)
{
    std::cout<<"running drawSpectra2D()"<<std::endl;
    std::cout<<"configFile  = "<< configFile.Data() <<std::endl;
    std::cout<<"inputFile   = "<< inputFile.Data()  <<std::endl;
    std::cout<<"outputFile  = "<< outputFile.Data() <<std::endl;

    InputConfiguration configInput = InputConfigurationParser::Parse(configFile.Data());
    CutConfiguration configCuts = CutConfigurationParser::Parse(configFile.Data());

    if (!configInput.isValid) {
        std::cout << "Input configuration is invalid." << std::endl;
        std::cout << "exiting" << std::endl;
        return;
    }
    if (!configCuts.isValid) {
        std::cout << "Cut configuration is invalid." << std::endl;
        std::cout << "exiting" << std::endl;
        return;
    }

    /*
     * drawing behavior :
     *      1. If N = # formulas and N = # selections, then N histograms will be drawn,
     *      2. If 1 = # formulas and N = # selections, then N histograms will be drawn with the same formula.
     *      3. If N = # formulas and 1 = # selections, then N histograms will be drawn with the same selection.
     *      4. else, exit.
     */
    // input for mode
    int mode = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_mode];

    // input for TTree
    std::vector<std::string> treePaths = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treePath]);
    std::vector<std::string> treeFriendsPath = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeFriendPath]);
    std::vector<std::string> treeFriendsPathIndividual = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeFriendPathIndividual]);
    std::vector<std::string> formulas = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeFormula]);
    std::string selectionBase = configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeSelectionBase];
    std::vector<std::string> selections = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeSelection]);
    std::vector<std::string> selectionSplitter = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_treeSelectionSplitter]);
    std::vector<std::string> weights = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_weight]);

    // input for TH1
    std::vector<std::string> titles = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_title]));
    std::vector<std::string> titlesX = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_titleX]));
    std::vector<std::string> titlesY = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH1_titleY]));
    // nBinsx, xLow, xUp, nBinsy, yLow, yUp for a TH2D histogram
    std::vector<std::vector<float>> TH2D_Bins_List = ConfigurationParser::ParseListTH2D_Bins(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TH2D_Bins_List]);
    float titleOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_titleOffsetX];
    float titleOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_titleOffsetY];
    float markerSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_markerSize];
    int drawNormalized = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_drawNormalized];
    std::vector<std::string> drawOptions = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_drawOption]);
    std::vector<std::string> markerStyles = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_markerStyle]);
    std::vector<std::string> lineStyles = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_lineStyle]);
    std::vector<std::string> fillStyles = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_fillStyle]);
    std::vector<std::string> colors = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_color]);
    std::vector<std::string> fillColors = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_fillColor]);
    std::vector<std::string> lineColors = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_lineColor]);
    int lineWidth = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_lineWidth];

    // input for TLegend
    std::vector<std::string> legendEntryLabels = ConfigurationParser::ParseList(ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_legendEntryLabel]));
    std::string legendPosition = configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_legendPosition];
    float legendOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendOffsetX];
    float legendOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendOffsetY];
    int legendBorderSize = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_legendBorderSize];
    float legendWidth = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendWidth];
    float legendHeight = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendHeight];
    float legendTextSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_legendTextSize];

    // input for text objects
    std::string tmpText = ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_text]);
    std::vector<std::string> textLines = ConfigurationParser::ParseList(tmpText);
    int textFont = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_textFont];
    float textSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textSize];
    std::string textPosition = configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_textPosition];
    float textOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textOffsetX];
    float textOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textOffsetY];

    std::string tmpTextOverPad = ConfigurationParser::ParseLatex(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_textAbovePad]);
    std::vector<std::string> textsOverPad = ConfigurationParser::ParseList(tmpTextOverPad);
    std::vector<std::string> textsOverPadAlignments = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_textAbovePadAlign]);
    int textAbovePadFont = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_textAbovePadFont];
    float textAbovePadSize = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textAbovePadSize];
    float textAbovePadOffsetX = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textAbovePadOffsetX];
    float textAbovePadOffsetY = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_textAbovePadOffsetY];

    // input for TLine
    // y-axis positions of the horizontal lines to be drawn
    std::vector<float> TLines_horizontal = ConfigurationParser::ParseListFloat(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TLine_horizontal]);
    std::vector<std::string> lineStyles_horizontal = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_LineStyle_horizontal]);
    // x-axis positions of the vertical lines to be drawn
    std::vector<float> TLines_vertical = ConfigurationParser::ParseListFloat(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_TLine_vertical]);
    std::vector<std::string> lineStyles_vertical = ConfigurationParser::ParseList(configInput.proc[INPUT::kPERFORMANCE].s[INPUT::k_LineStyle_vertical]);

    // input for TCanvas
    int windowWidth = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_windowWidth];
    int windowHeight = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_windowHeight];
    float leftMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_leftMargin];
    float rightMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_rightMargin];
    float bottomMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_bottomMargin];
    float topMargin = configInput.proc[INPUT::kPERFORMANCE].f[INPUT::k_topMargin];
    int setLogx = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_setLogx];
    int setLogy = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_setLogy];
    int setLogz = configInput.proc[INPUT::kPERFORMANCE].i[INPUT::k_setLogz];

    // set default values
    if (selections.size() == 0) selections.push_back("1");
    if (weights.size() == 0)    weights.push_back(INPUT_DEFAULT::TH1_weight.c_str());   // default weight = 1.
    if (titleOffsetX == 0) titleOffsetX = INPUT_DEFAULT::titleOffsetX;
    if (titleOffsetY == 0) titleOffsetY = INPUT_DEFAULT::titleOffsetY;
    if (drawNormalized >= INPUT_TH1::kN_TYPE_NORM) drawNormalized = INPUT_DEFAULT::drawNormalized;
    if (lineWidth == 0)  lineWidth = INPUT_DEFAULT::lineWidth;

    if (markerSize == 0)  markerSize = INPUT_DEFAULT::markerSize;

    if (textFont == 0)  textFont = INPUT_DEFAULT::textFont;
    if (textSize == 0)  textSize = INPUT_DEFAULT::textSize;

    if (windowWidth  == 0)  windowWidth = INPUT_DEFAULT::windowWidth;
    if (windowHeight == 0)  windowHeight = INPUT_DEFAULT::windowHeight;
    if (leftMargin == 0) leftMargin = INPUT_DEFAULT::leftMargin;
    if (rightMargin == 0) rightMargin = INPUT_DEFAULT::rightMargin;
    if (bottomMargin == 0) bottomMargin = INPUT_DEFAULT::bottomMargin;
    if (topMargin == 0) topMargin = INPUT_DEFAULT::topMargin;

    int nTrees = treePaths.size();
    int nFriends = treeFriendsPath.size();
    int nFriendsIndividual = treeFriendsPathIndividual.size();
    int nFormulas = formulas.size();
    int nSelections = selections.size();
    int nSelectionSplitter = selectionSplitter.size();
    int nWeights = weights.size();
    int nTitles = titles.size();
    int nTitlesX = titlesX.size();
    int nTitlesY = titlesY.size();
    int nTH2D_Bins_List = TH2D_Bins_List[0].size();
    int nDrawOptions = drawOptions.size();
    int nMarkerStyles = markerStyles.size();
    int nLineStyles = lineStyles.size();
    int nFillStyles = fillStyles.size();
    int nColors = colors.size();
    int nFillColors = fillColors.size();
    int nLineColors = lineColors.size();
    int nLegendEntryLabels = legendEntryLabels.size();
    int nTextLines = textLines.size();
    int nTextsOverPad = textsOverPad.size();
    int nTextsOverPadAlignments = textsOverPadAlignments.size();
    int nTLines_horizontal = TLines_horizontal.size();
    int nLineStyles_horizontal = lineStyles_horizontal.size();
    int nTLines_vertical = TLines_vertical.size();
    int nLineStyles_vertical = lineStyles_vertical.size();

    // verbose about input configuration
    std::cout<<"Input Configuration :"<<std::endl;
    std::cout << "mode = " << mode << std::endl;
    if (mode == INPUT_MODE::k_comparison) {
        // in comparison mode "inputFile" should have the following format
        // inputFile = <inputFile1>,<inputFile2>,...
        // there should be no single space between <inputFile1> and <inputFile2>.
        // the idea is to feed the input samples as a single argument and split them in the macro.
        std::cout << "comparison mode : Spectra from two input samples are going to be compared." << std::endl;
    }
    std::cout << "nTrees = " << nTrees << std::endl;
    for (int i=0; i<nTrees; ++i) {
        std::cout << Form("treePaths[%d] = %s", i, treePaths.at(i).c_str()) << std::endl;
    }
    std::cout << "nFriends = " << nFriends << std::endl;
    for (int i=0; i<nFriends; ++i) {
        std::cout << Form("treeFriendsPath[%d] = %s", i, treeFriendsPath.at(i).c_str()) << std::endl;
    }
    std::cout << "nFriendsIndividual = " << nFriendsIndividual << std::endl;
    for (int i=0; i<nFriendsIndividual; ++i) {
        std::cout << Form("treeFriendsPathIndividual[%d] = %s", i, treeFriendsPathIndividual.at(i).c_str()) << std::endl;
    }
    std::cout << "nFormulas     = " << nFormulas << std::endl;
    for (int i=0; i<nFormulas; ++i) {
        std::cout << Form("formulas[%d]   = %s", i, formulas.at(i).c_str()) << std::endl;
    }
    std::cout << "selectionBase = " << selectionBase.c_str() << std::endl;
    std::cout << "nSelections   = " << nSelections << std::endl;
    for (int i=0; i<nSelections; ++i) {
        std::cout << Form("selections[%d] = %s", i, selections.at(i).c_str()) << std::endl;
    }
    std::cout << "nSelectionSplitter = " << nSelectionSplitter << std::endl;
    for (int i=0; i<nSelectionSplitter; ++i) {
        std::cout << Form("selectionSplitter[%d] = %s", i, selectionSplitter.at(i).c_str()) << std::endl;
    }
    std::cout << "nWeights   = " << nWeights << std::endl;
    for (int i=0; i<nWeights; ++i) {
        std::cout << Form("weights[%d] = %s", i, weights.at(i).c_str()) << std::endl;
    }

    std::cout << "nTitles   = " << nTitles << std::endl;
    for (int i=0; i<nTitles; ++i) {
        std::cout << Form("titles[%d] = %s", i, titles.at(i).c_str()) << std::endl;
    }
    std::cout << "nTitlesX   = " << nTitlesX << std::endl;
    for (int i=0; i<nTitlesX; ++i) {
        std::cout << Form("titlesX[%d] = %s", i, titlesX.at(i).c_str()) << std::endl;
    }
    std::cout << "nTitlesY   = " << nTitlesY << std::endl;
    for (int i=0; i<nTitlesY; ++i) {
        std::cout << Form("titlesY[%d] = %s", i, titlesY.at(i).c_str()) << std::endl;
    }
    std::cout << "nTH2D_Bins_List = " << nTH2D_Bins_List << std::endl;
    for (int i=0; i<nTH2D_Bins_List; ++i) {
        std::cout << Form("TH2D_Bins_List[%d] = { ", i);
        std::cout << Form("%.0f, ", TH2D_Bins_List[0].at(i));
        std::cout << Form("%f, ", TH2D_Bins_List[1].at(i));
        std::cout << Form("%f }", TH2D_Bins_List[2].at(i));
        std::cout << " { ";
        std::cout << Form("%.0f, ", TH2D_Bins_List[3].at(i));
        std::cout << Form("%f, ", TH2D_Bins_List[4].at(i));
        std::cout << Form("%f }", TH2D_Bins_List[5].at(i)) << std::endl;;
    }
    std::cout << "titleOffsetX = " << titleOffsetX << std::endl;
    std::cout << "titleOffsetY = " << titleOffsetY << std::endl;
    std::cout << "markerSize = " << markerSize << std::endl;
    std::cout << "drawNormalized = " << drawNormalized << std::endl;
    std::cout << "nDrawOptions   = " << nDrawOptions << std::endl;
    for (int i = 0; i<nDrawOptions; ++i) {
        std::cout << Form("drawOptions[%d] = %s", i, drawOptions.at(i).c_str()) << std::endl;
    }
    std::cout << "nMarkerStyles  = " << nMarkerStyles << std::endl;
    for (int i = 0; i<nMarkerStyles; ++i) {
        std::cout << Form("markerStyles[%d] = %s", i, markerStyles.at(i).c_str()) << std::endl;
    }
    std::cout << "nLineStyles   = " << nLineStyles << std::endl;
    for (int i = 0; i<nLineStyles; ++i) {
        std::cout << Form("lineStyles[%d] = %s", i, lineStyles.at(i).c_str()) << std::endl;
    }
    std::cout << "nFillStyles   = " << nFillStyles << std::endl;
    for (int i = 0; i<nFillStyles; ++i) {
        std::cout << Form("fillStyles[%d] = %s", i, fillStyles.at(i).c_str()) << std::endl;
    }
    std::cout << "nColors   = " << nColors << std::endl;
    for (int i = 0; i<nColors; ++i) {
        std::cout << Form("colors[%d] = %s", i, colors.at(i).c_str()) << std::endl;
    }
    std::cout << "nFillColors = " << nFillColors << std::endl;
    for (int i = 0; i<nFillColors; ++i) {
        std::cout << Form("fillColors[%d] = %s", i, fillColors.at(i).c_str()) << std::endl;
    }
    std::cout << "nLineColors = " << nLineColors << std::endl;
    for (int i = 0; i<nLineColors; ++i) {
        std::cout << Form("lineColors[%d] = %s", i, lineColors.at(i).c_str()) << std::endl;
    }
    std::cout << "lineWidth = " << lineWidth << std::endl;

    std::cout << "nLegendEntryLabels   = " << nLegendEntryLabels << std::endl;
    for (int i = 0; i<nLegendEntryLabels; ++i) {
        std::cout << Form("legendEntryLabels[%d] = %s", i, legendEntryLabels.at(i).c_str()) << std::endl;
    }
    if (nLegendEntryLabels > 0) {
        std::cout << "legendPosition   = " << legendPosition.c_str() << std::endl;
        if (legendPosition.size() == 0) std::cout<< "No position is provided, legend will not be drawn." <<std::endl;
        std::cout << "legendOffsetX    = " << legendOffsetX << std::endl;
        std::cout << "legendOffsetY    = " << legendOffsetY << std::endl;
        std::cout << "legendBorderSize = " << legendBorderSize << std::endl;
        std::cout << "legendWidth      = " << legendWidth << std::endl;
        std::cout << "legendHeight     = " << legendHeight << std::endl;
        std::cout << "legendTextSize   = " << legendTextSize << std::endl;
    }

    std::cout << "nTextLines   = " << nTextLines << std::endl;
    for (int i = 0; i<nTextLines; ++i) {
        std::cout << Form("textLines[%d] = %s", i, textLines.at(i).c_str()) << std::endl;
    }
    if (nTextLines > 0) {
        std::cout << "textFont = " << textFont << std::endl;
        std::cout << "textSize = " << textSize << std::endl;
        std::cout << "textPosition = " << textPosition << std::endl;
        std::cout << "textOffsetX  = " << textOffsetX << std::endl;
        std::cout << "textOffsetY  = " << textOffsetY << std::endl;
    }

    std::cout << "nTextsOverPad = " << nTextsOverPad << std::endl;
    for (int i = 0; i<nTextsOverPad; ++i) {
        std::cout << Form("textsOverPad[%d] = %s", i, textsOverPad.at(i).c_str()) << std::endl;
    }
    if (nTextsOverPad > 0) {
        std::cout << "nTextsOverPadAlignments = " << nTextsOverPadAlignments << std::endl;
        for (int i = 0; i<nTextsOverPadAlignments; ++i) {
            std::cout << Form("textsOverPadAlignments[%d] = %s", i, textsOverPadAlignments.at(i).c_str()) << std::endl;
        }
        std::cout << "textAbovePadFont = " << textAbovePadFont << std::endl;
        std::cout << "textAbovePadSize = " << textAbovePadSize << std::endl;
        std::cout << "textAbovePadOffsetX  = " << textAbovePadOffsetX << std::endl;
        std::cout << "textAbovePadOffsetY  = " << textAbovePadOffsetY << std::endl;
    }

    std::cout << "nTLines_horizontal = " << nTLines_horizontal << std::endl;
    for (int i = 0; i<nTLines_horizontal; ++i) {
        std::cout << Form("TLines_horizontal[%d] = %f", i, TLines_horizontal.at(i)) << std::endl;
    }
    if (nTLines_horizontal > 0) {
        std::cout << "nLineStyles_horizontal = " << nLineStyles_horizontal << std::endl;
        for (int i = 0; i<nLineStyles_horizontal; ++i) {
            std::cout << Form("lineStyles_horizontal[%d] = %s", i, lineStyles_horizontal.at(i).c_str()) << std::endl;
        }
    }
    std::cout << "nTLines_vertical = " << nTLines_vertical << std::endl;
    for (int i = 0; i<nTLines_vertical; ++i) {
        std::cout << Form("TLines_vertical[%d] = %f", i, TLines_vertical.at(i)) << std::endl;
    }
    if (nTLines_vertical > 0) {
        std::cout << "nLineStyles_vertical = " << nLineStyles_vertical << std::endl;
        for (int i = 0; i<nLineStyles_vertical; ++i) {
            std::cout << Form("lineStyles_vertical[%d] = %s", i, lineStyles_vertical.at(i).c_str()) << std::endl;
        }
    }

    std::cout << "windowWidth = " << windowWidth << std::endl;
    std::cout << "windowHeight = " << windowHeight << std::endl;
    std::cout << "leftMargin   = " << leftMargin << std::endl;
    std::cout << "rightMargin  = " << rightMargin << std::endl;
    std::cout << "bottomMargin = " << bottomMargin << std::endl;
    std::cout << "topMargin    = " << topMargin << std::endl;
    std::cout << "setLogx = " << setLogx << std::endl;
    std::cout << "setLogy = " << setLogy << std::endl;
    std::cout << "setLogz = " << setLogz << std::endl;

    // cut configuration

    // verbose about cut configuration
    std::cout<<"Cut Configuration :"<<std::endl;

    std::cout<<"Input handling :"<< std::endl;

    std::vector<std::string> inputFileArguments = InputConfigurationParser::ParseFileArgument(inputFile.Data());
    int nInputFileArguments = inputFileArguments.size();
    // if no mode is specified (which is what happens most of the time), then it is expected that nInputFileArguments = 1.
    std::cout<<"nInputFileArguments (number of input file arguments) = "<< nInputFileArguments << std::endl;
    for (int i = 0; i < nInputFileArguments; ++i) {
        std::cout << Form("inputFileArguments[%d] = %s", i, inputFileArguments.at(i).c_str()) << std::endl;
    }

    std::vector<std::vector<std::string>> inputFiles(nInputFileArguments);
    std::cout<<"#####"<< std::endl;
    for (int i = 0; i < nInputFileArguments; ++i) {

        if (nInputFileArguments > 1) {
            std::cout<<"###"<< std::endl;
            std::cout<<"inputFileArgument = " << inputFileArguments.at(i).c_str() << std::endl;
        }

        inputFiles[i] = InputConfigurationParser::ParseFiles(inputFileArguments.at(i));
        std::cout<<"input ROOT files : num = " << inputFiles[i].size() << std::endl;
        for (std::vector<std::string>::iterator it = inputFiles[i].begin() ; it != inputFiles[i].end(); ++it) {
            std::cout<<(*it).c_str()<< std::endl;
        }
    }
    std::cout<<"##### END #####"<< std::endl;

    // check consistency of the input file arguments with the mode
    if (mode == INPUT_MODE::k_noMode && nInputFileArguments > 1) {
        std::cout<<"no specific mode is chosen. more than one input samples are provided."<< std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }
    if (mode == INPUT_MODE::k_comparison && nInputFileArguments == 1) {
        std::cout<<"comparison mode is chosen. But only one input sample is provided."<< std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }

    if (nTrees == 1 && nFriendsIndividual > 0) {
        std::cout<<"nTrees = "<< nTrees <<", nFriendsIndividual = " << nFriendsIndividual << std::endl;
        std::cout<<"There is only one tree to be plotted, it does not make sense to use individual friend trees."<< std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }
    else if (nTrees > 1 && nFriendsIndividual > 0 && nTrees != nFriendsIndividual) {
        std::cout<<"nTrees = "<< nTrees <<", nFriendsIndividual = " << nFriendsIndividual << std::endl;
        std::cout<<"exiting"<< std::endl;
        return;
    }

    if (nSelectionSplitter == 1) {
        std::cout << "nSelectionSplitter = "<< nSelectionSplitter << std::endl;
        std::cout << "selectionSplitter has been set to have exactly one selection"<< std::endl;
        std::cout << "selectionSplitter is allowed to be either empty or to have more than one selections"<< std::endl;
        std::cout << "exiting"<< std::endl;
        return;
    }
    int nSplits = 1;
    if (nSelectionSplitter > 1)  nSplits = nSelectionSplitter;

    int nSelectionsTot = nSelections * nSplits;
    int nFormulasTot = nFormulas * nSplits;

    TH1::SetDefaultSumw2();
    int nHistos = nFormulasTot;
    if (nFormulas == 1 && nSelections > nFormulas) nHistos = nSelectionsTot;
    else if (nFormulas == 1 && nSelections == 1 && nTrees > nFormulas) nHistos = nTrees * nSplits;
    else if (nFormulas > 1 && nSelections > 1 && nFormulas != nSelections) {
        std::cout << "mismatch of number of formulas and number of selections"<< std::endl;
        std::cout << "nHistos     = "<< nHistos << std::endl;
        std::cout << "nSelections = "<< nSelections << std::endl;
        std::cout << "exiting " << std::endl;
        return;
    }
    else if (nFormulas > 1 && nTrees > 1 && nFormulas != nTrees) {
        std::cout << "mismatch of number of formulas and number of trees"<< std::endl;
        std::cout << "nHistos = "<< nHistos << std::endl;
        std::cout << "nTrees  = "<< nTrees << std::endl;
        std::cout << "exiting " << std::endl;
        return;
    }
    else if (nSelections > 1 && nTrees > 1 && nSelections != nTrees) {
        std::cout << "mismatch of number of selections and number of trees"<< std::endl;
        std::cout << "nHistos     = "<< nHistos << std::endl;
        std::cout << "nSelections = "<< nSelections << std::endl;
        std::cout << "nTrees      = "<< nTrees << std::endl;
        std::cout << "exiting " << std::endl;
        return;
    }
    TFile* output = TFile::Open(outputFile.Data(),"RECREATE");
    output->cd();

    int nHistosInput = nHistos/nSplits;     // number of histograms without considering selectionSplitter
    std::cout << "nHistos = " << nHistos << std::endl;
    TH2D* h[nHistos];
    for (int i=0; i<nHistos; ++i) {
        int nBinsx  = (int)TH2D_Bins_List[0].at(0);
        float xLow = TH2D_Bins_List[1].at(0);
        float xUp  = TH2D_Bins_List[2].at(0);
        int nBinsy  = (int)TH2D_Bins_List[3].at(0);
        float yLow = TH2D_Bins_List[4].at(0);
        float yUp  = TH2D_Bins_List[5].at(0);
        if (nTH2D_Bins_List == nHistosInput) {
            nBinsx = (int)TH2D_Bins_List[0].at(i%nTH2D_Bins_List);
            xLow  = TH2D_Bins_List[1].at(i%nTH2D_Bins_List);
            xUp   = TH2D_Bins_List[2].at(i%nTH2D_Bins_List);
            nBinsy = (int)TH2D_Bins_List[3].at(i%nTH2D_Bins_List);
            yLow  = TH2D_Bins_List[4].at(i%nTH2D_Bins_List);
            yUp   = TH2D_Bins_List[5].at(i%nTH2D_Bins_List);
        }
        std::string title = "";
        if (nTitles == 1)  {
            if (titles.at(0).compare(CONFIGPARSER::nullInput) != 0)  title = titles.at(0).c_str();
        }
        else if (nTitles == nHistosInput)  {
            if (titles.at(i%nTitles).compare(CONFIGPARSER::nullInput) != 0)  title = titles.at(i%nTitles).c_str();
        }
        else if (nTitles == nHistos)  {
            if (titles.at(i).compare(CONFIGPARSER::nullInput) != 0)  title = titles.at(i).c_str();
        }

        std::string titleX = "";
        if (nTitlesX == 1) titleX = titlesX.at(0).c_str();
        else if (nTitlesX == nHistosInput) titleX = titlesX.at(i%nTitlesX).c_str();
        else if (nTitlesX == nHistos)      titleX = titlesX.at(i).c_str();

        std::string titleY = "";
        if (nTitlesY == 1) titleY = titlesY.at(0).c_str();
        else if (nTitlesY == nHistosInput) titleY = titlesY.at(i%nTitlesY).c_str();
        else if (nTitlesY == nHistos)      titleY = titlesY.at(i).c_str();

        h[i] = new TH2D(Form("h2D_%d", i),Form("%s;%s;%s", title.c_str(), titleX.c_str(), titleY.c_str()), nBinsx, xLow, xUp, nBinsy, yLow, yUp);
    }

    // if no mode is specified (which is what happens most of the time), then it is expected that nInputFileArguments = 1.
    // so in that case : 1.) the "TTree*" objects below are effectively 1D, not 2D. 2.) the loops below have effective depth 1, not 2.
    TTree* trees[nTrees][nInputFileArguments];
    TTree* treeFriends[nFriends][nInputFileArguments];
    TTree* treeFriendsIndividual[nFriendsIndividual][nInputFileArguments];
    TTree* treeHiForestInfo[nInputFileArguments];

    Long64_t entries[nInputFileArguments];
    Long64_t entriesSelected[nHistos];
    std::fill_n(entriesSelected, nHistos, 0);

    int nFiles[nInputFileArguments];
    TFile* fileTmp = 0;

    std::cout << "initial reading to get the number of entries (if there is only one input file) and HiForest info" << std::endl;
    for (int iInFileArg = 0; iInFileArg < nInputFileArguments; ++iInFileArg) {

        nFiles[iInFileArg] = inputFiles[iInFileArg].size();
        if (nInputFileArguments > 1) {
            std::cout <<"iInFileArg = " << iInFileArg << " , "<< std::endl;
        }

        // read the first file only to get the HiForest info
        std::string inputPath = inputFiles[iInFileArg].at(0).c_str();
        fileTmp = new TFile(inputPath.c_str(), "READ");

        bool treeExists = true;
        if (nFiles[iInFileArg] == 1) {
            // read one tree only to get the number of entries
            trees[0][iInFileArg] = (TTree*)fileTmp->Get(treePaths.at(0).c_str());
            if (!trees[0][iInFileArg]) {
                std::cout << "tree is not found in the path : "<< treePaths.at(0).c_str() <<". skipping file." << std::endl;
                treeExists = false;
            }
            if (treeExists) {
                entries[iInFileArg] = trees[0][iInFileArg]->GetEntries();
                std::cout << "entries = " << entries[iInFileArg] << std::endl;
            }
        }

        if (treeExists) {
            treeHiForestInfo[0] = (TTree*)fileTmp->Get("HiForest/HiForestInfo");
            if (!treeHiForestInfo[0]) {
                std::cout << "HiForest/HiForestInfo tree is not found." << std::endl;
                treeExists = false;
            }
            if (treeExists) {
                HiForestInfoController hfic(treeHiForestInfo[0]);
                if (iInFileArg == 0)  std::cout<<"### HiForestInfo Tree ###"<< std::endl;
                else                  std::cout<<"### HiForestInfo Tree, input "<< iInFileArg+1 << " ###" << std::endl;
                hfic.printHiForestInfo();
                std::cout<<"###"<< std::endl;
            }
        }

        fileTmp->Close();
    }

    std::cout << "TTree::Draw()" <<std::endl;
    for (int iInFileArg = 0; iInFileArg < nInputFileArguments; ++iInFileArg) {

        if (nInputFileArguments > 1) {
            std::cout <<"iInFileArg = " << iInFileArg << std::endl;
        }

        entries[iInFileArg] = 0;
        for (int iFile = 0; iFile < nFiles[iInFileArg]; ++iFile) {

            std::string inputPath = inputFiles[iInFileArg].at(iFile).c_str();
            std::cout <<"iFile = " << iFile << " , " ;
            std::cout <<"reading input file : " << inputPath.c_str() << std::endl;
            fileTmp = new TFile(inputPath.c_str(), "READ");

            // check if the file is usable, if not skip the file.
            if (isGoodFile(fileTmp) != 0) {
                std::cout << "File is not good. skipping file." << std::endl;
                continue;
            }

            bool treeExists = true;
            for (int i=0; i<nTrees; ++i) {
                trees[i][iInFileArg] = (TTree*)fileTmp->Get(treePaths.at(i).c_str());
                if (!trees[i][iInFileArg]) {
                    std::cout << "tree is not found in the path : "<< treePaths.at(i).c_str() <<". skipping file." << std::endl;
                    treeExists = false;
                }
            }
            for (int i=0; i<nFriends; ++i) {
                treeFriends[i][iInFileArg] = (TTree*)fileTmp->Get(treeFriendsPath.at(i).c_str());
                if (!treeFriends[i][iInFileArg]) {
                    std::cout << "tree is not found in the path : "<< treeFriendsPath.at(i).c_str() <<". skipping file." << std::endl;
                    treeExists = false;
                }
            }
            if (!treeExists)  continue;

            // add friends
            for (int i=0; i<nTrees; ++i) {
                for (int j=0; j<nFriends; ++j) {
                    trees[i][iInFileArg]->AddFriend(treeFriends[j][iInFileArg], Form("t%d", j));
                }
            }
            for (int i=0; i < nFriendsIndividual; ++i) {
                if (treeFriendsPathIndividual.at(i).compare(CONFIGPARSER::nullInput) != 0) {
                    treeFriendsIndividual[i][iInFileArg] = (TTree*)fileTmp->Get(treeFriendsPathIndividual.at(i).c_str());
                }
            }
            if (nFriendsIndividual > 0) {
                for (int i=0; i<nTrees; ++i) {
                    if (treeFriendsPathIndividual.at(i).compare(CONFIGPARSER::nullInput) != 0) {
                        trees[i][0]->AddFriend(treeFriendsIndividual[i][0], Form("tSelf%d", i));
                    }
                }
            }

            Long64_t entriesTmp = trees[0][iInFileArg]->GetEntries();      // assume all the trees have same number of entries
            entries[iInFileArg] += entriesTmp;

            if (nInputFileArguments == 1)  {
                std::cout << "entries in File = " << entriesTmp << std::endl;
            }
            else {
                std::cout << Form("entries[%d] = ", iInFileArg) << entriesTmp << std::endl;
            }

            output->cd();
            for (int i=0; i<nHistos; ++i) {

                int treeIndex = 0;
                if (nHistosInput == nTrees)  treeIndex = i%nTrees;
                // std::cout << "treePath = " << treePaths.at(treeIndex).c_str() << ", ";

                int iInFileArg = 0;
                if (mode == INPUT_MODE::k_comparison) {
                    iInFileArg = i%nInputFileArguments;
                    std::cout << "iInFileArg = " << iInFileArg << ", ";
                }

                std::string formula = formulas.at(0).c_str();
                std::string selection = selections.at(0).c_str();
                std::string weight = weights.at(0).c_str();
                if (nHistosInput == nFormulas)  formula = formulas.at(i%nFormulas).c_str();
                if (nHistosInput == nSelections)  selection = selections.at(i%nSelections).c_str();
                if (nHistosInput == nWeights)  weight = weights.at(i%nWeights).c_str();

                std::string selectionSplit = "";
                if (nSelectionSplitter > 1)  selectionSplit = selectionSplitter.at(i/ (nHistos/nSelectionSplitter)).c_str();

                // std::cout << "drawing histogram i = " << i << ", ";

                TCut selectionFinal = selectionBase.c_str();
                selectionFinal = selectionFinal && selection.c_str();
                if (selectionSplit.size() > 0)  selectionFinal = selectionFinal && selectionSplit.c_str();
                Long64_t entriesSelectedTmp = trees[treeIndex][iInFileArg]->GetEntries(selectionFinal.GetTitle());
                // std::cout << "entriesSelected in file = " << entriesSelectedTmp << std::endl;
                entriesSelected[i] += entriesSelectedTmp;

                TCut weight_AND_selection = Form("(%s)*(%s)", weight.c_str(), selectionFinal.GetTitle());
                trees[treeIndex][iInFileArg]->Draw(Form("%s >>+ %s", formula.c_str(), h[i]->GetName()), weight_AND_selection.GetTitle(), "goff");
            }
            fileTmp->Close();
        }
    }
    std::cout << "TTree::Draw() ENDED" <<std::endl;
    for (int i = 0; i < nInputFileArguments; ++i) {

        if (nInputFileArguments == 1)  {
            std::cout << "entries = " << entries[0] << std::endl;
        }
        else {
            std::cout << Form("entries[%d] = ", i) << entries[i] << std::endl;
        }
    }
    std::cout << "### selected entries" << std::endl;
    for (int i = 0; i < nHistos; ++i) {

        std::cout << "TH1D i = " << i << ", ";
        int treeIndex = 0;
        if (nHistosInput == nTrees)  treeIndex = i%nTrees;
        std::cout << "treePath = " << treePaths.at(treeIndex).c_str() << ", ";

        std::cout << "entriesSelected = " << entriesSelected[i] << std::endl;
    }
    std::cout << "###" << std::endl;

    // print info about histograms
    for (int i=0; i<nHistos; ++i) {
        std::cout << "#####" << std::endl;
        std::cout << Form("h[%d]", i) << std::endl;
        std::string summary = summaryTH1(h[i]);
        std::cout << summary.c_str() << std::endl;
    }

    output->cd();

    TH2D* h_normInt[nHistos];
    TH2D* h_normEvents[nHistos];
    for (int i=0; i<nHistos; ++i) {
        h[i]->Write();

        h_normInt[i] = (TH2D*)h[i]->Clone(Form("%s_normInt", h[i]->GetName()));
        h_normInt[i]->Scale(1./h[i]->Integral());
        h_normInt[i]->Write();

        h_normEvents[i] = (TH2D*)h[i]->Clone(Form("%s_normEvents", h[i]->GetName()));
        h_normEvents[i]->Scale(1./entriesSelected[i]);
        h_normEvents[i]->Write();
    }
    // histograms are written. After this point changes to the histograms will not be reflected in the output ROOT file.

    // set the style of the histograms for canvases to be written
    for (int i=0; i<nHistos; ++i) {
        h[i]->SetTitleOffset(titleOffsetX,"X");
        h[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normInt[i]->SetTitleOffset(titleOffsetX,"X");
        h_normInt[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normEvents[i]->SetTitleOffset(titleOffsetX,"X");
        h_normEvents[i]->SetTitleOffset(titleOffsetY,"Y");

        // default marker style and color
        h[i]->SetMarkerStyle(kFullCircle);
        h[i]->SetMarkerColor(kBlack);
        h_normInt[i]->SetMarkerStyle(kFullCircle);
        h_normInt[i]->SetMarkerColor(kBlack);
        h_normEvents[i]->SetMarkerStyle(kFullCircle);
        h_normEvents[i]->SetMarkerColor(kBlack);

        // no stats box in the final plots
        h[i]->SetStats(false);
        h_normInt[i]->SetStats(false);
        h_normEvents[i]->SetStats(false);
    }

    // write canvases
    TCanvas* c;
    for (int i=0; i<nHistos; ++i) {
        c = new TCanvas(Form("cnv_%d",i),"",windowWidth,windowHeight);
        c->SetTitle(h[i]->GetTitle());
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();

        h[i]->SetTitleOffset(titleOffsetX,"X");
        h[i]->SetTitleOffset(titleOffsetY,"Y");
        h[i]->SetStats(false);
        h[i]->Draw("colz");
        c->Write();
        c->Close();         // do not use Delete() for TCanvas.

        // normalized to 1.
        c = new TCanvas(Form("cnv_%d_normInt",i),"",windowWidth,windowHeight);
        c->SetTitle(h_normInt[i]->GetTitle());
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();

        h_normInt[i]->SetTitleOffset(titleOffsetX,"X");
        h_normInt[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normInt[i]->SetStats(false);
        h_normInt[i]->Draw("colz");
        c->Write();
        c->Close();         // do not use Delete() for TCanvas.

        // normalized by number of events
        c = new TCanvas(Form("cnv_%d_normEvents",i),"",windowWidth,windowHeight);
        c->SetTitle(h_normEvents[i]->GetTitle());
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();

        h_normEvents[i]->SetTitleOffset(titleOffsetX,"X");
        h_normEvents[i]->SetTitleOffset(titleOffsetY,"Y");
        h_normEvents[i]->SetStats(false);
        h_normEvents[i]->Draw("colz");
        c->Write();
        c->Close();         // do not use Delete() for TCanvas.
    }
    // canvases are written.

    // set style of the histograms for the canvases to be saved as picture
    for(int i=0; i<nHistos; ++i) {
        std::string drawOption = "colz";
        if (nDrawOptions == 1) {
            if (drawOptions.at(0).compare(CONFIGPARSER::nullInput) != 0)  drawOption = drawOptions.at(0).c_str();
        }
        else if (nDrawOptions == nHistosInput) {
            if (drawOptions.at(i).compare(CONFIGPARSER::nullInput) != 0)  drawOption = drawOptions.at(i%nDrawOptions).c_str();
        }
        // https://root.cern.ch/doc/master/classTObject.html#abe2a97d15738d5de00cd228e0dc21e56
        // TObject::SetDrawOption() is not suitable for the approach here.

        int markerStyle = GRAPHICS::markerStyle;
        if (nMarkerStyles == 1) markerStyle = GraphicsConfigurationParser::ParseMarkerStyle(markerStyles.at(0));
        else if (nMarkerStyles == nHistosInput) markerStyle = GraphicsConfigurationParser::ParseMarkerStyle(markerStyles.at(i%nMarkerStyles));
        h[i]->SetMarkerStyle(markerStyle);
        h_normInt[i]->SetMarkerStyle(markerStyle);
        h_normEvents[i]->SetMarkerStyle(markerStyle);

        int lineStyle = GRAPHICS::lineStyle;
        if (nLineStyles == 1)  lineStyle = GraphicsConfigurationParser::ParseLineStyle(lineStyles.at(0));
        else if (nLineStyles == nHistosInput)  lineStyle = GraphicsConfigurationParser::ParseLineStyle(lineStyles.at(i%nLineStyles));
        h[i]->SetLineStyle(lineStyle);
        h_normInt[i]->SetLineStyle(lineStyle);
        h_normEvents[i]->SetLineStyle(lineStyle);

        int fillStyle = GRAPHICS::fillStyle;
        if (nFillStyles == 1)  fillStyle = GraphicsConfigurationParser::ParseLineStyle(fillStyles.at(0));
        else if (nFillStyles == nHistosInput)  fillStyle = GraphicsConfigurationParser::ParseLineStyle(fillStyles.at(i%nFillStyles));
        h[i]->SetFillStyle(fillStyle);
        h_normInt[i]->SetFillStyle(fillStyle);
        h_normEvents[i]->SetFillStyle(fillStyle);

        int color = GRAPHICS::colors[i];
        if (nColors == 1) color = GraphicsConfigurationParser::ParseColor(colors.at(0));
        else if (nColors == nHistosInput) color = GraphicsConfigurationParser::ParseColor(colors.at(i%nColors));
        h[i]->SetMarkerColor(color);
        h[i]->SetLineColor(color);
        h_normInt[i]->SetMarkerColor(color);
        h_normInt[i]->SetLineColor(color);
        h_normEvents[i]->SetMarkerColor(color);
        h_normEvents[i]->SetLineColor(color);

        int fillColor = -1;
        if (nFillColors == 1) fillColor = GraphicsConfigurationParser::ParseColor(fillColors.at(0));
        else if (nFillColors == nHistosInput) fillColor = GraphicsConfigurationParser::ParseColor(fillColors.at(i%nFillColors));
        if (fillColor != -1)
        {
            h[i]->SetFillColor(fillColor);
            h_normInt[i]->SetFillColor(fillColor);
            h_normEvents[i]->SetFillColor(fillColor);
        }

        int lineColor = -1;
        if (nLineColors == 1) lineColor = GraphicsConfigurationParser::ParseColor(lineColors.at(0));
        else if (nLineColors == nHistosInput) lineColor = GraphicsConfigurationParser::ParseColor(lineColors.at(i%nLineColors));
        if (nLineColors != -1)
        {
            h[i]->SetLineColor(lineColor);
            h_normInt[i]->SetLineColor(lineColor);
            h_normEvents[i]->SetLineColor(lineColor);
        }

        if(lineWidth != INPUT_DEFAULT::lineWidth) {
            if (drawOption.find("hist") != std::string::npos) {
                h[i]->SetLineWidth(lineWidth);
                h_normInt[i]->SetLineWidth(lineWidth);
                h_normEvents[i]->SetLineWidth(lineWidth);
            }
        }

        h[i]->SetMarkerSize(markerSize);
        h_normInt[i]->SetMarkerSize(markerSize);
        h_normEvents[i]->SetMarkerSize(markerSize);
    }

    TH1D* h_draw[nHistos];
    for (int i=0; i<nHistos; ++i) {
        if (drawNormalized == INPUT_TH1::k_normInt) {
            h_draw[i] = (TH1D*)h_normInt[i]->Clone(Form("h_%d_draw", i));
        }
        else if (drawNormalized == INPUT_TH1::k_normEvents) {
            h_draw[i] = (TH1D*)h_normEvents[i]->Clone(Form("h_%d_draw", i));
        }
        else {  // no normalization
            h_draw[i] = (TH1D*)h[i]->Clone(Form("h_%d_draw", i));
        }
    }

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

        c = new TCanvas(Form("cnv_drawSpectra2D_%d", i),"",windowWidth,windowHeight);
        setCanvasMargin(c, leftMargin, rightMargin, bottomMargin, topMargin);
        setCanvasFinal(c, setLogx, setLogy, setLogz);
        c->cd();
        TLegend* leg = new TLegend();

        std::string drawOption = "";
        if (nDrawOptions == 1)  drawOption = drawOptions.at(0).c_str();
        else if (nDrawOptions == nHistosInput) drawOption = drawOptions.at(i%nDrawOptions).c_str();

        h_draw[i]->Draw(drawOption.c_str());

        if (nLegendEntryLabels == nHistosInput) {
            std::string label = legendEntryLabels.at(i%nLegendEntryLabels).c_str();
            std::string legendOption = "lpf";
            if (drawOption.find("hist") != std::string::npos)  legendOption = "lf";
            if (label.compare(CONFIGPARSER::nullInput) != 0)  leg->AddEntry(h_draw[i], label.c_str(), legendOption.c_str());
        }

        if (legendTextSize != 0)  leg->SetTextSize(legendTextSize);
        leg->SetBorderSize(legendBorderSize);
        double height = calcTLegendHeight(leg);
        double width = calcTLegendWidth(leg);
        if (legendHeight != 0)  height = legendHeight;
        if (legendWidth != 0)  width = legendWidth;
        if (legendPosition.size() > 0) {    // draw the legend if really a position is provided.
            setLegendPosition(leg, legendPosition, c, height, width, legendOffsetX, legendOffsetY);
            leg->Draw();
        }

        // add Text
        TLatex* latex = 0;
        if (nTextLines > 0) {
            latex = new TLatex();
            latex->SetTextFont(textFont);
            latex->SetTextSize(textSize);
            setTextAlignment(latex, textPosition);
            std::vector<std::pair<float,float>> textCoordinates = calcTextCoordinates(textLines, textPosition, c, textOffsetX, textOffsetY);
            for (int i = 0; i<nTextLines; ++i) {
                float x = textCoordinates.at(i).first;
                float y = textCoordinates.at(i).second;
                latex->DrawLatexNDC(x, y, textLines.at(i).c_str());
            }
        }

        // add Text above the pad
        TLatex* latexOverPad = 0;
        if (nTextsOverPad > 0) {
            latexOverPad = new TLatex();
            latexOverPad->SetTextFont(textAbovePadFont);
            latexOverPad->SetTextSize(textAbovePadSize);
            for (int i = 0; i < nTextsOverPad; ++i) {
                int textOverPadAlignment = GRAPHICS::textAlign;
                if (nTextsOverPadAlignments == 1) textOverPadAlignment = GraphicsConfigurationParser::ParseTextAlign(textsOverPadAlignments.at(0));
                else if (nTextsOverPadAlignments == nTextsOverPad) textOverPadAlignment = GraphicsConfigurationParser::ParseTextAlign(textsOverPadAlignments.at(i));

                latexOverPad->SetTextAlign(textOverPadAlignment);
                setTextAbovePad(latexOverPad, c, textAbovePadOffsetX, textAbovePadOffsetY);

                latexOverPad->DrawLatexNDC(latexOverPad->GetX(), latexOverPad->GetY(), textsOverPad.at(i).c_str());
            }
        }

        // add TLine
        TLine* line_horizontal[nTLines_horizontal];
        for (int iLine = 0; iLine<nTLines_horizontal; ++iLine) {
            // draw horizontal line
            double xmin = h[i]->GetXaxis()->GetBinLowEdge(h[i]->GetXaxis()->GetFirst());
            double xmax = h[i]->GetXaxis()->GetBinLowEdge(h[i]->GetXaxis()->GetLast()+1);

            int lineStyle_horizontal = GRAPHICS::lineStyle_horizontal;
            if (nLineStyles_horizontal == 1)
                lineStyle_horizontal = GraphicsConfigurationParser::ParseLineStyle(lineStyles_horizontal.at(0));
            else if (nLineStyles_horizontal == nTLines_horizontal)
                lineStyle_horizontal = GraphicsConfigurationParser::ParseLineStyle(lineStyles_horizontal.at(iLine));

            line_horizontal[iLine] = new TLine(xmin, TLines_horizontal.at(iLine), xmax, TLines_horizontal.at(iLine));
            line_horizontal[iLine]->SetLineStyle(lineStyle_horizontal);   // https://root.cern.ch/doc/master/TAttLine_8h.html#a7092c0c4616367016b70d54e5c680a69
            line_horizontal[iLine]->Draw();
        }
        // add TLine
        TLine* line_vertical[nTLines_vertical];
        for (int iLine = 0; iLine<nTLines_vertical; ++iLine) {
            // draw vertical line
            double ymin = h[i]->GetYaxis()->GetBinLowEdge(h[i]->GetYaxis()->GetFirst());
            double ymax = h[i]->GetYaxis()->GetBinLowEdge(h[i]->GetYaxis()->GetLast()+1);

            int lineStyle_vertical = GRAPHICS::lineStyle_vertical;
            if (nLineStyles_vertical == 1)
                lineStyle_vertical = GraphicsConfigurationParser::ParseLineStyle(lineStyles_vertical.at(0));
            else if (nLineStyles_vertical == nTLines_vertical)
                lineStyle_vertical = GraphicsConfigurationParser::ParseLineStyle(lineStyles_vertical.at(iLine));

            line_vertical[iLine] = new TLine(TLines_vertical.at(iLine), ymin, TLines_vertical.at(iLine), ymax);
            line_vertical[iLine]->SetLineStyle(lineStyle_vertical);   // https://root.cern.ch/doc/master/TAttLine_8h.html#a7092c0c4616367016b70d54e5c680a69
            line_vertical[iLine]->Draw();
        }
        c->Write();

        // save histograms as picture if a figure name is provided.
        // for now 2D canvases are not drawn on top, they are drawn separately.
        if (!outputFigureName.EqualTo("")) {
            std::string tmpOutputFigureName = outputFigureName.Data();
            if (tmpOutputFigureName.find(".") != std::string::npos) {     // file extension is specified
                if (nHistos > 1) {
                    // modify outputFile name
                    // if i=1, then "output.ext" becomes "output_2.ext"
                    size_t pos = tmpOutputFigureName.find_last_of(".");
                    tmpOutputFigureName.replace(pos,1, Form("_%d.", i+1));
                }
                c->SaveAs(tmpOutputFigureName.c_str());
            }
            else {  // file extension is NOT specified
                if (nHistos > 1) {
                    // modify outputFile name
                    // if i=1, then "output" becomes "output_2"
                    tmpOutputFigureName = Form("%s_%d", tmpOutputFigureName.c_str(), i+1);
                }

                c->SaveAs(Form("%s.C", tmpOutputFigureName.c_str()));
                c->SaveAs(Form("%s.png", tmpOutputFigureName.c_str()));
                c->SaveAs(Form("%s.pdf", tmpOutputFigureName.c_str()));
            }
        }

        leg->Delete();
        c->Close();
    }

    output->Close();
}
Exemple #27
0
void Muti_Plot(std::string mu_title,std::string selection,  const char **lineKind_Arr, TCut selectionC , std::string Var ,  const int ngr, const int nVarBins, double * VarBins_array , double **yArr2, double **yErrArr2)
{ 

	char filename[]="JetESR_status.txt";
	fstream myfile;
	myfile.open (filename,ios::out|ios::app);

	double VarBinsCenter[nVarBins];
	double VarBinsErr[nVarBins];
	for (int ibin=0; ibin<nVarBins; ibin++)
	{
		VarBinsCenter[ibin]= (VarBins_array[ibin] + VarBins_array[ibin+1]) /2;
		VarBinsErr[ibin]=(VarBins_array[ibin+1]- VarBins_array[ibin])/2;
	}

	cout<<"lineKind_Arr 1 = "<<lineKind_Arr[0]<<" ,lineKind_Arr2 = "<<lineKind_Arr[1]<<endl;
	cout<<"mu_title = "<<mu_title<<" selectionC = "<< selectionC<<endl;

	Can_result[counter1] = new TCanvas(Form("Can_result_%i",counter1));
	mutiGR[counter1] = new TMultiGraph("name",Form("%s",mu_title.c_str()));
	TGraphErrors *gr_mean[ngr];
	legend[counter1] = new TLegend(0.65,0.7,0.85,0.85);

	for(int igr=0; igr<ngr; igr++)
	{
		gr_mean[igr] = new TGraphErrors(nVarBins, VarBinsCenter, yArr2[igr], VarBinsErr , yErrArr2[igr]);
		gr_mean[igr]->SetTitle(Form("some title_%i", igr));
		gr_mean[igr]->SetFillStyle(0);
		gr_mean[igr]->SetMarkerStyle(1);
		gr_mean[igr]->SetLineColor(igr+1);	
		gr_mean[igr]->SetMarkerColor(igr+1);
		mutiGR[counter1]->Add(gr_mean[igr]);
		legend[counter1]->AddEntry( gr_mean[igr] ,lineKind_Arr[igr],"l"); 

	}


	mutiGR[counter1]->Draw("AP");
	mutiGR[counter1]->GetXaxis()->SetTitle(Form("%s",Var.c_str())); // must after draw to create a vitual histogram like object to set title.
	 if (mu_title.compare("JES") == 0)
	mutiGR[counter1]->GetYaxis()->SetTitle("#mu_{Reco./Gen.} akPu4PF");
   if (mu_title.compare("JER") == 0)
  mutiGR[counter1]->GetYaxis()->SetTitle("#sigma_{Reco./Gen.} akPu4PF");	
	mutiGR[counter1]->Draw("AP"); // draw again to let all the settting on it.
	legend[counter1]->SetBorderSize(0);
	legend[counter1]->Draw();

  TLegend *legend1 = new TLegend(0.3,0.7,0.6,0.85);
  legend1->AddEntry((TObject*)0,selection.c_str(),"");
  legend1->AddEntry((TObject*)0,"jtpt>80","");
  legend1->SetBorderSize(0);
  legend1->Draw();

/*	TLatex *tex = new TLatex(0.35,0.8,"#bf{#color[2]{|#eta_{jet}|<2.0}}");
	tex->SetNDC();
	tex->SetTextFont(43);
	tex->SetTextSize(26);
	tex->SetLineWidth(2);
	tex->Draw();
*/

	Can_result[counter1]->SaveAs(Form("./Plots/result_%s_%s_%s.pdf",mu_title.c_str(),selectionC.GetTitle() , Var.c_str())); 
	counter1++;
	cout<<"finish mutigraph"<<endl;
}
Exemple #28
0
void FitSignals(TTree * treeB, TCut cut, Int_t max){
  AliSignalProcesor proc;
  TF1 * f1 = proc.GetAsymGauss();
  TTreeSRedirector cstream("FitSignal.root");
  TFile *f = cstream.GetFile();

  char lname[100];
  sprintf(lname,"Fit%s", cut.GetTitle());
  TEventList *list = new TEventList(lname,lname);
  sprintf(lname,">>Fit%s", cut.GetTitle());
  treeB->Draw(lname,cut);
  treeB->SetEventList(list);
  Int_t nFits=0;
  for (Int_t ievent=0; ievent<list->GetN(); ievent++){
    if (nFits>max) break;
    if (nFits%50==0) printf("%d\n",nFits);
    char ename[100];
    sprintf(ename,"Fit%d", ievent);
    Double_t nsample = treeB->Draw("Graph.fY-Mean09:Graph.fX","","",1,ievent);
    Double_t * signal  = treeB->GetV1();
    Double_t * time  = treeB->GetV2();
    Double_t maxpos =0;
    Double_t max = 0;
    for (Int_t ipos = 0; ipos<nsample; ipos++){
      if (signal[ipos]>max){
	max    = signal[ipos];
	maxpos = ipos;
      }
    }

    Int_t first = TMath::Max(maxpos-10,0.);
    Int_t last  = TMath::Min(maxpos+60, nsample);
    //
    f->cd();
    TH1F his(ename,ename,last-first,first,last);
    for (Int_t ipos=0; ipos<last-first; ipos++){
      his.SetBinContent(ipos+1,signal[ipos+first]);
    }
    treeB->Draw("Sector:Row:Pad","","",1,ievent);
    Double_t sector = treeB->GetV1()[0];
    Double_t row    = treeB->GetV2()[0];
    Double_t pad    = treeB->GetV3()[0];
    //    TGraph  graph(last-first,&time[first],&signal[first]);
    f1->SetParameters(0.75*max,maxpos,1.1,0.8,0.25,0.2);
    //    TH1F * his = (TH1F*)graph.GetHistogram();
    his.Fit(f1,"q");
    his.Write(ename);
    gPad->Clear();
    his.Draw();
    gPad->Update();
    Double_t params[6];
    for (Int_t ipar=0; ipar<6; ipar++) params[ipar] = f1->GetParameters()[ipar];
    Double_t chi2 = TFitter::GetFitter()->Chisquare(6,params);
    TMatrixD cov(6,6);
    cov.SetMatrixArray(TFitter::GetFitter()->GetCovarianceMatrix());
    //
    // tail cancellation
    //
    Double_t x0[1000];
    Double_t x1[1000];
    Double_t x2[1000];
    for (Int_t ipos=0; ipos<last-first; ipos++){
      x0[ipos] = signal[ipos+first];
    }
    proc.TailCancelationALTRO1(x0,x1,0.85*0.339,0.09,last-first);
    proc.TailCancelationALTRO1(x1,x2,0.85,0.789,last-first);
    //
    sprintf(ename,"Cancel1_%d", ievent);
    TH1F his1(ename,ename,last-first,first,last);
    for (Int_t ipos=0; ipos<last-first; ipos++){
      his1.SetBinContent(ipos+1,x1[ipos]);
    }
    his1.Write(ename);
    sprintf(ename,"Cancel2_%d", ievent);
    TH1F his2(ename,ename,last-first,first,last);
    for (Int_t ipos=0; ipos<last-first; ipos++){
      his2.SetBinContent(ipos+1,x1[ipos]);
    }
    f1->SetParameters(0.75*max,maxpos,1.1,0.8,0.25,0.2);
    his2.Fit(f1,"q");
    his2.Write(ename);
    Double_t params2[6];
    for (Int_t ipar=0; ipar<6; ipar++) params2[ipar] = f1->GetParameters()[ipar];
    Double_t chi22 = TFitter::GetFitter()->Chisquare(6,params2);    
    TMatrixD cov2(6,6);
    cov2.SetMatrixArray(TFitter::GetFitter()->GetCovarianceMatrix());

    TGraph gr0(last-first, &time[first],x0);
    TGraph gr1(last-first, &time[first],x1);
    TGraph gr2(last-first, &time[first],x2);
    //
    cstream<<"Fit"<<
      "Sector="<<sector<<
      "Row="<<row<<
      "Pad="<<pad<<
      "First="<<first<<
      "Max="<<max<<
      "MaxPos="<<maxpos<<
      "chi2="<<chi2<<
      "chi22="<<chi22<<
      "Cov="<<&cov<<
      "Cov2="<<&cov2<<
      "gr0.="<<&gr0<<
      "gr1.="<<&gr1<<
      "gr2.="<<&gr2<<
      "p0="<<params[0]<<
      "p1="<<params[1]<<
      "p2="<<params[2]<<
      "p3="<<params[3]<<
      "p4="<<params[4]<<
      "p5="<<params[5]<<
      "p02="<<params2[0]<<
      "p12="<<params2[1]<<
      "p22="<<params2[2]<<
      "p32="<<params2[3]<<
      "p42="<<params2[4]<<
      "p52="<<params2[5]<<
      "\n";
    //    delete his;
    nFits++;
  }

}
void tnpScale_IDISO_el( bool printplot = false ) {

  //----------------------------------------
  // Files
  //----------------------------------------

  char* version = (char*) "V00-00-00";

  TChain *chmc   = new TChain("leptons");
  TChain *chdata = new TChain("leptons");

  char* suffix = "";
  //char* suffix = "_2jets";

  chmc->  Add(Form("smurf/%s/dymm_test%s.root"              , version , suffix));  
  chdata->Add(Form("smurf/%s/data_SingleEl_2012A%s.root"    , version , suffix));


  //----------------------------------------
  // bins 
  //----------------------------------------

  //float ptbin[] = {10., 15., 20., 30., 40., 50., 7000.};
  float ptbin[] = { 30. , 40. , 50. , 60. , 80.0 , 100.0 , 120.0 , 150.0 , 7000.};
  float etabin[] = {0, 0.8, 1.5, 2.1};
  int nptbin=8;
  int netabin=3;

  //
  // histogram
  //
  //deno
  TH2F *hmcid_deno 	= new TH2F("hmcid_deno", "hmcid_deno", nptbin, ptbin, netabin, etabin);
  TH2F *hmciso_deno 	= new TH2F("hmciso_deno", "hmciso_deno", nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_deno 	= new TH2F("hdataid_deno", "hdataid_deno", nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso_deno	= new TH2F("hdataiso_deno", "hdataiso_deno", nptbin, ptbin, netabin, etabin);
  hmcid_deno->Sumw2();
  hmciso_deno->Sumw2();
  hdataid_deno->Sumw2();
  hdataiso_deno->Sumw2();
  //num
  TH2F *hmcid_num 	= new TH2F("hmcid_num", "hmcid_num", nptbin, ptbin, netabin, etabin);
  TH2F *hmciso_num 	= new TH2F("hmciso_num", "hmciso_num", nptbin, ptbin, netabin, etabin);
  TH2F *hdataid_num 	= new TH2F("hdataid_num", "hdataid_num", nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso_num 	= new TH2F("hdataiso_num", "hdataiso_num", nptbin, ptbin, netabin, etabin);
  hmcid_num->Sumw2();
  hmciso_num->Sumw2();
  hdataid_num->Sumw2();
  hdataiso_num->Sumw2();
  // eff
  TH2F *hmcid 	= new TH2F("hmcid", "hmcid", nptbin, ptbin, netabin, etabin);
  TH2F *hmciso 	= new TH2F("hmciso", "hmciso", nptbin, ptbin, netabin, etabin);
  TH2F *hdataid 	= new TH2F("hdataid", "hdataid", nptbin, ptbin, netabin, etabin);
  TH2F *hdataiso 	= new TH2F("hdataiso", "hdataiso", nptbin, ptbin, netabin, etabin);
  hmcid->Sumw2();
  hmciso->Sumw2();
  hdataid->Sumw2();
  hdataiso->Sumw2();
  // SF
  TH2F *hsfid 	= new TH2F("hsfid", "hsfid", nptbin, ptbin, netabin, etabin);
  TH2F *hsfiso 	= new TH2F("hsfiso", "hsfiso", nptbin, ptbin, netabin, etabin);
  hsfid->Sumw2();
  hsfiso->Sumw2();

  TCut elid  	= "(leptonSelection&8)==8";            // ele id 
  TCut eliso 	= "(leptonSelection&16)==16";          // ele iso

  TCut zmass("abs(tagAndProbeMass-91)<15");
  TCut os("qProbe*qTag<0");
  TCut eltnp("(eventSelection&1)==1");
  //TCut eltnptrig("HLT_TNP_tag > 0 || HLT_TNPel_tag > 0");
  TCut eltnptrig("HLT_Ele27_WP80_tag > 0");
  TCut tag_eta21("abs(tag->eta())<2.1");
  TCut tag_pt30("tag->pt()>30.0");

  TCut met30("met<30");
  TCut nbl0("nbl==0");

  TCut njets0("njets==0");
  TCut njets1("njets==1");
  TCut njets2("njets==2");
  TCut njets3("njets==3");
  TCut njets4("njets>=4");

  //TCut tnpcut   = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && tag->pt()>30.0"; 

  TCut tnpcut;
  tnpcut += zmass;
  tnpcut += os;
  tnpcut += eltnp;
  tnpcut += eltnptrig;
  tnpcut += tag_eta21;
  tnpcut += tag_pt30;

  tnpcut += met30;
  tnpcut += nbl0;

  //tnpcut += njets2;

  cout << "Selection  : " << tnpcut.GetTitle()          << endl;
  cout << "Ndata      : " << chdata->GetEntries(tnpcut) << endl;
  cout << "NMC        : " << chmc->GetEntries(tnpcut)   << endl;

  chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+eliso,	      	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 	tnpcut+eliso+elid,	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+elid,	      	"goff");
  chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+elid+eliso,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+eliso,		"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 	tnpcut+eliso+elid,	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+elid,	       	"goff");
  chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+elid+eliso,	"goff");

  // get efficiencies 
  hmcid->Divide(hmcid_num,hmcid_deno,1,1,"B");
  hmciso->Divide(hmciso_num,hmciso_deno,1,1,"B");
  hdataid->Divide(hdataid_num,hdataid_deno,1,1,"B");
  hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1,"B");

  // hmcid->Divide(hmcid_num,hmcid_deno,1,1);
  // hmciso->Divide(hmciso_num,hmciso_deno,1,1);
  // hdataid->Divide(hdataid_num,hdataid_deno,1,1);
  // hdataiso->Divide(hdataiso_num,hdataiso_deno,1,1);
	
  // get scale factors
  hsfid->Divide(hdataid, hmcid, 1, 1);
  hsfiso->Divide(hdataiso, hmciso, 1, 1);

  // Draw histograms	
  //hmcid->Draw("text");

  // print table
  cout << " ------ MC ID ----- " << endl;
  printline(hmcid);
  cout << " ------ MC ISO ----- " << endl;
  printline(hmciso);
  cout << " ------ DATA ID ----- " << endl;
  printline(hdataid);
  cout << " ------ DATA ISO ----- " << endl;
  printline(hdataiso);
  cout << " ------ Scale Factor ID ----- " << endl;
  printline(hsfid);
  cout << " ------ Scale Factor ISO ----- " << endl;
  printline(hsfiso);

  TCanvas *c_iso[10];
  TCanvas *c_id[10];

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

    TCut mysel;
    if     ( i==0 ) mysel = TCut(tnpcut+njets0);
    else if( i==1 ) mysel = TCut(tnpcut+njets1);
    else if( i==2 ) mysel = TCut(tnpcut+njets2);
    else if( i==3 ) mysel = TCut(tnpcut+njets3);
    else if( i==4 ) mysel = TCut(tnpcut+njets4);

    c_iso[i] = new TCanvas(Form("c_iso_%i",i),Form("c_iso_%i",i),600,600);
    c_iso[i]->cd();
    printHisto( c_iso[i] , chdata , chmc , TCut(eliso) , TCut(mysel+elid) , "probe.pt()" , 10 , 0.0 , 300.0 , "lepton p_{T} [GeV]" , "iso efficiency" );
    if( printplot ) c_iso[i]->Print(Form("plots/iso_el_njets%i.pdf",i));

    c_id[i] = new TCanvas(Form("c_id_%i",i),Form("c_id_%i",i),600,600);
    c_id[i]->cd();
    printHisto( c_id[i] , chdata , chmc , TCut(elid) , TCut(mysel+eliso) , "probe.pt()" , 10 , 0.0 , 300.0 , "lepton p_{T} [GeV]" , "ID efficiency" );
    if( printplot ) c_id[i]->Print(Form("plots/id_el_njets%i.pdf",i));

  }

  /*

  //---------------------------
  // tag cuts
  //---------------------------

  TCut zmass("abs(tagAndProbeMass-91)<15");
  TCut eltnp("(eventSelection&1)==1");
  TCut mutnp("(eventSelection&2)==2");
  TCut os("qProbe*qTag<0");
  TCut tag_eta21("abs(tag->eta())<2.1");
  TCut tag_eta25("abs(tag->eta())<2.5");
  TCut njets1("njets>=1");
  TCut njets2("njets>=2");
  TCut njets3("njets>=3");
  TCut njets4("njets>=4");
  TCut tag_pt30("tag->pt()>30.0");
  TCut met30("met<30");
  TCut met20("met<20");
  TCut nbm0("nbm==0");
  TCut nbl0("nbl==0");
  TCut mt30("mt<30");
  TCut eltnptrig("HLT_TNP_tag > 0 || HLT_TNPel_tag > 0");
  TCut mutnptrig("HLT_IsoMu30_eta2p1_tag > 0");

  //---------------------------
  // tag cuts
  //---------------------------

  TCut mufo 	= "(leptonSelection&32768)==32768";    // mu fo
  TCut elfo     = "(leptonSelection&4)==4";            // ele fo 
  TCut elid  	= "(leptonSelection&8)==8";            // ele id 
  TCut eliso 	= "(leptonSelection&16)==16";          // ele iso
  TCut probept  = "probe->pt()>30";                    // probe pt
  TCut drprobe  = "drprobe<0.05";                      // dR(probe,pfcandidate)

  TCut eltnpcut;
  eltnpcut += zmass;
  eltnpcut += os;
  eltnpcut += eltnp;
  eltnpcut += tag_eta25;
  //eltnpcut += njets2;
  eltnpcut += tag_pt30;
  eltnpcut += eltnptrig;
  eltnpcut += met30;
  // eltnpcut += mt30;
  eltnpcut += nbl0;
  
  eltnpcut += elid;
  eltnpcut += probept;
  eltnpcut += drprobe;

  TCut mutnpcut;
  mutnpcut += zmass;
  mutnpcut += os;
  mutnpcut += mutnp;
  mutnpcut += tag_eta21;
  //mutnpcut += njets2;
  mutnpcut += tag_pt30;
  mutnpcut += mutnptrig;
  mutnpcut += met30;
  // mutnpcut += mt30;
  mutnpcut += nbl0;

  mutnpcut += muid;
  mutnpcut += probept;
  mutnpcut += drprobe;


  //eltnpcut += njets2;
  //eltnpcut += njets3;
  //eltnpcut += nbm0;
  //eltnpcut += mt30;
  //eltnpcut += met20;

  //TCut eltnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&1)==1 && qProbe*qTag<0 && abs(tag->eta())<2.5 && njets>=4 && tag->pt()>30.0 && met<30.0 && nbm==0 && mt<30"; 
  //TCut mutnpcut 	 = "abs(tagAndProbeMass-91)<15 && (eventSelection&2)==2 && HLT_IsoMu30_eta2p1_tag>0 && qProbe*qTag<0 && abs(tag->eta())<2.1 && njets>=4 && tag->pt()>30.0"; 

  TCut vtxweight = "vtxweight";

  cout << "Electrons:" << endl;
  cout << "Total MC yields 	: " << chmc->GetEntries(eltnpcut) << endl;
  cout << "Total DATA yields 	: " << chdata->GetEntries(eltnpcut) << endl;

  cout << "Muons:" << endl;
  cout << "Total MC yields 	: " << chmc->GetEntries(mutnpcut) << endl;
  cout << "Total DATA yields 	: " << chdata->GetEntries(mutnpcut) << endl;


  //TCut njets    = "njets>=2";
  TCut tkisoold = "tkisoold/probe->pt()>0.1";
  TCut tkisonew = "tkisonew/probe->pt()>0.1";

  //-----------------------------------------
  // check nvtx data vs. MC
  //-----------------------------------------

  TH1F *hnvtx_mc   = new TH1F("hnvtx_mc"  ,"",30,0,30);
  TH1F *hnvtx_data = new TH1F("hnvtx_data","",30,0,30);

  hnvtx_mc->Sumw2();
  hnvtx_data->Sumw2();

  chdata->Draw("nvtx>>hnvtx_data",(eltnpcut||mutnpcut));
  chmc->Draw("nvtx>>hnvtx_mc",(eltnpcut||mutnpcut)*vtxweight);

  TCanvas *c1 = new TCanvas();
  c1->cd();
  
  hnvtx_mc->SetLineColor(2);
  hnvtx_mc->SetMarkerColor(2);
  hnvtx_data->SetLineColor(4);
  hnvtx_data->SetMarkerColor(4);
  
  hnvtx_data->GetXaxis()->SetTitle("N_{VTX}");
  hnvtx_data->DrawNormalized();
  hnvtx_mc->DrawNormalized("same");

  TLegend *leg = new TLegend(0.6,0.6,0.8,0.8);
  leg->AddEntry(hnvtx_data,"data","lp");
  leg->AddEntry(hnvtx_mc,"MC","lp");
  leg->SetFillColor(0);
  leg->SetBorderSize(0);
  leg->Draw();

  if( printplot ) c1->Print("plots/nvtx.pdf");



  // Fill histograms
  //
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmcid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chmc->Draw("abs(probe->eta()):probe->pt()>>hmciso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_deno", 	tnpcut+"&&"+eliso,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataid_num", 		tnpcut+"&&"+eliso+"&&"+elid,	"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_deno", 	tnpcut+"&&"+elid,				"goff");
  // chdata->Draw("abs(probe->eta()):probe->pt()>>hdataiso_num", 	tnpcut+"&&"+elid+"&&"+eliso,	"goff");

  */
	
}
Exemple #30
0
  bool isEmpty () const {return from == 0 && to == 0 && strlen(cut.GetTitle()) == 0
			   && name.Length() == 0 && caption.Length() == 0;}