///////////////////////
// Get the number of entries in the event list
SEXP nEntriesEventList(SEXP eventList)
{
  TEventList* el = checkForEventListWrapper(eventList);
  
  SEXP n = NEW_INTEGER(1);
  INTEGER(n)[0] = el->GetN();
  
  return n;
}
void NCIdeogram::addTree(TTree *tree, const char *mu, const char *sigma)
{
	TLeaf *leafMu = tree->FindLeaf(mu);
	TLeaf *leafSigma = tree->FindLeaf(sigma);
	TEventList *elist = tree->GetEventList();
	Long64_t j,ix,nbr;
	
	nbr = elist ? elist->GetN() : tree->GetEntries();
	for (j = 0; j < nbr; j++) {
		ix = elist ? elist->GetEntry(j) : j;
		tree->GetEntry(ix);
		addPoint(leafMu->GetValue(), leafSigma->GetValue());
	}
} // addTree()
Example #3
0
void treeTest(  const TString fList = "temp.list",
                const TString fOutName = "fOut.root",
                Long64_t nEvents = 9999
                ) 
{

	gROOT->LoadMacro("$STAR/StRoot/StMuDSTMaker/COMMON/macros/loadSharedLibraries.C");
    gROOT->LoadMacro("makeEventList.C");
	loadSharedLibraries();

    TFile* fOut = new TFile(fOutName.Data(),"RECREATE");

    TH1D* hZdc = new TH1D("hZdc","hZdc", 50, 0.5, 5000.5);

	//----------------- Read data using StMuDstMaker ---------------//
	StChain* muChain = new StChain("StChain");
	StMuDstMaker* muMaker = new StMuDstMaker(0,0,"",fList.Data(),"st:MuDst.root", 100, "MuDst");

    muChain->Init();
    Float_t zdcCut = 1623;

    TEventList* eventList = makeEventList(muMaker->chain(), zdcCut);
    muMaker->SetEventList(eventList);
    Long64_t nList = eventList->GetN();
    if(nList < nEvents) {nEvents = nList;}

    for(Int_t i = 0; i <= (nEvents-1); i++)
    {
        muChain->Make();
        Float_t zdcWest = muMaker->muDst()->event()->zdcTriggerDetector().adc(0);
        Float_t zdcEast = muMaker->muDst()->event()->zdcTriggerDetector().adc(4);

        hZdc->Fill(zdcWest);
        hZdc->Fill(zdcEast);


    }

    muChain->Finish();
    fOut->Write();
    fOut->Close();

    delete muChain;
    delete eventList;

}
//////////////////////////
// Return all of the events as a big vector
SEXP getEntries(SEXP eventList)
{
  TEventList* el = checkForEventListWrapper(eventList);
  
  unsigned int l = el->GetN();
  
  SEXP e;
  PROTECT( e = NEW_INTEGER(l) );
  
  for ( unsigned int i = 0; i < l; ++i) {
    INTEGER(e)[i] = el->GetEntry(i);
  }
  
  UNPROTECT(1);
  
  return e;
}
Example #5
0
void listMatchedEvents(std::string fullPath, bool matchesonly = false)
{
    // Essentially a sort of diff for reco and gen tree
    // May get slow for large trees as the search for the matching entry in the second tree
    // traverses the whole tree. This is because for merged trees the order is not guaranteed
    const int fVerbose(1);
    // Open file
    TFile *f = TFile::Open(fullPath.c_str());
    if (f==0)
    {
	cout << "File " << fullPath << " not found -- exiting" << endl;
	return;
    }
    if(fVerbose>0)
	cout << "Succesfully opened file " << fullPath << endl;
    // Get TTree with GenEvents
    TTree* tgen = (TTree*) f->Get("genevents");
    if(fVerbose>0) cout << "Got TTree with " << tgen->GetEntries() << " entries" << endl;
    // Do a cut, if needed
    //tgen->Draw(">>lst","ptmu1>3&&ptmu2>3&&TMath::Abs(etamu1)<2.5&&TMath::Abs(etamu2)<2.5");
    tgen->Draw(">>lst","");
    TEventList *lst;
    lst = (TEventList*)gDirectory->Get("lst");
    tgen->SetEventList(lst);
    if(fVerbose>0) cout << " After cuts: " << lst->GetN() << " entries" << endl;

    // Get TTree with iRecoEvents
    TTree* treco = (TTree*) f->Get("events");
    if(fVerbose>0) cout << "Got TTree with " << treco->GetEntries() << " entries" << endl;

    // set branch addresses
    int genrun, genls, genevt;
    tgen->SetBranchAddress("run",&genrun);
    tgen->SetBranchAddress("LS",&genls);
    tgen->SetBranchAddress("event",&genevt);

    int recorun, recols, recoevt;
    treco->SetBranchAddress("run",&recorun);
    treco->SetBranchAddress("LS",&recols);
    treco->SetBranchAddress("event",&recoevt);

    int mcmatch;
    treco->SetBranchAddress("isMCmatch",&mcmatch);

    double ptmu1, ptmu2, ptpr, ptpi;
    tgen->SetBranchAddress("ptmu1",&ptmu1);
    tgen->SetBranchAddress("ptmu2",&ptmu2);
    tgen->SetBranchAddress("ptpr",&ptpr);
    tgen->SetBranchAddress("ptpi",&ptpi);
    double etamu1, etamu2, etapr, etapi;
    tgen->SetBranchAddress("etamu1",&etamu1);
    tgen->SetBranchAddress("etamu2",&etamu2);
    tgen->SetBranchAddress("etapr",&etapr);
    tgen->SetBranchAddress("etapi",&etapi);
    double phimu1, phimu2, phipr, phipi;
    tgen->SetBranchAddress("phimu1",&phimu1);
    tgen->SetBranchAddress("phimu2",&phimu2);
    tgen->SetBranchAddress("phipr",&phipr);
    tgen->SetBranchAddress("phipi",&phipi);

    cout << "#      run         LS      event     genidx    recoidx" << endl;
    cout << "---------- ---------- ---------- ---------- ----------" << endl;

    TLorentzVector tlvmu1, tlvmu2, tlvpr, tlvpi;
    tmph1 = new TH1F ("tmph1","tmphisto",20,3.096,3.098);
    tmph2 = new TH1F ("tmph2","tmphisto",20,1.112,1.120);
    tmph3 = new TH1F ("tmph3","tmphisto",20,5.61,5.64);
    tmph4 = new TH2F ("tmph4","tmphisto",20,0,5,20,-2,8);

    // outer loop on gen events
    for (int i=0; i!=lst->GetN(); i++)
    {
	tgen->GetEntry(lst->GetEntry(i));
	tlvmu1.SetPtEtaPhiM(ptmu1,etamu1,phimu1,0.105658367);
	tlvmu2.SetPtEtaPhiM(ptmu2,etamu2,phimu2,0.105658367);
	tlvpr.SetPtEtaPhiM( ptpr, etapr, phipr ,0.938272013);
	tlvpi.SetPtEtaPhiM( ptpi, etapi, phipi ,0.13957018);
	tmph1->Fill((tlvmu1+tlvmu2).M());
	tmph2->Fill((tlvpr+tlvpi).M());
	tmph3->Fill((tlvmu1+tlvmu2+tlvpr+tlvpi).M());
	tmph4->Fill((tlvpr+tlvpi).P(),tlvpr.P()-tlvpi.P());
	//cout << (tlvmu1+tlvmu2).M() << " " << (tlvpr+tlvpi).M() << " " << (tlvmu1+tlvmu2+tlvpr+tlvpi).M() << endl;
	if (!matchesonly)
	    cout << setw(10) << genrun << " " << setw(10) << genls << " " << setw(10) << genevt << " " << setw(10) << lst->GetEntry(i) << " ";
	// inner loop on reco events
	int nfound(0);
	for (int j=0; j!=treco->GetEntries(); j++)
	{
	    treco->GetEntry(j);
	    if(genrun==recorun && genls==recols && genevt==recoevt)
	    {
		nfound++;
		if (matchesonly && nfound==1)
		    cout << setw(10) << genrun << " " << setw(10) << genls << " " << setw(10) << genevt << " " << setw(10) << lst->GetEntry(i) << " ";
		if(nfound>1) cout << "                                 " << setw(10) << lst->GetEntry(i) << " ";
		cout << setw(10) << j << " match: " << mcmatch << endl;
	    }
	}
	if (!matchesonly && nfound==0) cout << "         -" << endl;
    }
    c2 = new TCanvas();
    c2->Divide(2,2);
    c2->cd(1);
    tmph1->Draw();
    c2->cd(2);
    tmph2->Draw();
    c2->cd(3);
    tmph3->Draw();
    c2->cd(4);
    tmph4->Draw();
}
Example #6
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++;
  }

}
Example #7
0
void RAA_HFVsValidation_MC(char *algo = "Vs", char *jet_type = "PF"){


  TStopwatch timer;
  timer.Start();
  
  TH1::SetDefaultSumw2();
  TH2::SetDefaultSumw2();

  gStyle->SetOptStat(0);

  cout<<"Running for Algorithm "<<algo<<" "<<jet_type<<endl;
 
  bool printDebug = true;
  TDatime date;

  const int nbins_pthat = 9;
  Double_t boundaries_pthat[nbins_pthat+1];
  char *fileName_pthat[nbins_pthat+1];
  Double_t xsection[nbins_pthat+1];
  Double_t entries[nbins_pthat]; 
  //there are two ways in which we can select the no of events we use to scale - it has to be between the pthat range. 
  //first file name - partial 50K statistics, second one is full statistics sample. 
  //similarly the entries number is for the small statistics. 
  
  // refer this twiki for the data and MC files: http://twiki.cern.ch/twiki/bin/viewauth/CMS/HiForestPA2014#PYTHIA_HYDJET_embedded_sample

  boundaries_pthat[0]=15;
  fileName_pthat[0] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat15_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[0] = "/export/d00/scratch/dav2105/badjets/bad15.root";
  xsection[0]= 2.034e-01;
  //entries[0] = ;//total - 48588
  
  boundaries_pthat[1]=30;
  fileName_pthat[1] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat30_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[1] = "/export/d00/scratch/dav2105/badjets/bad30.root";
  xsection[1]= 1.075e-02;
  // entries[1] = ;//total - 48428
  
  boundaries_pthat[2]=50;
  fileName_pthat[2] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat50_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[2] = "/export/d00/scratch/dav2105/badjets/bad50.root";
  xsection[2]= 1.025e-03;
  // entries[2] = ;//total - 50000
  
  boundaries_pthat[3]=80;
  fileName_pthat[3] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat80_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[3] = "/export/d00/scratch/dav2105/badjets/bad80.root";
  xsection[3]= 9.865e-05;
  // entries[3] = ;//total - 49500
  
  boundaries_pthat[4]=120;
  fileName_pthat[4] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat120_Track9_Jet30_matchEqR_merged_forest_0.root";  
  //fileName_pthat[4] = "/export/d00/scratch/dav2105/badjets/bad120.root";
  xsection[4]= 1.129e-05;
  // entries[4] = ;//total - 49500

  boundaries_pthat[5]=170;
  fileName_pthat[5] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat170_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[5] = "/export/d00/scratch/dav2105/badjets/bad120.root";
  xsection[5]= 1.465e-06;
  // entries[5] = ;//total - 49444

  boundaries_pthat[6]=220;
  fileName_pthat[6] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat220_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[6] = "/export/d00/scratch/dav2105/badjets/bad220.root";
  xsection[6]= 2.837e-07;
  // entries[6] = ;//total - 49460

  boundaries_pthat[7]=280;
  fileName_pthat[7] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat280_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[7] = "/export/d00/scratch/dav2105/badjets/bad280.root";
  xsection[7]= 5.323e-08;
  // entries[7] = ;//total - 49541

  boundaries_pthat[8]=370;
  fileName_pthat[8] = "/mnt/hadoop/cms/store/user/dgulhan/PYTHIA_HYDJET_Track9_Jet30_Pyquen_DiJet_TuneZ2_Unquenched_Hydjet1p8_2760GeV_merged/HiForest_PYTHIA_HYDJET_pthat370_Track9_Jet30_matchEqR_merged_forest_0.root";
  //fileName_pthat[8] = "/export/d00/scratch/dav2105/badjets/bad370.root";
  xsection[8]= 5.934e-09;
  // entries[8] = ;//total - 19031

  boundaries_pthat[9] = 2000;
  xsection[9] = 0.0;

  // Vertex & centrality reweighting for PbPb
  TF1 *fVz;
  fVz = new TF1("fVz","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x");
  fVz->SetParameters(9.86748e-01, -8.91367e-03, 5.35416e-04, 2.67665e-06, -2.01867e-06);

  //get the centrality weight from the root file created in the plotting macro. 
  TFile *fcentin = TFile::Open("/net/hisrv0001/home/rkunnawa/WORK/RAA/CMSSW_5_3_20/src/Output/PbPb_DataMC_cent_ratio_20141117.root");
  TH1F *hCentWeight = (TH1F*)fcentin->Get("hCentRatio");


  TH2F *hSumpTvsHF[15];
  TH2F *hSumpTvsHF_cent[nbins_cent+1];
  TH2F *hSumpTvshiBin[15];
  TH2F *hSumpTvshiBin_cent[nbins_cent+1];
  TH2F *hNJetsvsSumpT[nbins_cent+1];
  TH2F *hNJetsvsSumpT_noHF[nbins_cent+1];
  TH2F *hNJetsvsSumpT_HF[nbins_cent+1];
  TH1F *hSumpT[nbins_cent+1];
  TH1F *hPsi[5][15][nbins_cent+1];
  //TH2F *hPsi_2d[5][15][nbins_cent];

  TH2F *hPsivsHF[5][15];
  TH2F *hPsivsHF_cent[5][nbins_cent+1];
  TH2F *hvnvsHF[5][15];
  TH2F *hvnvscent[5][nbins_cent+1];

  // UseFull histograms: Event Plane from HF for the official versus HF/Vs algorithm calculation of the Event Plane.
  // first [3] array elements - Psi_2, Psi_3, Psi_4  only in the HF for tonight. 
  // [3] - total, p - positive and n - negative in eta; based on what we have from the https://github.com/CmsHI/cmssw/blob/forest_CMSSW_5_3_20/RecoHI/HiEvtPlaneAlgos/interface/HiEvtPlaneList.h#L31 
  TH1F *hEP_HF_Official[3][3][nbins_cent+1];
  TH1F *hEP_HF_Vs[3][3][nbins_cent+1];
  TH2F *hEP_HF[3][3][nbins_cent+1];
  TH1F *hAngle_2_HF_Vs[nbins_cent+1];
  TH1F *hAngle_3_HF_Vs[nbins_cent+1];
  TH1F *hAngle_4_HF_Vs[nbins_cent+1];
  TH1F *hAngle_2_HF_Official[nbins_cent+1];
  TH1F *hAngle_3_HF_Official[nbins_cent+1];
  TH1F *hAngle_4_HF_Official[nbins_cent+1];
  TH1F *hMagnitude_2_HF_Vs[nbins_cent+1];
  TH1F *hMagnitude_3_HF_Vs[nbins_cent+1];
  TH1F *hMagnitude_4_HF_Vs[nbins_cent+1];
  TH2F *hSub_vs_SumpT[nbins_cent+1];
  TH2F *hVsAngle_EP[3][nbins_cent+1];

  for(int i = 0;i<nbins_cent+1;i++){
    
    for(int z = 0;z<3;z++){
      for(int x = 0;x<3;x++){
	hEP_HF_Official[z][x][i] = new TH1F(Form("hEP_HF_Official_Psi%d_%d_cent%d",z,x,i),"",630,-3.15,3.15);
	hEP_HF_Vs[z][x][i] = new TH1F(Form("hEP_HF_Vs_Psi%d_%d_cent%d",z,x,i),"",630,-3.15,3.15);
	hEP_HF[z][x][i] = new TH2F(Form("hEP_HF_Psi%d_%d_cent%d",z,x,i),"",630,-3.15,3.15,630,-3.15,3.15);
      }
    }

    hSumpTvsHF_cent[i] = new TH2F(Form("hSumpT_vsHF_cent%d",i),"",5000,0,100000,5000,0,100000);
    hSumpTvshiBin_cent[i] = new TH2F(Form("hSumpT_vshiBin_cent%d",i),"",5000,0,100000,200,0,200);
    hNJetsvsSumpT[i] = new TH2F(Form("hNJetsvsSumpT_cent%d",i),"",50,0,50,5000,0,100000);
    hNJetsvsSumpT_noHF[i] = new TH2F(Form("hNJetsvsSumpT_noHF_cent%d",i),"",50,0,50,5000,0,100000);
    hNJetsvsSumpT_HF[i] = new TH2F(Form("hNJetsvsSumpT_HF_cent%d",i),"",50,0,50,5000,0,100000);
    hAngle_2_HF_Vs[i] = new TH1F(Form("hAngle_2_HF_Vs_cent%d",i),"",30,-3.15,+3.15);
    hAngle_3_HF_Vs[i] = new TH1F(Form("hAngle_3_HF_Vs_cent%d",i),"",30,-3.15,+3.15);
    hAngle_4_HF_Vs[i] = new TH1F(Form("hAngle_4_HF_Vs_cent%d",i),"",30,-3.15,+3.15);
    hAngle_2_HF_Official[i] = new TH1F(Form("hAngle_2_HF_Official_cent%d",i),"",60,-3.15,+3.15);
    hAngle_3_HF_Official[i] = new TH1F(Form("hAngle_3_HF_Official_cent%d",i),"",60,-3.15,+3.15);
    hAngle_4_HF_Official[i] = new TH1F(Form("hAngle_4_HF_Official_cent%d",i),"",60,-3.15,+3.15);
    hSumpT[i] = new TH1F(Form("hSumpT_cent%d",i),"",5000,0,100000);
    hMagnitude_2_HF_Vs[i] = new TH1F(Form("hMagnitude_2_HF_Vs_cent%d",i),"",1000,0,1);
    hMagnitude_3_HF_Vs[i] = new TH1F(Form("hMagnitude_3_HF_Vs_cent%d",i),"",1000,0,1);
    hMagnitude_4_HF_Vs[i] = new TH1F(Form("hMagnitude_4_HF_Vs_cent%d",i),"",1000,0,1);
    hSub_vs_SumpT[i] = new TH2F(Form("hSub_vs_SumpT_cent%d",i),"",1200,0,12000,1200,0,12000);
    hVsAngle_EP[0][i] = new TH2F(Form("hVsAngle_EP_2_cent%d",i),"",60,-3.15,+3.15,60,-3.15,+3.15);
    hVsAngle_EP[1][i] = new TH2F(Form("hVsAngle_EP_3_cent%d",i),"",60,-3.15,+3.15,60,-3.15,+3.15);
    hVsAngle_EP[2][i] = new TH2F(Form("hVsAngle_EP_4_cent%d",i),"",60,-3.15,+3.15,60,-3.15,+3.15);

    /*
    for(int b = 0;b<5;b++){

      hPsivsHF_cent[b][i] = new TH2F(Form("hPsi%d_cent%d",b,i),"",630,-3.15,+3.15,5000,0,100000);
      hvnvsHF[b][i] = new TH2F(Form("hvn%d_HF_cent%d",b,i),"",100,0,1,5000,0,100000);
      //hvnvscent[b][i] = new TH2F
      for(int a = 0;a<15;a++){

	//hPsi[b][a][i] = new TH1F(Form("hPsi_n%d_eta%d_cent%d",b,a,i),"",630,-3.15,3.15);
	
      }
      
    }
    */
  }
  
  /*  
  // declare the histograms in loops:
  for(int a = 0;a<15;a++){
    
    hSumpTvsHF[a] = new TH2F(Form("hSumpT_eta%d_vsHF",a),"",5000,0,100000,5000,0,100000);
    hSumpTvshiBin[a] = new TH2F(Form("hSumpT_eta%d_vshiBin",a),"",5000,0,100000,200,0,200);
    
    for(int b = 0;b<5;b++){
      
      hPsivsHF[b][a] = new TH2F(Form("hPsi%d_etabin%d_HF",b,a),"",630,-3.15,+3.15,5000,0,100000);
      hvnvsHF[b][a] = new TH2F(Form("hvn%d_etabin%d_HF",b,a),"",100,0,1,5000,0,100000);
      
    }// no of flow components
    
  }// eta bin
  */
  TH1F *hPtHat[no_radius];
  TH1F *hPtHatRaw[no_radius];
  // Setup jet data branches - this will be 2D with [radius][pthat-file], but the histogram here is just 1D with [radius]
  JetData *data[no_radius][nbins_pthat]; 
  for(int k = 0;k<no_radius;k++){
    hPtHatRaw[k] = new TH1F(Form("hPtHatRaw_R%d",list_radius[k]),"",nbins_pthat,boundaries_pthat);
    hPtHat[k] = new TH1F(Form("hPtHat_R%d",list_radius[k]),"",nbins_pthat,boundaries_pthat);
    if(printDebug)cout<<"Radius = "<<list_radius[k]<<endl;
    if(printDebug)cout<<"reading all the pbpb mc files"<<endl;
    for (int h=0;h<nbins_pthat;h++) {
      //cout<<Form("ak%s%dJetAnalyzer/t",algo,list_radius[k])<<endl;
      data[k][h] = new JetData(fileName_pthat[h],Form("ak%s%d%sJetAnalyzer/t",algo,list_radius[k],jet_type),Form("ak%s%d%sJetAnalyzer/t",algo,list_radius[k],jet_type),0,1);
      //cout<<"A"<<endl;
      TH1F *hPtHatTmp = new TH1F("hPtHatTmp","",nbins_pthat,boundaries_pthat);
      //cout<<"B"<<endl;
      data[k][h]->tJet->Project("hPtHatTmp","pthat");
      //cout<<"C"<<endl;
      hPtHatRaw[k]->Add(hPtHatTmp);
      //cout<<"D"<<endl;
      delete hPtHatTmp;
    }// pthat loop
  }
  
  
  for(int k = 0;k<no_radius;k++){
    if(printDebug)cout<<"Filling MC for radius = "<<list_radius[k]<<endl;
    // fill PbPb MC 
    if(printDebug)cout<<"Filling PbPb MC"<<endl;
    
    for (int h=0;h<nbins_pthat;h++) {
      if (xsection[h]==0) continue;
      if(printDebug)cout <<"Loading pthat"<<boundaries_pthat[h]<<" sample, cross section = "<<xsection[h]<< Form(" pthat>%.0f&&pthat<%.0f",boundaries_pthat[h],boundaries_pthat[h+1])<<endl;
      
      //TCut pthatcut = Form("pthat>%d && pthat<%d",boundaries_pthat[h],boundaries_pthat[h+1]);
      //double fentries_test = data[k][h]->tJet->GetEntries(pthatcut);
      //cout<<"fentries_test = "<<fentries_test<<endl;
      
      //from Pawan's code: /net/hisrv0001/home/pawan/Validation/CMSSW_7_1_1/src/combinePtHatBins/pbpbJEC2014/condor/CondorPbPbCalJec.C
      TEventList *el = new TEventList("el","el");
      //double pthat_event = data[k][h]->pthat;
      //double pthat_lower = boundaries_pthat[h];
      double pthat_upper = boundaries_pthat[h+1];
      stringstream selection; selection<<"pthat<"<<pthat_upper;
      
      data[k][h]->tJet->Draw(">>el",selection.str().c_str());
      double fentries = el->GetN();
      if(printDebug)cout<<"tree entries: "<<data[k][h]->tJet->GetEntries()<<" elist: "<<fentries<<endl;
      delete el;
      int test_counter = 0; 
      
      for (Long64_t jentry=0; jentry<data[k][h]->tJet->GetEntries();jentry++) {
	//for (Long64_t jentry=0; jentry<10;jentry++) {
	
        //cout<<"hi"<<endl;
        data[k][h]->tEvt->GetEntry(jentry);
        data[k][h]->tJet->GetEntry(jentry);
        data[k][h]->tSkim->GetEntry(jentry);
        	
        int pthatBin = hPtHat[k]->FindBin(data[k][h]->pthat);
	
	double scale = (double)(xsection[pthatBin-1]-xsection[pthatBin])/fentries;
	
	if(!data[k][h]->pcollisionEventSelection) continue;
        int cBin = findBin(data[k][h]->bin);
        //int cBin = nbins_cent-1;
        double weight_cent=1;
        double weight_pt=1;
        double weight_vz=1;
	Float_t cent = cBin;
	
        weight_cent = hCentWeight->GetBinContent(hCentWeight->FindBin(data[k][h]->bin));
	if(fabs(data[k][h]->vz)>15) continue;
	
        weight_vz = fVz->Eval(data[k][h]->vz);
	
        if(scale*weight_cent*weight_vz <=0 ) {
	  cout<<"RED FLAG RED FLAG RED FLAG"<<endl;
	  continue;
	}
	
	int jetCounter = 0;//counts jets which are going to be used in the supernova cut rejection. 
	
	for(int j = 0;j<nbins_eta;j++){
	  
	  for(int g = 0;g<data[k][h]->njets;g++){
	    
	    if(data[k][h]->jteta[g] >= boundaries_eta[j][0] && data[k][h]->jteta[g] < boundaries_eta[j][1]){
	      //cout<<"jtpt = "<<data[k][h]->jtpt[g]<<endl;
	      if(data[k][h]->jtpt[g]>=50) jetCounter++;
	      
	    }// eta selection loop
	    
	  }//jet loop
	  
	}//eta bins loop

	//constructing the x-,y- and x+,y+ based on the following equation: 
	// x- = sumpt[0]*vn[2][0]*cos(2*vpsi[2][0]) y- = sumpt[0]*vn[2][0]*sin(2*vpsi[2][0])
	Float_t Vs_2_x_minus = data[k][h]->sumpT[0]*data[k][h]->v_n[2][0]*TMath::Cos(2*data[k][h]->psi_n[2][0]);
	Float_t Vs_2_x_plus = data[k][h]->sumpT[14]*data[k][h]->v_n[2][14]*TMath::Cos(2*data[k][h]->psi_n[2][14]);
	Float_t Vs_2_y_minus = data[k][h]->sumpT[0]*data[k][h]->v_n[2][0]*TMath::Sin(2*data[k][h]->psi_n[2][0]);
	Float_t Vs_2_y_plus = data[k][h]->sumpT[14]*data[k][h]->v_n[2][14]*TMath::Sin(2*data[k][h]->psi_n[2][14]);
	Float_t Vs_2_x = Vs_2_x_minus + Vs_2_x_plus;
	Float_t Vs_2_y = Vs_2_y_minus + Vs_2_y_plus;
	Float_t Vs_2_angle = TMath::ATan2(Vs_2_y,Vs_2_x);
	hAngle_2_HF_Vs[cBin]->Fill(Vs_2_angle);
	hAngle_2_HF_Vs[nbins_cent]->Fill(Vs_2_angle);
	//cout<<"Vs_2_angle = "<<Vs_2_angle<<endl;

	Float_t Vs_3_x_minus = data[k][h]->sumpT[0]*data[k][h]->v_n[3][0]*TMath::Cos(3*data[k][h]->psi_n[3][0]);
	Float_t Vs_3_x_plus = data[k][h]->sumpT[14]*data[k][h]->v_n[3][14]*TMath::Cos(3*data[k][h]->psi_n[3][14]);
	Float_t Vs_3_y_minus = data[k][h]->sumpT[0]*data[k][h]->v_n[3][0]*TMath::Sin(3*data[k][h]->psi_n[3][0]);
	Float_t Vs_3_y_plus = data[k][h]->sumpT[14]*data[k][h]->v_n[3][14]*TMath::Sin(3*data[k][h]->psi_n[3][14]);
	Float_t Vs_3_x = Vs_3_x_minus + Vs_3_x_plus;
	Float_t Vs_3_y = Vs_3_y_minus + Vs_3_y_plus;
	Float_t Vs_3_angle = TMath::ATan2(Vs_3_y,Vs_3_x);
	hAngle_3_HF_Vs[cBin]->Fill(Vs_3_angle);
	hAngle_3_HF_Vs[nbins_cent]->Fill(Vs_3_angle);
	//cout<<"Vs_3_angle = "<<Vs_3_angle<<endl;

	Float_t Vs_4_x_minus = data[k][h]->sumpT[0]*data[k][h]->v_n[4][0]*TMath::Cos(4*data[k][h]->psi_n[4][0]);
	Float_t Vs_4_x_plus = data[k][h]->sumpT[14]*data[k][h]->v_n[4][14]*TMath::Cos(4*data[k][h]->psi_n[4][14]);
	Float_t Vs_4_y_minus = data[k][h]->sumpT[0]*data[k][h]->v_n[4][0]*TMath::Sin(4*data[k][h]->psi_n[4][0]);
	Float_t Vs_4_y_plus = data[k][h]->sumpT[14]*data[k][h]->v_n[4][14]*TMath::Sin(4*data[k][h]->psi_n[4][14]);
	Float_t Vs_4_x = Vs_4_x_minus + Vs_4_x_plus;
	Float_t Vs_4_y = Vs_4_y_minus + Vs_4_y_plus;
	Float_t Vs_4_angle = TMath::ATan2(Vs_4_y,Vs_4_x);
	hAngle_4_HF_Vs[cBin]->Fill(Vs_4_angle);
	hAngle_4_HF_Vs[nbins_cent]->Fill(Vs_4_angle);
      	//cout<<"Vs_4_angle = "<<Vs_4_angle<<endl;

	//lets get the maginitude of the x,y here: 
	Float_t Vs_Mag_2 = TMath::Sqrt(Vs_2_x*Vs_2_x + Vs_2_y*Vs_2_y);
	Float_t Vs_Mag_3 = TMath::Sqrt(Vs_3_x*Vs_3_x + Vs_3_y*Vs_3_y);
	Float_t Vs_Mag_4 = TMath::Sqrt(Vs_4_x*Vs_4_x + Vs_4_y*Vs_4_y);
	// need to calculate the Total per event (pfPt - pfVsPt) versus sumpT[0]+sumpT[14];
	Float_t pfPt_Tot = 0;
	Float_t pfVsPt_Tot = 0;
	for(int i = 0;i<data[k][h]->nPFpart;i++){
	  pfPt_Tot += data[k][h]->pfPt[i];
	  pfVsPt_Tot += data[k][h]->pfVsPt[i];
	}
	Float_t sumpT_HF = data[k][h]->sumpT[0] + data[k][h]->sumpT[14];

	hMagnitude_2_HF_Vs[cBin]->Fill(Vs_Mag_2/sumpT_HF);
	hMagnitude_2_HF_Vs[nbins_cent]->Fill(Vs_Mag_2/sumpT_HF);
	hMagnitude_3_HF_Vs[cBin]->Fill(Vs_Mag_3/sumpT_HF);
	hMagnitude_3_HF_Vs[nbins_cent]->Fill(Vs_Mag_3/sumpT_HF);
	hMagnitude_4_HF_Vs[cBin]->Fill(Vs_Mag_4/sumpT_HF);
	hMagnitude_4_HF_Vs[nbins_cent]->Fill(Vs_Mag_4/sumpT_HF);
	//Float_t sub_ratio = (Float_t)(pfPt_Tot-pfVsPt_Tot)/sumpT_HF;
	hSub_vs_SumpT[cBin]->Fill(sumpT_HF,pfPt_Tot-pfVsPt_Tot);
	hSub_vs_SumpT[nbins_cent]->Fill(sumpT_HF,pfPt_Tot-pfVsPt_Tot);

	hVsAngle_EP[0][cBin]->Fill(Vs_2_angle,2*data[k][h]->hiEvtPlanes[21]);
	hVsAngle_EP[1][cBin]->Fill(Vs_3_angle,3*data[k][h]->hiEvtPlanes[24]);
	hVsAngle_EP[2][cBin]->Fill(Vs_4_angle,4*data[k][h]->hiEvtPlanes[27]);

	hVsAngle_EP[0][nbins_cent]->Fill(Vs_2_angle,2*data[k][h]->hiEvtPlanes[21]);
	hVsAngle_EP[1][nbins_cent]->Fill(Vs_3_angle,3*data[k][h]->hiEvtPlanes[24]);
	hVsAngle_EP[2][nbins_cent]->Fill(Vs_4_angle,4*data[k][h]->hiEvtPlanes[27]);

	//getting the event plane information for the Official and Vs calculations. 
	/*
	hEP_HF_Official[0][0][cBin]->Fill(data[k][h]->hiEvtPlanes[21],scale*weight_vz*weight_cent);
	hEP_HF_Official[0][1][cBin]->Fill(data[k][h]->hiEvtPlanes[22],scale*weight_vz*weight_cent);
	hEP_HF_Official[0][2][cBin]->Fill(data[k][h]->hiEvtPlanes[23],scale*weight_vz*weight_cent);

	hEP_HF_Official[1][0][cBin]->Fill(data[k][h]->hiEvtPlanes[24],scale*weight_vz*weight_cent);
	hEP_HF_Official[1][1][cBin]->Fill(data[k][h]->hiEvtPlanes[25],scale*weight_vz*weight_cent);
	hEP_HF_Official[1][2][cBin]->Fill(data[k][h]->hiEvtPlanes[26],scale*weight_vz*weight_cent);

	hEP_HF_Official[2][0][cBin]->Fill(data[k][h]->hiEvtPlanes[27],scale*weight_vz*weight_cent);
	hEP_HF_Official[2][1][cBin]->Fill(data[k][h]->hiEvtPlanes[28],scale*weight_vz*weight_cent);
	hEP_HF_Official[2][2][cBin]->Fill(data[k][h]->hiEvtPlanes[29],scale*weight_vz*weight_cent);

	hEP_HF_Vs[0][0][cBin]->Fill(data[k][h]->psi_n[2][0],scale*weight_vz*weight_cent);
	hEP_HF_Vs[0][0][cBin]->Fill(data[k][h]->psi_n[2][14],scale*weight_vz*weight_cent);
	hEP_HF_Vs[0][1][cBin]->Fill(data[k][h]->psi_n[2][0],scale*weight_vz*weight_cent);
	hEP_HF_Vs[0][2][cBin]->Fill(data[k][h]->psi_n[2][14],scale*weight_vz*weight_cent);

	hEP_HF_Vs[1][0][cBin]->Fill(data[k][h]->psi_n[3][0],scale*weight_vz*weight_cent);
	hEP_HF_Vs[1][0][cBin]->Fill(data[k][h]->psi_n[3][14],scale*weight_vz*weight_cent);
	hEP_HF_Vs[1][1][cBin]->Fill(data[k][h]->psi_n[3][0],scale*weight_vz*weight_cent);
	hEP_HF_Vs[1][2][cBin]->Fill(data[k][h]->psi_n[3][14],scale*weight_vz*weight_cent);

	hEP_HF_Vs[2][0][cBin]->Fill(data[k][h]->psi_n[4][0],scale*weight_vz*weight_cent);
	hEP_HF_Vs[2][0][cBin]->Fill(data[k][h]->psi_n[4][14],scale*weight_vz*weight_cent);
	hEP_HF_Vs[2][1][cBin]->Fill(data[k][h]->psi_n[4][0],scale*weight_vz*weight_cent);
	hEP_HF_Vs[2][2][cBin]->Fill(data[k][h]->psi_n[4][14],scale*weight_vz*weight_cent);
	
	hEP_HF[0][0][cBin]->Fill(data[k][h]->hiEvtPlanes[21],data[k][h]->psi_n[2][0],scale*weight_vz*weight_cent);
	hEP_HF[0][0][cBin]->Fill(data[k][h]->hiEvtPlanes[21],data[k][h]->psi_n[2][14],scale*weight_vz*weight_cent);
	hEP_HF[0][1][cBin]->Fill(data[k][h]->hiEvtPlanes[22],data[k][h]->psi_n[2][0],scale*weight_vz*weight_cent);
	hEP_HF[0][2][cBin]->Fill(data[k][h]->hiEvtPlanes[23],data[k][h]->psi_n[2][14],scale*weight_vz*weight_cent);

	hEP_HF[1][0][cBin]->Fill(data[k][h]->hiEvtPlanes[24],data[k][h]->psi_n[3][0],scale*weight_vz*weight_cent);
	hEP_HF[1][0][cBin]->Fill(data[k][h]->hiEvtPlanes[24],data[k][h]->psi_n[3][14],scale*weight_vz*weight_cent);
	hEP_HF[1][1][cBin]->Fill(data[k][h]->hiEvtPlanes[25],data[k][h]->psi_n[3][0],scale*weight_vz*weight_cent);
	hEP_HF[1][2][cBin]->Fill(data[k][h]->hiEvtPlanes[26],data[k][h]->psi_n[3][14],scale*weight_vz*weight_cent);

	hEP_HF[2][0][cBin]->Fill(data[k][h]->hiEvtPlanes[27],data[k][h]->psi_n[4][0],scale*weight_vz*weight_cent);
	hEP_HF[2][0][cBin]->Fill(data[k][h]->hiEvtPlanes[27],data[k][h]->psi_n[4][14],scale*weight_vz*weight_cent);
	hEP_HF[2][1][cBin]->Fill(data[k][h]->hiEvtPlanes[28],data[k][h]->psi_n[4][0],scale*weight_vz*weight_cent);
	hEP_HF[2][2][cBin]->Fill(data[k][h]->hiEvtPlanes[29],data[k][h]->psi_n[4][14],scale*weight_vz*weight_cent);
	*/
	
	float sumpTtotal = 0;
	for(int a = 0;a<15;a++){
	  
	  //hSumpTvsHF[a]->Fill(data[k][h]->sumpT[a],data[k][h]->hiHF,scale*weight_vz*weight_cent);
	  //hSumpTvshiBin[a]->Fill(data[k][h]->sumpT[a],data[k][h]->bin,scale*weight_vz*weight_cent);
	  sumpTtotal+= data[k][h]->sumpT[a];
	  //for(int b = 0;b<5;b++){
	    
	  //  hPsivsHF[b][a]->Fill(data[k][h]->psi_n[b][a],data[k][h]->hiHF,scale*weight_vz*weight_cent);
	  //  hvnvsHF[b][a]->Fill(data[k][h]->v_n[b][a],data[k][h]->hiHF,scale*weight_vz*weight_cent);
	    //hPsi[cBin]->Fill(data[k][h]->psi_n[b][a]);
	  
	  //}// no of flow components 
	}// eta bin

	//Float_t sumpT_HF = data[k][h]->sumpT[0] + data[k][h]->sumpT[14];
	Float_t sumpT_noHF = 0;

	for(int a = 1;a<14;a++){
	  sumpT_noHF+= data[k][h]->sumpT[a];
	}
	
	hNJetsvsSumpT[cBin]->Fill(jetCounter,sumpTtotal,scale*weight_vz*weight_cent);
	hNJetsvsSumpT[nbins_cent]->Fill(jetCounter,sumpTtotal,scale*weight_vz*weight_cent);
	hNJetsvsSumpT_noHF[cBin]->Fill(jetCounter,sumpT_noHF,scale*weight_vz*weight_cent);
	hNJetsvsSumpT_noHF[nbins_cent]->Fill(jetCounter,sumpT_noHF,scale*weight_vz*weight_cent);
	hNJetsvsSumpT_HF[cBin]->Fill(jetCounter,sumpT_HF,scale*weight_vz*weight_cent);
	hNJetsvsSumpT_HF[nbins_cent]->Fill(jetCounter,sumpT_HF,scale*weight_vz*weight_cent);
	
	hSumpTvsHF_cent[cBin]->Fill(sumpTtotal,data[k][h]->hiHF,scale*weight_vz*weight_cent);
	hSumpTvsHF_cent[nbins_cent]->Fill(sumpTtotal,data[k][h]->hiHF,scale*weight_vz*weight_cent);
	//hSumpTvshiBin_cent[cBin]->Fill(data[k][h]->sumpT[a],data[k][h]->hiHF);
	hSumpT[cBin]->Fill(sumpTtotal,scale*weight_vz*weight_cent);
	hSumpT[nbins_cent]->Fill(sumpTtotal,scale*weight_vz*weight_cent);
       
	
      }// event entry loop

    }// pthat loop

  }// radius loop

  TFile fout(Form("/net/hisrv0001/home/rkunnawa/WORK/RAA/CMSSW_5_3_20/src/Output/PbPb_MC_HFVsValidation_total_histograms_ak%s%s_%d.root",algo,jet_type,date.GetDate()),"RECREATE");
  fout.cd();

  for(int i = 0;i<=nbins_cent;i++){
    hNJetsvsSumpT[i]->Write();
    hNJetsvsSumpT_noHF[i]->Write();
    hNJetsvsSumpT_HF[i]->Write();
    hSumpTvsHF_cent[i]->Write();
    hSumpT[i]->Write();
    hAngle_2_HF_Vs[i]->Write();
    hAngle_3_HF_Vs[i]->Write();
    hAngle_4_HF_Vs[i]->Write();
    hMagnitude_2_HF_Vs[i]->Write();
    hMagnitude_3_HF_Vs[i]->Write();
    hMagnitude_4_HF_Vs[i]->Write();
    hSub_vs_SumpT[i]->Write();
    hVsAngle_EP[0][i]->Write();
    hVsAngle_EP[1][i]->Write();
    hVsAngle_EP[2][i]->Write();
  }

}
void DrawPrototype3EMCalTower(                                                                                                                    //
    const TString infile = "/phenix/u/jinhuang/links/sPHENIX_work/Prototype_2017/Production_0216_UpdateCalib/beam_00003672-0000_DSTReader.root",  //
    bool plot_all = false, const double momentum = -16)
{
  beam_momentum_selection = momentum;

  SetOKStyle();
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(1111);
  TVirtualFitter::SetDefaultFitter("Minuit2");
  gSystem->Load("libg4eval.so");
  gSystem->Load("libqa_modules.so");
  gSystem->Load("libPrototype3.so");

  //  gROOT->LoadMacro("Prototype3_DSTReader.C+");

  if (!_file0)
  {
    TString chian_str = infile;
    chian_str.ReplaceAll("ALL", "*");

    TChain *t = new TChain("T");
    const int n = t->Add(chian_str);

    cout << "Loaded " << n << " root files with " << chian_str << endl;
    assert(n > 0);

    T = t;

    _file0 = new TFile;
    _file0->SetName(infile);
  }

  assert(_file0);

  T->SetAlias("ActiveTower_LG",
              "TOWER_LG_CEMC[].get_binphi()<8 && TOWER_LG_CEMC[].get_bineta()<8");
  T->SetAlias("EnergySum_LG",
              "1*Sum$(TOWER_LG_CEMC[].get_energy() * ActiveTower_LG)");

  T->SetAlias("ActiveTower_HG",
              "TOWER_HG_CEMC[].get_binphi()<8 && TOWER_HG_CEMC[].get_bineta()<8");
  T->SetAlias("EnergySum_HG",
              "1*Sum$(TOWER_HG_CEMC[].get_energy() * ActiveTower_HG)");

  //  T->SetAlias("C2_Inner_e", "1*TOWER_RAW_C2[0].energy");
  T->SetAlias("C2_Inner_e", "1*(TOWER_CALIB_C2[2].energy)");
  T->SetAlias("C2_Outer_e", "1*(TOWER_CALIB_C2[3].energy)");
  T->SetAlias("C2_Sum_e", "C2_Inner_e + C2_Outer_e");
  T->SetAlias("C1", "0 + TOWER_CALIB_C1[0].energy");

  //  "TOWER_CALIB_CEMC.energy * ( Sum$( TOWER_CALIB_CEMC.get_column()==2 && TOWER_CALIB_CEMC.get_row()==1

  T->SetAlias("Average_column",
              "Sum$(TOWER_CALIB_CEMC.get_column() * TOWER_CALIB_CEMC.get_energy())/Sum$(TOWER_CALIB_CEMC.get_energy())");
  T->SetAlias("Average_row",
              "Sum$(TOWER_CALIB_CEMC.get_row() * TOWER_CALIB_CEMC.get_energy())/Sum$(TOWER_CALIB_CEMC.get_energy())");

  T->SetAlias("Average_HODO_VERTICAL",
              "Sum$(TOWER_CALIB_HODO_VERTICAL.towerid * (abs(TOWER_CALIB_HODO_VERTICAL.energy)>30) * abs(TOWER_CALIB_HODO_VERTICAL.energy))/Sum$((abs(TOWER_CALIB_HODO_VERTICAL.energy)>30) * abs(TOWER_CALIB_HODO_VERTICAL.energy))");
  T->SetAlias("Valid_HODO_VERTICAL",
              "Sum$(abs(TOWER_CALIB_HODO_VERTICAL.energy)>30) > 0");

  T->SetAlias("Average_HODO_HORIZONTAL",
              "Sum$(TOWER_CALIB_HODO_HORIZONTAL.towerid * (abs(TOWER_CALIB_HODO_HORIZONTAL.energy)>30) * abs(TOWER_CALIB_HODO_HORIZONTAL.energy))/Sum$((abs(TOWER_CALIB_HODO_HORIZONTAL.energy)>30) * abs(TOWER_CALIB_HODO_HORIZONTAL.energy))");
  T->SetAlias("Valid_HODO_HORIZONTAL",
              "Sum$(abs(TOWER_CALIB_HODO_HORIZONTAL.energy)>30) > 0");

  T->SetAlias("No_Triger_VETO",
              "Sum$(abs(TOWER_RAW_TRIGGER_VETO.energy)>15)==0");

  T->SetAlias("Energy_Sum_col1_row2_3x3",
              "Sum$( (abs(TOWER_CALIB_CEMC.get_column()-1)<=1 && abs(TOWER_CALIB_CEMC.get_row()-2)<=1 ) * TOWER_CALIB_CEMC.get_energy())");
  T->SetAlias("Energy_Sum_col1_row2_5x5",
              "Sum$( (abs(TOWER_CALIB_CEMC.get_column()-1)<=2 && abs(TOWER_CALIB_CEMC.get_row()-2)<=2 ) * TOWER_CALIB_CEMC.get_energy())");
  T->SetAlias("Energy_Sum_col2_row2_5x5",
              "Sum$( (abs(TOWER_CALIB_CEMC.get_column()-2)<=2 && abs(TOWER_CALIB_CEMC.get_row()-2)<=2 ) * TOWER_CALIB_CEMC.get_energy())");
  T->SetAlias("Energy_Sum_CEMC", "1*Sum$(TOWER_CALIB_CEMC.get_energy())");
  T->SetAlias("Energy_Sum_RAW_CEMC", "1*Sum$(TOWER_RAW_CEMC.get_energy())");

  // 12 GeV calibration
  //  EDM=9.83335e-18    STRATEGY= 1      ERROR MATRIX ACCURATE
  //EXT PARAMETER                                   STEP         FIRST
  //NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE
  //1  p0           1.19768e+01   7.30605e-02   3.76799e-05   4.24290e-09
  //2  p1           8.71776e+00   6.82987e-02   3.52240e-05   6.80808e-08

  //    T->SetAlias("Energy_Sum_Hadron_CEMC",
  //        "1*Sum$(TOWER_CALIB_CEMC.get_energy())"); // full bias
  T->SetAlias("Energy_Sum_Hadron_CEMC",
              "1.14*12./8.71776e+00*Sum$(TOWER_CALIB_CEMC.get_energy())");  // full bias
                                                                            //  T->SetAlias("Energy_Sum_Hadron_CEMC",
                                                                            //      "1.14*12./8.71776e+00*(16./6.93250e+00)*(28/33.3405)*Sum$(TOWER_CALIB_CEMC.get_energy())"); // half-gain bias
  T->SetAlias("CEMC_MIP", "Energy_Sum_Hadron_CEMC<0.7");

  // 12 GeV calibration
  //  FCN=9.63681 FROM HESSE     STATUS=OK             14 CALLS          56 TOTAL
  //                      EDM=1.49963e-17    STRATEGY= 1      ERROR MATRIX ACCURATE
  //   EXT PARAMETER                                   STEP         FIRST
  //   NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE
  //    1  p0           9.50430e+00   8.42691e-02   3.83666e-06   1.41105e-08
  //    2  p1           6.99727e+00   1.06583e-01   4.85258e-06   5.85631e-08

  //  T->SetAlias("Energy_Sum_Hadron_HCALIN",
  //      "1*Sum$(TOWER_CALIB_LG_HCALIN.get_energy())");
  //  T->SetAlias("HCALIN_MIP", "Energy_Sum_Hadron_HCALIN<0.5");
  //  T->SetAlias("Energy_Sum_Hadron_HCALOUT",
  //      "1*Sum$(TOWER_CALIB_LG_HCALOUT.get_energy())");
  T->SetAlias("Energy_Sum_Hadron_HCALIN",
              "12./6.99727e+00*Sum$(TOWER_CALIB_LG_HCALIN.get_energy())");
  T->SetAlias("HCALIN_MIP", "Energy_Sum_Hadron_HCALIN<0.5");
  T->SetAlias("Energy_Sum_Hadron_HCALOUT",
              "12./9.50430e+00*Sum$(TOWER_CALIB_LG_HCALOUT.get_energy())");

  T->SetAlias("MIP_Count_Col2",
              "Sum$( abs( TOWER_RAW_CEMC.get_energy() )>20 && abs( TOWER_RAW_CEMC.get_energy() )<200 && TOWER_CALIB_CEMC.get_column() == 2 )");
  T->SetAlias("Pedestal_Count_AllCEMC",
              "Sum$( abs( TOWER_RAW_CEMC.get_energy() )<20)");

  //
  TCut event_sel = "1*1";

  if (plot_all)
  {
    //      event_sel = "1*1";
    //      cuts = "_all_event";
    //      event_sel = "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL";
    //      cuts = "_Valid_HODO";
    event_sel =
        "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && No_Triger_VETO";
    cuts = "_Valid_HODO_Trigger_VETO";
  }
  else
  {
    if (0)
    {  // energy selection
      event_sel = Form("(beam_MTNRG_GeV == %f)", beam_momentum_selection);
      cuts = Form("_%.0fGeV", beam_momentum_selection);

      cout << "Build event selection of " << (const char *) event_sel
           << endl;

      T->Draw(">>EventListRunCut", event_sel);
      TEventList *elist = gDirectory->GetObjectChecked("EventListRunCut",
                                                       "TEventList");
      cout << elist->GetN() << " / " << T->GetEntriesFast()
           << " events selected" << endl;
      T->SetEventList(elist);
    }

    //      event_sel = "1*1";
    //      cuts = "_all_event";
    //      event_sel = "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL";
    //      cuts = "_Valid_HODO";
    event_sel =
        "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && No_Triger_VETO";
    cuts = "_Valid_HODO_Trigger_VETO";

    //      event_sel =
    //          event_sel
    //              + "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && No_Triger_VETO  && (C2_Sum_e<50)";
    //      cuts = cuts + "_Valid_HODO_Trigger_VETO_C2_Sum_Hadron";

    //      event_sel =
    //          event_sel
    //              + "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && No_Triger_VETO && CEMC_MIP && (C2_Sum_e<100)";
    //      cuts = cuts + "_Valid_HODO_Trigger_VETO_CEMC_MIP_C2_Sum_Hadron";

    //      event_sel = "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && (MIP_Count_Col2 == 8) && (Pedestal_Count_AllCEMC >= 64 - 8)";
    //      cuts = "_Valid_HODO_MIP_Col2_PedestalOther";

    //      event_sel = "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && Average_HODO_VERTICAL>1.5 && Average_HODO_VERTICAL<4.5 && Average_HODO_HORIZONTAL>3.5 && Average_HODO_HORIZONTAL<6.5";
    //      cuts = "_Valid_HODO_center_col1_row2";

    //      event_sel =
    //          "C2_Inner_e>100 && Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && Average_HODO_HORIZONTAL>1.5 && Average_HODO_HORIZONTAL<4.5 && Average_HODO_VERTICAL>3.5 && Average_HODO_VERTICAL<6.5";
    //      cuts = "_Valid_HODO_center_col1_row2_C2";

    //      event_sel = "abs(Average_column - 1)<.5 && abs(Average_row - 2) < .5";
    //      cuts = "_tower_center_col1_row2";
    //      event_sel = "Valid_HODO_HORIZONTAL && Valid_HODO_VERTICAL && abs(C2_Inner_e)<10";
    //      cuts = "_Valid_HODO_VetoC2";
  }

  cout << "Build event selection of " << (const char *) event_sel << endl;

  T->Draw(">>EventList", event_sel);
  TEventList *elist = gDirectory->GetObjectChecked("EventList", "TEventList");
  cout << elist->GetN() << " / " << T->GetEntriesFast() << " events selected"
       << endl;

  T->SetEventList(elist);

  //  int rnd = rand();
  //  gDirectory->mkdir(Form("dir_%d", rnd));
  //  gDirectory->cd(Form("dir_%d", rnd));
  //  if (plot_all)
  //    EMCDistribution_SUM("Energy_Sum_col1_row2_5x5");

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_ShowShape("C1");

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_SUM("Energy_Sum_CEMC", "C1");
  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  //  if (plot_all)
  EMCDistribution_SUM_RawADC("Energy_Sum_RAW_CEMC", "C2_Sum_e");

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_SUM("Energy_Sum_col2_row2_5x5", "C2_Sum_e");

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_HCalCalibration();

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_Fast();

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_Fast("RAW");
  //
  //  int rnd = rand();
  //  gDirectory->mkdir(Form("dir_%d", rnd));
  //  gDirectory->cd(Form("dir_%d", rnd));
  //  if (plot_all)
  //    EMCDistribution_PeakSample_Fast();

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_Fast("CALIB", true);

  int rnd = rand();
  gDirectory->mkdir(Form("dir_%d", rnd));
  gDirectory->cd(Form("dir_%d", rnd));
  if (plot_all)
    EMCDistribution_ADC();

  //  if (!plot_all)
  //    T->Process("Prototype3_DSTReader.C+",
  //        TString(_file0->GetName())
  //            + TString("_DrawPrototype3EMCalTower_Prototype3_DSTReader") + cuts
  //            + TString(".dat"));
}
Example #9
0
//this file stores the data events in our signal regions in several histograms 
//that are used by MT2Results_PlotsAndTables.C
//can also choose to store files in control region or MC events
//additionally it creates a log file with run:lumisection:eventnumber for all those events.
void MakeDataFile(){

	fLogStream = new std::ostringstream();

	bool poisson = false;//set poissonian uncertainties, works from next root version on

	//decide on filename histograms are stored, also define the samples.dat
  	gROOT->ProcessLine(".x SetStyle_PRD.C");
	TString fOutDir                    = "../Results/Filtered/";
	TString outputname = "NewDataNumbers.root";
	if(ourfilter    ) outputname = "NewDataNumbersOurFilter.root";
	if(calometfilter) outputname = "NewDataNumbersOurFilterCaloMETfilter.root";
	if(tobtecfilter ) outputname = "NewDataNumbersOurFilterCaloMETfilterTOBTECFilter.root";
	if(poisson) outputname = "NewDataNumbersPoisson.root";
	TString samples = "samples/samples_HTandMET_filter.dat";

	//definition of the histograms
	map<string, TH1D*>    histos;
	for(int i2 = 0; i2<signalregionsize; ++i2){
	for(int i3 = 0; i3<HTbinsize;        ++i3){
		int NMT2bins;
		if(i3==0){
			if(signal_region[i2]=="2j0b")    NMT2bins = gNMT2bins_2j0b_lHT;
			if(signal_region[i2]=="2j1to2b") NMT2bins = gNMT2bins_2j1b_lHT;
			if(signal_region[i2]=="3to5j0b") NMT2bins = gNMT2bins_3j0b_lHT;
			if(signal_region[i2]=="3to5j1b") NMT2bins = gNMT2bins_3j1b_lHT;
			if(signal_region[i2]=="3to5j2b") NMT2bins = gNMT2bins_3j2b_lHT;
			if(signal_region[i2]=="6j0b")    NMT2bins = gNMT2bins_6j0b_lHT;
			if(signal_region[i2]=="6j1b")    NMT2bins = gNMT2bins_6j1b_lHT;
			if(signal_region[i2]=="6j2b")    NMT2bins = gNMT2bins_6j2b_lHT;
			if(signal_region[i2]=="3b")      NMT2bins = gNMT2bins_3b_lHT;
		} if(i3==1){
			if(signal_region[i2]=="2j0b")    NMT2bins = gNMT2bins_2j0b_mHT;
			if(signal_region[i2]=="2j1to2b") NMT2bins = gNMT2bins_2j1b_mHT;
			if(signal_region[i2]=="3to5j0b") NMT2bins = gNMT2bins_3j0b_mHT;
			if(signal_region[i2]=="3to5j1b") NMT2bins = gNMT2bins_3j1b_mHT;
			if(signal_region[i2]=="3to5j2b") NMT2bins = gNMT2bins_3j2b_mHT;
			if(signal_region[i2]=="6j0b")    NMT2bins = gNMT2bins_6j0b_mHT;
			if(signal_region[i2]=="6j1b")    NMT2bins = gNMT2bins_6j1b_mHT;
			if(signal_region[i2]=="6j2b")    NMT2bins = gNMT2bins_6j2b_mHT;
			if(signal_region[i2]=="3b")      NMT2bins = gNMT2bins_3b_mHT;
		} if(i3==2){
			if(signal_region[i2]=="2j0b")    NMT2bins = gNMT2bins_2j0b_hHT;
			if(signal_region[i2]=="2j1to2b") NMT2bins = gNMT2bins_2j1b_hHT;
			if(signal_region[i2]=="3to5j0b") NMT2bins = gNMT2bins_3j0b_hHT;
			if(signal_region[i2]=="3to5j1b") NMT2bins = gNMT2bins_3j1b_hHT;
			if(signal_region[i2]=="3to5j2b") NMT2bins = gNMT2bins_3j2b_hHT;
			if(signal_region[i2]=="6j0b")    NMT2bins = gNMT2bins_6j0b_hHT;
			if(signal_region[i2]=="6j1b")    NMT2bins = gNMT2bins_6j1b_hHT;
			if(signal_region[i2]=="6j2b")    NMT2bins = gNMT2bins_6j2b_hHT;
			if(signal_region[i2]=="3b")      NMT2bins = gNMT2bins_3b_hHT;
		}
  		double MT2bins[NMT2bins+1];
		if(i3==0){
			if(signal_region[i2]=="2j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j0b_lHT[i0]; }
			if(signal_region[i2]=="2j1to2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j1b_lHT[i0]; }
			if(signal_region[i2]=="3to5j0b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j0b_lHT[i0]; }
			if(signal_region[i2]=="3to5j1b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j1b_lHT[i0]; }
			if(signal_region[i2]=="3to5j2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j2b_lHT[i0]; }
			if(signal_region[i2]=="6j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j0b_lHT[i0]; }
			if(signal_region[i2]=="6j1b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j1b_lHT[i0]; }
			if(signal_region[i2]=="6j2b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j2b_lHT[i0]; }
			if(signal_region[i2]=="3b")      { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3b_lHT[i0];   }
		} if(i3==1){
			if(signal_region[i2]=="2j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j0b_mHT[i0];  }
			if(signal_region[i2]=="2j1to2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j1b_mHT[i0];  }
			if(signal_region[i2]=="3to5j0b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j0b_mHT[i0];  }
			if(signal_region[i2]=="3to5j1b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j1b_mHT[i0];  }
			if(signal_region[i2]=="3to5j2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j2b_mHT[i0];  }
			if(signal_region[i2]=="6j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j0b_mHT[i0];  }
			if(signal_region[i2]=="6j1b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j1b_mHT[i0];  }
			if(signal_region[i2]=="6j2b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j2b_mHT[i0];  }
			if(signal_region[i2]=="3b")      { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3b_mHT[i0];    }
		} if(i3==2){
			if(signal_region[i2]=="2j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j0b_hHT[i0];  }
			if(signal_region[i2]=="2j1to2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j1b_hHT[i0];  }
			if(signal_region[i2]=="3to5j0b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j0b_hHT[i0];  }
			if(signal_region[i2]=="3to5j1b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j1b_hHT[i0];  }
			if(signal_region[i2]=="3to5j2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j2b_hHT[i0];  }
			if(signal_region[i2]=="6j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j0b_hHT[i0];  }
			if(signal_region[i2]=="6j1b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j1b_hHT[i0];  }
			if(signal_region[i2]=="6j2b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j2b_hHT[i0];  }
			if(signal_region[i2]=="3b")      { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3b_hHT[i0];    }
		}

		string hs = string("_") + HT_bin[i3] + string("_") + signal_region[i2];
		string mapname = "MT2" + hs;
		if(histos.count(mapname) == 0 ) histos[mapname] = new TH1D(mapname.c_str(), "", NMT2bins, MT2bins);
	//	if(poisson) histos[mapname]->SetBinErrorOption((TH1::EBinErrorOpt)1);//store already here the poissonian errors, works from next root version on
	}}
	for(map<string,TH1D*>::iterator h=histos.begin(); h!=histos.end();++h){
		h->second->Sumw2();}

	//signal selection cuts
	std::ostringstream  fCutStreamSignal;
	fCutStreamSignal << " " 
	  << "misc.MT2>=100"                                               << "&&"
	  << "misc.MET>=30"                                                << "&&"
	  << "misc.HT >=450"                                               << "&&"
	  << "NEles==0"                                                    << "&&"
	  << "NMuons==0"                                                   << "&&"
	  << "NTausIDLoose3Hits==0"                                        << "&&"
	  << "misc.Jet0Pass ==1"                                           << "&&"
	  << "misc.Jet1Pass ==1"                                           << "&&"
	  << "misc.PassJet40ID ==1"                                        << "&&"
	  << "NJetsIDLoose40 >=2"                                          << "&&"
	  << "misc.MinMetJetDPhi4Pt40 >0.3"                                << "&&"
	  << "misc.Vectorsumpt < 70"                                       << "&&"
	  // Noise
	  << "(misc.HBHENoiseFlag == 0 || misc.ProcessID==10)"             << "&&" // for rare SM samples
	  << "misc.CSCTightHaloIDFlag == 0"                                << "&&"
	  << "misc.trackingFailureFlag==0"                                 << "&&"
	  << "misc.eeBadScFlag==0"                                         << "&&"
	  << "misc.EcalDeadCellTriggerPrimitiveFlag==0"                    << "&&"
	  << "misc.TrackingManyStripClusFlag==0"                           << "&&"
	  << "misc.TrackingTooManyStripClusFlag==0"                        << "&&"
	  << "misc.TrackingLogErrorTooManyClustersFlag==0"                 << "&&"
          << "misc.CrazyHCAL==0";
	fCutStreamSignal << "&&((misc.MET>=200&&misc.MT2>=200&&misc.HT<750)||(misc.HT>750))";
	fCutStreamSignal << "&&NJetsIDLoose40>=2";
	fCutStreamSignal << "&&misc.MET/misc.CaloMETRaw<=2.";
	TString cuts = fCutStreamSignal.str().c_str();

  std::ostringstream triggerStream;
  triggerStream << "( ( ( "
		<< "trigger.HLT_PFHT650_v5 == 1 || trigger.HLT_PFHT650_v6 == 1 || trigger.HLT_PFHT650_v7 == 1 || trigger.HLT_PFHT650_v8 == 1 || trigger.HLT_PFHT650_v9 == 1 || "
		<< "trigger.HLT_PFNoPUHT650_v1 == 1 || trigger.HLT_PFNoPUHT650_v3 == 1 || trigger.HLT_PFNoPUHT650_v4 == 1) ||";

  triggerStream << "( ( "
		<< "trigger.HLT_PFMET150_v2 == 1 || trigger.HLT_PFMET150_v3 == 1 || trigger.HLT_PFMET150_v4 == 1 || "
  		<< "trigger.HLT_PFMET150_v5 == 1 || trigger.HLT_PFMET150_v6 == 1 || trigger.HLT_PFMET150_v7 == 1 )"
		<< "||("
		<< "trigger.HLT_PFHT350_PFMET100_v3==1 || trigger.HLT_PFHT350_PFMET100_v4==1 || trigger.HLT_PFHT350_PFMET100_v5==1 || "
		<< "trigger.HLT_PFHT350_PFMET100_v6==1 || trigger.HLT_PFHT350_PFMET100_v7==1 || trigger.HLT_PFNoPUHT350_PFMET100_v1==1 || "
		<< "trigger.HLT_PFNoPUHT350_PFMET100_v3==1 || trigger.HLT_PFNoPUHT350_PFMET100_v4==1 ) ) )&&TOBTECTagger<=8&&ExtraBeamHaloFilter==0)";

	TString trigger = triggerStream.str().c_str();
	load(samples.Data());

	int counterAll = 0;

  	for(size_t i = 0; i < fSamples.size(); ++i){

	    string sampletype = (string)fSamples[i].type;
	    if(sampletype!="data") continue;//run only over data - extendable to MC 

	    Double_t sample_weight = fSamples[i].xsection * fSamples[i].kfact * fSamples[i].lumi / (fSamples[i].nevents*fSamples[i].PU_avg_weight);
	    if(fVerbose>2) cout << "ZnunuNumbers: looping over " << fSamples[i].name << " added in " << sampletype << endl;
	    if(fVerbose>2) cout << "              sample has weight " << sample_weight << " and " << fSamples[i].tree->GetEntries() << " entries" << endl; 
	    if(fVerbose>2 && fSamples[i].tree->GetEntries()==0) cout << "skip sample, has no entries" << endl;
            if(fSamples[i].tree->GetEntries()==0) continue;

	    MT2tree* fMT2tree = new MT2tree();
	    fSamples[i].tree->SetBranchAddress("MT2tree", &fMT2tree);
	    Long64_t nentries =  fSamples[i].tree->GetEntries();
	    Long64_t nbytes = 0, nb = 0;
	    int nev =0;
        
	    TString myCuts = cuts;// + "&&" + basecuts;
        
	    if( fSamples[i].type=="data") myCuts += " && " + trigger; //cuts to be aplied only on data
        
   	    cout << "Cuts for Flow: " << myCuts << endl;
   	    fSamples[i].tree->Draw(">>selList", myCuts);
        
	    TEventList *myEvtList = (TEventList*)gDirectory->Get("selList");
	    fSamples[i].tree->SetEventList(myEvtList);
	    int counter=0;
	    cout << "Filtering done, size=" <<myEvtList->GetN()  << endl;
	    if(myEvtList->GetSize()==0) continue;
	*fLogStream << "Sample " << fSamples[i].name << endl;
	//run over all selected events
        while(myEvtList->GetEntry(counter++) !=-1){	
		int jentry = myEvtList->GetEntry(counter-1);
            
		nb =  fSamples[i].tree->GetEntry(jentry);   nbytes += nb;
		fSamples[i].tree->SetBranchAddress("MT2tree", &fMT2tree);
		
		if ( fVerbose>2 && counter % 5000 == 0  )  cout << "+++ Proccessing event " << counter << endl;

		string sHT;//HT region
		if(fMT2tree->misc.HT<450.)      sHT = "_HTge0";
		else if(fMT2tree->misc.HT<750.) sHT = "_lowHT";
		else if(fMT2tree->misc.HT<1200.)sHT = "_mediumHT";
		else                            sHT = "_highHT";

		string ssignal;//topological region
		if(fMT2tree->NJetsIDLoose40 == 2 &&                                  fMT2tree->NBJets40CSVM == 0) ssignal = "_2j0b";
		if(fMT2tree->NJetsIDLoose40 == 2 &&                                  fMT2tree->NBJets40CSVM >= 1) ssignal = "_2j1to2b";
		if(fMT2tree->NJetsIDLoose40 >= 3 && fMT2tree->NJetsIDLoose40 <= 5 && fMT2tree->NBJets40CSVM == 0) ssignal = "_3to5j0b";
		if(fMT2tree->NJetsIDLoose40 >= 3 && fMT2tree->NJetsIDLoose40 <= 5 && fMT2tree->NBJets40CSVM == 1) ssignal = "_3to5j1b";
		if(fMT2tree->NJetsIDLoose40 >= 3 && fMT2tree->NJetsIDLoose40 <= 5 && fMT2tree->NBJets40CSVM == 2) ssignal = "_3to5j2b";
		if(                                                                  fMT2tree->NBJets40CSVM >= 3) ssignal = "_3b";
		if(fMT2tree->NJetsIDLoose40 >= 6 &&                                  fMT2tree->NBJets40CSVM == 0) ssignal = "_6j0b";
		if(fMT2tree->NJetsIDLoose40 >= 6 &&                                  fMT2tree->NBJets40CSVM == 1) ssignal = "_6j1b";
		if(fMT2tree->NJetsIDLoose40 >= 6 &&                                  fMT2tree->NBJets40CSVM == 2) ssignal = "_6j2b";

		string hh = sHT + ssignal;
		histos[(string)"MT2"        + hh]->Fill(fMT2tree->misc.MT2);//fill histogram
		if(fMT2tree->misc.MT2>histos[(string)"MT2"        + hh]->GetBinLowEdge(1)){
			if(sHT=="_lowHT" && (fMT2tree->trigger.HLT_PFHT350_PFMET100_v3==1||fMT2tree->trigger.HLT_PFHT350_PFMET100_v4==1||fMT2tree->trigger.HLT_PFHT350_PFMET100_v5==1||fMT2tree->trigger.HLT_PFHT350_PFMET100_v6==1||fMT2tree->trigger.HLT_PFHT350_PFMET100_v7==1 || fMT2tree->trigger.HLT_PFNoPUHT350_PFMET100_v1==1 || fMT2tree->trigger.HLT_PFNoPUHT350_PFMET100_v3==1 || fMT2tree->trigger.HLT_PFNoPUHT350_PFMET100_v4==1 ) ) *fLogStream << "HTMHT ";
			else if(sHT=="_lowHT") *fLogStream << "MET   ";
			else *fLogStream << "JetHT ";
			*fLogStream << int(fMT2tree->misc.Run) << ":" << int(fMT2tree->misc.LumiSection) << ":" << int(fMT2tree->misc.Event) << endl;//file log file (including trigger stream
			++counterAll;
		}
	}//while
	delete fMT2tree;
	delete fSamples[i].tree;

	}//for samples

	cout << "add overflow to last bin" << endl;
	for(map<string,TH1D*>::iterator h=histos.begin(); h!=histos.end();++h){
		h->second->SetBinContent(h->second->GetNbinsX(),
					 h->second->GetBinContent(h->second->GetNbinsX()  )+ 
					 h->second->GetBinContent(h->second->GetNbinsX()+1)  );
		h->second->SetBinError(  h->second->GetNbinsX(),
					 sqrt(h->second->GetBinError(h->second->GetNbinsX()  )*
					      h->second->GetBinError(h->second->GetNbinsX()  )+
					      h->second->GetBinError(h->second->GetNbinsX()+1)*
					      h->second->GetBinError(h->second->GetNbinsX()+1)  ));
	}

	cout << "Saving." << endl;
    	TFile *fsavefile = new TFile(fOutDir + outputname,"RECREATE");
	fsavefile->cd();
	for(map<string,TH1D*>::iterator h=histos.begin(); h!=histos.end();++h){
		h->second->Write();
	}
	fsavefile->Close();
	cout << "Saved histograms in " << fOutDir << outputname << endl;

	TString logname ="eventlistMT2inclusive.log"; 
	cout << counterAll << " events in " << logname.Data() << endl;
	ofstream f_log (logname.Data(), ios::trunc);
	f_log << fLogStream->str();
}
Example #10
0
void Plot(Char_t *filen = "jsf.root")
{
  //gROOT->Reset();
  gSystem->Load("libS4Utils.so");
  gSystem->Load("libAnlib.so");

  Int_t nZoneX = 4;
  Int_t nZoneY = 3;

  TCanvas *c1 = new TCanvas("c1","",0,0, 300*nZoneX, 300*nZoneY);
  c1->SetHighLightColor(5);
  c1->SetFillColor(19);
  c1->Divide(nZoneX,nZoneY);

  gStyle->SetOptFit();

  cerr << filen << endl;
  TFile   *filep = new TFile(filen);
  TNtupleD *tup   = (TNtupleD *)gROOT->FindObject("hEvt");

  //--
  // Preselection
  //--
#if 0
  TString sel("evis>0.");
#else
  TString sel("pt<20.&&abs(pl)<30.&&ycut>0.0015");
#endif
  tup->Draw(">>elist",sel.Data(),"goff");

  TEventList *elist = static_cast<TEventList*>(gROOT->FindObject("elist"));
  Int_t nlist = elist->GetN();
  cerr << "Nevent = " << nlist << endl;

  //--
  // Loop over preselected events
  //--
  Double_t kToDeg = 180./TMath::Pi();
  for (Int_t i=0; i<nlist; i++) {
#if 0
        Int_t event = elist->GetEntry(i);
        cerr << "i = " << i << " event = " << event << endl;
#else
        Int_t event = i;
#endif
        Double_t ntracks;
        Double_t evis;
        Double_t pt;
        Double_t pl;
        Double_t ycut;
        Double_t chi2;
        Double_t mh;
        Double_t mw1;
        Double_t mw2;
        Double_t mt1;
        Double_t mt2;
        Double_t mtt;

        tup->SetBranchAddress("ntracks",&ntracks);
        tup->SetBranchAddress("evis",&evis);
        tup->SetBranchAddress("pt",&pt);
        tup->SetBranchAddress("pl",&pl);
        tup->SetBranchAddress("ycut",&ycut);
        tup->SetBranchAddress("chi2",&chi2);
        tup->SetBranchAddress("mh",&mh);
        tup->SetBranchAddress("mw1",&mw1);
        tup->SetBranchAddress("mw2",&mw2);
        tup->SetBranchAddress("mt1",&mt1);
        tup->SetBranchAddress("mt2",&mt2);
        tup->SetBranchAddress("mtt",&mtt);

        tup->GetEntry(event);

        hMhMw->Fill(mh,  mw1, 1.);
        hMwMw->Fill(mw1, mw2, 1.);
        hMtMt->Fill(mt1, mt2, 1.);
	hEvis->Fill(evis, 1.);
	hPtPl->Fill(pt, pl, 1.);
        hMttMh->Fill(mtt,  mh, 1.);
  }
  Int_t id = 0;
  id++; c1->cd(id); hStat->Draw();
  id++; c1->cd(id); hMhMw->Draw();
  id++; c1->cd(id); hMhMw->ProjectionX()->Draw();
  id++; c1->cd(id); hMhMw->ProjectionY()->Draw();
  id++; c1->cd(id); hEvis->Draw();
  id++; c1->cd(id); hMwMw->Draw();
  id++; c1->cd(id); hMwMw->ProjectionX()->Draw();
  id++; c1->cd(id); hMwMw->ProjectionY()->Draw();
  id++; c1->cd(id); hMtMt->Draw();
  id++; c1->cd(id); hMtMt->ProjectionX()->Draw();
  id++; c1->cd(id); hMtMt->ProjectionY()->Draw();
  id++; c1->cd(id); hMttMh->ProjectionX()->Draw();
}
Example #11
0
void RAA_calo_pf_JetCorrelation_pp(int startfile = 10, int endfile = 11, int radius=2, int deltaR=2/*which i will divide by 10 later when using*/, Float_t CALOPTCUT = 30.0, Float_t PFPTCUT = 30.0, char *dataset = "MC", char *etaWidth = "n20_eta_p20"){

  TH1::SetDefaultSumw2();

  TStopwatch timer;
  timer.Start();

  TDatime date;
  
  bool printDebug = false;

  // Since this has to run on the HiForest files, it is best to run them as condor jobs similar to the Pp data read macro, along with the jet trees which get their branch address set. 
  
  std::string infile1;
  if(dataset == "Data")infile1 = "jetRAA_pp_data_forest.txt";
  if(dataset == "MC")infile1 = "jetRAA_pp_mc_forest.txt";

  std::ifstream instr1(infile1.c_str(),std::ifstream::in);
  std::string filename1;

  cout<<"reading from "<<startfile<<" to "<<endfile<<endl;

  if(dataset=="MC"){
    for(int ifile = 0;ifile<4*startfile;ifile++){
      instr1>>filename1;
    }
  }
  if(dataset=="Data"){
    for(int ifile = 0;ifile<startfile;ifile++){
      instr1>>filename1;
    }
  }

  
  const int N = 5;
  
  TChain *jetpp1[N][no_radius];

  string dir[N][no_radius];
  
  for(int k = 0;k<no_radius;k++){
    dir[0][k] = "hltanalysis";
    dir[1][k] = "skimanalysis";
    dir[2][k] = Form("ak%dCaloJetAnalyzer",3);
    dir[3][k] = Form("ak%dPFJetAnalyzer",radius);
    dir[4][k] = "hiEvtAnalyzer";
    //dir[5][k] = "hltobject";
    //dir[6][k] = "pfcandAnalyzer";
  }
  
  
  string trees[N] = {
    "HltTree",
    "HltTree",
    "t",
    "t",
    "HiTree"
    //"jetObjTree",
    //"pfTree"
  };
  
  //this loop is to assign the tree values before we go into the file loop. 
  for(int k = 0;k<no_radius;k++){
    for(int t = 0;t<N;t++){
      jetpp1[t][k] = new TChain(string(dir[t][k]+"/"+trees[t]).data());
    }//tree loop ends
  }// radius loop ends
  
  if(dataset == "Data"){
    for(int ifile = startfile;ifile<endfile;ifile++){
    
      instr1>>filename1;
      if(printDebug)cout<<"File: "<<filename1<<endl;
      for(int k = 0;k<no_radius;k++){

	for(int t = 0;t<N;t++){
	
	  jetpp1[t][k]->Add(filename1.c_str());
	  if(printDebug)cout << "Tree loaded  " << string(dir[t][k]+"/"+trees[t]).data() << endl;
	  if(printDebug)cout << "Entries : " << jetpp1[t][k]->GetEntries() << endl;
		
	}// tree loop ends
      
      }// radius loop ends
    
    }// file loop ends

  }

  // these different file loops for MC is necessary because of eachfile being split into 4 files except the last pthat 540 which has 5 files. 
  if(dataset == "MC" && startfile <10){
    for(int ifile = 4*startfile;ifile<4*endfile;ifile++){
    
      instr1>>filename1;
      if(printDebug)cout<<"File: "<<filename1<<endl;
      for(int k = 0;k<no_radius;k++){

	for(int t = 0;t<N;t++){
	
	  jetpp1[t][k]->Add(filename1.c_str());
	  if(printDebug)cout << "Tree loaded  " << string(dir[t][k]+"/"+trees[t]).data() << endl;
	  if(printDebug)cout << "Entries : " << jetpp1[t][k]->GetEntries() << endl;
		
	}// tree loop ends
      
      }// radius loop ends
    
    }// file loop ends

  }

  if(dataset == "MC" && startfile == 10){
    for(int ifile = 4*startfile;ifile<4*endfile+1;ifile++){
    
      instr1>>filename1;
      if(printDebug)cout<<"File: "<<filename1<<endl;
      for(int k = 0;k<no_radius;k++){

	for(int t = 0;t<N;t++){
	
	  jetpp1[t][k]->Add(filename1.c_str());
	  if(printDebug)cout << "Tree loaded  " << string(dir[t][k]+"/"+trees[t]).data() << endl;
	  if(printDebug)cout << "Entries : " << jetpp1[t][k]->GetEntries() << endl;
		
	}// tree loop ends
      
      }// radius loop ends
    
    }// file loop ends

  }
  
  for(int k = 0;k<no_radius;k++){
    jetpp1[2][k]->AddFriend(jetpp1[0][k]);
    jetpp1[2][k]->AddFriend(jetpp1[1][k]);
    jetpp1[2][k]->AddFriend(jetpp1[4][k]);
    //jetpp1[2][k]->AddFriend(jetpp1[5][k]);
    
    jetpp1[3][k]->AddFriend(jetpp1[0][k]);
    jetpp1[3][k]->AddFriend(jetpp1[1][k]);
    jetpp1[3][k]->AddFriend(jetpp1[4][k]);
    //jetpp1[3][k]->AddFriend(jetpp1[5][k]);
    
  }// radius loop ends
 
  // Ok this should now work. 

  cout<<"total no of entries in the combined forest files = "<<jetpp1[2][0]->GetEntries()<<endl;
  //  if(printDebug)cout<<"total no of entries in the Jet80 Tree     = "<<jetpp2[2][0]->GetEntries()<<endl;

  // get the centrality weight, vz weight and the scale from the cross section, pt weighting. 
  static const Int_t nbins_pthat = 11;
  Double_t xsection[nbins_pthat+1] = {2.034e-01, 1.075e-02, 1.025e-03,  9.865e-05, 1.129e-05, 1.465e-06, 2.837e-07, 5.323e-08, 5.934e-09, 8.125e-10, 1.468e-10, 0};
  Double_t boundaries_pthat[nbins_pthat+1] = {15, 30, 50, 80, 120, 170, 220, 280, 370, 460, 540, 2000};
  TH1F * hpthatBin = new TH1F("hpthatBin","",nbins_pthat, boundaries_pthat);

  // Vertex reweighting for pp
  TF1 *fVzPP = new TF1("fVzPP","[0]+[1]*x+[2]*x*x+[3]*x*x*x+[4]*x*x*x*x");
  fVzPP->SetParameters(8.41684e-01,-2.58609e-02,4.86550e-03,-3.10581e-04,2.07918e-05);
  
  
  TFile f(Form("/net/hisrv0001/home/rkunnawa/WORK/RAA/CMSSW_5_3_20/src/Output/pp_%s_closure_histogram_noJetID_deltaR_0p%d_ak%d_%d_%d.root",dataset,deltaR,radius,date.GetDate(),endfile),"RECREATE");
  f.cd();


  //set the branch addresses:
  // jet tree 1 - Calo 
  int nrefe_1;
  float pt_1[1000];
  float raw_1[1000];
  float refpt_1[1000];
  float eta_1[1000];
  float phi_1[1000];
  float chMax_1[1000];
  float trkMax_1[1000];
  float chSum_1[1000];
  float phSum_1[1000];
  float neSum_1[1000];
  float trkSum_1[1000];
  float phMax_1[1000];
  float neMax_1[1000];
  float eMax_1[1000];
  float muMax_1[1000];
  float eSum_1[1000];
  float muSum_1[1000];
  float jtpu_1[1000];
  float hcalSum_1[1000];
  float ecalSum_1[1000];
  int subid_1[1000];
  
  // jet tree 2 - PF
  int nrefe_2;
  float pt_2[1000];
  float raw_2[1000];
  float refpt_2[1000];
  float eta_2[1000];
  float eta_2_CM[1000];
  float phi_2[1000];
  float chMax_2[1000];
  float trkMax_2[1000];
  float chSum_2[1000];
  float phSum_2[1000];
  float neSum_2[1000];
  float trkSum_2[1000];
  float phMax_2[1000];
  float neMax_2[1000];
  float eMax_2[1000];
  float muMax_2[1000];
  float eSum_2[1000];
  float muSum_2[1000];
  float jtpu_2[1000];
  float hcalSum_2[1000];
  float ecalSum_2[1000];
  int subid_2[1000];
  
  // event tree
  int evt_1;
  int run_1;
  int lumi_1;
  float pthat_1;
  float vx_1;
  float vy_1;
  float vz_1;
  int hiNpix_1;
  int hiNtracks_1;
  float hiHF_1;
  float hiHFminus_1;
  float hiHFplus_1;
  float hiHFplusEta4_1;
  float hiHFminusEta4_1;
  int pPAcollisionEventSelectionPA_1;
  int pHBHENoiseFilter_1;
  int pprimaryvertexFilter_1;
  int pVertexFilterCutGplus_1;

  // trigger tree
  int jet40_1;
  int jet60_1;
  int jet80_1;
  int jet40_p_1;
  int jet60_p_1;
  int jet80_p_1;

  for(int k = 0;k<no_radius;k++){
    //set the branch addresses:  - one of the most boring parts of the code: 
    jetpp1[2][k]->SetBranchAddress("evt",&evt_1);
    jetpp1[2][k]->SetBranchAddress("run",&run_1);
    jetpp1[2][k]->SetBranchAddress("lumi",&lumi_1);
    if(dataset=="MC") jetpp1[2][k]->SetBranchAddress("pthat",&pthat_1);
    jetpp1[2][k]->SetBranchAddress("vz",&vz_1);
    jetpp1[2][k]->SetBranchAddress("vx",&vx_1);
    jetpp1[2][k]->SetBranchAddress("vy",&vy_1);
    jetpp1[2][k]->SetBranchAddress("hiNpix",&hiNpix_1);
    jetpp1[2][k]->SetBranchAddress("hiNtracks",&hiNtracks_1);
    jetpp1[2][k]->SetBranchAddress("hiHFminus",&hiHFminus_1);
    jetpp1[2][k]->SetBranchAddress("hiHF",&hiHF_1);
    jetpp1[2][k]->SetBranchAddress("hiHFplus",&hiHFplus_1);
    jetpp1[2][k]->SetBranchAddress("hiHFplusEta4",&hiHFplusEta4_1);
    jetpp1[2][k]->SetBranchAddress("hiHFminusEta4",&hiHFminusEta4_1);
    jetpp1[2][k]->SetBranchAddress("pPAcollisionEventSelectionPA",&pPAcollisionEventSelectionPA_1);
    jetpp1[2][k]->SetBranchAddress("pHBHENoiseFilter",&pHBHENoiseFilter_1);
    //jetpp1[2][k]->SetBranchAddress("pprimaryvertexFilter",&pprimaryvertexFilter_1);
    //jetpp1[2][k]->SetBranchAddress("pVertexFilterCutGplus",&pVertexFilterCutGplus_1);
  
    jetpp1[2][k]->SetBranchAddress("nref",&nrefe_1);
    jetpp1[2][k]->SetBranchAddress("jtpt",&pt_1);
    jetpp1[2][k]->SetBranchAddress("jteta",&eta_1);
    jetpp1[2][k]->SetBranchAddress("jtphi",&phi_1);
    jetpp1[2][k]->SetBranchAddress("rawpt",&raw_1);
    jetpp1[2][k]->SetBranchAddress("jtpu",&jtpu_1);
    jetpp1[2][k]->SetBranchAddress("chargedMax",&chMax_1);
    jetpp1[2][k]->SetBranchAddress("chargedSum",&chSum_1);
    jetpp1[2][k]->SetBranchAddress("trackMax",&trkMax_1);
    jetpp1[2][k]->SetBranchAddress("trackSum",&trkSum_1);
    jetpp1[2][k]->SetBranchAddress("photonMax",&phMax_1);
    jetpp1[2][k]->SetBranchAddress("photonSum",&phSum_1);
    jetpp1[2][k]->SetBranchAddress("neutralMax",&neMax_1);
    jetpp1[2][k]->SetBranchAddress("neutralSum",&neSum_1);
    jetpp1[2][k]->SetBranchAddress("eSum",&eSum_1);
    jetpp1[2][k]->SetBranchAddress("eMax",&eMax_1);
    jetpp1[2][k]->SetBranchAddress("muSum",&muSum_1);
    jetpp1[2][k]->SetBranchAddress("muMax",&muMax_1);
    jetpp1[2][k]->SetBranchAddress("ecalSum",&ecalSum_1);
    jetpp1[2][k]->SetBranchAddress("hcalSum",&hcalSum_1);
    
    jetpp1[3][k]->SetBranchAddress("nref",&nrefe_2);
    jetpp1[3][k]->SetBranchAddress("jtpt",&pt_2);
    jetpp1[3][k]->SetBranchAddress("jteta",&eta_2);
    jetpp1[3][k]->SetBranchAddress("jtphi",&phi_2);
    jetpp1[3][k]->SetBranchAddress("rawpt",&raw_2);
    jetpp1[3][k]->SetBranchAddress("jtpu",&jtpu_2);
    jetpp1[3][k]->SetBranchAddress("chargedMax",&chMax_2);
    jetpp1[3][k]->SetBranchAddress("chargedSum",&chSum_2);
    jetpp1[3][k]->SetBranchAddress("trackMax",&trkMax_2);
    jetpp1[3][k]->SetBranchAddress("trackSum",&trkSum_2);
    jetpp1[3][k]->SetBranchAddress("photonMax",&phMax_2);
    jetpp1[3][k]->SetBranchAddress("photonSum",&phSum_2);
    jetpp1[3][k]->SetBranchAddress("neutralMax",&neMax_2);
    jetpp1[3][k]->SetBranchAddress("neutralSum",&neSum_2);
    jetpp1[3][k]->SetBranchAddress("eSum",&eSum_2);
    jetpp1[3][k]->SetBranchAddress("eMax",&eMax_2);
    jetpp1[3][k]->SetBranchAddress("muSum",&muSum_2);
    jetpp1[3][k]->SetBranchAddress("muMax",&muMax_2);
    jetpp1[3][k]->SetBranchAddress("ecalSum",&ecalSum_2);
    jetpp1[3][k]->SetBranchAddress("hcalSum",&hcalSum_2);
    
    if(dataset=="MC"){

      jetpp1[2][k]->SetBranchAddress("subid",&subid_1);
      jetpp1[3][k]->SetBranchAddress("subid",&subid_2);
      jetpp1[2][k]->SetBranchAddress("refpt",&refpt_1);
      jetpp1[3][k]->SetBranchAddress("refpt",&refpt_2);

    }
    

    jetpp1[2][k]->SetBranchAddress("HLT_PAJet40_NoJetID_v1",&jet40_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet40_NoJetID_v1_Prescl",&jet40_p_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet60_NoJetID_v1",&jet60_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet60_NoJetID_v1_Prescl",&jet60_p_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet80_NoJetID_v1",&jet80_1);
    jetpp1[2][k]->SetBranchAddress("HLT_PAJet80_NoJetID_v1_Prescl",&jet80_p_1);

    // jetpp1[2][k]->SetBranchAddress("id",&trgObj_id_1);
    // jetpp1[2][k]->SetBranchAddress("pt",&trgObj_pt_1);
    // jetpp1[2][k]->SetBranchAddress("eta",&trgObj_eta_1);
    // jetpp1[2][k]->SetBranchAddress("phi",&trgObj_phi_1);
    // jetpp1[2][k]->SetBranchAddress("mass",&trgObj_mass_1);
    
    /*
    jetpp1[2][k]->SetBranchAddress("nPFpart", &nPFpart);
    jetpp1[2][k]->SetBranchAddress("pfId", pfId);
    jetpp1[2][k]->SetBranchAddress("pfPt", pfPt);
    jetpp1[2][k]->SetBranchAddress("pfVsPtInitial", pfVsPtInitial);
    jetpp1[2][k]->SetBranchAddress("pfVsPt", pfVsPt);
    jetpp1[2][k]->SetBranchAddress("pfEta", pfEta);
    jetpp1[2][k]->SetBranchAddress("pfPhi", pfPhi);
    jetpp1[2][k]->SetBranchAddress("pfArea", pfArea);
    jetpp1[2][k]->SetBranchAddress("vn",&v_n);
    jetpp1[2][k]->SetBranchAddress("psin",&psi_n);
    jetpp1[2][k]->SetBranchAddress("sumpt",&sumpT);
    */

  }// radius loop
  cout<<"after branch declaration"<<endl;

  cout<<"after histogram declaration"<<endl;

  Float_t calopt, pfpt, deltar, chMax, phMax, neMax, muMax, eMax, chSum, phSum, neSum, muSum, eSum, hcalSum, ecalSum;
  Int_t  jet80, jet80_prescl, jet60, jet60_prescl, jet40, jet40_prescl; 
  Int_t evt_value;
  Int_t run_value;
  Int_t lumi_value;
  Float_t weight;
  Float_t subid, pfrawpt, calorawpt, pfrefpt, calorefpt, pfjtpu, calojtpu, vz, pthat, caloeta, calophi, pfeta, pfphi;
  
  TTree* matchJets = new TTree("matchedJets","Ntuple containing important information about matched jets");
  matchJets->Branch("calopt",&calopt,"calopt/F");   matchJets->Branch("phSum",&phSum,"phSum/F");
  matchJets->Branch("pfpt",&pfpt,"pfpt/F");         matchJets->Branch("neSum",&neSum,"neSum/F");
  matchJets->Branch("deltar",&deltar,"deltar/F");   matchJets->Branch("muSum",&muSum,"muSum/F");
  matchJets->Branch("chMax",&chMax,"chMax/F");      matchJets->Branch("eSum",&eSum,"eSum/F");
  matchJets->Branch("phMax",&phMax,"phMax/F"); 
  matchJets->Branch("neMax",&neMax,"neMax/F");      matchJets->Branch("jet80",&jet80,"jet80/I");
  matchJets->Branch("muMax",&muMax,"muMax/F");      matchJets->Branch("jet80_prescl",&jet80_prescl,"jet80_prescl/I");
  matchJets->Branch("eMax",&eMax,"eMax/F");         matchJets->Branch("jet60",&jet60,"jet60/I");
  matchJets->Branch("chSum",&chSum,"chSum/F");      matchJets->Branch("jet60_prescl",&jet60_prescl,"jet60_prescl/I");
  matchJets->Branch("jet40",&jet40,"jet40/I");      matchJets->Branch("jet40_prescl",&jet40_prescl,"jet40_prescl/I");
  matchJets->Branch("hcalSum",&hcalSum,"hcalSum/F");matchJets->Branch("ecalSum",&ecalSum,"ecalSum/F");
  matchJets->Branch("run_value",&run_value,"run_value/I");
  matchJets->Branch("evt_value",&evt_value,"evt_value/I");
  matchJets->Branch("lumi_value",&lumi_value,"lumi_value/I");
  matchJets->Branch("caloeta", &caloeta, "caloeta/F");
  matchJets->Branch("calophi", &calophi, "calophi/F");
  matchJets->Branch("pfeta", &pfeta, "pfeta/F");
  matchJets->Branch("pfphi", &pfphi, "pfphi/F");
  if(dataset=="MC") matchJets->Branch("subid",&subid,"subid/I"); matchJets->Branch("pfrawpt",&pfrawpt,"pfrawpt/F");
  if(dataset=="MC") matchJets->Branch("pfrefpt",&pfrefpt,"pfrefpt/F"); matchJets->Branch("pfjtpu",&pfjtpu,"pfjtpu/F");
  if(dataset=="MC") matchJets->Branch("calorefpt",&calorefpt,"calorefpt/F");
  if(dataset=="MC") matchJets->Branch("pthat",&pthat,"pthat/F"); if(dataset=="MC") matchJets->Branch("vz",&vz,"vz/F");
  if(dataset=="MC") matchJets->Branch("weight",&weight,"weight/F");
  matchJets->Branch("calorawpt",&calorawpt,"calorawpt/F");
  matchJets->Branch("calojtpu",&calojtpu,"calojtpu/F");
  
  TTree* unmatchPFJets = new TTree("unmatchedPFJets","Ntuple containing important information about unmatched PF jets");
  unmatchPFJets->Branch("phSum",&phSum,"phSum/F");
  unmatchPFJets->Branch("pfpt",&pfpt,"pfpt/F");         unmatchPFJets->Branch("neSum",&neSum,"neSum/F");
  unmatchPFJets->Branch("deltar",&deltar,"deltar/F");   unmatchPFJets->Branch("muSum",&muSum,"muSum/F");
  unmatchPFJets->Branch("chMax",&chMax,"chMax/F");      unmatchPFJets->Branch("eSum",&eSum,"eSum/F");
  unmatchPFJets->Branch("phMax",&phMax,"phMax/F");
  unmatchPFJets->Branch("neMax",&neMax,"neMax/F");      unmatchPFJets->Branch("jet80",&jet80,"jet80/I");
  unmatchPFJets->Branch("muMax",&muMax,"muMax/F");      unmatchPFJets->Branch("jet80_prescl",&jet80_prescl,"jet80_prescl/I");
  unmatchPFJets->Branch("eMax",&eMax,"eMax/F");         unmatchPFJets->Branch("jet60",&jet60,"jet60/I");
  unmatchPFJets->Branch("chSum",&chSum,"chSum/F");      unmatchPFJets->Branch("jet60_prescl",&jet60_prescl,"jet60_prescl/I");
  unmatchPFJets->Branch("jet40",&jet40,"jet40/I");      unmatchPFJets->Branch("jet40_prescl",&jet40_prescl,"jet40_prescl/I");
  unmatchPFJets->Branch("hcalSum",&hcalSum,"hcalSum/F");unmatchPFJets->Branch("ecalSum",&ecalSum,"ecalSum/F");
  unmatchPFJets->Branch("run_value",&run_value,"run_value/I");
  unmatchPFJets->Branch("evt_value",&evt_value,"evt_value/I");
  unmatchPFJets->Branch("lumi_value",&lumi_value,"lumi_value/I");
  unmatchPFJets->Branch("pfeta", &pfeta, "pfeta/F");
  unmatchPFJets->Branch("pfphi", &pfphi, "pfphi/F");
  if(dataset=="MC") unmatchPFJets->Branch("subid",&subid,"subid/I"); unmatchPFJets->Branch("pfrawpt",&pfrawpt,"pfrawpt/F");
  if(dataset=="MC") unmatchPFJets->Branch("pfrefpt",&pfrefpt,"pfrefpt/F"); unmatchPFJets->Branch("pfjtpu",&pfjtpu,"pfjtpu/F");
  if(dataset=="MC") unmatchPFJets->Branch("weight",&weight,"weight/F");
  if(dataset=="MC") unmatchPFJets->Branch("pthat",&pthat,"pthat/F"); if(dataset=="MC") unmatchPFJets->Branch("vz",&vz,"vz/F");
  
  TTree* unmatchCaloJets = new TTree("unmatchedCaloJets","Ntuple containing important information about unmatched Calo jets");
  unmatchCaloJets->Branch("phSum",&phSum,"phSum/F");
  unmatchCaloJets->Branch("calopt",&calopt,"calopt/F");   unmatchCaloJets->Branch("neSum",&neSum,"neSum/F");
  unmatchCaloJets->Branch("deltar",&deltar,"deltar/F");   unmatchCaloJets->Branch("muSum",&muSum,"muSum/F");
  unmatchCaloJets->Branch("chMax",&chMax,"chMax/F");      unmatchCaloJets->Branch("eSum",&eSum,"eSum/F");
  unmatchCaloJets->Branch("phMax",&phMax,"phMax/F");     
  unmatchCaloJets->Branch("neMax",&neMax,"neMax/F");      unmatchCaloJets->Branch("jet80",&jet80,"jet80/I");
  unmatchCaloJets->Branch("muMax",&muMax,"muMax/F");      unmatchCaloJets->Branch("jet80_prescl",&jet80_prescl,"jet80_prescl/I");
  unmatchCaloJets->Branch("eMax",&eMax,"eMax/F");         unmatchCaloJets->Branch("jet60",&jet60,"jet60/I");
  unmatchCaloJets->Branch("chSum",&chSum,"chSum/F");      unmatchCaloJets->Branch("jet60_prescl",&jet60_prescl,"jet60_prescl/I");
  unmatchCaloJets->Branch("jet40",&jet40,"jet40/I");      unmatchCaloJets->Branch("jet40_prescl",&jet40_prescl,"jet40_prescl/I");
  unmatchCaloJets->Branch("hcalSum",&hcalSum,"hcalSum/F");unmatchCaloJets->Branch("ecalSum",&ecalSum,"ecalSum/F");
  unmatchCaloJets->Branch("run_value",&run_value,"run_value/I");
  unmatchCaloJets->Branch("evt_value",&evt_value,"evt_value/I");
  unmatchCaloJets->Branch("lumi_value",&lumi_value,"lumi_value/I");
  unmatchCaloJets->Branch("caloeta", &caloeta, "caloeta/F");
  unmatchCaloJets->Branch("calophi", &calophi, "calophi/F");
  if(dataset=="MC") unmatchCaloJets->Branch("subid",&subid,"subid/I"); 
  if(dataset=="MC") unmatchCaloJets->Branch("calorefpt",&calorefpt,"calorefpt/F");
  if(dataset=="MC") unmatchCaloJets->Branch("pthat",&pthat,"pthat/F"); if(dataset=="MC") unmatchCaloJets->Branch("vz",&vz,"vz/F");
  if(dataset=="MC") unmatchCaloJets->Branch("weight",&weight,"weight/F");
  unmatchCaloJets->Branch("calorawpt",&calorawpt,"calorawpt/F");
  unmatchCaloJets->Branch("calojtpu",&calojtpu,"calojtpu/F");


  TH1F * hEvents = new TH1F("hEvents","",20,0,10);

  // define the histograms 

  // define the histograms necessary for that MC closure test.
  TH2F *hpp_mcclosure_matrix_HLT;
  TH2F *hpp_mcclosure_matrix;
  //TH2F *hpp_response;
  TH1F *hpp_mcclosure_JetComb_data;
  TH1F *hpp_mcclosure_data;
  TH1F *hpp_mcclosure_Jet80_data;
  TH1F *hpp_mcclosure_Jet60_data;
  TH1F *hpp_mcclosure_Jet40_data;
  TH1F *hpp_mcclosure_gen;
  TH1F *hpp_mcclosure_JetComb_gen;
  TH1F *hpp_mcclosure_Jet80_gen;
  TH1F *hpp_mcclosure_Jet60_gen;
  TH1F *hpp_mcclosure_Jet40_gen;
  
  hpp_mcclosure_matrix_HLT = new TH2F(Form("hpp_mcclosure_matrix_HLT_R%d_%s",radius,etaWidth),Form("Matrix for mcclosure refpt jtpt from Jet triggers R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
  hpp_mcclosure_matrix = new TH2F(Form("hpp_mcclosure_matrix_R%d_%s",radius,etaWidth),Form("Matrix for mcclosure refpt jtpt from Jet triggers R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt,nbins_pt,boundaries_pt);
  //cout<<"C"<<endl;
  hpp_mcclosure_data = new TH1F(Form("hpp_mcclosure_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_JetComb_data = new TH1F(Form("hpp_mcclosure_JetComb_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger combined  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet80_data = new TH1F(Form("hpp_mcclosure_Jet80_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger 80  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet60_data = new TH1F(Form("hpp_mcclosure_Jet60_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger 60  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet40_data = new TH1F(Form("hpp_mcclosure_Jet40_data_R%d_%s",radius,etaWidth),Form("data for unfolding mc closure test trigger 40  R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);

  hpp_mcclosure_gen = new TH1F(Form("hpp_mcclosure_gen_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_JetComb_gen = new TH1F(Form("hpp_mcclosure_gen_JetComb_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger combined R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet80_gen = new TH1F(Form("hpp_mcclosure_gen_Jet80_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger 80 R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet60_gen = new TH1F(Form("hpp_mcclosure_gen_Jet60_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger 60 R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);
  hpp_mcclosure_Jet40_gen = new TH1F(Form("hpp_mcclosure_gen_Jet40_R%d_%s",radius,etaWidth),Form("gen spectra for unfolding mc closure test trigger 40 R%d %s ",radius,etaWidth),nbins_pt,boundaries_pt);

  
  // declare the 2d calo and pf candidate vectors, deltaR_calovsPF is going to be a 3d vector like so:
  // calo jet on x axis, pf jet on y axis, and delta R, calopT, pfpT on z axis.
  // we also need to add in the trigger information here since we need to know what trigger the matching comes from. maybe i can run that later as an added check. for now just to see if the algorithm is working should try to run things. 
  //vector<vector<double> > caloJet;
  //vector<vector<double> > pfJet;

  // start the loop process

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

    Long64_t nentries = jetpp1[2][k]->GetEntries();
    //Long64_t nentries = 100;

    Long64_t fentries= 1;
    if(dataset=="MC"){
      TEventList *el = new TEventList("el","el");
      double pthat_upper = boundaries_pthat[startfile + 1];
      stringstream selection; selection<<"pthat<"<<pthat_upper;
      
      jetpp1[2][k]->Draw(">>el",selection.str().c_str());
      fentries = el->GetN();
      delete el;
    }
    
    for(Long64_t nentry = 0; nentry<nentries;nentry++){
      if(printDebug)cout<<"event no = "<<nentry<<endl;
      for(int t = 0;t<N;t++)  jetpp1[t][k]->GetEntry(nentry);
      
      hEvents->Fill(0);

      //int centBin = findBin(hiBin_1);
      //if(centBin==-1) continue;
      //if(pHBHENoiseFilter_1==0 || pcollisionEventSelection_1==0) continue; 
      if(pPAcollisionEventSelectionPA_1==0) continue; 
      hEvents->Fill(1);
      if(dataset=="Data") if(pHBHENoiseFilter_1==0 ) continue;
      hEvents->Fill(2);

      if(fabs(vz_1)>15) continue;
      //cout<<"passed the selection"<<endl;

      hEvents->Fill(3);

      weight = 1;

      if(dataset=="MC"){
	
	int pthatBin = hpthatBin->FindBin(pthat_1);
	
	double scale = (double)(xsection[pthatBin-1]-xsection[pthatBin])/fentries;

	Float_t weight_vz = fVzPP->Eval(vz_1);
	weight = scale*weight_vz;

      }

      // start doing the search for the match. - best thing to do would be to create a 2D match delta R matrix with each calo jet and pf jet. Once thats done - find the smallest entry in that matrix. the i,j of that smallest entry are matched. now remove the row i and column j and then we have a new distance matrix. where we need to find the smallest element again. keep doing this till we have either no rows or no columns.  

      // declare the necessary variables:
      Float_t deltaRCaloPF = 0;
      Float_t calojet_eta = 0;
      Float_t calojet_phi = 0;
      Float_t calojet_pt = 0;
      Float_t pfjet_eta = 0;
      Float_t pfjet_phi = 0;
      Float_t pfjet_pt = 0;
      
      vector<vector<double> > matchedCaloPFJet;
      vector<vector<vector<double> > > deltaR_calovsPF;
      int calosize = 0;
      Float_t deltapT = 0;
      int calomatchcounter = 0;
      
      for(int g = 0;g<nrefe_1;g++){
	
	calojet_eta = eta_1[g];
	calojet_phi = phi_1[g];
	calojet_pt = pt_1[g];
	
	if(calojet_pt < CALOPTCUT) continue;
	if(TMath::Abs(calojet_eta) > 2.0) continue;
	
	int pfmatchcounter = 0;
	deltaR_calovsPF.push_back(vector<vector<double> > ());
	
	calosize++;
	
	for(int j = 0;j<nrefe_2;j++){

	  pfjet_eta = eta_2[j];
	  pfjet_phi = phi_2[j];
	  pfjet_pt = pt_2[j];

	  if(pfjet_pt < PFPTCUT) continue;
	  if(TMath::Abs(pfjet_eta) > 2.0) continue;

	  deltaRCaloPF = Calc_deltaR(calojet_eta, calojet_phi, pfjet_eta, pfjet_phi);
	  
	  // if(deltaRCaloPF > (Float_t)deltaR/10) continue;
	  deltapT = TMath::Abs(calojet_pt - pfjet_pt);

	  deltaR_calovsPF[calomatchcounter].push_back(vector<double> ());
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(deltaRCaloPF); // 0 - delta R
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(deltapT); // 1 - delta pT	  
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(g); // 2 - calo counter 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(calojet_pt); // 3 - calo jet pT 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(j); // 4 - pf counter 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(pfjet_pt); // 5 - pf jet pT
	  // this will have the candidate variables for the matched jets. 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chMax_2[j]); // 6 - chMax 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phMax_2[j]); // 7 - phMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neMax_2[j]); // 8 - neMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muMax_2[j]); // 9 - muMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eMax_2[j]); // 10 - eMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chSum_2[j]); // 11 - chSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phSum_2[j]); // 12 - phSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neSum_2[j]); // 13 - neSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muSum_2[j]); // 14 - muSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eSum_2[j]); // 15 - eSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(0.0); // 16 - this is the variable which will tell me if a jet is matched.
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(hcalSum_2[j]); // 17 - hcalSum 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(ecalSum_2[j]); // 18 - hcalSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(raw_2[j]); // 19 - raw pt
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(jtpu_2[j]); // 20 - jtpu
	  //all the following candidate information is for the calo jets 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chMax_1[g]); // 21 - chMax 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phMax_1[g]); // 22 - phMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neMax_1[g]); // 23 - neMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muMax_1[g]); // 24 - muMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eMax_1[g]); // 25 - eMax
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(chSum_1[g]); // 26 - chSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(phSum_1[g]); // 27 - phSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(neSum_1[g]); // 28 - neSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(muSum_1[g]); // 29 - muSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(eSum_1[g]); // 30 - eSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(hcalSum_1[g]); // 31 - hcalSum 
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(ecalSum_1[g]); // 32 - hcalSum
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(raw_1[g]); // 33 - raw pt
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(jtpu_1[g]); // 34 - jtpu

	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(pfjet_eta); // 35 - pf eta
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(pfjet_phi); // 36 - pf phi
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(calojet_eta); // 37 - calo eta
	  deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(calojet_phi); // 38 - calo phi
	  
	  if(dataset=="MC") {
	    deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(refpt_1[g]); // 39 calo ref pt 
	    deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(refpt_2[j]); // 40 pf ref pt 
	    deltaR_calovsPF[calomatchcounter][pfmatchcounter].push_back(subid_2[j]); // 41 - subid only for MC
	    
	  }
	  
	  
	  ++pfmatchcounter;

	}// pf jet loop
	++calomatchcounter;
	
      }// calo jet loop

      // set the event variables before proceeding to the matching. 
      jet80 = jet80_1;
      jet80_prescl = jet80_p_1;
      jet60 = jet60_1;
      jet60_prescl = jet60_p_1;
      jet40 = jet40_1;
      jet40_prescl = jet40_p_1;
      run_value = run_1;
      evt_value = evt_1;
      lumi_value = lumi_1;
      vz = vz_1;
      if(dataset=="MC")pthat = pthat_1;

      if(printDebug)cout<<deltaR_calovsPF.size()<<endl;
      if(printDebug)for(int a = 0;a<deltaR_calovsPF.size();++a) cout<<deltaR_calovsPF[a].size()<<" ";
      if(printDebug)cout<<endl<<"going to small matching"<<endl;
      
      // now that we have the 2D matrix, lets find the smallest delta R element from that and fill in the value of the 

      Float_t smallDeltaR = 10;
      Int_t small_calo = 0;
      Int_t small_pf = 0;

      for(int c = 0;c<deltaR_calovsPF.size();++c){
	// if(printDebug)cout<<"going through all rows in the  matrix "<<c<<endl;
	for(int a = 0;a<deltaR_calovsPF.size();++a){
	  // if(printDebug)cout<<"calo jet iteration "<<a<<endl;
	  for(int b = 0;b<deltaR_calovsPF[a].size();++b){
	    // if(printDebug)cout<<"pf jet iteration "<<b<<endl;
	    
	    if(deltaR_calovsPF[a][b][16]==1){ 
	      break;
	    }
	    if(smallDeltaR > deltaR_calovsPF[a][b][0]){
	      
	      smallDeltaR = deltaR_calovsPF[a][b][0];
	      small_calo = a;
	      small_pf = b;
	      
	    }
	  }
	}
	
	if(smallDeltaR > (Float_t)deltaR/10 || deltaR_calovsPF[small_calo][small_pf][16] == 1) continue;
	
	calopt = deltaR_calovsPF[small_calo][small_pf][3];
	pfpt = deltaR_calovsPF[small_calo][small_pf][5];
	if(dataset=="MC"){
	  pfrefpt = deltaR_calovsPF[small_calo][small_pf][40];
	  calorefpt = deltaR_calovsPF[small_calo][small_pf][39];
	  subid = deltaR_calovsPF[small_calo][small_pf][41]; 
	}
	pfrawpt = deltaR_calovsPF[small_calo][small_pf][19]; 
	calorawpt = deltaR_calovsPF[small_calo][small_pf][33]; 
	pfjtpu = deltaR_calovsPF[small_calo][small_pf][20]; 
	calojtpu = deltaR_calovsPF[small_calo][small_pf][34];
	deltar = deltaR_calovsPF[small_calo][small_pf][0];
	chMax = deltaR_calovsPF[small_calo][small_pf][6];
	phMax = deltaR_calovsPF[small_calo][small_pf][7];
	neMax = deltaR_calovsPF[small_calo][small_pf][8];
	muMax = deltaR_calovsPF[small_calo][small_pf][9];
	eMax = deltaR_calovsPF[small_calo][small_pf][10];
	chSum = deltaR_calovsPF[small_calo][small_pf][11];
	phSum = deltaR_calovsPF[small_calo][small_pf][12];
	neSum = deltaR_calovsPF[small_calo][small_pf][13];
	muSum = deltaR_calovsPF[small_calo][small_pf][14];
	eSum = deltaR_calovsPF[small_calo][small_pf][15];
	pfeta = deltaR_calovsPF[small_calo][small_pf][35];
	pfphi = deltaR_calovsPF[small_calo][small_pf][36];
	caloeta = deltaR_calovsPF[small_calo][small_pf][37];
	calophi = deltaR_calovsPF[small_calo][small_pf][38];
	hcalSum = deltaR_calovsPF[small_calo][small_pf][17];
	ecalSum = deltaR_calovsPF[small_calo][small_pf][18];
	
	//matchJets->Fill();
	
	if(c==0) hEvents->Fill(4);
	  
	if(dataset=="MC"){
	  // fill in the matched histograms with the Jet ID cuts:
	  if(subid!=0) continue;
	
	  Float_t Sumcand = chSum + phSum + neSum + muSum;

	  //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	    if(nentry%2==1) {
	      hpp_mcclosure_matrix->Fill(pfrefpt, pfpt, weight);
	      hpp_mcclosure_gen->Fill(pfrefpt, weight);
	    }
	    if(nentry%2==1) {
	      hpp_mcclosure_data->Fill(pfpt, weight);
	    }
	    //}
	  
	  if(jet40 == 1 && jet60==0 && jet80 == 0){

	    //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	      }
	      //}

	    // if(calopt/pfpt > 0.85) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	    //   }
	    // }

	    // if(calopt/pfpt <= 0.5 && eMax/Sumcand < 0.05) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	    //   }
	    // }
	  
	  }

	  if(jet60 == 1 && jet80 == 0){

	    //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	      }
	      //}

	    // if(calopt/pfpt > 0.85) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	    //   }
	    // }

	    // if(calopt/pfpt <= 0.5 && eMax/Sumcand < 0.05) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	    //   }
	    // }
	  
	  
	  }

	  if(jet80==1){

	    //if(calopt/pfpt > 0.5 && calopt/pfpt <= 0.85 && eMax/Sumcand < ((Float_t)18/7 *(Float_t)calopt/pfpt - (Float_t)9/7)){
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	      }
	      //}

	    // if(calopt/pfpt > 0.85) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	    //   }
	    // }

	    // if(calopt/pfpt <= 0.5 && eMax/Sumcand < 0.05) {
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
	    // 	hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	    //   }
	    //   if(nentry%2==1) {
	    // 	hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	    //   }
	    // }
	  
	  
	  }

	}


	smallDeltaR = 10;
	for(int b = 0;b<deltaR_calovsPF[small_calo].size();++b){
	  deltaR_calovsPF[small_calo][b][16] = 1; // by setting this value you effectively remove that calo and pf jet for further matching // removes the column for getting matched. 
	}
	for(int a = 0;a<deltaR_calovsPF.size();++a){
	  deltaR_calovsPF[a][small_pf][16] = 1; // this removes the whole row from getting matched later. 
	}

      }// running it for the number of calo jets: 

      if(printDebug)cout<<"now going to find unmatched pf jets"<<endl;
      // ok Now lets find the un-matched jets and fill the necessary unmatched ntuple:

      if(deltaR_calovsPF.size() == 0) continue;
      for(int b = 0;b<deltaR_calovsPF[0].size();++b){
	if(printDebug)cout<<"pf jet iteration "<<b<<endl;

	if(deltaR_calovsPF[0][b][16] == 1) continue;

	pfpt = deltaR_calovsPF[0][b][5];
	deltar = deltaR_calovsPF[0][b][0];
	if(dataset=="MC"){
	  pfrefpt = deltaR_calovsPF[0][b][40];
	  subid = deltaR_calovsPF[0][b][41]; 
	}
	pfrawpt = deltaR_calovsPF[0][b][19]; 
	pfjtpu = deltaR_calovsPF[0][b][20]; 
	chMax = deltaR_calovsPF[0][b][6];
	phMax = deltaR_calovsPF[0][b][7];
	neMax = deltaR_calovsPF[0][b][8];
	muMax = deltaR_calovsPF[0][b][9];
	eMax = deltaR_calovsPF[0][b][10];
	chSum = deltaR_calovsPF[0][b][11];
	phSum = deltaR_calovsPF[0][b][12];
	neSum = deltaR_calovsPF[0][b][13];
	muSum = deltaR_calovsPF[0][b][14];
	eSum = deltaR_calovsPF[0][b][15];
	pfeta = deltaR_calovsPF[0][b][35];
	pfphi = deltaR_calovsPF[0][b][36];
	hcalSum = deltaR_calovsPF[0][b][17];
	ecalSum = deltaR_calovsPF[0][b][18];
	
	//unmatchPFJets->Fill();

	if(b==0) hEvents->Fill(5);

	if(dataset=="MC"){
	  // fill in the matched histograms with the Jet ID cuts:
	  if(subid!=0) continue;
	
	  Float_t Sumcand = chSum + phSum + neSum + muSum;

	  //if(eMax/Sumcand < 0.05) {
	    if(nentry%2==1) {
	      hpp_mcclosure_matrix->Fill(pfrefpt, pfpt, weight);
	      hpp_mcclosure_gen->Fill(pfrefpt, weight);
	    }
	    if(nentry%2==1) {
	      hpp_mcclosure_data->Fill(pfpt, weight);
	    }
	    //}
	  
	  
	  if(jet40 == 1 && jet60 == 0 && jet80 == 0){

	    //if(eMax/Sumcand < 0.05) {
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet40_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet40_data->Fill(pfpt, weight);
	      }
	      //}
	  
	  }

	  if(jet60 == 1 && jet80 == 0){

	    //if(eMax/Sumcand < 0.05) {
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet60_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet60_data->Fill(pfpt, weight);
	      }
	      //}
	  
	  
	  }

	  if(jet80==1){

	    //if(eMax/Sumcand < 0.05) {
	      if(nentry%2==1) {
		hpp_mcclosure_matrix_HLT->Fill(pfrefpt, pfpt, weight);
		hpp_mcclosure_Jet80_gen->Fill(pfrefpt, weight);
	      }
	      if(nentry%2==1) {
		hpp_mcclosure_Jet80_data->Fill(pfpt, weight);
	      }
	      //}
	  
	  
	  }
	}

	
      }// unmatched PF jets
      
      if(printDebug)cout<<"now going to find unmatched calo jets"<<endl;

      if(deltaR_calovsPF[0].size() == 0) continue;
      
      for(int a = 0;a<deltaR_calovsPF.size();++a){
	if(printDebug)cout<<"calo jet iteration "<<a<<endl;

	if(deltaR_calovsPF[a][0][16] == 1) continue;

	calopt = deltaR_calovsPF[a][0][3];
	deltar = deltaR_calovsPF[a][0][0];
	if(dataset=="MC"){
	  calorefpt = deltaR_calovsPF[a][0][39];
	  subid = deltaR_calovsPF[a][0][41]; 
	}
	calorawpt = deltaR_calovsPF[a][0][33]; 
	calojtpu = deltaR_calovsPF[a][0][34]; 
	chMax = deltaR_calovsPF[a][0][21];
	phMax = deltaR_calovsPF[a][0][22];
	neMax = deltaR_calovsPF[a][0][23];
	muMax = deltaR_calovsPF[a][0][24];
	eMax = deltaR_calovsPF[a][0][25];
	chSum = deltaR_calovsPF[a][0][26];
	phSum = deltaR_calovsPF[a][0][27];
	neSum = deltaR_calovsPF[a][0][28];
	muSum = deltaR_calovsPF[a][0][29];
	eSum = deltaR_calovsPF[a][0][30];
	caloeta = deltaR_calovsPF[a][0][37];
	calophi = deltaR_calovsPF[a][0][38];
	hcalSum = deltaR_calovsPF[a][0][31];
	ecalSum = deltaR_calovsPF[a][0][32];
	
	//unmatchCaloJets->Fill();

      }

    }// event loop 

  }// radius loop


  // matchJets->Write();
  // matchJets->Print();
  // unmatchPFJets->Write();
  // unmatchPFJets->Print();
  // unmatchCaloJets->Write();
  // unmatchCaloJets->Print();


  hpp_mcclosure_JetComb_data->Add(hpp_mcclosure_Jet80_data);
  hpp_mcclosure_JetComb_data->Add(hpp_mcclosure_Jet60_data);
  hpp_mcclosure_JetComb_data->Add(hpp_mcclosure_Jet40_data);

  hpp_mcclosure_JetComb_gen->Add(hpp_mcclosure_Jet80_gen);
  hpp_mcclosure_JetComb_gen->Add(hpp_mcclosure_Jet60_gen);
  hpp_mcclosure_JetComb_gen->Add(hpp_mcclosure_Jet40_gen);

  hpp_mcclosure_matrix_HLT->Write();
  hpp_mcclosure_matrix->Write();
  hpp_mcclosure_JetComb_data->Write();
  hpp_mcclosure_data->Write();
  hpp_mcclosure_Jet80_data->Write();
  hpp_mcclosure_Jet60_data->Write();
  hpp_mcclosure_Jet40_data->Write();
  hpp_mcclosure_JetComb_gen->Write();    
  hpp_mcclosure_gen->Write();    
  hpp_mcclosure_Jet80_gen->Write();
  hpp_mcclosure_Jet60_gen->Write();
  hpp_mcclosure_Jet40_gen->Write();
    

  hEvents->Write();

  timer.Stop();
  cout<<"Macro finished: "<<endl;
  cout<<"CPU time (min)  = "<<(Float_t)timer.CpuTime()/60<<endl;
  cout<<"Real time (min) = "<<(Float_t)timer.RealTime()/60<<endl;
  
}
//call this macro via root -l -b -q AddBranchEventsMT2tree.C++
//This code takes a text file containing run:lumisection:event:taggervalue (tagger value is a new filter you want to add to your tree),
//an old MT2tree file that does not contain that tagger
// and creates a new MT2tree file, which is a copy of the old one and contains additionally that tagger.
void AddBranchEventsMT2tree() {
// Example of Root macro to copy a subset of a Tree to a new Tree
// Only selected entries are copied to the new Tree.
// The input file has been generated by the program in $ROOTSYS/test/Event
// with   Event 1000 1 99 1
//Author: Rene Brun
   
//modified: Hannsjoerg Weber, 28/08/2013

   //make cleaning
   // get eventlist to clean
   // vector contains <run, < <lumisection, event>, taggervalue > >
   vector<pair<pair<int,pair<int,int> >,float> > rls; rls.clear();
   char buffer[200];
   ifstream filterdat("/shome/haweber/AODFiles_MT2SR/taggerlist/ControlRegionSinglePhotonPart1.dat");
   while( filterdat.getline(buffer, 200, '\n') ){
	int rrun(-1), lls(-1), eevent(-1), d1(-1); float ttagger(-1);
	sscanf(buffer, "*\t%d\t*\t%d\t*\t%d\t*\t%d\t*\t%f", &d1, &eevent, &lls, &rrun, &ttagger);
	pair<int,int> t1(lls,eevent);
	pair<int,pair<int,int> > t2(rrun,t1);
        pair<pair<int,pair<int,int> >, float> t3(t2,ttagger);
	rls.push_back(t3);
   }
cout << "Events for filtering " << rls.size() << endl;

   // get the old rootfile including events that should be tagged and define new event file including tagger variable
   TString oldfilename = "/shome/haweber/MT2Analysis/MT2trees/MT2_V02-03-02/20130914_8TeV_1g_removed/lowHT/SinglePhoton-Run2012C-PromptReco-v2-2.root";
   TString newfilename = "/shome/haweber/MT2Analysis/MT2trees/MT2_V02-03-02/20130914_8TeV_1g_removed/lowHT/SinglePhoton-Run2012C-PromptReco-v2-2_Filter.root";

	// if you want to apply an additional event selection, define cuts here
	std::ostringstream cutStream;
	std::ostringstream cutStreamBase;
	cutStream << " " 
		<< "NTausIDLoose3Hits+NMuons+NEles==0"                   << "&&"
		<< "misc.Jet0Pass==1&&misc.Jet1Pass==1"                  << "&&"
		<< "misc.Vectorsumpt<70&& misc.MinMetJetDPhi4Pt40 >0.3";
		cutStream << "&&((misc.MET>200&&misc.HT<=750&&misc.HT>=450&&misc.MT2>200)||(misc.HT>750&&misc.MET>30&&misc.MT2>=100))";
	cutStreamBase << " " 
      << "misc.PassJet40ID ==1"                             << "&&"
      << "(misc.HBHENoiseFlag == 0 || misc.ProcessID==10)"  << "&&" // not there for fastsim (i.e. signal)
      << "misc.CSCTightHaloIDFlag == 0"                     << "&&"
      << "misc.trackingFailureFlag==0"                      << "&&"
      << "misc.eeBadScFlag==0"                              << "&&"
      << "misc.EcalDeadCellTriggerPrimitiveFlag==0"         << "&&"
      << "misc.TrackingManyStripClusFlag==0"                << "&&"
      << "misc.TrackingTooManyStripClusFlag==0"             << "&&"
      << "misc.TrackingLogErrorTooManyClustersFlag==0"      << "&&"
      << "misc.CrazyHCAL==0";

	TString cuts = cutStream.str().c_str();
	TString basecuts = cutStreamBase.str().c_str();
//	TString myCuts = cuts + "&&" + basecuts;// if cuts should be applied DO NOT comment this line
	TString myCuts = "";// if no cuts should be applied DO NOT comment this line

   //Get old file, old tree and set top branch address
   TFile *oldfile = new TFile(oldfilename.Data());
   TTree *oldtree = (TTree*)oldfile->Get("MassTree");

   MT2tree* fMT2tree = new MT2tree();
   oldtree->SetBranchAddress("MT2tree", &fMT2tree);
   Long64_t nentries =  oldtree->GetEntries();
   Long64_t nbytes = 0, nb = 0;
   int nev =0;

   //Create a new file + a clone of old tree in new file
   Float_t TOBTECTagger(-1);
   Float_t HOTagger(-1);
   Bool_t ExtraBeamHaloFilter(false);
   TFile *newfile = new TFile(newfilename.Data(),"RECREATE");
   TTree *newtree = oldtree->CloneTree(0);//clone all branches, but no event
   TBranch *newBranch  = newtree->Branch("TOBTECTagger", &TOBTECTagger, "TOBTECTagger/F");
   TBranch *newBranch2 = newtree->Branch("ExtraBeamHaloFilter", &ExtraBeamHaloFilter, "ExtraBeamHaloFilter/O");
   TBranch *newBranch3 = newtree->Branch("HOTagger", &HOTagger, "HOTagger/F");

   oldtree->Draw(">>selList", myCuts);
   TEventList *myEvtList = (TEventList*)gDirectory->Get("selList");
   oldtree->SetEventList(myEvtList);
   int counter=0;
   int numEvt = myEvtList->GetN();
   int printEvt = 100000;
   if(myEvtList->GetN()<1000000) printEvt = myEvtList->GetN()/25;
   cout << "Filtering done, size=" <<myEvtList->GetN()  << endl;
   while(myEvtList->GetEntry(counter++) !=-1){
	int jentry = myEvtList->GetEntry(counter-1);
	nb =  oldtree->GetEntry(jentry);   nbytes += nb;
	oldtree->SetBranchAddress("MT2tree", &fMT2tree);
	if(counter%printEvt==0) cout << "Process event " << counter << endl;	

	//make cleaning
	bool keep = true;
	int p=-1;
	for(int nn=0; nn<rls.size();++nn){
		if((rls[nn].first).first!=fMT2tree->misc.Run) continue; // --> run over matching 
		if(((rls[nn].first).second).first!=fMT2tree->misc.LumiSection) continue; // --> LS over matching 
		if(fMT2tree->misc.Event>0){
			if(((rls[nn].first).second).second==fMT2tree->misc.Event) { 
				TOBTECTagger = rls[nn].second;
				keep=false; p=nn; break;
			}
		}
		else{	//if event > INT_MAX correct overflow back.
			int evtt = ((rls[nn].first).second).second + INT_MAX;
			evtt = evtt - INT_MAX;
			if(evtt==fMT2tree->misc.Event) {keep=false; p=nn; break;}
		}
	}
	//two additional taggers
	bool beamhalo = false;
	float ho = fMT2tree->misc.MET/fMT2tree->misc.CaloMETRaw;
	if(fMT2tree->misc.CaloMETRaw<=0) ho=999.;
	HOTagger = ho;
	if(fMT2tree->jet[0].lv.DeltaPhi(fMT2tree->jet[1].lv)<0.2 && !(fMT2tree->jet[0].isPFIDMedium)) beamhalo = true;
	ExtraBeamHaloFilter = beamhalo;

	if(keep) TOBTECTagger = -1;
	newtree->Fill();
	if(!keep){
		//remove event from rls vector --> increases speed.
		int tt = p;
		rls.erase(rls.begin()+p);
	}
   }
   newtree->Print();
   newtree->AutoSave();
   delete oldfile;
   delete newfile;
}
//GetBEfficiency input histograms for pt binned only (1d), pt and eta binned (2d), pt binned in eta slices (1d)
void GetBEfficiency_InputHistograms(){
	gROOT->ProcessLine(".x SetStyle_PRD.C");

	gROOT->SetStyle("Plain");
	gStyle->SetOptStat(0);

	bool runQCD   = false;//set false if want to save some time //useful if look at high MT2
	bool onlyQCD  = false;//set false if want to save some time //useful if look at high MT2
	bool calcsusy = true;//at the moment has no genflavour // skip it
	bool runData  = false;//set false if want to save some time //at the moment not used, only for xchecks

	bool fHT      = true;//to change  htskim
	bool fMET     = false; //to change metskim
	bool fChange  = true; //use this only if you want to change the skims by hand

	//not implemented here, yet
	bool ttbarxsecup   = false;
	bool ttbarxsecdown = false;
	bool wjetsxsecup   = false;
	bool wjetsxsecdown = false;

//	TString samples         = "/shome/haweber/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samples_Stop_53X_0bMET30_corr.dat";//Dileptons
//	TString samples         = "/shome/haweber/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samples_type1MET_CHS_53X_MET.dat";//MET
//	TString samples         = "/shome/haweber/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samples_type1MET_CHS_53X_HT.dat";//HT
//	TString samples         = "/shome/haweber/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samples_type1MET_CHS_53X_MET_newTTbar.dat";//MET
	TString samples         = "/dataLOCAL/paktinat/Projects/MT2/MT2_V02-03-02/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samplesMine.dat";//HT
//	TString samples         = "/shome/haweber/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samples_type1MET_CHS_53X_METorHT.dat";//HT
	TString outputdir 	= "/dataLOCAL/paktinat/Projects/MT2/MT2_V02-03-02/MT2Analysis/Code/Efficiencies/InputHistos/";//if not empty end with slash
//	TString outputdir 	= "/shome/haweber/MT2Analysis_8TeV/Code/Efficiencies/test/InputHistos/";//if not empty end with slash
	Util::MakeOutputDir(outputdir);
//	TString outputname 	= "BEfficiencies_histos_DileptonicStop_CSVM.root";
//	TString outputname 	= "BEfficiencies_histos_ge2jets_0l_CSVM_HT750orMET200_MinDPhiPt40_noQCD.root";
//	TString outputname 	= "BEfficiencies_histos_ge2jets_0l_CSVM_HT750orMET200_MinDPhi4_noQCD.root";
//	TString outputname 	= "BEfficiencies_histos_ge2jets_CSVM_HT750orMET200_MinDPhiPt40_noQCD.root";
//	TString outputname 	= "BEfficiencies_histos_ge2jets_CSVM_HT750orMET200_MinDPhi4.root";
//	TString outputname 	= "BEfficiencies_histos_ge2jets_CSVM_HT450andMET200_MinDPhi4_newTTbar.root";
	TString outputname 	= "BEfficiencies_histos_ge2jets_CSVM_HT750andMET30_MinDPhi4_newTTbar_noQCD.root";

//	TString outputname 	= "BEfficiencies_histos_HT_ge3jets_0l_CSVM_allMT2_MinDPhi40.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge3jets_0l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge3jets_ge1l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge6jets_0l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge6jets_ge1l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_HT_eq2jets_0l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_HT_eq2jets_ge1l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge3jets_0l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge3jets_ge1l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge6jets_0l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge6jets_ge1l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_eq2jets_0l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_eq2jets_ge1l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge3jets_0l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge3jets_ge1l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge6jets_0l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_ge6jets_ge1l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_eq2jets_0l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_HT_eq2jets_ge1l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge3jets_0l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge3jets_ge1l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge6jets_0l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge6jets_ge1l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_MET_eq2jets_0l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_MET_eq2jets_ge1l_CSVM_allMT2.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge3jets_0l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge3jets_ge1l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge6jets_0l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge6jets_ge1l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_eq2jets_0l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_eq2jets_ge1l_CSVM_MT2lt125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge3jets_0l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge3jets_ge1l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge6jets_0l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_ge6jets_ge1l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_eq2jets_0l_CSVM_MT2ge125.root";
//	TString outputname 	= "BEfficiencies_histos_MET_eq2jets_ge1l_CSVM_MT2ge125.root";

	int btaggername = 4; //0: TCHE, 1: TCHP, 2: SSVHE, 3: SSVHP, 4: CSV, 5: JP
	//CSV: L: 0.244, M: 0.679, T: 0.898
	//JP:  L: 0.275, M: 0.545, T: 0.790
	//TCHPT: 3.41, SSVHEM: 1.74, SSVHPT: 2.00
	double bdiscr_value = 0.679;
	int WP = 1;// WP: 0: loose, 1: medium, 2: tight
	double bpt = 20.;
	double beta = 2.4;
	const int Nptbins   = 17; double ptbins[Nptbins+1]     = {20, 30, 40, 50, 60, 70, 80, 100, 120, 160, 210, 260, 320, 400, 500, 600, 800, 1000};
//	const int Nptbins   = 16; double ptbins[Nptbins+1]     = {20, 30, 40, 50, 60, 70, 80, 100, 120, 160, 210, 260, 320, 400, 500, 670, 750};
	const int NetabinsL =  4; double etabinsL[NetabinsL+1] = {0.0, 0.5, 1.0, 1.5, 2.4};
	const int NetabinsM =  3; double etabinsM[NetabinsM+1] = {0.0, 0.8, 1.6, 2.4};
	const int NetabinsT =  1; double etabinsT[NetabinsT+1] = {0.0, 2.4};

	map<string, TH2D*> histos2d;
	map<string, TH1D*> histospt;

	const int sampletypesize = 10;
	string sample_type[sampletypesize] = {"QCD", "WJets", "ZJets", "TTbar", "SingleTop", "Other", "mc", "mcNOqcd", "susy", "data"};//same as type in samples.dat

	const int prefixsize = 10;
	string prefix[10] = {"B", "C", "L", "NonB", "All", "BTaggedB", "BTaggedC", "BTaggedL", "BTaggedNonB", "BTaggedAll"};


	for(int is = 0; is<sampletypesize; ++is){
	   for(int js = 0; js<10; ++js){
		string hs = string("_") + sample_type[is];
		string mapname;
		mapname = prefix[js] + "Jet" + hs;
		if(WP==0 && histos2d.count(mapname) == 0 ) histos2d[mapname] = new TH2D((mapname+string("_2d")).c_str(), "eff", Nptbins, ptbins, NetabinsL, etabinsL);
		if(WP==1 && histos2d.count(mapname) == 0 ) histos2d[mapname] = new TH2D((mapname+string("_2d")).c_str(), "eff", Nptbins, ptbins, NetabinsM, etabinsM);
		if(WP==2 && histos2d.count(mapname) == 0 ) histos2d[mapname] = new TH2D((mapname+string("_2d")).c_str(), "eff", Nptbins, ptbins, NetabinsT, etabinsT);
		if(         histospt.count(mapname) == 0 ) histospt[mapname] = new TH1D( mapname.c_str(),                "eff", Nptbins, ptbins);
	   }
	}
	
	for(map<string,TH2D*>::iterator h=histos2d.begin(); h!=histos2d.end();++h){
		//cout << "Load " << h->first << endl;
		h->second->Sumw2();}
	for(map<string,TH1D*>::iterator h=histospt.begin(); h!=histospt.end();++h){
		//cout << "Load " << h->first << endl;
		h->second->Sumw2();}

	cout << "Histograms loaded" << endl;
	
	std::ostringstream cutStream;
	cutStream       << " " 	  
     << "(misc.ProcessID!=6||(misc.Event!=1689009&&misc.Event!=2275452&&misc.Event!=1946785&&misc.Event!=1936763&&misc.Event!=1890738&&misc.Event!=1757319))" << "&&" //summer QCD 53X
     << "(misc.ProcessID!=10||(Susy.MassChi==350&&Susy.MassLSP==50))" << "&&" // T2bb M_stop = 350, M_lsp = 50
 //    << "(misc.ProcessID!=10||(Susy.MassChi==600&&Susy.MassLSP==50))" << "&&" // T2bb M_stop = 600, M_lsp = 50

//	  << "misc.MT2 >=0"                                      << "&&" 
//	  << "misc.MT2 < 125"                                    << "&&" 
//	  << "misc.MT2 >=125"                                    << "&&" 
	  << "misc.MET>=30"                                      << "&&"
	  << "misc.HT>=450"                                      << "&&"
	  << "misc.Jet0Pass ==1"                                 << "&&"
	  << "misc.Jet1Pass ==1"                                 << "&&"
//	  << "misc.SecondJPt  >100"                              << "&&"
	  << "misc.PassJetID ==1"                                << "&&"
	  << "misc.Vectorsumpt < 70"                             << "&&"
//	  << "(NJetsIDLoose40 +NEles +NMuons)>=3"                << "&&"
	  << "misc.MinMetJetDPhi4>0.3"                           << "&&"
//	  << "misc.MinMetJetDPhiPt40>0.3"                        << "&&"
//        << "NBJetsCSVM     >=1"                                << "&&"
//        JetSkim
	  << "NJetsIDLoose40 >=2"                                << "&&"
//	  << "NJetsIDLoose40 >=3"                                << "&&"
//	  << "NJetsIDLoose40 >=6"                                << "&&"
//	  << "NJetsIDLoose40 ==2"                                << "&&"
//        HTskim
//	  << "misc.HT >=750"                                     << "&&" 
//        METskim
//	  << "misc.MET >=200"                                    << "&&"
//	  LeptonSkim
//	  << "(NEles+NMuons) ==0"                                << "&&"
//	  << "(NEles+NMuons) >=1"                                << "&&"
// Stop Skim -------------------------
//	  << "NJetsIDLoose40 >=2"                                << "&&"
//        << "(NEles+NMuons) >=2"                                << "&&"
//        << "NBJetsCSVM     >=1"                                << "&&"
//	  << "NJetsIDLoose40 >=3"                                << "&&" 
// Noise -- first 6 are official filters
	  << "( misc.ProcessID==10 || misc.HBHENoiseFlag == 0)"  << "&&"
	  << "misc.CSCTightHaloIDFlag == 0"                      << "&&"
	  << "(misc.ProcessID==10||misc.hcalLaserEventFlag==0)"  << "&&"
//	  << "(misc.isFastSim || misc.HBHENoiseFlag == 0)"       << "&&"
//	  << "(misc.isFastSim || misc.CSCTightHaloIDFlag == 0)"  << "&&"
//	  << "(misc.isFastSim || misc.hcalLaserEventFlag == 0)"  << "&&"
	  << "misc.trackingFailureFlag == 0"                     << "&&"
	  << "misc.eeBadScFlag == 0"                             << "&&"
	  << "misc.EcalDeadCellTriggerPrimitiveFlag == 0";

	TString cuts = cutStream.str().c_str();
/*
	std::ostringstream triggerStreamEE;
	triggerStreamEE << "( "
	  << "(trigger.HLT_DiElectrons==1)" << " )";
	TString triggerEE = triggerStreamEE.str().c_str();
	std::ostringstream triggerStreamEMu;
	triggerStreamEMu << "( "
	  << "(trigger.HLT_EMu==1)" << " )";
	TString triggerEMu = triggerStreamEMu.str().c_str();
	std::ostringstream triggerStreamMuMu;
	triggerStreamMuMu << "( "
	  << "(trigger.HLT_DiMuons==1)" << " )";
	TString triggerMuMu = triggerStreamMuMu.str().c_str();
*//*
	std::ostringstream triggerStream;
	triggerStream << "( "
			<< "trigger.HLT_PFHT650_v5 == 1 || trigger.HLT_PFHT650_v6 == 1 || trigger.HLT_PFHT650_v7 == 1 || "
			<< "trigger.HLT_PFHT650_v8 == 1 || trigger.HLT_PFHT650_v9 == 1 || "
			<< "trigger.HLT_PFNoPUHT650_v1 == 1 || trigger.HLT_PFNoPUHT650_v3 == 1)";
	
	TString trigger = triggerStream.str().c_str();
*/
	std::ostringstream triggerStream;
	triggerStream << "( "
			<< "trigger.HLT_PFMET150_v2 == 1 || trigger.HLT_PFMET150_v3 == 1 || trigger.HLT_PFMET150_v4 == 1 || "
			<< "trigger.HLT_PFMET150_v5 == 1 || trigger.HLT_PFMET150_v6 == 1 || trigger.HLT_PFMET150_v7 == 1 )";
	TString trigger = triggerStream.str().c_str();
  

	load(samples.Data());

	for(size_t i = 0; i < fSamples.size(); ++i){

   	    if(runData==false && fSamples[i].type=="data") continue;
	    if(calcsusy==false && fSamples[i].type=="susy") continue;
	    if(runQCD==false   && fSamples[i].sname=="QCD") continue;
	    if(onlyQCD==true   && fSamples[i].sname!="QCD" && runQCD) continue;

	    string sampletype = (string)fSamples[i].type;
	    bool METskim = false;
	    bool HTskim  = false;
	    TString path = fSamples[i].file->GetName();
	    if(path.Contains("METskim")) METskim = true;
	    if(path.Contains("HTskim"))  HTskim  = true;
	    if(fChange){
		if(fHT)  { HTskim = true;  METskim = false; }
		if(fMET) { HTskim = false; METskim = true;  }
	    	if(!(fMET || fHT)) { HTskim = false; METskim = false; }
	    }
//		cout << true << " " << path << " " << METskim << " " << HTskim << endl;
	    if(!(METskim || HTskim)) continue;
	    if(sampletype==(string)"mc"){
		if(fSamples[i].sname=="QCD") sampletype = (string)fSamples[i].sname;
		else if(fSamples[i].sname=="Wtolnu") sampletype = (string)"WJets";
		else if(fSamples[i].sname=="DY")     sampletype = (string)"ZJets";
		else if(fSamples[i].name=="TTbar")   sampletype = (string)"TTbar";
		else if(fSamples[i].name=="TTbar_Had")   sampletype = (string)"TTbar";
		else if(fSamples[i].name=="TTbar_SemiLep")   sampletype = (string)"TTbar";
		else if(fSamples[i].name=="TTbar_FullyLep")   sampletype = (string)"TTbar";
		else if(fSamples[i].sname=="TTbarV") sampletype = (string)"TTbar";
		else if(fSamples[i].sname=="Top")    sampletype = (string)"SingleTop";//no ttbar
		//else if(fSamples[i].sname=="VV" || fSamples[i].sname=="VVV") sampletype = (string)"VV/VVV";
		else sampletype = (string)"Other";
	    }
	//    if(sampletype==(string)"susy") sampletype=(string)"Stop";

	    Double_t sample_weight = fSamples[i].xsection * fSamples[i].kfact * fSamples[i].lumi / (fSamples[i].nevents);
	    if(fVerbose>2) cout << "B-Efficiency: looping over " << fSamples[i].name << endl;
	    if(fVerbose>2) cout << "              sample has weight " << sample_weight << " and " << fSamples[i].tree->GetEntries() << " entries" << endl; 
	    if(fVerbose>2 && fSamples[i].tree->GetEntries()==0) cout << "skip sample, has no entries" << endl;
            if(fSamples[i].tree->GetEntries()==0) continue;
	    MT2tree* fMT2tree = new MT2tree();
	    fSamples[i].tree->SetBranchAddress("MT2tree", &fMT2tree);
	    Long64_t nentries =  fSamples[i].tree->GetEntries();
	    Long64_t nbytes = 0, nb = 0;
	    int nev =0;

	    TString myCuts = cuts;
	    if(HTskim)  myCuts = myCuts + " && misc.HT>750";
	    if(METskim) myCuts = myCuts + " && misc.HT<=750 && misc.MET>200";//METskim excluding HTskim

	/*
	    if( fSamples[i].type=="data" && fSamples[i].sname=="EE-Data") { myCuts += " && " + triggerEE; }//cuts to be aplied only on data
	    else if( fSamples[i].type=="data" && fSamples[i].sname=="EMu-Data") { myCuts += " && " + triggerEMu; }//cuts to be aplied only on data
	    else if( fSamples[i].type=="data" && fSamples[i].sname=="MuMu-Data") { myCuts += " && " + triggerMuMu; } //cuts to be aplied only on data
	    else if(fSamples[i].type=="data") {cout << "data not usuable" << " type " << fSamples[i].type << " Sname " << fSamples[i].sname << endl; continue; }//not 
	*/
	    if( fSamples[i].type=="data") { myCuts += " && " + trigger; }

   	    cout << "Cuts for Flow: " << myCuts << endl;
   	    fSamples[i].tree->Draw(">>selList", myCuts);

	    TEventList *myEvtList = (TEventList*)gDirectory->Get("selList");

	    fSamples[i].tree->SetEventList(myEvtList);

	    int counter=0;
	    cout << "Filtering done, size=" <<myEvtList->GetN()  << endl;
	    if(myEvtList->GetSize()==0) continue;
        while(myEvtList->GetEntry(counter++) !=-1){	
      		int jentry = myEvtList->GetEntry(counter-1);
            
            nb =  fSamples[i].tree->GetEntry(jentry);   nbytes += nb;
            fSamples[i].tree->SetBranchAddress("MT2tree", &fMT2tree);
            
            if ( fVerbose>2 && counter % 50000 == 0 )  cout << "+++ Proccessing event " << counter << endl;


	    //if((fSamples[i].sname!="VVV"&&fSamples[i].sname!="TTbarV" && fSamples[i].type!="susy"&&sampletype!="Stop")  && fMT2tree->misc.HBHENoiseFlag!=0     ) continue;//test
	    //if((fSamples[i].sname!="VVV"&&fSamples[i].sname!="TTbarV" && fSamples[i].type!="susy"&&sampletype!="Stop")  && fMT2tree->misc.hcalLaserEventFlag!=0) continue;//test
            Double_t weight = sample_weight;
            if (!fMT2tree->misc.isData ) weight = weight * fMT2tree->pileUp.Weight; // pile-up reweighting for MC 
 /*           Bool_t recoedee   = false;// exact 2 ele, 0 muo
            Bool_t recoedemu  = false;// exact 1 ele, 1 muo
            Bool_t recoedmumu = false;// exact 0 ele, 2 muo
		//change this - might have some inefficiencies - three leptons with one not passing IDMedium==1
		//20-20 selection --> third lepton is 10 GeV 
            if(fMT2tree->NEles>=2 &&fMT2tree->ele[0].lv.Pt()>20&&fMT2tree->ele[1].lv.Pt()>20&&fMT2tree->ele[2].lv.Pt()<20&&(fMT2tree->NMuons==0||fMT2tree->muo[0].lv.Pt()<10) && fMT2tree->ele[0].IDMedium==1 && fMT2tree->ele[1].IDMedium==1) recoedee   = true;
            if(fMT2tree->NMuons>=2&&fMT2tree->muo[0].lv.Pt()>20&&fMT2tree->muo[1].lv.Pt()>20&&fMT2tree->muo[2].lv.Pt()<10&&(fMT2tree->NEles ==0||fMT2tree->ele[0].lv.Pt()<10)) recoedmumu = true;
            if(fMT2tree->NMuons>=1&&fMT2tree->muo[0].lv.Pt()>20&&fMT2tree->muo[1].lv.Pt()<10&&fMT2tree->NEles>=1 &&fMT2tree->ele[0].lv.Pt()>20&&fMT2tree->ele[1].lv.Pt()<10 && fMT2tree->ele[0].IDMedium==1) recoedemu  = true;//XXX change emu to 20/20 selection, left ee,mumu at 20/10 for now
	    //id cuts?

            Bool_t recoedosee   = false;// opposite sign
            Bool_t recoedosemu  = false;// opposite sign
            Bool_t recoedosmumu = false;// opposite sign
	    if(recoedee   && (fMT2tree->ele[0].Charge)*(fMT2tree->ele[1].Charge)==(-1)) recoedosee   = true;
	    if(recoedemu  && (fMT2tree->ele[0].Charge)*(fMT2tree->muo[0].Charge)==(-1)) recoedosemu  = true;
	    if(recoedmumu && (fMT2tree->muo[0].Charge)*(fMT2tree->muo[1].Charge)==(-1)) recoedosmumu = true;
            Bool_t recoedeenZ   = false;// off Z
            Bool_t recoedemunZ  = false;// off Z -> is not requirement, so this variable should be useless
            Bool_t recoedmumunZ = false;// off Z
	    if(recoedee   && ((fMT2tree->ele[0].lv + fMT2tree->ele[1].lv).M()<81 || (fMT2tree->ele[0].lv + fMT2tree->ele[1].lv).M()>101) ) recoedeenZ   = true;
	    if(recoedemu  && ((fMT2tree->ele[0].lv + fMT2tree->muo[0].lv).M()<81 || (fMT2tree->ele[0].lv + fMT2tree->muo[0].lv).M()>101) ) recoedemunZ  = true;
	    if(recoedmumu && ((fMT2tree->muo[0].lv + fMT2tree->muo[1].lv).M()<81 || (fMT2tree->muo[0].lv + fMT2tree->muo[1].lv).M()>101) ) recoedmumunZ = true;

	    if(!(recoedee)   && !(recoedemu)   && !(recoedmumu)  ) continue;//require dilepton
	    if(!(recoedosee) && !(recoedosemu) && !(recoedosmumu) ) continue;//require os-dilepton, maybe comment this for background est.

	    if(recoedee   && !(fMT2tree->misc.isData) ) weight = 0.960 * weight * 0.953366;//from SSb Florida
	    if(recoedemu  && !(fMT2tree->misc.isData) ) weight = 0.934 * weight;//from SSb Florida
	    if(recoedmumu && !(fMT2tree->misc.isData) ) weight = 0.875 * weight * 1.031213;//from SSb Florida
*/
	   	if(wjetsxsecup  ==true && fSamples[i].sname=="Wtolnu")	weight = weight*0.7;
	   	if(wjetsxsecdown==true && fSamples[i].sname=="Wtolnu")	weight = weight*1.3;
	   	if(ttbarxsecup  ==true && fSamples[i].name== "TTbar" )	weight = weight*0.85;
	   	if(ttbarxsecdown==true && fSamples[i].name== "TTbar" )	weight = weight*1.15;

		for(int k = 0; k<fMT2tree->NJets; ++k){
			if(fMT2tree->jet[k].isPFIDLoose==false) continue;
			if(fMT2tree->jet[k].Flavour<=-7777 && fMT2tree->misc.isData==false) continue;//MC sample veto if no btagging information
			if(abs(fMT2tree->jet[k].Flavour>100)) cout << "jet " << k << "has flavour " << fMT2tree->jet[k].Flavour << endl;
			float btagdiscr=-1;
			if(btaggername==0)      btagdiscr = fMT2tree->jet[k].bTagProbTCHE;
			else if(btaggername==1) btagdiscr = fMT2tree->jet[k].bTagProbTCHP;
			else if(btaggername==2) btagdiscr = fMT2tree->jet[k].bTagProbSSVHE;
			else if(btaggername==3) btagdiscr = fMT2tree->jet[k].bTagProbSSVHP;
			else if(btaggername==4) btagdiscr = fMT2tree->jet[k].bTagProbCSV;
			else if(btaggername==5) btagdiscr = fMT2tree->jet[k].bTagProbJProb;
			else                    btagdiscr = fMT2tree->jet[k].bTagProbCSV;
			float jetpt = fMT2tree->jet[k].lv.Pt();
			float jeteta= fabs(fMT2tree->jet[k].lv.Eta() );
			//float jetMT2= fMT2tree->misc.MT2;
			int jetabsflavour = abs(fMT2tree->jet[k].Flavour);
			if(jetpt<bpt)   continue;
			if(jeteta>beta) continue;
			histospt[string("AllJet_") + sampletype]->Fill(jetpt, weight );
			histos2d[string("AllJet_") + sampletype]->Fill(jetpt, jeteta, weight );
			if(jetabsflavour==5){
				histospt[string("BJet_") + sampletype]->Fill(jetpt, weight );
				histos2d[string("BJet_") + sampletype]->Fill(jetpt, jeteta, weight );
			}
			else if(jetabsflavour==4){
				histospt[string("CJet_") + sampletype]->Fill(jetpt, weight );
				histos2d[string("CJet_") + sampletype]->Fill(jetpt, jeteta, weight );
			}
			else{
				histospt[string("LJet_") + sampletype]->Fill(jetpt, weight );
				histos2d[string("LJet_") + sampletype]->Fill(jetpt, jeteta, weight );
			}
			if(btagdiscr>=bdiscr_value){
				histospt[string("BTaggedAllJet_") + sampletype]->Fill(jetpt, weight );
				histos2d[string("BTaggedAllJet_") + sampletype]->Fill(jetpt, jeteta, weight );
				if(jetabsflavour==5){
					histospt[string("BTaggedBJet_") + sampletype]->Fill(jetpt, weight );
					histos2d[string("BTaggedBJet_") + sampletype]->Fill(jetpt, jeteta, weight );
				}
				else if(jetabsflavour==4){
					histospt[string("BTaggedCJet_") + sampletype]->Fill(jetpt, weight );
					histos2d[string("BTaggedCJet_") + sampletype]->Fill(jetpt, jeteta, weight );
				}
				else{
					histospt[string("BTaggedLJet_") + sampletype]->Fill(jetpt, weight );
					histos2d[string("BTaggedLJet_") + sampletype]->Fill(jetpt, jeteta, weight );
				}
			}
		}//for(int k = 0; k<fMT2tree->NJets; ++k)
	   }
	   delete fMT2tree;
	}//for(size_t i = 0; i < fSamples.size(); ++i)

	cout << "add overflow bins" << endl;
	for(map<string,TH2D*>::iterator h=histos2d.begin(); h!=histos2d.end();++h){
		//there should not be any underflow, just look at overflow
		int nbinsx = h->second->GetNbinsX();
		int nbinsy = h->second->GetNbinsY();
		for(int ix = 1; ix<= nbinsx;++ix){
			h->second->SetBinContent(ix, nbinsy, 
						h->second->GetBinContent(ix,nbinsy) +
						h->second->GetBinContent(ix, nbinsy+1));
			h->second->SetBinError(ix, nbinsy, 
						sqrt(h->second->GetBinError(ix,nbinsy)*h->second->GetBinError(ix,nbinsy) +
						h->second->GetBinError(ix, nbinsy+1)*h->second->GetBinError(ix, nbinsy+1)) );
		}
		for(int iy = 1; iy<= nbinsy;++iy){
			h->second->SetBinContent(nbinsx, iy, 
						h->second->GetBinContent(nbinsx,iy) +
						h->second->GetBinContent(nbinsx+1, iy));
			h->second->SetBinError(nbinsx, iy, 
						sqrt(h->second->GetBinError(nbinsx,iy)*h->second->GetBinError(nbinsx,iy) +
						h->second->GetBinError(nbinsx+1, iy)*h->second->GetBinError(nbinsx+1, iy)) );
		}
		h->second->SetBinContent(nbinsx, nbinsy, 
						h->second->GetBinContent(nbinsx,nbinsy) +
						h->second->GetBinContent(nbinsx+1, nbinsy+1));
		h->second->SetBinError(nbinsx, nbinsy, 
					sqrt(h->second->GetBinError(nbinsx,nbinsy)*h->second->GetBinError(nbinsx,nbinsy) +
					h->second->GetBinError(nbinsx+1, nbinsy+1)*h->second->GetBinError(nbinsx+1, nbinsy+1)) );
	}
	for(map<string,TH1D*>::iterator h=histospt.begin(); h!=histospt.end();++h){
		//there should not be any underflow, just look at overflow
		int nbinsx = h->second->GetNbinsX();
		h->second->SetBinContent(nbinsx, h->second->GetBinContent(nbinsx) + h->second->GetBinContent(nbinsx+1));
		h->second->SetBinError(  nbinsx, h->second->GetBinError(nbinsx  )*h->second->GetBinError(nbinsx  ) +
                                                 h->second->GetBinError(nbinsx+1)*h->second->GetBinError(nbinsx+1) );
	}


	cout << "merge mc histograms into one" << endl;
	//fill mc histogram from the samples histograms
	for(int ists = 0; ists<sampletypesize; ++ists){
		if((sample_type[ists])==("data")) continue;
		if((sample_type[ists])==("susy")) continue;
		if((sample_type[ists])==("mc") ) continue;//have all mc subsamples only
		string helptype = string("_") + sample_type[ists];
		string helpmc = "_mc";
		string helpmcnoqcd = "_mcNOqcd";
		histospt[string("BJet")   + helpmc]->Add(histospt[string("BJet")   + helptype], 1.);
		histospt[string("CJet")   + helpmc]->Add(histospt[string("CJet")   + helptype], 1.);
		histospt[string("LJet")   + helpmc]->Add(histospt[string("LJet")   + helptype], 1.);
		histospt[string("AllJet") + helpmc]->Add(histospt[string("AllJet") + helptype], 1.);
		histos2d[string("BJet")   + helpmc]->Add(histos2d[string("BJet")   + helptype], 1.);
		histos2d[string("CJet")   + helpmc]->Add(histos2d[string("CJet")   + helptype], 1.);
		histos2d[string("LJet")   + helpmc]->Add(histos2d[string("LJet")   + helptype], 1.);
		histos2d[string("AllJet") + helpmc]->Add(histos2d[string("AllJet") + helptype], 1.);
		histospt[string("BTaggedBJet")   + helpmc]->Add(histospt[string("BTaggedBJet")   + helptype], 1.);
		histospt[string("BTaggedCJet")   + helpmc]->Add(histospt[string("BTaggedCJet")   + helptype], 1.);
		histospt[string("BTaggedLJet")   + helpmc]->Add(histospt[string("BTaggedLJet")   + helptype], 1.);
		histospt[string("BTaggedAllJet") + helpmc]->Add(histospt[string("BTaggedAllJet") + helptype], 1.);
		histos2d[string("BTaggedBJet")   + helpmc]->Add(histos2d[string("BTaggedBJet")   + helptype], 1.);
		histos2d[string("BTaggedCJet")   + helpmc]->Add(histos2d[string("BTaggedCJet")   + helptype], 1.);
		histos2d[string("BTaggedLJet")   + helpmc]->Add(histos2d[string("BTaggedLJet")   + helptype], 1.);
		histos2d[string("BTaggedAllJet") + helpmc]->Add(histos2d[string("BTaggedAllJet") + helptype], 1.);
		if(sample_type[ists]==string("QCD")) continue;
		histospt[string("BJet")   + helpmcnoqcd]->Add(histospt[string("BJet")   + helptype], 1.);
		histospt[string("CJet")   + helpmcnoqcd]->Add(histospt[string("CJet")   + helptype], 1.);
		histospt[string("LJet")   + helpmcnoqcd]->Add(histospt[string("LJet")   + helptype], 1.);
		histospt[string("AllJet") + helpmcnoqcd]->Add(histospt[string("AllJet") + helptype], 1.);
		histos2d[string("BJet")   + helpmcnoqcd]->Add(histos2d[string("BJet")   + helptype], 1.);
		histos2d[string("CJet")   + helpmcnoqcd]->Add(histos2d[string("CJet")   + helptype], 1.);
		histos2d[string("LJet")   + helpmcnoqcd]->Add(histos2d[string("LJet")   + helptype], 1.);
		histos2d[string("AllJet") + helpmcnoqcd]->Add(histos2d[string("AllJet") + helptype], 1.);
		histospt[string("BTaggedBJet")   + helpmcnoqcd]->Add(histospt[string("BTaggedBJet")   + helptype], 1.);
		histospt[string("BTaggedCJet")   + helpmcnoqcd]->Add(histospt[string("BTaggedCJet")   + helptype], 1.);
		histospt[string("BTaggedLJet")   + helpmcnoqcd]->Add(histospt[string("BTaggedLJet")   + helptype], 1.);
		histospt[string("BTaggedAllJet") + helpmcnoqcd]->Add(histospt[string("BTaggedAllJet") + helptype], 1.);
		histos2d[string("BTaggedBJet")   + helpmcnoqcd]->Add(histos2d[string("BTaggedBJet")   + helptype], 1.);
		histos2d[string("BTaggedCJet")   + helpmcnoqcd]->Add(histos2d[string("BTaggedCJet")   + helptype], 1.);
		histos2d[string("BTaggedLJet")   + helpmcnoqcd]->Add(histos2d[string("BTaggedLJet")   + helptype], 1.);
		histos2d[string("BTaggedAllJet") + helpmcnoqcd]->Add(histos2d[string("BTaggedAllJet") + helptype], 1.);

	}
	cout << "merge C and L histograms to NonB" << endl;
	for(int ists = 0; ists<sampletypesize; ++ists){
		string helptype = string("_") + sample_type[ists];
		histospt[string("NonBJet")   + helptype]->Add(histospt[string("CJet")   + helptype], 1.);
		histospt[string("NonBJet")   + helptype]->Add(histospt[string("LJet")   + helptype], 1.);
		histos2d[string("NonBJet")   + helptype]->Add(histos2d[string("CJet")   + helptype], 1.);
		histos2d[string("NonBJet")   + helptype]->Add(histos2d[string("LJet")   + helptype], 1.);
		histospt[string("BTaggedNonBJet")   + helptype]->Add(histospt[string("BTaggedCJet")   + helptype], 1.);
		histospt[string("BTaggedNonBJet")   + helptype]->Add(histospt[string("BTaggedLJet")   + helptype], 1.);
		histos2d[string("BTaggedNonBJet")   + helptype]->Add(histos2d[string("BTaggedCJet")   + helptype], 1.);
		histos2d[string("BTaggedNonBJet")   + helptype]->Add(histos2d[string("BTaggedLJet")   + helptype], 1.);
	}
	cout << "save histogram" << endl;
	TFile *fsavefile = new TFile(outputdir+outputname,"RECREATE");
	fsavefile->cd();
	for(map<string,TH2D*>::iterator h=histos2d.begin(); h!=histos2d.end();++h){
		h->second->Write();}
	for(map<string,TH1D*>::iterator h=histospt.begin(); h!=histospt.end();++h){
		h->second->Write();}
	fsavefile->Close();

	cout << "Saved histograms in " << outputdir << outputname << endl;

}//void GetBEfficiency_InputHistograms()
Example #14
0
//this code create the so-called 'PrintOuts' as done with the MT2tree::PrintOut() function
void PrintOutEvents(){

	bool savetofile = true;//save the printout to the file PrintOut.log, default = true
	bool onlyData = true;  //run only over data, default = true

//	TString  samples = "/shome/haweber/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samples_MET_filter.dat";//only dummy
//	TString  samples = "/shome/haweber/MT2Analysis_8TeV/Code/MT2AnalysisCode/RootMacros/samples/samples_HT_filter.dat";//only dummy
	TString samples = "samples/samples_HTandMET_filter.dat";

	//event selection for which you want to have the printout - complicated stuff can also be done later
	std::ostringstream cutStream;
	std::ostringstream cutStreamBase;
	cutStream << " " 
	//	<< "NBJets40CSVM >= 3"		<< "&&"
		<< "NJetsIDLoose40 >= 2"		<< "&&"
		<< "NEles+NMuons+NTausIDLoose3Hits  ==0"<< "&&"
	//	<< "misc.MT2>=250"                      << "&&"
		<< "misc.Jet0Pass ==1"                      << "&&"
		<< "misc.Jet1Pass ==1"                      << "&&"
		<< "misc.Vectorsumpt < 70";
		cutStream  << "&& misc.MinMetJetDPhi4Pt40 >0.3";
//	cutStream << "&&misc.HT<750&&misc.HT>=450&&misc.MET>200";
//	cutStream << "&&misc.HT>=750&&misc.MET>30";
	cutStream << "&&((misc.HT<750&&misc.HT>=450&&misc.MET>200)||(misc.HT>=750&&misc.MET>30))";

	//Higgs
//	cutStream <<"&&NJetsIDLoose40 >= 4"<<"&&"
  //  		  <<"NBJetsCSVM>=2"<<"&&"
	//	  <<"GetSelBBMinv()>250";
	
	cutStreamBase << " " 
      << "misc.PassJet40ID ==1"                      << "&&"
      << "(misc.HBHENoiseFlag == 0 || misc.ProcessID==10)"  << "&&" // for rare SM samples
      << "misc.CSCTightHaloIDFlag == 0"             << "&&"
      << "misc.trackingFailureFlag==0"              << "&&"
      << "misc.eeBadScFlag==0"                      << "&&"
      << "misc.EcalDeadCellTriggerPrimitiveFlag==0" << "&&"
      << "misc.TrackingManyStripClusFlag==0"             << "&&"
      << "misc.TrackingTooManyStripClusFlag==0"          << "&&"
      << "misc.TrackingLogErrorTooManyClustersFlag==0"   << "&&"
      << "misc.CrazyHCAL==0";
	cutStreamBase << "&&misc.MET/misc.CaloMETRaw<=2.";
	cutStreamBase << "&&TOBTECTagger<=8&&ExtraBeamHaloFilter==0";// ONLY ON DATA
	TString cuts = cutStream.str().c_str();
	TString basecuts = cutStreamBase.str().c_str();

	load(samples.Data());

	//if have extremely many events can only select a random subset of those
	TRandom3 *random = new TRandom3(0);//somehow truly random with this seed
	vector<int> randvec; randvec.clear();
	for(int i =0; i<40;++i)
		randvec.push_back(random->Integer(7750));
	delete random;
	sort(randvec.begin(), randvec.end());
	//for(int i=0; i<randvec.size();++i) cout << "randvec["<<i<<"]="<<randvec[i] << endl;
	int counter1 = 0; int counter2 = 0;

	//don't run events twice - this vector makes that sure (in case event is in both MET and HT trigger stream)
	   vector<pair<int,pair<int,int> > > rls; rls.clear();


   	for(size_t i = 0; i < fSamples.size(); ++i){
        
   	    if(onlyData && fSamples[i].type!="data") continue;

	    MT2tree* fMT2tree = new MT2tree();
	    fSamples[i].tree->SetBranchAddress("MT2tree", &fMT2tree);
	    Long64_t nentries =  fSamples[i].tree->GetEntries();
	    Long64_t nbytes = 0, nb = 0;
	    int nev =0;
        
	    TString myCuts = cuts + "&&" + basecuts;
        
	    //if( fSamples[i].type=="data") myCuts += " && " + trigger; //cuts to be aplied only on data
        
	    cout << "sample " << fSamples[i].name << endl;
   	    cout << "Cuts for Flow: " << myCuts << endl;
   	    fSamples[i].tree->Draw(">>selList", myCuts);
        
	    TEventList *myEvtList = (TEventList*)gDirectory->Get("selList");
	    fSamples[i].tree->SetEventList(myEvtList);
	    int counter=0;
	    cout << "Filtering done, size=" <<myEvtList->GetN()  << endl;
	    if(myEvtList->GetSize()==0) continue;
		//run over selected events
        while(myEvtList->GetEntry(counter++) !=-1){	
		int jentry = myEvtList->GetEntry(counter-1);
            
		nb =  fSamples[i].tree->GetEntry(jentry);   nbytes += nb;
		fSamples[i].tree->SetBranchAddress("MT2tree", &fMT2tree);
		//implementation of running over random subset
//		if(counter1==randvec[counter2]){
//			++counter2;
//			fMT2tree->PrintOut(savetofile);
//		}

		pair <int,int> dummy1(fMT2tree->misc.LumiSection,fMT2tree->misc.Event);
		pair <int,pair<int,int> > dummy(fMT2tree->misc.Run, dummy1);
		bool newevt = true;
		for(int nn = 0; nn<rls.size(); ++nn){
			if(rls[nn].first==dummy.first && rls[nn].second.first==dummy.second.first && rls[nn].second.second==dummy.second.second) {newevt = false; break;}
		}
		if(newevt){
			rls.push_back(dummy);
			fMT2tree->PrintOut(savetofile);//safe the printout
			++counter1;
		}

	}
	delete fMT2tree;
	delete fSamples[i].tree;
	}
	cout << "Printed out " << counter1 << " events." << endl;
}
void TMVAClassificationApplication( TString myMethodList = "" ) 
{   
#ifdef __CINT__
   gROOT->ProcessLine( ".O0" ); // turn off optimization in CINT
#endif

   //---------------------------------------------------------------

   // This loads the library
   TMVA::Tools::Instance();

   // set verbosity
   //TMVA::Tools::Instance().Log().SetMinType(kINFO);

   // Default MVA methods to be trained + tested
   std::map<std::string,int> Use;

   Use["BDT"]             = 1; // uses Adaptive Boost
   Use["Category"]        = 1;

   std::cout << std::endl;
   std::cout << "==> Start TMVAClassificationApplication" << std::endl;

   // Select methods (don't look at this code - not of interest)
   if (myMethodList != "") {
      for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

      std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
      for (UInt_t i=0; i<mlist.size(); i++) {
         std::string regMethod(mlist[i]);

         if (Use.find(regMethod) == Use.end()) {
            std::cout << "Method \"" << regMethod 
                      << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
            for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
               std::cout << it->first << " ";
            }
            std::cout << std::endl;
            return;
         }
         Use[regMethod] = 1;
      }
   }

   // --------------------------------------------------------------------------------------------------

   // --- Create the Reader object

   TMVA::Reader *reader = new TMVA::Reader( "Color:!Silent" );    
   reader->SetMsgType(kINFO);


   // CMS STATS:
   //
   // Create a set of variables and declare them to the reader
   // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
   Float_t met;
   Float_t HT;
   Float_t minMLB;
   Float_t leptonJetsMETSum;
   reader->AddVariable( "met",              &met );
   reader->AddVariable( "HT",               &HT );
   reader->AddVariable( "minMLB",           &minMLB );
   reader->AddVariable( "leptonJetsMETSum", &leptonJetsMETSum );



   // CMS STATS:
   // *** VERY IMPORTANT! ***
   // TMVA notoriously has problems with integer and other non-float branches.
   // Better not to use them at all and convert them to Float_t. If you happen
   // to have integer branches that you need, as in this example, you should create
   // corresponding float spectator variables and assign them in the event loop.
   // 
   // Spectator variables declared in the training have to be added to the reader, too
   //
   // Note that the corresponding branches are integer, so we create floats too!
   Int_t nBTag;
   Int_t nJets;
   Int_t nLeptons;
   Int_t isMuon1;
   Int_t isMuon2;
   Int_t isMuon3;
   Int_t isMuon4;
   Float_t nBTagFloat;
   Float_t nJetsFloat;
   Float_t nLeptonsFloat;
   Float_t isMuon1Float;
   Float_t isMuon2Float;
   Float_t isMuon3Float;
   Float_t isMuon4Float;
   Float_t leptonSumMass;
   reader->AddSpectator( "nBTag", &nBTagFloat );
   reader->AddSpectator( "nJets", &nJetsFloat );
   reader->AddSpectator( "nLeptons", &nLeptonsFloat );
   reader->AddSpectator( "isMuon1", &isMuon1Float );
   reader->AddSpectator( "isMuon2", &isMuon2Float );
   reader->AddSpectator( "isMuon3", &isMuon3Float );
   reader->AddSpectator( "isMuon4", &isMuon4Float );
   reader->AddSpectator( "leptonSumMass", &leptonSumMass );



   // CMS STATS:
   // cut definitions. Define categories and overall selection.
#include "TMVA_tprime_cuts.C"



   // Add artificial spectators for distinguishing categories
   Float_t Category_mycat1, Category_mycat2, Category_mycat3, Category_mycat4;
   TString sCat1("Category_cat1:=");
   TString sCat2("Category_cat2:=");
   TString sCat3("Category_cat3:=");
   TString sCat4("Category_cat4:=");
   sCat1.Append(cut_os_cat1);
   sCat2.Append(cut_os_cat2);
   sCat3.Append(cut_ss);
   sCat4.Append(cut_tri);
   reader->AddSpectator( sCat1, &Category_mycat1 );
   reader->AddSpectator( sCat2, &Category_mycat2 );
   reader->AddSpectator( sCat3, &Category_mycat3 );
   reader->AddSpectator( sCat4, &Category_mycat4 );


   // --- Book the MVA methods

   TString dir    = "weights/";
   TString prefix = "TMVAClassification";

   // Book method(s)
   for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      if (it->second) {
         TString methodName = TString(it->first) + TString(" method");
         TString weightfile = dir + prefix + TString("_") + TString(it->first) + TString(".weights.xml");
         reader->BookMVA( methodName, weightfile ); 
      }
   }

   
   // Book output histograms
   UInt_t nbin = 100;
   TH1F * histBdt(0);
   TH1F * histCat(0);

   if (Use["BDT"])           histBdt     = new TH1F( "MVA_BDT",           "MVA_BDT",           nbin, -0.8, 0.8 );
   if (Use["Category"])      histCat     = new TH1F( "MVA_Category",      "MVA_Category",      nbin, -2., 2. );


   // Prepare input tree (this must be replaced by your data source)
   // in this example, there is a toy tree with signal and one with background events
   // we'll later on use only the "signal" events for the test in this example.
   //   
   TFile *input(0);


   // CMS STATS:
   // Specify files with data, for which you want to compute the classifier values
   TString fname = "./data/pass7_OS_test1/TTbar_MuMu/all.root";   
   //TString fname = "./data/pass7_TRI_test1/TTbar_MuMu/all.root";   


   if (!gSystem->AccessPathName( fname )) 
      input = TFile::Open( fname ); // check if file in local directory exists
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;
   
   // --- Event loop

   // Prepare the event tree
   // - here the variable names have to corresponds to your tree
   // - you can use the same variables as above which is slightly faster,
   //   but of course you can use different ones and copy the values inside the event loop
   //
   std::cout << "--- Select signal sample" << std::endl;
   TTree* theTree = (TTree*)input->Get("MVA");
   //Float_t userVar1, userVar2;
   theTree->SetBranchAddress( "met",              &met );
   theTree->SetBranchAddress( "HT",               &HT );
   theTree->SetBranchAddress( "minMLB",           &minMLB );
   theTree->SetBranchAddress( "leptonJetsMETSum", &leptonJetsMETSum );


   // spectators
   theTree->SetBranchAddress( "leptonSumMass", &leptonSumMass );
   theTree->SetBranchAddress( "nJets", &nJets );
   theTree->SetBranchAddress( "nBTag", &nBTag );
   theTree->SetBranchAddress( "nLeptons", &nLeptons );
   theTree->SetBranchAddress( "isMuon1", &isMuon1 );
   theTree->SetBranchAddress( "isMuon2", &isMuon2 );
   theTree->SetBranchAddress( "isMuon3", &isMuon3 );
   theTree->SetBranchAddress( "isMuon4", &isMuon4 );


   std::vector<Float_t> vecVar(4); // vector for EvaluateMVA tests


   // CMS STATS:
   //       
   //       A little trick: loop over only selected events

   // make event list
   theTree->Draw(">>EvtList", mycut);
   TEventList * pEvtList = (TEventList *)gROOT->FindObject("EvtList");
   long int nEvents = pEvtList->GetN();

   //std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
   std::cout << "--- Processing: " << nEvents << " events" << std::endl;
   TStopwatch sw;
   sw.Start();
   //for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {
   for (Long64_t ievt=0; ievt<nEvents; ++ievt) {

      if (ievt%1000 == 0) std::cout << "--- ... Processing event: " << ievt << std::endl;

      //theTree->GetEntry(ievt);
      theTree->GetEntry(pEvtList->GetEntry(ievt));


      // CMS STATS:
      // *** HERE we assign integer branches' values to float spectator variables
      //     Otherwise our category cuts would fail
      //
      nBTagFloat=(Float_t)nBTag;
      nJetsFloat=(Float_t)nJets;
      nLeptonsFloat=(Float_t)nLeptons;
      isMuon1Float  = (Float_t)isMuon1;
      isMuon2Float  = (Float_t)isMuon2;
      isMuon3Float  = (Float_t)isMuon3;
      isMuon4Float  = (Float_t)isMuon4;



      // --- Return the MVA outputs and fill into histograms

      if (Use["BDT"          ])   histBdt    ->Fill( reader->EvaluateMVA( "BDT method"           ) );
      if (Use["Category"     ])   histCat    ->Fill( reader->EvaluateMVA( "Category method"      ) );

   }

   // Get elapsed time
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();


   // --- Write histograms

   TFile *target  = new TFile( "TMVApp.root","RECREATE" );
   if (Use["BDT"          ])   histBdt    ->Write();
   if (Use["Category"     ])   histCat    ->Write();

   target->Close();

   std::cout << "--- Created root file: \"TMVApp.root\" containing the MVA output histograms" << std::endl;
  
   delete reader;
    
   std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl;
}