Пример #1
0
void KeepOnlyGain()
{
   TChain* tree = new TChain("SiStripCalib/APVGain");
   tree->Add("Gains_Tree.root");


   TFile* out_file = new TFile("Gains.root","recreate");
   TDirectory* out_dir = out_file->mkdir("SiStripCalib","SiStripCalib");
   out_dir->cd();


   TTree* out_tree = tree->CloneTree(0);
   out_tree->SetName("APVGain");
   out_tree->Write();

   int TreeStep = tree->GetEntries()/50;if(TreeStep==0)TreeStep=1;
   for (unsigned int ientry = 0; ientry < tree->GetEntries(); ientry++) {
      if(ientry%TreeStep==0){printf(".");fflush(stdout);}
      tree->GetEntry(ientry);
      out_tree->Fill();
   }printf("\n");

   out_file->Write();
   out_file->Close();

}
Пример #2
0
void morestrict()
{
    const Int_t Ncha = 6;

    Float_t N[Ncha]  = {0};
    Float_t dN[Ncha] = {0};

    Float_t ADC[Ncha]  = {0};
    Float_t dADC[Ncha] = {0};

    Float_t ADCw[Ncha]  = {0};
    Float_t dADCw[Ncha] = {0};

    ifstream dat;
    dat.open("Run4Nseg.txt");
    cout<<"channel \t ADC \t dADC \t ADCw \t dADCw \t N \t dN"<<endl;
    for (Int_t i=1; i<Ncha; i++) {
        dat>>ADC[i]>>dADC[i]>>ADCw[i]>>dADCw[i]>>N[i]>>dN[i];
        cout<<i<<" \t "<<ADC[i]<<" \t "<<dADC[i]<<" \t "
            <<ADCw[i]<<" \t "<<dADCw[i]<<" \t "
            <<N[i]<<" \t "<<dN[i]<<endl;
    }
    dat.close();

    TChain* pstr = new TChain("pstree","root");
    pstr->AddFile("Run4selected.root");

    Int_t Cha_MCAEnergy[8];
    pstr->SetBranchAddress("Cha_MCAEnergy",Cha_MCAEnergy);

    TFile* foutput = new TFile("Run4smaller.root","recreate");
    TTree *newtree = pstr->CloneTree(0);

    Int_t Nevt = pstr->GetEntries();
    cout<<"total events: "<<Nevt<<endl;

    for (Int_t i=0; i<Nevt; i++) {
        if (i%10000==0)
            cout<<"now event: "<<i<<endl;

        pstr->GetEntry(i);

        Int_t Nseg=0;
        for (Int_t j=1; j<Ncha; j++) {
            if (Cha_MCAEnergy[j]>ADC[j]-ADCw[j] &&
                    Cha_MCAEnergy[j]<ADC[j]+ADCw[j]) {
                Nseg++;
            }
        }

        if (Nseg==1) {
            newtree->Fill();
        }
    }

    newtree->Write();
    foutput->Close();
}
Пример #3
0
int Fitter::Save_sWeights()
{
	struct NameValTuple {string name; double val;};
	TFile* pFile = new TFile(outputSweights.c_str(), "RECREATE");
	TChain* pChain = new TChain;
	TTree* pTree = NULL;
	Long64_t nEntries = 0, iEntry=0;
	BranchProxy<double> bp;
	vector<NameValTuple> nameValTuples;
	
	if(!pFile){ cerr << "Error creating file" << endl; return 1; }
	if(InitChain(pChain)) return 1;	
	
	// Deactivate branches that would have the same name as the added branches
	for(auto& pVec_pdfs : {&sigPdfs, &bkgPdfs})
	for(auto& pdf : *pVec_pdfs)
	{
		NameValTuple nv = {pdf.GetYld().GetName()};
		string swBranchName = nv.name+"_sw";
		if(pChain->GetBranch(swBranchName.c_str()))
			pChain->SetBranchStatus(swBranchName.c_str(), 0);
		nameValTuples.push_back(nv);
	}
	
	pTree = pChain->CloneTree(0);
	bp.Connect(pChain, branchName.c_str());
	nEntries = pChain->GetEntries();
	
	for(auto& nv : nameValTuples)
	{
		string swBranchName = nv.name + "_sw";
		string branchTitle = swBranchName + "/D";
		
		pTree->Branch(swBranchName.c_str(), &nv.val, branchTitle.c_str());	
	}
	
	for(Long64_t i=0; i<nEntries; ++i)
	{
		pChain->GetEntry(i);
		if(!range.In(bp)) continue;
		
		for(auto& nv : nameValTuples) 
			nv.val = pSPlot->GetSWeight(iEntry, (nv.name+"_sw").c_str());
		
		++iEntry;
		pTree->Fill();
	}
	pTree->AutoSave();
	
	delete pFile;
	delete pChain;
	
	return 0;
}
void mergetree(TString file1 = "/afs/cern.ch/work/s/shuai/public/diboson/trees/test/testnewsh/fullsig/treeEDBR_TTBAR_xww.root", TString file2 = "/afs/cern.ch/work/s/shuai/public/diboson/trees/test/testnewsh/fullsideband/treeEDBR_TTBAR_xww.root",TString outfile = "mergetreeTest.root")
{
	cout<<"file1 :"<<file1<<endl;
	cout<<"file2 :"<<file2<<endl;
	TChain * chain = new TChain("SelectedCandidates");
	chain->Add(file1);
	int nsig = chain->GetEntries();
	chain->Add(file2);
	int ntotal = chain->GetEntries();
	int nside = ntotal-nsig;
	cout<<"file1 entries: "<<nsig<<endl;
	cout<<"file2 entries: "<<nside<<endl;
	cout<<"file1+file2 entries: "<<ntotal<<endl;	
	
    TFile * outputfile = new TFile(outfile,"RECREATE");
	TTree * outTree = chain->CloneTree(0);

    int nCands;
	//int nEvt;
    chain->SetBranchAddress("nCands",&nCands);
    //chain->SetBranchAddress("nEvt",&nEvt);

	vector <int> sideEvent;

	//save events with signal region candidate for filesig
	for(int i =0; i<nsig; i++)
	{
		//if(i%10000==0)cout<<i<<endl;
		//if(i>200000)break;
		chain->GetEntry(i);
		//cout<<nEvt<<endl;
		//chain->GetEntry(nsig+i);
		//cout<<nEvt<<endl;
		
		if(nCands>0)outTree->Fill();//this event have signal region candidate ( 2 means there are Wmunu and Welenu. This will be filtered by loose lepton veto  )
		else sideEvent.push_back(nsig+i);	
	}
	
	for(int j=0; j<sideEvent.size(); j++ )
	{
		//if(j%10000==0)cout<<j<<endl;
		//if(j>200000)break;
		int n = sideEvent.at(j);
		chain->GetEntry(n);
		if(nCands>0)outTree->Fill();
	}
	
	cout<<"outTree entries: "<<outTree->GetEntries()<<endl;
	
	outputfile->cd();
	outTree->Write();
	outputfile->Close();
}
Пример #5
0
void pre(Int_t setID)
{
    TChain* pstr = new TChain("PSTree","root");
    if (setID==1) {
        for (Int_t i=1; i<10; i++)
            pstr->AddFile(Form("/remote/pclg-10/SIEGFRIED_II/Cd_SII_PS/Cd_In_SII_PS000%d.root",i));
        for (Int_t i=70; i<85; i++)
            pstr->AddFile(Form("/remote/pclg-10/SIEGFRIED_II/Cd_SII_PS/Cd_In_SII_PS00%d.root",i));
    }
    else if (setID==2)
        for (Int_t i=10; i<30; i++)
            pstr->AddFile(Form("/remote/pclg-10/SIEGFRIED_II/Cd_SII_PS/Cd_In_SII_PS00%d.root",i));
    else if (setID==3)
        for (Int_t i=30; i<50; i++)
            pstr->AddFile(Form("/remote/pclg-10/SIEGFRIED_II/Cd_SII_PS/Cd_In_SII_PS00%d.root",i));
    else if (setID==4)
        for (Int_t i=50; i<70; i++)
            pstr->AddFile(Form("/remote/pclg-10/SIEGFRIED_II/Cd_SII_PS/Cd_In_SII_PS00%d.root",i));

    Int_t Cha_MCAEnergy[8];
    pstr->SetBranchAddress("Cha_MCAEnergy",Cha_MCAEnergy);

    TFile* foutput = new TFile(Form("Run4pre%d.root",setID),"recreate");
    TTree *newtree = pstr->CloneTree(0);

    const Int_t Ncha = 7;

    Int_t Nevt = pstr->GetEntries();
    cout<<"Total Events: "<<Nevt<<endl;

    for (Int_t i=0; i<Nevt; i++) {
        if (i%10000==0)
            cout<<"Now event: "<<i<<endl;

        pstr->GetEntry(i);

        Int_t Nseg=0;
        for (Int_t j=1; j<Ncha-1; j++) {
            if (Cha_MCAEnergy[j]>1000 && Cha_MCAEnergy[j]<7000) {
                Nseg++;
            }
        }
        if (Nseg==1) {
            newtree->Fill();
        }
        if (i%10000==0) newtree->Write();
    }

    newtree->Write();
    foutput->Close();
}
Пример #6
0
void again()
{
    TChain* pstr = new TChain("PSTree","root");
    for (Int_t i=1; i<5; i++) pstr->AddFile(Form("Run4pre%d.root",i));

    Int_t Cha_MCAEnergy[8];
    pstr->SetBranchAddress("Cha_MCAEnergy",Cha_MCAEnergy);

    TFile* foutput = new TFile("Run4selected.root","recreate");
    TTree *newtree = pstr->CloneTree(0);

    Int_t Nevt = pstr->GetEntries();
    cout<<"Total Events: "<<Nevt<<endl;

    for (Int_t i=0; i<Nevt; i++) {
        if (i%10000==0)
            cout<<"Now event: "<<i<<endl;

        pstr->GetEntry(i);

        Int_t Nseg=0;
        if (Cha_MCAEnergy[1]>3800 && Cha_MCAEnergy[1]<5200) {
            Nseg++;
        }
        for (Int_t j=2; j<=3; j++) {
            if (Cha_MCAEnergy[j]>2200 && Cha_MCAEnergy[j]<3200) {
                Nseg++;
            }
        }
        for (Int_t j=4; j<=5; j++) {
            if (Cha_MCAEnergy[j]>3000 && Cha_MCAEnergy[j]<4400) {
                Nseg++;
            }
        }

        if (Nseg==1) {
            newtree->Fill();
        }
    }

    newtree->Write();
    foutput->Close();

}
Пример #7
0
void mergeDATA(TString Tree="/afs/cern.ch/work/s/shuai/public/diboson/trees/productionv7_newMJ/fullallrange")
{

	TFile * outputfile = new TFile(Tree+"/treeEDBR_data_xww.root","RECREATE");

	TString treename;
	treename = "SelectedCandidates";

	TChain * chain_SingleEle = new TChain(treename);
	TChain * chain_SingleMu = new TChain(treename);
/*
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012A_13Jul2012_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012A_recover_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012B_13Jul2012_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C_24Aug2012_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C_EcalRecove_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C_PromptReco_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012D_PromptReco_xww.root");

	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012A_13Jul2012_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012A_recover_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012B_13Jul2012_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C_24Aug2012_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C_EcalRecove_xww.root");	
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C_PromptReco_xww.root");	
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012D_PromptReco_xww.root");
*/

	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012A-22Jan2013_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012B-22Jan2013_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C-22Jan2013_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012D-22Jan2013_xww.root");	

	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012A-22Jan2013_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012B-22Jan2013_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C-22Jan2013_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012D-22Jan2013_xww.root");



	TChain * chain = new TChain(treename);
	chain->Add(chain_SingleEle);
	int nele = chain->GetEntries();
	chain->Add(chain_SingleMu);
	int ntotal = chain->GetEntries();
	int nmu  = ntotal - nele;
	cout<<"ele entries: "<<nele<<endl;
	cout<<"mu entries: "<<nmu<<endl;
	cout<<"ele+mu entries: "<<ntotal<<endl;

	TTree * outTree = chain->CloneTree(0);

	double lep[99];
	int nLooseEle;
	int nLooseMu;
	chain->SetBranchAddress("lep", lep);
	chain->SetBranchAddress("nLooseMu", &nLooseMu);
	chain->SetBranchAddress("nLooseEle",&nLooseEle);

	//fill only lep==0 for SingEle
	for(int i=0; i<nele; i++)
	{
		chain->GetEntry(i);
		if(nLooseEle+nLooseMu!=1)continue;
		if(lep[0]==0)outTree->Fill();
	}
	//fill only lep==1 for SingMu
	
	for(int i=nele; i<ntotal; i++)
	{
		chain->GetEntry(i);
		if(nLooseEle+nLooseMu!=1)continue;
		if(lep[0]==1)outTree->Fill();
	}
	

	cout<<"output entries:  "<<outTree->GetEntries()<<endl;

	outputfile->cd();
	outTree->Write();
	outputfile->Close();

}
// Main function
int CCInclusiveEventSelection(std::string GeneratorName, unsigned int ThreadNumber, unsigned int NumberOfThreads)
{

    string Version = "v05_08_00";

//     string GeneratorName = "prodgenie_bnb_nu_cosmic";
//     string GeneratorName = "prodgenie_bnb_nu";
//     string GeneratorName = "prodcosmics_corsika_inTime";
//     string GeneratorName = "data_onbeam_bnb";
//     string GeneratorName = "data_offbeam_bnbext";
//     string GeneratorName = "prodgenie_bnb_nu_cosmic_uboone";
//     string GeneratorName = "prodgenie_bnb_nu_cosmic_sc_uboone";

    // Initialize and fill track reco product names
    std::vector<string> TrackProdNameVec;

//     TrackProdNameVec.push_back("pandoraNuKHit");
//     TrackProdNameVec.push_back("pandoraCosmic");
    TrackProdNameVec.push_back("pandoraNu");
//     TrackProdNameVec.push_back("pmtrack");
//     TrackProdNameVec.push_back("pandoraNuPMA");
//     TrackProdNameVec.push_back("trackkalmanhit");

    // Initialize and fill vertex reco product names
    std::vector<string> VertexProdNameVec;

//     VertexProdNameVec.push_back("nuvtx");
//     VertexProdNameVec.push_back("pandoraCosmic");
    VertexProdNameVec.push_back("pandoraNu");
//     VertexProdNameVec.push_back("pmtrack");

    std::string FileNumberStr;

    if(NumberOfThreads > 1)
    {
        FileNumberStr = "_" + std::to_string(ThreadNumber);
    }
    else
    {
        FileNumberStr = "";
    }

    std::cout << "Data Sample : " << GeneratorName << std::endl;


    TChain *treenc = new TChain("analysistree/anatree");

    if(GeneratorName == "data_onbeam_bnb")
    {
//         treenc -> Add( ("/pnfs/uboone/persistent/users/aschu/onbeam_data_bnbSWtrigger/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
        std::ifstream FileNames("/pnfs/uboone/persistent/users/aschu/devel/v05_11_01/hadd/GOODBNBBEAM/filesana.list");

        std::string FileName;

        while(std::getline(FileNames,FileName))
        {
            std::cout << FileName << std::endl;
            treenc -> Add((FileName).c_str());
        }
    }
    else if(GeneratorName == "data_offbeam_bnbext")
    {
//         treenc -> Add( ("/pnfs/uboone/persistent/users/aschu/offbeam_data_bnbSWtrigger/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
        std::ifstream FileNames("/pnfs/uboone/persistent/users/aschu/devel/v05_11_01/hadd/GOODEXTBNB/filesana.list");

        std::string FileName;

        while(std::getline(FileNames,FileName))
        {
            std::cout << FileName << std::endl;
            treenc -> Add((FileName).c_str());
        }
    }
    else if(GeneratorName == "prodgenie_bnb_nu_cosmic_uboone")
    {
        treenc -> Add( ("/pnfs/uboone/persistent/users/aschu/MC_BNB_Cosmic/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
    }
    else if(GeneratorName == "TEM" || GeneratorName == "MEC" || GeneratorName == "MA" || GeneratorName == "BITE")
    {
        treenc -> Add( ("/pnfs/uboone/persistent/users/aschu/"+GeneratorName+"/"+GeneratorName+"merge.root").c_str() );
    }
    else
    {
        treenc -> Add( ("/lheppc46/data/uBData/anatrees/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
    }

//     treenc -> Add( ("/lheppc46/data/uBData/anatrees/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
//     treenc -> Add( ("/media/christoph/200EFBDA63AA160B/anatrees/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
//     treenc -> Add( ("/pnfs/uboone/persistent/users/aschu/onbeam_data_bnbSWtrigger/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
//     treenc -> Add( ("/pnfs/uboone/persistent/users/aschu/offbeam_data_bnbSWtrigger/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );
//     treenc -> Add( ("/pnfs/uboone/persistent/users/aschu/MC_BNB_Cosmic/"+GeneratorName+"_"+Version+"_anatree.root").c_str() );

    //maximum array sizes
    const int maxentries = 35000;
    const int maxtracks = 10000;
    const int maxvtx = 500;
    const int maxnu = 10;
    const int maxmc = 10;
    const int kMaxFlashes = 5000;

    //Define variables to read from Tree
    Int_t           event;
    Int_t           run;
    Int_t           subrun;
    Int_t           triggerbits; //this is only important for data. 2048 = BNB stream
    Double_t        potbnb; //this is only important for data

    Short_t         ntracks_reco; //number of reco tracks
    Short_t         trkbestplane[maxtracks]; //plane that has most hits for a given track
    Float_t         trklen[maxtracks]; //track length
    Float_t         trkstartx[maxtracks];
    Float_t         trkstarty[maxtracks];
    Float_t         trkstartz[maxtracks];
    Float_t         trkendx[maxtracks];
    Float_t         trkendy[maxtracks];
    Float_t         trkendz[maxtracks];
    Float_t         trktheta[maxtracks];
    Float_t         trkphi[maxtracks];
    Float_t         trkmomrange[maxtracks]; //track momentum calculated from track range
    Short_t         trkId[maxtracks];
    Short_t         trkorigin[maxtracks][3]; //for MC only: which true particle contributes most hits to the reco track: 2 = cosmic. 1 = neutrino
    Int_t           TrackIDTruth[maxtracks][3]; // MC id matched with reco track
    bool            vertexatstart[maxtracks]; //for analysis: is the vertex at start of the track?
    bool            vertexatend[maxtracks]; //for analysis: ist the vertex at end of track?

    Int_t           no_flashes; //number of flashes in the event
    Float_t         flash_time[kMaxFlashes]; //flash time (in microseconds)
    Float_t         flash_pe[kMaxFlashes]; //total number of photoelectrons corresponding to the flash
    Float_t         flash_zcenter[kMaxFlashes]; //z center of flash (in cm)
    Float_t         flash_ycenter[kMaxFlashes]; //y center of flash (in cm)

    Short_t         nvtx;
    Float_t         vtxx[maxvtx];
    Float_t         vtxy[maxvtx];
    Float_t         vtxz[maxvtx];

    //finding candidate nu interaction vertex in event
    bool            candvertex[maxvtx];
    Short_t         candtrack[maxvtx];
    Float_t         candlength[maxvtx];
    Short_t         numuvertex = -1;
    Short_t         mutrack = -1;
    Float_t         mutracklength = 0;

    //MC truth
    Int_t           mcevts_truth; //neutrino interactions per event
    Float_t         nuvtxx_truth[maxmc]; //true vertex x (in cm)
    Float_t         nuvtxy_truth[maxmc];
    Float_t         nuvtxz_truth[maxmc];
    Int_t           ccnc_truth[maxmc]; //CC = 0, NC = 1
    Int_t           nuPDG_truth[maxmc]; //true neutrino pdg code. numu = 14
    Int_t           mode_truth[maxmc]; //QE = 0, RES = 1, DIS = 2
    Int_t	    PDG_truth[maxtracks];

    Int_t	   NumberOfMCTracks;

    Float_t	   XMCTrackStart[maxtracks];
    Float_t	   YMCTrackStart[maxtracks];
    Float_t	   ZMCTrackStart[maxtracks];

    Float_t	   XMCTrackEnd[maxtracks];
    Float_t	   YMCTrackEnd[maxtracks];
    Float_t	   ZMCTrackEnd[maxtracks];

    Int_t          MCTrackID[maxtracks];
    Int_t          MCTrueIndex[maxtracks];


    //define cut variables
    double flashwidth = 80; //cm. Distance flash-track
    double distcut = 5; //cm. Distance track start/end to vertex
    double lengthcut = 75; //cm. Length of longest track
    double beammin = 3.55/*-0.36*/; //us. Beam window start
    double beammax = 5.15/*-0.36*/; //us. Beam window end
    double PEthresh = 50; //PE
    double MCTrackToMCVtxDist = 0.5; //cm. distance between mc track start and mc vertex
    double TrackToMCDist = 5; //cm. Distance track start/end to mcvertex

    if(GeneratorName == "data_bnb" || GeneratorName == "data_onbeam_bnb")
    {
        std::cout << "Changed beam gate window for on-beam data" << std::endl;
        beammin = 3.3;
        beammax = 4.9;
    }
    if(GeneratorName == "data_offbeam_bnbext")
    {
        std::cout << "Changed beam gate window for off-beam data" << std::endl;
        beammin = 3.65;
        beammax = 5.25;
    }
    if(GeneratorName == "prodcosmics_corsika_inTime")
    {
        std::cout << "Changed beam gate window for Corsika sample" << std::endl;
        beammin = 3.2;
        beammax = 4.8;
    }

    // Loop over all product names
    for(const auto& TrackingName : TrackProdNameVec)
    {
        for(const auto& VertexingName : VertexProdNameVec)
        {
            // Open output file
            TFile* OutputFile = new TFile(("rootfiles/Hist_Track_"+TrackingName+ "_Vertex_" + VertexingName + "_"+GeneratorName+"_"+Version+FileNumberStr+"_Old.root").c_str(),"RECREATE");
            // Make a clone tree which gets filled
            TTree *SelectionTree = treenc->CloneTree(0);

            treenc -> SetBranchAddress("event", &event);
            treenc -> SetBranchAddress("potbnb", &potbnb);
            treenc -> SetBranchAddress("no_flashes", &no_flashes);
            treenc -> SetBranchAddress("flash_time", flash_time);
            treenc -> SetBranchAddress("flash_pe", flash_pe);
            treenc -> SetBranchAddress("flash_zcenter", flash_zcenter);
            treenc -> SetBranchAddress("flash_ycenter", flash_ycenter);
            treenc -> SetBranchAddress("mcevts_truth", &mcevts_truth);
            treenc -> SetBranchAddress("nuvtxx_truth", nuvtxx_truth);
            treenc -> SetBranchAddress("nuvtxy_truth", nuvtxy_truth);
            treenc -> SetBranchAddress("nuvtxz_truth", nuvtxz_truth);
            treenc -> SetBranchAddress("ccnc_truth", ccnc_truth);
            treenc -> SetBranchAddress("nuPDG_truth", nuPDG_truth);
            treenc -> SetBranchAddress("pdg", PDG_truth);
            treenc -> SetBranchAddress("mode_truth", mode_truth);
            treenc -> SetBranchAddress("geant_list_size", &NumberOfMCTracks);
            treenc -> SetBranchAddress("StartPointx", XMCTrackStart);
            treenc -> SetBranchAddress("StartPointy", YMCTrackStart);
            treenc -> SetBranchAddress("StartPointz", ZMCTrackStart);
            treenc -> SetBranchAddress("EndPointx", XMCTrackEnd);
            treenc -> SetBranchAddress("EndPointy", YMCTrackEnd);
            treenc -> SetBranchAddress("EndPointz", ZMCTrackEnd);
            treenc -> SetBranchAddress("TrackId", MCTrackID);
            treenc -> SetBranchAddress("MCTruthIndex", MCTrueIndex);

            // Product specific stuff
            treenc -> SetBranchAddress(("ntracks_"+TrackingName).c_str(),&ntracks_reco);
            treenc -> SetBranchAddress(("trkstartx_"+TrackingName).c_str(),trkstartx);
            treenc -> SetBranchAddress(("trkstarty_"+TrackingName).c_str(),trkstarty);
            treenc -> SetBranchAddress(("trkstartz_"+TrackingName).c_str(),trkstartz);
            treenc -> SetBranchAddress(("trkendx_"+TrackingName).c_str(),trkendx);
            treenc -> SetBranchAddress(("trkendy_"+TrackingName).c_str(),trkendy);
            treenc -> SetBranchAddress(("trkendz_"+TrackingName).c_str(),trkendz);
            treenc -> SetBranchAddress(("trktheta_"+TrackingName).c_str(),trktheta);
            treenc -> SetBranchAddress(("trkphi_"+TrackingName).c_str(),trkphi);
            treenc -> SetBranchAddress(("trkorigin_"+TrackingName).c_str(),trkorigin);
            treenc -> SetBranchAddress(("trkidtruth_"+TrackingName).c_str(),TrackIDTruth);
            treenc -> SetBranchAddress(("trkpidbestplane_"+TrackingName).c_str(), trkbestplane);

            // Program hack to apply for non uniform naming of nuvtx
            if(VertexingName != "nuvtx")
            {
                treenc -> SetBranchAddress(("nvtx_"+VertexingName).c_str(), &nvtx);
                treenc -> SetBranchAddress(("vtxx_"+VertexingName).c_str(), vtxx);
                treenc -> SetBranchAddress(("vtxy_"+VertexingName).c_str(), vtxy);
                treenc -> SetBranchAddress(("vtxz_"+VertexingName).c_str(), vtxz);
            }
            else
            {
                treenc -> SetBranchAddress("nnuvtx", &nvtx);
                treenc -> SetBranchAddress("nuvtxx", vtxx);
                treenc -> SetBranchAddress("nuvtxy", vtxy);
                treenc -> SetBranchAddress("nuvtxz", vtxz);
            }

            int theflash = -1;

            double diststart = 0;
            double distend = 0;
            double length = 0;

            int ntrue = 0;

            int TrackCandidate;
            int VertexCandidate;

            int MCTrackCandidate;
            int MCVertexCandidate;
            int NuMuCCTrackCandidate;

            unsigned int EventsWithFlash = 0;
            unsigned int EventsVtxInFV = 0;
            unsigned int EventsTrackNearVertex = 0;
            unsigned int EventsFlashMatched = 0;
            unsigned int EventsTracksInFV = 0;
            unsigned int EventsNearVtx = 0;
            unsigned int EventsTrackLong = 0;
            unsigned int EventsTruelyReco = 0;

            unsigned int MCEventsWithFlash = 0;
            unsigned int MCEventsVtxInFV = 0;
            unsigned int MCEventsTrackNearVertex = 0;
            unsigned int MCEventsFlashMatched = 0;
            unsigned int MCEventsTracksInFV = 0;
            unsigned int MCEventsNearVtx = 0;
            unsigned int MCEventsTrackLong = 0;

            unsigned int NumberOfSignalTruth = 0;
            unsigned int NumberOfSignalTruthSel = 0;
            unsigned int NumberOfBgrNCTruthSel = 0;
            unsigned int NumberOfBgrNumuBarTruthSel = 0;
            unsigned int NumberOfBgrNueTruthSel = 0;
            unsigned int NumberOfBgrCosmicSel = 0;
            unsigned int NumberOfBgrNuOutFVSel = 0;
            unsigned int NumberOfUnknownCCBgr = 0;
            unsigned int NumberOfUnknownBgr = 0;

            TBranch* BrTrackCand = SelectionTree->Branch("TrackCand",&TrackCandidate,"TrackCand/I");
            TBranch* BrVtxCand = SelectionTree->Branch("VertexCand",&VertexCandidate,"VertexCand/I");
            TBranch* BrMCTrackCand = SelectionTree->Branch("MCTrackCand",&MCTrackCandidate,"MCTrackCand/I");
            TBranch* BrMCVtxCand = SelectionTree->Branch("MCVertexCand",&MCVertexCandidate,"MCVertexCand/I");

            double TotalPOT = 0.0;

            int Size = treenc -> GetEntries();

            // Set start and end event number for multiple threads
            unsigned long int StartEvent = Size*(ThreadNumber - 1)/NumberOfThreads;
            unsigned long int EndEvent = Size*ThreadNumber/NumberOfThreads;

            std::cout << "number of events used is: " << EndEvent-StartEvent << " of " << Size << std::endl;
            
            //Event Loop
            for(int i = StartEvent; i < EndEvent; i++)
            {
                if(i == 121558 && GeneratorName == "MEC") continue;
                if(i%1000 == 0) cout << "\t... " << i << endl;

                // Get tree entries
                treenc -> GetEntry(i);

                bool flashtag = false;
                float flashmax = 0;

                // Loop over all flashes
                for(int f = 0; f < no_flashes; f++)
                {
                    // If the flash is in the beam window and above threshold set flashtag to true
                    if( (flash_time[f] > beammin && flash_time[f] < beammax) && flash_pe[f] > PEthresh )
                    {
                        flashtag = true; //the event does have a flash inside the beam window

                        // If the new flash has more PE than the current maximum, replace the maximum
                        if(flash_pe[f] > flashmax)
                        {
                            theflash = f;
                            flashmax = flash_pe[f];
                        }
                    }
                } // flash loop

                // Preset MC candidate variables
                MCTrackCandidate = -1;
                MCVertexCandidate = -1;
                NuMuCCTrackCandidate = -1;

                // Loop over all MC neutrino vertices
                for(unsigned vertex_no = 0; vertex_no < mcevts_truth; vertex_no++)
                {
                    // Check if there is a numuCC vertex in the FV
                    if( nuPDG_truth[vertex_no] == 14 && ccnc_truth[vertex_no] == 0 && inFV(nuvtxx_truth[vertex_no],nuvtxy_truth[vertex_no],nuvtxz_truth[vertex_no]) )
                    {
                        // Increase truth count
                        NumberOfSignalTruth++;
                        
                        // Loop over all MC particles
                        for(unsigned track_no = 0; track_no < NumberOfMCTracks; track_no++)
                        {
                            // If the a muon is not contained in a singel neutrino event, set mc-track contained flag to false
                            if( PDG_truth[track_no] == 13 
                                && MCTrueIndex[track_no] == vertex_no&& sqrt(pow(XMCTrackStart[track_no] - nuvtxx_truth[vertex_no],2) + pow(YMCTrackStart[track_no] - nuvtxy_truth[vertex_no],2) + pow(ZMCTrackStart[track_no] - nuvtxz_truth[vertex_no],2)) < MCTrackToMCVtxDist )
                            {
                                // Fill track candidate index
                                NuMuCCTrackCandidate = track_no;
                            }
                        } // MC particle loop
                    } // If numuCC in FV
                } // MC vertex loop

                // If the flash tag is ture and we have POT
                if(flashtag)
                {
                    // Prepare flags
                    bool VertexInFVFlag = true;
                    bool TrackDistanceFlag = true;
                    bool FlashMatchFlag = true;
                    bool TrackContainedFlag = false;

                    // Increase events with flash > 50 PE and within beam window
                    EventsWithFlash++;
                    if(NuMuCCTrackCandidate > -1)
                        MCEventsWithFlash++;

                    // Initialize Track Candidate properties
                    TrackCandidate = -1;
                    float TrackCandLength = 0;

                    VertexCandidate = -1;

                    // Loop over all vertices
                    for(int v = 0; v < nvtx; v++)
                    {
                        // If the vertex is contained
                        if(inFV(vtxx[v], vtxy[v], vtxz[v]))
                        {
                            // Increase count of events with a vertex in FV
                            if(VertexInFVFlag)
                            {
                                EventsVtxInFV++;
                                if(NuMuCCTrackCandidate > -1)
                                    MCEventsVtxInFV++;

                                VertexInFVFlag = false;
                            }

                            unsigned int TrackCountAtVertex = 0;

                            // Loop over all reconstructed tracks
                            for(int j = 0; j < ntracks_reco; j++)
                            {
                                // Calculate distances from track start/end to vertex and calculate track lenth
                                diststart = sqrt((vtxx[v] - trkstartx[j])*(vtxx[v] - trkstartx[j]) + (vtxy[v] - trkstarty[j])*(vtxy[v] - trkstarty[j]) + (vtxz[v] - trkstartz[j])*(vtxz[v] - trkstartz[j]));
                                distend = sqrt((vtxx[v] - trkendx[j])*(vtxx[v] - trkendx[j]) + (vtxy[v] - trkendy[j])*(vtxy[v] - trkendy[j]) + (vtxz[v] - trkendz[j])*(vtxz[v] - trkendz[j]));
                                length = sqrt(pow(trkstartx[j] - trkendx[j],2) + pow(trkstarty[j] - trkendy[j],2) + pow(trkstartz[j] - trkendz[j],2));

                                // If the track vertex distance is within cut, increase track count
                                if(diststart < distcut || distend < distcut)
                                {
                                    // Increase count of events with a distance to vertex < 5 cm
                                    if(TrackDistanceFlag)
                                    {
                                        EventsTrackNearVertex++;
                                        if(NuMuCCTrackCandidate > -1)
                                            MCEventsTrackNearVertex++;

                                        TrackDistanceFlag = false;
                                    }

                                    // Increase track at vertex count
                                    TrackCountAtVertex++;

                                    // Find the longest track from this vertex
                                    if(length > TrackCandLength)
                                    {
                                        TrackCandLength = length;
                                        TrackCandidate = j;
                                        VertexCandidate = v;
                                    }
                                } // if track vertex distance is within cut distance
                            } // reco track loop
                        } // if vertex is contained
                    } // vertex loop

                    // If the longest track length is filled
                    if(TrackCandidate > -1)
                    {
                        // If the longest track is flash matched
                        if( FlashTrackDist(flash_zcenter[theflash], trkstartz[TrackCandidate], trkendz[TrackCandidate]) < flashwidth )
                        {
                            if(FlashMatchFlag)
                            {
                                EventsFlashMatched++;
                                if(NuMuCCTrackCandidate > -1)
                                    MCEventsFlashMatched++;

                                FlashMatchFlag = false;
                                // Set track contained flag true, so the other cuts can be applied on this vertex
                                TrackContainedFlag = true;
                            }

                            // If the longest track is fully contained
                            if( inFV(trkstartx[TrackCandidate], trkstarty[TrackCandidate], trkstartz[TrackCandidate])
                                    && inFV(trkendx[TrackCandidate], trkendy[TrackCandidate], trkendz[TrackCandidate])
                                    && TrackContainedFlag )
                            {
                                EventsTracksInFV++;
                                if(NuMuCCTrackCandidate > -1)
                                    MCEventsTracksInFV++;

                                // If longest track is longer than 75 cm
                                if(TrackCandLength > lengthcut)
                                {
                                    // If track origin is neutrino
                                    if(trkorigin[TrackCandidate][trkbestplane[TrackCandidate]] == 1)
                                    {
                                        // Loop over all MCTracks
                                        for(unsigned track_no = 0; track_no < NumberOfMCTracks; track_no++)
                                        {
                                            // If MCTrackID is the same as the back tracked TruthID
                                            if(MCTrackID[track_no] == TrackIDTruth[TrackCandidate][trkbestplane[TrackCandidate]])
                                            {
                                                // Store new MCTrackCandidate and MCVertexCandidate
                                                MCTrackCandidate = track_no;
                                                MCVertexCandidate = MCTrueIndex[track_no];
                                            }
                                        } // end MCtrack loop
                                    } // if neutrino origin

                                    EventsTrackLong++;
                                    if(NuMuCCTrackCandidate > -1)
                                        MCEventsTrackLong++;

                                    // If the event is a CC interaction and the selected track is of neutrino origin
                                    if(MCVertexCandidate > -1 && ccnc_truth[MCVertexCandidate] == 0 && trkorigin[TrackCandidate][trkbestplane[TrackCandidate]] == 1)
                                    {
                                        // If there is a track candidate
                                        if(nuPDG_truth[MCVertexCandidate] == 14 && inFV(nuvtxx_truth[MCVertexCandidate],nuvtxy_truth[MCVertexCandidate],nuvtxz_truth[MCVertexCandidate]))
                                        {
                                            NumberOfSignalTruthSel++;
                                        }
                                        else if(nuPDG_truth[MCVertexCandidate] == -14) // if anti-neutrino
                                        {
                                            NumberOfBgrNumuBarTruthSel++;
                                        }
                                        else if(abs(nuPDG_truth[MCVertexCandidate]) == 12) // if electron like neutrino
                                        {
                                            NumberOfBgrNueTruthSel++;
                                        }
                                        else if(!inFV(nuvtxx_truth[MCVertexCandidate],nuvtxy_truth[MCVertexCandidate],nuvtxz_truth[MCVertexCandidate])) // if not in fiducial volume
                                        {
                                            NumberOfBgrNuOutFVSel++;
                                        }
                                        else
                                        {
                                            NumberOfUnknownCCBgr++;
                                        }
                                    } // if CC interaction
                                    else if(MCVertexCandidate > -1 && ccnc_truth[MCVertexCandidate] == 1 && trkorigin[TrackCandidate][trkbestplane[TrackCandidate]] == 1) // else if NC interaction
                                    {
                                        NumberOfBgrNCTruthSel++;
                                    }
                                    else if(trkorigin[TrackCandidate][trkbestplane[TrackCandidate]] != 1) // If selected track is not associated to a neutrino
                                    {
                                        NumberOfBgrCosmicSel++;
                                    }
                                    else
                                    {
                                        NumberOfUnknownBgr++;
                                    }

                                    SelectionTree -> Fill();

                                    double TrkStartMCStartDist = sqrt(pow(XMCTrackStart[MCTrackCandidate] - trkstartx[TrackCandidate],2) + pow(YMCTrackStart[MCTrackCandidate] - trkstarty[TrackCandidate],2) + pow(ZMCTrackStart[MCTrackCandidate] - trkstartz[TrackCandidate],2));
                                    double TrkEndMCEndDist = sqrt(pow(XMCTrackEnd[MCTrackCandidate] - trkendx[TrackCandidate],2) + pow(YMCTrackEnd[MCTrackCandidate] - trkendy[TrackCandidate],2) + pow(ZMCTrackEnd[MCTrackCandidate] - trkendz[TrackCandidate],2));
                                    double TrkStartMCEndDist = sqrt(pow(XMCTrackEnd[MCTrackCandidate] - trkstartx[TrackCandidate],2) + pow(YMCTrackEnd[MCTrackCandidate] - trkstarty[TrackCandidate],2) + pow(ZMCTrackEnd[MCTrackCandidate] - trkstartz[TrackCandidate],2));
                                    double TrkEndMCStartDist = sqrt(pow(XMCTrackStart[MCTrackCandidate] - trkendx[TrackCandidate],2) + pow(YMCTrackStart[MCTrackCandidate] - trkendy[TrackCandidate],2) + pow(ZMCTrackStart[MCTrackCandidate] - trkendz[TrackCandidate],2));

                                    // if the muon track of the NuMuCC interaction is matched correctly
                                    if( MCVertexCandidate > -1 && inFV(nuvtxx_truth[MCVertexCandidate],nuvtxy_truth[MCVertexCandidate],nuvtxz_truth[MCVertexCandidate])
                                            && PDG_truth[MCTrackCandidate] == 13 && MCTrackID[MCTrackCandidate] == TrackIDTruth[TrackCandidate][trkbestplane[TrackCandidate]] )
                                    {
                                        EventsTruelyReco++;
                                    }
                                } // if track is longer than 75 cm
                            } // if track is contained
                            // Set track contained flag false
                            TrackContainedFlag = false;
                        } // If flash matched
                    } // If there is a longest track
                } // if flashtag

                // Increase the neutrino count
                ntrue++;

                // Add POT count
                TotalPOT += potbnb;
            }//loop over all events

            OutputFile->cd();

//             SelectionTree->Print();
            SelectionTree->Write();

            std::cout << "--------------------------------------------------------------------------------------------" << std::endl;
            std::cout << std::endl;
            std::cout << "Track Reco Product Name : " << TrackingName << "  Vertex Reco Product Name : " << VertexingName << std::endl;
            std::cout << "Total POT : " << TotalPOT*1e12 << std::endl;
            std::cout << "number of CC events with vertex in FV : " << ntrue << std::endl;
            std::cout << "number of events with flash > 50 PE : " << EventsWithFlash << " " << MCEventsWithFlash << std::endl;
            std::cout << "number of events with vtx in FV : " << EventsVtxInFV << " " << MCEventsVtxInFV << std::endl;
            std::cout << "number of events with track start/end within 5cm to vtx : " << EventsTrackNearVertex << " " << MCEventsTrackNearVertex << std::endl;
            std::cout << "number of events with tracks matched within 80cm to flash : " << EventsFlashMatched << " " << MCEventsFlashMatched << std::endl;
            std::cout << "number of events with contained tracks : " << EventsTracksInFV << " " << MCEventsTracksInFV << std::endl;
            std::cout << "number of events with longest track > 75cm : " << EventsTrackLong << " " << MCEventsTrackLong << std::endl;
            std::cout << "number of events with track start end within 5cm to mc-vtx : " << EventsTruelyReco << std::endl;
            std::cout << "number of events with contained MC tracks : " << NumberOfSignalTruth << std::endl;
            std::cout << "number of well selected events : " << NumberOfSignalTruthSel << std::endl;
            std::cout << "number of NC events selected : " << NumberOfBgrNCTruthSel << std::endl;
            std::cout << "number of anti-Neutrino events selected : " << NumberOfBgrNumuBarTruthSel << std::endl;
            std::cout << "number of Nu_e events selected : " << NumberOfBgrNueTruthSel << std::endl;
            std::cout << "number of events selected cosmic : " << NumberOfBgrCosmicSel << std::endl;
            std::cout << "number of nu_mu events out of FV : " << NumberOfBgrNuOutFVSel <<std::endl;
            std::cout << "event selection efficiency : " <<  (float)NumberOfSignalTruthSel/(float)NumberOfSignalTruth << std::endl;
//             std::cout << "event selection purity : " << (float)NumberOfSignalTruthSel/(float)(NumberOfBgrNCTruthSel+NumberOfBgrNumuBarTruthSel+NumberOfBgrNueTruthSel)
            std::cout << "event selection correctness : " <<  (float)EventsTruelyReco/(float)EventsTrackLong << std::endl;
//             std::cout << "event selection missid rate : " <<  fabs((float)EventsTruelyReco-(float)NumberOfSignalTruth)/(float)NumberOfSignalTruth << std::endl;
            std::cout << std::endl;
            std::cout << "number of unknown CC bgr : " <<  NumberOfUnknownCCBgr << std::endl;
            std::cout << "number of unknown bgr : " <<  NumberOfUnknownBgr << std::endl;
            std::cout << std::endl;
            std::cout << "--------------------------------------------------------------------------------------------" << std::endl;

            delete BrMCTrackCand;
            delete BrTrackCand;
            delete BrVtxCand;
            delete BrMCVtxCand;

            delete SelectionTree;

            OutputFile->Close();

            // Erase all branch addresses for the next iteration
            treenc -> ResetBranchAddresses();

        } // Loop over all vertexing data products
    } // Loop over all tracking data products

    return 0;

} // end main function
Пример #9
0
void TreeFiller(string inFiles, string outFile, string histName) {

	
	TChain *origFiles = new TChain("treeVars", "treeVars");
	origFiles->Add(inFiles.c_str());
	
	int nEntries = origFiles->GetEntries();
	cout << "The old chain contains " << nEntries << " entries." << endl;
	
	
	float puWeight, jet1Eta, jet2Eta, deltaY, genTopPt1, genTopPt2, jet1Mass, jet2Mass, jet1MinMass, jet2MinMass, jet1BDisc, jet2BDisc, jet1SubjetMaxBDisc, jet2SubjetMaxBDisc,
			jet1tau32, jet2tau32, jet1Pt, jet2Pt, jet1bSF, jet2bSF, jet1bSFErrUp, jet2bSFErrUp, jet1bSFErrDn, jet2bSFErrDn, jetPtForMistag, mttMass, mttMassPred, mistagWt, mistagWtErr, mistagWtAll, mistagWtNsubAll, mistagWtNsub, NNoutput, ptReweight, cutflow, index, trigWt;
	int jet1NSubjets, jet2NSubjets, jet1Parton, jet2Parton, npv;
		
	origFiles->SetBranchAddress("npv", &npv);
	origFiles->SetBranchAddress("jet1Eta", &jet1Eta);
	origFiles->SetBranchAddress("jet2Eta", &jet2Eta);
	origFiles->SetBranchAddress("deltaY", &deltaY);
	origFiles->SetBranchAddress("jet1Mass", &jet1Mass);
	origFiles->SetBranchAddress("jet2Mass", &jet2Mass);
	origFiles->SetBranchAddress("jet1minMass", &jet1MinMass);
	origFiles->SetBranchAddress("jet2minMass", &jet2MinMass);
	origFiles->SetBranchAddress("jet1Nsubj", &jet1NSubjets);
	origFiles->SetBranchAddress("jet2Nsubj", &jet2NSubjets);
	origFiles->SetBranchAddress("jet1BDisc", &jet1BDisc);
	origFiles->SetBranchAddress("jet2BDisc", &jet2BDisc);
	origFiles->SetBranchAddress("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet1tau32", &jet1tau32);
	origFiles->SetBranchAddress("jet2tau32", &jet2tau32);
	origFiles->SetBranchAddress("jet1Pt", &jet1Pt);
	origFiles->SetBranchAddress("jet2Pt", &jet2Pt);
	origFiles->SetBranchAddress("jetPtForMistag", &jetPtForMistag);
	origFiles->SetBranchAddress("mttMass", &mttMass);
	origFiles->SetBranchAddress("mttMassPred", &mttMassPred);
	origFiles->SetBranchAddress("index", &index);
	origFiles->SetBranchAddress("cutflow", &cutflow);
	origFiles->SetBranchAddress("NNoutput", &NNoutput);
	origFiles->SetBranchAddress("mistagWt", &mistagWt);
	origFiles->SetBranchAddress("genTopPt1", &genTopPt1);	
	origFiles->SetBranchAddress("genTopPt2", &genTopPt2);
	origFiles->SetBranchAddress("jet1Parton", &jet1Parton);
	origFiles->SetBranchAddress("jet2Parton", &jet2Parton);	
	origFiles->SetBranchAddress("trigWt", &trigWt);
	
	TFile *newFile = new TFile(outFile.c_str(), "RECREATE");
	TTree *newTree = origFiles->CloneTree(0);
	newTree->Branch("mistagWtNsub", &mistagWtNsub, "mistagWtNsub/F");
	newTree->Branch("mistagWtNsubAll", &mistagWtNsubAll, "mistagWtNsubAll/F");
	newTree->Branch("mistagWtAll", &mistagWtAll, "mistagWtAll/F");
	newTree->Branch("ptReweight", &ptReweight, "ptReweight/F");
	newTree->Branch("puWeight", &puWeight, "puWeight/F");
	newTree->Branch("jet1bSF", &jet1bSF, "jet1bSF/F");
	newTree->Branch("jet2bSF", &jet2bSF, "jet2bSF/F");
	newTree->Branch("jet1bSFErrUp", &jet1bSFErrUp, "jet1bSFErrUp/F");
	newTree->Branch("jet2bSFErrUp", &jet2bSFErrUp, "jet2bSFErrUp/F");
	newTree->Branch("jet1bSFErrDn", &jet1bSFErrDn, "jet1bSFErrDn/F");
	newTree->Branch("jet2bSFErrDn", &jet2bSFErrDn, "jet2bSFErrDn/F");
	newTree->Branch("mistagWtErr", &mistagWtErr, "mistagWtErr/F");

	newTree->SetBranchAddress("mistagWtNsub", &mistagWtNsub);
	newTree->SetBranchAddress("misagWtNsubAll", &mistagWtNsubAll);
	newTree->SetBranchAddress("mistagWtAll", &mistagWtAll);
	newTree->SetBranchAddress("ptReweight", &ptReweight);
	newTree->SetBranchAddress("puWeight", &puWeight);
	newTree->SetBranchAddress("mistagWtErr", &mistagWtErr);

/*	
	TMVA::Reader* reader = new TMVA::Reader();
	reader->AddVariable("jet1Eta", &jet1Eta);
	reader->AddVariable("jet2Eta", &jet2Eta);
	reader->AddVariable("deltaY", &deltaY);
	reader->AddVariable("jet1Mass", &jet1Mass);
	reader->AddVariable("jet2Mass", &jet2Mass);
	reader->AddVariable("jet1BDisc", &jet1BDisc);
	reader->AddVariable("jet2BDisc", &jet2BDisc);
	reader->AddVariable("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	reader->AddVariable("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	reader->AddVariable("jet1tau32", &jet1tau32);
	reader->AddVariable("jet2tau32", &jet2tau32);
	reader->AddVariable("jet1Pt", &jet1Pt);
	reader->AddVariable("jet2Pt", &jet2Pt);
	reader->AddVariable("mttMass", &mttMass);

	reader->BookMVA("MLP", "weights/TMVA_tt_Zp_MLP.weightsZp10_cut4.xml");
*/	
	//TFile *mistagFileLow = new TFile("notCSVL_notCSVM_mistag.root");
	//TFile *mistagFileMed = new TFile("CSVL_notCSVM_mistag.root");
	//TFile *mistagFileHi = new TFile("CSVM_mistag.root");
	TFile *mistagFile = new TFile("Jul3_mistag.root");//data_AllBscore_mistag_Dec16.root");
	histName = "MISTAG_RATE_SUB_TTBAR_Inclusive";
	TFile *triggerFile = new TFile("trigger_weights.root");
	TH1F *triggerHist = (TH1F *) triggerFile->Get("triggerHist");
	TH3F *mistagRateHistAll = (TH3F *) mistagFile->Get( histName.c_str() )->Clone();	
	cout << histName << endl;
	cout << "Entries " << mistagRateHistAll->Integral() << endl;	
	TFile *puFile = new TFile("puHists.root");
	TH1F *puWeightsHist = (TH1F *) puFile->Get("weightsH");
	
	for (int i = 0; i < origFiles->GetEntries(); i++){
	
		origFiles->GetEntry(i);
		if  (i % 1000000 == 0) cout << 100*(float(i) / float(nEntries)) << " Percent Complete." << endl;
		mistagWt = 0.000;
		mistagWtNsub = 30.0000;
		puWeight = puWeightsHist->GetBinContent(npv); 	
		triggerWt = triggerHist->GetBinContent( triggerHist->FindBin( jet1Pt + jet2Pt ) );

		if (cutflow == 4 || index == 1){
		
			if (genTopPt1 > 400) genTopPt1 = 400;
			if (genTopPt2 > 400) genTopPt2 = 400;
			//NNoutput =  reader->EvaluateMVA("MLP");
			ptReweight = sqrt( exp(0.156 - 0.00137*genTopPt1)*exp(0.156 - 0.00137*genTopPt2) );			
		
			
			jet1bSF = 1.0;
			jet1bSFErrUp = 1.0;
			jet1bSFErrDn = 1.0;
			jet2bSF = 1.0;
			jet2bSFErrUp = 1.0;
			jet2bSFErrDn = 1.0;

			if (jet1BDisc > 0.679){
				jet1bSF = findBSF(jet1Pt, jet1Eta, jet1Parton, 0);
				jet1bSFErrUp = findBSF(jet1Pt, jet1Eta, jet1Parton, 1);
				jet1bSFErrDn = findBSF(jet1Pt, jet1Eta, jet1Parton, -1);
			}
			if (jet2BDisc > 0.679){
				jet2bSF = findBSF(jet2Pt, jet2Eta, jet2Parton, 0);
				jet2bSFErrUp = findBSF(jet2Pt, jet2Eta, jet2Parton, 1);
				jet2bSFErrDn = findBSF(jet2Pt, jet2Eta, jet2Parton, -1);
			}

	
			if (index == 1) {
				
				float bScore = -9.99;
				float tauScore = 9.99;
				int probeJet = 0;
				if (jet1Pt == jetPtForMistag) {
					probeJet = 1;
					bScore = jet1SubjetMaxBDisc;
					tauScore = jet1tau32;
				}
				if (jet2Pt == jetPtForMistag) {
					bScore = jet2SubjetMaxBDisc;
					tauScore = jet2tau32;
					probeJet = 2;
				}

				int bin = mistagRateHistAll->FindBin( ptMap(jetPtForMistag),bMap(bScore),tauMap(tauScore) );
				mistagWt = mistagRateHistAll->GetBinContent( bin );
				mistagWtErr = mistagRateHistAll->GetBinError( bin );
			}
		
			newTree->Fill();
		
		}
		

	}


	
	
	


	newFile->cd();
	newTree->Write();
	newFile->Write();
	newFile->Close();
	
}
Пример #10
0
void Slimmer(TString InputCfAName, TString output_filename)
{
    
  TChain * chainA = new TChain("/configurableAnalysis/eventA");   
  TChain * chainB = new TChain("/configurableAnalysis/eventB");    
  chainA->Add(InputCfAName);
  chainB->Add(InputCfAName);

  InitializeA(chainA);
  InitializeB(chainB);
  
  chainA->SetBranchStatus("*",0);
  chainB->SetBranchStatus("*",0);

  chainA->SetBranchStatus("els_conversion_dist",1);
  chainA->SetBranchStatus("els_conversion_dcot",1);
  chainA->SetBranchStatus("PU_TrueNumInteractions",1);
  chainA->SetBranchStatus("rho_kt6PFJetsForIsolation2011",1);
  chainA->SetBranchStatus("els_PFphotonIsoR03",1);
  chainA->SetBranchStatus("els_PFneutralHadronIsoR03",1);
  chainA->SetBranchStatus("els_PFchargedHadronIsoR03",1);
  chainA->SetBranchStatus("els_hasMatchedConversion",1);

  chainB->SetBranchStatus("mus_charge",1);
  chainB->SetBranchStatus("mus_pt",1);
  chainB->SetBranchStatus("mus_eta",1);
  chainB->SetBranchStatus("mus_et",1);
  chainB->SetBranchStatus("mus_phi",1);
  chainB->SetBranchStatus("mus_px",1);
  chainB->SetBranchStatus("mus_py",1);
  chainB->SetBranchStatus("mus_pz",1);
  chainB->SetBranchStatus("mus_tk_chi2",1);
  chainB->SetBranchStatus("mus_tk_ndof",1);
  chainB->SetBranchStatus("mus_tk_numvalhits",1);
  chainB->SetBranchStatus("mus_tk_numvalPixelhits",1);
  chainB->SetBranchStatus("mus_tk_px",1);
  chainB->SetBranchStatus("mus_tk_py",1);
  chainB->SetBranchStatus("mus_tk_pz",1);
  chainB->SetBranchStatus("mus_tk_pt",1);
  chainB->SetBranchStatus("mus_tk_ptErr",1);
  chainB->SetBranchStatus("mus_tk_numpixelWthMeasr",1);
  chainB->SetBranchStatus("mus_tk_vx",1);
  chainB->SetBranchStatus("mus_tk_vy",1);
  chainB->SetBranchStatus("mus_tk_vz",1);
  chainB->SetBranchStatus("mus_tk_d0dum",1);
  chainB->SetBranchStatus("mus_tk_phi",1);
  chainB->SetBranchStatus("mus_cm_pt",1);
  chainB->SetBranchStatus("mus_cm_ptErr",1);
  chainB->SetBranchStatus("mus_cm_chi2",1);
  chainB->SetBranchStatus("mus_cm_ndof",1);
  chainB->SetBranchStatus("mus_stamu_pt",1);
  chainB->SetBranchStatus("mus_stamu_ptErr",1);
  chainB->SetBranchStatus("mus_tIso",1);
  chainB->SetBranchStatus("mus_cIso",1);
  chainB->SetBranchStatus("mus_energy",1);
  chainB->SetBranchStatus("mus_ecalIso",1);
  chainB->SetBranchStatus("mus_hcalIso",1);
  chainB->SetBranchStatus("mus_ecalvetoDep",1);
  chainB->SetBranchStatus("mus_hcalvetoDep",1);
  chainB->SetBranchStatus("mus_id_GlobalMuonPromptTight",1);
  chainB->SetBranchStatus("mus_id_AllTrackerMuons",1);
  chainB->SetBranchStatus("mus_id_AllGlobalMuons",1);
  chainB->SetBranchStatus("mus_isTrackerMuon",1);
  chainB->SetBranchStatus("mus_isGlobalMuon",1);
  chainB->SetBranchStatus("mus_num_matches",1);
  chainB->SetBranchStatus("mus_isPFMuon",1);
  chainB->SetBranchStatus("mus_numberOfMatchedStations",1);
  chainB->SetBranchStatus("mus_pfIsolationR03_sumChargedHadronPt",1);
  chainB->SetBranchStatus("mus_pfIsolationR03_sumChargedParticlePt",1);
  chainB->SetBranchStatus("mus_pfIsolationR03_sumNeutralHadronEt",1);
  chainB->SetBranchStatus("mus_pfIsolationR03_sumNeutralHadronEtHighThreshold",1);
  chainB->SetBranchStatus("mus_pfIsolationR03_sumPhotonEt",1);
  chainB->SetBranchStatus("mus_pfIsolationR03_sumPhotonEtHighThreshold",1);
  chainB->SetBranchStatus("mus_pfIsolationR03_sumPUPt",1);
  chainB->SetBranchStatus("mus_pfIsolationR04_sumChargedHadronPt",1);
  chainB->SetBranchStatus("mus_pfIsolationR04_sumChargedParticlePt",1);
  chainB->SetBranchStatus("mus_pfIsolationR04_sumNeutralHadronEt",1);
  chainB->SetBranchStatus("mus_pfIsolationR04_sumNeutralHadronEtHighThreshold",1);
  chainB->SetBranchStatus("mus_pfIsolationR04_sumPhotonEt",1);
  chainB->SetBranchStatus("mus_pfIsolationR04_sumPhotonEtHighThreshold",1);
  chainB->SetBranchStatus("mus_pfIsolationR04_sumPUPt",1);
  chainB->SetBranchStatus("mus_dB",1);

  chainB->SetBranchStatus("pfcand_pdgId",1);
  chainB->SetBranchStatus("pfcand_particleId",1);
  chainB->SetBranchStatus("pfcand_pt",1);
  chainB->SetBranchStatus("pfcand_pz",1);
  chainB->SetBranchStatus("pfcand_px",1);
  chainB->SetBranchStatus("pfcand_py",1);
  chainB->SetBranchStatus("pfcand_eta",1);
  chainB->SetBranchStatus("pfcand_phi",1);
  chainB->SetBranchStatus("pfcand_theta",1);
  chainB->SetBranchStatus("pfcand_energy",1);
  chainB->SetBranchStatus("pfcand_charge",1);

  chainB->SetBranchStatus("pf_mus_pt",1);
  chainB->SetBranchStatus("pf_mus_eta",1);
  chainB->SetBranchStatus("pf_mus_et",1);
  chainB->SetBranchStatus("pf_mus_tk_chi2",1);
  chainB->SetBranchStatus("pf_mus_tk_ndof",1);
  chainB->SetBranchStatus("pf_mus_tk_numvalhits",1);
  chainB->SetBranchStatus("pf_mus_tk_numvalPixelhits",1);
  chainB->SetBranchStatus("pf_mus_tk_pt",1);
  chainB->SetBranchStatus("pf_mus_tk_ptErr",1);
  chainB->SetBranchStatus("pf_mus_cm_pt",1);
  chainB->SetBranchStatus("pf_mus_cm_ptErr",1);
  chainB->SetBranchStatus("pf_mus_cm_chi2",1);
  chainB->SetBranchStatus("pf_mus_cm_ndof",1);
  chainB->SetBranchStatus("pf_mus_stamu_pt",1);
  chainB->SetBranchStatus("pf_mus_stamu_ptErr",1);
  chainB->SetBranchStatus("pf_mus_tIso",1);
  chainB->SetBranchStatus("pf_mus_cIso",1);
  chainB->SetBranchStatus("pf_mus_energy",1);
  chainB->SetBranchStatus("pf_mus_ecalIso",1);
  chainB->SetBranchStatus("pf_mus_hcalIso",1);
  chainB->SetBranchStatus("pf_mus_tk_d0dum",1);
  chainB->SetBranchStatus("pf_mus_tk_phi",1);
  chainB->SetBranchStatus("pf_mus_phi",1);
  chainB->SetBranchStatus("pf_mus_px",1);
  chainB->SetBranchStatus("pf_mus_py",1);
  chainB->SetBranchStatus("pf_mus_pz",1);
  chainB->SetBranchStatus("pf_mus_id_GlobalMuonPromptTight",1);
  chainB->SetBranchStatus("pf_mus_charge",1);
  chainB->SetBranchStatus("pf_mus_num_matches",1);
  chainB->SetBranchStatus("pf_mus_tk_numpixelWthMeasr",1);
  chainB->SetBranchStatus("pf_mus_tk_vz",1);
  chainB->SetBranchStatus("mus_tk_LayersWithMeasurement",1);
  chainB->SetBranchStatus("pf_mus_isTrackerMuon",1);
  chainB->SetBranchStatus("pf_mus_isGlobalMuon",1);
  chainB->SetBranchStatus("pf_mus_chargedHadronIso",1);
  chainB->SetBranchStatus("pf_mus_neutralHadronIso",1);
  chainB->SetBranchStatus("pf_mus_photonIso",1);

  chainB->SetBranchStatus("els_pt",1);
  chainB->SetBranchStatus("els_ptError",1);
  chainB->SetBranchStatus("els_n_inner_layer");
  chainB->SetBranchStatus("els_px",1);
  chainB->SetBranchStatus("els_py",1);
  chainB->SetBranchStatus("els_pz",1);
  chainB->SetBranchStatus("els_et",1);
  chainB->SetBranchStatus("els_eta",1);
  chainB->SetBranchStatus("els_phi",1);
  chainB->SetBranchStatus("els_charge",1);
  chainB->SetBranchStatus("els_isEB",1);
  chainB->SetBranchStatus("els_isEE",1);
  chainB->SetBranchStatus("els_simpleEleId70relIso",1);
  chainB->SetBranchStatus("els_simpleEleId70cIso",1);
  chainB->SetBranchStatus("els_simpleEleId80cIso",1);
  chainB->SetBranchStatus("els_simpleEleId80relIso",1);
  chainB->SetBranchStatus("els_simpleEleId85cIso",1);
  chainB->SetBranchStatus("els_simpleEleId85relIso",1);
  chainB->SetBranchStatus("els_simpleEleId90cIso",1);
  chainB->SetBranchStatus("els_simpleEleId90relIso",1);
  chainB->SetBranchStatus("els_simpleEleId95cIso",1);
  chainB->SetBranchStatus("els_simpleEleId95relIso",1);
  chainB->SetBranchStatus("els_tIso",1);
  chainB->SetBranchStatus("els_cIso",1);
  chainB->SetBranchStatus("els_hcalIso",1);
  chainB->SetBranchStatus("els_ecalIso",1);
  chainB->SetBranchStatus("els_d0dum",1);
  chainB->SetBranchStatus("els_tk_phi",1);
  chainB->SetBranchStatus("els_tk_pt",1);
  chainB->SetBranchStatus("els_tk_pz",1);
  chainB->SetBranchStatus("els_robustTightId",1);
  chainB->SetBranchStatus("els_dr03EcalRecHitSumEt",1);
  chainB->SetBranchStatus("els_dr03TkSumPt",1);
  chainB->SetBranchStatus("els_dr03HcalTowerSumEt",1);
  chainB->SetBranchStatus("els_sigmaIEtaIEta",1);
  chainB->SetBranchStatus("els_dPhiIn",1);
  chainB->SetBranchStatus("els_dEtaIn",1);
  chainB->SetBranchStatus("els_dPhiOut",1);
  chainB->SetBranchStatus("els_dEtaOut",1);
  chainB->SetBranchStatus("els_scEta",1);
  chainB->SetBranchStatus("els_hadOverEm",1);
  chainB->SetBranchStatus("els_isEB",1);
  chainB->SetBranchStatus("els_isEE",1);
  chainB->SetBranchStatus("els_energy",1);
  chainB->SetBranchStatus("els_scEnergy",1);
  chainB->SetBranchStatus("els_scE2x5Max",1);
  chainB->SetBranchStatus("els_scE5x5",1);
  chainB->SetBranchStatus("els_scE1x5",1);
  chainB->SetBranchStatus("els_dr03HcalDepth1TowerSumEt",1);
  chainB->SetBranchStatus("els_dr03HcalDepth2TowerSumEt",1);
  chainB->SetBranchStatus("els_eOverPIn",1);
  chainB->SetBranchStatus("els_numlosthits",1);
  chainB->SetBranchStatus("els_vx",1);
  chainB->SetBranchStatus("els_vy",1);
  chainB->SetBranchStatus("els_vz",1);
  chainB->SetBranchStatus("els_caloEnergy",1);

  chainB->SetBranchStatus("pf_els_pt",1);
  chainB->SetBranchStatus("pf_els_ptError",1);
  chainB->SetBranchStatus("pf_els_n_inner_layer");
  chainB->SetBranchStatus("pf_els_px",1);
  chainB->SetBranchStatus("pf_els_py",1);
  chainB->SetBranchStatus("pf_els_pz",1);
  chainB->SetBranchStatus("pf_els_et",1);
  chainB->SetBranchStatus("pf_els_eta",1);
  chainB->SetBranchStatus("pf_els_phi",1);
  chainB->SetBranchStatus("pf_els_charge",1);
  chainB->SetBranchStatus("pf_els_isEB",1);
  chainB->SetBranchStatus("pf_els_isEE",1);
  chainB->SetBranchStatus("pf_els_simpleEleId70relIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId70cIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId80cIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId80relIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId85cIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId85relIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId90cIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId90relIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId95cIso",1);
  chainB->SetBranchStatus("pf_els_simpleEleId95relIso",1);
  chainB->SetBranchStatus("pf_els_tIso",1);
  chainB->SetBranchStatus("pf_els_cIso",1);
  chainB->SetBranchStatus("pf_els_hcalIso",1);
  chainB->SetBranchStatus("pf_els_ecalIso",1);
  chainB->SetBranchStatus("pf_els_d0dum",1);
  chainB->SetBranchStatus("pf_els_tk_phi",1);
  chainB->SetBranchStatus("pf_els_robustTightId",1);
  chainB->SetBranchStatus("pf_els_dr03EcalRecHitSumEt",1);
  chainB->SetBranchStatus("pf_els_dr03TkSumPt",1);
  chainB->SetBranchStatus("pf_els_dr03HcalTowerSumEt",1);
  chainB->SetBranchStatus("pf_els_sigmaIEtaIEta",1);
  chainB->SetBranchStatus("pf_els_dPhiIn",1);
  chainB->SetBranchStatus("pf_els_dEtaIn",1);
  chainB->SetBranchStatus("pf_els_dPhiOut",1);
  chainB->SetBranchStatus("pf_els_dEtaOut",1);
  chainB->SetBranchStatus("pf_els_scEta",1);
  chainB->SetBranchStatus("pf_els_hadOverEm",1);
  chainB->SetBranchStatus("pf_els_isEB",1);
  chainB->SetBranchStatus("pf_els_isEE",1);
  chainB->SetBranchStatus("pf_els_energy",1);
  chainB->SetBranchStatus("pf_els_scEnergy",1);
  chainB->SetBranchStatus("pf_els_scE2x5Max",1);
  chainB->SetBranchStatus("pf_els_scE5x5",1);
  chainB->SetBranchStatus("pf_els_scE1x5",1);
  chainB->SetBranchStatus("pf_els_dr03HcalDepth1TowerSumEt",1);
  chainB->SetBranchStatus("pf_els_dr03HcalDepth2TowerSumEt",1);
  chainB->SetBranchStatus("pf_els_eOverPIn",1);
  chainB->SetBranchStatus("pf_els_numlosthits",1);
  chainB->SetBranchStatus("pf_els_vx",1);
  chainB->SetBranchStatus("pf_els_vy",1);
  chainB->SetBranchStatus("pf_els_vz",1);
  chainB->SetBranchStatus("pf_els_chargedHadronIso",1);
  chainB->SetBranchStatus("pf_els_neutralHadronIso",1);
  chainB->SetBranchStatus("pf_els_photonIso",1);

  chainB->SetBranchStatus("jets_AK5PFclean_rawPt",1);
  chainB->SetBranchStatus("jets_AK5PFclean_et",1);
  chainB->SetBranchStatus("jets_AK5PFclean_btag_TC_highPur",1);
  chainB->SetBranchStatus("jets_AK5PFclean_btag_TC_highEff",1);
  chainB->SetBranchStatus("jets_AK5PFclean_btag_secVertexHighPur",1);
  chainB->SetBranchStatus("jets_AK5PFclean_btag_secVertexHighEff",1);
  chainB->SetBranchStatus("jets_AK5PFclean_btag_secVertexCombined",1);
  chainB->SetBranchStatus("jets_AK5PFclean_btag_jetProb",1);
  chainB->SetBranchStatus("jets_AK5PFclean_btag_jetBProb",1);
  chainB->SetBranchStatus("jets_AK5PFclean_jetCharge",1);
  chainB->SetBranchStatus("jets_AK5PFclean_partonFlavour",1);
  chainB->SetBranchStatus("jets_AK5PFclean_parton_Id",1);
  chainB->SetBranchStatus("jets_AK5PFclean_parton_motherId",1);
  chainB->SetBranchStatus("jets_AK5PFclean_energy",1);
  chainB->SetBranchStatus("jets_AK5PFclean_pt",1);
  chainB->SetBranchStatus("jets_AK5PFclean_px",1);
  chainB->SetBranchStatus("jets_AK5PFclean_py",1);
  chainB->SetBranchStatus("jets_AK5PFclean_gen_pt",1);
  chainB->SetBranchStatus("jets_AK5PFclean_gen_phi",1);
  chainB->SetBranchStatus("jets_AK5PFclean_pz",1);
  chainB->SetBranchStatus("jets_AK5PFclean_eta",1);
  chainB->SetBranchStatus("jets_AK5PFclean_ehf",1);
  chainB->SetBranchStatus("jets_AK5PFclean_phi",1);
  chainB->SetBranchStatus("jets_AK5PFclean_neutralEmE",1);
  chainB->SetBranchStatus("jets_AK5PFclean_chgEmE",1);
  chainB->SetBranchStatus("jets_AK5PFclean_neutralHadE",1);
  chainB->SetBranchStatus("jets_AK5PFclean_chgHadE",1);
  chainB->SetBranchStatus("jets_AK5PFclean_mu_Mult",1);
  chainB->SetBranchStatus("jets_AK5PFclean_neutral_Mult",1);
  chainB->SetBranchStatus("jets_AK5PFclean_chg_Mult",1);
  chainB->SetBranchStatus("jets_AK5PFclean_corrFactorRaw",1);
  chainB->SetBranchStatus("jets_AK5PFclean_photonEnergy",1);

  chainB->SetBranchStatus("jets_AK5PF_et",1);
  chainB->SetBranchStatus("jets_AK5PF_btag_TC_highPur",1);
  chainB->SetBranchStatus("jets_AK5PF_btag_TC_highEff",1);
  chainB->SetBranchStatus("jets_AK5PF_btag_secVertexHighPur",1);
  chainB->SetBranchStatus("jets_AK5PF_btag_secVertexHighEff",1);
  chainB->SetBranchStatus("jets_AK5PF_btag_secVertexCombined",1);
  chainB->SetBranchStatus("jets_AK5PF_btag_jetProb",1);
  chainB->SetBranchStatus("jets_AK5PF_btag_jetBProb",1);
  chainB->SetBranchStatus("jets_AK5PF_jetCharge",1);
  chainB->SetBranchStatus("jets_AK5PF_partonFlavour",1);
  chainB->SetBranchStatus("jets_AK5PF_parton_Id",1);
  chainB->SetBranchStatus("jets_AK5PF_parton_motherId",1);
  chainB->SetBranchStatus("jets_AK5PF_energy",1);
  chainB->SetBranchStatus("jets_AK5PF_pt",1);
  chainB->SetBranchStatus("jets_AK5PF_px",1);
  chainB->SetBranchStatus("jets_AK5PF_py",1);
  chainB->SetBranchStatus("jets_AK5PF_gen_pt",1);
  chainB->SetBranchStatus("jets_AK5PF_gen_phi",1);
  chainB->SetBranchStatus("jets_AK5PF_pz",1);
  chainB->SetBranchStatus("jets_AK5PF_eta",1);
  chainB->SetBranchStatus("jets_AK5PF_ehf",1);
  chainB->SetBranchStatus("jets_AK5PF_phi",1);
  chainB->SetBranchStatus("jets_AK5PF_neutralEmE",1);
  chainB->SetBranchStatus("jets_AK5PF_chgEmE",1);
  chainB->SetBranchStatus("jets_AK5PF_neutralHadE",1);
  chainB->SetBranchStatus("jets_AK5PF_chgHadE",1);
  chainB->SetBranchStatus("jets_AK5PF_mu_Mult",1);
  chainB->SetBranchStatus("jets_AK5PF_neutral_Mult",1);
  chainB->SetBranchStatus("jets_AK5PF_chg_Mult",1);
  chainB->SetBranchStatus("jets_AK5PF_corrFactorRaw",1);
  chainB->SetBranchStatus("jets_AK5PF_photonEnergy",1);	
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_px",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_py",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_pz",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_energy",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_phi",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_eta",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_index",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT10_nconstituents",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_px",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_py",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_pz",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_energy",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_phi",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_eta",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_index",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT15_nconstituents",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_px",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_py",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_pz",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_energy",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_phi",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_eta",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_index",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT20_nconstituents",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_px",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_py",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_pz",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_energy",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_phi",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_eta",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_index",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT25_nconstituents",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_px",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_py",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_pz",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_energy",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_phi",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_eta",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_index",1);
  chainB->SetBranchStatus("fastjets_AK5PFclean_R1p2_R0p5pT30_nconstituents",1);
  

  chainB->SetBranchStatus("pfmets_et",1);
  chainB->SetBranchStatus("pfmets_ex",1);
  chainB->SetBranchStatus("pfmets_ey",1);
  chainB->SetBranchStatus("pfmets_phi",1);
  chainB->SetBranchStatus("pfmets_sumEt",1);
  chainB->SetBranchStatus("pfmets_gen_et",1);
  chainB->SetBranchStatus("pfmets_gen_phi",1);

  chainB->SetBranchStatus("pfTypeImets_et",1);
  chainB->SetBranchStatus("pfTypeImets_ex",1);
  chainB->SetBranchStatus("pfTypeImets_ey",1);
  chainB->SetBranchStatus("pfTypeImets_phi",1);
  chainB->SetBranchStatus("pfTypeImets_sumEt",1);
  chainB->SetBranchStatus("pfTypeImets_gen_et",1);
  chainB->SetBranchStatus("pfTypeImets_gen_phi",1);

  chainB->SetBranchStatus("pv_x",1);
  chainB->SetBranchStatus("pv_y",1);
  chainB->SetBranchStatus("pv_z",1);
  chainB->SetBranchStatus("pv_tracksSize",1);
  chainB->SetBranchStatus("pv_ndof",1);
  chainB->SetBranchStatus("pv_isFake",1);
  chainB->SetBranchStatus("Npv",1);

  chainB->SetBranchStatus("run",1);
  chainB->SetBranchStatus("event",1);
  chainB->SetBranchStatus("lumiblock",1);
  chainB->SetBranchStatus("bunchCrossing",1);

  chainB->SetBranchStatus("beamSpot_y",1);
  chainB->SetBranchStatus("beamSpot_x",1);

  chainB->SetBranchStatus("weight",1);
  chainB->SetBranchStatus("model_params",1);

  // Make the new file
  TFile *newFile = new TFile(output_filename.Data(),"RECREATE");
  TDirectoryFile *dir = new TDirectoryFile("configurableAnalysis","configurableAnalysis");
  dir->cd();
  TTree *newtreeA = chainA->CloneTree(0);
  TTree *newtreeB = chainB->CloneTree(0);

  Int_t nentries = (Int_t)chainB->GetEntries();

  for (int iEnt = 0; iEnt<nentries; iEnt++) {
    chainA->GetEntry(iEnt);
    chainB->GetEntry(iEnt);
    newtreeA->Fill();
    newtreeB->Fill();
  }

  newtreeA->AutoSave();
  newtreeB->AutoSave();
  newFile->Write();
  newFile->Close();

}
Пример #11
0
int main(int argc, char* argv[]) {

  //ROOT::Cintex::Cintex::Enable();
  if(argc<2){
      std::cout << "Input parameters: 1) W,Z,TAU,QCD,DATA" << std::endl;
      exit(EXIT_SUCCESS);
  }
  bool doTruthW = false;
  bool doTruthZ = false;
  bool doTruthTau = false;
  bool doTruthQCD = false;
  bool doTruth = false;
  if(strcmp(argv[1],"W")==0) doTruthW=true;
  else if(strcmp(argv[1],"Z")==0) doTruthZ=true;
  else if(strcmp(argv[1],"TAU")==0) doTruthTau=true;
  else if(strcmp(argv[1],"QCD")==0) doTruthQCD=true;
  if(doTruthW||doTruthZ||doTruthTau||doTruthQCD) doTruth=true;
  int mother=-1;
  int child1=-1;
  int child2=-1;
  bool doMinBias = false;
  bool doMu = true;
  bool doMuid = false;
  bool doStaco = false;
  if(doTruthW) { 
      mother=24; // W
      child1=13; // muon
      child2=14; // neutrino
      std::cout << "======> Running on W-->munu Monte Carlo simulation. <======" << std::endl; 
  }
  else if(doTruthZ) { 
      mother=23; // Z
      child1=13; // muon
      child2=13; // muon 
      std::cout << "======> Running on Z-->mumu Monte Carlo simulation. <======" << std::endl; 
  }
  else if(doTruthTau) { 
      mother=15; // tau
      child1=13; // muon
      child2=14; // neutrino(s) 
      std::cout << "======> Running on W-->taunu-->mununu Monte Carlo simulation. <======" << std::endl; 
  }
  else if(doTruthQCD) { 
      child1=13; // muon
      std::cout << "======> Running on QCD Monte Carlo simulation. <======" << std::endl; 
  }
  else if(doMinBias) { std::cout << "======> Running on Minimum Bias Data. <======" << std::endl; }
  else { std::cout << "======> Running on Data. <======" << std::endl; }
  if(doTruth&&doMinBias){

      std::cout << "PLEASE CHOOSE TO RUN ON EITHER MC OR DATA." << std::endl;
      exit(0);
  }
  std::string argStr;
  std::ifstream ifs;
  ifs.open("input.txt");

  // split by ','
  std::vector<std::string> fileList;
  
  std::getline(ifs,argStr);
  for (size_t i=0,n; i <= argStr.length(); i=n+1)
  {
      n = argStr.find_first_of(',',i);
      if (n == std::string::npos)
          n = argStr.length();
      std::string tmp = argStr.substr(i,n-i);
      fileList.push_back(tmp);
  }

  cout << fileList.size() << " files used for processing." << endl;
  // open input files
  TChain* fChain = new TChain("HeavyIonD3PD");

  for (int iFile=0; iFile<fileList.size(); ++iFile)
    {
      std::cout << "open " << fileList[iFile].c_str() << std::endl;
      // Add each file to the TChain
      fChain->Add(fileList[iFile].c_str());
    }
  int entries = fChain->GetEntries();
  std::cout << "entries=" << fChain->GetEntries() << std::endl;

  TFile* fout=0;
  fout=new TFile("skimmed.root","RECREATE");
  TTree* outputTree = new TTree("MuonD3PD","MuonD3PD");
  TTree* outputTallTree = fChain->CloneTree(0);

  // Handle to D3PD
  EventAnalysis* EvtAna = new EventAnalysis(fChain, doTruth, doMinBias);
  EvtAna->SetOutputBranches(outputTree);

  MuonAnalysis* muMuonAna = NULL, *muidMuonAna = NULL, *stacoMuonAna = NULL; 
  if(doMu){
    std::cout << "USING MUON RECONSTRUCTION CHAIN." << std::endl;
    muMuonAna = new MuonAnalysis("mu", doTruth, doMinBias);
    muMuonAna->SetOutputBranches(outputTree);
  }
  if(doMuid){
    std::cout << "USING MUID RECONSTRUCTION CHAIN." << std::endl;
    muidMuonAna = new MuonAnalysis("muid", doTruth, doMinBias);
    muidMuonAna->SetOutputBranches(outputTree);
  }
  if(doStaco){
    std::cout << "USING STACO RECONSTRUCTION CHAIN." << std::endl;
    stacoMuonAna = new MuonAnalysis("staco", doTruth, doMinBias);
    stacoMuonAna->SetOutputBranches(outputTree);
  }

  TruthAnalysis* truAna = NULL;
  if(doTruth){
    truAna = new TruthAnalysis();
    truAna->SetOutputBranches(outputTree);

  }

  // Total number of muons in the sample
  int nMuMuons = 0, nMuidMuons = 0, nStacoMuons = 0;
  for(int iev=0; iev<entries; iev++) {
     // Comment out to activate only select branches. 
     // If you do, outputTallTree will only write muon information and
     // will not dump the entire event information.

      fChain->GetEntry(iev);
      // entry in tree
      int entry = EvtAna->LoadTree(iev);
      if (entry < 0) continue;
      if(iev%1000==0) {
        std::cout << " Event no: " << iev << std::endl;
      }
      // No. of muons w/ pt>20 GeV in this event
      int nHiPtMuMuons=0;
      //if(iev==10000) break; //hack
      if( !EvtAna->LoopEvent(entry) ) continue;
      if(doTruth){
        if(doTruthQCD) truAna->LoopEventQCD(EvtAna,entry,child1); 
        else truAna->LoopEvent(EvtAna,entry,mother,child1,child2);
        int nTruthMu = truAna->GetNumTruthMuon();
        if(nTruthMu==0) continue;
        
      }
      if(doMu) { 
          muMuonAna->LoopEvent(EvtAna,entry);
          int nmu = muMuonAna->GetNumMuMuon();
          nHiPtMuMuons = muMuonAna->GetNumHiPtMuMuon();
          // At least 1 good muon in event
          if( !(doTruth) && (nmu==0) ) continue;
          nMuMuons+=nmu;
      }
      if(doMuid) { 
          muidMuonAna->LoopEvent(EvtAna,entry);
          int nmu = muidMuonAna->GetNumMuidMuon();
          // At least 1 good muon in event
          if( !(doTruth) && (nmu==0) ) continue;
          nMuidMuons+=nmu;
      }
      if(doStaco) { 
          stacoMuonAna->LoopEvent(EvtAna,entry);
          int nmu = stacoMuonAna->GetNumStacoMuon();
          // At least 1 good muon in event
          if( !(doTruth) && (nmu==0) ) continue;
          nStacoMuons+=nmu;
      }

      // Fill once per HiP event
      outputTree->Fill();
      /// If we have a good high pt (20 GeV) muon in the event, 
      /// save all event information to a 2nd tree
      if(nHiPtMuMuons>0 && !doTruth){
	outputTallTree->Fill();
      }
  }//iev
  fout->cd();
  if(doMu) {
      std::cout << "Total number of good \"mu\" muons: " << nMuMuons << std::endl;
      muMuonAna->WriteHistosToFile(fout);
  }
  if(doMuid) {
      std::cout << "Total number of good \"muid\" muons: " << nMuidMuons << std::endl;
      muidMuonAna->WriteHistosToFile(fout);
  }
  if(doStaco){ 
      std::cout << "Total number of good \"staco\" muons: " << nStacoMuons << std::endl;
      stacoMuonAna->WriteHistosToFile(fout);
  }

  if(!doTruth) outputTallTree->Write();
  EvtAna->WriteHistosToFile(fout);
  delete EvtAna;
  if(muMuonAna!=NULL) delete muMuonAna;
  if(muidMuonAna!=NULL) delete muidMuonAna;
  if(stacoMuonAna!=NULL) delete stacoMuonAna;
  outputTree->Write();

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

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

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

       // input configuration
       int collisionType = configInput.proc[INPUT::kSKIM].i[INPUT::k_collisionType];
       std::string treePath = configInput.proc[INPUT::kSKIM].s[INPUT::k_treePath];

       // set default values
       if (treePath.size() == 0)  treePath = "ggHiNtuplizer/EventTree";

       // verbose about input configuration
       std::cout<<"Input Configuration :"<<std::endl;
       std::cout << "collisionType = " << collisionType << std::endl;
       const char* collisionName =  getCollisionTypeName((COLL::TYPE)collisionType).c_str();
       std::cout << "collision = " << collisionName << std::endl;
       std::cout << "treePath = " << treePath.c_str() << std::endl;

       // cut configuration
       float cut_vz = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].f[CUTS::EVT::k_vz];
       int cut_pcollisionEventSelection = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pcollisionEventSelection];
       int cut_pPAprimaryVertexFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pPAprimaryVertexFilter];
       int cut_pBeamScrapingFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pBeamScrapingFilter];

       int cut_nMu = configCuts.proc[CUTS::kSKIM].obj[CUTS::kMUON].i[CUTS::MUO::k_nMu];

       // bool isMC = collisionIsMC((COLL::TYPE)collisionType);
       bool isHI = collisionIsHI((COLL::TYPE)collisionType);
       bool isPP = collisionIsPP((COLL::TYPE)collisionType);

       // verbose about cut configuration
       std::cout<<"Cut Configuration :"<<std::endl;
       std::cout<<"cut_vz = "<< cut_vz <<std::endl;
       if (isHI) {
           std::cout<<"cut_pcollisionEventSelection = "<< cut_pcollisionEventSelection <<std::endl;
       }
       else {   // PP
           std::cout<<"cut_pPAprimaryVertexFilter = "<< cut_pPAprimaryVertexFilter <<std::endl;
           std::cout<<"cut_pBeamScrapingFilter = "<< cut_pBeamScrapingFilter <<std::endl;
       }

       std::cout<<"cut_nMu = "<<cut_nMu<<std::endl;

       std::vector<std::string> inputFiles = InputConfigurationParser::ParseFiles(inputFile.Data());

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

       TChain* treeHLT   = new TChain("hltanalysis/HltTree");
       TChain* treeggHiNtuplizer  = new TChain("ggHiNtuplizer/EventTree");
       TChain* treeHiEvt = new TChain("hiEvtAnalyzer/HiTree");
       TChain* treeSkim  = new TChain("skimanalysis/HltTree");
       TChain* treeHiForestInfo = new TChain("HiForest/HiForestInfo");

       for (std::vector<std::string>::iterator it = inputFiles.begin() ; it != inputFiles.end(); ++it) {
          treeHLT->Add((*it).c_str());
          treeggHiNtuplizer->Add((*it).c_str());
          treeHiEvt->Add((*it).c_str());
          treeSkim->Add((*it).c_str());
          treeHiForestInfo->Add((*it).c_str());
       }

       HiForestInfoController hfic(treeHiForestInfo);
       std::cout<<"### HiForestInfo Tree ###"<< std::endl;
       hfic.printHiForestInfo();
       std::cout<<"###"<< std::endl;

       treeHLT->SetBranchStatus("*",0);     // disable all branches
       treeHLT->SetBranchStatus("HLT_HI*SinglePhoton*Eta*",1);     // enable photon branches
       treeHLT->SetBranchStatus("HLT_HI*DoublePhoton*Eta*",1);     // enable photon branches
       treeHLT->SetBranchStatus("*DoubleMu*",1);                      // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL1Mu*",1);                     // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL2Mu*",1);                     // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL3Mu*",1);                     // enable muon branches
       
       // specify explicitly which branches to store, do not use wildcard
       treeHiEvt->SetBranchStatus("*",1);

       // specify explicitly which branches to store, do not use wildcard
       treeSkim->SetBranchStatus("*",0);

       Int_t pcollisionEventSelection;  // this filter is used for HI.
       if (isHI) {
           treeSkim->SetBranchStatus("pcollisionEventSelection",1);
           if (treeSkim->GetBranch("pcollisionEventSelection")) {
               treeSkim->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
           }
           else {   // overwrite to default
               pcollisionEventSelection = 1;
               std::cout<<"could not get branch : pcollisionEventSelection"<<std::endl;
               std::cout<<"set to default value : pcollisionEventSelection = "<<pcollisionEventSelection<<std::endl;
           }
       }
       else {
           pcollisionEventSelection = 0;    // default value if the collision is not HI, will not be used anyway.
       }
       Int_t pPAprimaryVertexFilter;    // this filter is used for PP.
       if (isPP) {
           treeSkim->SetBranchStatus("pPAprimaryVertexFilter",1);
           if (treeSkim->GetBranch("pPAprimaryVertexFilter")) {
               treeSkim->SetBranchAddress("pPAprimaryVertexFilter",&pPAprimaryVertexFilter);
           }
           else {   // overwrite to default
               pPAprimaryVertexFilter = 1;
               std::cout<<"could not get branch : pPAprimaryVertexFilter"<<std::endl;
               std::cout<<"set to default value : pPAprimaryVertexFilter = "<<pPAprimaryVertexFilter<<std::endl;
           }
       }
       else {
           pPAprimaryVertexFilter = 0;      // default value if the collision is not PP, will not be used anyway.
       }
       Int_t pBeamScrapingFilter;   // this filter is used for PP.
       if (isPP) {
           treeSkim->SetBranchStatus("pBeamScrapingFilter",1);
           if (treeSkim->GetBranch("pBeamScrapingFilter")) {
               treeSkim->SetBranchAddress("pBeamScrapingFilter",&pBeamScrapingFilter);
           }
           else {   // overwrite to default
               pBeamScrapingFilter = 1;
               std::cout<<"could not get branch : pBeamScrapingFilter"<<std::endl;
               std::cout<<"set to default value : pBeamScrapingFilter = "<<pBeamScrapingFilter<<std::endl;
           }
       }
       else {
           pBeamScrapingFilter = 0;     // default value if the collision is not PP, will not be used anyway.
       }

       ggHiNtuplizer ggHi;
       ggHi.setupTreeForReading(treeggHiNtuplizer);
       
       hiEvt hiEvt;
       hiEvt.setupTreeForReading(treeHiEvt);

       TFile* output = new TFile(outputFile,"RECREATE");
       TTree *configTree = setupConfigurationTreeForWriting(configCuts);

       // output tree variables
       TTree *outputTreeHLT           = treeHLT->CloneTree(0);
       outputTreeHLT->SetName("hltTree");
       outputTreeHLT->SetTitle("subbranches of hltanalysis/HltTree");
       TTree *outputTreeggHiNtuplizer = treeggHiNtuplizer->CloneTree(0);
       TTree *outputTreeHiEvt = treeHiEvt->CloneTree(0);
       outputTreeHiEvt->SetName("HiEvt");
       outputTreeHiEvt->SetTitle("subbranches of hiEvtAnalyzer/HiTree");
       TTree* outputTreeSkim  = treeSkim->CloneTree(0);
       outputTreeSkim->SetName("skim");
       outputTreeSkim->SetTitle("subbranches of skimanalysis/HltTree");
       TTree* outputTreeHiForestInfo = treeHiForestInfo->CloneTree(0);
       outputTreeHiForestInfo->SetName("HiForestInfo");
       outputTreeHiForestInfo->SetTitle("first entry of HiForest/HiForestInfo");
       
       outputTreeHLT->SetMaxTreeSize(MAXTREESIZE);
       outputTreeggHiNtuplizer->SetMaxTreeSize(MAXTREESIZE);
       outputTreeHiEvt->SetMaxTreeSize(MAXTREESIZE);
       outputTreeHiForestInfo->SetMaxTreeSize(MAXTREESIZE);

       // write HiForestInfo
       treeHiForestInfo->GetEntry(0);
       outputTreeHiForestInfo->Fill();

       TTree *diMuonTree = new TTree("dimuon","muon pairs");
       diMuonTree->SetMaxTreeSize(MAXTREESIZE);

       dimuon diMu;
       diMu.branchDiMuonTree(diMuonTree);

       EventMatcher* em = new EventMatcher();
       Long64_t duplicateEntries = 0;

       Long64_t entries = treeggHiNtuplizer->GetEntries();
       Long64_t entriesPassedEventSelection = 0;
       Long64_t entriesAnalyzed = 0;
       std::cout << "entries = " << entries << std::endl;
       std::cout<< "Loop : " << treePath.c_str() <<std::endl;
       for (Long64_t j_entry=0; j_entry<entries; ++j_entry)
       {
           if (j_entry % 20000 == 0)  {
             std::cout << "current entry = " <<j_entry<<" out of "<<entries<<" : "<<std::setprecision(2)<<(double)j_entry/entries*100<<" %"<<std::endl;
           }

           treeHLT->GetEntry(j_entry);
           treeggHiNtuplizer->GetEntry(j_entry);
           treeHiEvt->GetEntry(j_entry);
           treeSkim->GetEntry(j_entry);

           bool eventAdded = em->addEvent(ggHi.run,ggHi.lumis,ggHi.event,j_entry);
           if(!eventAdded) // this event is duplicate, skip this one.
           {
               duplicateEntries++;
               continue;
           }

           // event selection
           if (!(TMath::Abs(hiEvt.vz) < cut_vz))  continue;
           if (isHI) {
               if ((pcollisionEventSelection < cut_pcollisionEventSelection))  continue;
           }
           else {
               if (pPAprimaryVertexFilter < cut_pPAprimaryVertexFilter || pBeamScrapingFilter < cut_pBeamScrapingFilter)  continue;
           }
           entriesPassedEventSelection++;

           // skip if there are no muon pairs to study
           if(ggHi.nMu < cut_nMu)  continue;
           entriesAnalyzed++;

           diMu.makeDiMuonPairs(ggHi);

           outputTreeHLT->Fill();
           outputTreeggHiNtuplizer->Fill();
           outputTreeHiEvt->Fill();
           outputTreeSkim->Fill();
           diMuonTree->Fill();
       }
       std::cout<< "Loop ENDED : " << treePath.c_str() <<std::endl;
       std::cout << "entries            = " << entries << std::endl;
       std::cout << "duplicateEntries   = " << duplicateEntries << std::endl;
       std::cout << "entriesPassedEventSelection   = " << entriesPassedEventSelection << std::endl;
       std::cout << "entriesAnalyzed    = " << entriesAnalyzed << std::endl;
       std::cout << "outputTreeHLT->GetEntries()           = " << outputTreeHLT->GetEntries() << std::endl;
       std::cout << "outputTreeggHiNtuplizer->GetEntries() = " << outputTreeggHiNtuplizer->GetEntries() << std::endl;
       std::cout << "outputTreeHiEvt->GetEntries() = " << outputTreeHiEvt->GetEntries() << std::endl;
       std::cout << "outputTreeSkim->GetEntries()  = " << outputTreeSkim->GetEntries() << std::endl;
       std::cout << "diMuonTree->GetEntries()          = " << diMuonTree->GetEntries() << std::endl;

       // overwrite existing trees
       outputTreeHLT->Write("", TObject::kOverwrite);
       outputTreeggHiNtuplizer->Write("", TObject::kOverwrite);
       outputTreeHiEvt->Write("", TObject::kOverwrite);
       diMuonTree->Write("", TObject::kOverwrite);

       configTree->Write("", TObject::kOverwrite);

       output->Write("", TObject::kOverwrite);
       output->Close();

       std::cout<<"dimuonSkim() - END"   <<std::endl;
}
Пример #13
0
int main(int argc, char* argv[]){
  setstyle();

  char inputFileName[400];
  char outputFileName[400];
  
  if ( argc < 2 ){
    cout << "Error at Input: please specify an input .root file";
    cout << " and an (optional) output filename" << endl;
    cout << "Example:   ./Calibrate_xADC input_file.root" << endl;
    cout << "Example:   ./Calibrate_xADC input_file.root -o output_file.root" << endl;
    return 1;
  }

  sscanf(argv[1],"%s", inputFileName);
  bool user_output = false;
  for (int i=0;i<argc;i++){
    if (strncmp(argv[i],"-o",2)==0){
      sscanf(argv[i+1],"%s", outputFileName);
      user_output = true;
    }
  }

  string output_name;
  if(!user_output){
    string input_name = string(inputFileName);
    // strip path from input name
    while(input_name.find("/") != string::npos)
      input_name.erase(input_name.begin(),
		       input_name.begin()+
		       input_name.find("/")+1);
    if(input_name.find(".root") != string::npos)
      input_name.erase(input_name.find(".root"),5);
    output_name = input_name+"_xADCcalib.root";
    sprintf(outputFileName,"%s.root",inputFileName);
  } else {
    output_name = string(outputFileName);
  }

  TChain* tree = new TChain("xADC_fit");
  tree->AddFile(inputFileName);

  xADCfitBase* base = new xADCfitBase(tree);

  int N = tree->GetEntries();
  if(N == 0) return 0;

  map<pair<int,int>, int> MMFE8VMM_to_index;
  
  vector<int>             vMMFE8;  // board ID
  vector<int>             vVMM;    // VMM number
  vector<vector<double> > vmeanQ;
  vector<vector<double> > vmeanQerr;
  vector<vector<double> > vDAC;

  int MMFE8;
  int VMM;

  for(int i = 0; i < N; i++){
    base->GetEntry(i);

    MMFE8 = base->MMFE8;
    VMM   = base->VMM;

    // add a new MMFE8+VMM combination 
    if(MMFE8VMM_to_index.count(pair<int,int>(MMFE8,VMM)) == 0){
      int ind = int(vMMFE8.size());
      MMFE8VMM_to_index[pair<int,int>(MMFE8,VMM)] = ind;
      vMMFE8.push_back(MMFE8);
      vVMM.push_back(VMM);
      vmeanQ.push_back(vector<double>());
      vmeanQerr.push_back(vector<double>());
      vDAC.push_back(vector<double>());
    }

    // MMFE8+VMM index
    int index = MMFE8VMM_to_index[pair<int,int>(MMFE8,VMM)];

    vDAC[index].push_back(base->DAC);
    vmeanQ[index].push_back(base->meanQ);
    vmeanQerr[index].push_back(base->meanQerr);
  }

  int Nindex = vMMFE8.size();

  vector<TGraphErrors*> vgraph;
  vector<double> vsigma;
  vector<double> vQmin;
  for(int index = 0; index < Nindex; index++){
    int Npoint = vDAC[index].size();
    double DAC[Npoint];
    double meanQ[Npoint];
    double meanQerr[Npoint];
    double sigma = 0.;

    double Qmin = -1.;
    for(int p = 0; p < Npoint; p++){
      DAC[p] = vDAC[index][p];
      meanQ[p] = vmeanQ[index][p];
      meanQerr[p] = vmeanQerr[index][p];
      // if(meanQerr[p] > sigma)
      // 	sigma = meanQerr[p];
      sigma += meanQerr[p]/double(Npoint);

      if(meanQ[p] < Qmin || Qmin < 0.)
	Qmin = meanQ[p];
    }

    vgraph.push_back(new TGraphErrors(Npoint, DAC, meanQ, 0, meanQerr));
    vsigma.push_back(sigma);
    vQmin.push_back(Qmin);
  }

  TFile* fout = new TFile(output_name.c_str(), "RECREATE");

  // write xADCBase tree to outputfile
  //TChain* base_tree = new TChain("xADC_data");
  //base_tree->AddFile(inputFileName);
  //TTree* new_base_tree = base_tree->CloneTree();
  //fout->cd();
  //new_base_tree->Write();

  // add plots of charge v DAC for each
  // MMFE8+VMM combo to output file
  fout->mkdir("xADCfit_plots");
  fout->cd("xADCfit_plots");
  for(int i = 0; i < Nindex; i++){
    char stitle[50];
    sprintf(stitle, "Board #%d, VMM #%d", vMMFE8[i], vVMM[i]);
    char scan[50];
    sprintf(scan, "c_xADXfit_Board%d_VMM%d", vMMFE8[i], vVMM[i]);
    TCanvas* can = Plot_Graph(scan, vgraph[i], "Test Pulse DAC", "Input Charge (fC)", stitle);
    can->Write();
    delete can;
  }
  fout->cd("");

  // write xADCfitBase tree to outputfile
  TTree* newtree = tree->CloneTree();
  fout->cd();
  newtree->Write();
  delete newtree;
  delete base;
  delete tree;

  // Output xADC calib tree
  double calib_MMFE8;
  double calib_VMM;
  double calib_sigma;
  double calib_c0;
  double calib_A2;
  double calib_t02;
  double calib_d21;
  double calib_chi2;
  double calib_prob;
  
  TTree* calib_tree = new TTree("xADC_calib", "xADC_calib");
  calib_tree->Branch("MMFE8", &calib_MMFE8);
  calib_tree->Branch("VMM", &calib_VMM);
  calib_tree->Branch("sigma", &calib_sigma);
  calib_tree->Branch("c0", &calib_c0);
  calib_tree->Branch("A2", &calib_A2);
  calib_tree->Branch("t02", &calib_t02);
  calib_tree->Branch("d21", &calib_d21);
  calib_tree->Branch("chi2", &calib_chi2);
  calib_tree->Branch("prob", &calib_prob);

  // Perform fits on each vector of 
  // charge v DACMMFE8+VMM graphs
  fout->mkdir("xADCcalib_plots");
  fout->cd("xADCcalib_plots");

  vector<TF1*> vfunc;

  for(int index = 0; index < Nindex; index++){
    char fname[50];
    sprintf(fname, "funcP0P2P1_MMFE8-%d_VMM-%d", 
	    vMMFE8[index], vVMM[index]);
    int ifunc = vfunc.size();
    vfunc.push_back(new TF1(fname, P0_P2_P1, 0., 400., 4));

    vfunc[ifunc]->SetParName(0, "c_{0}");
    //vfunc[ifunc]->SetParameter(0, 20.);
    vfunc[ifunc]->SetParameter(0, vQmin[index]);
    vfunc[ifunc]->SetParName(1, "A_{2}");
    vfunc[ifunc]->SetParameter(1, 0.003);
    vfunc[ifunc]->SetParName(2, "t_{0 , 2}");
    vfunc[ifunc]->SetParameter(2, 50.);
    vfunc[ifunc]->SetParName(3, "d_{2 , 1}");
    vfunc[ifunc]->SetParameter(3, 50.);
    
    vfunc[ifunc]->SetParLimits(3, 0., 10000.);
    
    vgraph[index]->Fit(fname, "EQ");

    char stitle[50];
    sprintf(stitle, "Board #%d, VMM #%d", vMMFE8[index], vVMM[index]);
    char scan[50];
    sprintf(scan, "c_xADXcalib_Board%d_VMM%d", vMMFE8[index], vVMM[index]);
    TCanvas* can = Plot_Graph(scan, vgraph[index], "Test Pulse DAC", "Input Charge (fC)", stitle);
    can->Write();
    delete can;

   calib_MMFE8 = vMMFE8[index];
   calib_VMM = vVMM[index];
   calib_sigma = vsigma[index];
   calib_c0 = vfunc[ifunc]->GetParameter(0);
   calib_A2 = vfunc[ifunc]->GetParameter(1);
   calib_t02 = vfunc[ifunc]->GetParameter(2);
   calib_d21 = vfunc[ifunc]->GetParameter(3);
   calib_chi2 = vfunc[ifunc]->GetChisquare();
   calib_prob = vfunc[ifunc]->GetProb();

   calib_tree->Fill();
  }
  fout->cd("");

  // Write calib_tree to output file
  fout->cd("");
  calib_tree->Write();
  fout->Close();
}
Пример #14
0
int filter(TString inputDir, long n_evt=100,bool is11=false,bool isFR=false)
{
	long TotalEvents=n_evt;
	
	//options
	bool is2011=is11;
    int N_ALL=4;
    int N_ELMU=-3;
    if(isFR){
		N_ALL=-4;
		N_ELMU=3;
	}
           
    double cut_mu_pt=9.0;
    double cut_mu_eta=2.4; 
    double cut_el_pt=9.0;
    double cut_el_eta=2.5;
    double cut_tau_pt=19.0;
    double cut_tau_eta=2.3;
    
    if(isFR) cut_tau_pt=0.0;
    
    double cut_dR=-0.09;
    double lepton_mass_min=50.0;
    double lepton_mass_max=150.0;
    
	std::string doubEle="HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_v";
	std::string doubEle2="HLT_Ele17_CaloIdL_CaloIsoVL_Ele8_CaloIdL_CaloIsoVL_v";
	
    std::string doubMu="HLT_Mu17_Mu8_v";
    std::string doubMu2="HLT_Mu17_TkMu8_v"; // "HLT_Mu13_Mu8_v" in 2011
    if(is2011) doubMu2="HLT_Mu13_Mu8_v";
    std::string doubMu3="HLT_DoubleMu7_v";
    
    bool debug = false;
    

	
	TChain *chain = new TChain("t");
	chain->Add(inputDir+"*root*");
	
	
	
	//////////////////////// end of modular part ////////////////////////////////////////
	/////////////////////////COMMON part //////////////////////////////////////////
	myevent* in = new myevent();
	chain->SetBranchAddress("myevent",&in);
	
	long MaxEvents = chain->GetEntries();
	if(TotalEvents > MaxEvents || TotalEvents < 0) TotalEvents=MaxEvents;
	
	std::cout << "There are " << MaxEvents << " entries." << std::endl;
	
	
	//bookkeeping
	ofstream lumi;
	long current_run=-1;
	long current_lumi=-1;
    long m_allEvents=0;
	lumi.open("lumi.csv");
	
	//output definition
	
	 TFile *newFile = new TFile("output.root","recreate");
	TChain *newchain = (TChain*)chain->CloneTree(0);
	 TTree *tree = newchain->GetTree();
	
	
	for(uint i =0; i < TotalEvents; i++)
	{
		chain->GetEntry(i);
		m_allEvents++;
		
		if(debug) std::cout << "Processing entry " << i << " event: " << in->eventNumber << std::endl;
		if(i%1000==0)std::cout << "Analyzing entry no. " << i << std::endl;
		
		// storing lumis
		if(in->runNumber!=current_run || in->lumiNumber!=current_lumi){
			lumi << in->runNumber << " " << in->lumiNumber << std::endl;
			current_run=in->runNumber;
			current_lumi=in->lumiNumber;
		}
		
		if(PassFilter(in, debug, doubEle, doubEle2, doubMu, doubMu2, doubMu3,
			         is2011, N_ALL, N_ELMU, 
			         cut_mu_pt, cut_mu_eta, cut_el_pt, cut_el_eta, cut_tau_pt, cut_tau_eta,		    
			         cut_dR, lepton_mass_min, lepton_mass_max)
		   ) tree->Fill();
	}
	
	newFile->cd();
	newFile->Write();
	newFile->Close();
	
	 ofstream log1;       
     log1.open("total.txt");
     log1 << m_allEvents << std::endl;
     log1.close();
     
	return 0;
}
void photonRaaSkim(const TString configFile, const TString inputFile, const TString outputFile, COLL::TYPE colli)
{
    std::cout<<"running photonRaaSkim()"<<std::endl;
    std::cout<<"configFile  = "<< configFile.Data() <<std::endl;
    std::cout<<"inputFile   = "<< inputFile.Data() <<std::endl;
    std::cout<<"outputFile  = "<< outputFile.Data() <<std::endl;

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

    // input configuration
/*    int collisionType;
    if (configInput.isValid) {
        collisionType = configInput.proc[INPUT::kSKIM].i[INPUT::k_collisionType];
    }
    else {
        collisionType = COLL::kPP;
    }
*/
    // verbose about input configuration
    int collisionType = colli;
    std::cout<<"Input Configuration :"<<std::endl;
    std::cout << "collisionType = " << collisionType << std::endl;
    const char* collisionName =  getCollisionTypeName((COLL::TYPE)collisionType).c_str();
    std::cout << "collision = " << collisionName << std::endl;

    // cut configuration
    float cut_vz;
    int cut_pcollisionEventSelection;
    int cut_pPAprimaryVertexFilter;
    int cut_pBeamScrapingFilter;

    float cutPhoEt;
    float cutPhoEta;

    if (configCuts.isValid) {
        cut_vz = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].f[CUTS::EVT::k_vz];
        cut_pcollisionEventSelection = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pcollisionEventSelection];
        cut_pPAprimaryVertexFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pPAprimaryVertexFilter];
        cut_pBeamScrapingFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pBeamScrapingFilter];

        cutPhoEt = configCuts.proc[CUTS::kSKIM].obj[CUTS::kPHOTON].f[CUTS::PHO::k_et];
        cutPhoEta = configCuts.proc[CUTS::kSKIM].obj[CUTS::kPHOTON].f[CUTS::PHO::k_eta];

    }
    else {
        cut_vz = 15;
        cut_pcollisionEventSelection = 1;
        cut_pPAprimaryVertexFilter = 1;
        cut_pBeamScrapingFilter = 1;

        cutPhoEt = 15;
        cutPhoEta = 1.44;
    }

    bool isMC = collisionIsMC((COLL::TYPE)collisionType);
    bool isHI = collisionIsHI((COLL::TYPE)collisionType);
    bool isPP = collisionIsPP((COLL::TYPE)collisionType);

    // verbose about cut configuration
    std::cout<<"Cut Configuration :"<<std::endl;
    std::cout<<"cut_vz = "<< cut_vz <<std::endl;
    if (isHI) {
        std::cout<<"cut_pcollisionEventSelection = "<< cut_pcollisionEventSelection <<std::endl;
    }
    else {   // PP
        std::cout<<"cut_pPAprimaryVertexFilter = "<< cut_pPAprimaryVertexFilter <<std::endl;
        std::cout<<"cut_pBeamScrapingFilter = "<< cut_pBeamScrapingFilter <<std::endl;
    }

    std::cout<<"cutPhoEt  = "<<cutPhoEt<<std::endl;
    std::cout<<"cutPhoEta = "<<cutPhoEta<<std::endl;

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

    TChain* treeHLT   = new TChain("hltanalysis/HltTree");
    TChain* treeggHiNtuplizer  = new TChain("ggHiNtuplizer/EventTree");
    TChain* treeHiEvt = new TChain("hiEvtAnalyzer/HiTree");
    TChain* treeSkim  = new TChain("skimanalysis/HltTree");
    TChain* treeHiForestInfo = new TChain("HiForest/HiForestInfo");
    TChain* treeGen=0;
    if(isMC) treeGen  = new TChain("HiGenParticleAna/hi");

    // pthatWeight Calculation block! 
    int nPthat = 5;
    float pthatCut[nPthat+1];
    const char* lowestPthatFileName="";
    int nfiles = 0;
    for (std::vector<std::string>::iterator it = inputFiles.begin() ; it != inputFiles.end(); ++it) {
        treeHLT->Add((*it).c_str());
        treeggHiNtuplizer->Add((*it).c_str());
        treeHiEvt->Add((*it).c_str());
        treeSkim->Add((*it).c_str());
        treeHiForestInfo->Add((*it).c_str());
        if(isMC) treeGen->Add((*it).c_str());
        if(isMC && (nfiles==0)) { 
            lowestPthatFileName = (*it).c_str(); 
            TString str(lowestPthatFileName);
            cout << "lowestPthatFileName = " << lowestPthatFileName << endl;
            if(str.Contains("15")) {
                float temp[] = {15,30,50,80,120,9999};          
                for(int j=0;j<nPthat+1;j++){
                    pthatCut[j] = temp[j];
                }
            } else if(str.Contains("30")) {
                float temp[] = {30,50,80,120,170,9999};          
                for(int j=0;j<nPthat+1;j++){
                    pthatCut[j] = temp[j];
                }
            }
        }
        nfiles++;
    }

    float tmpWeight[nPthat];
    if(isMC) {
        for(int j=0; j<nPthat ; j++){
            tmpWeight[j] = xSecCal(lowestPthatFileName,treeHiEvt, pthatCut[j], pthatCut[j+1]);
            cout << collisionName << ", pthatWeight of " << pthatCut[j] << " to " << pthatCut[j+1] << " = " << tmpWeight[j] << endl;
        }
    }
/*
    HiForestInfoController hfic(treeHiForestInfo);
    std::cout<<"### HiForestInfo Tree ###"<< std::endl;
    hfic.printHiForestInfo();
    std::cout<<"###"<< std::endl;
*/
    treeHLT->SetBranchStatus("*",0);     // disable all branches
    treeHLT->SetBranchStatus("HLT_HI*SinglePhoton*Eta*",1);     // enable photon branches
    treeHLT->SetBranchStatus("HLT_HI*DoublePhoton*Eta*",1);     // enable photon branches

    float vz;
    Int_t hiBin;
    UInt_t run, lumis;
    ULong64_t event;
    float pthat, pthatWeight;
    treeHiEvt->SetBranchAddress("vz",&vz);
    treeHiEvt->SetBranchAddress("hiBin",&hiBin);
    treeHiEvt->SetBranchAddress("run", &run);
    treeHiEvt->SetBranchAddress("evt", &event);
    treeHiEvt->SetBranchAddress("lumi", &lumis);
    if(isMC) {
        //treeHiEvt->Branch("pthatWeight", &pthatWeight, "pthatWeight/F");
        treeHiEvt->SetBranchAddress("pthat", &pthat);
    }   

    // specify explicitly which branches to store, do not use wildcard
    treeSkim->SetBranchStatus("*",0);

    Int_t pcollisionEventSelection;  // this filter is used for HI.
    if (isHI) {
        treeSkim->SetBranchStatus("pcollisionEventSelection",1);
        if (treeSkim->GetBranch("pcollisionEventSelection")) {
            treeSkim->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
        }
        else {   // overwrite to default
            pcollisionEventSelection = 1;
            std::cout<<"could not get branch : pcollisionEventSelection"<<std::endl;
            std::cout<<"set to default value : pcollisionEventSelection = "<<pcollisionEventSelection<<std::endl;
        }
    }
    else {
        pcollisionEventSelection = 0;    // default value if the collision is not HI, will not be used anyway.
    }
    Int_t pPAprimaryVertexFilter;    // this filter is used for PP.
    if (isPP) {
        treeSkim->SetBranchStatus("pPAprimaryVertexFilter",1);
        if (treeSkim->GetBranch("pPAprimaryVertexFilter")) {
            treeSkim->SetBranchAddress("pPAprimaryVertexFilter",&pPAprimaryVertexFilter);
        }
        else {   // overwrite to default
            pPAprimaryVertexFilter = 1;
            std::cout<<"could not get branch : pPAprimaryVertexFilter"<<std::endl;
            std::cout<<"set to default value : pPAprimaryVertexFilter = "<<pPAprimaryVertexFilter<<std::endl;
        }
    }
    else {
        pPAprimaryVertexFilter = 0;      // default value if the collision is not PP, will not be used anyway.
    }
    Int_t pBeamScrapingFilter;   // this filter is used for PP.
    if (isPP) {
        treeSkim->SetBranchStatus("pBeamScrapingFilter",1);
        if (treeSkim->GetBranch("pBeamScrapingFilter")) {
            treeSkim->SetBranchAddress("pBeamScrapingFilter",&pBeamScrapingFilter);
        }
        else {   // overwrite to default
            pBeamScrapingFilter = 1;
            std::cout<<"could not get branch : pBeamScrapingFilter"<<std::endl;
            std::cout<<"set to default value : pBeamScrapingFilter = "<<pBeamScrapingFilter<<std::endl;
        }
    }
    else {
        pBeamScrapingFilter = 0;     // default value if the collision is not PP, will not be used anyway.
    }

    // objects for z-jet correlations
    ggHiNtuplizer ggHi;
    ggHi.setupTreeForReading(treeggHiNtuplizer);    // treeggHiNtuplizer is input
    treeggHiNtuplizer->SetBranchStatus("*",0);
    treeggHiNtuplizer->SetBranchStatus("run",1);
    treeggHiNtuplizer->SetBranchStatus("event",1);
    treeggHiNtuplizer->SetBranchStatus("lumis",1);
    treeggHiNtuplizer->SetBranchStatus("nPho",1);
    treeggHiNtuplizer->SetBranchStatus("pho*",1);
    treeggHiNtuplizer->SetBranchStatus("pf*",1);
    //treeggHiNtuplizer->SetBranchStatus("tower*",1);
    if(isMC) treeggHiNtuplizer->SetBranchStatus("mc*",1);



    TFile* output = TFile::Open(outputFile,"RECREATE");
    TTree* configTree = setupConfigurationTreeForWriting(configCuts);

    // output tree variables
    TTree *outputTreeHLT=0, *outputTreeggHiNtuplizer=0, 
          *outputTreeHiEvt=0, *outputTreeSkim=0, *outputTreeHiForestInfo=0, *outputTreeGen=0;

    // output tree variables
    outputTreeHLT    = treeHLT->CloneTree(0);
    outputTreeggHiNtuplizer = treeggHiNtuplizer->CloneTree(0);
    outputTreeHiEvt = treeHiEvt->CloneTree(0);
    outputTreeSkim   = treeSkim->CloneTree(0);
    outputTreeHiForestInfo = treeHiForestInfo->CloneTree(0);
    if(isMC) outputTreeGen = treeGen ->CloneTree(0);

    outputTreeSkim->SetName("skimTree");
    outputTreeHLT->SetMaxTreeSize(MAXTREESIZE);
    outputTreeggHiNtuplizer->SetMaxTreeSize(MAXTREESIZE);
    outputTreeHiEvt->SetMaxTreeSize(MAXTREESIZE);
    outputTreeSkim->SetMaxTreeSize(MAXTREESIZE);
    outputTreeHiForestInfo->SetMaxTreeSize(MAXTREESIZE);
    if(isMC) outputTreeGen->SetMaxTreeSize(MAXTREESIZE);

    if(isMC) outputTreeHiEvt->Branch("pthatWeight", &pthatWeight, "pthatWeight/F");
  

    /////// Event Matching for DATA ///////
    EventMatcher* em = new EventMatcher();
    Long64_t duplicateEntries = 0;
    Long64_t entriesPassedEventSelection =0;
    Long64_t entriesAnalyzed =0;
    Long64_t entriesSpikeRejected=0;
    Long64_t entries = treeggHiNtuplizer->GetEntries();
    std::cout << "entries = " << entries << std::endl;
    std::cout<< "Loop : ggHiNtuplizer/EventTree" <<std::endl;
    //for (Long64_t j_entry=10000; j_entry<10100; ++j_entry)
    for (Long64_t j_entry=0; j_entry<entries; ++j_entry)
    {
        if (j_entry % 2000 == 0)  {
            std::cout << "current entry = " <<j_entry<<" out of "<<entries<<" : "<<std::setprecision(2)<<(double)j_entry/entries*100<<" %"<<std::endl;
        }

        treeHLT->GetEntry(j_entry);
        treeggHiNtuplizer->GetEntry(j_entry);
        treeSkim->GetEntry(j_entry);
        treeHiEvt->GetEntry(j_entry);
        treeHiForestInfo->GetEntry(j_entry);
        if(isMC) treeGen->GetEntry(j_entry);

        bool eventAdded = em->addEvent(run,lumis,event,j_entry);
        //std::cout << run << " " << lumis << " " << event << " " << j_entry << std::endl;
        if(!eventAdded) // this event is duplicate, skip this one.
        {
            duplicateEntries++;
            continue;
        }

        if(isMC) {
            if((pthat>=pthatCut[0]) && (pthat<pthatCut[1])) pthatWeight = tmpWeight[0];
            else if((pthat>=pthatCut[1]) && (pthat<pthatCut[2])) pthatWeight = tmpWeight[1];
            else if((pthat>=pthatCut[2]) && (pthat<pthatCut[3])) pthatWeight = tmpWeight[2];
            else if((pthat>=pthatCut[3]) && (pthat<pthatCut[4])) pthatWeight = tmpWeight[3];
            else if((pthat>=pthatCut[4]) && (pthat<pthatCut[5])) pthatWeight = tmpWeight[4];
            else continue;
        }
        // event selection
        if (!(TMath::Abs(vz) < cut_vz))  continue;
        if (isHI) {
            if ((pcollisionEventSelection < cut_pcollisionEventSelection))  continue;
        }
        else {
            if (pPAprimaryVertexFilter < cut_pPAprimaryVertexFilter || pBeamScrapingFilter < cut_pBeamScrapingFilter)  continue;
        }
        entriesPassedEventSelection++;

        // photon block
        // find leading photon
        int phoIdx = -1;     // index of the leading photon
        double maxPhoEt = -1;
        for(int i=0; i<ggHi.nPho; ++i)
        {
            bool failedEtCut  = (ggHi.phoEt->at(i) < cutPhoEt) ;
            bool failedEtaCut = (TMath::Abs(ggHi.phoEta->at(i)) > cutPhoEta) ;
            bool failedSpikeRejection;
            bool failedHotSpotRejection;
            //if (isHI) {
            failedSpikeRejection =( (ggHi.phoEta->at(i)<1.44) && 
                    (ggHi.phoSigmaIEtaIEta->at(i) < 0.002 ||
                     ggHi.pho_swissCrx->at(i)     > 0.9   ||
                     TMath::Abs(ggHi.pho_seedTime->at(i)) > 3) );
            // }
            // else {
            //     failedSpikeRejection = (ggHi.phoSigmaIEtaIEta->at(i) < 0.002);
            // }

            failedHotSpotRejection = (
                (ggHi.phoE3x3->at(i)/ggHi.phoE5x5->at(i) > 2./3.-0.03 && ggHi.phoE3x3->at(i)/ggHi.phoE5x5->at(i) < 2./3.+0.03) &&
                (ggHi.phoE1x5->at(i)/ggHi.phoE5x5->at(i) > 1./3.-0.03 && ggHi.phoE1x5->at(i)/ggHi.phoE5x5->at(i) < 1./3.+0.03) &&
                (ggHi.phoE2x5->at(i)/ggHi.phoE5x5->at(i) > 2./3.-0.03 && ggHi.phoE2x5->at(i)/ggHi.phoE5x5->at(i) < 2./3.+0.03) );
            
            bool failedHoverE = (ggHi.phoHoverE->at(i) > 0.2);      // <0.1 cut is applied after corrections
            //               bool failedEnergyRatio = ((float)ggHi.phoSCRawE->at(i)/ggHi.phoE->at(i) < 0.5);

            if (failedEtCut)          continue;
            if (failedEtaCut)         continue;
            if (failedSpikeRejection) continue;
            if (failedHotSpotRejection) {entriesSpikeRejected++; continue;}
            if (failedHoverE)         continue;
            //               if (failedEnergyRatio)    continue;    // actually applied after corrections

            if (ggHi.phoEt->at(i) > maxPhoEt)
            {
                maxPhoEt = ggHi.phoEt->at(i);
                phoIdx = i;
            }
        }
        if (phoIdx == -1) continue;
        entriesAnalyzed++;

        outputTreeHLT->Fill();
        outputTreeggHiNtuplizer->Fill();
        outputTreeHiEvt->Fill();
        outputTreeSkim->Fill();
        outputTreeHiForestInfo->Fill();
        if(isMC) outputTreeGen->Fill();
    }// event loop closed here

    std::cout<<  "Loop ENDED : ggHiNtuplizer/EventTree" <<std::endl;
    std::cout << "entries            = " << entries << std::endl;
    std::cout << "duplicateEntries   = " << duplicateEntries << std::endl;
    std::cout << "entriesPassedEventSelection   = " << entriesPassedEventSelection << std::endl;
    std::cout << "entriesAnalyzed               = " << entriesAnalyzed << std::endl;
    std::cout << "entriesSpikeRejected          = " << entriesSpikeRejected << std::endl;
    std::cout << "outputTreeHLT->GetEntries()   = " << outputTreeHLT->GetEntries() << std::endl;
    std::cout << "outputTreeggHiNtuplizer->GetEntries()   = " << outputTreeggHiNtuplizer->GetEntries() << std::endl;
    std::cout << "outputTreeSkim->GetEntries()  = " << outputTreeSkim->GetEntries() << std::endl;
    std::cout << "outputTreeHiEvt->GetEntries() = " << outputTreeHiEvt->GetEntries() << std::endl;
    std::cout << "outputTreeHiForestInfo->GetEntries() = " << outputTreeHiForestInfo->GetEntries() << std::endl;
    if(isMC) std::cout << "outputTreeGen->GetEntries() = " << outputTreeGen->GetEntries() << std::endl;


    output->cd();
    configTree->Write("",TObject::kOverwrite);
    output->Write("",TObject::kOverwrite);
    output->Close();
}
//<<<<<<< testMEMCalc.C
//void testMEMCalc(TString fileName,int channel){
//int main(){
//TString fileName="../../../../../../MELA/test/ggtoHtoZZ4l_VariousKDs_0+m0+h_withDisc_withMELA.root";
//int channel=3;
//=======
//void testMEMCalc(TString fileName,int channel){
int main(){
TString fileName="/afs/cern.ch/work/c/chmartin/private/Fa2stuff/MC_from_JHU/SMHiggsToZZTo4L_M-126_8TeV_powheg15-JHUgenV4-pythia6_false.root";
int channel=3;
//>>>>>>> 1.8
  TChain* t = new TChain("SelectedTree");
  t->Add(fileName);
  
  fileName.ReplaceAll(".root","_test.root");
  TFile* file = new TFile(fileName,"RECREATE");

  TTree* tree = (TTree*) t->CloneTree(0,"fast");

  MEMs test(8,125.65,"", false);

  double p0plus_mela_test,p2_mela_test,p2qqb_mela_test;
  double bkg_mela_test,p0plus_melaNorm_test;
  double p0hplus_mela_test,p1plus_mela_test;
  double p0minus_mela_test,p1_mela_test;

  double p0plus_VAJHU_test,p2_VAJHU_test,p2qqb_VAJHU_test;
  double p0hplus_VAJHU_test,p1plus_VAJHU_test;
  double p0minus_VAJHU_test,p1_VAJHU_test;

  double qqZZ_VAMCFM_test,ggZZ_VAMCFM_test,p0plus_VAMCFM_test;
  double qqZZ_VAMCFMNorm_test;

  double p0plus_mad, p0minus_mad, p2_mad, qqZZ_mad;

  double KDsigbkg, KD0minus, KD0hplus, KD2mplus;

  double dummy1,dummy2;
	
	double pg1g4_mela, pg1g4_VAJHU, pg1g2_mela, pg1g2_VAJHU, pg1g4_pi2_VAJHU, pg1g2_pi2_VAJHU;
	double ggzz_VAMCFM, ggzz_c5_VAMCFM, ggzz_c1_VAMCFM,ggzz_ci_VAMCFM;
  // new branches
  tree->Branch("p0plus_mela_test",&p0plus_mela_test,"p0plus_mela_test/D");
  tree->Branch("p0hplus_mela_test",&p0hplus_mela_test,"p0hplus_mela_test/D");
  tree->Branch("p0minus_mela_test",&p0minus_mela_test,"p0minus_mela_test/D");
  tree->Branch("p1_mela_test",&p1_mela_test,"p1_mela_test/D");
  tree->Branch("p1plus_mela_test",&p1plus_mela_test,"p1plus_mela_test/D");
  tree->Branch("p2_mela_test",&p2_mela_test,"p2_mela_test/D");
  tree->Branch("p2qqb_mela_test",&p2qqb_mela_test,"p2qqb_mela_test/D");

  tree->Branch("p0plus_melaNorm_test",&p0plus_melaNorm_test,"p0plus_melaNorm_test/D");
  tree->Branch("bkg_mela_test",&bkg_mela_test,"bkg_mela_test/D");

  tree->Branch("p0plus_VAMCFM_test",&p0plus_VAMCFM_test,"p0plus_VAMCFM_test/D");
  tree->Branch("qqZZ_VAMCFM_test",&qqZZ_VAMCFM_test,"qqZZ_VAMCFM_test/D");
  tree->Branch("qqZZ_VAMCFMNorm_test",&qqZZ_VAMCFMNorm_test,"qqZZ_VAMCFMNorm_test/D");
  tree->Branch("ggZZ_VAMCFM_test",&ggZZ_VAMCFM_test,"ggZZ_VAMCFM_test/D");

  tree->Branch("ggzz_VAMCFM_test",&ggzz_VAMCFM,"ggzz_VAMCFM_test/D");
  tree->Branch("ggzz_c5_VAMCFM_test",&ggzz_c5_VAMCFM,"ggzz_c5_VAMCFM_test/D");
  tree->Branch("ggzz_c1_VAMCFM_test",&ggzz_c1_VAMCFM,"ggzz_c1_VAMCFM_test/D");
  tree->Branch("ggzz_ci_VAMCFM_test",&ggzz_ci_VAMCFM,"ggzz_ci_VAMCFM_test/D");

  tree->Branch("p0plus_VAJHU_test",&p0plus_VAJHU_test,"p0plus_VAJHU_test/D");
  tree->Branch("p0minus_VAJHU_test",&p0minus_VAJHU_test,"p0minus_VAJHU_test/D");
  tree->Branch("p0hplus_VAJHU_test",&p0hplus_VAJHU_test,"p0hplus_VAJHU_test/D");
  tree->Branch("p1_VAJHU_test",&p1_VAJHU_test,"p1_VAJHU_test/D");
  tree->Branch("p1plus_VAJHU_test",&p1plus_VAJHU_test,"p1plus_VAJHU_test/D");
  tree->Branch("p2_VAJHU_test",&p2_VAJHU_test,"p2_VAJHU_test/D");
  tree->Branch("p2qqb_VAJHU_test",&p2qqb_VAJHU_test,"p2qqb_VAJHU_test/D");

  tree->Branch("p2_mad",&p2_mad,"p2_mad/D");
  tree->Branch("p0plus_mad",&p0plus_mad,"p0plus_mad/D");
  tree->Branch("p0minus_mad",&p0minus_mad,"p0minus_mad/D");
  tree->Branch("qqZZ_mad",&qqZZ_mad,"qqZZ_mad/D");

  tree->Branch("KDsigbkg",&KDsigbkg,"KDsigbkg/D");
  tree->Branch("KD0minus",&KD0minus,"KD0minus/D");
  tree->Branch("KD0hplus",&KD0hplus,"KD0hplus/D");
  tree->Branch("KD2mplus",&KD2mplus,"KD2mplus/D");

  tree->Branch("pg1g4_mela_test",&pg1g4_mela,"pg1g4_mela_test/D");
  tree->Branch("pg1g4_VAJHU_test",&pg1g4_VAJHU,"pg1g4_VAJHU_test/D");
  tree->Branch("pg1g2_mela_test",&pg1g2_mela,"pg1g2_mela_test/D");
  tree->Branch("pg1g2_VAJHU_test",&pg1g2_VAJHU,"pg1g2_VAJHU_test/D");
  tree->Branch("pg1g2_pi2_VAJHU_test",&pg1g2_pi2_VAJHU,"pg1g2_pi2_VAJHU_test/D");
  tree->Branch("pg1g4_pi2_VAJHU_test",&pg1g4_pi2_VAJHU,"pg1g4_pi2_VAJHU_test/D");
	
	double p0_self_VAJHU;
  tree->Branch("p0_self_VAJHU",&p0_self_VAJHU,"p0_self_VAJHU/D");
  // old branches

  float mzz,m1,m2,h1,h2,hs,phi,phi1,pt4l,Y4l;

  t->SetBranchAddress("ZZMass",&mzz);
  t->SetBranchAddress("Z1Mass",&m1);
  t->SetBranchAddress("Z2Mass",&m2);
  t->SetBranchAddress("helcosthetaZ1",&h1);
  t->SetBranchAddress("helcosthetaZ2",&h2);
  t->SetBranchAddress("costhetastar",&hs);
  t->SetBranchAddress("helphi",&phi);
  t->SetBranchAddress("phistarZ1",&phi1);
  t->SetBranchAddress("ZZPt",&pt4l);
  t->SetBranchAddress("ZZRapidity",&Y4l);

  vector<TLorentzVector> p4;
  vector<int> id;

  // channel 1: 4e 2: 4mu 2: 2e2mu
  if(channel==1){
    id.push_back(11);
    id.push_back(-11);
    id.push_back(11);
    id.push_back(-11);  
  }
  if(channel==2){
    id.push_back(13);
    id.push_back(-13);
    id.push_back(13);
    id.push_back(-13);  
  }
  if(channel==3){
    id.push_back(11);
    id.push_back(-11);
    id.push_back(13);
    id.push_back(-13);  
  }

  //for(int i=0 ; i<t->GetEntries(); i++){
  for(int i=0 ; i<500; i++){

    t->GetEntry(i);
    //t->Show(i);
    if ( i % 100 == 0 ) cout << i << "/" << t->GetEntries() << endl;

    if(mzz>140) continue;

    p4 = Calculate4Momentum(mzz,m1,m2,acos(hs),acos(h1),acos(h2),phi1,phi,pt4l,Y4l);
    
    test.computeME(kSMHiggs,kAnalytical,p4,id,p0plus_mela_test);
    test.computeME(kSMHiggs,kMELA_HCP,p4,id,p0plus_melaNorm_test);
    test.computeME(kqqZZ,kMELA_HCP,p4,id,bkg_mela_test);

    test.computeME(k0hplus,kAnalytical,p4,id,p0hplus_mela_test);
    test.computeME(k0minus,kAnalytical,p4,id,p0minus_mela_test);
    test.computeME(k1minus,kAnalytical,p4,id,p1_mela_test);
    test.computeME(k1plus,kAnalytical,p4,id,p1plus_mela_test);
    test.computeME(k2mplus_gg,kAnalytical,p4,id,p2_mela_test);
    test.computeME(k2mplus_qqbar,kAnalytical,p4,id,p2qqb_mela_test);
   
    test.computeME(kggZZ,kMCFM,p4,id,ggZZ_VAMCFM_test);
    //test.computeME(kSMHiggs,kMCFM,p4,id,p0plus_VAMCFM_test);
    test.computeME(kggZZ_SMHiggs,kMCFM,p4,id,p0plus_VAMCFM_test);
    test.computeME(kqqZZ,kMCFM,p4,id,qqZZ_VAMCFM_test);

    test.computeME(kSMHiggs,kJHUGen,p4,id,p0plus_VAJHU_test);
    test.computeME(k0hplus,kJHUGen,p4,id,p0hplus_VAJHU_test);
    test.computeME(k0minus,kJHUGen,p4,id,p0minus_VAJHU_test);
    test.computeME(k1minus,kJHUGen,p4,id,p1_VAJHU_test);
    test.computeME(k1plus,kJHUGen,p4,id,p1plus_VAJHU_test);
    test.computeME(k2mplus_gg,kJHUGen,p4,id,p2_VAJHU_test);
    test.computeME(k2mplus_qqbar,kJHUGen,p4,id,p2qqb_VAJHU_test);

    test.computeME(kSMHiggs,kMEKD,p4,id,p0plus_mad);
    test.computeME(k2mplus_gg,kMEKD,p4,id,p2_mad);
    test.computeME(k0minus,kMEKD,p4,id,p0minus_mad);
    test.computeME(kqqZZ,kMEKD,p4,id,qqZZ_mad);

    test.computeME_Interference(kg1g4,kAnalytical,p4,id,pg1g4_mela);
    test.computeME_Interference(kg1g4,kJHUGen,p4,id,pg1g4_VAJHU);
    test.computeME_Interference(kg1g4_pi_2,kJHUGen,p4,id,pg1g4_pi2_VAJHU);
    test.computeME_Interference(kg1g2_pi_2,kJHUGen,p4,id,pg1g2_pi2_VAJHU);
    test.computeME_Interference(kg1g2,kAnalytical,p4,id,pg1g2_mela);
    test.computeME_Interference(kg1g2,kJHUGen,p4,id,pg1g2_VAJHU);
   	vector<complex<double> > *prod = new vector<complex<double> >;
   	vector<complex<double> >* decay = new vector<complex<double> >;
		decay->push_back(1.0);
		decay->push_back(0.0);
		decay->push_back(0.0);
		decay->push_back(0.0);
    test.computeME(kSpin0_gg,kJHUGen,p4,id,prod,decay, p0_self_VAJHU);
    qqZZ_VAMCFMNorm_test=test.qqZZ_MCFMNorm;

    //test.computeMEs(p4,id);

    vector<complex<double> > *coupling = new vector<complex<double> >;
    vector<complex<double> > *couplingprod= new vector<complex<double> >;
    test.computeME(MEMNames::kggZZ, MEMNames::kMCFM, p4, id, ggzz_VAMCFM);
    complex<double> coup(1.,0.);
    coupling->push_back(coup);
    //cout<<(*coupling).size()<<endl;

    test.computeME(MEMNames::kggZZ_SMHiggs, MEMNames::kJHUGen, p4, id, couplingprod,coupling, ggzz_c1_VAMCFM);
    coupling->clear();
    coup=5.;
    coupling->push_back(coup);
    test.computeME(MEMNames::kggZZ_SMHiggs, MEMNames::kJHUGen, p4, id, couplingprod,coupling, ggzz_c5_VAMCFM);
    coupling->clear();
    coup.real(0.);
    coup.imag(1.);
    coupling->push_back(coup);
    test.computeME(MEMNames::kggZZ_SMHiggs, MEMNames::kJHUGen, p4, id, couplingprod,coupling, ggzz_ci_VAMCFM);

    test.computeKD(kSMHiggs,kJHUGen,kqqZZ,kMCFM,&MEMs::probRatio,KDsigbkg,dummy1,dummy2);
    test.computeKD(kSMHiggs,kJHUGen,k0minus,kJHUGen,&MEMs::probRatio,KD0minus,dummy1,dummy2);
    test.computeKD(kSMHiggs,kJHUGen,k0hplus,kJHUGen,&MEMs::probRatio,KD0hplus,dummy1,dummy2);
    test.computeKD(kSMHiggs,kJHUGen,k2mplus_gg,kJHUGen,&MEMs::probRatio,KD2mplus,dummy1,dummy2);
    double KD;
    test.computeKD(kSMHiggs,kMEKD,kqqZZ,kMCFM,&MEMs::probRatio,KD,dummy1,dummy2);

    if(KD>=1.0 || KD<=0.0)
      cout << "KD: " << KD << endl;
    /*
    cout << "p0plusJHU: " << p0plus_VAJHU_test << endl;
    cout << "qqZZMCFM: " << qqZZ_VAMCFMNorm_test << endl;
    cout << "sigbkg: " << KDsigbkg << endl;
    */

    /*
    cout << "p0plus: " << p0plus_mad << endl;
    cout << "p0minus: " << p0minus_mad << endl;
    cout << "p2: " << p2_mad << endl;
    cout << "qqZZ: " << qqZZ_mad << endl;

    double KD,pA,pB;
    test.computeKD(kSMHiggs,k0minus,kAnalytical,p4,id,KD,pA,pB);
    cout << "pseudoMELA: " << KD << endl;
    test.computeKD(kSMHiggs,k2mplus_gg,kAnalytical,p4,id,KD,pA,pB);
    cout << "graviMELA: " << KD << endl;
    test.computeKD(kSMHiggs,kqqZZ,kMELA_HCP,p4,id,KD,pA,pB);
    cout << "MELA: " << KD << endl;
    */

    tree->Fill();

  } // end loop over events

  file->cd();
  tree->Write();
  file->Close();

}
Пример #17
0
// default is Drell-Yan MC with minimal cuts
void skims(int dataset = 0,
           int whichSkims = 1) {

  if      ( whichSkims == 0 ) std::cout << " \n*** MERGING ALL THE FILES ***\n\n";
  else if ( whichSkims == 1 ) std::cout << " \n*** APPLYING MINIMAL CUTS ***\n\n";
  else if ( whichSkims == 2 ) std::cout << " \n*** APPLYING TIGHT CUTS, BUT ACCEPTANCE AND TRIGGER SELECTIONS ***\n\n";
  else {
    std::cout << "NO SKIMS TYPE DEFINED!\n";
    return;
  }


  TChain* tree = new TChain("tree");

  // ======== Monte Carlo ==========
  if ( dataset == 0 ) {
    std::cout << "DYJetsToLL_M50 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDYJetsToLL
    #include "scripts/htomm/skims/V00-01-10/chainDYJetsToLL"
  }
  
  else if ( dataset == 1 ) {
    std::cout << "DYToMuMu DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYToMuMu_M-20_CT10_TuneZ2star_v2_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYToMuMu_M-20_CT10_TuneZ2star_v2_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDYToMuMu
    #include "scripts/htomm/skims/V00-01-10/chainDYToMuMu"
  }
  
  else if ( dataset == 2 ) {
    std::cout << "TTJets DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCTTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola_Summer12_DR53X-PU_S10_START53_V7C-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCTTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola_Summer12_DR53X-PU_S10_START53_V7C-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainTTJets
    #include "scripts/htomm/skims/V00-01-10/chainTTJets"
  }

  else if ( dataset == 3 ) {
    std::cout << "DYToTauTau DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYToTauTau_M-20_CT10_TuneZ2star_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYToTauTau_M-20_CT10_TuneZ2star_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDYToTauTau
    #include "scripts/htomm/skims/V00-01-10/chainDYToTauTau"
  }

  else if ( dataset == 4 ) {
    std::cout << "WJetsToLNu DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCWJetsToLNu_TuneZ2Star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCWJetsToLNu_TuneZ2Star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainWJetsToLNu
    #include "scripts/htomm/skims/V00-01-10/chainWJetsToLNu"
  }

  else if ( dataset == 5 ) {
    std::cout << "WW DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCWW_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCWW_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainWW
    #include "scripts/htomm/skims/V00-01-10/chainWW"
  }

  else if ( dataset == 6 ) {
    std::cout << "WZ DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCWZ_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCWZ_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainWZ
    #include "scripts/htomm/skims/V00-01-10/chainWZ"
  }

  else if ( dataset == 7 ) {
    std::cout << "ZZ DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCZZ_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCZZ_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainZZ
    #include "scripts/htomm/skims/V00-01-10/chainZZ"
  }

  else if ( dataset == 8 ) {
    std::cout << "QCD DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCQCD_Pt_20_MuEnrichedPt_15_TuneZ2star_8TeV_pythia6_Summer12_DR53X-PU_S10_START53_V7A-v3/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCQCD_Pt_20_MuEnrichedPt_15_TuneZ2star_8TeV_pythia6_Summer12_DR53X-PU_S10_START53_V7A-v3/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainQCD_Pt_20_MuEnrichedPt_15
    #include "scripts/htomm/skims/V00-01-10/chainQCD_Pt_20_MuEnrichedPt_15"
  }
  else if ( dataset == 9 ) {
    std::cout << "DY2JetsToLL_M50 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDY2JetsToLL
    #include "scripts/htomm/skims/V00-01-10/chainDY2JetsToLL"
  }


  // ======== Special Monte Carlo =========
  else if ( dataset == 9990 ) {
    std::cout << "DYJetsToLL_PtZ-50To70 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_PtZ-50To70_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_PtZ-50To70_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDYJetsToLL_PtZ-50To70
    #include "scripts/htomm/skims/V00-01-10/chainDYJetsToLL_PtZ-50To70"
  }

  else if ( dataset == 9991 ) {
    std::cout << "DYJetsToLL_PtZ-70To100 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_PtZ-70To100_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_PtZ-70To100_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDYJetsToLL_PtZ-70To100
    #include "scripts/htomm/skims/V00-01-10/chainDYJetsToLL_PtZ-70To100"
  }

  else if ( dataset == 9992 ) {
    std::cout << "DYJetsToLL_PtZ-100 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_PtZ-100_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesMCDYJetsToLL_PtZ-100_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDYJetsToLL_PtZ-100
    #include "scripts/htomm/skims/V00-01-10/chainDYJetsToLL_PtZ-100"
  }



  // ======== Data ==========
  // Single Muon Dataset
  else if ( dataset == 10 ) {
    std::cout << "SingleMu 2012A-13Jul2012-v1 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012A-13Jul2012-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012A-13Jul2012-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainSingleMuRun2012A-13Jul2012-v1
    #include "scripts/htomm/skims/V00-01-10/chainSingleMuRun2012A-13Jul2012-v1"
  }

  else if ( dataset == 11 ) {
    std::cout << "SingleMu 2012A-recover-06Aug2012-v1 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012A-recover-06Aug2012-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012A-recover-06Aug2012-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainSingleMuRun2012A-recover-06Aug2012-v1
    #include "scripts/htomm/skims/V00-01-10/chainSingleMuRun2012A-recover-06Aug2012-v1"
  }

  else if ( dataset == 12 ) {
    std::cout << "SingleMu 2012B-13Jul2012-v1 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012B-13Jul2012-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012B-13Jul2012-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainSingleMuRun2012B-13Jul2012-v1
    #include "scripts/htomm/skims/V00-01-10/chainSingleMuRun2012B-13Jul2012-v1"
  }

  else if ( dataset == 13 ) {
    std::cout << "SingleMu 2012C-24Aug2012-v1 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012C-24Aug2012-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012C-24Aug2012-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainSingleMuRun2012C-24Aug2012-v1
    #include "scripts/htomm/skims/V00-01-10/chainSingleMuRun2012C-24Aug2012-v1"
  }

  else if ( dataset == 14 ) {
    std::cout << "SingleMu 2012C-PromptReco-v2 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012C-PromptReco-v2/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012C-PromptReco-v2/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainSingleMuRun2012C-PromptReco-v2
    #include "scripts/htomm/skims/V00-01-10/chainSingleMuRun2012C-PromptReco-v2"
  }

  else if ( dataset == 15 ) {
    std::cout << "SingleMu 2012D-PromptReco-v1 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012D-PromptReco-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataSingleMuRun2012D-PromptReco-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainSingleMuRun2012D-PromptReco-v1
    #include "scripts/htomm/skims/V00-01-10/chainSingleMuRun2012D-PromptReco-v1"
  }


  // Double Muon Dataset
  else if ( dataset == 20 ) {
    std::cout << "DoubleMu 2012A-13Jul2012-v1 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012A-13Jul2012-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012A-13Jul2012-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012A-13Jul2012-v1
    #include "scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012A-13Jul2012-v1"
  }

  else if ( dataset == 21 ) {
    std::cout << "DoubleMu 2012B-13Jul2012-v4 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012B-13Jul2012-v4/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012B-13Jul2012-v4/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012B-13Jul2012-v4
    #include "scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012B-13Jul2012-v4"
  }

  else if ( dataset == 22 ) {
    std::cout << "DoubleMu 2012C-24Aug2012-v1 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012C-24Aug2012-v1/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012C-24Aug2012-v1/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012C-24Aug2012-v1
    #include "scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012C-24Aug2012-v1"
  }

  else if ( dataset == 23 ) {
    std::cout << "DoubleMu 2012C-PromptReco-v2 DATASET\n";
    //ls /data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012C-PromptReco-v2/ | grep root | awk '{print "tree->AddFile(\"/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/NtuplesDataDoubleMuRun2012C-PromptReco-v2/"$1"\");"}' >> scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012C-PromptReco-v2
    #include "scripts/htomm/skims/V00-01-10/chainDoubleMuRun2012C-PromptReco-v2"
  }

  else {
    std::cout << "NO DATASET DEFINED!\n";
    return;
  }


  // ======== DEFINE THE FILENAME ========
  TString path = "/data/uftrig01b/digiovan/root/higgs/CMSSW_5_3_5/V00-01-10/";

  TFile *newfile;

  if      ( dataset == 0 ) path+= "NtuplesMCDYJetsToLL_M-50_TuneZ2Star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v1/";
  else if ( dataset == 1 ) path+= "NtuplesMCDYToMuMu_M-20_CT10_TuneZ2star_v2_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1/";
  else if ( dataset == 2 ) path+= "NtuplesMCTTJets_MassiveBinDECAY_TuneZ2star_8TeV-madgraph-tauola_Summer12_DR53X-PU_S10_START53_V7C-v1/";
  else if ( dataset == 3 ) path+= "NtuplesMCDYToTauTau_M-20_CT10_TuneZ2star_8TeV-powheg-pythia6_Summer12_DR53X-PU_S10_START53_V7A-v1/";
  else if ( dataset == 4 ) path+= "NtuplesMCWJetsToLNu_TuneZ2Star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/";
  else if ( dataset == 5 ) path+= "NtuplesMCWW_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/";
  else if ( dataset == 6 ) path+= "NtuplesMCWZ_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/";
  else if ( dataset == 7 ) path+= "NtuplesMCZZ_TuneZ2star_8TeV_pythia6_tauola_Summer12_DR53X-PU_S10_START53_V7A-v1/";
  else if ( dataset == 8 ) path+= "NtuplesMCQCD_Pt_20_MuEnrichedPt_15_TuneZ2star_8TeV_pythia6_Summer12_DR53X-PU_S10_START53_V7A-v3/";
  else if ( dataset == 9 ) path+= "NtuplesMCDY2JetsToLL_M-50_TuneZ2Star_8TeV-madgraph_Summer12_DR53X-PU_S10_START53_V7A-v1/";

  else if ( dataset == 9990 ) path+="NtuplesMCDYJetsToLL_PtZ-50To70_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v1/";
  else if ( dataset == 9990 ) path+="NtuplesMCDYJetsToLL_PtZ-70To100_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/";
  else if ( dataset == 9992 ) path+="NtuplesMCDYJetsToLL_PtZ-100_TuneZ2star_8TeV-madgraph-tarball_Summer12_DR53X-PU_S10_START53_V7A-v2/";

  else if ( dataset == 10 ) path+="NtuplesDataSingleMuRun2012A-13Jul2012-v1/";
  else if ( dataset == 11 ) path+="NtuplesDataSingleMuRun2012A-recover-06Aug2012-v1/";
  else if ( dataset == 12 ) path+="NtuplesDataSingleMuRun2012B-13Jul2012-v1/";
  else if ( dataset == 13 ) path+="NtuplesDataSingleMuRun2012C-24Aug2012-v1/";
  else if ( dataset == 14 ) path+="NtuplesDataSingleMuRun2012C-PromptReco-v2/";
  else if ( dataset == 15 ) path+="NtuplesDataSingleMuRun2012D-PromptReco-v1/";
                                 
  else if ( dataset == 20 ) path+="NtuplesDataDoubleMuRun2012A-13Jul2012-v1/";
  else if ( dataset == 21 ) path+="NtuplesDataDoubleMuRun2012B-13Jul2012-v4/";
  else if ( dataset == 22 ) path+="NtuplesDataDoubleMuRun2012C-24Aug2012-v1/";
  else if ( dataset == 23 ) path+="NtuplesDataDoubleMuRun2012C-PromptReco-v2/";

  else {
    std::cout << "NO DATASET DEFINED!\n";
    return;
  }



  if      (whichSkims == 0) path += "merged/";
  else if (whichSkims == 1) path += "minimal/";
  else if (whichSkims == 2) path += "complete/";
  else {
    std::cout << "NO SKIMS TYPE DEFINED!\n";
    return;
  }



  if      ( dataset == 0 ) path += "DYJetsToLL_";
  else if ( dataset == 1 ) path += "DYToMuMu_";
  else if ( dataset == 2 ) path += "TTJets_";
  else if ( dataset == 3 ) path += "DYToTauTau_";
  else if ( dataset == 4 ) path += "WJetsToLNu_";
  else if ( dataset == 5 ) path += "WW_";
  else if ( dataset == 6 ) path += "WZ_";
  else if ( dataset == 7 ) path += "ZZ_";
  else if ( dataset == 8 ) path += "QCD_Pt_20_MuEnrichedPt_15_";
  else if ( dataset == 9 ) path += "DY2JetsToLL_";


  else if ( dataset == 9990 ) path += "DYJetsToLL_PtZ-50To70_";
  else if ( dataset == 9990 ) path += "DYJetsToLL_PtZ-70To100_";
  else if ( dataset == 9992 ) path += "DYJetsToLL_PtZ-100_";


  else if ( dataset == 10 ) path += "SingleMuRun2012A-13Jul2012-v1_";
  else if ( dataset == 11 ) path += "SingleMuRun2012A-recover-06Aug2012-v1_";
  else if ( dataset == 12 ) path += "SingleMuRun2012B-13Jul2012-v1_";
  else if ( dataset == 13 ) path += "SingleMuRun2012C-24Aug2012-v1_";
  else if ( dataset == 14 ) path += "SingleMuRun2012C-PromptReco-v2_";
  else if ( dataset == 15 ) path += "SingleMuRun2012D-PromptReco-v1_";


  else if ( dataset == 20 ) path += "DoubleMuRun2012A-13Jul2012-v1_";
  else if ( dataset == 21 ) path += "DoubleMuRun2012B-13Jul2012-v4_";
  else if ( dataset == 22 ) path += "DoubleMuRun2012C-24Aug2012-v1_";
  else if ( dataset == 23 ) path += "DoubleMuRun2012C-PromptReco-v2_";

  else {
    std::cout << "NO DATASET DEFINED!\n";
    return;
  }


  if      (whichSkims == 0) newfile = new TFile(path+"merged.root","recreate");
  else if (whichSkims == 1) newfile = new TFile(path+"minimal.root","recreate");
  else if (whichSkims == 2) newfile = new TFile(path+"complete.root","recreate");
  else {
    std::cout << "NO SKIMS TYPE DEFINED!\n";
    return;
  }


  std::cout << "saving in file " << newfile -> GetName() << std::endl;
  TTree *newtree = tree->CloneTree(0);


  // ======== GET THE HANDLES FOR SKIMMING ========
  float recoCandMass;
  tree->SetBranchAddress("recoCandMass", &recoCandMass);

  float vertexNormChiSquare, angleDiMuons;

  tree->SetBranchAddress("vertexNormChiSquare", &vertexNormChiSquare);
  tree->SetBranchAddress("angleDiMuons"       , &angleDiMuons );
  
  _MuonInfo reco1, reco2;
  
  tree->SetBranchAddress("reco1", &reco1);
  tree->SetBranchAddress("reco2", &reco2);


  // ======== PERFORM THE SKIMMING ========
  cout<<"Loop over the " << tree->GetEntries() << " entries ...\n";
  for (int iEvt=0; iEvt < tree->GetEntries(); iEvt++) {
    
    if ( (iEvt % 500000)==0 ) cout << "event " << iEvt << endl;
    tree -> GetEntry(iEvt);

    // additional selection cuts
    if (recoCandMass <  60 && whichSkims > 0) continue;
    //if (recoCandMass > 160 && whichSkims > 0) continue;
    if (vertexNormChiSquare > 10 && whichSkims > 0) continue; 
    if (angleDiMuons > TMath::Pi()-0.02 && whichSkims > 0) continue;

    if (!isKinTight_2012_noAcc(reco1) && whichSkims > 1) continue;
    if (!isKinTight_2012_noAcc(reco2) && whichSkims > 1) continue;

    newtree->Fill(); 
  }

  newtree->Print();
  newtree->AutoSave();
  
  std::cout << "new tree has " << newtree -> GetEntries() << std::endl;
  delete newfile;
}
Пример #18
0
void TreeFiller(string inFiles, string outFile, string histName) {

	
	TChain *origFiles = new TChain("treeVars", "treeVars");
	origFiles->Add(inFiles.c_str());
	
	int nEntries = origFiles->GetEntries();
	cout << "The old chain contains " << nEntries << " entries." << endl;
	
	
	float jet1Eta, jet2Eta, deltaY, genTopPt1, genTopPt2, jet1Mass, jet2Mass, jet1MinMass, jet2MinMass, jet1BDisc, jet2BDisc, jet1SubjetMaxBDisc, jet2SubjetMaxBDisc,
			jet1tau32, jet2tau32, jet1Pt, jet2Pt, jetPtForMistag, mttMass, mttMassPred, mistagWt, mistagWtAll, mistagWtNsubAll, mistagWtNsub, index, cutflow, NNoutput, ptReweight;
	int jet1NSubjets, jet2NSubjets;
		
	
	origFiles->SetBranchAddress("jet1Eta", &jet1Eta);
	origFiles->SetBranchAddress("jet2Eta", &jet2Eta);
	origFiles->SetBranchAddress("deltaY", &deltaY);
	origFiles->SetBranchAddress("jet1Mass", &jet1Mass);
	origFiles->SetBranchAddress("jet2Mass", &jet2Mass);
	origFiles->SetBranchAddress("jet1minMass", &jet1MinMass);
	origFiles->SetBranchAddress("jet2minMass", &jet2MinMass);
	origFiles->SetBranchAddress("jet1Nsubj", &jet1NSubjets);
	origFiles->SetBranchAddress("jet2Nsubj", &jet2NSubjets);
	origFiles->SetBranchAddress("jet1BDisc", &jet1BDisc);
	origFiles->SetBranchAddress("jet2BDisc", &jet2BDisc);
	origFiles->SetBranchAddress("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet1tau32", &jet1tau32);
	origFiles->SetBranchAddress("jet2tau32", &jet2tau32);
	origFiles->SetBranchAddress("jet1Pt", &jet1Pt);
	origFiles->SetBranchAddress("jet2Pt", &jet2Pt);
	origFiles->SetBranchAddress("jetPtForMistag", &jetPtForMistag);
	origFiles->SetBranchAddress("mttMass", &mttMass);
	origFiles->SetBranchAddress("mttMassPred", &mttMassPred);
	origFiles->SetBranchAddress("index", &index);
	origFiles->SetBranchAddress("cutflow", &cutflow);
	origFiles->SetBranchAddress("NNoutput", &NNoutput);
	origFiles->SetBranchAddress("mistagWt", &mistagWt);
	origFiles->SetBranchAddress("genTopPt1", &genTopPt1);	
	origFiles->SetBranchAddress("genTopPt2", &genTopPt2);	

	
	TFile *newFile = new TFile(outFile.c_str(), "RECREATE");
	TTree *newTree = origFiles->CloneTree(0);
	newTree->Branch("mistagWtNsub", &mistagWtNsub, "mistagWtNsub/F");
	newTree->Branch("mistagWtNsubAll", &mistagWtNsubAll, "mistagWtNsubAll/F");
	newTree->Branch("mistagWtAll", &mistagWtAll, "mistagWtAll/F");
	newTree->Branch("ptReweight", &ptReweight, "ptReweight/F");

	newTree->SetBranchAddress("mistagWtNsub", &mistagWtNsub);
	newTree->SetBranchAddress("misagWtNsubAll", &mistagWtNsubAll);
	newTree->SetBranchAddress("mistagWtAll", &mistagWtAll);
	newTree->SetBranchAddress("ptReweight", &ptReweight);
	
/*	
	TMVA::Reader* reader = new TMVA::Reader();
	reader->AddVariable("jet1Eta", &jet1Eta);
	reader->AddVariable("jet2Eta", &jet2Eta);
	reader->AddVariable("deltaY", &deltaY);
	reader->AddVariable("jet1Mass", &jet1Mass);
	reader->AddVariable("jet2Mass", &jet2Mass);
	reader->AddVariable("jet1BDisc", &jet1BDisc);
	reader->AddVariable("jet2BDisc", &jet2BDisc);
	reader->AddVariable("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	reader->AddVariable("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	reader->AddVariable("jet1tau32", &jet1tau32);
	reader->AddVariable("jet2tau32", &jet2tau32);
	reader->AddVariable("jet1Pt", &jet1Pt);
	reader->AddVariable("jet2Pt", &jet2Pt);
	reader->AddVariable("mttMass", &mttMass);

	reader->BookMVA("MLP", "weights/TMVA_tt_Zp_MLP.weightsZp10_cut4.xml");
*/	
	//TFile *mistagFileLow = new TFile("notCSVL_notCSVM_mistag.root");
	//TFile *mistagFileMed = new TFile("CSVL_notCSVM_mistag.root");
	//TFile *mistagFileHi = new TFile("CSVM_mistag.root");
	TFile *mistagFileLow = new TFile("Jan21_mistag.root");//data_LowBscore_mistag_Dec16.root");
	TFile *mistagFileMed = new TFile("Jan21_mistag.root");//data_MedBscore_mistag_Dec16.root");
	TFile *mistagFileHi = new TFile("Jan21_mistag.root");//data_HiBscore_mistag_Dec16.root");
	TFile *mistagFile = new TFile("Jan21_mistag.root");//data_AllBscore_mistag_Dec16.root");
	histName = "MISTAG_RATE_SUB_TTBAR_Inclusive";
	TH1F *mistagRateHistAll = (TH1F *) mistagFile->Get( histName.c_str() )->Clone();	
	TH1F *mistagRateHistLow = (TH1F *) mistagFileLow->Get( histName.c_str() )->Clone();	
	TH1F *mistagRateHistMed = (TH1F *) mistagFileMed->Get( histName.c_str() )->Clone();	
	TH1F *mistagRateHistHi = (TH1F *) mistagFileHi->Get( histName.c_str() )->Clone();	
	string histName2 = "MISTAG_RATE_SUB_TTBAR_InclNsub";
	TH1F *mistagRateHistNSAll = (TH1F *) mistagFile->Get( histName2.c_str() )->Clone();	
	TH1F *mistagRateHistNSLow = (TH1F *) mistagFileLow->Get( histName2.c_str() )->Clone();	
	TH1F *mistagRateHistNSMed = (TH1F *) mistagFileMed->Get( histName2.c_str() )->Clone();	
	TH1F *mistagRateHistNSHi = (TH1F *) mistagFileHi->Get( histName2.c_str() )->Clone();	
	cout << histName << endl;
	cout << "Entries " << mistagRateHistAll->Integral() << endl;	
	cout << "Entries2 " << mistagRateHistNSHi->Integral() << endl;
	
	for (int i = 0; i < origFiles->GetEntries(); i++){
	
		origFiles->GetEntry(i);
		if  (i % 1000000 == 0) cout << 100*(float(i) / float(nEntries)) << " Percent Complete." << endl;
		mistagWt = 0.000;
		mistagWtNsub = 30.0000;
	
		if (cutflow == 4 || index == 1){
		
			if (genTopPt1 > 400) genTopPt1 = 400;
			if (genTopPt2 > 400) genTopPt2 = 400;
			//NNoutput =  reader->EvaluateMVA("MLP");
			ptReweight = sqrt( exp(0.156 - 0.00137*genTopPt1)*exp(0.156 - 0.00137*genTopPt2) );			
			
			if (index == 1) {
				
				float bScore = -9.99;
				float tauScore = 9.99;
				int probeJet = 0;
				if (jet1Pt == jetPtForMistag) {
					probeJet = 1;
					bScore = jet1SubjetMaxBDisc;
					tauScore = jet2tau32;
				}
				if (jet2Pt == jetPtForMistag) {
					bScore = jet2SubjetMaxBDisc;
					tauScore = jet1tau32;
					probeJet = 2;
				}


				if (bScore > 0.679) mistagWt = mistagRateHistHi->GetBinContent( mistagRateHistHi->FindBin( jetPtForMistag ) );			
				else if (bScore > 0.244) mistagWt = mistagRateHistMed->GetBinContent( mistagRateHistMed->FindBin( jetPtForMistag ) );			
				else mistagWt = mistagRateHistLow->GetBinContent( mistagRateHistLow->FindBin( jetPtForMistag ) );			
				mistagWtAll = mistagRateHistAll->GetBinContent( mistagRateHistAll->FindBin( jetPtForMistag ) );

				if (tauScore < 0.7){

				if (bScore > 0.679) mistagWtNsub = mistagRateHistNSHi->GetBinContent( mistagRateHistNSHi->FindBin( jetPtForMistag ) );			
				else if (bScore > 0.244) mistagWtNsub = mistagRateHistNSMed->GetBinContent( mistagRateHistNSMed->FindBin( jetPtForMistag ) );			
				else mistagWtNsub = mistagRateHistNSLow->GetBinContent( mistagRateHistNSLow->FindBin( jetPtForMistag ) );			
				mistagWtNsubAll = mistagRateHistNSAll->GetBinContent( mistagRateHistNSAll->FindBin( jetPtForMistag ) );
				}
				else {
				mistagWtNsub = 0.0;
				mistagWtNsubAll = 0.0;
				}
				//mttMass = mttMassPred;
				//NNoutput = reader->EvaluateMVA("MLP");
			}
			
			
			newTree->Fill();
		
		}
		

	}


	
	
	newTree->Draw("mistagWtNsub", "index == 1");	
	


	newFile->cd();
	newTree->Write();
	newFile->Write();
	newFile->Close();
	
}
void minBiasJetSkim(const TString configFile, const TString inputFile, const TString outputFile)
{
       std::cout<<"running minBiasJetSkim()"<<std::endl;
       std::cout<<"configFile  = "<< configFile.Data() <<std::endl;
       std::cout<<"inputFile   = "<< inputFile.Data() <<std::endl;
       std::cout<<"outputFile  = "<< outputFile.Data() <<std::endl;

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

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

       // cut configuration
       float cut_vz = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].f[CUTS::EVT::k_vz];
       int cut_pcollisionEventSelection = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pcollisionEventSelection];

       std::vector<std::string> jetCollections = ConfigurationParser::ParseList(configCuts.proc[CUTS::kSKIM].obj[CUTS::kJET].s[CUTS::JET::k_jetCollection]);
       int nMaxEvents_minBiasMixing = configCuts.proc[CUTS::kSKIM].obj[CUTS::kGAMMAJET].i[CUTS::GJT::k_nMaxEvents_minBiasMixing];
       int nCentralityBins = configCuts.proc[CUTS::kSKIM].obj[CUTS::kGAMMAJET].i[CUTS::GJT::k_nCentralityBins];
       int nVertexBins = configCuts.proc[CUTS::kSKIM].obj[CUTS::kGAMMAJET].i[CUTS::GJT::k_nVertexBins];
       int nEventPlaneBins = configCuts.proc[CUTS::kSKIM].obj[CUTS::kGAMMAJET].i[CUTS::GJT::k_nEventPlaneBins];

       int nJetCollections = jetCollections.size();

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

       std::cout<<"nJetCollections = "<< nJetCollections <<std::endl;
       for (int i=0; i<nJetCollections; ++i) {
           std::cout << Form("jetCollections[%d] = %s", i, jetCollections.at(i).c_str()) << std::endl;
       }
       std::cout<<"nMaxEvents_minBiasMixing = "<< nMaxEvents_minBiasMixing <<std::endl;
       std::cout<<"nCentralityBins          = "<< nCentralityBins <<std::endl;
       std::cout<<"nVertexBins              = "<< nVertexBins <<std::endl;
       std::cout<<"nEventPlaneBins          = "<< nEventPlaneBins <<std::endl;

       std::vector<std::string> inputFiles = InputConfigurationParser::ParseFiles(inputFile.Data());

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

       TChain* treeHLT   = new TChain("hltanalysis/HltTree");
       TChain* treeEvent = new TChain("ggHiNtuplizer/EventTree");
       TChain* treeJets[nJetCollections];
       for (int i=0; i<nJetCollections; ++i) {
           treeJets[i] = new TChain(Form("%s/t", jetCollections.at(i).c_str()));
       }
       TChain* treeHiEvt = new TChain("hiEvtAnalyzer/HiTree");
       TChain* treeSkim  = new TChain("skimanalysis/HltTree");
       TChain* treeHiForestInfo = new TChain("HiForest/HiForestInfo");

       for (std::vector<std::string>::iterator it = inputFiles.begin() ; it != inputFiles.end(); ++it) {
          treeHLT->Add((*it).c_str());
          treeEvent->Add((*it).c_str());
          for (int i=0; i<nJetCollections; ++i) {
              treeJets[i]->Add((*it).c_str());
          }
          treeHiEvt->Add((*it).c_str());
          treeSkim->Add((*it).c_str());
          if (it == inputFiles.begin())  treeHiForestInfo->Add((*it).c_str());
       }

       HiForestInfoController hfic(treeHiForestInfo);
       std::cout<<"### HiForestInfo Tree ###"<< std::endl;
       hfic.printHiForestInfo();
       std::cout<<"###"<< std::endl;

       treeHLT->SetBranchStatus("*",0);     // disable all branches

       treeEvent->SetBranchStatus("*",0);
       treeEvent->SetBranchStatus("run",1);
       treeEvent->SetBranchStatus("event",1);
       treeEvent->SetBranchStatus("lumis",1);

       for (int i=0; i<nJetCollections; ++i) {
           treeJets[i]->SetBranchStatus("*",0);        // disable all branches
           treeJets[i]->SetBranchStatus("nref",1);     // enable jet branches
           treeJets[i]->SetBranchStatus("rawpt",1);    // enable jet branches
           treeJets[i]->SetBranchStatus("jtpt",1);     // enable jet branches
           treeJets[i]->SetBranchStatus("jteta",1);    // enable jet branches
           treeJets[i]->SetBranchStatus("jtphi",1);    // enable jet branches
           treeJets[i]->SetBranchStatus("jty",1);      // enable jet branches
           treeJets[i]->SetBranchStatus("jtpu",1);     // enable jet branches
           treeJets[i]->SetBranchStatus("jtm",1);      // enable jet branches
           treeJets[i]->SetBranchStatus("track*",1);
           treeJets[i]->SetBranchStatus("charged*",1);
           treeJets[i]->SetBranchStatus("photon*",1);
           treeJets[i]->SetBranchStatus("neutral*",1);
           treeJets[i]->SetBranchStatus("eMax*",1);
           treeJets[i]->SetBranchStatus("eSum*",1);
           treeJets[i]->SetBranchStatus("eN*",1);
           treeJets[i]->SetBranchStatus("muMax*",1);
           treeJets[i]->SetBranchStatus("muSum*",1);
           treeJets[i]->SetBranchStatus("muN*",1);
       }

       // specify explicitly which branches to store, do not use wildcard
       treeHiEvt->SetBranchStatus("*",0);
       treeHiEvt->SetBranchStatus("run",1);
       treeHiEvt->SetBranchStatus("evt",1);
       treeHiEvt->SetBranchStatus("lumi",1);
       treeHiEvt->SetBranchStatus("vz",1);
       treeHiEvt->SetBranchStatus("hiBin",1);
       treeHiEvt->SetBranchStatus("hiHF",1);
       treeHiEvt->SetBranchStatus("hiHFplus",1);
       treeHiEvt->SetBranchStatus("hiHFminus",1);
       treeHiEvt->SetBranchStatus("hiHFplusEta4",1);
       treeHiEvt->SetBranchStatus("hiHFminusEta4",1);
      //  treeHiEvt->SetBranchStatus("hiNevtPlane",1);

       float vz;
       Int_t hiBin;
       Float_t         hiEvtPlanes[29];   //[hiNevtPlane]
       treeHiEvt->SetBranchAddress("hiEvtPlanes",&hiEvtPlanes);

       treeHiEvt->SetBranchAddress("vz",&vz);
       treeHiEvt->SetBranchAddress("hiBin",&hiBin);

       // specify explicitly which branches to store, do not use wildcard
       treeSkim->SetBranchStatus("*",0);
       treeSkim->SetBranchStatus("ana_step",1);
       treeSkim->SetBranchStatus("pcollisionEventSelection",1);
       treeSkim->SetBranchStatus("pHBHENoiseFilterResultProducer",1);
       treeSkim->SetBranchStatus("HBHENoiseFilterResultRun1",1);
       treeSkim->SetBranchStatus("HBHENoiseFilterResultRun2Loose",1);
       treeSkim->SetBranchStatus("HBHENoiseFilterResultRun2Tight",1);
       treeSkim->SetBranchStatus("HBHENoiseFilterResult",1);
       treeSkim->SetBranchStatus("HBHEIsoNoiseFilterResult",1);

       Int_t pcollisionEventSelection;

       if (treeSkim->GetBranch("pcollisionEventSelection")) {
           treeSkim->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
       }
       else {   // overwrite to default
           pcollisionEventSelection = 1;
           std::cout<<"could not get branch : pcollisionEventSelection"<<std::endl;
           std::cout<<"set to default value : pcollisionEventSelection = "<<pcollisionEventSelection<<std::endl;
       }

       // event information
       UInt_t run, lumis;
       ULong64_t event;
       treeEvent->SetBranchAddress("run", &run);
       treeEvent->SetBranchAddress("event", &event);
       treeEvent->SetBranchAddress("lumis", &lumis);

       TFile* output = new TFile(outputFile,"RECREATE");

       TTree *configTree = setupConfigurationTreeForWriting(configCuts);

       int centBinWidth = 200/nCentralityBins;  // number of "hiBin"s that a centrality bin covers
       int vertexBinWidth = 30/nVertexBins;     // number of "vz"s    that a vertex     bin covers
       float eventPlaneBinWidth = TMath::Pi()/nEventPlaneBins;     // number of "vz"s    that a vertex     bin covers
                                                // accepted vz range is -15 to 15.

       TTree *outputTreesHLT[nCentralityBins][nVertexBins][nEventPlaneBins];
       TTree *outputTreesEvent[nCentralityBins][nVertexBins][nEventPlaneBins];
       TTree *outputTreesJet[nCentralityBins][nVertexBins][nEventPlaneBins][nJetCollections];
       TTree *outputTreesHiEvt[nCentralityBins][nVertexBins][nEventPlaneBins];
       TTree *outputTreesSkim[nCentralityBins][nVertexBins][nEventPlaneBins];

       Long64_t nEntriesFilled[nCentralityBins][nVertexBins][nEventPlaneBins];    // number of events read for a centrality bin
       for(int i=0; i<nCentralityBins; ++i)
       {
           for(int j=0; j<nVertexBins; ++j){
             for(int l=0; l<nEventPlaneBins; ++l) {

               nEntriesFilled[i][j][l] = 0;

               outputTreesHLT[i][j][l] = treeHLT->CloneTree(0);
               outputTreesHLT[i][j][l]->SetName(Form("hltTree_centBin%d_vzBin%d_evPlaneBin%d", i, j, l));
               outputTreesHLT[i][j][l]->SetTitle(Form("subbranches of hltanalysis/HltTree for centrality bin %d vz bin %d evPlane Bin %d", i, j, l));
               outputTreesHLT[i][j][l]->SetMaxTreeSize(MAXTREESIZE);

               outputTreesEvent[i][j][l] = treeEvent->CloneTree(0);
               outputTreesEvent[i][j][l]->SetName(Form("EventTree_centBin%d_vzBin%d_evPlaneBin%d", i, j, l));
               outputTreesEvent[i][j][l]->SetTitle(Form("subbranches of ggHiNtuplizer/EventTree for centrality bin %d vz bin %d evPlane Bin %d", i, j, l));
               outputTreesEvent[i][j][l]->SetMaxTreeSize(MAXTREESIZE);

               for(int k=0; k<nJetCollections; ++k){
                   std::string jetCollectionName = jetCollections.at(k).c_str();
                   outputTreesJet[i][j][l][k] = treeJets[k]->CloneTree(0);
                   outputTreesJet[i][j][l][k]->SetName(Form("%s_centBin%d_vzBin%d_evPlaneBin%d", jetCollectionName.c_str(), i, j, l));
                   outputTreesJet[i][j][l][k]->SetTitle(Form("subbranches of %s/t for centrality bin %d vz bin %d evPlane Bin %d", jetCollectionName.c_str(), i, j, l));
                   outputTreesJet[i][j][l][k]->SetMaxTreeSize(MAXTREESIZE);
               }

               outputTreesHiEvt[i][j][l] = treeHiEvt->CloneTree(0);
               outputTreesHiEvt[i][j][l]->SetName(Form("HiEvt_centBin%d_vzBin%d_evPlaneBin%d", i, j, l));
               outputTreesHiEvt[i][j][l]->SetTitle(Form("subbranches of hiEvtAnalyzer/HiTree for centrality bin %d vz bin %d evPlane Bin %d", i, j, l));
               outputTreesHiEvt[i][j][l]->SetMaxTreeSize(MAXTREESIZE);

               outputTreesSkim[i][j][l] = treeSkim->CloneTree(0);
               outputTreesSkim[i][j][l]->SetName(Form("skim_centBin%d_vzBin%d_evPlaneBin%d", i, j, l));
               outputTreesSkim[i][j][l]->SetTitle(Form("subbranches of skimanalysis/HltTree for centrality bin %d vz bin %d evPlane Bin %d", i, j, l));
               outputTreesSkim[i][j][l]->SetMaxTreeSize(MAXTREESIZE);
             }
           }
       }
//       TTree* outputTreeHiForestInfo = treeHiForestInfo->CloneTree(0);
//       outputTreeHiForestInfo->SetName("HiForestInfo");
//       outputTreeHiForestInfo->SetTitle("first entry of HiForest/HiForestInfo");
//
//       outputTreeHiForestInfo->SetMaxTreeSize(MAXTREESIZE);
//
//       // write HiForestInfo
//       treeHiForestInfo->GetEntry(0);
//       outputTreeHiForestInfo->Fill();

       EventMatcher* em = new EventMatcher();
       Long64_t duplicateEntries = 0;

       Long64_t entries = treeEvent->GetEntries();
       Long64_t entriesAnalyzed = 0;
       std::cout << "entries         = " << entries << std::endl;
       std::cout<< "Loop : ggHiNtuplizer/EventTree" <<std::endl;
       for (Long64_t j_entry=0; j_entry<entries; ++j_entry)
       {
           if (j_entry % 20000 == 0)  {
             std::cout << "current entry = " <<j_entry<<" out of "<<entries<<" : "<<std::setprecision(2)<<(double)j_entry/entries*100<<" %"<<std::endl;
           }

           treeHLT->GetEntry(j_entry);
           treeEvent->GetEntry(j_entry);
           for (int i = 0; i<nJetCollections; ++i) {
               treeJets[i]->GetEntry(j_entry);
           }
           treeHiEvt->GetEntry(j_entry);
           treeSkim->GetEntry(j_entry);

           bool eventAdded = em->addEvent(run,lumis,event,j_entry);
           if(!eventAdded) // this event is duplicate, skip this one.
           {
               duplicateEntries++;
               continue;
           }

           // event selection
           if(!(TMath::Abs(vz) < cut_vz)) continue;
           if(pcollisionEventSelection < cut_pcollisionEventSelection) continue;
           entriesAnalyzed++;

           int centBin = hiBin / centBinWidth;
           int vzBin   = (vz+15) / vertexBinWidth;
           int evplaneBin = (hiEvtPlanes[8]+(TMath::Pi()/2.)) / eventPlaneBinWidth;
          //  std::cout<<evplaneBin<< " bin " << eventPlaneBinWidth << " value " << hiEvtPlanes[8]+(TMath::Pi()/2.) << std::endl;
           if (nEntriesFilled[centBin][vzBin][evplaneBin] > nMaxEvents_minBiasMixing) continue;

           outputTreesHLT[centBin][vzBin][evplaneBin]->Fill();
           outputTreesEvent[centBin][vzBin][evplaneBin]->Fill();
           for (int i = 0; i<nJetCollections; ++i) {
               outputTreesJet[centBin][vzBin][evplaneBin][i]->Fill();
           }
           outputTreesHiEvt[centBin][vzBin][evplaneBin]->Fill();
           outputTreesSkim[centBin][vzBin][evplaneBin]->Fill();

           nEntriesFilled[centBin][vzBin][evplaneBin]++;
       }
       std::cout<<  "Loop ENDED : ggHiNtuplizer/EventTree" <<std::endl;
       std::cout << "entries            = " << entries << std::endl;
       std::cout << "duplicateEntries   = " << duplicateEntries << std::endl;
       std::cout << "entriesAnalyzed    = " << entriesAnalyzed << std::endl;

       for(int i=0; i<nCentralityBins; ++i){
           for(int j=0; j<nVertexBins; ++j){
             for(int l=0; l<nEventPlaneBins; ++l){
                 std::cout<<Form("outputTreesJet[%d][%d][%d]->GetEntries() = %lld", i, j, l, outputTreesEvent[i][j][l]->GetEntries())<<std::endl;
                 if (outputTreesEvent[i][j][l]->GetEntries() < 100) {
                     std::cout<< "Be careful : less than 100 events were put into centBin = "<<i<<" , vertexBin = "<<j<<" , EventPlaneBin = "<<l<<std::endl;
                 }
             }
          }
       }

       configTree->Write("",TObject::kOverwrite);

       output->Write("",TObject::kOverwrite);
       output->Close();

       std::cout<<"minBiasJetSkim() - END"<<std::endl;
}