def main(): from FWCore.ParameterSet.VarParsing import VarParsing options = VarParsing ('analysis') options.inputFiles = "/afs/cern.ch/work/d/devdatta/CMSREL/Flashgg/CMSSW_9_4_2/src/flashgg/myMicroAODOutputFile.root" options.parseArguments() events = Events(options.inputFiles) nevents = 0 for event in events: h_jets = Handle("std::vector<std::vector<flashgg::Jet> >") event.getByLabel("flashggFinalJets", h_jets) print( "N(jets) = %i" % len(h_jets.product()) ) jets = h_jets.product()[0] for jet in jets: print( "jet pt = %f DeepCSVBDisc = %f" % (jet.pt(), jet.bDiscriminator("pfDeepCSVJetTags:probb")+jet.bDiscriminator("pfDeepCSVJetTags:probbb")) ) h_dipho = Handle("std::vector<flashgg::DiPhotonCandidate>") event.getByLabel("flashggDiPhotons", h_dipho) diphos = h_dipho.product() print( "N(diphotons) = %i" %len(diphos) ) for dipho in diphos: print( "Diphoton pt = %f" % dipho.pt() )
def processSample(self): self.nTot = 0 self.nFailPF = 0 self.nPFMatched = 0 print self.files events = Events(self.files) vertices = Handle("std::vector<reco::Vertex>") leps = Handle("std::vector<{}>".format(self.__class__.lepTypeStr)) pfCands = Handle("std::vector<pat::PackedCandidate>") for iEv, ev in enumerate(events): if iEv % 5000 == 0: print "{} processing event {}".format(self.name, iEv) ev.getByLabel(self.__class__.vtxCollection, vertices) try: pv = vertices.product()[0] except: print "WARNING: No good vertices in event {}. Skipping.".format(iEv) continue ev.getByLabel(self.__class__.lepCollection, leps) ev.getByLabel(self.__class__.pfCandCollection, pfCands) candHolder = PFCandHolder(pfCands) for lep in leps.product(): self.bookLepton(lep, candHolder) print "{} done! {} events processed.".format(self.name, iEv)
def fetchStubs(event,ontime=True): phiSeg2 = Handle ('std::vector<L1MuKBMTCombinedStub>') event.getByLabel('simKBmtfStubs',phiSeg2) if ontime: filtered=filter(lambda x: x.bxNum()==0, phiSeg2.product()) return filtered else: return phiSeg2.product()
def fetchSegmentsEta(event,ontime=True): thetaSeg = Handle ('L1MuDTChambThContainer') event.getByLabel('dtTriggerPrimitiveDigis',thetaSeg) if ontime: filtered=filter(lambda x: x.bxNum()==0, thetaSeg.product().getContainer()) return filtered else: return thetaSeg.product().getContainer()
def fetchStubsOLD(event,ontime=False,isData=True): phiSeg = Handle ('L1MuDTChambPhContainer') if not isData: event.getByLabel('simTwinMuxDigis',phiSeg) else: event.getByLabel('BMTFStage2Digis',phiSeg) if ontime: filtered=filter(lambda x: x.bxNum()==0, phiSeg.product().getContainer()) return filtered else: return phiSeg.product().getContainer()
def fetchSegmentsPhi(event,ontime=True,twinMux=True): phiSeg = Handle ('L1MuDTChambPhContainer') if twinMux: event.getByLabel('simTwinMuxDigis',phiSeg) else: event.getByLabel('simDtTriggerPrimitiveDigis',phiSeg) if ontime: filtered=filter(lambda x: x.bxNum()==0, phiSeg.product().getContainer()) return filtered else: return phiSeg.product().getContainer()
def printTriggers(eventsRef): from DataFormats.FWLite import Handle, Events triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), ("TriggerResults","","HLT") for iev, event in enumerate(eventsRef): eventsRef.getByLabel(triggerBitLabel, triggerBits) 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), ": ", ("PASS" if triggerBits.product().accept(i) else "fail (or not run)") if iev > 10: break
class TriggerAndEventSelectionObject : """Class to select triggers and ensure rho is sane""" def __init__(self, inputTrigs): self.rhoHandle = Handle("double") self.rhoLabel = ( "ttbsmAna", "rho" ) self.myTrigIndexHandle = Handle( "std::vector<int>") self.myTrigIndexLabel = ( "ttbsmAna", "myTrigIndex" ) self.prescalesHandle = Handle( "std::vector<int>") self.prescalesLabel = ( "ttbsmAna", "prescales" ) self.trigNamesHandle = Handle( "std::vector<string>") self.trigNamesLabel = ( "ttbsmAna", "trigNames" ) self.trigs = inputTrigs def select(self, event) : if not event.object().isValid(): return False event.getByLabel (self.myTrigIndexLabel, self.myTrigIndexHandle) if not self.myTrigIndexHandle.isValid(): print 'myTrigIndex is invalid' return False myTrigIndices = self.myTrigIndexHandle.product() event.getByLabel (self.prescalesLabel, self.prescalesHandle) if not self.prescalesHandle.isValid(): print 'prescales is invalid' return False prescales = self.prescalesHandle.product() event.getByLabel (self.rhoLabel, self.rhoHandle) if not self.rhoHandle.isValid(): print 'rho is invalid' return False rho = self.rhoHandle.product()[0] if abs(rho) > 100 or rho < 0.0 : print 'AAAACCCKK!!! rho = ' + str(rho) return False found = False firedTrig = -1 for mytrig in self.trigs : if mytrig in myTrigIndices : found = True firedTrig = mytrig break return found
def getHepMCParticles(event): handle = Handle ('std::vector<reco::GenParticle>') label = ("genParticles") event.getByLabel (label, handle) genps = handle.product() geninfo = Handle("GenEventInfoProduct") event.getByLabel ("generator", geninfo) weight = geninfo.product().weights()[0] nfound=0 q1=ROOT.TLorentzVector(0.,0.,0.,0.) q2=ROOT.TLorentzVector(0.,0.,0.,0.) wl=ROOT.TLorentzVector(0.,0.,0.,0.) wn=ROOT.TLorentzVector(0.,0.,0.,0.) zp=ROOT.TLorentzVector(0.,0.,0.,0.) zm=ROOT.TLorentzVector(0.,0.,0.,0.) topEvent = False for genp in genps: if abs(genp.pdgId())==6: topEvent = True if (genp.status()==1 and abs(genp.pdgId())<7): if nfound!=0 : q2.SetPxPyPzE(genp.px(),genp.py(),genp.pz(),genp.energy()) nfound=nfound+1 else: q1.SetPxPyPzE(genp.px(),genp.py(),genp.pz(),genp.energy()) nfound=nfound+1 wlep = [11, -11] wnu = [12, -12] if restrictChan == "wp": wlep = [-11] wnu = [12] elif restrictChan == "wm": wlep =[ 11] wnu = [-12] if (genp.status()==1 and genp.pdgId() in wlep): wl.SetPxPyPzE(genp.px(),genp.py(),genp.pz(),genp.energy()) if (genp.status()==1 and genp.pdgId() in wnu): wn.SetPxPyPzE(genp.px(),genp.py(),genp.pz(),genp.energy()) if (genp.status()==1 and genp.pdgId()==13): zp.SetPxPyPzE(genp.px(),genp.py(),genp.pz(),genp.energy()) if (genp.status()==1 and genp.pdgId()==-13): zm.SetPxPyPzE(genp.px(),genp.py(),genp.pz(),genp.energy()) if nfound != 2: raise RuntimeError("Number of quarks != 2! Found "+nfound) return zp,zm,wl,wn,q1,q2,topEvent,weight
def loop(self,maxEvents=-1): muonHandle = Handle('std::vector<pat::Muon>'); muonLabel = "mySelectedPatMuons" #mySelectedPatMuons2p1" muonPt = ROOT.TH1D("muonPt"+"_"+self.label,"muonPt",50,0,200) muonNum = ROOT.TH1D("muonNum"+"_"+self.label,"muonNum",5,-0.5,4.5) leadingMuonPt = ROOT.TH1D("leadingMuonPt"+"_"+self.label,"leadingMuonPt",50,0,200) secondLeadingMuonPt = ROOT.TH1D("secondLeadingMuonPt"+"_"+self.label,"secondLeadingMuonPt",50,0,200) ################ metHandle = Handle('std::vector<pat::MET>'); metLabel = "DiMuonmyselectedPatMETs" metPt = ROOT.TH1D("firstMETPt"+"_"+self.label,"firstMETPt",50,0,200) metNum = ROOT.TH1D("metNum"+"_"+self.label,"metNum",5,-0.5,4.5) ####################### diLepMuonCandHandle = Handle('std::vector<pat::CompositeCandidate>') ;diLepMuonCandLabel="DiLepCandMuons" diLepMuonCandMass = ROOT.TH1D("diLepMuonCandMass"+"_"+self.label,"diLepMuonCandMass",100,0.0,200) diLepMuonCandNum = ROOT.TH1D("diLepMuonCandNum"+"_"+self.label,"diLepMuonCandNum",5,-0.5,4.5) ############# offlinePVtxsHandle = Handle('std::vector<reco::Vertex>'); offlinePVtxsLabel = "offlinePrimaryVertices" offlinePVtxsNum = self.myTH1D.create("offlinePVtxs",51,-0.5,50.5) ################## if self.events.size() > 0: for i,event in enumerate(self.events): if maxEvents > 0 and i >= maxEvents: break ####### muons event.getByLabel(muonLabel,muonHandle) muons = muonHandle.product() muonNum.Fill(muons.size()) leadingMuonPt.Fill(muons[0].pt()) secondLeadingMuonPt.Fill(muons[1].pt()) for muon in muons: muonPt.Fill(muon.pt()) ######## mets event.getByLabel(metLabel,metHandle) mets = metHandle.product() metNum.Fill(mets.size()) metPt.Fill(mets[0].pt()) ########## diLepMuonCand event.getByLabel(diLepMuonCandLabel,diLepMuonCandHandle); diLepMuonCands = diLepMuonCandHandle.product();diLepMuonCandNum.Fill(diLepMuonCands.size()) for cand in diLepMuonCands: diLepMuonCandMass.Fill(cand.mass()) ################# Vtxs event.getByLabel(offlinePVtxsLabel,offlinePVtxsHandle); offlinePVtxs = offlinePVtxsHandle.product() offlinePVtxsNum.Fill(offlinePVtxs.size()) else: print "warning no events in ",self.events._filenames ## save hists self.plots.update({"muonNum":muonNum.Clone(),"muonPt":muonPt.Clone(),"metNum":metNum,"metPt":metPt,"diLepMuonCandNum":diLepMuonCandNum,"diLepMuonCandMass":diLepMuonCandMass,"leadingMuonPt":leadingMuonPt.Clone(),"secondLeadingMuonPt":secondLeadingMuonPt.Clone(),"offlinePVtxsNum":offlinePVtxsNum.Clone() }) for h in self.plots.values(): setattr(h,'label',self.label)
def analyze_gen(): events = Events ('/nfs/dust/cms/user/usaiem/gen/genall.root') handle = Handle ('LHEEventProduct') label = ("source") ROOT.gROOT.SetBatch() ROOT.gROOT.SetStyle('Plain') # white background zmassHist = ROOT.TH1F ("zmass", "Z Candidate Mass", 50, 20, 220) zevts=0 wevts=0 hevts=0 for event in events: event.getByLabel (label, handle) lhe = handle.product() hepeup=lhe.hepeup() pup= hepeup.PUP idup= hepeup.IDUP mothup= hepeup.MOTHUP for i in idup: if abs(i)==23: zevts+=1 break elif abs(i)==24: wevts+=1 break elif abs(i)==25: hevts+=1 break print 'zevts',zevts print 'wevts',wevts print 'hevts',hevts
class GenParticle(object): def begin(self, event): self.nGenParticles = [ ] self.genParticle_pdgId = [ ] self.genParticle_eta = [ ] self.genParticle_phi = [ ] self.genParticle_energy = [ ] self._attach_to_event(event) self.handleGenParticles = Handle("std::vector<reco::GenParticle>") def _attach_to_event(self, event): event.nGenParticles = self.nGenParticles event.genParticle_pdgId = self.genParticle_pdgId event.genParticle_eta = self.genParticle_eta event.genParticle_phi = self.genParticle_phi event.genParticle_energy = self.genParticle_energy def event(self, event): self._attach_to_event(event) edm_event = event.edm_event edm_event.getByLabel("genParticles", self.handleGenParticles) genparts = self.handleGenParticles.product() self.nGenParticles[:] = [genparts.size()] self.genParticle_pdgId[:] = [e.pdgId() for e in genparts] self.genParticle_eta[:] = [e.eta() for e in genparts] self.genParticle_phi[:] = [e.phi() for e in genparts] self.genParticle_energy[:] = [e.energy() for e in genparts] def end(self): self.handleGenParticles = None
def count(inputPath): files = [inputPath] events = Events(files) handlePFMETs = Handle("std::vector<reco::PFMET>") for event in events: run = event.eventAuxiliary().run() lumi = event.eventAuxiliary().luminosityBlock() eventId = event.eventAuxiliary().event() event.getByLabel(("pfMet", "", "RECO"), handlePFMETs) met = handlePFMETs.product().front() print '%6d' % run, print '%10d' % lumi, print '%9d' % eventId, print '%10.3f' % met.pt(), print '%10.3f' % met.px(), print '%10.3f' % met.py(), print '%10.2f' % (met.phi()/math.pi*180.0), print
def main(): preFnal = 'dcache:/pnfs/cms/WAX/11' preCern = 'rfio:/castor/cern.ch/cms' pre = preCern files = [pre+'/store/express/Run2010A/ExpressPhysics/FEVT/v4/000/138/737/FEC10B07-5281-DF11-B3D2-0030487A3DE0.root'] events = Events (files) handleBSpot = Handle ("reco::BeamSpot") label = ("offlineBeamSpot") #f = ROOT.TFile("analyzerPython.root", "RECREATE") #f.cd() #muonPt = ROOT.TH1F("muonPt", "pt", 100, 0.,300.) # loop over events i = 0 for event in events: i = i + 1 if i%10 == 0: print i event.getByLabel (label, handleBSpot) # get the product spot = handleBSpot.product() print " x = "+str(spot.x0()) if i==10: break
def setEventTree(self, event, expand_key_func=None): self.clear() handle = Handle("vector<reco::GenParticle>") event.getByLabel(self.collection, handle) def fill_tree(gen_particle, parent_item): expanded = False for p in xrange(gen_particle.numberOfDaughters()): p = gen_particle.daughter(p) item = QtGui.QTreeWidgetItem( parent_item, [ "%d" % p.pdgId(), "%d" % p.status(), "%f" % p.energy(), "%f" % p.px(), "%f" % p.py(), "%f" % p.pz(), ] ) if not parent_item: self.addTopLevelItem(item) if expand_key_func and expand_key_func(p): expanded = True expanded = fill_tree(p, item) or expanded if parent_item and expanded: parent_item.setExpanded(True) return expanded for gp in iter(handle.product()): if not gp.mother(): fill_tree(gp, None)
class Histo: def __init__(self, src, fillfn, *args): self.handle = Handle(src[0]) self.label = src[1] self.hist = ROOT.TH1F(*args) self.hist.Sumw2() if not fillfn: self.fillfn = lambda x: x[0] if len(x)>0 else 0 else: self.fillfn = fillfn self.weight_handle = None self.weight_label = None def fill(self, event): try: event.getByLabel(self.label, self.handle) if self.weight_handle: event.getByLabel(self.weight_label, self.weight_handle) if self.handle.isValid(): prod = self.handle.product() if self.weight_handle and self.weight_handle.isValid(): w = self.weight_handle.product()[0] else: w = 1.0 self.hist.Fill(self.fillfn(prod), w) except ValueError as e: print "Error while filling histogram: ", self.label, " ", str(e) sys.exit(1)
class skimAnalyzerCount(Analyzer): # --------------------------------------------- # TO FINDS THE INITIAL EVENTS BEFORE THE SKIM # --------------------------------------------- def declareHandles(self): super(skimAnalyzerCount, self).declareHandles() self.counterHandle = Handle("edm::MergeableCounter") def beginLoop(self): super(skimAnalyzerCount, self).beginLoop() print "Counting the total events before the skim by accessing luminosity blocks" lumis = Lumis(self.cfg_comp.files) totalEvents = 0 for lumi in lumis: lumi.getByLabel("prePathCounter", self.counterHandle) totalEvents += self.counterHandle.product().value self.counters.addCounter("SkimReport") self.count = self.counters.counter("SkimReport") self.count.register("All Events") self.count.inc("All Events", totalEvents) print "Done -> proceeding with the analysis" def process(self, iEvent, event): return True
def fetchStubsOLDTheta(event,isData=True): phiSeg = Handle ('L1MuDTChambThContainer') if not isData: event.getByLabel('dtTriggerPrimitiveDigis',phiSeg) else: event.getByLabel('BMTFStage2Digis',phiSeg) return phiSeg.product().getContainer()
def fetchBMTF(event,isData,etaMax=1.2): bmtfH = Handle ('BXVector<l1t::RegionalMuonCand>') if isData: event.getByLabel('BMTFStage2Digis:BMTF',bmtfH) else: event.getByLabel('simBmtfDigis:BMTF',bmtfH) bmtf=bmtfH.product() bmtfMuons=[] for bx in [0]: for j in range(0,bmtf.size(bx)): mu = bmtf.at(bx,j) pt = mu.hwPt()*0.5 K=1.0/pt K=1.181*K/(1+0.4867*K) pt=1.0/K #### phi=globalBMTFPhi(mu,'BMTF') rawP = rawPhi(mu) eta = mu.hwEta()*0.010875 if abs(eta)<=etaMax: b = BMTFMuon(mu,pt,eta,phi) b.rawPhi=rawP bmtfMuons.append(b) return sorted(bmtfMuons,key=lambda x: x.pt(),reverse=True)
def getWeightsFromEDMFile(edm_file_name, cross_section=1): if "/store/" in edm_file_name: edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/", edm_file_name]) elif not os.path.isfile(edm_file_name): raise FileNotFoundException("File %s was not found." % edm_file_name) events = Events(edm_file_name) eventsHandle = Handle("LHEEventProduct") lheLabel = getLHEInfoTag(events, eventsHandle) lhe_weight_sums = [] weight_ids = [] for i, event in enumerate(events): event.getByLabel(lheLabel, eventsHandle) lheStuff = eventsHandle.product() weights = lheStuff.weights() #orig = lheStuff.originalXWGTUP() if i == 0: weight_ids = [w.id for w in weights] lhe_weight_sums = [w.wgt for w in weights] else: for j, weight in enumerate(weights): lhe_weight_sums[j] += weight.wgt if cross_section != 0: norm = cross_section/lhe_weight_sums[0] lhe_weight_sums = [w*norm for w in lhe_weight_sums] return getVariations(weight_ids, lhe_weight_sums)
class HFPreRecHit(object): def begin(self, event): self.hfrechit_ieta = [ ] self.hfrechit_iphi = [ ] self.hfrechit_QIE10_index = [ ] self.hfrechit_QIE10_energy = [ ] self._attach_to_event(event) self.handleHFPreRecHit = Handle("edm::SortedCollection<HFPreRecHit,edm::StrictWeakOrdering<HFPreRecHit> >") # SortedCollection: https://github.com/cms-sw/cmssw/blob/CMSSW_8_1_X/DataFormats/Common/interface/SortedCollection.h # HFPreRecHit: https://github.com/cms-sw/cmssw/blob/CMSSW_8_1_X/DataFormats/HcalRecHit/interface/HFPreRecHit.h def _attach_to_event(self, event): event.hfrechit_ieta = self.hfrechit_ieta event.hfrechit_iphi = self.hfrechit_iphi event.hfrechit_QIE10_index = self.hfrechit_QIE10_index event.hfrechit_QIE10_energy = self.hfrechit_QIE10_energy def event(self, event): self._attach_to_event(event) edm_event = event.edm_event edm_event.getByLabel('hfprereco', self.handleHFPreRecHit) hfPreRecoHits = self.handleHFPreRecHit.product() self.hfrechit_ieta[:] = [h.id().ieta() for h in hfPreRecoHits]*2 self.hfrechit_iphi[:] = [h.id().iphi() for h in hfPreRecoHits]*2 self.hfrechit_QIE10_index[:] = [0]*len(hfPreRecoHits) + [1]*len(hfPreRecoHits) self.hfrechit_QIE10_energy[:] = [h.getHFQIE10Info(i).energy() for i in (0, 1) for h in hfPreRecoHits] + [h.getHFQIE10Info(1).energy() for h in hfPreRecoHits] def end(self): self.handleHFPreRecHit = None
def checkTriggerSelection(eventsRef, args): from DataFormats.FWLite import Handle, Events triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), ("TriggerResults","","HLT") eventsRef.getByLabel(triggerBitLabel, triggerBits) success = False names = eventsRef.object().triggerNames(triggerBits.product()) for i in xrange(triggerBits.product().size()): for path in args.selectHLTPath.split(','): if re.match(path, names.triggerName(i)): success = success | (True if triggerBits.product().accept(i) else False) # No need to test all the paths, since they are in OR: a # single True is enough to stop the loop. if success: return success return success
def getWeightIDs(edm_file_name) : if "/store/" in edm_file_name : edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/", edm_file_name]) elif not os.path.isfile(edm_file_name) : raise FileNotFoundException("File %s was not found." % edm_file_name) runs = Runs(edm_file_name) runInfoHandle = Handle("LHERunInfoProduct") lheLabel = WeightTools.getLHEInfoTag(runs, runInfoHandle) run = runs.__iter__().next() run.getByLabel(lheLabel, runInfoHandle) lheStuff = runInfoHandle.product() lines = [] for i, h in enumerate(lheStuff.headers_begin()) : if i == lheStuff.headers_size() : break hlines = [] isWeights = False for line in h.lines() : hlines.append(line) if 'weightgroup' in line : isWeights = True if isWeights : lines.extend(hlines) break return ''.join(lines).rstrip("<")
def runOnce(params, eventList): # put the entire old script in here print "Initializing, foo is %s" % params['foo'] Mpostfix = '' muonPtHandle = Handle( "std::vector<float>" ) muonPtLabel = ( "pfShyftTupleMuons"+ Mpostfix, "pt" ) muonEtaHandle = Handle( "std::vector<float>" ) muonEtaLabel = ( "pfShyftTupleMuons"+ Mpostfix, "eta" ) muonPhiHandle = Handle( "std::vector<float>" ) muonPhiLabel = ( "pfShyftTupleMuons"+ Mpostfix, "phi" ) muonPfisoHandle = Handle( "std::vector<float>" ) muonPfisoLabel = ( "pfShyftTupleMuons"+ Mpostfix, "pfiso" ) for event in eventList: print "Got event, foo is %s" % (params['foo']) event.getByLabel (muonPtLabel, muonPtHandle) oldtime = time.time() if not muonPtHandle.isValid(): muonPts = None else: muonPts = muonPtHandle.product() print muonPts event.getByLabel (muonEtaLabel, muonEtaHandle) if not muonEtaHandle.isValid(): muonPts = None else: muonPts = muonEtaHandle.product() print muonPts event.getByLabel(muonPhiLabel, muonPhiHandle) if not muonPhiHandle.isValid(): muonPts = None else: muonPts = muonPhiHandle.product() print muonPts event.getByLabel (muonPfisoLabel, muonPfisoHandle) if not muonPfisoHandle.isValid(): muonPts = None else: muonPts = muonPfisoHandle.product() print muonPts print "-- time %s" % (time.time() - oldtime) yield None print "Shutting down, foo is %s" % params['foo']
class Test(object): def __init__(self, msg, type, inlabel, outlabel, tests): self.msg = msg self.inhandle = Handle(type) self.outhandle = Handle(type) self.inlabel = inlabel self.outlabel = outlabel, self.tests = tests or [] def __call__(self, event): event.getByLabel(*(list(self.inlabel) + [self.inhandle])) event.getByLabel(*(list(self.outlabel) + [self.outhandle])) print(self.msg) for a, b in compare_bx_vector(self.inhandle.product(), self.outhandle.product()): for t in self.tests: t(a, b)
def trackNtuplizer(eventsRef, t, container_kind="std::vector<reco::Track>", collection_label="generalTracks", thread_id = 1): from DataFormats.FWLite import Handle, Events tracksRef = Handle(container_kind) muonsRef = Handle("std::vector<reco::Muon>") vertexRef = Handle("std::vector<reco::Vertex>") vertexLabel = "offlinePrimaryVertices" displaced_vertices_Ref = Handle("vector<reco::PFDisplacedVertex>") displaced_vertices_label = "particleFlowDisplacedVertex" label = collection_label # sip = ROOT.SignedImpactParameter() # print "Analyzing Tracks: %s" % collection_label processed = 0 skipped = 0 sys.stdout.write('\n') total_events = float(eventsRef.size()) accepted_events = 0 for e in range(eventsRef.size()): if processed%10 == 0: if args.selectHLTPath: logme("%3.0f%% acc:%4.3f%% | " % ((processed/total_events)*100., (accepted_events/total_events)*100. ), thread_id) # sys.stdout.write("\r%3.2f%% accepted: %3.2f%%" % ((processed/total_events)*100., # (accepted_events/total_events)*100. # )) # sys.stdout.flush() else: logme("%3.0f%% | " % ((processed/total_events)*100.), thread_id) # sys.stdout.write("\r%f%%" % ((processed/total_events)*100.)) # sys.stdout.flush() a = eventsRef.to(e) processed += 1 if args.selectHLTPath: if not checkTriggerSelection(eventsRef, args): continue else: accepted_events += 1 a = eventsRef.getByLabel(label, tracksRef) a = eventsRef.getByLabel("muons", muonsRef) a = eventsRef.getByLabel(vertexLabel, vertexRef) a = eventsRef.getByLabel(displaced_vertices_label, displaced_vertices_Ref) PVCollection = map(lambda x: vertexRef.product()[0], tracksRef.product()) PVCollectionMuons = map(lambda x: vertexRef.product()[0], muonsRef.product()) event_vars.fillBranches(t, eventsRef.eventAuxiliary(), False) if args.tracks: track_vars.fillBranchesVector(t, tracksRef.product(), False) if args.muons: muon_args = map(lambda x: (x.innerTrack() if x.isTrackerMuon() else x.bestTrack() , x), muonsRef.product()) globalMuon_vars.fillBranchesVector(t, muon_args, False) if args.vertices: vertex_vars.fillBranchesVector(t, vertexRef.product(), False) if args.displacedV: displaced_vertex_vars.fillBranchesVector(t, displaced_vertices_Ref.product(), False) t.tree.Fill() t.reset() sys.stdout.write('\n')
def get_info(infile,particle, outfile, histo, variable): ##################################### ################# File #file = ROOT.TFile(particle+"_tmp.root", "recreate") # open new root file #tree = ROOT.TTree("plots", "plots") # Open a tree #t.Branch(particle, n, particle'/D') events = Events (infile) handleGen = Handle ("vector<reco::GenParticle>") #label = "prunedGenParticles" label = "genParticles" #print handleGen histo.UseCurrentStyle() if particle in PDG.keys(): for event in events: #print event #nparticles = 0 event.getByLabel (label, handleGen) gens = handleGen.product() #storeParticles = std.vector(float)() Ptvector=[] # for p in gens: infoParticle = TLorentzVector() #print 'id',p.pdgId(), p.status(), 'status' #print 'name', p.pdgId(), p.status(), p.p4() tmpValue=0 if abs( int(p.pdgId()) ) == int(PDG[particle]): if p.status() == 3: #nparticles += 1 infoParticle.SetPxPyPzE(p.px(),p.py(),p.pz(),p.et()) Ptvector.append(infoParticle.Pt()) if int(Variables[variable])==1: histo.Fill(infoParticle.Pt()) if int(Variables[variable])==2: histo.Fill(infoParticle.M()) if int(Variables[variable])==3: histo.Fill(infoParticle.Eta()) #histo.Fill(infoParticle.E()) if int(Variables[variable])==4: histo.Fill(len(Ptvector)) if int(Variables[variable])==11: histo.Fill(max(Ptvector)) #storeParticles.push_back(infoParticle.Et()) can = TCanvas('can', '', 800,600) can.cd() histo.Draw() #if histo.GetNbinsX() > 50: #histo.GetXaxis().SetLabelSize(0.02) #else: #histo.GetXaxis().SetLabelSize(0.03) can.SetBorderMode(0) can.SetBorderSize(0) can.SetFillColor(kWhite) can.SetLeftMargin(0.10) #can.SaveAs(allnames.replace('_','')+'temp.png') can.SaveAs(particle+'_'+variable+'temp.pdf') del can
class SkimAnalyzerCount( Analyzer ): #--------------------------------------------- # TO FINDS THE INITIAL EVENTS BEFORE THE SKIM #--------------------------------------------- def __init__(self, cfg_ana, cfg_comp, looperName): super(SkimAnalyzerCount, self).__init__(cfg_ana, cfg_comp, looperName) self.useLumiBlocks = self.cfg_ana.useLumiBlocks if (hasattr(self.cfg_ana,'useLumiBlocks')) else False def declareHandles(self): super(SkimAnalyzerCount, self).declareHandles() self.counterHandle = Handle("edm::MergeableCounter") self.mchandles['GenInfo'] = AutoHandle( ('generator','',''), 'GenEventInfoProduct' ) def beginLoop(self, setup): super(SkimAnalyzerCount,self).beginLoop(setup) self.counters.addCounter('SkimReport') self.count = self.counters.counter('SkimReport') self.count.register('All Events') if self.cfg_comp.isMC: self.count.register('Sum Weights') if not self.useLumiBlocks: #print 'Will actually count events instead of accessing lumi blocks' return True print 'Counting the total events before the skim by accessing luminosity blocks' lumis = Lumis(self.cfg_comp.files) totalEvents=0 for lumi in lumis: if lumi.getByLabel('prePathCounter',self.counterHandle): totalEvents+=self.counterHandle.product().value else: self.useLumiBlocks = False break if self.useLumiBlocks: self.count.inc('All Events',totalEvents) if self.cfg_comp.isMC: self.count.inc('Sum Weights',totalEvents) print 'Done -> proceeding with the analysis' else: print 'Failed -> will have to actually count events (this can happen if the input dataset is not a CMG one)' def process(self, event): if not self.useLumiBlocks: self.readCollections( event.input ) self.count.inc('All Events') if self.cfg_comp.isMC: self.count.inc('Sum Weights', self.mchandles['GenInfo'].product().weight()) return True
class TrigHelper: def __init__(self, verbose=False): self.verbose = verbose self.trigLabel = ("dijetTriggerFilter", "jetPaths") self.trigHandle = Handle("std::vector<std::string>") # Here are the trigger thresholds for the various eta bins. # In the following, each entry is an eta bin. The # two fields are then [etamin,etamax], and the # list of mjj thresholds for HLT_Jet60,110,190,240,370. self.trigThresholds = [50.0, 150.0, 220.0, 300.0, 450.0, 7000.0] self.trigsToKeep = ["HLT_Jet60", "HLT_Jet110", "HLT_Jet190", "HLT_Jet240", "HLT_Jet370"] def passEventMC(self, event, ptAvg): for ibin in range(0, len(self.trigThresholds)): if ptAvg >= self.trigThresholds[ibin] and ptAvg < self.trigThresholds[ibin + 1]: return True def passEventData(self, event, ptAvg): iTrigHist = None event.getByLabel(self.trigLabel, self.trigHandle) trigs = self.trigHandle.product() acceptedPaths = [] trigPassedName = None passPtAvgTrig = False # If there are any accepted paths, cache them. Then match to the lookup table "trigThresholds" to see if # the event is in the correct mjj bin for the trigger in question. if len(trigs) > 0: for ipath in xrange(len(trigs) - 1, -1, -1): path = trigs[ipath] for ikeep in xrange(len(self.trigsToKeep) - 1, -1, -1): if self.verbose: print " ----- checking trigger " + self.trigsToKeep[ikeep] + " : ptAvgThreshold = " + str( self.trigThresholds[ikeep] ) if ( path.find(self.trigsToKeep[ikeep]) >= 0 and ptAvg >= self.trigThresholds[ikeep] and ptAvg < self.trigThresholds[ikeep + 1] ): trigPassedName = path iTrigHist = ikeep passPtAvgTrig = True if self.verbose: print " -----------> Joy and elation, it worked! trigger = " + self.trigsToKeep[ iTrigHist ] break if passPtAvgTrig == True: break passEvent = passPtAvgTrig return [passEvent, iTrigHist]
def get_info(infile,particle, outfile): ##################################### events = Events (infile) handleGen = Handle ("vector<reco::GenParticle>") label = "genParticles" if particle in PDG.keys(): # For histos hmass = TH1F( particle+' mass', particle+' mass',100,480,520) # gh 500 MeV #hmass = TH1F( particle+' mass', particle+' mass',100,980,1020) # gh 1 TeV #hmass = TH1F( particle+' mass', particle+' mass',100,160,180) # 4Top hmass.SetXTitle(particle+' Mass [GeV]') hnparticles = TH1F('number of '+particle+' and '+particle+'bar','number of '+particle+' and '+particle+'bar',5,2,6) #hpt2 = TH1F(particle +' pt', 'hardest '+ particle + 'pt',100,0,500) #hpt = TH1F('pt','pt',100,0,500) hpt = TH1F(particle+' pt','pt',500,0,1000) hpt.SetXTitle(particle+' pt [GeV]') heta = TH1F(particle+' eta',particle+' eta',100,-5,5) heta.SetXTitle(particle+' eta') # entry = 0 for event in events: #entry += 1 nparticles = 0 # print "Event ", count event.getByLabel (label, handleGen) gens = handleGen.product() highpt = [] for p in gens: #print 'id',p.pdgId(), p.status(), 'status' if abs( int(p.pdgId()) ) == int(PDG[particle]): if p.status() == 22: # 22 for ttbar, W and gh, 23 for 'final' particles nparticles += 1 # highpt.append(p.pt()) # print 'nparticles', nparticles hpt.Fill(float(p.pt())) heta.Fill(float(p.eta())) hmass.Fill(float(p.mass())) hnparticles.Fill(nparticles) # hpt2.Fill(max(highpt)) hmass.Draw() c1.SaveAs(outfile+'_'+particle+'_mass.png') # hpt2.SetFillColor(kBlue) # hpt.SetFillColor(kWhite) # hpt2.GetYaxis().SetRangeUser(0.,400) # hpt2.Draw() # hpt.Draw("same") hpt.Draw() c1.SaveAs(outfile+'_'+particle+'_pt.png') heta.Draw() c1.SaveAs(outfile+'_'+particle+'_eta.png') hnparticles.Draw() c1.SaveAs(outfile+'_'+particle+'_nparticles.png')
nomadspin_pdgid_index = [] # loop over events count = 0 for event in events: if count > 5: break lep_mad = TLorentzVector(0, 0, 0, 0) ele_mad = TLorentzVector(0, 0, 0, 0) mu_mad = TLorentzVector(0, 0, 0, 0) tau_mad = TLorentzVector(0, 0, 0, 0) neu_mad = TLorentzVector(0, 0, 0, 0) count = count + 1 if count % 100 == 0: print "count = ", count event.getByLabel(labelPruned, handlePruned) pruned = handlePruned.product() event.getByLabel(geninfoLabel, geninfo) info_pruned = geninfo.product() weight_mad = info_pruned.weight() / abs(info_pruned.weight()) neu_posi = -999 ele_posi = -999 mu_posi = -999 for p in pruned: if (p.isDirectHardProcessTauDecayProductFinalState()): print 'ID:', p.pdgId() lep_mad.SetPtEtaPhiE(p.pt(), p.eta(), p.phi(), p.energy()) madspin_TLorentzVector.append(lep_mad.Clone()) madspin_pdgid_index.append(p.pdgId()) for i in range(len(madspin_pdgid_index)): tau_mad = tau_mad + madspin_TLorentzVector[i] tauphi_mad.Fill(tau_mad.Phi(), weight_mad)
for FILE in FILES: for iev, event in enumerate(FILE): NEvents.Fill(0) event.getByLabel(mu12Label, mu12) event.getByLabel(mu3Label, mu3) event.getByLabel(metsLabel, mets) event.getByLabel(tausLabel, taus) event.getByLabel(jetsLabel, jets) event.getByLabel(lheEventLabel, lheEvent) #print "LHE:", lheEvent.isValid(), #for i in range(lheInfo.weights().size() ): # print "\tWeight#" + i + "=", lheInfo->weights()[i].wgt highestPt = 0 for i, mu in enumerate(mu12.product()): if highestPt == 0: m1 = mu highestPt = m1.pt() elif mu.pt() > m1.pt(): m2 = m1 m1 = mu highestPt = m1.pt() else: m2 = mu if m1.pt() < 26.0: continue NEvents.Fill(1) bestdR = 10000 foundTau = False
def convertGENSIM(infiles, outfilename, Nmax=-1, isPythia=False): """Loop over GENSIM events and save custom trees.""" start1 = time.time() lqids = [46] if isPythia else [9000002, 9000006] print ">>> loading files..." events = Events(infiles) outfile = TFile(outfilename, 'RECREATE') print ">>> creating trees and branches..." tree_event = TTree('event', 'event') tree_jet = TTree('jet', 'jet') tree_mother = TTree('mother', 'mother') tree_decay = TTree('decay', 'decay') tree_assoc = TTree('assoc', 'assoc') # EVENT tree_event.addBranch('nbgen', 'i') tree_event.addBranch('nbcut', 'i') tree_event.addBranch('ntgen', 'i') tree_event.addBranch('njet', 'i') tree_event.addBranch('nlepton', 'i') tree_event.addBranch('ntau', 'i') tree_event.addBranch('ntaucut', 'i') tree_event.addBranch('nnu', 'i') tree_event.addBranch('nlq', 'i') tree_event.addBranch('ntau_assoc', 'i') tree_event.addBranch('ntau_decay', 'i') tree_event.addBranch('nbgen_decay', 'i') tree_event.addBranch('met', 'f') tree_event.addBranch('jpt1', 'f') tree_event.addBranch('jpt2', 'f') tree_event.addBranch('sumjet', 'f') tree_event.addBranch('dphi_jj', 'f') tree_event.addBranch('deta_jj', 'f') tree_event.addBranch('dr_jj', 'f') tree_event.addBranch('ncentral', 'i') tree_event.addBranch('mjj', 'f') tree_event.addBranch('lq1_mass', 'f') tree_event.addBranch('lq2_mass', 'f') tree_event.addBranch('lq1_pt', 'f') tree_event.addBranch('lq2_pt', 'f') tree_event.addBranch('tau1_pt', 'f') tree_event.addBranch('tau1_eta', 'f') tree_event.addBranch('tau2_pt', 'f') tree_event.addBranch('tau2_eta', 'f') tree_event.addBranch('st', 'f') # scalar sum pT tree_event.addBranch('st_met', 'f') # scalar sum pT with MET tree_event.addBranch('weight', 'f') # LQ DECAY tree_mother.addBranch('pid', 'i') tree_mother.addBranch('moth', 'i') tree_mother.addBranch('status', 'i') tree_mother.addBranch('pt', 'f') tree_mother.addBranch('eta', 'f') tree_mother.addBranch('phi', 'f') tree_mother.addBranch('mass', 'f') tree_mother.addBranch('inv', 'f') tree_mother.addBranch('ndau', 'i') tree_mother.addBranch('dau', 'i') tree_mother.addBranch('dphi_ll', 'f') tree_mother.addBranch('deta_ll', 'f') tree_mother.addBranch('dr_ll', 'f') tree_mother.addBranch('st', 'f') # scalar sum pT tree_mother.addBranch('st_met', 'f') # scalar sum pT with MET tree_mother.addBranch('weight', 'f') # FROM LQ DECAY tree_decay.addBranch('pid', 'i') tree_decay.addBranch('pt', 'f') tree_decay.addBranch('eta', 'f') tree_decay.addBranch('phi', 'f') tree_decay.addBranch('lq_mass', 'f') tree_decay.addBranch('ptvis', 'f') tree_decay.addBranch('type', 'i') tree_decay.addBranch('isBrem', 'i') tree_decay.addBranch('weight', 'f') # NOT FROM LQ DECAY (ASSOCIATED) tree_assoc.addBranch('pid', 'i') tree_assoc.addBranch('moth', 'i') tree_assoc.addBranch('pt', 'f') tree_assoc.addBranch('ptvis', 'f') tree_assoc.addBranch('eta', 'f') tree_assoc.addBranch('phi', 'f') tree_assoc.addBranch('weight', 'f') # JETS tree_jet.addBranch('pt', 'f') tree_jet.addBranch('eta', 'f') tree_jet.addBranch('phi', 'f') tree_jet.addBranch('weight', 'f') hist_LQ_decay = TH1F('LQ_decay', "LQ decay", 60, -30, 30) handle_gps, label_gps = Handle( 'std::vector<reco::GenParticle>'), 'genParticles' handle_jets, label_jets = Handle('std::vector<reco::GenJet>'), 'ak4GenJets' handle_met, label_met = Handle('vector<reco::GenMET>'), 'genMetTrue' handle_weight, label_weight = Handle('GenEventInfoProduct'), 'generator' evtid = 0 sec_per_evt = 0.023 # seconds per event Ntot = Nmax if Nmax > 0 else events.size() step = stepsize(Ntot) print ">>> start processing %d events, ETA %s..." % ( Ntot, formatTimeShort(sec_per_evt * Ntot)) start_proc = time.time() # LOOP OVER EVENTS for event in events: #print '='*30 #print evtid if Nmax > 0 and evtid >= Nmax: break if evtid > 0 and evtid % step == 0: print ">>> processed %4s/%d events, ETA %s" % ( evtid, Ntot, ETA(start_proc, evtid + 1, Ntot)) evtid += 1 event.getByLabel(label_gps, handle_gps) gps = handle_gps.product() event.getByLabel(label_jets, handle_jets) jets = handle_jets.product() event.getByLabel(label_met, handle_met) met = handle_met.product() event.getByLabel(label_weight, handle_weight) gweight = handle_weight.product() weight = gweight.weight() # GEN PARTICLES gps_mother = [p for p in gps if isFinal(p) and abs(p.pdgId()) in [42]] gps_final = [ p for p in gps if isFinal(p) and abs(p.pdgId()) in [5, 6, 15, 16] + lqids ] gps_mother = [ p for p in gps_final if abs(p.pdgId()) in lqids and p.status() > 60 ] #not(moth.numberOfDaughters()==2 and abs(moth.daughter(0).pdgId()) in lqids) gps_bgen = [ p for p in gps_final if abs(p.pdgId()) == 5 and p.status() == 71 ] gps_bcut = [p for p in gps_bgen if p.pt() > 20 and abs(p.eta()) < 2.5] gps_tgen = [p for p in gps_final if abs(p.pdgId()) == 6] #[-1:] gps_nugen = [p for p in gps_final if abs(p.pdgId()) == 16] gps_tau = [ p for p in gps_final if abs(p.pdgId()) == 15 and p.status() == 2 ] gps_tau.sort(key=lambda p: p.pt(), reverse=True) gps_taucut = [p for p in gps_tau if p.pt() > 20 and abs(p.eta()) < 2.5] #print '-'*10 #for p in gps_tgen: # printParticle(p) #if gps_tgen: # print "has top" #for p in gps_nugen: # printParticle(p) # REMOVE TOP QUARK if its final daughter is also in the list for top in gps_tgen[:]: dau = top while abs(dau.daughter(0).pdgId()) == 6: dau = dau.daughter(0) if dau != top and dau in gps_tgen: gps_tgen.remove(top) # REMOVE JET-LEPTON OVERLAP jets, dummy = cleanObjectCollection(jets, gps_tau, dRmin=0.5) njets = 0 sumjet = 0 jets30 = [] for jet in jets: if jet.pt() > 30 and abs(jet.eta()) < 5: sumjet += jet.pt() njets += 1 tree_jet.pt[0] = jet.pt() tree_jet.eta[0] = jet.eta() tree_jet.phi[0] = jet.phi() tree_jet.weight[0] = weight tree_jet.Fill() jets30.append(jet) # MULTIPLICITIES tree_event.nlq[0] = len(gps_mother) tree_event.nbcut[0] = len(gps_bcut) tree_event.nbgen[0] = len(gps_bgen) tree_event.ntgen[0] = len(gps_tgen) tree_event.njet[0] = njets tree_event.nlepton[0] = len(gps_tau) tree_event.ntau[0] = len(gps_tau) tree_event.ntaucut[0] = len(gps_taucut) tree_event.nnu[0] = len(gps_nugen) # JETS tree_event.met[0] = met[0].pt() tree_event.sumjet[0] = sumjet if len(jets30) >= 2: centrajpt1s = findCentrajpt1s(jets30[:2], jets30[2:]) tree_event.ncentral[0] = len(centrajpt1s) else: tree_event.ncentral[0] = -9 if (len(jets30) >= 2): tree_event.jpt1[0] = jets30[0].pt() tree_event.jpt2[0] = jets30[1].pt() tree_event.dphi_jj[0] = deltaPhi(jets30[0].phi(), jets30[1].phi()) tree_event.deta_jj[0] = jets30[0].eta() - jets30[1].eta() tree_event.dr_jj[0] = deltaR(jets30[0].eta(), jets30[0].phi(), jets30[1].eta(), jets30[1].phi()) dijetp4 = jets30[0].p4() + jets30[1].p4() tree_event.mjj[0] = dijetp4.M() elif (len(jets30) == 1): tree_event.jpt1[0] = jets30[0].pt() tree_event.jpt2[0] = -1 tree_event.dphi_jj[0] = -9 tree_event.deta_jj[0] = -9 tree_event.dr_jj[0] = -1 tree_event.mjj[0] = -1 else: tree_event.jpt1[0] = -1 tree_event.jpt2[0] = -1 tree_event.dphi_jj[0] = -9 tree_event.deta_jj[0] = -9 tree_event.dr_jj[0] = -1 tree_event.mjj[0] = -1 # SCALAR SUM PT if len(gps_taucut) >= 2 and len(gps_bcut) >= 1: st = 0 #gps_taucut.sort(key=lambda p: p.pt(), reverse=True) gps_bcut.sort(key=lambda p: p.pt(), reverse=True) #taus_assoc.sort(key=lambda p: p.pt(), reverse=True) #taus_decay.sort(key=lambda p: p.pt(), reverse=True) #bgen_decay.sort(key=lambda p: p.pt(), reverse=True) for part in gps_taucut[2:] + gps_bcut[1:]: st += part.pt() stmet = st + met[0].pt() else: st = -1 stmet = -1 tree_event.tau1_pt[0] = gps_tau[0].pt() tree_event.tau1_eta[0] = gps_tau[0].eta() tree_event.tau2_pt[0] = gps_tau[1].pt() tree_event.tau2_eta[0] = gps_tau[1].eta() tree_event.st[0] = st tree_event.st_met[0] = stmet tree_mother.st[0] = st tree_mother.st_met[0] = stmet tree_event.weight[0] = weight #print 'len, gps_mother = ', len(gps_mother) #if len(gps_mother)==1: # print gps_mother[0].pdgId(), gps_mother[0].status(), gps_mother[0].pt(), gps_mother[0].eta(), gps_mother[0].phi() # print '1 (ndaughter, daughter pdgid) =', gps_mother[0].numberOfDaughters(), gps_mother[0].daughter(0).pdgId(), '(pdgId, status, pt, eta, phi) = ', gps_mother[0].pdgId(), gps_mother[0].status(), gps_mother[0].pt(), gps_mother[0].eta(), gps_mother[0].phi() #if len(gps_mother)>=2: # print '2 (ndaughter, daughter 1/2 pdgid) =', gps_mother[0].numberOfDaughters(), gps_mother[0].daughter(0).pdgId(), gps_mother[0].daughter(1).pdgId(), '(pdgId, status, pt, eta, phi) = ', gps_mother[0].pdgId(), gps_mother[0].status(), gps_mother[0].pt(), gps_mother[0].eta(), gps_mother[0].phi() # print '2 (ndaughter, daughter 1/2 pdgid) =', gps_mother[1].numberOfDaughters(), gps_mother[1].daughter(0).pdgId(), gps_mother[1].daughter(1).pdgId(), '(pdgId, status, pt, eta, phi) = ', gps_mother[1].pdgId(), gps_mother[1].status(), gps_mother[1].pt(), gps_mother[1].eta(), gps_mother[1].phi() # TAU taus_assoc = [] for gentau in gps_tau: while gentau.status() != 2: gentau = gentau.daughter(0) genfinDaughters = finalDaughters(gentau, []) genptvis = p4sumvis(genfinDaughters).pt() # CHECK MOTHER taumoth = gentau.mother(0) mothpid = abs(taumoth.pdgId()) from_LQ = False #from_had = False # from hadron decay #print '-'*30 while mothpid != 2212: #print taumoth.pdgId() if mothpid in lqids: from_LQ = True break elif 100 < mothpid < 10000: #and mothpid!=2212: #from_had = True break taumoth = taumoth.mother(0) mothpid = abs(taumoth.pdgId()) # ASSOC if not from_LQ: tree_assoc.pt[0] = gentau.pt() tree_assoc.ptvis[0] = genptvis tree_assoc.eta[0] = gentau.eta() tree_assoc.phi[0] = gentau.phi() tree_assoc.pid[0] = gentau.pdgId() tree_assoc.moth[0] = taumoth.pdgId() tree_assoc.weight[0] = weight tree_assoc.Fill() #if not from_had: taus_assoc.append(gentau) # B QUARK for genb in gps_bgen: bmoth = genb.mother(0) mothpid = abs(bmoth.pdgId()) from_LQ = False while mothpid != 2212: if mothpid in lqids: from_LQ = True break bmoth = bmoth.mother(0) mothpid = abs(bmoth.pdgId()) if not from_LQ: tree_assoc.pt[0] = genb.pt() tree_assoc.ptvis[0] = -1 tree_assoc.eta[0] = genb.eta() tree_assoc.phi[0] = genb.phi() tree_assoc.pid[0] = genb.pdgId() tree_assoc.moth[0] = bmoth.pdgId() tree_assoc.weight[0] = weight tree_assoc.Fill() # MOTHER LQ #print '-'*80 taus_decay = [] bgen_decay = [] gps_mother.sort(key=lambda p: p.pt(), reverse=True) for moth in gps_mother: dau_pid = 0 pair = [] if moth.numberOfDaughters() == 2: if moth.daughter(0).pdgId() in [ 21, 22 ] or moth.daughter(1).pdgId() in [21, 22]: continue if abs(moth.daughter(0).pdgId() ) in lqids: # single production with t-channel LQ continue lq_moth = moth.mother(0) while abs(lq_moth.pdgId()) in lqids: lq_moth = lq_moth.mother(0) for i in range(moth.numberOfDaughters()): #print '\t', dau.pdgId() dau = moth.daughter(i) # TAU isBrem = False if abs(dau.pdgId()) == 15: while dau.status() != 2: dau = dau.daughter(0) if dau.numberOfDaughters() == 2 and abs( dau.daughter(0).pdgId()) == 15 and dau.daughter( 1).pdgId() == 22: #print "This is brems !?!" isBrem = True else: taus_decay.append(dau) # BOTTOM QUARK elif abs(dau.pdgId()) == 5: dau_pid = dau.pdgId() bgen_decay.append(dau) # TOP QUARK elif abs(dau.pdgId()) == 6: dau_pid = dau.pdgId() newdau = dau while abs(newdau.daughter(0).pdgId()) == 6: newdau = newdau.daughter(0) if isFinal(newdau): dau = newdau pair.append(dau.p4()) tree_decay.lq_mass[0] = moth.mass() tree_decay.pid[0] = dau.pdgId() tree_decay.pt[0] = dau.pt() tree_decay.eta[0] = dau.eta() tree_decay.phi[0] = dau.phi() tree_decay.isBrem[0] = isBrem if abs(dau.pdgId()) == 15: finDaughters = finalDaughters(dau, []) ptvis = p4sumvis(finDaughters).pt() tree_decay.ptvis[0] = ptvis decaymode = tauDecayMode(dau) tree_decay.type[0] = decaydict[decaymode] #print decaymode, 'vis pt = ', ptvis , 'tau pt = ', dau.pt() if ptvis > dau.pt(): print "%s, vis pt = %s, tau pt = %s " % ( decaymode, ptvis, dau.pt()) + '!' * 30 else: tree_decay.ptvis[0] = dau.pt() tree_decay.type[0] = -1 tree_decay.weight[0] = weight tree_decay.Fill() if abs(moth.pdgId()) in lqids: hist_LQ_decay.Fill(dau.pdgId()) if len(pair) == 2: tree_mother.inv[0] = (pair[0] + pair[1]).mass() tree_mother.dphi_ll[0] = deltaPhi(pair[0].phi(), pair[1].phi()) tree_mother.deta_ll[0] = pair[0].eta() - pair[1].eta() tree_mother.dr_ll[0] = deltaR(pair[0].eta(), pair[0].phi(), pair[1].eta(), pair[1].phi()) else: tree_mother.inv[0] = -1 tree_mother.dphi_ll[0] = -99 tree_mother.deta_ll[0] = -99 tree_mother.dr_ll[0] = -99 tree_mother.pid[0] = moth.pdgId() tree_mother.moth[0] = lq_moth.pdgId() tree_mother.status[0] = moth.status() tree_mother.mass[0] = moth.mass() tree_mother.pt[0] = moth.pt() tree_mother.eta[0] = moth.eta() tree_mother.phi[0] = moth.phi() tree_mother.ndau[0] = len(pair) tree_mother.dau[0] = dau_pid # save PDG ID for quark daughter tree_mother.weight[0] = weight tree_mother.Fill() if len(gps_mother) == 1: tree_event.lq1_mass[0] = gps_mother[0].mass() tree_event.lq1_pt[0] = gps_mother[0].pt() tree_event.lq2_mass[0] = -1 tree_event.lq2_pt[0] = -1 elif len(gps_mother) >= 2: tree_event.lq1_mass[0] = gps_mother[0].mass() tree_event.lq1_pt[0] = gps_mother[0].pt() tree_event.lq2_mass[0] = gps_mother[1].mass() tree_event.lq2_pt[0] = gps_mother[1].pt() else: tree_event.lq1_mass[0] = -1 tree_event.lq1_pt[0] = -1 tree_event.lq2_mass[0] = -1 tree_event.lq2_pt[0] = -1 tree_event.ntau_assoc[0] = len(taus_assoc) tree_event.ntau_decay[0] = len(taus_decay) tree_event.nbgen_decay[0] = len(bgen_decay) tree_event.Fill() print ">>> processed %4s events in %s" % ( evtid, formatTime(time.time() - start_proc)) print ">>> writing to output file %s..." % (outfilename) outfile.Write() outfile.Close() print ">>> done in in %s" % (formatTime(time.time() - start1))
def histograms(files): #eta_thresholds = [0] #color={0:ROOT.kBlack, 1.3:ROOT.kBlue, 2.5:ROOT.kRed, 3:ROOT.kMagenta} eta_thresholds = [-1.3, 1.3] # you can put here whatever interval you wish resp = {} thresholds = [10**(x / 10.) for x in range(10, 25)] jecvspt = ROOT.TProfile("jecvspt", "jecvspt", len(thresholds) - 1, array.array('d', thresholds)) jecvseta = ROOT.TProfile("jecvseta", "jecvseta", 20, -5., 5., 0.1, 1.5) respvseta = ROOT.TProfile("responsevseta", "responsevseta", 20, -5., 5., 0.1, 1.5) for eta_th in eta_thresholds: resp[eta_th] = ROOT.TProfile("response", "response", len(thresholds) - 1, array.array('d', thresholds)) resp[eta_th].SetName("response " + str(eta_th)) for fileName in files: events = Events(fileName) HLTJetHandle = Handle('std::vector<pat::Jet>') # GenJetHandle = Handle('std::vector<reco::GenJet>') deltaRMin = ROOT.TH1F("deltaRMin", "", 100, 0., 1.0) for event in events: # event.getByLabel(("ak4GenJets"), GenJetHandle) # genJets = GenJetHandle.product() # event.getByLabel(("slimmedJetsPuppi"), HLTJetHandle) # l2Jets = HLTJetHandle.product() # for genJet in genJets: # if genJet.pt() < 10: continue # deltaR_min = 0.4 # jetEt = -1000 # for jet in l2Jets: # deltar = deltaR(genJet.eta(), genJet.phi(), jet.eta(),jet.phi()) # if deltar < deltaR_min: # deltaR_min = deltar # jetEt = jet.et() # deltaRMin.Fill(deltaR_min) # if jetEt < -20: continue # if abs(genJet.eta()) > eta_thresholds[0] and abs(genJet.eta()) < eta_thresholds[1]: # resp[eta_thresholds[0]].Fill(genJet.et(), jetEt / (genJet.et())) # respvseta.Fill(genJet.eta(), jetEt / (genJet.et()) ) event.getByLabel(JetCollection, HLTJetHandle) l2Jets = HLTJetHandle.product() deltaR_min = 0.1 jetPt = -1000 for jet in l2Jets: if abs(jet.eta()) > 1.3: continue if jet.pt() < 20: continue genJet = jet.genJet() if not genJet: continue if genJet.pt() < 20: continue # if genJet.pt() > 200: continue deltar = deltaR(genJet.eta(), genJet.phi(), jet.eta(), jet.phi()) if deltar < deltaR_min: deltaR_min = deltar jetPt = jet.pt() if jetPt < -20: continue deltaRMin.Fill(deltaR_min) if abs(genJet.eta()) > eta_thresholds[0] and abs( genJet.eta()) < eta_thresholds[1]: # print genJet.pt(), jet.pt(), jet.correctedP4(0).pt(), jet.correctedP4(1).pt(), jet.correctedP4(2).pt() #, jet.correctedP4(3).pt() resp[eta_thresholds[0]].Fill(genJet.pt(), jetPt / (genJet.pt())) respvseta.Fill(genJet.eta(), jetPt / (genJet.pt())) jecvspt.Fill(genJet.pt(), jet.pt() / jet.correctedP4(0).pt()) jecvseta.Fill(genJet.eta(), jet.pt() / jet.correctedP4(0).pt()) c1 = ROOT.TCanvas() resp[eta_thresholds[0]].Draw() c1.SaveAs("resVSpt_" + str(eta_thresholds[0]) + jetType + ".pdf") c2 = ROOT.TCanvas() deltaRMin.Draw() c2.SaveAs("deltaR_" + jetType + ".pdf") respvseta.GetYaxis().SetRangeUser(0.1, 1.5) respvseta.Draw() c2.SaveAs("resVsEta_" + jetType + ".pdf") jecvspt.Draw() c2.SaveAs("jecVsPt_" + jetType + ".pdf") jecvseta.Draw() c2.SaveAs("jecVsEta_" + jetType + ".pdf") mylist = [deltaRMin, respvseta] mylist.append(resp[eta_thresholds[0]]) return mylist
def run(self): # handles genH, genN = Handle( "std::vector<reco::GenParticle>"), "prunedGenParticles" infoH, infoN = Handle("GenEventInfoProduct"), "generator" lheH, lheN = Handle("LHEEventProduct"), "externalLHEProducer" start = time.time() # loop over the events ############################################### for i, event in enumerate(self.events): if i % 1000 == 0: print "Processing event", i, '/', self.events.size() if self.debug: if i % 100 == 0: print "Processing event", i, '/', self.events.size() if i > 1000: break # fill with default values fill_default(self.variables) # load LHE product event.getByLabel(lheN, lheH) lhe = lheH.product() hepeup = lhe.hepeup() self.variables['scale'][0] = hepeup.SCALUP self.variables['alphaQCD'][0] = hepeup.AQCDUP self.variables['alphaQED'][0] = hepeup.AQEDUP isW = False isWToMuNu = False Wp4_lhe = [0., 0., 0., 0., 0.] for p in range(hepeup.NUP): if self.verbose: print 'HEPEUP...', p, 'pdg:', hepeup.IDUP[ p], '(', hepeup.PUP[p][0], hepeup.PUP[p][ 1], hepeup.PUP[p][2], hepeup.PUP[p][3], ')' # first parton if p == 0: self.variables['id1'][0] = hepeup.IDUP[p] self.variables['x1'][0] = hepeup.PUP[p][3] / 6500. elif p == 1: self.variables['id2'][0] = hepeup.IDUP[p] self.variables['x2'][0] = hepeup.PUP[p][3] / 6500. if abs(hepeup.IDUP[p]) == 13: isWToMuNu = True if abs(hepeup.IDUP[p]) == (24 if self.DY == 'CC' else 23): isW = True for x in range(5): Wp4_lhe[x] = hepeup.PUP[p][x] Wp4 = ROOT.TLorentzVector(Wp4_lhe[0], Wp4_lhe[1], Wp4_lhe[2], Wp4_lhe[3]) self.variables['lhe_y'][0] = Wp4.Rapidity() self.variables['lhe_qt'][0] = Wp4.Pt() self.variables['lhe_mass'][0] = Wp4.M() self.variables['lhe_phi'][0] = Wp4.Phi() # consider only W->munu events if not (isW and isWToMuNu): continue # LHE weights norm = abs(lhe.originalXWGTUP()) wid = 0 for w in lhe.weights(): if wid >= 109: continue #if self.verbose: # print w.id, w.wgt self.variables['weights'][wid] = w.wgt / norm wid += 1 # read gen particles event.getByLabel(genN, genH) genParticles = list(genH.product()) # filter muons, neutrinos and gammas muons = [p for p in genParticles if isMuon(p)] neutrinos = [p for p in genParticles if isNeutrino(p)] gammas = [p for p in genParticles if isPhoton(p)] # sort by pt muons.sort(reverse=True) neutrinos.sort(reverse=True) # CC: consider events with 0 muons to study acceptance if self.DY == 'CC' and len(muons) == 0: if self.verbose: print "No muon in W>munu for event", i, ". Try to understand why:" print " > W rapidity: ", self.variables['lhe_y'][0] self.variables['muLost'][0] += 1.0 if len(neutrinos) > 0: self.variables[t + '_nu_pt'][0] = neutrinos[0].p4().Pt() self.variables[t + '_nu_eta'][0] = neutrinos[0].p4().Eta() self.variables[t + '_nu_phi'][0] = neutrinos[0].p4().Phi() # consider events with 0 neutrinos to study acceptance if self.DY == 'CC' and len(neutrinos) == 0: if self.verbose: print "No muon neutrinos for event", i, ". Try to understand why:" print " > W rapidity: ", self.variables['lhe_y'][0] print " > Muon rapidity: ", muons[0].p4().Rapidity() self.variables['nuLost'][0] += 1.0 if len(muons) > 0: self.variables[t + '_mu_pt'][0] = muons[0].p4().Pt() self.variables[t + '_mu_eta'][0] = muons[0].p4().Eta() self.variables[t + '_mu_phi'][0] = muons[0].p4().Phi() # NC: consider events with 1 muons to study acceptance if self.DY == 'NC' and len(muons) < 2: if self.verbose: print "No muons in Z>mumu for event", i, ". Try to understand why:" print " > Z rapidity: ", self.variables['lhe_y'][0] self.variables['muLost'][0] += 1.0 if len(muons) == 1: self.variables[t + '_nu_pt'][0] = muons[0].p4().Pt() self.variables[t + '_nu_eta'][0] = muons[0].p4().Eta() self.variables[t + '_nu_phi'][0] = muons[0].p4().Phi() # if no muons or no neutrinos, save the event and continue if self.DY == 'CC': if (len(muons) == 0 or len(neutrinos) == 0): if self.save_tree: self.outtree.Fill() continue elif self.DY == 'NC': if len(muons) < 2: if self.save_tree: self.outtree.Fill() continue # the muon is the first ranked by pt if CC else the mu+ mu = muons[0] if self.DY == 'NC': mu = (muons[0] if muons[0].pdgId() == -13 else muons[1]) self.variables['isFromW'][0] += int( isFromW(mu) if self.DY == 'CC' else isFromZ(mu)) self.variables['mu_charge'][0] = mu.pdgId() if self.verbose: printp('muon', mu, '') # the neutrino is the first ranked by pt if CC else the mu- nu = None if self.DY == 'CC': nu = neutrinos[0] elif self.DY == 'NC': nu = (muons[0] if muons[0].pdgId() == +13 else muons[1]) self.variables['isFromW'][0] += int( isFromW(nu) if self.DY == 'CC' else isFromZ(nu)) self.variables['nu_charge'][0] = nu.pdgId() if self.verbose: printp('neut', nu, '') # pre-FSR mother = mu mu_prefsr = mu while (mother.numberOfMothers() > 0): if self.verbose: printp('MOTH', mother, '') if abs(mother.pdgId()) == 13 and mother.statusFlags( ).isLastCopyBeforeFSR(): mu_prefsr = mother mother = mother.mother(0) mother = nu nu_prefsr = nu while (mother.numberOfMothers() > 0): if self.verbose: printp('MOTH', mother, '') if abs(mother.pdgId()) == 13 and mother.statusFlags( ).isLastCopyBeforeFSR(): nu_prefsr = mother mother = mother.mother(0) # standard dressing alorithm mu_fsr, nu_fsr = [], [] gammas.sort(reverse=True) for ng, g in enumerate(gammas): dR_mu = deltaR(mu, g) dR_nu = deltaR(nu, g) dR = (dR_mu if self.DY == 'CC' else min(dR_mu, dR_nu)) if dR < 0.1: if self.DY == 'CC': mu_fsr.append(g.p4()) if self.verbose: printp('>gam', g, 'dR:{:03.2f}'.format(dR) + ' to muon') elif self.DY == 'NC': if dR_mu < dR_nu: mu_fsr.append(g.p4()) if self.verbose: printp('>gam', g, 'dR:{:03.2f}'.format(dR) + ' to muon-') else: nu_fsr.append(g.p4()) if self.verbose: printp('>gam', g, 'dR:{:03.2f}'.format(dR) + ' to mu+') # bare mup4 = ROOT.TLorentzVector(mu.p4().Px(), mu.p4().Py(), mu.p4().Pz(), mu.p4().E()) nup4 = ROOT.TLorentzVector(nu.p4().Px(), nu.p4().Py(), nu.p4().Pz(), nu.p4().E()) # pre-FSR mup4_prefsr = ROOT.TLorentzVector(mu_prefsr.p4().Px(), mu_prefsr.p4().Py(), mu_prefsr.p4().Pz(), mu_prefsr.p4().E()) nup4_prefsr = copy.deepcopy( nup4) if self.DY == 'CC' else ROOT.TLorentzVector( nu_prefsr.p4().Px(), nu_prefsr.p4().Py(), nu_prefsr.p4().Pz(), nu_prefsr.p4().E()) # dressed mup4_recfsr = copy.deepcopy(mup4) for g in mu_fsr: mup4_recfsr += ROOT.TLorentzVector(g.Px(), g.Py(), g.Pz(), g.E()) nup4_recfsr = copy.deepcopy(nup4) if self.DY == 'NC': for g in nu_fsr: nup4_recfsr += ROOT.TLorentzVector(g.Px(), g.Py(), g.Pz(), g.E()) # list of p4 for W Wp4 = {} Wp4['Wbare'] = mup4 + nup4 # the mu+nu p4 after FSR Wp4['WpreFSR'] = mup4_prefsr + nup4_prefsr # the mu+nu p4 pre-FSR Wp4['Wdress'] = mup4_recfsr + nup4_recfsr # the mu+nu p4 w/ dressed mu for t in ['Wbare', 'Wdress', 'WpreFSR']: self.variables[t + '_mass'][0] = Wp4[t].M() self.variables[t + '_qt'][0] = Wp4[t].Pt() self.variables[t + '_y'][0] = Wp4[t].Rapidity() self.variables[t + '_phi'][0] = Wp4[t].Phi() mup4LV = mup4 nup4LV = nup4 if t == 'Wdress': mup4LV = mup4_recfsr nup4LV = nup4_recfsr elif t == 'WpreFSR': mup4LV = mup4_prefsr nup4LV = nup4_prefsr self.variables[t + '_mu_pt'][0] = mup4LV.Pt() self.variables[t + '_mu_eta'][0] = mup4LV.Eta() self.variables[t + '_mu_phi'][0] = mup4LV.Phi() self.variables[t + '_nu_pt'][0] = nup4LV.Pt() self.variables[t + '_nu_eta'][0] = nup4LV.Eta() self.variables[t + '_nu_phi'][0] = nup4LV.Phi() # the CS variables ps = boost_to_CS_root(Lp4=mup4LV, Wp4=Wp4[t]) self.variables[t + '_ECS'][0] = ps[0] self.variables[t + '_cosCS'][0] = ps[1] self.variables[t + '_phiCS'][0] = ps[2] if self.save_histo: if t not in ['Wdress']: continue for w in self.weights_for_histos: fill_coefficients( histos=self.histos, charge=self.variables['mu_charge'][0], coefficients_for_histos=self. coefficients_for_histos, var='Wdress', weight_name=w, ps_W=(Wp4[t].Rapidity(), Wp4[t].Pt()), ps_CS=(ps[1], ps[2]), weight=self.variables['weights'][w]) if self.DY == 'NC': fill_coefficients( histos=self.histos, charge=self.variables['nu_charge'][0], coefficients_for_histos=self. coefficients_for_histos, var='Wdress', weight_name=w, ps_W=(Wp4[t].Rapidity(), Wp4[t].Pt()), ps_CS=(-ps[1], ps[2] + math.pi - (2 * math.pi if (ps[2] + math.pi) > 2 * math.pi else 0.0)), weight=self.variables['weights'][w]) # fill the tree if self.save_tree: self.outtree.Fill() ############################################### stop = time.time() # save and close self.outfile.cd() if self.save_tree: self.outtree.Write("tree", ROOT.TObject.kOverwrite) if self.save_histo: for kq, q in self.histos.items(): print 'Charge: ' + kq self.outfile.mkdir(kq) for kv, v in q.items(): print '\tVar: ' + kv self.outfile.mkdir(kq + '/' + kv) for kc, c in v.items(): print '\t\tVar: ' + kc self.outfile.mkdir(kq + '/' + kv + '/' + kc) for kw, w in c.items(): print '\t\t\tWeight: ' + kw + '.....', w[ 0].GetEntries(), 'entries' self.outfile.cd(kq + '/' + kv + '/' + kc) w[0].Write('', ROOT.TObject.kOverwrite) w[1].Write('', ROOT.TObject.kOverwrite) self.outfile.cd() if self.debug and self.save_tree: add_vars(tree=self.outtree, debug=True) self.outfile.Close() print "Output file closed. Processed ", i, "events in " + "{:03.0f}".format( stop - start) + " sec.(" + "{:03.0f}".format( i / (stop - start)) + " Hz)"
def printDaughters(particle, level): # genPrint(particle, level) if (level < 6 and particle.numberOfDaughters() > 0): for kDaughter in range(0, particle.numberOfDaughters()): daughter = particle.daughter(kDaughter) genPrint(daughter, level) if ((daughter.pdgId() > 9 or daughter.pdgId() < -9) and not daughter.pdgId() == 1): printDaughters(daughter, level + 1) for event in events: event.getByLabel(genParticleTAG, handleGenParticles) genParticles = handleGenParticles.product() for genParticle in genParticles: if (genParticle.pdgId() == 9900024 or genParticle.pdgId() == -9900024): # recursive function printing decay printDaughters(genParticle, 1) nuR = genParticle.daughter(1) nWR[genParticle.pdgId()] += 1 nWRdaughter0[genParticle.daughter(0).pdgId()] += 1 nNuR[nuR.pdgId()] += 1 nWstarR[nuR.daughter(1).pdgId()] += 1 nNuRdaughter0[nuR.daughter(0).pdgId()] += 1 if (nuR.numberOfDaughters() > 2):
handleLHEEventProduct = Handle ("LHEEventProduct") labelLHEEventProduct = ("source") n_weighted_run_over = 0 n_run_over = 0 n_weighted_selected = 0 n_selected = 0 for event in events: n_run_over += 1 event.getByLabel (labelLHEEventProduct, handleLHEEventProduct) lheevent = handleLHEEventProduct.product() n_leptons = 0 n_photons = 0 if lheevent.originalXWGTUP() > 0: n_weighted_run_over += 1 else: n_weighted_run_over -= 1 for i in range(0,len(lheevent.hepeup().IDUP)): v=ROOT.TLorentzVector() v.SetPxPyPzE(lheevent.hepeup().PUP.at(i)[0],lheevent.hepeup().PUP.at(i)[1],lheevent.hepeup().PUP.at(i)[2],lheevent.hepeup().PUP.at(i)[3]) if lheevent.hepeup().ISTUP.at(i) != 1: continue
def fetchCSCGEANT(event): geantH = Handle('vector<PSimHit>') event.getByLabel('g4SimHits:MuonCSCHits', geantH) geant = filter(lambda x: x.pabs() > 0.5 and abs(x.particleType()) == 13, geantH.product()) return geant
if i % 1000 == 0 : print ' ---> Event ' + str(i) ## _____ ____ __. _____ ____. __ __________.__ __ ## / _ \ | |/ _| / | | | | _____/ |_ \______ \ | _____/ |_ ______ ## / /_\ \| < / | |_ | |/ __ \ __\ | ___/ | / _ \ __\/ ___/ ## / | \ | \/ ^ / /\__| \ ___/| | | | | |_( <_> ) | \___ \ ## \____|__ /____|__ \____ | \________|\___ >__| |____| |____/\____/|__| /____ > ## \/ \/ |__| \/ \/ # get rho and vertices for JEC event.getByLabel (rhoLabel, rhoHandle) event.getByLabel (pvLabel, pvHandle) rhoValue = rhoHandle.product() pvs = pvHandle.product() #print rhoValue[0] if options.verbose : print '------ AK4 jets ------' # use getByLabel, just like in cmsRun event.getByLabel (jetlabel0, jethandle0) # get the product jets0 = jethandle0.product() # loop over jets and fill hists ijet = 0 for jet in jets0 : if ijet >= options.maxjets : break
electrons, electronLabel = Handle( "std::vector<pat::Electron>"), "slimmedElectrons" for iev, event in enumerate(events): if iev > 10: break event.getByLabel(muonLabel, muons) event.getByLabel(electronLabel, electrons) print "\nEvent %d: run %6d, lumi %4d, event %12d" % ( iev, event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(), event.eventAuxiliary().event()) # Muons for i, mu in enumerate(muons.product()): if mu.pt() < 5 or not mu.isLooseMuon(): continue print "muon %2d: pt %4.1f, POG loose id %d." % (i, mu.pt(), mu.isLooseMuon()) selectMuon(muons.product(), i, event) print selectMuon # Electrons for i, el in enumerate(electrons.product()): if el.pt() < 5: continue print "elec %2d: pt %4.1f, supercluster eta %+5.3f, sigmaIetaIeta %.3f (%.3f with full5x5 shower shapes), pass conv veto %d" % ( i, el.pt(), el.superCluster().eta(), el.sigmaIetaIeta(), el.full5x5_sigmaIetaIeta(), el.passConversionVeto()) passfail = selectElectron(electrons.product(), i, event) print selectElectron
recoMu_eta = list() recoMu_dR = list() # deltaR between leading and subleading for i, event in enumerate(events, 1): if i % 1000 == 1: print("{} Event : {}".format(bkgType, i)) # if i>50: break ############################################# ## GEN ############################################# event.getByLabel(genLbl, genHdl) if not genHdl.isValid(): continue genp = genHdl.product() nGen = len(genp) # print('Number of gen particles: {}'.format(nGen)) if i == 1: print("{:6} {:6} {:6} {:>12} {:>12} {:>12}".format( "pdgId", "momPid", "status", "pT", "eta", "phi")) print("=" * (6 * 3 + 5 + 12 * 3)) mompid_ = [23, 24] # Z/W momCol_ = [g for g in genp if g.isLastCopy() and abs(g.pdgId()) in mompid_] muCol_ = sorted( [g for g in genp if g.isLastCopy() and abs(g.pdgId()) == 13], key=lambda p: p.pt(), reverse=True, )[:6]
else: inputfile = str(sys.argv[1]) openfile = TFile.Open(inputfile, "READ") events = Events(openfile) ## Handle(Type). Example Handles: #handle = Handle('std::vector<reco::GenParticle>') handle = Handle('vector<reco::GenParticle>') label = ("genParticles", "", "SIM") # Each item in this for loop is an entire gg-->H-->ZZd-->4lep process ### numProcess = 0 for count, e in enumerate(events, 1): if count > 100: break e.getByLabel(label, handle) genParticles = handle.product() numProcess += 1 # Each item in this for loop is a single particle in the process above ### for p in genParticles: if not p.isHardProcess(): continue #print p.pdgId(),p.pt(),p.eta() # Potentially interesting quantities: # charge(), p4(), p(), energy(), et?, et2?, # mass(), massSqr(), pt(), phi(), theta(), eta() # rapidity(), vertex(), status(), longLived() # isElectron(), isMuon(), is StandAloneMuon() # isGlobalMuon(), isTrackerMuon(), isCaloMuon() # is Photon(), isConvertedPhoton(), isJet() if p.pdgId() == 1023: #print "-"*20 print "Process %d: %f" % (count, p.mass())
lxplus = '/eos/cms/store/group/dpg_hcal/comm_hcal/CMS_POS/cosmic/525486FA-F98F-0849-843E-1E23C444DCB2.root' if path.exists(aachen): inputfile = aachen elif path.exists(lxplus): inputfile = lxplus else: print('No input file found!') events = Events(inputfile) muonhandle = Handle('vector<reco::Muon>') muonlabel = 'muons' for event in events: event.getByLabel(muonlabel, muonhandle) muons = muonhandle.product() for muon in muons: depths = [] # use depths.append(x) to add an item to the list # Can you figure out how to extract calorimeter energy and depth information from the reco::Muon class? # Check the CMSSW doxygen for all its members/functions: http://cmsdoxygen.web.cern.ch/cmsdoxygen/CMSSW_10_6_1_patch2/doc/html/df/de3/classreco_1_1Muon.html if all(d in depths for d in [1,2,3,4]): hist.Fill(hadEnergy) ROOT.gStyle.SetOptFit(1) c = ROOT.TCanvas('c', 'c', 500, 450) c.cd() hist.Draw() hist.Fit('landau')
h_genht_pfht900 = ROOT.TH1F("h_genht_pfht900", "", 100, 0, 3000) h_genht_pfht1050 = ROOT.TH1F("h_genht_pfht1050", "", 100, 0, 3000) # loop over events count = 0 for event in events: pfjet = 0 ncount = 0 count += 1 """ if count > 100: continue """ #genjets event.getByLabel(labelgenfatjet, handle_genfatjet) event.getByLabel(labelgenjet, handle_genjet) fatgenjet = handle_genfatjet.product() genjet = handle_genjet.product() #genparticles event.getByLabel(labelPruned, handlePruned) pruned = handlePruned.product() event.getByLabel(labelPacked, handlePacked) packed = handlePacked.product() #recoMET event.getByLabel(label_recoMET_noHF, handle_recoMET_noHF) recomet_nohf = handle_recoMET_noHF.product() event.getByLabel(label_recoMET, handle_recoMET) recomet = handle_recoMET.product() #genMET event.getByLabel(label_genMET, handle_genMET) genmet = handle_genMET.product() #recojets
tree.Branch('t_gamma_distance_all', t_gamma_distance_all, 't_gamma_distance_allT/D') tree.Branch('t_h_pt', t_h_pt, 't_h_pt/D') tree.Branch('t_s_mass', t_s_mass, 't_s_mass/D') tree.Branch('t_s_pt', t_s_pt, 't_s_pt/D') tree.Branch('t_b_pt_all', t_b_pt_all, 't_b_pt_all/D') higgs_x = 0 higgs_y = 0 higgs_z = 0 for i, event in enumerate(events): #print "\nEvent", i event.getByLabel(genParticlesN, genParticlesH) gen_particles = genParticlesH.product() #print len(gen_particles); #LOOP OVER ALL PARTICLES s_p4_list = [] daughter_p4_list = [] for g in gen_particles: #FIND HIGGS if g.pdgId() == 25 and g.status() == 22: print "higgs, ", g.pt() #t_h_pt[0] = g.pt() higgs_x = g.vertex().x() higgs_y = g.vertex().y() higgs_z = g.vertex().z()
if 'inLHE' not in inputFile: inFile = os.path.join(inputDir, inputFile) file_count += 1 events = Events(inFile) nevents = int(events.size()) if file_count % 10 == 0: print("Analyzing file # %d" % file_count) #print("Number of events: %d" % nevents) for event in events: event.getByLabel(metLabel, mets) event.getByLabel(genParticleLabel, genParticles) MET_hist.Fill(mets.product()[0].pt()) numLQ = [0, 0, 0] if args.LQhist: if mets.product()[0].pt() < MET_bounds[0]: for particle in genParticles.product(): if abs(particle.pdgId()) == 1104 and particle.status( ) == 22: numLQ[0] += 1 numLQ_hist1.Fill(numLQ[0])
100 * count / totevents) + '% -- ' #Here we split up event processing based on number of jobs #This is set up to have jobs range from 1 to the total number of jobs (ie dont start at job 0) if jobs != 1: if (count - 1) % jobs == 0: jobiter += 1 count_index = count - (jobiter - 1) * jobs if count_index != num: continue if usegenweight: try: event.getByLabel(GeneratorLabel, GeneratorHandle) gen = GeneratorHandle.product() Nevents.Fill(0., gen.weightProduct()) except: continue AK8LV = Makelv(AK8HL, event) if len(AK8LV) == 0: continue tindex, bindex = Hemispherize(AK8LV, AK8LV) bJetsh1 = [] bJetsh0 = [] topJetsh1 = [] topJetsh0 = []
from ROOT import gROOT, gStyle, TCanvas, TF1, TFile, TTree, gRandom, TH1F, TH2F import os eventsRef = Events("SingleEleC_Run200091_Event656063159_lumi538_AOD.root") eventsNew = Events("step2_inAOD_74.root") tracks = Handle("std::vector<reco::Track>") label = "generalTracks" quality = "highPurity" i=0 a= eventsRef.to(i) print "Event", i a=eventsRef.getByLabel(label, tracks) for track in tracks.product(): if (track.phi()>0) : continue if (track.eta()<0) : continue if (track.pt()<2) : continue if (track.quality(track.qualityByName(quality))) : print "ori", track.phi(),track.eta(),track.pt(),track.ndof(),track.chi2(), track.algo() i=1 a= eventsNew.to(i) print "Event", i a=eventsNew.getByLabel(label, tracks) for track in tracks.product(): if (track.phi()>0) : continue if (track.eta()<0) : continue if (track.pt()<2) : continue if (track.quality(track.qualityByName(quality))) :
def cand(pair): return pair[0].p4() + pair[1].p4() dphi = ROOT.Math.VectorUtil.DeltaPhi deltaR = ROOT.Math.VectorUtil.DeltaR hdrpt = ROOT.TH2D("ZdeltaRllvsPt", "DeltaR Z leptons;#DeltaR(l_{1}, l_{2});p_{T,Z};Counts", 30, 0, 3, 60, 0, 600) for iev, event in enumerate(events): event.getByLabel('prunedGenParticles', genHandle) genParticles = genHandle.product() leptons = [ p for p in genParticles if p.isHardProcess() and abs(p.pdgId()) in [11, 13] ] leadingPair = None for i, lep1 in enumerate(leptons): lep2 = filter( lambda l: l.pdgId() == -lep1.pdgId() and l.mother() == lep1.mother( ), leptons) if len(lep2) != 1: print "wtf" lep2 = lep2[0] pair = (lep1, lep2) if lep1.pt() > lep2.pt() else (lep2, lep1) if not leadingPair:
#!/usr/bin/env python from DataFormats.FWLite import Events, Handle, Lumis from ROOT import * gROOT.ProcessLine(".x tdrstyle.C") files = [ "file:/cmsdas/data/ShortEX_Muon/RelValZMM_13_MINIAODSIM/0AF36725-FB1A-E511-BCB2-0025905A497A.root", #"/store/relval/CMSSW_7_4_6/RelValZMM_13/MINIAODSIM/PU50ns_MCRUN2_74_V8-v2/00000/0AF36725-FB1A-E511-BCB2-0025905A497A.root", ] events = Events(files) muonHandle = Handle('std::vector<pat::Muon>') for iEvent, event in enumerate(events): print 'Analyzing', iEvent, 'th event' event.getByLabel('slimmedMuons', muonHandle) muons = muonHandle.product() if muons.size() < 2: continue muon1, muon2 = muons[0], muons[1] if muon2.pt() <= 1: continue print "Leading pt, eta, phi, charge = ", (muon1.pt(), muon1.eta(), muon1.phi(), muon1.charge()) print "Trailing pt, eta, phi, charge = ", (muon2.pt(), muon2.eta(), muon2.phi(), muon2.charge())
# like and edm::InputTag label1 = ("prunedGenParticles") f = ROOT.TFile("prunedGenParticle_unittest_fwlite.root", "RECREATE") f.cd() # loop over events i = 0 for event in events: i = i + 1 print '--------- Processing Event ' + str(i) # use getByLabel, just like in cmsRun event.getByLabel (label1, handle1) # get the product gens = handle1.product() for igen in range(0,len(gens)) : gen = gens[igen] if gen.numberOfDaughters() > 1 : print '{0:6.0f} : pdgid = {1:6.0f}, status = {2:6.0f}, da0 id = {3:6.0f}, da1 = {4:6.0f}, '.format( igen, gen.pdgId(), gen.status(), gen.daughter(0).pdgId(), gen.daughter(1).pdgId() ) elif gen.numberOfDaughters() > 0 : print '{0:6.0f} : pdgid = {1:6.0f}, status = {2:6.0f}, da0 id = {3:6.0f}, da1 = {4:6.0f}, '.format( igen, gen.pdgId(), gen.status(), gen.daughter(0).pdgId(), -9999 ) else : print '{0:6.0f} : pdgid = {1:6.0f}, status = {2:6.0f}, da0 id = {3:6.0f}, da1 = {4:6.0f}, '.format( igen, gen.pdgId(), gen.status(), -9999, -9999
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(fatjetLabel, fatjets) event.getByLabel(metLabel, mets) event.getByLabel(vertexLabel, vertices) event.getByLabel(vertexLabel, verticesScore) print "\nEvent %d: run %6d, lumi %4d, event %12d" % ( iev, event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(), event.eventAuxiliary().event()) # Vertices if len(vertices.product()) == 0 or vertices.product()[0].ndof() < 4: print "Event has no good primary vertex." continue else: PV = vertices.product()[0] print "PV at x,y,z = %+5.3f, %+5.3f, %+6.3f, ndof: %.1f, score: (pt2 of clustered objects) %.1f" % ( PV.x(), PV.y(), PV.z(), PV.ndof(), verticesScore.product().get(0)) # Muons for i, mu in enumerate(muons.product()): if mu.pt() < 5 or not mu.isLooseMuon(): continue print "muon %2d: pt %4.1f, dz(PV) %+5.3f, POG loose id %d, tight id %d." % ( i, mu.pt(), mu.muonBestTrack().dz( PV.position()), mu.isLooseMuon(), mu.isTightMuon(PV)) # Electrons
for iev, event in enumerate(events): if iev > 10: break event.getByLabel(muonLabel[0], muonLabel[1], muonLabel[2], muons) event.getByLabel(electronLabel[0], electronLabel[1], electronLabel[2], electrons) event.getByLabel(photonLabel[0], photonLabel[1], photonLabel[2], photons) print "\nEvent %d: run %6d, lumi %4d, event %12d" % ( iev, event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(), event.eventAuxiliary().event()) # Muons for i, mu in enumerate(muons.product()): if mu.pt() < 5 or not mu.isLooseMuon(): continue print "muon %2d: pt %4.1f, POG loose id %d." % (i, mu.pt(), mu.isLooseMuon()) for selectMuon in selectMuons: selectMuon(muons.product(), i, event) print selectMuon # Electrons for i, el in enumerate(electrons.product()): if el.pt() < 5: continue print "elec %2d: pt %4.1f, supercluster eta %+5.3f, sigmaIetaIeta %.3f (%.3f with full5x5 shower shapes), pass conv veto %d" % ( i, el.pt(), el.superCluster().eta(), el.sigmaIetaIeta(), el.full5x5_sigmaIetaIeta(), el.passConversionVeto()) passfail_byvalue = selectElectron(el, event) passfail = selectElectron(electrons.product(), i, event)
def cscSegmentsPhi(event, ontime=True, twinMux=True): phiSeg = Handle('std::vector<std::pair<CSCDetId,CSCCorrelatedLCTDigi> >') event.getByLabel('cscTriggerHits', phiSeg) digis = phiSeg.product() return digis
print inputfile # loop over events cnt = 0 for event in events: numlep = 0 numjets = 0 visE = 0 visEonlyjets = 0 numjets_PF = 0 visE_PF = 0 visEonlyjets_PF = 0 event.getByLabel(label, handle) genparticles = handle.product() for particle in genparticles: if particle.status() == 1: #if stable if abs(particle.pdgId()) in leptons: if particle.pt() > 3: numlep += 1 hist_leptonpt.Fill(particle.pt()) conept = 0 isolation = 0 pvec = TLorentzVector() pvec.SetPtEtaPhiM(particle.pt(), particle.eta(), particle.phi(), particle.mass()) for oparticle in genparticles: if oparticle.status() == 1:
} print('start processing') accepted = 0 for i, event in enumerate(events): nEvent = event._event.id().event() print("processing event {0}: {1}...".format(i, nEvent)) # Save information on the first electron in an event, # if there is any the first electron of the event.getByLabel(('slimmedElectrons'), ele_handle) electrons = ele_handle.product() if not len(electrons): continue event.getByLabel(('fixedGridRhoFastjetAll'), rho_handle) event.getByLabel(('reducedEgamma:reducedConversions'), conv_handle) event.getByLabel(('offlineBeamSpot'), bs_handle) convs = conv_handle.product() beam_spot = bs_handle.product() rho = rho_handle.product() ele = electrons[0] i = accepted
from DataFormats.FWLite import Handle, Events triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), ("TriggerResults","","HLT") triggerObjects, triggerObjectLabel = Handle("std::vector<pat::TriggerObjectStandAlone>"), "selectedPatTrigger" triggerPrescales, triggerPrescaleLabel = Handle("pat::PackedTriggerPrescales"), "patTrigger" # open file (you can use 'edmFileUtil -d /store/whatever.root' to get the physical file name) events = Events("file:DYJetsToLL_M-50_13TeV-madgraph-pythia8-tauola_v2-Spring14miniaod-PU20bx25_POSTLS170_V5-v1.root") 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(i), ": ", ("PASS" if triggerBits.product().accept(i) else "fail (or not run)") print "\n === TRIGGER OBJECTS ===" for j,to in enumerate(triggerObjects.product()): to.unpackPathNames(names); print "Trigger object pt %6.2f eta %+5.3f phi %+5.3f " % (to.pt(),to.eta(),to.phi()) print " collection: ", to.collection() print " type ids: ", ", ".join([str(f) for f in to.filterIds()]) print " filters: ", ", ".join([str(f) for f in to.filterLabels()]) pathslast = set(to.pathNames(True)) print " paths: ", ", ".join([("%s*" if f in pathslast else "%s")%f for f in to.filterLabels()]) if iev > 10: break
print print "Opening ", filesInput print events = Events(filesInput) genParticles_source, genParticles_label = Handle( "vector<reco::GenParticle>"), ("genParticles") offVtx_source, offVtx_label = Handle("vector<reco::Vertex>"), ( "offlinePrimaryVertices") genMET_source, genMET_label = Handle("vector<reco::GenMET>"), ("genMetTrue") for iev, event in enumerate(events): event.getByLabel(offVtx_label, offVtx_source) sumPt2 = 0 sumPt2 = 0 iVtx = -1 VtxMax = -1 for idx, vtx in enumerate(offVtx_source.product()): sumPt2 = 0 trk = vtx.tracks_begin() for i in range(vtx.tracksSize()): sumPt2 += trk.get().pt()**2 trk += 1 if sumPt2 > VtxMax: VtxMax = sumPt2 iVtx = idx event.getByLabel(genMET_label, genMET_source) event.getByLabel(genParticles_label, genParticles_source) genMET = genMET_source.product()[0].pt() genZVtx = genParticles_source.product()[2].vz()
# start looping on the events for i, ev in enumerate(events): ###################################################################################### # controls on the events being processed if maxevents > 0 and i > maxevents: break if i % 100 == 0: print '===> processing %d / %d event' % (i, totevents) ###################################################################################### # access the jets ev.getByLabel(label_jets, handle_jets) jets = map(Jet, handle_jets.product()) ev.getByLabel(label_jets_up, handle_jets_up) jets_up = map(Jet, handle_jets_up.product()) for jet in jets + jets_up: jet.deepflavour_prob_b = jet.btag('pfDeepFlavourJetTags:probb') jet.deepflavour_prob_bb = jet.btag('pfDeepFlavourJetTags:probbb') jet.deepflavour_prob_lepb = jet.btag('pfDeepFlavourJetTags:problepb') jet.deepflavour_score = jet.deepflavour_prob_b + \ jet.deepflavour_prob_bb + \ jet.deepflavour_prob_lepb print 'normal jets' for jet in jets: print jet, '\t', jet.partonFlavour(), '\t', jet.deepflavour_score
from DataFormats.FWLite import Handle, Runs import ROOT lheruninfo=Handle('LHERunInfoProduct') runs=Runs('root://eoscms//eos/cms/store/group/phys_top/gkrintir/TopHI/HINPbPbAutumn18DR_skims/WJetsToLNu_TuneCP5_HydjetDrumMB_5p02TeV-amcatnloFXFX-pythia8/B02D2CBB-AFBB-B741-B810-6D00B71B2AAD.root') #runs=Runs('root://cms-xrd-global.cern.ch//store/himc/HINPbPbAutumn18DR/TT_TuneCP5_HydjetDrumMB_5p02TeV-powheg-pythia8/AODSIM/mva98_103X_upgrade2018_realistic_HI_v11-v1/270000/EF779097-4F67-024E-A13E-5EE36B3E5101.root') for r in runs: r.getByLabel('externalLHEProducer',lheruninfo) it=lheruninfo.product().headers_begin() while it!=lheruninfo.product().headers_end(): lines=it.lines() allowPrint=False wgtCtr=0 for i in xrange(0,lines.size()): linestr=lines.at(i) if '<weightgroup' in linestr : allowPrint=True if '</weightgroup' in linestr : allowPrint=False if not allowPrint : continue if 'weightgroup' in linestr : print '*'*50 print linestr print '*'*50 else: if not 'weight' in linestr : continue print wgtCtr,linestr wgtCtr+=1 it.next()