示例#1
0
import ROOT, math, sys
from DataFormats.FWLite import Events, Handle
from ROOT import TLorentzVector
from MotivationClass_EP import Motivation_EP

##### Reading in files from 'TTJetsMCdilep.txt'
print 'Reading TT-files'
TTJetsFiles = open('TTJetsMCdilep.txt')
files = TTJetsFiles.readlines()
TTJetsFiles = []
for f in files:
    TTJetsFiles.append(
        'dcap://grid-dcap-extern.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms'
        + f.rstrip('\n'))

events_TT = Events(TTJetsFiles)

##### Reading in files from 'TTTT_TuneZ2star_8TeV-madgraph-tauola.txt'
print 'Reading TTTT-files'
TTTTJetsFiles = open('TTTT_TuneZ2star_8TeV-madgraph-tauola_mini.txt')
files = TTTTJetsFiles.readlines()
TTTTJetsFiles = []
for f in files:
    TTTTJetsFiles.append(
        'dcap://grid-dcap-extern.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms'
        + f.rstrip('\n'))

events_TTTT = Events(TTTTJetsFiles)

##### Run Motivation
mot = Motivation_EP(events_TT, events_TTTT, "_Test_TT", "_Test_TTTT")
示例#2
0
def Match(inFiles, sample):

    h_npv = Handle("std::int")
    h_genparticles = Handle("vector<reco::GenParticle>")

    h_ak8_pt = Handle("std::vector<float>")
    h_ak8_eta = Handle("std::vector<float>")
    h_ak8_phi = Handle("std::vector<float>")
    h_ak8_e = Handle("std::vector<float>")

    l_npv = ("vertexInfo", "npv")

    l_genparticles = ("filteredPrunedGenParticles")

    l_ak8_pt = ("jetsAK8CHS", "jetAK8CHSPt")
    l_ak8_eta = ("jetsAK8CHS", "jetAK8CHSEta")
    l_ak8_phi = ("jetsAK8CHS", "jetAK8CHSPhi")
    l_ak8_e = ("jetsAK8CHS", "jetAK8CHSE")

    fileOut = rt.TFile.Open("jetMatchingTree_Hbb_t_" + sample + "_.root",
                            "RECREATE")

    tree = Tree("jetMatchingTree",
                "Tree for matching AK8 jets to gen H and t",
                model=Event)
    evts_processed = 0
    nOverallTop = 0
    nOverallHiggs = 0
    nPair = 0
    for f in inFiles:

        events = Events(f)

        nevents = 0

        for event in events:
            if evts_processed % 1000 == 0:
                print 'Events processed: ', evts_processed
            #if int(evts_processed) == 10000: break
            evts_processed += 1
            event.getByLabel(l_npv, h_npv)
            event.getByLabel(l_genparticles, h_genparticles)

            event.getByLabel(l_ak8_pt, h_ak8_pt)
            event.getByLabel(l_ak8_eta, h_ak8_eta)
            event.getByLabel(l_ak8_phi, h_ak8_phi)
            event.getByLabel(l_ak8_e, h_ak8_e)

            if len(h_npv.product()) < 1: continue

            #if len(h_ak8_pt.product()) < 1: continue

            tree.npv = h_npv.product()[0]

            n_AK8 = 0
            n_Higgs = 0
            n_Top = 0

            n_MatchedToHiggs = 0
            n_MatchedToTop = 0
            n_AK8MatchedToHiggs = 0
            n_AK8MatchedToTop = 0
            m_tH = 0
            p4_Higgs = []
            p4_Hdau0 = []
            p4_Hdau1 = []
            p4_Top = []
            p4_W = []
            p4_Tdau0 = []
            p4_Tdau1 = []
            p4_AK8 = []
            if h_genparticles.product().size() > 0:
                for igen in xrange(h_genparticles.product().size()):

                    pdgid = h_genparticles.product()[igen].pdgId()

                    nDaughters = h_genparticles.product(
                    )[igen].numberOfDaughters()

                    if abs(pdgid) == 25:
                        if nDaughters != 2: continue

                        firstDaughter = h_genparticles.product(
                        )[igen].daughter(0).pdgId()
                        secondDaughter = h_genparticles.product(
                        )[igen].daughter(1).pdgId()
                        if abs(firstDaughter) != 5 or abs(secondDaughter) != 5:
                            continue

                        genPt = h_genparticles.product()[igen].pt()
                        genEta = h_genparticles.product()[igen].eta()
                        genPhi = h_genparticles.product()[igen].phi()
                        genE = h_genparticles.product()[igen].energy()

                        dau0Pt = h_genparticles.product()[igen].daughter(
                            0).pt()
                        dau0Eta = h_genparticles.product()[igen].daughter(
                            0).eta()
                        dau0Phi = h_genparticles.product()[igen].daughter(
                            0).phi()
                        dau0E = h_genparticles.product()[igen].daughter(
                            0).energy()

                        dau1Pt = h_genparticles.product()[igen].daughter(
                            1).pt()
                        dau1Eta = h_genparticles.product()[igen].daughter(
                            1).eta()
                        dau1Phi = h_genparticles.product()[igen].daughter(
                            1).phi()
                        dau1E = h_genparticles.product()[igen].daughter(
                            1).energy()

                        p4GenHiggs = rt.TLorentzVector()
                        p4GenHiggs.SetPtEtaPhiE(genPt, genEta, genPhi, genE)

                        p4Hdau0 = rt.TLorentzVector()
                        p4Hdau0.SetPtEtaPhiE(dau0Pt, dau0Eta, dau0Phi, dau0E)

                        p4Hdau1 = rt.TLorentzVector()
                        p4Hdau1.SetPtEtaPhiE(dau1Pt, dau1Eta, dau1Phi, dau1E)

                        p4_Higgs.append(p4GenHiggs)
                        p4_Hdau0.append(p4Hdau0)
                        p4_Hdau1.append(p4Hdau1)

                        tree.pt_Higgs[n_Higgs] = p4GenHiggs.Pt()
                        tree.eta_Higgs[n_Higgs] = p4GenHiggs.Eta()
                        tree.phi_Higgs[n_Higgs] = p4GenHiggs.Phi()
                        tree.e_Higgs[n_Higgs] = p4GenHiggs.Energy()
                        tree.m_Higgs[n_Higgs] = p4GenHiggs.Mag()

                        n_Higgs += 1

                    elif abs(pdgid) == 6:
                        if nDaughters != 2: continue

                        firstDaughter = h_genparticles.product(
                        )[igen].daughter(0).pdgId()
                        secondDaughter = h_genparticles.product(
                        )[igen].daughter(1).pdgId()
                        hadronic = False
                        if abs(firstDaughter) == 24 and abs(
                                secondDaughter) == 5 or abs(
                                    firstDaughter) == 5 and abs(
                                        secondDaughter) == 24:
                            for idaughter in xrange(nDaughters):
                                if abs(h_genparticles.product()[igen].daughter(
                                        idaughter).pdgId()) != 24:
                                    continue
                                nGDaughters = h_genparticles.product(
                                )[igen].daughter(
                                    idaughter).numberOfDaughters()
                                for igDaughter in xrange(nGDaughters):
                                    gDaughter = h_genparticles.product(
                                    )[igen].daughter(idaughter).daughter(
                                        igDaughter).pdgId()
                                    if abs(gDaughter) == 24:
                                        nggDaughters = h_genparticles.product(
                                        )[igen].daughter(idaughter).daughter(
                                            igDaughter).numberOfDaughters()
                                        for iggDaughter in xrange(
                                                nggDaughters):
                                            ggDaughter = h_genparticles.product(
                                            )[igen].daughter(
                                                idaughter).daughter(
                                                    igDaughter).daughter(
                                                        iggDaughter).pdgId()
                                            if abs(ggDaughter) in xrange(1, 7):
                                                hadronic = True
                                            else:
                                                hadronic = False
                                    else:
                                        if abs(gDaughter) in xrange(1, 7):
                                            hadronic = True
                                        else:
                                            hadronic = False
                            if not hadronic: continue

                            genPt = h_genparticles.product()[igen].pt()
                            genEta = h_genparticles.product()[igen].eta()
                            genPhi = h_genparticles.product()[igen].phi()
                            genE = h_genparticles.product()[igen].energy()

                            dau0Pt = h_genparticles.product()[igen].daughter(
                                0).pt()
                            dau0Eta = h_genparticles.product()[igen].daughter(
                                0).eta()
                            dau0Phi = h_genparticles.product()[igen].daughter(
                                0).phi()
                            dau0E = h_genparticles.product()[igen].daughter(
                                0).energy()

                            dau1Pt = h_genparticles.product()[igen].daughter(
                                1).pt()
                            dau1Eta = h_genparticles.product()[igen].daughter(
                                1).eta()
                            dau1Phi = h_genparticles.product()[igen].daughter(
                                1).phi()
                            dau1E = h_genparticles.product()[igen].daughter(
                                1).energy()

                            p4GenTop = rt.TLorentzVector()
                            p4GenTop.SetPtEtaPhiE(genPt, genEta, genPhi, genE)

                            p4Tdau0 = rt.TLorentzVector()
                            p4Tdau0.SetPtEtaPhiE(dau0Pt, dau0Eta, dau0Phi,
                                                 dau0E)

                            p4Tdau1 = rt.TLorentzVector()
                            p4Tdau1.SetPtEtaPhiE(dau1Pt, dau1Eta, dau1Phi,
                                                 dau1E)

                            p4_Top.append(p4GenTop)
                            p4_Tdau0.append(p4Tdau0)
                            p4_Tdau1.append(p4Tdau1)

                            tree.pt_Top[n_Top] = p4GenTop.Pt()
                            tree.eta_Top[n_Top] = p4GenTop.Eta()
                            tree.phi_Top[n_Top] = p4GenTop.Phi()
                            tree.e_Top[n_Top] = p4GenTop.Energy()
                            tree.m_Top[n_Top] = p4GenTop.Mag()

                            if firstDaughter == 24:
                                tree.pt_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).pt()
                                tree.eta_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).eta()
                                tree.phi_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).phi()
                                tree.e_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).energy()

                                tree.m_W[n_Top] = p4Tdau0.Mag()
                            elif secondDaughter == 24:
                                p4_W.append(p4Tdau1)
                                tree.pt_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).pt()
                                tree.eta_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).eta()
                                tree.phi_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).phi()
                                tree.e_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).energy()

                                tree.m_W[n_Top] = p4Tdau1.Mag()

                            n_Top += 1

            for ijet in xrange(len(h_ak8_pt.product())):
                jetPt = h_ak8_pt.product()[ijet]
                jetEta = h_ak8_eta.product()[ijet]
                jetPhi = h_ak8_phi.product()[ijet]
                jetE = h_ak8_e.product()[ijet]

                if abs(jetPt) < 300: continue
                if abs(jetEta) > 2.4: continue

                p4AK8 = rt.TLorentzVector()
                p4AK8.SetPtEtaPhiE(jetPt, jetEta, jetPhi, jetE)

                p4_AK8.append(p4AK8)

                tree.pt_AK8[n_AK8] = p4AK8.Pt()
                tree.eta_AK8[n_AK8] = p4AK8.Eta()
                tree.phi_AK8[n_AK8] = p4AK8.Phi()
                tree.e_AK8[n_AK8] = p4AK8.Energy()
                n_AK8 += 1
                if p4_Higgs:
                    for iHiggs in xrange(n_Higgs):
                        if p4AK8.DeltaR(p4_Higgs[iHiggs]) > 0.3: continue
                        if p4AK8.DeltaR(p4_Hdau0[iHiggs]) > 0.8: continue
                        if p4AK8.DeltaR(p4_Hdau1[iHiggs]) > 0.8: continue

                        tree.pt_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Pt()
                        tree.eta_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Eta()
                        tree.phi_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Phi()
                        tree.e_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Energy()
                        tree.m_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Mag()

                        tree.pt_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Pt()
                        tree.eta_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Eta()
                        tree.phi_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Phi()
                        tree.e_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Energy()
                        tree.m_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Mag()

                        n_AK8MatchedToHiggs = n_AK8MatchedToHiggs + 1
                if p4_Top:
                    for iTop in xrange(n_Top):
                        if p4AK8.DeltaR(p4_Top[iTop]) > 0.3: continue
                        if p4AK8.DeltaR(p4_Tdau0[iTop]) > 0.8: continue
                        if p4AK8.DeltaR(p4_Tdau1[iTop]) > 0.8: continue

                        tree.pt_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Pt()
                        tree.eta_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Eta(
                        )
                        tree.phi_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Phi(
                        )
                        tree.e_MatchedTop[n_MatchedToTop] = p4_Top[
                            iTop].Energy()
                        tree.m_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Mag()

                        tree.pt_AK8MatchedToTop[n_AK8MatchedToTop] = p4AK8.Pt()
                        tree.eta_AK8MatchedToTop[
                            n_AK8MatchedToTop] = p4AK8.Eta()
                        tree.phi_AK8MatchedToTop[
                            n_AK8MatchedToTop] = p4AK8.Phi()
                        tree.e_AK8MatchedToTop[
                            n_AK8MatchedToTop] = p4AK8.Energy()
                        tree.m_AK8MatchedToTop[n_AK8MatchedToTop] = p4AK8.Mag()

                        n_AK8MatchedToTop = n_AK8MatchedToTop + 1

            if p4_Higgs and p4_Top:
                m_tH = (p4_Higgs[0] + p4_Top[0]).Mag()
                tree.m_tH = m_tH
            if n_AK8MatchedToTop > 0:
                nOverallTop += 1
            if n_AK8MatchedToHiggs > 0:
                nOverallHiggs += 1
            if n_AK8MatchedToTop > 0 and n_AK8MatchedToHiggs > 0:
                nPair += 1
            tree.n_AK8 = n_AK8
            tree.n_Higgs = n_Higgs
            tree.n_Top = n_Top
            tree.n_AK8MatchedToHiggs = n_AK8MatchedToHiggs
            tree.n_AK8MatchedToTop = n_AK8MatchedToTop
            tree.nevents = nevents
            tree.fill()

            nevents += 1
    print nOverallTop
    print nOverallHiggs
    print nPair
    tree.Write()
    fileOut.Close()
示例#3
0
parser.add_argument("-n",
                    "--numEvents",
                    default="-1",
                    help="Total number of events to store")
parser.add_argument("-V",
                    "--verbose",
                    action="store_true",
                    help="Turn verbosity on")
parser.add_argument("-s",
                    "--save",
                    action="store_true",
                    help="Save event information to pickle file")
parser.add_argument("-f", "--file", required=True, help="AOD file to analyze")
args = parser.parse_args()

events = Events(args.file)

VERBOSE = args.verbose
EVENTS = int(args.numEvents)
SAVE = args.save

# vertexing information to store
data = {
    "genParticles": {},
    "sortedPrimaryVertices": {},
    "offlinePrimaryVertices": {},
    "offlinePrimaryVerticesWithBS": {}
}

sortedPV_handle = Handle('vector<reco::Vertex>')
offlinePV_handle = Handle('vector<reco::Vertex>')
def processSubsample(file):
    events = Events (file)

    # create handle outside of loop
    genhandle          = Handle ('std::vector<reco::GenParticle>')
    elehandle          = Handle ('std::vector<cmg::DiObject<cmg::Electron,cmg::Electron> >')
    muhandle           = Handle ('std::vector<cmg::DiObject<cmg::Muon,cmg::Muon> >')
    jethandle          = Handle ('std::vector<cmg::VJet>')
    # like and edm::InputTag
    nevent = 0 
    for event in events:
        nevent += 1
        if nevent % 10000 ==0:
            print "event: " + str(nevent)
            
        #print str(event.eventAuxiliary().run())
        #print str(event.object().triggerResultsByName("CMG").accept("preselEleMergedPath"))
        # determine generated flavor and get generated kinematics
        haveleptons=0
        havejet=0
        havez=0
        flavor=""
        genZlep      = root.TLorentzVector()
        genlepton1p4 = root.TLorentzVector()
        genlepton1C  = 0
        genlepton2p4 = root.TLorentzVector()
        genlepton2C  = 0
        genjetp4     = root.TLorentzVector()
        event.getByLabel ("genParticles", genhandle)
        genparticles = genhandle.product()
        for genp in genparticles:
            if (abs(genp.pdgId())==11 or abs(genp.pdgId())==13) and genp.mother().pdgId()==23:
                #print "found lepton "+str(genp.pdgId())
                if(abs(genp.pdgId())==11):
                    flavor = "ele"
                if(abs(genp.pdgId())==13):
                    flavor = "mu"                    
                if haveleptons==0:
                    genlepton1p4 = genp.p4()
                    genlepton1C = genp.charge()
                    haveleptons=1                
                elif haveleptons==1:
                    genlepton2p4 = genp.p4()
                    genlepton2C = genp.charge()
                    haveleptons=2
            if abs(genp.pdgId())==23 and genp.numberOfDaughters()>0 and abs(genp.daughter(1).pdgId())<7:
                genjetp4=genp.p4()
                havejet=1
            if abs(genp.pdgId())==23 and genp.numberOfDaughters()>0 and abs(genp.daughter(1).pdgId())>7:
                genZlep=genp.p4()
                havez=1

            if haveleptons==2 and havejet==1 and havez==1:
                break

        #print str(nevent)+ "  " + flavor
        # gen-level acceptance cuts:
        if genjetp4.pt()<80: # hadronic Z acceptance cut
            continue
        if genjetp4.mass()<70 or genjetp4.mass()>110: # hadronic Z acceptance cut
            continue        
        if (genlepton1p4 + genlepton2p4).pt() < 80: # leptonic Z acceptance cut
            continue 
        if (genlepton1p4 + genlepton2p4).mass() < 70 or(genlepton1p4 + genlepton2p4).mass() >110 :
            continue 
        if flavor == "ele": # electron acceptance
            if abs(genlepton1p4.eta())>2.5:
                continue
            if abs(genlepton2p4.eta())>2.5:
                continue
            if genlepton1p4.pt()<40 or genlepton2p4.pt()<40:
                continue
        if flavor == "mu": # muon acceptance
            if abs(genlepton1p4.eta())>2.4:
                continue
            if abs(genlepton2p4.eta())>2.4:
                continue
            if genlepton1p4.pt()<20 or genlepton2p4.pt()<20:
                continue
            if genlepton1p4.pt()<40 and genlepton2p4.pt()<40:
                contine
        if genjetp4.pt() <30: # jet acceptance
            continue
        if abs(genjetp4.eta())>2.4:
            continue

            
        #fill pure gen info
        if flavor == "ele":
            histo_ele_gen.Fill(genZlep.pt(),abs(genZlep.Eta()))
        if flavor == "mu":
            histo_mu_gen.Fill(genZlep.pt(),abs(genZlep.Eta()))
        histo_jet_gen.Fill(genjetp4.pt(),abs(genjetp4.eta()))

        if(event.eventAuxiliary().event() ==  2434343111):# strange fualty event
            continue
        if(event.eventAuxiliary().event() ==  43111):# strange fualty event
            continue
        #print str(event.eventAuxiliary().event())
        # fill matched jets objects
        event.getByLabel ("jetIDMerged", jethandle)
        recojets = jethandle.product()
        closest = -1
        closestDr = 99999.
        index = -1
        for jet in recojets:
            index += 1
            #acceptance cuts
            if jet.prunedMass() < 70 or jet.prunedMass() > 110:
                continue
            if jet.pt() < 80:
                continue
            if abs(jet.eta())>2.4:
                continue
            if not jet.getSelection("cuts_looseJetId"):
                continue
            if not jet.getSelection("cuts_TOBTECjetsId"):
                continue
            if jet.sourcePtr().get().userFloat("tau2")/jet.sourcePtr().get().userFloat("tau1") > 0.5:
                continue
            
            histo_jet_reco.Fill(jet.pt(),abs(jet.eta()))
            dr = deltaR(jet.eta(),jet.phi(),genjetp4.eta(),genjetp4.phi())
            if dr < closestDr:
                closestDr = dr
                closest = index

        if index != -1 and closestDr < 0.8: # found a matching VJet
            histo_jet_genMatch.Fill(genjetp4.pt(),abs(genjetp4.eta()))
            histo_jet_recoMatch.Fill(recojets[index].pt(),abs(recojets[index].eta()))
            if histo_jet_genMatch.FindBin(genjetp4.pt(),abs(genjetp4.eta())) == histo_jet_genMatch.FindBin(recojets[index].pt(),abs(recojets[index].eta())):
                histo_jet_stab.Fill(genjetp4.pt(),abs(genjetp4.eta()))
                histo_jet_pur.Fill(recojets[index].pt(),abs(recojets[index].eta()))

        #only proceed to leptons if event filters pass
        #this ensures trigger eff is taken into account
        #other event fitlers could go anywhere but need to be restricted to
        #either leptons or jets to avoid double counting
        if not event.object().triggerResultsByName("CMG").accept("eventFilterPath"):
            #print "failed trigger"
            continue

        #print "startele"
        # fill matched electrons objects
        if flavor == "ele":
            event.getByLabel ("ZeeCand", elehandle)
            recoeles = elehandle.product()
            closest1 = -1
            closestDr1 = 99999.
            index1 = -1
            for ele in recoeles:
                index1 += 1
            #acceptance cuts
                if ele.pt() < 80:
                    continue
            
                histo_ele_reco.Fill(ele.pt(),abs(ele.eta()))
                dr1 = deltaR(ele.eta(),ele.phi(),genZlep.eta(),genZlep.phi())
                if dr1 < closestDr1 :
                    closestDr1 = dr1
                    closest1 = index1

            if index1 != -1 and closestDr1 < 0.5: # found a matching electron for genlepon1
                histo_ele_genMatch.Fill(genZlep.pt(),abs(genZlep.Eta()))
                if histo_ele_genMatch.FindBin(genZlep.pt(),abs(genZlep.Eta())) == histo_ele_genMatch.FindBin(recoeles[index1].pt(),abs(recoeles[index1].eta())):
                    histo_ele_stab.Fill(genZlep.pt(),abs(genZlep.Eta()))
                    histo_ele_pur.Fill(recoeles[index1].pt(),abs(recoeles[index1].eta()))

    
           
       # fill matched muon objects
        if flavor == "mu":
            event.getByLabel ("ZmmCand", muhandle)
            recomus = muhandle.product()
            closest1 = -1
            closestDr1 = 99999.
            index1 = -1
            for mu in recomus:
                index1 += 1
            #acceptance cuts
                if mu.pt() < 80:
                    continue
                
                histo_mu_reco.Fill(mu.pt(),abs(mu.eta()))
                dr1 = deltaR(mu.eta(),mu.phi(),genZlep.eta(),genZlep.phi())
                if dr1 < closestDr1 :
                    closestDr1 = dr1
                    closest1 = index1


            if index1 != -1 and closestDr1 < 0.1: # found a matching muctron for genlepon1
                histo_mu_genMatch.Fill(genZlep.pt(),abs(genZlep.Eta()))
                histo_mu_recoMatch.Fill(recomus[index1].pt(),abs(recomus[index1].eta()))
                if histo_mu_genMatch.FindBin(genZlep.pt(),abs(genZlep.Eta())) == histo_mu_genMatch.FindBin(recomus[index1].pt(),abs(recomus[index1].eta())):
                    histo_mu_stab.Fill(genZlep.pt(),abs(genZlep.Eta()))
                    histo_mu_pur.Fill(recomus[index1].pt(),abs(recomus[index1].eta()))
示例#5
0
文件: ptdiff.py 项目: VinInn/pyTools
from DataFormats.FWLite import Handle, Events

from ROOT import gROOT, gStyle, TCanvas, TF1, TFile, TTree, gRandom, TH1F, TH2F
import os

gStyle.SetOptStat(111111)

eventsRef = Events("step3_40PU25ns_ori.root")
#eventsNew = Events("step3_40PU25ns_ori.root")
eventsNew = Events("step3_40PU25ns_vinoptmatch.root")
dir = 'ttbar_40PU25ns'

#eventsRef = Events('step2_SingleMuPt100_ori.root')
#eventsNew = Events('step2_SingleMuPt100_vinoptmatch.root')

#eventsRef = Events('SingleGamma10_ori.root')
#eventsNew = Events('SingleGamma10_vinpotmatch.root')

#eventsRef = Events('SinglePiPt1_ori.root')
#eventsNew = Events('SinglePi1_vinpotmatch.root')
#dir = "pi1"

#eventsRef = Events("TTBAR_relval_ori.root")
#eventsNew = Events("TTBAR_relval_vinpoptmatch.root")
#dir = 'ttbar'

eventsNew = Events("jetHT_reco_new2.root")
# eventsNew = Events('jetHT_reco_newTkGeom.root')

eventsRef = Events("jetHT_reco_710_ori.root")
# eventsNew = Events('jetHT_vinoptmatch_3.root')
示例#6
0
# initialise output files to save the flat ntuples
outfile_gen = ROOT.TFile('tau_gen_tuple.root', 'recreate')
ntuple_gen = ROOT.TNtuple('tree', 'tree', ':'.join(branches))
tofill_gen = OrderedDict(
    zip(branches,
        [-99.] * len(branches)))  # initialise all branches to unphysical -99

outfile_reco = ROOT.TFile('tau_reco_tuple.root', 'recreate')
ntuple_reco = ROOT.TNtuple('tree', 'tree', ':'.join(branches))
tofill_reco = OrderedDict(
    zip(branches,
        [-99.] * len(branches)))  # initialise all branches to unphysical -99

##########################################################################################
# Get ahold of the events
events = Events(
    'outputFULL.root')  # make sure this corresponds to your file name!
maxevents = -1  # max events to process
totevents = events.size()  # total number of events in the files

##########################################################################################
# instantiate the handles to the relevant collections.
# Do this *outside* the event loop
# Reminder: you can see the names of the collections stored in your input file by doing:
# edmDumpEventContent outputFULL.root

# PAT taus
label_taus = ('patTaus', '', 'TAURECO')
handle_taus = Handle('std::vector<pat::Tau>')

# PAT jets
label_jets = ('slimmedJets', '', 'PAT')
示例#7
0
    return math.atan((2 * z / 0.1) * math.tan(delta_phi_bend))


bend_2_1_3 = ROOT.TH1D("bend_2_1_3", "bend_2_1_3", 21, 0, 20)
bend_2_1_2 = ROOT.TH1D("bend_2_1_2", "bend_2_1_2", 21, 0, 20)
bend_2_2_2 = ROOT.TH1D("bend_2_2_2", "bend_2_2_2", 21, 0, 20)
bend_2_3_2 = ROOT.TH1D("bend_2_3_2", "bend_2_3_2", 21, 0, 20)
bend_2_4_2 = ROOT.TH1D("bend_2_4_2", "bend_2_4_2", 21, 0, 20)

wire_2_1_3 = ROOT.TH1D("wire_2_1_3", "wire_2_1_3", 112, 1, 112)
wire_2_1_2 = ROOT.TH1D("wire_2_1_2", "wire_2_1_2", 112, 1, 112)
wire_2_2_2 = ROOT.TH1D("wire_2_2_2", "wire_2_2_2", 112, 1, 112)
wire_2_3_2 = ROOT.TH1D("wire_2_3_2", "wire_2_3_2", 112, 1, 112)
wire_2_4_2 = ROOT.TH1D("wire_2_4_2", "wire_2_4_2", 112, 1, 112)

events = Events(['file:/scratch2/Leah/CMSSW_10_1_7/src/cscHits.root'])

N = 0
#make histograms for each (encap,station,ring) to find individual offsets
#x-axis is curvature (charge/pT); y-axis is phi(calculated by me)-phi(system)

for event in events:
    N = N + 1
    #    if N==100000:
    #        break;

    #real muons
    genMuons = fetchGEN(event)
    segmentsPhiDT = fetchDTSegmentsPhi(event)
    geantDT = fetchDTGEANT(event)
    geantCSC = fetchCSCGEANT(event)
示例#8
0
2mu2e 1:76489:173934403
2mu2e 1:45909:104394887
2mu2e 1:59905:136223608
2mu2e 1:3682:8371771
'''

f_dy_lt50 = os.path.join(
    os.getenv('CMSSW_BASE'),
    'src/Firefighter/ffConfig/python/production/Skim2LJ18/bkgmc/DYJetsToLL_M-10to50_TuneCP5_13TeV-madgraphMLM-pythia8.yml'
)
f_dy_gt50 = os.path.join(
    os.getenv('CMSSW_BASE'),
    'src/Firefighter/ffConfig/python/production/Skim2LJ18/bkgmc/DYJetsToLL_M-50_TuneCP5_13TeV-madgraphMLM-pythia8.yml'
)
files = []
files.extend(yaml.load(open(f_dy_gt50), Loader=yaml.Loader)['fileList'][0])

res = []
for f in tqdm(files):
    events = Events(f)
    for event in events:
        _run = event.object().id().run()
        _lumi = event.object().luminosityBlock()
        _event = event.object().id().event()
        tag = '{}:{}:{}'.format(_run, _lumi, _event)
        if tag in events_to_inspect:
            res.append((tag, f))
            # print(tag, f)

for tag, f in res:
    print(tag, f)
def analyze(deltaR, relPt, stNum):
    # deltaR: DeltaR of the matching cone
    # relPt: allowed relative pT deviation (1 = no deviation, 0 = infinit deviation)
    for file in fileList:
        event = [threading.Event(), threading.Event()]
        eventList.append(event)
    t = threading.Thread(target=downloadAll)
    t.start()

    ROOT.gROOT.SetStyle('Plain')  # white background

    ##    PLOTS   ##
    # Only RECO working / L1 working
    qualityCodes = ROOT.TH1D("QualityCodes", "QualityCodes", 100, -1.5, 98.5)
    qualityCodes2d = ROOT.TH2D("Quality Codes 2D", "Quality Codes 2D", 20,
                               -10.5, 9.5, 10, -5.5, 4.5)
    qualityCodes2dWrong = ROOT.TH2D("Quality Codes 2D Wrong",
                                    "Quality Codes 2D Wrong", 20, -10.5, 9.5,
                                    10, -5.5, 4.5)
    realPtVsL1Pt = ROOT.TH2D("Real Pt vs L1 HO Pt", "Real Pt vs L1 HO Pt", 100,
                             0, 500, 100, 0, 500)
    realPhiVsL1Phi = ROOT.TH2D("Real Phi vs L1 HO Pt", "Real Phi vs L1 HO Pt",
                               100, -.5, .5, 100, -.5, .5)
    realEtaVsL1Eta = ROOT.TH2D("Real Eta vs L1 HO Pt", "Real Eta vs L1 HO Pt",
                               100, -.5, .5, 100, -.5, .5)
    recoPositionOfMuons = ROOT.TH2D("Reco Position", "Reco Position", 100, -.5,
                                    .5, 628, -1. * math.pi, math.pi)
    genPositionsOfRecMuons = ROOT.TH2D("Gen Position of reconstructed muons",
                                       "Gen Position of reconstructed muons",
                                       100, -.5, .5, 628, -1. * math.pi,
                                       math.pi)

    numberOfFails = 0
    numberOfRecoveries = 0
    numberOfRecEvents = 0
    numberOfTooMany = 0

    for f in range(len(fileList)):

        eventList[f][0].wait()  #warten auf beide events event.wait()
        eventList[f][1].wait()
        print 'Files ', fileList[f][0], ' and ', fileList[f][
            1], ' are ready... analyzing them'

        eventsBad = Events(fileList[f][1])  #sample with dead MB1
        eventsGood = Events(fileList[f][0])

        eventsBad.toBegin()
        eventsGood.toBegin()

        eventsGood_iter = eventsGood.__iter__()
        eventsBad_iter = eventsBad.__iter__()

        for i in xrange(MAX_NUMBER):
            # GET THE EVENTS
            badEvent = eventsBad_iter.next()
            goodEvent = eventsGood_iter.next()

            # GET THE HANDLES
            badEvent.getByLabel(label, badMuonsHandle)
            badRecoMuons = badMuonsHandle.product()

            goodEvent.getByLabel(labelGenParticles, genParticlesHandle)
            genParticles = genParticlesHandle.product()

            badEvent.getByLabel(labelL1, badL1MuonsHandle)
            badL1Muons = badL1MuonsHandle.product()

            goodEvent.getByLabel(label, goodMuonsHandle)
            goodRecoMuons = goodMuonsHandle.product()

            goodEvent.getByLabel(labelL1, goodL1MuonsHandle)
            goodL1Muons = goodL1MuonsHandle.product()

            badEvent.getByLabel(labelHoEntries, hoEntriesHandle)
            badHoEntries = hoEntriesHandle.product()

            badEvent.getByLabel(labelPhiContainer, phiContainerHandle)
            phiContainer = phiContainerHandle.product()
            #----- END GET THE HANDLES -----
            badEvent.getByLabel(labelPhiContainer, phiContainerHandle)
            phiContainer = phiContainerHandle.product()
            #----- END GET THE HANDLES -----
            phiDigis = phiContainer.getContainer()

            badEvent.getByLabel(labelThContainer, thContainerHandle)
            thContainer = thContainerHandle.product()
            #----- END GET THE HANDLES -----
            thDigis = thContainer.getContainer()

            l1MuonTuple = []

            recoMuon = 0
            matchingBadMuon = 1  #L1Muon
            matchingGoodMuon = 2  #L1Muon

            matchedToGenRecoMuon = Utils.getMatch(genParticles[0],
                                                  goodRecoMuons, .1, .7)
            #print matchedToGenRecoMuon, " Matched to"

            for element in goodRecoMuons:
                if Utils.isInRange(element):
                    thisTuple = [
                        element,
                        Utils.getMatch(element, badL1Muons, deltaR, relPt),
                        Utils.getMatch(element, goodL1Muons, deltaR, relPt)
                    ]
                    l1MuonTuple.append(thisTuple)

            for j in range(len(l1MuonTuple)):
                element = l1MuonTuple[j]
                if not element[matchingGoodMuon] == None:
                    if element[matchingBadMuon] == None:
                        if abs(element[recoMuon].eta()) < Utils.getEta(
                                3.85, 1.28):
                            if element[recoMuon].phi(
                            ) >= -10. * math.pi / 180. and element[
                                    recoMuon].phi() < 20. / 180. * math.pi:
                                numberOfFails = numberOfFails + 1
                                print 'Event ' + str(
                                    i) + ', RECO (gen), pT: ', str(
                                        element[recoMuon].pt()), ' eta: ', str(
                                            element[recoMuon].eta()
                                        ), 'phi ', str(element[recoMuon].phi())
                                if printDigis(phiDigis, thDigis):
                                    candidates = getMuonCandidates(
                                        phiDigis, thDigis, badHoEntries,
                                        qualityCodes2d, stNum)
                                    if candidates:
                                        numberOfRecEvents = numberOfRecEvents + 1
                                    for c in candidates:
                                        c.printInfo()
                                        qualityCodes.Fill(c.quality)
                                        realPtVsL1Pt.Fill(
                                            element[recoMuon].pt(), c.pt)
                                        realPhiVsL1Phi.Fill(
                                            element[recoMuon].phi(), c.phi)
                                        realEtaVsL1Eta.Fill(
                                            element[recoMuon].eta(), c.eta)
                                        recoPositionOfMuons.Fill(c.eta, c.phi)
                                        numberOfRecoveries = numberOfRecoveries + 1
                                    if not candidates:
                                        qualityCodes.Fill(-1)
                                    if candidates:
                                        genPositionsOfRecMuons.Fill(
                                            element[recoMuon].eta(),
                                            element[recoMuon].phi())
                                    print '--------------------------- '
                    else:
                        if printDigis(phiDigis, thDigis):
                            candidates = getMuonCandidates(
                                phiDigis, thDigis, badHoEntries,
                                qualityCodes2dWrong, stNum)  #change plots!
                            for c in candidates:
                                c.printInfo()
                            if len(c) > 1:
                                numberOfTooMany = numberOfTooMany + 1

                    # Here we have the muons that are detected in L1 for the working detector, but are not detected in the non working detector anymore
                    # element[recoMuon] is the corresponding RECO muon (meaning the 'GEN' muon)
        #files Loeschen
        print 'Removing file: ', fileList[f][1]
        os.remove(fileList[f][1])  #sample with dead MB1
        print 'Removing file: ', fileList[f][0]
        os.remove(fileList[f][0])
    print 'Number of additional fails: ', str(numberOfFails)
    print 'Number of recovered events: ', str(numberOfRecEvents)
    print 'Number of recoveries : ', str(numberOfRecoveries)
    save('Quality.root', qualityCodes, realPtVsL1Pt, realPhiVsL1Phi,
         realEtaVsL1Eta, qualityCodes2d, genPositionsOfRecMuons,
         recoPositionOfMuons, qualityCodes2dWrong)
示例#10
0
vertices, vertexLabel = Handle(
    "std::vector<reco::Vertex>"), "offlinePrimaryVertices"
pfcands, pfcandLabel = Handle("std::vector<reco::PFCandidate>"), "particleFlow"
pfclusterhf, pfclusterhfLabel = Handle(
    "std::vector<reco::PFCluster>"), "particleFlowClusterHF"
pfrechithf, pfrechithfLabel = Handle(
    "std::vector<reco::PFRecHit>"), "particleFlowRecHitHF"
pftracks, pftrackLabel = Handle("std::vector<reco::PFRecTrack>"), "pfTrack"

# Phase2 SinglePion PU200
#events = Events('root://cms-xrd-global.cern.ch//store/mc/Phase2HLTTDRWinter20DIGI/SinglePion_PT0to200/GEN-SIM-DIGI-RAW/PU200_110X_mcRun4_realistic_v3-v2/10000/DD90F2CA-90F5-E449-96AC-6A868594B25E.root')
# Phase2 SinglePion NoPU
#events = Events('root://cms-xrd-global.cern.ch//store/mc/Phase2HLTTDRWinter20DIGI/SinglePion_PT0to200/GEN-SIM-DIGI-RAW/NoPU_110X_mcRun4_realistic_v3-v2/50000/E3B81E3A-9B35-A54B-A6E0-2A4D41CD83A5.root')
# Run 3
events = Events(
    'root://cms-xrd-global.cern.ch//store/relval/CMSSW_11_0_0_patch1/RelValSinglePiPt60GeV/GEN-SIM-DIGI-RAW/110X_mcRun3_2021_realistic_v6-v1/10000/BA6D7F51-9A29-0C4D-8480-08AF3874C33F.root'
)

for iev, event in enumerate(events):
    if iev >= 100: break
    event.getByLabel(genparLabel, genparticles)
    #event.getByLabel(caloparLabel, caloparticles)
    event.getByLabel(simtrackLabel, simtracks)
    #event.getByLabel(vertexLabel, vertices)
    #event.getByLabel(pfcandLabel, pfcands)
    #event.getByLabel(pfclusterhfLabel, pfclusterhf)
    #event.getByLabel(pfrechithfLabel, pfrechithf)
    #event.getByLabel(pftrackLabel, pftracks)

    # Vertices
    # H_NPV.Fill(len(vertices.product()))
示例#11
0
hJetsSoftDropMass = ROOT.TH1F("hJetsSoftDropMass", ";jet SoftDrop mass (GeV)",
                              30, 0, 300)
hJetsCSV = ROOT.TH1F("hJetsCSV", ";CSV value", 100, 0, 1)
hJetsCHF = ROOT.TH1F("hJetsCHF", ";Charged Hadron Fraction", 100, 0, 1)

hJet1Pt = ROOT.TH1F("hJet1Pt", ";jet pt (GeV)", 100, 0, 1000)
hJet1TrimmedMass = ROOT.TH1F("hJet1TrimmedMass", ";jet Trimmed mass (GeV)", 30,
                             0, 300)
hJet1PrunedMass = ROOT.TH1F("hJet1PrunedMass", ";jet Pruned mass (GeV)", 30, 0,
                            300)
hJet1SoftDropMass = ROOT.TH1F("hJet1SoftDropMass", ";jet SoftDrop mass (GeV)",
                              30, 0, 300)
hJet1CHF = ROOT.TH1F("hJet1CHF", ";Charged Hadron Fraction", 100, 0, 1)

#EVENT LOOP
events = Events('jettoolbox.root')
PUMethod = 'Puppi'

handle = Handle("std::vector<pat::Jet>")
label = ("selectedPatJetsAK4PF" + PUMethod)

# loop over events in this file
nevents = 0
for event in events:

    nevents += 1
    if nevents % 10 == 0: print '    ---> Event ' + str(nevents)

    event.getByLabel(label, handle)
    jets = handle.product()
示例#12
0
def processSubsample(file):
    events = Events(file)

    # create handle outside of loop
    genhandle = Handle('std::vector<reco::GenParticle>')
    #recofullhandleEle  = Handle ('std::vector<pat::Muon>')
    #recofullhandleMu   = Handle ('std::vector<pat::Muon>')
    elehandle = Handle('std::vector<cmg::Electron>')
    muhandle = Handle('std::vector<cmg::Muon>')
    jethandle = Handle('std::vector<cmg::VJet>')
    # a label is just a tuple of strings that is initialized just
    # like and edm::InputTag
    nevent = 0
    for event in events:
        nevent += 1
        if nevent % 10000 == 0:
            print "event: " + str(nevent)

        # determine generated flavor and get generated kinematics
        haveleptons = 0
        havejet = 0
        flavor = ""
        genlepton1p4 = root.TLorentzVector()
        genlepton1C = 0
        genlepton2p4 = root.TLorentzVector()
        genlepton2C = 0
        genjetp4 = root.TLorentzVector()
        event.getByLabel("genParticles", genhandle)
        genparticles = genhandle.product()
        for genp in genparticles:
            if (abs(genp.pdgId()) == 11 or abs(genp.pdgId())
                    == 13) and genp.mother().pdgId() == 23:
                if (abs(genp.pdgId()) == 11):
                    flavor = "ele"
                if (abs(genp.pdgId()) == 13):
                    flavor = "mu"
                if haveleptons == 0:
                    genlepton1p4 = genp.p4()
                    genlepton1C = genp.charge()
                    haveleptons = 1
                elif haveleptons == 1:
                    genlepton2p4 = genp.p4()
                    genlepton2C = genp.charge()
                    haveleptons = 2
            if abs(genp.pdgId()) == 23 and genp.numberOfDaughters(
            ) > 0 and abs(genp.daughter(1).pdgId()) < 7:
                genjetp4 = genp.p4()
                havejet = 1

            if haveleptons == 2 and havejet == 1:
                break

        # gen-level acceptance cuts:
        if genjetp4.pt() < 80:  # hadronic Z acceptance cut
            continue
        if genjetp4.mass() < 70 or genjetp4.mass(
        ) > 110:  # hadronic Z acceptance cut
            continue
        if (genlepton1p4 +
                genlepton2p4).pt() < 80:  # leptonic Z acceptance cut
            continue
        if (genlepton1p4 + genlepton2p4).mass() < 70 or (
                genlepton1p4 + genlepton2p4).mass() > 110:
            continue
        if flavor == "ele":  # electron acceptance
            if abs(genlepton1p4.eta()) > 2.5:
                continue
            if abs(genlepton2p4.eta()) > 2.5:
                continue
            if genlepton1p4.pt() < 40 or genlepton2p4.pt() < 40:
                continue
        if flavor == "mu":  # muon acceptance
            if abs(genlepton1p4.eta()) > 2.4:
                continue
            if abs(genlepton2p4.eta()) > 2.4:
                continue
            if genlepton1p4.pt() < 20 or genlepton2p4.pt() < 20:
                continue
            if genlepton1p4.pt() < 40 and genlepton2p4.pt() < 40:
                contine
        if genjetp4.pt() < 30:  # jet acceptance
            continue
        if abs(genjetp4.eta()) > 2.4:
            continue

        #fill pure gen info
        if flavor == "ele":
            histo_ele_gen.Fill(genlepton1p4.pt(), abs(genlepton1p4.eta()))
            histo_ele_gen.Fill(genlepton2p4.pt(), abs(genlepton2p4.eta()))
        if flavor == "mu":
            histo_mu_gen.Fill(genlepton1p4.pt(), abs(genlepton1p4.eta()))
            histo_mu_gen.Fill(genlepton2p4.pt(), abs(genlepton2p4.eta()))
        histo_jet_gen.Fill(genjetp4.pt(), abs(genjetp4.eta()))

        # fill matched jets objects
        event.getByLabel("jetIDMerged", jethandle)
        recojets = jethandle.product()
        closest = -1
        closestDr = 99999.
        index = -1
        for jet in recojets:
            index += 1
            #acceptance cuts
            if jet.prunedMass() < 70 or jet.prunedMass() > 110:
                continue
            if jet.pt() < 80:
                continue
            if abs(jet.eta()) > 2.4:
                continue
            histo_jet_reco.Fill(jet.pt(), abs(jet.eta()))
            dr = deltaR(jet.eta(), jet.phi(), genjetp4.eta(), genjetp4.phi())
            if dr < closestDr:
                closestDr = dr
                closest = index

        if index != -1 and closestDr < 0.8:  # found a matching VJet
            histo_jet_genMatch.Fill(genjetp4.pt(), abs(genjetp4.eta()))
            histo_jet_recoMatch.Fill(recojets[index].pt(),
                                     abs(recojets[index].eta()))
            if histo_jet_genMatch.FindBin(genjetp4.pt(), abs(
                    genjetp4.eta())) == histo_jet_genMatch.FindBin(
                        recojets[index].pt(), abs(recojets[index].eta())):
                histo_jet_stab.Fill(genjetp4.pt(), abs(genjetp4.eta()))
                histo_jet_pur.Fill(recojets[index].pt(),
                                   abs(recojets[index].eta()))

        #print "startele"
        # fill matched electrons objects
        if flavor == "ele":
            event.getByLabel("electronPresel", elehandle)
            recoeles = elehandle.product()
            closest1 = -1
            closestDr1 = 99999.
            index1 = -1
            closest2 = -1
            closestDr2 = 99999.
            index2 = -1
            for ele in recoeles:
                index1 += 1
                index2 += 1
                #acceptance cuts
                if ele.pt() < 40:
                    continue
                if abs(ele.eta()) > 2.5:
                    continue
                if abs(ele.sourcePtr().get().superCluster().get().eta(
                )) < 1.566 and abs(ele.sourcePtr().get().superCluster().get().
                                   eta()) > 1.4442:
                    continue
                histo_ele_reco.Fill(ele.pt(), abs(ele.eta()))
                dr1 = deltaR(ele.eta(), ele.phi(), genlepton1p4.eta(),
                             genlepton1p4.phi())
                dr2 = deltaR(ele.eta(), ele.phi(), genlepton2p4.eta(),
                             genlepton2p4.phi())
                if dr1 < closestDr1 and ele.charge() == genlepton1C:
                    closestDr1 = dr1
                    closest1 = index1
                if dr2 < closestDr2 and ele.charge() == genlepton2C:
                    closestDr2 = dr2
                    closest2 = index2

            if index1 != -1 and closestDr1 < 0.3:  # found a matching electron for genlepon1
                histo_ele_genMatch.Fill(genlepton1p4.pt(),
                                        abs(genlepton1p4.eta()))
                histo_ele_recoMatch.Fill(recoeles[index1].pt(),
                                         abs(recoeles[index1].eta()))
                if histo_ele_genMatch.FindBin(
                        genlepton1p4.pt(),
                        abs(genlepton1p4.eta())) == histo_ele_genMatch.FindBin(
                            recoeles[index1].pt(),
                            abs(recoeles[index1].eta())):
                    histo_ele_stab.Fill(genlepton1p4.pt(),
                                        abs(genlepton1p4.eta()))
                    histo_ele_pur.Fill(recoeles[index1].pt(),
                                       abs(recoeles[index1].eta()))

            if index2 != -1 and closestDr2 < 0.3:  # found a matching electron for genlepon2
                histo_ele_genMatch.Fill(genlepton2p4.pt(),
                                        abs(genlepton2p4.eta()))
                histo_ele_recoMatch.Fill(recoeles[index2].pt(),
                                         abs(recoeles[index2].eta()))
                if histo_ele_genMatch.FindBin(
                        genlepton2p4.pt(),
                        abs(genlepton2p4.eta())) == histo_ele_genMatch.FindBin(
                            recoeles[index2].pt(),
                            abs(recoeles[index2].eta())):
                    histo_ele_stab.Fill(genlepton2p4.pt(),
                                        abs(genlepton2p4.eta()))
                    histo_ele_pur.Fill(recoeles[index2].pt(),
                                       abs(recoeles[index2].eta()))

    # fill matched muon objects
        if flavor == "mu":
            event.getByLabel("muonPreselNoIso", muhandle)
            recomus = muhandle.product()
            closest1 = -1
            closestDr1 = 99999.
            index1 = -1
            closest2 = -1
            closestDr2 = 99999.
            index2 = -1
            for mu in recomus:
                index1 += 1
                index2 += 1
                #acceptance cuts
                if mu.pt() < 20:
                    continue
                if abs(mu.eta()) > 2.4:
                    continue
                histo_mu_reco.Fill(mu.pt(), abs(mu.eta()))
                dr1 = deltaR(mu.eta(), mu.phi(), genlepton1p4.eta(),
                             genlepton1p4.phi())
                dr2 = deltaR(mu.eta(), mu.phi(), genlepton2p4.eta(),
                             genlepton2p4.phi())
                if dr1 < closestDr1 and mu.charge() == genlepton1C:
                    closestDr1 = dr1
                    closest1 = index1
                if dr2 < closestDr2 and mu.charge() == genlepton2C:
                    closestDr2 = dr2
                    closest2 = index2

            if index1 != -1 and closestDr1 < 0.3:  # found a matching muctron for genlepon1
                histo_mu_genMatch.Fill(genlepton1p4.pt(),
                                       abs(genlepton1p4.eta()))
                histo_mu_recoMatch.Fill(recomus[index1].pt(),
                                        abs(recomus[index1].eta()))
                if histo_mu_genMatch.FindBin(
                        genlepton1p4.pt(),
                        abs(genlepton1p4.eta())) == histo_mu_genMatch.FindBin(
                            recomus[index1].pt(), abs(recomus[index1].eta())):
                    histo_mu_stab.Fill(genlepton1p4.pt(),
                                       abs(genlepton1p4.eta()))
                    histo_mu_pur.Fill(recomus[index1].pt(),
                                      abs(recomus[index1].eta()))

            if index2 != -1 and closestDr2 < 0.3:  # found a matching muctron for genlepon2
                histo_mu_genMatch.Fill(genlepton2p4.pt(),
                                       abs(genlepton2p4.eta()))
                histo_mu_recoMatch.Fill(recomus[index2].pt(),
                                        abs(recomus[index2].eta()))
                if histo_mu_genMatch.FindBin(
                        genlepton2p4.pt(),
                        abs(genlepton2p4.eta())) == histo_mu_genMatch.FindBin(
                            recomus[index2].pt(), abs(recomus[index2].eta())):
                    histo_mu_stab.Fill(genlepton2p4.pt(),
                                       abs(genlepton2p4.eta()))
                    histo_mu_pur.Fill(recomus[index2].pt(),
                                      abs(recomus[index2].eta()))
示例#13
0
import sys
from DataFormats.FWLite import Events, Handle

# Make VarParsing object
# https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideAboutPythonConfigFile#VarParsing_Example
from FWCore.ParameterSet.VarParsing import VarParsing
options = VarParsing ('python')
options.parseArguments()

# Events takes either
# - single file name
# - list of file names
# - VarParsing options

# use Varparsing object
events = Events (options)
# use single file name
#events = Events ("root://cmsxrootd.fnal.gov///store/mc/RunIISummer20UL17MiniAODv2/DYJetsToMuMu_M-50_TuneCP5_13TeV-madgraphMLM-pythia8/MINIAODSIM/PUForMUOVal_106X_mc2017_realistic_v9-v2/100000/002FD620-0EF8-F044-9D21-7303C48FF2A0.root")

# create handle outside of loop
handle  = Handle ("std::vector<pat::Muon>")

# for now, label is just a tuple of strings that is initialized just
# like and edm::InputTag
label = ("slimmedMuons")

# Create histograms, etc.
ROOT.gROOT.SetBatch()        # don't pop up canvases
ROOT.gROOT.SetStyle('Plain') # white background
zmassHist = ROOT.TH1F ("zmass", "Z Candidate Mass", 50, 20, 220)
示例#14
0
from DataFormats.FWLite import Handle, Events
from ROOT import gROOT, gStyle, TCanvas, TF1, TFile, TTree, gRandom, TH1F, TH2F
import os

eventsRef = Events("step3.root")

tracksRef = Handle("std::vector<reco::Track>")
label = "generalTracks"
quality = "highPurity"
#quality = "tight"
#quality = "loose"

mcMatchRef = Handle("std::vector<float>")

nmu = 0
nmuOnly = 0
nmuNotConf = 0
for i in range(0, eventsRef.size()):
    #for i in range(0, 200):
    a = eventsRef.to(i)
    print "Event", i
    a = eventsRef.getByLabel(label, tracksRef)
    a = eventsRef.getByLabel("trackMCQuality", mcMatchRef)
    mcMatch = mcMatchRef.product()
    trVal = []
    k = -1
    for track in tracksRef.product():
        k += 1
        #   if (track.phi()<0) : continue
        if (abs(track.eta()) > 2.3): continue
        if (track.pt() < 4): continue
示例#15
0
vertices, vertexLabel = Handle("std::vector<reco::Vertex>"), "offlinePrimaryVertices"
pfcands, pfcandLabel = Handle("std::vector<reco::PFCandidate>"), "particleFlow"

pfcandPtScore = Handle("edm::ValueMap<float>")
verticesScore = Handle("edm::ValueMap<float>")

print len(sys.argv)

if len(sys.argv)>1:
    output=sys.argv[1]
else:
    output="PFH_CaloEnergy_JetHT_2018D-10_6_0_MatrixTest"
        
# open file (you can use 'edmFileUtil -d /store/whatever.root' to get the physical file name)
if output == "PFH_CaloEnergy_FlatQCD_NoPU_2018":
    events = Events('root://cmsxrootd.fnal.gov//store/relval/CMSSW_10_6_0/RelValQCD_FlatPt_15_3000HS_13/GEN-SIM-RECO/106X_upgrade2018_realistic_v4-v1/10000/6C4012B3-14CA-8844-8301-D4B253D75644.root')
elif output == "PFH_CaloEnergy_FlatQCD_PU_2018":
    events = Events('root://cmsxrootd.fnal.gov//store/relval/CMSSW_10_6_0/RelValQCD_FlatPt_15_3000HS_13/GEN-SIM-RECO/PU25ns_106X_upgrade2018_realistic_v4-v1/10000/FDEFFEB4-107A-8B44-8E52-F84F8B3E158A.root')
elif output == "PFH_CaloEnergy_SingleMuon_2016C":
    events = Events('root://cmsxrootd.fnal.gov//store/data/Run2016C/SingleMuon/AOD/07Aug17-v1/110001/44B1F7D7-3F80-E711-AE45-001E67E6F4A9.root')
elif output == "PFH_CaloEnergy_SingleMuon_2017C":
    events = Events('root://cmsxrootd.fnal.gov//store/data/Run2017C/SingleMuon/AOD/17Nov2017-v1/70000/A073FB9C-6CDA-E711-9551-02163E01A465.root')
elif output == "PFH_CaloEnergy_SingleMuon_2018C":
    events = Events('root://cmsxrootd.fnal.gov//store/data/Run2018C/SingleMuon/AOD/17Sep2018-v1/00001/56DF33B4-0A6E-2747-99BC-3FD669B097FF.root')
elif output == "PFH_CaloEnergy_SingleMuon_2016H-10_6_0_Relval":
    events = Events('root://cmsxrootd.fnal.gov//store/relval/CMSSW_10_6_0/SingleMuon/RECO/106X_dataRun2_v10_RelVal_2016H-v1/10000/BC6B00A1-72AF-FF44-861E-87DD48C2F41C.root')
elif output == "PFH_CaloEnergy_SingleMuon_2017F-10_6_0_Relval":
    events = Events('root://cmsxrootd.fnal.gov//store/relval/CMSSW_10_6_0/SingleMuon/RECO/106X_dataRun2_v10_RelVal_2017F-v1/10000/515ED924-A207-2146-9C0F-6F99A20F2DB0.root')
elif output == "PFH_CaloEnergy_SingleMuon_2018C-10_6_0_Relval":
    events = Events('root://cmsxrootd.fnal.gov//store/relval/CMSSW_10_6_0/SingleMuon/RECO/106X_dataRun2_v10_resub_RelVal_2018C-v1/10000/66466716-600E-B540-BB79-6FC151D62972.root')
elif output == "PFH_CaloEnergy_JetHT_2018D-10_6_0_MatrixTest":
示例#16
0
simHitsLabel, simHits = ("g4SimHits", "MuonGEMHits"), Handle("vector<PSimHit>")

h_cls = ROOT.TH2D("GEM RecHit Cluster size",
                  "GEM RecHit Cluster size; Cluster size; i#eta", 10, 0, 10, 8,
                  1, 9)
h_dx = ROOT.TH1D("GEM RecHit Resolution X",
                 "GEM RecHit Resolution X; #delta x; i#eta", 30, -5, 5)
h_sim_ieta = ROOT.TH1D("GEM SimHit i#eta",
                       "GEM SimHit i#eta; i#eta; Number of GEMSimHit", 8, 1, 9)
h_sim_ieta_matched = ROOT.TH1D(
    "GEM SimHit i#eta matched",
    "GEM SimHit i#eta matched; #ieta; Number of GEMSimHit", 8, 1, 9)

fdir = "../step3.root"

events = Events(fdir)
for iev, event in enumerate(events):
    print "iev", iev

    event.getByLabel(simHitsLabel, simHits)
    event.getByLabel(gemRecHitsLabel, gemRecHits)

    for rh in gemRecHits.product():
        h_cls.Fill(rh.gemId().roll(), rh.clusterSize())

    for sh in simHits.product():
        detId = ROOT.DetId(sh.detUnitId())
        if detId.det() != 2: continue  # Muon detector
        if detId.subdetId() != 4: continue  # GEM detector

        gemDetId = ROOT.GEMDetId(detId)
示例#17
0
#! /usr/bin/env python3
import ROOT
from DataFormats.FWLite import Events, Handle

events = Events(['good_a.root'])

handleGP = Handle("edmtest::Thing")
labelGP = ("Thing")

for event in events:
    if event.getByLabel(labelGP, handleGP):
        prod = handleGP.product()
示例#18
0
def main():
    vhdl_dict = VHDLConstantsParser.parse_vhdl_file("../data/ugmt_constants.vhd")

    opts = parse_options()
    fname_dict = discover_emu_files(opts.emudirectory)

    ALGODELAY = 60 #first frame with valid = 1

    max_events = int((1024-ALGODELAY)/6)

    for pattern, fnames in fname_dict.iteritems():

        print "+"*30, pattern, "+"*30
        events = Events(fnames['root'])

        out_handle = Handle('BXVector<l1t::Muon>')
        imd_handle = Handle('BXVector<l1t::Muon>')
        bar_handle = Handle('std::vector<l1t::L1TRegionalMuonCandidate>')
        fwd_handle = Handle('std::vector<l1t::L1TRegionalMuonCandidate>')
        ovl_handle = Handle('std::vector<l1t::L1TRegionalMuonCandidate>')

        calo_handle = Handle('std::vector<l1t::L1TGMTInputCaloSum>')

        basedir_mp7 = "patterns/compressed/"
        path = '{path}/{pattern}/'.format(path=basedir_mp7, pattern=pattern)

        input_buffer = PatternDumper(basedir_mp7+pattern+".txt", vhdl_dict, BufferWriter)
        output_buffer = PatternDumper(basedir_mp7+pattern+"_out.txt", vhdl_dict, BufferWriter)

        if opts.delay > 0:
            input_buffer.writeEmptyFrames(opts.delay)

        output_buffer.writeEmptyFrames(ALGODELAY)
        cntr = 0
        for i, event in enumerate(events):
            event.getByLabel("microGMTEmulator", out_handle)
            event.getByLabel("microGMTEmulator", "intermediateMuons", imd_handle)
            event.getByLabel("uGMTInputProducer", "BarrelTFMuons", bar_handle)
            event.getByLabel("uGMTInputProducer", "ForwardTFMuons", fwd_handle)
            event.getByLabel("uGMTInputProducer", "OverlapTFMuons", ovl_handle)

            event.getByLabel("uGMTInputProducer", "TriggerTowerSums", calo_handle)

            calo_sums_raw = calo_handle.product()
            calo_sums = get_calo_list(calo_sums_raw)

            emu_out_muons = out_handle.product()
            outmuons = get_muon_list_out(emu_out_muons, "OUT", vhdl_dict)
            imd_prod = imd_handle.product()
            imdmuons = get_muon_list_out(imd_prod, "IMD", vhdl_dict)
            emu_bar_muons = bar_handle.product()
            bar_muons = get_muon_list(emu_bar_muons, "BMTF", vhdl_dict)
            emu_ovl_muons = ovl_handle.product()
            ovlp_muons = get_muon_list(emu_ovl_muons, "OMTF_POS", vhdl_dict)
            ovln_muons = get_muon_list(emu_ovl_muons, "OMTF_NEG", vhdl_dict)
            emu_fwd_muons = fwd_handle.product()
            fwdp_muons = get_muon_list(emu_fwd_muons, "EMTF_POS", vhdl_dict)
            fwdn_muons = get_muon_list(emu_fwd_muons, "EMTF_NEG", vhdl_dict)
            for mu in outmuons:
                if mu.bitword != 0: cntr += 1
            input_buffer.writeFrameBasedInputBX(bar_muons, fwdp_muons, fwdn_muons, ovlp_muons, ovln_muons, calo_sums)
            output_buffer.writeFrameBasedOutputBX(outmuons, imdmuons)

            if i%(max_events-1) == 0 and i != 0: # dump every max_events
                ifile = i/max_events
                print "Writing file {pattern}_{ifile}.zip for event {i}".format(pattern=pattern, ifile=ifile, i=i)
                dump_files(path, pattern, ifile, input_buffer, output_buffer, opts.delay, ALGODELAY)


            if (i+1)%1000 == 0:
                print "  processing the {i}th event".format(i=i+1)
        print 'n final muons: ', cntr
        if i%(max_events-1) != 0:
            ifile = i/max_events
            dump_files(path, pattern, ifile, input_buffer, output_buffer, opts.delay, ALGODELAY)

        print (i+1)/max_events
示例#19
0
hETau_TauPt = ROOT.TH1F("hETau_TauPt", "tau Pt;P_{t};N_{events}", 50, 0, 500)
hETau_EPt = ROOT.TH1F("hETau_EPt", "electron Pt;P_{t};N_{events}", 50, 0, 500)
hETau_dR = ROOT.TH1F("hETau_dR", "e - #tau delta R;#delta R;N_{events}", 20, 0,
                     1)

hMuTau_M = ROOT.TH1F("hMuTau_M", "#mu - #tau mass;M_{#mu#tau};N_{events}", 100,
                     0, 100)
hMuTau_TauPt = ROOT.TH1F("hMuTau_TauPt", "tau Pt;P_{t};N_{events}", 50, 0, 500)
hMuTau_MuPt = ROOT.TH1F("hMuTau_MuPt", "muon Pt;P_{t};N_{events}", 50, 0, 500)
hMuTau_dR = ROOT.TH1F("hMuTau_dR", "#mu - #tau delta R;#delta R;N_{events}",
                      20, 0, 1)

#for job in jobs:

events = Events(
    prefix +
    "ggh01_M125_Toa01a01_M15_Tomumutautau_slc7_amd64_gcc700_CMSSW_10_6_19_tarball_7918040_15_recoAOD.root"
)
nevt = 0
for event in events:
    nevt += 1

    event.getByLabel(labelGenJet, handleGenJet)
    jets = handleGenJet.product()

    jets = []
    for jet in handleGenJet.product():
        if jet.pt() < 20 or abs(jet.eta()) > 2.5: continue
        jets += [jet]

    jets.sort(key=lambda x: x.pt(), reverse=True)
taus, tauLabel = Handle("std::vector<pat::Tau>"), "slimmedTaus"
jets, jetLabel = Handle("std::vector<pat::Jet>"), "slimmedJets"
fatjets, fatjetLabel = Handle("std::vector<pat::Jet>"), "slimmedJetsAK8"
mets, metLabel = Handle("std::vector<pat::MET>"), "slimmedMETs"
vertices, vertexLabel = Handle(
    "std::vector<reco::Vertex>"), "offlineSlimmedPrimaryVertices"
pfcands, pfcandLabel = Handle(
    "std::vector<pat::PackedCandidate>"), "packedPFCandidates"
pfcandHcalDepthLabel = ("packedPFCandidates", "hcalDepthEnergyFractions")

pfcandPtScore = Handle("edm::ValueMap<float>")
hcalDepthScore = Handle("edm::ValueMap<pat::HcalDepthEnergyFractions>")
verticesScore = Handle("edm::ValueMap<float>")

# open file (you can use 'edmFileUtil -d /store/whatever.root' to get the physical file name)
events = Events('file:step3_inMINIAODSIM.root')

for iev, event in enumerate(events):
    if iev >= 10: break
    event.getByLabel(muonLabel, muons)
    event.getByLabel(electronLabel, electrons)
    event.getByLabel(photonLabel, photons)
    event.getByLabel(tauLabel, taus)
    event.getByLabel(jetLabel, jets)
    event.getByLabel(metLabel, mets)
    event.getByLabel(vertexLabel, vertices)
    event.getByLabel(vertexLabel, verticesScore)
    event.getByLabel(pfcandLabel, pfcands)
    event.getByLabel(pfcandHcalDepthLabel, hcalDepthScore)
    print "\nEvent %d: run %6d, lumi %4d, event %12d" % (
        iev,
示例#21
0
# FWLite aggregates ALL of the information immediately, which
# can take a long time to parse.
files = []
with open(options.files) as filelist:
    for line in filelist:
        if len(line) <= 2:
            continue
        s = 'root://' + options.xrootd + '/' + line.rstrip()
        files.append( s )
        print 'Added ' + s

# loop over files
nevents = 0
for ifile in files :
    print 'Processing file ' + ifile
    events = Events (ifile)
    if options.maxevents > 0 and nevents > options.maxevents :
        break

    # loop over events in this file
    i = 0
    for event in events:
        if options.maxevents > 0 and nevents > options.maxevents :
            break
        i += 1
        nevents += 1

        if i % 1000 == 0 :
            print '    ---> Event ' + str(i)

        ##    _____   ____  __.  _____        ____.       __    __________.__          __
示例#22
0
            line = commentRE.sub('', line).strip()  # get rid of comments
            if not line:
                # don't bother with blank lines
                continue
            listOfFiles.append(line)
        source.close()
    if options.prefix:
        oldList = listOfFiles
        listOfFiles = []
        for name in oldList:
            listOfFiles.append(options.prefix + name)

    if not listOfFiles:
        raise RuntimeError("You have not provided any files")

    events = Events(listOfFiles)

    handle = Handle('vector<PileupSummaryInfo>')
    label = ('addPileupInfo')

    ROOT.gROOT.SetBatch()  # don't pop up canvases

    # loop over events
    countDict = {}
    total = 0.
    for event in events:
        event.getByLabel(label, handle)
        pileups = handle.product()
        for pileup in pileups:
            if pileup.getBunchCrossing() == options.bx:
                break
from ROOT import *
from math import sqrt
from DataFormats.FWLite import Handle, Events
events = Events("output.root")
secondaryVertices = Handle("std::vector<reco::VertexCompositeCandidate>")
mass_histogram = TH1F("mass", "mass", 100, 0.4, 0.6)
dxy_histogram = TH1F("dxy", "dxy", 100, 0, 50)

i = 0
events.toBegin()
for event in events:
    print "Event:", i
    event.getByLabel("SecondaryVerticesFromLooseTracks", "Kshort",
                     secondaryVertices)
    j = 0
    sv = secondaryVertices.product()
    for vertex in sv:
        print "    Vertex:", j, vertex.vx(), vertex.vy(), vertex.vz()
        mass_histogram.Fill(vertex.mass())
        dxy_histogram.Fill(sqrt(vertex.vx()**2 + vertex.vy()**2))
        j += 1

    i += 1
c = TCanvas("c", "c", 800, 800)
mass_histogram.Draw()
c.SaveAs("sec_vert_mass.png")

c2 = TCanvas("c2", "c2", 800, 800)
dxy_histogram.Draw()
c2.SaveAs("sec_vert_dxy.png")
示例#24
0
commoncf = "abs(" + mZ + "-90.2)<12.&&muonsPt[0]>15 && muonsPt[1]>15 && muonsPFRelIso[0]<0.15 && muonsPFRelIso[1]<0.15"
#c.Scan(mZ,"muonsPt[0]>15 && muonsPt[1]>15 && muonsPFRelIso[0]<0.15 && muonsPFRelIso[1]<0.15")
c.Draw(">>eList", commoncf)
eList = ROOT.gDirectory.Get('eList')


def getVarName(v):
    return v.split('/')[0]


def getVarType(v):
    if v.count('/'): return v.split('/')[1]
    return 'F'


events = Events(filelist)
pfhandle = Handle("vector<reco::PFCandidate>")
events.toBegin()
labelpf = ("particleFlow")
#labelpfmet = ("pfMet")
labelpfmet = ("patPFMet")
#pfMethandle = Handle("vector<reco::PFMET>")
pfMethandle = Handle("float")

usedPFTypes = categories.keys()
storedVars = ['MEx/F', 'MEy/F', 'nCand/I']
extraVars = [
    'phiZ/F', 'ptZ/F', 'MEx/F', 'MEy/F', 'nCand/I', 'patMEx/F', 'patMEy/F',
    'ngoodVertices/I'
]
示例#25
0
import ROOT
from DataFormats.FWLite import Handle, Events

events = Events(
    "root://cmseos.fnal.gov//store/user/jmanagan/TrackingHATS2017/tracks_and_vertices_DoubleMuon2017C_299370.root"
)

clusterSummary = Handle("ClusterSummary")

h = ROOT.TH2F("h", "h", 100, 0, 20000, 100, 0, 100000)

events.toBegin()
for event in events:
    event.getByLabel("clusterSummaryProducer", clusterSummary)
    cs = clusterSummary.product()
    try:
        h.Fill(
            cs.GetGenericVariable(cs.NMODULESPIXELS, cs.BPIX) +
            cs.GetGenericVariable(cs.NMODULESPIXELS, cs.FPIX),
            cs.GetGenericVariable(cs.NMODULES, cs.TRACKER))
    except TypeError:
        pass

h.Draw()
h.Fit("pol1")
示例#26
0
import ROOT
import os
import psutil

process = psutil.Process(os.getpid())
print process.__dict__
print process.memory_info().__dict__
from DataFormats.FWLite import Handle, Events
ROOT.gSystem.Load("libFWCoreFWLite.so")
ROOT.gSystem.Load("libDataFormatsFWLite.so")
ROOT.FWLiteEnabler.enable()

makeitleak = True
altCall = True

events = Events(["testoutAOD100.root"])
offEle_source, offEle_label = Handle("vector<reco::GsfElectron>"), (
    "gedGsfElectrons")
offMu_source, offMu_label = Handle("vector<reco::Muon>"), ("muons")
MuGlobalTracks_source, MuGlobalTracks_label = Handle("vector<reco::Track>"), (
    "globalTracks")
if makeitleak:
    eleLooseID_source, eleLooseID_label = Handle("<edm::ValueMap<bool>>"), (
        "egmGsfElectronIDs:cutBasedElectronID_Fall17_94X_V1_loose")
    eleTightID_source, eleTightID_label = Handle("<edm::ValueMap<bool>>"), (
        "egmGsfElectronIDs:cutBasedElectronID_Fall17_94X_V1_tight")
offJets_source, offJets_label = Handle("vector<reco::PFJet>"), ("ak4PFJetsCHS")
offbTags_source, offbTags_label = Handle(
    "edm::AssociationVector<edm::RefToBaseProd<reco::Jet>,vector<float>>"), (
        "pfCombinedInclusiveSecondaryVertexV2BJetTags")
    #if not 'psi' in study: continue
    dataset = CMSSW + ' ' + study
    print "\nProcessing %s" % dataset

    maxBkgEff = info['maxBkgEff']
    if CMSSW in info['files']:
        files = info['files'][CMSSW]
    else:
        print "No %s in %s dictionary, skipping it" % (CMSSW, study)
        continue
    print "\nNumber of input files: %d" % len(files)
    if not len(files):
        print "No input files provided for %s" % dataset
        continue

    events = Events(files)
    totEvents = events.size()
    print "Total number of events: %d" % totEvents
    maxEvents = totEvents
    if n_events_limit and n_events_limit < totEvents:
        maxEvents = n_events_limit
    print "\nWill process %d events" % maxEvents

    for analysis, cuts in preSelection.items():
        #if not 'BPH-18-002' in analysis: continue
        label = analysis + ' from ' + CMSSW + ' ' + study

        print "\nProcessing %s with %s pre-selection:" % (dataset, analysis)
        muonPtCut = "%.2f\t< pT(muon) [GeV]\t< %.2f" % (cuts['minPt'],
                                                        cuts['maxPt'])
        muonPtCutText = "%.1f < p_{T}(#mu) < %.1f" % (
def loopMiniAOD(files, hnum, hdenom, hnLS, Triggers2Save, maxEvents = -1, isMC = False, jsonFile = None):
    t0 = time.time()
    
    expJSON = None
    if jsonFile is not None:
        expJSON = expandJSON(jsonFile)
    
    
    eventsOff = Events(files)
    offJets_source, offJets_label = Handle("vector<pat::Jet>"), (jetCollection)
    offEle_source, offEle_label = Handle("vector<pat::Electron>"), (electronCollection)
    offMu_source, offMu_label = Handle("vector<pat::Muon>"), (muonCollection)
    triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), (triggerResults)
    if isMC:
        pileUp_source, pileUp_label = Handle("vector<PileupSummaryInfo>"), ("slimmedAddPileupInfo")
    tdiff = time.time()
    evtsProcessed = 0

    prevLS = 0
    prevLS2 = 0
    for i,event in enumerate(eventsOff):
        if i%10000==0 and i != 0:
            print "Event {0:10d} | Total time: {1:8f} | Diff time {2:8f}".format(i, time.time()-t0,time.time()-tdiff)
            tdiff = time.time()
        if maxEvents != -1 and i >= maxEvents:
            break
        lumi = event.eventAuxiliary().luminosityBlock()
        
        inJSON = False
        if expJSON is not None:
            evt = event.eventAuxiliary().event()
            run = event.eventAuxiliary().run()
            if str(run) in expJSON.keys():
                if lumi in expJSON[str(run)]:
                    inJSON = True

        LSInJSON = True
        if not inJSON and expJSON is not None:
            if prevLS2 != lumi:
                print run, lumi, "not in JSON"
                prevLS2 = lumi
            LSInJSON = False
            continue

        if prevLS != lumi:
            print "At a new LS {0} (previous {1})".format(lumi,prevLS)
            prevLS = lumi

            if LSInJSON:
                hnLS.Fill(0.5)

        
        event.getByLabel(offJets_label, offJets_source)
        event.getByLabel(offEle_label, offEle_source)
        event.getByLabel(offMu_label, offMu_source)
        event.getByLabel(triggerBitLabel, triggerBits)
        
        if isMC:
            event.getByLabel(pileUp_label, pileUp_source)

        var2Fill = 0
        ht = 0
        nJets = 0
        for jet in offJets_source.product():
            if jet.pt() > 30 and abs(jet.eta()) < 2.4:
                nJets += 1
                ht += jet.pt()

        var2Fill = ht
            
        names = event.object().triggerNames(triggerBits.product())
        triggerspassing = []
        Tresults = {}
        names = event.object().triggerNames(triggerBits.product())
        triggerNames = names.triggerNames()
        for i,triggerName in enumerate(triggerNames):
            if triggerName.split("_v")[0] in Triggers2Save:
                index = names.triggerIndex(triggerName)
                if checkTriggerIndex(triggerName,index,names.triggerNames()):
                    if triggerBits.product().accept(index):
                        Tresults[triggerName.split("_v")[0]] = 1
                    else:
                        Tresults[triggerName.split("_v")[0]] = 0

        if Tresults[Triggers2Save[0]] == 1:
            hdenom.Fill(var2Fill)
        if Tresults[Triggers2Save[1]] == 1 and Tresults[Triggers2Save[0]] == 1:
            hnum[0].Fill(var2Fill)
        if Tresults[Triggers2Save[2]] == 1 and Tresults[Triggers2Save[0]] == 1:
            hnum[1].Fill(var2Fill)
        if Tresults[Triggers2Save[3]] == 1 and Tresults[Triggers2Save[0]] == 1:
            hnum[2].Fill(var2Fill)
        if Tresults[Triggers2Save[4]] == 1 and Tresults[Triggers2Save[0]] == 1:
            hnum[3].Fill(var2Fill)
        if Tresults[Triggers2Save[5]] == 1 and Tresults[Triggers2Save[0]] == 1:
            hnum[4].Fill(var2Fill)
        if (Tresults[Triggers2Save[5]] == 1 or Tresults[Triggers2Save[4]] == 1 or Tresults[Triggers2Save[3]] == 1) and Tresults[Triggers2Save[0]] == 1:
            hnum[5].Fill(var2Fill)

    print "Events processed: {0}".format(i)
    print "Total time MiniAOD: {0:8f}".format(time.time()-t0)
    return evtsProcessed   
示例#29
0
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import ROOT
from DataFormats.FWLite import Events, Handle

ROOT.gROOT.SetBatch()



events = Events(sys.argv[1])

for event in events:
    lh = (("gedPhotons", "", "RECO"), Handle("vector<reco::Photon>"))
    event.getByLabel(*lh)
    photons = lh[1].product()
    for i, g in enumerate(photons):
        print(i, g.pt(), g.hasPixelSeed(), g.hadronicOverEm())
    print('-'*80)
示例#30
0
    for i in mcsamples:
        print i
    sys.exit()

thefile = ""

if options.sample in mcsamples:
    thefile = mcsamples[options.sample]['files'][0]
elif options.sample in datasamples:
    thefile = datasamples[options.sample]['files'][0]
else:
    sys.exit()

print thefile

events = Events(thefile)

for iev, event in enumerate(events):
    event.getByLabel(triggerBitLabel, triggerBits)
    event.getByLabel(triggerObjectLabel, triggerObjects)
    event.getByLabel(triggerPrescaleLabel, triggerPrescales)

    print "\nEvent %d: run %6d, lumi %4d, event %12d" % (
        iev,
        event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(),
        event.eventAuxiliary().event())
    print "\n === TRIGGER PATHS ==="
    names = event.object().triggerNames(triggerBits.product())
    for i in xrange(triggerBits.product().size()):
        print "Trigger ", names.triggerName(
            i), ", prescale ", triggerPrescales.product().getPrescaleForIndex(