Ejemplo n.º 1
0
void
PrintAlignment()
{
  AliCDBManager* cdb   = AliCDBManager::Instance();
  cdb->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  AliCDBEntry*   align = cdb->Get("FMD/Align/Data");
  if (!align) {
    Error("PrintAlignment","didn't alignment data from CDB");
    return;
  }
  
  TClonesArray* array = dynamic_cast<TClonesArray*>(align->GetObject());
  if (!array) {
    Warning("PrintAlignement", "Invalid align data from CDB");
    return;
  }
  Int_t nAlign = array->GetEntries();
  for (Int_t i = 0; i < nAlign; i++) {
    AliAlignObjParams* a = static_cast<AliAlignObjParams*>(array->At(i));
    Double_t ang[3];
    Double_t trans[3];
    a->GetAngles(ang);
    a->GetTranslation(trans);
    std::cout << a->GetVolPath() << "\n" 
	      << "  translation: "
	      << "(" << std::setw(12) << trans[0] 
	      << "," << std::setw(12) << trans[1] 
	      << "," << std::setw(12) << trans[2] << ")\n"
	      << "  rotation:    "
	      << "(" << std::setw(12) << ang[0] 
	      << "," << std::setw(12) << ang[1] 
	      << "," << std::setw(12) << ang[2]  << ")" << std::endl;
    // a->Print();
  }
}
Ejemplo n.º 2
0
void analyzer()
{

  TString processName = "ZJets";

  TFile* f = TFile::Open(Form("hist_%s.root", processName.Data()), "recreate");

  // Create chain of root trees
  TChain chain("DelphesMA5tune");
  //kisti
  //chain.Add("/cms/home/tjkim/fcnc/sample/ZToLL50-0Jet_sm-no_masses/events_*.root");
  //hep
  chain.Add("/Users/tjkim/Work/fcnc/samples/ZToLL50-0Jet_sm-no_masses/events_*.root");  

  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();
  
  // Get pointers to branches used in this analysis
  TClonesArray *branchMuon = treeReader->UseBranch("DelphesMA5tuneMuon");
  
  // Book histograms
  TH1 *histDiMuonMass = new TH1F("dimuon_mass","Di-Muon Invariant Mass (GeV)",100, 50, 150);
 
  // Loop over all events

  for(Int_t entry = 0; entry < numberOfEntries; ++entry)
  {
    // Load selected branches with data from specified event
    treeReader->ReadEntry(entry);
 
    int nmuon = 0; 
    for( int i = 0; i < branchMuon->GetEntries(); i++)
    {
      Muon *muon = (Muon*) branchMuon->At(i);
      if( muon->PT <= 20 || abs(muon->Eta) >= 2.4 ) continue;
      nmuon = nmuon + 1 ;
    }

    if( nmuon >= 2){

      Muon *mu1 = (Muon*) branchMuon->At(0);
      Muon *mu2 = (Muon*) branchMuon->At(1);

      // Plot di-muon invariant mass 
      histDiMuonMass->Fill(((mu1->P4()) + (mu2->P4())).M());
    }
 
  }

  // Show resulting histograms
  histDiMuonMass->Write();

  f->Close();

}
Ejemplo n.º 3
0
void digitsTOF(Int_t nevents, Int_t nfiles){


  TH1F *hadc     = new TH1F("hadc","ADC [bin]",200, -100., 10000.);
  TH1F *hadclog     = new TH1F("hadclog","ADC [bin]",200, -1., 7.);
  
    TTree *treeD=0x0;
  
    TClonesArray *digits =0x0;
  
    for (Int_t event=0; event<nevents; event++) {
      cout << "Event " << event << endl;

      treeD = GetTreeD(event, "TOF", nfiles);
      if ( ! treeD ) {
        cerr << "Event directory not found in " << nfiles <<  " files" << endl;
        exit(1);
      }      

      digits = NULL;
      treeD->SetBranchAddress("TOF", &digits);

      for(Int_t iev=0; iev<treeD->GetEntries(); iev++){
	treeD->GetEntry(iev);

	for (Int_t j = 0; j < digits->GetEntries(); j++) {
	  IlcTOFdigit* dig = dynamic_cast<IlcTOFdigit*> (digits->At(j));
	  hadc->Fill(dig->GetAdc());
	  if(dig->GetAdc()>0)hadclog->Fill(TMath::Log10(dig->GetAdc()));
	}

      }
    }

   TFile fc("digits.TOF.root","RECREATE");
   fc.cd();
   
   hadc->Write();
   hadclog->Write();

   fc.Close();

}
Ejemplo n.º 4
0
void digitsPHOS(Int_t nevents, Int_t nfiles)
{

 TH1F * hadc = new TH1F ("hadc", "hadc", 100, -10, 200);
 TH1F * hadcLog = new TH1F ("hadclog", "hadclog", 100, -2, 4);
 IlcRunLoader* runLoader = IlcRunLoader::Open("gilc.root","Event","READ");
 IlcPHOSLoader * phosLoader = dynamic_cast<IlcPHOSLoader*>(runLoader->GetLoader("PHOSLoader"));
 
 for (Int_t ievent=0; ievent <nevents; ievent++) {
  // for (Int_t ievent = 0; ievent < runLoader->GetNumberOfEvents(); ievent++) {
   runLoader->GetEvent(ievent) ;
   phosLoader->CleanDigits() ; 
   phosLoader->LoadDigits("READ") ;
   TClonesArray * digits    = phosLoader->Digits() ;
   printf("Event %d contains %d digits\n",ievent,digits->GetEntriesFast());
   
   
   for (Int_t j = 0; j < digits->GetEntries(); j++) {
     
     IlcPHOSDigit* dig = dynamic_cast<IlcPHOSDigit*> (digits->At(j));
     //cout << dig->GetEnergy() << endl;
     hadc->Fill(dig->GetEnergy());
     if(dig->GetEnergy()>0)
       hadcLog->Fill(TMath::Log10(dig->GetEnergy()));
     
   }
   
 }
 
 TFile fc("digits.PHOS.root","RECREATE");
 fc.cd();
 hadc->Write();
 hadcLog->Write();
 fc.Close();


}
Ejemplo n.º 5
0
    void fill(const JMETree& jme) {
        eventinfo.runNum = jme.run;
        eventinfo.evtNum = jme.evt;
        eventinfo.lumiSec = jme.lumi;
        eventinfo.nPU =  jme.npus->size() ? (*jme.npus)[0] : 0;
        eventinfo.nPUmean = jme.tnpus->size() ? (*jme.tnpus)[0] : 0;
        eventinfo.rhoIso = 0;
        eventinfo.rhoJet = jme.rho;
        eventinfo.triggerBits = 0;
        for(auto i = jme.paths->cbegin() ;  i != jme.paths->cend() ; ++i) {
            //cout << "testing " << *i << endl;
            for(auto i2 = triggernames->cbegin(); i2 != triggernames->cend() ; ++i2) {
                if(*i2 > *i) break;
                //cout << "trying " << *i2 << endl;
                if(i->compare(0,min(i->size(),i2->size()),*i2) == 0) {
                    //std::cout << "setting" << *i << ", " << *i2 << " " << i2-triggernames->cbegin() << endl;
                    eventinfo.triggerBits[i2-triggernames->cbegin()] = true;
                }
            }
            //std::cout << *i << endl;
        }
        //eventinfo.triggerBits = jme.prescales->size();
        eventinfo.pfMET =  (*jme.met_p4)[0].Pt();// not stored atm, to be done later
        eventinfo.pfMETphi = (*jme.met_p4)[0].Phi();
        geneventinfo.id_1 = jme.pdf_id->first;
        geneventinfo.id_2 = jme.pdf_id->second;
        geneventinfo.x_1 = jme.pdf_x->first;
        geneventinfo.x_2 = jme.pdf_x->second;
        geneventinfo.weight = jme.weight;
        //geneventinfo.pthat = jme.pthat; // is missing in the header - but anyway not needed (at the moment)


        vertices->Clear();
        jets->Clear();
        addjets->Clear();


        for(unsigned int j = 0 ; j < jme.position->size() ; ++j) {
            assert(vertices->GetEntries() < vertices->GetSize());
            const int index = vertices->GetEntries();
            new((*vertices)[index]) baconhep::TVertex();
            baconhep::TVertex    *pVertex = (baconhep::TVertex*)(*vertices)[index];
            //pVertex->nTracksFit =
            pVertex->ndof = (*jme.ndof)[j];
            pVertex->chi2 = (*jme.normalizedChi2)[j];
            pVertex->x = (*jme.position)[j].X();
            pVertex->y = (*jme.position)[j].Y();
            pVertex->z = (*jme.position)[j].Z();
        }



        for(unsigned int j = 0 ; j < jme.p4->size() ; ++j) {
            assert(jets->GetEntries() < jets->GetSize());
            const int index = jets->GetEntries();
            new((*jets)[index]) baconhep::TJet();
            baconhep::TJet    *pJet = (baconhep::TJet*)(*jets)[index];
            pJet->pt    = (*jme.p4)[j].pt();
            pJet->eta   = (*jme.p4)[j].eta();
            pJet->phi   = (*jme.p4)[j].phi();
            pJet->mass  = (*jme.p4)[j].mass();
            pJet->ptRaw = (*jme.p4)[j].pt() * (*jme.jec_toraw)[j];
            //pJet->csv = (*jme.pfCombinedSecondaryVertexV2BJetTags)[j];  // only stored in AK4PFCHS, to be done later
            pJet->area  = (*jme.jtarea)[j];
            pJet->genpt    = (*jme.gen_p4)[j].pt();
            pJet->geneta   = (*jme.gen_p4)[j].eta();
            pJet->genphi   = (*jme.gen_p4)[j].phi();
            pJet->genm  = (*jme.gen_p4)[j].mass();
            pJet->betaStar = (*jme.betaStar)[j];
            //std::cout << pJet->pt << std::endl;
        }


        tree->Fill();

    }
void run_radius_correction ()
{
    TStopwatch timer;
    timer.Start();

    gStyle->SetPalette(1,0);
    gStyle->SetHistLineWidth(2);

    // ----  Load libraries   -------------------------------------------------
    gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C");
    basiclibs();
    gROOT->LoadMacro("$VMCWORKDIR/macro/rich/cbmlibs.C");
    cbmlibs();

   // gROOT->LoadMacro("$VMCWORKDIR/macro/rich/setstyle.C");
   // setphdStyle();
    SetStyles();

    char fileMC[200], fileRec[200];

    sprintf(fileMC,"/d/cbm02/slebedev/rich/JUL09/correction/mc.00.root");
    cout<<fileMC<<endl;
    TFile *f1 = new TFile(fileMC,"R");
    TTree* t1 = f1->Get("cbmsim");
    TFolder *fd1 = f1->Get("cbmroot");
    TClonesArray* fMCTracks = (TClonesArray*) fd1->FindObjectAny("MCTrack");
    t1->SetBranchAddress(fMCTracks->GetName(),&fMCTracks);

    sprintf(fileRec, "/d/cbm02/slebedev/rich/JUL09/correction/reco.00.root");
    TFile *f = new TFile(fileRec,"R");
    TTree* t = f->Get("cbmsim");
    TFolder *fd = f->Get("cbmout");
    TClonesArray *fRichRings = (TClonesArray*) fd->FindObjectAny("RichRing");
    t->SetBranchAddress(fRichRings->GetName(),&fRichRings);
    TClonesArray *fRichMatches = (TClonesArray*) fd->FindObjectAny("RichRingMatch");
    t->SetBranchAddress(fRichMatches->GetName(),&fRichMatches);

    //Int_t fNofBinsX = 40;
    //Int_t fNofBinsY = 50;
    Int_t fNofBinsX = 25;
    Int_t fNofBinsY = 25;
    ///A axis
    TH2D* fh_axisAXYCount;
    TH2D* fh_axisAXYW;
    TH2D* fh_axisAXY;
    TH2D* fh_axisASigma;
    TH2D* mapaxisAXY;


    ///B axis
    TH2D* fh_axisBXYCount;
    TH2D* fh_axisBXYW;
    TH2D* fh_axisBXY;
    TH2D* fh_axisBSigma;
    TH2D* mapaxisBXY;

    mapaxisAXY = new TH2D("fh_mapaxisAXY","dA distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    mapaxisBXY = new TH2D("fh_mapaxisBXY","dB distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXYCount = new TH2D("fh_axisAXYCount","A Count",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXYW = new TH2D("fh_axisAXYW","",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXYCount = new TH2D("fh_axisBXYCount","B Count",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXYW = new TH2D("fh_axisBXYW","",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisAXY = new TH2D("fh_axisAXY","A distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);
    fh_axisBXY = new TH2D("fh_axisBXY","B distribution (x,y);X, [cm];Y, [cm]",fNofBinsX,-200,200,fNofBinsY,-250,250);

    Double_t fMinAaxis = 4.5;
    Double_t fMaxAaxis = 7.5;

    ///Set Mean value of A and B axeses, Compact RICH
    //Double_t fMeanAaxis = 5.06;
    //Double_t fMeanBaxis = 4.65;

    ///Set Mean value of A and B axeses, Large RICH
    Double_t fMeanAaxis = 6.17;
    Double_t fMeanBaxis = 5.6;

    Int_t nEvents=t->GetEntries();
    cout<<" nEvents ="<<nEvents<<endl;
    for(Int_t ievent=0;ievent<nEvents; ievent++ ) {
        cout<<"ievent = "<<ievent;
        CbmRichRing *ring=NULL;
        CbmRichRingMatch *match=NULL;
        t->GetEntry(ievent);
        t1->GetEntry(ievent);
        Int_t nofRings = fRichRings->GetEntries();
        cout<<"  nofRings = "<<nofRings;
        cout<<"  nofMatches = "<< fRichMatches->GetEntries() ;
        cout<<"  nofMCTracks = "<<fMCTracks->GetEntries() << endl;

        for(Int_t iRing=0; iRing < nofRings; iRing++){
            ring = (CbmRichRing*)fRichRings->At(iRing);
            if (!ring) continue;
            match = (CbmRichRingMatch*)fRichMatches->At(iRing);
            if (!match) continue;

            Int_t trackId = match->GetMCTrackID();
            if (trackId == -1) continue;
            if (trackId > fMCTracks->GetEntries()) continue;

            CbmMCTrack* mcTrack = (CbmMCTrack*)fMCTracks->At(trackId);
            if (!mcTrack) continue;
            Int_t pdg = TMath::Abs(mcTrack->GetPdgCode());
            Int_t motherId = mcTrack->GetMotherId();
            if (pdg != 11) continue;
            if (motherId != -1) continue;

            Double_t radius = ring->GetRadius();
            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis();
            Double_t centerX = ring->GetCenterX();
            Double_t centerY = ring->GetCenterY();

            if (axisA > fMaxAaxis || axisB > fMaxAaxis) continue;
            if (axisA < fMinAaxis || axisB < fMinAaxis) continue;

            fh_axisAXYW->Fill(centerX, centerY, axisA);
            fh_axisAXYCount->Fill(centerX, centerY);

            fh_axisBXYW->Fill(centerX, centerY, axisB);
            fh_axisBXYCount->Fill(centerX, centerY);
        } //iRing
    } //iEvent

    fh_axisAXY->Divide(fh_axisAXYW,fh_axisAXYCount);
    fh_axisBXY->Divide(fh_axisBXYW,fh_axisBXYCount);


///create two correction maps
    for (Int_t iX = 1; iX < mapaxisAXY->GetNbinsX() + 1; iX++){
        for (Int_t iY = 1; iY < mapaxisAXY->GetNbinsY() + 1; iY++){
        	if (fh_axisAXYCount->GetBinContent(iX, iY) != 0){
        		mapaxisAXY->SetBinContent(iX, iY, fMeanAaxis - fh_axisAXY->GetBinContent(iX, iY) );
        	} else {
        		mapaxisAXY->SetBinContent(iX, iY, -99999999.);
        	}

        	if (fh_axisBXYCount->GetBinContent(iX, iY) != 0){
        		mapaxisBXY->SetBinContent(iX, iY, fMeanBaxis - fh_axisBXY->GetBinContent(iX, iY) );
        	} else {
        		mapaxisBXY->SetBinContent(iX, iY, -99999999.);
        	}
        }
    }

    c1_0 = new TCanvas("c1_0","c1_0",10,10,600,600);
    c1_0->Divide(1,2);
    c1_0->cd(1);
    fh_axisAXYCount->Draw("COLZ");
    c1_0->cd(2);
    fh_axisBXYCount->Draw("COLZ");

    c1 = new TCanvas("c1","c1",10,10,600,600);
    c1->Divide(1,2);
    c1->cd(1);
    fh_axisAXY->SetMinimum(5.0);
    fh_axisAXY->SetMaximum(6.4);
    fh_axisAXY->Draw("COLZ");
    c1->cd(2);
    fh_axisBXY->SetMinimum(5.0);
    fh_axisBXY->SetMaximum(6.0);
    fh_axisBXY->Draw("COLZ");

    c2 = new TCanvas("c2","c2",10,10,600,600);
    c2->Divide(1,2);
    c2->cd(1);
    mapaxisAXY->SetMinimum(-0.5);
    mapaxisAXY->SetMaximum(0.5);
    mapaxisAXY->Draw("COLZ");
    c2->cd(2);
    mapaxisBXY->SetMinimum(-0.5);
    mapaxisBXY->SetMaximum(0.5);
    mapaxisBXY->Draw("COLZ");


///// Check correction procedure
    TH1D* fh_Abefore = new TH1D("fh_Abefore","A before;A, [cm];yield", 300, 0., 9.);;
    TH1D* fh_Bbefore= new TH1D("fh_Bbefore","B before;B, [cm];yield", 300, 0., 9.);;

    TH1D* fh_A = new TH1D("fh_A","A after;A, [cm];yield", 300, 0., 9.);;
    TH1D* fh_B = new TH1D("fh_B","B after;B, [cm];yield", 300, 0., 9.);;

    cout <<"Check correction procedure......" << endl;
    for(Int_t ievent=0;ievent<nEvents;ievent++ ) {
        CbmRichRing *ring=NULL;
       // if (ievent % 100 == 0) cout << ievent << "   ";
        //t1->GetEntry(ievent);
        t->GetEntry(ievent);
        t1->GetEntry(ievent);
        Int_t nofRings = fRichRings->GetEntries();

        for(Int_t iRing=0; iRing < nofRings; iRing++){

            ring = (CbmRichRing*)fRichRings->At(iRing);
            if (!ring) continue;
            match = (CbmRichRingMatch*)fRichMatches->At(iRing);
            if (!match) continue;

            Int_t trackId = match->GetMCTrackID();
            if (trackId == -1) continue;
            if (trackId > fMCTracks->GetEntries()) continue;

            CbmMCTrack* mcTrack = (CbmMCTrack*)fMCTracks->At(trackId);
            if (!mcTrack) continue;
            Int_t pdg = TMath::Abs(mcTrack->GetPdgCode());
            Int_t motherId = mcTrack->GetMotherId();
            if (pdg != 11) continue;
            if (motherId != -1) continue;

            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis();
            if (axisA > fMaxAaxis || axisB > fMaxAaxis) continue;
            if (axisA < fMinAaxis || axisB < fMinAaxis) continue;

            Double_t radius = ring->GetRadius();
            Double_t centerX = ring->GetCenterX();
            Double_t centerY = ring->GetCenterY();
            Double_t axisAbefore = ring->GetAaxis();
            Double_t axisBbefore = ring->GetBaxis();
            fh_Abefore->Fill(axisAbefore);
            fh_Bbefore->Fill(axisBbefore);

            Double_t axisA = ring->GetAaxis();
            Double_t axisB = ring->GetBaxis() ;

            axisA += mapaxisAXY->GetBinContent(mapaxisAXY->FindBin(centerX,centerY));
            axisB += mapaxisBXY->GetBinContent(mapaxisBXY->FindBin(centerX,centerY));

            fh_A->Fill(axisA);
            fh_B->Fill(axisB);
        } //iRing
    }//iEvent


  //  gStyle->SetOptStat(0);
    c3 = new TCanvas("c3","c3",10,10,600,600);
    c3->Divide(2,2);
    c3->cd(1);
    fh_Abefore->Scale(1./fh_Abefore->Integral());
    fh_Abefore->SetMaximum(fh_Abefore->GetMaximum()*1.3);
    fh_Abefore->Draw();
    fh_Abefore->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_Abefore->Fit("gaus");
    Double_t sigmaAb = fh_Abefore->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtAb[30];
    sprintf(sigmaTxtAb,"sigma = %.3f",sigmaAb);
    TText* txtAb = new TText(4.3, fh_Abefore->GetMaximum()*0.85, sigmaTxtAb);
    txtAb->SetTextSize(0.1);
    txtAb->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(2);
    fh_Bbefore->Scale(1./fh_Bbefore->Integral());
    fh_Bbefore->SetMaximum(fh_Bbefore->GetMaximum()*1.3);
    fh_Bbefore->Draw();
    fh_Bbefore->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_Bbefore->Fit("gaus");
    Double_t sigmaBb = fh_Bbefore->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtBb[30];
    sprintf(sigmaTxtBb,"sigma = %.3f",sigmaBb);
    TText* txtBb = new TText(4.3, fh_Bbefore->GetMaximum()*0.85, sigmaTxtBb);
    txtBb->SetTextSize(0.1);
    txtBb->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(3);
    fh_A->Scale(1./fh_A->Integral());
    fh_A->SetMaximum(fh_A->GetMaximum()*1.3);
    fh_A->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_A->Draw();
    fh_A->Fit("gaus");
    Double_t sigmaA = fh_A->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtA[30];
    sprintf(sigmaTxtA,"sigma = %.3f",sigmaA);
    TText* txtA = new TText(4.3, fh_A->GetMaximum()*0.85, sigmaTxtA);
    txtA->SetTextSize(0.1);
    txtA->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);

    c3->cd(4);
    fh_B->Scale(1./fh_B->Integral());
    fh_B->SetMaximum(fh_B->GetMaximum()*1.3);
    fh_B->SetAxisRange(fMinAaxis, fMaxAaxis);
    fh_B->Draw();
    fh_B->Fit("gaus");
    Double_t sigmaB = fh_B->GetFunction("gaus")->GetParameter("Sigma");
    char sigmaTxtB[30];
    sprintf(sigmaTxtB,"sigma = %.3f",sigmaB);
    TText* txtB = new TText(4.3, fh_B->GetMaximum()*0.85, sigmaTxtB);
    txtB->SetTextSize(0.1);
    txtB->Draw();
    gPad->SetGridx(true);
    gPad->SetGridy(true);


/// Write correction map to the file
    TFile *file = new TFile("radius_correction_map.root", "recreate");
    mapaxisAXY->Write();
    mapaxisBXY->Write();
    file->Close();

}
Ejemplo n.º 7
0
//!PG main function
int 
  selector (TChain * tree, histos & plots, int if_signal)
{
 
 plots.v_hardTAGPt = -99;
 plots.v_softTAGPt = -99;
 plots.v_TAGDProdEta = -99;
 plots.v_TAGDeta = -99;
 plots.v_TAGMinv = -99;
 plots.v_LepLep = -99;
 plots.v_hardLEPPt = -99;
 plots.v_softLEPPt = -99;
 plots.v_LEPDPhi = -99;
 plots.v_LEPDEta = -99;
 plots.v_LEPDR = -99;
 plots.v_LEPMinv = -99;
 plots.v_LEPProdCharge = -99;
 plots.v_hardLEPCharge = -99;
 plots.v_softLEPCharge = -99;
 plots.v_MET = -99;
 
 plots.v_ojets = -99 ;
 plots.v_ojetsCJV = -99 ;
 plots.v_ojetsRegionalCJV = -99 ;
 
 plots.v_ojetsZepp_01 = -99 ;
 plots.v_ojetsZepp_02 = -99 ;
 plots.v_ojetsZepp_03 = -99 ;
 plots.v_ojetsZepp_04 = -99 ;
 plots.v_ojetsZepp_05 = -99 ;
 plots.v_ojetsZepp_06 = -99 ;
 plots.v_ojetsZepp_07 = -99 ;
 plots.v_ojetsZepp_08 = -99 ;
 plots.v_ojetsZepp_09 = -99 ;
 plots.v_ojetsZepp_10 = -99 ;
 plots.v_ojetsZepp_11 = -99 ;
 plots.v_ojetsZepp_12 = -99 ;
 plots.v_ojetsZepp_13 = -99 ;
 plots.v_ojetsZepp_14 = -99 ;
 
 plots.v_decay_Channel_e = -99 ;
 plots.v_decay_Channel_mu = -99 ;
 plots.v_decay_Channel_tau = -99 ;
 
 
 TClonesArray * genParticles = new TClonesArray ("TParticle") ;
 tree->SetBranchAddress ("genParticles", &genParticles) ;
 
 
//  TClonesArray * tagJets = new TClonesArray ("TLorentzVector") ; 
//  tree->SetBranchAddress ("tagJets", &tagJets) ;
 TClonesArray * otherJets_temp = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress (g_KindOfJet.c_str(), &otherJets_temp) ;
//  tree->SetBranchAddress ("otherJets", &otherJets_temp) ;
 
 
 TClonesArray * electrons = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("electrons", &electrons) ;
 TClonesArray * muons = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("muons", &muons) ;
 TClonesArray * MET = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("MET", &MET) ;
 TClonesArray * tracks = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("tracks", &tracks) ;
 
 TClonesArray * tagJets = new TClonesArray ("TLorentzVector") ; 
 TClonesArray * otherJets = new TClonesArray ("TLorentzVector") ;
 
  
 int EleId[100];
 float IsolEleSumPt_VBF[100];
 int nEle;
 int EleCharge[30];
 tree->SetBranchAddress ("nEle", &nEle) ;
 tree->SetBranchAddress ("EleId",EleId ) ;
 tree->SetBranchAddress ("IsolEleSumPt_VBF",IsolEleSumPt_VBF ) ;
 tree->SetBranchAddress ("EleCharge",EleCharge ) ;
 
 float IsolMuTr[100];
 int nMu ;
 int MuCharge[30];
 tree->SetBranchAddress ("nMu", &nMu) ;
 tree->SetBranchAddress ("IsolMuTr",IsolMuTr ) ;
 tree->SetBranchAddress ("MuCharge", MuCharge) ;
 

 int IdEvent;
 tree->SetBranchAddress ("IdEvent", &IdEvent) ;
 
 
 int nentries = (int) tree->GetEntries () ;

 
 plots.passedJetAndLepNumberSelections = 0;
 plots.analyzed = 0;
 
 plots.analyzed_ee = 0;
 plots.analyzed_mumu = 0;
 plots.analyzed_tautau = 0;
 plots.analyzed_emu = 0;
 plots.analyzed_etau = 0;
 plots.analyzed_mutau = 0;
  
 plots.passedJetAndLepNumberSelections_ee = 0;
 plots.passedJetAndLepNumberSelections_mumu = 0;
 plots.passedJetAndLepNumberSelections_tautau = 0;
 plots.passedJetAndLepNumberSelections_emu = 0;
 plots.passedJetAndLepNumberSelections_etau = 0;
 plots.passedJetAndLepNumberSelections_mutau = 0;

 
 
 //PG loop over the events
 for (int evt = 0 ; evt < nentries ; ++evt)
 {

  tree->GetEntry (evt) ;
  
  tagJets -> Clear () ;  
  otherJets -> Clear () ;    
  
  
    //---- check if signal ----
  if (if_signal && (IdEvent!=123 && IdEvent!=124)) continue;
  plots.analyzed++;
  
   //!---- MC ----

  if (IdEvent==123 || IdEvent==124) { //---- VBF event ----
   plots.v_decay_Channel_e = 0;
   plots.v_decay_Channel_mu = 0;
   plots.v_decay_Channel_tau = 0;
   for (int iGen = 0; iGen < genParticles->GetEntries() ; ++iGen){
    TParticle* myparticle = (TParticle*) genParticles->At(iGen);
    if (abs(myparticle->GetPdgCode()) == 24) { //---- W
     Int_t mother1 = 0;
     mother1 = myparticle->GetMother(0);
     if (mother1 == 25) { //---- mother is higgs ----
      for (int iDaughter = 0; iDaughter<2; iDaughter++){
       if (abs(myparticle->GetDaughter(iDaughter)) == 11) {//---- W -> e
        plots.v_decay_Channel_e++;
       }
       if (abs(myparticle->GetDaughter(iDaughter)) == 13) {//---- W -> mu    
        plots.v_decay_Channel_mu++;
       }
       if (abs(myparticle->GetDaughter(iDaughter)) == 15) {//---- W -> tau
        plots.v_decay_Channel_tau++;
       }       
      }
     }
    }
   }
  }

  if (plots.v_decay_Channel_e == 2) plots.analyzed_ee++;
  if (plots.v_decay_Channel_mu == 2) plots.analyzed_mumu++;
  if (plots.v_decay_Channel_tau == 2) plots.analyzed_tautau++;
  if (plots.v_decay_Channel_e == 1 && plots.v_decay_Channel_mu == 1) plots.analyzed_emu++;
  if (plots.v_decay_Channel_e == 1 && plots.v_decay_Channel_tau == 1) plots.analyzed_etau++;
  if (plots.v_decay_Channel_mu == 1 && plots.v_decay_Channel_tau == 1) plots.analyzed_mutau++;
  
  
  
  
  
  
  
  int cutId = 0 ;

  plots.increase (cutId++) ; //AM 0 -> total number of events


//   std::cerr << "--- preambolo leptoni " << std::endl;           
  
  std::vector<lepton> leptons ;
            
      //PG pour electrons into leptons collection
      //PG ---------------------------------------

      //PG loop over electrons
  for (int iele = 0; iele < electrons->GetEntries () ; ++iele)
  {
   TLorentzVector * theEle = (TLorentzVector*) (electrons->At (iele)) ;
   lepton dummy (theEle, 0, iele) ;
   leptons.push_back (dummy) ;
  } //PG loop over electrons

      //PG loop over muons
  for (int imu = 0 ; imu < nMu ; ++imu)
  {
   TLorentzVector * theMu = (TLorentzVector*) (muons->At (imu)) ;
   lepton dummy (theMu, 1, imu) ;
   leptons.push_back (dummy) ;
  } //PG loop over muons

//PG this check is not necessary
//PG      if (leptons.size () < 2) continue ;

  
  
//   std::cerr << "--- inizia leptoni " << std::endl;
  
  
      //PG 2 LEPTONS
      //PG ---------

/* 
applied after the leptons choice: 
  in this case it is possible to differentiate the selections depending on the 
  position of each lepton in the pt-sorting.
  the algorithm searches the first two most energetic candidates which satisfy 
  the ID selections required for the first and second lepton respectively.
  
  Then check for channel analysis according to "g_LepLep"
     0 == ee
     1 == mumu
     2 == emu
     3 == mue
  pt ordered
  
*/

  sort (leptons.rbegin (), leptons.rend (), lessThan ()) ;

  lepton primoLEP ;
  lepton secondoLEP ;

  double first_lepton_charge = 0;
  double second_lepton_charge = 0;
  
  int lepton_counter = 0;
  int electron_counter = 0;
  int muon_counter = 0;
    
      //PG find the first lepton
  int ilep = 0 ;
  for ( ; ilep < leptons.size () ; ++ilep)
  {
   if (leptons.at (ilep).m_flav == 0) //PG electron
   {
               //PG iso check
    bool eleIso = (IsolEleSumPt_VBF[leptons.at (ilep).m_index] /  
      leptons.at (ilep).m_kine->Pt () ) < g_IsoElectron ; // 0.2 per il momento
    if (g_ISO1[0] == 1 && eleIso != 1) continue;
              
              //PG eleID check
    int eleID = EleId[leptons.at (ilep).m_index] ;
    if      (g_ID1 == 100 && (eleID/100) != 1) continue;
    else if (g_ID1 == 10  && ((eleID%100)/10) != 1) continue;
    else if (g_ID1 == 1   && (eleID%10) != 1) continue;
    first_lepton_charge = EleCharge[leptons.at (ilep).m_index];
   }
   else //PG muon
   {
              //PG iso check
    bool muIso = (IsolMuTr[leptons.at (ilep).m_index] /  
      leptons.at (ilep).m_kine->Pt () ) < g_IsoMuon ; 
    if (g_ISO1[1] == 1 && muIso != 1) continue;
    first_lepton_charge = MuCharge[leptons.at (ilep).m_index];
   }  
   primoLEP = leptons[ilep] ;
   lepton_counter++;
   if (leptons.at (ilep).m_flav == 0) electron_counter++;
   else muon_counter++;
   break ;
   } //PG find the first lepton

  
      //PG find the second lepton
  bool flag_secondoLEP = false;
  for (++ilep ; ilep < leptons.size () ; ++ilep)
  {
   if (leptons.at (ilep).m_flav == 0) //PG electron
   {
               //PG iso check
    bool eleIso = (IsolEleSumPt_VBF[leptons.at (ilep).m_index] /  
      leptons.at (ilep).m_kine->Pt () ) < g_IsoElectron ; // 0.2 per il momento
    if (g_ISO2[0] == 1 && eleIso != 1) continue;
              
              //PG eleID check
    int eleID = EleId[leptons.at (ilep).m_index] ;
    if      (g_ID2 == 100 && (eleID/100) != 1) continue;
    else if (g_ID2 == 10  && ((eleID%100)/10) != 1) continue;
    else if (g_ID2 == 1   && (eleID%10) != 1) continue;
    second_lepton_charge = EleCharge[leptons.at (ilep).m_index];
   }
   else //PG muon
   {
              //PG iso check
    bool muIso = (IsolMuTr[leptons.at (ilep).m_index] /  
      leptons.at (ilep).m_kine->Pt () ) < g_IsoMuon ; 
    if (g_ISO2[1] == 1 && muIso != 1) continue;
    second_lepton_charge = MuCharge[leptons.at (ilep).m_index];
   }  
   if (!flag_secondoLEP) {
    secondoLEP = leptons[ilep] ;
    flag_secondoLEP = true;
   }
   
   if (leptons.at (ilep).m_kine->Pt () > 0) {
    if (leptons.at (ilep).m_flav == 0) electron_counter++;
    else muon_counter++;
    lepton_counter++;
    }
   
  } //PG find the second lepton

 //---- AM 3 --- 2 leptons after Id      
 if (primoLEP.m_flav == -1 || secondoLEP.m_flav == -1) continue ;
  
 //---- AM 4 check for the two most transverse-energetic leptons have the right flavours
  
 plots.v_numLep = lepton_counter;
 plots.v_numEle = electron_counter;
 plots.v_numMu = muon_counter; 
 
 if (primoLEP.m_flav == 0 && secondoLEP.m_flav == 0) plots.v_LepLep = 0 ;
 if (primoLEP.m_flav == 1 && secondoLEP.m_flav == 1) plots.v_LepLep = 1 ;
 if (primoLEP.m_flav == 0 && secondoLEP.m_flav == 1) plots.v_LepLep = 2 ;
 if (primoLEP.m_flav == 1 && secondoLEP.m_flav == 0) plots.v_LepLep = 3 ;

      
      
 plots.v_hardLEPPt = primoLEP.m_kine->Pt () ; 
   //---- AM 5 pt_min of the most energetic lepton
  
 plots.v_softLEPPt = secondoLEP.m_kine->Pt () ;
   //---- AM 6 pt_min of the least energetic lepton
   
 plots.v_LEPDPhi = deltaPhi (primoLEP.m_kine->Phi (), secondoLEP.m_kine->Phi ()) ;
  //---- AM 7 Delta_phi_min between leptons

 plots.v_LEPDEta = deltaEta (primoLEP.m_kine->Eta (), secondoLEP.m_kine->Eta ()) ;
 plots.v_LEPDR = deltaR (primoLEP.m_kine->Phi (),primoLEP.m_kine->Eta (), secondoLEP.m_kine->Phi (), secondoLEP.m_kine->Eta ()) ;

 
   
  TLorentzVector sumLEP = *(primoLEP.m_kine) + *(secondoLEP.m_kine) ;
  plots.v_LEPMinv = sumLEP.M () ;
  //---- AM 9 MInv_min of leptons
  
  
  plots.v_LEPProdCharge = first_lepton_charge * second_lepton_charge ;
  plots.v_hardLEPCharge = first_lepton_charge ;
  plots.v_softLEPCharge = second_lepton_charge ;
      
  
      //PG MET
      //PG ---

//   std::cerr << "--- finito " << std::endl;
  
  TLorentzVector* met = ((TLorentzVector*) (MET->At(0))) ;
      //correct for muons
  for (int i = 0 ; i < nMu ; i++)
  {
   TLorentzVector * mu_v = (TLorentzVector*) (muons->At (i)) ;
   
   if (mu_v->Pt () > 3)
   {
    met->SetPx (met->Px () - mu_v->Px ()) ;
    met->SetPy (met->Py () - mu_v->Py ()) ;
   }
  }      
  
  plots.v_MET = met->Pt () ;
  
  
 
  

    
    
    
  //---- AM 11 Met_min ----------------> Met correction ?
  
//      if (((TLorentzVector*) (MET->At (0)))->Pt () < g_METMin) continue ; plots.increase (cutId++) ; //PG 10
      
  
  
  
  

      //PG Ztautau vetos
      //PG -------------
      
      //PG the two electrons should not be opposite to each other
//       
//   TVector2 primoLEPT (primoLEP.m_kine->X (), primoLEP.m_kine->Y ()) ;
//   TVector2 secondoLEPT (secondoLEP.m_kine->X (), secondoLEP.m_kine->Y ()) ;
//   TVector2 METT (met->X (), met->Y ()) ;
// 
//   double Sum = METT * primoLEPT + METT * secondoLEPT / (1 + primoLEPT * secondoLEPT) ;
//   double Dif = METT * primoLEPT - METT * secondoLEPT / (1 - primoLEPT * secondoLEPT) ;
//       
//   TVector2 METT1 = 0.5 * (Sum + Dif) * primoLEPT ;
//   TVector2 METT2 = 0.5 * (Sum - Dif) * secondoLEPT ;
//       
//   double ptNu1 = METT1.Mod () / cos (primoLEP.m_kine->Theta ()) ;
//   double ptNu2 = METT2.Mod () / cos (secondoLEP.m_kine->Theta ()) ;

  
  
  
  
  plots.m_tree_selections->Fill();
  plots.passedJetAndLepNumberSelections++;

  if (plots.v_decay_Channel_e == 2) plots.passedJetAndLepNumberSelections_ee++;
  if (plots.v_decay_Channel_mu == 2) plots.passedJetAndLepNumberSelections_mumu++;
  if (plots.v_decay_Channel_tau == 2) plots.passedJetAndLepNumberSelections_tautau++;
  if (plots.v_decay_Channel_e == 1 && plots.v_decay_Channel_mu == 1) plots.passedJetAndLepNumberSelections_emu++;
  if (plots.v_decay_Channel_e == 1 && plots.v_decay_Channel_tau == 1) plots.passedJetAndLepNumberSelections_etau++;
  if (plots.v_decay_Channel_mu == 1 && plots.v_decay_Channel_tau == 1) plots.passedJetAndLepNumberSelections_mutau++;
   
    
 } //PG loop over the events


 plots.m_efficiency->Fill();
 plots.m_efficiency->Write();
 plots.m_tree_selections->Write();

 delete otherJets_temp ;
 delete tagJets  ;  
 delete otherJets  ;
 delete electrons  ;
 delete muons  ;    
 delete MET  ;      
 delete tracks  ;   

 return 0;
  
}
int main(int argc, char **argv){
	std::cout.precision(4);
	// Counting time
	Double_t initialTime = clock();

	/*
	 * Histograms
	 */
	// All jets
	TH1 *h_numberJet = new TH1F("Number Jets","Number Jets",11,-0.5,10.5);

	// Non Isr jets
	TH1 *h_jet_PT = new TH1F("Jet PT","Jet PT", 201,0.0,600.0);
	TH1 *h_jet_Eta = new TH1F("Jet Eta","Jet Eta", 171,-5.0,5.0);
	TH1 *h_jet_Phi = new TH1F("Jet Phi","Jet Phi", 375,-3.5,3.5);
	TH1 *h_jet_DPhi_MET = new TH1F("Jet - MET Delta_Phi","Jet - MET Delta_Phi",300,0.0,4.0);
	TH1 *h_jet_DPhi_MET_hpt = new TH1F("Jet - MET Delta_Phi_hpt","Jet - MET Delta_Phi_hpt",300,0.0,4.0);
	TH1 *h_jet_MT = new TH1F("Jet Transverse mass","Jet Transverse Mass",201,0.0,600.0);
	TH1 *h_jet_Delta_PT = new TH1F("Jet Delta-PT","Non ISR Delta-PT", 201,0.0,300.0);
	TH1 *h_jet_PT_HT = new TH1F("Jet PT-HT ratio","Jet PT-HT ratio",201,-0.0025,1.0025);
	TH1 *h_jet_PT_over_PT_others = new TH1F("Jet PT/PT_others","Jet PT/PT_others",401,-0.0025,2.0025);
	TH1 *h_jet_Eta_over_Eta_others = new TH1F("Jet Eta/Eta_others","Jet Eta/Eta_others",401,-0.0025,2.0025);
	TH1 *h_jet_DPhi_over_Phi_others = new TH1F("Jet Phi/Phi_others","Jet Phi/Phi_others",401,-0.0025,2.0025);
	TH1 *h_jet_Delta_Eta = new TH1F("Jet Delta-Eta","Jet Delta-Eta", 171,0.0,5.0);
	TH1 *h_jet_DPhi_MET_other = new TH1F("Jet - MET Delta_Phi other","Jet - MET Delta_Phi other",300,0.0,4.0);
	TH1 *h_jet_multiplicity = new TH1F("Jet - Multiplicity","Jet - Multiplicity",101,-0.5,100.5);
	TH1 *h_jet_DeltaR = new TH1F ("Jet - Delta_R","Jet - Delta_R",201,-0.0025,0.8025);
	TH1 *h_jet_Delta_PT_leading = new TH1F("Delta PT: leading - Jet","Delta PT: leading - Jet", 201,0.0,600.0);
	TH1 *h_jet_Delta_Eta_leading = new TH1F("Delta Eta: Jet - leading","Delta Eta: Jet - leading", 171,0.0,8.0);

	TH2 *h2_jet_PTEta=new TH2F("Non_ISR_Jet_PT_Eta","Non ISR Jet PT Vs. Eta",201,-1.25,501.25,201,-4.02,4.02);

	// ISR jets
	TH1 *h_ISR_PT = new TH1F("ISR PT","ISR PT", 201,0.0,600.0);
	TH1 *h_ISR_Eta = new TH1F("ISR Eta","ISR Eta", 171,-5.0,5.0);
	TH1 *h_ISR_Phi = new TH1F("ISR Phi","ISR Phi", 375,-3.5,3.5);
	TH1 *h_ISR_DPhi_MET = new TH1F("ISR - MET Delta_Phi","ISR - MET Delta_Phi",300,0.0,4.0);
	TH1 *h_ISR_DPhi_MET_hpt = new TH1F("ISR - MET Delta_Phi_hpt","ISR - MET Delta_Phi_hpt",300,0.0,4.0);
	TH1 *h_ISR_MT = new TH1F("ISR Transverse mass","ISR Transverse Mass",201,0.0,600.0);
	TH1 *h_ISR_Delta_PT = new TH1F("ISR Delta-PT","ISR Delta-PT", 201,0.0,300.0);
	TH1 *h_ISR_PT_HT = new TH1F("ISR PT-HT ratio","ISR PT-HT ratio",201,-0.0025,1.0025);
	TH1 *h_ISR_PT_over_PT_others = new TH1F("ISR PT/PT_others","ISR PT/PT_others",401,-0.0025,2.0025);
	TH1 *h_ISR_Eta_over_Eta_others = new TH1F("ISR Eta/Eta_others","ISR Eta/Eta_others",401,-0.0025,2.0025);
	TH1 *h_ISR_DPhi_over_Phi_others = new TH1F("ISR Phi/Phi_others","ISR Phi/Phi_others",401,-0.0025,2.0025);
	TH1 *h_ISR_Delta_Eta = new TH1F("ISR Delta-Eta","ISR Delta-Eta", 171,0.0,5.0);
	TH1 *h_ISR_DPhi_MET_other = new TH1F("ISR - MET Delta_Phi other","ISR - MET Delta_Phi other",300,0.0,4.0);
	TH1 *h_ISR_multiplicity = new TH1F("ISR - Multiplicity","ISR - Multiplicity",101,-0.5,100.5);
	TH1 *h_ISR_DeltaR = new TH1F ("ISR - Delta_R","ISR - Delta_R",201,-0.0025,0.8025);
	TH1 *h_ISR_Delta_PT_leading = new TH1F("Delta PT: leading - ISR","Delta PT: leading - ISR", 201,0.0,600.0);
	TH1 *h_ISR_Delta_Eta_leading = new TH1F("Delta Eta: ISR - leading","Delta Eta: ISR - leading", 171,0.0,8.0);

	TH2 *h2_ISR_PTEta=new TH2F("ISR_Jet_PT_Eta","ISR Jet PT Vs. Eta",201,-1.25,501.25,201,-4.02,4.02);

	// MET
	TH1 *h_MET = new TH1F("Missing ET","Missing ET",200,0,600);
	TH1 *h_MET_hpt1 = new TH1F("Missing ET high_ISR_pt-1","Missing ET high_ISR_pt-1",200,0.0,600.0);
	TH1 *h_MET_hpt2 = new TH1F("Missing ET high_ISR_pt-2","Missing ET high_ISR_pt-2",200,0.0,600.0);
	TH1 *h_MET_hpt3 = new TH1F("Missing ET high_ISR_pt-3","Missing ET high_ISR_pt-3",200,0.0,600.0);
	TH1 *h_MET_hpt4 = new TH1F("Missing ET high_ISR_pt-4","Missing ET high_ISR_pt-4",200,0.0,600.0);

	TH2 *h2_dif_PTEta=new TH2F("FSR_ISR_Jet_PT_Eta_Difference","Difference between FSR and ISR Jet PT Vs. Eta distributions",201,-1.25,501.25,201,-4.02,4.02);
	TH2 *h2_dif_lead_PTEta=new TH2F("Lead_ISR_Jet_PT_Eta_Difference","Difference between Lead and ISR Jet PT Vs. Eta distributions",201,-1.25,501.25,201,-4.02,4.02);

	// Leading PT
	TH1 *h_leading_PT = new TH1F("Leading PT","Leading PT", 201,0.0,600.0);
	TH1 *h_leading_MT = new TH1F("Leading Transverse mass","Leading Transverse Mass",201,0.0,600.0);
	TH1 *h_leading_Eta = new TH1F("Leading Eta","Leading Eta", 171,-5.0,5.0);
	TH1 *h_leading_DPhi_MET = new TH1F("Leading - MET Delta_Phi","Leading - MET Delta_Phi",300,0.0,4.0);

	TH2 *h2_leading_PTEta=new TH2F("Leading_Jet_PT_Eta","Leading Jet PT Vs. Eta",201,-1.25,501.25,201,-4.02,4.02);

	// Other variables
	TH1 *h_HT = new TH1F("HT","HT",201,0.0,600.0);
	TH1 *h_HT_R1 = new TH1F("HT_R1","HT_R1",51,-0.01,1.01);
	TH1 *h_HT_R2 = new TH1F("HT_R2","HT_R2",51,-0.01,1.01);

	// B tagging
	TH1 *h_BTag = new TH1F("BTag","BTag",5,-0.5,4.5);
	TH1 *h_BTag_PT = new TH1F("BTag PT","BTag PT", 201,0.0,600.0);
	TH1 *h_BTag_Eta = new TH1F("BTag Eta","BTag Eta", 171,-5.0,5.0);
	TH1 *h_BTag_DPhi_MET = new TH1F("BTag - MET Delta_Phi","BTag - MET Delta_Phi",300,0.0,4.0);
	TH1 *h_BTags_per_Event = new TH1F("BTags per event","BTags per event",5,-0.5,4.5);

	// Further analysis
	TH1 *h_ISR_PT_comp = new TH1F("ISR PT for comparison","ISR PT for comparison with histo", 20,0.0,800.0);
	TH1 *h_ISR_Eta_comp = new TH1F("ISR Eta for comparison","ISR Eta for comparison with histo", 20,-4.2,4.2);
	TH1 *h_ISR_DPhi_MET_comp = new TH1F("ISR Phi for comparison","ISR Phi for comparison with histo", 20,0,PI);

	// To check the histograms' creation
	TH1 *hist_ISR_PT = new TH1F("ISR PT comp","ISR PT comp", 20,0.0,800.0);
	TH1 *hist_ISR_Abs_Eta = new TH1F("ISR Abs Eta comp","ISR Abs Eta comp", 20,0.0,5.2);
	TH1 *hist_ISR_DPhi_MET = new TH1F("ISR Delta Phi comp","ISR Delta Phi comp", 20,0.0,PI);
	TH1 *hist_ISR_PT_ratio = new TH1F("ISR PT/PT_others comp","ISR PT/PT_others comp",20,0.0,8.0);
	TH1 *hist_ISR_Delta_Eta = new TH1F("ISR Delta-Eta comp","ISR Delta-Eta comp", 20,0.0,7.0);
	TH1 *hist_ISR_DPhi_MET_other = new TH1F("ISR - MET Delta_Phi other comp","ISR - MET Delta_Phi other comp",20,0.0,PI);
	TH1 *hist_ISR_Delta_PT_leading = new TH1F("Delta PT: leading - ISR comp","Delta PT: leading - ISR comp", 20,0.0,500.0);
	TH1 *hist_ISR_Delta_Eta_leading = new TH1F("Delta Eta: ISR - leading comp","Delta Eta: ISR - leading comp", 20,0.0,6.5);
	TH1 *hist_jet_PT = new TH1F("Jet PT comp","Jet PT comp", 20,0.0,800.0);
	TH1 *hist_jet_Abs_Eta = new TH1F("Jet Abs Eta comp","Jet Abs Eta comp", 20,0.0,5.2);
	TH1 *hist_jet_DPhi_MET = new TH1F("Jet Delta Phi comp","Jet Delta Phi comp", 20,0.0,PI);
	TH1 *hist_jet_PT_ratio = new TH1F("Jet PT/PT_others comp","Jet PT/PT_others comp",20,0.0,7.0);
	TH1 *hist_jet_Delta_Eta = new TH1F("Jet Delta-Eta comp","Jet Delta-Eta comp", 20,0.0,8.0);
	TH1 *hist_jet_DPhi_MET_other = new TH1F("Jet - MET Delta_Phi other comp","Jet - MET Delta_Phi other comp",20,0.0,PI);
	TH1 *hist_jet_Delta_PT_leading = new TH1F("Delta PT: leading - Jet comp","Delta PT: leading - Jet comp", 20,0.0,500.0);
	TH1 *hist_jet_Delta_Eta_leading = new TH1F("Delta Eta: Jet - leading comp","Delta Eta: Jet - leading comp", 20,0.0,6.5);

	for(int iRun = 1; iRun < 11; iRun ++){
		// Create chains of root trees
		TChain chain_Delphes("Delphes");

		// Loading simulations from Delphes
		Char_t *local_path;
		local_path = (Char_t*) malloc(512*sizeof(Char_t));
		if (atServer)
			strcpy(local_path,"/home/af.garcia1214/PhenoMCsamples/Simulations/MG_pythia8_delphes_parallel/"); // At the server
		else
			strcpy(local_path,"/home/afgarcia1214/Documentos/Simulations/"); // At the University's pc

		Char_t *head_folder;
		head_folder = (Char_t*) malloc(512*sizeof(Char_t));
		if (Matching)
			strcpy(head_folder,"_Tops_Events_WI_Matching/");
		else
			strcpy(head_folder,"_Tops_Events_WI/");
		head_folder[0] = channel;
		head_folder[13] = ISR_or_NOT[0];
		head_folder[14] = ISR_or_NOT[1];

		Char_t current_folder[] = "_Tops_MG_1K_AG_WI_003/";
		current_folder[0] = channel;
		current_folder[15] = ISR_or_NOT[0];
		current_folder[16] = ISR_or_NOT[1];

		Char_t unidad = 0x30 + iRun%10;
		Char_t decena = 0x30 + int(iRun/10)%10;
		Char_t centena = 0x30 + int(iRun/100)%10;

		current_folder[18] = centena;
		current_folder[19] = decena;
		current_folder[20] = unidad;

		Char_t *file_delphes;
		file_delphes = (Char_t*) malloc(512*sizeof(Char_t));
		strcpy(file_delphes,local_path);
		strcat(file_delphes,head_folder);
		strcat(file_delphes,current_folder);
		strcat(file_delphes,"Events/run_01/output_delphes.root");

		cout << "\nReading the file: \nDelphes: " << file_delphes << endl;

		chain_Delphes.Add(file_delphes);
		// Objects of class ExRootTreeReader for reading the information
		ExRootTreeReader *treeReader_Delphes = new ExRootTreeReader(&chain_Delphes);

		Long64_t numberOfEntries = treeReader_Delphes->GetEntries();

		// Get pointers to branches used in this analysis
		TClonesArray *branchJet = treeReader_Delphes->UseBranch("Jet");
		TClonesArray *branchMissingET = treeReader_Delphes->UseBranch("MissingET");

		cout << endl;
		cout << " Number of Entries Delphes = " << numberOfEntries << endl;
		cout << endl;

		// particles, jets and vectors
		MissingET *METpointer;
		TLorentzVector *vect_currentJet = new TLorentzVector;
		TLorentzVector *vect_auxJet = new TLorentzVector;
		TLorentzVector *vect_leading = new TLorentzVector;
		Jet *currentJet = new Jet;
		Jet *auxJet = new Jet;
		TRefArray array_temp;

		// Temporary variables
		Double_t MET = 0.0; // Missing transverse energy
		Double_t delta_phi = 0.0; // difference between the phi angle of MET and the jet
		Double_t transverse_mass = 0.0; // Transverse mass
		Double_t HT = 0.0; // Sum of jets' PT
		Double_t HT_R1 = 0.0; // Sum of jets' PT which are in the same hemisphere of the ISR jet hemisphere
		Double_t HT_R2 = 0.0; // Sum of jets' PT which are in the opposite hemisphere of the ISR jet hemisphere
		Double_t ISR_Eta = 0.0; // Pseudorapidity of the ISR jet
		Int_t number_Btags = 0; // Number of B jets per event
		Int_t ISR_Btags = 0; // Number of BTags which are also ISR jets
		Double_t delta_PT_jet = 0.0; // |PT-<PT>|
		Double_t PT_sum = 0.0; // sum(PT)
		Double_t PT_aver = 0.0; // <PT>
		Double_t Delta_eta_aver = 0.0; // sum_i|eta-eta_i|/(Nj-1)
		Double_t Delta_phi_sum = 0.0; // sum delta_phi
		Double_t Delta_phi_other_jets = 0.0; // Average of delta phi of other jets
		Double_t PT_ratio = 0.0; // PT/PT_others
		Double_t Eta_ratio = 0.0; // Eta/Eta_others
		Double_t Eta_sum = 0.0; // sum(Eta)
		Double_t Delta_R = 0.0; // Size of the jet
		Double_t Delta_phi_ratio = 0.0; // Delta_phi/Delta_phi_others
		Double_t Delta_PT_leading = 0.0; // PT - PT_leading
		Double_t Delta_Eta_leading = 0.0; // |Eta - Eta_leading|

		/*
		 * Some variables used through the code
		 */
		Int_t ISR_jets[numberOfEntries];
		Int_t NumJets = 0;

	    Char_t *local_path_binary;
	    local_path_binary = (Char_t*) malloc(512*sizeof(Char_t));
	    if (atServer)
	    	strcpy(local_path_binary,"/home/af.garcia1214/PhenoMCsamples/Results/matching_Results/"); // At the server
	    else
	    	strcpy(local_path_binary,"/home/afgarcia1214/Documentos/Results_and_data/matching_Results/"); // At the University's pc

		Char_t *head_folder_binary;
		head_folder_binary = (Char_t*) malloc(512*sizeof(Char_t));
		if (Matching)
			strcpy(head_folder_binary,"_Tops_matchs_WI_Matching/");
		else
			strcpy(head_folder_binary,"_Tops_matchs_WI/");
	    head_folder_binary[0] = channel;
	    head_folder_binary[13] = ISR_or_NOT[0];
	    head_folder_binary[14] = ISR_or_NOT[1];

	    Char_t matching_name[] = "ISR_jets_Tops_WI_003.bn";
	    matching_name[8] = channel;
	    matching_name[14] = ISR_or_NOT[0];
	    matching_name[15] = ISR_or_NOT[1];

		matching_name[17] = centena;
		matching_name[18] = decena;
		matching_name[19] = unidad;

	    Char_t * fileName;
	    fileName = (Char_t*) malloc(512*sizeof(Char_t));
	    strcpy(fileName,local_path_binary);
	    strcat(fileName,head_folder_binary);
	    strcat(fileName,matching_name);

		ifstream ifs(fileName,ios::in | ios::binary);

		for (Int_t j = 0; j<numberOfEntries; j++){
				ifs.read((Char_t *) (ISR_jets+j),sizeof(Int_t));
		}
		ifs.close();

		// Jet with greatest PT
		Double_t PT_max = 0;
		Int_t posLeadingPT = -1;
		Int_t ISR_greatest_PT = 0;
		Double_t MT_leading_jet = 0.0; // Transverse mass

		/*
		 * Main cycle of the program
		 */
		numberOfEntries = 100000;
		for (Int_t entry = 0; entry < numberOfEntries; ++entry){
			// Progress
			if(numberOfEntries>10 && (entry%((int)numberOfEntries/10))==0.0){
				cout<<"progress = "<<(entry*100/numberOfEntries)<<"%\t";
				cout<< "Time :"<< (clock()-initialTime)/double_t(CLOCKS_PER_SEC)<<"s"<<endl;
			}

			// Load selected branches with data from specified event
			treeReader_Delphes->ReadEntry(entry);

			// MET
			METpointer = (MissingET*) branchMissingET->At(0);
			MET = METpointer->MET;
			h_MET->Fill(MET);

			NumJets=branchJet->GetEntries();
			h_numberJet->Fill(NumJets);

			// checking the ISR
			if (ISR_jets[entry] == -1 || NumJets < 3)
				continue;

			PT_max = 0;
			posLeadingPT = -1;
			HT = 0;
			HT_R1 = 0;
			HT_R2 = 0;
			number_Btags = 0;

			delta_PT_jet = 0.0;
			PT_aver = 0.0;
			PT_sum = 0.0;
			Delta_eta_aver = 0.0;
			Delta_phi_sum = 0.0;
			Delta_phi_other_jets = 0.0;
			Delta_phi_ratio = 0.0;
			Delta_PT_leading = 0.0;
			Delta_Eta_leading = 0.0;

			PT_ratio = 0.0;
			Eta_ratio = 0.0;
			Eta_sum = 0.0;

			Delta_R = 0.0;

			if (ISR_jets[entry] >= NumJets){
				cout << "Error en el matching" << endl;
				return 1;
			}

			// Preliminary for. It is used to calculate PT_aver and Delta_phi_sum
			for (Int_t iJet = 0; iJet<NumJets; iJet++){
				currentJet = (Jet*) branchJet->At(iJet);
				vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
				delta_phi = deltaAng(vect_currentJet->Phi(), METpointer->Phi);
				PT_sum += vect_currentJet->Pt();
				Eta_sum += vect_currentJet->Eta();
				Delta_phi_sum += delta_phi;
				// HT
				HT += vect_currentJet->Pt();
				// HT ratios
				if((vect_currentJet->Eta()*ISR_Eta) > 0)
					HT_R1 += vect_currentJet->Pt();
				else
					HT_R2 += vect_currentJet->Pt();
				// PT Leading jet
				if(PT_max < vect_currentJet->Pt()){
					PT_max = vect_currentJet->Pt();
					posLeadingPT = iJet;
				}
			}

			//PT_aver
			PT_aver = PT_sum/NumJets;

			// Leading PT
			currentJet = (Jet*) branchJet->At(posLeadingPT);
			vect_leading->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);

			// ISR jet
			currentJet = (Jet*) branchJet->At(ISR_jets[entry]);
			vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
			ISR_Eta = vect_currentJet->Eta();

			for (Int_t iJet = 0; iJet<NumJets; iJet++){
				currentJet = (Jet*) branchJet->At(iJet);
				vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
				delta_phi = deltaAng(vect_currentJet->Phi(), METpointer->Phi);
				transverse_mass = sqrt(2*vect_currentJet->Pt()*MET*(1-cos(delta_phi)));

				// Correlated variables
				delta_PT_jet = TMath::Abs(vect_currentJet->Pt()-PT_aver);
				Delta_phi_other_jets = (Delta_phi_sum-delta_phi)/(NumJets-1);
				PT_ratio = vect_currentJet->Pt()*(NumJets-1)/(PT_sum-vect_currentJet->Pt());
				Eta_ratio = vect_currentJet->Eta()*(NumJets-1)/(Eta_sum-vect_currentJet->Eta());
				Delta_phi_ratio = delta_phi*(NumJets-1)/(Delta_phi_sum-delta_phi);

				Delta_Eta_leading = TMath::Abs(vect_currentJet->Eta()-vect_leading->Eta());
				Delta_PT_leading = vect_leading->Pt()-vect_currentJet->Pt();

				Delta_eta_aver = 0.0;
				// For cycle used to calculate Delta_eta_aver
				for(Int_t iJet2 = 0; iJet2<NumJets; iJet2++){
					auxJet = (Jet*) branchJet->At(iJet2);
					vect_auxJet->SetPtEtaPhiM(auxJet->PT,auxJet->Eta,auxJet->Phi,auxJet->Mass);
					if (iJet2 != iJet) Delta_eta_aver += TMath::Abs(vect_auxJet->Eta()-vect_currentJet->Eta());
				}
				Delta_eta_aver = Delta_eta_aver/(NumJets-1);
				Delta_R = sqrt(pow(currentJet->DeltaEta,2)+pow(currentJet->DeltaPhi,2));

				// Multiplicity
				array_temp = (TRefArray) currentJet->Constituents;

				if (iJet != ISR_jets[entry]){ // Non ISR
					h_jet_PT->Fill(vect_currentJet->Pt());
					h_jet_Eta->Fill(vect_currentJet->Eta());
					h_jet_Phi->Fill(vect_currentJet->Phi());
					h_jet_DPhi_MET->Fill(delta_phi);
					h_jet_MT->Fill(transverse_mass);
					h_jet_Delta_PT->Fill(delta_PT_jet);
					h_jet_Delta_Eta->Fill(Delta_eta_aver);
					h_jet_DPhi_MET_other->Fill(Delta_phi_other_jets);
					h_jet_PT_HT->Fill(vect_currentJet->Pt()/HT);
					h_jet_multiplicity->Fill(array_temp.GetEntries());
					h_jet_PT_over_PT_others->Fill(PT_ratio);
					h_jet_Eta_over_Eta_others->Fill(Eta_ratio);
					h_jet_DeltaR->Fill(Delta_R);
					h_jet_DPhi_over_Phi_others->Fill(Delta_phi_ratio);
					h_jet_Delta_PT_leading->Fill(Delta_PT_leading);
					h_jet_Delta_Eta_leading->Fill(Delta_Eta_leading);
					if (vect_currentJet->Pt()>240)
						h_jet_DPhi_MET_hpt->Fill(delta_phi);
					h2_jet_PTEta->Fill(vect_currentJet->Pt(),vect_currentJet->Eta());

					// For testing creating histo
					hist_jet_PT->Fill(vect_currentJet->Pt());
					hist_jet_Abs_Eta->Fill(TMath::Abs(vect_currentJet->Eta()));
					hist_jet_DPhi_MET->Fill(delta_phi);
					hist_jet_PT_ratio->Fill(PT_ratio);
					hist_jet_Delta_Eta->Fill(Delta_eta_aver);
					hist_jet_DPhi_MET_other->Fill(Delta_phi_other_jets);
					hist_jet_Delta_PT_leading->Fill(Delta_PT_leading);
					hist_jet_Delta_Eta_leading->Fill(Delta_Eta_leading);
				}
				else{ //ISR
					h_ISR_PT->Fill(vect_currentJet->Pt());
					h_ISR_Eta->Fill(vect_currentJet->Eta());
					h_ISR_Phi->Fill(vect_currentJet->Phi());
					h_ISR_DPhi_MET->Fill(delta_phi);
					h_ISR_Eta_comp->Fill(vect_currentJet->Eta());
					h_ISR_PT_comp->Fill(vect_currentJet->Pt());
					h_ISR_DPhi_MET_comp->Fill(delta_phi);
					h_ISR_Delta_PT->Fill(delta_PT_jet);
					h_ISR_Delta_Eta->Fill(Delta_eta_aver);
					h_ISR_DPhi_MET_other->Fill(Delta_phi_other_jets);
					h_ISR_PT_HT->Fill(vect_currentJet->Pt()/HT);
					h_ISR_multiplicity->Fill(array_temp.GetEntries());
					h_ISR_PT_over_PT_others->Fill(PT_ratio);
					h_ISR_Eta_over_Eta_others->Fill(Eta_ratio);
					h_ISR_DeltaR->Fill(Delta_R);
					h_ISR_DPhi_over_Phi_others->Fill(Delta_phi_ratio);
					h_ISR_Delta_PT_leading->Fill(Delta_PT_leading);
					h_ISR_Delta_Eta_leading->Fill(Delta_Eta_leading);
					if (vect_currentJet->Pt()>120)
						h_MET_hpt1->Fill(MET);
					if (vect_currentJet->Pt()>200)
						h_MET_hpt2->Fill(MET);
					if (vect_currentJet->Pt()>240){
						h_MET_hpt3->Fill(MET);
						h_ISR_DPhi_MET_hpt->Fill(delta_phi);
					}
					if (vect_currentJet->Pt()>300)
						h_MET_hpt4->Fill(MET);
					h2_ISR_PTEta->Fill(vect_currentJet->Pt(),vect_currentJet->Eta());
					// Transverse mass
					h_ISR_MT->Fill(transverse_mass);

					// For testing creating histo
					hist_ISR_PT->Fill(vect_currentJet->Pt());
					hist_ISR_Abs_Eta->Fill(TMath::Abs(vect_currentJet->Eta()));
					hist_ISR_DPhi_MET->Fill(delta_phi);
					hist_ISR_PT_ratio->Fill(PT_ratio);
					hist_ISR_Delta_Eta->Fill(Delta_eta_aver);
					hist_ISR_DPhi_MET_other->Fill(Delta_phi_other_jets);
					hist_ISR_Delta_PT_leading->Fill(Delta_PT_leading);
					hist_ISR_Delta_Eta_leading->Fill(Delta_Eta_leading);
				}

				// BTag
				h_BTag->Fill(currentJet->BTag);
				if (currentJet->BTag == 1){ // The current jet is B Tagged
					h_BTag_PT->Fill(vect_currentJet->Pt());
					h_BTag_Eta->Fill(vect_currentJet->Eta());
					h_BTag_DPhi_MET->Fill(delta_phi);
					number_Btags++;

					if (iJet == ISR_jets[entry]){ // If the ISR jet is also a B jet
						ISR_Btags++;
					}
				}
			}

			// Jet with greatest PT
			if (posLeadingPT != -1){
				h_leading_PT->Fill(PT_max);
				if(posLeadingPT == ISR_jets[entry]) ISR_greatest_PT++;

				currentJet = (Jet*) branchJet->At(posLeadingPT);
				vect_currentJet->SetPtEtaPhiM(currentJet->PT,currentJet->Eta,currentJet->Phi,currentJet->Mass);
				delta_phi = deltaAng(vect_currentJet->Phi(), METpointer->Phi);
				MT_leading_jet = sqrt(2*vect_currentJet->Pt()*MET*(1-cos(delta_phi)));
				h_leading_MT->Fill(MT_leading_jet);

				h_leading_Eta->Fill(vect_currentJet->Eta());
				h_leading_DPhi_MET->Fill(delta_phi);

				h2_leading_PTEta->Fill(vect_currentJet->Pt(),vect_currentJet->Eta());
			}

			// HT
			if (1 < HT_R1/HT || 1 < HT_R2/HT){
				cout << "Error en el evento: " << entry << endl;
				cout << "HT: " << HT << "\tHT_R1: " << HT_R1 << "\tHT_R2: " << HT_R2 << endl;
				return 1;
			}

			h_HT->Fill(HT);
			h_HT_R1->Fill(HT_R1/HT);
			h_HT_R2->Fill(HT_R2/HT);
			h_BTags_per_Event->Fill(number_Btags);

		}

		cout<<"progress = 100%\t";
		cout<< "Time :"<< (clock()-initialTime)/double_t(CLOCKS_PER_SEC)<<"s"<<endl;
		cout<< "Percentage of events where the ISR jet is the jet with greatest PT: " << (Double_t) (ISR_greatest_PT*100)/numberOfEntries << "%\n";
		cout<< "Percentage of events where the ISR jet is tagged as Bjet: " << (Double_t) (ISR_Btags*100)/numberOfEntries << "%\n";

	} // End run's for cicle

	TFile* hfile = new TFile("./histos/histos.root", "RECREATE");
	h_jet_DPhi_MET->Write();
	h_jet_Eta->Write();
	h_jet_PT->Write();
	h_jet_Phi->Write();
	h_jet_MT->Write();
	h_jet_Delta_PT->Write();
	h_jet_Delta_Eta->Write();
	h_jet_DPhi_MET_other->Write();
	h_jet_PT_HT->Write();
	h_jet_multiplicity->Write();
	h_jet_PT_over_PT_others->Write();
	h_jet_Eta_over_Eta_others->Write();
	h_jet_DeltaR->Write();
	h_jet_DPhi_over_Phi_others->Write();
	h_jet_Delta_Eta_leading->Write();
	h_jet_Delta_PT_leading->Write();

	h_ISR_DPhi_MET->Write();
	h_ISR_Eta->Write();
	h_ISR_PT->Write();
	h_ISR_Phi->Write();
	h_ISR_MT->Write();
	h_ISR_Delta_PT->Write();
	h_ISR_Delta_Eta->Write();
	h_ISR_DPhi_MET_other->Write();
	h_ISR_PT_HT->Write();
	h_ISR_multiplicity->Write();
	h_ISR_PT_over_PT_others->Write();
	h_ISR_Eta_over_Eta_others->Write();
	h_ISR_DeltaR->Write();
	h_ISR_DPhi_over_Phi_others->Write();
	h_ISR_Delta_Eta_leading->Write();
	h_ISR_Delta_PT_leading->Write();

	h_MET->Write();
	h_MET_hpt1->Write();
	h_MET_hpt2->Write();
	h_MET_hpt3->Write();

	h_leading_MT->Write();
	h_leading_PT->Write();
	h_leading_Eta->Write();
	h_leading_DPhi_MET->Write();

	h_HT->Write();
	h_HT_R1->Write();
	h_HT_R2->Write();

	h_numberJet->Write();

	h_BTag->Write();
	h_BTag_PT->Write();
	h_BTag_Eta->Write();
	h_BTag_DPhi_MET->Write();
	h_BTags_per_Event->Write();

	h2_ISR_PTEta->Write();
	h2_jet_PTEta->Write();
	h2_dif_PTEta->Add(h2_ISR_PTEta,h2_jet_PTEta,1,-1);
	h2_dif_PTEta->Write();

	h2_dif_lead_PTEta->Add(h2_ISR_PTEta,h2_leading_PTEta,1,-1);
	h2_dif_lead_PTEta->Write();

	{
        TCanvas *C = new TCanvas("Eta","Pseudorapidity",1280,720);
		Present(h_ISR_Eta,h_jet_Eta,C,1,"h","Num. Jets / Total",122);
		C->Write();
		C->Close();

        C = new TCanvas("Eta ISR vs BTag","Pseudorapidity ISR vs BTag",1280,720);
		Present(h_ISR_Eta,h_BTag_Eta,C,1,"h","Num. Jets / Total",122);
		C->Write();
		C->Close();

        C = new TCanvas("Eta ISR vs Leading","Pseudorapidity ISR vs Leading",1280,720);
		Present(h_ISR_Eta,h_leading_Eta,C,1,"h","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum","Transverse momentum",1280,720);
		Present(h_ISR_PT,h_jet_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR vs Leading","Transverse momentum ISR vs Leading",1280,720);
		Present(h_ISR_PT,h_leading_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR vs B_Tag","Transverse momentum ISR vs B_Tag",1280,720);
		Present(h_ISR_PT,h_BTag_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR, B_Tag, Leading","Transverse momentum ISR, B_Tag, Leading",1280,720);
		Present_3(h_ISR_PT,h_BTag_PT,h_leading_PT,C,2,"PT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse momentum ISR, B_Tag, Leading LOG","Transverse momentum ISR, B_Tag, Leading LOG",1280,720);
		Present_3(h_ISR_PT,h_BTag_PT,h_leading_PT,C,2,"PT [GeV]","Num. Jets / Total",12,12,true);
		C->Write();
		C->Close();

		C = new TCanvas("Transverse mass Leading vs ISR Jet","Transverse mass Leading vs ISR Jet",1280,720);
		Present(h_ISR_MT,h_leading_MT,C,2,"MT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Transverse mass ISR vs Jet","Transverse mass ISR vs Jet",1280,720);
		Present(h_ISR_MT,h_jet_MT,C,2,"MT [GeV]","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Phi","Phi",1280,720);
		Present(h_ISR_Phi,h_jet_Phi,C,3,"f","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Delta Phi - Jet - MET","Delta Phi - Jet - MET",1280,720);
		Present(h_ISR_DPhi_MET,h_jet_DPhi_MET,C,3,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Delta Phi - Jet - MET - Btag","Delta Phi - Jet - MET - Btag",1280,720);
		Present(h_ISR_DPhi_MET,h_BTag_DPhi_MET,C,3,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Delta Phi - Jet - MET - leading","Delta Phi - Jet - MET - leading",1280,720);
		Present(h_ISR_DPhi_MET,h_leading_DPhi_MET,C,1,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("MET > 120","MET > 120",1280,720);
		Present(h_MET,h_MET_hpt1,C,2,"MET","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("MET > 200","MET > 200",1280,720);
		Present(h_MET,h_MET_hpt2,C,2,"MET","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("MET > 240","MET > 240",1280,720);
		Present(h_MET,h_MET_hpt3,C,2,"MET","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("HT ratio comparison","HT ratio comparison",1280,720);
		Present(h_HT_R1,h_HT_R2,C,2,"HT","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("PT vs ETA - ISR","PT vs ETA - ISR",1280,720);
		Plot_Single_2D(h2_ISR_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - Jet","PT vs ETA - Jet",1280,720);
		Plot_Single_2D(h2_jet_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - Diff with any jet","PT vs ETA - Diff with any jet",1280,720);
		Plot_Single_2D(h2_dif_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - leading","PT vs ETA - leading",1280,720);
		Plot_Single_2D(h2_leading_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("PT vs ETA - Diff with leading","PT vs ETA - Diff with leading",1280,720);
		Plot_Single_2D(h2_dif_lead_PTEta,C,2, "PT [GeV]", "h", 12, 122);
        C->Write();
        C->Close();

		C = new TCanvas("HT","HT",1280,720);
		Plot_Single(h_HT,C,2, "HT [GeV]", "Num. Jets / Total", 12, 12);
        C->Write();
        C->Close();

		C = new TCanvas("Number_of_B_Tags","Number of B Tags",1280,720);
		Plot_Single(h_BTags_per_Event,C,2, "B Tags / event", "Num. Jets / Total", 12, 12);
        C->Write();
        C->Close();

		C = new TCanvas("Jet_multiplitcity","Jet multiplicity",1280,720);
        Present(h_ISR_multiplicity,h_jet_multiplicity,C,2,"Tracks","Num. Jets / Total");
        C->Write();
        C->Close();

		C = new TCanvas("Delta_R_-_Jet_size","Delta R - Jet Size",1280,720);
		Present(h_ISR_DeltaR,h_jet_DeltaR,C,1,"Delta_R","Num. Jets / Total");
		C->Write();
		C->Close();

        // Correlated variables
        C = new TCanvas("Cor_Delta_PT_Jet", "Delta PT jet",1280,720);
        Present(h_ISR_Delta_PT,h_jet_Delta_PT,C,2,"PT [GeV]","Num. Jets / Total");
        C->Write();
        C->Close();

		C = new TCanvas("Cor_PT_proportion","PT proportion",1280,720);
		Present(h_ISR_PT_HT,h_jet_PT_HT,C,2,"PT/HT","Num. Jets / Total");
		C->Write();
		C->Close();

        C = new TCanvas("Cor_Delta_Eta_Average","Delta Eta Average",1280,720);
		Present(h_ISR_Delta_Eta,h_jet_Delta_Eta,C,2,"Dh","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Cor_Delta_Phi_Jet_MET_other_jets","Delta Phi - Jet MET - other jets",1280,720);
		Present(h_ISR_DPhi_MET_other,h_jet_DPhi_MET_other,C,2,"Df","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Cor_PT_over_<PT_other>","PT/<PT_other>",1280,720);
		Present(h_ISR_PT_over_PT_others,h_jet_PT_over_PT_others,C,2,"PT/<PT>","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Cor_Eta_over_<Eta_other>","Eta/<Eta_other>",1280,720);
		Present(h_ISR_Eta_over_Eta_others,h_jet_Eta_over_Eta_others,C,3,"h/<h>","Num. Jets / Total",122);
		C->Write();
		C->Close();

		C = new TCanvas("Cor_Delta_Phi_over_<Delta_Phi_other>","Delta_Phi/<Delta_Phi_other>",1280,720);
		Present(h_ISR_DPhi_over_Phi_others,h_jet_DPhi_over_Phi_others,C,3,"Df/<Df>","Num. Jets / Total",122);
		C->Write();
		C->Close();

		// Comparison with the leading Jet
		C = new TCanvas("Leading_Delta_PT","Delta PT: PT_leading-PT",1280,720);
		Present(h_ISR_Delta_PT_leading,h_jet_Delta_PT_leading,C,2,"(PT_leading - PT)","Num. Jets / Total");
		C->Write();
		C->Close();

		C = new TCanvas("Leading_Delta_Eta","Delta Eta: |Eta-Eta_leading|",1280,720);
		Present(h_ISR_Delta_Eta_leading,h_jet_Delta_Eta_leading,C,2,"|Eta - Eta_leading|","Num. Jets / Total");
		C->Write();
		C->Close();

	}

	hfile->Close();

	TFile* hfile2 = new TFile("./histos/histos2.root", "RECREATE");
	h_ISR_PT_comp->Write();
	h_ISR_Eta_comp->Write();
	h_ISR_DPhi_MET_comp->Write();

	hist_ISR_PT->Write();
	hist_ISR_Abs_Eta->Write();
	hist_ISR_DPhi_MET->Write();
	hist_ISR_PT_ratio->Write();
	hist_ISR_Delta_Eta->Write();
	hist_ISR_DPhi_MET_other->Write();
	hist_ISR_Delta_PT_leading->Write();
	hist_ISR_Delta_Eta_leading->Write();

	hist_jet_PT->Write();
	hist_jet_Abs_Eta->Write();
	hist_jet_DPhi_MET->Write();
	hist_jet_PT_ratio->Write();
	hist_jet_Delta_Eta->Write();
	hist_jet_DPhi_MET_other->Write();
	hist_jet_Delta_PT_leading->Write();
	hist_jet_Delta_Eta_leading->Write();

	hfile2->Close();

	return 0;
}
Ejemplo n.º 9
0
void GeneralExample(const char *inputFile, const char *outputFile)
{
  //  gSystem->Load("libDelphes");

  // Create chain of root trees
  TChain chain("Delphes");
  chain.Add(inputFile);
  
  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();
  
  // Get pointers to branches used in this analysis
  TClonesArray *branchGenJet = treeReader->UseBranch("GenJet");
  TClonesArray *branchJet = treeReader->UseBranch("Jet");
  TClonesArray *branchRho = treeReader->UseBranch("Rho");
  TClonesArray *branchGlobalRho = treeReader->UseBranch("GlobalRho");
  TClonesArray *branchNPU = treeReader->UseBranch("NPU");
  
  TClonesArray *branchElectron = treeReader->UseBranch("Electron");
  TClonesArray *branchMuon = treeReader->UseBranch("Muon");
  TClonesArray *branchPhoton = treeReader->UseBranch("Photon");

  // Constituents will be 0 otherwise
  TClonesArray *branchEFlowTrack = treeReader->UseBranch("EFlowTrack");
  TClonesArray *branchEFlowTower = treeReader->UseBranch("EFlowTower");
  TClonesArray *branchEFlowMuon = treeReader->UseBranch("EFlowMuon");
  TClonesArray *branchGenParticle = treeReader->UseBranch("Particle");
  TClonesArray *branchBeamSpotParticle = treeReader->UseBranch("BeamSpotParticle");

  TClonesArray *branchMissingET = treeReader->UseBranch("MissingET");
  TClonesArray *branchGenMissingET = treeReader->UseBranch("GenMissingET");
  TClonesArray *branchPileUpJetIDMissingET = treeReader->UseBranch("PileUpJetIDMissingET");
  TClonesArray *branchPuppiMissingET = treeReader->UseBranch("PuppiMissingET");


  bool verbose = true;
  bool listJetTowers = false;
  bool listMET = true;
  bool listRho = false;

  bool treeMET = true;

  TFile *f;
  TTree *t;
    //  TH1F *hdmet, hdpujidmet, hdpuppimet;
    //  TH1F *hfdmet, hfdpujidmet, hfdpuppimet;
    //  TH2F *h2met, h2pujidmet, h2puppimet;
  float genmet, met, puppimet, pujidmet;
  float genmetx, metx, puppimetx, pujidmetx;
  float genmety, mety, puppimety, pujidmety;


  if (treeMET) {
    f = new TFile(outputFile,"RECREATE");
    t = new TTree("t","t");
    t->Branch("genmet",&genmet,"genmet/F");
    t->Branch("met",&met,"met/F");
    t->Branch("pujidmet",&pujidmet,"pujidmet/F");
    t->Branch("puppimet",&puppimet,"puppimet/F");
    t->Branch("genmetx",&genmetx,"genmetx/F");
    t->Branch("metx",&metx,"metx/F");
    t->Branch("pujidmetx",&pujidmetx,"pujidmetx/F");
    t->Branch("puppimetx",&puppimetx,"puppimetx/F");
    t->Branch("genmety",&genmety,"genmety/F");
    t->Branch("mety",&mety,"mety/F");
    t->Branch("pujidmety",&pujidmety,"pujidmety/F");
    t->Branch("puppimety",&puppimety,"puppimety/F");

  }

  // Loop over all events
  for(Int_t entry = 0; entry < numberOfEntries; ++entry)
  {
    // Load selected branches with data from specified event
    treeReader->ReadEntry(entry);
  
    if (listMET||verbose||entry%5000==0) cout << "Event " << entry << " / " << numberOfEntries << endl;
    
    for (int i = 0 ;  i < branchGenMissingET->GetEntries() ; i++) {
      MissingET *m = (MissingET*) branchGenMissingET->At(i);
      if (verbose || listMET) cout << "Gen MissingET: " << m->MET << endl;
      genmet = m->MET;
      genmetx = m->MET*cos(m->Phi);
      genmety = m->MET*sin(m->Phi);
    }

    for (int i = 0 ;  i < branchMissingET->GetEntries() ; i++) {
      MissingET *m = (MissingET*) branchMissingET->At(i);
      if (verbose || listMET) cout << "MissingET: " << m->MET << endl;
      met = m->MET;
      metx = m->MET*cos(m->Phi);
      mety = m->MET*sin(m->Phi);

    }

    for (int i = 0 ;  i < branchPileUpJetIDMissingET->GetEntries() ; i++) {
      MissingET *m = (MissingET*) branchPileUpJetIDMissingET->At(i);
      if (verbose || listMET) cout << "MissingET using PileUpJetID: " << m->MET << endl;
      pujidmet = m->MET;
      pujidmetx = m->MET*cos(m->Phi);
      pujidmety = m->MET*sin(m->Phi);
    }

    for (int i = 0 ;  i < branchPuppiMissingET->GetEntries() ; i++) {
      MissingET *m = (MissingET*) branchPuppiMissingET->At(i);
      if (verbose || listMET) cout << "Puppi MissingET: " << m->MET << endl;
      puppimet = m->MET;
      puppimetx = m->MET*cos(m->Phi);
      puppimety = m->MET*sin(m->Phi);
    }

    if (treeMET) t->Fill();

    for (int i = 0 ; i < branchRho->GetEntries() ; i++) {
      Rho *rho = (Rho*) branchRho->At(i);
      if (verbose || listRho) cout << "  Rho (" << rho->Edges[0] << "-" << rho->Edges[1] << "): " << rho->Rho << endl;
    }

    for (int i = 0 ; i < branchGlobalRho->GetEntries() ; i++) {
      Rho *rho = (Rho*) branchGlobalRho->At(i);
      if (verbose || listRho) cout << "  GlobalRho (" << rho->Edges[0] << "-" << rho->Edges[1] << "): " << rho->Rho << endl;
    }


    //    cout << "before scalarHT" << endl;
    // I have cheated and recorded the true number of pileup vertices in a "ScalarHT" object!
    ScalarHT *NPU = (ScalarHT*) branchNPU->At(0);
    int nPUvertices_true = (int)NPU->HT;
    if (verbose) cout << "  Number of true pileup vertices: " << nPUvertices_true << endl;

    // One particle from primary vertex
    if (verbose && branchBeamSpotParticle) {
      cout << branchBeamSpotParticle->GetEntries() << endl;
      GenParticle *part = (GenParticle*) branchBeamSpotParticle->At(0);
      cout <<  "  True primary vertex X Y Z T: " << part->X << " " << part->Y << " " << part->Z << " " << part->T << endl;
    }

    // Status code 3 (+high pt leptons, b+t quarks, etc)  particle collection
    if (verbose && branchGenParticle) {
      for (int i = 0 ; i < branchGenParticle->GetEntries() ; i++ ) {
	GenParticle *part = (GenParticle*) branchGenParticle->At(i);
	cout << "     Status code" << part->Status << " generator particle PID Pt Eta Phi Z T (at origin) "  << part->PID << " "
	     << part->PT << " " << part->Eta << " " << part->Phi << " " << part->Z << " " << part->T << endl;
      }
    }
      
    if (verbose) {

      for (int i = 0 ; i < branchElectron->GetEntries() ; i++) {
	Electron *ele = (Electron*) branchElectron->At(i);
	cout << "    Electron " << i << ": PT Eta Phi Isolation " << ele->PT << " " << ele->Eta << " " << ele->Phi << " " << ele->IsolationVar << endl;
	GenParticle *part = (GenParticle*) ele->Particle.GetObject();
	if (part) {
	  cout << "      Electron matches to generated particle with Status code" << part->Status << " generator particle PID Pt Eta Phi Z T (at origin) "  << part->PID << " "
	       << part->PT << " " << part->Eta << " " << part->Phi << " " << part->Z << " " << part->T << endl;
	} else {
	  cout << "      Electron does not match to a generated particle" << endl;
	}
      }

      for (int i = 0 ; i < branchPhoton->GetEntries() ; i++) {
        Photon *pho = (Photon*) branchPhoton->At(i);
        cout << "    Photon " << i << ": PT Eta Phi Isolation T " << pho->PT << " " << pho->Eta << " " << pho->Phi << " " << pho->IsolationVar << " " << pho->TOuter << endl;
      }

      for (int i = 0 ; i < branchMuon->GetEntries() ; i++) {
        Muon *mu = (Muon*) branchMuon->At(i);
        cout << "    Muon " << i << ": PT Eta Phi Isolation " << mu->PT << " " << mu->Eta << " " << mu->Phi << " " << mu->IsolationVar << endl;
      }

      for (int i = 0 ; i < branchGenJet->GetEntries() ; i++) {
        Jet *jet = (Jet*) branchGenJet->At(i);
        if (jet->PT > 30.) {
          cout << "  Gen Jet " << i << endl;
          cout << "    pT: " << jet->PT << endl;
          cout << "    Eta: " << jet->Eta << endl;
          cout << "    Phi: " << jet->Phi << endl;
	  /*
          cout << "    Area: " << jet->AreaP4().Pt() << endl;
          cout << "    Constituents: " << jet->Constituents.GetEntries() << endl;
          if (branchGenParticleWithPU) { // now same colection
            for (int j = 0 ; j < jet->Constituents.GetEntries() ; j++) {
              TObject *obj = jet->Constituents[j];
              if (obj && obj->IsA() == GenParticle::Class()) {
                GenParticle *part = static_cast<GenParticle *> ( obj ) ;
                cout << "     Jet constituent Pt Eta Phi Z T (at origin) " << part->PT << " " << part->Eta << " " << part->Phi << " " << part->Z << " " << part->T << endl;
              } else {
                cout << "     Jet constituent is not a particle (?)" << endl;
              }
            }
          }
	  */
        }
      }

      // Loop over jets
      for (int i = 0 ; i < branchJet->GetEntries() ; i++) {
	Jet *jet = (Jet*) branchJet->At(i);
	if (jet->PT > 30.) {
	  cout << "  Jet " << i << endl;
	  cout << "    pT: " << jet->PT << endl;
	  cout << "    Eta: " << jet->Eta << endl;
	  cout << "    BTag: " << bool(jet->BTag&1) << " | " << bool(jet->BTag&2) << endl;
          cout << "    TauTag: " << jet->TauTag << endl;
	  //	  cout << "    Area: " << jet->AreaP4().Pt() << endl;
	  cout << "    Jet Pileup ID" << endl;
	  cout << "      Beta*: " << jet->BetaStar << endl;
	  cout << "      Fractional pT in annuli (<0.1, 0.1-0.2, ..., 0.4-0.5) " << jet->FracPt[0] << " " << jet->FracPt[1] << " " << jet->FracPt[2] << " " << jet->FracPt[3] << " " << jet->FracPt[4] << endl;
	  cout << "      <dR^2>: " << jet->MeanSqDeltaR << endl;
          cout << "      NNeutrals: " << jet->NNeutrals << endl;
	  cout << "      NCharged: " << jet->NCharged << endl;
	  cout << "    Number of constituents: " << jet->Constituents.GetEntries() << endl;
	  if (listJetTowers && branchEFlowTrack && branchEFlowTower && branchEFlowMuon) {
	    for (int j = 0 ; j < jet->Constituents.GetEntries() ; j++) {
	      TObject *obj = jet->Constituents[j];
	      if (obj && obj->IsA() == Tower::Class()) {
		Tower *tow = static_cast<Tower *> ( obj ) ;
		cout << "     Jet constituent Et Eta Phi Time (at calo) " << tow->ET << " " << tow->Eta << " " << tow->Phi << " " << tow->TOuter << endl;
	      } else {
		//		cout << "  not a tower - could check if it's a track instead (cf. Example3.C)" << endl;
	      }
	    }
	  }
	}
      }
    } // verbose 

  } // event

  if (treeMET) {
    f->cd();
    t->Write();
    f->Close();
  }

}
Ejemplo n.º 10
0
void RecoTrack_wSks(char *ridffile="./ridf/sm_com/sdaq02/run0208.ridf", Int_t nevent=100000000000){
//void RecoTrack_wSks(char *ridffile="./ridf/sm_com/sdaq02/run0208.ridf", Int_t nevent=100){

  TArtStoreManager * sman = TArtStoreManager::Instance();
  TArtEventStore *estore = new TArtEventStore;
  estore->Open(ridffile);

  TArtBigRIPSParameters * bripsparameters = TArtBigRIPSParameters::Instance();
  bripsparameters->LoadParameter((char*)"db/BigRIPSPlastic.xml");

  TArtSAMURAIParameters * samuraiparameters = TArtSAMURAIParameters::Instance();
  samuraiparameters->LoadParameter((char*)"db/SAMURAIFDC1.xml");
  samuraiparameters->LoadParameter((char*)"db/SAMURAIFDC2.xml");

  TArtCalibPlastic * calpla     = new TArtCalibPlastic;
  TArtCalibSAMURAI * calsamurai = new TArtCalibSAMURAI;

  TArtRecoFragment *reco = new TArtRecoFragment();
  TClonesArray *fdc1trks = (TClonesArray*)sman->FindDataContainer("SAMURAIFDC1Track");
  TClonesArray *fdc2trks = (TClonesArray*)sman->FindDataContainer("SAMURAIFDC2Track");
  TClonesArray *frags = (TClonesArray*)sman->FindDataContainer("SAMURAIFragment");

  calsamurai->LoadDCTDCDistribution((char*)"db/dc/run0203.root"); // for 3T Brho scan analysis

  Double_t fdc1chi2, fdc2chi2;
  Double_t delta, brho, trchi2, trpos[3], trl2hod;
  Double_t f3plat, f3plaq;
  Double_t f13plat, f13plaq;
  Int_t trstatus, trnhit;

  TFile *fout = new TFile("fout.root","RECREATE");
  TTree *otree = new TTree("otree","otree");
  otree->Branch("f3plaq",&f3plaq,"f3plaq/D");
  otree->Branch("f3plat",&f3plat,"f3plat/D");
  otree->Branch("f13plaq",&f13plaq,"f13plaq/D");
  otree->Branch("f13plat",&f13plat,"f13plat/D");
  otree->Branch("tr1chi2",&fdc1chi2,"tr1chi1/D");
  otree->Branch("tr2chi2",&fdc2chi2,"tr2chi1/D");
  otree->Branch("delta",&delta,"delta/D");

  otree->Branch("trstatus",&trstatus,"trstatus/I");
  otree->Branch("brho",&brho,"brho/D");
  otree->Branch("trchi2",&trchi2,"trchi2/D");
  otree->Branch("trnhit",&trnhit,"trnhit/I");
  otree->Branch("trpos",trpos,"trpos[3]/D");
  otree->Branch("trl2hod",&trl2hod,"trl2hod/D");

  int neve = 0;
  while(estore->GetNextEvent()&&neve < nevent){

    if(neve%1000==0) cout << "event: " << neve << endl;

    //    if(neve<33410) {neve ++; continue;} if(neve%100==0) cout << "event: " << neve << endl;

    calpla->ClearData();
    calsamurai->ClearData();
    reco->ClearData();

    calpla->ReconstructData();
    calsamurai->ReconstructData();
    reco->ReconstructData();

    f3plat = -9999; f3plaq = -9999;
    f13plat = -9999; f13plaq = -9999;
    fdc1chi2 = -9999; fdc2chi2 = -9999;
    delta = -9999; 
    brho = -9999;
    trchi2 = -9999;
    for(int i=0;i<3;i++) trpos[i] = -9999;
    trl2hod = -9999;
    trstatus = 0;
    trnhit = -1;

    TArtPlastic *pla = calpla->FindPlastic((char*)"F3pl");
    if(pla){
      if(pla->GetTLRaw() > 0 && pla->GetTRRaw() > 0)
	f3plat = ((Double_t)pla->GetTLRaw() + (Double_t)pla->GetTRRaw())/2;
      if(pla->GetQLRaw() > 0 && pla->GetQRRaw() > 0)
	f3plaq = pla->GetQAveRaw();
    }
    else{
      cout << "cannot find f3pla object!!" << endl;
    }

    pla = calpla->FindPlastic((char*)"F13pl-1");
    if(pla){
      if(pla->GetTLRaw() > 0 && pla->GetTRRaw() > 0)
	f13plat = ((Double_t)pla->GetTLRaw() + (Double_t)pla->GetTRRaw())/2;
      if(pla->GetQLRaw() > 0 && pla->GetQRRaw() > 0)
	f13plaq = pla->GetQAveRaw();
    }
    else{
      cout << "cannot find f13pla-1 object!!" << endl;
    }

    int nfdc1trks = fdc1trks->GetEntries();
    int nfdc2trks = fdc2trks->GetEntries();
    int nfrags = frags->GetEntries();

    cout << "num of fdc1trks in event: " << nfdc1trks << endl;
    for(int i=0;i<nfdc1trks&&i<1;i++){
      TArtDCTrack *trk = (TArtDCTrack*)fdc1trks->At(i);
      int nhit = trk->GetNumHitLayer();
      int ndf  = trk->GetNDF();
      fdc1chi2 = trk->GetChi2()/(double)ndf;
      /*
      cout << "fdc1tr " << i << endl;
      cout << "chi2/ndf: " << fdc1chi2 << endl;
      cout << "    nhit: " << nhit << endl;
      for(int j=0;j<nhit;j++){
	cout << "       hitx[" << j << "]= " << trk->GetHitXPosition(j);
	cout << "       hitz[" << j << "]= " << trk->GetHitZPosition(j);
	cout << "    planeid[" << j << "]= " << trk->GetHitPlaneID(j) << endl; 
      }
      */
    }

    cout << "num of fdc2trks in event: " << nfdc2trks << endl;
    for(int i=0;i<nfdc2trks&&i<1;i++){
      TArtDCTrack *trk = (TArtDCTrack*)fdc2trks->At(i);
      int nhit = trk->GetNumHitLayer();
      int ndf  = trk->GetNDF();
      fdc2chi2 = trk->GetChi2()/(double)ndf;;
      /*
      cout << "fdc2tr " << i << endl;
      cout << "  chi2: " << fdc2chi2 << endl;
      cout << "  nhit: " << nhit << endl;
      for(int j=0;j<nhit;j++){
	cout << "       hitx[" << j << "]= " << trk->GetHitXPosition(j);
	cout << "       hitz[" << j << "]= " << trk->GetHitZPosition(j);
	cout << "    planeid[" << j << "]= " << trk->GetHitPlaneID(j) << endl; 
      }
      */
    }

    cout << "num of frags in event: " << nfrags << endl;

    for(int i=0;i<nfrags&&i<1;i++){
      TArtFragment *f= (TArtFragment*)frags->At(i);
      delta = f->GetDelta();
      brho = f->GetBrho();
      trchi2 = f->GetChi2();
      trpos[0] = f->GetPrimaryPosition().X();
      trpos[1] = f->GetPrimaryPosition().Y();
      trpos[2] = f->GetPrimaryPosition().Z();
      trl2hod = f->GetPathLengthToHOD();
      trstatus = f->GetRKtraceStatus() ? 1 : 0;
      trnhit = f->GetNHit();

      cout << "Ana Delta:" << delta << endl;
      cout << "Ana  Brho:" << brho << endl;
    }

    otree->Fill();
    neve ++;


    cout << endl;
    cout << endl;
    cout << endl;

  }

  fout->Write();
  fout->Close();

}
Ejemplo n.º 11
0
void computeAccSelZeeBinned(const TString conf,            // input file
                            const TString outputDir,        // output directory
			    const Int_t   doPU
) {
  gBenchmark->Start("computeAccSelZeeBinned");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t MASS_LOW   = 60;
  const Double_t MASS_HIGH  = 120;
  const Double_t PT_CUT     = 25;
  const Double_t ETA_CUT    = 2.5;
  const Double_t ELE_MASS   = 0.000511;

  const Double_t ETA_BARREL = 1.4442;
  const Double_t ETA_ENDCAP = 1.566;

  const Int_t BOSON_ID  = 23;
  const Int_t LEPTON_ID = 11;
  
  // efficiency files
  const TString dataHLTEffName     = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/MG/eff.root";
  const TString dataHLTEffName_pos = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/MG/eff.root";
  const TString dataHLTEffName_neg = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/MG/eff.root";

  const TString zeeHLTEffName      = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/CT/eff.root";
  const TString zeeHLTEffName_pos  = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/CT/eff.root";
  const TString zeeHLTEffName_neg  = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleHLTEff/CT/eff.root";
  
  const TString dataGsfSelEffName     = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/MG/eff.root";
  const TString dataGsfSelEffName_pos = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/MG/eff.root";
  const TString dataGsfSelEffName_neg = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/MG/eff.root";

  const TString zeeGsfSelEffName      = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/CT/eff.root";
  const TString zeeGsfSelEffName_pos  = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/CT/eff.root";
  const TString zeeGsfSelEffName_neg  = "/afs/cern.ch/work/x/xniu/public/WZXSection/wz-efficiency/EleGsfSelEff/CT/eff.root";

  // load pileup reweighting file
  TFile *f_rw = TFile::Open("../Tools/pileup_rw_76X.root", "read");
  TH1D *h_rw = (TH1D*) f_rw->Get("h_rw_golden");


  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString> fnamev;  // file name per input file
  vector<TString> labelv;  // TLegend label per input file
  vector<Int_t>   colorv;  // plot color per input file
  vector<Int_t>   linev;   // plot line style per input file

  //
  // parse .conf file
  //
  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    
    string fname;
    Int_t color, linesty;
    stringstream ss(line);
    ss >> fname >> color >> linesty;
    string label = line.substr(line.find('@')+1);
    fnamev.push_back(fname);
    labelv.push_back(label);
    colorv.push_back(color);
    linev.push_back(linesty);
  }
  ifs.close();

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  
  TH2D *h=0;
  
  //
  // HLT efficiency
  //
  cout << "Loading trigger efficiencies..." << endl;

  TFile *dataHLTEffFile_pos = new TFile(dataHLTEffName_pos);
  CEffUser2D dataHLTEff_pos;
  dataHLTEff_pos.loadEff((TH2D*)dataHLTEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataHLTEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataHLTEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataHLTEffFile_neg = new TFile(dataHLTEffName_neg);
  CEffUser2D dataHLTEff_neg;
  dataHLTEff_neg.loadEff((TH2D*)dataHLTEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataHLTEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataHLTEffFile_neg->Get("hErrhEtaPt"));
  
  TFile *zeeHLTEffFile_pos = new TFile(zeeHLTEffName_pos);
  CEffUser2D zeeHLTEff_pos;
  zeeHLTEff_pos.loadEff((TH2D*)zeeHLTEffFile_pos->Get("hEffEtaPt"), (TH2D*)zeeHLTEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zeeHLTEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *zeeHLTEffFile_neg = new TFile(zeeHLTEffName_neg);
  CEffUser2D zeeHLTEff_neg;
  zeeHLTEff_neg.loadEff((TH2D*)zeeHLTEffFile_neg->Get("hEffEtaPt"), (TH2D*)zeeHLTEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zeeHLTEffFile_neg->Get("hErrhEtaPt"));
  
  h =(TH2D*)dataHLTEffFile_pos->Get("hEffEtaPt");
  TH2D *hHLTErr_pos = new TH2D("hHLTErr_pos", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                                 h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  TH2D *hHLTErr_neg = new TH2D("hHLTErr_neg", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                                 h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  
  //
  // Selection efficiency
  //
  cout << "Loading GSF+selection efficiencies..." << endl;
  
  TFile *dataGsfSelEffFile_pos = new TFile(dataGsfSelEffName_pos);
  CEffUser2D dataGsfSelEff_pos;
  dataGsfSelEff_pos.loadEff((TH2D*)dataGsfSelEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataGsfSelEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataGsfSelEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataGsfSelEffFile_neg = new TFile(dataGsfSelEffName_neg);
  CEffUser2D dataGsfSelEff_neg;
  dataGsfSelEff_neg.loadEff((TH2D*)dataGsfSelEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataGsfSelEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataGsfSelEffFile_neg->Get("hErrhEtaPt"));

  TFile *zeeGsfSelEffFile_pos = new TFile(zeeGsfSelEffName_pos);
  CEffUser2D zeeGsfSelEff_pos;
  zeeGsfSelEff_pos.loadEff((TH2D*)zeeGsfSelEffFile_pos->Get("hEffEtaPt"), (TH2D*)zeeGsfSelEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zeeGsfSelEffFile_pos->Get("hErrhEtaPt"));

  TFile *zeeGsfSelEffFile_neg = new TFile(zeeGsfSelEffName_neg);
  CEffUser2D zeeGsfSelEff_neg;
  zeeGsfSelEff_neg.loadEff((TH2D*)zeeGsfSelEffFile_neg->Get("hEffEtaPt"), (TH2D*)zeeGsfSelEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zeeGsfSelEffFile_neg->Get("hErrhEtaPt"));
 
  h =(TH2D*)dataGsfSelEffFile_pos->Get("hEffEtaPt");
  TH2D *hGsfSelErr_pos = new TH2D("hGsfSelErr_pos", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                                       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  TH2D *hGsfSelErr_neg = new TH2D("hGsfSelErr_neg", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
                                                       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo   *info = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr     = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *electronArr    = new TClonesArray("baconhep::TElectron");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");

  TFile *infile=0;
  TTree *eventTree=0;
  
  // Variables to store acceptances and uncertainties (per input file)
  vector<Double_t> nEvtsv, nSelv;
  vector<Double_t> nSelCorrv, nSelCorrVarv;
  vector<Double_t> accv, accCorrv;
  vector<Double_t> accErrv, accErrCorrv;

  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");

  //
  // loop through files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {  

    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << " ..." << endl;
    infile = TFile::Open(fnamev[ifile]); 
    assert(infile);

    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);  
    eventTree->SetBranchAddress("Info",              &info); TBranch *infoBr     = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("GenEvtInfo",         &gen); TBranch *genBr      = eventTree->GetBranch("GenEvtInfo");
    eventTree->SetBranchAddress("GenParticle", &genPartArr); TBranch *genPartBr  = eventTree->GetBranch("GenParticle");
    eventTree->SetBranchAddress("Electron",   &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
    eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");

    nEvtsv.push_back(0);
    nSelv.push_back(0);
    nSelCorrv.push_back(0);
    nSelCorrVarv.push_back(0);

    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
      genBr->GetEntry(ientry);
      genPartArr->Clear(); genPartBr->GetEntry(ientry);
      infoBr->GetEntry(ientry);

      Int_t glepq1=-99;
      Int_t glepq2=-99;

      if (fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
      TLorentzVector *vec=new TLorentzVector(0,0,0,0);
      TLorentzVector *lep1=new TLorentzVector(0,0,0,0);
      TLorentzVector *lep2=new TLorentzVector(0,0,0,0);
      toolbox::fillGen(genPartArr, BOSON_ID, vec, lep1, lep2,&glepq1,&glepq2,1);
      if(vec->M()<MASS_LOW || vec->M()>MASS_HIGH) continue;      
      delete vec; delete lep1; delete lep2;

      vertexArr->Clear();
      vertexBr->GetEntry(ientry);
      double npv  = vertexArr->GetEntries();
      Double_t weight=gen->weight;
      if(doPU>0) weight*=h_rw->GetBinContent(h_rw->FindBin(info->nPUmean));

      nEvtsv[ifile]+=weight;        

      // trigger requirement               
      if (!isEleTrigger(triggerMenu, info->triggerBits, kFALSE)) continue;
      
      // good vertex requirement
      if(!(info->hasGoodPV)) continue;
      
      electronArr->Clear();
      electronBr->GetEntry(ientry);

      for(Int_t i1=0; i1<electronArr->GetEntriesFast(); i1++) {
  	const baconhep::TElectron *ele1 = (baconhep::TElectron*)((*electronArr)[i1]);
	
	// check ECAL gap
	if(fabs(ele1->scEta)>=ETA_BARREL && fabs(ele1->scEta)<=ETA_ENDCAP) continue;
	
	//double ele1_pt = gRandom->Gaus(ele1->pt*getEleScaleCorr(ele1->scEta,0), getEleResCorr(ele1->scEta,0));

	if(ele1->pt	     < PT_CUT && ele1->scEt < PT_CUT)	  continue;  // lepton pT cut
        if(fabs(ele1->scEta) > ETA_CUT && fabs(ele1->eta) > ETA_CUT)	  continue;  // lepton |eta| cut
        if(!passEleID(ele1,info->rhoIso)) continue;  // lepton selection
	//if(!isEleTriggerObj(triggerMenu, ele1->hltMatchBits, kFALSE, kFALSE)) continue;

        TLorentzVector vEle1(0,0,0,0);
	vEle1.SetPtEtaPhiM(ele1->pt, ele1->eta, ele1->phi, ELE_MASS);
	Bool_t isB1 = (fabs(ele1->scEta)<ETA_BARREL) ? kTRUE : kFALSE;

        for(Int_t i2=i1+1; i2<electronArr->GetEntriesFast(); i2++) {          
	  const baconhep::TElectron *ele2 = (baconhep::TElectron*)((*electronArr)[i2]);
	  
	  // check ECAL gap
	  if(fabs(ele2->scEta)>=ETA_BARREL && fabs(ele2->scEta)<=ETA_ENDCAP) continue;
	  //double ele2_pt = gRandom->Gaus(ele2->scEt*getEleScaleCorr(ele2->scEta,0), getEleResCorr(ele2->scEta,0));
	  if(ele1->q == ele2->q)	continue;
          if(ele2->pt        < PT_CUT && ele2->scEt < PT_CUT)    continue;  // lepton pT cut
          if(fabs(ele2->scEta) > ETA_CUT && fabs(ele2->eta) > ETA_CUT)   continue;  // lepton |eta| cut
	  if(!passEleID(ele2,info->rhoIso)) continue;  // lepton selection

          TLorentzVector vEle2(0,0,0,0);
	  vEle2.SetPtEtaPhiM(ele2->pt, ele2->eta, ele2->phi, ELE_MASS);  
          Bool_t isB2 = (fabs(ele2->scEta)<ETA_BARREL) ? kTRUE : kFALSE;

	  if(!isEleTriggerObj(triggerMenu, ele1->hltMatchBits, kFALSE, kFALSE) && !isEleTriggerObj(triggerMenu, ele2->hltMatchBits, kFALSE, kFALSE)) continue;
	  
	  // mass window
          TLorentzVector vDilep = vEle1 + vEle2;
          if((vDilep.M()<MASS_LOW) || (vDilep.M()>MASS_HIGH)) continue;
          
          /******** We have a Z candidate! HURRAY! ********/
          Double_t effdata, effmc;
          //Double_t sceta1 = (fabs(ele1->scEta)<2.5) ? ele1->scEta : 0.99*(ele1->scEta);
	  Double_t sceta1 = ele1->scEta;
          //Double_t sceta2 = (fabs(ele2->scEta)<2.5) ? ele2->scEta : 0.99*(ele2->scEta);
    	  Double_t sceta2 = ele2->scEta;

          Double_t corr=1;
	  
	  effdata=1; effmc=1;
          if(ele1->q>0) { 
            effdata *= (1.-dataHLTEff_pos.getEff(sceta1, ele1->scEt));
            effmc   *= (1.-zeeHLTEff_pos.getEff(sceta1, ele1->scEt));
          } else {
            effdata *= (1.-dataHLTEff_neg.getEff(sceta1, ele1->scEt)); 
            effmc   *= (1.-zeeHLTEff_neg.getEff(sceta1, ele1->scEt)); 
          }
          if(ele2->q>0) {
            effdata *= (1.-dataHLTEff_pos.getEff(sceta2, ele2->scEt)); 
            effmc   *= (1.-zeeHLTEff_pos.getEff(sceta2, ele2->scEt));
          } else {
            effdata *= (1.-dataHLTEff_neg.getEff(sceta2, ele2->scEt)); 
            effmc   *= (1.-zeeHLTEff_neg.getEff(sceta2, ele2->scEt));
          }
          effdata = 1.-effdata;
          effmc   = 1.-effmc;
          corr *= effdata/effmc;


          effdata=1; effmc=1;
          if(ele1->q>0) { 
            effdata *= dataGsfSelEff_pos.getEff(sceta1, ele1->scEt); 
            effmc   *= zeeGsfSelEff_pos.getEff(sceta1, ele1->scEt); 
          } else {
            effdata *= dataGsfSelEff_neg.getEff(sceta1, ele1->scEt); 
            effmc   *= zeeGsfSelEff_neg.getEff(sceta1, ele1->scEt); 
          }
          if(ele2->q>0) {
            effdata *= dataGsfSelEff_pos.getEff(sceta2, ele2->scEt); 
            effmc   *= zeeGsfSelEff_pos.getEff(sceta2, ele2->scEt);
          } else {
            effdata *= dataGsfSelEff_neg.getEff(sceta2, ele2->scEt); 
            effmc   *= zeeGsfSelEff_neg.getEff(sceta2, ele2->scEt);
          }
          corr *= effdata/effmc;
	  
	  // scale factor uncertainties
	  if(ele1->q>0) {	    
	    Double_t effdata = dataGsfSelEff_pos.getEff(sceta1, ele1->scEt);
	    Double_t errdata = TMath::Max(dataGsfSelEff_pos.getErrLow(sceta1, ele1->scEt), dataGsfSelEff_pos.getErrHigh(sceta1, ele1->scEt));
            Double_t effmc   = zeeGsfSelEff_pos.getEff(sceta1, ele1->scEt); 
	    Double_t errmc   = TMath::Max(zeeGsfSelEff_pos.getErrLow(sceta1, ele1->scEt), zeeGsfSelEff_pos.getErrHigh(sceta1, ele1->scEt));
	    Double_t errGsfSel = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
	    hGsfSelErr_pos->Fill(sceta1, ele1->scEt, errGsfSel);
	  } else {
	    Double_t effdata = dataGsfSelEff_neg.getEff(sceta1, ele1->scEt);
	    Double_t errdata = TMath::Max(dataGsfSelEff_neg.getErrLow(sceta1, ele1->scEt), dataGsfSelEff_neg.getErrHigh(sceta1, ele1->scEt));
            Double_t effmc   = zeeGsfSelEff_neg.getEff(sceta1, ele1->scEt); 
	    Double_t errmc   = TMath::Max(zeeGsfSelEff_neg.getErrLow(sceta1, ele1->scEt), zeeGsfSelEff_neg.getErrHigh(sceta1, ele1->scEt));
	    Double_t errGsfSel = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
	    hGsfSelErr_neg->Fill(sceta1, ele1->scEt, errGsfSel);
	  }

	  if(ele2->q>0) {	    
	    Double_t effdata = dataHLTEff_pos.getEff(sceta2, ele2->scEt);
	    Double_t errdata = TMath::Max(dataHLTEff_pos.getErrLow(sceta2, ele2->scEt), dataHLTEff_pos.getErrHigh(sceta2, ele2->scEt));
            Double_t effmc   = zeeHLTEff_pos.getEff(sceta2, ele2->scEt); 
	    Double_t errmc   = TMath::Max(zeeHLTEff_pos.getErrLow(sceta2, ele2->scEt), zeeHLTEff_pos.getErrHigh(sceta2, ele2->scEt));
	    Double_t errHLT = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
	    hHLTErr_pos->Fill(sceta2, ele2->scEt, errHLT);
	  } else {
	    Double_t effdata = dataHLTEff_neg.getEff(sceta2, ele2->scEt);
	    Double_t errdata = TMath::Max(dataHLTEff_neg.getErrLow(sceta2, ele2->scEt), dataHLTEff_neg.getErrHigh(sceta2, ele2->scEt));
            Double_t effmc   = zeeHLTEff_neg.getEff(sceta2, ele2->scEt); 
	    Double_t errmc   = TMath::Max(zeeHLTEff_neg.getErrLow(sceta2, ele2->scEt), zeeHLTEff_neg.getErrHigh(sceta2, ele2->scEt));
	    Double_t errHLT = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
	    hHLTErr_neg->Fill(sceta2, ele2->scEt, errHLT);
	  }

	  nSelv[ifile]+=weight;
	  nSelCorrv[ifile]+=weight*corr;
	  nSelCorrVarv[ifile]+=weight*weight*corr*corr;
	}
      }
    }
    
    Double_t var=0;
    for(Int_t iy=0; iy<=hHLTErr_pos->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr_pos->GetNbinsX(); ix++) {
	Double_t err=hHLTErr_pos->GetBinContent(ix,iy);
	var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hHLTErr_neg->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr_neg->GetNbinsX(); ix++) {
	Double_t err=hHLTErr_neg->GetBinContent(ix,iy);
	var+=err*err;
      }
    }
    cout << "var1: " << var << endl;
    for(Int_t iy=0; iy<=hGsfSelErr_pos->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hGsfSelErr_pos->GetNbinsX(); ix++) {
	Double_t err=hGsfSelErr_pos->GetBinContent(ix,iy);
	var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hGsfSelErr_neg->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hGsfSelErr_neg->GetNbinsX(); ix++) {
	Double_t err=hGsfSelErr_neg->GetBinContent(ix,iy);
	var+=err*err;
      }
    }
    cout << "var2: " << var << endl;

    nSelCorrVarv[ifile]+=var;

    // compute acceptances
    std::cout << nEvtsv[ifile] << " " << nSelv[ifile] << std::endl;
    accv.push_back(nSelv[ifile]/nEvtsv[ifile]);         accErrv.push_back(sqrt(accv[ifile]*(1. +accv[ifile])/nEvtsv[ifile]));
    accCorrv.push_back(nSelCorrv[ifile]/nEvtsv[ifile]); accErrCorrv.push_back(accCorrv[ifile]*sqrt((nSelCorrVarv[ifile])/(nSelCorrv[ifile]*nSelCorrv[ifile]) + 1./nEvtsv[ifile]));
    
    delete infile;
    infile=0, eventTree=0;  
  }  
  delete info;
  delete gen;
  delete electronArr;  
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " Z -> e e" << endl;
  cout << "  Mass window: [" << MASS_LOW << ", " << MASS_HIGH << "]" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    cout << "   ================================================" << endl;
    cout << "    Label: " << labelv[ifile] << endl;
    cout << "     File: " << fnamev[ifile] << endl;
    cout << endl;
    cout << "    *** Acceptance ***" << endl;
    cout << "          nominal: " << setw(12) << nSelv[ifile]   << " / " << nEvtsv[ifile] << " = " << accv[ifile]   << " +/- " << accErrv[ifile] << endl;
    cout << "     SF corrected: " << accCorrv[ifile] << " +/- " << accErrCorrv[ifile] << endl;
    cout << endl;
  }
  
  char txtfname[100];
  sprintf(txtfname,"%s/binned.txt",outputDir.Data());
  ofstream txtfile;
  txtfile.open(txtfname);
  txtfile << "*" << endl;
  txtfile << "* SUMMARY" << endl;
  txtfile << "*--------------------------------------------------" << endl;
  txtfile << " Z -> e e" << endl;
  txtfile << "  Mass window: [" << MASS_LOW << ", " << MASS_HIGH << "]" << endl;
  txtfile << "  pT > " << PT_CUT << endl;
  txtfile << "  |eta| < " << ETA_CUT << endl;
  txtfile << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    txtfile << "   ================================================" << endl;
    txtfile << "    Label: " << labelv[ifile] << endl;
    txtfile << "     File: " << fnamev[ifile] << endl;
    txtfile << endl;
    txtfile << "    *** Acceptance ***" << endl;
    txtfile << "          nominal: " << setw(12) << nSelv[ifile]   << " / " << nEvtsv[ifile] << " = " << accv[ifile]   << " +/- " << accErrv[ifile] << endl;
    txtfile << "     SF corrected: " << accCorrv[ifile] << " +/- " << accErrCorrv[ifile] << endl;
    txtfile << endl;
  }
  txtfile.close();
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("computeAccSelZeeBinned"); 
}
Ejemplo n.º 12
0
//void electron_master(const char* file_list="checkP10ic/electrons.list",const char* output="checkP10ic/electroncalib.root", const char* dbDate="2009-04-10 00:11:00", const char* geantfile="geant_func.root", const char* gfname="checkP10ic/mip.gains", const char* ngname="checkP10ic/electron.gains", const char* rgname="matrel.gains",const char* ffname="checkP10ic/electron.fits"){
void electron_master(const char* file_list="checkP11id/electrons.list",const char* output="checkP11id/electroncalib2.root", const char* dbDate="2009-04-10 00:11:00", const char* gfname="checkP11id/mip.gains", const char* ngname="checkP11id/electron2.gains",const char* ffname="checkP11id/electron2.fits"){
  //**********************************************//
  //Load Libraries                                //
  //**********************************************//
  gROOT->Macro("LoadLogger.C");
  gROOT->Macro("loadMuDst.C");
  gSystem->Load("StTpcDb");
  gSystem->Load("StDaqLib");
  gSystem->Load("StDetectorDbMaker");
  gSystem->Load("St_db_Maker");
  gSystem->Load("StDbUtilities");
  gSystem->Load("StEmcRawMaker");
  gSystem->Load("StMcEvent");
  gSystem->Load("StMcEventMaker");//***
  gSystem->Load("StEmcSimulatorMaker");//***
  gSystem->Load("StEmcADCtoEMaker");
  gSystem->Load("StEpcMaker");
  gSystem->Load("StDbBroker");
  gSystem->Load("StEEmcUtil");
  gSystem->Load("StAssociationMaker");
  gSystem->Load("StEmcTriggerMaker");
  gSystem->Load("StTriggerUtilities");
  gSystem->Load("StEmcOfflineCalibrationMaker");

  cout<<"input filelist: "<<file_list<<endl;
  cout<<"output:          "<<output<<endl;
  cout<<"db Date:        "<<dbDate<<endl;


  //**********************************************//
  //Initialize Stuff                              //
  //**********************************************//

  CalibrationHelperFunctions *helper = new CalibrationHelperFunctions();
	
  StBemcTablesWriter *bemctables = new StBemcTablesWriter();
  bemctables->loadTables(dbDate,"sim");
  StEmcDecoder* decoder = bemctables->getDecoder();


  //chain all input files together
  char file[300];
  TChain* tree = new TChain("skimTree");
  ifstream filelist(file_list);
  while(1){
    filelist >> file;
    if(!filelist.good()) break;
    cout<<file<<endl;
    tree->Add(file);
  }

  const int ntowers = 4800;
  const int nrings = 40;
  const int ncrates = 30;
  float gains[ntowers];
  int status[ntowers];
  float peaks[ntowers];
  float peakerr[ntowers];
  float gainerr[ntowers];

  ifstream gainfile(gfname);
  while(1){
    int id,stat;
    float peak,err,gain,eta,theta;
    gainfile >> id >> peak >> err >> stat;
    if(!gainfile.good())break;
    eta = helper->getEta(id);
    theta = helper->getTheta(id);
    gain = 0.264*(1+0.056*eta*eta)/(sin(theta)*peak);
    peaks[id-1] = peak;
    gains[id-1] = gain;
    if(status[id-1] != 1 || stat != 1) status[id-1] = stat;
    peakerr[id-1] = err;
    //cout<<id<<" "<<gain;
  }


  TFile* geant_file = new TFile("geant_fits.root","READ");
  TF1* geant_fits[20];
  for(int i = 0; i < 20; i++){
    TString fname = "fit_";
    fname += i;
    geant_fits[i] = (TF1*)geant_file->Get(fname);
  }


  TFile outfile(output,"RECREATE");

  TH1 *crate_histo[ncrates];
  TF1 *crate_fit[ncrates];
  TH1 *electron_histo[ntowers];
  TF1 *fit[ntowers];
  TH1 *prs_histo[ntowers];
  TH1 *ring_histo[nrings];
  TH1 *ring2_histo[nrings/2];
  TF1 *ring2fit[nrings/2];

  TH1 *etacrate_histo[ncrates*20];
  TH1 *etacrate_histo_p[ncrates*20];
  TH1 *etacrate_histo_n[ncrates*20];

  TH1 *bghisto[21];
  TH2F* drvsep = new TH2F("drvsep","drvsep",60,0,3.0,100,0.0,0.03);

  TF1 *ringfit[nrings];
  TH2F* ring_pve[nrings];
  TH2F* jan_pve[6];
  float eta;
  int etaindex;
  TH1F* ringprec = new TH1F("ringprec","",40,-1.0,1.0);
  TH1F* ringprec2 = new TH1F("ringprec2","",40,-1.0,1.0);
  ringprec->SetYTitle("E/p");
  ringprec->SetXTitle("#eta");
  ringprec2->SetYTitle("E/p");
  ringprec2->SetXTitle("#eta");
  TH1F* ring2prec = new TH1F("ring2prec","",nrings/2,-1.0,1.0);
  TH1F* ring2prec2 = new TH1F("ring2prec2","",nrings/2,-1.0,1.0);
  ring2prec->SetYTitle("E/p");
  ring2prec->SetXTitle("#eta");
  ring2prec2->SetYTitle("E/p");
  ring2prec2->SetXTitle("#eta");
  double ew[nrings];

  TH2F* trgcheck = new TH2F("trgcheck","trgcheck",2,-0.5,1.5,3,-0.5,2.5);

  TH1F* crateprec = new TH1F("crateprec","",30,0.5,30.5);
  crateprec->SetXTitle("Crate");
  crateprec->SetYTitle("E/p");

  TH2F *energyleak = new TH2F("energyleak","",20,0.0,0.03,20,0.0,1.0);
  TH2F *findbg = new TH2F("findbg","",20,0.0,0.03,30,0.0,5.0);
  TH1F *energymean = new TH1F("energymean","",20,0.0,0.03);
  TH1F *leakmean = new TH1F("leakmean","",20,0.0,0.03);
  energyleak->SetXTitle("#DeltaR");
  energyleak->SetYTitle("leaked energy / total energy");
  findbg->SetXTitle("#DeltaR");
  findbg->SetYTitle("Total energy / track momentum");
  TH2F *tevsp = new TH2F("tevsp","",50,0.0,20.0,50,0.0,30.0);
  TH1F *pmean = new TH1F("pmean","",20,0.0,15.0);
  tevsp->SetXTitle("track momentum (GeV)");
  tevsp->SetYTitle("Total Energy (GeV)");
  TH2F *tevspcent = new TH2F("tevspcent","",20,0.0,15.0,20,0.0,15.0);
  tevspcent->SetXTitle("track momentum (GeV)");
  tevspcent->SetYTitle("Energy in central tower (GeV)");
  TH1F *cmean = new TH1F("cmain","",20,0.0,15.0);
  TH2F *sistertracks = new TH2F("sistertracks","",20,0.0,8.0,20,0.0,8.0);
  sistertracks->SetXTitle("Track momentum (GeV)");
  sistertracks->SetYTitle("Neighbor momentum (GeV)");
  TH2F* dEdxvsp = new TH2F("dEdxvsp","",100,0.15,1.3,100,-5.7,-5.);
  dEdxvsp->SetXTitle("Log(p)");
  dEdxvsp->SetYTitle("Log(dE/dx)");
  TH2F* dEdxvsp_east = new TH2F("dEdxvsp_east","",100,0.15,1.3,100,-5.7,-5.0);
  dEdxvsp_east->SetXTitle("Log(p)");
  dEdxvsp_east->SetYTitle("Log(dE/dx)");
  TH2F* dEdxvsp_west = new TH2F("dEdxvsp_west","",100,0.15,1.3,100,-5.7,-5.0);
  dEdxvsp_west->SetXTitle("Log(p)");
  dEdxvsp_west->SetYTitle("Log(dE/dx)");
  TH2F* energyleak2 = new TH2F("energyleak2","",20,0.0,0.03,20,0.0,1.0);
  TH1F* energymean2 = new TH1F("energymean2","",20,0.0,0.03);
  TH1F* towermult = new TH1F("towermult","",9,0.0,9.0);
  energyleak2->SetXTitle("#DeltaR");
  energyleak2->SetYTitle("leaked energy/total energy");
  towermult->SetXTitle("Neighbors with energy");
  TH2F* multvsp = new TH2F("multvsp","",20,0.0,20.0,9,0.0,9.0);
  multvsp->SetXTitle("Track momentum (GeV)");
  multvsp->SetYTitle("Neighbors with energy");
  TH1F* multmean = new TH1F("multmean","",20,0.0,20.0);
  TH2F* tep3 = new TH2F("tep3","2 < p < 3",20,0.0,0.03,20,0.0,4.0);
  TH2F* tep5 = new TH2F("tep5","3 < p < 5",20,0.0,0.03,20,0.0,4.0);
  TH2F* tep10 = new TH2F("tep10","5 < p < 10",20,0.0,0.03,20,0.0,4.0);
  tep3->SetXTitle("DeltaR");
  tep3->SetYTitle("Total energy / track momentum");
  tep5->SetXTitle("DeltaR");
  tep5->SetYTitle("Total energy / track momentum");
  tep10->SetXTitle("DeltaR");
  tep10->SetYTitle("Total energy / track momentum");
  TH1F* tep3mean = new TH1F("tep3mean","",20,0,0.03);
  TH1F* tep5mean = new TH1F("tep5mean","",20,0,0.03);
  TH1F* tep10mean = new TH1F("tep10mean","",20,0,0.03);
  TH1F* multen = new TH1F("multen","",40,0.0,1.0);
  multen->SetXTitle("Energy in neighbor towers (GeV)");
  TH1F* east_histo = new TH1F("east_histo","Electron E/p in East",40,0.0,2.0);
  TH1F* west_histo = new TH1F("west_histo","Electron E/p in West",40,0.0,2.0);
  TH1F* all_histo = new TH1F("all_histo","Electron E/p",40,0.0,2.0);
  TH1F* notrg = new TH1F("notrg","Electron E/p",40,0.0,2.0);
  TH2F* pvsep = new TH2F("pvsep","Electron p vs E/p",120,0,3.0,20,0,20.0);
  pvsep->SetYTitle("p (Gev)");
  pvsep->SetXTitle("E/p");
  TH2F* pvsep0 = new TH2F("pvsep0","Electron p vs E/p",120,0,3.0,20,0,20.0);
  pvsep0->SetYTitle("p (Gev)");
  pvsep0->SetXTitle("E/p");
  TH2F* evsep = new TH2F("evsep","Electron E vs E/p",120,0,3.0,20,0,20.0);
  evsep->SetYTitle("E (GeV)");
  evsep->SetXTitle("E/p");

  TH1F* bsmde = new TH1F("bsmde","BSMDE ADC TOT",1500,0,1500);
  TH1F* bsmdp = new TH1F("bsmdp","BSMDP ADC TOT",1500,0,1500);

  TH1F* bsmde_central = new TH1F("bsmde_central","BSMDE ADC TOT",100,0,1500);
  TH1F* bsmde_mid = new TH1F("bsmde_mid","BSMDE ADC TOT",100,0,1500);
  TH1F* bsmde_outer = new TH1F("bsmde_outer","BSMDE ADC TOT",100,0,1500);

  TH2F* bsmdep = new TH2F("bsmdep","BSMDE v BSMDP",100,0,1500,100,0,1500);

  TH2F* bsmdevp = new TH2F("bsmdevp","BSMDE v p",100,1.0,15.0,100,0,1500);
  TH2F* bsmdpvp = new TH2F("bsmdpvp","BSMDP v p",100,1.0,15.0,100,0,1500);
  TH2F* bsmdevep = new TH2F("bsmdevep","BSMDE v E/p",100,0.0,2.0,100,0,1500);
  TH2F* bsmdpvep = new TH2F("bsmdpvep","BSMDP v E/p",100,0.0,2.0,100,0,1500);

  TH2F* bsmdeve = new TH2F("bsmdeve","BSMDE v E",100,1.0,30.0,100,0,1500);
  TH2F* bsmdpve = new TH2F("bsmdpve","BSMDP v E",100,1.0,30.0,100,0,1500);

  TH1F* httrig = new TH1F("httrig","HT Trigger",5,-0.5,4.5);

  TH1F* pplus = new TH1F("pplus","e+ p",100,0,20);
  TH1F* pminus = new TH1F("pminus","e- p",100,0,20);

  TH1F* posep = new TH1F("posep","e+ E/p",60,0,3.0);
  TH1F* negep = new TH1F("negep","e- E/p",60,0,3.0);


   //create the tower histograms
  char name1[100];

  for(int i = 0; i < ncrates; i++){
    for(int j = 0; j < 20; j++){
      TString ecname,ecnamep,ecnamen;
      ecname += "etacrate_";
      int cr = i+1;
      int et = j;
      ecname += cr;
      ecname += "_";
      ecname += et;
      ecnamep += ecname;
      ecnamen += ecname;
      ecnamep.ReplaceAll("te_","te_p_");
      ecnamen.ReplaceAll("te_","te_n_");
      etacrate_histo[i*20+j] = new TH1F(ecname.Data(),ecname.Data(),60,0.0,3.0);
      etacrate_histo_p[i*20+j] = new TH1F(ecnamep.Data(),ecnamep.Data(),60,0.0,3.0);
      etacrate_histo_n[i*20+j] = new TH1F(ecnamen.Data(),ecnamen.Data(),60,0.0,3.0);

    }
  }

  for(int i=0; i<ntowers; i++){
    char nameeh[100];
    sprintf(nameeh,"electron_histo_%i",i+1);
    electron_histo[i] = new TH1D(nameeh,"",60,0.,3.0);
    electron_histo[i]->SetXTitle("E/p");
    //sprintf(name1,"prs_histo_%i",i+1);
    //prs_histo[i] = new TH1D(name1,"",60,0.,500.);
    //prs_histo[i]->SetXTitle("ADC");
  }

  for(int i = 0; i < 21; i++){
    TString namebg;
    namebg += "bg_";
    namebg += i+25;
    bghisto[i] = new TH1F(namebg.Data(),namebg.Data(),60,0,3.0);
  }

  for(int i = 0; i < ncrates; i++){
    char name[100];
    char title[100];
    sprintf(name,"crate_%i",i+1);
    sprintf(title,"E/p for Crate %i",i+1);
    crate_histo[i] = new TH1F(name,title,60,0.,3.0);
    crate_histo[i]->SetXTitle("E/p");
  }

  for(int i = 0; i < nrings/2; i++){
    char name[100];
    sprintf(name,"ring2_histo_%i",i);
    ring2_histo[i] = new TH1F(name,"",60,0.,3.0);
    ring2_histo[i]->SetXTitle("E/p");
  }

  char name2[100];
  for(int i=0; i<nrings;i++)
    {
      sprintf(name2,"ring_histo_%i",i);
      //ring_histo[i] = new TH1D(name2,"",30,0.,140.0);
      //ring_histo[i]->SetXTitle("ADC / GeV Sin(#theta)");
      ring_histo[i] = new TH1D(name2,"",60,0.,3.0);
      ring_histo[i]->SetXTitle("E/p");
      char namerpve[100];
      sprintf(namerpve,"ring_pve_%i",i);
      ring_pve[i] = new TH2F(namerpve,"",20,0,20.0,20,0,20.0);
      ring_pve[i]->SetXTitle("E (GeV)");
      ring_pve[i]->SetYTitle("p (GeV)");
    }

  for(int i = 0; i < 6; i++){
    char jname[100];
    sprintf(jname,"jan_pve_%i",i);
    jan_pve[i] = new TH2F(jname,"",120,0,3.0,20,0,20.0);
    jan_pve[i]->SetXTitle("E/p");
    jan_pve[i]->SetYTitle("p (GeV)");
  }
  //global graphics functions
  gStyle->SetOptStat("oue");
  gStyle->SetOptFit(111);
  gStyle->SetCanvasColor(10);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetOptTitle(0);
  gStyle->SetPalette(1);
  gStyle->SetStatColor(0);

  StEmcOfflineCalibrationTrack* track = new StEmcOfflineCalibrationTrack();
  StEmcOfflineCalibrationCluster* cluster = new StEmcOfflineCalibrationCluster();
  tree->SetBranchAddress("clusters",&cluster);

  //**********************************************//
  //Loop Over Tracks, Fill Histograms             //
  //**********************************************//

  int nentries = tree->GetEntries();
  cout<<nentries<<endl;
  int ngoodhit = 0;
  int nplt10 = 0;
  int nnosis = 0;
  int nfinal = 0;
  int nbsmdgood = 0;
  int nnottrig = 0;
  int nfidu = 0;
  int nenterexit = 0;
  for(int j=0; j<nentries; j++){
    tree->GetEntry(j);
    track = &(cluster->centralTrack);
    TClonesArray *tracks = cluster->tracks;
    if(j % 500000 == 0) cout<<"reading "<<j<<" of "<<nentries<<endl;

    httrig->Fill((float)track->htTrig);

    if(track->charge > 0)pplus->Fill(track->p);
    if(track->charge < 0)pminus->Fill(track->p);

    int bsmdeadctot = 0;
    int bsmdpadctot = 0;
    for(int i = 0; i < 11; i++){
      if(track->smde_adc[i] > track->smde_pedestal[i])bsmdeadctot += track->smde_adc[i] - track->smde_pedestal[i];
      if(track->smdp_adc[i] > track->smdp_pedestal[i])bsmdpadctot += track->smdp_adc[i] - track->smdp_pedestal[i];
    }

    double dR = TMath::Sqrt(track->deta*track->deta + track->dphi*track->dphi);


    double scaled_adc = (track->tower_adc[0] - track->tower_pedestal[0]) / track->p;

    int index = track->tower_id[0];

    //figure out eta and etaindex
    eta = helper->getEta(index);
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);
    int geantetaindex = ((TMath::Nint(fabs(eta) * 1000.0) + 25)/50 - 1);

    double geant_scale = geant_fits[geantetaindex]->Eval(dR);
    scaled_adc /= geant_scale;
    //double geant_scale = geant_fit->Eval(dR);
    //scaled_adc *= geant_scale;
    //cout<<scaled_adc<<endl;

    //now rescale dR for last ring to make cuts work
    if(geantetaindex == 19)dR *= 0.025/0.017;

    //double tgain = bemctables->calib(1,track->tower_id[0])*gains[index-1];
    double tgain = gains[index-1];


    if((track->tower_adc[0] - track->tower_pedestal[0]) < 2.5 * track->tower_pedestal_rms[0])continue;
    ngoodhit++;
    dEdxvsp->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));
    if(track->tower_id[0] <= 2400)dEdxvsp_west->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));
    if(track->tower_id[0] > 2400)dEdxvsp_east->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));

    trgcheck->Fill(track->nonhtTrig,track->htTrig);

    if(track->tower_id[0] != track->tower_id_exit)continue;
    nenterexit++;

    if(status[index-1]!=1)continue;

    pvsep0->Fill(scaled_adc*tgain,track->p);
    if(track->p > 10)continue;	
    nplt10++;		

    //if(track->p < 1.5)continue;
    //if(track->p < 3.0)continue;
    if(track->htTrig == 2 && track->nonhtTrig == 0)continue;
    nnottrig++;
    //change the fiducial cut to a square with diagonal = 0.06 in deta, dphi space
    float squarefid = 0.02;//0.03/TMath::Sqrt(2.0);
    //if(TMath::Abs(track->deta) > squarefid || TMath::Abs(track->dphi) > squarefid)continue;

    //calculate geant scaled, pedestal subtracted adc
    //if(dR > 0.0125)continue;
    int numsis = tracks->GetEntries();
    float totalbtow = 0;
    float maxEt = 0;
    int maxId = -1;
    for(int i = 0; i < 9; i++){
      if(track->tower_adc[i] - track->tower_pedestal[i] < 0)continue;
      float theta = helper->getTheta(track->tower_id[i]);
      float nextEt = (track->tower_adc[i] - track->tower_pedestal[i]) * bemctables->calib(1,track->tower_id[i])*sin(theta);
      totalbtow += nextEt;
      if(nextEt > maxEt){
	maxEt = nextEt;
	maxId = i;
      }
    }

    if(track->dEdx > 3.5e-6 && track->dEdx <5.0e-6 && numsis ==0 &&maxId == 0)drvsep->Fill(scaled_adc*tgain,dR);
    if(dR > 0.02)continue;
    nfidu++;
    //if(track->p > 6.0)continue;				
    //if(track->p > 15)continue;
    //cout<<track->dEdx<<endl;


    //if(track->dEdx*1000000 > 4.5 || track->dEdx*1000000 < 3.5)continue;

    //cout<<track->htTrig<<endl;

    for(int i = 0; i < 21; i++){
      if(numsis > 0)break;
      if(maxId != 0)break;
      if(track->dEdx*1e7 > 25 + i && track->dEdx*1e7 < 26+i)bghisto[i]->Fill(scaled_adc*tgain);
    }

    //if(track->dEdx < 3.5e-6 || track->dEdx > 5.0e-6)continue;
    if(track->dEdx < 3.5e-6 || track->dEdx > 4.5e-6)continue;
    //if((bsmdeadctot > -1 && bsmdeadctot < 50) && (bsmdpadctot < 50 && bsmdpadctot > -1))continue;
    nbsmdgood++;
    //if(bsmdeadctot < 500) continue;

    //if(bsmdeadctot < 84.*track->p)continue;
    //if(bsmdeadctot > 200.*track->p + 1500)continue;

    //if(bsmdpadctot < 800)continue;

    if(numsis > 0)continue;

    nnosis++;
    if(maxId != 0) continue;


    nfinal++;
    if(track->htTrig!=2)notrg->Fill(scaled_adc*tgain);

    //if(!track->nonhtTrig)continue;
    //if(track->nHits < 25)continue;
    //if(status[index-1]==1)ring_histo[etaindex]->Fill(scaled_adc*gains[index-1]);

    //scaled_adc = totalbtow/track->p;
    //tgain = 1.0;

    float phi = helper->getPhi(index);
    int crate,sequence;
    decoder->GetCrateFromTowerId(index,crate,sequence);
    etacrate_histo[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);
    if(track->charge > 0)etacrate_histo_p[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);
    if(track->charge < 0)etacrate_histo_n[(crate-1)*20+geantetaindex]->Fill(scaled_adc*tgain);

    electron_histo[index-1]->Fill(scaled_adc*tgain);
    ring_histo[etaindex]->Fill(scaled_adc*tgain);
    if(etaindex == 0 || etaindex == 39){
      //cout<<etaindex<<" "<<tgain<<" "<<track->p<<" "<<scaled_adc*tgain*track->p<<" "<<scaled_adc*tgain<<endl;
    }
    //cout<<index<<" "<<gains[index-1]<<" "<<scaled_adc*track->p<<" "<<track->p<<" "<<status[index-1]<<endl;
    ring_pve[etaindex]->Fill(scaled_adc*tgain*track->p,track->p);

    dEdxvsp->Fill(TMath::Log10(track->p),TMath::Log10(track->dEdx));

    float abseta = TMath::Abs(eta);
    if(abseta > 0.95){
      jan_pve[5]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.9){
      jan_pve[4]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.6){
      jan_pve[3]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.3){
      jan_pve[2]->Fill(scaled_adc*tgain,track->p);
    }else if(abseta > 0.05){
      jan_pve[1]->Fill(scaled_adc*tgain,track->p);
    }else{
      jan_pve[0]->Fill(scaled_adc*tgain,track->p);
    }

    all_histo->Fill(scaled_adc*tgain);
    pvsep->Fill(scaled_adc*tgain,track->p);
    evsep->Fill(scaled_adc*tgain,track->p*scaled_adc*tgain);
    tevsp->Fill(track->p,scaled_adc*tgain*track->p);

    if(track->charge > 0)posep->Fill(scaled_adc*tgain);
    if(track->charge < 0)negep->Fill(scaled_adc*tgain);

    //if(scaled_adc*tgain < 0.7 || scaled_adc*tgain > 5.0)continue;
    bsmde->Fill(bsmdeadctot);
    bsmdp->Fill(bsmdpadctot);
    bsmdep->Fill(bsmdeadctot,bsmdpadctot);

    if(abseta > 0.6){
      bsmde_outer->Fill(bsmdeadctot);
    }else if(abseta > 0.3){
      bsmde_mid->Fill(bsmdeadctot);
    }else{
      bsmde_central->Fill(bsmdeadctot);
    }

    bsmdevp->Fill(track->p,bsmdeadctot);
    bsmdpvp->Fill(track->p,bsmdpadctot);
    bsmdevep->Fill(scaled_adc*tgain,bsmdeadctot);
    bsmdpvep->Fill(scaled_adc*tgain,bsmdpadctot);

    bsmdeve->Fill(scaled_adc*tgain*track->p,bsmdeadctot);
    bsmdpve->Fill(scaled_adc*tgain*track->p,bsmdpadctot);

    if(dR > 0.015)continue;
    if(track->tower_id[0] <= 2400){
      west_histo->Fill(scaled_adc*tgain);
    }
    if(track->tower_id[0] > 2400){
      east_histo->Fill(scaled_adc*tgain);
    }

  }
  cout<<"processed electron tree"<<endl;
  cout<<"ngoodhit: "<<ngoodhit<<endl;
  cout<<"nenterexit: "<<nenterexit<<endl;
  cout<<"n not trig: "<<nnottrig<<endl;
  cout<<"n p < 10: "<<nplt10<<endl;
  cout<<"n in fidu: "<<nfidu<<endl;
  cout<<"nbsmdhit: "<<nbsmdgood<<endl;
  cout<<"n no sis: "<<nnosis<<endl;
  cout<<"n final: "<<nfinal<<endl;

  //double ew[21];
  for(int h=0;h<21;h++){
    TH1D* projection = energyleak->ProjectionY("projection",h,h);
    float mean = projection->GetMean();
    energymean->SetBinContent(h,mean);
    TH1D* projection1 = findbg->ProjectionY("projection1",h,h);
    float mean1 = projection1->GetMean();
    leakmean->SetBinContent(h,mean1);
    TH1D* projection2 = tevsp->ProjectionY("projection2",h,h);
    float mean2 = projection2->GetMean();
    pmean->SetBinContent(h,mean2);
    //ew[h] = projection2->GetRMS();
    TH1D* projection3 = tevspcent->ProjectionY("projection3",h,h);
    float mean3 = projection3->GetMean();
    cmean->SetBinContent(h,mean3);
    TH1D* projection4 = energyleak2->ProjectionY("projection4",h,h);
    float mean4 = projection4->GetMean();
    energymean2->SetBinContent(h,mean4);
    TH1D* projection5 = multvsp->ProjectionY("projection5",h,h);
    float mean5 = projection5->GetMean();
    multmean->SetBinContent(h,mean5);
    TH1D* projection6 = tep3->ProjectionY("projection6",h,h);
    float mean6 = projection6->GetMean();
    tep3mean->SetBinContent(h,mean6);
    TH1D* projection7 = tep3->ProjectionY("projection7",h,h);
    float mean7 = projection7->GetMean();
    tep5mean->SetBinContent(h,mean7);
    TH1D* projection8 = tep3->ProjectionY("projection8",h,h);
    float mean8 = projection8->GetMean();
    tep10mean->SetBinContent(h,mean8);
  }

  TF1* fitleak = new TF1("fitleak","[0]",0,0.03);
  fitleak->SetLineWidth(0.1);
  leakmean->Fit(fitleak,"rq");


  //**********************************************//
  //Fit Tower Histograms                          //
  //**********************************************//
  /*
  for(int i=0; i<ntowers; i++){
	  
    if(i%600 == 0) cout<<"fitting tower "<<i+1<<" of "<<ntowers<<endl;
		
    sprintf(name,"fit_%i",i+1);
		
		//this fit is for the electron tree
    fit[i] = new TF1(name,fit_function,0.,140.,6);
    fit[i]->SetParameter(1,65.);
    fit[i]->SetParameter(2,10.);
    fit[i]->SetParameter(3,10.); //relative height of peak to bg
    fit[i]->SetParameter(4,10.);
    fit[i]->SetParameter(5,3.);
    fit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma");
		
    fit[i]->SetLineColor(kGreen);
    fit[i]->SetLineWidth(0.6);
		
    electron_histo[i]->Fit(fit[i],"rq");
  }
  */
  //**********************************************//
  //Fit Ring Histograms                           //
  //**********************************************//

  for(int i=0; i<nrings; i++){
	  
    //cout<<"fitting ring "<<i+1<<" of "<<nrings<<endl;
		
    sprintf(name,"ring_fit_%i",i);
    /*
    ringfit[i] = new TF1(name,fit_function,0.,140.,6);
    ringfit[i]->SetParameter(1,1.);
    ringfit[i]->SetParameter(2,0.2);
    ringfit[i]->SetParameter(3,1.5); //relative height of peak to bg
    ringfit[i]->SetParameter(4,0.15);
    ringfit[i]->SetParameter(5,0.8);
    ringfit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma");
    */		
    //TF1* ffff = new TF1("ffff","expo(0) + gaus(2)",0.4,1.7);

    ring_histo[i]->Sumw2();
    //ring_histo[i]->Rebin(3);

    ringfit[i] = new TF1(name,"pol1(0) + gaus(2)");
    ringfit[i]->SetParLimits(0,0,10.0*ring_histo[i]->GetBinContent(1));
    ringfit[i]->SetParLimits(1,-10000,0);
    ringfit[i]->SetParLimits(2,0,10.0*ring_histo[i]->GetMaximum());
    ringfit[i]->SetParLimits(3,0,10);
    ringfit[i]->SetParameter(0,ring_histo[i]->GetBinContent(1));
    ringfit[i]->SetParameter(1,-ring_histo[i]->GetBinContent(1)/6.0);
    ringfit[i]->SetParameter(2,ring_histo[i]->GetMaximum());
    ringfit[i]->SetParameter(3,0.95);
    ringfit[i]->SetParameter(4,0.15);
    ringfit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    /*
    ringfit[i] = new TF1(name,fit_function2,0.1,2.5,8);
    ringfit[i]->SetParameter(1,1.);
    ringfit[i]->SetParameter(2,0.2);
    ringfit[i]->SetParameter(3,1.5); //relative height of peak to bg
    ringfit[i]->SetParameter(4,0.25);
    ringfit[i]->SetParameter(5,0.15);
    ringfit[i]->SetParameter(7,0.8);
    ringfit[i]->SetParNames("Constant","Mean","Sigma","Peak Ratio","Bg Mean","Bg Sigma","Bg2 constant","Bg2 decay");
    	
    */
    ringfit[i]->SetLineColor(kBlue);
    ringfit[i]->SetLineWidth(0.6);
    
    ring_histo[i]->Fit(ringfit[i],"rql","",0.2,1.7);
		
    ringprec->SetBinContent(i+1,(ringfit[i]->GetParameter(3)));
    ringprec->SetBinError(i+1,ringfit[i]->GetParameter(4));
    ringprec2->SetBinContent(i+1,(ringfit[i]->GetParameter(3)));
    ringprec2->SetBinError(i+1,ringfit[i]->GetParError(3));
    //ew[i] = 4066/(60*(fit[i]->GetParameter(2))*(fit[i]->GetParameter(2)));

    float mean = ringfit[i]->GetParameter(3);
    float merr = ringfit[i]->GetParError(3);
    cout<<"ring "<<i<<" "<<mean<<" "<<merr/mean<<" "<<ring_histo[i]->GetEntries()<<endl;
  }

  for(int i = 0; i < nrings/2; i++){
    ring2_histo[i]->Add(ring_histo[2*i]);
    ring2_histo[i]->Add(ring_histo[2*i+1]);
    sprintf(name,"ring2_fit_%i",i);
    ring2fit[i] = new TF1(name,"pol1(0) + gaus(2)",0.3,1.7);

    ring2_histo[i]->Rebin(3);

    ring2fit[i]->SetParLimits(0,0,10.0*ring2_histo[i]->GetBinContent(1));
    ring2fit[i]->SetParLimits(1,-10000,0);
    ring2fit[i]->SetParLimits(2,0,10.0*ring2_histo[i]->GetMaximum());
    ring2fit[i]->SetParLimits(3,0,10);
    ring2fit[i]->SetParLimits(4,0.17,0.175);
    ring2fit[i]->SetParameter(0,ring2_histo[i]->GetBinContent(1));
    ring2fit[i]->SetParameter(1,-ring2_histo[i]->GetBinContent(1)/6.0);
    ring2fit[i]->SetParameter(2,ring2_histo[i]->GetMaximum());
    ring2fit[i]->SetParameter(3,0.95);
    ring2fit[i]->SetParameter(4,0.11245);
    ring2fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");

    ring2_histo[i]->Fit(ring2fit[i],"rql","",0.3,1.7);

    ring2prec->SetBinContent(i+1,(ring2fit[i]->GetParameter(3)));
    ring2prec->SetBinError(i+1,ring2fit[i]->GetParameter(4));
    ring2prec2->SetBinContent(i+1,(ring2fit[i]->GetParameter(3)));
    ring2prec2->SetBinError(i+1,ring2fit[i]->GetParError(3));

    cout<<"ring2 "<<i<<" "<<ring2fit[i]->GetParameter(3)<<" "<<ring2fit[i]->GetParError(3)<<endl;
  }

  for(int i = 0; i < ntowers; i++){
    char name[100];
    sprintf(name,"electron_fit_%i",i+1);
    /*
    fit[i] = new TF1(name,"pol1(0)+gaus(2)");
    fit[i]->SetParLimits(0,0,10.0*electron_histo[i]->GetBinContent(1));
    fit[i]->SetParLimits(1,-10000,0);
    fit[i]->SetParLimits(2,0,10.0*electron_histo[i]->GetMaximum());
    fit[i]->SetParLimits(3,0,10);
    fit[i]->SetParameter(0,electron_histo[i]->GetBinContent(1));
    fit[i]->SetParameter(1,-electron_histo[i]->GetBinContent(1)/6.0);
    fit[i]->SetParameter(2,electron_histo[i]->GetMaximum());
    fit[i]->SetParameter(3,0.95);
    fit[i]->SetParameter(4,0.15);
    fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    */
    fit[i] = new TF1(name,"pol0(0)+gaus(1)");
    fit[i]->SetParLimits(0,0,10.0*electron_histo[i]->GetBinContent(1));
    fit[i]->SetParLimits(1,0,10.0*electron_histo[i]->GetMaximum());
    fit[i]->SetParLimits(2,0,10);
    fit[i]->SetParameter(0,electron_histo[i]->GetBinContent(1));
    fit[i]->SetParameter(1,electron_histo[i]->GetMaximum());
    fit[i]->SetParameter(2,0.95);
    fit[i]->SetParameter(3,0.15);
    fit[i]->SetParNames("constant1","constant2","Mean","Sigma");

    electron_histo[i]->Fit(fit[i],"rql","",0.3,1.7);
  }

  ofstream fitfile(ffname);

  TF1* etacrate_fit[ncrates*20];
  for(int ii = 0; ii < ncrates; ii++){
    for(int j = 0; j < 20; j++){
      TString ecname;
      ecname += "fit";
      int cr = ii+1;
      int et = j;
      int i = ii*20 + j;
      //ecname += cr;
      //ecname += "_";
      //ecname += et;
      etacrate_fit[i] = new TF1(ecname.Data(),"pol1(0) + gaus(2)",0.25,1.6);
      //etacrate_fit[i]->SetParLimits(0,0,10.0*etacrate_histo[i]->GetBinContent(1));
      etacrate_histo[i]->Rebin();
      etacrate_fit[i]->SetParLimits(1,-10000,0);
      etacrate_fit[i]->SetParLimits(2,0,10.0*etacrate_histo[i]->GetMaximum());
      etacrate_fit[i]->SetParLimits(3,0,10);
      etacrate_fit[i]->SetParameter(0,etacrate_histo[i]->GetBinContent(2));
      etacrate_fit[i]->SetParameter(1,-etacrate_histo[i]->GetBinContent(2)/3.0);
      etacrate_fit[i]->SetParameter(2,etacrate_histo[i]->GetMaximum());
      etacrate_fit[i]->SetParameter(3,0.96134);
      etacrate_fit[i]->SetParameter(4,0.141123);
      etacrate_fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
      
      etacrate_histo[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      etacrate_histo_p[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      etacrate_histo_n[i]->Fit(etacrate_fit[i],"rql","",0.25,1.5);
      fitfile << i << " " << etacrate_histo[i]->GetFunction("fit")->GetParameter(3) << " " << etacrate_histo_p[i]->GetFunction("fit")->GetParameter(3) << " " << etacrate_histo_n[i]->GetFunction("fit")->GetParameter(3) << endl;

    }
  }

  ofstream newgain(ngname);
  

  float gains2[ntowers];
  float gerr2[ntowers];
  for(int i = 0; i < ntowers; i++){
    float eta = helper->getEta(i+1);
    int crate,sequence;
    decoder->GetCrateFromTowerId(i+1,crate,sequence);
    int geantetaindex = ((TMath::Nint(fabs(eta) * 1000.0) + 25)/50 - 1);
    TString ecname;
    ecname += "fit";
    //int cr = ii+1;
    //int et = j;
    //int i = ii*20 + j;
    //ecname += crate;
    //ecname += "_";
    //ecname += geantetaindex;
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    int etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);
    //float adjust = ring2fit[(int)etaindex/2]->GetParameter(3);
    //cout<<etaindex<<" "<<(int)etaindex/2<<" "<<adjust<<endl;
    //float adjust = fit[i]->GetParameter(3);
    float ng = 0;
    float ne = 0;
    if(status[i] == 1){
      //float og = bemctables->calib(1,i+1)*gains[i];
      float og = gains[i];
      //float aerr = ring2fit[(int)etaindex/2]->GetParError(3);
      float adjust = etacrate_histo[(crate-1)*20+geantetaindex]->GetFunction("fit")->GetParameter(3);
      float aerr = etacrate_histo[(crate-1)*20+geantetaindex]->GetFunction("fit")->GetParError(3);
      if(geantetaindex == 19){
	adjust = ringfit[etaindex]->GetParameter(3);
	aerr = ringfit[etaindex]->GetParError(3);
      }
      ng = og/adjust;
      float gerr = peakerr[i]*gains[i]/peaks[i];
      ne = sqrt(pow(og*aerr/(adjust*adjust),2) + pow(gerr/adjust,2));
    }
    newgain << i+1 << " " << ng << " " << ne << " " << status[i] << endl;
    gains2[i] = ng;
    gerr2[i] = ne;


  }

  newgain.close();

    ///////////////////////////////////////
   //Using new gains regenerate by crate//
  ///////////////////////////////////////


  /*
  for(int j=0; j<nentries; j++){
    tree->GetEntry(j);
    track = &(cluster->centralTrack);
    TClonesArray *tracks = cluster->tracks;

    int bsmdeadctot = 0;
    int bsmdpadctot = 0;
    for(int i = 0; i < 11; i++){
      if(track->smde_adc[i] > track->smde_pedestal[i])bsmdeadctot += track->smde_adc[i] - track->smde_pedestal[i];
      if(track->smdp_adc[i] > track->smdp_pedestal[i])bsmdpadctot += track->smdp_adc[i] - track->smdp_pedestal[i];
    }

    double dR = TMath::Sqrt(track->deta*track->deta + track->dphi*track->dphi);


    double scaled_adc = (track->tower_adc[0] - track->tower_pedestal[0]) / track->p;
    double geant_scale = geant_fit->Eval(dR);
    scaled_adc *= geant_scale;
    //cout<<scaled_adc<<endl;
    int index = track->tower_id[0];

    //figure out eta and etaindex
    eta = helper->getEta(index);
    if(TMath::Abs(eta) > 0.968) eta += 0.005 * TMath::Abs(eta)/eta;
    etaindex = ((TMath::Nint(eta * 1000.0) + 25)/50 + 19);

    double tgain = bemctables->calib(1,track->tower_id[0])*gains[index-1]*gains2[index-1];
    //double tgain = gains[index-1];


    if((track->tower_adc[0] - track->tower_pedestal[0]) < 2.5 * track->tower_pedestal_rms[0])continue;

    if(track->tower_id[0] != track->tower_id_exit)continue;

    if(track->htTrig == 2)continue;
    if(track->p > 6)continue;	

    if(dR > 0.025)continue;

    if(track->dEdx < 3.4e-6)continue;
    if((bsmdeadctot > -1 && bsmdeadctot < 50) && (bsmdpadctot < 50 && bsmdpadctot > -1))continue;

    int numsis = tracks->GetEntries();
    if(numsis > 0)continue;

    float totalbtow = 0;
    float maxEt = 0;
    int maxId = -1;
    for(int i = 0; i < 9; i++){
      if(track->tower_adc[i] - track->tower_pedestal[i] < 0)continue;
      float theta = helper->getTheta(track->tower_id[i]);
      float nextEt = (track->tower_adc[i] - track->tower_pedestal[i]) * bemctables->calib(1,track->tower_id[i])*sin(theta);
      totalbtow += nextEt;
      if(nextEt > maxEt){
	maxEt = nextEt;
	maxId = i;
      }
    }
    if(maxId != 0) continue;

    eta = helper->getEta(index);
    float phi = helper->getPhi(index);
    int crate = lookup_crate(eta,phi);
    if(status[index-1]==1)crate_histo[crate-1]->Fill(scaled_adc*tgain);
  }

  for(int i = 0; i < ncrates; i++){
    sprintf(name,"crate_fit_%i",i);
    crate_histo[i]->Sumw2();	
    crate_histo[i]->Rebin(4);	

    crate_fit[i] = new TF1(name,"pol1(0) + gaus(2)",0.3,1.7);
    crate_fit[i]->SetParLimits(0,0,10.0*crate_histo[i]->GetBinContent(1));
    crate_fit[i]->SetParLimits(1,-10000,0);
    crate_fit[i]->SetParLimits(2,0,10.0*crate_histo[i]->GetMaximum());
    crate_fit[i]->SetParLimits(3,0,10);
    crate_fit[i]->SetParameter(0,crate_histo[i]->GetBinContent(1));
    crate_fit[i]->SetParameter(1,-crate_histo[i]->GetBinContent(1)/6.0);
    crate_fit[i]->SetParameter(2,-crate_histo[i]->GetMaximum());
    crate_fit[i]->SetParameter(3,0.929);
    crate_fit[i]->SetParameter(4,0.156);
    crate_fit[i]->SetParNames("constant1","Slope","constant2","Mean","Sigma");
    crate_fit[i]->SetLineColor(kBlue);
    crate_fit[i]->SetLineWidth(0.6);


    crate_histo[i]->Fit(crate_fit[i],"rql","",0.3,1.8);
    float mean = crate_histo[i]->GetFunction(name)->GetParameter(3);
    float merr = crate_histo[i]->GetFunction(name)->GetParError(3);
    crateprec->SetBinContent(i+1,mean);
    crateprec->SetBinError(i+1,merr);
    cout<<"crate "<<i+1<<" "<<mean<<" "<<merr/mean<<endl;
  }
  
  ofstream newgain(ngname);

  float gains3[ntowers];
  float gerr3[ntowers];
  for(int i = 0; i < ntowers; i++){
    float eta = helper->getEta(i+1);
    float phi = helper->getPhi(i+1);
    int crate = lookup_crate(eta,phi);
    float adjust = crate_fit[crate-1]->GetParameter(3);
    float og = bemctables->calib(1,i)*gains[i]*gains2[i];
    float ng = og;
    float aerr = crate_fit[crate-1]->GetParError(3);
    float ne = sqrt(pow(gains[i]*gerr2[i],2) + pow(gains2[i]*gainerr[i],2));
    if(fabs(adjust-1)/aerr > 1.5){
      ne = sqrt(pow(ne/(adjust),2)+pow(og*aerr/(adjust*adjust),2));
      ng /= adjust;
    }
    newgain << i+1 << " " << ng << " " << ne << " " << status[i] << endl;
    gains3[i] = ng;
    gerr3[i] = ne;
  }

  newgain.close();
  */
  outfile.Write();
  outfile.Close();

}
Ejemplo n.º 13
0
bdump(){
  /* 
  * Loading the evio-root shared library. Change the path if running the script
  * from a different directory.
  */
  gSystem->Load("../lib/libEvioRoot.so");  
  TEvioFileReader *reader = new TEvioFileReader();
  TEvioDataEvent  *event  = new TEvioDataEvent();
  reader->open("/home/celentan/WORK/BeamDump/GenoaTest/data/run_JLabFadc_000626.evio.0");
  
  TH1D *hADC0 = new TH1D("hADC0","",500,0.0,500.); 
  TH1D *hADC00 = new TH1D("hADC00","",500,0.0,500.);
  
  TH1D *hADC1 = new TH1D("hADC1","",500,0.0,500.);
  TH1D *hADC2 = new TH1D("hADC2","",500,0.0,500.);
  TH1D *hADC3 = new TH1D("hADC3","",500,0.0,500.);
  TH1D *hADC4 = new TH1D("hADC4","",500,0.0,500.);
  
  
  
  TH1D *hCHARGE0 = new TH1D("hCHARGE0","",2500,-1000.0,20000.);
  TH1D *hCHARGE1 = new TH1D("hCHARGE1","",500,-1000.0,20000.);
  TH1D *hCHARGE2 = new TH1D("hCHARGE2","",500,-1000.0,20000.);
  TH1D *hCHARGE3 = new TH1D("hCHARGE3","",500,-1000.0,20000.);
  TH1D *hCHARGE4 = new TH1D("hCHARGE4","",500,-1000.0,20000.);
  
  
  TH2D *hSTRIP0,*hSTRIP1,*hSTRIP2,*hSTRIP3,*hSTRIP4;
  
  
  
  
  int icounter = 0;
  int Nevents = reader->getEntries();
  reader->next();reader->next();
  
  
  hSTRIP0=new TH2D("hSTRIP0","",Nevents/600,0,Nevents,500,-1000,15000.);
  hSTRIP1=new TH2D("hSTRIP1","",Nevents/600,0,Nevents,500,-1000,20000.);
  hSTRIP2=new TH2D("hSTRIP2","",Nevents/600,0,Nevents,500,-1000,20000.);
  hSTRIP3=new TH2D("hSTRIP3","",Nevents/600,0,Nevents,500,-1000,20000.);
  hSTRIP4=new TH2D("hSTRIP4","",Nevents/600,0,Nevents,500,-1000,20000.);
  
  
  hSTRIP00=new TH2D("hSTRIP00","",Nevents/600,0,Nevents,500,-1000,15000.);
  hSTRIP10=new TH2D("hSTRIP10","",Nevents/600,0,Nevents,500,-1000,20000.);
  hSTRIP20=new TH2D("hSTRIP20","",Nevents/600,0,Nevents,500,-1000,20000.);
  hSTRIP30=new TH2D("hSTRIP30","",Nevents/600,0,Nevents,500,-1000,20000.);
  hSTRIP40=new TH2D("hSTRIP40","",Nevents/600,0,Nevents,500,-1000,20000.);
  
  TClonesArray *flash;
  TClonesArray *tdcL;
  TCanvas *c=new TCanvas("c","c");
  while( reader->next() == true ){
    
    flash=0;
    tdcL=0;
    hADC00->Reset();
    if (icounter==(Nevents-10)) break;
    
  
    // if (icounter==10000) break;
    /* reader->getEvent(*event);*/
    tdcL = reader->getTDC(1,57607);//tag mother, tag TDC 
    if (tdcL!=0){
      int nentries = tdcL->GetEntries();   
      for(int loop = 0; loop < nentries; loop++){	
	TTDCClass *tdc = (TTDCClass *) tdcL->At(loop);
	int slot = tdc->GetSlot();
	int channel = tdc->GetChannel();
	int value = tdc->GetValue();
	
	//cout<<slot<<" "<<channel<<" "<<value<<endl;
      }
    }
    
    
    flash= reader->getFlashADC(1,57601); //tag mother, tag FADC
    
    
    if (flash!=0){
      int nentries1 = flash->GetEntries();
      
      vector< int > v0,v1,v2,v3,v4;
      double q0,q1,q2,q3,q4;
      double ped0,ped1,ped2,ped3,ped4; 
      
      
      for(int loop = 0; loop < nentries1; loop++){
	TADCClass *adc = (TADCClass *) flash->At(loop);

	int slot    = adc->GetSlot();
	int channel = adc->GetChannel();
	int nsamples = adc->GetRows();
	int value;
		
	//	cout << " SLOT = " << adc->GetSlot() << "  CHANNEL = " << adc->GetChannel() << " "<<nsamples<<endl;
	for(int i = 0; i < nsamples; i++){
	  value = adc->GetValue(i);
	  if ((slot == 4) && (channel == 1)){
	    hADC0->Fill(i,value);
	    hADC00->Fill(i,value);
	    v0.push_back(value);
	  }
	  else if  ((slot == 4) && (channel == 1)){
	    hADC1->Fill(i,value);
	    v1.push_back(value);
	  }
	  else if  ((slot == 4) && (channel == 2)){
	    hADC2->Fill(i,value);
	    v2.push_back(value);
	  }
	  else if  ((slot == 4) && (channel == 3)){
	    hADC3->Fill(i,value);
	    v3.push_back(value);
	  }
	  else if  ((slot == 4) && (channel == 4)){
	    hADC4->Fill(i,value);
	    v4.push_back(value);
	  }
	}
	
      }
      
      if(icounter%100==0) {
	  cout << " processed " << icounter << "  events " << endl;
	  c->cd();
	  hADC00->Draw();
	  
	  hADC00->GetYaxis()->SetRangeUser(0,1E3);
	  c->Modified();
	  c->Update();
      }
      q0=integrate(v0,10,80,300,400,ped0);
    //  q0=integrate(v0,30,280,0,20,ped0);
      q1=integrate(v1,150,250,0,50,ped1);
      q2=integrate(v2,150,250,0,50,ped2);
      q3=integrate(v3,150,250,0,50,ped3);
      q4=integrate(v4,150,250,0,50,ped4);
      
      
      hCHARGE0->Fill(q0);
      hCHARGE1->Fill(q1);
      hCHARGE2->Fill(q2);
      hCHARGE3->Fill(q3);
      hCHARGE4->Fill(q4);
      
      hSTRIP0->Fill(icounter,q0);
      hSTRIP1->Fill(icounter,q1);
      hSTRIP2->Fill(icounter,q2);
      hSTRIP3->Fill(icounter,q3);
      hSTRIP4->Fill(icounter,q4);
      
      
      hSTRIP00->Fill(icounter,ped0);
      hSTRIP10->Fill(icounter,ped1);
      hSTRIP20->Fill(icounter,ped2);
      hSTRIP30->Fill(icounter,ped3);
      hSTRIP40->Fill(icounter,ped4);
    }
    icounter++;
  }
  
  delete flash;
  delete tdcL;
  //  cin.get();
  
  
  hADC0->Scale(1./icounter);
  hADC1->Scale(1./icounter);
  hADC2->Scale(1./icounter);
  hADC3->Scale(1./icounter);
  hADC4->Scale(1./icounter);
  
  TCanvas *c0=new TCanvas("c0","c0");
  c0->Divide(2,2);
  c0->cd(1);hADC0->Draw();
  c0->cd(2);hCHARGE0->Draw();
  c0->cd(3);hSTRIP0->ProfileX()->Draw();
  c0->cd(4);hSTRIP00->ProfileX()->Draw();
  
  TCanvas *c1=new TCanvas("c1","c1");
  c1->Divide(2,2);
  c1->cd(1);hADC1->Draw();
  c1->cd(2);hADC2->Draw();
  c1->cd(3);hADC3->Draw();
  c1->cd(4);hADC4->Draw();
  
  TCanvas *c11=new TCanvas("c11","c11");
  c11->Divide(2,2);
  c11->cd(1);hCHARGE1->Draw();
  c11->cd(2);hCHARGE2->Draw();
  c11->cd(3);hCHARGE3->Draw();
  c11->cd(4);hCHARGE4->Draw();
  
  TCanvas *c12=new TCanvas("c12","c12");
  c12->Divide(2,2);
  c12->cd(1);hSTRIP1->ProfileX()->Draw();
  c12->cd(2);hSTRIP2->ProfileX()->Draw();
  c12->cd(3);hSTRIP3->ProfileX()->Draw();
  c12->cd(4);hSTRIP4->ProfileX()->Draw();
  
  TCanvas *c13=new TCanvas("c13","c13");
  c13->Divide(2,2);
  c13->cd(1);hSTRIP10->ProfileX()->Draw();
  c13->cd(2);hSTRIP20->ProfileX()->Draw();
  c13->cd(3);hSTRIP30->ProfileX()->Draw();
  c13->cd(4);hSTRIP40->ProfileX()->Draw();
  
  
  
  cout<<"END"<<endl;
  
  
}
Ejemplo n.º 14
0
int
main (int argc, char *argv[])
{
  if (argc != 3)
    {
      cout << "Usage: " << argv[0] << " INPUT_FILE OUTPUT_FILE" << endl;
      cout << "  or:  " << argv[0] << " INPUT_LIST OUTPUT_FILE" << endl;
      cout << "Run vertexing performance analysis on INPUT_FILE and store output to OUTPUT_FILE. If the" << endl;
      cout << "first argument is a text file, analysis is run on each file listed inside." << endl;
      cout << endl;

      return 0;
    }
  string inputFile = argv[1], outputFile = argv[2], upperInputFile;
  upperInputFile.resize (inputFile.length ());
  transform (inputFile.begin (), inputFile.end (), upperInputFile.begin (), ::toupper);

  // so canvases don't appear on the screen when being created
  // very useful when running on the OSU T3 from CERN
  gROOT->SetBatch();

  //Create chain of root trees
  TChain chain("Delphes");

  if (upperInputFile.length () < 5 || upperInputFile.substr (upperInputFile.length () - 5, 5) != ".ROOT")
  {
    ifstream fin (inputFile);
    string line;
    while(getline(fin, line))
      {
	chain.Add(line.c_str());
      }
    fin.close();
  }
  else
    chain.Add(inputFile.c_str());

  
  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();
  cout << "processing " << numberOfEntries << " events..." << endl << endl;

  // Get pointers to branches used in this analysis
  TClonesArray *branchTrack = treeReader->UseBranch("Track");
  TClonesArray *branchNPU = treeReader->UseBranch("NPU");
  TClonesArray *branchCluster = treeReader->UseBranch("Cluster");
  TClonesArray *branchVBFquarks = treeReader->UseBranch("VBFquarks");


  ///////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////
  // Book histograms
  ///////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////

  TH1::SetDefaultSumw2();

  // VBF Quark Histograms
  TH1D *hVBFQuarkEta   = new TH1D("VBFQuarkEta", ";VBF quark #eta", 1000, -5.0, 5.0);
  TH1D *hVBFQuarkPt   = new TH1D("VBFQuarkPt", ";VBF quark p_{T} [GeV]", 1000, 0.0, 1000.0);
  TH2D *hVBFQuarkEtaVsPhi   = new TH2D("VBFQuarkPt", ";VBF quark #phi;VBF quark #eta", 500, -3.5, 3.5, 500, -5.0, 5.0);

  // Track Histograms
  TH1D *hTrackPt   = new TH1D("TrackPt", "; Track p_{T} [GeV]", 400, 0.0, 200.0);
  TH1D *hVBFTrackPt   = new TH1D("VBFTrackPt", ";VBF track p_{T} [GeV]", 400, 0.0, 200.0);
  TH1D *hPUTrackPt   = new TH1D("PUTrackPt", ";PU track p_{T} [GeV]", 400, 0.0, 200.0);
  TH1D *hTrackX = new TH1D("TrackX", "; Track x [mm]", 300, -3, 3);
  TH1D *hTrackY = new TH1D("TrackY", "; Track y [mm]", 300, -3, 3);
  TH1D *hTrackZ = new TH1D("TrackZ", "; Track z [mm]", 300, -300, 300);

  TH1D *hTrackEX = new TH1D("TrackEX", "; Track #sigma_{x} [mm]", 100, 0, 1);
  TH1D *hTrackEY = new TH1D("TrackEY", "; Track #sigma_{y} [mm]", 100, 0, 1);
  TH1D *hTrackEZ = new TH1D("TrackEZ", "; Track #sigma_{z} [mm]", 100, 0, 20);

  TH1D *hTrackXSmearingShift = new TH1D("TrackXSmearingShift", "; Track x_{smeared} - x_{true} [mm]", 100, -2, 2);
  TH1D *hTrackYSmearingShift = new TH1D("TrackYSmearingShift", "; Track y_{smeared} - y_{true} [mm]", 100, -2, 2);
  TH1D *hTrackZSmearingShift = new TH1D("TrackZSmearingShift", "; Track z_{smeared} - z_{true} [mm]", 100, -50, 50);

  TH1D *hTrackDisplacementClusterX = new TH1D("TrackDisplacementClusterX", "; |Track x - Cluster x| [mm]", 100, 0, 10);
  TH1D *hTrackDisplacementClusterY = new TH1D("TrackDisplacementClusterY", "; |Track y - Cluster y| [mm]", 100, 0, 10);
  TH1D *hTrackDisplacementClusterZ = new TH1D("TrackDisplacementClusterZ", "; |Track z - Cluster z| [mm]", 100, 0, 300);

  TH1D *hTrackDisplacementInteractionX = new TH1D("TrackDisplacementInteractionX", "; |Track x - Interaction x| [mm]", 100, 0, 10);
  TH1D *hTrackDisplacementInteractionY = new TH1D("TrackDisplacementInteractionY", "; |Track y - Interaction y| [mm]", 100, 0, 10);
  TH1D *hTrackDisplacementInteractionZ = new TH1D("TrackDisplacementInteractionZ", "; |Track z - Interaction z| [mm]", 100, 0, 50);

  // Cluster Histograms
  TH1D *hClusterX = new TH1D("ClusterX", "; Cluster x [mm]", 300, -3, 3);
  TH1D *hClusterEX = new TH1D("ClusterEX", "; Cluster #sigmax [mm]", 100, 0, 0.1);
  TH1D *hClusterY = new TH1D("ClusterY", "; Cluster y [mm]", 300, -3, 3);
  TH1D *hClusterEY = new TH1D("ClusterEY", "; Cluster #sigmay [mm]", 100, 0, 0.1);
  TH1D *hClusterZ = new TH1D("ClusterZ", "; Cluster z [mm]", 300, -300, 300);
  TH1D *hClusterEZ = new TH1D("ClusterEZ", "; Cluster #sigmaz [mm]", 100, 0, 0.1);
  TH2D *hClusterTransversePosition = new TH2D("ClusterTransversePosition", "; Cluster x [mm]; Cluster y [mm]", 300, -3,3, 300, -3, 3);
  TH2D *hClusterRZPosition = new TH2D("ClusterRZPosition", "; Cluster z [mm]; Cluster r [mm]", 100, -300, 300, 100, 0, 1.5);

  // Reco PV Histograms
  TH1D *hRecoPVX = new TH1D("RecoPVX", "; Reco PV x [mm]", 300, -3, 3);
  TH1D *hRecoPVY = new TH1D("RecoPVY", "; Reco PV y [mm]", 300, -3, 3);
  TH1D *hRecoPVZ = new TH1D("RecoPVZ", "; Reco PV z [mm]", 300, -300, 300);
  TH1D *hRecoPVTrackPurity = new TH1D("RecoPVTrackPurity", "; Fraction of Reco PV tracks from primary interaction", 101, 0, 1.01);
  TH1D *hRecoPVMomentumPurity = new TH1D("RecoPVMomentumPurity", "; Fraction of Reco PV momentum from primary interaction", 101, 0, 1.01);
  TH2D *hRecoPVTransversePosition = new TH2D("RecoPVTransversePosition", "; Reco PV x [mm]; Reco PV y [mm]", 300, -3, 3, 300, -3, 3);
  TH2D *hRecoPVRZPosition = new TH2D("RecoPVRZPosition", "; RecoPV z [mm]; RecoPV r [mm]", 100, -300, 300, 100, 0, 1.5);

  // Gen PV Histograms
  TH1D *hGenPVX = new TH1D("GenPVX", "; Gen PV x [mm]", 300, -3, 3);
  TH1D *hGenPVY = new TH1D("GenPVY", "; Gen PV y [mm]", 300, -3, 3);
  TH1D *hGenPVZ = new TH1D("GenPVZ", "; Gen PV z [mm]", 300, -300, 300);
  TH2D *hGenPVTransversePosition = new TH2D("GenPVTransversePosition", "; Gen PV x [mm]; Gen PV y [mm]", 300, -3, 3, 300, -3, 3);
  TH2D *hGenPVRZPosition = new TH2D("GenPVRZPosition", "; Gen PV z [mm]; Gen PV r [mm]", 100, -300, 300, 100, 0, 1.5);

  // PV Comparison Histograms
  TH1D *hPVdisplacementZ = new TH1D("PVdisplacementZ", "; z_{gen PV} - z_{reco PV} [mm]", 200, -10, 10);
  TH1D *hAbsPVdisplacementZ = new TH1D("AbsPVdisplacementZ", ";|z_{gen PV} - z_{reco PV}| [mm]", 200, 0, 10);
  TH2D *hZRecoPVVsZGenPV = new TH2D("ZRecoPVVsZGenPV", "; z_{gen PV} [mm]; z_{reco PV} [mm]", 1000, -150, 150, 1000, -150, 150);
  TH2D *hNumTracksRecoPVVsNumTracksGenPV = new TH2D("NumTracksRecoPVVsNumTracksGenPV", ";number of tracks in Gen PV;number of tracks in Reco PV", 300, 0, 300, 300, 0, 300);
  TH2D *hPtRecoPVVsPtGenPV = new TH2D("PtRecoPVVsPtGenPV", ";#Sigma p_{T} of tracks in Gen PV;#Sigma p_{T} of tracks in Reco PV", 200, 0, 600, 200, 0, 600);

  // Size Histograms
  TH1D *hNumTracksPerEvent   = new TH1D("NumTracksPerEvent",   "; Num. of Tracks Per Event",   100,  0.0, 10000);
  TH1D *hNumTracksPerCluster = new TH1D("NumTracksPerCluster", "; Num. of Tracks Per Cluster", 100, 0.0, 500.0);
  TH1D *hNumClustersPerEvent = new TH1D("NumClustersPerEvent", "; Num. of Clusters Per Event", 100,  0.0, 100.0 );
  TH1D *hNumInteractionsPerEvent = new TH1D("NumInteractionsPerEvent", "; Num. of Interactions Per Event", 201,  0.0, 201.0 );
  TH2D *hNumClustersVsNumInteractions = new TH2D("NumClustersVsNumInteractions", ";number of interactions;number of clusters", 200, 0.0, 200.0, 200, 0.0, 200.0);
  TH2D *hPVDisplacementVsNumInteractions = new TH2D("PVDisplacementVsNInteractions", ";|z_{gen PV} - z_{reco PV}| [mm];number of interactions", 1000, 0, 10, 201, 0.0, 201.0);

  // Other Histograms
  TH1D *hClusteredTrackFraction = new TH1D("ClusteredTrackFraction", "; Fraction of tracks successfully clustered", 101, 0, 1.01);
  TH1D *hClusteredMomentumFraction = new TH1D("ClusteredMomentumFraction", "; Fraction of track p_{T} successfully clustered", 101, 0, 1.01);
  TH2D *hCorrectPrimaryVertex = new TH2D("CorrectPrimaryVertex", "; Number of Pileup Vertices; True/False Correct PV", 200, 0, 200, 2, 0, 1);


  ///////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////
  // Begin loop over all events
  ///////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////

  signal (SIGINT, signalHandler);
  for (Int_t entry = 0; entry < numberOfEntries && !interrupted; ++entry)
    {

      // Load selected branches with data from specified event
      if(!(entry % REPORT_EVERY))
        cout << "processing event " << (entry + 1) << "..." << endl;

      treeReader->ReadEntry(entry);

      // N.B. this is a hack put in by Andrew using the ScalarHT class
      // it's the number of pileup interactions, it's not actually the HT
      unsigned nInteractions = (unsigned) ((ScalarHT *) branchNPU->At(0))->HT + 1;
      unsigned nClusters = branchCluster->GetEntries();

      hNumInteractionsPerEvent->Fill(nInteractions);
      hNumClustersPerEvent->Fill(nClusters);
      hNumClustersVsNumInteractions->Fill(nInteractions,nClusters);
      hNumTracksPerEvent->Fill(branchTrack->GetEntries());

      // the cluster branch is sorted by sum pt**2, so first entry is the reconstructed primary vertex
      Cluster *recoPV = (Cluster *) branchCluster->At(0);

      double genPVX = 0;
      double genPVY = 0;
      double genPVZ = 0;

      int nUnclusteredTracks = 0;
      int nClusteredTracks = 0;
      double unclusteredMomentum = 0;
      double clusteredMomentum = 0;

      int nTracksInGenPV = 0;
      int nTracksInRecoPV = 0;
      double momentumInGenPV = 0;
      double momentumInRecoPV = 0;
      double recoPVtrackPurity = 0;
      double recoPVmomentumPurity = 0;

      map<int, double> clusterXPositionMap; // < cluster index , weighted average X position >
      map<int, double> clusterYPositionMap; // < cluster index , weighted average Y position >
      map<int, double> clusterZPositionMap; // < cluster index , weighted average Z position >

      map<int, double> interactionXPositionMap; // < interaction index , weighted average X position >
      map<int, double> interactionXWeightMap; // < interaction index , sum of weights >                                                                                                                   
      map<int, double> interactionYPositionMap; // < interaction index , weighted average Y position >
      map<int, double> interactionYWeightMap; // < interaction index , sum of weights >                                                                                                                   
      map<int, double> interactionZPositionMap; // < interaction index , weighted average Z position >
      map<int, double> interactionZWeightMap; // < interaction index , sum of weights >                                                                                                                   

      for (int iVBFquark = 0; iVBFquark < branchVBFquarks->GetEntries (); iVBFquark++)
        {
          GenParticle *vbfQuark = (GenParticle *) branchVBFquarks->At (iVBFquark);
          hVBFQuarkEta->Fill (vbfQuark->Eta);
          hVBFQuarkPt->Fill (vbfQuark->PT);
          hVBFQuarkEtaVsPhi->Fill (vbfQuark->Phi, vbfQuark->Eta);
        }

      ///////////////////////////////////////////////////////////////////////////////////////////////
      ///////////////////////////////////////////////////////////////////////////////////////////////
      // Begin loop over all clusters in the event
      ///////////////////////////////////////////////////////////////////////////////////////////////
      ///////////////////////////////////////////////////////////////////////////////////////////////

      for(int iCluster = 0; iCluster < branchCluster->GetEntries(); iCluster++)
        {
          Cluster *cluster = (Cluster *) branchCluster->At(iCluster);

	  hNumTracksPerCluster->Fill(cluster->NDF);
	  
          clusterXPositionMap[cluster->Index] = cluster->X;
          clusterYPositionMap[cluster->Index] = cluster->Y;
          clusterZPositionMap[cluster->Index] = cluster->Z;

          //fill corresponding histograms

          hClusterX->Fill(cluster->X);
          hClusterEX->Fill(cluster->ErrorX);
          hClusterY->Fill(cluster->Y);
          hClusterEY->Fill(cluster->ErrorY);
          hClusterZ->Fill(cluster->Z);
          hClusterEZ->Fill(cluster->ErrorZ);
          hClusterTransversePosition->Fill(cluster->X,cluster->Y);
          double clusterRadius = sqrt(cluster->X * cluster->X + cluster->Y * cluster->Y);
          hClusterRZPosition->Fill(cluster->Z,clusterRadius);
        }


      ///////////////////////////////////////////////////////////////////////////////////////////////
      ///////////////////////////////////////////////////////////////////////////////////////////////
      // Begin loop over all tracks in the event
      ///////////////////////////////////////////////////////////////////////////////////////////////
      ///////////////////////////////////////////////////////////////////////////////////////////////

      for(int iTrack = 0; iTrack < branchTrack->GetEntries(); iTrack++){

	Track *track = (Track *) branchTrack->At(iTrack);

        if (abs (track->PID) != 13) // N.B.: this will only work for H->4mu
          {
            if (track->IsPU)
              hPUTrackPt->Fill (track->PT);
            else
              hVBFTrackPt->Fill (track->PT);
          }

	hTrackPt->Fill(track->PT);          
	hTrackX->Fill(track->X);
	hTrackY->Fill(track->Y);
	hTrackZ->Fill(track->Z);
//	hTrackEX->Fill(track->ErrorX); FIXME
//	hTrackEY->Fill(track->ErrorY); FIXME
//	hTrackEZ->Fill(track->ErrorZ); FIXME
//	hTrackXSmearingShift->Fill(track->X-track->TrueX); FIXME
//	hTrackYSmearingShift->Fill(track->Y-track->TrueY); FIXME
//	hTrackZSmearingShift->Fill(track->Z-track->TrueZ); FIXME


	// calculate amount of tracks/pt that was clustered
	if(track->ClusterIndex >= 0){ //this means it was clustered
	  nClusteredTracks++;
	  clusteredMomentum += track->PT;
	}
	else{
	  nUnclusteredTracks++;
	  unclusteredMomentum += track->PT;
	}

	// calculate and store useful information about the generated and reconstructed primary vertices	
	if (track->IsPU==0){ // it's a track from the GEN PV
//	  genPVX += track->TrueX; FIXME
//	  genPVY += track->TrueY; FIXME
//	  genPVZ += track->TrueZ; FIXME
	  nTracksInGenPV++;
	  momentumInGenPV += track->PT;
	}
	if (track->ClusterIndex==recoPV->Index){ // comes from the RECO primary vertex
	  nTracksInRecoPV++;
	  momentumInRecoPV += track->PT;
	  if (track->IsPU==0){ // also comes from the GEN primary vertex
	    recoPVtrackPurity++;
	    recoPVmomentumPurity += track->PT;
	  }
	}

	// store the positions of each generated interaction
	if (!interactionXPositionMap.count (track->IsPU))
	  {
	    interactionXPositionMap[track->IsPU] = 0.0;
	    interactionXWeightMap[track->IsPU] = 0.0;
	  }
//	interactionXPositionMap[track->IsPU] += track->TrueX; FIXME
	interactionXWeightMap[track->IsPU] += 1.0;
	if (!interactionYPositionMap.count (track->IsPU))
	  {
	    interactionYPositionMap[track->IsPU] = 0.0;
	    interactionYWeightMap[track->IsPU] = 0.0;
	  }
//	interactionYPositionMap[track->IsPU] += track->TrueY; FIXME
	interactionYWeightMap[track->IsPU] += 1.0;
	if (!interactionZPositionMap.count (track->IsPU))
	  {
	    interactionZPositionMap[track->IsPU] = 0.0;
	    interactionZWeightMap[track->IsPU] = 0.0;
	  }
//	interactionZPositionMap[track->IsPU] += track->TrueZ; FIXME
	interactionZWeightMap[track->IsPU] += 1.0;

      } // end loop over all tracks

      for(map<int, double>::const_iterator interaction = interactionXPositionMap.begin (); interaction != interactionXPositionMap.end (); interaction++)
        {
          interactionXPositionMap.at(interaction->first) /= interactionXWeightMap.at(interaction->first);
          interactionYPositionMap.at(interaction->first) /= interactionYWeightMap.at(interaction->first);
          interactionZPositionMap.at(interaction->first) /= interactionZWeightMap.at(interaction->first);
        }

      if(recoPVtrackPurity == 0)
	{
	  hCorrectPrimaryVertex->Fill(nInteractions, 0);
	}
      if(recoPVtrackPurity > 0 && recoPVtrackPurity <=1)
	{
	  hCorrectPrimaryVertex->Fill(nInteractions, 1);
	}

      genPVX /= nTracksInGenPV;
      genPVY /= nTracksInGenPV;
      genPVZ /= nTracksInGenPV;
      recoPVtrackPurity /= nTracksInRecoPV;
      recoPVmomentumPurity /= momentumInRecoPV;

      hRecoPVTrackPurity->Fill(recoPVtrackPurity);
      hRecoPVMomentumPurity->Fill(recoPVmomentumPurity);
      hNumTracksRecoPVVsNumTracksGenPV->Fill(nTracksInGenPV,recoPV->NDF);
      hPtRecoPVVsPtGenPV->Fill(momentumInGenPV,momentumInRecoPV);

      hClusteredTrackFraction->Fill(float(nClusteredTracks)/(nClusteredTracks+nUnclusteredTracks));
      hClusteredMomentumFraction->Fill(clusteredMomentum/(clusteredMomentum+unclusteredMomentum));

      hRecoPVX->Fill(recoPV->X);
      hRecoPVY->Fill(recoPV->Y);
      hRecoPVZ->Fill(recoPV->Z);
      hRecoPVTransversePosition->Fill(recoPV->X,recoPV->Y);

      hGenPVX->Fill(genPVX);
      hGenPVY->Fill(genPVY);
      hGenPVZ->Fill(genPVZ);
      hGenPVTransversePosition->Fill(genPVX,genPVY);

      double pvRadius = sqrt(recoPV->X * recoPV->X + recoPV->Y * recoPV->Y);
      double genPVRadius = sqrt(genPVX * genPVX + genPVY * genPVY);

      hRecoPVRZPosition->Fill(recoPV->Z,pvRadius);
      hGenPVRZPosition->Fill(genPVZ,genPVRadius);

      hPVdisplacementZ->Fill(genPVZ - recoPV->Z);
      hAbsPVdisplacementZ->Fill(fabs(genPVZ - recoPV->Z));
      hZRecoPVVsZGenPV->Fill(genPVZ, recoPV->Z);
      hPVDisplacementVsNumInteractions->Fill(fabs(genPVZ - recoPV->Z), nInteractions);



      //re-loop over all the tracks and fill the special histograms
      for(int iTrack = 0; iTrack < branchTrack->GetEntries(); iTrack++)
        {
          Track *track = (Track *) branchTrack->At(iTrack);
	  if (track->ClusterIndex >=0){//only include clustered tracks
	    
	    hTrackDisplacementClusterX->Fill(fabs(track->X - clusterXPositionMap.at(track->ClusterIndex)));
	    hTrackDisplacementClusterY->Fill(fabs(track->Y - clusterYPositionMap.at(track->ClusterIndex)));
	    hTrackDisplacementClusterZ->Fill(fabs(track->Z - clusterZPositionMap.at(track->ClusterIndex)));
	  }
          hTrackDisplacementInteractionX->Fill(fabs(track->X - interactionXPositionMap.at(track->IsPU)));
          hTrackDisplacementInteractionY->Fill(fabs(track->Y - interactionYPositionMap.at(track->IsPU)));
          hTrackDisplacementInteractionZ->Fill(fabs(track->Z - interactionZPositionMap.at(track->IsPU)));
        }



    } // end loop over events


  // Save resulting histograms
  TFile *fout = TFile::Open(outputFile.c_str(), "recreate");


  fout->cd();
  TDirectory *vbfQuarkFolder = fout->mkdir("VBF Quark Histograms");
  vbfQuarkFolder->cd();

  // VBF Quark Histograms
  hVBFQuarkEta->Write ();
  hVBFQuarkPt->Write ();
  hVBFQuarkEtaVsPhi->Write ();


  fout->cd();
  TDirectory *trackFolder = fout->mkdir("Track Histograms");
  trackFolder->cd();

  // Track Histograms
  hTrackPt->Write();
  hVBFTrackPt->Write();
  hPUTrackPt->Write();
  hTrackX->Write();
  hTrackY->Write();
  hTrackZ->Write();
  hTrackEX->Write();
  hTrackEY->Write();
  hTrackEZ->Write();
  hTrackXSmearingShift->Write();
  hTrackYSmearingShift->Write();
  hTrackZSmearingShift->Write();
  hTrackDisplacementClusterX->Write();
  hTrackDisplacementClusterY->Write();
  hTrackDisplacementClusterZ->Write();
  hTrackDisplacementInteractionX->Write();
  hTrackDisplacementInteractionY->Write();
  hTrackDisplacementInteractionZ->Write();


  fout->cd();
  TDirectory *clusterFolder = fout->mkdir("Cluster Histograms");
  clusterFolder->cd();

  // Cluster Histograms
  hClusterX->Write();
  hClusterEX->Write();
  hClusterY->Write();
  hClusterEY->Write();
  hClusterZ->Write();
  hClusterEZ->Write();
  hNumTracksPerCluster->Write();
  hClusterTransversePosition->Write();
  hClusterRZPosition->Write();


  fout->cd();
  TDirectory *eventFolder = fout->mkdir("Event Histograms");
  eventFolder->cd();

  // Reco PV Histograms
  hRecoPVX->Write();
  hRecoPVY->Write();
  hRecoPVZ->Write();
  hRecoPVTrackPurity->Write();
  hRecoPVMomentumPurity->Write();
    
  // Gen PV Histograms
  hGenPVX->Write();
  hGenPVY->Write();
  hGenPVZ->Write();
  
  // Size Histograms
  hNumTracksPerEvent->Write();
  hNumClustersPerEvent->Write();
  hNumInteractionsPerEvent->Write();

  // 2D Histograms
  hNumClustersVsNumInteractions->Write();
  hRecoPVTransversePosition->Write();
  hGenPVTransversePosition->Write();

  hRecoPVRZPosition->Write();
  hGenPVRZPosition->Write();
  hPVDisplacementVsNumInteractions->Write();

  hCorrectPrimaryVertex->Write();

  // Gen/Reco PV Comparison Histograms
  hNumTracksRecoPVVsNumTracksGenPV->Write();
  hPtRecoPVVsPtGenPV->Write();
  hPVdisplacementZ->Write();
  hAbsPVdisplacementZ->Write();
  hZRecoPVVsZGenPV->Write();

  // Other Histograms
  hClusteredTrackFraction->Write();
  hClusteredMomentumFraction->Write();

  fout->Close();
}
Ejemplo n.º 15
0
void TestEMCALSDigit()
{
  
  // Getting EMCAL Detector and Geometry.
  
  AliRunLoader *rl = AliRunLoader::Open("galice.root",AliConfig::GetDefaultEventFolderName(),"read");
  
  if (rl == 0x0)
    cout<<"Can not instatiate the Run Loader"<<endl;
  
  rl->LoadgAlice();//Needed to get geometry
  
  AliEMCALLoader *emcalLoader = dynamic_cast<AliEMCALLoader*>
    (rl->GetDetectorLoader("EMCAL"));
  
  TGeoManager::Import("geometry.root");
  
  AliRun * alirun   = rl->GetAliRun(); // Needed to get Geometry
  AliEMCALGeometry * geom ;
  if(alirun){
    AliEMCAL * emcal  = (AliEMCAL*)alirun->GetDetector("EMCAL");
    geom = emcal->GetGeometry();
  }
  
  if (geom == 0) cout<<"Did not get geometry from EMCALLoader"<<endl;
  else   geom->PrintGeometry();
  
  //Load Digits
  rl->LoadSDigits("EMCAL");
  
  //Get maximum number of events
  Int_t maxevent =  rl->GetNumberOfEvents();
  cout<<"Number of events "<<maxevent<<endl;
  //maxevent = 10 ;
  
  Int_t iEvent  = -1 ;
  Float_t amp   = -1 ;
  Float_t time  = -1 ;
  Int_t id      = -1 ;
  Int_t iSupMod =  0 ;
  Int_t iTower  =  0 ;
  Int_t iIphi   =  0 ;
  Int_t iIeta   =  0 ;
  Int_t iphi    =  0 ;
  Int_t ieta    =  0 ;
  
  AliEMCALDigit * dig;
  
  for ( iEvent=0; iEvent<maxevent; iEvent++)
    {
      cout <<  " ======> Event " << iEvent << endl ;
      //Load Event
      rl->GetEvent(iEvent);
      
      //Fill array of digits
      TClonesArray *digits = emcalLoader->SDigits();
      
      //Get digits from the list      
      for(Int_t idig = 0; idig< digits->GetEntries();idig++){
	//cout<<">> idig "<<idig<<endl;
	dig = static_cast<AliEMCALDigit *>(digits->At(idig)) ;
	
	if(dig != 0){
	  id   = dig->GetId() ; //cell (digit) label
	  amp  = dig->GetAmplitude(); //amplitude in cell (digit)
	  time = dig->GetTime();//time of creation of digit after collision
	  
	  cout<<"Cell ID "<<id<<" Amp "<<amp<<endl;//" time "<<time<<endl;
	  
	  //Geometry methods  
	  if(geom){
	    geom->GetCellIndex(id,iSupMod,iTower,iIphi,iIeta); 
	    //Gives SuperModule and Tower numbers
	    geom->GetCellPhiEtaIndexInSModule(iSupMod,iTower,
					      iIphi, iIeta,iphi,ieta);
	    //Gives label of cell in eta-phi position per each supermodule
	    cout<< "SModule "<<iSupMod<<"; Tower "<<iTower <<"; Eta "<<iIeta
		<<"; Phi "<<iIphi<<"; Cell Eta "<<ieta<<"; Cell Phi "<<iphi<<endl;
	  }
	}
	else
	  cout<<"Digit pointer 0x0"<<endl;
      }
      
    }


}
void computeAccSelZmmBinned_PileupSys(const TString conf,      // input file
			    const TString inputDir,
                            const TString outputDir,  // output directory
			    const Int_t   doPU,
			    const TString PUtype
) {
  gBenchmark->Start("computeAccSelZmmBinned");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t MASS_LOW   = 60;
  const Double_t MASS_HIGH  = 120;
  const Double_t PT_CUT     = 25;
  const Double_t ETA_CUT    = 2.4;
  const Double_t MUON_MASS  = 0.105658369;

  const Int_t BOSON_ID  = 23;
  const Int_t LEPTON_ID = 13;
  
  // efficiency files
  const TString dataHLTEffName_pos = inputDir + "MuHLTEff/MGpositive/eff.root";
  const TString dataHLTEffName_neg = inputDir + "MuHLTEff/MGnegative/eff.root";
  const TString zmmHLTEffName_pos  = inputDir + "MuHLTEff/CTpositive/eff.root";
  const TString zmmHLTEffName_neg  = inputDir + "MuHLTEff/CTnegative/eff.root";

  const TString dataSelEffName_pos = inputDir + "MuSITEff/MGpositive_FineBin/eff.root";
  const TString dataSelEffName_neg = inputDir + "MuSITEff/MGnegative_FineBin/eff.root";
  const TString zmmSelEffName_pos  = inputDir + "MuSITEff/CTpositive/eff.root";
  const TString zmmSelEffName_neg  = inputDir + "MuSITEff/CTnegative/eff.root";

  const TString dataTrkEffName_pos = inputDir + "MuSITEff/MGpositive_FineBin/eff.root";
  const TString dataTrkEffName_neg = inputDir + "MuSITEff/MGnegative_FineBin/eff.root";
  const TString zmmTrkEffName_pos  = inputDir + "MuSITEff/CTpositive/eff.root";
  const TString zmmTrkEffName_neg  = inputDir + "MuSITEff/CTnegative/eff.root";

  const TString dataStaEffName_pos = inputDir + "MuStaEff/MGpositive/eff.root";
  const TString dataStaEffName_neg = inputDir + "MuStaEff/MGnegative/eff.root";
  const TString zmmStaEffName_pos  = inputDir + "MuStaEff/CTpositive/eff.root";
  const TString zmmStaEffName_neg  = inputDir + "MuStaEff/CTnegative/eff.root";
  
  // load pileup reweighting file
  TFile *f_rw = TFile::Open("../Tools/puWeights_76x.root", "read");
  TH1D *h_rw = (TH1D*) f_rw->Get(PUtype.Data());
 
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString> fnamev;  // file name per input file
  vector<TString> labelv;  // TLegend label per input file
  vector<Int_t>   colorv;  // plot color per input file
  vector<Int_t>   linev;   // plot line style per input file

  //
  // parse .conf file
  //
  ifstream ifs;
  ifs.open(conf.Data());
  assert(ifs.is_open());
  string line;
  while(getline(ifs,line)) {
    if(line[0]=='#') continue;
    
    string fname;
    Int_t color, linesty;
    stringstream ss(line);
    ss >> fname >> color >> linesty;
    string label = line.substr(line.find('@')+1);
    fnamev.push_back(fname);
    labelv.push_back(label);
    colorv.push_back(color);
    linev.push_back(linesty);
  }
  ifs.close();

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);  

  TH2D *h=0;

  //
  // HLT efficiency
  //
  cout << "Loading trigger efficiencies..." << endl;
  
  TFile *dataHLTEffFile_pos = new TFile(dataHLTEffName_pos);
  CEffUser2D dataHLTEff_pos;
  dataHLTEff_pos.loadEff((TH2D*)dataHLTEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataHLTEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataHLTEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataHLTEffFile_neg = new TFile(dataHLTEffName_neg);
  CEffUser2D dataHLTEff_neg;
  dataHLTEff_neg.loadEff((TH2D*)dataHLTEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataHLTEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataHLTEffFile_neg->Get("hErrhEtaPt"));
    
  TFile *zmmHLTEffFile_pos = new TFile(zmmHLTEffName_pos);
  CEffUser2D zmmHLTEff_pos;
  zmmHLTEff_pos.loadEff((TH2D*)zmmHLTEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmHLTEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmHLTEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *zmmHLTEffFile_neg = new TFile(zmmHLTEffName_neg);
  CEffUser2D zmmHLTEff_neg;
  zmmHLTEff_neg.loadEff((TH2D*)zmmHLTEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmHLTEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmHLTEffFile_neg->Get("hErrhEtaPt"));

  h =(TH2D*)dataHLTEffFile_pos->Get("hEffEtaPt");
  TH2D *hHLTErr_pos = new TH2D("hHLTErr_pos", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  TH2D *hHLTErr_neg = new TH2D("hHLTErr_neg", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  
  //
  // Selection efficiency
  //
  cout << "Loading selection efficiencies..." << endl;
  
  TFile *dataSelEffFile_pos = new TFile(dataSelEffName_pos);
  CEffUser2D dataSelEff_pos;
  dataSelEff_pos.loadEff((TH2D*)dataSelEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataSelEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataSelEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataSelEffFile_neg = new TFile(dataSelEffName_neg);
  CEffUser2D dataSelEff_neg;
  dataSelEff_neg.loadEff((TH2D*)dataSelEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataSelEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataSelEffFile_neg->Get("hErrhEtaPt"));
  
  TFile *zmmSelEffFile_pos = new TFile(zmmSelEffName_pos);
  CEffUser2D zmmSelEff_pos;
  zmmSelEff_pos.loadEff((TH2D*)zmmSelEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmSelEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmSelEffFile_pos->Get("hErrhEtaPt"));

  TFile *zmmSelEffFile_neg = new TFile(zmmSelEffName_neg);
  CEffUser2D zmmSelEff_neg;
  zmmSelEff_neg.loadEff((TH2D*)zmmSelEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmSelEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmSelEffFile_neg->Get("hErrhEtaPt"));

  h =(TH2D*)dataSelEffFile_pos->Get("hEffEtaPt");
  TH2D *hSelErr_pos = new TH2D("hSelErr_pos", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  TH2D *hSelErr_neg = new TH2D("hSelErr_neg", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());

  //
  // Standalone efficiency
  //
  cout << "Loading standalone efficiencies..." << endl;
  
  TFile *dataStaEffFile_pos = new TFile(dataStaEffName_pos);
  CEffUser2D dataStaEff_pos;
  dataStaEff_pos.loadEff((TH2D*)dataStaEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataStaEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataStaEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataStaEffFile_neg = new TFile(dataStaEffName_neg);
  CEffUser2D dataStaEff_neg;
  dataStaEff_neg.loadEff((TH2D*)dataStaEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataStaEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataStaEffFile_neg->Get("hErrhEtaPt"));
  
  TFile *zmmStaEffFile_pos = new TFile(zmmStaEffName_pos);
  CEffUser2D zmmStaEff_pos;
  zmmStaEff_pos.loadEff((TH2D*)zmmStaEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmStaEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmStaEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *zmmStaEffFile_neg = new TFile(zmmStaEffName_neg);
  CEffUser2D zmmStaEff_neg;
  zmmStaEff_neg.loadEff((TH2D*)zmmStaEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmStaEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmStaEffFile_neg->Get("hErrhEtaPt"));

  h =(TH2D*)dataStaEffFile_pos->Get("hEffEtaPt");
  TH2D *hStaErr_pos = new TH2D("hStaErr_pos", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  TH2D *hStaErr_neg = new TH2D("hStaErr_neg", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());

  //
  // Tracker efficiency
  //
  cout << "Loading track efficiencies..." << endl;
  
  TFile *dataTrkEffFile_pos = new TFile(dataTrkEffName_pos);
  CEffUser2D dataTrkEff_pos;
  dataTrkEff_pos.loadEff((TH2D*)dataTrkEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataTrkEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataTrkEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataTrkEffFile_neg = new TFile(dataTrkEffName_neg);
  CEffUser2D dataTrkEff_neg;
  dataTrkEff_neg.loadEff((TH2D*)dataTrkEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataTrkEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataTrkEffFile_neg->Get("hErrhEtaPt"));
  
  TFile *zmmTrkEffFile_pos = new TFile(zmmTrkEffName_pos);
  CEffUser2D zmmTrkEff_pos;
  zmmTrkEff_pos.loadEff((TH2D*)zmmTrkEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmTrkEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmTrkEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *zmmTrkEffFile_neg = new TFile(zmmTrkEffName_neg);
  CEffUser2D zmmTrkEff_neg;
  zmmTrkEff_neg.loadEff((TH2D*)zmmTrkEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmTrkEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmTrkEffFile_neg->Get("hErrhEtaPt"));

  h =(TH2D*)dataTrkEffFile_pos->Get("hEffEtaPt");
  TH2D *hTrkErr_pos = new TH2D("hTrkErr_pos", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());
  TH2D *hTrkErr_neg = new TH2D("hTrkErr_neg", "",h->GetNbinsX(),h->GetXaxis()->GetXmin(),h->GetXaxis()->GetXmax(),
			       h->GetNbinsY(),h->GetYaxis()->GetXmin(),h->GetYaxis()->GetXmax());

  // Data structures to store info from TTrees
  baconhep::TEventInfo *info   = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr     = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *muonArr        = new TClonesArray("baconhep::TMuon");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;
   
  // Variables to store acceptances and uncertainties (per input file)
  vector<Double_t> nEvtsv, nSelv;
  vector<Double_t> nSelCorrv, nSelCorrVarv;
  vector<Double_t> accv, accCorrv;
  vector<Double_t> accErrv, accErrCorrv;

  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");
  
  //
  // loop through files
  //
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {  

    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << " ..." << endl;
    infile = TFile::Open(fnamev[ifile]); 
    assert(infile);
  
    eventTree = (TTree*)infile->Get("Events"); assert(eventTree);  
    eventTree->SetBranchAddress("Info",             &info); TBranch *infoBr = eventTree->GetBranch("Info");
    eventTree->SetBranchAddress("GenEvtInfo",        &gen); TBranch *genBr  = eventTree->GetBranch("GenEvtInfo");
    eventTree->SetBranchAddress("GenParticle",&genPartArr); TBranch* genPartBr = eventTree->GetBranch("GenParticle");
    eventTree->SetBranchAddress("Muon",          &muonArr); TBranch *muonBr = eventTree->GetBranch("Muon");   
    eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");

    nEvtsv.push_back(0);
    nSelv.push_back(0);
    nSelCorrv.push_back(0);
    nSelCorrVarv.push_back(0);

    //
    // loop over events
    //      
    for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
      genBr->GetEntry(ientry);
      genPartArr->Clear(); genPartBr->GetEntry(ientry);
      infoBr->GetEntry(ientry);

      Int_t glepq1=-99;
      Int_t glepq2=-99;

      if (fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
      TLorentzVector *vec=new TLorentzVector(0,0,0,0);
      TLorentzVector *lep1=new TLorentzVector(0,0,0,0);
      TLorentzVector *lep2=new TLorentzVector(0,0,0,0);
      toolbox::fillGen(genPartArr, BOSON_ID, vec, lep1, lep2,&glepq1,&glepq2,1);
      if(vec->M()<MASS_LOW || vec->M()>MASS_HIGH) continue;
      delete vec; delete lep1; delete lep2;

      vertexArr->Clear();
      vertexBr->GetEntry(ientry);
      double npv  = vertexArr->GetEntries();
      Double_t weight=gen->weight;
      if(doPU>0) weight*=h_rw->GetBinContent(h_rw->FindBin(info->nPUmean));

      nEvtsv[ifile]+=weight;
      
      // trigger requirement               
      if (!isMuonTrigger(triggerMenu, info->triggerBits)) continue;

      // good vertex requirement
      if(!(info->hasGoodPV)) continue;
    
      muonArr->Clear();
      muonBr->GetEntry(ientry);

      for(Int_t i1=0; i1<muonArr->GetEntriesFast(); i1++) {
  	const baconhep::TMuon *mu1 = (baconhep::TMuon*)((*muonArr)[i1]);

        if(mu1->pt	  < PT_CUT)  continue;  // lepton pT cut
        if(fabs(mu1->eta) > ETA_CUT) continue;  // lepton |eta| cut
        if(!passMuonID(mu1))	     continue;  // lepton selection
	
	TLorentzVector vMu1(0,0,0,0);
	vMu1.SetPtEtaPhiM(mu1->pt, mu1->eta, mu1->phi, MUON_MASS);

        for(Int_t i2=i1+1; i2<muonArr->GetEntriesFast(); i2++) {
          const baconhep::TMuon *mu2 = (baconhep::TMuon*)((*muonArr)[i2]);
        
          if(mu1->q == mu2->q)	       continue;  // opposite charge requirement
          if(mu2->pt        < PT_CUT)  continue;  // lepton pT cut
          if(fabs(mu2->eta) > ETA_CUT) continue;  // lepton |eta| cut
	  if(!passMuonID(mu2))	       continue;  // lepton selection

          TLorentzVector vMu2(0,0,0,0);
	  vMu2.SetPtEtaPhiM(mu2->pt, mu2->eta, mu2->phi, MUON_MASS);  

          // trigger match
	  if(!isMuonTriggerObj(triggerMenu, mu1->hltMatchBits, kFALSE) && !isMuonTriggerObj(triggerMenu, mu2->hltMatchBits, kFALSE)) continue;
	  
	  // mass window
          TLorentzVector vDilep = vMu1 + vMu2;
          if((vDilep.M()<MASS_LOW) || (vDilep.M()>MASS_HIGH)) continue;
          
          /******** We have a Z candidate! HURRAY! ********/
          Double_t effdata, effmc;
	  Double_t corr=1;
	  
	  effdata=1; effmc=1;    
          if(mu1->q>0) { 
            effdata *= (1.-dataHLTEff_pos.getEff(mu1->eta, mu1->pt)); 
            effmc   *= (1.-zmmHLTEff_pos.getEff(mu1->eta, mu1->pt)); 
          } else {
            effdata *= (1.-dataHLTEff_neg.getEff(mu1->eta, mu1->pt)); 
            effmc   *= (1.-zmmHLTEff_neg.getEff(mu1->eta, mu1->pt)); 
          }
          if(mu2->q>0) {
            effdata *= (1.-dataHLTEff_pos.getEff(mu2->eta, mu2->pt)); 
            effmc   *= (1.-zmmHLTEff_pos.getEff(mu2->eta, mu2->pt));
          } else {
            effdata *= (1.-dataHLTEff_neg.getEff(mu2->eta, mu2->pt)); 
            effmc   *= (1.-zmmHLTEff_neg.getEff(mu2->eta, mu2->pt));
          }
          effdata = 1.-effdata;
          effmc   = 1.-effmc;
          corr *= effdata/effmc;
    
          effdata=1; effmc=1;
          if(mu1->q>0) { 
            effdata *= dataSelEff_pos.getEff(mu1->eta, mu1->pt); 
            effmc   *= zmmSelEff_pos.getEff(mu1->eta, mu1->pt); 
          } else {
            effdata *= dataSelEff_neg.getEff(mu1->eta, mu1->pt); 
            effmc   *= zmmSelEff_neg.getEff(mu1->eta, mu1->pt); 
          }
          if(mu2->q>0) {
            effdata *= dataSelEff_pos.getEff(mu2->eta, mu2->pt); 
            effmc   *= zmmSelEff_pos.getEff(mu2->eta, mu2->pt);
          } else {
            effdata *= dataSelEff_neg.getEff(mu2->eta, mu2->pt); 
            effmc   *= zmmSelEff_neg.getEff(mu2->eta, mu2->pt);
          }
          corr *= effdata/effmc;
    
          effdata=1; effmc=1;
          if(mu1->q>0) { 
            effdata *= dataStaEff_pos.getEff(mu1->eta, mu1->pt); 
            effmc   *= zmmStaEff_pos.getEff(mu1->eta, mu1->pt); 
          } else {
            effdata *= dataStaEff_neg.getEff(mu1->eta, mu1->pt); 
            effmc   *= zmmStaEff_neg.getEff(mu1->eta, mu1->pt); 
          }
          if(mu2->q>0) {
            effdata *= dataStaEff_pos.getEff(mu2->eta, mu2->pt); 
            effmc   *= zmmStaEff_pos.getEff(mu2->eta, mu2->pt);
          } else {
            effdata *= dataStaEff_neg.getEff(mu2->eta, mu2->pt); 
            effmc   *= zmmStaEff_neg.getEff(mu2->eta, mu2->pt);
          }
          corr *= effdata/effmc;
    
          effdata=1; effmc=1;
          if(mu1->q>0) { 
            effdata *= dataTrkEff_pos.getEff(mu1->eta, mu1->pt); 
            effmc   *= zmmTrkEff_pos.getEff(mu1->eta, mu1->pt); 
          } else {
            effdata *= dataTrkEff_neg.getEff(mu1->eta, mu1->pt); 
            effmc   *= zmmTrkEff_neg.getEff(mu1->eta, mu1->pt); 
          }
          if(mu2->q>0) {
            effdata *= dataTrkEff_pos.getEff(mu2->eta, mu2->pt); 
            effmc   *= zmmTrkEff_pos.getEff(mu2->eta, mu2->pt);
          } else {
            effdata *= dataTrkEff_neg.getEff(mu2->eta, mu2->pt); 
            effmc   *= zmmTrkEff_neg.getEff(mu2->eta, mu2->pt);
          }
          //corr *= effdata/effmc;
	  
	  // scale factor uncertainties                                                                                                                                         
	  // TRACKER
          if(mu1->q>0) {
            Double_t effdata = dataTrkEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataTrkEff_pos.getErrLow(mu1->eta, mu1->pt), dataTrkEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmTrkEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmTrkEff_pos.getErrLow(mu1->eta, mu1->pt), zmmTrkEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t errTrk = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hTrkErr_pos->Fill(mu1->eta, mu1->pt, errTrk);
          } else {
            Double_t effdata = dataTrkEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataTrkEff_neg.getErrLow(mu1->eta, mu1->pt), dataTrkEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmTrkEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmTrkEff_neg.getErrLow(mu1->eta, mu1->pt), zmmTrkEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t errTrk = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hTrkErr_neg->Fill(mu1->eta, mu1->pt, errTrk);
          }

          if(mu2->q>0) {
            Double_t effdata = dataTrkEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataTrkEff_pos.getErrLow(mu2->eta, mu2->pt), dataTrkEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmTrkEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmTrkEff_pos.getErrLow(mu2->eta, mu2->pt), zmmTrkEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t errTrk = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
	    /*   if(mu2->eta>1.2 && mu2->eta<2.1) 
	      {
		errTrk=0.0013;
		}*/
            hTrkErr_pos->Fill(mu2->eta, mu2->pt, errTrk);
          } else {
            Double_t effdata = dataTrkEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataTrkEff_neg.getErrLow(mu2->eta, mu2->pt), dataTrkEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmTrkEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmTrkEff_neg.getErrLow(mu2->eta, mu2->pt), zmmTrkEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t errTrk = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
	    /*  if(mu2->eta>1.2 && mu2->eta<2.1) 
	      {
		errTrk=0.0013;
	      }
	      hTrkErr_neg->Fill(mu2->eta, mu2->pt, errTrk);*/
          }
	  // STANDALONE
          if(mu1->q>0) {
            Double_t effdata = dataStaEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataStaEff_pos.getErrLow(mu1->eta, mu1->pt), dataStaEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmStaEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmStaEff_pos.getErrLow(mu1->eta, mu1->pt), zmmStaEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t errSta = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hStaErr_pos->Fill(mu1->eta, mu1->pt, errSta);
          } else {
            Double_t effdata = dataStaEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataStaEff_neg.getErrLow(mu1->eta, mu1->pt), dataStaEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmStaEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmStaEff_neg.getErrLow(mu1->eta, mu1->pt), zmmStaEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t errSta = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hStaErr_neg->Fill(mu1->eta, mu1->pt, errSta);
          }

          if(mu2->q>0) {
            Double_t effdata = dataStaEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataStaEff_pos.getErrLow(mu2->eta, mu2->pt), dataStaEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmStaEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmStaEff_pos.getErrLow(mu2->eta, mu2->pt), zmmStaEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t errSta = ((effdata/effmc))*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hStaErr_pos->Fill(mu2->eta, mu2->pt, errSta);
          } else {
            Double_t effdata = dataStaEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataStaEff_neg.getErrLow(mu2->eta, mu2->pt), dataStaEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmStaEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmStaEff_neg.getErrLow(mu2->eta, mu2->pt), zmmStaEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t errSta = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hStaErr_neg->Fill(mu2->eta, mu2->pt, errSta);
	  }

	  // SELECTION
          if(mu1->q>0) {
            Double_t effdata = dataSelEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataSelEff_pos.getErrLow(mu1->eta, mu1->pt), dataSelEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmSelEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmSelEff_pos.getErrLow(mu1->eta, mu1->pt), zmmSelEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t errSel = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hSelErr_pos->Fill(mu1->eta, mu1->pt, errSel);
          } else {
            Double_t effdata = dataSelEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataSelEff_neg.getErrLow(mu1->eta, mu1->pt), dataSelEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmSelEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmSelEff_neg.getErrLow(mu1->eta, mu1->pt), zmmSelEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t errSel = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hSelErr_neg->Fill(mu1->eta, mu1->pt, errSel);
          }

          if(mu2->q>0) {
            Double_t effdata = dataSelEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataSelEff_pos.getErrLow(mu2->eta, mu2->pt), dataSelEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmSelEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmSelEff_pos.getErrLow(mu2->eta, mu2->pt), zmmSelEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t errSel = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hSelErr_pos->Fill(mu2->eta, mu2->pt, errSel);
          } else {
            Double_t effdata = dataSelEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataSelEff_neg.getErrLow(mu2->eta, mu2->pt), dataSelEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmSelEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmSelEff_neg.getErrLow(mu2->eta, mu2->pt), zmmSelEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t errSel = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hSelErr_neg->Fill(mu2->eta, mu2->pt, errSel);
	  }

	  //HLT
          if(mu1->q>0) {
            Double_t effdata = dataHLTEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataHLTEff_pos.getErrLow(mu1->eta, mu1->pt), dataHLTEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmHLTEff_pos.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmHLTEff_pos.getErrLow(mu1->eta, mu1->pt), zmmHLTEff_pos.getErrHigh(mu1->eta, mu1->pt));
            Double_t errHLT = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hHLTErr_pos->Fill(mu1->eta, mu1->pt, errHLT);
          } else {
            Double_t effdata = dataHLTEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errdata = TMath::Max(dataHLTEff_neg.getErrLow(mu1->eta, mu1->pt), dataHLTEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t effmc   = zmmHLTEff_neg.getEff(mu1->eta, mu1->pt);
            Double_t errmc   = TMath::Max(zmmHLTEff_neg.getErrLow(mu1->eta, mu1->pt), zmmHLTEff_neg.getErrHigh(mu1->eta, mu1->pt));
            Double_t errHLT = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hHLTErr_neg->Fill(mu1->eta, mu1->pt, errHLT);
          }

          if(mu2->q>0) {
            Double_t effdata = dataHLTEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataHLTEff_pos.getErrLow(mu2->eta, mu2->pt), dataHLTEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmHLTEff_pos.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmHLTEff_pos.getErrLow(mu2->eta, mu2->pt), zmmHLTEff_pos.getErrHigh(mu2->eta, mu2->pt));
            Double_t errHLT = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hHLTErr_pos->Fill(mu2->eta, mu2->pt, errHLT);
          } else {
            Double_t effdata = dataHLTEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errdata = TMath::Max(dataHLTEff_neg.getErrLow(mu2->eta, mu2->pt), dataHLTEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t effmc   = zmmHLTEff_neg.getEff(mu2->eta, mu2->pt);
            Double_t errmc   = TMath::Max(zmmHLTEff_neg.getErrLow(mu2->eta, mu2->pt), zmmHLTEff_neg.getErrHigh(mu2->eta, mu2->pt));
            Double_t errHLT = (effdata/effmc)*sqrt(errdata*errdata/effdata/effdata + errmc*errmc/effmc/effmc);
            hHLTErr_neg->Fill(mu2->eta, mu2->pt, errHLT);
          }
	  
	  nSelv[ifile]    +=weight;
	  nSelCorrv[ifile]+=weight*corr;
	  nSelCorrVarv[ifile]+=weight*weight*corr*corr;
        }
      }      
    }

    Double_t var=0;
    for(Int_t iy=0; iy<=hHLTErr_pos->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr_pos->GetNbinsX(); ix++) {
        Double_t err=hHLTErr_pos->GetBinContent(ix,iy);
        var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hHLTErr_neg->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hHLTErr_neg->GetNbinsX(); ix++) {
        Double_t err=hHLTErr_neg->GetBinContent(ix,iy);
        var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hSelErr_pos->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hSelErr_pos->GetNbinsX(); ix++) {
        Double_t err=hSelErr_pos->GetBinContent(ix,iy);
        var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hSelErr_neg->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hSelErr_neg->GetNbinsX(); ix++) {
        Double_t err=hSelErr_neg->GetBinContent(ix,iy);
        var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hTrkErr_pos->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hTrkErr_pos->GetNbinsX(); ix++) {
        Double_t err=hTrkErr_pos->GetBinContent(ix,iy);
        //var+=err*err;
	var+=0.0;
      }
    }
    for(Int_t iy=0; iy<=hTrkErr_neg->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hTrkErr_neg->GetNbinsX(); ix++) {
        Double_t err=hTrkErr_neg->GetBinContent(ix,iy);
	var+=0.0;
        //var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hStaErr_pos->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hStaErr_pos->GetNbinsX(); ix++) {
        Double_t err=hStaErr_pos->GetBinContent(ix,iy);
	var+=err*err;
      }
    }
    for(Int_t iy=0; iy<=hStaErr_neg->GetNbinsY(); iy++) {
      for(Int_t ix=0; ix<=hStaErr_neg->GetNbinsX(); ix++) {
        Double_t err=hStaErr_neg->GetBinContent(ix,iy);
	var+=err*err;
      }
    }

    nSelCorrVarv[ifile]+=var;

    // compute acceptances
    accv.push_back(nSelv[ifile]/nEvtsv[ifile]);     accErrv.push_back(accv[ifile]*sqrt((1.+accv[ifile])/nEvtsv[ifile]));
    accCorrv.push_back(nSelCorrv[ifile]/nEvtsv[ifile]); accErrCorrv.push_back(accCorrv[ifile]*sqrt((nSelCorrVarv[ifile])/(nSelCorrv[ifile]*nSelCorrv[ifile]) + 1./nEvtsv[ifile]));
    
    delete infile;
    infile=0, eventTree=0;  
  }  
  delete info;
  delete gen;
  delete muonArr;

    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================    
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " Z -> mu mu" << endl;
  cout << "  Mass window: [" << MASS_LOW << ", " << MASS_HIGH << "]" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    cout << "   ================================================" << endl;
    cout << "    Label: " << labelv[ifile] << endl;
    cout << "     File: " << fnamev[ifile] << endl;
    cout << endl;
    cout << "    *** Acceptance ***" << endl;
    cout << "          nominal: " << setw(12) << nSelv[ifile]   << " / " << nEvtsv[ifile] << " = " << accv[ifile]   << " +/- " << accErrv[ifile] << endl;
    cout << "     SF corrected: " << accCorrv[ifile] << " +/- " << accErrCorrv[ifile] << endl;
    cout << endl;
  }
  
  char txtfname[100];
  sprintf(txtfname,"%s/binned.txt",outputDir.Data());
  ofstream txtfile;
  txtfile.open(txtfname);
  txtfile << "*" << endl;
  txtfile << "* SUMMARY" << endl;
  txtfile << "*--------------------------------------------------" << endl;
  txtfile << " Z -> mu mu" << endl;
  txtfile << "  Mass window: [" << MASS_LOW << ", " << MASS_HIGH << "]" << endl;
  txtfile << "  pT > " << PT_CUT << endl;
  txtfile << "  |eta| < " << ETA_CUT << endl;
  txtfile << endl;
  
  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
    txtfile << "   ================================================" << endl;
    txtfile << "    Label: " << labelv[ifile] << endl;
    txtfile << "     File: " << fnamev[ifile] << endl;
    txtfile << endl;
    txtfile << "    *** Acceptance ***" << endl;
    txtfile << "          nominal: " << setw(12) << nSelv[ifile]   << " / " << nEvtsv[ifile] << " = " << accv[ifile]   << " +/- " << accErrv[ifile] << endl;
    txtfile << "     SF corrected: " << accCorrv[ifile] << " +/- " << accErrCorrv[ifile] << endl;
    txtfile << endl;
  }
  txtfile.close();
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("computeAccSelZmmBinned"); 
}
Ejemplo n.º 17
0
//  -------------------------------------------------------------------------
//
//   ----- General Macro for R3B CALIFA Data Display
//         Author: Hector Alvarez <*****@*****.**>
//         Last Update: 26/09/14
//         Comments:
//         THAT IS A TEMPLATE FOR OTHER DISPLAY/ANALYSIS MACRO. COPY AND USE.
//         CAN DISPLAY RAWHITs OR CRYSTALHITs 
//	
//  -------------------------------------------------------------------------
//
//   Usage: 
//      > root -l 
//      ROOT> .L plot.C
//      ROOT> plot("inputFile")
//     
//     where inputFile is the input file :) 
//     Define histograms and fill them in the loop!
//  -------------------------------------------------------------------------
void plot(TString inputFile="") {

  gROOT->SetStyle("Default");
  //gStyle->SetOptTitle(0);
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  
  TFile *file1 = TFile::Open(inputFile);
  
  //HISTOGRAMS DEFINITION
  TH1F* hEnergy = new TH1F("hEnergy","Energy",1000,0,2000);
  TH2F* hEnergyvsID = new TH2F("hEnergyvsID","EnergyvsID",500,0,2500,128,0,127);
  TH2F* hTimevsID = new TH2F("hTimevsID","TimevsID",500,1450000000000,1460000000000,128,0,127);
  TH2F* hEnergyvsTime = new TH2F("hEnergyvsTime","EnergyvsTime",500,0,2500,500,1450000000000,1650000000000);



  TTree* caloTree = (TTree*)file1->Get("cbmsim");
 
  //Raw Hits (input)
  TClonesArray* rawHitCA;  
  R3BCaloRawHit** rawHit;
  rawHitCA = new TClonesArray("R3BCaloRawHit",5);
  TBranch *branchRawHit = caloTree->GetBranch("CaloRawHit");
  if(branchRawHit) branchRawHit->SetAddress(&rawHitCA);
  
  //Crystal Hits
  TClonesArray* crystalHitCA;  
  R3BCaloCrystalHit** crystalHit;
  crystalHitCA = new TClonesArray("R3BCaloCrystalHit",5);
  TBranch *branchCrystalHit = caloTree->GetBranch("CaloCrystalHit");
  if(branchCrystalHit) branchCrystalHit->SetAddress(&crystalHitCA);
  
  Long64_t nevents = caloTree->GetEntries();
  Int_t rawHitsPerEvent =0;
  Int_t crystalHitsPerEvent =0;
  
  for(Int_t i=0;i<nevents;i++){
    if(i%100000 == 0) printf("Event:%i\n",i);
    
    rawHitCA->Clear();
    crystalHitCA->Clear();

    caloTree->GetEvent(i);
    rawHitsPerEvent = rawHitCA->GetEntries(); 
    crystalHitsPerEvent = crystalHitCA->GetEntries(); 
    
    if(rawHitsPerEvent>0) {
      rawHit = new R3BCaloRawHit*[rawHitsPerEvent];
      for(Int_t j=0;j<rawHitsPerEvent;j++){
	//rawHit[j] = new R3BCaloRawHit;
	rawHit[j] = (R3BCaloRawHit*) rawHitCA->At(j);      
      }
    }
    if(crystalHitsPerEvent>0) {
      crystalHit = new R3BCaloCrystalHit*[crystalHitsPerEvent];
      for(Int_t j=0;j<crystalHitsPerEvent;j++){
	//crystalHit[j] = new R3BCaloCrystalHit;
	crystalHit[j] = (R3BCaloCrystalHit*) crystalHitCA->At(j);      
      }
    }
    
    //filling info
    if(rawHitsPerEvent>0) {
      for(Int_t h=0;h<rawHitsPerEvent;h++){
	hEnergy->Fill(rawHit[h]->GetEnergy());
	hEnergyvsID->Fill(rawHit[h]->GetEnergy(),rawHit[h]->GetCrystalId());
	hTimevsID->Fill(rawHit[h]->GetTime(),rawHit[h]->GetCrystalId());
	hEnergyvsTime->Fill(rawHit[h]->GetEnergy(),rawHit[h]->GetTime());
      }
    }    
    if(crystalHitsPerEvent>0) {
      for(Int_t h=0;h<crystalHitsPerEvent;h++){
	hEnergy->Fill(crystalHit[h]->GetEnergy());
      }
    }  

    
    if(rawHitsPerEvent) delete [] rawHit;
    if(crystalHitsPerEvent) delete [] crystalHit;
    
  }
  
  TCanvas* c1 = new TCanvas("Info","Info",0,0,780,1200);
	c1->SetFillColor(0);
	c1->SetFrameFillColor(0);
	c1->Divide(2,2);
	//MC TRACK CANVAS
	c1->cd(1);
	hEnergy->Draw();
	c1->cd(2);
	hEnergyvsID->Draw("COLZ");
	c1->cd(3);
	hEnergyvsTime->Draw("COLZ");
	c1->cd(4);
	hTimevsID->Draw("COLZ");
}
Ejemplo n.º 18
0
void compare(TString filenameA, TString filenameB)
{
    TFile *fileA = TFile::Open(filenameA);
    TTree *tree = (TTree *)fileA->Get("cbmsim");
    tree->AddFriend("cbmsimB = cbmsim", filenameB);

    TClonesArray *digisA = new TClonesArray("R3BLandDigi");
    tree->GetBranch("LandDigi")->SetAutoDelete(kFALSE);
    tree->SetBranchAddress("LandDigi", &digisA);

    TClonesArray *digisB = new TClonesArray("R3BLandDigi");
    tree->GetBranch("cbmsimB.LandDigi")->SetAutoDelete(kFALSE);
    tree->SetBranchAddress("cbmsimB.LandDigi", &digisB);



    TH1D *hNumLandDigis = new TH1D("hNumLandDigis", "N(LandDigis, A) - N(LandDigis, B)", 51, -25., 25.);
    TH1D *hEtot  = new TH1D("hEtot", "E(tot, A) - E(tot, B)", 201, -100., 100.);
    TH1D *hEtotA = new TH1D("hEtotA", "E(tot, A)", 2000, 1., 2001.);
    TH1D *hEtotB = new TH1D("hEtotB", "E(tot, B)", 2000, 1., 2001.);
    TH1D *hTmin  = new TH1D("hTmin", "T(min, A) - T(min, B)", 201, -10., 10.);

    UInt_t nentries = tree->GetEntries();
    for (UInt_t ev = 0; ev < nentries; ev++) {
        digisA->Clear();
        digisB->Clear();

        tree->GetEntry(ev);


        int nA = digisA->GetEntries();
        int nB = digisB->GetEntries();
        hNumLandDigis->Fill(nA - nB);


        R3BLandDigi *digi;
        double EtotA = 0.;
        for (int i = 0; i < nA; i++) {
            digi = (R3BLandDigi *)digisA->At(i);
            EtotA += digi->GetQdc();
        }
        hEtotA->Fill(EtotA);
        double EtotB = 0.;
        for (int i = 0; i < nB; i++) {
            digi = (R3BLandDigi *)digisB->At(i);
            EtotB += digi->GetQdc();
        }
        hEtotB->Fill(EtotB);
        hEtot->Fill(EtotA - EtotB);


        double TminA = 1000;
        for (int i = 0; i < nA; i++) {
            digi = (R3BLandDigi *)digisA->At(i);
            if (digi->GetTdc() < TminA) {
                TminA = digi->GetTdc();
            }
        }
        double TminB = 1000;
        for (int i = 0; i < nB; i++) {
            digi = (R3BLandDigi *)digisB->At(i);
            if (digi->GetTdc() < TminB) {
                TminB = digi->GetTdc();
            }
        }
        hTmin->Fill(TminA - TminB);
    }


    TCanvas *c1 = new TCanvas("c1", "", 900, 700);
    c1->Divide(2, 2);
    c1->cd(1);
    hNumLandDigis->Draw();
    c1->cd(2);
    hEtot->Draw();
    c1->cd(3);
    hTmin->Draw();
    c1->cd(4);
    hEtotA->Draw();
    hEtotB->SetLineColor(kRed);
    hEtotB->Draw("same");

}
Ejemplo n.º 19
0
void selectZmmGen(const TString conf="zmmgen.conf", // input file
                  const TString outputDir="."   // output directory
	          ) {
  gBenchmark->Start("selectZmmGen");

//--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t MASS_LOW  = 40;
  const Double_t MASS_HIGH = 200;
  const Double_t PT_CUT    = 22;
  const Double_t ETA_CUT   = 2.4;
  const Double_t MUON_MASS = 0.105658369;

  const Int_t BOSON_ID  = 23;
  const Int_t LEPTON_ID = 13;

  // load trigger menu                                                                                                  
  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");

  // load pileup reweighting file  

  TFile *f_rw = TFile::Open("../Tools/pileup_rw_baconDY.root", "read"); 
  
  // for systematics we need 3
  TH1D *h_rw = (TH1D*) f_rw->Get("h_rw_golden");
  TH1D *h_rw_up = (TH1D*) f_rw->Get("h_rw_up_golden");
  TH1D *h_rw_down = (TH1D*) f_rw->Get("h_rw_down_golden"); 

  if (h_rw==NULL) cout<<"WARNIG h_rw == NULL"<<endl;
  if (h_rw_up==NULL) cout<<"WARNIG h_rw == NULL"<<endl;
  if (h_rw_down==NULL) cout<<"WARNIG h_rw == NULL"<<endl;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString>  snamev;      // sample name (for output files)  
  vector<CSample*> samplev;     // data/MC samples

  //
  // parse .conf file
  //
  confParse(conf, snamev, samplev);
 
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  const TString ntupDir = outputDir + TString("/ntuples");
  gSystem->mkdir(ntupDir,kTRUE);

  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  matchGen;
  UInt_t  npv, npu;
  UInt_t  triggerDec;
  UInt_t  goodPV;
  UInt_t  matchTrigger;
  UInt_t  ngenlep;
  TLorentzVector *genlep1=0, *genlep2=0;
  Int_t   genq1, genq2;
  UInt_t nlep;
  TLorentzVector *lep1=0, *lep2=0;
  Int_t   q1, q2;
  Float_t scale1fbGen,scale1fb,scale1fbUp,scale1fbDown;

  std::vector<float> *lheweight = new std::vector<float>();

 // Data structures to store info from TTrees
  baconhep::TEventInfo *info   = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *muonArr    = new TClonesArray("baconhep::TMuon");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;

  //
  // loop over samples
  //  
  for(UInt_t isam=0; isam<samplev.size(); isam++) {
    
    // Assume signal sample is given name "zmm" - flag to store GEN Z kinematics
    Bool_t isSignal = snamev[isam].Contains("zmm",TString::kIgnoreCase);
    
    // flag to reject Z->mm events when selecting at wrong-flavor background events
    Bool_t isWrongFlavor = (snamev[isam].CompareTo("zxx",TString::kIgnoreCase)==0);
    
    CSample* samp = samplev[isam];

    //
    // Set up output ntuple
    //
    TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.raw.root");

    TFile *outFile = new TFile(outfilename,"RECREATE"); 
    TTree *outTree = new TTree("Events","Events");
    outTree->Branch("runNum",     &runNum,     "runNum/i");      // event run number
    outTree->Branch("lumiSec",    &lumiSec,    "lumiSec/i");     // event lumi section
    outTree->Branch("evtNum",     &evtNum,     "evtNum/i");      // event number
    outTree->Branch("matchGen",   &matchGen,   "matchGen/i");    // event has both leptons matched to MC Z->ll
    outTree->Branch("npv",        &npv,        "npv/i");         // number of primary vertices
    outTree->Branch("npu",        &npu,        "npu/i");         // number of in-time PU events (MC)
    outTree->Branch("triggerDec",   &triggerDec,   "triggerDec/i");    // event pass the trigger
    outTree->Branch("goodPV",   &goodPV,   "goodPV/i");    // event has a good PV
    outTree->Branch("matchTrigger",   &matchTrigger,   "matchTrigger/i");    // event has at least one lepton matched to the trigger
    outTree->Branch("ngenlep",     &ngenlep,     "ngenlep/i");      // number of gen leptons
    outTree->Branch("genlep1",   "TLorentzVector",  &genlep1);     // gen lepton1 4-vector
    outTree->Branch("genlep2",   "TLorentzVector",  &genlep2);     // gen lepton2 4-vector
    outTree->Branch("genq1",          &genq1,         "genq1/I");          // charge of lepton1
    outTree->Branch("genq2",          &genq2,         "genq2/I");          // charge of lepton2
    outTree->Branch("nlep",     &nlep,     "nlep/i");      // number of leptons
    outTree->Branch("lep1",       "TLorentzVector",  &lep1);     // lepton1 4-vector
    outTree->Branch("lep2",       "TLorentzVector",  &lep2);     // lepton2 4-vector
    outTree->Branch("q1",          &q1,         "q1/I");          // charge of lepton1
    outTree->Branch("q2",          &q2,         "q2/I");          // charge of lepton2
    outTree->Branch("scale1fbGen",   &scale1fbGen,   "scale1fbGen/F");    // event weight per 1/fb (MC)
    outTree->Branch("scale1fb",   &scale1fb,   "scale1fb/F");    // event weight per 1/fb (MC)
    outTree->Branch("scale1fbUp",    &scale1fbUp,   "scale1fbUp/F");    // event weight per 1/fb (MC)
    outTree->Branch("scale1fbDown",    &scale1fbDown,   "scale1fbDown/F");    // event weight per 1/fb (MC)
    outTree->Branch("lheweight",  &lheweight);

    //
    // loop through files
    //
    const UInt_t nfiles = samp->fnamev.size();
    for(UInt_t ifile=0; ifile<nfiles; ifile++) {  

      // Read input file and get the TTrees
      cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... " << endl; cout.flush();
      infile = TFile::Open(samp->fnamev[ifile]); 
      assert(infile);
      
      eventTree = (TTree*)infile->Get("Events");
      assert(eventTree);  
      eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
      eventTree->SetBranchAddress("Muon", &muonArr);   TBranch *muonBr = eventTree->GetBranch("Muon");
      eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");
      Bool_t hasGen = eventTree->GetBranchStatus("GenEvtInfo");
      TBranch *genBr=0, *genPartBr=0;
      if(hasGen) {
        eventTree->SetBranchAddress("GenEvtInfo", &gen); genBr = eventTree->GetBranch("GenEvtInfo");
	eventTree->SetBranchAddress("GenParticle",&genPartArr); genPartBr = eventTree->GetBranch("GenParticle");
      }

      // Compute MC event weight per 1/fb
      const Double_t xsec = samp->xsecv[ifile];
      Double_t totalWeightGen=0;
      Double_t totalWeight=0;
      Double_t totalWeightUp=0;
      Double_t totalWeightDown=0;
      Double_t puWeight=0;
      Double_t puWeightUp=0;
      Double_t puWeightDown=0;
      if (hasGen) {
	for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
	  infoBr->GetEntry(ientry);
	  genBr->GetEntry(ientry);
	  puWeight = h_rw->GetBinContent(h_rw->FindBin(info->nPUmean));
	  puWeightUp = h_rw_up->GetBinContent(h_rw_up->FindBin(info->nPUmean));
	  puWeightDown = h_rw_down->GetBinContent(h_rw_down->FindBin(info->nPUmean));
	  totalWeightGen+=gen->weight;
	  totalWeight+=gen->weight*puWeight;
	  totalWeightUp+=gen->weight*puWeightUp;
	  totalWeightDown+=gen->weight*puWeightDown;
	}
      }


      //
      // loop over events
      //
      Double_t nsel=0, nselvar=0;
      for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
	infoBr->GetEntry(ientry);

        if(ientry%1000000==0) cout << "Processing event " << ientry << ". " << (double)ientry/(double)eventTree->GetEntries()*100 << " percent done with this file." << endl;

	Double_t weightGen=1;
	Double_t weight=1;
	Double_t weightUp=1;
	Double_t weightDown=1;
	if(xsec>0 && totalWeightGen>0) weightGen = xsec/totalWeightGen;
        if(xsec>0 && totalWeight>0) weight = xsec/totalWeight;
	if(xsec>0 && totalWeightUp>0) weightUp = xsec/totalWeightUp;
	if(xsec>0 && totalWeightDown>0) weightDown = xsec/totalWeightDown;
	if(hasGen) {
	  genPartArr->Clear();
	  genBr->GetEntry(ientry);
	  genPartBr->GetEntry(ientry);
	  puWeight = h_rw->GetBinContent(h_rw->FindBin(info->nPUmean));
	  puWeightUp = h_rw_up->GetBinContent(h_rw_up->FindBin(info->nPUmean));
	  puWeightDown = h_rw_down->GetBinContent(h_rw_down->FindBin(info->nPUmean));
	  weightGen*=gen->weight;
	  weight*=gen->weight*puWeight;
	  weightUp*=gen->weight*puWeightUp;
	  weightDown*=gen->weight*puWeightDown;
	}

	// veto z -> xx decays for signal and z -> mm for bacground samples (needed for inclusive DYToLL sample)
        if (isWrongFlavor && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))==LEPTON_ID) continue;
        else if (isSignal && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
     

	// trigger requirement
	Bool_t passMuTrigger = kFALSE;
	if (isMuonTrigger(triggerMenu, info->triggerBits)) passMuTrigger=kTRUE;
	
        // good vertex requirement
	Bool_t hasGoodPV = kFALSE;
        if((info->hasGoodPV)) hasGoodPV=kTRUE;

	muonArr->Clear();
        muonBr->GetEntry(ientry);

	Int_t n_mu=0;
	TLorentzVector vlep1(0., 0., 0., 0.);
	TLorentzVector vlep2(0., 0., 0., 0.);
	Bool_t hasTriggerMatch = kFALSE;

	for(Int_t i1=0; i1<muonArr->GetEntriesFast(); i1++) {
          const baconhep::TMuon *mu = (baconhep::TMuon*)((*muonArr)[i1]);

	  double Mu_Pt=mu->pt;
	
	  if(Mu_Pt     < PT_CUT)        continue;  // lepton pT cut
	  if(fabs(mu->eta) > ETA_CUT)       continue;  // lepton |eta| cut
	  if(!passMuonID(mu))               continue;  // lepton selection

          if(isMuonTriggerObj(triggerMenu, mu->hltMatchBits, kFALSE)) hasTriggerMatch=kTRUE;
	  
	  if(Mu_Pt>vlep1.Pt())
	    {
	      vlep2=vlep1;
	      vlep1.SetPtEtaPhiM(Mu_Pt, mu->eta, mu->phi, MUON_MASS);
	      q2=q1;
	      q1=mu->q;
	    }
	  else if(Mu_Pt<=vlep1.Pt()&&Mu_Pt>vlep2.Pt())
	    {
	      vlep2.SetPtEtaPhiM(Mu_Pt, mu->eta, mu->phi, MUON_MASS);
	      q2=mu->q;
	    }
	 
	  n_mu++;
	}

	Int_t n_genmu=0;
	Int_t glepq1=-99;
	Int_t glepq2=-99;
	TLorentzVector *gvec=new TLorentzVector(0,0,0,0);
	TLorentzVector *glep1=new TLorentzVector(0,0,0,0);
	TLorentzVector *glep2=new TLorentzVector(0,0,0,0);
	TLorentzVector *gph=new TLorentzVector(0,0,0,0);
	Bool_t hasGenMatch = kFALSE;
	if(isSignal && hasGen) {
	  toolbox::fillGen(genPartArr, BOSON_ID, gvec, glep1, glep2,&glepq1,&glepq2,1);
	  
	  Bool_t match1 = ( ((glep1) && toolbox::deltaR(vlep1.Eta(), vlep1.Phi(), glep1->Eta(), glep1->Phi())<0.5) ||
			    ((glep2) && toolbox::deltaR(vlep1.Eta(), vlep1.Phi(), glep2->Eta(), glep2->Phi())<0.5) );
	      
	  Bool_t match2 = ( ((glep1) && toolbox::deltaR(vlep2.Eta(), vlep2.Phi(), glep1->Eta(), glep1->Phi())<0.5) ||
                                ((glep2) && toolbox::deltaR(vlep2.Eta(), vlep2.Phi(), glep2->Eta(), glep2->Phi())<0.5) );

	  for(Int_t i=0; i<genPartArr->GetEntriesFast(); i++) {
	    const baconhep::TGenParticle* genloop = (baconhep::TGenParticle*) ((*genPartArr)[i]);
	    if(fabs(genloop->pdgId)!=22) continue;
	    gph->SetPtEtaPhiM(genloop->pt, genloop->eta, genloop->phi, genloop->mass);
	    if(toolbox::deltaR(gph->Eta(),gph->Phi(),glep1->Eta(),glep1->Phi())<0.1)
	      {
		glep1->operator+=(*gph);
	      }
	    if(toolbox::deltaR(gph->Eta(),gph->Phi(),glep2->Eta(),glep2->Phi())<0.1)
	      {
		glep2->operator+=(*gph);
	      }
	  }

	  if(glep1->Pt() >= PT_CUT && fabs(glep1->Eta())< ETA_CUT)
	    {
	      genlep1=glep1;
	      genq1=glepq1;
	      n_genmu++;
	    }
	  if(glep2->Pt() >= PT_CUT && fabs(glep2->Eta())< ETA_CUT)
	    {
	      genlep2=glep2;
	      genq2=glepq2;
	      n_genmu++;
	    }
	  
	  if(match1 && match2) hasGenMatch = kTRUE;
	}

	//
	// Fill tree
	//
	runNum   = info->runNum;
	lumiSec  = info->lumiSec;
	evtNum   = info->evtNum;

	if (hasGenMatch) matchGen=1;
	else matchGen=0;
	if (passMuTrigger) triggerDec=1;
	else triggerDec=0;
	if (hasGoodPV) goodPV=1;
	else goodPV=0;
	if (hasTriggerMatch) matchTrigger=1;
	else matchTrigger=0;
	
	vertexArr->Clear();
	vertexBr->GetEntry(ientry);
	
	npv      = vertexArr->GetEntries();
	npu      = info->nPUmean;
	scale1fbGen = weightGen;
	scale1fb = weight;
	scale1fbUp = weightUp;
	scale1fbDown = weightDown;

	lheweight->clear();
	for (int j = 0; j<=110; j++)
	  {
	    lheweight->push_back(gen->lheweight[j]);
	  }

	ngenlep=n_genmu;

	nlep=n_mu;
	lep1=&vlep1;
        lep2=&vlep2;
	
	nsel+=weight;
	nselvar+=weight*weight;

	outTree->Fill();

	delete gvec;
	delete glep1;
	delete glep2;
	delete gph;
	lep1=0, lep2=0;
	genlep1=0, genlep2=0;
      }
      delete infile;
      infile=0, eventTree=0;    
      
      cout << nsel  << " +/- " << sqrt(nselvar);
      cout << endl;
    }
    outFile->Write();
    outFile->Close(); 
  }
  delete h_rw;
  delete h_rw_up;
  delete h_rw_down;
  delete f_rw;
  delete info;
  delete gen;
  delete genPartArr;
  delete muonArr;
  delete vertexArr;
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectZmmGen"); 
}
Ejemplo n.º 20
0
// analisi
Bool_t CheckSingle(const char* esdFileName,Bool_t kGRID){
  //inizializzo a zero ncluster (di tree T)
  //for (int ifc=0;ifc<10000;ifc++) ncluster[ifc]=0;
  
  // check the content of the ESD
  
  AliPIDResponse *pidr = new AliPIDResponse();
  
  // open the ESD file
  TFile* esdFile = TFile::Open(esdFileName);
  if (!esdFile || !esdFile->IsOpen()){
    Error("CheckESD", "opening ESD file %s failed", esdFileName);
    return kFALSE;
  }
  
  TString mctrkref(esdFileName);
  mctrkref.ReplaceAll("AliESDs.root","TrackRefs.root");
  TString fgal(esdFileName);
  fgal.ReplaceAll("AliESDs.root","galice.root");
  
  if(kGRID){
    fgal.Insert(0,"alien://");
    mctrkref.Insert(0,"alien://");
  }
  
  TTree *trkref;
  
  printf("ESD = %s\n",esdFileName);
  
  TFile *ftrkref; 
  if(isMC) ftrkref = TFile::Open(mctrkref.Data());
  
  AliHeader *h = new AliHeader();
  
  TFile *fgalice;
  if(isMC) fgalice = TFile::Open(fgal.Data());
  TTree *tgalice;
  if(isMC){
    tgalice = (TTree *) fgalice->Get("TE");
    tgalice->SetBranchAddress("Header",&h);
  }
  
  AliRunLoader* runLoader = NULL;
  
  AliRun *gAlice;
  if(isMC) runLoader = AliRunLoader::Open(fgal.Data());
  if(runLoader){
    runLoader->LoadgAlice();
    gAlice = runLoader->GetAliRun();
    if (!gAlice) {
      Error("CheckESD", "no galice object found");
      return kFALSE;
    }
    runLoader->LoadKinematics();
    runLoader->LoadHeader();
  }
  
  AliESDEvent * esd = new AliESDEvent;
  //  printf("esd object = %x\n",esd);
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree){
    Error("CheckESD", "no ESD tree found");
    return kFALSE;
  }
  esd->ReadFromTree(tree); // crea link tra esd e tree
  
  TClonesArray* tofcl;  // array dinamico
  TClonesArray* tofhit;
  TClonesArray* tofmatch;
  
  Int_t nev = tree->GetEntries(); //ogni entries evento
  Float_t mag;
  
  printf("nev = %i\n",nev);
  
  //azzero il contatore delle tracce del TTree T
  //ntracks=0;
  AliStack* stack=NULL;
  
  Int_t trkassociation[1000000];
  
  for(Int_t ie=0;ie < nev;ie++){
    if(runLoader){
      runLoader->GetEvent(ie);
      
      // select simulated primary particles, V0s and cascades
      stack = runLoader->Stack();
    }
    
    if(isMC) trkref = (TTree *) ftrkref->Get(Form("Event%i/TreeTR",ie));
    tree->GetEvent(ie);
    if(isMC) tgalice->GetEvent(ie);
    
    if(isMC) interactiontime = h->GenEventHeader()->InteractionTime()*1E+12;
    
    mag = esd->GetMagneticField();
    
    AliTOFHeader *tofh = esd->GetTOFHeader();
    ntofcl = tofh->GetNumberOfTOFclusters();
    
    esd->ConnectTracks(); // Deve essere sempre chiamato dopo aver letto l'evento (non troverebbe l'ESDevent). Scrivo in tutte le tracce l origine dell evento così poi da arrivare ovunque(tipo al cluster e al tempo quindi).
    
    
    //Riempio variabile del tree "T"
    //nevento=ie;
    
    if(! esd->GetVertex()){
      esd->ResetStdContent();
      continue;// una volta fatto il connect manda un flag ; siccome qua c'era un continue(non si arriva in fondo al ciclo) bisogna resettarlo altrimenti lo trova già attivo.
    }
    
    tofcl = esd->GetESDTOFClusters(); // AliESDTOFCluster *cltof = tofcl->At(i);
    if(tofcl->GetEntries() == 0){
      esd->ResetStdContent();
      continue;
    }
    tofhit = esd->GetESDTOFHits(); // AliESDTOFHit *hittof = tofhit->At(i);
    tofmatch = esd->GetESDTOFMatches(); // AliESDTOFHit *mathctof = tofmatch->At(i);
    
    // loop over tracks
    
    pidr->SetTOFResponse(esd,AliPIDResponse::kTOF_T0); //per recuperare lo start time ("esd", "tipo start time"), tipo cioè o il TOF stesso o il T0 o il best, ovvero la combinazione dei 2
    
    Int_t ntrk = esd->GetNumberOfTracks();
    
    //printf("%i) TPC tracks = %i -- TOF cluster = %i - TOF hit = %i -- matchable info = %i\n",ie,ntrk,tofcl->GetEntries(),tofhit->GetEntries(),tofmatch->GetEntries());
    
    Double_t time[AliPID::kSPECIESC];
    
    
    if(isMC && stack){// create association trackref
      printf("nMC track = %i\n",stack->GetNtrack());
      for(Int_t ist=0;ist < stack->GetNtrack();ist++){
	trkassociation[ist]=-1;
      }
      for(Int_t iref=0;iref < trkref->GetEntries();iref++){
	trkref->GetEvent(iref);
	Int_t trkreference = trkref->GetLeaf("TrackReferences.fTrack")->GetValue();
	if(trkreference > -1 && trkreference < 1000000){
	  trkassociation[trkreference] = iref;
	}
      }
    }
    
    for (Int_t iTrack = 0; iTrack < ntrk; iTrack++){
      AliESDtrack* track = esd->GetTrack(iTrack);
      
      // select tracks of selected particles
      if ((track->GetStatus() & AliESDtrack::kITSrefit) == 0) continue;//almeno un hit nell ITS
      if (track->GetConstrainedChi2() > 4) continue; //se brutto X^2
      if ((track->GetStatus() & AliESDtrack::kTOFout) == 0) continue; //se traccia matchata con tof
      if(track->GetNumberOfTPCClusters() < 70) continue;
      Float_t p =track->P();
      
      itrig = 0;
      timetrig = 0;
      
      if(p > 0.9 && p < 1.1){
 	track->GetIntegratedTimes(time);
	
	itrig = iTrack;
	timetrig = track->GetTOFsignal() - time[2];
	iTrack = ntrk;
      }
    }
    
    printf("real loop, ntrk = %i\n",ntrk);
  
    for (Int_t iTrack = 0; iTrack < ntrk; iTrack++){
      AliESDtrack* track = esd->GetTrack(iTrack);
      
      // select tracks of selected particles
      if ((track->GetStatus() & AliESDtrack::kITSrefit) == 0) continue;//almeno un hit nell ITS
      if (track->GetConstrainedChi2() > 4) continue; //se brutto X^2
      
      //if ((track->GetStatus() & AliESDtrack::kTOFout) == 0) continue; //se traccia matchata con tof
      if(track->GetNumberOfTPCClusters() < 70) continue;

      TOFout = (track->GetStatus() & AliESDtrack::kTOFout) > 0;

      track->GetIntegratedTimes(time);
      
      Float_t dx = track->GetTOFsignalDx(); //leggo i residui tra traccia e canale tof acceso
      Float_t dz = track->GetTOFsignalDz();
      
      mism = 0;
      
      dedx = track->GetTPCsignal();
      
      Int_t label = TMath::Abs(track->GetLabel());
      if(stack){
	TParticle *part=stack->Particle(label);
	pdg = part->GetPdgCode();
      }
      
      Int_t TOFlabel[3];
      track->GetTOFLabel(TOFlabel);
      
      //  printf("%i %i %i %i\n",label,TOFlabel[0],TOFlabel[1],TOFlabel[2]);
      
      ChannelTOF[0] = track->GetTOFCalChannel();
      //      printf("geant time = %f\n",gtime);
      //getchar();
      // if(TMath::Abs(dx) > 1.25 || TMath::Abs(dz) > 1.75) continue; // is inside the pad
      
      //riempio il numro di cludter e impulso trasverso per traccia del TTree T
      ncluster=track->GetNTOFclusters();
      impulso_trasv=track->Pt();
      impulso=track->P();
      
      StartTime = pidr->GetTOFResponse().GetStartTime(track->P());
      StartTimeRes = pidr->GetTOFResponse().GetStartTimeRes(track->P());
      
      if(track->Pt() > 0.9 && track->Pt() < 1.5){  //impulso non troppo alto per separazione tra particelle
	Float_t dt = track->GetTOFsignal() - time[2] - pidr->GetTOFResponse().GetStartTime(track->P());//tempo TOF(è lo stesso di Gettime, solo che lo prendo dale tracce)(già calibrato) -ip del PI (posizione 0 e, posizione 1 mu, pos 2 PI, pos 3 K,pos 4 p) -start time
	Float_t dtKa = track->GetTOFsignal() - time[3] - pidr->GetTOFResponse().GetStartTime(track->P());
	Float_t dtPr = track->GetTOFsignal() - time[4] - pidr->GetTOFResponse().GetStartTime(track->P());
	hdt->Fill(dt);
	hdtKa->Fill(dtKa);
	hdtPr->Fill(dtPr);
      }
      
      charge = track->Charge();
      phi = track->Phi();
      eta = track->Eta();

      GetPositionAtTOF(track,mag,coord);
      phiExt = TMath::ATan2(coord[1],coord[0]);
      etaExt =  -TMath::Log(TMath::Tan(0.5*TMath::ATan2(sqrt(coord[0]*coord[0]+coord[1]*coord[1]),coord[2])));

      for (int i=0;i<(track->GetNTOFclusters());i++){
	int idummy=track->GetTOFclusterArray()[i];
        
	AliESDTOFCluster *cl = (AliESDTOFCluster *) tofcl->At(idummy);
        
	tempo[i]=cl->GetTime();
	tot[i]=cl->GetTOT();
        
	ChannelTOF[i]=cl->GetTOFchannel();
		
	if(i==0){
	  GetResolutionAtTOF(track,mag,ChannelTOF[i],res);
	}
	
	for(int im=cl->GetNMatchableTracks();im--;){ //o così o da n-1 a 0 //for(int im=cl->GetNMatchableTracks();im>0;im--) non andava bene perchè non prendeva mai lo 0  
	  
	  //	    if(track->GetNTOFclusters()==2) printf("-- %i) %f %f\n",im,cl->GetLength(im),cl->GetIntegratedTime(2,im));
	  
	  if(cl->GetTrackIndex(im) == track->GetID()){
	    exp_time_el[i] = cl->GetIntegratedTime(0,im); // pi = 2
	    exp_time_mu[i] = cl->GetIntegratedTime(1,im); // pi = 2
	    exp_time_pi[i] = cl->GetIntegratedTime(2,im); // pi = 2
	    exp_time_ka[i] = cl->GetIntegratedTime(3,im); // pi = 2
	    exp_time_pr[i] = cl->GetIntegratedTime(4,im); // pi = 2
	    L[i] = cl->GetLength(im);
	    //		  if(track->GetNTOFclusters()==2)printf("%i) %f %f\n",i,L[i],exp_time_pi[i]);
	    DeltaX[i]=cl->GetDx(im); // mettendolo dentro questo if dovrei prendere i residui di una stessa traccia
	    DeltaZ[i]=cl->GetDz(im);
	  }
	}
      }
         
      //ReMatch();
      
      Int_t jref=0;
      if(isMC){
	if(TOFlabel[0] > -1 && TOFlabel[0] < 1000000){
	  trkref->GetEvent(trkassociation[TOFlabel[0]]);
	  if(TOFlabel[0] == trkref->GetLeaf("TrackReferences.fTrack")->GetValue()){
	    //  printf("trk -> %i (%i)\n",trkref->GetLeaf("TrackReferences.fTrack")->GetValue(),trkref->GetLeaf("TrackReferences.fTrack")->GetValue(jref));	
	    while(jref > -1 && trkref->GetLeaf("TrackReferences.fTrack")->GetValue(jref) != 0){
	      //printf("det = %i\n",trkref->GetLeaf("TrackReferences.fDetectorId")->GetValue(jref));
	      if(trkref->GetLeaf("TrackReferences.fDetectorId")->GetValue(jref) == 4){
		gtime=trkref->GetLeaf("TrackReferences.fTime")->GetValue(jref)*1E+12;
		xgl = trkref->GetLeaf("TrackReferences.fX")->GetValue(jref);
		ygl = trkref->GetLeaf("TrackReferences.fY")->GetValue(jref);
		zgl = trkref->GetLeaf("TrackReferences.fZ")->GetValue(jref);
		MakeTrueRes();
		jref =  100;
	      }
	      jref++;
	    }
	  }
	}
      }
      
      
      if(TMath::Abs(label) != TOFlabel[0] && stack){
	mism=2;
	
	while(TOFlabel[0] != -1 && TOFlabel[0] != label){
	  TOFlabel[0] = stack->Particle(TOFlabel[0])->GetMother(0);
	}
	
	if(label == TOFlabel[0])
	  mism=1;	
	
      }
      
      //AddDelay();
      T->Fill(); //cout<<"riempio il tree  "<<endl; //Riempio tree "T"
    
      
      
      //incremento il contatore delle tracce del TTree T matchate e che superano i tagli
      //ntracks++;
      
    }//end of for(tracks)
      
      
    
    esd->ResetStdContent();
    
    
    
  } //end of for(events)

  if(runLoader){
    runLoader->UnloadHeader();
    runLoader->UnloadKinematics();
    delete runLoader;
  }
  
  esdFile->Close();
  if(isMC) ftrkref->Close();
  if(isMC) fgalice->Close();
}
Ejemplo n.º 21
0
rdEEevent(int neve=300,  TString Tname0="/star/u/eemcdb/dataFeb11/run00006.eeTree", int flag=0, float Emax=40.) {
    TString Tname0="../sim2003/mc_eve2";
    gSystem->Load("StRoot/StEEmcUtil/EEevent/libEEevent.so");

    //  gStyle->SetPalette(1,0);
    gStyle->SetOptStat(111111);

    TString Tname;
    Tname=Tname0;

    printf("read upto %d events from file=%s.root\n",neve,Tname.Data());
    TFile *f = new TFile(Tname+".root");
    assert(f->IsOpen());
    TTree *t4 = (TTree*)f->Get("EEtree");
    assert(t4);
    // create a pointer to an event object. This will be used
    // to read the branch values.
    EEeventDst *event = new EEeventDst();

    //if (gROOT->IsBatch()) return;  new TBrowser();  t4->StartViewer();  return;
    TBranch *br = t4->GetBranch("EEdst");
    br->SetAddress(&event);
    Int_t nevent = (Int_t)t4->GetEntries();
    for (Int_t ie=0; ie<nevent; ie++) {
        if(ie>=neve) break;
        printf("\niEve=%d  ---------- \n",ie);
        int i;

        //read this branch only
        br->GetEntry(ie);
        event->print();

        int nSec=event->Sec->GetEntries();
        printf("%d sectors with data\n",nSec);

        int is;
        for(is=0; is<nSec; is++) {
            EEsectorDst *sec=(EEsectorDst*)event->Sec->At(is);
            //      sec->print();
            TClonesArray *hitA=sec->getTwHits();
            assert(hitA);
            int ih;
            for(ih=0; ih<hitA->GetEntries(); ih++) {
                char sub;
                int eta;
                float ener;
                EEtwHitDst *hit=(EEtwHitDst*)hitA->At(ih);
                hit->get(sub,eta,ener);
                if(ie<5) printf("    ih=%d sec=%d sub=%c etaBin=%d ener=%f\n",ih, sec->getID(), sub, eta,ener);
                //	hit->print();
            }

        }


    }

#if 0

    // allocate memory for needed branches
    TClonesArray *secA=new TClonesArray("EEsectorDst",1000);
    TBranch *BRsec = t4->GetBranch("Sec");   // set the branch address
    BRsec->SetAddress(&secA);

    int eveID=0;
    TBranch *BRid = t4->GetBranch("ID");
    BRid->SetAddress(&eveID);

    Int_t nevent = (Int_t)t4->GetEntries();
    printf("Total events in TTree=%d\n",nevent);


    // ...........  LOOP OVER EVENTS ............

    for (Int_t ie=0; ie<nevent; ie++) {
        if(ie>=neve) break;
        int i;

        //read this branch only
        BRid->GetEntry(ie);
        BRsec->GetEntry(ie);

        if(ie%1==0) printf("\n\iEve=%d  nSec=%d with data \n",ie,secA->GetEntries());

        //    if(ie%1==0) printf("\n\iEve=%d eveID=%d, eveType=%d, nSec=%d with data :\n",ie,eveID,eveType,secA->GetEntries());
        if(ie%1==0) printf("\n\iEve=%d eveID=%d, nSec=%d with data :\n",ie,eveID,secA->GetEntries());


        int is;
        for(is=0; is<secA->GetEntries(); is++) {
            EEsectorDst *sec=(EEsectorDst*)secA->At(is);
            if(ie<1) sec->print();

            TClonesArray *hitA;
            int ih;

            TClonesArray *hitAA[]= {sec->getPre1Hits(),sec->getPre2Hits(),sec->getTwHits(),sec->getPostHits(),sec->getSmdUHits(),sec->getSmdVHits()};
            int iz;
            for(iz=0; iz<4; iz++) { // over tower/pre/post
                hitA=hitAA[iz];
                if(ie<1)    printf("  sectorID=%d  iz=%d nHit=%d :\n",sec->getID(),iz,hitA->GetEntries());
            }// end of loop over pre1/2/Tw/Post


            for(iz=4; iz<6; iz++) { // over SMD U/V
                hitA=hitAA[iz];
                if(ie<1) printf("  sectorID=%d  iz=%d nHit=%d :\n",sec->getID(),iz,hitA->GetEntries());
                for(ih=0; ih<hitA->GetEntries(); ih++) {
                    EEsmdHitDst *hit2=(EEsmdHitDst*)hitA->At(ih);
                    int strip;
                    float ener;
                    hit2->get(strip,ener);
                    if(ie<1) printf("    ih=%d strip=%d etaBin=%d ener=%f\n",ih, sec->getID(), strip,ener);
                    hit->print();
                }
            }// end of loop over pre1/2/Tw/Post


        }// end of loop over sector

    }
#endif
    printf("\n\nTotal events in B TTree=%d\n",nevent);


}
Ejemplo n.º 22
0
void tpccfind(Int_t threshold, Float_t thr = 2,
	      Int_t i1 = 2, Int_t i2 = 2, 
	      Int_t tharea =20, Int_t thmax=100)
{  
  ///////////////////////GRAPHICS//DECLARATION//////////////////////
  TCanvas  * c1 = new TCanvas("padcluster","Cluster finder 1",700,900);
  c1->cd();
  TCanvas  * c2 = new TCanvas("padcluster2","Cluster finder 2",700,900);
  c2->cd();
  c1->cd();
  TPad * pad11 = new TPad("pad11","",0.01,0.76,0.48,0.95,21);
  pad11->Draw();
  TPad * pad12 = new TPad("pad12","",0.51,0.76,0.95,0.95,21);
  pad12->Draw();
  TPad * pad21 = new TPad("pad21","",0.01,0.56,0.49,0.74,21);
  pad21->Draw();
  TPad * pad22 = new TPad("pad22","",0.51,0.56,0.95,0.74,21);
  pad22->Draw();
  TPad * pad31 = new TPad("pad31","",0.01,0.36,0.49,0.54,21);
  pad31->Draw();
  TPad * pad32 = new TPad("pad32","",0.51,0.36,0.95,0.54,21);
  pad32->Draw();
  TPad * pad41 = new TPad("pad41","",0.01,0.16,0.49,0.34,21);
  pad41->Draw();
  TPad * pad42 = new TPad("pad42","",0.51,0.16,0.95,0.34,21);
  pad42->Draw();

  c2->cd();
  TPad * pad11_2 = new TPad("pad11_2","",0.01,0.76,0.48,0.95,21);
  pad11_2->Draw();
  TPad * pad12_2 = new TPad("pad12_2","",0.51,0.76,0.95,0.95,21);
  pad12_2->Draw();
  /////////////////////HISTOGRAMS///DECLARATION///////////////////////
  pad11->cd();
  TH1F * hsx = new TH1F("hsx","Sigma of distribution in time",40,0,2);
  pad12->cd();
  TH1F * hsy = new TH1F("hsy","Sigma of distribution in pads",40,0,2);

  pad21->cd();
  TProfile * hsx2 = new TProfile("hsx2","Sigma of distribution in time",
			 20,100,500);
  pad22->cd();
  TProfile * hsy2 = new TProfile("hsy2","Sigma of distribution in pads",
			 20,100,500);

  pad31->cd();
  TH1F * harea = new TH1F("harea","Area of the peak",26,0,52);
  pad32->cd();
  TH1F * hmax = new TH1F("hmax","Maximal amplitude in peak",30,0,150);
 

  pad41->cd();  
  TProfile * harea2= new TProfile("harea2","Area dependence z coordinata",
			 20,100,500);
  pad42->cd();
  TProfile * hmax2 = new TProfile("hmax2","Maximal amplitude dependence",
			 20,100,500);
  pad41->cd();  

  pad11_2->cd();
  TProfile * harea2p= new TProfile("harea2p","Area dependence on pad coordinata",
			 20,0,100);
  pad12_2->cd();
  TProfile * hmax2p = new TProfile("hmax2p","Maximal amplitude dependence on pad",
			 20,0,50);
  //////////////////CALCULATION//////////////////////////////////////////

  for (Int_t k = i1;k <=i2; k++)
    {
      tpcanal(1,k,10,0,kFALSE);
      TClusterFinder * cf=new TClusterFinder(0,0,threshold,1);
      cf->GetHisto(&gtpc.GetHis1());
      TClonesArray * arr = cf->FindClusters();
      cf->Delete();
      Int_t size = arr->GetEntries();
      
      if ( size>0 )   
	for (Int_t i=0 ; i<size;i++)
	  {
	    Int_t index;
	    TCluster *c=(TCluster*)arr->UncheckedAt(i);
	    hsx->Fill(TMath::Sqrt(c.fSigmaX2));
	    hsy->Fill(TMath::Sqrt(c.fSigmaY2));    
	    if  (TMath::Sqrt(c.fSigmaX2)<thr)
	      hsx2->Fill(c.fX,TMath::Sqrt(c.fSigmaX2),1);
	    if  (TMath::Sqrt(c.fSigmaY2)<thr)
	      hsy2->Fill(c.fX,TMath::Sqrt(c.fSigmaY2),1);       
	    hmax->Fill(c.fMax);
	    harea->Fill(c.fArea);
	    if (c.fArea<tharea)  harea2->Fill(c.fX,c.fArea,1);
            if (c.fMax<thmax) hmax2->Fill(c.fX,c.fMax,1);
	    if (c.fArea<tharea)  harea2p->Fill(c.fY,c.fArea,1);
            if (c.fMax<thmax) hmax2p->Fill(c.fY,c.fMax,1);
	    
	  }
    } 
  gStyle->SetOptStat(1);
  pad11->cd();
  hsx->Draw();
  pad12->cd();
  hsy->Draw();

  pad21->cd();
  hsx2->Draw();
  pad22->cd();
  hsy2->Draw();

  pad31->cd();
  harea->Draw();
  pad32->cd();
  hmax->Draw();

  pad41->cd();
  harea2->Draw();
  pad42->cd();
  hmax2->Draw();


  c1->cd();
  TPaveText * comment = new TPaveText(0.05,0.02,0.95,0.14,"NDC");
  comment->SetTextAlign(12);
  comment->SetFillColor(42);   
  comment->ReadFile("clusters.txt");
  comment->Draw();
  c2->cd();
  pad11_2->cd();
  harea2p->Draw();
  pad12_2->cd();
  hmax2p->Draw();


}
Ejemplo n.º 23
0
//void LeptonEnergy(const char *inputFile = "sourceFiles/LO/ttbar_LO_total.root")
void LeptonEnergy(const TString & file)
{

  //const char *inputFile = Form("/home/tjkim/work/pheno/topmass/sourceFiles/LO/fromSayaka/ttbar_%s.root",file.Data());
  //gSystem->Load("/export/apps/delphes//libDelphes");
  const char *inputFile = Form("/data/users/seohyun/analysis/ttbar_%s.root",file.Data());
  gSystem->Load("/home/seohyun/delphes/libDelphes.so");
/*
  TFile *f2 = TFile::Open("weightfunc2.root");
  TFile *f3 = TFile::Open("weightfunc3.root");
  TFile *f5 = TFile::Open("weightfunc5.root");
  TFile *f15 = TFile::Open("weightfunc15.root");

  const int nmass = 151;
  float mymass[ nmass ];
  float integral2[ nmass ];
  float integral3[ nmass ];
  float integral5[ nmass ];
  float integral15[ nmass ];
  for(int i=0; i < nmass ; i++){
    integral2[i] = 0.0;
    integral3[i] = 0.0;
    integral5[i] = 0.0;
    integral15[i] = 0.0;
  }

  TGraph * g2[nmass];
  TGraph * g3[nmass];
  TGraph * g5[nmass];
  TGraph * g15[nmass];

  TIter next(f2->GetListOfKeys());
  TKey *key;
  int i = 0;
  while( (key = (TKey*) next())) {
    TClass *cl = gROOT->GetClass( key->GetClassName());
    if( !cl->InheritsFrom("TGraph")) continue;
    g2[i] = (TGraph*) key->ReadObj();
    string mass = g2[i]->GetName(); 
    float temp = atof(mass.c_str()); 
    mymass[i] = temp;
    i++;
  }

  TIter next(f3->GetListOfKeys());
  i = 0;
  while( (key = (TKey*) next())) {
    TClass *cl = gROOT->GetClass( key->GetClassName());
    if( !cl->InheritsFrom("TGraph")) continue;
    g3[i] = (TGraph*) key->ReadObj();
    i++;
  }

  TIter next(f5->GetListOfKeys());
  i = 0;
  while( (key = (TKey*) next())) {
    TClass *cl = gROOT->GetClass( key->GetClassName());
    if( !cl->InheritsFrom("TGraph")) continue;
    g5[i] = (TGraph*) key->ReadObj();
    i++;
  }

  TIter next(f15->GetListOfKeys());
  i = 0;
  while( (key = (TKey*) next())) {
    TClass *cl = gROOT->GetClass( key->GetClassName());
    if( !cl->InheritsFrom("TGraph")) continue;
    g15[i] = (TGraph*) key->ReadObj();
    i++;
  } 

  TFile * res = TFile::Open("hist_LO_res_v3.root");
  TH1F * h_acc = (TH1F*) res->Get("h_totalacc_lepton"); 
*/

  //TFile* f = TFile::Open("hist_LO_res_60.root", "recreate");
  TFile* f = TFile::Open(Form("170717/hist_%s.root",file.Data()), "recreate");

  // Create chain of root trees
  TChain chain("Delphes");
  chain.Add(inputFile);
 
  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();

  // Get pointers to branches used in this analysis
  TClonesArray *branchParticle = treeReader->UseBranch("Particle");
  TClonesArray *branchMuon = treeReader->UseBranch("Muon");
  TClonesArray *branchElectron = treeReader->UseBranch("Electron");
  TClonesArray *branchJet = treeReader->UseBranch("Jet");

  TClonesArray *branchEvent = treeReader->UseBranch("Event");
 
  GenParticle *particle;
  GenParticle *daughter1;
  GenParticle *daughter2;
  GenParticle *granddaughter1_1;
  GenParticle *granddaughter1_2;
  GenParticle *granddaughter2_1;
  GenParticle *granddaughter2_2;

  GenParticle *genelectron;
  GenParticle *genmuon;

  LHEFEvent * event;

  // Create TTree
  //Float_t Muon_E;
  //Float_t Electron_E;
  //Float_t Lepton_E;
  //Float_t Lepton_E_reco;
  //TTree * tree = new TTree("tree","lepton energy");
  //tree->Branch("Lepton_E",&Lepton_E,"Lepton_E/F"); 
  //tree->Branch("Lepton_E_reco",&Lepton_E_reco,"Lepton_E_reco/F"); 
  //tree->Branch("Muon_E",&Muon_E,"Muon_E/F"); 
  //tree->Branch("Electron_E",&Electron_E,"Electron_E/F"); 

  // Book histograms
  TH1 * channel = new TH1F("channel", "ttbar event categorization", 7, 0.0, 7.0);

  TH1 * h_muon_energy = new TH1F("h_muon_energy", "muon energy distribution", 5000, 0, 500);
  TH1 * h_electron_energy = new TH1F("h_electron_energy", "electron energy distribution", 5000, 0, 500);
  TH1 * h_lepton_energy = new TH1F("h_lepton_energy", "lepton energy distribution", 5000, 0, 500);

  //TH1 * h_muon_energy_acc = new TH1F("h_muon_energy_acc", "muon energy distribution", 5000, 0, 500);
  //TH1 * h_electron_energy_acc = new TH1F("h_electron_energy_acc", "electron energy distribution", 5000, 0, 500);
  TH1 * h_lepton_energy_acc = new TH1F("h_lepton_energy_acc", "lepton energy distribution", 5000, 0, 500);

  //TH1 * h_muon_energy_reco = new TH1F("h_muon_energy_reco", "muon energy distribution at RECO", 5000, 0, 500);
  //TH1 * h_electron_energy_reco = new TH1F("h_electron_energy_reco", "electron energy distribution at RECO", 5000, 0, 500);
  TH1 * h_lepton_energy_reco = new TH1F("h_lepton_energy_reco", "lepton energy distribution at RECO", 5000, 0, 500);
  TH2 * h2_lepton_energy_response = new TH2F("h2_lepton_energy_response", "lepton energy response", 5000, 0, 500,5000,0,500);

  //TH1 * h_muon_energy_reco_S2 = new TH1F("h_muon_energy_reco_S2", "muon energy distribution at RECO", 5000, 0, 500);
  //TH1 * h_electron_energy_reco_S2 = new TH1F("h_electron_energy_reco_S2", "electron energy distribution at RECO", 5000, 0, 500);
  //TH1 * h_lepton_energy_reco_S2 = new TH1F("h_lepton_energy_reco_S2", "lepton energy distribution at RECO", 5000, 0, 500);
  //TH1 * h_lepton_nbjets_reco_S2 = new TH1F("h_lepton_nbjets_reco_S2","number of b jets",5,0,5);

  //TH1 * h_muon_energy_reco_final = new TH1F("h_muon_energy_reco_final", "muon energy distribution at RECO", 5000, 0, 500);
  //TH1 * h_electron_energy_reco_final = new TH1F("h_electron_energy_reco_final", "electron energy distribution at RECO", 5000, 0, 500);
  TH1 * h_lepton_energy_reco_final = new TH1F("h_lepton_energy_reco_final", "lepton energy distribution at RECO", 5000, 0, 500);
  TH2 * h2_lepton_energy_final_response = new TH2F("h2_lepton_energy_final_response", "lepton energy response", 5000, 0, 500,5000,0,500);

  //std::vector<float> lepton_E;
  //std::vector<float> lepton_E_final;

  int ndileptonic = 0; //ee, mm, tautau
  int ndileptonic2 = 0; //ee, mm, tau->ee, mm
  int ndileptonic3 = 0; //ee, mm
  int nsemileptonic = 0;
  int nsemileptonic2 = 0;
  int nsemileptonic3 = 0;
  int nhadronic = 0;

  // Loop over all events
  for(Int_t entry = 0; entry < numberOfEntries; ++entry)
  {
    //if( entry == 100000) break;
    if( entry%1000 == 0) cout << "starting with " << entry << endl;
    // Load selected branches with data from specified event
    treeReader->ReadEntry(entry);
 
    int nmuons = 0;
    int nelectrons= 0;
    int ntaumuons = 0;
    int ntauelectrons= 0;
    int ntaus = 0 ;
    int nhadrons = 0 ;
    // If event contains at least 1 particle
    int ntop = 0;

    double genweight = 1.0;
    if(branchEvent->GetEntries() > 0)
    {

      event = (LHEFEvent * ) branchEvent->At(0);
      genweight = event->Weight;
      //cout << "event number = " << event->Number << endl;
      //cout << "event weight = " << event->Weight << endl;

    }

    //Lepton_E = -1.0;
    
    if(branchParticle->GetEntries() > 0)
    {
      
      for(int i = 0; i < branchParticle->GetEntriesFast() ; i++){
        if(ntop == 2) break;

        particle = (GenParticle *) branchParticle->At(i);
    
        int status = particle->Status; 

        bool LO = true;
        //if( LO ) cout << "THIS IS LO..." << endl;
        if( status != 3) continue;

        int id = particle->PID; 

        double gen_pt = particle->PT;
        double gen_eta = particle->Eta;
        //Leading order
        if( LO) {
          if( abs(id) == 11 ){
            genelectron = particle;
            double energy = genelectron->E;
            h_electron_energy->Fill( energy, genweight );
            h_lepton_energy->Fill( energy, genweight );
            //Lepton_E = energy;
            //for(int i=0; i < nmass; i++){
            //  float w = g2[i]->Eval( energy );
            //  integral2[i] = integral2[i] + w ;
            //}
            //lepton_E.push_back( energy );
            if( energy > 20 && fabs(gen_eta) < 2.4) {
              //h_electron_energy_acc->Fill( energy, genweight );
              h_lepton_energy_acc->Fill( energy, genweight );
              nmuons++;
            }
            //daughter1 = (GenParticle*) branchParticle->At( particle->D1);
            //daughter2 = (GenParticle*) branchParticle->At( particle->D2);
            //int d1_id = abs(daughter1->PID);
            //int d2_id = abs(daughter2->PID);
            //cout << "electron daughter  " << d1_id  << " , " << d2_id << endl;     
          }else if( abs(id) == 13 ){
            genmuon = particle;
            double energy = genmuon->E;
            h_muon_energy->Fill( energy, genweight );
            h_lepton_energy->Fill( energy, genweight );
            //Lepton_E = energy;
            //for(int i=0; i < nmass; i++){
            //  float w = g2[i]->Eval( energy );
            //  integral2[i] = integral2[i] + w ;
            //}
            //lepton_E.push_back( energy );
            if( energy > 20 && fabs(gen_eta) < 2.4) {
              //h_muon_energy_acc->Fill( energy, genweight );
              h_lepton_energy_acc->Fill( energy, genweight );
              nelectrons++;
            }
            //int d1_id = -1;
            //int d2_id = -1;
            //if( particle->D1 >= branchParticle->GetEntries()){
            //  daughter1 = (GenParticle*) branchParticle->At( particle->D1);
            //  int d1_id = abs(daughter1->PID);
            //}
            //if( particle->D1 >= branchParticle->GetEntries()){
            //  daughter1 = (GenParticle*) branchParticle->At( particle->D1);
            //  int d1_id = abs(daughter1->PID);
            //}
            //cout << "muon daughter  " << d1_id  << " , " << d2_id << endl;            
          }
        //NLO
        }else if( abs(id) == 6 ) {
          ntop++;
          particle = (GenParticle*) branchParticle->At( i ) ;
          if( particle->D1 >= branchParticle->GetEntries() ) continue;
          bool lasttop  =  false ;
          while( !lasttop ){
            if( particle->D1 >= branchParticle->GetEntries() ) break;
            GenParticle * d = (GenParticle *) branchParticle->At( particle->D1 );
            if( abs(d->PID) != 6 ) { 
              lasttop = true;
            }
            else { particle = d ; }
          } 

          if( particle->D1 >= branchParticle->GetEntries() || particle->D2 >= branchParticle->GetEntries() ){
           continue;
          }

          daughter1 = (GenParticle*) branchParticle->At( particle->D1) ;
          daughter2 = (GenParticle*) branchParticle->At( particle->D2) ;
  
 
          bool lastW = false;
          int d1_id = abs(daughter1->PID);
          int d2_id = abs(daughter2->PID);

          //cout << "top daughter  " << d1_id  << " , " << d2_id << endl;

          while( !lastW) {
            if( daughter1->D1 >= branchParticle->GetEntries() ) break;
            GenParticle * d = (GenParticle *) branchParticle->At( daughter1->D1 );
            if( abs(d->PID) != 24 ) { lastW = true; }
            else {
              daughter1 = d ;
            } 
          } 

          if( daughter1->D1 >= branchParticle->GetEntries() || daughter1->D2 >= branchParticle->GetEntries() ){
           continue;
          }

          granddaughter1_1 = (GenParticle*) branchParticle->At( daughter1->D1) ;
          granddaughter1_2 = (GenParticle*) branchParticle->At( daughter1->D2) ;
          granddaughter2_1 = (GenParticle*) branchParticle->At( daughter2->D1) ;
          granddaughter2_2 = (GenParticle*) branchParticle->At( daughter2->D2) ;    
 
          int gd1_1_id = abs(granddaughter1_1->PID);
          int gd1_2_id = abs(granddaughter1_2->PID);
          int gd2_1_id = abs(granddaughter2_1->PID);
          int gd2_2_id = abs(granddaughter2_2->PID);

          //cout << "W daughters = " << gd1_1_id << " , " << gd1_2_id << " , " << gd2_1_id << " , " << gd2_2_id << endl;
          int W_dau_status = granddaughter1_1->Status ;

          //if( gd1_1_id > gd1_2_id ) cout << "Something is WRONG ! " << endl;

          GenParticle * le = (GenParticle * ) branchParticle->At( granddaughter1_1->D1 );
          //GenParticle * leda = (GenParticle * ) branchParticle->At( le->D1);
          if( gd1_1_id == 11 || gd1_1_id == 13 ){
            cout << le->D1 << " , " << le->D2 << endl;
          //  cout << " original id and status = " << gd1_1_id << " , " <<  W_dau_status  << " le id and status = " << le->PID << " , " << le->Status <<  " leda id and status = " << leda->PID << " , " << leda->Status << endl;
          }

          if( gd1_1_id == 11 ) { 
            nelectrons++;
            //genelectron = granddaughter1_2;
            genelectron = le;
          }
          else if( gd1_1_id == 13 ) { 
            nmuons++;
            //genmuon = granddaughter1_2;
            genmuon = le;
          }
          else if( gd1_1_id == 15 ) {
            ntaus++;

            /*
            if( granddaughter1_2->D1 >= branchParticle->GetEntries() || granddaughter1_2->D2 >= branchParticle->GetEntries() ){
              continue;
            }

            GenParticle * taudaughter1 = (GenParticle*) branchParticle->At( granddaughter1_2->D1) ;
            GenParticle * taudaughter2 = (GenParticle*) branchParticle->At( granddaughter1_2->D2) ;
            int taud1_id = abs(taudaughter1->PID);
            int taud2_id = abs(taudaughter2->PID);

            //cout << "tau daughter = " << taud1_id << " " << taud2_id << endl;

            if( taud1_id == 11 || taud1_id == 12 ) ntauelectrons++;
            else if( taud1_id == 13 || taud1_id == 14 ) ntaumuons++;
            else if( taud1_id == 15 || taud1_id == 16 ) {
              if( taudaughter1->D1 >= branchParticle->GetEntries() || taudaughter1->D2 >= branchParticle->GetEntries() ){
              continue;
            }

              GenParticle * taugranddaughter1 = (GenParticle*) branchParticle->At( taudaughter1->D1) ;
              GenParticle * taugranddaughter2 = (GenParticle*) branchParticle->At( taudaughter1->D2) ;
              int taugd1_id = abs(taugranddaughter1->PID);
              int taugd2_id = abs(taugranddaughter2->PID);
              //cout << "tau grand daughter = " << taugd1_id << " " << taugd2_id << endl;
              if( taugd1_id == 11 || taugd1_id == 12 ) ntauelectrons++;
              else if( taugd1_id == 13 || taugd1_id == 14 ) ntaumuons++;
            ㅜㅜ  else { continue; }
          
            } else { continue; }
            */
          }else{
            nhadrons++;
          }
          //cout << "nelectrons = " << nelectrons << " nmuons = " << nmuons << " ntaus = " << ntaus << " nhadrons = " << nhadrons << endl;
        }
      }
    }
  
    if( LO ){


    }else{
      int remaining = 0 ;
      int nleptons = nelectrons + nmuons + ntaus;
      if( nleptons == 2 && nhadrons == 0){
         //cout << "dilepton" << endl;
         ndileptonic++;
         if( ntaus ==0 || ( ntaus == 1 && (ntauelectrons+ntaumuons) == 1) || (ntaus == 2 && (ntauelectrons+ntaumuons) == 2)  ) { 
           ndileptonic2++; 
         }  
         if( ntaus == 0) ndileptonic3++;
      }else if( nleptons == 1 && nhadrons == 1){
         //cout << "lepton+jets" << endl;
         nsemileptonic++;
         if( ntaus ==0 || ( ntaus == 1 && (ntauelectrons+ntaumuons) == 1) ) nsemileptonic2++;
         if( ntaus == 0 ) {
           nsemileptonic3++;
           if( nmuons ) {
             h_muon_energy->Fill(genmuon->E, genweight);
             h_lepton_energy->Fill(genmuon->E, genweight);
           }
           if( nelectrons ) {
             h_electron_energy->Fill(genelectron->E, genweight);
             h_lepton_energy->Fill(genelectron->E, genweight);
           }
         }
      }else if ( nleptons == 0 && nhadrons == 2 ){
         //cout << "hadronic" << endl;
         nhadronic++;
      }else{
         //cout << "remaining" << endl;
         remaining++;
      }
    }

    Muon * mymuon;
    Electron * myelectron; 
    bool passmuon = false; 
    bool passelectron = false; 

    if(branchMuon->GetEntries() > 0)
    {
      bool mymuonpass = false;
      for(int i = 0; i < branchMuon->GetEntriesFast() ; i++){ 
        Muon * muon =  (Muon *) branchMuon->At(i);
        if( muon->P4().E() > 20 && fabs( muon->P4().Eta() < 2.4) ){
          mymuon = muon;
          mymuonpass = true;
        }
        break;
      }
     
      if( mymuonpass && ( nmuons > 0 || nelectrons > 0 ) ){ 
        //h_muon_energy_reco->Fill(mymuon->P4().E(), genweight);
        h_lepton_energy_reco->Fill(mymuon->P4().E(), genweight);
        h2_lepton_energy_response->Fill(mymuon->P4().E(), genmuon->E, genweight);
        passmuon = true;
      }

    }

    
    if(branchElectron->GetEntries() > 0)
    {
      bool myelectronpass = false;
      for(int i = 0; i < branchElectron->GetEntriesFast() ; i++){
        Electron * electron =  (Electron *) branchElectron->At(i);
        if( electron->P4().E() > 20 && fabs( electron->P4().Eta() < 2.4) ){
          myelectron = electron;
          myelectronpass = true;
        }
        break;
      }
      if( myelectronpass && ( nmuons > 0 || nelectrons > 0 ) ){
        //h_electron_energy_reco->Fill(myelectron->P4().E(), genweight);
        h_lepton_energy_reco->Fill(myelectron->P4().E(), genweight);
        h2_lepton_energy_response->Fill(myelectron->P4().E(), genelectron->E, genweight);
        passelectron = true;
      }
    }

    if(branchJet->GetEntries() > 0 )
    {
      int njets = 0;
      int nbjets = 0;
      for(int i = 0; i < branchJet->GetEntriesFast() ; i++){
        Jet * jet =  (Jet *) branchJet->At(i);
        if( jet->P4().Pt() > 30 && fabs( jet->P4().Eta() < 2.5) ){
          njets++;
          if( jet->BTag ) nbjets++;
        }
      }
    }

    //Muon_E = -9.0;
    //Electron_E = -9.0;
    //Lepton_E_reco = -1.0;
    float Energy = 9.0;
    if( passelectron && !passmuon && njets >= 4){
      float myele_energy = myelectron->P4().E();
      //h_electron_energy_reco_S2->Fill(myele_energy, genweight);
      //h_lepton_energy_reco_S2->Fill(myele_energy, genweight);
      //h_lepton_nbjets_reco_S2->Fill(nbjets);
      if( nbjets >= 2 ){
        //h_electron_energy_reco_final->Fill(myele_energy, genweight);
        h_lepton_energy_reco_final->Fill(myele_energy, genweight);
        h2_lepton_energy_final_response->Fill(myele_energy, genelectron->E, genweight);
      }
      //lepton_E_final.push_back( myelectron->P4().E() );
      //for(int i=0; i < nmass; i++){
      //  float corr = 1.0/ h_acc->Interpolate( myelectron->P4().E() );
      //  float w = g2[i]->Eval( myelectron->P4().E() );
        //integral2[i] = integral2[i] + w*corr ;
      //}
      //Electron_E = myele_energy;
      //Lepton_E_reco = myele_energy;
    }

    if( passmuon && !passelectron && njets >= 4){
      float mymuon_energy = mymuon->P4().E();
      //h_muon_energy_reco_S2->Fill(mymuon_energy, genweight);
      //h_lepton_energy_reco_S2->Fill(mymuon_energy, genweight);
      //h_lepton_nbjets_reco_S2->Fill(nbjets);
      if( nbjets >= 2  ){
      //  h_muon_energy_reco_final->Fill(mymuon_energy, genweight);
        h_lepton_energy_reco_final->Fill(mymuon_energy, genweight);
        h2_lepton_energy_final_response->Fill(mymuon_energy, genmuon->E, genweight);
      }
      //lepton_E_final.push_back( mymuon->P4().E() );
      //for(int i=0; i < nmass; i++){
      //  float corr = 1.0/ h_acc->Interpolate( mymuon->P4().E() );
      //  float w = g2[i]->Eval( mymuon->P4().E() );
        //integral2[i] = integral2[i] + w*corr ;
      //}
      //Muon_E = mymuon_energy;
      //Lepton_E_reco = mymuon_energy;
    }

/*
    for(int i=0; i < nmass; i++){
    //for(int i=0; i < 0; i++){
      float lenergy = -9;
      if( Muon_E > 0 && Electron_E < 0 ) lenergy = Muon_E;
      if( Muon_E < 0 && Electron_E > 0 ) lenergy = Electron_E;
      float acc = h_acc->Interpolate( lenergy );
      integral2[i] = integral2[i] +  g2[i]->Eval( lenergy ) /acc ;
      integral3[i] = integral3[i] +  g3[i]->Eval( lenergy ) /acc ;
      integral5[i] = integral5[i] +  g5[i]->Eval( lenergy ) /acc ;
      integral15[i] = integral15[i] +  g15[i]->Eval( lenergy ) /acc ;
    }
*/
    //if( passmuon && passelectron) cout << "Lepton E = " << Lepton_E << endl;
    //tree->Fill();
  }

  //tree->Print();
//  for(int m=0; m < nmass; m++){
//    for(int i=0; i < 400;i++){
//      float bincenter = h_lepton_energy->GetBinCenter(i+1);
//      float binconten = h_lepton_energy->GetBinContent(i+1);
//      float weight_value = g2[m]->Eval( bincenter );
//      integral2[m] = integral2[m] + weight_value*binconten;
//    }
//  }

/*
  for(int m=0; m < nmass; m++){
    for(int i=0; i < lepton_E_final.size() ;i++){
      float energy = lepton_E_final[i];
      float corr = 1.0/ h_acc->Interpolate( energy );
      float weight_value2 = g2[m]->Eval( bincenter );
      float weight_value3 = g3[m]->Eval( bincenter );
      float weight_value5 = g5[m]->Eval( bincenter );
      float weight_value15 = g15[m]->Eval( bincenter );
      integral2[m] = integral2[m] + weight_value2*corr;
      integral3[m] = integral3[m] + weight_value3*corr;
      integral5[m] = integral5[m] + weight_value5*corr;
      integral15[m] = integral15[m] + weight_value15*corr;
    }
  }

  TGraph * final2 = new TGraph();
  TGraph * final3 = new TGraph();
  TGraph * final5 = new TGraph();
  TGraph * final15 = new TGraph();
  for (Int_t i=0;i<nmass;i++) {
    final2->SetPoint(i, mymass[i], integral2[i]);
    final3->SetPoint(i, mymass[i], integral3[i]);
    final5->SetPoint(i, mymass[i], integral5[i]);
    final15->SetPoint(i, mymass[i], integral15[i]);
  }
  final2->SetName("n2");
  final3->SetName("n3");
  final5->SetName("n5");
  final15->SetName("n15");
  final2->Write();
  final3->Write();
  final5->Write();
  final15->Write();
*/

  if( remaining != 0 ) cout << "Someting is wrong" << endl;
  //TCanvas * c = new TCanvas("c","c",1000,600);
  channel->SetBinContent(1,ndileptonic);
  channel->SetBinContent(2,ndileptonic2);
  channel->SetBinContent(3,ndileptonic3);
  channel->SetBinContent(4,nsemileptonic);
  channel->SetBinContent(5,nsemileptonic2);
  channel->SetBinContent(6,nsemileptonic3);
  channel->SetBinContent(7,nhadronic);

  channel->GetXaxis()->SetBinLabel(1,"Dileptonic");
  channel->GetXaxis()->SetBinLabel(2,"DileptonicTau");
  channel->GetXaxis()->SetBinLabel(3,"DileptonicNoTau");
  channel->GetXaxis()->SetBinLabel(4,"Semileptonic");
  channel->GetXaxis()->SetBinLabel(5,"SemileptonicTau");
  channel->GetXaxis()->SetBinLabel(6,"SemileptonicNoTau");
  channel->GetXaxis()->SetBinLabel(7,"Hadronic");

  //int nBins = 400;
  //h_lepton_energy->AddBinContent(nBins, h_lepton_energy->GetBinContent(nBins+1));
  //h_lepton_energy_reco_final->AddBinContent(nBins, h_lepton_energy_reco_final->GetBinContent(nBins+1));
  
  // Show resulting histograms
  channel->SetStats(0000);
  double scale = 1.0/numberOfEntries;
  channel->Scale( scale );  
  //channel->Draw("HText0");
/*  
  channel->Write();
  h_muon_energy->Write();
  h_electron_energy->Write();
  h_lepton_energy->Write();

  h_muon_energy_acc->Write();
  h_electron_energy_acc->Write();
  h_lepton_energy_acc->Write();

  h_muon_energy_reco->Write();
  h_electron_energy_reco->Write();
  h_lepton_energy_reco->Write();
 
  h_muon_energy_reco_final->Write();
  h_electron_energy_reco_final->Write();
  h_lepton_energy_reco_final->Write();
*/  
  f->Write();
  f->Close();
}
Ejemplo n.º 24
0
void readTrigger()
{
  TLorentzVector eplus[50], eminus[50];
  TLorentzVector momentum,  momentum_pair;
  TVector3 mom;
  Float_t px, py, pz;
  Int_t pdg;
  Int_t nplus=0, nminus=0, njpsi=0; 

  TH1F *hEl = new TH1F("hEl","number of electrons", 10,0,10);
  TH1F *hPtel = new TH1F("hPtel"," dN/dPt ",100,0,4);
  TH1F *hPel = new TH1F("hPel"," dN/dP ",100,0,30);
   
 
  // Load basic libraries


  gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C");
  basiclibs();
  gSystem->Load("libPhysics");
  
  gSystem->Load("libGeoBase");
  gSystem->Load("libParBase");
  gSystem->Load("libBase");
  gSystem->Load("libCbmBase");
  gSystem->Load("libCbmData");
  gSystem->Load("libJpsi.so");

  Char_t fileName[100];
  Int_t fNevents = 0;
  Int_t fElectronEvents=0; 
  for (Int_t ifile=0; ifile<1; ifile++)
    {
      TFile *f1 = new TFile(Form("jpsitrigger.25gev.pure.0000.root",ifile));
      TTree* t1 =(TTree*) f1->Get("cbmsim");
      TFolder *fd1 =(TFolder*)  f1->Get("cbmout");

      TClonesArray* fJpsi = (TClonesArray*)fd1->FindObjectAny("CbmJpsiTriggerElectron");
      t1->SetBranchAddress("CbmJpsiTriggerElectron",&fJpsi);
      
      
      Int_t nevent = t1->GetEntries();
      cout<<nevent<<endl;
      nplus=0; nminus=0;
      for(Int_t i=0; i<nevent; i++)
	{
	  nplus = 0;  
	  nminus = 0;
	  fNevents++;
	  t1->GetEntry(i);
	  Int_t nel = fJpsi->GetEntries();
	  for ( Int_t iel=0; iel<nel; iel++)
	    { 
	      CbmJpsiTriggerElectron *jel = (CbmJpsiTriggerElectron*)fJpsi->At(iel);
	      mom = jel->GetMomentum();
	      hPel->Fill(mom.Mag());
	      hPtel->Fill(mom.Pt());
	      if (mom.Pt() < 1.2) continue;
	      momentum.SetVectM(mom,0.000511);
	      pdg = jel -> GetPdg();
	      Double_t ann = jel -> GetAnn();
	      Double_t like = jel -> GetLike();
	      Double_t wkn = jel -> GetWkn();
	      Double_t ran = gRandom->Rndm();
	        if(ann > 0.8 ) 
		{
		  eplus[nplus]=momentum; 
		  nplus++;
		  eplus[nplus].SetXYZT(0,0,0,0);

		}	
	    }
	  hEl->Fill(nplus);
	
	  if ( nplus>1 )   fElectronEvents++;  
    } // event loop
 
      f1->Close();
    }

  cout<< " ElectronEvents "<< fElectronEvents<<endl;
 TFile *fmass = new TFile("jpsiTrigger.hist.root","RECREATE");
 
  hEl->Scale(1./Float_t (fNevents));
  hEl->Write();
  hPel->Scale(1./Float_t (fNevents ));
  hPel->Write();
  hPtel->Scale(1./Float_t (fNevents));
  hPtel->Write();
}
Ejemplo n.º 25
0
//!PG main function
int 
  selector (TChain * tree, histos & plots, int if_signal)
{
 
 plots.v_Jet_1_Pt = -99;
 plots.v_Jet_2_Pt = -99;
 plots.v_Jet_3_Pt = -99;
 plots.v_Jet_4_Pt = -99;
 plots.v_Jet_5_Pt = -99;
 plots.v_Jet_6_Pt = -99;

 plots.v_Jet_1_x = -99;
 plots.v_Jet_2_x = -99;
 plots.v_Jet_3_x = -99;
 plots.v_Jet_4_x = -99;
 plots.v_Jet_5_x = -99;
 plots.v_Jet_6_x = -99;

 plots.v_Jet_1_y = -99;
 plots.v_Jet_2_y = -99;
 plots.v_Jet_3_y = -99;
 plots.v_Jet_4_y = -99;
 plots.v_Jet_5_y = -99;
 plots.v_Jet_6_y = -99;

 plots.v_Jet_1_z = -99;
 plots.v_Jet_2_z = -99;
 plots.v_Jet_3_z = -99;
 plots.v_Jet_4_z = -99;
 plots.v_Jet_5_z = -99;
 plots.v_Jet_6_z = -99;

 plots.v_Jet_1_e = -99;
 plots.v_Jet_2_e = -99;
 plots.v_Jet_3_e = -99;
 plots.v_Jet_4_e = -99;
 plots.v_Jet_5_e = -99;
 plots.v_Jet_6_e = -99;
 
 plots.v_Jet_1_eta = -99;
 plots.v_Jet_2_eta = -99;
 plots.v_Jet_3_eta = -99;
 plots.v_Jet_4_eta = -99;
 plots.v_Jet_5_eta = -99;
 plots.v_Jet_6_eta = -99;
 
 plots.v_Jet_1_phi = -99;
 plots.v_Jet_2_phi = -99;
 plots.v_Jet_3_phi = -99;
 plots.v_Jet_4_phi = -99;
 plots.v_Jet_5_phi = -99;
 plots.v_Jet_6_phi = -99;
 
 plots.v_Jet_1_DR = -99;
 plots.v_Jet_2_DR = -99;
 plots.v_Jet_3_DR = -99;
 plots.v_Jet_4_DR = -99;
 plots.v_Jet_5_DR = -99;
 plots.v_Jet_6_DR = -99;
 
 plots.v_numEle = -99;
 plots.v_numMu = -99;
 plots.v_numJets = -99;
 plots.v_totNumJets = -99;
  
 
//  TClonesArray * tagJets = new TClonesArray ("TLorentzVector") ; 
//  tree->SetBranchAddress ("tagJets", &tagJets) ;
 TClonesArray * otherJets_temp = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress (g_KindOfJet.c_str(), &otherJets_temp) ;
//  tree->SetBranchAddress ("otherJets", &otherJets_temp) ;
 
 
 TClonesArray * electrons = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("electrons", &electrons) ;
 TClonesArray * muons = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("muons", &muons) ;
 TClonesArray * MET = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("MET", &MET) ;
 TClonesArray * tracks = new TClonesArray ("TLorentzVector") ;
 tree->SetBranchAddress ("tracks", &tracks) ;
 
 TClonesArray * tagJets = new TClonesArray ("TLorentzVector") ; 
 TClonesArray * otherJets = new TClonesArray ("TLorentzVector") ;
 
 
 TClonesArray * HiggsParticle = new TClonesArray ("TParticle") ;
 tree->SetBranchAddress ("HiggsParticle", &HiggsParticle) ;
 
  
 int EleId[100];
 float IsolEleSumPt_VBF[100];
 int nEle;
 tree->SetBranchAddress ("nEle", &nEle) ;
 tree->SetBranchAddress ("EleId",EleId ) ;
 tree->SetBranchAddress ("IsolEleSumPt_VBF",IsolEleSumPt_VBF ) ;

 float IsolMuTr[100];
 int nMu ;
 tree->SetBranchAddress ("nMu", &nMu) ;
 tree->SetBranchAddress ("IsolMuTr",IsolMuTr ) ;

 int IdEvent;
 tree->SetBranchAddress ("IdEvent", &IdEvent) ;
 
 
 int nentries = (int) tree->GetEntries () ;

 
 plots.passedJetAndLepNumberSelections = 0;
 plots.analyzed = 0;
 
 //PG loop over the events
//  std::cerr << " --- nentries = " << nentries << std::endl;
//  nentries = std::min(10000,nentries);
//  nentries = 10000;
 
 if (g_numEvents!= -1) nentries = std::min(g_numEvents,nentries);

 std::cerr << " --- nentries = " << nentries << std::endl;
 
 for (int evt = 0 ; evt < nentries ; ++evt)
 {
  if (!(evt%1000)) std::cerr << " --- evt = " << evt << std::endl;
  
  plots.v_Jet_1_Pt = -99;
  plots.v_Jet_2_Pt = -99;
  plots.v_Jet_3_Pt = -99;
  plots.v_Jet_4_Pt = -99;
  plots.v_Jet_5_Pt = -99;
  plots.v_Jet_6_Pt = -99;
  plots.v_Jet_7_Pt = -99;
  plots.v_Jet_8_Pt = -99;
  
  plots.v_Jet_1_x = -99;
  plots.v_Jet_2_x = -99;
  plots.v_Jet_3_x = -99;
  plots.v_Jet_4_x = -99;
  plots.v_Jet_5_x = -99;
  plots.v_Jet_6_x = -99;
  plots.v_Jet_7_x = -99;
  plots.v_Jet_8_x = -99;

  plots.v_Jet_1_y = -99;
  plots.v_Jet_2_y = -99;
  plots.v_Jet_3_y = -99;
  plots.v_Jet_4_y = -99;
  plots.v_Jet_5_y = -99;
  plots.v_Jet_6_y = -99;
  plots.v_Jet_7_y = -99;
  plots.v_Jet_8_y = -99;

  plots.v_Jet_1_z = -99;
  plots.v_Jet_2_z = -99;
  plots.v_Jet_3_z = -99;
  plots.v_Jet_4_z = -99;
  plots.v_Jet_5_z = -99;
  plots.v_Jet_6_z = -99;
  plots.v_Jet_7_z = -99;
  plots.v_Jet_8_z = -99;

  plots.v_Jet_1_e = -99;
  plots.v_Jet_2_e = -99;
  plots.v_Jet_3_e = -99;
  plots.v_Jet_4_e = -99;
  plots.v_Jet_5_e = -99;
  plots.v_Jet_6_e = -99;
  plots.v_Jet_7_e = -99;
  plots.v_Jet_8_e = -99;
  
  plots.v_Jet_1_eta = -99;
  plots.v_Jet_2_eta = -99;
  plots.v_Jet_3_eta = -99;
  plots.v_Jet_4_eta = -99;
  plots.v_Jet_5_eta = -99;
  plots.v_Jet_6_eta = -99;
  plots.v_Jet_7_eta = -99;
  plots.v_Jet_8_eta = -99;
 
  plots.v_Jet_1_phi = -99;
  plots.v_Jet_2_phi = -99;
  plots.v_Jet_3_phi = -99;
  plots.v_Jet_4_phi = -99;
  plots.v_Jet_5_phi = -99;
  plots.v_Jet_6_phi = -99;
  plots.v_Jet_7_phi = -99;
  plots.v_Jet_8_phi = -99;

  plots.v_Jet_1_DR = -99;
  plots.v_Jet_2_DR = -99;
  plots.v_Jet_3_DR = -99;
  plots.v_Jet_4_DR = -99;
  plots.v_Jet_5_DR = -99;
  plots.v_Jet_6_DR = -99;
  plots.v_Jet_7_DR = -99;
  plots.v_Jet_8_DR = -99;
 
  plots.v_numEle = -99;
  plots.v_numMu = -99;
  plots.v_numJets = -99;
  plots.v_totNumJets = -99;
  
  tree->GetEntry (evt) ;
  
  tagJets -> Clear () ;  
  otherJets -> Clear () ;    
  
  
  
    //---- check if signal ----
  if (if_signal && (IdEvent!=123 && IdEvent!=124)) continue;
  plots.analyzed++;
  
  
  //---- MC data ----
  std::vector<TLorentzVector*> MCJets ;
  
  TLorentzVector* MCJets_temp[6] ;
  int counter = 0;
  
  if (if_signal && (IdEvent==123 || IdEvent==124)){
   for(int ii=0; ii<9; ii++){
//     if (ii==0 || ii==1){
//     if (ii!=0 && ii!=1 && ii!=2 && ii!=3 && ii!=6){
    if (ii!=2 && ii!=3 && ii!=6){
     TParticle* myparticle = (TParticle*) HiggsParticle->At(ii);
//      std::cerr << "pdg = " << ii << " = " << myparticle->GetPdgCode() << std::endl;
     MCJets_temp[counter] = new TLorentzVector;
     myparticle->Momentum(*(MCJets_temp[counter]));
     MCJets.push_back((MCJets_temp[counter]));
     counter++;
    }
   }
  }
  

  
   //---- find Tagging Jets ----
 
  double m_jetPtMin = 15.;
  double m_jetEtaMax = 5.;
  double m_jetDEtaMin = -1;
  double m_jetMjjMin = -1;
 
  

  std::vector<myJet> goodJets ;

//   std::cerr << std::endl << std::endl << std::endl << std::endl << std::endl;
  
  for (int l=0; l<otherJets_temp->GetEntries (); l++ ){
   TLorentzVector* jet_temp = (TLorentzVector*) otherJets_temp->At(l);
   if (jet_temp->Pt()<m_jetPtMin) continue;
   //---- Eta max threshold ----
   if (jet_temp->Eta()>m_jetEtaMax) continue;
   //---- pt min threshold ----
   myJet dummy (jet_temp, 0, 0) ;
   goodJets.push_back (dummy) ;
  }
  
//   for (int gg=0; gg<goodJets.size(); gg++ ) std::cerr << " goodJets[" << gg << "] = " << &(goodJets.at(gg)) << std::endl;
  
  sort (goodJets.rbegin (), goodJets.rend (), lessThan ()) ;
  
  
  std::vector<std::pair<TLorentzVector*,TLorentzVector*> > Vect_PairQuark_RecoJet;
  std::vector<double> Map2D_PairQuark_RecoJet;

  int counter_map = 0;
    
  for (int rr=0; rr<std::min(g_numJet,static_cast<int>(goodJets.size())); rr++ ){ //--- loop over recoJets ----
   for (int k=0; k<MCJets.size(); k++ ){ //--- loop over quarks ----
    TLorentzVector* quark_temp = MCJets.at(k);
    TLorentzVector* jet_temp = goodJets.at(rr).m_kine;
    double DR = ROOT::Math::VectorUtil::DeltaR(quark_temp->BoostVector(),jet_temp->BoostVector());
    Map2D_PairQuark_RecoJet.push_back(DR);
    counter_map++;
   } //--- end loop over recoJet ----
  } //--- end loop over quarks ----

  

  int selected_pair_jet[6] ;
  int selected_pair_quark[6] ;
  for (int jj=0; jj<MCJets.size(); jj++ ){  
   selected_pair_jet[jj] = -1;
   selected_pair_quark[jj] = -1;
  }
  
  for (int jj=0; jj<MCJets.size(); jj++ ){  
   double DR_min = 1000;
   counter_map = 0;
   int temp_selected_pair_jet = -1;
   int temp_selected_pair_quark = -1;
   for (int rr=0; rr<std::min(g_numJet,static_cast<int>(goodJets.size())); rr++ ){ //--- loop over recoJets ----
    for (int k=0; k<MCJets.size(); k++ ){ //--- loop over quarks ----
     bool already_done = false;
     for (int qq=0; qq<MCJets.size(); qq++) {
      if ((selected_pair_jet[qq] == rr) || (selected_pair_quark[qq] == k)) already_done = true;
     }
     if (!already_done){
      double DR_temp = Map2D_PairQuark_RecoJet.at(counter_map);
      if (DR_temp<DR_min) {
       DR_min = DR_temp;
       temp_selected_pair_jet = rr;
       temp_selected_pair_quark = k;
      }
     }
     counter_map++;
    }
   }
   selected_pair_jet[jj] = temp_selected_pair_jet;
   selected_pair_quark[jj] = temp_selected_pair_quark;
  }  
  
  
  for (int rr=0; rr<std::min(g_numJet,static_cast<int>(goodJets.size())); rr++ ){ //--- loop over recoJets ----
   for (int k=0; k<MCJets.size(); k++ ){ //--- loop over quarks ----
    bool used_one = false;
    for (int qq=0; qq<MCJets.size(); qq++) {
     if ((selected_pair_jet[qq] == rr) && (selected_pair_quark[qq] == k)) used_one = true;
    }
    if (used_one){
     TLorentzVector* quark_temp = MCJets.at(k);
     TLorentzVector* jet_temp = goodJets.at(rr).m_kine;
     std::pair<TLorentzVector*,TLorentzVector*> PairQuark_RecoJet(quark_temp,jet_temp);
     Vect_PairQuark_RecoJet.push_back(PairQuark_RecoJet);
    }
   } //--- end loop over recoJet ----
  } //--- end loop over quarks ----

  
    
    
  for (int iJet=0; iJet<std::min(g_numJet,static_cast<int>(goodJets.size())); iJet++){
   
   double minDR = -1000;
   double eta_reco_temp = goodJets.at (iJet).m_kine->Eta () ;
   double phi_reco_temp = goodJets.at (iJet).m_kine->Phi () ;  
    
   for (int pp=0; pp<static_cast<int>(Vect_PairQuark_RecoJet.size()); pp++ ){
    double eta_1 = Vect_PairQuark_RecoJet.at(pp).second->Eta();
    double phi_1 = Vect_PairQuark_RecoJet.at(pp).second->Phi();

    double DR_temp = deltaR(phi_1,eta_1,phi_reco_temp,eta_reco_temp);
    if (DR_temp<0.001) {
     double eta_2 = Vect_PairQuark_RecoJet.at(pp).first->Eta();
     double phi_2 = Vect_PairQuark_RecoJet.at(pp).first->Phi();
     minDR = deltaR(phi_1,eta_1,phi_2,eta_2);
     break;
    }
   }
    
    
   if (iJet==0) {
    plots.v_Jet_1_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_1_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_1_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_1_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_1_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_1_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_1_DR = minDR;
   }
   if (iJet==1) {
    plots.v_Jet_2_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_2_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_2_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_2_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_2_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_2_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_2_DR = minDR;
   }
   if (iJet==2) {
    plots.v_Jet_3_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_3_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_3_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_3_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_3_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_3_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_3_DR = minDR;
   }
   if (iJet==3) {
    plots.v_Jet_4_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_4_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_4_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_4_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_4_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_4_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_4_DR = minDR;
   }
   if (iJet==4) {
    plots.v_Jet_5_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_5_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_5_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_5_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_5_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_5_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_5_DR = minDR;
   }
   if (iJet==5) {
    plots.v_Jet_6_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_6_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_6_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_6_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_6_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_6_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_6_DR = minDR;
   }
   if (iJet==6) {
    plots.v_Jet_7_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_7_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_7_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_7_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_7_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_7_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_7_DR = minDR;
   }
   if (iJet==7) {
    plots.v_Jet_8_Pt = goodJets.at (iJet).m_kine->Pt () ;
    plots.v_Jet_8_x = goodJets.at (iJet).m_kine->X () ;
    plots.v_Jet_8_y = goodJets.at (iJet).m_kine->Y () ;
    plots.v_Jet_8_z = goodJets.at (iJet).m_kine->Z () ;
    plots.v_Jet_8_eta = goodJets.at (iJet).m_kine->Eta () ;
    plots.v_Jet_8_phi = goodJets.at (iJet).m_kine->Phi () ;
    plots.v_Jet_8_DR = minDR;
   }
  }  
  
  
  int numJets = goodJets.size();
  plots.v_numJets = numJets;
  plots.v_totNumJets = static_cast<double>(otherJets_temp->GetEntries ());
 
  
  
  //---- leptons ----
  
  plots.v_numEle = 0;
  plots.v_numMu = 0;
 
  std::vector<lepton> leptons ;
            
  //---- AM ---- loop over electrons
  for (int iele = 0; iele < electrons->GetEntries () ; ++iele)
  {
   TLorentzVector * theEle = (TLorentzVector*) (electrons->At (iele)) ;
   lepton dummy (theEle, 0, iele) ;
   leptons.push_back (dummy) ;
  } 

  //---- AM ---- loop over muons
  for (int imu = 0 ; imu < nMu ; ++imu)
  {
   TLorentzVector * theMu = (TLorentzVector*) (muons->At (imu)) ;
   lepton dummy (theMu, 1, imu) ;
   leptons.push_back (dummy) ;
  }
  

  for (int ilep=0 ; ilep < leptons.size () ; ++ilep){
   if (leptons.at (ilep).m_flav == 0) {//PG electron
    plots.v_numEle += 1;
   }
   if (leptons.at (ilep).m_flav == 1) {//PG muon
    plots.v_numMu += 1;
   }
  }
  
  
  plots.m_tree_selections->Fill();
  if (numJets >=6 ) plots.passedJetAndLepNumberSelections++;
  

  for (int hh=0; hh<counter; hh++) delete MCJets_temp[hh];
  
 } //PG loop over the events

//  std::cerr << "---- Finishes ----" << std::endl;
 
 g_OutputFile->cd(0);
 plots.m_efficiency->Fill();
 plots.m_efficiency->Write();
 plots.m_tree_selections->Write();

//  std::cerr << "---- Written ----" << std::endl;
 
 delete otherJets_temp ;
 delete tagJets  ;  
 delete otherJets  ;
 delete electrons  ;
 delete muons  ;    
 delete MET  ;      
 delete tracks  ;   

//  std::cerr << "---- Deleted ----" << std::endl;
 
 return 0;
  
}
Ejemplo n.º 26
0
void selectAntiWm(const TString conf="wm.conf", // input file
              const TString outputDir="."       // output directory
) {
  gBenchmark->Start("selectAntiWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.4;
  const Double_t MUON_MASS = 0.105658369;

  const Double_t VETO_PT   = 10;
  const Double_t VETO_ETA  = 2.4;

  const Int_t BOSON_ID  = 24;
  const Int_t LEPTON_ID = 13;

  // load trigger menu
  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");

  // load pileup reweighting file
  TFile *f_rw = TFile::Open("../Tools/pileup_weights_2015B.root", "read");
  TH1D *h_rw = (TH1D*) f_rw->Get("npv_rw");

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString>  snamev;      // sample name (for output files)  
  vector<CSample*> samplev;     // data/MC samples

  //
  // parse .conf file
  //
  confParse(conf, snamev, samplev);
  const Bool_t hasData = (samplev[0]->fnamev.size()>0);

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  const TString ntupDir = outputDir + TString("/ntuples");
  gSystem->mkdir(ntupDir,kTRUE);
  
  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  UInt_t  id_1, id_2;
  Double_t x_1, x_2, xPDF_1, xPDF_2;
  Double_t scalePDF, weightPDF;
  TLorentzVector *genV=0, *genLep=0;
  Float_t genVPt, genVPhi, genVy, genVMass;
  Float_t genLepPt, genLepPhi;
  Float_t scale1fb, puWeight;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Float_t tkMet, tkMetPhi, tkSumEt, tkMt, tkU1, tkU2;
  Float_t mvaMet, mvaMetPhi, mvaSumEt, mvaMt, mvaU1, mvaU2;
  Int_t   q;
  TLorentzVector *lep=0;
  ///// muon specific /////
  Float_t trkIso, emIso, hadIso;
  Float_t pfChIso, pfGamIso, pfNeuIso, pfCombIso;
  Float_t d0, dz;
  Float_t muNchi2;
  UInt_t nPixHits, nTkLayers, nValidHits, nMatch, typeBits;
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo *info  = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen  = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *muonArr    = new TClonesArray("baconhep::TMuon");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;
  
  //
  // loop over samples
  //  
  for(UInt_t isam=0; isam<samplev.size(); isam++) {
    
    // Assume data sample is first sample in .conf file
    // If sample is empty (i.e. contains no ntuple files), skip to next sample
    Bool_t isData=kFALSE;
    if(isam==0 && !hasData) continue;
    else if (isam==0) isData=kTRUE;
    
    // Assume signal sample is given name "wm"
    Bool_t isSignal = (snamev[isam].CompareTo("wm",TString::kIgnoreCase)==0);
    // flag to reject W->mnu events when selecting wrong-flavor background events
    Bool_t isWrongFlavor = (snamev[isam].CompareTo("wx",TString::kIgnoreCase)==0);  
    
    CSample* samp = samplev[isam];
  
    //
    // Set up output ntuple
    //
    TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.root");
    TFile *outFile = new TFile(outfilename,"RECREATE"); 
    TTree *outTree = new TTree("Events","Events");

    outTree->Branch("runNum",     &runNum,     "runNum/i");     // event run number
    outTree->Branch("lumiSec",    &lumiSec,    "lumiSec/i");    // event lumi section
    outTree->Branch("evtNum",     &evtNum,     "evtNum/i");     // event number
    outTree->Branch("npv",        &npv,        "npv/i");        // number of primary vertices
    outTree->Branch("npu",        &npu,        "npu/i");        // number of in-time PU events (MC)
    outTree->Branch("id_1",       &id_1,       "id_1/i");       // PDF info -- parton ID for parton 1
    outTree->Branch("id_2",       &id_2,       "id_2/i");       // PDF info -- parton ID for parton 2
    outTree->Branch("x_1",        &x_1,        "x_1/d");        // PDF info -- x for parton 1
    outTree->Branch("x_2",        &x_2,        "x_2/d");        // PDF info -- x for parton 2
    outTree->Branch("xPDF_1",     &xPDF_1,     "xPDF_1/d");     // PDF info -- x*F for parton 1
    outTree->Branch("xPDF_2",     &xPDF_2,     "xPDF_2/d");     // PDF info -- x*F for parton 2
    outTree->Branch("scalePDF",   &scalePDF,   "scalePDF/d");   // PDF info -- energy scale of parton interaction
    outTree->Branch("weightPDF",  &weightPDF,  "weightPDF/d");  // PDF info -- PDF weight
    outTree->Branch("genV",       "TLorentzVector", &genV);     // GEN boson 4-vector (signal MC)
    outTree->Branch("genLep",     "TLorentzVector", &genLep);   // GEN lepton 4-vector (signal MC)
    outTree->Branch("genVPt",     &genVPt,     "genVPt/F");     // GEN boson pT (signal MC)
    outTree->Branch("genVPhi",    &genVPhi,    "genVPhi/F");    // GEN boson phi (signal MC)
    outTree->Branch("genVy",      &genVy,      "genVy/F");      // GEN boson rapidity (signal MC)
    outTree->Branch("genVMass",   &genVMass,   "genVMass/F");   // GEN boson mass (signal MC)
    outTree->Branch("genLepPt",   &genLepPt,   "genLepPt/F");   // GEN lepton pT (signal MC)
    outTree->Branch("genLepPhi",  &genLepPhi,  "genLepPhi/F");  // GEN lepton phi (signal MC)
    outTree->Branch("scale1fb",   &scale1fb,   "scale1fb/F");   // event weight per 1/fb (MC)
    outTree->Branch("puWeight",   &puWeight,   "puWeight/F");    // scale factor for pileup reweighting (MC)
    outTree->Branch("met",        &met,        "met/F");        // MET
    outTree->Branch("metPhi",     &metPhi,     "metPhi/F");     // phi(MET)
    outTree->Branch("sumEt",      &sumEt,      "sumEt/F");      // Sum ET
    outTree->Branch("mt",         &mt,         "mt/F");         // transverse mass
    outTree->Branch("u1",         &u1,         "u1/F");         // parallel component of recoil
    outTree->Branch("u2",         &u2,         "u2/F");         // perpendicular component of recoil
    outTree->Branch("tkMet",      &tkMet,      "tkMet/F");      // MET (track MET)
    outTree->Branch("tkMetPhi",   &tkMetPhi,   "tkMetPhi/F");   // phi(MET) (track MET)
    outTree->Branch("tkSumEt",    &tkSumEt,    "tkSumEt/F");    // Sum ET (track MET)
    outTree->Branch("tkMt",       &tkMt,       "tkMt/F");       // transverse mass (track MET)
    outTree->Branch("tkU1",       &tkU1,       "tkU1/F");       // parallel component of recoil (track MET)
    outTree->Branch("tkU2",       &tkU2,       "tkU2/F");       // perpendicular component of recoil (track MET)
    outTree->Branch("mvaMet",     &mvaMet,     "mvaMet/F");     // MVA MET
    outTree->Branch("mvaMetPhi",  &mvaMetPhi,  "mvaMetPhi/F");  // phi(MVA MET)
    outTree->Branch("mvaSumEt",   &mvaSumEt,   "mvaSumEt/F");   // Sum ET (MVA MET)
    outTree->Branch("mvaMt",      &mvaMt,      "mvaMt/F");      // transverse mass (MVA MET)
    outTree->Branch("mvaU1",      &mvaU1,      "mvaU1/F");      // parallel component of recoil (mva MET)
    outTree->Branch("mvaU2",      &mvaU2,      "mvaU2/F");      // perpendicular component of recoil (mva MET)
    outTree->Branch("q",          &q,          "q/I");          // lepton charge
    outTree->Branch("lep",        "TLorentzVector", &lep);      // lepton 4-vector
    ///// muon specific /////
    outTree->Branch("trkIso",     &trkIso,     "trkIso/F");     // track isolation of lepton
    outTree->Branch("emIso",      &emIso,      "emIso/F");      // ECAL isolation of lepton
    outTree->Branch("hadIso",     &hadIso,     "hadIso/F");     // HCAL isolation of lepton
    outTree->Branch("pfChIso",    &pfChIso,    "pfChIso/F");    // PF charged hadron isolation of lepton
    outTree->Branch("pfGamIso",   &pfGamIso,   "pfGamIso/F");   // PF photon isolation of lepton
    outTree->Branch("pfNeuIso",   &pfNeuIso,   "pfNeuIso/F");   // PF neutral hadron isolation of lepton
    outTree->Branch("pfCombIso",  &pfCombIso,  "pfCombIso/F");  // PF combined isolation of lepton
    outTree->Branch("d0",         &d0,         "d0/F");         // transverse impact parameter of lepton
    outTree->Branch("dz",         &dz,         "dz/F");         // longitudinal impact parameter of lepton
    outTree->Branch("muNchi2",    &muNchi2,    "muNchi2/F");    // muon fit normalized chi^2 of lepton
    outTree->Branch("nPixHits",   &nPixHits,   "nPixHits/i");   // number of pixel hits of muon
    outTree->Branch("nTkLayers",  &nTkLayers,  "nTkLayers/i");  // number of tracker layers of muon
    outTree->Branch("nMatch",     &nMatch,     "nMatch/i");     // number of matched segments of muon	 
    outTree->Branch("nValidHits", &nValidHits, "nValidHits/i"); // number of valid muon hits of muon 
    outTree->Branch("typeBits",   &typeBits,   "typeBits/i");   // number of valid muon hits of muon 
    
    //
    // loop through files
    //
    const UInt_t nfiles = samp->fnamev.size();
    for(UInt_t ifile=0; ifile<nfiles; ifile++) {  

      // Read input file and get the TTrees
      cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... "; cout.flush();
      infile = TFile::Open(samp->fnamev[ifile]); 
      assert(infile);
      
      Bool_t hasJSON = kFALSE;
      baconhep::RunLumiRangeMap rlrm;
      if(samp->jsonv[ifile].CompareTo("NONE")!=0) { 
	hasJSON = kTRUE;
	rlrm.addJSONFile(samp->jsonv[ifile].Data()); 
      }

      eventTree = (TTree*)infile->Get("Events");
      assert(eventTree);
      eventTree->SetBranchAddress("Info", &info);    TBranch *infoBr = eventTree->GetBranch("Info");
      eventTree->SetBranchAddress("Muon", &muonArr); TBranch *muonBr = eventTree->GetBranch("Muon");
      eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");
      Bool_t hasGen = eventTree->GetBranchStatus("GenEvtInfo");
      TBranch *genBr=0, *genPartBr=0;
      if(hasGen) {
        eventTree->SetBranchAddress("GenEvtInfo", &gen); genBr = eventTree->GetBranch("GenEvtInfo");
        eventTree->SetBranchAddress("GenParticle",&genPartArr); genPartBr = eventTree->GetBranch("GenParticle");
      }
    
      // Compute MC event weight per 1/fb
      const Double_t xsec = samp->xsecv[ifile];
      Double_t totalWeight=0;

      if (hasGen) {
	TH1D *hall = new TH1D("hall", "", 1,0,1);
	eventTree->Draw("0.5>>hall", "GenEvtInfo->weight");
	totalWeight=hall->Integral();
	delete hall;
	hall=0;
      }

      //
      // loop over events
      //
      Double_t nsel=0, nselvar=0;
      for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
        infoBr->GetEntry(ientry);

	if(ientry%1000000==0) cout << "Processing event " << ientry << ". " << (double)ientry/(double)eventTree->GetEntries()*100 << " percent done with this file." << endl;

        Double_t weight=1;
        if(xsec>0 && totalWeight>0) weight = xsec/totalWeight;
	if(hasGen) {
          genPartArr->Clear();
          genBr->GetEntry(ientry);
          genPartBr->GetEntry(ientry);
	  weight*=gen->weight;
        }

        // veto w -> xv decays for signal and w -> mv for bacground samples (needed for inclusive WToLNu sample)
        if (isWrongFlavor && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))==LEPTON_ID) continue;
	else if (isSignal && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
        
	// check for certified lumi (if applicable)
        baconhep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
        if(hasJSON && !rlrm.hasRunLumi(rl)) continue;  

        // trigger requirement               
	if (!isMuonTrigger(triggerMenu, info->triggerBits)) continue;
      
        // good vertex requirement
        if(!(info->hasGoodPV)) continue;

        //
	// SELECTION PROCEDURE:
	//  (1) Look for 1 good muon matched to trigger
	//  (2) Reject event if another muon is present passing looser cuts
	//
	muonArr->Clear();
        muonBr->GetEntry(ientry);

	Int_t nLooseLep=0;
	const baconhep::TMuon *goodMuon=0;
	Bool_t passSel=kFALSE;

        for(Int_t i=0; i<muonArr->GetEntriesFast(); i++) {
          const baconhep::TMuon *mu = (baconhep::TMuon*)((*muonArr)[i]);

          if(fabs(mu->eta) > VETO_PT)  continue; // loose lepton |eta| cut
          if(mu->pt        < VETO_ETA) continue; // loose lepton pT cut
//          if(passMuonLooseID(mu)) nLooseLep++; // loose lepton selection
          if(nLooseLep>1) {  // extra lepton veto
            passSel=kFALSE;
            break;
          }
          
          if(fabs(mu->eta) > ETA_CUT)         continue; // lepton |eta| cut
          if(mu->pt < PT_CUT)                 continue; // lepton pT cut   
          if(!passAntiMuonID(mu))             continue; // lepton anti-selection
          if(!isMuonTriggerObj(triggerMenu, mu->hltMatchBits, kFALSE)) continue;
	  
	  passSel=kTRUE;
	  goodMuon = mu;
	}

	if(passSel) {	  
	  /******** We have a W candidate! HURRAY! ********/
	  nsel+=weight;
          nselvar+=weight*weight;
	  
	  TLorentzVector vLep; 
	  vLep.SetPtEtaPhiM(goodMuon->pt, goodMuon->eta, goodMuon->phi, MUON_MASS);

	  //
	  // Fill tree
	  //
	  runNum   = info->runNum;
	  lumiSec  = info->lumiSec;
	  evtNum   = info->evtNum;
	  
	  vertexArr->Clear();
	  vertexBr->GetEntry(ientry);

	  npv      = vertexArr->GetEntries();
	  npu	   = info->nPUmean;
	  genV      = new TLorentzVector(0,0,0,0);
          genLep    = new TLorentzVector(0,0,0,0);
	  genVPt    = -999;
          genVPhi   = -999;
          genVy     = -999;
          genVMass  = -999;
          u1        = -999;
          u2        = -999;
          tkU1      = -999;
          tkU2      = -999;
	  mvaU1     = -999;
          mvaU2     = -999;
          id_1      = -999;
          id_2      = -999;
          x_1       = -999;
          x_2       = -999;
          xPDF_1    = -999;
          xPDF_2    = -999;
          scalePDF  = -999;
          weightPDF = -999;

	  if(isSignal && hasGen) {
	    TLorentzVector *gvec=new TLorentzVector(0,0,0,0);
            TLorentzVector *glep1=new TLorentzVector(0,0,0,0);
            TLorentzVector *glep2=new TLorentzVector(0,0,0,0);
	    toolbox::fillGen(genPartArr, BOSON_ID, gvec, glep1, glep2,1);

            if (gvec && glep1) {
	      genV      = new TLorentzVector(0,0,0,0);
              genV->SetPtEtaPhiM(gvec->Pt(),gvec->Eta(),gvec->Phi(),gvec->M());
              genLep    = new TLorentzVector(0,0,0,0);
              genLep->SetPtEtaPhiM(glep1->Pt(),glep1->Eta(),glep1->Phi(),glep1->M());
              genVPt    = gvec->Pt();
              genVPhi   = gvec->Phi();
              genVy     = gvec->Rapidity();
              genVMass  = gvec->M();
              genLepPt  = glep1->Pt();
              genLepPhi = glep1->Phi();

	      TVector2 vWPt((genVPt)*cos(genVPhi),(genVPt)*sin(genVPhi));
	      TVector2 vLepPt(vLep.Px(),vLep.Py());
	      
	      TVector2 vMet((info->pfMETC)*cos(info->pfMETCphi), (info->pfMETC)*sin(info->pfMETCphi));
	      TVector2 vU = -1.0*(vMet+vLepPt);
	      u1 = ((vWPt.Px())*(vU.Px()) + (vWPt.Py())*(vU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      u2 = ((vWPt.Px())*(vU.Py()) - (vWPt.Py())*(vU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|

	      TVector2 vTkMet((info->trkMET)*cos(info->trkMETphi), (info->trkMET)*sin(info->trkMETphi));
	      TVector2 vTkU = -1.0*(vTkMet+vLepPt);
	      tkU1 = ((vWPt.Px())*(vTkU.Px()) + (vWPt.Py())*(vTkU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      tkU2 = ((vWPt.Px())*(vTkU.Py()) - (vWPt.Py())*(vTkU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|
	      
	      TVector2 vMvaMet((info->mvaMET)*cos(info->mvaMETphi), (info->mvaMET)*sin(info->mvaMETphi));
	      TVector2 vMvaU = -1.0*(vMvaMet+vLepPt);
	      mvaU1 = ((vWPt.Px())*(vMvaU.Px()) + (vWPt.Py())*(vMvaU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      mvaU2 = ((vWPt.Px())*(vMvaU.Py()) - (vWPt.Py())*(vMvaU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|
          
            }
	    id_1      = gen->id_1;
            id_2      = gen->id_2;
            x_1       = gen->x_1;
            x_2       = gen->x_2;
            xPDF_1    = gen->xPDF_1;
            xPDF_2    = gen->xPDF_2;
            scalePDF  = gen->scalePDF;
            weightPDF = gen->weight;

	    delete gvec;
            delete glep1;
            delete glep2;
            gvec=0; glep1=0; glep2=0;
	  }
	  scale1fb = weight;
	  puWeight = h_rw->GetBinContent(info->nPUmean+1);
	  met	   = info->pfMETC;
	  metPhi   = info->pfMETCphi;
	  sumEt    = 0;
	  mt       = sqrt( 2.0 * (vLep.Pt()) * (info->pfMETC) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->pfMETCphi))) );
	  tkMet    = info->trkMET;
          tkMetPhi = info->trkMETphi;
          tkSumEt  = 0;
          tkMt     = sqrt( 2.0 * (vLep.Pt()) * (info->trkMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->trkMETphi))) );
	  mvaMet   = info->mvaMET;
          mvaMetPhi = info->mvaMETphi;
          mvaSumEt  = 0;
          mvaMt     = sqrt( 2.0 * (vLep.Pt()) * (info->mvaMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->mvaMETphi))) );
	  q        = goodMuon->q;
	  lep      = &vLep;
	  
	  ///// muon specific /////
	  trkIso     = goodMuon->trkIso;
          emIso      = goodMuon->ecalIso;
          hadIso     = goodMuon->hcalIso;
          pfChIso    = goodMuon->chHadIso;
          pfGamIso   = goodMuon->gammaIso;
          pfNeuIso   = goodMuon->neuHadIso;
          pfCombIso  = goodMuon->chHadIso + TMath::Max(goodMuon->neuHadIso + goodMuon->gammaIso -
						       0.5*(goodMuon->puIso),Double_t(0));
	  d0         = goodMuon->d0;
	  dz         = goodMuon->dz;
	  muNchi2    = goodMuon->muNchi2;
	  nPixHits   = goodMuon->nPixHits;
	  nTkLayers  = goodMuon->nTkLayers;
	  nMatch     = goodMuon->nMatchStn;
	  nValidHits = goodMuon->nValidHits;
	  typeBits   = goodMuon->typeBits;

	  outTree->Fill();
	  delete genV;
	  delete genLep;
	  genV=0, genLep=0, lep=0;
        }
      }
      delete infile;
      infile=0, eventTree=0;    

      cout << nsel  << " +/- " << sqrt(nselvar);
      if(isam!=0) cout << " per 1/fb";
      cout << endl;
    }
    outFile->Write();
    outFile->Close();
  }
  delete h_rw;
  delete f_rw;
  delete info;
  delete gen;
  delete genPartArr;
  delete muonArr;
  delete vertexArr;
      
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " W -> mu nu" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << endl;
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectAntiWm"); 
}
Ejemplo n.º 27
0
TPCTOFpid(const Char_t *filename, Int_t evMax = kMaxInt, Int_t startEv = 0)
{
  
  /* include path for ACLic */
  gSystem->AddIncludePath("-I$ALICE_ROOT/include");
  gSystem->AddIncludePath("-I$ALICE_ROOT/TOF");
  /* load libraries */
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  /* build analysis task class */
  gROOT->LoadMacro("AliAnalysisParticle.cxx+g");
  gROOT->LoadMacro("AliAnalysisEvent.cxx+g");
  gROOT->LoadMacro("AliAnalysisTrack.cxx+g");

  /* open file, get tree and connect */
  TFile *filein = TFile::Open(filename);
  TTree *treein = (TTree *)filein->Get("aodTree");
  printf("got \"aodTree\": %d entries\n", treein->GetEntries());
  AliAnalysisEvent *analysisEvent = new AliAnalysisEvent();
  TClonesArray *analysisTrackArray = new TClonesArray("AliAnalysisTrack");
  AliAnalysisTrack *analysisTrack = NULL;
  treein->SetBranchAddress("AnalysisEvent", &analysisEvent);
  treein->SetBranchAddress("AnalysisTrack", &analysisTrackArray);

  /**************************************************************/
  /*** HISTOS ***************************************************/
  /**************************************************************/

  /* run-time binning */
  for (Int_t ibin = 0; ibin < NsigmaBins + 1; ibin++)
    sigmaBin[ibin] = sigmaMin + ibin * sigmaStep;

  /* THnSparse */
  THnSparse *hTPCTOFpid[AliPID::kSPECIES][kNCharges];
  for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++) {
    for (Int_t icharge = 0; icharge< kNCharges; icharge++) {
      hTPCTOFpid[ipart][icharge] = new THnSparseF(Form("hTPCTOFpid_%s_%s", AliPID::ParticleName(ipart), chargeName[icharge]), "", kNHistoParams, NparamsBins);
      for (Int_t iparam = 0; iparam < kNHistoParams; iparam++) {
	hTPCTOFpid[ipart][icharge]->SetBinEdges(iparam, paramBin[iparam]);
      }
    }
  }

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

  /* TOF PID response */
  AliTOFPIDResponse tofResponse;
  tofResponse.SetTimeResolution(tofReso);
  /* TPC PID response */
  AliTPCPIDResponse *tpcResponse = AliAnalysisTrack::GetTPCResponse();

  /* start stopwatch */
  TStopwatch timer;
  timer.Start();

  /* loop over events */
  Bool_t hastofpid;
  Int_t charge, index;
  UShort_t dedxN;
  Double_t ptpc, dedx, bethe, deltadedx, dedx_sigma, tpcsignal;
  Double_t p, time, time_sigma, timezero, timezero_sigma, tof, tof_sigma, texp, texp_sigma, deltat, deltat_sigma, tofsignal;
  Double_t tpctofsignal;
  Double_t param[kNHistoParams];
  for (Int_t iev = startEv; iev < treein->GetEntries() && iev < evMax; iev++) {
    /* get event */
    treein->GetEvent(iev);
    if (iev % 100 == 0) printf("iev = %d\n", iev);
    /* check vertex */
    if (!analysisEvent->AcceptVertex()) continue;
    /* check collision candidate */
    if (!analysisEvent->IsCollisionCandidate()) continue;
    /* check centrality quality */
    if (analysisEvent->GetCentralityQuality() != 0.) continue;

    /*** ACCEPTED EVENT ***/

    /* apply time-zero TOF correction */
    analysisEvent->ApplyTimeZeroTOFCorrection();

    /* get centrality */
    param[kCentrality] = analysisEvent->GetCentralityPercentile(AliAnalysisEvent::kCentEst_V0M);

    /* loop over tracks */
    for (Int_t itrk = 0; itrk < analysisTrackArray->GetEntries(); itrk++) {
      /* get track */
      analysisTrack = (AliAnalysisTrack *)analysisTrackArray->At(itrk);
      if (!analysisTrack) continue;
      /* check accepted track */
      if (!analysisTrack->AcceptTrack()) continue;
      /* get charge */
      charge = analysisTrack->GetSign() > 0. ? kPositive : kNegative;

      /*** ACCEPTED TRACK ***/
      
      /* check TOF pid */
      if (!analysisTrack->HasTOFPID() || !analysisTrack->HasTPCPID()) continue;
      
      /*** ACCEPTED TRACK WITH TPC+TOF PID ***/

      /* apply expected time correction */
      analysisTrack->ApplyTOFExpectedTimeCorrection();
      
      /* get track info */
      p = analysisTrack->GetP();
      param[kPt] = analysisTrack->GetPt();

      /* get TPC info */
      dedx = analysisTrack->GetTPCdEdx();
      dedxN = analysisTrack->GetTPCdEdxN();
      ptpc = analysisTrack->GetTPCmomentum();
      
      /* get TOF info */
      time = analysisTrack->GetTOFTime();
      time_sigma = tofReso;
      timezero = analysisEvent->GetTimeZeroTOF(p);
      timezero_sigma = analysisEvent->GetTimeZeroTOFSigma(p);
      tof = time - timezero;
      tof_sigma = TMath::Sqrt(time_sigma * time_sigma + timezero_sigma * timezero_sigma);

      /* loop over particle IDs */
      for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++) {
	
	/* check rapidity */
	if (TMath::Abs(analysisTrack->GetY(AliPID::ParticleMass(ipart))) > 0.5) continue;

	/*** ACCEPTED TRACK WITHIN CORRECT RAPIDITY ***/
	
	/* TPC signal */
	bethe = tpcResponse->GetExpectedSignal(ptpc, ipart);
	deltadedx = dedx - bethe;
	dedx_sigma = tpcResponse->GetExpectedSigma(ptpc, dedxN, ipart);
	tpcsignal = deltadedx / dedx_sigma;
	param[kTPCsignal] = tpcsignal;
	
	/* TOF expected time */
	texp = analysisTrack->GetTOFExpTime(ipart);
	texp_sigma = analysisTrack->GetTOFExpTimeSigma(ipart);
	
	/* TOF signal */
	deltat = tof - texp;
	deltat_sigma = TMath::Sqrt(tof_sigma * tof_sigma + texp_sigma * texp_sigma);
	tofsignal = deltat / deltat_sigma;
	param[kTOFsignal] = tofsignal;

	/* TPC+TOF signal */
	tpctofsignal = TMath::Sqrt(tpcsignal * tpcsignal + tofsignal * tofsignal);
	param[kTPCTOFsignal] = tpctofsignal;

	/* fill histo */
	hTPCTOFpid[ipart][charge]->Fill(param);

      } /* end of loop over particle IDs */      
    } /* end of loop over tracks */
  } /* end of loop over events */
  
  /* start stopwatch */
  timer.Stop();
  timer.Print();
  
  /* output */
  TFile *fileout = TFile::Open(Form("TPCTOFpid.%s", filename), "RECREATE");
  for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++) {
    for (Int_t icharge = 0; icharge < kNCharges; icharge++) {
      hTPCTOFpid[ipart][icharge]->Write();
    }
  }
  fileout->Close();
  
}
Ejemplo n.º 28
0
void MakeBJetEfficiencyNtuple(const string inputFilename, const string outputFilename, int denominatorType = 0)
{  
  gBenchmark->Start("WWTemplate");

  //*****************************************************************************************
  //Define Data Era
  //*****************************************************************************************
  UInt_t DataEra = kDataEra_NONE;
  DataEra = kDataEra_2012_MC;

  cout << "using DataEra = " << DataEra << endl;


  //*****************************************************************************************
  //Setup Output Tree
  //*****************************************************************************************
  TFile *outputFile = new TFile(outputFilename.c_str(), "RECREATE");
  cmsana::EfficiencyTree *effTree = new cmsana::EfficiencyTree;
  effTree->CreateTree();
  effTree->tree_->SetAutoFlush(0);

  UInt_t NDenominatorsFilled = 0;
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  
  
  //
  // Access samples and fill histograms
  TTree *eventTree=0;  
   
  // Data structures to store info from TTrees
  cmsana::TEventInfo *info    = new cmsana::TEventInfo();
  TClonesArray *jetArr = new TClonesArray("cmsana::TJet");
  TClonesArray *pfcandidateArr = new TClonesArray("cmsana::TPFCandidate");
  TClonesArray *genparticleArr = new TClonesArray("cmsana::TGenParticle");
  TClonesArray *genjetArr = new TClonesArray("cmsana::TGenJet");

  Int_t NEvents = 0;



  //********************************************************
  // Get Tree
  //********************************************************
  eventTree = getTreeFromFile(inputFilename.c_str(),"Events"); 
  TBranch *infoBr;
  TBranch *jetBr;
  TBranch *pfcandidateBr;
  TBranch *genparticleBr;
  TBranch *genjetBr;
  
  
  //*****************************************************************************************
  //Loop over Data Tree
  //*****************************************************************************************
  // Set branch address to structures that will store the info  
  eventTree->SetBranchAddress("Info",       &info);  infoBr       = eventTree->GetBranch("Info");
  eventTree->SetBranchAddress("PFJet", &jetArr); jetBr  = eventTree->GetBranch("PFJet");
  eventTree->SetBranchAddress("PFCandidate", &pfcandidateArr); pfcandidateBr = eventTree->GetBranch("PFCandidate");
  eventTree->SetBranchAddress("GenParticle", &genparticleArr); genparticleBr = eventTree->GetBranch("GenParticle");
  eventTree->SetBranchAddress("GenJet", &genjetArr); genjetBr = eventTree->GetBranch("GenJet");

  cout << "InputFile " << inputFilename << " --- Total Events : " << eventTree->GetEntries() << endl;
  for(UInt_t ientry=0; ientry < eventTree->GetEntries(); ientry++) {       	
    infoBr->GetEntry(ientry);
		
    if (ientry % 100 == 0) cout << "Event " << ientry << endl;

    Double_t eventweight = info->eventweight;

    //********************************************************
    // Load the branches
    //********************************************************
    jetArr->Clear(); 
    pfcandidateArr->Clear(); 
    genparticleArr->Clear(); 
    genjetArr->Clear(); 
    jetBr->GetEntry(ientry);
    pfcandidateBr->GetEntry(ientry);
    genparticleBr->GetEntry(ientry);
    genjetBr->GetEntry(ientry);
 

    //********************************************************
    // Pileup Energy Density
    //********************************************************
    Double_t rho = info->RhoKt6PFJets;
    UInt_t EAEra = kDataEra_2012_Data;


    if (denominatorType == 0) {
    //********************************************************
    // genjets denominator
    //********************************************************
      for(Int_t k=0; k<genjetArr->GetEntries(); k++) {
        const cmsana::TGenJet *genjet = (cmsana::TGenJet*)((*genjetArr)[k]);

        //some kinematic cuts to save ntupling time
        if (!(genjet->pt > 30)) continue;
        if (!(fabs(genjet->eta) < 2.5)) continue;        

        bool pass = false;
        //Find matching jet
        for(Int_t i=0; i<jetArr->GetEntriesFast(); i++) {
          const cmsana::TJet *jet = (cmsana::TJet*)((*jetArr)[i]);
          if (!(jet->pt > 20)) continue;
          if (!(fabs(jet->eta) < 2.5)) continue;
          
          //match in dR?
          double DR = cmsana::deltaR(jet->eta,jet->phi,genjet->eta,genjet->phi);
          if (!(DR < 0.5)) continue;

          if (!(jet->CombinedSecondaryVertexBJetTagsDisc > 0.679)) continue;
          
          pass = true;
          break;
        }
        
        effTree->weight = eventweight;
        effTree->mass = 0;
        effTree->pt = genjet->pt;
        effTree->eta = genjet->eta;
        effTree->phi = genjet->phi;
        effTree->rho = info->RhoKt6PFJets;
        effTree->q = 0;
        effTree->npv = info->nGoodPV;
        effTree->npu = info->nPU;
        effTree->matchedPdgId = genjet->matchedPdgId;
        effTree->run = info->runNum;
        effTree->lumi = info->lumiSec;
        effTree->event = info->evtNum;
        effTree->pass = pass;

        //***********************
        //Fill Denominator
        //***********************
        NDenominatorsFilled++;
        effTree->tree_->Fill();

      }//loop over genjet denominators
    } //if denominatorType == 0

  } //loop over events
  
  cout << "Total Denominators: " << NDenominatorsFilled << endl;

  delete info;
  delete jetArr;
  delete pfcandidateArr;
  delete genparticleArr;
  delete genjetArr;

  outputFile->Write();
  outputFile->Close();
  
  delete outputFile;
  if (effTree) delete effTree;
} 
Ejemplo n.º 29
0
void Example1(const char *inputFile)
{
  gSystem->Load("libDelphes");

  // Create chain of root trees
  TChain chain("Delphes");
  chain.Add(inputFile);

  // Create object of class ExRootTreeReader
  ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
  Long64_t numberOfEntries = treeReader->GetEntries();

  // Get pointers to branches used in this analysis
  TClonesArray *branchJet = treeReader->UseBranch("Jet");
  TClonesArray *branchElectron = treeReader->UseBranch("Electron");
  TClonesArray *branchEvent = treeReader->UseBranch("Event");

  // Book histograms
  TH1 *histJetPT = new TH1F("jet_pt", "jet P_{T}", 100, 0.0, 100.0);
  TH1 *histMass = new TH1F("mass", "M_{inv}(e_{1}, e_{2})", 100, 40.0, 140.0);

  // Loop over all events
  for(Int_t entry = 0; entry < numberOfEntries; ++entry)
  {
    // Load selected branches with data from specified event
    treeReader->ReadEntry(entry);

    
    //HepMCEvent *event = (HepMCEvent*) branchEvent -> At(0);
    //LHEFEvent *event = (LHEFEvent*) branchEvent -> At(0);
    //Float_t weight = event->Weight;

    // If event contains at least 1 jet
    if(branchJet->GetEntries() > 0)
    {
      // Take first jet
      Jet *jet = (Jet*) branchJet->At(0);

      // Plot jet transverse momentum
      histJetPT->Fill(jet->PT);

      // Print jet transverse momentum
      cout << "Jet pt: "<<jet->PT << endl;
    }

    Electron *elec1, *elec2;

    // If event contains at least 2 electrons
    if(branchElectron->GetEntries() > 1)
    {
      // Take first two electrons
      elec1 = (Electron *) branchElectron->At(0);
      elec2 = (Electron *) branchElectron->At(1);

      // Plot their invariant mass
      histMass->Fill(((elec1->P4()) + (elec2->P4())).M());
    }
  }

  // Show resulting histograms
  histJetPT->Draw();
  histMass->Draw();
}
Ejemplo n.º 30
0
void selectWe(const TString conf="we.conf", // input file
              const TString outputDir=".",  // output directory
              const Bool_t  doScaleCorr=0   // apply energy scale corrections?
             ) {
    gBenchmark->Start("selectWe");

    //--------------------------------------------------------------------------------------------------------------
    // Settings
    //==============================================================================================================

    const Double_t PT_CUT   = 25;
    const Double_t ETA_CUT  = 2.5;
    const Double_t ELE_MASS = 0.000511;

    const Double_t VETO_PT   = 10;
    const Double_t VETO_ETA  = 2.5;

    const Double_t ECAL_GAP_LOW  = 1.4442;
    const Double_t ECAL_GAP_HIGH = 1.566;

    const Double_t escaleNbins  = 2;
    const Double_t escaleEta[]  = { 1.4442, 2.5   };
    const Double_t escaleCorr[] = { 0.992,  1.009 };

    const Int_t BOSON_ID  = 24;
    const Int_t LEPTON_ID = 11;

    // load trigger menu
    const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");

    // load pileup reweighting file
    TFile *f_rw = TFile::Open("../Tools/pileup_rw_Golden.root", "read");
    TH1D *h_rw = (TH1D*) f_rw->Get("h_rw_golden");
    TH1D *h_rw_up = (TH1D*) f_rw->Get("h_rw_up_golden");
    TH1D *h_rw_down = (TH1D*) f_rw->Get("h_rw_down_golden");

    //--------------------------------------------------------------------------------------------------------------
    // Main analysis code
    //==============================================================================================================

    vector<TString>  snamev;      // sample name (for output files)
    vector<CSample*> samplev;     // data/MC samples

    //
    // parse .conf file
    //
    confParse(conf, snamev, samplev);
    const Bool_t hasData = (samplev[0]->fnamev.size()>0);

    // Create output directory
    gSystem->mkdir(outputDir,kTRUE);
    const TString ntupDir = outputDir + TString("/ntuples");
    gSystem->mkdir(ntupDir,kTRUE);

    //
    // Declare output ntuple variables
    //
    UInt_t  runNum, lumiSec, evtNum;
    UInt_t  npv, npu;
    UInt_t  id_1, id_2;
    Double_t x_1, x_2, xPDF_1, xPDF_2;
    Double_t scalePDF, weightPDF;
    TLorentzVector *genV=0, *genLep=0;
    Float_t genVPt, genVPhi, genVy, genVMass;
    Float_t genLepPt, genLepPhi;
    Float_t scale1fb, puWeight, puWeightUp, puWeightDown;
    Float_t met, metPhi, sumEt, mt, u1, u2;
    Float_t tkMet, tkMetPhi, tkSumEt, tkMt, tkU1, tkU2;
    Float_t mvaMet, mvaMetPhi, mvaSumEt, mvaMt, mvaU1, mvaU2;
    Float_t puppiMet, puppiMetPhi, puppiSumEt, puppiMt, puppiU1, puppiU2;
    Int_t   q;
    TLorentzVector *lep=0;
    Int_t lepID;
    ///// electron specific /////
    Float_t trkIso, emIso, hadIso;
    Float_t pfChIso, pfGamIso, pfNeuIso, pfCombIso;
    Float_t sigieie, hovere, eoverp, fbrem, ecalE;
    Float_t dphi, deta;
    Float_t d0, dz;
    UInt_t  isConv, nexphits, typeBits;
    TLorentzVector *sc=0;

    // Data structures to store info from TTrees
    baconhep::TEventInfo *info   = new baconhep::TEventInfo();
    baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
    TClonesArray *genPartArr     = new TClonesArray("baconhep::TGenParticle");
    TClonesArray *electronArr    = new TClonesArray("baconhep::TElectron");
    TClonesArray *scArr          = new TClonesArray("baconhep::TPhoton");
    TClonesArray *vertexArr      = new TClonesArray("baconhep::TVertex");

    TFile *infile=0;
    TTree *eventTree=0;

    //
    // loop over samples
    //
    for(UInt_t isam=0; isam<samplev.size(); isam++) {

        // Assume data sample is first sample in .conf file
        // If sample is empty (i.e. contains no ntuple files), skip to next sample
        Bool_t isData=kFALSE;
        if(isam==0 && !hasData) continue;
        else if (isam==0) isData=kTRUE;

        // Assume signal sample is given name "we" -- flag to store GEN W kinematics
        Bool_t isSignal = (snamev[isam].CompareTo("we",TString::kIgnoreCase)==0);
        // flag to reject W->enu events when selecting at wrong-flavor background events
        Bool_t isWrongFlavor = (snamev[isam].CompareTo("wx",TString::kIgnoreCase)==0);

        CSample* samp = samplev[isam];

        //
        // Set up output ntuple
        //
        TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.root");
        if(isam!=0 && !doScaleCorr) outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.raw.root");
        TFile *outFile = new TFile(outfilename,"RECREATE");
        TTree *outTree = new TTree("Events","Events");

        outTree->Branch("runNum",     &runNum,     "runNum/i");      // event run number
        outTree->Branch("lumiSec",    &lumiSec,    "lumiSec/i");     // event lumi section
        outTree->Branch("evtNum",     &evtNum,     "evtNum/i");      // event number
        outTree->Branch("npv",        &npv,        "npv/i");         // number of primary vertices
        outTree->Branch("npu",        &npu,        "npu/i");         // number of in-time PU events (MC)
        outTree->Branch("id_1",       &id_1,       "id_1/i");        // PDF info -- parton ID for parton 1
        outTree->Branch("id_2",       &id_2,       "id_2/i");        // PDF info -- parton ID for parton 2
        outTree->Branch("x_1",        &x_1,        "x_1/d");         // PDF info -- x for parton 1
        outTree->Branch("x_2",        &x_2,        "x_2/d");         // PDF info -- x for parton 2
        outTree->Branch("xPDF_1",     &xPDF_1,     "xPDF_1/d");      // PDF info -- x*F for parton 1
        outTree->Branch("xPDF_2",     &xPDF_2,     "xPDF_2/d");      // PDF info -- x*F for parton 2
        outTree->Branch("scalePDF",   &scalePDF,   "scalePDF/d");    // PDF info -- energy scale of parton interaction
        outTree->Branch("weightPDF",  &weightPDF,  "weightPDF/d");   // PDF info -- PDF weight
        outTree->Branch("genV",      "TLorentzVector", &genV);       // GEN boson 4-vector (signal MC)
        outTree->Branch("genLep",    "TLorentzVector", &genLep);     // GEN lepton 4-vector (signal MC)
        outTree->Branch("genVPt",     &genVPt,     "genVPt/F");      // GEN boson pT (signal MC)
        outTree->Branch("genVPhi",    &genVPhi,    "genVPhi/F");     // GEN boson phi (signal MC)
        outTree->Branch("genVy",      &genVy,      "genVy/F");       // GEN boson rapidity (signal MC)
        outTree->Branch("genVMass",   &genVMass,   "genVMass/F");    // GEN boson mass (signal MC)
        outTree->Branch("genLepPt",   &genLepPt,   "genLepPt/F");    // GEN lepton pT (signal MC)
        outTree->Branch("genLepPhi",  &genLepPhi,  "genLepPhi/F");   // GEN lepton phi (signal MC)
        outTree->Branch("scale1fb",   &scale1fb,   "scale1fb/F");    // event weight per 1/fb (MC)
        outTree->Branch("puWeight",   &puWeight,   "puWeight/F");    // scale factor for pileup reweighting (MC)
        outTree->Branch("puWeightUp",    &puWeightUp,   "puWeightUp/F");    // scale factor for pileup reweighting (MC)
        outTree->Branch("puWeightDown",    &puWeightDown,   "puWeightDown/F");    // scale factor for pileup reweighting (MC)
        outTree->Branch("met",        &met,        "met/F");         // MET
        outTree->Branch("metPhi",     &metPhi,     "metPhi/F");      // phi(MET)
        outTree->Branch("sumEt",      &sumEt,      "sumEt/F");       // Sum ET
        outTree->Branch("mt",         &mt,         "mt/F");          // transverse mass
        outTree->Branch("u1",         &u1,         "u1/F");          // parallel component of recoil
        outTree->Branch("u2",         &u2,         "u2/F");          // perpendicular component of recoil
        outTree->Branch("tkMet",      &tkMet,      "tkMet/F");       // MET (track MET)
        outTree->Branch("tkMetPhi",   &tkMetPhi,   "tkMetPhi/F");    // phi(MET) (track MET)
        outTree->Branch("tkSumEt",    &tkSumEt,    "tkSumEt/F");     // Sum ET (track MET)
        outTree->Branch("tkMt",       &tkMt,       "tkMt/F");        // transverse mass (track MET)
        outTree->Branch("tkU1",       &tkU1,       "tkU1/F");        // parallel component of recoil (track MET)
        outTree->Branch("tkU2",       &tkU2,       "tkU2/F");        // perpendicular component of recoil (track MET)
        outTree->Branch("mvaMet",     &mvaMet,     "mvaMet/F");      // MVA MET
        outTree->Branch("mvaMetPhi",  &mvaMetPhi,  "mvaMetPhi/F");   // phi(MVA MET)
        outTree->Branch("mvaSumEt",   &mvaSumEt,   "mvaSumEt/F");    // Sum ET (mva MET)
        outTree->Branch("mvaMt",      &mvaMt,      "mvaMt/F");       // transverse mass (mva MET)
        outTree->Branch("mvaU1",      &mvaU1,      "mvaU1/F");       // parallel component of recoil (mva MET)
        outTree->Branch("mvaU2",      &mvaU2,      "mvaU2/F");       // perpendicular component of recoil (mva MET)
        outTree->Branch("puppiMet",    &puppiMet,   "puppiMet/F");      // Puppi MET
        outTree->Branch("puppiMetPhi", &puppiMetPhi,"puppiMetPhi/F");   // phi(Puppi MET)
        outTree->Branch("puppiSumEt",  &puppiSumEt, "puppiSumEt/F");    // Sum ET (Puppi MET)
        outTree->Branch("puppiU1",     &puppiU1,    "puppiU1/F");       // parallel component of recoil (Puppi MET)
        outTree->Branch("puppiU2",     &puppiU2,    "puppiU2/F");       // perpendicular component of recoil (Puppi MET)
        outTree->Branch("q",          &q,          "q/I");           // lepton charge
        outTree->Branch("lep",       "TLorentzVector", &lep);        // lepton 4-vector
        outTree->Branch("lepID",      &lepID,      "lepID/I");       // lepton PDG ID
        ///// electron specific /////
        outTree->Branch("trkIso",     &trkIso,     "trkIso/F");      // track isolation of tag lepton
        outTree->Branch("emIso",      &emIso,      "emIso/F");       // ECAL isolation of tag lepton
        outTree->Branch("hadIso",     &hadIso,     "hadIso/F");      // HCAL isolation of tag lepton
        outTree->Branch("pfChIso",    &pfChIso,    "pfChIso/F");     // PF charged hadron isolation of lepton
        outTree->Branch("pfGamIso",   &pfGamIso,   "pfGamIso/F");    // PF photon isolation of lepton
        outTree->Branch("pfNeuIso",   &pfNeuIso,   "pfNeuIso/F");    // PF neutral hadron isolation of lepton
        outTree->Branch("pfCombIso",  &pfCombIso,  "pfCombIso/F");   // PF combined isolation of electron
        outTree->Branch("sigieie",    &sigieie,    "sigieie/F");     // sigma-ieta-ieta of electron
        outTree->Branch("hovere",     &hovere,     "hovere/F");      // H/E of electron
        outTree->Branch("eoverp",     &eoverp,     "eoverp/F");      // E/p of electron
        outTree->Branch("fbrem",      &fbrem,      "fbrem/F");       // brem fraction of electron
        outTree->Branch("dphi",       &dphi,       "dphi/F");        // GSF track - ECAL dphi of electron
        outTree->Branch("deta",       &deta,       "deta/F");        // GSF track - ECAL deta of electron
        outTree->Branch("ecalE",      &ecalE,      "ecalE/F");       // ECAL energy of electron
        outTree->Branch("d0",         &d0,         "d0/F");          // transverse impact parameter of electron
        outTree->Branch("dz",         &dz,         "dz/F");          // longitudinal impact parameter of electron
        outTree->Branch("isConv",     &isConv,     "isConv/i");      // conversion filter flag of electron
        outTree->Branch("nexphits",   &nexphits,   "nexphits/i");    // number of missing expected inner hits of electron
        outTree->Branch("typeBits",   &typeBits,   "typeBits/i");    // electron type of electron
        outTree->Branch("sc",        "TLorentzVector", &sc);         // supercluster 4-vector

        //
        // loop through files
        //
        const UInt_t nfiles = samp->fnamev.size();
        for(UInt_t ifile=0; ifile<nfiles; ifile++) {

            // Read input file and get the TTrees
            cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... ";
            cout.flush();
            infile = TFile::Open(samp->fnamev[ifile]);
            assert(infile);

            Bool_t hasJSON = kFALSE;
            baconhep::RunLumiRangeMap rlrm;
            if(samp->jsonv[ifile].CompareTo("NONE")!=0) {
                hasJSON = kTRUE;
                rlrm.addJSONFile(samp->jsonv[ifile].Data());
            }

            eventTree = (TTree*)infile->Get("Events");
            assert(eventTree);
            eventTree->SetBranchAddress("Info",     &info);
            TBranch *infoBr     = eventTree->GetBranch("Info");
            eventTree->SetBranchAddress("Electron", &electronArr);
            TBranch *electronBr = eventTree->GetBranch("Electron");
            eventTree->SetBranchAddress("PV",   &vertexArr);
            TBranch *vertexBr = eventTree->GetBranch("PV");

            Bool_t hasGen = eventTree->GetBranchStatus("GenEvtInfo");
            TBranch *genBr=0, *genPartBr=0;
            if(hasGen) {
                eventTree->SetBranchAddress("GenEvtInfo", &gen);
                genBr = eventTree->GetBranch("GenEvtInfo");
                eventTree->SetBranchAddress("GenParticle",&genPartArr);
                genPartBr = eventTree->GetBranch("GenParticle");
            }

            // Compute MC event weight per 1/fb
            const Double_t xsec = samp->xsecv[ifile];
            Double_t totalWeight=0;

            if (hasGen) {
                TH1D *hall = new TH1D("hall", "", 1,0,1);
                eventTree->Draw("0.5>>hall", "GenEvtInfo->weight");
                totalWeight=hall->Integral();
                delete hall;
                hall=0;
            }

            //
            // loop over events
            //
            Double_t nsel=0, nselvar=0;
            for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
                infoBr->GetEntry(ientry);

                if(ientry%1000000==0) cout << "Processing event " << ientry << ". " << (double)ientry/(double)eventTree->GetEntries()*100 << " percent done with this file." << endl;

                Double_t weight=1;
                if(xsec>0 && totalWeight>0) weight = xsec/totalWeight;
                if(hasGen) {
                    genPartArr->Clear();
                    genBr->GetEntry(ientry);
                    genPartBr->GetEntry(ientry);
                    weight*=gen->weight;
                }

                // veto w -> xv decays for signal and w -> ev for bacground samples (needed for inclusive WToLNu sample)
                if (isWrongFlavor && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))==LEPTON_ID) continue;
                else if (isSignal && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;

                // check for certified lumi (if applicable)
                baconhep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);
                if(hasJSON && !rlrm.hasRunLumi(rl)) continue;

                // trigger requirement
                if (!isEleTrigger(triggerMenu, info->triggerBits, isData)) continue;

                // good vertex requirement
                if(!(info->hasGoodPV)) continue;

                //
                // SELECTION PROCEDURE:
                //  (1) Look for 1 good electron matched to trigger
                //  (2) Reject event if another electron is present passing looser cuts
                //
                electronArr->Clear();
                electronBr->GetEntry(ientry);

                Int_t nLooseLep=0;
                const baconhep::TElectron *goodEle=0;
                Bool_t passSel=kFALSE;

                for(Int_t i=0; i<electronArr->GetEntriesFast(); i++) {
                    const baconhep::TElectron *ele = (baconhep::TElectron*)((*electronArr)[i]);

                    // check ECAL gap
                    if(fabs(ele->scEta)>=ECAL_GAP_LOW && fabs(ele->scEta)<=ECAL_GAP_HIGH) continue;

                    // apply scale and resolution corrections to MC
                    Double_t elescEt_corr = ele->scEt;
                    if(doScaleCorr && snamev[isam].CompareTo("data",TString::kIgnoreCase)!=0)
                        elescEt_corr = gRandom->Gaus(ele->scEt*getEleScaleCorr(ele->scEta,0),getEleResCorr(ele->scEta,0));

                    if(fabs(ele->scEta)   > VETO_ETA) continue;        // loose lepton |eta| cut
                    if(elescEt_corr       < VETO_PT)  continue;        // loose lepton pT cut
                    if(passEleLooseID(ele,info->rhoIso)) nLooseLep++;  // loose lepton selection
                    if(nLooseLep>1) {  // extra lepton veto
                        passSel=kFALSE;
                        break;
                    }

                    if(fabs(ele->scEta)   > ETA_CUT)     continue;  // lepton |eta| cut
                    if(elescEt_corr       < PT_CUT)      continue;  // lepton pT cut
                    if(!passEleID(ele,info->rhoIso))     continue;  // lepton selection
                    if(!isEleTriggerObj(triggerMenu, ele->hltMatchBits, kFALSE, isData)) continue;

                    passSel=kTRUE;
                    goodEle = ele;
                }

                if(passSel) {

                    //******* We have a W candidate! HURRAY! ********
                    nsel+=weight;
                    nselvar+=weight*weight;

                    // apply scale and resolution corrections to MC
                    Double_t goodElept_corr = goodEle->pt;
                    if(doScaleCorr && snamev[isam].CompareTo("data",TString::kIgnoreCase)!=0)
                        goodElept_corr = gRandom->Gaus(goodEle->pt*getEleScaleCorr(goodEle->scEta,0),getEleResCorr(goodEle->scEta,0));

                    TLorentzVector vLep(0,0,0,0);
                    TLorentzVector vSC(0,0,0,0);
                    // apply scale and resolution corrections to MC
                    if(doScaleCorr && snamev[isam].CompareTo("data",TString::kIgnoreCase)!=0) {
                        vLep.SetPtEtaPhiM(goodElept_corr, goodEle->eta, goodEle->phi, ELE_MASS);
                        vSC.SetPtEtaPhiM(gRandom->Gaus(goodEle->scEt*getEleScaleCorr(goodEle->scEta,0),getEleResCorr(goodEle->scEta,0)), goodEle->scEta, goodEle->scPhi, ELE_MASS);
                    } else {
                        vLep.SetPtEtaPhiM(goodEle->pt,goodEle->eta,goodEle->phi,ELE_MASS);
                        vSC.SetPtEtaPhiM(goodEle->scEt,goodEle->scEta,goodEle->scPhi,ELE_MASS);
                    }

                    //
                    // Fill tree
                    //
                    runNum    = info->runNum;
                    lumiSec   = info->lumiSec;
                    evtNum    = info->evtNum;

                    vertexArr->Clear();
                    vertexBr->GetEntry(ientry);

                    npv      = vertexArr->GetEntries();
                    npu	    = info->nPUmean;
                    genV      = new TLorentzVector(0,0,0,0);
                    genLep    = new TLorentzVector(0,0,0,0);
                    genVPt    = -999;
                    genVPhi   = -999;
                    genVy     = -999;
                    genVMass  = -999;
                    genLepPt  = -999;
                    genLepPhi = -999;
                    u1        = -999;
                    u2        = -999;
                    tkU1      = -999;
                    tkU2      = -999;
                    mvaU1     = -999;
                    mvaU2     = -999;
                    puppiU1     = -999;
                    puppiU2     = -999;
                    id_1      = -999;
                    id_2      = -999;
                    x_1       = -999;
                    x_2       = -999;
                    xPDF_1    = -999;
                    xPDF_2    = -999;
                    scalePDF  = -999;
                    weightPDF = -999;

                    if(isSignal && hasGen) {
                        TLorentzVector *gvec=new TLorentzVector(0,0,0,0);
                        TLorentzVector *glep1=new TLorentzVector(0,0,0,0);
                        TLorentzVector *glep2=new TLorentzVector(0,0,0,0);
                        toolbox::fillGen(genPartArr, BOSON_ID, gvec, glep1, glep2,1);

                        if (gvec && glep1) {
                            genV      = new TLorentzVector(0,0,0,0);
                            genV->SetPtEtaPhiM(gvec->Pt(),gvec->Eta(),gvec->Phi(),gvec->M());
                            genLep    = new TLorentzVector(0,0,0,0);
                            genLep->SetPtEtaPhiM(glep1->Pt(),glep1->Eta(),glep1->Phi(),glep1->M());
                            genVPt    = gvec->Pt();
                            genVPhi   = gvec->Phi();
                            genVy     = gvec->Rapidity();
                            genVMass  = gvec->M();
                            genLepPt  = glep1->Pt();
                            genLepPhi = glep1->Phi();

                            TVector2 vWPt((genVPt)*cos(genVPhi),(genVPt)*sin(genVPhi));
                            TVector2 vLepPt(vLep.Px(),vLep.Py());

                            TVector2 vMet((info->pfMETC)*cos(info->pfMETCphi), (info->pfMETC)*sin(info->pfMETCphi));
                            TVector2 vU = -1.0*(vMet+vLepPt);
                            u1 = ((vWPt.Px())*(vU.Px()) + (vWPt.Py())*(vU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
                            u2 = ((vWPt.Px())*(vU.Py()) - (vWPt.Py())*(vU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|

                            TVector2 vTkMet((info->trkMET)*cos(info->trkMETphi), (info->trkMET)*sin(info->trkMETphi));
                            TVector2 vTkU = -1.0*(vTkMet+vLepPt);
                            tkU1 = ((vWPt.Px())*(vTkU.Px()) + (vWPt.Py())*(vTkU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
                            tkU2 = ((vWPt.Px())*(vTkU.Py()) - (vWPt.Py())*(vTkU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|

                            TVector2 vMvaMet((info->mvaMET)*cos(info->mvaMETphi), (info->mvaMET)*sin(info->mvaMETphi));
                            TVector2 vMvaU = -1.0*(vMvaMet+vLepPt);
                            mvaU1 = ((vWPt.Px())*(vMvaU.Px()) + (vWPt.Py())*(vMvaU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
                            mvaU2 = ((vWPt.Px())*(vMvaU.Py()) - (vWPt.Py())*(vMvaU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|

                            TVector2 vPuppiMet((info->puppET)*cos(info->puppETphi), (info->puppET)*sin(info->puppETphi));
                            TVector2 vPuppiU = -1.0*(vPuppiMet+vLepPt);
                            puppiU1 = ((vWPt.Px())*(vPuppiU.Px()) + (vWPt.Py())*(vPuppiU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
                            puppiU2 = ((vWPt.Px())*(vPuppiU.Py()) - (vWPt.Py())*(vPuppiU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|

                        }
                        id_1      = gen->id_1;
                        id_2      = gen->id_2;
                        x_1       = gen->x_1;
                        x_2       = gen->x_2;
                        xPDF_1    = gen->xPDF_1;
                        xPDF_2    = gen->xPDF_2;
                        scalePDF  = gen->scalePDF;
                        weightPDF = gen->weight;

                        delete gvec;
                        delete glep1;
                        delete glep2;
                        gvec=0;
                        glep1=0;
                        glep2=0;
                    }
                    scale1fb = weight;
                    puWeight = h_rw->GetBinContent(h_rw->FindBin(npu));
                    puWeightUp = h_rw_up->GetBinContent(h_rw_up->FindBin(npu));
                    puWeightDown = h_rw_down->GetBinContent(h_rw_down->FindBin(npu));
                    met	   = info->pfMETC;
                    metPhi   = info->pfMETCphi;
                    sumEt    = 0;
                    mt       = sqrt( 2.0 * (vLep.Pt()) * (info->pfMETC) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->pfMETCphi))) );
                    tkMet	   = info->trkMET;
                    tkMetPhi = info->trkMETphi;
                    tkSumEt  = 0;
                    tkMt     = sqrt( 2.0 * (vLep.Pt()) * (info->trkMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->trkMETphi))) );
                    mvaMet   = info->mvaMET;
                    mvaMetPhi = info->mvaMETphi;
                    mvaSumEt  = 0;
                    mvaMt     = sqrt( 2.0 * (vLep.Pt()) * (info->mvaMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->mvaMETphi))) );
// 	  TVector2 vLepPt(vLep.Px(),vLep.Py());
// 	  TVector2 vPuppi((info->puppET)*cos(info->puppETphi), (info->puppET)*sin(info->puppETphi));
// 	  TVector2 vpp; vpp=vPuppi-vLepPt;
                    puppiMet   = info->puppET;
                    puppiMetPhi = info->puppETphi;
                    puppiSumEt  = 0;
                    puppiMt     = sqrt( 2.0 * (vLep.Pt()) * (info->puppET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->puppETphi))) );
                    q        = goodEle->q;
                    lep      = &vLep;

                    ///// electron specific /////
                    sc       = &vSC;
                    trkIso    = goodEle->trkIso;
                    emIso     = goodEle->ecalIso;
                    hadIso    = goodEle->hcalIso;
                    pfChIso   = goodEle->chHadIso;
                    pfGamIso  = goodEle->gammaIso;
                    pfNeuIso  = goodEle->neuHadIso;
                    pfCombIso = goodEle->chHadIso + TMath::Max(goodEle->neuHadIso + goodEle->gammaIso -
                                (info->rhoIso)*getEffAreaEl(goodEle->scEta), 0.);
                    sigieie   = goodEle->sieie;
                    hovere    = goodEle->hovere;
                    eoverp    = goodEle->eoverp;
                    fbrem     = goodEle->fbrem;
                    dphi      = goodEle->dPhiIn;
                    deta      = goodEle->dEtaIn;
                    ecalE     = goodEle->ecalEnergy;
                    d0        = goodEle->d0;
                    dz        = goodEle->dz;
                    isConv    = goodEle->isConv;
                    nexphits  = goodEle->nMissingHits;
                    typeBits  = goodEle->typeBits;

                    outTree->Fill();
                    delete genV;
                    delete genLep;
                    genV=0, genLep=0, lep=0, sc=0;
                }
            }
            delete infile;
            infile=0, eventTree=0;

            cout << nsel  << " +/- " << sqrt(nselvar);
            if(isam!=0) cout << " per 1/pb";
            cout << endl;
        }
        outFile->Write();
        outFile->Close();
    }
    delete h_rw;
    delete h_rw_up;
    delete h_rw_down;
    delete f_rw;
    delete info;
    delete gen;
    delete genPartArr;
    delete electronArr;
    delete vertexArr;

    //--------------------------------------------------------------------------------------------------------------
    // Output
    //==============================================================================================================

    cout << "*" << endl;
    cout << "* SUMMARY" << endl;
    cout << "*--------------------------------------------------" << endl;
    cout << " W -> e nu" << endl;
    cout << "  pT > " << PT_CUT << endl;
    cout << "  |eta| < " << ETA_CUT << endl;
    if(doScaleCorr)
        cout << "  *** Scale corrections applied ***" << endl;
    cout << endl;

    cout << endl;
    cout << "  <> Output saved in " << outputDir << "/" << endl;
    cout << endl;

    gBenchmark->Show("selectWe");
}