void readmcsample(TH1D &nom, TH1D &rw, TH1D &nomratio, bool doGen){
 cout<<"reading data for "<<File_Signal_reco<<endl;
  TChain* t;
  if (!doGen) t= new TChain(reco_name.c_str(),reco_name.c_str());
  else t= new TChain(gen_name.c_str(),gen_name.c_str());
  int nfiles;
  if (!doGen) nfiles=t->Add(File_Signal_reco.c_str());
  else nfiles=t->Add(File_Signal_gen.c_str());

  TBranch *b_reco=t->GetBranch("reco");
  TBranch *b_truth=t->GetBranch("truth");
  TLeaf *l_mass=b_reco->GetLeaf("z_y");
  if (doMass) l_mass=b_reco->GetLeaf("z_m");
  if (doGen) {
    l_mass=b_truth->GetLeaf("z_y");
    if (doMass) l_mass=b_truth->GetLeaf("z_m");
  }
  TLeaf *l_phistar=b_reco->GetLeaf("z_phistar_dressed");
  TLeaf *l_phistar_true=b_truth->GetLeaf("z_phistar_dressed");
  int nweights;
  t->SetBranchAddress("weight_size",&nweights);
  t->GetEntry(0);
  cout<<"The sample has nweights: "<<nweights<<endl;
  double weights[nweights];
  int weightid[nweights];
  t->SetBranchAddress("weights",&weights);
  t->SetBranchAddress("weight_ids",&weightid);
  
  // TFile f_zy("ratio_y.root");
  // ratio = (TH1F*)f_zy.Get("ratio");
  // f_zy.Close();
  TFile f_zm("ratio_zmass.root");
  TH1F *ratio = (TH1F*)f_zm.Get("ratio_histo");
  cout<<"Entries: "<<t->GetEntries()<<endl;
  for (int i=0; i<t->GetEntries();i++){
    t->GetEntry(i);
    double phistar=l_phistar->GetValue();
    double mass=l_mass->GetValue();
    double phistar_true=l_phistar_true->GetValue();
    double weight =1;
    for (int w=0; w<nweights;w++){
      if (weightid[w]==1 || weightid[w]==2 || weightid[w]==12 || weightid[w]==13 || weightid[w]==20 || weightid[w]==30) {weight=weight*weights[w];}
    }
    int idx=ratio->GetXaxis()->FindBin(mass);
    if (ratio->GetBinContent(idx)!=0){
     if (!doGen){
	nom.Fill(phistar,weight);
	nomratio.Fill(phistar,weight);
	weight=weight*ratio->GetBinContent(idx);
	rw.Fill(phistar,weight);
     }
      else{
	nom.Fill(phistar_true,weight);
	nomratio.Fill(phistar_true,weight);
	weight=weight*ratio->GetBinContent(idx);
	rw.Fill(phistar_true,weight);
      }
    }
  }
}
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();
}
示例#3
0
void mca()
{
    TChain* pstr = new TChain("PSTree","root");
    pstr->AddFile("Run4selected.root");

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

    const Int_t Ncha = 7;
    TH1F *MCA[Ncha];
    MCA[0] = new TH1F("MCA0","MCA Spectrum for the core",3000,1000,7000);
    MCA[1] = new TH1F("MCA1","MCA Spectrum for segment 1",700,3800,5200);
    for (Int_t i=2; i<=3; i++)
        MCA[i] = new TH1F(Form("MCA%d",i),Form("MCA Spectrum for segment %d",i),500,2200,3200);
    for (Int_t i=4; i<=5; i++)
        MCA[i] = new TH1F(Form("MCA%d",i),Form("MCA Spectrum for segment %d",i+12),700,3000,4400);
    MCA[6] = new TH1F("MCA6","MCA Spectrum for segment 18",10000,1000,21000);

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

        for (Int_t j=0; j<Ncha; j++)
            MCA[j]->Fill((Float_t) Cha_MCAEnergy[j]);
    }

    TFile* foutput = new TFile("Run4mca.root","recreate");
    for (Int_t i=0; i<Ncha; i++) MCA[i]->Write();
    foutput->Close();
}
示例#4
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();

}
示例#5
0
int Fitter::LoadData()
{
	TChain* pChain = new TChain;
	Long64_t nEntries = 0;
	BranchProxy<double> bp;

	pFitVar = new RooRealVar(branchName.c_str(), plotAxisLabel.c_str(), range.minimum, range.maximum, branchUnit.c_str());
	pData = new RooDataSet("data", "data", *pFitVar);
	
	cout << "Loading data" << endl;
	
	if(InitChain(pChain)) return 1;	
	pChain->SetBranchStatus("*", 0);
	bp.Connect(pChain, branchName.c_str());
	nEntries = pChain->GetEntries();
	
	for(Long64_t i=0; i<nEntries; ++i)
	{
		pChain->GetEntry(i);
		if(!range.In(bp)) continue;
		*pFitVar = bp;
		pData->add(*pFitVar);
	}
	
	delete pChain;
	
	return 0;
}
示例#6
0
TH1D* GetDataPhiStar() {
    cout << "reading data" << endl;
    vector<std::string> File_Data = Get_File_Data();
    TH1D* h_phistar = new TH1D("phistar", "phistar", nphistar, phistarBins);
    //TH1D *h_phistar= new TH1D("phistar","phistar",160,50,130);
    h_phistar->Sumw2();
    TChain* t = new TChain(reco_name.c_str(), reco_name.c_str());
    int nfiles;
    for (int i = 0; i < File_Data.size(); i++) {
        nfiles = t->Add(File_Data[i].c_str());
    }
    TBranch* b_reco = t->GetBranch("reco");
    TLeaf* l_m = b_reco->GetLeaf("z_m");
    TLeaf* l_phistar = b_reco->GetLeaf("z_phistar_dressed");
    TLeaf* l_e0_q = b_reco->GetLeaf("e_charge0");
    TLeaf* l_e1_q = b_reco->GetLeaf("e_charge1");
    cout << "Entries: " << t->GetEntries() << endl;
    for (int i = 0; i < t->GetEntries(); i++) {
        t->GetEntry(i);
        double E0_q = l_e0_q->GetValue();
        double E1_q = l_e1_q->GetValue();
        //if (E0_q!=E1_q) continue;
        h_phistar->Fill(l_phistar->GetValue(), 1);
        //h_phistar->Fill(l_m->GetValue(),1);
    }
    cout << "filled data phistar histogram" << endl;
    return h_phistar;
}
示例#7
0
void AssembleSingleFile(std::string FileList, std::string BaseDirectory, std::string OutputName)
{
  
  TFile *f = TFile::Open(OutputName.c_str(),"RECREATE");
  TChain * ch = CreateChainFromList_opt(FileList.c_str(),BaseDirectory.c_str(),"pmtresponse/PhotonLibraryData",false);
  
  Int_t Voxel, OpChannel;
  Float_t Visibility;
  ch->SetBranchAddress("Voxel",      &Voxel);
  ch->SetBranchAddress("OpChannel",  &OpChannel);
  ch->SetBranchAddress("Visibility", &Visibility);

  TTree * tt = new TTree("PhotonLibraryData","PhotonLibraryData");
  tt->Branch("Voxel",      &Voxel,      "Voxel/I");
  tt->Branch("OpChannel",  &OpChannel,  "OpChannel/I");
  tt->Branch("Visibility", &Visibility, "Visibility/F");
  
  for(int i=0; i!=ch->GetEntries(); ++i)
    {
      ch->GetEntry(i);
      tt->Fill();
    }
  
  f->Write();
  f->Close();
}
示例#8
0
TH1D* GetBGPhiStar(std::string FileName, double sampleweight) {
    TH1D* phistartemp = new TH1D("phistar", "phistar", nphistar, phistarBins);
    //TH1D *phistartemp= new TH1D("phistar","phistar",160,50,130);
    phistartemp->Sumw2();

    gErrorIgnoreLevel = kError;
    cout << "reading data for " << FileName << endl;
    TChain* t = new TChain(reco_name.c_str(), reco_name.c_str());
    int nfiles;
    nfiles = t->Add(FileName.c_str());

    TBranch* b_reco = t->GetBranch("reco");
    TLeaf* l_phistar = b_reco->GetLeaf("z_phistar_dressed");
    TLeaf* l_m = b_reco->GetLeaf("z_m");
    TLeaf* l_e0_q = b_reco->GetLeaf("e_charge0");
    TLeaf* l_e1_q = b_reco->GetLeaf("e_charge1");
    int nweights;
    t->SetBranchAddress("weight_size", &nweights);
    t->GetEntry(0);
    cout << "The sample has nweights: " << nweights << endl;
    double weights[nweights];
    int weightid[nweights];
    t->SetBranchAddress("weights", &weights);
    t->SetBranchAddress("weight_ids", &weightid);

    cout << "reading data for " << FileName << endl;
    cout << "Entries: " << t->GetEntries() << endl;
    for (int i = 0; i < t->GetEntries(); i++) {
        t->GetEntry(i);
        double E0_q = l_e0_q->GetValue();
        double E1_q = l_e1_q->GetValue();
        //cout<<E0_q<<" "<<E1_q<<endl;
        //if (E0_q!=E1_q) continue;
        double phistar = l_phistar->GetValue();
        double weight = sampleweight;
        for (int w = 0; w < nweights; w++) {
            if (weightid[w] == 1 || weightid[w] == 2 || weightid[w] == 12
                    || weightid[w] == 13 || weightid[w] == 20 || weightid[w] == 30) {
                weight = weight * weights[w];
            }
        }
        phistartemp->Fill(phistar, weight);
        //phistartemp->Fill(l_m->GetValue(),weight);
    }
    cout << "done reading data for " << FileName << endl;
    return phistartemp;
}
示例#9
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();
}
示例#10
0
void drawPtSpectrum() {

  TStyle *simpleStyle = new TStyle("simpleStyle","");
  simpleStyle->SetCanvasColor(0);
  simpleStyle->SetFrameFillColor(0);
  simpleStyle->SetStatColor(0);
  simpleStyle->SetOptStat(0);
  simpleStyle->SetTitleFillColor(0);
  simpleStyle->SetCanvasBorderMode(0);
  simpleStyle->SetPadBorderMode(0);
  simpleStyle->SetFrameBorderMode(0);
  simpleStyle->cd();

  TChain* chain = new TChain("jetTree");

  chain->Add("2ndLevelOutputFile_PhotonJet15.root");
  chain->Add("2ndLevelOutputFile_PhotonJet30.root");
  chain->Add("2ndLevelOutputFile_PhotonJet80.root");
  chain->Add("2ndLevelOutputFile_PhotonJet170.root");
  chain->Add("2ndLevelOutputFile_PhotonJet300.root");
  chain->Add("2ndLevelOutputFile_PhotonJet470.root");
  chain->Add("2ndLevelOutputFile_PhotonJet800.root");

  Float_t eventWeight;
  chain->SetBranchAddress("eventWeight", &eventWeight);

  Float_t ptHat;
  chain->SetBranchAddress("ptHat", &ptHat);

  TH1F* h1_ptSpectrum = new TH1F("ptSpectrum", "", 100, 0., 1000.);
  h1_ptSpectrum->SetXTitle("#hat{p}_{T} [GeV/c]");
  h1_ptSpectrum->SetMarkerStyle(20);
  h1_ptSpectrum->SetMarkerSize(1.4);



  Int_t nEntries = chain->GetEntries();


  for( Int_t iEntry = 0; iEntry<nEntries; ++iEntry) {
 
    if( (iEntry%100000) == 0 ) std::cout << "Entry: " << iEntry << "/" << nEntries << std::endl;
    chain->GetEntry(iEntry);

    h1_ptSpectrum->Fill(ptHat, eventWeight);

  }

  TCanvas* c1 = new TCanvas("c1", "c1", 800, 600);
  c1->cd();
  c1->SetLogy();
  h1_ptSpectrum->Draw("P");
  c1->SaveAs("ptSpectrum.eps");

}
示例#11
0
long selectevents(const TString &fileName) {
    TChain* chain = new TChain("MVATree");
    if( fileName.EndsWith(".root") ) {
        chain->Add(fileName);
    }

    int N_Jets;
    chain->SetBranchAddress("N_Jets",&N_Jets);
    float* Jet_Pt = new float[120];
    chain->SetBranchAddress("Jet_Pt",Jet_Pt);
    float* Jet_Phi = new float[120];
    chain->SetBranchAddress("Jet_Phi",Jet_Phi);
    float DeltaPhi;
    chain->SetBranchAddress("DeltaPhi",&DeltaPhi);
    float PtAve;
    chain->SetBranchAddress("PtAve",&PtAve);
    float* Jet_Eta = new float[120];
    chain->SetBranchAddress("Jet_Eta",Jet_Eta);
    float* Jet_CSV = new float[120];
    chain->SetBranchAddress("Jet_CSV",Jet_CSV);
    float* Jet_HadFlav = new float[120];
    chain->SetBranchAddress("Jet_HadronFlav",Jet_HadFlav);
    float* Jet_PartFlav = new float[120];
    chain->SetBranchAddress("Jet_PartonFlav",Jet_PartFlav);
    float Weight_XS;
    chain->SetBranchAddress("Weight_XS",&Weight_XS);

    long nentries=0;
    long n_selected=0;
    float dphicut=2.7;
    float pt3cut=0.1;
    float etamin=2.1;

    nentries = chain->GetEntries();
    cout <<"counting events in "<< fileName << endl;
    cout << "total number of MC events: " << nentries << endl;
    for (long iEntry=0; iEntry<nentries; iEntry++) {
        if(iEntry%100000==0) cout << "analyzing event " << iEntry << endl;
//     if(iEntry>1000000) break;
        chain->GetEntry(iEntry);
        double ptave=PtAve;
        if(N_Jets >=2) {
            if (DeltaPhi> dphicut ) {
                if (abs(Jet_Eta[0])<etamin && abs(Jet_Eta[1])<etamin) {
                    if (N_Jets >=3) {
                        if (Jet_Pt[2]/ptave < pt3cut) n_selected++;
                    }
                    else if (N_Jets==2) n_selected++;
                }
            }
        }
    }
    cout << n_selected<< " Events selected" << endl;
    return n_selected;
}
示例#12
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;
}
示例#13
0
void Master_test( ){//main programme
    TChain* t = new TChain("rd51tbgeo");
    t->Add("../CRC-Run0308_Muon_10k_MSPL4_HVScan_710pt7_710pt1_710pt0_T20_T20_T20_Lat21-141010_224141-0.root");
    
    ClassReadTree CRC(t);

    TCanvas * c1 = new TCanvas("c1","",1);
    TGraphErrors *gr1 = new TGraphErrors(t->GetEntries());
    TGraphErrors *gr2 = new TGraphErrors(t->GetEntries());
    TGraphErrors *gr3 = new TGraphErrors(t->GetEntries());

    //for( int iEv = 0 ; iEv < t->GetEntries() ; iEv++){//
    for( int iEv = 0 ; iEv < 8 ; iEv++){//	Event Loop Starts
	t->GetEntry(iEv);

	//cout<<"===>  "<<CRC.g1xcl_geoposX[0]<<endl;
	//cout<<"===>  "<<CRC.g2xcl_geoposX[0]<<endl;
	//cout<<"===>  "<<CRC.g3xcl_geoposX[0]<<endl;
	if (CRC.g1xcl_geoposX[0]>0)
	    gr1->SetPoint(iEv*3, 100, CRC.g1xcl_geoposX[0]);
//	else
//	    gr1->SetPoint(iEv*3, 100, -10);
	if (CRC.g2xcl_geoposX[0]>0)
	    gr1->SetPoint(iEv*3+1, 380, CRC.g2xcl_geoposX[0]);
//	else
//	    gr1->SetPoint(iEv*3+1, 380, -10);
	if (CRC.g3xcl_geoposX[0]>0)
	    gr1->SetPoint(iEv*3+2, 830, CRC.g3xcl_geoposX[0]);
//	else
//	    gr1->SetPoint(iEv*3+2, 830, -10);

	
    }// End Event Loop
    gr1->SetMarkerColor(kBlue);
    gr1->SetMarkerStyle(21);
    gr2->SetMarkerColor(kRed);
    gr2->SetMarkerStyle(21);
    gr3->SetMarkerColor(kGreen);
    gr3->SetMarkerStyle(21);
    gr1->GetXaxis()->SetRangeUser(50., 900.);
    gr2->GetXaxis()->SetRangeUser(50., 900.);
    gr3->GetXaxis()->SetRangeUser(50., 900.);
    gr1->Draw("AP");
    //gr3->Draw("AP");
    //gr2->Draw("samesP*");
    //gr3->Draw("samesP*");
    TMultiGraph *mg = new TMultiGraph();
    mg->Add(gr1);
    mg->Add(gr2);
    mg->Add(gr3);
    //mg->Draw("APL");
    c1->SaveAs("Hit_Distribution.pdf");
}
示例#14
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();
}
示例#15
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();

}
示例#16
0
// main
int main(int argc, char *argv[]){
  
  TString fileNameTree = argv[1];
  TString minMass = argv[2];
  TString maxMass = argv[3];

  Int_t maxEntries = atoi(argv[4]);


  //std::cout << "maxEntries = " << maxEntries << std::endl;

  TChain *chain = new TChain("T");
  chain->Add(fileNameTree);
  chain->GetEntry(0); 
  
  int nentries = int(chain->GetEntries());
  cout << "+++++ No. of entries in the input tree: " << nentries << endl;

  // string for the cut on the selected invariant mass windowm    
  TString mass_cut=minMass+"*"+minMass+"<2*(event.mu1.fP4.fCoordinates.fT*event.mu2.fP4.fCoordinates.fT-event.mu1.fP4.fCoordinates.fX*event.mu2.fP4.fCoordinates.fX-event.mu1.fP4.fCoordinates.fY*event.mu2.fP4.fCoordinates.fY-event.mu1.fP4.fCoordinates.fZ*event.mu2.fP4.fCoordinates.fZ) && 2*(event.mu1.fP4.fCoordinates.fT*event.mu2.fP4.fCoordinates.fT-event.mu1.fP4.fCoordinates.fX*event.mu2.fP4.fCoordinates.fX-event.mu1.fP4.fCoordinates.fY*event.mu2.fP4.fCoordinates.fY-event.mu1.fP4.fCoordinates.fZ*event.mu2.fP4.fCoordinates.fZ)<"+maxMass+"*"+maxMass;
  //std::cout<<"String for cut: "+mass_cut<<std::endl;
  
  TString outFileName =  ((TObjString*)((((TObjString*)(fileNameTree.Tokenize("/"))->Last())->String().Tokenize("."))->At(0)))->String();


  TFile* fileTreeOut = TFile::Open(outFileName+"_Mass_"+minMass+"_"+maxMass+".root","RECREATE");
  fileTreeOut->cd();
  
  TTree *newtree = chain->CopyTree(mass_cut,"",maxEntries); // use a sub-sample this when debugging
  //TTree *newtree = chain->CopyTree(mass_cut);
  newtree->AutoSave();

  nentries = int(newtree->GetEntries());
  cout << "+++++ No. of entries in the output tree: " << nentries << endl;

  fileTreeOut->Write();
  fileTreeOut->Close();

  delete chain;

  
  return 0;
}
示例#17
0
//-------------------------------------------------------------------
void TestReadStuple()
{
	  TChain *myTree = new TChain("Stuple");

 //DATA
 //myTree->Add("/mnt/autofs/misc/nbay03.a/samantha/RESULTS/STUPLES/StupleV2_noMinVtx_noMinJet_TLphoEleRemoved.root");
 myTree->Add("/mnt/autofs/misc/nbay03.a/samantha/RESULTS/STUPLES/Stuple_noMinVtx_noMinJet_TLphoEleRemoved.root");

	Stuple *myStuple = new Stuple; 

	myTree->SetBranchStatus("pho_num", 1);		// number of electrons so we know how much to read from arrays
	myTree->SetBranchStatus("ele_num", 1);
	myTree->SetBranchStatus("jet_num", 1);

	myTree->SetBranchStatus("ele_Index", 1);
	myTree->SetBranchStatus("ele_Etc", 1);
	myTree->SetBranchStatus("ele_Ntight", 1);
	myTree->SetBranchStatus("ele_Nloose", 1);
	myTree->SetBranchStatus("ele_matchJetIndex", 1);	//if a matching jet is found and removed from jet list


	myTree->SetBranchAddress("pho_num", &myStuple->pho_num);		// number of electrons so we know how much to read from arrays
	myTree->SetBranchAddress("ele_num", &myStuple->ele_num);
	myTree->SetBranchAddress("jet_num", &myStuple->jet_num);

	myTree->SetBranchAddress("ele_Ntight", &myStuple->ele_Ntight);
	myTree->SetBranchAddress("ele_Nloose", &myStuple->ele_Nloose);
	myTree->SetBranchAddress("ele_Index", &myStuple->ele_Index);
	myTree->SetBranchAddress("ele_Etc", &myStuple->ele_Etc);
	myTree->SetBranchAddress("ele_matchJetIndex", &myStuple->ele_matchJetIndex);	//if a matching jet is found and removed from jet list


	//for (unsigned i =0 ; i < myTree->GetEntries(); ++i) {
	for (unsigned i =0 ; i < 100; ++i) {
		myTree->GetEntry(i);
		std::cout << myStuple->ele_num << std::endl;
		for (unsigned j = 0 ; j < myStuple->ele_num; ++j) {
			std::cout << myStuple->ele_matchJetIndex[j] << std::endl;

		}
	}
}
示例#18
0
void countMuonsPerRunD3PD(){

  //gInterpreter->GenerateDictionary("map<int, double >","map.h;map");
  int cutValue = 11;
  float ptmin = 10.0;
  //float ptmin = 4.;
  //TString fileNameMuonIn = "/afs/cern.ch/user/t/tbalestr/public/16.6.2.5/WorkArea/run/HISingleMuon.root";

///7.3 ub^-1 2010 data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_Aug4_v2.root";
  ///2011 PbPb data
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_merged_26May.root";
  //TString fileNameMuonIn = "/tmp/tbalestr/HISingleMuon_DPD_HP_30May.root";

  TString baseString = "/mnt/Lustre/cgrp/atlas_hi/tbalestri/";
  TString fileNameMuonIn = baseString+"HardProbesFiles/HISingleMuonHardProbesData.04.17.2013.root";  
  TFile* fMuIn = new TFile(fileNameMuonIn, "READ");
  if ( !fMuIn->IsOpen() ) {
    std::cout << fMuIn << " not found!" << std::endl;
  }

  TFile* outFile = new TFile("muonsPerRun.root","recreate");
  
  ///lumi in ub^-1
  std::vector<double> vLumi;
  vLumi.push_back(0.0137422);
  vLumi.push_back(0.126333);
  vLumi.push_back(1.28605451);
  vLumi.push_back(0.08307752);
  vLumi.push_back(3.948807);
  vLumi.push_back(2.766361);
  vLumi.push_back(3.606919);
  vLumi.push_back(3.809249);
  vLumi.push_back(4.11709);
  vLumi.push_back(4.88581);
  vLumi.push_back(2.50513);
  vLumi.push_back(0.0619227);
  vLumi.push_back(0.9694949);
  vLumi.push_back(0.582203);
  vLumi.push_back(5.42834);
  vLumi.push_back(4.20247);
  vLumi.push_back(0.38549);
  vLumi.push_back(5.50425);
  vLumi.push_back(3.15969);
  vLumi.push_back(4.19951);
  vLumi.push_back(5.24396);
  vLumi.push_back(5.30817);
  vLumi.push_back(0.0433861);
  vLumi.push_back(5.29888);
  vLumi.push_back(5.30346);
  vLumi.push_back(0.757212);
  vLumi.push_back(5.985104);
  vLumi.push_back(5.1515);
  vLumi.push_back(6.57761);
  vLumi.push_back(1.75062);
  vLumi.push_back(5.43771);
  vLumi.push_back(3.13928);
  vLumi.push_back(5.14981);
  vLumi.push_back(4.90751);
  vLumi.push_back(2.521785);
  vLumi.push_back(6.45269);
  vLumi.push_back(3.59951);
  vLumi.push_back(5.33795);
  vLumi.push_back(6.16766);
  vLumi.push_back(1.77379);
  vLumi.push_back(0.923454);
  vLumi.push_back(2.07656);

  std::vector<int> vRun;
  vRun.push_back(193211);
  vRun.push_back(193270);
  vRun.push_back(193291);
  vRun.push_back(193295);
  vRun.push_back(193321);
  vRun.push_back(193403);
  vRun.push_back(193412);
  vRun.push_back(193447);
  vRun.push_back(193463);
  vRun.push_back(193481);
  vRun.push_back(193491);
  vRun.push_back(193492);
  vRun.push_back(193493);
  vRun.push_back(193494);
  vRun.push_back(193546);
  vRun.push_back(193558);
  vRun.push_back(193599);
  vRun.push_back(193604);
  vRun.push_back(193641);
  vRun.push_back(193655);
  vRun.push_back(193662);
  vRun.push_back(193679);
  vRun.push_back(193687);
  vRun.push_back(193718);
  vRun.push_back(193795);
  vRun.push_back(193823);
  vRun.push_back(193825);
  vRun.push_back(193826);
  vRun.push_back(193834);
  vRun.push_back(193890);
  vRun.push_back(194017);
  vRun.push_back(194060);
  vRun.push_back(194061);
  vRun.push_back(194121);
  vRun.push_back(194160);
  vRun.push_back(194163);
  vRun.push_back(194179);
  vRun.push_back(194192);
  vRun.push_back(194193);
  vRun.push_back(194370);
  vRun.push_back(194374);
  vRun.push_back(194382);
  const int nRuns = vRun.size(); 

  TGraphErrors* grLumi = new TGraphErrors(nRuns);
  TGraphErrors* grMuPerLumi = new TGraphErrors(nRuns);

  int valNt[30], EF_mu4_MSonly_L1TE50_Matched20[30],EF_mu4_L1VTE50_Matched20[30],runNt, mu_muid_nNt;
  int EF_mu10_MSonly_EFFS_L1ZDC_Matched20[30], EF_mu10_MSonly_EFFS_L1TE10_Matched20[30],EF_mu10_MSonly_EFFS_L1TE20_Matched20[30];
  int EF_mu10_MSonly_EFFS_L1ZDC, EF_mu10_MSonly_EFFS_L1TE10, EF_mu10_MSonly_EFFS_L1TE20, EF_mu4_MSonly_L1TE50, EF_mu4_L1VTE50;
  float ptNt[30], centralityNt,etaNt[30],eLossNt[30],scatNt[30];

  TChain* tree = new TChain("tree","tree");
  std::cout << "Filling the tree for " << fileNameMuonIn << std::endl;
  tree->Add(fileNameMuonIn);
  // --- Set branch adresses ---
  tree->SetBranchAddress("val", &valNt);
  tree->SetBranchAddress("pt", &ptNt);
  tree->SetBranchAddress("eta", &etaNt);
  tree->SetBranchAddress("eLoss",&eLossNt);
  tree->SetBranchAddress("scat",&scatNt);
  tree->SetBranchAddress("mu_muid_n", &mu_muid_nNt);
  tree->SetBranchAddress("run", &runNt);
  tree->SetBranchAddress("centrality", &centralityNt); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50", &EF_mu4_MSonly_L1TE50); 
  tree->SetBranchAddress("EF_mu4_L1VTE50", &EF_mu4_L1VTE50); 
  tree->SetBranchAddress("EF_mu4_MSonly_L1TE50_Matched20", &EF_mu4_MSonly_L1TE50_Matched20); 
  tree->SetBranchAddress("EF_mu4_L1VTE50_Matched20", &EF_mu4_L1VTE50_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC", &EF_mu10_MSonly_EFFS_L1ZDC); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10", &EF_mu10_MSonly_EFFS_L1TE10); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20", &EF_mu10_MSonly_EFFS_L1TE20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", &EF_mu10_MSonly_EFFS_L1ZDC_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE10_Matched20", &EF_mu10_MSonly_EFFS_L1TE10_Matched20); 
  tree->SetBranchAddress("EF_mu10_MSonly_EFFS_L1TE20_Matched20", &EF_mu10_MSonly_EFFS_L1TE20_Matched20); 

  tree->SetBranchStatus("*",0);
  tree->SetBranchStatus("val", 1);
  tree->SetBranchStatus("pt", 1);
  tree->SetBranchStatus("eta", 1);
  tree->SetBranchStatus("eLoss",1);
  tree->SetBranchStatus("scat",1);
  tree->SetBranchStatus("mu_muid_n", 1);
  tree->SetBranchStatus("run", 1);
  tree->SetBranchStatus("centrality", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50", 1); 
  tree->SetBranchStatus("EF_mu4_MSonly_L1TE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu4_L1VTE50_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1ZDC_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE10_Matched20", 1); 
  tree->SetBranchStatus("EF_mu10_MSonly_EFFS_L1TE20_Matched20", 1); 

 std::cout << "Number of entries: " << tree->GetEntries() << std::endl; 
 
 ///map runnumber to #mu
 ///need to used multimap since >1 muon 
 ///value for each run number key
 std::multimap < int, int> runMap;

  ///loop over all events
  for ( int i = 0; i < tree->GetEntries(); ++i ) {
 //   if(i>10000) break;
    tree->LoadTree(i);
    tree->GetEntry(i);

    if(i%10000==0) std::cout << "Event " << i << std::endl;

        for(int imu = 0; imu<mu_muid_nNt; imu++){
            if (
                (valNt[imu]>cutValue) 
                && abs(etaNt[imu])>0.1 
                && abs(etaNt[imu])<2.4 
                && ptNt[imu]>ptmin 
                && centralityNt>=0. 
                && centralityNt<=0.8
                && ( (EF_mu10_MSonly_EFFS_L1ZDC&&EF_mu10_MSonly_EFFS_L1ZDC_Matched20[imu]) ||
                    (EF_mu10_MSonly_EFFS_L1TE10&&EF_mu10_MSonly_EFFS_L1TE10_Matched20[imu])
                    ||(EF_mu10_MSonly_EFFS_L1TE20&&EF_mu10_MSonly_EFFS_L1TE20_Matched20[imu]) )	
		        ){
                ///count number of muons in this run that pass
                runMap.insert(make_pair (runNt,1) );
               }
         } //imu
   } //i
                
   std::cout << std::endl;
   std::cout << "-------------------------  " << std::endl;
   std::cout << " S U M M A R Y " << std::endl;
   std::cout << "-------------------------  " << std::endl;

   TString spreadSheetName = "muonCountingSpreadSheet.csv";
   std::ofstream spreadSheet;
   spreadSheet.open(spreadSheetName);

   double totLumi = 0.0, totalMu = 0;
   for(int iRun = 0; iRun<nRuns; ++iRun){

        int muonsPassed = runMap.count( vRun[iRun] );
        ///Muons per nb^-1
        double muPerLumi = (double)muonsPassed/vLumi[iRun]/1000.0;
        ///Number of muons passed in run iRun
        std::cout << "Index: " << iRun+1 << "\tRun: " << vRun[iRun] << 
            "\tLumi: " << vLumi[iRun]/1000.0 << "\tMuons: " << muonsPassed << "\tMuons/nb^-1: " 
            << muPerLumi << std::endl;

        totLumi += vLumi[iRun]/1000.0;
        totalMu += muonsPassed;

        grMuPerLumi->SetPoint(iRun,vRun[iRun],muPerLumi);
        grMuPerLumi->SetPointError(iRun,0.5, TMath::Sqrt(muonsPassed)/vLumi[iRun]/1000.0);

        grLumi->SetPoint(iRun,totLumi,totalMu);
        grLumi->SetPointError(iRun, 0.0, 0.0);

        writeToSpreadsheet(spreadSheet,iRun+1,vRun[iRun],vLumi[iRun]/1000.,muonsPassed);
   }

   grMuPerLumi->Draw("ape");
   grLumi->Draw("ape");

   outFile->cd();
   grLumi->Write("muonLumiDependence");
   grMuPerLumi->Write("muonPerLumi");

   std::cout << " Total Luminosity: " << totLumi << " nb^-1 " << std::endl;
   std::cout << " Total Muons passed: " << totalMu << std::endl;

   spreadSheet.close();
                
/*
            
  cout << "Number of runs: " << runMap.size() << endl;
  cout << "Run \t" << "Luminosity(ub^-1) \t" << " #muons \t" << "muons/lumi" << endl;
  ///map run lumi to #mu
  //std::map < int, double> lumiMap;
  for (unsigned int j = 0; j<runMap.size(); ++j){
    int runTemp = vRun.at(j);
    double lumiTemp = vLumi.at(j);
    map <int,int>::const_iterator iPairFound = runMap.find(runTemp);
    cout << iPairFound->first << " \t " << lumiTemp << " \t " << " \t " << iPairFound->second << " \t " << " \t " << (double)iPairFound->second/lumiTemp << endl; 
    sum += runMap[runTemp];
  }

  cout << "Total Luminosity = " << totLumi << endl;
  cout << "Total = " << sum << endl;
  */
}
示例#19
0
//---------------------------------------------------------------------------//
//Main Method
//---------------------------------------------------------------------------//
int main(int argc, char** argv)
{	
	TApplication *App = new TApplication("Application",(Int_t*)&argc, argv);
	TCanvas *Canvas = new TCanvas("canvas", "Canvas", 640, 640);

	// Set up ROOT as we require.
	SetupROOT();

	// Get list of files to run over. 
	TString fileName("/storage/epp2/phseaj/exercise/basket_2010b.list");
	std::ifstream inputFile(fileName.Data(), ios::in);

	// Declare a TChain for the TGlobalPID module
	TChain *gRecon = new TChain("ReconDir/Global");
	TChain *gGenVtx = new TChain("TruthDir/Vertices");
	// Check if the file exists.
	if (!inputFile.is_open()){
	std::cout << "ERROR: File prod4 files not found!" << std::endl;
		std::cout << " - This file should contain a list of all data files to be processed." << std::endl;
		return 0;
	}
	else{
		std::string curFileName;

		// Add the input files to the TChains.
		//only doing 10 of the basket files, revert to while to do whole run
	//	while(getline(inputFile,curFileName)){
		for(int l = 0; l<10; l++){
			if(getline(inputFile,curFileName)){
				gRecon->Add(curFileName.c_str());
				gGenVtx->Add(curFileName.c_str());
			}
		}
	}

	std::cout << "Got input file(s)." << std::endl;

	//Setup access to the Recon tree
	int NPIDs(0);  // This variable counts the number of particles per event
	int NVtxFGD1(0), NVtxFGD2(0);
        // Declare a TClonesArray to hold objects of type TGlobalPID
 	TClonesArray *globalPIDs = new TClonesArray("ND::TGlobalReconModule::TGlobalPID",50);
	TClonesArray *VtxFGD1 = new TClonesArray("ND::TTruthVerticesModule::TTruthVertex",50);    
	TClonesArray *VtxFGD2 = new TClonesArray("ND::TTruthVerticesModule::TTruthVertex",50);    
    // Associate the right branch in the TTree to the right local variable
	gRecon->SetBranchAddress("NPIDs",&NPIDs);
    gRecon->SetBranchAddress("PIDs",&globalPIDs);
	gGenVtx->SetBranchAddress("VtxFGD1", &VtxFGD1);
	gGenVtx->SetBranchAddress("NVtxFGD1", &NVtxFGD1);
	gGenVtx->SetBranchAddress("VtxFGD2", &VtxFGD2);
	gGenVtx->SetBranchAddress("NVtxFGD2", &NVtxFGD2);
	//check that truthdir and recon have the same number of entries
	if(gRecon->GetEntries() != gGenVtx->GetEntries()) 
		cout<<"not equal entries, probably wrong"<<endl;
	// Loop over the entries in the TChain.

	//========================================================
	//			Declare Graphs n stuff here
	//========================================================

	//adding tclones arrays for use with detectors
	Int_t NTPCs;
	TClonesArray *TPC;

	Int_t NFDGs;
	TClonesArray *FDG;

	Int_t NECALs;
	TClonesArray *ECAL;

	Int_t NPODs;
	TClonesArray *POD;

	Int_t NSMRDs;
	TClonesArray *SMRD;

	//adding a 2d graph general purpose, change titles each time!
	TH1D *graph1 = new TH1D("graph1","Momenta of TPC PIDs from FDGs", 100, -50.0 , 50.0);
	
	Int_t ninteract(0), nfgd(0),nfgdqes(0),fgdqesneu(0);
	//========================================================
	//	end		Declare Graphs n stuff here
	//========================================================

	// Loop over the entries in the TChain. (only 1/1000 of whole entries atm)
	for(unsigned int i = 0; i < gRecon->GetEntries()/10; ++i) {
		if((i+1)%10000 == 0) std::cout << "Processing event: " << (i+1) << std::endl;
		//display status every 10,000 th entry

	// Get an entry for the Recon tree
		gRecon->GetEntry(i);
		gGenVtx->GetEntry(i);
		ND::TGlobalReconModule::TGlobalPID *gTrack = NULL;

		//added new loop for truth vertex
		gGenVtx->GetEntry(i);
		
		for (int j=0; j<NPIDs; j++) {
			// Get a specific track from the TClonesArray
			gTrack = (ND::TGlobalReconModule::TGlobalPID*)globalPIDs->At(j);
			//get truevertex (in example, also gets trueparticle, can add in later)
			ND::TTrueVertex vtx = gTrack->TrueParticle.Vertex;
			//get position lorrentz vector
			TLorentzVector vec = vtx.Position;
			ninteract++;
			if(ABS(vec.X())<832.2 && ABS(vec.Y()-55)<832.2 && ((vec.Z()>123.45&&vec.Z()<446.95)||(vec.Z()>1481.45&&vec.Z()<1807.95))){	//is it in one of the FGDs?
				nfgd++;
				if(vtx.ReactionCode.find("Weak[NC],QES;",0)!=-1){
					unsigned long det;
					det = gTrack->Detectors;
					string detstr;
					stringstream stream;
					stream << det;
					detstr = stream.str();
					if(detstr.find("1",0)||detstr.find("2",0)||detstr.find("3",0)){
						graph1->Fill((Double_t)gTrack->FrontMomentum);	
					} 	
					nfgdqes++;
				}	
			}
			TClonesArray *TPCObjects = new TClonesArray("ND::TGlobalReconModule::TTPCObject",gTrack->NTPCs);
			ND::TGlobalReconModule::TObject *tpcTrack = NULL;
			for ( int k = 0 ; k < gTrack->NTPCs; k++) {
				tpcTrack = (ND::TGlobalReconModule::TObject*) TPCObjects->At(k);
				//now we can access  variables through tpcTrack->PullEle for example
			}
		}

	} // End loop over events

//plotting bits at the end :D
	graph1->Draw();
	App->Run();
	return 0;
}
示例#20
0
void Draw_BDiJetImbalance()
{
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

  //==========================================================================//
  // SET RUNNING CONDITIONS
  //==========================================================================//
  bool print_plots = true;

  bool is_pp = false;

  // const char* inFile = "HFtag_bjet.root";
  // const char* inFile = "HFtag_bjet_pp.root";
  // const char* inFile = "/phenix/plhf/dcm07e/sPHENIX/bjetsims/test.root";
  // if (!is_pp)
  //   const char* inFile = "HFtag_bjet_AuAu0-10.root";

  const char* inDir = "/phenix/plhf/dcm07e/sPHENIX/bjetsims/ana";

  // // desired nn integrated luminosity [pb^{-1}]
  // double lumiDesired = 175;
  // if ( !is_pp )
  //   lumiDesired = 229; // AuAu 0-10% central (10B events)
  // desired nn integrated luminosity [pb^{-1}]
  double lumiDesired = 200;
  TString scol("p + p #sqrt{s_{_{NN}}} = 200 GeV");
  TString slumi(Form("#int L dt = %.0f pb^{-1} |z| < 10 cm", lumiDesired));
  if ( !is_pp )
  {
    // equivelant nn luminosity:
    // N_{evt}^{NN} / sigma_NN = N_{evt}^{AA}*Ncoll / sigma_NN
    // = 10e9 * 962 / 42e9 pb = 229 pb^-1
    double evntDesired = 24e9; // AuAu 0-10% central
    lumiDesired = evntDesired * 962 / 42e9; // AuAu 0-10% central
    scol = "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV";
    slumi = Form("%.0fB events |z| < 10 cm", evntDesired / 1.e9);
  }

  // luminosity per file generated [pb^{-1}]
  double lumiPerFile = 99405 / (4.641e-06 * 1e12);
  double lumiRead = 0;

  double pT1min = 20;
  double pT2min = 10;
  // double etamax = 1.0;
  double etamax = 0.7;

  // double bJetEff = 0.5; // b-jet tagging efficiency
  double bJetEff = 0.60; // p+p b-jet tagging efficiency
  if ( !is_pp )
    bJetEff = 0.40;

  double bJetPur = 0.40; // b-jet tagging purity

  double RAA = 1.0;
  if (!is_pp)
    RAA = 0.6;

  const int NETACUT = 3;
  double etacut[] = {1.3, 1.0, 0.7};
  double etaColor[] = {kBlue, kRed, kBlack};

  const int PTCUT = 3;
  double ptcut[] = {10, 20, 40};
  double ptColor[] = {kBlue, kRed, kBlack};

  //==========================================================================//
  // DECLARE VARIABLES
  //==========================================================================//

  //-- tree variables
  TChain *ttree;
  Int_t           event;
  Int_t           truthjet_n;
  Int_t           truthjet_parton_flavor[100];
  Int_t           truthjet_hadron_flavor[100];
  Float_t         truthjet_pt[100];
  Float_t         truthjet_eta[100];
  Float_t         truthjet_phi[100];

  //-- histograms

  TH1D* hjet_pT = new TH1D("hjet_pT", ";p_{T}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hjet_eta = new TH1D("hjet_eta", ";#eta^{jet}", 40, -2., 2.);
  TH1D* hjet_phi = new TH1D("hjet_phi", ";#phi^{jet}", 40, -4, 4);

  TH1D* hdijet_pT1 = new TH1D("hdijet_pT1", ";p_{T,1}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hdijet_pT2 = new TH1D("hdijet_pT2", ";p_{T,2}^{jet} [GeV/c]", 20, 0, 100);
  TH1D* hdijet_xj = new TH1D("hdijet_xj", ";x_{j} = p_{T,2} / p_{T,1}; event fraction", 10, 0, 1);
  TH1D* hdijet_dphi = new TH1D("hdijet_dphi", ";|#Delta#phi_{12}|; event fraction", 10, 0, TMath::Pi());

  TH1D* hdijet_sing_pT1 = new TH1D("hdijet_sing_pT1",
                                   ";p_{T,1} [GeV/c];Fraction of Dijet / Single Accepted",
                                   20, 00, 100);
  TH1D* hdijet_sing_eta2 = new TH1D("hdijet_sing_eta2",
                                    ";#eta_{2};Fraction of Dijet / Single Accepted",
                                    15, -1.5, 1.5);
  TH1D* hdijet_eff_pT1[3];
  TH1D* hdijet_eff_eta2[3];
  for (int i = 0; i < NETACUT; i++)
  {
    hdijet_eff_pT1[i] = new TH1D(Form("hdijet_eff_pT1_%i", i),
                                 ";p_{T,1} [GeV/c];Fraction of Dijet / Single Accepted",
                                 20, 00, 100);
    hdijet_eff_pT1[i]->SetLineColor(etaColor[i]);
    hdijet_eff_pT1[i]->SetLineWidth(2);
  } // i
  for (int i = 0; i < PTCUT; i++)
  {
    hdijet_eff_eta2[i] = new TH1D(Form("hdijet_eff_eta2_%i", i),
                                  ";#eta;Fraction of Dijet / Single Accepted",
                                  15, -1.5, 1.5);
    hdijet_eff_eta2[i]->SetLineColor(etaColor[i]);
    hdijet_eff_eta2[i]->SetLineWidth(2);
  } // i

  hjet_pT->Sumw2();
  hjet_eta->Sumw2();
  hjet_phi->Sumw2();

  hdijet_pT1->Sumw2();
  hdijet_pT2->Sumw2();
  hdijet_dphi->Sumw2();
  hdijet_xj->Sumw2();

  // for fixing the uncertainties
  TH1D* hdijet_xj_fix;

  //-- other
  TRandom3 *rand = new TRandom3();

  bool acc[100];

  //==========================================================================//
  // LOAD TTREE
  //==========================================================================//
  // cout << endl;
  // cout << "--> Reading data from " << inFile << endl;

  // TFile *fin = TFile::Open(inFile);
  // if (!fin)
  // {
  //   cout << "ERROR!! Unable to open " << inFile << endl;
  //   return;
  // }

  // ttree = (TTree*) fin->Get("ttree");
  // if (!ttree)
  // {
  //   cout << "ERROR!! Unable to find ttree in " << inFile << endl;
  //   return;
  // }

  cout << endl;
  cout << "--> Reading data from dir: " << inDir << endl;

  // calculate the number of files necessary for the desired luminosity
  int nfiles = (int)(lumiDesired / lumiPerFile);
  cout << "  desired luminosity : " << lumiDesired << endl;
  cout << "  luminosity per file: " << lumiPerFile << endl;
  cout << "  N files needed     : " << nfiles << endl;


  // check the number of files found in the directory
  int nfound = (gSystem->GetFromPipe(Form("ls %s/*.root | wc -l", inDir))).Atoi();
  cout << "  N files found      : " << nfound << endl;

  if (nfound < nfiles)
  {
    cout << "WARNING!! There are not enough files for the desired luminosity." << endl;
    cout << "          Will scale the statistical uncertainties accordingly." << endl;
    // return;
  }

  // chain the desired files
  ttree = new TChain("ttree");
  int nread = 0;

  TString fileList = gSystem->GetFromPipe(Form("ls %s/*.root", inDir));

  int spos = fileList.First("\n");
  while (spos > 0 && nread < nfiles)
  {
    TString tfile = fileList(0, spos);
    // cout << tsub << endl;

    ttree->Add(tfile.Data());


    // chop off the file
    fileList = fileList(spos + 1, fileList.Length());
    spos = fileList.First("\n");
    nread++;
  }

  cout << " successfully read in " << nread << " files" << endl;
  lumiRead = lumiPerFile * nread;


  ttree->SetBranchAddress("event", &event);
  ttree->SetBranchAddress("truthjet_n", &truthjet_n);
  ttree->SetBranchAddress("truthjet_parton_flavor", truthjet_parton_flavor);
  ttree->SetBranchAddress("truthjet_hadron_flavor", truthjet_hadron_flavor);
  ttree->SetBranchAddress("truthjet_pt", truthjet_pt);
  ttree->SetBranchAddress("truthjet_eta", truthjet_eta);
  ttree->SetBranchAddress("truthjet_phi", truthjet_phi);

  Long64_t nentries = ttree->GetEntries();


  //==========================================================================//
  // GET MOMENTUM IMBALANCE
  //==========================================================================//
  cout << endl;
  cout << "--> Running over " << nentries << endl;

  int iprint = 0;
  for (Long64_t ientry = 0; ientry < nentries; ientry++)
  {
    ttree->GetEntry(ientry);

    if (ientry % 100000 == 0) cout << "----> Processing event " << ientry << endl;

    //-- apply acceptance to each jet
    for (int i = 0; i < truthjet_n; i++)
      acc[i] = (rand->Uniform() < bJetEff);
      // acc[i] = (rand->Uniform() < bJetEff) && (rand->Uniform() < RAA);

    //-- get kinematics for all b-jets
    for (int i = 0; i < truthjet_n; i++)
    {
      if (TMath::Abs(truthjet_parton_flavor[i]) != 5)
        continue;

      // single b-jet kinematics
      hjet_pT->Fill(truthjet_pt[i]);
      hjet_eta->Fill(truthjet_eta[i]);
      hjet_phi->Fill(truthjet_phi[i]);

      for (int j = i + 1; j < truthjet_n; j++)
      {
        if (TMath::Abs(truthjet_parton_flavor[j]) != 5)
          continue;


        // find the leading and subleading jets
        int i1, i2;
        double pT1, pT2;
        double phi1, phi2;
        double eta1, eta2;
        bool acc1, acc2;

        if (truthjet_pt[i] > truthjet_pt[j])
        {
          i1 = i;
          i2 = j;
        }
        else
        {
          i1 = j;
          i2 = i;
        }

        pT1 = truthjet_pt[i1];
        phi1 = truthjet_phi[i1];
        eta1 = truthjet_eta[i1];
        acc1 = acc[i1];

        pT2 = truthjet_pt[i2];
        phi2 = truthjet_phi[i2];
        eta2 = truthjet_eta[i2];
        acc2 = acc[i2];



        if (iprint < 20)
        {
          cout << " ientry: " << ientry << endl
               << "        i1:" << i1 << " pT1:" << pT1 << " eta1:" << eta1 << " acc1:" << acc1 << endl
               << "        i2:" << i2 << " pT2:" << pT2 << " eta2:" << eta2 << " acc2:" << acc2 << endl;
          iprint++;
        }



        // check if we accept the leading jet
        // only take RAA hit once
        if ( pT1 < pT1min || TMath::Abs(eta1) > etamax || !acc1  || rand->Uniform() > RAA)
          continue;

        // calculate the delta phi
        double dphi = TMath::Abs(TMath::ATan2(TMath::Sin(phi1 - phi2), TMath::Cos(phi1 - phi2)));
        if (dphi > TMath::Pi())
          cout << " " << truthjet_phi[i] << " " << truthjet_phi[j] << " " << dphi << endl;

        // calculate efficiency for finding the dijet
        hdijet_sing_pT1->Fill(pT1);

        // cut on the subleading jet
        if ( pT2 < pT2min || TMath::Abs(eta2) > etamax || !acc2 )
          continue;

        hdijet_sing_eta2->Fill(eta2);


        // fill efficiency for finding the dijet
        for (int k = 0; k < NETACUT; k++)
        {
          if ( TMath::Abs(eta2) < etacut[k])
            hdijet_eff_pT1[k]->Fill(pT1);
        }
        for (int k = 0; k < PTCUT; k++)
        {
          if (pT2 > ptcut[k])
            hdijet_eff_eta2[k]->Fill(eta2);
        }

        hdijet_dphi->Fill(dphi);

        if ( dphi < 2.*TMath::Pi() / 3)
          continue;


        // fill diagnostic histograms

        hdijet_pT1->Fill(pT1);
        hdijet_pT2->Fill(pT2);
        hdijet_xj->Fill(pT2 / pT1);

      } // j
    } // i

  } // ientry

  // first get some statistics
  cout << " N b dijets: " << hdijet_dphi->Integral() << endl;
  cout << " N b dijets w / dphi cut: " << hdijet_xj->Integral() << endl;

  // calculate efficiencies
  for (int i = 0; i < NETACUT; i++)
  {
    hdijet_eff_pT1[i]->Divide(hdijet_sing_pT1);
    cout << " i: " << hdijet_eff_pT1[i]->GetMaximum() << endl;
  }
  for (int i = 0; i < PTCUT; i++)
  {
    hdijet_eff_eta2[i]->Divide(hdijet_sing_eta2);
  }

  //-- normalize to integral 1
  hdijet_dphi->Scale(1. / hdijet_dphi->Integral());
  hdijet_xj->Scale(1. / hdijet_xj->Integral());

  //-- scale statistical uncertainties if not enough simulated events
  if ( lumiRead < lumiDesired )
  {
    cout << endl;
    cout << "-- Scaling statistical uncertainties by:" << endl;
    cout << "  sqrt(" << lumiRead << "/" << lumiDesired << ") = "
         << TMath::Sqrt(lumiRead / lumiDesired) << endl;
    for (int ix = 1; ix <= hdijet_xj->GetNbinsX(); ix++)
    {
      double be = hdijet_xj->GetBinError(ix);
      be = be * TMath::Sqrt(lumiRead / lumiDesired);
      hdijet_xj->SetBinError(ix, be);
    } // ix
  }

  //-- fix statistical uncertainties for purity
  hdijet_xj_fix = (TH1D*) hdijet_xj->Clone("hdijet_xj_fix");
  hdijet_xj_fix->SetLineColor(kRed);
  hdijet_xj_fix->SetMarkerColor(kRed);
  for (int ix = 1; ix <= hdijet_xj->GetNbinsX(); ix++)
  {
    double bc = hdijet_xj->GetBinContent(ix);
    double be = hdijet_xj->GetBinError(ix);

    // increase the bin error due to the purity
    // need to square it, once for each bjet
    be = be / TMath::Sqrt(bJetPur * bJetPur);
    hdijet_xj_fix->SetBinError(ix, be);
  } // ix



  //==========================================================================//
  // <x_j>
  //==========================================================================//
  cout << endl;
  cout << "--> Calculating <x_j>" << endl;

  double sum = 0;
  double w = 0;
  double err = 0;
  for (int i = 1; i <= hdijet_xj->GetNbinsX(); i++)
  {
    double c = hdijet_xj->GetBinContent(i);
    if (c > 0)
    {
      sum += c * hdijet_xj->GetBinCenter(i);
      w += c;
      err += TMath::Power(c * hdijet_xj->GetBinError(i), 2);
    }
  }
  double mean = sum / w;
  err = TMath::Sqrt(err) / w;

  cout << "  <x_j>=" << mean << " +/- " << err << endl;

  //==========================================================================//
  // PLOT OBJECTS
  //==========================================================================//
  cout << endl;
  cout << "-- > Plotting" << endl;

  hdijet_xj->SetMarkerStyle(kFullCircle);
  hdijet_xj->SetMarkerColor(kBlack);
  hdijet_xj->SetLineColor(kBlack);
  // hdijet_xj->GetYaxis()->SetTitleFont(63);
  // hdijet_xj->GetYaxis()->SetTitleSize(24);
  // hdijet_xj->GetYaxis()->SetTitleOffset(1.4);
  // hdijet_xj->GetYaxis()->SetLabelFont(63);
  // hdijet_xj->GetYaxis()->SetLabelSize(20);
  // hdijet_xj->GetXaxis()->SetTitleFont(63);
  // hdijet_xj->GetXaxis()->SetTitleSize(24);
  // hdijet_xj->GetXaxis()->SetTitleOffset(1.0);
  // hdijet_xj->GetXaxis()->SetLabelFont(63);
  // hdijet_xj->GetXaxis()->SetLabelSize(20);

  hdijet_xj_fix->SetMarkerStyle(kFullCircle);
  hdijet_xj_fix->SetMarkerColor(kBlack);
  hdijet_xj_fix->SetLineColor(kBlack);

  hdijet_dphi->SetMarkerStyle(kFullCircle);
  hdijet_dphi->SetMarkerColor(kBlack);
  hdijet_dphi->SetLineColor(kBlack);
  hdijet_dphi->GetYaxis()->SetTitleFont(63);
  hdijet_dphi->GetYaxis()->SetTitleSize(24);
  hdijet_dphi->GetYaxis()->SetTitleOffset(1.4);
  hdijet_dphi->GetYaxis()->SetLabelFont(63);
  hdijet_dphi->GetYaxis()->SetLabelSize(20);
  hdijet_dphi->GetXaxis()->SetTitleFont(63);
  hdijet_dphi->GetXaxis()->SetTitleSize(24);
  hdijet_dphi->GetXaxis()->SetTitleOffset(1.0);
  hdijet_dphi->GetXaxis()->SetLabelFont(63);
  hdijet_dphi->GetXaxis()->SetLabelSize(20);

  hdijet_pT1->SetLineColor(kBlue);
  hdijet_pT2->SetLineColor(kRed);

  TH1D* heff_axis_pt = new TH1D("heff_axis_pt",
                                "; p_{T, 1} [GeV / c]; Fraction of Dijet / Single Accepted",
                                20, 00, 100);
  heff_axis_pt->SetMinimum(0);
  heff_axis_pt->SetMaximum(1.);
  heff_axis_pt->GetYaxis()->SetTitleFont(63);
  heff_axis_pt->GetYaxis()->SetTitleSize(24);
  heff_axis_pt->GetYaxis()->SetTitleOffset(1.4);
  heff_axis_pt->GetYaxis()->SetLabelFont(63);
  heff_axis_pt->GetYaxis()->SetLabelSize(20);
  heff_axis_pt->GetXaxis()->SetTitleFont(63);
  heff_axis_pt->GetXaxis()->SetTitleSize(24);
  heff_axis_pt->GetXaxis()->SetTitleOffset(1.0);
  heff_axis_pt->GetXaxis()->SetLabelFont(63);
  heff_axis_pt->GetXaxis()->SetLabelSize(20);

  TH1D* heff_axis_eta = new TH1D("heff_axis_eta",
                                 "; #eta_{2}; Fraction of Dijet / Single Accepted",
                                 150, -1.5, 1.5);
  heff_axis_eta->SetMinimum(0);
  heff_axis_eta->SetMaximum(1.);
  heff_axis_eta->GetYaxis()->SetTitleFont(63);
  heff_axis_eta->GetYaxis()->SetTitleSize(24);
  heff_axis_eta->GetYaxis()->SetTitleOffset(1.4);
  heff_axis_eta->GetYaxis()->SetLabelFont(63);
  heff_axis_eta->GetYaxis()->SetLabelSize(20);
  heff_axis_eta->GetXaxis()->SetTitleFont(63);
  heff_axis_eta->GetXaxis()->SetTitleSize(24);
  heff_axis_eta->GetXaxis()->SetTitleOffset(1.0);
  heff_axis_eta->GetXaxis()->SetLabelFont(63);
  heff_axis_eta->GetXaxis()->SetLabelSize(20);

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_pT1[i]->SetLineColor(etaColor[i]);

//-- legends
  TLegend *leg_jetpt = new TLegend(0.6, 0.5, 0.95, 0.95);
  leg_jetpt->SetFillStyle(0);
  leg_jetpt->SetBorderSize(0);
  leg_jetpt->SetTextFont(63);
  leg_jetpt->SetTextSize(12);
  leg_jetpt->AddEntry(hjet_pT, "Inclusive b - jet", "L");
  leg_jetpt->AddEntry(hdijet_pT1, "leading b - jet", "L");
  leg_jetpt->AddEntry(hdijet_pT2, "subleading b - jet", "L");


//-- other
  TLatex ltxt;
  ltxt.SetNDC();
  ltxt.SetTextFont(63);
  ltxt.SetTextSize(20);

//==========================================================================//
// PLOT
//==========================================================================//

// plot b-jet kinematics
  TCanvas *cjet = new TCanvas("cjet", "b - jet", 1200, 400);
  cjet->SetMargin(0, 0, 0, 0);
  cjet->Divide(3, 1);

  cjet->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cjet->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cjet->GetPad(3)->SetMargin(0.12, 0.02, 0.12, 0.02);

  cjet->cd(1);
  gPad->SetLogy();
  hjet_pT->GetYaxis()->SetRangeUser(0.5, 1.5 * hjet_pT->GetMaximum());
  hjet_pT->GetXaxis()->SetRangeUser(0, 50);
  hjet_pT->Draw();
  // hdijet_pT1->Draw("same");
  // hdijet_pT2->Draw("same");

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

  cjet->cd(2);
  hjet_eta->Draw("HIST");

  cjet->cd(3);
  hjet_phi->Draw("HIST");


// plot dijet eff
  TCanvas *ceff = new TCanvas("ceff", "eff", 1200, 600);
  ceff->Divide(2, 1);
  ceff->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  ceff->GetPad(1)->SetTicks(1, 1);
  ceff->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);
  ceff->GetPad(2)->SetTicks(1, 1);

  ceff->cd(1);

  heff_axis_pt->Draw();

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_pT1[i]->Draw("L same");

  ceff->cd(2);

  heff_axis_eta->Draw();

  for (int i = 0; i < NETACUT; i++)
    hdijet_eff_eta2[i]->Draw("L same");

// plot dijet checks
  TCanvas *cdijet2 = new TCanvas("cdijet2", "dijet", 1200, 600);
  cdijet2->SetMargin(0, 0, 0, 0);
  cdijet2->Divide(2, 1);

  cdijet2->GetPad(1)->SetMargin(0.12, 0.02, 0.12, 0.02);
  cdijet2->GetPad(2)->SetMargin(0.12, 0.02, 0.12, 0.02);

  cdijet2->cd(1);
  hdijet_xj->Draw();

  ltxt.DrawLatex(0.2, 0.92, "Di b-jets (Pythia8)");
  ltxt.DrawLatex(0.2, 0.86, "p + p #sqrt{s_{_{NN}}}=200 GeV");
  ltxt.DrawLatex(0.2, 0.80, "anti - k_ {T}, R = 0.4");
  ltxt.DrawLatex(0.2, 0.74, Form("p_{T, 1} > % .0f GeV", pT1min));
  ltxt.DrawLatex(0.2, 0.68, Form("p_{T, 2} > % .0f GeV", pT2min));
  ltxt.DrawLatex(0.2, 0.62, Form(" | #Delta#phi_{12}| > 2#pi/3"));

  cdijet2->cd(2);
  hdijet_dphi->Draw();






  // make this one consistent with sPHENIX style
  TCanvas *cdijet = new TCanvas("cdijet", "dijet", 600, 600);
  // cdijet->SetMargin(0.12, 0.02, 0.12, 0.02);
  // cdijet->SetTicks(1, 1);
  cdijet->cd();
  hdijet_xj_fix->GetYaxis()->SetRangeUser(0, 0.3);
  hdijet_xj_fix->Draw();
  // hdijet_xj->Draw("same");


  TLegend *legsphenix = new TLegend(0.15, 0.5, 0.5, 0.9);
  legsphenix->SetFillStyle(0);
  legsphenix->SetBorderSize(0);
  legsphenix->AddEntry("", "#it{#bf{sPHENIX}} Simulation", "");
  legsphenix->AddEntry("", "Di b-jets (Pythia8, CTEQ6L)", "");
  // if (is_pp)
  // {
  //   legsphenix->AddEntry("", "p + p #sqrt{s_{_{NN}}} = 200 GeV", "");
  //   legsphenix->AddEntry("", Form("#int L dt = %.0f pb^{-1} |z| < 10 cm", lumiDesired), "");
  // }
  // else
  // {
  //   legsphenix->AddEntry("", "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV", "");
  //   legsphenix->AddEntry("", "10B events |z| < 10 cm", "");
  // }
  legsphenix->AddEntry("", scol.Data(), "");
  legsphenix->AddEntry("", slumi.Data(), "");
  legsphenix->AddEntry("", "anti-k_{T}, R = 0.4", "");
  legsphenix->AddEntry("", Form(" |#eta| < %.1f", etamax), "");
  legsphenix->AddEntry("", Form(" |#Delta#phi_{12}| > 2#pi/3"), "");
  legsphenix->AddEntry("", Form("p_{T, 1} > % .0f GeV", pT1min), "");
  legsphenix->AddEntry("", Form("p_{T, 2} > % .0f GeV", pT2min), "");
  legsphenix->AddEntry("", Form("%.0f%% b-jet Eff, %.0f%% b-jet Pur.", bJetEff * 100., bJetPur * 100.), "");
  legsphenix->Draw("same");

  // ltxt.DrawLatex(0.2, 0.92, "Di b-jets (Pythia8)");
  // if (is_pp)
  // {
  //   ltxt.DrawLatex(0.2, 0.86, "p + p #sqrt{s_{_{NN}}} = 200 GeV");
  //   ltxt.DrawLatex(0.2, 0.80, "#int L dt = 175 pb^{-1} |z| < 10 cm");
  // }
  // else
  // {
  //   ltxt.DrawLatex(0.2, 0.86, "0-10% Au + Au #sqrt{s_{_{NN}}}=200 GeV");
  //   ltxt.DrawLatex(0.2, 0.80, "10B events |z| < 10 cm");
  // }
  // ltxt.DrawLatex(0.2, 0.74, "anti-k_{T}, R = 0.4");
  // ltxt.DrawLatex(0.2, 0.68, Form("p_{T, 1} > % .0f GeV", pT1min));
  // ltxt.DrawLatex(0.2, 0.62, Form("p_{T, 2} > % .0f GeV", pT2min));
  // ltxt.DrawLatex(0.2, 0.56, Form(" |#eta| < %.0f", etamax));
  // ltxt.DrawLatex(0.2, 0.50, Form(" |#Delta#phi_{12}| > 2#pi/3"));


  //==========================================================================//
  // PRINT PLOTS
  //==========================================================================//
  if (print_plots)
  {
    if (is_pp)
    {
      // cjet->Print("bjet_kinematics_pp.pdf");
      // cdijet2->Print("dibjet_2panel_pp.pdf");
      cdijet->Print("dibjet_imbalance_pp.pdf");
      cdijet->Print("dibjet_imbalance_pp.C");
      cdijet->Print("dibjet_imbalance_pp.root");

      TFile *fout = new TFile("dibjet_imbalance_histos_pp.root","RECREATE");
      fout->cd();
      hdijet_xj->Write();
      hdijet_xj_fix->Write();
      fout->Close();
      delete fout;

    }
    else
    {
      cdijet->Print("dibjet_imbalance_AuAu0-10.pdf");
      cdijet->Print("dibjet_imbalance_AuAu0-10.C");
      cdijet->Print("dibjet_imbalance_AuAu0-10.root");

      TFile *fout = new TFile("dibjet_imbalance_histos_AuAu0-10.root","RECREATE");
      fout->cd();
      hdijet_xj->Write();
      hdijet_xj_fix->Write();
      fout->Close();
      delete fout;
    }
  }

}
示例#21
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 closure_jetfakepho(){//main  
  
  int channel = 1; // 1 = eg; 2 = mg
	 
  TChain *sigtree = new TChain("signalTree");
  if(channel == 1)sigtree->Add("../../../data/resTree_egsignal_2016.root");
  else if(channel ==2)sigtree->Add("../../../data/resTree_mgsignal_2016.root");

  TChain *controltree = new TChain("jetTree");
  if(channel == 1)controltree->Add("../../../data/resTree_egsignal_2016.root");
  else if(channel == 2)controltree->Add("../../../data/resTree_mgsignal_2016.root");

  std::ostringstream outputname;
  if(channel == 1)outputname << "jet-fake-pho_egpt.root";
  else if(channel == 2)outputname << "jet-fake-pho_mgpt.root";
  TFile *outputfile = TFile::Open(outputname.str().c_str(),"RECREATE");
  outputfile->cd();

//*********** histo list **********************//
//  TH1F *p_controlPhoEt = new TH1F("p_controlPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);
//  TH1F *p_sigPhoEt  = new TH1F("p_sigPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);
//  TH1F *p_fakesPhoEt = new TH1F("p_fakesPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);
//  TH1F *p_elebkgPhoEt = new TH1F("p_elebkgPhoEt","#gamma E_{T}; E_{T} (GeV)",300,35,335);

  TH1F *p_controlPhoEt = new TH1F("p_controlPhoEt",";pt;",115,35,150);
  TH1F *p_sigPhoEt  = new TH1F("p_sigPhoEt",";pt;",115,35,150);
  TH1F *p_fakesPhoEt = new TH1F("p_fakesPhoEt",";pt;",115,35,150);
  TH1F *p_elebkgPhoEt = new TH1F("p_elebkgPhoEt",";pt;",115,35,150);

  sigtree->Draw("phoEt >> p_sigPhoEt", "sigMET < 70");
  controltree->Draw("phoEt >> p_controlPhoEt", "sigMET < 70");

  //p_sigPhoEt->SetBinContent(115, p_sigPhoEt->GetBinContent(115) + p_sigPhoEt->GetBinContent(116));
  //p_controlPhoEt->SetBinContent(115, p_controlPhoEt->GetBinContent(115) + p_controlPhoEt->GetBinContent(116));
  
  p_sigPhoEt->Sumw2();
  p_controlPhoEt->Sumw2();
//************ Proxy Tree **********************//
if(channel == 1){
  TChain *proxytree = new TChain("proxyTree");
  proxytree->Add("../../../data/resTree_egsignal_2016.root");

  float proxyphoEt(0);
  float proxysigMET(0);
  
  proxytree->SetBranchAddress("phoEt",     &proxyphoEt);
  proxytree->SetBranchAddress("sigMET",    &proxysigMET);
 
  for (unsigned ievt(0); ievt<proxytree->GetEntries(); ++ievt){//loop on entries
	proxytree->GetEntry(ievt);

    if(proxysigMET > 70)continue;
	double w_ele = 1; 
    for(unsigned i(0); i<nelePtBins-1; i++){
      if(proxyphoEt > elePtBins[i] && proxyphoEt < elePtBins[i+1])w_ele=elefakepho[i];
    }
    if(proxyphoEt >= 120)w_ele = 0.0124176; 
	p_elebkgPhoEt->Fill(proxyphoEt,w_ele);
  }
  p_elebkgPhoEt->Sumw2();
  p_sigPhoEt->Add(p_elebkgPhoEt, -1);
}
  for(unsigned ibin(1); ibin < p_sigPhoEt->GetSize()-1; ibin++){
    double xvalue = p_sigPhoEt->GetBinCenter(ibin);
    double frac(0),fracerror(0);
    for(unsigned i(0); i<19; i++) 
      if(xvalue >= PtBin[i] && xvalue < PtBin[i+1]){
        frac = fracHad[i];
        fracerror = fracHadError[i];
      }
    if(xvalue >= 140){ frac = (fracHad[18]+fracHad[17])/2; fracerror = fracHadError[18];}
    
    double binvalue = p_sigPhoEt->GetBinContent(ibin)*frac;
    double binerror = p_sigPhoEt->GetBinError(ibin);  
    if(binvalue == 0)continue;
    double totalerror = sqrt(binvalue*binvalue*fracerror*fracerror + binerror*binerror*frac*frac);
    p_fakesPhoEt->SetBinContent(ibin, binvalue);
    p_fakesPhoEt->SetBinError(ibin, binerror);
  }

outputfile->Write();

Double_t plotPtBins[]={35,40,45,50,55,60,65,70,75,80,85,90,100,110,120,130,140,160,200};
gStyle->SetOptStat(0);
TCanvas *c_pt = new TCanvas("Photon_Pt", "Photon P_{T}",800,800);
c_pt->cd();
TPad *pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1.0);
pad1->SetBottomMargin(0.1);
pad1->Draw();  
pad1->cd();  
gPad->SetLogy();
TH1 *new_controlPhoEt = p_controlPhoEt->Rebin(5);
TH1 *new_fakesPhoEt = p_fakesPhoEt->Rebin(5);
new_controlPhoEt->GetXaxis()->SetRangeUser(35,150);
new_fakesPhoEt->GetXaxis()->SetRangeUser(35,150);
new_controlPhoEt->Draw("EP");
new_controlPhoEt->SetLineColor(kBlack);
new_controlPhoEt->SetMarkerStyle(20);
new_fakesPhoEt->SetLineColor(kRed);
new_fakesPhoEt->SetMarkerStyle(20);
new_fakesPhoEt->SetMarkerColor(kRed);
new_fakesPhoEt->Draw("EP same");
TLegend *leg =  new TLegend(0.6,0.7,0.9,0.9);
leg->SetFillStyle(0);
gStyle->SetLegendBorderSize(1);
gStyle->SetLegendFillColor(0);
leg->AddEntry(new_controlPhoEt,"hadron proxies");
leg->AddEntry(new_fakesPhoEt,"fake photons");
leg->Draw("same");

TF1 *fitfunc_num = new TF1("fitfunc_num","expo(0)+expo(3)",35,150);
TF1 *fitfunc_den = new TF1("fitfunc_den","expo(0)+expo(3)",35,150);

c_pt->cd();
TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 1, 0.25);
pad2->Draw();
pad2->cd();
TH1F *ratio=(TH1F*)new_fakesPhoEt->Clone("transfer factor");
ratio->Divide(new_controlPhoEt);
ratio->SetTitle("");
ratio->GetYaxis()->SetTitle("proxies/fake");
ratio->GetXaxis()->SetLabelFont(63);
ratio->GetXaxis()->SetLabelSize(14);
ratio->GetYaxis()->SetLabelFont(63);
ratio->GetYaxis()->SetLabelSize(14);
ratio->Draw();

RooRealVar pt("pt","",35,150);
//pt.setBins(33);
new_controlPhoEt->SetMaximum(new_controlPhoEt->GetEntries());
new_fakesPhoEt->SetMaximum(new_fakesPhoEt->GetEntries());
RooDataHist* hist_den = new RooDataHist("hist_den","hist_den",pt,new_controlPhoEt);
RooDataHist* hist_num = new RooDataHist("hist_num","hist_num",pt,new_fakesPhoEt);
RooHistPdf*  pdf_den  = new RooHistPdf("pdf_den","pdf_den", pt, *hist_den);
RooHistPdf*  pdf_num  = new RooHistPdf("pdf_num","pdf_num", pt, *hist_num);
RooRealVar coeff1_den("coeff1_den","coeff1", 1, -15, 10*new_controlPhoEt->GetEntries());
RooRealVar coeff2_den("coeff2_den","coeff2", 1, -15, 10*new_controlPhoEt->GetEntries());
RooRealVar lambda1_den("lambda1_den","lambda1", 0.02, -1, 1);
RooRealVar lambda2_den("lambda2_den","lambda2", 0.02, -1, 1);
RooExponential expo1_den("expo1_den", "exponential PDF", pt, lambda1_den);
RooExponential expo2_den("expo2_den", "exponential PDF", pt, lambda2_den);
RooAddPdf model_den("model_den","",RooArgList(expo1_den, expo2_den),RooArgList(coeff1_den, coeff2_den));

RooRealVar coeff1_num("coeff1_num","coeff1", 1, -15, 10*new_fakesPhoEt->GetEntries());
RooRealVar coeff2_num("coeff2_num","coeff2", 1, -15, 10*new_fakesPhoEt->GetEntries());
RooRealVar lambda1_num("lambda1_num","lambda1", 0.02, -1, 1);
RooRealVar lambda2_num("lambda2_num","lambda2", 0.02, -1, 1);
RooExponential expo1_num("expo1_num", "exponential PDF", pt, lambda1_num);
RooExponential expo2_num("expo2_num", "exponential PDF", pt, lambda2_num);
RooAddPdf model_num("model_num","",RooArgList(expo1_num, expo2_num),RooArgList(coeff1_num, coeff2_num));

//RooMCStudy* mcstudy_den = new RooMCStudy(*pdf_den,pt,RooFit::FitModel(model_den),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(),
//				       RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::PrintEvalErrors(0)));
//RooMCStudy* mcstudy_num = new RooMCStudy(*pdf_num,pt,RooFit::FitModel(model_num),RooFit::Binned(kTRUE),RooFit::Silence(),RooFit::Extended(),
//				       RooFit::FitOptions(RooFit::Save(kTRUE),RooFit::PrintEvalErrors(0)));
//RooChi2MCSModule chi2mod_den;
//RooChi2MCSModule chi2mod_num;
//mcstudy_den->addModule(chi2mod_den);
//mcstudy_num->addModule(chi2mod_num);
//mcstudy_den->generateAndFit(1000,new_controlPhoEt->GetEntries());
//mcstudy_num->generateAndFit(1000,new_fakesPhoEt->GetEntries());

//TH1* chi2_den = mcstudy_den->fitParDataSet().createHistogram("chi2"); 
//TH1* prob_den = mcstudy_den->fitParDataSet().createHistogram("prob");   
//TH1* chi2_num = mcstudy_num->fitParDataSet().createHistogram("chi2"); 
//TH1* prob_num = mcstudy_num->fitParDataSet().createHistogram("prob");   
//TH1* result_den = mcstudy_den->fitParDataSet().createHistogram("hh");
//TH1* result_den = mcstudy_den->fitResult(0)->correlationHist("c000") ;
//chi2_num->SetLineColor(kRed) ;
//prob_num->SetLineColor(kRed) ;

TCanvas* mccan = new TCanvas("mccan","mccan",800,400) ;
mccan->Divide(2) ;
//mccan->cd(1) ; gPad->SetLeftMargin(0.15) ; chi2_den->GetYaxis()->SetTitleOffset(1.4) ; chi2_den->Draw() ; chi2_num->Draw("esame") ;
//mccan->cd(2) ; gPad->SetLeftMargin(0.15) ; prob_den->GetYaxis()->SetTitleOffset(1.4) ; prob_den->Draw() ; prob_num->Draw("esame") ;
RooPlot* den_frame = pt.frame(RooFit::Title("jet proxies"));
RooPlot* num_frame = pt.frame(RooFit::Title("candidate photon X hadron factor"));

mccan->cd(1);
gPad->SetLogy();
den_frame->SetMaximum(new_controlPhoEt->GetEntries());
RooFitResult* reden = model_den.fitTo(*hist_den,RooFit::SumW2Error(kTRUE),RooFit::Save());
hist_den->plotOn(den_frame);
model_den.plotOn(den_frame,
		 RooFit::FillColor(kBlue-4));
den_frame->Draw();

mccan->cd(2);
gPad->SetLogy();
num_frame->SetMaximum(10000);
num_frame->SetMinimum(10);
RooFitResult* renum = model_num.fitTo(*hist_num,RooFit::SumW2Error(kTRUE),RooFit::Save());
hist_num->plotOn(num_frame);
model_num.plotOn(num_frame,
		 RooFit::FillColor(kBlue-4));
num_frame->Draw();

pt.setRange("signal",35,150);
RooAbsReal* igx_den1 = expo1_den.createIntegral(pt,RooFit::Range("signal"));
RooAbsReal* igx_den2 = expo2_den.createIntegral(pt,RooFit::Range("signal"));
RooAbsReal* igx_num1 = expo1_num.createIntegral(pt,RooFit::Range("signal"));
RooAbsReal* igx_num2 = expo2_num.createIntegral(pt,RooFit::Range("signal"));
std::cout << "inte den1=" << igx_den1->getVal() << " den2=" << igx_den2->getVal() << " num1=" << igx_num1->getVal() << " num2=" << igx_num2->getVal() << std::endl;
std::cout << "totalden=" << new_controlPhoEt->GetEntries() << std::endl;
fitfunc_den->SetParameter(1,lambda1_den.getVal());
fitfunc_den->SetParameter(3,lambda2_den.getVal());
fitfunc_num->SetParameter(1,lambda1_num.getVal());
fitfunc_num->SetParameter(3,lambda2_num.getVal());
new_fakesPhoEt->Fit("fitfunc_num");
new_controlPhoEt->Fit("fitfunc_den");
c_pt->cd();
pad1->cd();
fitfunc_den->Draw("same");
fitfunc_num->Draw("same");
if(channel == 1)c_pt->SaveAs("JetFake_ratio_eg.pdf");
else if(channel == 2)c_pt->SaveAs("JetFake_ratio_mg.pdf");
//  NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE 
//   1  p0           9.73181e+00   2.26898e-01   2.78046e-05   9.10547e-03
//   2  p1          -3.34186e-02   1.55081e-03   4.43967e-07   7.43686e-01
//  3  p3           9.55643e+00   2.70401e-01   3.31514e-05   7.64064e-03
//  4  p4          -3.34188e-02   1.82847e-03   5.28578e-07   5.89368e-01
//FCN=95.1209 FROM MIGRAD    STATUS=CONVERGED     253 CALLS         254 TOTAL
//                    EDM=2.21358e-08    STRATEGY= 1      ERROR MATRIX ACCURATE 
// EXT PARAMETER                                   STEP         FIRST   
// NO.   NAME      VALUE            ERROR          SIZE      DERIVATIVE 
//  1  p0           2.27259e+00   1.40250e+00   3.06094e-04  -1.34231e-05
//  2  p1           2.05848e-02   9.68368e-03   2.22428e-06  -1.31028e-02
//  3  p3           1.24698e+01   9.85422e-03   9.76944e-06  -3.21533e-02
//   4  p4          -4.47018e-02   2.05076e-04   1.63128e-07  -1.91568e+00

mccan->SaveAs("JetFake_ptfitting.pdf");
for(unsigned i(0); i< 23; i++){
  Double_t bincenter = i*5.0+2.5;
  std::cout << "bin" << i << "  " << ratio->GetBinContent(i) << "  predict = " << fitfunc_num->Eval(bincenter)/fitfunc_den->Eval(bincenter) << std::endl;
}
}
示例#23
0
void rateStudy() {
  const int NRUNS = 25;
  const int NCH = 32;
  const int NBINS = 32;

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

  TMultiGraph *mg = new TMultiGraph();

  TLegend *legend=new TLegend(0.65,0.15,0.88,0.55);
  legend->SetNColumns(4);
  legend->SetFillColor(0);

  TH1F* hRate = new TH1F("hRate", "hist", 32.0, 0, 8.0);

  //Color buffer
  const int NCOLORS = 32;
  int color[NCOLORS] = {73, 2, 3, 4, 99, 6, 7, 8, 9, 12, 28, 32, 34,
                        28, 50, 51, 56, 58, 88, 99, 1, 208, 209,
                        218, 212, 210, 221, 224, 225, 226, 227, 228 };

  ifstream fin;
  //fin.open("runlist.txt");
  fin.open("filter_runlist.txt");

  string line = "";

  TFile* out = new TFile("outtemp.root", "REACREATE");
  TH1F* h = new TH1F("h","hist", NBINS, 0, NBINS);
  TF1* pois = new TF1("pois","[0]*TMath::Poisson(x,[1])",0,50);
  TF1* ppp = new TF1("ppp","[0]*TMath::Power(0.5,x*[1])",0.01,1.0);


  for (int ch = 0; ch < NCH; ++ch) {

    //if ( ch==26 || ch==27 )
    //continue;

    //Graph points and errors
    Double_t x[NRUNS];
    Double_t y[NRUNS];
    Double_t errX[NRUNS] = {0};
    Double_t errY[NRUNS] = {0};

    int fileCounter = 0;
    while(getline(fin, line)) {
      vector<double> data = parse(line);
      stringstream filePath;
      filePath << "pmtratestudy/run" << data[0] << "*.root";
      cout << "opening file at " << filePath.str() << endl;
      cout << "file counter: " << fileCounter << " channel=" << ch << endl;
      //TFile* f = new TFile(filePath.str().c_str());
      //TTree* t = (TTree *)f->Get("eventtree");
      TChain* t = new TChain("eventtree");
      t->Add( filePath.str().c_str() );
      out->cd();

      x[fileCounter] = data[1];

      int nfires[NCH] = {0};
      int samples = 0;
      float chmax = 0.0;
      t->SetBranchAddress("nfires", &nfires);
      t->SetBranchAddress("samples", &samples);
      t->SetBranchAddress("chmax", &chmax);
      
      h->Reset();
      
      int nentries = t->GetEntries();
      for (int entry = 0; entry < nentries; ++entry) {
        t->GetEntry(entry);
        if (chmax < 100.0) {
          h->Fill(nfires[ch]);
        }
      }


      
      pois->SetParameter(0,1);
      pois->SetParameter(1, h->GetMean());

      h->Fit(pois,"RQ","",0,50);
      //TF1 *myfit = (TF1 *)h->GetFunction("pois");
      TF1 *myfit = (TF1 *)pois;
      Double_t lambda = myfit->GetParameter(1);  
      h->Draw();
      stringstream histFileName;
      histFileName << "hist/h" << data[0] << "_ch" << ch << ".png";
      c1->SaveAs(histFileName.str().c_str());
      //Graph with poisson method
#if 1
      y[fileCounter] = lambda / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = myfit->GetParError(1) / ((samples - 1) * 15.625E-6);
#endif
      //Graph with mean method
#if 0
      y[fileCounter] = h->GetMean() / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = h->GetMeanError() / ((samples - 1) * 15.625E-6);
#endif
      cout << x[fileCounter] << ", " << y[fileCounter] 
           << " | " << (samples - 1) << endl;
      delete t;
      //f->Close();
      fileCounter++;
    } 

    ppp->SetParameter(0,1);
    ppp->SetParameter(1,0.4);
     
    TGraphErrors* gr = new TGraphErrors(NRUNS, x, y, errX, errY);
    gr->SetLineColor(color[ch % NCOLORS]);
    cout << "color: " << color[ch % NCOLORS] << endl;
    gr->SetLineWidth(2);
    gr->SetMarkerStyle(7);
    gr->Fit("ppp","R0","Q0",0.045,2.0);
    TF1 *afit = (TF1 *)gr->GetFunction("ppp");
    Double_t aRate = 1/afit->GetParameter(1);  
    if (aRate > 0) {
      hRate->Fill(aRate);
    }
    gr->GetXaxis()->SetTitle("Run Date");
    gr->GetYaxis()->SetTitle("Rate [kHz]");

    stringstream entryName, fileName;
    entryName << "Channel" << ch;
    gr->SetTitle(entryName.str().c_str());
    fileName << "plots/" << ch << ".png";
    legend->AddEntry(gr, entryName.str().c_str());
    gr->Draw("alp");
    c1->SaveAs(fileName.str().c_str());
    mg->Add(gr);
    cout << "added plot to mg\n";
    fin.clear();
    fin.seekg(0, ios::beg);
  } // loop over channel
  hRate->Draw();
  hRate->Fit("gaus");
  c1->SaveAs("hrate.pdf");
  mg->Draw("alp");
  mg->GetXaxis()->SetTitle("Days since first run");
  mg->GetYaxis()->SetTitle("Rate [kHz]");
  mg->SetTitle("All channels: Rate vs. Days since first Run");

  legend->Draw();
  c1->SaveAs("mg.pdf");
  
}
示例#24
0
//------------------------------------------------------------------------------
// LatinosTreeScript
//------------------------------------------------------------------------------
void LatinosTreeScript(TString rootPath,
		       Float_t luminosity,
		       Int_t   jetChannel,
		       TString flavorChannel,
		       TString theSample,
		       TString systematic,
		       Bool_t  verbose)
{
  TH1::SetDefaultSumw2();

  TString path = Form("rootfiles/%s/%djet/%s/", systematic.Data(), jetChannel, flavorChannel.Data());

  gSystem->mkdir(path, kTRUE);

  TFile* output = new TFile(path + theSample + ".root", "recreate");


  // Counting histograms
  //----------------------------------------------------------------------------
  TH1F* hWTrigger     = new TH1F("hWTrigger",     "", 3, 0, 3);
  TH1F* hWMetCut      = new TH1F("hWMetCut",      "", 3, 0, 3);
  TH1F* hWLowMinv     = new TH1F("hWLowMinv",     "", 3, 0, 3);
  TH1F* hWZVeto       = new TH1F("hWZVeto",       "", 3, 0, 3);
  TH1F* hWpMetCut     = new TH1F("hWpMetCut",     "", 3, 0, 3);
  TH1F* hWJetVeto     = new TH1F("hWJetVeto",     "", 3, 0, 3);
  TH1F* hWDeltaPhiJet = new TH1F("hWDeltaPhiJet", "", 3, 0, 3);
  TH1F* hWSoftMuVeto  = new TH1F("hWSoftMuVeto",  "", 3, 0, 3); 
  TH1F* hWExtraLepton = new TH1F("hWExtraLepton", "", 3, 0, 3);
  TH1F* hWPtll        = new TH1F("hWPtll",        "", 3, 0, 3);
  TH1F* hWTopTagging  = new TH1F("hWTopTagging",  "", 3, 0, 3);

  TH1F* hWeffTrigger     = new TH1F("hWeffTrigger",     "", 3, 0, 3);
  TH1F* hWeffMetCut      = new TH1F("hWeffMetCut",      "", 3, 0, 3);
  TH1F* hWeffLowMinv     = new TH1F("hWeffLowMinv",     "", 3, 0, 3);
  TH1F* hWeffZVeto       = new TH1F("hWeffZVeto",       "", 3, 0, 3);
  TH1F* hWeffpMetCut     = new TH1F("hWeffpMetCut",     "", 3, 0, 3);
  TH1F* hWeffJetVeto     = new TH1F("hWeffJetVeto",     "", 3, 0, 3);
  TH1F* hWeffDeltaPhiJet = new TH1F("hWeffDeltaPhiJet", "", 3, 0, 3);
  TH1F* hWeffSoftMuVeto  = new TH1F("hWeffSoftMuVeto",  "", 3, 0, 3); 
  TH1F* hWeffExtraLepton = new TH1F("hWeffExtraLepton", "", 3, 0, 3);
  TH1F* hWeffPtll        = new TH1F("hWeffPtll",        "", 3, 0, 3);
  TH1F* hWeffTopTagging  = new TH1F("hWeffTopTagging",  "", 3, 0, 3);


  // WW level histograms
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1WWLevel       = new TH1F("hPtLepton1WWLevel",       "", 200, 0, 200);
  TH1F* hPtLepton2WWLevel       = new TH1F("hPtLepton2WWLevel",       "", 200, 0, 200);
  TH1F* hPtDiLeptonWWLevel      = new TH1F("hPtDiLeptonWWLevel",      "", 200, 0, 200);
  TH1F* hMinvWWLevel            = new TH1F("hMinvWWLevel",            "", 200, 0, 200);
  TH1F* hMtWWLevel              = new TH1F("hMtWWLevel",              "", 250, 0, 250);
  TH1F* hNJets30WWLevel         = new TH1F("hNJetsPF30WWLevel",       "",  10, 0,  10);
  TH1F* hpfMetWWLevel           = new TH1F("hpfMetWWLevel",           "", 150, 0, 150);
  TH1F* hppfMetWWLevel          = new TH1F("hppfMetWWLevel",          "", 150, 0, 150);
  TH1F* hchMetWWLevel           = new TH1F("hchMetWWLevel",           "", 150, 0, 150);
  TH1F* hpchMetWWLevel          = new TH1F("hpchMetWWLevel",          "", 150, 0, 150);
  TH1F* hpminMetWWLevel         = new TH1F("hpminMetWWLevel",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsWWLevel   = new TH1F("hDeltaRLeptonsWWLevel",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsWWLevel = new TH1F("hDeltaPhiLeptonsWWLevel", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetWWLevel     = new TH1F("hDPhiPtllJetWWLevel",     "",  32, 0, 3.2);

  TH1F* h_WWLevel_TightFailEvents = new TH1F("h_WWLevel_TightFailEvents", "", 3, 0 , 3);
  TH1F* h_WWLevel_TightTightEvents = new TH1F("h_WWLevel_TightTightEvents", "", 3, 0 , 3);
  TH1F* h_WWLevel_TightLooseEvents = new TH1F("h_WWLevel_TightLooseEvents", "", 3, 0 , 3);


  // TwoLeptons level histograms
  //----------------------------------------------------------------------------
  TH1F* hPtLepton1TwoLeptonsLevel       = new TH1F("hPtLepton1TwoLeptonsLevel",       "", 200, 0, 200);
  TH1F* hPtLepton2TwoLeptonsLevel       = new TH1F("hPtLepton2TwoLeptonsLevel",       "", 200, 0, 200);
  TH1F* hPtDiLeptonTwoLeptonsLevel      = new TH1F("hPtDiLeptonTwoLeptonsLevel",      "", 200, 0, 200);
  TH1F* hMinvTwoLeptonsLevel            = new TH1F("hMinvTwoLeptonsLevel",            "", 200, 0, 200);
  TH1F* hMtTwoLeptonsLevel              = new TH1F("hMtTwoLeptonsLevel",              "", 250, 0, 250);
  TH1F* hNJets30TwoLeptonsLevel         = new TH1F("hNJetsPF30TwoLeptonsLevel",       "",  10, 0,  10);
  TH1F* hpfMetTwoLeptonsLevel           = new TH1F("hpfMetTwoLeptonsLevel",           "", 150, 0, 150);
  TH1F* hppfMetTwoLeptonsLevel          = new TH1F("hppfMetTwoLeptonsLevel",          "", 150, 0, 150);
  TH1F* hchMetTwoLeptonsLevel           = new TH1F("hchMetTwoLeptonsLevel",           "", 150, 0, 150);
  TH1F* hpchMetTwoLeptonsLevel          = new TH1F("hpchMetTwoLeptonsLevel",          "", 150, 0, 150);
  TH1F* hpminMetTwoLeptonsLevel         = new TH1F("hpminMetTwoLeptonsLevel",         "", 150, 0, 150);
  TH1F* hDeltaRLeptonsTwoLeptonsLevel   = new TH1F("hDeltaRLeptonsTwoLeptonsLevel",   "",  50, 0,   5);
  TH1F* hDeltaPhiLeptonsTwoLeptonsLevel = new TH1F("hDeltaPhiLeptonsTwoLeptonsLevel", "",  32, 0, 3.2);
  TH1F* hDPhiPtllJetTwoLeptonsLevel     = new TH1F("hDPhiPtllJetTwoLeptonsLevel",     "",  32, 0, 3.2);

  TH1F* h_TwoLeptons_TightFailEvents = new TH1F("h_TwoLeptons_TightFailEvents", "", 3, 0 , 3);
  TH1F* h_TwoLeptons_TightTightEvents = new TH1F("h_TwoLeptons_TightTightEvents", "", 3, 0 , 3);
  TH1F* h_TwoLeptons_TightLooseEvents = new TH1F("h_TwoLeptons_TightLooseEvents", "", 3, 0 , 3);



  // Dilepton level differential histograms 
  //----------------------------------------------------------------------------

  //differential in dilepton (eta, pt, ptll, mll, dphill), jets (jetpt1, njet), transverse mass? 2-jet bin?
  
  Double_t pt1bins[8] = {20,40,60,80,100,125,150,200}; 
  Double_t eta1bins[9] = {-2.4,-1.8,-1.2,-0.6,0,0.6,1.2,1.8,2.4};
  Double_t mllbins[9] = {20,40,60,80,100,125,150,175,200};
  Double_t dphibins[13] = {0,0.25,0.5,0.75,1,1.25,1.5,1.75,2,2.25,2.5,2.75,3};
  Double_t ptllbins[8] = {30,40,50,60,70,85,120,150};

  TH1F* hPtLepton1DilepLevel_Diff  = new TH1F("hPtLepton1DilepLevel_Diff",       "", 7, pt1bins);
  TH1F* hEtaLepton1DilepLevel_Diff  = new TH1F("hEtaLepton1DilepLevel_Diff",       "", 8, eta1bins);
  TH1F* hDileptonDilepLevel_Diff  = new TH1F("hDileptonDilepLevel_Diff",       "", 7, ptllbins);
  TH1F* hMinvDilepLevel_Diff  = new TH1F("hMinvDilepLevel_Diff",       "", 8, mllbins);
  TH1F* hDeltaPhiDilepLevel_Diff  = new TH1F("hDeltaPhiDilepLevel_Diff",       "", 12, dphibins);


  // WW level differential histograms 
  //----------------------------------------------------------------------------

  TH1F* hPtLepton1WWLevel_Diff  = new TH1F("hPtLepton1WWLevel_Diff",       "",7, pt1bins);
  TH1F* hEtaLepton1WWLevel_Diff  = new TH1F("hEtaLepton1WWLevel_Diff",       "", 8, eta1bins);
  TH1F* hDileptonWWLevel_Diff  = new TH1F("hDileptonWWLevel_Diff",       "", 7, ptllbins);
  TH1F* hMinvWWLevel_Diff  = new TH1F("hMinvWWLevel_Diff",       "", 8, mllbins);
  TH1F* hDeltaPhiWWLevel_Diff  = new TH1F("hDeltaPhiWWLevel_Diff",       "", 12, dphibins);




  // Data-driven methods: Z+jets
  //----------------------------------------------------------------------------
  TH1F* hNinZevents     [numberDYMVACuts];
  TH1F* hNoutZevents    [numberDYMVACuts];
  TH1F* hNinLooseZevents[numberDYMVACuts];
  TH1F* hMassInZevents  [numberDYMVACuts];
  TH1F* hMassOutZevents [numberDYMVACuts];

  for (Int_t nC=0; nC<numberDYMVACuts; nC++) {
    hNinZevents     [nC] = new TH1F(Form("hNinZevents%.1i",      nC+1 ), "",   3, 0,   3);
    hNoutZevents    [nC] = new TH1F(Form("hNoutZevents%.1i",     nC+1 ), "",   3, 0,   3);
    hNinLooseZevents[nC] = new TH1F(Form("hNinLooseZevents%.1i", nC+1 ), "",   3, 0,   3);
    hMassInZevents  [nC] = new TH1F(Form("hMassInZevents%.1i",   nC+1 ), "", 200, 0, 200);
    hMassOutZevents [nC] = new TH1F(Form("hMassOutZevents%.1i",  nC+1 ), "", 200, 0, 200);

   


  }


  // Data-driven methods: Top
  //----------------------------------------------------------------------------
  TH1F* hTopTaggedEvents            = new TH1F("hTopTaggedEvents",            "", 3, 0, 3);
  TH1F* hNTopControlRegion          = new TH1F("hNTopControlRegion",          "", 3, 0, 3);
  TH1F* hNTopTaggedTopControlRegion = new TH1F("hNTopTaggedTopControlRegion", "", 3, 0, 3);

  TH1F* hbTagDisTopTaggedEvents            = new TH1F("hbTagDisTopTaggedEvents",            "", 300, -10, 20);
  TH1F* hbTagDisNTopControlRegion          = new TH1F("hbTagDisNTopControlRegion",          "", 300, -10, 20);
  TH1F* hbTagDisNTopTaggedTopControlRegion = new TH1F("hbTagDisNTopTaggedTopControlRegion", "", 300, -10, 20);


  //----------------------------------------------------------------------------
  // Input files
  //----------------------------------------------------------------------------
  TString filesPath;

  if (runAtOviedo) filesPath = " /hadoop/LatinosSkims/ReducedTrees/R53X_S1_V08_S2_V09_S3_V13/";
  if (runAtIfca)   filesPath = "/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/Systematics2013_nominals_fromMaiko/"; 
  if (runEOS)      filesPath = "root://eoscms.cern.ch//eos/cms/store/group/phys_higgs/cmshww/amassiro/RunI/trees/tree_skim_wwmin_09Jan2014/";

  if (rootPath != "") filesPath = rootPath;

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

  if (theSample == "DataRun2012_Total") {

    tree->Add(filesPath + "/data/" + "latino_RunA_892pbinv.root");
    tree->Add(filesPath + "/data/" + "latino_RunB_4404pbinv.root");
    tree->Add(filesPath + "/data/" + "latino_RunC_7032pbinv.root");
    tree->Add(filesPath + "/data/" + "latino_RunD_7274pbinv.root");
  }

  else if (theSample == "WJetsFakes_Total_old") {
    tree->Add("/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/R53X_S1_V08_S2_V09_S3_V13/Moriond13/latino_LooseLoose_19.5fb.root");

 }
  else if (theSample == "WJetsFakes_Total") {
      
    tree->Add(filesPath + "/wjets/" + "latino_RunA_892pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_RunB_4404pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_RunC_7032pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_RunD_7274pbinv_LooseLoose.root");
    tree->Add(filesPath + "/wjets/" + "latino_082_WGstarToElNuMad.root");
    tree->Add(filesPath + "/wjets/" + "latino_083_WGstarToMuNuMad.root");
    tree->Add(filesPath + "/wjets/" + "latino_084_WGstarToTauNuMad.root");
    tree->Add(filesPath + "/wjets/" + "latino_085_WgammaToLNuG.root");
    tree->Add(filesPath + "/wjets/" + "latino_086_ZgammaToLLuG.root");

  }
  else if (theSample == "ggWWto2L") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_001_GluGluToWWTo4L.root");
  }
  else if (theSample == "WWTo2L2Nu") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_000_WWJets2LMad.root");
  }
  else if (theSample == "WWTo2L2Nu_pow") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_006_WWJets2LPowheg.root");
  }
  else if (theSample == "WWTo2L2Nu_nonSkim_pow") {
    tree->Add("/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/DiferentialXSection/NoSkim_puW_effW_triggW/latino006.root");
  }
  else if (theSample == "WWTo2L2Nu_mcnlo") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_002_WWto2L2NuMCatNLO.root");
  }
  else if (theSample == "WWTo2L2Nu_mcnlo_nnll") {
    tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/nnllResummation/latino002_nll_ewk.root");
  }
  else if (theSample == "WWTo2L2Nu_pow_nnll") {
    tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/nnllResummation/latino006_nll_ewk.root");
  }
  else if (theSample == "WWTo2L2Nu_mad_nnll") {
    tree->Add("/gpfs/csic_projects/cms/calderon/WWGEN/nnllResummation/latino000_nll_ewk.root");
  } else if (theSample == "WZ") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_074_WZJetsMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_078_WZTo2L2QMad.root");
  }
  else if (theSample == "ZZ") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_075_ZZJetsMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_079_ZZTo2L2QMad.root"); 
  }
  else if (theSample == "TTbar") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_019_TTTo2L2Nu2B.root");
  }
  else if (theSample == "TW") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_011_TtWFullDR.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_012_TbartWFullDR.root");
  }
  else if (theSample == "Top") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_019run_TTTo2L2Nu2B.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_011_TtWFullDR.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_012_TbartWFullDR.root");
  }
  else if (theSample == "DY") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_036_DY10toLLMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_037_DY50toLLMad.root");
  }
  else if (theSample == "DYtautau") { // Only for OF channels!!! 
    tree->Add(filesPath + "/templates/" + "latino_DYtt_19.5fb.root"); // CHECK PATH    
  }
  else if (theSample == "Zgamma") { 
    tree->Add(filesPath + "/" + systematic + "/" + "latino_086_ZgammaToLLuG.root");
  }
  else if (theSample == "WgammaNoStar") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_085_WgammaToLNuG.root");
  }
  else if (theSample == "WgammaStar") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_082_WGstarToElNuMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_083_WGstarToMuNuMad.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_084_WGstarToTauNuMad.root");
  }
  else if (theSample == "HWW125") { 
    tree->Add(filesPath + "/" + systematic + "/" + "latino_1125_ggToH125toWWTo2LAndTau2Nu.root");
  }
  else if (theSample =="GamGamWW"){
    tree->Add(filesPath + "/" + systematic + "/" + "latino_008_GamGamWW.root");    
  }
  else if (theSample == "WJets") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_080_WJetsToLNuMad.root");
    //CHECK PATH: tree->Add("/gpfs/csic_projects/tier3data/LatinosSkims/ReducedTrees/R53X_S1_V08_S2_V09_S3_V13/MC_LooseLoose/4L/latino_080_WJetsToLNuMad.root");
  }
  else if (theSample == "VVV") {
    tree->Add(filesPath + "/" + systematic + "/" + "latino_088_WWGJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_089_WZZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_090_ZZZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_091_WWZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_092_WWWJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_093_TTWJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_094_TTZJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_095_TTWWJets.root");
    tree->Add(filesPath + "/" + systematic + "/" + "latino_096_TTGJets.root");
  }
  else {
    return;
  }


  // Declaration of leaf types
  //----------------------------------------------------------------------------
  Float_t baseW;        tree->SetBranchAddress("baseW"       , &baseW);
  Float_t channel;      tree->SetBranchAddress("channel"     , &channel);
  Float_t chmet;        tree->SetBranchAddress("chmet"       , &chmet);
  Float_t dataset;      tree->SetBranchAddress("dataset"     , &dataset);
  Float_t dphill;       tree->SetBranchAddress("dphill"      , &dphill);
  Float_t dphilljet;    tree->SetBranchAddress("dphilljet"   , &dphilljet);
  Float_t dphilljetjet; tree->SetBranchAddress("dphilljetjet", &dphilljetjet);
  Float_t drll;         tree->SetBranchAddress("drll"        , &drll);
  Float_t effW;         tree->SetBranchAddress("effW"        , &effW);
  Float_t jeteta1;      tree->SetBranchAddress("jeteta1"     , &jeteta1);
  Float_t jeteta2;      tree->SetBranchAddress("jeteta2"     , &jeteta2);
  Float_t jeteta3;      tree->SetBranchAddress("jeteta3"     , &jeteta3);
  Float_t jetpt1;       tree->SetBranchAddress("jetpt1"      , &jetpt1);
  Float_t jetpt2;       tree->SetBranchAddress("jetpt2"      , &jetpt2);
  Float_t jetpt3;       tree->SetBranchAddress("jetpt3"      , &jetpt3);
  Float_t jettche1;     tree->SetBranchAddress("jettche1"    , &jettche1);
  Float_t jettche2;     tree->SetBranchAddress("jettche2"    , &jettche2);
  Float_t mctruth;      tree->SetBranchAddress("mctruth"     , &mctruth);
  Float_t mll;          tree->SetBranchAddress("mll"         , &mll);
  Float_t mpmet;        tree->SetBranchAddress("mpmet"       , &mpmet); 
  Float_t mth;          tree->SetBranchAddress("mth"         , &mth);
  Float_t nbjet;        tree->SetBranchAddress("nbjet"       , &nbjet);
  Float_t nbjettche;    tree->SetBranchAddress("nbjettche"   , &nbjettche);
  Float_t nextra;       tree->SetBranchAddress("nextra"      , &nextra);
  Float_t njet;         tree->SetBranchAddress("njet"        , &njet);
  Float_t nvtx;         tree->SetBranchAddress("nvtx"        , &nvtx);
  Float_t pchmet;       tree->SetBranchAddress("pchmet"      , &pchmet);
  Float_t pfmet;        tree->SetBranchAddress("pfmet"       , &pfmet);
  Float_t ppfmet;       tree->SetBranchAddress("ppfmet"      , &ppfmet);
  Float_t pt1;          tree->SetBranchAddress("pt1"         , &pt1);
  Float_t pt2;          tree->SetBranchAddress("pt2"         , &pt2);
  Float_t eta1;          tree->SetBranchAddress("eta1"         , &eta1);
  Float_t eta2;          tree->SetBranchAddress("eta2"         , &eta2);
  Float_t ch1;          tree->SetBranchAddress("ch1"         , &ch1);
  Float_t ch2;          tree->SetBranchAddress("ch2"         , &ch2);
  Float_t ptll;         tree->SetBranchAddress("ptll"        , &ptll);
  Float_t softtche;     tree->SetBranchAddress("softtche"    , &softtche);
  Float_t trigger;      tree->SetBranchAddress("trigger"     , &trigger);
  Float_t triggW;       tree->SetBranchAddress("triggW"      , &triggW);
  Int_t   bveto;        tree->SetBranchAddress("bveto"       , &bveto);
  Int_t   bveto_ip;     tree->SetBranchAddress("bveto_ip"    , &bveto_ip);
  Int_t   bveto_mu;     tree->SetBranchAddress("bveto_mu"    , &bveto_mu);
  Int_t   bveto_nj30;   tree->SetBranchAddress("bveto_nj30"  , &bveto_nj30);
  Int_t   dphiveto;     tree->SetBranchAddress("dphiveto"    , &dphiveto);
  Int_t   sameflav;     tree->SetBranchAddress("sameflav"    , &sameflav);
  Int_t   zveto;        tree->SetBranchAddress("zveto"       , &zveto);
  UInt_t  event;        tree->SetBranchAddress("event"       , &event);
  UInt_t  lumi;         tree->SetBranchAddress("lumi"        , &lumi);
  UInt_t  run;          tree->SetBranchAddress("run"         , &run);

  Int_t pass2012ICHEP1;  tree->SetBranchAddress("pass2012ICHEP1", &pass2012ICHEP1);
  Int_t pass2012ICHEP2;  tree->SetBranchAddress("pass2012ICHEP2", &pass2012ICHEP2);
  
    Float_t dymva1;          tree->SetBranchAddress("dymva1"         , &dymva1);

  

    Float_t nllW = 1; 
    if ( theSample.Contains("_nnll") && jetChannel == 0)
      tree->SetBranchAddress("nllW", &nllW);

    Float_t fakeW;

  if (theSample.Contains("WJetsFakes"))
    tree->SetBranchAddress("fakeW", &fakeW);

  Float_t puW;
  
  if (!theSample.Contains("WJetsFakes") && !theSample.Contains("Data"))
    tree->SetBranchAddress("puW", &puW);


  // Set the channel
  //----------------------------------------------------------------------------
  Float_t SelectedChannel = -999;

  if      (flavorChannel == "MuMu") SelectedChannel =  0;
  else if (flavorChannel == "EE"  ) SelectedChannel =  1;
  else if (flavorChannel == "EMu" ) SelectedChannel =  2;
  else if (flavorChannel == "MuE" ) SelectedChannel =  3;
  else if (flavorChannel == "OF" )  SelectedChannel =  4;
  else if (flavorChannel == "SF" )  SelectedChannel =  5;
  
  //  else if (flavorChannel == "All" ) SelectedChannel = -1;


  //----------------------------------------------------------------------------
  // Loop
  //----------------------------------------------------------------------------
  for (int ievent=0; ievent<tree->GetEntries(); ievent++) {
    
    tree->GetEntry(ievent);
    
    Double_t efficiencyW = effW * triggW;
    Double_t totalW      = -999;

    
    Double_t mybaseW = 5984.0/999864; 
    //5812.3/539594; // mcnlo 
    //5812.3/1933235; // madgraph (1933232)
    // 5812.3/999864; // powheg (999860)


    if (theSample.Contains("Data"))
      totalW = 1.0;

    else if (theSample.Contains("WJetsFakes")) { 
      totalW = fakeW;
     
      if ( dataset >= 82 && dataset <= 85 ) 
	totalW  = fakeW * (1 + 0.5 * (dataset >= 82 && dataset <= 84)) * baseW * puW * effW * triggW * luminosity;
    
    }

    else if (theSample.Contains("_nnll") ) {
      efficiencyW = puW * effW * triggW *nllW;
      totalW      = (1 + 0.5 * (dataset >= 82 && dataset <= 84)) * mybaseW * efficiencyW * luminosity;
    } 

    else {
      efficiencyW = puW * effW * triggW ;
      totalW      = (1 + 0.5 * (dataset >= 82 && dataset <= 84)) * baseW * efficiencyW * luminosity;
    }

    //cout <<mybaseW << endl;

    //if (theSample.Contains("DYtautau") && dataset != 86) totalW *= (19.4/12.1);


    // Help variables
    //--------------------------------------------------------------------------
    //   Int_t dphiv = ((njet <= 1 && dphiveto) || (njet > 1 && dphilljetjet < 165.*TMath::DegToRad()));

    Int_t dphiv = (njet <= 1 || (njet > 1 && dphilljetjet < 165.*TMath::DegToRad()));

    Float_t metvar = (njet <= 1) ? mpmet : pfmet;

    Float_t jetbin = njet;

    Float_t dyMVA = ( !sameflav || ( (njet!=0 || dymva1>0.88) && (njet!=1 || dymva1>0.84) && ( njet==0 || njet==1 || (pfmet > 45.0)) ) );

	    
    if (njet == 3) jetbin = 2;  


    Int_t vbfsel = ((jetpt3 <= 30 || !(jetpt3 > 30 && ((jeteta1-jeteta3 > 0 && jeteta2-jeteta3 < 0) || (jeteta2-jeteta3 > 0 && jeteta1-jeteta3 < 0)))));


    // The selection begins here
    //--------------------------------------------------------------------------
    if (theSample == "DY" && mctruth == 2 && (flavorChannel == "EMu" || flavorChannel == "MuE")) continue;
    if (run == 201191) continue;
    if (trigger != 1) continue;
    if (pt2 <= 20) continue; // increase the pt of the leptons to further reduce Wjets 
    if (pt1 <= 20) continue; // increase the pt of the leptons to further reduce Wjets 
    if (ch1*ch2 > 0) continue;

    if (dataset == 86 && (flavorChannel == "MuMu" || flavorChannel == "EE")) continue; 

    if ((SelectedChannel == -1) || (channel == SelectedChannel)    || 
	(SelectedChannel == 4 && (channel == 2 || channel == 3) )  || 
	(SelectedChannel == 5 && (channel == 0 || channel == 1) ) ) {



      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      //
      // Data-driven methods
      //
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      // if (pfmet > 20 && mpmet > 20 && mll > 12 && ptll > 45 && nextra == 0 && (dphiv || !sameflav)) { OLD CUTS
	
      // if( pfmet > 20 && mpmet > 20 && mll > 12&& nextra == 0 && (dphiv || !sameflav) && dyMVA && ptll>30 && (!sameflav || ptll>45) ) { 

      if( pfmet > 20 && mpmet > 20 && mll > 12&& nextra == 0 && (dphiv || !sameflav)  && ptll>30 && (!sameflav || ptll>45) ) { 



	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//
	// Z+jets
	//
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//if (dphiv && jetbin == jetChannel && bveto_mu && (bveto_ip && (nbjettche == 0 || njet > 3))) { OLD CUTS

	if( jetbin == jetChannel && bveto_mu && bveto_ip==1 && nbjettche==0 && ptll > 45) { 


	  // Loop over the metvar bins
	  //--------------------------------------------------------------------
	  for (size_t mc=0; mc<numberDYMVACuts; mc ++) {
	    
	    if ( jetbin == 0 ) { 

	      if ( dymva1 > DYMVACut_0j[mc] && fabs(mll - ZMASS) < 7.5) {
		hNinLooseZevents[mc]->Fill(1,totalW);
	      }

	      if (dymva1 > DYMVACut_0j[mc] && dymva1 < DYMVACut_0j[mc+1]) {   
		if (fabs(mll - ZMASS) < 7.5) {
		  hNinZevents[mc]   ->Fill(  1, totalW);
		  hMassInZevents[mc]->Fill(mll, totalW);
		}
		else if (fabs(mll - ZMASS) > 15) {  
		  hNoutZevents[mc]   ->Fill(  1, totalW);
		  hMassOutZevents[mc]->Fill(mll, totalW);
		}
	      }
	    }

	    if ( jetbin == 1 ) { 

	      if ( dymva1 > DYMVACut_1j[mc] && fabs(mll - ZMASS) < 7.5) {
		hNinLooseZevents[mc]->Fill(1,totalW);
	      }

	      if (dymva1 > DYMVACut_1j[mc] && dymva1 < DYMVACut_1j[mc+1]) {   
		if (fabs(mll - ZMASS) < 7.5) {
		  hNinZevents[mc]   ->Fill(  1, totalW);
		  hMassInZevents[mc]->Fill(mll, totalW);
		}
		else if (fabs(mll - ZMASS) > 15) {  
		  hNoutZevents[mc]   ->Fill(  1, totalW);
		  hMassOutZevents[mc]->Fill(mll, totalW);
		}
	      }
	    }


	  }
	}
      
      


	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//
	// Top
	//
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

	//   if (zveto  && metvar > (20 + 25*sameflav)) { OLD CUTS

	if ( zveto && dyMVA ) {

	  
	  // btag_eff denominator
	  if ((jetChannel == 0 && njet == 1 && nbjet == 1) || // jetBProbabilityBJetTags discriminator
	      (jetChannel == 1 && njet == 2 && jettche2 > 2.1) ||
	      (jetChannel == 2)) {

	    hNTopControlRegion->Fill(1, totalW);
	    hbTagDisNTopControlRegion->Fill(jettche2, totalW);
	    
	    // btag_eff numerator
	    if ((jetChannel == 0 && !bveto_nj30) || // bveto_nj30 == tche>2.1 && jetPt[10,30] && softMuonVeto for jetPt<30 
		(jetChannel == 1 && jettche1 > 2.1) ||
		(jetChannel == 2)) {
	      
	      hNTopTaggedTopControlRegion->Fill(1, totalW);
	      hbTagDisNTopTaggedTopControlRegion->Fill(jettche2, totalW);
	    }
	  }
	  
	}

	// Top-tagged events for ttbar estimation
	//----------------------------------------------------------------------
	if (zveto && dyMVA) {

	  if ((jetChannel == 0 && njet == 0 && !bveto) ||
	      (jetChannel == 1 && njet == 1 && bveto && jettche1 > 2.1) || // bveto == bveto_nj30 == tche>2.1 && jetPt[10,30] && softMuonVeto (no pt requirement)
	      (jetChannel == 2)) {
	    
	    hTopTaggedEvents->Fill(1, totalW);
	    hbTagDisTopTaggedEvents->Fill(jettche2, totalW);
	  }
	}
      }


      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      //
      // Main analisis
      //
      //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


  

      hWTrigger   ->Fill(1, totalW); 
      hWeffTrigger->Fill(1, efficiencyW);



	  hPtLepton1TwoLeptonsLevel      ->Fill(pt1,       totalW);
	  hPtLepton2TwoLeptonsLevel      ->Fill(pt2,       totalW);
	  hPtDiLeptonTwoLeptonsLevel     ->Fill(ptll,      totalW);
	  hMinvTwoLeptonsLevel           ->Fill(mll,       totalW);
	  hMtTwoLeptonsLevel             ->Fill(mth,       totalW);
	  hNJets30TwoLeptonsLevel        ->Fill(njet,      totalW);
	  hpfMetTwoLeptonsLevel          ->Fill(pfmet,     totalW);
	  hppfMetTwoLeptonsLevel         ->Fill(ppfmet,    totalW);
	  hchMetTwoLeptonsLevel          ->Fill(chmet,     totalW);
	  hpchMetTwoLeptonsLevel         ->Fill(pchmet,    totalW);
	  hpminMetTwoLeptonsLevel        ->Fill(mpmet,     totalW);
	  hDeltaRLeptonsTwoLeptonsLevel  ->Fill(drll,      totalW);
	  hDeltaPhiLeptonsTwoLeptonsLevel->Fill(dphill,    totalW);
	  hDPhiPtllJetTwoLeptonsLevel    ->Fill(dphilljet, totalW);



	  //if ( (pass2012ICHEP1 && !pass2012ICHEP2) || (!pass2012ICHEP1 && pass2012ICHEP2))    
	    h_TwoLeptons_TightFailEvents ->Fill(1, totalW); 
	  
	  if ( pass2012ICHEP1 && pass2012ICHEP2) 
	    h_TwoLeptons_TightTightEvents ->Fill(1, totalW); 
	  

	  if ( pass2012ICHEP1 || pass2012ICHEP2) 
	    h_TwoLeptons_TightLooseEvents ->Fill(1, totalW); 
	


    if (nextra == 0) {
			
	    hWExtraLepton->Fill(1, totalW);
	    hWeffExtraLepton->Fill(1, efficiencyW);
      
	    if (pfmet > 20 ) { // removed for differential xsec
	   
	      hWMetCut->Fill(1, totalW);
	      hWeffMetCut->Fill(1, efficiencyW);
	
	      if (mll > 12) {
	    
		hWLowMinv->Fill(1, totalW);
		hWeffLowMinv->Fill(1, efficiencyW);

		if (zveto==1 || !sameflav) {
		  
		  hWZVeto->Fill(1, totalW); 
		  hWeffZVeto->Fill(1, efficiencyW); 

		  if (mpmet > 20  && dyMVA ) { 

		
		    hWpMetCut->Fill(1, totalW);
		    hWeffpMetCut->Fill(1, efficiencyW);		  
		    

		    if (dphiv || !sameflav) {


		      hWDeltaPhiJet->Fill(1, totalW);
		      hWeffDeltaPhiJet->Fill(1, efficiencyW);


		      if (bveto_mu) { //--> third soft lepton with pt> 3GeV 
		      
			hWSoftMuVeto->Fill(1, totalW); 
			hWeffSoftMuVeto->Fill(1, efficiencyW);
		     

			 
			if ( ptll>30 && (!sameflav || ptll>45) ) {
			    
			  hWPtll->Fill(1, totalW);
			  hWeffPtll->Fill(1, efficiencyW);
			  

			  if (jetbin == jetChannel) {
			    
			    hWJetVeto->Fill(1, totalW);
			    hWeffJetVeto->Fill(1, efficiencyW);
			    

			    if (bveto_ip==1 &&  nbjettche==0) {
			      
			      hWTopTagging->Fill(1, totalW);
			      hWeffTopTagging->Fill(1, efficiencyW);

		       
			
			  
			  hPtLepton1WWLevel      ->Fill(pt1,       totalW);
			  hPtLepton2WWLevel      ->Fill(pt2,       totalW);
			  hPtDiLeptonWWLevel     ->Fill(ptll,      totalW);
			  hMinvWWLevel           ->Fill(mll,       totalW);
			  hMtWWLevel             ->Fill(mth,       totalW);
			  hNJets30WWLevel        ->Fill(njet,      totalW);
			  hpfMetWWLevel          ->Fill(pfmet,     totalW);
			  hppfMetWWLevel         ->Fill(ppfmet,    totalW);
			  hchMetWWLevel          ->Fill(chmet,     totalW);
			  hpchMetWWLevel         ->Fill(pchmet,    totalW);
			  hpminMetWWLevel        ->Fill(mpmet,     totalW);
			  hDeltaRLeptonsWWLevel  ->Fill(drll,      totalW);
			  hDeltaPhiLeptonsWWLevel->Fill(dphill,    totalW);
			  hDPhiPtllJetWWLevel    ->Fill(dphilljet, totalW);

			  hPtLepton1WWLevel_Diff  ->Fill(pt1,       totalW);
			  hEtaLepton1WWLevel_Diff ->Fill(eta1,      totalW);
			  hDileptonWWLevel_Diff   ->Fill(ptll,      totalW);
			  hMinvWWLevel_Diff       ->Fill(mll,       totalW);
			  hDeltaPhiWWLevel_Diff   ->Fill(dphill,    totalW);


			  //if ( (pass2012ICHEP1 && !pass2012ICHEP2) || (!pass2012ICHEP1 && pass2012ICHEP2))    
			    h_WWLevel_TightFailEvents ->Fill(1, totalW); 
			  
			   if ( (pass2012ICHEP1 && pass2012ICHEP2)) 
			     h_WWLevel_TightTightEvents ->Fill(1, totalW); 
			  
			    if ( pass2012ICHEP1 || pass2012ICHEP2) 
			      h_WWLevel_TightLooseEvents ->Fill(1, totalW); 
	


			}
			  }
		      }		      
		    }
		  }
		}
	      }
	    }
	  }
	}
      
      
  }
  
}
	  
  verbose = true;

  // Print
  //----------------------------------------------------------------------------
  if (verbose) {

    float norm = 1933235;

    /*
    cout << "Dilepton Level TF  " <<  h_TwoLeptons_TightFailEvents   ->GetEntries() << endl;
    cout << "Dilepton Level TT  " <<  h_TwoLeptons_TightTightEvents  ->GetEntries() << endl;
    cout << "Dilepton Level TL  " <<  h_TwoLeptons_TightLooseEvents  ->GetEntries() << endl;

    cout << "Dilepton Level TF  " <<  h_TwoLeptons_TightFailEvents   ->GetSumOfWeights() << endl;
    cout << "Dilepton Level TT  " <<  h_TwoLeptons_TightTightEvents  ->GetSumOfWeights() << endl;
    cout << "Dilepton Level TL  " <<  h_TwoLeptons_TightLooseEvents  ->GetSumOfWeights() << endl;


    cout << "WW Level TF  " <<  h_WWLevel_TightFailEvents   ->GetEntries() << endl;
    cout << "WW Level TT  " <<  h_WWLevel_TightTightEvents  ->GetEntries() << endl;
    cout << "WW Level TL  " <<  h_WWLevel_TightLooseEvents  ->GetEntries() << endl;

    cout << "WW Level TF  " <<  h_WWLevel_TightFailEvents   ->GetSumOfWeights() << endl;
    cout << "WW Level TT  " <<  h_WWLevel_TightTightEvents  ->GetSumOfWeights() << endl;
    cout << "WW Level TL  " <<  h_WWLevel_TightLooseEvents  ->GetSumOfWeights() << endl;

    */

    cout << endl;
    cout << " Expected number of RAW events for " << theSample.Data() << endl;
    cout << " ------------------+-----------" << endl;
    cout << " trigger           | " << hWTrigger    ->GetEntries() << endl;
    cout << " extra lepton veto | " << hWExtraLepton->GetEntries() << endl;
    cout << " MET cut           | " << hWMetCut     ->GetEntries() << endl;
    cout << " low minv cut      | " << hWLowMinv    ->GetEntries() << endl;
    cout << " Z veto            | " << hWZVeto      ->GetEntries() << endl;
    cout << " projected MET cut | " << hWpMetCut    ->GetEntries() << endl;
    cout << " DeltaPhiJet veto  | " << hWDeltaPhiJet->GetEntries() << endl;    
    cout << " soft muon veto    | " << hWSoftMuVeto ->GetEntries() << endl;
    cout << " ptll cut          | " << hWPtll       ->GetEntries() << endl;
    cout << " jet veto          | " << hWJetVeto    ->GetEntries() << endl;
    cout << " top tagging       | " << hWTopTagging ->GetEntries() << endl; 


    /*
   
    cout << hWTrigger    ->GetEntries() << endl;
    cout << hWExtraLepton->GetEntries() << endl;
    cout << hWMetCut     ->GetEntries() << endl;
    cout << hWLowMinv    ->GetEntries() << endl;
    cout << hWZVeto      ->GetEntries() << endl;
    cout << hWpMetCut    ->GetEntries() << endl;
    cout << hWDeltaPhiJet->GetEntries() << endl;    
    cout << hWSoftMuVeto ->GetEntries() << endl;
    cout << hWTopTagging ->GetEntries() << endl;
    cout << hWPtll       ->GetEntries() << endl;
    cout << hWJetVeto    ->GetEntries() << endl;
    


    
    cout << endl;
    */

    /*
    
    if (!theSample.Contains("Data")) {
      cout << endl;
      cout << " Normalized to " << luminosity << " 1/fb" << endl;
      cout << " ------------------+-----------" << endl;
      cout << " trigger           | " << hWTrigger    ->GetSumOfWeights() << endl;
      cout << " extra lepton veto | " << hWExtraLepton->GetSumOfWeights() << endl;
      cout << " MET cut           | " << hWMetCut     ->GetSumOfWeights() << endl;
      cout << " low minv cut      | " << hWLowMinv    ->GetSumOfWeights() << endl;
      cout << " Z veto            | " << hWZVeto      ->GetSumOfWeights() << endl;
      cout << " projected MET cut | " << hWpMetCut    ->GetSumOfWeights() << endl;
      cout << " DeltaPhiJet veto  | " << hWDeltaPhiJet->GetSumOfWeights() << endl;     
      cout << " soft muon veto    | " << hWSoftMuVeto ->GetSumOfWeights() << endl;
      cout << " jet veto          | " << hWJetVeto    ->GetSumOfWeights() << endl;
      cout << " top tagging       | " << hWTopTagging ->GetSumOfWeights() << endl; 

      cout << endl;

          }
 
    */


    //cout << hWTopTagging->GetBinContent(2) << " +- " << hWTopTagging->GetBinError(2) << endl;	 
 }


  // Save the histograms
  //----------------------------------------------------------------------------
  output->cd();
  output->Write("", TObject::kOverwrite);
  output->Close();
  
}
示例#25
0
void StatisticTest(string statTest, double & testEstimator, double & testPvalue, TString cut, TChain * chain, TString variable, TF1 * f, double RangeMin, double RangeMax) //, TH1D * hh, int nbOfBins)
{
	//for Kolmogorov-Smirnov test you have put statTest = "KS"
	//for Anderson-Darling statTest = "AD"


	// ------------------------------------------ //	
	// create a table of our variable (with cuts) //
	// ------------------------------------------ //

	TChain * ReducedChain = (TChain *) chain->CopyTree(cut);
	float value;
        ReducedChain->SetBranchAddress(variable,&value);

	int nEvents = ReducedChain->GetEntries();

	Double_t * sample = new Double_t[nEvents];

	//Double_t * sample2 = new Double_t[nbOfBins];

	for (int ievt = 0 ; ievt < nEvents; ievt++)
        {
                ReducedChain->GetEntry(ievt);
                //sample.push_back(value);
        	sample[ievt] = value;
	}

/*
	for (int ievt = 0 ; ievt < nbOfBins; ievt++)
	{
		sample2[ievt] = hh->GetBinContent(ievt + 1);
		//cout<<endl<<"sample2[ievt] = "<<sample2[ievt]<<endl;
	}
*/


	// -------------------------------------- //        
        // Transform the TF1 and create a GoFTest //
        // -------------------------------------- //	

	ROOT::Math::WrappedTF1 wf1(*f);

	ROOT::Math::GoFTest* goftest_1 = new ROOT::Math::GoFTest(nEvents, sample, wf1, ROOT::Math::GoFTest::kPDF, RangeMin, RangeMax);
	//ROOT::Math::GoFTest* goftest_1 = new ROOT::Math::GoFTest(nbOfBins, sample2, wf1, ROOT::Math::GoFTest::kCDF, RangeMin, RangeMax);

	// ---------------------------------------- //        
        // Return the test statistic and the pvalue //
        // ---------------------------------------- //


	if(statTest == "KS")
	{
		testEstimator = goftest_1-> KolmogorovSmirnovTest("t");
		testPvalue = goftest_1-> KolmogorovSmirnovTest();
	}

	if(statTest == "AD")
        {
                testEstimator = goftest_1-> AndersonDarlingTest("t");
                testPvalue = goftest_1-> AndersonDarlingTest();
        }


	delete sample;
	delete goftest_1;
	sample = 0;
	goftest_1 = 0;

}
int process(TChain *trigOnlyChain, MAPJson *jsonMap, MAPTrigOnly mapTo, TString nameChain, TString file, int iFile, int nEntries,
            TString dirIn, TString dirOut, TString usr_hlt, int iJson, 
	    bool GetTrigOnly, bool debug) {

  // TrigOnly MAP //                                                                                          
  MAPTrigOnly::iterator iterMapTo;
  pair<int,int> runevtTo;
  int iEntryTo=-1;

  // OUTPUT FILE //
  if(debug) cout << "--- define output file : " ;
  ostringstream ossi("");
  ossi << iFile ;
  //                                                                                                                                 
  TFile *outfile = new TFile(dirIn+"spikes_"+ossi.str()+".root","RECREATE");
  //ofstream outcheckdata(dirIn+"logcheckdata_"+ossi.str()+".txt",ios::out);
  ofstream outlog(dirOut+"/logs/log_"+ossi.str()+".txt",ios::out);
  ofstream outcheckL1(dirOut+"/checkL1/checkL1_"+ossi.str()+".txt",ios::out);

  //outlog << "TRY TRY TRY" << endl;
  //outcheckL1 << "TRY TRY TRY" << endl;
  //outcheckdata << "TRY TRY TRY" << endl;

  if(debug) cout << "spikes_"+ossi.str()+".root" << endl;
  ossi.str("");

  // INPUT TREE //                                                                                                                   
  if(debug) cout << "--- add data trees to myChain" << endl;
  TChain * myChain = new TChain(nameChain);
  myChain->Add(file);

  // VARIABLES //                                                                                      
  int nEvent, nRun, nLumi ; // data                                                      
  int nEvent_To, nRun_To, nLumi_To; // trigOnly
  // Vertices //
  int vtx_N;
  double _vtx_x[200], _vtx_y[200], _vtx_z[200];
  double _vtx_normalizedChi2[200], _vtx_ndof[200], _vtx_nTracks[200], _vtx_d0[200];

  // Trigger Paths //                                                                           
  int trig_hltInfo[250];
  //int _trig_isEleHLTpath;                                                                                    
  int trig_HLT_path[4]; // unbias, EG5, EG8, EG12
  char trig_fired_names[5000];
  vector<string> m_HLT_pathsV;
  vector<string> m_HLT_triggered;
  vector<int> m_HLT_pathsV_check;

  // Spikes
  int spike_N,spike_TTieta[5000], spike_TTiphi[5000], spike_Rieta[5000], spike_Riphi[5000], spike_severityLevel[5000], 
    spike_outOfTime[5000], spike_TT_sFGVB[5000], spike_TT_adc[5000], spike_TT_sFGVB_E[5000][5], spike_TT_adc_E[5000][5],
    spike_TT_t[5000], spike_TT_tE[5000];
  double  spike_Et[5000], spike_eta[5000], spike_phi[5000], spike_theta[5000];
  int spike_RCTL1iso[5000], spike_RCTL1noniso[5000], spike_RCTL1iso_To[5000], spike_RCTL1noniso_To[5000], 
    spike_RCTL1iso_M_To[5000], spike_RCTL1noniso_M_To[5000],
    spike_maxEGtrig[5000], spike_maxEGtrig_To[5000], spike_maxEGtrig_M_To[5000];
  
  int spike_out_TTieta, spike_out_TTiphi, spike_out_Rieta, spike_out_Riphi, spike_out_severityLevel, 
    spike_out_outOfTime, spike_out_TT_sFGVB, spike_out_TT_adc, spike_out_TT_sFGVB_E[5], spike_out_TT_adc_E[5],
    spike_out_TT_t, spike_out_TT_tE;
  double  spike_out_Et, spike_out_eta, spike_out_phi, spike_out_theta;
  int spike_out_RCTL1iso, spike_out_RCTL1noniso, spike_out_RCTL1iso_To, spike_out_RCTL1noniso_To, 
    spike_out_RCTL1iso_M_To, spike_out_RCTL1noniso_M_To,
    spike_out_maxEGtrig, spike_out_maxEGtrig_To, spike_out_maxEGtrig_M_To;
  
  // TP info
  const int nTow = 4032;
  int trig_tower_N,trig_tower_ieta[nTow],trig_tower_iphi[nTow],trig_tower_adc[nTow],trig_tower_sFGVB[nTow],trig_tower_FG[nTow];
  int trig_tower_N_M,trig_tower_ieta_M[nTow],trig_tower_iphi_M[nTow],trig_tower_adc_M[nTow],trig_tower_sFGVB_M[nTow],
    trig_tower_FG_M[nTow];
  int trig_tower_N_E,trig_tower_ieta_E[nTow],trig_tower_iphi_E[nTow],trig_tower_adc_E[nTow][5],trig_tower_sFGVB_E[nTow][5],
    trig_tower_FG_E[nTow][5];

  // HCAL TP //
  int trig_tower_hcal_N, trig_tower_hcal_ieta[4032], trig_tower_hcal_iphi[4032], trig_tower_hcal_FG[4032],trig_tower_hcal_et[4032];

  // L1 Candidates //                                                                                                             
  int trig_L1emIso_N, trig_L1emNonIso_N; 
  int trig_L1emIso_N_To, trig_L1emNonIso_N_To, trig_L1emIso_N_M_To, trig_L1emNonIso_N_M_To;

  // L1 candidates info //
  int trig_L1emIso_ieta[4], trig_L1emIso_iphi[4], trig_L1emIso_rank[4];
  int trig_L1emNonIso_ieta[4], trig_L1emNonIso_iphi[4], trig_L1emNonIso_rank[4];

  int trig_L1emIso_ieta_To[4], trig_L1emIso_iphi_To[4], trig_L1emIso_rank_To[4];
  int trig_L1emNonIso_ieta_To[4], trig_L1emNonIso_iphi_To[4], trig_L1emNonIso_rank_To[4];
  int trig_L1emIso_ieta_M_To[4], trig_L1emIso_iphi_M_To[4], trig_L1emIso_rank_M_To[4];
  int trig_L1emNonIso_ieta_M_To[4], trig_L1emNonIso_iphi_M_To[4], trig_L1emNonIso_rank_M_To[4];

  // INITIALIZATION //                                                                                                               
  //                                                                                                                                 
  // Global                                                                                                                        
  nEvent = 0;
  nRun = 0;
  nLumi = 0;
  //                                                                                                                          
  // Vertices                                                                                                                   
  vtx_N = 0;
  for(int iv=0;iv<200;iv++) {
    _vtx_normalizedChi2[iv] = 0.;
    _vtx_ndof[iv] = 0.;
    _vtx_nTracks[iv] = 0.;
    _vtx_d0[iv] = 0.;
    _vtx_x[iv] = 0.;
    _vtx_y[iv] = 0.;
    _vtx_z[iv] = 0.;
  }
  //                                                                                                                        
  // L1 candidates                                                                                              
  trig_L1emIso_N    = 0;
  trig_L1emNonIso_N = 0;
  trig_L1emIso_N_M_To  = 0;
  trig_L1emNonIso_N_M_To = 0;

  for(int il1=0 ; il1<4 ; il1++) {
    trig_L1emIso_ieta[il1] = 0;
    trig_L1emIso_iphi[il1] = 0;
    trig_L1emIso_rank[il1] = 0;
    trig_L1emNonIso_ieta[il1] = 0;
    trig_L1emNonIso_iphi[il1] = 0;
    trig_L1emNonIso_rank[il1] = 0;

    trig_L1emIso_ieta_To[il1] = 0;
    trig_L1emIso_iphi_To[il1] = 0;
    trig_L1emIso_rank_To[il1] = 0;
    trig_L1emNonIso_ieta_To[il1] = 0;
    trig_L1emNonIso_iphi_To[il1] = 0;
    trig_L1emNonIso_rank_To[il1] = 0;

    trig_L1emIso_ieta_M_To[il1] = 0;
    trig_L1emIso_iphi_M_To[il1] = 0;
    trig_L1emIso_rank_M_To[il1] = 0;
    trig_L1emNonIso_ieta_M_To[il1] = 0;
    trig_L1emNonIso_iphi_M_To[il1] = 0;
    trig_L1emNonIso_rank_M_To[il1] = 0;
  }

  // Trigger towers              
  trig_tower_N = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta[iTow] = trig_tower_iphi[iTow]  = -999;
    trig_tower_adc[iTow]  = trig_tower_sFGVB[iTow] = trig_tower_FG[iTow] = -999;
  }
  trig_tower_N_M = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta_M[iTow] = trig_tower_iphi_M[iTow]  = -999;
    trig_tower_adc_M[iTow]  = trig_tower_sFGVB_M[iTow] = trig_tower_FG_M[iTow] = -999;
  }
  trig_tower_N_E = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_ieta_E[iTow] = trig_tower_iphi_E[iTow] = -999;
    for(int i=0 ; i<5 ; i++)
      trig_tower_adc_E[iTow][i] = trig_tower_sFGVB_E[iTow][i] = trig_tower_FG_E[iTow][i] = -999;
  }
  trig_tower_hcal_N = 0;
  for(int iTow=0 ; iTow<nTow ; iTow++) {
    trig_tower_hcal_ieta[iTow] = trig_tower_hcal_iphi[iTow]  = -999;
    trig_tower_hcal_FG[iTow]  = trig_tower_hcal_et[iTow] = -999;
  }

  // SPIKES //
  spike_N = 0;  
  for(int isp=0 ; isp<5000 ; isp++) {
    spike_outOfTime[isp] = -999;
    spike_severityLevel[isp] = -999 ;
    //spike_SwissCross[isp] = -999 ;
    spike_Et[isp] = -999 ;
    spike_phi[isp] = -999 ;
    spike_eta[isp] = -999 ;
    spike_theta[isp] = -999 ;
    spike_TTiphi[isp] = -999 ;
    spike_TTieta[isp] = -999 ;
    spike_TT_t[isp] = -999 ;
    spike_TT_tE[isp] = -999 ;
    spike_TT_sFGVB[isp] = -999 ;
    spike_TT_adc[isp] = -999 ;
    spike_Riphi[isp] = -999 ;
    spike_Rieta[isp] = -999 ;

    for(int i=0;i<5;i++) {
      spike_TT_sFGVB_E[isp][i] = -999 ;
      spike_TT_adc_E[isp][i]   = -999 ;
    }
  }

  spike_out_outOfTime = -999;
  spike_out_severityLevel = -999 ;
  //spike_out_SwissCross = -999 ;
  spike_out_Et = -999 ;
  spike_out_phi = -999 ;
  spike_out_eta = -999 ;
  spike_out_theta = -999 ;
  spike_out_TTiphi = -999 ;
  spike_out_TTieta = -999 ;
  spike_out_TT_t = -999 ;
  spike_out_TT_tE = -999 ;
  spike_out_TT_sFGVB = -999 ;
  spike_out_TT_adc = -999 ;
  spike_out_Riphi = -999 ;
  spike_out_Rieta = -999 ;
  
  for(int i=0;i<5;i++) {
    spike_out_TT_sFGVB_E[i] = -999 ;
    spike_out_TT_adc_E[i]   = -999 ;
  }

  myChain->SetBranchAddress("nEvent",&nEvent);
  myChain->SetBranchAddress("nRun",&nRun);
  myChain->SetBranchAddress("nLumi",&nLumi);

  // Vertices
  myChain->SetBranchAddress("vtx_N",&vtx_N);

  //myChain->SetBranchAddress("trig_HLT_path",&trig_HLT_path);
  myChain->SetBranchAddress("trig_fired_names",&trig_fired_names);
  myChain->SetBranchAddress("trig_hltInfo",&trig_hltInfo);

  // L1 candidates                             
  myChain->SetBranchAddress("trig_L1emIso_N", &trig_L1emIso_N);
  myChain->SetBranchAddress("trig_L1emIso_ieta", &trig_L1emIso_ieta);
  myChain->SetBranchAddress("trig_L1emIso_iphi", &trig_L1emIso_iphi);
  myChain->SetBranchAddress("trig_L1emIso_rank", &trig_L1emIso_rank);

  myChain->SetBranchAddress("trig_L1emNonIso_N", &trig_L1emNonIso_N);
  myChain->SetBranchAddress("trig_L1emNonIso_ieta", &trig_L1emNonIso_ieta);
  myChain->SetBranchAddress("trig_L1emNonIso_iphi", &trig_L1emNonIso_iphi);
  myChain->SetBranchAddress("trig_L1emNonIso_rank", &trig_L1emNonIso_rank);

  // Spikes
  myChain->SetBranchAddress("spike_N",&spike_N);
  myChain->SetBranchAddress("spike_TTieta",&spike_TTieta);
  myChain->SetBranchAddress("spike_TTiphi",&spike_TTiphi);
  myChain->SetBranchAddress("spike_Rieta",&spike_Rieta);
  myChain->SetBranchAddress("spike_Riphi",&spike_Riphi);
  myChain->SetBranchAddress("spike_severityLevel",&spike_severityLevel);
  myChain->SetBranchAddress("spike_outOfTime",&spike_outOfTime);
  myChain->SetBranchAddress("spike_Et",&spike_Et);
  myChain->SetBranchAddress("spike_eta",&spike_eta);
  myChain->SetBranchAddress("spike_phi",&spike_phi);
  myChain->SetBranchAddress("spike_theta",&spike_theta);

  // TrigOnly Chain //
  trigOnlyChain->SetBranchAddress("nRun", &nRun_To);
  trigOnlyChain->SetBranchAddress("nLumi", &nLumi_To);
  trigOnlyChain->SetBranchAddress("nEvent", &nEvent_To);

  trigOnlyChain->SetBranchAddress("trig_HLT_path",&trig_HLT_path);

  trigOnlyChain->SetBranchAddress("trig_tower_N", &trig_tower_N);
  trigOnlyChain->SetBranchAddress("trig_tower_ieta",  &trig_tower_ieta);
  trigOnlyChain->SetBranchAddress("trig_tower_iphi",  &trig_tower_iphi);
  trigOnlyChain->SetBranchAddress("trig_tower_adc",  &trig_tower_adc);
  trigOnlyChain->SetBranchAddress("trig_tower_sFGVB",  &trig_tower_sFGVB);
  //trigOnlyChain->SetBranchAddress("trig_tower_FG",  &trig_tower_FG);

  trigOnlyChain->SetBranchAddress("trig_tower_N_E",     &trig_tower_N_E);
  trigOnlyChain->SetBranchAddress("trig_tower_ieta_E",  &trig_tower_ieta_E);
  trigOnlyChain->SetBranchAddress("trig_tower_iphi_E",  &trig_tower_iphi_E);
  trigOnlyChain->SetBranchAddress("trig_tower_adc_E",   &trig_tower_adc_E);
  trigOnlyChain->SetBranchAddress("trig_tower_sFGVB_E", &trig_tower_sFGVB_E);
  //trigOnlyChain->SetBranchAddress("trig_tower_FG_E", &trig_tower_FG_E);

  // HCAL TP                                                        
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_N", &trig_tower_hcal_N);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_ieta",  &trig_tower_hcal_ieta);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_iphi",  &trig_tower_hcal_iphi);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_et",  &trig_tower_hcal_et);
  trigOnlyChain->SetBranchAddress("trig_tower_hcal_FG",  &trig_tower_hcal_FG);

  // L1 candidates collections                        
  trigOnlyChain->SetBranchAddress("trig_L1emIso_N", &trig_L1emIso_N_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_ieta", &trig_L1emIso_ieta_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_iphi", &trig_L1emIso_iphi_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_rank", &trig_L1emIso_rank_To);

  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_N", &trig_L1emNonIso_N_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_ieta", &trig_L1emNonIso_ieta_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_iphi", &trig_L1emNonIso_iphi_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_rank", &trig_L1emNonIso_rank_To);

  trigOnlyChain->SetBranchAddress("trig_L1emIso_N_M", &trig_L1emIso_N_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_ieta_M", &trig_L1emIso_ieta_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_iphi_M", &trig_L1emIso_iphi_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emIso_rank_M", &trig_L1emIso_rank_M_To);

  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_N_M", &trig_L1emNonIso_N_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_ieta_M", &trig_L1emNonIso_ieta_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_iphi_M", &trig_L1emNonIso_iphi_M_To);
  trigOnlyChain->SetBranchAddress("trig_L1emNonIso_rank_M", &trig_L1emNonIso_rank_M_To);


  // OUTPUT TREE //

  TTree * outtree = new TTree("Spikes","Spikes");
  // General informations //
  outtree->Branch("nRun",&nRun,"nRun/I");
  outtree->Branch("nLumi",&nLumi,"nLumi/I");
  outtree->Branch("nEvent",&nEvent,"nEvent/I");

  // Vertices //
  outtree->Branch("vtx_N",&vtx_N,"vtx_N/I");

  outtree->Branch("trig_HLT_path",&trig_HLT_path,"trig_HLT_path[4]/I");
  outtree->Branch("trig_fired_names",&trig_fired_names,"trig_fired_names[5000]/C");
  outtree->Branch("trig_hltInfo",&trig_hltInfo,"trig_hltInfo[250]/I");

  // Trigger towers //
  outtree->Branch("trig_tower_N",&trig_tower_N,"trig_tower_N/I");
  outtree->Branch("trig_tower_ieta",&trig_tower_ieta,"trig_tower_ieta[4032]/I");
  outtree->Branch("trig_tower_iphi",&trig_tower_iphi,"trig_tower_iphi[4032]/I");
  outtree->Branch("trig_tower_adc",&trig_tower_adc,"trig_tower_adc[4032]/I");
  outtree->Branch("trig_tower_sFGVB",&trig_tower_sFGVB,"trig_tower_sFGVB[4032]/I");
  outtree->Branch("trig_tower_FG",&trig_tower_FG,"trig_tower_FG[4032]/I");
  //                                                               
  outtree->Branch("trig_tower_N_E",&trig_tower_N_E,"trig_tower_N_E/I");
  outtree->Branch("trig_tower_ieta_E",&trig_tower_ieta_E,"trig_tower_ieta_E[4032]/I");
  outtree->Branch("trig_tower_iphi_E",&trig_tower_iphi_E,"trig_tower_iphi_E[4032]/I");
  outtree->Branch("trig_tower_adc_E",&trig_tower_adc_E,"trig_tower_adc_E[4032][5]/I");
  outtree->Branch("trig_tower_sFGVB_E",&trig_tower_sFGVB_E,"trig_tower_sFGVB_E[4032][5]/I");
  outtree->Branch("trig_tower_FG_E",&trig_tower_FG_E,"trig_tower_FG_E[4032][5]/I");

  // HCAL TP                                 
  outtree->Branch("trig_tower_hcal_N", &trig_tower_hcal_N, "trig_tower_hcal_N/I");
  outtree->Branch("trig_tower_hcal_ieta",  &trig_tower_hcal_ieta,  "trig_tower_hcal_ieta[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_iphi",  &trig_tower_hcal_iphi,  "trig_tower_hcal_iphi[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_et",  &trig_tower_hcal_et,  "trig_tower_hcal_et[trig_tower_N]/I");
  outtree->Branch("trig_tower_hcal_FG",  &trig_tower_hcal_FG,  "trig_tower_hcal_FG[trig_tower_N]/I");

  // L1 candidates from Data
  outtree->Branch("trig_L1emIso_N",     &trig_L1emIso_N,     "trig_L1emIso_N/I");
  outtree->Branch("trig_L1emIso_ieta",  &trig_L1emIso_ieta,  "trig_L1emIso_ieta[4]/I");
  outtree->Branch("trig_L1emIso_iphi",  &trig_L1emIso_iphi,  "trig_L1emIso_iphi[4]/I");
  outtree->Branch("trig_L1emIso_rank",  &trig_L1emIso_rank,  "trig_L1emIso_rank[4]/I");

  outtree->Branch("trig_L1emNonIso_N",     &trig_L1emNonIso_N,     "trig_L1emNonIso_N/I");
  outtree->Branch("trig_L1emNonIso_ieta",  &trig_L1emNonIso_ieta,  "trig_L1emNonIso_ieta[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi",  &trig_L1emNonIso_iphi,  "trig_L1emNonIso_iphi[4]/I");
  outtree->Branch("trig_L1emNonIso_rank",  &trig_L1emNonIso_rank,  "trig_L1emNonIso_rank[4]/I");
  
  // L1 candidates from TrigOnly 
  outtree->Branch("trig_L1emIso_N_To",     &trig_L1emIso_N_To,     "trig_L1emIso_N_To/I");
  outtree->Branch("trig_L1emIso_ieta_To",  &trig_L1emIso_ieta_To,  "trig_L1emIso_ieta_To[4]/I");
  outtree->Branch("trig_L1emIso_iphi_To",  &trig_L1emIso_iphi_To,  "trig_L1emIso_iphi_To[4]/I");
  outtree->Branch("trig_L1emIso_rank_To",  &trig_L1emIso_rank_To,  "trig_L1emIso_rank_To[4]/I");
  //                                                                                                   
  outtree->Branch("trig_L1emNonIso_N_To", &trig_L1emNonIso_N_To, "trig_L1emNonIso_N_To/I");
  outtree->Branch("trig_L1emNonIso_ieta_To", &trig_L1emNonIso_ieta_To, "trig_L1emNonIso_ieta_To[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi_To", &trig_L1emNonIso_iphi_To, "trig_L1emNonIso_iphi_To[4]/I");
  outtree->Branch("trig_L1emNonIso_rank_To", &trig_L1emNonIso_rank_To, "trig_L1emNonIso_rank_To[4]/I");

  outtree->Branch("trig_L1emIso_N_M_To",     &trig_L1emIso_N_M_To,     "trig_L1emIso_N_M_To/I");
  outtree->Branch("trig_L1emIso_ieta_M_To",  &trig_L1emIso_ieta_M_To,  "trig_L1emIso_ieta_M_To[4]/I");
  outtree->Branch("trig_L1emIso_iphi_M_To",  &trig_L1emIso_iphi_M_To,  "trig_L1emIso_iphi_M_To[4]/I");
  outtree->Branch("trig_L1emIso_rank_M_To",  &trig_L1emIso_rank_M_To,  "trig_L1emIso_rank_M_To[4]/I");
  //                                                                                
  outtree->Branch("trig_L1emNonIso_N_M_To", &trig_L1emNonIso_N_M_To, "trig_L1emNonIso_N_M_To/I");
  outtree->Branch("trig_L1emNonIso_ieta_M_To", &trig_L1emNonIso_ieta_M_To, "trig_L1emNonIso_ieta_M_To[4]/I");
  outtree->Branch("trig_L1emNonIso_iphi_M_To", &trig_L1emNonIso_iphi_M_To, "trig_L1emNonIso_iphi_M_To[4]/I");
  outtree->Branch("trig_L1emNonIso_rank_M_To", &trig_L1emNonIso_rank_M_To, "trig_L1emNonIso_rank_M_To[4]/I");

  outtree->Branch("spike_TTieta",&spike_out_TTieta,"spike_TTieta/I");
  outtree->Branch("spike_TTiphi",&spike_out_TTiphi,"spike_TTiphi/I");
  //
  outtree->Branch("spike_TT_t",&spike_out_TT_t,"spike_TT_t/I");
  outtree->Branch("spike_TT_sFGVB",&spike_out_TT_sFGVB,"spike_TT_sFGVB/I");
  outtree->Branch("spike_TT_adc",&spike_out_TT_adc,"spike_TT_adc/I");
  outtree->Branch("spike_TT_tE",&spike_out_TT_tE,"spike_TT_tE/I");
  outtree->Branch("spike_TT_sFGVB_E",&spike_out_TT_sFGVB_E,"spike_TT_sFGVB[5]/I");
  outtree->Branch("spike_TT_adc_E",&spike_out_TT_adc_E,"spike_TT_adc[5]/I");
  //
  outtree->Branch("spike_Rieta",&spike_out_Rieta,"spike_Rieta/I");
  outtree->Branch("spike_Riphi",&spike_out_Riphi,"spike_Riphi/I");
  outtree->Branch("spike_severityLevel",&spike_out_severityLevel,"spike_severityLevel/I");
  outtree->Branch("spike_outOfTime",&spike_out_outOfTime,"spike_outOfTime/I");
  outtree->Branch("spike_Et",&spike_out_Et,"spike_Et/D");
  outtree->Branch("spike_eta",&spike_out_eta,"spike_eta/D");
  outtree->Branch("spike_phi",&spike_out_phi,"spike_phi/D");
  outtree->Branch("spike_theta",&spike_out_theta,"spike_theta/D");
  //
  outtree->Branch("spike_maxEGtrig",&spike_out_maxEGtrig,"spike_maxEGtrig/I");
  outtree->Branch("spike_maxEGtrig_To",&spike_out_maxEGtrig_To,"spike_maxEGtrig_To/I");
  outtree->Branch("spike_maxEGtrig_M_To",&spike_out_maxEGtrig_M_To,"spike_maxEGtrig_M_To/I");
  //
  outtree->Branch("spike_RCTL1iso",&spike_out_RCTL1iso,"spike_RCTL1iso/I");
  outtree->Branch("spike_RCTL1noniso",&spike_out_RCTL1noniso,"spike_RCTL1noniso/I");
  outtree->Branch("spike_RCTL1iso_To",&spike_out_RCTL1iso_To,"spike_RCTL1iso_To/I");
  outtree->Branch("spike_RCTL1noniso_To",&spike_out_RCTL1noniso_To,"spike_RCTL1noniso_To/I");
  outtree->Branch("spike_RCTL1iso_M_To",&spike_out_RCTL1iso_M_To,"spike_RCTL1iso_M_To/I");
  outtree->Branch("spike_RCTL1noniso_M_To",&spike_out_RCTL1noniso_M_To,"spike_RCTL1noniso_M_To/I");

  // Variables
  bool isGoodRun, evt_trig_EG12;
  TString filename;

  // Map TT
  MAPTT adcTT;
  MAPTT::iterator iterTT;
  pair<int,int> coords;
  int TT_t, TT_tE;

  int numEntries = myChain->GetEntries () ;
  int nProcess = numEntries;
  if(nEntries>=0 && nEntries<numEntries)
    nProcess = nEntries;

  int nCurrentRun = -999;
  outlog << "will process " << nProcess << "/" << numEntries << "entries" << endl;

  // Loop over entries //
  for (int iEvent = 0 ; iEvent < nProcess ; iEvent++ ) {
    
    // TP Initialization                                                                                                           
    trig_tower_N = 0;
    for(int iTow=0 ; iTow<nTow ; iTow++) {
      trig_tower_ieta[iTow] = trig_tower_iphi[iTow]  = -999;
      trig_tower_adc[iTow]  = trig_tower_sFGVB[iTow] = -999;
    }
    trig_tower_N_M = 0;
    for(int iTow=0 ; iTow<nTow ; iTow++) {
      trig_tower_ieta_M[iTow] = trig_tower_iphi_M[iTow]  = -999;
      trig_tower_adc_M[iTow]  = trig_tower_sFGVB_M[iTow] = -999;
    }
    trig_tower_N_E = 0;
    for(int iTow=0 ; iTow<nTow ; iTow++) {
      trig_tower_ieta_E[iTow] = trig_tower_iphi_E[iTow] = -999;
      for(int i=0 ; i<5 ; i++)
	trig_tower_adc_E[iTow][i] = trig_tower_sFGVB_E[iTow][i] = -999;
    }

    // L1 candidates                                                                                                               
    trig_L1emIso_N    = 0;
    trig_L1emNonIso_N = 0;
    trig_L1emIso_N_M_To  = 0;
    trig_L1emNonIso_N_M_To = 0;
    trig_L1emIso_N_To  = 0;
    trig_L1emNonIso_N_To = 0;

    for(int il1=0 ; il1<4 ; il1++) {
      trig_L1emIso_ieta[il1] = 0;
      trig_L1emIso_iphi[il1] = 0;
      trig_L1emIso_rank[il1] = 0;
      trig_L1emNonIso_ieta[il1] = 0;
      trig_L1emNonIso_iphi[il1] = 0;
      trig_L1emNonIso_rank[il1] = 0;

      trig_L1emIso_ieta_To[il1] = 0;
      trig_L1emIso_iphi_To[il1] = 0;
      trig_L1emIso_rank_To[il1] = 0;
      trig_L1emNonIso_ieta_To[il1] = 0;
      trig_L1emNonIso_iphi_To[il1] = 0;
      trig_L1emNonIso_rank_To[il1] = 0;

      trig_L1emNonIso_ieta_M_To[il1] = 0;
      trig_L1emNonIso_iphi_M_To[il1] = 0;
      trig_L1emNonIso_rank_M_To[il1] = 0;
      trig_L1emIso_ieta_M_To[il1] = 0;
      trig_L1emIso_iphi_M_To[il1] = 0;
      trig_L1emIso_rank_M_To[il1] = 0;
    }

    for(int isp=0 ; isp<5000 ; isp++) {
      spike_outOfTime[isp] = -999;
      spike_severityLevel[isp] = -999 ;
      //spike_SwissCross[isp] = -999 ;
      spike_Et[isp] = -999 ;
      spike_phi[isp] = -999 ;
      spike_eta[isp] = -999 ;
      spike_theta[isp] = -999 ;
      spike_TTiphi[isp] = -999 ;
      spike_TTieta[isp] = -999 ;
      spike_TT_t[isp] = -999 ;
      spike_TT_tE[isp] = -999 ;
      spike_TT_sFGVB[isp] = -999 ;
      spike_TT_adc[isp] = -999 ;
      spike_Riphi[isp] = -999 ;
      spike_Rieta[isp] = -999 ;

      for(int i=0;i<5;i++) {
	spike_TT_sFGVB_E[isp][i] = -999 ;
	spike_TT_adc_E[isp][i]   = -999 ;
      }
    }
    
    myChain->GetEntry (iEvent) ;

    // show processed file                                                                                                         
    if(iEvent==0) {
      filename = myChain->GetFile()->GetName() ;
      outlog << "File : " << filename << endl << endl;
    }
    else if( filename != myChain->GetFile()->GetName() ) {
      filename = myChain->GetFile()->GetName() ;
      outlog << "File : " << myChain->GetFile()->GetName() << endl << endl;
    }

    // show current run/iCat processed                                                                                             
    if(iEvent==0) {
      nCurrentRun = nRun ;
      outlog << "nRun=" << nRun << endl;
    }
    else if(nRun!=nCurrentRun) {
      nCurrentRun=nRun ;
      outlog << "nRun=" << nRun << endl;
    }

    if(debug) cout << "iJson = " << iJson << endl;
    if( iJson>-1 && iJson<5) {
      isGoodRun = AcceptEventByRunAndLumiSection(nRun, nLumi, jsonMap[iJson]);
      if(!isGoodRun) {
	outlog << "failed JSON" << endl;
	continue;
      }
    }

    // JSON selection ////////////////////////////////////////////
    if(debug) cout << "iJson = " << iJson << endl;
    if( iJson>-1 && iJson<5) {
      isGoodRun = false;
      isGoodRun = AcceptEventByRunAndLumiSection(nRun, nLumi, jsonMap[iJson]);
      if(!isGoodRun) {
	outlog << "failed JSON" << endl;
	continue;
      }
    }
    
    // HLT selection //
    if(usr_hlt=="unbias")
      if(trig_HLT_path[0]==0) continue;
    
    // Map the trigger tower //////////////////////////////////////////////////////////////////////
    adcTT.clear();
    for(int t=0 ; t<trig_tower_N ; t++) {
      coords = make_pair( trig_tower_ieta[t] , trig_tower_iphi[t] );
      adcTT[coords].first = t;
    }
    for(int t=0 ; t<trig_tower_N_E ; t++) {
      coords = make_pair( trig_tower_ieta_E[t] , trig_tower_iphi_E[t] );
      iterTT = adcTT.find( coords );

      if( iterTT != adcTT.end() ) {
	adcTT[coords].second = t;
      }
    }
    
    // Load trigOnly information ////////////////////////////////////////////////////////////////////                              
    if( GetTrigOnly ) {

      runevtTo = make_pair(nRun,nEvent);
      iterMapTo = mapTo.find( runevtTo );
      //                                                                                                                           
      if( iterMapTo != mapTo.end() )
	iEntryTo = mapTo[ runevtTo ];
      else iEntryTo = -1;
      //                                                                                                                           
      outlog << "trigOnly info : nRun=" << nRun << " | nEvent=" << nEvent << " | iEntryTo=" << iEntryTo << endl;
      //                                                                                                                           
      if(iEntryTo>=0) {
	trigOnlyChain->GetEntry( iEntryTo );
	if(debug) cout << "----> got entry from trigOnlyChain" << endl;
      }
      else {
	if(debug) cout << "----> entry not mapped" << endl;
	continue;
      }
    }

    // MATCHING SPIKE / L1-CANDIDATE //////////////////////////////////////////////////////////////////                         
    evt_trig_EG12=false;

    outcheckL1 << "ISO_N_data : " ;
    for(int i=0 ; i<4 ; i++) {
      outcheckL1 << "(" << trig_L1emIso_ieta[i] << ";" << trig_L1emIso_iphi[i] << ")=" << trig_L1emIso_rank[i] << " | ";
      if(trig_L1emIso_rank[i] >= 12) evt_trig_EG12=true;
    }

    outcheckL1 << endl
	       << "NONISO_N_data : ";
    for(int i=0 ; i<4 ; i++) {
      outcheckL1 << "(" << trig_L1emNonIso_ieta[i] << ";" << trig_L1emNonIso_iphi[i] << ")=" << trig_L1emNonIso_rank[i] << " | ";
      if(trig_L1emNonIso_rank[i] >= 12) evt_trig_EG12=true;
    }

    if(!evt_trig_EG12) continue;

    outcheckL1 << endl
	       << "ISO_N : " ;
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emIso_ieta_To[i] << ";" << trig_L1emIso_iphi_To[i] << ")=" << trig_L1emIso_rank_To[i] << " | ";

    outcheckL1 << endl
	       << "NONISO_N : ";
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emNonIso_ieta_To[i] << ";" << trig_L1emNonIso_iphi_To[i] << ")=" << trig_L1emNonIso_rank_To[i] 
		 << " | ";

    outcheckL1 << endl
	       << "ISO_M : ";
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emIso_ieta_M_To[i] << ";" << trig_L1emIso_iphi_M_To[i] << ")=" << trig_L1emIso_rank_M_To[i] 
		 << " | ";

    outcheckL1 << endl
	       << "NONISO_M : ";
    for(int i=0 ; i<4 ; i++)
      outcheckL1 << "(" << trig_L1emNonIso_ieta_M_To[i] << ";" << trig_L1emNonIso_iphi_M_To[i] << ")=" 
		 << trig_L1emNonIso_rank_M_To[i] << " | ";

    outcheckL1 << endl << endl;
  

    ///////////////////////////////////////
    // LOOP OVER SPIKES ///////////////////
    ///////////////////////////////////////

    for(int iS=0 ; iS<spike_N ; iS++) {

      if(iS>=5000) break;
      if(spike_Et[iS]<=0) continue;

      // Find spikes'TT informations
      coords = make_pair( spike_TTieta[iS] , spike_TTiphi[iS] );
      iterTT = adcTT.find( coords );
      if( iterTT != adcTT.end() ) {
	TT_t  = (iterTT->second).first ;
	TT_tE = (iterTT->second).second ;
	
	if(TT_t<0  || TT_t  >= 4032) continue;
	spike_TT_t[iS]  = TT_t ;
	spike_TT_sFGVB[iS] = trig_tower_sFGVB[ TT_t ];
	spike_TT_adc[iS] = trig_tower_adc[ TT_t ];
	
	if(TT_tE<0 || TT_tE >= 4032) continue;
	spike_TT_tE[iS] = TT_tE ;
	for(int iSam=0 ; iSam<5 ; iSam++) {
	  spike_TT_sFGVB_E[iS][iSam] = trig_tower_sFGVB_E[ TT_tE ][iSam];
	  spike_TT_adc_E[iS][iSam] = trig_tower_adc_E[ TT_tE ][iSam];
	}
      }

      // Match spike to L1 candidate
      spike_maxEGtrig[iS] = spike_maxEGtrig_To[iS] = spike_maxEGtrig_M_To[iS] = 0;
      
      matchL1toSpike( trig_L1emIso_N, trig_L1emIso_ieta, trig_L1emIso_iphi, trig_L1emIso_rank,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1iso[iS], spike_maxEGtrig[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N, trig_L1emIso_ieta, trig_L1emIso_iphi, trig_L1emIso_rank,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1noniso[iS], spike_maxEGtrig[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_To, trig_L1emIso_ieta_To, trig_L1emIso_iphi_To, trig_L1emIso_rank_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1iso_To[iS], spike_maxEGtrig_To[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_To, trig_L1emIso_ieta_To, trig_L1emIso_iphi_To, trig_L1emIso_rank_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1noniso_To[iS], spike_maxEGtrig_To[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_M_To, trig_L1emIso_ieta_M_To, trig_L1emIso_iphi_M_To, trig_L1emIso_rank_M_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1iso_M_To[iS], spike_maxEGtrig_M_To[iS], outcheckL1 );
      
      matchL1toSpike( trig_L1emIso_N_M_To, trig_L1emIso_ieta_M_To, trig_L1emIso_iphi_M_To, trig_L1emIso_rank_M_To,
		      spike_Rieta[iS],  spike_Riphi[iS],  spike_RCTL1noniso_M_To[iS], spike_maxEGtrig_M_To[iS], outcheckL1 );
      

      // Fill the tree //
      spike_out_outOfTime = spike_outOfTime[iS] ;
      spike_out_severityLevel = spike_severityLevel[iS] ;
      spike_out_Et = spike_Et[iS] ;
      spike_out_phi = spike_phi[iS] ;
      spike_out_eta = spike_eta[iS] ;
      spike_out_theta = spike_theta[iS] ;
      spike_out_TTiphi = spike_TTiphi[iS] ;
      spike_out_TTieta = spike_TTieta[iS] ;
      spike_out_TT_t = spike_TT_t[iS] ;
      spike_out_TT_tE = spike_TT_tE[iS] ;
      spike_out_TT_sFGVB = spike_TT_sFGVB[iS] ;
      spike_out_TT_adc = spike_TT_adc[iS] ;
      spike_out_Riphi = spike_Riphi[iS] ;
      spike_out_Rieta = spike_Rieta[iS] ;

      spike_out_maxEGtrig      = spike_maxEGtrig[iS];
      spike_out_maxEGtrig_To   = spike_maxEGtrig_To[iS];
      spike_out_maxEGtrig_M_To = spike_maxEGtrig_M_To[iS];

      spike_out_RCTL1iso = spike_RCTL1iso[iS];
      spike_out_RCTL1noniso = spike_RCTL1noniso[iS];
      spike_out_RCTL1iso_To = spike_RCTL1iso_To[iS];
      spike_out_RCTL1noniso_To = spike_RCTL1noniso_To[iS];
      spike_out_RCTL1iso_M_To = spike_RCTL1iso_M_To[iS];
      spike_out_RCTL1noniso_M_To = spike_RCTL1noniso_M_To[iS];


      for(int i=0;i<5;i++) {
	spike_out_TT_sFGVB_E[i] = spike_TT_sFGVB_E[iS][i] ;
	spike_out_TT_adc_E[i]   = spike_TT_adc_E[iS][i] ;
      }
      
      outtree->Fill();
    }

  }

    // Record tree
  outlog << "recording tree..." << endl;
  outtree->Write();
  outlog << "recorded !" << endl;
  outfile->Close();
  outlog << "file closed." << endl;

  return 1;

}
示例#27
0
int main (int argc, char** argv)
{  
  std::cout<<"--------> DUMPER: READ RECO DATA AND PRODUCE PROFILE PLOTS <--------"<<std::endl;
  
  
  //--------Read Options--------------------------------
  std::string inputFileList(argv[1]);
  std::string outputLabel = argv[2];
  int entriesMax = atoi(argv[3]);
  
  std::cout << "--------------------------------" << std::endl;
  std::cout << "inputFileList: "       << argv[1] << std::endl;
  std::cout << "outputLabel: "         << argv[2] << std::endl;
  std::cout << "entriesMax: "          << argv[3] << std::endl;
  std::cout << "--------------------------------" << std::endl;
  
  
  //-------start to read the input file list--------
  
  TChain* treeReco = new TChain("ntu");
  RecoTreeVars recoTV;
  InitRecoTree(treeReco,recoTV);
  FillChain(treeReco,inputFileList);
  
  
  //---------output histograms----------------
  TFile* outputFile = TFile::Open(Form("plots/plots_studyProfiles_%s.root",outputLabel.c_str()),"RECREATE");
  TH2F* h2_beamPosition_TDC = new TH2F("h2_beamPosition_TDC","",100,-240,-140.,100,-146,-46.);
  TH2F* h2_beamPosition_hodo11 = new TH2F("h2_beamPosition_hodo11","",160,-210.,-130.,160,-155.,-75.);
  TH2F* h2_beamPosition_hodo22 = new TH2F("h2_beamPosition_hodo22","",160,-210.,-130.,160,-155.,-75.);
  TH2F* h2_beamPosition_hodo12 = new TH2F("h2_beamPosition_hodo12","",160,-210.,-130.,160,-155.,-75.);
  TH2F* h2_beamPosition_hodo21 = new TH2F("h2_beamPosition_hodo21","",160,-210.,-130.,160,-155.,-75.);
  
  std::map<int,TProfile*> p_cellProfileX_TDC;
  std::map<int,TProfile*> p_cellProfileX_hodo12;
  std::map<int,TProfile*> p_cellProfileY_TDC;
  std::map<int,TProfile*> p_cellProfileY_hodo12;
  std::map<int,TH1F*> h_cell_charge;
  for(int iCh = 0; iCh < 32; ++iCh)
  {
    p_cellProfileX_TDC[iCh]    = new TProfile(Form("p_cell%02dProfileX_TDC",iCh),"",   100,-240.,-140.);
    p_cellProfileX_hodo12[iCh] = new TProfile(Form("p_cell%02dProfileX_hodo12",iCh),"",160,-210.,-130.);
    p_cellProfileY_TDC[iCh]    = new TProfile(Form("p_cell%02dProfileY_TDC",iCh),"",   100,-146., -46.);
    p_cellProfileY_hodo12[iCh] = new TProfile(Form("p_cell%02dProfileY_hodo12",iCh),"",160,-155., -75.);
    h_cell_charge[iCh] = new TH1F(Form("h_cell%02d_charge",iCh),"",100000,0., 10000000.);
  }
  
  TH1F* h_total_charge = new TH1F("h_total_charge","",100000,0., 10000000.);
  TProfile2D* p2_cellPosition_TDC    = new TProfile2D("p2_cellPosition_TDC",   "",100,-240.,-140.,100,-152.,-52.);
  TProfile2D* p2_cellPosition_hodo12 = new TProfile2D("p2_cellPosition_hodo12","",160,-210.,-130.,160,-155.,-75.);
  
  
  //-----Data loop--------------------------------------------------------
  int nEntries = treeReco -> GetEntries();
  if( entriesMax < 0 ) entriesMax = nEntries;
  for(int iEntry = 0; iEntry < entriesMax; ++iEntry)
  {
    if( iEntry%1 == 0 ) std::cout << ">>> reading entry: " << iEntry << " / " << nEntries << "\r" << std::flush;
    
    
    //---Read the entry
    ClearRecoTreeVars(recoTV);
    treeReco->GetEntry(iEntry);
    
    
    //---Reconstruct beam position
    float beamX_TDC = -recoTV.tableX + recoTV.tdcX;
    float beamY_TDC = -recoTV.tableY + recoTV.tdcY;
    
    float hodoX1 = GetHodoWire(recoTV.nHodoX1,recoTV.hodoX1);
    float hodoY1 = GetHodoWire(recoTV.nHodoY1,recoTV.hodoY1);
    float hodoX2 = GetHodoWire(recoTV.nHodoX2,recoTV.hodoX2);
    float hodoY2 = GetHodoWire(recoTV.nHodoY2,recoTV.hodoY2);
    float beamX_hodo1 = hodoX1 >= 0 ? -recoTV.tableX + 0.5*hodoX1 : -999;
    float beamY_hodo1 = hodoY1 >= 0 ? -recoTV.tableY - 0.5*hodoY1 : -999;
    float beamX_hodo2 = hodoX2 >= 0 ? -recoTV.tableX + 0.5*hodoX2 : -999;
    float beamY_hodo2 = hodoY2 >= 0 ? -recoTV.tableY - 0.5*hodoY2 : -999;
    
    
    //---Fill histograms
    h2_beamPosition_TDC -> Fill(beamX_TDC,beamY_TDC);
    if( beamX_hodo1 != -999 && beamY_hodo1 != -999 ) h2_beamPosition_hodo11 -> Fill(beamX_hodo1,beamY_hodo1);
    if( beamX_hodo2 != -999 && beamY_hodo2 != -999 ) h2_beamPosition_hodo22 -> Fill(beamX_hodo2,beamY_hodo2);
    if( beamX_hodo1 != -999 && beamY_hodo2 != -999 ) h2_beamPosition_hodo12 -> Fill(beamX_hodo1,beamY_hodo2);
    if( beamX_hodo2 != -999 && beamY_hodo1 != -999 ) h2_beamPosition_hodo21 -> Fill(beamX_hodo2,beamY_hodo1);
    
    float total_charge = 0.;
    for(int iCh = 0; iCh < 32; ++iCh)
    {
      if( recoTV.amp_DQM[iCh] > 500 ) p2_cellPosition_TDC    -> Fill(beamX_TDC,  beamY_TDC,  32*(iCh%2)+pow(-1,iCh)*iCh);
      if( recoTV.amp_DQM[iCh] > 500 ) p2_cellPosition_hodo12 -> Fill(beamX_hodo1,beamY_hodo2,32*(iCh%2)+pow(-1,iCh)*iCh);
      if( recoTV.amp_DQM[iCh] > 0. && recoTV.amp_DQM[iCh] < 999999. )
      {
        p_cellProfileX_TDC[iCh]    -> Fill(beamX_TDC,  recoTV.amp_DQM[iCh]);
        p_cellProfileX_hodo12[iCh] -> Fill(beamX_hodo1,recoTV.amp_DQM[iCh]);
        p_cellProfileY_TDC[iCh]    -> Fill(beamY_TDC,  recoTV.amp_DQM[iCh]);
        p_cellProfileY_hodo12[iCh] -> Fill(beamY_hodo2,recoTV.amp_DQM[iCh]);
        h_cell_charge[iCh] -> Fill(recoTV.charge_DQM[iCh]);
        if(iCh==12 || iCh==13 || iCh==18 || iCh==19)
          total_charge += recoTV.charge_DQM[iCh];
      }
    }
    
    if( (fabs(beamX_hodo1+180.) < 5.) &&
        (fabs(beamY_hodo2+117.) < 5.) )
      h_total_charge -> Fill(total_charge);
  }
  std::cout << std::endl;
  
  
  // //-----close everything-----------------------------------------------------
  outputFile -> Write();
  outputFile -> Close();
  
  
  //---------Done-----------------------------------------------------------------
}
示例#28
0
void ntupleViewer_Chain_MC(){

  const double beamspot=-0.005;

//  gROOT->Reset();
  gStyle->SetOptStat(1111);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetPadBorderMode(0);

  gStyle->SetCanvasColor(10);
  gStyle->SetPadColor(10);
  gStyle->SetFillColor(10);
  gStyle->SetStatColor(10);
  gStyle->SetTitleFillColor(10);

std::string addMe = "MC_";

TH1D* eta_All             =new TH1D( (addMe + std::string("eta_All")).c_str()        , (addMe + std::string("eta_All")).c_str(),25,-3,3);
TH1D* eta_withVertex      =new TH1D( (addMe + std::string("eta_withVertex")).c_str() , (addMe + std::string("eta_withVertex")).c_str(),25,-3,3);
TH1D* eta_AssVertex       =new TH1D( (addMe + std::string("eta_AssVertex")).c_str()  , (addMe + std::string("eta_AssVertex")).c_str(),25,-3,3);
  TH1D* phi_All             =new TH1D( (addMe + std::string("phi_All")).c_str()        , (addMe + std::string("phi_All")).c_str(),25,-3.1415,3.1415);
  TH1D* phi_withVertex      =new TH1D( (addMe + std::string("phi_withVertex")).c_str() , (addMe + std::string("phi_withVertex")).c_str(),25,-3.1415,3.1415);
  TH1D* phi_AssVertex       =new TH1D( (addMe + std::string("phi_AssVertex")).c_str()  , (addMe + std::string("phi_AssVertex")).c_str(),25,-3.1415,3.1415);
TH1D* pt_All              =new TH1D( (addMe + std::string("pt_All")).c_str()         , (addMe + std::string("pt_All")).c_str(),400,0.,40);
TH1D* pt_withVertex       =new TH1D( (addMe + std::string("pt_withVertex")).c_str()  , (addMe + std::string("pt_withVertex")).c_str(),400,0.,40);
TH1D* pt_AssVertex        =new TH1D( (addMe + std::string("pt_AssVertex")).c_str()   , (addMe + std::string("pt_AssVertex")).c_str(),400,0.,40);
  TH1D* track_multip_All       =new TH1D( (addMe + std::string("track_multip_All")).c_str()       , (addMe + std::string("track_multip_All")).c_str(),201,0,200);
  TH1D* track_multip_withVertex=new TH1D( (addMe + std::string("track_multip_withVertex")).c_str(), (addMe + std::string("track_multip_withVertex")).c_str(),201,0,200);
  TH1D* track_multip_AssVertex =new TH1D( (addMe + std::string("track_multip_AssVertex")).c_str() , (addMe + std::string("track_multip_AssVertex")).c_str(),201,0,200);
TH2D* pt_vs_multip_All              =new TH2D( (addMe + std::string("pt_vs_multip_All")).c_str()         , (addMe + std::string("pt_vs_multip_All")).c_str(),400,0.,40,201,0,200);
TH2D* pt_vs_multip_withVertex       =new TH2D( (addMe + std::string("pt_vs_multip_withVertex")).c_str()  , (addMe + std::string("pt_vs_multip_withVertex")).c_str(),400,0.,40,201,0,200);
TH2D* pt_vs_multip_AssVertex        =new TH2D( (addMe + std::string("pt_vs_multip_AssVertex")).c_str()   , (addMe + std::string("pt_vs_multip_AssVertex")).c_str(),400,0.,40,201,0,200);
  TH2D* pt_vs_ndof_All              =new TH2D( (addMe + std::string("pt_vs_ndof_All")).c_str()         , (addMe + std::string("pt_vs_ndof_All")).c_str(),400,0.,40,61,0,60);
  TH2D* pt_vs_ndof_withVertex       =new TH2D( (addMe + std::string("pt_vs_ndof_withVertex")).c_str()  , (addMe + std::string("pt_vs_ndof_withVertex")).c_str(),400,0.,40,61,0,60);
  TH2D* pt_vs_ndof_AssVertex        =new TH2D( (addMe + std::string("pt_vs_ndof_AssVertex")).c_str()   , (addMe + std::string("pt_vs_ndof_AssVertex")).c_str(),400,0.,40,61,0,60);
TH1D* ndof_All              =new TH1D( (addMe + std::string("ndof_All")).c_str()         , (addMe + std::string("ndof_All")).c_str(),61,0,60);
TH1D* ndof_withVertex       =new TH1D( (addMe + std::string("ndof_withVertex")).c_str()  , (addMe + std::string("ndof_withVertex")).c_str(),61,0,60);
TH1D* ndof_AssVertex        =new TH1D( (addMe + std::string("ndof_AssVertex")).c_str()   , (addMe + std::string("ndof_AssVertex")).c_str(),61,0,60);
  TH1D* normChi2_All        =new TH1D( (addMe + std::string("normChi2_All")).c_str()        , (addMe + std::string("normChi2_All")).c_str(),25,0,20);
  TH1D* normChi2_withVertex =new TH1D( (addMe + std::string("normChi2_withVertex")).c_str() , (addMe + std::string("normChi2_withVertex")).c_str(),25,0,20);
  TH1D* normChi2_AssVertex  =new TH1D( (addMe + std::string("normChi2_AssVertex")).c_str()  , (addMe + std::string("normChi2_AssVertex")).c_str(),25,0,20);
TH2D* chi2_vs_pT_All       =new TH2D( (addMe + std::string("chi2_vs_pT_All")).c_str()       , (addMe + std::string("chi2_vs_pT_All")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_withVertex=new TH2D( (addMe + std::string("chi2_vs_pT_withVertex")).c_str(), (addMe + std::string("chi2_vs_pT_withVertex")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_AssVertex =new TH2D( (addMe + std::string("chi2_vs_pT_AssVertex")).c_str() , (addMe + std::string("chi2_vs_pT_AssVertex")).c_str(),25,0,20,400,0.,40);
  TH2D* chi2_vs_pT_lowMultip_All       =new TH2D( (addMe + std::string("chi2_vs_pT_lowMultip_All")).c_str()       , (addMe + std::string("chi2_vs_pT_lowMultip_All")).c_str(),25,0,20,400,0.,40);
  TH2D* chi2_vs_pT_lowMultip_withVertex=new TH2D( (addMe + std::string("chi2_vs_pT_lowMultip_withVertex")).c_str(), (addMe + std::string("chi2_vs_pT_lowMultip_withVertex")).c_str(),25,0,20,400,0.,40);
  TH2D* chi2_vs_pT_lowMultip_AssVertex =new TH2D( (addMe + std::string("chi2_vs_pT_lowMultip_AssVertex")).c_str() , (addMe + std::string("chi2_vs_pT_lowMultip_AssVertex")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_highMultip_All       =new TH2D( (addMe + std::string("chi2_vs_pT_highMultip_All")).c_str()       , (addMe + std::string("chi2_vs_pT_highMultip_All")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_highMultip_withVertex=new TH2D( (addMe + std::string("chi2_vs_pT_highMultip_withVertex")).c_str(), (addMe + std::string("chi2_vs_pT_highMultip_withVertex")).c_str(),25,0,20,400,0.,40);
TH2D* chi2_vs_pT_highMultip_AssVertex =new TH2D( (addMe + std::string("chi2_vs_pT_highMultip_AssVertex")).c_str() , (addMe + std::string("chi2_vs_pT_highMultip_AssVertex")).c_str(),25,0,20,400,0.,40);
  TH1D* vertexes            =new TH1D( (addMe + std::string("vertexes")).c_str()       , (addMe + std::string("vertexes")).c_str(),5,0,5);
  TH1D* vertexes_z          =new TH1D( (addMe + std::string("vertexes_z")).c_str()     , (addMe + std::string("vertexes_z")).c_str(),25,-20,20);
  TH2D* vertexes_xy         =new TH2D( (addMe + std::string("vertexes_xy")).c_str()    , (addMe + std::string("vertexes_xy")).c_str(),200,-10,10,200,-10,10);
  TH1D* deltaZ_trackPV      =new TH1D( (addMe + std::string("deltaZ_trackPV")).c_str() , (addMe + std::string("deltaZ_trackPV")).c_str(),50,-25,25);
  TH1D* deltaZ_trackPV_ZOOM      =new TH1D( (addMe + std::string("deltaZ_trackPV_ZOOM")).c_str() , (addMe +  std::string("deltaZ_trackPV_ZOOM")).c_str(),100,-3,3);
TH1D* deltaX_trackPV      =new TH1D( (addMe + std::string("deltaX_trackPV")).c_str() , (addMe + std::string("deltaX_trackPV")).c_str(),50,-25,25);
TH1D* deltaX_trackPV_ZOOM      =new TH1D( (addMe + std::string("deltaX_trackPV_ZOOM")).c_str() , (addMe + std::string("deltaX_trackPV_ZOOM")).c_str(),100,-3,3);
  TH1D* deltaY_trackPV      =new TH1D( (addMe + std::string("deltaY_trackPV")).c_str() , (addMe + std::string("deltaY_trackPV")).c_str(),50,-25,25);
  TH1D* deltaY_trackPV_ZOOM      =new TH1D( (addMe + std::string("deltaY_trackPV_ZOOM")).c_str() , (addMe + std::string("deltaY_trackPV_ZOOM")).c_str(),100,-3,3);
TH1D* vertexesNum_NoutTrk =new TH1D( (addMe + std::string("vertexesNum_NoutTrk")).c_str() , (addMe + std::string("vertexesNum_NoutTrk")).c_str(),50,0,50);
TH1D* deltaZ_v1v2         =new TH1D( (addMe + std::string("deltaZ_v1v2")).c_str()    , (addMe + std::string("deltaZ_v1v2")).c_str(),100,0,50);
  TH1D* dZ_All      =new TH1D( (addMe + std::string("dZ_All")).c_str() , (addMe +  std::string("dZ_All")).c_str(),100,-3,3);
  TH1D* d0_All      =new TH1D( (addMe + std::string("d0_All")).c_str() , (addMe + std::string("d0_All")).c_str(),100,-3,3);
TH1D* dZPoint_Ass      =new TH1D( (addMe + std::string("dZPoint_Ass")).c_str() , (addMe +  std::string("dZPoint_Ass")).c_str(),100,-3,3);
TH1D* d0Point_Ass      =new TH1D( (addMe + std::string("d0Point_Ass")).c_str() , (addMe + std::string("d0Point_Ass")).c_str(),100,-3,3);
TH1D* dZ_Ass      =new TH1D( (addMe + std::string("dZ_Ass")).c_str() , (addMe +  std::string("dZ_Ass")).c_str(),100,-3,3);
TH1D* d0_Ass      =new TH1D( (addMe + std::string("d0_Ass")).c_str() , (addMe + std::string("d0_Ass")).c_str(),100,-3,3);
  TH1D* dZPoint_Vtx      =new TH1D( (addMe + std::string("dZPoint_Vtx")).c_str() , (addMe +  std::string("dZPoint_Vtx")).c_str(),100,-3,3);
  TH1D* d0Point_Vtx      =new TH1D( (addMe + std::string("d0Point_Vtx")).c_str() , (addMe + std::string("d0Point_Vtx")).c_str(),100,-3,3);
  TH1D* dZ_Vtx      =new TH1D( (addMe + std::string("dZ_Vtx")).c_str() , (addMe +  std::string("dZ_Vtx")).c_str(),100,-3,3);
  TH1D* d0_Vtx      =new TH1D( (addMe + std::string("d0_Vtx")).c_str() , (addMe + std::string("d0_Vtx")).c_str(),100,-3,3);
TH1D* dZ_Vtx_LARGE      =new TH1D( (addMe + std::string("dZ_Vtx_LARGE")).c_str() , (addMe + std::string("dZ_Vtx_LARGE")).c_str(),500,-15,15);
  TH1D* hthrust_z_All            =new TH1D( (addMe + std::string("hthrust_z_All")).c_str()       , (addMe + std::string("thrust_z_All")).c_str(),50,-1.1,1.1);
  TH1D* hthrust_z_withVertex     =new TH1D( (addMe + std::string("hthrust_z_withVertex")).c_str(), (addMe + std::string("thrust_y_withVertex")).c_str(),50,-1.1,1.1);
  TH1D* hthrust_z_AssVertex      =new TH1D( (addMe + std::string("hthrust_z_AssVertex")).c_str() , (addMe + std::string("thrust_z_AssVertex")).c_str(),50,-1.1,1.1);
TH1D* chargeAsymmetry_All = new TH1D( (addMe + std::string("chargeAsymmetry_All")).c_str() , (addMe + std::string("chargeAsymmetry_All")).c_str(),20,-10,10);
TH1D* chargeAsymmetry_AssVertex = new TH1D( (addMe + std::string("chargeAsymmetry_AssVertex")).c_str() , (addMe + std::string("chargeAsymmetry_AssVertex")).c_str(),20,-10,10);

//*******  partonic analysis *******  

TH1D* eta_All_HC             =new TH1D( (addMe + std::string("eta_All_HC")).c_str()        , (addMe + std::string("eta_All_HC")).c_str(),25,-3,3);
TH1D* eta_AssVertex_HC       =new TH1D( (addMe + std::string("eta_AssVertex_HC")).c_str()  , (addMe + std::string("eta_AssVertex_HC")).c_str(),25,-3,3);
TH1D* pt_All_HC              =new TH1D( (addMe + std::string("pt_All_HC")).c_str()         , (addMe + std::string("pt_All_HC")).c_str(),400,0.,40);
TH1D* pt_AssVertex_HC        =new TH1D( (addMe + std::string("pt_AssVertex_HC")).c_str()   , (addMe + std::string("pt_AssVertex_HC")).c_str(),400,0.,40);
  TH1D* track_multip_All_HC       =new TH1D( (addMe + std::string("track_multip_All_HC")).c_str()       , (addMe + std::string("track_multip_All_HC")).c_str(),201,0,200);
  TH1D* track_multip_AssVertex_HC =new TH1D( (addMe + std::string("track_multip_AssVertex_HC")).c_str() , (addMe + std::string("track_multip_AssVertex_HC")).c_str(),201,0,200);

TH1D* eta_All_DD             =new TH1D( (addMe + std::string("eta_All_DD")).c_str()        , (addMe + std::string("eta_All_DD")).c_str(),25,-3,3);
TH1D* eta_AssVertex_DD       =new TH1D( (addMe + std::string("eta_AssVertex_DD")).c_str()  , (addMe + std::string("eta_AssVertex_DD")).c_str(),25,-3,3);
TH1D* pt_All_DD              =new TH1D( (addMe + std::string("pt_All_DD")).c_str()         , (addMe + std::string("pt_All_DD")).c_str(),400,0.,40);
TH1D* pt_AssVertex_DD        =new TH1D( (addMe + std::string("pt_AssVertex_DD")).c_str()   , (addMe + std::string("pt_AssVertex_DD")).c_str(),400,0.,40);
  TH1D* track_multip_All_DD       =new TH1D( (addMe + std::string("track_multip_All_DD")).c_str()       , (addMe + std::string("track_multip_All_DD")).c_str(),201,0,200);
  TH1D* track_multip_AssVertex_DD =new TH1D( (addMe + std::string("track_multip_AssVertex_DD")).c_str() , (addMe + std::string("track_multip_AssVertex_DD")).c_str(),201,0,200);

TH1D* eta_All_SD             =new TH1D( (addMe + std::string("eta_All_SD")).c_str()        , (addMe + std::string("eta_All_SD")).c_str(),25,-3,3);
TH1D* eta_AssVertex_SD       =new TH1D( (addMe + std::string("eta_AssVertex_SD")).c_str()  , (addMe + std::string("eta_AssVertex_SD")).c_str(),25,-3,3);
TH1D* pt_All_SD              =new TH1D( (addMe + std::string("pt_All_SD")).c_str()         , (addMe + std::string("pt_All_SD")).c_str(),400,0.,40);
TH1D* pt_AssVertex_SD        =new TH1D( (addMe + std::string("pt_AssVertex_SD")).c_str()   , (addMe + std::string("pt_AssVertex_SD")).c_str(),400,0.,40);
  TH1D* track_multip_All_SD       =new TH1D( (addMe + std::string("track_multip_All_SD")).c_str()       , (addMe + std::string("track_multip_All_SD")).c_str(),201,0,200);
  TH1D* track_multip_AssVertex_SD =new TH1D( (addMe + std::string("track_multip_AssVertex_SD")).c_str() , (addMe + std::string("track_multip_AssVertex_SD")).c_str(),201,0,200);


//*********************************  

  TChain fChain ("MyAnalyzer/EventTree") ;
  fChain.Add("MCntuple_Summer09-D6T_STARTUP3X_V8I_900GeV-v2/res/*root");
  dati Input(&fChain);
  int entries = fChain.GetEntries();

//*******  TRUST_Z histograms *****
//deleted
//

//*******  TRACK parameters  ******

cout<<"corro su "<<entries<<" entries"<<endl;

for(int eventn=0;eventn<entries;eventn++){
  fChain.GetEntry(eventn);

//id_process test

int unClassified=0;
vector<int> unClassifiedId;
if ( !(Input.genEventScale==11 ||  Input.genEventScale==12 ||   Input.genEventScale==13 ||
       Input.genEventScale==28 ||  Input.genEventScale==53 ||   Input.genEventScale==68 ||
       Input.genEventScale==92 ||Input.genEventScale==93 || Input.genEventScale==94 ) )
  {
  unClassified++;
  bool alreadyFound=false;
  for( int i=0;i<unClassifiedId.size();i++)
      if (Input.genEventScale==unClassifiedId[i]) alreadyFound=true;
      
  if(!alreadyFound){
    unClassifiedId.push_back(runNumber);
    } 
  }


  int chargePlusY=0;
  int chargeMinusY=0;
  
  int trackCounter_HC=0;
  int trackCounter_SD=0;
  int trackCounter_DD=0;

//All
  track_multip_All->Fill(Input.numTracks);
  for(Int_t trackn=0;trackn<Input.numTracks;trackn++){ //tutte le tracce dell'evento	
      	  
    eta_All->Fill(Input.track_eta[trackn]);
    phi_All->Fill(Input.track_phi[trackn]);
    pt_All->Fill(Input.track_pt[trackn]);
    normChi2_All->Fill(Input.track_normalizedChi2[trackn]);
    chi2_vs_pT_All->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
    pt_vs_multip_All->Fill(Input.track_pt[trackn],Input.numTracks);
    pt_vs_ndof_All->Fill(Input.track_pt[trackn],Input.track_ndof[trackn]);
    ndof_All->Fill(Input.track_ndof[trackn]);
    if (Input.numTracks>100)    chi2_vs_pT_highMultip_All->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
    else                  chi2_vs_pT_lowMultip_All->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
    dZ_All->Fill( Input.track_dz[trackn] );
    d0_All->Fill( Input.track_d0[trackn] );

    if ( Input.track_py[trackn]>0. )  chargePlusY+=Input.track_charge[trackn];
    else                              chargeMinusY+=Input.track_charge[trackn];

    //partonic analysis

    if (Input.genEventScale==11 ||  Input.genEventScale==12 ||   Input.genEventScale==13 ||
      Input.genEventScale==28 ||  Input.genEventScale==53 ||   Input.genEventScale==68)
      {//HC
      trackCounter_HC++;
      eta_All_HC->Fill(Input.track_eta[trackn]);
      pt_All_HC->Fill(Input.track_pt[trackn]);
     }
    else if (Input.genEventScale==92 ||Input.genEventScale==93)
      {//SD
      trackCounter_SD++;
      eta_All_SD->Fill(Input.track_eta[trackn]);
      pt_All_SD->Fill(Input.track_pt[trackn]);
      }
    else if (Input.genEventScale==94 )
      {//DD
      trackCounter_DD++;
      eta_All_DD->Fill(Input.track_eta[trackn]);
      pt_All_DD->Fill(Input.track_pt[trackn]);
      }

    }//tutte le tracce dell'evento
 
  track_multip_All_HC->Fill(trackCounter_HC);
  track_multip_All_SD->Fill(trackCounter_SD);
  track_multip_All_DD->Fill(trackCounter_DD);
  
  chargeAsymmetry_All->Fill(chargePlusY+chargeMinusY);


//vertex presence requirement
  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++)
    {
    if(Input.vertex_z[vertexn]!=beamspot){  //vertice non ricostruito valore del beam spot
      if(fabs(Input.vertex_z[vertexn]-beamspot)<10){
        track_multip_withVertex->Fill(Input.numTracks);
	for(Int_t trackn=0;trackn<Input.numTracks;trackn++){
      	  
	  //if (track_pt[trackn]>8.) continue;
	  
	  eta_withVertex->Fill(Input.track_eta[trackn]);
	  phi_withVertex->Fill(Input.track_phi[trackn]);
	  pt_withVertex->Fill(Input.track_pt[trackn]);
	  normChi2_withVertex->Fill(Input.track_normalizedChi2[trackn]); 
          chi2_vs_pT_withVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
          pt_vs_multip_withVertex->Fill(Input.track_pt[trackn],Input.numTracks);
          pt_vs_ndof_withVertex->Fill(Input.track_pt[trackn],Input.track_ndof[trackn]);
          ndof_withVertex->Fill(Input.track_ndof[trackn]);
          if (Input.numTracks>100)    chi2_vs_pT_highMultip_withVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
          else                  chi2_vs_pT_lowMultip_withVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);

	  dZPoint_Vtx->Fill( (Input.track_vz[trackn]-Input.vertex_z[vertexn])- ( (Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_px[trackn] +  (Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_py[trackn])/(Input.track_pt[trackn]) * Input.track_pz[trackn]/Input.track_pt[trackn] );
	  d0Point_Vtx->Fill( (-(Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_py[trackn]+(Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_px[trackn])/Input.track_pt[trackn] );
	    dZ_Vtx->Fill( Input.track_dz[trackn] );
	    dZ_Vtx_LARGE->Fill( Input.track_dz[trackn] );
	    d0_Vtx->Fill( Input.track_d0[trackn] );
          
	  }
	}
      break; 
      }//vertice non ricostruito valore del beam spot
    }


//Vertex Association requirement

  chargePlusY=0;
  chargeMinusY=0;
  trackCounter_HC=0;
  trackCounter_SD=0;
  trackCounter_DD=0;

  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++)
    {
    //std::cout<<"vertices z: "<<Input.vertex_z[vertexn]<<endl;
    if(Input.vertex_z[vertexn]!=beamspot){  //vertice non ricostruito valore del beam spot
      if(fabs(Input.vertex_z[vertexn]-beamspot)<10){
        int fillCounter=0;
	for(Int_t trackn=0;trackn<Input.numTracks;trackn++){
      	  
	  double dZ_cut= (Input.track_vz[trackn]-Input.vertex_z[vertexn])- ( (Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_px[trackn] +  (Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_py[trackn])/(Input.track_pt[trackn]) * Input.track_pz[trackn]/Input.track_pt[trackn] ;
	  double d0_cut= (-(Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_py[trackn]+(Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_px[trackn])/Input.track_pt[trackn] ;
	  
	  //if ( fabs(track_vz[trackn]-vertex_z[vertexn])<1. )  //old cut in acceptance
	  if ( fabs(dZ_cut)<0.36 && fabs(d0_cut)<0.18 && 
	       Input.track_highPurity[trackn]==1 && Input.track_pt[trackn]>0.29)
	    {
	    fillCounter++;
	    eta_AssVertex->Fill(Input.track_eta[trackn]);
	    phi_AssVertex->Fill(Input.track_phi[trackn]);
	    pt_AssVertex->Fill(Input.track_pt[trackn]);
	    normChi2_AssVertex->Fill(Input.track_normalizedChi2[trackn]);
            chi2_vs_pT_AssVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
            pt_vs_multip_AssVertex->Fill(Input.track_pt[trackn],Input.numTracks);
            pt_vs_ndof_AssVertex->Fill(Input.track_pt[trackn],Input.track_ndof[trackn]);
            ndof_AssVertex->Fill(Input.track_ndof[trackn]);
            if (Input.numTracks>100)    chi2_vs_pT_highMultip_AssVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
            else                  chi2_vs_pT_lowMultip_AssVertex->Fill(Input.track_normalizedChi2[trackn],Input.track_pt[trackn]);
	    
	    dZPoint_Ass->Fill( (Input.track_vz[trackn]-Input.vertex_z[vertexn])- ( (Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_px[trackn] +  (Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_py[trackn])/(Input.track_pt[trackn]) * Input.track_pz[trackn]/Input.track_pt[trackn] );
	    d0Point_Ass->Fill( (-(Input.track_vx[trackn]-Input.vertex_x[vertexn])*Input.track_py[trackn]+(Input.track_vy[trackn]-Input.vertex_y[vertexn])*Input.track_px[trackn])/Input.track_pt[trackn] );
	    dZ_Ass->Fill( Input.track_dz[trackn] );
	    d0_Ass->Fill( Input.track_d0[trackn] );

            if ( Input.track_py[trackn]>0. )  chargePlusY+=Input.track_charge[trackn];
            else                        chargeMinusY+=Input.track_charge[trackn];

            //partonic analysis

            if (Input.genEventScale==11 ||  Input.genEventScale==12 ||   Input.genEventScale==13 ||
                Input.genEventScale==28 ||  Input.genEventScale==53 ||   Input.genEventScale==68)
              {//HC
	      trackCounter_HC++;
              eta_AssVertex_HC->Fill(Input.track_eta[trackn]); 
              pt_AssVertex_HC->Fill(Input.track_pt[trackn]);
              }
            else if (Input.genEventScale==92 ||Input.genEventScale==93)
              {//SD
	      trackCounter_SD++;
              eta_AssVertex_SD->Fill(Input.track_eta[trackn]);
              pt_AssVertex_SD->Fill(Input.track_pt[trackn]);
              }
            else if (Input.genEventScale==94 )
              {//DD
	      trackCounter_DD++;
              eta_AssVertex_DD->Fill(Input.track_eta[trackn]);
              pt_AssVertex_DD->Fill(Input.track_pt[trackn]);
	      }

	    }
          }
	  
        track_multip_AssVertex->Fill(fillCounter);
        track_multip_AssVertex_HC->Fill(trackCounter_HC);
        track_multip_AssVertex_SD->Fill(trackCounter_SD);
        track_multip_AssVertex_DD->Fill(trackCounter_DD);

        chargeAsymmetry_AssVertex->Fill(chargePlusY+chargeMinusY);
	}
      break; 
      }//vertice non ricostruito valore del beam spot
    }

}

  if (unClassifiedId.size()!=0){
    cout<<"cio' dei, e sti muli do che te li meti, ah?!"<<endl;
      for (int id=0;id<unClassifiedId.size();id++)
        cout<<unClassifiedId[id]<<" ";
    cout<<endl;
    }
  
//***** VERTEX properties *****

int contime=0;
int eventsWithRealVertex=0;
int eventsWithRealGoodVertex0;
cout<<"corro su "<<entries<<" entries"<<endl;
for(int eventn=0;eventn<entries;eventn++){
  fChain.GetEntry(eventn);

  int fill;
  if (Input.numVertices==1){
    if (Input.vertex_z[0]==beamspot) fill = 0;
    else                             fill = 1;
    }
  else fill = Input.numVertices;  
  vertexes->Fill(fill);

  if (Input.numVertices>1)
    deltaZ_v1v2->Fill( fabs(Input.vertex_z[0]-Input.vertex_z[1]) );
  
  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++){
    if(Input.vertex_z[vertexn]!=beamspot){  //vertice non ricostruito valore del beam spot
	vertexesNum_NoutTrk->Fill(Input.vertex_nOutgoingTracks[vertexn]);
	vertexes_z->Fill(Input.vertex_z[vertexn]);
	vertexes_xy->Fill(Input.vertex_x[vertexn],Input.vertex_y[vertexn]);
    }//vertice non ricostruito valore del beam spot
  }

  for(Int_t vertexn=0;vertexn<Input.numVertices;vertexn++)
    {
    if(Input.vertex_z[0]!=beamspot){  //vertice non ricostruito valore del beam spot
      if(fabs(Input.vertex_z[vertexn]-beamspot)<10){
        contime++;
	for(Int_t trackn=0;trackn<Input.numTracks;trackn++){
	  deltaZ_trackPV->Fill(Input.track_vz[trackn]-Input.vertex_z[vertexn]);  
	  deltaZ_trackPV_ZOOM->Fill(Input.track_vz[trackn]-Input.vertex_z[vertexn]);  
	    deltaX_trackPV->Fill(Input.track_vx[trackn]-Input.vertex_x[vertexn]);  
	    deltaX_trackPV_ZOOM->Fill(Input.track_vx[trackn]-Input.vertex_x[vertexn]);  
	  deltaY_trackPV->Fill(Input.track_vy[trackn]-Input.vertex_y[vertexn]);  
	  deltaY_trackPV_ZOOM->Fill(Input.track_vy[trackn]-Input.vertex_y[vertexn]);  
          }
	break;       
        }
      }//vertice non ricostruito valore del beam spot
    }

}

cout<<"eventi con vertice reale e buono, li gavemo contai: "<<contime<<endl;

double averageMultip = track_multip_AssVertex->GetMean();
TH1D* KNO_scaling = new TH1D("KNO_scaling","KNO_scaling",track_multip_AssVertex->GetNbinsX(),0.,double(track_multip_AssVertex->GetNbinsX())/averageMultip);
  KNO_scaling->GetXaxis()->SetTitle("n / < n >");
  KNO_scaling->GetYaxis()->SetTitle("< n >   P_{n}");
  for (int k=1; k<=KNO_scaling->GetNbinsX(); k++)
    KNO_scaling->SetBinContent(k,averageMultip*track_multip_AssVertex->GetBinContent(k));


if (realdata){

  //********* SetStatisticalError Real Data *********

  setStatError(eta_withVertex);
  setStatError(eta_All);
  setStatError(eta_AssVertex);
  setStatError(phi_withVertex);
  setStatError(phi_All);
  setStatError(phi_AssVertex);
  setStatError(pt_withVertex);
  setStatError(pt_All);
  setStatError(pt_AssVertex);
  setStatError(normChi2_withVertex);
  setStatError(normChi2_All);
  setStatError(normChi2_AssVertex);
  setStatError(vertexes);
  setStatError(vertexes_z);
  setStatError(deltaZ_trackPV);
  setStatError(vertexesNum_NoutTrk);

  //****   marker styles  *****  

  eta_withVertex->SetMarkerStyle(22);
  eta_AssVertex->SetMarkerStyle(22);
  eta_All->SetMarkerStyle(22);
  phi_withVertex->SetMarkerStyle(22);
  phi_AssVertex->SetMarkerStyle(22);
  phi_All->SetMarkerStyle(22);
  pt_withVertex->SetMarkerStyle(22);
  pt_AssVertex->SetMarkerStyle(22);
  pt_All->SetMarkerStyle(22);
  normChi2_withVertex->SetMarkerStyle(22);
  normChi2_AssVertex->SetMarkerStyle(22);
  normChi2_All->SetMarkerStyle(22);

  vertexes_z->SetMarkerStyle(22);
  deltaZ_trackPV->SetMarkerStyle(22);
  vertexesNum_NoutTrk->SetMarkerStyle(22);

  vertexes->SetMarkerStyle(22);
  }

  vertexes->GetXaxis()->SetBinLabel(1,"BeamSpot");
  vertexes->GetXaxis()->SetBinLabel(2,"1 Vertex");
  vertexes->GetXaxis()->SetBinLabel(3,"2 Vertices");
  vertexes->GetXaxis()->SetBinLabel(4,"3 Vertices");
  vertexes->GetXaxis()->SetBinLabel(5,"4 Vertices");
  vertexes->GetXaxis()->SetTitle("N^{vtx}/evt");

  deltaZ_v1v2->GetXaxis()->SetTitle("|v^{1}_{z}-v^{1}_{z}|");


//***** saving histos *****

  std::string fileToOpen="histoMC_fromChain_addpTcutAndGenLevelObservations.root";  
  TFile outFile((fileToOpen).c_str(),"RECREATE");
 
  eta_withVertex->Write();
  eta_All->Write();
  phi_withVertex->Write();
  phi_All->Write();
  pt_withVertex ->Write();
  pt_All->Write();
  normChi2_withVertex->Write();
  normChi2_All->Write();

  vertexes->Write();
  vertexes_z->Write();
  vertexes_xy->Write();
  deltaZ_trackPV->Write();
  vertexesNum_NoutTrk->Write();
  deltaZ_v1v2->Write();

  eta_AssVertex->Write();
  phi_AssVertex->Write();
  pt_AssVertex ->Write();
  normChi2_AssVertex->Write();
  
  hthrust_z_All->Write();
  hthrust_z_withVertex->Write();
  hthrust_z_AssVertex->Write();

  track_multip_All->Write();
  track_multip_withVertex->Write();
  track_multip_AssVertex->Write();
    chi2_vs_pT_All->Write();
    chi2_vs_pT_withVertex->Write();
    chi2_vs_pT_AssVertex->Write();
  chi2_vs_pT_lowMultip_All->Write();
  chi2_vs_pT_lowMultip_withVertex->Write();
  chi2_vs_pT_lowMultip_AssVertex->Write();
    chi2_vs_pT_highMultip_All->Write();
    chi2_vs_pT_highMultip_withVertex->Write();
    chi2_vs_pT_highMultip_AssVertex->Write();

  pt_vs_multip_All->Write();
  pt_vs_multip_withVertex->Write();
  pt_vs_multip_AssVertex->Write();  
    pt_vs_ndof_All->Write();        
    pt_vs_ndof_withVertex->Write(); 
    pt_vs_ndof_AssVertex->Write();  

  deltaX_trackPV->Write();
  deltaX_trackPV_ZOOM->Write(); 
    deltaY_trackPV->Write();  
    deltaY_trackPV_ZOOM->Write();  

    dZ_All->Write();
    d0_All->Write();
  dZPoint_Ass->Write();
  d0Point_Ass->Write();
    dZ_Ass->Write();
    d0_Ass->Write();
  dZPoint_Vtx->Write();
  d0Point_Vtx->Write();
    dZ_Vtx->Write();
    dZ_Vtx_LARGE->Write();
    d0_Vtx->Write();

//   KNO_scaling->Write();

   ndof_All->Write();
   ndof_withVertex->Write();
   ndof_AssVertex->Write();
  
  chargeAsymmetry_All->Write();
  chargeAsymmetry_AssVertex->Write();

  eta_All_HC->Write();
  eta_AssVertex_HC->Write();
  pt_All_HC->Write();
  pt_AssVertex_HC->Write();
  track_multip_All_HC->Write();
  track_multip_AssVertex_HC->Write();
  eta_All_DD->Write();
  eta_AssVertex_DD->Write();
  pt_All_DD->Write();
  pt_AssVertex_DD->Write();
  track_multip_All_DD->Write();
  track_multip_AssVertex_DD->Write();
  eta_All_SD->Write();
  eta_AssVertex_SD->Write();
  pt_All_SD->Write();
  pt_AssVertex_SD->Write();
  track_multip_All_SD->Write();
  track_multip_AssVertex_SD->Write();
  
  outFile.Close();
}
示例#29
0
void getSkimCutflow(TString files) {
  
  TChain *fChain = new TChain("cutFlow");   //!pointer to the analyzed TTree or TChain
   // Declaration of leaf types
   UInt_t          startCount_;
   UInt_t          met200Count_;
   UInt_t          numJetsCount_;
   UInt_t          numCSVMCount_;
   UInt_t          minDeltaPhiCount_;
   UInt_t          muonVetoCount_;
   UInt_t          electronVetoCount_;

   // List of branches
   TBranch        *b_startCount;   //!
   TBranch        *b_met200Count;   //!
   TBranch        *b_numJetsCount;   //!
   TBranch        *b_numCSVMCount;   //!
   TBranch        *b_minDeltaPhiCount;   //!
   TBranch        *b_muonVetoCount;   //!
   TBranch        *b_electronVetoCount;   //!

   fChain->SetBranchAddress("startCount", &startCount_, &b_startCount);
   fChain->SetBranchAddress("met200Count", &met200Count_, &b_met200Count);
   fChain->SetBranchAddress("numJetsCount", &numJetsCount_, &b_numJetsCount);
   fChain->SetBranchAddress("numCSVMCount", &numCSVMCount_, &b_numCSVMCount);
   fChain->SetBranchAddress("minDeltaPhiCount", &minDeltaPhiCount_, &b_minDeltaPhiCount);
   fChain->SetBranchAddress("muonVetoCount", &muonVetoCount_, &b_muonVetoCount);
   fChain->SetBranchAddress("electronVetoCount", &electronVetoCount_, &b_electronVetoCount);

   fChain->Add(files);

   int startCount(0);
   int met200Count(0);
   int numJetsCount(0);
   int numCSVMCount(0);
   int minDeltaPhiCount(0);
   int muonVetoCount(0);
   int electronVetoCount(0);

  for (unsigned int entry=0; entry<fChain->GetEntries(); entry++) {
    fChain->GetEntry(entry);
    startCount+=startCount_;
    met200Count+=met200Count_;
    numJetsCount+=numJetsCount_;
    numCSVMCount+=numCSVMCount_;
    minDeltaPhiCount+=minDeltaPhiCount_;
    muonVetoCount+=muonVetoCount_;
    electronVetoCount+=electronVetoCount_;
  }

  printf("*****Cutflow*****\n");
  printf("startCount\t\t\t%d\n",startCount);
  printf("met200Count\t\t\t%d\n",met200Count);
  printf("numJetsCount\t\t\t%d\n",numJetsCount);
  printf("numCSVMCount\t\t\t%d\n",numCSVMCount);
  printf("minDeltaPhiCount\t\t%d\n",minDeltaPhiCount);
  printf("muonVetoCount\t\t\t%d\n",muonVetoCount);
  printf("electronVetoCount\t\t%d\n",electronVetoCount);

   return;

}
示例#30
0
void Campaign4Example()
{
    std::ostringstream os;
    std::string path = "../../data/ds10/data/test_processing/Run";
    std::vector<int> run_id_list;   
    run_id_list.push_back(3007);
    run_id_list.push_back(3008);
    	
    TChain *chain = new TChain("Events");

    if (! USE_DB)
    {
	std::cout<<"WARNING: Database access disabled ! Make sure to check run list manually"<<std::endl;
    }
    //Check runs for validity and add them to the TChain
    for(vector<int>::const_iterator it = run_id_list.begin(); it != run_id_list.end(); it++)
    {
	if (USE_DB)
	{
	    if ( ! DB_does_run_exist("rundb", "daqruns", *it))
	    {
		std::cout<<"Run "<<(*it)<<" does not exist in the database"<<std::endl;
		continue;
	    }
	    
	    if(DB_get_string("rundb", "daqruns", *it, "comment").find("HARDWARE_ISSUE") != string::npos) 
	    {
		std::cout << "Run" << *it << " has HARDWARE ISSUES. Skipping ..." <<std::endl;
		continue;
	    }       
	    
	    if(DB_get_string("rundb", "daqruns", *it, "type").find("laser") == string::npos 
	       && DB_get_string("rundb", "daqruns", *it, "type").find("*junk") == string::npos 
	       && DB_get_string("rundb", "daqruns", *it, "type").find("darkbox") == string::npos 
	       && DB_get_string("rundb", "daqruns", *it, "type").find("other") == string::npos)
		
	    {
		os.str("");
		os << path << setw(6) << setfill('0') << *it << ".root";
		chain->Add(os.str().c_str());
	    }
	}
	else
	{
	    os.str("");
	    os << path << setw(6) << setfill('0') << *it << ".root";
	    chain->Add(os.str().c_str());
	}
    }

    //Create EventData object to store information from ROOT TTree
    EventData* event = NULL;
    chain->SetBranchAddress("event", &event);
    int n_events = chain->GetEntries();

    //Create output histograms
    TFile* f = new TFile ("Run4example.root", "RECREATE");
    TH1F* s1_hist = new TH1F("s1_hist", "S1 Spectrum", 100, 0, 2000);
    TH2F* s2s1_f90_hist = new TH2F("s2s1_f90_hist", "Log(S2/S1) vs F90", 100, 0, 1, 100, -3, 3.2);

    //Loop over all events in TTree
    for(int n = 0; n < n_events; n = n + 1)
    {
		
        if ( n % 10000 == 0)
            std::cout<<"Processing Event: "<<n<<"/"<<n_events<<std::endl;
        
        chain->GetEntry(n);
        
	//Identify S1 and S2 pulses
	Int_t s1_pulse_number;
	std::vector<Int_t> s2_pulse_number;
	s1s2_Identifier(event, s1_pulse_number, s2_pulse_number);
	

	if (s1_pulse_number == -1)
	    continue;
	
	Int_t s2_multiplicity = s2_pulse_number.size();
	if (s2_multiplicity != 1)
	    continue;

	//Calculate energies
	Double_t s1_fixed = -1;
	if (event->sum_of_int[s1_pulse_number].fixed_npe1_valid)
	    s1_fixed = event->sum_of_int[s1_pulse_number].fixed_npe1;

	
	Double_t s2_fixed = -1;
	if (event->sum_of_int[s2_pulse_number[0]].fixed_npe2_valid)
	    s2_fixed = event->sum_of_int[s2_pulse_number[0]].fixed_npe2;
       

	//Calculate drift time
        Double_t t_drift = -1;
	if (s2_multiplicity > 0)
	    t_drift = drift_time_eval (event, s1_pulse_number, s2_pulse_number[0]);
	
	//CUTS
	if ( start_time(event) 
	     && more_one_pulses(event) 
	     && nosat(event) 
	     && nodesync(event) 
	     && s1_fixed > 4. 
	     && s1_fixed < 600. 
	     && s2_multiplicity == 1 
	     && s2_fixed > 10. 
	     && t_drift > 10. 
	     && t_drift < 85.
	     && ! late_peak (event, s1_pulse_number))
	{
	    s1_hist->Fill(s1_fixed);
	    s2s1_f90_hist->Fill(event->sum_of_int[s1_pulse_number].f90, TMath::Log10(s2_fixed/s1_fixed));
	}
    }//Finish loop over events

    s1_hist->Write();
    s2s1_f90_hist->Write();
    f->Close();
}