def dumpevent(f): events = Events(f) for i, event in enumerate(events, 1): _run = event.object().id().run() _lumi = event.object().luminosityBlock() _event = event.object().id().event() eventId = '{}-{}-{}'.format(_run, _lumi, _event) print(eventId.center(60, '_')) dsaofljHdl = Handle("vector<edm::FwdPtr<reco::PFCandidate> >") event.getByLabel(("leptonjetSourceDSAMuon", "inclusive", "FF"), dsaofljHdl) assert (dsaofljHdl.isValid()) for mucand in dsaofljHdl.product(): mu = mucand.muonRef() printmuon(mu, event) pfmuofljHdl = Handle("vector<edm::FwdPtr<reco::PFCandidate> >") event.getByLabel(("leptonjetSourcePFMuon", "inclusive", "FF"), pfmuofljHdl) assert (pfmuofljHdl.isValid()) for mucand in pfmuofljHdl.product(): mu = mucand.muonRef() printmuDetId(mu)
def printmuon(mu, event): print("pT: {:.3}GeV (eta, phi): ({:.3}, {:.3})".format( mu.pt(), mu.eta(), mu.phi())) mutk = mu.outerTrack() ncsc = mutk.hitPattern().cscStationsWithValidHits() ndt = mutk.hitPattern().dtStationsWithValidHits() ncschits = mutk.hitPattern().numberOfValidMuonCSCHits() ndthits = mutk.hitPattern().numberOfValidMuonDTHits() print("N(DT+CSC):", ndt + ncsc) print("N(DT+CSC)hits: ", ndthits + ncschits) print("ptErr/pt: {:.3}".format(mutk.ptError() / mutk.pt())) print("normalizedChi2: {:.3}".format(mutk.normalizedChi2())) overlapratioHdl = Handle("edm::ValueMap<float>") event.getByLabel(("dsamuonExtra", "maxSegmentOverlapRatio", "FF"), overlapratioHdl) assert (overlapratioHdl.isValid()) print("overlap ratio:", overlapratioHdl.product().get(mu.id(), mu.key())) localdrHdl = Handle("edm::ValueMap<float>") event.getByLabel(("dsamuonExtra", "minExtrapolateInnermostLocalDr", "FF"), localdrHdl) assert (localdrHdl.isValid()) print("local dR:", localdrHdl.product().get(mu.id(), mu.key())) printmuDetId(mu) print("++++++++++++++++++++++++++++++")
def main(): ak4chsHdl = Handle("std::vector<reco::PFJet>") ak4chsLbl = ("ak4PFJetsCHS", "", "RECO") bTagHdl = Handle( "edm::AssociationVector<edm::RefToBaseProd<reco::Jet>,vector<float>,edm::RefToBase<reco::Jet>,unsigned int,edm::helper::AssociationIdenticalKeyReference>" ) bTagLbl = ("pfCombinedInclusiveSecondaryVertexV2BJetTags", "", "RECO") events = Events(fn) print("Sample's event size: ", events.size()) for i, event in enumerate(events, 1): if i > 30: break event.getByLabel(bTagLbl, bTagHdl) if not bTagHdl.isValid(): continue event.getByLabel(ak4chsLbl, ak4chsHdl) if not ak4chsHdl.isValid(): continue btagDiscr = bTagHdl.product() ak4chs = ak4chsHdl.product() print("Event", "{:>4} :".format(i)) # res = [btagDiscr[ak4chs.refAt(i)].second for i in range(len(ak4chs))] res = [x.second for x in btagDiscr] print(len(ak4chs), [round(x, 3) for x in res if x > 0])
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(): print 'invalid' 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 event.getByLabel(self.trigNamesLabel, self.trigNamesHandle) trigNames = self.trigNamesHandle.product() # trigNames = cms.InputTag("hltPathsReference") #print "trigNames Size", len(trigNames) found = False firedTrig = -1 for mytrig in trigNames: print "fired", mytrig for testtrig in self.trigs: print "testing", testtrig if testtrig == mytrig: found = True break if found: break return found
def FillHistos(files, hpt, hcsv, hptLeading, hcsvLeading, hpu, maxEvents=-1): eventsOff = Events(files) pileUp_source, pileUp_label = Handle("vector<PileupSummaryInfo>"), ( "slimmedAddPileupInfo") offJets_source, offJets_label = Handle("vector<pat::Jet>"), ("slimmedJets") for i, event in enumerate(eventsOff): if i % 10000 == 0: print "Processing event {0:10}".format(i) if maxEvents != -1 and i > maxEvents: break event.getByLabel(offJets_label, offJets_source) event.getByLabel(pileUp_label, pileUp_source) bunchCrossing = 12 if pileUp_source.isValid(): if bunchCrossing >= pileUp_source.product().size( ) or pileUp_source.product().at( bunchCrossing).getBunchCrossing() != 0: found = False for bunchCrossing in range(pileUp_source.product().size()): if pileUp_source.product().at( bunchCrossing).getBunchCrossing() == 0: found = True break if not found: Exception("Check pileupSummaryInfos!") print "I'm using bunchCrossing=", bunchCrossing pu = pileUp_source.product().at( bunchCrossing).getTrueNumInteractions() else: print "!!!!!!" if pu < 20 or pu > 70: continue hpu.Fill(pu) if offJets_source.isValid(): leadingFilled = False for Jet in offJets_source.product(): if Jet.pt() > 30 and abs(Jet.eta()) < 2.4: hpt.Fill(Jet.pt()) hcsv.Fill( Jet.bDiscriminator( "pfCombinedInclusiveSecondaryVertexV2BJetTags")) if not leadingFilled: hptLeading.Fill(Jet.pt()) hcsvLeading.Fill( Jet.bDiscriminator( "pfCombinedInclusiveSecondaryVertexV2BJetTags") ) leadingFilled = True return i
def printsegments(event): cscsegHdl = Handle( "edm::RangeMap<CSCDetId,edm::OwnVector<CSCSegment,edm::ClonePolicy<CSCSegment> >,edm::ClonePolicy<CSCSegment> >" ) event.getByLabel(("cscSegments", "", "RECO"), cscsegHdl) assert (cscsegHdl.isValid()) print("N(CSC) seg:", len(cscsegHdl.product())) dtsegHdl = Handle( "edm::RangeMap<DTChamberId,edm::OwnVector<DTRecSegment4D,edm::ClonePolicy<DTRecSegment4D> >,edm::ClonePolicy<DTRecSegment4D> >" ) event.getByLabel(("dt4DSegments", "", "RECO"), dtsegHdl) assert (dtsegHdl.isValid()) print("N(DT) seg:", len(dtsegHdl.product()))
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
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)
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']
def process(self, event): # if not MC, nothing to do if not self.cfg_comp.isMC: return True event.lheHT = 0 event.lheNj = 0 event.lheV_pt = 0 h = Handle('LHEEventProduct') event.input.getByLabel('externalLHEProducer', h) if not h.isValid(): return True self.readCollections(event.input) hepeup = h.product().hepeup() pup = hepeup.PUP l = None lBar = None nu = None nuBar = None for i in xrange(0, len(pup)): id = hepeup.IDUP[i] status = hepeup.ISTUP[i] idabs = abs(id) if status == 1 and ( (idabs == 21) or (idabs > 0 and idabs < 7)): # gluons and quarks event.lheHT += sqrt( pup[i][0]**2 + pup[i][1]**2) # first entry is px, second py event.lheNj += 1 if idabs in [12, 14, 16]: if id > 0: nu = i else: nuBar = i if idabs in [11, 13, 15]: if id > 0: l = i else: lBar = i v = None if l and lBar: #Z to LL v = (l, lBar) elif l and nuBar: #W v = (l, nuBar) elif lBar and nu: #W v = (nu, lBar) elif nu and nuBar: #Z to nn v = (nu, nuBar) if v: event.lheV_pt = sqrt((pup[v[0]][0] + pup[v[1]][0])**2 + (pup[v[0]][1] + pup[v[1]][1])**2) return True
class AtLheN(Analyzer): """ Attach `nLheElectrons`, `nLheMuos`, `nLheTaus` to the `event`. These are the numbers of the electrons, muons, and taus in LHE. """ def __init__(self, cfg_ana, cfg_comp, looperName): super(AtLheN, self).__init__(cfg_ana, cfg_comp, looperName) self.lheh = Handle('LHEEventProduct') def process(self, event): if not self.cfg_comp.isMC: return True try: event.input.getByLabel('externalLHEProducer', self.lheh) except: self._attach_dummy_to(event) return True if not self.lheh.isValid(): self._attach_dummy_to(event) return True self.readCollections(event.input) nLheElectrons = 0 nLheMuons = 0 nLheTaus = 0 hepeup = self.lheh.product().hepeup() pup = hepeup.PUP for i in xrange(0, len(pup)): pdgabs = abs(hepeup.IDUP[i]) status = hepeup.ISTUP[i] if status == 1 and pdgabs == 11: nLheElectrons += 1 if status == 1 and pdgabs == 13: nLheMuons += 1 if status == 1 and pdgabs == 15: nLheTaus += 1 event.nLheElectrons = nLheElectrons event.nLheMuons = nLheMuons event.nLheTaus = nLheTaus return True def _attach_dummy_to(self, event): event.nLheElectrons = 0 event.nLheMuons = 0 event.nLheTaus = 0
def process(self, event): # if not MC, nothing to do if not self.cfg_comp.isMC: return True event.lheHT=0 event.lheNj=0 event.lheV_pt = 0 h=Handle('LHEEventProduct') event.input.getByLabel( 'externalLHEProducer',h) if not h.isValid() : return True self.readCollections( event.input ) hepeup=h.product().hepeup() pup=hepeup.PUP l=None lBar=None nu=None nuBar=None for i in xrange(0,len(pup)): id=hepeup.IDUP[i] status = hepeup.ISTUP[i] idabs=abs(id) if status == 1 and ( ( idabs == 21 ) or (idabs > 0 and idabs < 7) ) : # gluons and quarks event.lheHT += sqrt( pup[i][0]**2 + pup[i][1]**2 ) # first entry is px, second py event.lheNj +=1 if idabs in [12,14,16] : if id > 0 : nu = i else : nuBar = i if idabs in [11,13,15] : if id > 0 : l = i else : lBar = i v=None if l and lBar : #Z to LL v=(l,lBar) elif l and nuBar : #W v=(l,nuBar) elif lBar and nu : #W v=(nu,lBar) elif nu and nuBar : #Z to nn v=(nu,nuBar) if v : event.lheV_pt = sqrt( (pup[v[0]][0]+pup[v[1]][0])**2 + (pup[v[0]][1]+pup[v[1]][1])**2 ) return True
class Histo: def __init__(self, src, fillfn, *args): self.handle = Handle(src[0]) self.label = src[1] self.hist = ROOT.TH1F(*args) if not fillfn: self.fillfn = lambda x: x[0] if len(x) > 0 else 0 else: self.fillfn = fillfn def fill(self, event): event.getByLabel(self.label, self.handle) if self.handle.isValid(): prod = self.handle.product() self.hist.Fill(self.fillfn(prod))
def main(): jetHdl, jetLbl = Handle("std::vector<reco::PFJet>"), ("ffLeptonJet", "", "FF") sjetHdl, sjetLbl = ( Handle("std::vector<reco::BasicJet>"), ("ffLeptonJetSubjets", "", "FF"), ) subjetHdl, subjetLbl = ( Handle("std::vector<reco::PFJet>"), ("ffLeptonJetSubjets", "SubJets", "FF"), ) jetSjetMapHdl, jetSjetMapLbl = ( Handle("edm::Association<edm::View<reco::Jet> >"), ("ffLeptonJetSLeptonJetMap", "", "FF"), ) events = Events(fn) print("Sample's event size: ", events.size()) for i, event in enumerate(events, 1): if i > 10: break event.getByLabel(jetLbl, jetHdl) assert jetHdl.isValid() event.getByLabel(sjetLbl, sjetHdl) assert sjetHdl.isValid() event.getByLabel(subjetLbl, subjetHdl) assert subjetHdl.isValid() event.getByLabel(jetSjetMapLbl, jetSjetMapHdl) assert jetSjetMapHdl.isValid() jets = jetHdl.product() sjets = sjetHdl.product() subjets = subjetHdl.product() jetsjetMap = jetSjetMapHdl.product() print("\n+++ Event {} +++".format(i)) print("-" * 79) print("jet size:\t", len(jets)) print("sjet size:\t", len(sjets)) print("subjet size:\t", len(subjets)) print(dir(sjetHdl)) print(dir(sjets)) print(dir(jetsjetMap))
def printmuon(event): dsaHdl = Handle("vector<reco::Track>") event.getByLabel(("displacedStandAloneMuons", "", "RECO"), dsaHdl) assert (dsaHdl.isValid()) for mu in dsaHdl.product(): print("pT: {:.3}GeV (eta, phi): ({:.3}, {:.3})".format( mu.pt(), mu.eta(), mu.phi())) print( "track.innerPosition().x()-track.vx():", "{:.3}-{:.3}={:.3}".format(mu.innerPosition().x(), mu.vx(), mu.innerPosition().x() - mu.vx())) print( "track.innerPosition().y()-track.vy():", "{:.3}-{:.3}={:.3}".format(mu.innerPosition().y(), mu.vy(), mu.innerPosition().x() - mu.vy()))
def total_processed(self, fn): """ Returns the total (unskimmed/filtered) count of events processed per this file. Only correct when lumi-blocks are never split. Loops over the lumi blocks in the file, so is not particularly fast. """ lumis = Lumis(fn) tot = 0 handle = Handle("edm::MergeableCounter") for lumi in lumis: lumi.getByLabel("singleTopPathStep1MuPreCount", handle) if handle.isValid(): tot += handle.product().value else: raise Exception("counter not found") return tot
def printPixelClusters(eventsRef, args): container_kind = "edmNew::DetSetVector<SiPixelCluster>" collection_label = args.pixelcluster if args.pixelcluster else "siPixelClusters" from DataFormats.FWLite import Handle, Events clustersRef = Handle(container_kind) label = collection_label for e in range(eventsRef.size()): a = eventsRef.to(e) a = eventsRef.getByLabel(label, clustersRef) print "Run: %7d, LS: %5d, Event: %14d\n" % (eventsRef.eventAuxiliary().run(), eventsRef.eventAuxiliary().luminosityBlock(), eventsRef.eventAuxiliary().event()) if not clustersRef.isValid(): print "Missing collection ", label, container_kind continue for det in clustersRef.product(): for cluster in det: print cluster.adc()
def momentumValue(moduleLabel, productInstanceLabel, processLabel, handleLabel): handle = Handle(handleLabel) events.toBegin() runningSum = 0 for event in events: event.getByLabel(moduleLabel, productInstanceLabel, processLabel, handle) if not handle.isValid(): return -1 runningSum = handle.product().GetEvent().particles_size() begin = handle.product().GetEvent().particles_begin() end = handle.product().GetEvent().particles_end() for p in loop(begin, end): runningSum += p.momentum().x() + p.momentum().y() + p.momentum().z( ) break return runningSum
def meanValue(functionPtr, moduleLabel, productInstanceLabel, processLabel, handleLabel): runningSum = 0 n = 0 handle = Handle(handleLabel) events.toBegin() for event in events: event.getByLabel(moduleLabel, productInstanceLabel, processLabel, handle) if not handle.isValid(): return -1 runningSum += sum([functionPtr(prod) for prod in handle.product()]) n += len(handle.product()) if n > 0: runningSum /= n else: runningSum = 0 return runningSum
def main(): isvHdl = Handle("std::vector<reco::Vertex>") isvLbl = ("inclusiveSecondaryVertices", "", "RECO") events = Events(fn) print("Sample's event size: ", events.size()) for i, event in enumerate(events, 1): if i > 10: break event.getByLabel(isvLbl, isvHdl) if not isvHdl.isValid(): continue isv = isvHdl.product() print("Event", "{:>4} :".format(i), *[formatPoint(v.position()) for v in isv if v.isValid()])
def printSimTrackInformation(eventsRef, args): # printPixelClusters(eventsRef, args) container_kind = "std::vector<SimTrack>" collection_label = args.simtracks if args.simtracks else "g4SimHits" from DataFormats.FWLite import Handle, Events tracksRef = Handle(container_kind) label = collection_label for e in range(eventsRef.size()): a = eventsRef.to(e) a = eventsRef.getByLabel(label, tracksRef) print "Run: %7d, LS: %5d, Event: %14d\n" % (eventsRef.eventAuxiliary().run(), eventsRef.eventAuxiliary().luminosityBlock(), eventsRef.eventAuxiliary().event()) if not tracksRef.isValid(): print "Missing collection ", label, container_kind continue for i, track in enumerate(tracksRef.product()): print "%d] %d %f %f %f" % (i, track.type(), track.momentum().eta(), track.momentum().phi(), track.momentum().pt())
class SimpleHandle: """ A simple interface tying fwlite::Handle<T> and a 3-tuple for a label. """ def make_handle(self, dtype): if dtype=="vfloat": self.handle = Handle("std::vector<float>") elif dtype=="float": self.handle = Handle("float") elif dtype=="double": self.handle = Handle("double") elif dtype=="int": self.handle = Handle("int") else: raise ValueError("Undefined type: %s" % dtype) def __init__(self, dtype, label, instance, process): self.dtype = dtype self.label = label self.instance = instance self.process = process self.make_handle(self.dtype) def get(self, events): """ Returns the product of a handle if valid, ValueError if invalid. """ exc = None try: events.getByLabel((self.label, self.instance, self.process), self.handle) except Exception as e: exc = e self.make_handle(self.dtype) if not exc and self.handle.isValid(): return self.handle.product() else: return NA
def printVertexInformation(eventsRef, container_kind = "std::vector<reco::Vertex>", collection_label = "offlinePrimaryVertices"): from DataFormats.FWLite import Handle, Events verticesRef = Handle(container_kind) label = collection_label print "Analyzing Vertices: %s" % collection_label for e in range(eventsRef.size()): a = eventsRef.to(e) a = eventsRef.getByLabel(label, verticesRef) print "Run: %7d, LS: %5d, Event: %14d\n" % (eventsRef.eventAuxiliary().run(), eventsRef.eventAuxiliary().luminosityBlock(), eventsRef.eventAuxiliary().event()) print HEADER_VTX if not verticesRef.isValid(): print "Missing collection ", label, container_kind continue tr = [] dump_index = 0 for vertex in verticesRef.product(): tr.append((vertex.chi2(), vertex.ndof(), vertex.normalizedChi2(), vertex.isFake(), vertex.isValid(), vertex.tracksSize(), vertex.x(), vertex.y(), vertex.z(), vertex.xError(), vertex.yError(), vertex.zError(), dump_index)) dump_index += 1 for t in tr: print "(%9.6f %9.6f %9.6f %5d %8d %8d %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %6d)" % t print HEADER_VTX
class LHEAnalyzer(Analyzer): """ """ def __init__(self, cfg_ana, cfg_comp, looperName): super(LHEAnalyzer, self).__init__(cfg_ana, cfg_comp, looperName) self.lheh = Handle('LHEEventProduct') def declareHandles(self): super(LHEAnalyzer, self).declareHandles() # self.mchandles['lhestuff'] = AutoHandle( 'externalLHEProducer','LHEEventProduct') def beginLoop(self, setup): super(LHEAnalyzer, self).beginLoop(setup) def process(self, event): # if not MC, nothing to do if not self.cfg_comp.isMC: return True event.lheHT = 0 event.lheHTIncoming = 0 #restrict HT computation to particles that have status<0 mothers event.lheNj = 0 event.lheNb = 0 event.lheNc = 0 event.lheNl = 0 event.lheNg = 0 event.lheV_pt = 0 try: event.input.getByLabel('externalLHEProducer', self.lheh) except: return True if not self.lheh.isValid(): return True self.readCollections(event.input) hepeup = self.lheh.product().hepeup() pup = hepeup.PUP l = None lBar = None nu = None nuBar = None for i in range(0, len(pup)): id = hepeup.IDUP[i] status = hepeup.ISTUP[i] idabs = abs(id) mothIdx = max( hepeup.MOTHUP[i][0] - 1, 0 ) #first and last mother as pair; first entry has index 1 in LHE; incoming particles return motherindex 0 mothIdxTwo = max(hepeup.MOTHUP[i][1] - 1, 0) mothStatus = hepeup.ISTUP[mothIdx] mothStatusTwo = hepeup.ISTUP[mothIdxTwo] hasIncomingAsMother = mothStatus < 0 or mothStatusTwo < 0 if status == 1 and ( (idabs == 21) or (idabs > 0 and idabs < 7)): # gluons and quarks pt = sqrt(pup[i][0]**2 + pup[i][1]**2) # first entry is px, second py event.lheHT += pt if hasIncomingAsMother: event.lheHTIncoming += pt event.lheNj += 1 if idabs == 5: event.lheNb += 1 if idabs == 4: event.lheNc += 1 if idabs in [1, 2, 3]: event.lheNl += 1 if idabs == 21: event.lheNg += 1 if idabs in [12, 14, 16]: if id > 0: nu = i else: nuBar = i if idabs in [11, 13, 15]: if id > 0: l = i else: lBar = i v = None if l and lBar: #Z to LL v = (l, lBar) elif l and nuBar: #W v = (l, nuBar) elif lBar and nu: #W v = (nu, lBar) elif nu and nuBar: #Z to nn v = (nu, nuBar) if v: event.lheV_pt = sqrt((pup[v[0]][0] + pup[v[1]][0])**2 + (pup[v[0]][1] + pup[v[1]][1])**2) return True
cutFlow = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # loop over events count = 0 print "Start looping" for event in events: count = count + 1 if count % 10000 == 0: print '--------- Processing Event ' + str(count) cutFlow[0] += 1 #Require exactly one lepton (e or mu) lepType = 0 # Let 0 = muon, 1 = electron event.getByLabel(muonPtLabel, muonPtHandle) if not muonPtHandle.isValid(): continue muonPts = muonPtHandle.product() nMuonsVal = 0 for imuonPt in range(0, len(muonPts)): muonPt = muonPts[imuonPt] if muonPt > 45.0: nMuonsVal += 1 lepType = 0 nMuons.Fill(nMuonsVal) if nMuonsVal < 1: continue
mistag = ROOT.TH1F("mistag", "mistag", 400, 0, 2000 ) print "Loop over events - calculate mistag rate" eventCount = 0 for event in events_mistag: eventCount = eventCount +1 x = random.random() #print 'event '+ str(eventCount) + ' x = ' + str(x) #trigger stuff event.getByLabel (myTrigIndexLabel, myTrigIndexHandle) if not myTrigIndexHandle.isValid(): print 'myTrigIndex is invalid' continue myTrigIndices = myTrigIndexHandle.product() event.getByLabel (prescalesLabel, prescalesHandle) if not prescalesHandle.isValid(): print 'prescales is invalid' continue prescales = prescalesHandle.product() event.getByLabel (trigNamesLabel, trigNamesHandle) if not trigNamesHandle.isValid(): print 'trigNames is invalid' continue trigNames = trigNamesHandle.product()
# PileupReweighting if not options.data : event.getByLabel(pileupWeightsLabel, pileupWeightsH) pileupProduct = pileupWeightsH.product() pileupWeight[0] = pileupProduct[0] pileupWeightUp[0] = pileupProduct[1] pileupWeightDown[0] = pileupProduct[2] else: runNumber[0] = event.object().id().run() lumiNumber[0] = event.object().id().luminosityBlock() eventNumber[0] = event.object().id().event() # Get the "product" of the handle (i.e. what it's "pointing to" in C++) if muonsH.isValid(): muons = muonsH.product() if electronsH.isValid(): electrons = electronsH.product() #Require exactly one lepton if muonsH.isValid() and electronsH.isValid(): if len(muons) == 0 and len(electrons) == 0: continue nMuons = 0 if muonsH.isValid(): for imu in muons: if imu.pt() > lepPtMin: nMuons += 1
print '----------------W+Jets event types-----------------' print '---W + 0 Jets: ' + str( count_W_noJets) + ' (%.4f%%)' % (100.0 * count_W_noJets / count) print '---W + b-Jets: ' + str( count_W_bJets) + ' (%.4f%%)' % (100.0 * count_W_bJets / count) print '---W + c-Jets: ' + str( count_W_cJets) + ' (%.4f%%)' % (100.0 * count_W_cJets / count) print '---W + LF-Jets: ' + str( count_W_LFJets) + ' (%.4f%%)' % (100.0 * count_W_LFJets / count) count = count + 1 # print '----------------------------------------------------------------' # print 'NEW EVENT' #open genEvent Information event.getByLabel(GenEventLabel, GenEventHandle) if GenEventHandle.isValid(): GenEvent = GenEventHandle.product() if GenEvent.weight() != 1.0: print 'EVENT WEIGHT = ' + str(GenEvent.weight()) # #find out whether the event was qqbar or not # mother_ids = [] # event.getByLabel( GenLabel, GenHandle ) # lep_charge = 0 # is_qq = False # is_semilep = False # if GenHandle.isValid() : # GenParticles = GenHandle.product() # for ig in GenParticles : # #check if it's a proton # if ig.pdgId() == 2212 :
count += 1 # If using PU reweighting, get the number of simulated pileup interactions if options.puWeighting is not None: weight *= LumiWeights.weight3D( event.object() ) #------------------------------------------ # Now get the event weight. # - Weight by the generator weight (cross section for this event) #------------------------------------------ passGen = False # Get the generator product event.getByLabel( generatorLabel, generatorHandle ) if generatorHandle.isValid() : generatorInfo = generatorHandle.product() # weight is the generator weight if options.usePY8 : weight *= generatorInfo.weight()/pow(generatorInfo.binningValues()[0]/15.,4.5) else : weight *= generatorInfo.weight() passGen = True if options.verbose : print 'event weight = ' + str(weight) # Get mean-pt-per-unit-area
"root://cmseos.fnal.gov//store/user/wsi/MCSIDM/CRAB_PrivateMC/SIDM_BsTo2DpTo2Mu2e_MBs-400_MDp-1p2_ctau-24/181027_064400/0000/GENSIM_1.root" ) print("len(events): ", events.size()) handle = Handle("std::vector<reco::GenParticle>") label = ("genParticles", "", "SIM") for i, event in enumerate(events, 1): if i > 10: break print("---------------------------------") print("## Event ", i) event.getByLabel(label, handle) if not handle.isValid(): continue gen = handle.product() nGen = len(gen) print("Number of gen particles: ", nGen) print( "{:5} {:6} {:>8} {:>8} {:>8} {:^6} {:^8} {:^10} {:<15} {:^30} {:>8} {:>8} {:>8}" .format( "pdgId", "status", "pT", "eta", "phi", "isHP", "mom0.pId",
#################### REPORT PROGRESS #################### if count % options.printEvery == 1: print 'entry #' + str(count) print 'events passed all but btag cuts : ' + str( count_all_cuts_but_btag_cuts) print 'events passed all cuts : ' + str(count_all_cuts) #################### Hard cut off ####################### #Check to make sure the event type is correct original_particles = [] orig_partons = [] lep_ids = [] if options.mc == 'yes': event.getByLabel(GenLabel, GenHandle) if GenHandle.isValid(): GenParticles = GenHandle.product() for ig in GenParticles: if ig.pt() < 0: continue #Look through all the particles for protons; append their first daughters to the list if ig.pdgId() == 2212: original_particles.append(ig.daughter(0).pdgId()) for i in range(ig.numberOfDaughters()): orig_partons.append(ig.daughter(i).pdgId()) #Look through particles for all ts if math.fabs(ig.pdgId()) == 6 and ig.status() == 3: #look through all the daughters for Ws. for i in range(ig.numberOfDaughters()): dau = ig.daughter(i) if math.fabs(dau.pdgId()) == 24:
class tree_maker: def __init__(self, outputname, seed, mistagFileStr, modMassFileStr, triggerFileStr): # load all the event info: self.numbtag = 0 self.name = outputname self.seed = seed self.mistagFileStr = mistagFileStr self.modMassFileStr = modMassFileStr self.triggerFileStr = triggerFileStr #General Quantities #N Primary Vertices self.npvHandle = Handle("unsigned int") self.npvLabel = ("diffmogen", "npv") #MET Pt and Phi - why not eta? self.metPtHandle = Handle("double") self.metPtLabel = ("diffmogen", "metpt") self.metPhiHandle = Handle("double") self.metPhiLabel = ("diffmogen", "metphi") #Pruned Jet Collection #We need this for CSV values and subjet CSV values self.prunedHandle = Handle( "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > > " ) self.prunedLabel = ("diffmoca8pp", "PrunedCA8CORR") #Btagging CSV values self.CSVHandle = Handle("std::vector<double>") self.CSVLabel = ("diffmoca8pp", "PrunedCA8csv") #Subjet btagging CSV values self.subjet1CSVHandle = Handle("std::vector<double>") self.subjet1CSVLabel = ("diffmoca8pp", "PrunedCA8sub0csv") self.subjet2CSVHandle = Handle("std::vector<double>") self.subjet2CSVLabel = ("diffmoca8pp", "PrunedCA8sub1csv") self.subjet3CSVHandle = Handle("std::vector<double>") self.subjet3CSVLabel = ("diffmoca8pp", "PrunedCA8sub2csv") self.subjet4CSVHandle = Handle("std::vector<double>") self.subjet4CSVLabel = ("diffmoca8pp", "PrunedCA8sub3csv") #TopTagged Jet collection #Eventually this is the one we will use most likely self.topTaggedHandle = Handle( "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > > " ) self.topTaggedLabel = ("diffmoca8tt", "TopTaggedPrunedCA8CORR") #Number of Subjets self.NsubjetsHandle = Handle("std::vector<unsigned int>") self.NsubjetsLabel = ("diffmoca8tt", "TopTaggedPrunedCA8nsub") #Min-pairwise Mass self.minMassHandle = Handle("std::vector<double>") self.minMassLabel = ("diffmoca8tt", "TopTaggedPrunedCA8topTagMinMass") #Top Mass self.topTagTopMassHandle = Handle("std::vector<double>") self.topTagTopMassLabel = ("diffmoca8tt", "TopTaggedPrunedCA8topTagTopMass") #Unpruned Jet collection #We need this to get N-subjettiness self.unprunedHandle = Handle( "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > > " ) self.unprunedLabel = ("diffmoca8", "UnprunedCA8CORR") #N-Subjettiness(tau) self.t1Handle = Handle("std::vector<double>") self.t1Label = ("diffmoca8", "UnprunedCA8tau1") self.t2Handle = Handle("std::vector<double>") self.t2Label = ("diffmoca8", "UnprunedCA8tau2") self.t3Handle = Handle("std::vector<double>") self.t3Label = ("diffmoca8", "UnprunedCA8tau3") self.t4Handle = Handle("std::vector<double>") self.t4Label = ("diffmoca8", "UnprunedCA8tau4") #Number of Daughters self.NdaughtersHandle = Handle("std::vector<unsigned int>") self.NdaughtersLabel = ("diffmoca8", "UnprunedCA8nsub") #Trigger self.triggerHandle = Handle("edm::TriggerResults") self.triggerLabel = ("TriggerResults") self.__book__() def __book__(self): if (self.mistagFileStr == ''): self.doMistag = False else: self.mistagFile = ROOT.TFile(self.mistagFileStr + ".root") self.mistagFile.cd() self.mistag = ROOT.TH1F() self.mistag = self.mistagFile.Get( "MISTAG_MPM_REVERSE_SUB_TTBAR").Clone() self.mistag.SetName('mistag') ROOT.SetOwnership(self.mistag, False) self.doMistag = True if (self.modMassFileStr == ''): self.doModMass = False else: self.modMassFile = ROOT.TFile(self.modMassFileStr + ".root") self.modMassFile.cd() self.modMass = ROOT.TH1F() self.modMass = self.modMassFile.Get( "jetMassOneTag_MassWindow").Clone() self.modMass.SetName('modMass') ROOT.SetOwnership(self.modMass, False) self.doModMass = True if (self.triggerFileStr == ''): self.doTrigger = False else: self.triggerFile = ROOT.TFile(self.triggerFileStr + ".root") self.triggerFile.cd() self.trigger = self.triggerFile.Get("TRIGGER_EFF").Clone() self.trigger.SetName('trigger') ROOT.SetOwnership(self.trigger, False) self.doTrigger = True print "Booking Histograms and Trees..." self.f = ROOT.TFile(self.name + ".root", "recreate") self.f.cd() self.treeVars = ROOT.TTree('treeVars', 'treeVars') self.run = array('i', [-1]) self.event = array('l', [-1]) self.lumi = array('i', [-1]) self.npv = array('i', [-1]) self.index = array('i', [-1]) self.trigWt = array('f', [-1.0]) self.MET = array('f', [-1.0]) self.jet1pt = array('f', [-1.0]) self.jet2pt = array('f', [-1.0]) self.jet1eta = array('f', [-10.0]) self.jet2eta = array('f', [-10.0]) self.jet1phi = array('f', [-10.0]) self.jet2phi = array('f', [-10.0]) self.jet1mass = array('f', [-1.0]) self.jet2mass = array('f', [-1.0]) self.jet1topMass = array('f', [-1.0]) self.jet2topMass = array('f', [-1.0]) self.jet1topMassRaw = array('f', [-1.0]) self.jet2topMassRaw = array('f', [-1.0]) self.jet1csv = array('f', [-1.0]) self.jet2csv = array('f', [-1.0]) self.jet1maxSubjetCSV = array('f', [-1.0]) self.jet2maxSubjetCSV = array('f', [-1.0]) self.jet1tau32 = array('f', [-1.0]) self.jet2tau32 = array('f', [-1.0]) self.jet1tau31 = array('f', [-1.0]) self.jet2tau31 = array('f', [-1.0]) self.jet1tau21 = array('f', [-1.0]) self.jet2tau21 = array('f', [-1.0]) self.jet1nSubj = array('i', [-1]) self.jet2nSubj = array('i', [-1]) self.jet1minMass = array('f', [-1.0]) self.jet2minMass = array('f', [-1.0]) self.jet1nDaughters = array('i', [-1]) self.jet2nDaughters = array('i', [-1]) self.deltaY = array('f', [-10.0]) self.deltaPhi = array('f', [-10.0]) self.cutflow = array('f', [-1.0]) self.mistagWt = array('f', [-1.0]) self.mistagWt1B = array('f', [-1.0]) self.mistagWt2B = array('f', [-1.0]) self.htSum = array('f', [-1.0]) self.triggerEff = array('f', [1.0]) self.treeVars.Branch('run', self.run, 'run/I') self.treeVars.Branch('event', self.event, 'event/L') self.treeVars.Branch('lumi', self.lumi, 'lumi/I') self.treeVars.Branch('npv', self.npv, 'npv/I') self.treeVars.Branch('index', self.index, 'index/I') self.treeVars.Branch('trigWt', self.trigWt, 'trigWt/F') self.treeVars.Branch('MET', self.MET, 'MET/F') self.treeVars.Branch('jet1pt', self.jet1pt, 'jet1pt/F') self.treeVars.Branch('jet2pt', self.jet2pt, 'jet2pt/F') self.treeVars.Branch('jet1eta', self.jet1eta, 'jet1eta/F') self.treeVars.Branch('jet2eta', self.jet2eta, 'jet2eta/F') self.treeVars.Branch('jet1phi', self.jet1phi, 'jet1phi/F') self.treeVars.Branch('jet2phi', self.jet2phi, 'jet2phi/F') self.treeVars.Branch('jet1mass', self.jet1mass, 'jet1mass/F') self.treeVars.Branch('jet2mass', self.jet2mass, 'jet2mass/F') self.treeVars.Branch('jet1topMass', self.jet1topMass, 'jet1topMass/F') self.treeVars.Branch('jet2topMass', self.jet2topMass, 'jet2topMass/F') self.treeVars.Branch('jet1topMassRaw', self.jet1topMassRaw, 'jet1topMassRaw/F') self.treeVars.Branch('jet2topMassRaw', self.jet2topMassRaw, 'jet2topMassRaw/F') self.treeVars.Branch('jet1csv', self.jet1csv, 'jet1csv/F') self.treeVars.Branch('jet2csv', self.jet2csv, 'jet2csv/F') self.treeVars.Branch('jet1maxSubjetCSV', self.jet1maxSubjetCSV, 'jet1maxSubjetCSV/F') self.treeVars.Branch('jet2maxSubjetCSV', self.jet2maxSubjetCSV, 'jet2maxSubjetCSV/F') self.treeVars.Branch('jet1tau32', self.jet1tau32, 'jet1tau32/F') self.treeVars.Branch('jet2tau32', self.jet2tau32, 'jet2tau32/F') self.treeVars.Branch('jet1tau31', self.jet1tau31, 'jet1tau31/F') self.treeVars.Branch('jet2tau31', self.jet2tau31, 'jet2tau31/F') self.treeVars.Branch('jet1tau21', self.jet1tau21, 'jet1tau21/F') self.treeVars.Branch('jet2tau21', self.jet2tau21, 'jet2tau21/F') self.treeVars.Branch('jet1nSubj', self.jet1nSubj, 'jet1nSubj/I') self.treeVars.Branch('jet2nSubj', self.jet2nSubj, 'jet2nSubj/I') self.treeVars.Branch('jet1minMass', self.jet1minMass, 'jet1minMass/F') self.treeVars.Branch('jet2minMass', self.jet2minMass, 'jet2minMass/F') self.treeVars.Branch('jet1nDaughters', self.jet1nDaughters, 'jet1nDaughters/I') self.treeVars.Branch('jet2nDaughters', self.jet2nDaughters, 'jet2nDaughters/I') self.treeVars.Branch('deltaY', self.deltaY, 'deltaY/F') self.treeVars.Branch('deltaPhi', self.deltaPhi, 'deltaPhi/F') self.treeVars.Branch('cutflow', self.cutflow, 'cutflow/F') self.treeVars.Branch('mistagWt', self.mistagWt, 'mistagWt/F') self.treeVars.Branch('mistagWt1B', self.mistagWt1B, 'mistagWt1B/F') self.treeVars.Branch('mistagWt2B', self.mistagWt2B, 'mistagWt2B/F') self.treeVars.Branch('htSum', self.htSum, 'htSum/F') self.treeVars.Branch('triggerEff', self.triggerEff, 'triggerEff/F') self.invarmass = array('f', [-1.0]) self.jetangle = array('f', [-10.0]) self.treeVars.Branch('invariant_mass', self.invarmass, 'invarmass/F') self.treeVars.Branch('angle_between_jets', self.jetangle, 'jetangle/F') def analyze(self, event): self.run[0] = event.object().id().run() self.event[0] = event.object().id().event() self.lumi[0] = event.object().id().luminosityBlock() event.getByLabel(self.npvLabel, self.npvHandle) event.getByLabel(self.metPtLabel, self.metPtHandle) event.getByLabel(self.metPhiLabel, self.metPhiHandle) event.getByLabel(self.prunedLabel, self.prunedHandle) event.getByLabel(self.unprunedLabel, self.unprunedHandle) event.getByLabel(self.topTaggedLabel, self.topTaggedHandle) event.getByLabel(self.CSVLabel, self.CSVHandle) event.getByLabel(self.subjet1CSVLabel, self.subjet1CSVHandle) event.getByLabel(self.subjet2CSVLabel, self.subjet2CSVHandle) event.getByLabel(self.subjet3CSVLabel, self.subjet3CSVHandle) event.getByLabel(self.subjet4CSVLabel, self.subjet4CSVHandle) event.getByLabel(self.t1Label, self.t1Handle) event.getByLabel(self.t2Label, self.t2Handle) event.getByLabel(self.t3Label, self.t3Handle) event.getByLabel(self.t4Label, self.t4Handle) event.getByLabel(self.NdaughtersLabel, self.NdaughtersHandle) event.getByLabel(self.NsubjetsLabel, self.NsubjetsHandle) event.getByLabel(self.minMassLabel, self.minMassHandle) event.getByLabel(self.topTagTopMassLabel, self.topTagTopMassHandle) npv = self.npvHandle.product()[0] metPt = self.metPtHandle.product()[0] metPhi = self.metPhiHandle.product()[0] CSVVals = self.CSVHandle.product() subjet1CSV = self.subjet1CSVHandle.product() subjet2CSV = self.subjet2CSVHandle.product() subjet3CSV = self.subjet3CSVHandle.product() subjet4CSV = self.subjet4CSVHandle.product() Tau1 = self.t1Handle.product() Tau2 = self.t2Handle.product() Tau3 = self.t3Handle.product() Tau4 = self.t4Handle.product() nSubjets = self.NsubjetsHandle.product() nDaughters = self.NdaughtersHandle.product() minMass = self.minMassHandle.product() topTagTopMass = self.topTagTopMassHandle.product() jet1topTagged = 0 jet2topTagged = 0 HTsum = 0 if (self.prunedHandle.isValid() and self.unprunedHandle.isValid() and self.topTaggedHandle.isValid()): unpj = self.unprunedHandle.product() pj = self.prunedHandle.product() ttpj = self.topTaggedHandle.product() #Total number of events seen: self.cutflow[0] = 0.0 self.treeVars.Fill() ## approximately 3% of the time we have more pj than unpj. Why? Shouldn't this be impossible? ## The pruning can separate 2 subjets into standalone jets so this makes sense if len(unpj) < len(pj): self.numbtag = self.numbtag + 1 #One jet, including top tagged: if len(pj) < 1 or len(unpj) < 1 or len(ttpj) < 1: self.cutflow[0] = 0.1 self.treeVars.Fill() if len(pj) < 1: self.cutflow[0] = 0.11 self.treeVars.Fill() if len(unpj) < 1: self.cutflow[0] = 0.12 self.treeVars.Fill() if len(ttpj) < 1: self.cutflow[0] = 0.13 self.treeVars.Fill() self.reset() return #Make sure there's at least a top condidiate by checking the pT nTopCand = 0 for i in range(0, len(ttpj)): if (ttpj[i].pt() > 400): nTopCand = nTopCand + 1 HTsum += ttpj[i].pt() if nTopCand < 1: self.reset() return self.htSum[0] = HTsum self.MET[0] = metPt self.npv[0] = npv #Number of events with >=1 i top jet with pt >400 self.cutflow[0] = 1.0 self.treeVars.Fill() #Reorder to make sure the highest pT is first. This is after any JEC. Is this correct? #pt_sorted_jets = ttpj pt_sorted_jets = ReorderByPt(ttpj) #We need these for the substructure ca1 = ROOT.TLorentzVector() #We create the CA jet to match and fill the first jet's parameters ca1.SetPtEtaPhiM(pt_sorted_jets[0].Pt(), pt_sorted_jets[0].Eta(), pt_sorted_jets[0].Phi(), pt_sorted_jets[0].M()) self.jet1pt[0] = ca1.Pt() self.jet1eta[0] = ca1.Eta() self.jet1phi[0] = ca1.Phi() self.jet1mass[0] = ca1.M() #Match unpruned jets with pruned - so we have both subjet btagging and nsubjettiness #This returns the index of the jet in the first collection that matches within dr = 0.4 to the jet of the second argument jet1matchIndex = MatchCol(unpj, ca1) #This is temporary so we get the correct pj index for CSV and subjet CSV jet1matchIndex_pj = MatchCol(pj, ca1) #Again temporary to match toptagged for Nsubjets, minMass, and topMass jet1matchIndex_tt = MatchCol(ttpj, ca1) #Make sure matching is correct for jet1 if jet1matchIndex == -1 or jet1matchIndex_pj == -1 or jet1matchIndex_tt == -1: self.cutflow[0] = 1.1 self.treeVars.Fill() if jet1matchIndex == -1: self.cutflow[0] = 1.11 self.treeVars.Fill() if jet1matchIndex_pj == -1: self.cutflow[0] = 1.12 self.treeVars.Fill() if jet1matchIndex_tt == -1: self.cutflow[0] = 1.13 self.treeVars.Fill() self.reset() return #Make sure the subjets are filled if len(nSubjets) == 0: self.cutflow[0] = 1.2 self.treeVars.Fill() self.reset() return #Top Tagging Parameters jet1minMassVal = minMass[jet1matchIndex_tt] self.jet1nSubj[0] = nSubjets[jet1matchIndex_tt] self.jet1minMass[0] = jet1minMassVal #### This should rightfully be jet1mass and jet2mass #### self.jet1topMass[0] = topTagTopMass[jet1matchIndex_tt] self.jet1topMassRaw[0] = topTagTopMass[jet1matchIndex_tt] #Check if jet 1 is top taggged if self.jet1topMass[0] > 140.0 and self.jet1topMass[ 0] < 250.0 and self.jet1minMass[ 0] > 50.0 and self.jet1nSubj[0] > 2: #First jet is fully Top-Tagged self.cutflow[0] = 2.0 self.treeVars.Fill() jet1topTagged = 1 else: self.cutflow[0] = 1.3 self.treeVars.Fill() # self.reset() #We don't want to return so that we can fill the mistag contribution # return #Do the same as above for a second jet now if len(pj) < 2 or len(unpj) < 2 or len(ttpj) < 2: if jet1topTagged: self.cutflow[0] = 2.1 self.treeVars.Fill() if len(pj) < 2: self.cutflow[0] = 2.11 self.treeVars.Fill() if len(unpj) < 2: self.cutflow[0] = 2.12 self.treeVars.Fill() if len(ttpj) < 2: self.cutflow[0] = 2.13 self.treeVars.Fill() self.cutflow[0] = 2.2 self.treeVars.Fill() self.reset() return #Jet 2 Basic Parameters ca2 = ROOT.TLorentzVector() ca2.SetPtEtaPhiM(pt_sorted_jets[1].Pt(), pt_sorted_jets[1].Eta(), pt_sorted_jets[1].Phi(), pt_sorted_jets[1].M()) self.jet2pt[0] = ca2.Pt() self.jet2eta[0] = ca2.Eta() self.jet2phi[0] = ca2.Phi() self.jet2mass[0] = ca2.M() #Jet 2 Matching jet2matchIndex_tt = MatchCol(ttpj, ca2) jet2matchIndex_pj = MatchCol(pj, ca2) jet2matchIndex = MatchCol(unpj, ca2) #Make sure matching is correct for jet2 if jet2matchIndex == -1 or jet2matchIndex_pj == -1 or jet2matchIndex_tt == -1: if jet1topTagged: self.cutflow[0] = 2.3 self.treeVars.Fill() if jet2matchIndex == -1: self.cutflow[0] = 2.31 self.treeVars.Fill() if jet2matchIndex_pj == -1: self.cutflow[0] = 2.32 self.treeVars.Fill() if jet2matchIndex_tt == -1: self.cutflow[0] = 2.33 self.treeVars.Fill() self.cutflow[0] = 2.4 self.treeVars.Fill() self.reset() return #2nd jet with pT > 400: jet2ptcheck = 0 if self.jet2pt[0] > 400.: jet2ptcheck = 1 if jet1topTagged: self.cutflow[0] = 3.0 self.treeVars.Fill() #Temporary else: self.cutflow[0] = 9.1 self.treeVars.Fill() else: if jet1topTagged: self.cutflow[0] = 2.5 self.treeVars.Fill() #Temporary else: self.cutflow[0] = 9.2 self.treeVars.Fill() # self.reset() # return #Jet 2 top-tagging parameters jet2minMassVal = minMass[jet2matchIndex_tt] self.jet2nSubj[0] = nSubjets[jet2matchIndex_tt] self.jet2minMass[0] = jet2minMassVal self.jet2topMass[0] = topTagTopMass[jet2matchIndex_tt] self.jet2topMassRaw[0] = topTagTopMass[jet2matchIndex_tt] ##################### We don't really need this but here it is ################################### if len(nDaughters) > 0: self.jet1nDaughters[0] = nDaughters[jet1matchIndex] self.jet2nDaughters[0] = nDaughters[jet2matchIndex] #Invarient Mass self.invarmass[0] = (ca1 + ca2).M() #Angular Parameters self.jetangle[0] = ca1.DeltaR(ca2) self.deltaY[0] = (ca1.Rapidity() - ca2.Rapidity()) deltaPhi = ca1.Phi() - ca2.Phi() if deltaPhi > ROOT.TMath.Pi(): deltaPhi = deltaPhi - 2 * ROOT.TMath.Pi() if deltaPhi < -ROOT.TMath.Pi(): deltaPhi = deltaPhi + 2 * ROOT.TMath.Pi() self.deltaPhi[0] = deltaPhi #Nsubjettiness if Tau2[jet1matchIndex] == 0 or Tau2[jet2matchIndex] == 0 or Tau1[ jet1matchIndex] == 0 or Tau1[jet2matchIndex] == 0: if jet1topTagged and jet2ptcheck: self.cutflow[0] == 3.1 self.treeVars.Fill() self.cutflow[0] = 3.2 self.treeVars.Fill() self.reset() return jet1tau32Val = Tau3[jet1matchIndex] / Tau2[jet1matchIndex] jet2tau32Val = Tau3[jet2matchIndex] / Tau2[jet2matchIndex] self.jet1tau32[0] = jet1tau32Val self.jet2tau32[0] = jet2tau32Val jet1tau31Val = Tau3[jet1matchIndex] / Tau1[jet1matchIndex] jet2tau31Val = Tau3[jet2matchIndex] / Tau1[jet2matchIndex] self.jet1tau31[0] = jet1tau31Val self.jet2tau31[0] = jet2tau31Val jet1tau21Val = Tau2[jet1matchIndex] / Tau1[jet1matchIndex] jet2tau21Val = Tau2[jet2matchIndex] / Tau1[jet2matchIndex] self.jet1tau21[0] = jet1tau21Val self.jet2tau21[0] = jet2tau21Val #Fill the btagging information self.jet1csv[0] = CSVVals[jet1matchIndex_pj] self.jet2csv[0] = CSVVals[jet2matchIndex_pj] #Fill the subjet btagging information if jet1matchIndex_pj > len(subjet1CSV) or jet1matchIndex_pj > len( subjet2CSV) or jet1matchIndex_pj > len( subjet3CSV) or jet1matchIndex_pj > len(subjet4CSV): print "Out of range: %i, %i, %i, %i, %i, %i, %i" % ( jet1matchIndex_pj, len(subjet1CSV), len(subjet2CSV), len(subjet3CSV), len(subjet4CSV), len(pt_sorted_jets), len(unpj)) self.reset() return jet1subjetCSVs = [] jet1subjetCSVs.append(subjet1CSV[jet1matchIndex_pj]) jet1subjetCSVs.append(subjet2CSV[jet1matchIndex_pj]) jet1subjetCSVs.append(subjet3CSV[jet1matchIndex_pj]) jet1subjetCSVs.append(subjet4CSV[jet1matchIndex_pj]) if jet2matchIndex_pj > len(subjet1CSV) or jet2matchIndex_pj > len( subjet2CSV) or jet2matchIndex_pj > len( subjet3CSV) or jet2matchIndex_pj > len(subjet4CSV): print "Out of range: %i, %i, %i, %i, %i, %i, %i" % ( jet2matchIndex_pj, len(subjet1CSV), len(subjet2CSV), len(subjet3CSV), len(subjet4CSV), len(pt_sorted_jets), len(unpj)) self.reset() return jet2subjetCSVs = [] jet2subjetCSVs.append(subjet1CSV[jet2matchIndex_pj]) jet2subjetCSVs.append(subjet2CSV[jet2matchIndex_pj]) jet2subjetCSVs.append(subjet3CSV[jet2matchIndex_pj]) jet2subjetCSVs.append(subjet4CSV[jet2matchIndex_pj]) self.jet1maxSubjetCSV[0] = max(jet1subjetCSVs) self.jet2maxSubjetCSV[0] = max(jet2subjetCSVs) #Check if the second jet is top-tagged if self.jet2topMass[0] > 140.0 and self.jet2topMass[ 0] < 250.0 and self.jet2minMass[ 0] > 50.0 and self.jet2nSubj[0] > 2: #Two top-tagged jets with pt>400 if jet1topTagged and jet2ptcheck: jet2topTagged = 1 self.cutflow[0] = 4.0 self.index[0] = 1 self.treeVars.Fill() #Second jet is top tagged, but the first is not elif jet2ptcheck: jet2topTagged = 1 self.cutflow[0] = 3.4 self.treeVars.Fill() #Temporary else: self.cutflow[0] = 10.1 self.treeVars.Fill() else: self.cutflow[0] = 3.3 self.treeVars.Fill() # self.reset() # return #Mistag Contribution if nTopCand < 2: self.reset() return #Temporary self.cutflow[0] = 11 self.treeVars.Fill() temp_x = ROOT.TRandom3(self.seed) x = temp_x.Uniform(1.0) bTag1 = max(jet1subjetCSVs) > 0.679 bTag2 = max(jet2subjetCSVs) > 0.679 bTagLoose1 = max(jet1subjetCSVs) > 0.244 bTagLoose2 = max(jet2subjetCSVs) > 0.244 topTag1WP1 = jet1topTagged and jet1tau32Val < 0.7 and bTagLoose1 topTag2WP1 = jet2topTagged and jet2tau32Val < 0.7 and bTagLoose2 topTag1WP2 = jet1topTagged and jet1tau32Val < 0.6 and bTagLoose1 topTag2WP2 = jet2topTagged and jet2tau32Val < 0.6 and bTagLoose2 topTag1WP3 = jet1topTagged and jet1tau32Val < 0.55 and bTag1 topTag2WP3 = jet2topTagged and jet2tau32Val < 0.55 and bTag2 topTag1WP4 = jet1topTagged and jet1tau32Val < 0.5 and bTag1 and jet1minMassVal > 65 topTag2WP4 = jet2topTagged and jet2tau32Val < 0.5 and bTag2 and jet2minMassVal > 65 topTag1WP5 = jet1topTagged and jet1tau32Val < 0.4 and bTag1 and jet1minMassVal > 55 topTag2WP5 = jet2topTagged and jet2tau32Val < 0.4 and bTag2 and jet2minMassVal > 55 if self.doMistag: mistagBin1 = self.mistag.FindBin(self.jet1pt[0]) mistagBin2 = self.mistag.FindBin(self.jet2pt[0]) # mistag_1B_Bin1 = self.mistag_1B.FindBin(self.jet1pt[0]) # mistag_1B_Bin2 = self.mistag_1B.FindBin(self.jet2pt[0]) # mistag_2B_Bin1 = self.mistag_2B.FindBin(self.jet1pt[0]) # mistag_2B_Bin2 = self.mistag_12.FindBin(self.jet2pt[0]) #Make sure we're not in the overflow and underflow (we should never be under) if self.mistag.IsBinOverflow(mistagBin1): mistagBin1 = self.mistag.GetNbinsX() elif mistagBin1 == 0: mistagBin1 = 1 if self.mistag.IsBinOverflow(mistagBin2): mistagBin2 = self.mistag.GetNbinsX() elif mistagBin2 == 0: mistagBin2 = 1 # if self.mistag_1B.IsBinOverflow(mistag_1B_Bin1): # mistag_1B_Bin1 = self.mistag_1B.GetNbinsX() # elif mistag_1B_Bin1 == 0: # mistag_1B_Bin1 = 1 # if self.mistag_1B.IsBinOverflow(mistag_1B_Bin2): # mistag_1B_Bin2 = self.mistag_1B.GetNbinsX() # elif mistag_1B_Bin2 == 0: # mistag_1B_Bin2 = 1 # if self.mistag_2B.IsBinOverflow(mistag_2B_Bin1): # mistag_2B_Bin1 = self.mistag_2B.GetNbinsX() # elif mistag_2B_Bin1 == 0: # mistag_2B_Bin1 = 1 # if self.mistag_2B.IsBinOverflow(mistag_2B_Bin2): # mistag_2B_Bin2 = self.mistag_2B.GetNbinsX() # elif mistag_2B_Bin2 == 0: # mistag_2B_Bin2 = 1 if self.doTrigger: triggerBin = self.trigger.FindBin(HTsum) if self.trigger.IsBinOverflow(triggerBin): triggerBin = self.trigger.GetNbinsX() elif triggerBin == 0: triggerBin = 1 self.triggerEff = self.trigger.GetBinContent(triggerBin) if x < 0.5: if jet1topTagged: if self.doModMass: self.jet2topMass[0] = self.modMass.GetRandom() if self.doMistag: self.mistagWt[0] = self.mistag.GetBinContent( mistagBin2) else: self.mistagWt[0] = 0 self.mistagWt1B[ 0] = 0 #self.mistag_1B.GetBinContent( mistagBin2 ) self.mistagWt2B[ 0] = 0 #self.mistag_2B.GetBinContent( mistagBin2 ) self.index[0] = 2 self.treeVars.Fill() self.reset() if x >= 0.5: if jet2topTagged: if self.doModMass: self.jet1topMass[0] = self.modMass.GetRandom() if self.doMistag: self.mistagWt[0] = self.mistag.GetBinContent( mistagBin1) else: self.mistagWt[0] = 0 self.mistagWt1B[ 0] = 0 #self.mistag_1B.GetBinContent( mistagBin1 ) self.mistagWt2B[ 0] = 0 #self.mistag_2B.GetBinContent( mistagBin1 ) self.index[0] = 2 self.treeVars.Fill() self.reset() #self.treeVars.Fill() self.reset() return def reset(self): self.run[0] = -1 self.event[0] = -1 self.lumi[0] = -1 self.npv[0] = -1 self.index[0] = -1 self.trigWt[0] = -1.0 self.MET[0] = -1.0 self.jet1pt[0] = -1.0 self.jet2pt[0] = -1.0 self.jet1eta[0] = -10.0 self.jet2eta[0] = -10.0 self.jet1phi[0] = -10.0 self.jet2phi[0] = -10.0 self.jet1mass[0] = -1.0 self.jet2mass[0] = -1.0 self.jet1topMass[0] = -1.0 self.jet2topMass[0] = -1.0 self.jet1topMassRaw[0] = -1.0 self.jet2topMassRaw[0] = -1.0 self.jet1csv[0] = -1.0 self.jet2csv[0] = -1.0 self.jet1maxSubjetCSV[0] = -1.0 self.jet2maxSubjetCSV[0] = -1.0 self.jet1tau32[0] = -1.0 self.jet2tau32[0] = -1.0 self.jet1tau31[0] = -1.0 self.jet2tau31[0] = -1.0 self.jet1tau21[0] = -1.0 self.jet2tau21[0] = -1.0 self.jet1nSubj[0] = -1 self.jet2nSubj[0] = -1 self.jet1minMass[0] = -1.0 self.jet2minMass[0] = -1.0 self.jet1nDaughters[0] = -1 self.jet2nDaughters[0] = -1 self.deltaY[0] = -10.0 self.deltaPhi[0] = -10.0 self.cutflow[0] = -1.0 self.mistagWt[0] = -1.0 self.mistagWt1B[0] = -1.0 self.mistagWt2B[0] = -1.0 self.htSum[0] = -1.0 self.triggerEff[0] = -1.0 self.invarmass[0] = -1.0 self.jetangle[0] = -10.0 def __del__(self): print str(self.numbtag) self.f.cd() self.f.Write() self.f.Close() if self.doMistag: self.mistagFile.Close() if self.doModMass: self.modMassFile.Close() if self.doTrigger: self.triggerFile.Close()
class LHEAnalyzer( Analyzer ): """ """ def __init__(self, cfg_ana, cfg_comp, looperName ): super(LHEAnalyzer,self).__init__(cfg_ana,cfg_comp,looperName) self.lheh=Handle('LHEEventProduct') def declareHandles(self): super(LHEAnalyzer, self).declareHandles() # self.mchandles['lhestuff'] = AutoHandle( 'externalLHEProducer','LHEEventProduct') def beginLoop(self, setup): super(LHEAnalyzer,self).beginLoop(setup) def process(self, event): # if not MC, nothing to do if not self.cfg_comp.isMC: return True event.lheHT=0 event.lheHTIncoming=0 #restrict HT computation to particles that have status<0 mothers event.lheNj=0 event.lheNb=0 event.lheNc=0 event.lheNl=0 event.lheNg=0 event.lheV_pt = 0 try: event.input.getByLabel( 'externalLHEProducer',self.lheh) except : return True if not self.lheh.isValid() : return True self.readCollections( event.input ) hepeup=self.lheh.product().hepeup() pup=hepeup.PUP l=None lBar=None nu=None nuBar=None for i in range(0,len(pup)): id=hepeup.IDUP[i] status = hepeup.ISTUP[i] idabs=abs(id) mothIdx = max(hepeup.MOTHUP[i][0]-1,0) #first and last mother as pair; first entry has index 1 in LHE; incoming particles return motherindex 0 mothIdxTwo = max(hepeup.MOTHUP[i][1]-1,0) mothStatus = hepeup.ISTUP[mothIdx] mothStatusTwo = hepeup.ISTUP[mothIdxTwo] hasIncomingAsMother = mothStatus<0 or mothStatusTwo<0 if status == 1 and ( ( idabs == 21 ) or (idabs > 0 and idabs < 7) ) : # gluons and quarks pt = sqrt( pup[i][0]**2 + pup[i][1]**2 ) # first entry is px, second py event.lheHT += pt if hasIncomingAsMother: event.lheHTIncoming += pt event.lheNj +=1 if idabs==5: event.lheNb += 1 if idabs==4: event.lheNc += 1 if idabs in [1,2,3]: event.lheNl += 1 if idabs==21: event.lheNg += 1 if idabs in [12,14,16] : if id > 0 : nu = i else : nuBar = i if idabs in [11,13,15] : if id > 0 : l = i else : lBar = i v=None if l and lBar : #Z to LL v=(l,lBar) elif l and nuBar : #W v=(l,nuBar) elif lBar and nu : #W v=(nu,lBar) elif nu and nuBar : #Z to nn v=(nu,nuBar) if v : event.lheV_pt = sqrt( (pup[v[0]][0]+pup[v[1]][0])**2 + (pup[v[0]][1]+pup[v[1]][1])**2 ) return True
eleTight_eta.clear() vars.pileUpWeight = 1.0 if (count % 1000) == 0: print count,'run/lumi/event',info.run,info.lumi,info.event tree.AutoSave() count += 1 #get the LHE product info vars.mStop = -1 vars.mLSP = -1 if runOnMC and runSMS: event.getByLabel(('source'),lheH) if lheH.isValid(): lhe = lheH.product() for i in xrange(lhe.comments_size()): comment = lhe.getComment(i) if 'model' not in comment: continue comment = comment.replace('\n','') parameters = comment.split(' ')[2] masses = map(float,parameters.split('_')[-2:]) vars.mStop = masses[0] vars.mLSP = masses[1] if skimEvents and not (vars.mLSP == mLSPskim ) : #TODO: For Moriond, only consider the zero LSP mass strip continue #store how many of each model we see point = (vars.mStop,vars.mLSP)
class LHEAnalyzer(Analyzer): """ """ def __init__(self, cfg_ana, cfg_comp, looperName): super(LHEAnalyzer, self).__init__(cfg_ana, cfg_comp, looperName) self.lheh = Handle('LHEEventProduct') def declareHandles(self): super(LHEAnalyzer, self).declareHandles() # self.mchandles['lhestuff'] = AutoHandle( 'externalLHEProducer','LHEEventProduct') def beginLoop(self, setup): super(LHEAnalyzer, self).beginLoop(setup) def process(self, event): # if not MC, nothing to do if not self.cfg_comp.isMC: return True event.lheHT = 0 event.lheNj = 0 event.lheV_pt = 0 try: event.input.getByLabel('externalLHEProducer', self.lheh) except: return True if not self.lheh.isValid(): return True self.readCollections(event.input) hepeup = self.lheh.product().hepeup() pup = hepeup.PUP l = None lBar = None nu = None nuBar = None for i in xrange(0, len(pup)): id = hepeup.IDUP[i] status = hepeup.ISTUP[i] idabs = abs(id) if status == 1 and ( (idabs == 21) or (idabs > 0 and idabs < 7)): # gluons and quarks event.lheHT += sqrt( pup[i][0]**2 + pup[i][1]**2) # first entry is px, second py event.lheNj += 1 if idabs in [12, 14, 16]: if id > 0: nu = i else: nuBar = i if idabs in [11, 13, 15]: if id > 0: l = i else: lBar = i v = None if l and lBar: #Z to LL v = (l, lBar) elif l and nuBar: #W v = (l, nuBar) elif lBar and nu: #W v = (nu, lBar) elif nu and nuBar: #Z to nn v = (nu, nuBar) if v: event.lheV_pt = sqrt((pup[v[0]][0] + pup[v[1]][0])**2 + (pup[v[0]][1] + pup[v[1]][1])**2) return True
class zbbPlots: ##################### def __init__(self,isMC=False): ######################################### self.root_output_file = ROOT.TFile("zbbPlots.root","RECREATE") self.isMC = isMC self.counterLabels = ('TotalEventCounter','AfterPVFilterCounter', 'AfterNSFilterCounter', 'AfterPATCounter', 'AfterCandidatesCounter', 'AfterJetsCounter') self.muonLabel="patMuonsWithTrigger" self.electronLabel ="patElectronsWithTrigger" self.metLabel="patMETs" self.jetLabel="cleanPatJetsPF" self.zllLabel="zMMCand" self.triggerLabel="patTriggerEvent" def beginJob(self): ######################################### self.root_output_file.cd() # lumi block plots self.h1_eventCounters = ROOT.TH1F("lumicounter","lumicounter",6,-0.5,5.5) for theCounterLabel in self.counterLabels: self.h1_eventCounters.GetXaxis().SetBinLabel(self.counterLabels.index(theCounterLabel)+1,theCounterLabel); # muon plots self.h1_muonPt = ROOT.TH1F("muonPt", "pt", 100, 0.,300.) self.h1_muonEta = ROOT.TH1F("muonEta","eta", 100, -3., 3.) self.h1_muonPhi = ROOT.TH1F("muonPhi","phi", 100, -5., 5.) # trigger plots self.h1_triggerBit = ROOT.TH1F("triggerBits","trigger bits",20,0,20) # create handle outside of loop self.counterHandle = Handle("edm::MergeableCounter") self.muonHandle = Handle("std::vector<pat::Muon>") self.electronHandle = Handle("std::vector<pat::Electron>") self.jetHandle = Handle("std::vector<pat::Jet>") self.metHandle = Handle("std::vector<pat::MET>") self.zllCandidateHandle = Handle("std::vector<reco::CompositeCandidate>") self.triggerEventHandle = Handle("pat::TriggerEvent") def analyzeEvent(self,event): ######################################### # get the muon product try: event.getByLabel (self.muonLabel, self.muonHandle) if self.muonHandle.isValid(): muonsCollection = self.muonHandle.product() for theMuon in muonsCollection : self.h1_muonPt.Fill( theMuon.pt() ) self.h1_muonEta.Fill( theMuon.eta() ) self.h1_muonPhi.Fill( theMuon.phi() ) except: print "Muon not found" # get the electron product try: event.getByLabel (self.electronLabel, self.electronHandle) if self.electronHandle.isValid(): electronsCollection = self.electronHandle.product() except: print "Electron not found" # get the jet product try: event.getByLabel (self.jetLabel, self.jetHandle) if self.jetHandle.isValid(): jetCollection = self.jetHandle.product() except: print "Jet not found" # get the met product try: event.getByLabel (self.metLabel, self.metHandle) if self.metHandle.isValid(): metCollection = self.metHandle.product() except: print "MET not found" # get the zll candidate product try: event.getByLabel (self.zllLabel, self.zllCandidateHandle) if self.zllCandidateHandle.isValid(): zllCandidatesCollection = self.zllCandidateHandle.product() except: print "Zll not found" # get the trigger info product try: event.getByLabel (self.triggerLabel, self.triggerEventHandle) if self.triggerEventHandle.isValid(): triggerEvent = self.triggerEventHandle.product() selTriggers = ehf.selectedTriggers(triggerEvent) for trigger,triggered in enumerate(selTriggers): if triggered : self.h1_triggerBit.Fill(trigger) except: print "Trigger not found" def analyzeLumiBlock(self,lumi_block): ######################################### for theCounterLabel in self.counterLabels: try: lumi_block.getByLabel (theCounterLabel, self.counterHandle) if self.counterHandle.isValid(): self.h1_eventCounters.AddBinContent(self.counterLabels.index(theCounterLabel)+1,self.counterHandle.product().value) except: print "Lumi block not found" def endJob(self): ######################################### self.root_output_file.cd() self.root_output_file.Write() if not self.root_output_file is None: self.root_output_file.Close()
handle = Handle("std::vector<reco::GenParticle>") def recurseDaughters(part): daug = [] for n in range(part.numberOfDaughters()): daug.append(recurseDaughters(part.daughter(n))) if len(daug)==0: return [part.pdgId()] def iterateDaughters(particles): partl = [p for p in particles] daugl = [map(lambda x: partl.index(x), [p.daughter(i) for i in range(p.numberOfDaughters())]) for p in particles] partl = [p.pdgId() for p in particles] return partl, daugl n = 0 trees = [] for event in events: print n event.getByLabel(label, handle) if handle.isValid(): particles = handle.product() trees.append(iterateDaughters(particles)) n += 1 if n==10: break of = open("decay_tree.pickle", "w") cPickle.dump(trees, of) of.close()
count = count + 1 percentDone = float(count) / float(ntotal) * 100.0 ################################################ # Require exactly one lepton (e or mu) # ------------------------------------ # Our ntuples have both muon and electron # events, and hence we must select events # based on one or the other type. # To accomplish this we check the products # for the type we're currently plotting # (Mu or Ele), and check if the product is # present. ################################################ event.getByLabel (muonPtLabel, muonPtHandle) if not muonPtHandle.isValid(): muonPts = None else : muonPts = muonPtHandle.product() event.getByLabel (electronPtLabel, electronPtHandle) if not electronPtHandle.isValid(): electronPts = None else : electronPts = electronPtHandle.product() # If neither muons nor electrons are found, skip if muonPts is None and electronPts is None : continue # If we are looking for muons but none are found, skip if options.lepType == 0 and muonPts is None : continue
if not path: continue event.getByLabel(('razorMJDiHemiHadBox'),hemiHadH) if len(hemiHadH.product()): hemi = hemiHadH.product()[0] vars.Rsq = hemi.Rsq() vars.mR = hemi.mR() vars.hemi1Mass = hemi.leg1().mass() vars.hemi2Mass = hemi.leg2().mass() info.hemisphereBalance = (10*hemi.leg1().numConstituents()) + hemi.leg2().numConstituents() if vars.Rsq < 0.03 or vars.mR < 500: continue event.getByLabel(('razorMJPFJetSel30'),jetSel30H) if not jetSel30H.isValid(): continue jets = jetSel30H.product() info.nJet = len(jets) event.getByLabel(('cmgTriggerObjectSel'),triggerH) hlt = triggerH.product()[0] filters.quadTriggerFilter = hlt.getSelectionRegExp("^HLT_QuadJet[0-9]+.*_v[0-9]+$") filters.sixTriggerFilter = hlt.getSelectionRegExp("^HLT_SixJet[0-9]+.*_v[0-9]+$") filters.eightTriggerFilter = hlt.getSelectionRegExp("^HLT_EightJet[0-9]+.*_v[0-9]+$") filters.l1MultiJetFilter = hlt.getSelectionRegExp("^HLT_L1MultiJet_v[0-9]+$") filters.triggerFilter = filters.quadTriggerFilter or filters.sixTriggerFilter or filters.eightTriggerFilter #if not filters.l1MultiJetFilter: continue for f in filter_tags: event.getByLabel(f,filterH)
count = count + 1 if count % 10000 == 0: print '--------- Processing Event ' + str(count) if options.num != 'all': if not (eventsbegin[ifile - 1] <= count <= eventsend[ifile - 1]): continue #if count > 200000: #break # if mptv % 100 == 0 : # print '--------- mptv fail ' + str(mptv) #Require exactly one lepton (e or mu) lepType = 0 # Let 0 = muon, 1 = electron event.getByLabel(muonPtLabel, muonPtHandle) if not muonPtHandle.isValid(): mptv += 1 continue muonPts = muonPtHandle.product() #if True : # event.getByLabel (muonPfisoLabel, muonPfisoHandle) # if not muonPfisoHandle.isValid(): # continue #muonPfisos = muonPfisoHandle.product() nMuonsVal = 0 for imuonPt in range(0, len(muonPts)): muonPt = muonPts[imuonPt] if muonPt > 45.0: nMuonsVal += 1
if (count % 1000) == 0: print count,'run/lumi/event',info.run,info.lumi,info.event tree.AutoSave() count += 1 event.getByLabel(('TriggerResults','','MJSkim'),pathTriggerH) pathTrigger = pathTriggerH.product() pathTriggerNames = event.object().triggerNames(pathTrigger) filters.hadBoxFilter = pathTrigger.accept(pathTriggerNames.triggerIndex('razorMJSkimSequenceHadPath')) filters.eleBoxFilter = pathTrigger.accept(pathTriggerNames.triggerIndex('razorMJSkimSequenceElePath')) filters.muBoxFilter = pathTrigger.accept(pathTriggerNames.triggerIndex('razorMJSkimSequenceMuPath')) filters.tauBoxFilter = pathTrigger.accept(pathTriggerNames.triggerIndex('razorMJSkimSequenceTauPath')) event.getByLabel(('razorMJDiHemiHadBox'),hemiHadH) if not hemiHadH.isValid(): continue if len(hemiHadH.product()): hemi = hemiHadH.product()[0] vars.Rsq = hemi.Rsq() vars.mR = hemi.mR() vars.hemi1Mass = hemi.leg1().mass() vars.hemi2Mass = hemi.leg2().mass() info.hemisphereBalance = (10*hemi.leg1().numConstituents()) + hemi.leg2().numConstituents() #if vars.Rsq < 0.03 or vars.mR < 500: # continue event.getByLabel(('razorMJPFJetSel30'),jetSel30H) if not jetSel30H.isValid(): continue jets = jetSel30H.product() info.nJet = len(jets)
events = Events(ifile) products = {} for event in events: if options.maxevents > 0 and nevents > options.maxevents: break nevents += 1 nevents_file += 1 if (nevents_file % 1000 == 0): print nevents, ' Completed' event.getByLabel(jetsLabel, jetsHandle) if not jetsHandle.isValid(): continue jets = jetsHandle.product() event.getByLabel(npvLabel, npvHandle) npv[0] = npvHandle.product()[0] puFile = ROOT.TFile.Open( "root://cmseos.fnal.gov//store/user/pilot/VLQAnaMay/puWeights.root", "READ") puFileUp = ROOT.TFile.Open( "root://cmseos.fnal.gov//store/user/pilot/VLQAnaMay/puWeightsUp.root", "READ") puFileDn = ROOT.TFile.Open( "root://cmseos.fnal.gov//store/user/pilot/VLQAnaMay/puWeightsDn.root", "READ")
# isWQQ = True # elif ('c' in extraJets and '~c' not in extraJets) or ('~c' in extraJets and 'c' not in extraJets) : # isWc = True # else : # isWlight = True # # if GenEventHandle.isValid() : # GenEvent = GenEventHandle.product() # if GenEvent.weight() < 0 : # count_negative_weights+=1 # else : # count_positive_weights+=1 #Open genparticles information from the file event.getByLabel( GenLabel, GenHandle ) if GenHandle.isValid() : GenParticles = GenHandle.product() for ig in GenParticles : if ig.pt()<0 :#or ig.status() != 23 :# not in range(20,30) and ig.status() not in range(70,80)) : continue ist = ig.pdgId() == 6 and ig.status() == 3 istbar = ig.pdgId() == -6 and ig.status() == 3 #if not (ist or istbar) : # continue #print out a whole bunch of shit about this event nMothers = ig.numberOfMothers() nDaughters = ig.numberOfDaughters() s = '[ ' for i in range(nMothers) : s = s + getId(ig.mother(i).pdgId()) + '('+str(ig.mother(i).status())+') ' s = s + '] '
def analyze(self, event) : """Analyzes event""" event.getByLabel (self.allTopTagLabel, self.allTopTagHandle) topJets = self.allTopTagHandle.product() self.cutflow.Fill(0.5,1) nTopCand = 0 for i in range(0,len(topJets) ) : if( topJets[i].pt() > 350 ) : nTopCand = nTopCand + 1 if nTopCand < 2 : return #pairMass = 0.0 #ttMass = 0.0 weight = 1.0 if self.useGenWeight : event.getByLabel( self.weightsLabel, self.weightsHandle ) weight = self.weightsHandle.product()[0] if self.triggerWeight != "noWeight" : jetTriggerWeight = 1.0 if topJets[0].pt() < 800: bin0 = self.triggerHist.FindBin(topJets[0].pt()) jetTriggerWeight = self.triggerHist.GetBinContent(bin0) deltaTriggerEff = 0.5*(1.0-jetTriggerWeight) jetTriggerWeightUp = jetTriggerWeight + deltaTriggerEff jetTriggerWeightDown = jetTriggerWeight - deltaTriggerEff jetTriggerWeightUp = min(1.0,jetTriggerWeightUp) jetTriggerWeightDown = max(0.0,jetTriggerWeightDown) if self.triggerWeight == "Nominal" : weight = weight*jetTriggerWeight if self.triggerWeight == "Up" : weight = weight*jetTriggerWeightUp if self.triggerWeight == "Down" : weight = weight*jetTriggerWeightDown #print 'topJets[0].pt() ' + str(topJets[0].pt()) #print 'jetTriggerWeight ' + str(jetTriggerWeight) event.getByLabel (self.allTopTagMinMassLabel, self.allTopTagMinMassHandle) topJetMinMass= self.allTopTagMinMassHandle.product() event.getByLabel (self.allTopTagNSubjetsLabel, self.allTopTagNSubjetsHandle) topJetNSubjets= self.allTopTagNSubjetsHandle.product() event.getByLabel (self.allTopTagTopMassLabel, self.allTopTagTopMassHandle) topJetMass= self.allTopTagTopMassHandle.product() event.getByLabel (self.allTopTagPassLabel, self.allTopTagPassHandle ) topJetPass= self.allTopTagPassHandle.product() event.getByLabel( self.metLabel, self.h_met) mets = self.h_met.product() if self.pdfWeight != "nominal" : iweight = 0.0 event.getByLabel( self.pdfLabel, self.pdfHandle ) pdfs = self.pdfHandle.product() if self.pdfWeight == "up" : for pdf in pdfs[0::2] : iweight = iweight + pdf else : for pdf in pdfs[1::2] : iweight = iweight + pdf iweight = iweight / len(pdfs) * 2.0 weight = iweight ttMass = 0.0 deltaPhi = topJets[0].phi() - topJets[1].phi() if deltaPhi > ROOT.TMath.Pi(): deltaPhi = deltaPhi - 2*ROOT.TMath.Pi() if deltaPhi < -ROOT.TMath.Pi(): deltaPhi = deltaPhi + 2*ROOT.TMath.Pi() #ptCuts = topJets[0].pt() > 450 and topJets[1].pt() > 450 ptCuts = topJets[0].pt() > 350 and topJets[1].pt() > 350 etaCuts = abs(topJets[0].Rapidity()) < 2.4 and abs(topJets[1].Rapidity()) < 2.4 deltaPhiCut = abs(deltaPhi)>2.1 passType11KinCuts = ptCuts and etaCuts and deltaPhiCut if ptCuts: self.cutflow.Fill(1.5,1) if etaCuts: self.cutflow.Fill(2.5,1) if deltaPhiCut: self.cutflow.Fill(3.5,1) topMassCuts = topJetMass[0] > 140 and topJetMass[0] < 250 and topJetMass[1] > 140 and topJetMass[1] < 250 if topMassCuts: self.cutflow.Fill(4.5,1) nSubjetsCuts = topJetNSubjets[0] > 2 and topJetNSubjets[1] > 2 if nSubjetsCuts: self.cutflow.Fill(5.5,1) minMassCuts = topJetMinMass[0] > 50 and topJetMinMass[1] > 50 if minMassCuts: self.cutflow.Fill(6.5,1) if passType11KinCuts : topTag0 = topJetMass[0] > 140 and topJetMass[0] < 250 and topJetMinMass[0] > 50 and topJetNSubjets[0] > 2 topTag1 = topJetMass[1] > 140 and topJetMass[1] < 250 and topJetMinMass[1] > 50 and topJetNSubjets[1] > 2 passType11 = topTag0 and topTag1 ttMass = (topJets[0]+topJets[1]).mass() ht = topJets[0].pt() + topJets[1].pt() myrand = ROOT.gRandom.Uniform(140,250) jet0P4_massFlat = copy.copy(topJets[0]) jet0P4_massFlat.SetM( myrand ) ttMassJet0MassFlat = (topJets[1]+jet0P4_massFlat).mass() myrand2 = ROOT.gRandom.Uniform(140,250) jet1P4_massFlat = copy.copy(topJets[1]) jet1P4_massFlat.SetM( myrand2 ) ttMassJet1MassFlat = (topJets[0]+jet1P4_massFlat).mass() myrand_QCDdist_jet0 = self.modMassHist.GetRandom() jet0P4_modmassQCDdist = copy.copy(topJets[0]) jet0P4_modmassQCDdist.SetM( myrand_QCDdist_jet0 ) ttMassJet0modmassQCDdist = (topJets[1]+jet0P4_modmassQCDdist).mass() myrand_QCDdist_jet1 = self.modMassHist.GetRandom() jet1P4_modmassQCDdist = copy.copy(topJets[1]) jet1P4_modmassQCDdist.SetM( myrand_QCDdist_jet1 ) ttMassJet1modmassQCDdist = (topJets[0]+jet1P4_modmassQCDdist).mass() #ibin0 = self.triggerHist.FindBin(topJets[0].pt()) #jetTriggerWeight = self.triggerHist.GetBinContent(bin0) ttMassMod3Jet0Flat = ttMass ttMassMod3Jet1Flat = ttMass if topJets[0].mass() < 140 or topJets[0].mass() > 250: ttMassMod3Jet0Flat = ttMassJet0MassFlat if topJets[1].mass() < 140 or topJets[1].mass() > 250: ttMassMod3Jet1Flat = ttMassJet1MassFlat ttMassModJet0QCDdist = ttMass ttMassModJet1QCDdist = ttMass if topJets[0].mass() < 140 or topJets[0].mass() > 250: ttMassModJet0QCDdist = ttMassJet0modmassQCDdist if topJets[1].mass() < 140 or topJets[1].mass() > 250: ttMassModJet1QCDdist = ttMassJet1modmassQCDdist self.jetMass.Fill( topJets[0].mass(), weight ) self.jetMass.Fill( topJets[1].mass(), weight ) self.jetPt.Fill( topJets[0].pt(), weight ) self.jetPt.Fill( topJets[1].pt(), weight ) self.jetEta.Fill( topJets[0].eta(), weight ) self.jetEta.Fill( topJets[1].eta(), weight ) self.jetRap.Fill( topJets[0].Rapidity(), weight ) self.jetRap.Fill( topJets[1].Rapidity(), weight ) self.jetMinMass.Fill( topJetMinMass[0], weight ) self.jetMinMass.Fill( topJetMinMass[1], weight ) self.mttCandMass.Fill( ttMass, weight ) if passType11 : self.topTagMass.Fill( topJets[0].mass(), weight ) self.topTagMass.Fill( topJets[1].mass(), weight ) self.topTagPt.Fill( topJets[0].pt(), weight ) self.topTagPt.Fill( topJets[1].pt(), weight ) self.topTagMinMass.Fill( topJetMinMass[0], weight ) self.topTagMinMass.Fill( topJetMinMass[1], weight ) self.mttMass.Fill( ttMass, weight ) self.met.Fill( mets[0].pt(), weight ) self.ht.Fill( ht, weight ) h_mtt = Handle("double") event.getByLabel( ("ttbsmAna", "mttgen"), h_mtt) if h_mtt.isValid(): mtt = h_mtt.product() self.mtt_gen.Fill(mtt[0]) self.mtt_gen_vs_reco.Fill(mtt[0], ttMass) if not self.useMC : self.runPairs.append( [event.object().id().run(), event.object().id().event(), event.object().id().luminosityBlock() , ttMass] ) self.mttMassTriggerWeighted.Fill( ttMass, weight ) #background estiation x = ROOT.gRandom.Uniform() if x < 0.5 : if topTag0 : self.jetPtOneTag.Fill( topJets[1].pt(), weight ) self.jetRapOneTag.Fill( topJets[1].Rapidity(), weight ) self.jetMassOneTag.Fill( topJets[1].mass(), weight ) self.mttPredDist. Accumulate( ttMass, topJets[1].pt(), topTag1, weight ) self.mttPredDistMassCut. Accumulate( ttMass, topJets[1].pt(), topTag1, weight ) self.mttPredDistModMassFlat. Accumulate( ttMassJet1MassFlat, topJets[1].pt(), topTag1, weight ) self.mttPredDistMod3MassFlat. Accumulate( ttMassMod3Jet1Flat, topJets[1].pt(), topTag1, weight ) self.mttPredDistMod3MassFlatSubtract. Accumulate( ttMassMod3Jet1Flat, topJets[1].pt(), topTag1, weight ) self.mttPredDistModMassQCDdistSubtract. Accumulate( ttMassModJet1QCDdist, topJets[1].pt(), topTag1, weight ) self.metPred.Accumulate( mets[0].pt(), topJets[1].pt(), topTag1, weight ) if x >= 0.5 : if topTag1 : self.jetPtOneTag.Fill( topJets[0].pt(), weight ) self.jetRapOneTag.Fill( topJets[0].Rapidity(), weight ) self.jetMassOneTag.Fill( topJets[0].mass(), weight ) self.mttPredDist. Accumulate( ttMass, topJets[0].pt(), topTag0, weight ) self.mttPredDistMassCut. Accumulate( ttMass, topJets[0].pt(), topTag0, weight ) self.mttPredDistModMassFlat. Accumulate( ttMassJet0MassFlat, topJets[0].pt(), topTag0, weight ) self.mttPredDistMod3MassFlat. Accumulate( ttMassMod3Jet0Flat, topJets[0].pt(), topTag0, weight ) self.mttPredDistMod3MassFlatSubtract. Accumulate( ttMassMod3Jet0Flat, topJets[0].pt(), topTag0, weight ) self.mttPredDistModMassQCDdistSubtract. Accumulate( ttMassModJet0QCDdist, topJets[0].pt(), topTag0, weight ) self.metPred.Accumulate( mets[0].pt(), topJets[0].pt(), topTag0, weight )
def analyze(self, event) : """Analyzes event""" #badlistSet = set(self.badlist) self.run[0] = event.object().id().run() self.event[0] = event.object().id().event() self.lumi[0] = event.object().id().luminosityBlock() #thisEvent = '{0}:{1}:{2}'.format(self.run[0], self.lumi[0], self.event[0]) #if thisEvent in badlistSet: # print "Found Bad HCAL Laser Event", thisEvent # return event.getByLabel (self.allTopTagLabel, self.allTopTagHandle) topJets = self.allTopTagHandle.product() event.getByLabel (self.allTopTagCHELabel, self.allTopTagCHEHandle) event.getByLabel (self.allTopTagNELabel, self.allTopTagNEHandle) event.getByLabel (self.allTopTagNumPFLabel, self.allTopTagNumPFHandle) event.getByLabel (self.allTopTagNumCHLabel, self.allTopTagNumCHHandle) event.getByLabel (self.allTopTagNumNELabel, self.allTopTagNumNEHandle) topJetsCHE = self.allTopTagCHEHandle.product() topJetsNE = self.allTopTagNEHandle.product() topJetsNumPF = self.allTopTagNumPFHandle.product() topJetsNumCH = self.allTopTagNumCHHandle.product() topJetsNumNE = self.allTopTagNumNEHandle.product() event.getByLabel (self.allTopTagSubjetsLabel, self.allTopTagSubjetsHandle) event.getByLabel (self.allca8Label, self.allca8Handle) event.getByLabel (self.allNsub1Label, self.allNsub1Handle) event.getByLabel (self.allNsub2Label, self.allNsub2Handle) event.getByLabel (self.allNsub3Label, self.allNsub3Handle) event.getByLabel (self.allNsub4Label, self.allNsub4Handle) event.getByLabel (self.allTopTagBDiscLabel, self.allTopTagBDiscHandle) event.getByLabel (self.allTopTagSubjetBDiscLabel, self.allTopTagSubjetBDiscHandle) event.getByLabel (self.allTopTagSubjetJetIDLabel, self.allTopTagSubjetJetIDHandle) topSubjets = self.allTopTagSubjetsHandle.product() ca8Jets = self.allca8Handle.product() tau1Vals = self.allNsub1Handle.product() tau2Vals = self.allNsub2Handle.product() tau3Vals = self.allNsub3Handle.product() tau4Vals = self.allNsub4Handle.product() topBDisc = self.allTopTagBDiscHandle.product() topSubjetsBDisc = self.allTopTagSubjetBDiscHandle.product() topJetID = self.allTopTagSubjetJetIDHandle.product() event.getByLabel( self.metLabel, self.h_met ) mets = self.h_met.product() self.MET[0] = mets[0].pt() self.cutflow.Fill(0.5,1) upperWindowEdge = 250 HTsum = 0.0 nTopCand = 0 for i in range(0,len(topJets) ) : if( topJets[i].pt() > 400 ) : nTopCand = nTopCand + 1 HTsum += topJets[i].pt() if nTopCand < 2 : return #pairMass = 0.0 #ttMass = 0.0 weight = 1.0 if self.useGenWeight : event.getByLabel( self.weightsLabel, self.weightsHandle ) weight = self.weightsHandle.product()[0] if self.triggerWeight != "noWeight" : jetTriggerWeight = 1.0 jetTriggerWeight1 = 1.0 jetTriggerWeight2 = 0.0 if HTsum < 2000: bin0 = self.triggerHist.FindBin(HTsum) #bin0 = self.triggerHist.FindBin(topJets[0].pt()) jetTriggerWeight1 = self.triggerHist.GetBinContent(bin0) if HTsum < 2000: #bin1 = self.triggerHist.FindBin(topJets[1].pt()) bin1 = self.triggerHist.FindBin(HTsum) #jetTriggerWeight2 = self.triggerHist.GetBinContent(bin1) deltaTriggerEff1 = 0.5*(1.0-jetTriggerWeight1) deltaTriggerEff = 0.5*(1.0-jetTriggerWeight) deltaTriggerEff2 = 0.5*(1.0-jetTriggerWeight2) jetTriggerWeightUp = jetTriggerWeight + deltaTriggerEff jetTriggerWeightDown = jetTriggerWeight - deltaTriggerEff jetTriggerWeightUp = min(1.0,jetTriggerWeightUp) jetTriggerWeightDown = max(0.0,jetTriggerWeightDown) jetTriggerWeightUp1 = jetTriggerWeight1 + deltaTriggerEff1 jetTriggerWeightDown1 = jetTriggerWeight1 - deltaTriggerEff1 jetTriggerWeightUp1 = min(1.0,jetTriggerWeightUp1) jetTriggerWeightDown1 = max(0.0,jetTriggerWeightDown1) jetTriggerWeightUp2 = jetTriggerWeight2 + deltaTriggerEff2 jetTriggerWeightDown2 = jetTriggerWeight2 - deltaTriggerEff2 jetTriggerWeightUp2 = min(1.0,jetTriggerWeightUp2) jetTriggerWeightDown2 = max(0.0,jetTriggerWeightDown2) if self.triggerWeight == "Nominal" : weight = weight*(jetTriggerWeight1) if self.triggerWeight == "Up" : weight = weight*jetTriggerWeightUp1 if self.triggerWeight == "Down" : weight = weight*jetTriggerWeightDown1 #print 'topJets[0].pt() ' + str(topJets[0].pt()) #print 'jetTriggerWeight ' + str(jetTriggerWeight) event.getByLabel (self.allTopTagMinMassLabel, self.allTopTagMinMassHandle) topJetMinMass= self.allTopTagMinMassHandle.product() event.getByLabel (self.allTopTagNSubjetsLabel, self.allTopTagNSubjetsHandle) topJetNSubjets= self.allTopTagNSubjetsHandle.product() event.getByLabel (self.allTopTagTopMassLabel, self.allTopTagTopMassHandle) topJetMass= self.allTopTagTopMassHandle.product() event.getByLabel (self.allTopTagPassLabel, self.allTopTagPassHandle ) topJetPass= self.allTopTagPassHandle.product() if self.pdfWeight != "nominal" : iweight = 0.0 event.getByLabel( self.pdfLabel, self.pdfHandle ) pdfs = self.pdfHandle.product() if self.pdfWeight == "up" : for pdf in pdfs[0::2] : iweight = iweight + pdf*pdf else : for pdf in pdfs[1::2] : iweight = iweight + pdf*pdf iweight = iweight / len(pdfs) * 0.5 weight = sqrt(weight*weight + iweight*iweight) ttMass = 0.0 deltaPhi = topJets[0].phi() - topJets[1].phi() if deltaPhi > ROOT.TMath.Pi(): deltaPhi = deltaPhi - 2*ROOT.TMath.Pi() if deltaPhi < -ROOT.TMath.Pi(): deltaPhi = deltaPhi + 2*ROOT.TMath.Pi() CHE0 = topJetsCHE[0]; CHE1 = topJetsCHE[1]; NE0 = topJetsNE[0]; NE1 = topJetsNE[1]; if NE0 == 0: NE0 = 0.0001 if NE1 == 0: NE1 = 0.0001 #find matching ca8jet to top jet for Nsubjetiness deltaRmin1 = 999. deltaRmin2 = 999. # ca8jet0 = ca8Jets[0] # ca8jet1 = ca8Jets[1] # for ca8jet in ca8Jets: # if (ca8jet.DeltaR(topJets[0]) < deltaRmin1): # ca8jet0 = ca8jet # deltaRmin1 = ca8jet.DeltaR(topJets[0]) # if (ca8jet.DeltaR(topJets[1]) < deltaRmin2): # ca8jet1 = ca8jet # deltaRmin2 = ca8jet.DeltaR(topJets[1]) # # print ca8jet0.pt(), ca8jet1.pt(), topJets[0].pt(), topJets[1].pt() tagJet0Subjets = [] tagJet0BDiscs = [] tagJet1Subjets = [] tagJet1BDiscs = [] i = 0 while i < (topJetNSubjets[0] + topJetNSubjets[1]): if i < topJetNSubjets[0]: tagJet0Subjets.append(topSubjets[i]) tagJet0BDiscs.append(topSubjetsBDisc[i]) elif i < (topJetNSubjets[0] + topJetNSubjets[1]): tagJet1Subjets.append(topSubjets[i]) tagJet1BDiscs.append(topSubjetsBDisc[i]) i += 1 tau32_jet1 = tau3Vals[0] / tau2Vals[0] tau32_jet2 = tau3Vals[1] / tau2Vals[1] bdisc_jet1 = topBDisc[0] bdisc_jet2 = topBDisc[1] maxSubjBDisc0 = max(tagJet0BDiscs) maxSubjBDisc1 = max(tagJet1BDiscs) groomed_jet1 = ROOT.TLorentzVector(0.0,0.0,0.0,0.0) groomed_jet2 = ROOT.TLorentzVector(0.0,0.0,0.0,0.0) for subjet in tagJet0Subjets: groomed_jet1 += ROOT.TLorentzVector(subjet.px(), subjet.py(), subjet.pz(), subjet.energy()) for subjet in tagJet1Subjets: groomed_jet2 += ROOT.TLorentzVector(subjet.px(), subjet.py(), subjet.pz(), subjet.energy()) #ptCuts = topJets[0].pt() > 450 and topJets[1].pt() > 450 ptCuts = topJets[0].pt() > 400 and topJets[1].pt() > 400 etaCuts = abs(topJets[0].Rapidity() - topJets[1].Rapidity()) < 1.0 and abs(topJets[0].Rapidity()) < 2.4 and abs(topJets[1].Rapidity()) < 2.4 and not (abs(topJets[0].eta()) < 1.5 and abs(topJets[0].eta()) > 1.0 and topJetsCHE[0] / NE0 > 2.0) and not (abs(topJets[1].eta()) < 1.5 and abs(topJets[1].eta()) > 1.0 and topJetsCHE[1] / NE1 > 2.0) #etaCuts = abs(topJets[0].Rapidity() - topJets[1].Rapidity()) < 1.0 and abs(topJets[0].Rapidity()) < 2.4 and abs(topJets[1].Rapidity()) < 2.4 and not (abs(topJets[0].eta()) < 1.5 and abs(topJets[0].eta()) > 1.0 and topJetsCHE[0] / NE0 > 2.0) and not (abs(topJets[1].eta()) < 1.5 and abs(topJets[1].eta()) > 1.0 and topJetsCHE[1] / NE1 > 2.0) #etaCuts = abs(topJets[0].Rapidity() - topJets[1].Rapidity()) < 1.0 and abs(topJets[0].Rapidity()) < 2.4 and abs(topJets[1].Rapidity()) < 2.4 #etaCuts = abs(topJets[0].Rapidity()) < 2.4 and abs(topJets[1].Rapidity()) < 2.4 deltaPhiCut = abs(deltaPhi)>2.1 passType11KinCuts = ptCuts #and etaCuts and deltaPhiCut if ptCuts: self.cutflow.Fill(1.5,1) if etaCuts: self.cutflow.Fill(2.5,1) if deltaPhiCut: self.cutflow.Fill(3.5,1) topMassCuts = topJetMass[0] > 140 and topJetMass[0] < 250 and topJetMass[1] > 140 and topJetMass[1] < 250 if topMassCuts: self.cutflow.Fill(4.5,1) nSubjetsCuts = topJetNSubjets[0] > 2 and topJetNSubjets[1] > 2 if nSubjetsCuts: self.cutflow.Fill(5.5,1) minMassCuts = topJetMinMass[0] > 50 and topJetMinMass[1] > 50 if minMassCuts: self.cutflow.Fill(6.5,1) if passType11KinCuts : topTag0 = topJetMass[0] > 140 and topJetMass[0] < upperWindowEdge and topJetMinMass[0] > 50 and topJetNSubjets[0] > 2 topTag1 = topJetMass[1] > 140 and topJetMass[1] < upperWindowEdge and topJetMinMass[1] > 50 and topJetNSubjets[1] > 2 failTopTag0 = topJetMass[0] > 140 and topJetMass[0] < upperWindowEdge and topJetMinMass[0] < 30 failTopTag1 = topJetMass[1] > 140 and topJetMass[1] < upperWindowEdge and topJetMinMass[1] < 30 passType11 = topTag0 and topTag1 ttMass = (topJets[0]+topJets[1]).mass() MWweight1 = self.mistag.GetBinContent(self.mistag.FindBin(topJets[0].pt() ) ) MWweight2 = self.mistag.GetBinContent(self.mistag.FindBin(topJets[1].pt() ) ) myrand = ROOT.gRandom.Uniform(140,250) jet0P4_massFlat = copy.copy(topJets[0]) jet0P4_massFlat.SetM( myrand ) ttMassJet0MassFlat = (topJets[1]+jet0P4_massFlat).mass() myrand2 = ROOT.gRandom.Uniform(140,250) jet1P4_massFlat = copy.copy(topJets[1]) jet1P4_massFlat.SetM( myrand2 ) ttMassJet1MassFlat = (topJets[0]+jet1P4_massFlat).mass() myrand_QCDdist_jet0 = self.modMassHist.GetRandom() jet0P4_modmassQCDdist = copy.copy(topJets[0]) jet0P4_modmassQCDdist.SetM( myrand_QCDdist_jet0 ) ttMassJet0modmassQCDdist = (topJets[1]+jet0P4_modmassQCDdist).mass() myrand_QCDdist_jet1 = self.modMassHist.GetRandom() jet1P4_modmassQCDdist = copy.copy(topJets[1]) jet1P4_modmassQCDdist.SetM( myrand_QCDdist_jet1 ) ttMassJet1modmassQCDdist = (topJets[0]+jet1P4_modmassQCDdist).mass() #ibin0 = self.triggerHist.FindBin(topJets[0].pt()) #jetTriggerWeight = self.triggerHist.GetBinContent(bin0) ttMassMod3Jet0Flat = ttMass ttMassMod3Jet1Flat = ttMass if (topJets[0].mass() < 140 or topJets[0].mass() > 250) and (topJets[1].mass() < 140 or topJets[1].mass() > 250): ttMassMod3Jet0Flat = ttMassJet0MassFlat self.jetMassMW.Fill( myrand, MWweight1*MWweight2) if (topJets[1].mass() < 140 or topJets[1].mass() > 250) and (topJets[0].mass() < 140 or topJets[0].mass() > 250): ttMassMod3Jet1Flat = ttMassJet1MassFlat self.jetMassMW.Fill( myrand2, MWweight2*MWweight1) ttMassModJet0QCDdist = ttMass ttMassModJet1QCDdist = ttMass #if topJets[0].mass() < 140 or topJets[0].mass() > 250: ttMassModJet0QCDdist = ttMassJet0modmassQCDdist #if topJets[1].mass() < 140 or topJets[1].mass() > 250: ttMassModJet1QCDdist = ttMassJet1modmassQCDdist self.jetMass.Fill( topJets[0].mass(), weight ) self.jetMass.Fill( topJets[1].mass(), weight ) self.jetPt.Fill( topJets[0].pt(), weight ) self.jetPt.Fill( topJets[1].pt(), weight ) self.jetEta.Fill( topJets[0].eta(), weight ) self.jetEta.Fill( topJets[1].eta(), weight ) self.jetMinMass.Fill( topJetMinMass[0], weight ) self.jetMinMass.Fill( topJetMinMass[1], weight ) self.mttCandMass.Fill( ttMass, weight ) if passType11 : self.topTagMass.Fill( topJets[0].mass(), weight ) self.topTagMass.Fill( topJets[1].mass(), weight ) self.topTagPt.Fill( topJets[0].pt(), weight ) self.topTagPt.Fill( topJets[1].pt(), weight ) self.topTagMinMass.Fill( topJetMinMass[0], weight ) self.topTagMinMass.Fill( topJetMinMass[1], weight ) self.mttMassT[0] = ttMass self.jet1SubjetMaxBDisc[0] = maxSubjBDisc0 self.jet1BDisc[0] = topBDisc[0] self.jet1MassGroomed[0] = groomed_jet1.M() self.jet1tau32[0] = tau32_jet1 self.jet2SubjetMaxBDisc[0] = maxSubjBDisc1 self.jet2BDisc[0] = topBDisc[1] self.jet2MassGroomed[0] = groomed_jet2.M() self.jet2tau32[0] = tau32_jet2 self.jet1minMass[0] = topJetMinMass[0] self.jet2minMass[0] = topJetMinMass[1] self.jet1Nsubj[0] = topJetNSubjets[0] self.jet2Nsubj[0] = topJetNSubjets[1] self.index[0] = 1 self.jet1PtT[0] = topJets[0].pt() self.jet2PtT[0] = topJets[1].pt() self.jet1Eta[0] = topJets[0].Rapidity() self.jet2Eta[0] = topJets[1].Rapidity() self.jet1Phi[0] = topJets[0].phi() self.jet2Phi[0] = topJets[1].phi() self.sumJetPt[0] = HTsum self.jet1MassT[0] = topJets[0].mass() self.jet2MassT[0] = topJets[1].mass() self.jet1CHE[0] = topJetsCHE[0] self.jet1NE[0] = topJetsNE[0] self.jet1NumPF[0] = topJetsNumPF[0] self.jet1NumCH[0] = topJetsNumCH[0] self.jet1NumNE[0] = topJetsNumNE[0] self.jet2CHE[0] = topJetsCHE[1] self.jet2NE[0] = topJetsNE[1] self.jet2NumPF[0] = topJetsNumPF[1] self.jet2NumCH[0] = topJetsNumCH[1] self.jet2NumNE[0] = topJetsNumNE[1] self.trigWt[0] = weight self.event[0] = event.object().id().event() self.run[0] = event.object().id().run() self.lumi[0] = event.object().id().luminosityBlock() self.treeVars.Fill() self.mttMass.Fill( ttMass, weight ) if not self.useMC : self.runPairs.append( [event.object().id().run(), event.object().id().event(), event.object().id().luminosityBlock() , ttMass] ) self.mttMassTriggerWeighted.Fill( ttMass, weight ) h_mtt = Handle("double") event.getByLabel( ("ttbsmAna", "mttgen"), h_mtt) if h_mtt.isValid(): mtt = h_mtt.product() self.mtt_gen.Fill(mtt[0]) self.mtt_gen_vs_reco.Fill(mtt[0], ttMass) #background estiation x = ROOT.gRandom.Uniform() eventStr = str(event.object().id().run()) + ' ' + str(event.object().id().event()) + '\n' self.textfile.write(eventStr) mistagWt1 = self.mistag.GetBinContent( self.mistag.FindBin(topJets[1].pt()) ) mistagWt0 = self.mistag.GetBinContent( self.mistag.FindBin(topJets[0].pt()) ) if x < 0.5 : if topTag0: self.mistagWt[0] = self.mistag.GetBinContent( self.mistag.FindBin(topJets[1].pt()) ) mistagRateErr = self.mistag.GetBinError(self.mistag.FindBin(topJets[1].pt() )) self.jetPtOneTag.Fill( topJets[1].pt(), weight ) self.jetMassOneTag.Fill( topJets[1].mass(), weight ) self.mttPredDist. Accumulate( ttMass, topJets[1].pt(), topTag1, weight ) self.mttPredDistErr.Fill(ttMass, mistagRateErr) self.ptPredDistErr.Fill(topJets[1].pt(), mistagRateErr) self.mttPredDistMassCut. Accumulate( ttMass, topJets[1].pt(), topTag1, weight ) self.mttPredDistModMassFlat. Accumulate( ttMassJet1MassFlat, topJets[1].pt(), topTag1, weight ) self.mttPredDistMod3MassFlat. Accumulate( ttMassMod3Jet1Flat, topJets[1].pt(), topTag1, weight ) self.mttPredDistMod3MassFlatSubtract. Accumulate( ttMassMod3Jet1Flat, topJets[1].pt(), topTag1, weight ) self.mttPredDistModMassQCDdistSubtract. Accumulate( ttMassModJet1QCDdist, topJets[1].pt(), topTag1, weight ) self.mttMassT[0] = ttMassModJet1QCDdist self.index[0] = 0 self.jet1PtT[0] = topJets[0].pt() self.jet2PtT[0] = topJets[1].pt() self.jet1Eta[0] = topJets[0].Rapidity() self.jet2Eta[0] = topJets[1].Rapidity() self.jet1Phi[0] = topJets[0].phi() self.jet2Phi[0] = topJets[1].phi() self.jet1CHE[0] = topJetsCHE[0] self.jet1NE[0] = topJetsNE[0] self.jet1NumPF[0] = topJetsNumPF[0] self.jet1NumCH[0] = topJetsNumCH[0] self.jet1NumNE[0] = topJetsNumNE[0] self.jet2CHE[0] = topJetsCHE[1] self.jet2NE[0] = topJetsNE[1] self.jet2NumPF[0] = topJetsNumPF[1] self.jet2NumCH[0] = topJetsNumCH[1] self.jet2NumNE[0] = topJetsNumNE[1] self.sumJetPt[0] = HTsum self.jet1MassT[0] = topJets[0].mass() self.jet2MassT[0] = myrand_QCDdist_jet1 self.trigWt[0] = weight self.treeVars.Fill() self.ptPredDist.Accumulate(topJets[1].pt(), topJets[1].pt(), topTag1, weight) if x >= 0.5 : if topTag1: self.mistagWt[0] = self.mistag.GetBinContent( self.mistag.FindBin(topJets[0].pt()) ) mistagRateErr = self.mistag.GetBinError(self.mistag.FindBin(topJets[0].pt()) ) self.jetPtOneTag.Fill( topJets[0].pt(), weight ) self.jetMassOneTag.Fill( topJets[0].mass(), weight ) self.mttPredDist. Accumulate( ttMass, topJets[0].pt(), topTag0, weight ) self.mttPredDistErr.Fill(ttMass, mistagRateErr) self.ptPredDistErr.Fill(topJets[0].pt(), mistagRateErr) self.mttPredDistMassCut. Accumulate( ttMass, topJets[0].pt(), topTag0, weight ) self.mttPredDistModMassFlat. Accumulate( ttMassJet0MassFlat, topJets[0].pt(), topTag0, weight ) self.mttPredDistMod3MassFlat. Accumulate( ttMassMod3Jet0Flat, topJets[0].pt(), topTag0, weight ) self.mttPredDistMod3MassFlatSubtract. Accumulate( ttMassMod3Jet0Flat, topJets[0].pt(), topTag0, weight ) self.mttPredDistModMassQCDdistSubtract. Accumulate( ttMassModJet0QCDdist, topJets[0].pt(), topTag0, weight ) self.ptPredDist.Accumulate(topJets[0].pt(), topJets[0].pt(), topTag0, weight) self.mttMassT[0] = ttMassModJet0QCDdist self.index[0] = 0 self.jet1PtT[0] = topJets[0].pt() self.jet2PtT[0] = topJets[1].pt() self.jet1Eta[0] = topJets[0].Rapidity() self.jet2Eta[0] = topJets[1].Rapidity() self.jet1Phi[0] = topJets[0].phi() self.jet2Phi[0] = topJets[1].phi() self.jet1CHE[0] = topJetsCHE[0] self.jet1NE[0] = topJetsNE[0] self.jet1NumPF[0] = topJetsNumPF[0] self.jet1NumCH[0] = topJetsNumCH[0] self.jet1NumNE[0] = topJetsNumNE[0] self.jet2CHE[0] = topJetsCHE[1] self.jet2NE[0] = topJetsNE[1] self.jet2NumPF[0] = topJetsNumPF[1] self.jet2NumCH[0] = topJetsNumCH[1] self.jet2NumNE[0] = topJetsNumNE[1] self.sumJetPt[0] = HTsum self.jet1MassT[0] = myrand_QCDdist_jet0 self.jet2MassT[0] = topJets[1].mass() self.trigWt[0] = weight self.treeVars.Fill()
# find & count leptons # ------------------------------------------------------------------------------------- nMuons = 0 nElectrons = 0 igoodMu = -1 igoodEle = -1 # ------------------------------------------------------------------------------------- # muon channel # ------------------------------------------------------------------------------------- if options.lepType == "muon": event.getByLabel (muonPtLabel, muonPtHandle) if not muonPtHandle.isValid(): continue muonPts = muonPtHandle.product() event.getByLabel (muonPfisoLabel, muonPfisoHandle) if not muonPfisoHandle.isValid(): continue muonPfisos = muonPfisoHandle.product() event.getByLabel (muonEtaLabel, muonEtaHandle) muonEtas = muonEtaHandle.product() # loop over muons and make selection for imuonPt in range(0,len(muonPts)): muonPt = muonPts[imuonPt] if muonPt > MIN_MU_PT and abs(muonEtas[imuonPt]) < MAX_MU_ETA :
if (count % 1000) == 0: print count, 'run/lumi/event', info.run, info.lumi, info.event count += 1 event.getByLabel(('TriggerResults', '', 'MJSkim'), pathTriggerH) pathTrigger = pathTriggerH.product() #start by vetoing events that didn't pass the offline selection pathTriggerNames = event.object().triggerNames(pathTrigger) path = pathTrigger.wasrun(pathTriggerNames.triggerIndex('multijetPathNoTrigger')) and \ pathTrigger.accept(pathTriggerNames.triggerIndex('multijetPathNoTrigger')) filters.selectionFilter = path if not path: continue event.getByLabel(('razorMJPFJetSel30'), jetSel30H) if not jetSel30H.isValid(): continue jets = jetSel30H.product() info.nJet = len(jets) if info.nJet < 6: continue event.getByLabel(('cmgTriggerObjectSel'), triggerH) hlt = triggerH.product()[0] filters.quadTriggerFilter = hlt.getSelectionRegExp( "^HLT_QuadJet[0-9]+.*_v[0-9]+$") filters.sixTriggerFilter = hlt.getSelectionRegExp( "^HLT_SixJet[0-9]+.*_v[0-9]+$") filters.eightTriggerFilter = hlt.getSelectionRegExp( "^HLT_EightJet[0-9]+.*_v[0-9]+$") filters.l1MultiJetFilter = hlt.getSelectionRegExp( "^HLT_L1MultiJet_v[0-9]+$")
#!/usr/bin/env python from __future__ import print_function import ROOT from DataFormats.FWLite import Events, Handle ROOT.gROOT.SetBatch() events = Events('../cfg/ljGun_AODSIM.root') handle = Handle('std::vector<reco::GenParticle>') label = ('genParticles') for i, event in enumerate(events): print("---------------------------------") print("## Event ", i) event.getByLabel(label, handle) if not handle.isValid(): continue genpar = handle.product() for p in genpar: print(p.pdgId(), end=' ') print()
# ------------------------------------------------------------------------------------- # end truth loop # ------------------------------------------------------------------------------------- ak5GenJets = [] ca8GenJets = [] # ------------------------------------------------------------------------------------- # get AK5 gen jets # ------------------------------------------------------------------------------------- event.getByLabel( ak5GenJetPtLabel, ak5GenJetPtHandle ) if ak5GenJetPtHandle.isValid() == False : continue event.getByLabel( ak5GenJetEtaLabel, ak5GenJetEtaHandle ) event.getByLabel( ak5GenJetPhiLabel, ak5GenJetPhiHandle ) event.getByLabel( ak5GenJetMassLabel, ak5GenJetMassHandle ) ak5GenJetPt = ak5GenJetPtHandle.product() ak5GenJetEta = ak5GenJetEtaHandle.product() ak5GenJetPhi = ak5GenJetPhiHandle.product() ak5GenJetMass = ak5GenJetMassHandle.product() if len(ak5GenJetPt) == 0 : continue # loop over AK5 gen jets for iak5 in xrange( len(ak5GenJetPt) ) :
while dphi > pi: dphi -= 2*pi while dphi < -pi: dphi += 2*pi return dphi def deltaR(eta1,phi1,eta2,phi2): return math.sqrt( (eta1-eta2)**2 + deltaPhi(phi1,phi2)**2) for iev,event in enumerate(events): if verbose: print("\nEvent %d: run %6d, lumi %4d, event %12d" % (iev,event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(),event.eventAuxiliary().event())) event.getByLabel(clusterLabel, clusters) event.getByLabel(genParticlesLabel,genParticles) ## check that handle is valid if not clusters.isValid(): print("Cluster handle is invalid") if not genParticles.isValid(): print("GP handle not valid") ## -- if verbose: print("-> BX=0") if verbose: print("-> clusters=",clusters,"\n","product=",clusters.product()) print("--------------------------------") print("GP SIZE=",genParticles.product().size()) for gp in genParticles.product(): if gp.status() == 1: print("-> Found GP",gp.pt(),gp.eta(),gp.phi(),gp.pdgId()) print("--------------------------------") ## get 0 bunch crossing vector ptsum = [ROOT.TLorentzVector(),ROOT.TLorentzVector() ]
percentDone = float(count) / float(ntotal) * 100.0 #define and initialize Ht Ht = 0.0 ################################################ # Retrieve the jet four-vector # ------------------------------------ # The jet 4-vectors are large and hence # take a long time to read out. If you don't # need the other products (eta,phi,mass of jet) # then don't read them out. ################################################ event.getByLabel(jetPtLabel, jetPtHandle) if not jetPtHandle.isValid(): jetPts = None else: jetPts = jetPtHandle.product() if jetPts is None: continue event.getByLabel(jetEtaLabel, jetEtaHandle) jetEtas = jetEtaHandle.product() event.getByLabel(jetPhiLabel, jetPhiHandle) jetPhis = jetPhiHandle.product() event.getByLabel(jetMassLabel, jetMassHandle) jetMasses = jetMassHandle.product() # Find the njet bin we're in njets = -1
event.getByLabel(MuGlobalTracks_label, MuGlobalTracks_source) if makeitleak: event.getByLabel(eleLooseID_label , eleLooseID_source) event.getByLabel(eleTightID_label , eleTightID_source) event.getByLabel(caloJets_label, caloJets_source) event.getByLabel(calobtag_label, calobtag_source) event.getByLabel(calodeepbtag_label, calodeepbtag_source) event.getByLabel(pfJets_label, pfJets_source) event.getByLabel(pfbtag_label, pfbtag_source) event.getByLabel(pfdeepbtag_label, pfdeepbtag_source) event.getByLabel(offJets_label, offJets_source) event.getByLabel(VerticesOff_label, VerticesOff_source) event.getByLabel(triggerBitLabel, triggerBits) if not onlyGet: bJets = {} if calobtag_source.isValid(): for jet in caloJets_source.product(): calobtags = calobtag_source.product() for ibjet in range(len(calobtags)): jobj = calobtags.key(ibjet).get() #print jobj,jobj.pt(),calobtags.value(ibjet) bJets[ibjet] = (jobj.eta(), jobj.phi(), calobtags.value(ibjet)) print bJets bJets = {} if calodeepbtag_source.isValid(): for jet in caloJets_source.product(): calobtags = calodeepbtag_source.product() for ibjet in range(len(calobtags)): jobj = calobtags.key(ibjet).get() #print jobj,jobj.pt(),calobtags.value(ibjet)
def deltaR(eta1, phi1, eta2, phi2): return math.sqrt((eta1 - eta2)**2 + deltaPhi(phi1, phi2)**2) for iev, event in enumerate(events): if verbose: print("\nEvent %d: run %6d, lumi %4d, event %12d" % (iev, event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(), event.eventAuxiliary().event())) event.getByLabel(clusterLabel, clusters) event.getByLabel(genParticlesLabel, genParticles) ## check that handle is valid if not clusters.isValid(): print("Cluster handle is invalid") if not genParticles.isValid(): print("GP handle not valid") ## -- if verbose: print("-> BX=0") if verbose: print("-> clusters=", clusters, "\n", "product=", clusters.product()) print("--------------------------------") print("GP SIZE=", genParticles.product().size()) for gp in genParticles.product(): if gp.status() == 1: print("-> Found GP", gp.pt(), gp.eta(), gp.phi(), gp.pdgId()) print("--------------------------------") ## get 0 bunch crossing vector
def loopOnEvents(): events= Events(inputfiles) pfCand_h = Handle ("vector<reco::PFCandidate>") pfCand_l = ( "particleFlow","" ) # candidate Chi chicCand_h = Handle ("vector<reco::CompositeCandidate>") chicCand_l = ( "chib","chicCompCand","chibs5" ) #candidate J/Psi jpsiCand_h = Handle ("vector<pat::CompositeCandidate>") #sometimes reco:: oder pat:: jpsiCand_l = ( "chib","jpsiCompCand" ,"chibs5") jpsiCandPAT_h = Handle ("vector<pat::CompositeCandidate>") jpsiCandPAT_l = ( "onia2MuMuPatTrkTrk","" ) #candidate gamma gammaCand_h = Handle ("vector<reco::CompositeCandidate>") gammaCand_l = ( "chib","gammaCompCand" ,"chibs5") convCand_h = Handle ("vector<reco::Conversion>") convCand_l = ( "allConversions","" ) vtxCand_h = Handle('vector<reco::Vertex>') vtxCand_l = ('offlinePrimaryVertices') events= Events(inputfiles) # loop over events nevents = 0 for event in events: if nevents % 100 == 0 : print 'Events Processed ' , nevents #if nevents > 1000: #break #print "run %d \t lumi %d \t orbit %d \t file %s" % (event._event.getRun().run(),event._event.luminosityBlock(), event._event.orbitNumber(),event._event.getTFile().GetName()) nevents += 1 event.getByLabel (pfCand_l,pfCand_h) event.getByLabel (chicCand_l,chicCand_h) event.getByLabel (jpsiCand_l,jpsiCand_h) event.getByLabel (jpsiCandPAT_l,jpsiCandPAT_h) event.getByLabel (gammaCand_l,gammaCand_h) event.getByLabel (convCand_l,convCand_h) event.getByLabel (vtxCand_l,vtxCand_h) if not chicCand_h.isValid() : continue if vtxCand_h.isValid() != True : print "no vertex in the event " continue args={} args['chicColl'] = chicCand_h.product() args['jpsiColl'] = jpsiCand_h.product() args['jpsiCollPAT'] = jpsiCandPAT_h.product() args['gammaColl'] = gammaCand_h.product() args['convColl'] = convCand_h.product() args['vtxColl'] = vtxCand_h.product() args['pfColl'] = pfCand_h.product() args['nevents'] = nevents analyzeEvent(args) print "Number of events: ", nevents print "Number of chib candidates: ", ncands
count = count + 1 if count % 10000 == 0: print "--------- Processing Event " + str(count) if options.num != "all": if not (eventsbegin[ifile - 1] <= count <= eventsend[ifile - 1]): continue # if count > 900000: # break # if mptv % 100 == 0 : # print '--------- mptv fail ' + str(mptv) # Require exactly one lepton (e or mu) lepType = 0 # Let 0 = muon, 1 = electron event.getByLabel(muonPtLabel, muonPtHandle) if not muonPtHandle.isValid(): mptv += 1 continue muonPts = muonPtHandle.product() if True: event.getByLabel(muonPfisoLabel, muonPfisoHandle) if not muonPfisoHandle.isValid(): continue muonPfisos = muonPfisoHandle.product() nMuonsVal = 0 for imuonPt in range(0, len(muonPts)): muonPt = muonPts[imuonPt] if muonPt > 45.0: if options.useLoose:
recoMu_n = list() recoMu_pt = list() recoMu_eta = list() recoMu_dR = list() # deltaR between leading and subleading for i, event in enumerate(events, 1): if i % 1000 == 1: print("ZZ Event : {}".format(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 # Z momCol_ = [g for g in genp if g.isLastCopy() and abs(g.pdgId()) == mompid_] muCol_ = sorted( [g for g in genp if g.isLastCopy() and abs(g.pdgId()) == 13], key=lambda p: p.pt(),
PileUp = puHandle.product() bin1 = PilePlot.FindBin(PileUp[0]) weight *= PilePlot.GetBinContent(bin1) # ------------------------------------------------------------------------------------- # If doing PDF systematatics: # Get the envelopes of the various PDF sets for this event. # Use the max and min values of all of the eigenvectors as the envelope. # ------------------------------------------------------------------------------------- if options.pdfSys != 0.0 or options.pdfSet != 0.0 : if options.pdfSet == 1.0 : event.getByLabel( pdfWeightMSTWLabel, pdfWeightMSTWHandle ) if pdfWeightMSTWHandle.isValid() == False : continue pdfWeight = pdfWeightMSTWHandle.product() elif options.pdfSet == 2.0 : event.getByLabel( pdfWeightNNPDFLabel, pdfWeightNNPDFHandle ) if pdfWeightNNPDFHandle.isValid() == False : continue pdfWeight = pdfWeightNNPDFHandle.product() else : event.getByLabel( pdfWeightCT10Label, pdfWeightCT10Handle ) if pdfWeightCT10Handle.isValid() == False : continue pdfWeight = pdfWeightCT10Handle.product() nMembers = len(pdfWeight)
metHandle = Handle("std::vector<float>") metLabel = ("pfShyftTupleMET" + postfix, "pt") # loop over events count = 0 print "Start looping" for event in events: count = count + 1 if count % 10000 == 0: print "--------- Processing Event " + str(count) # Require exactly one lepton (e or mu) lepType = 0 # Let 0 = muon, 1 = electron event.getByLabel(muonPtLabel, muonPtHandle) if not muonPtHandle.isValid(): continue muonPts = muonPtHandle.product() nMuonsVal = 0 for imuonPt in range(0, len(muonPts)): muonPt = muonPts[imuonPt] if muonPt > 45.0: nMuonsVal += 1 lepType = 0 nMuons.Fill(nMuonsVal) if len(muonPts) < 1: continue
event.getByLabel(('TriggerResults', '', 'MJSkim'), pathTriggerH) pathTrigger = pathTriggerH.product() pathTriggerNames = event.object().triggerNames(pathTrigger) filters.hadBoxFilter = pathTrigger.accept( pathTriggerNames.triggerIndex('razorMJSkimSequenceHadPath')) filters.eleBoxFilter = pathTrigger.accept( pathTriggerNames.triggerIndex('razorMJSkimSequenceElePath')) filters.muBoxFilter = pathTrigger.accept( pathTriggerNames.triggerIndex('razorMJSkimSequenceMuPath')) filters.tauBoxFilter = pathTrigger.accept( pathTriggerNames.triggerIndex('razorMJSkimSequenceTauPath')) event.getByLabel(('razorMJDiHemiHadBox'), hemiHadH) if not hemiHadH.isValid(): continue if len(hemiHadH.product()): hemi = hemiHadH.product()[0] vars.Rsq = hemi.Rsq() vars.mR = hemi.mR() vars.hemi1Mass = hemi.leg1().mass() vars.hemi2Mass = hemi.leg2().mass() info.hemisphereBalance = (10 * hemi.leg1().numConstituents() ) + hemi.leg2().numConstituents() #if vars.Rsq < 0.03 or vars.mR < 500: # continue event.getByLabel(('razorMJPFJetSel30'), jetSel30H) if not jetSel30H.isValid(): continue jets = jetSel30H.product()