本文整理汇总了Python中DataFormats.FWLite.Events.to方法的典型用法代码示例。如果您正苦于以下问题:Python Events.to方法的具体用法?Python Events.to怎么用?Python Events.to使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DataFormats.FWLite.Events
的用法示例。
在下文中一共展示了Events.to方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Events
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
class Events(object):
def __init__(self, files, tree_name):
self.events = FWLiteEvents(files)
def __len__(self):
return self.events.size()
def __getattr__(self, key):
return getattr(self.events, key)
def __getitem__(self, iEv):
self.events.to(iEv)
return self
示例2: Events
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
class Events(object):
def __init__(self, files, tree_name, options=None):
if options is not None :
if not hasattr(options,"inputFiles"):
options.inputFiles=files
if not hasattr(options,"maxEvents"):
options.maxEvents = 0
if not hasattr(options,"secondaryInputFiles"):
options.secondaryInputFiles = []
self.events = FWLiteEvents(options=options)
else :
self.events = FWLiteEvents(files)
def __len__(self):
return self.events.size()
def __getattr__(self, key):
return getattr(self.events, key)
def __getitem__(self, iEv):
self.events.to(iEv)
return self
示例3: Events
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
class Events(object):
def __init__(self, files, tree_name, options=None):
from DataFormats.FWLite import Events as FWLiteEvents
#TODO not sure we still need the stuff below
from ROOT import gROOT, gSystem, AutoLibraryLoader
print "Loading FW Lite"
gSystem.Load("libFWCoreFWLite");
gROOT.ProcessLine('FWLiteEnabler::enable();')
gSystem.Load("libFWCoreFWLite");
gSystem.Load("libDataFormatsPatCandidates");
from ROOT import gInterpreter
gInterpreter.ProcessLine("using namespace reco;")
gInterpreter.ProcessLine("using edm::refhelper::FindUsingAdvance;")
if options is not None :
if not hasattr(options,"inputFiles"):
options.inputFiles=files
if not hasattr(options,"maxEvents"):
options.maxEvents = 0
if not hasattr(options,"secondaryInputFiles"):
options.secondaryInputFiles = []
self.events = FWLiteEvents(options=options)
else :
self.events = FWLiteEvents(files)
def __len__(self):
return self.events.size()
def __getattr__(self, key):
return getattr(self.events, key)
def __getitem__(self, iEv):
self.events.to(iEv)
return self
示例4: loop
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
def loop(fname) :
mus = [Handle("vector<reco::Track> "), "generalTracks"]
eventsRef = Events(fname)
for i in range(0, eventsRef.size()):
a= eventsRef.to(i)
a=eventsRef.getByLabel(mus[1],mus[0])
pmus = []
for mu in mus[0].product() :
if (mu.pt()<5) : continue
if (not mu.innerOk()) : continue
e = 1000*(mu.momentum().r()-mu.outerMomentum().r())
if (e<0) : continue
print e
z = abs(mu.outerPosition().z())
r = mu.outerPosition().rho()
#rhoH.Fill(mu.outerPosition().rho(),e)
zH.Fill(mu.outerPosition().z(),e)
etaH.Fill(mu.outerPosition().eta(),e)
if (z>240) :
xyeH.Fill(mu.outerPosition().x(),mu.outerPosition().y(),e)
xyH.Fill(mu.outerPosition().x(),mu.outerPosition().y(),1)
if (r<120) :phiH.Fill(mu.outerPosition().phi(),e)
rhoH.Fill(r,e)
c1 = TCanvas( 'c1', fname, 200, 10, 1000, 1400 )
gStyle.SetOptStat(111111)
gStyle.SetHistLineWidth(2)
c1.Divide(2,3)
c1.cd(1)
rhoH.Draw()
c1.cd(2)
zH.Draw()
c1.cd(3)
xyH.Draw("COLZ")
c1.cd(4)
xyeH.Divide(xyH)
xyeH.Draw("COLZ")
c1.cd(5)
etaH.Draw()
c1.cd(6)
phiH.Draw()
c1.Print("eloss"+fname+".png")
示例5: __init__
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
class Loop:
'''Manages looping and navigation on a set of events.'''
def __init__(self, name, component, cfg):
'''Build a loop object.
listOfFiles can be "*.root".
name will be used to make the output directory'''
self.name = name
self.cmp = component
self.cfg = cfg
self.events = Events( glob.glob( self.cmp.files) )
self.triggerList = TriggerList( self.cmp.triggers )
if self.cmp.isMC:
self.trigEff = TriggerEfficiency()
self.trigEff.tauEff = None
self.trigEff.lepEff = None
if self.cmp.tauEffWeight is not None:
self.trigEff.tauEff = getattr( self.trigEff,
self.cmp.tauEffWeight )
if self.cmp.muEffWeight is not None:
self.trigEff.lepEff = getattr( self.trigEff,
self.cmp.muEffWeight )
#self.cmp.turnOnCurve = None
#if self.cmp.isMC:
# if self.cmp.tauTriggerTOC is not None:
# self.cmp.turnOnCurve = TurnOnCurve( self.cmp.tauTriggerTOC )
self._MakeOutputDir()
self.counters = Counters()
self.averages = {}
# self.histograms = []
self.InitHandles()
def _MakeOutputDir(self):
index = 0
name = self.name
while True:
try:
# print 'mkdir', self.name
os.mkdir( name )
break
except OSError:
index += 1
name = '%s_%d' % (self.name, index)
self.logger = logging.getLogger(self.name)
self.logger.addHandler(logging.FileHandler('/'.join([self.name,
'log.txt'])))
def LoadCollections(self, event ):
'''Load all collections'''
for str,handle in self.handles.iteritems():
handle.Load( event )
# could do something clever to get the products... a setattr maybe?
def InitHandles(self):
'''Initialize all handles for the products we want to read'''
self.handles = {}
self.handles['cmgTauMuCorFullSelSVFit'] = AutoHandle( 'cmgTauMuCorSVFitFullSel',
'std::vector<cmg::DiObject<cmg::Tau,cmg::Muon>>')
## self.handles['cmgTauMu'] = AutoHandle( 'cmgTauMu',
## 'std::vector<cmg::DiObject<cmg::Tau,cmg::Muon>>')
self.handles['cmgTriggerObjectSel'] = AutoHandle( 'cmgTriggerObjectSel',
'std::vector<cmg::TriggerObject>>')
if self.cmp.isMC and self.cmp.vertexWeight is not None:
self.handles['vertexWeight'] = AutoHandle( self.cmp.vertexWeight,
'double' )
self.handles['vertices'] = AutoHandle( 'offlinePrimaryVertices',
'std::vector<reco::Vertex>' )
self.handles['leptons'] = AutoHandle( 'cmgMuonSel',
'std::vector<cmg::Muon>' )
self.handles['jets'] = AutoHandle( 'cmgPFJetSel',
'std::vector<cmg::PFJet>' )
def InitOutput(self):
'''Initialize histograms physics objects, counters.'''
#COLIN do I really need to declare them?
# declaring physics objects
self.diTau = None
self.triggerObject = None
# declaring counters and averages
self.counters = Counters()
self.counters.addCounter('triggerPassed')
self.counters.addCounter('exactlyOneDiTau')
self.counters.addCounter('singleDiTau')
self.counters.addCounter('VBF')
# self.averages['triggerWeight']=Average('triggerWeight')
self.averages['lepEffWeight']=Average('lepEffWeight')
self.averages['tauEffWeight']=Average('tauEffWeight')
#.........这里部分代码省略.........
示例6: Events
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
#inputFiles = inputFiles[:1] if not small else inputFiles
print "Running over files:",inputFiles
print "plotDir:",options.plotDir
handles={k:Handle(edmCollections[k][0]) for k in edmCollections.keys()}
res={}
events = Events(inputFiles)
events.toBegin()
products={}
size=events.size() #if not small else 2000
missingCollections=[]
for nev in range(size):
if nev%1000==0:print nev,'/',size
events.to(nev)
eaux=events.eventAuxiliary()
run=eaux.run()
if options.run>0 and not run==options.run:
# print run, options.run
continue
for k in [ x for x in edmCollections.keys() if x not in missingCollections]:
try:
events.getByLabel(edmCollections[k][1:],handles[k])
products[k]=handles[k].product()
except:
products[k]=None
print "Not found:",k
missingCollections.append(k)
d={}
示例7: TH1F
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
ptmiss = TH1F("pt miss","pt miss",100,-10.,10.)
ptr = TH1F("pt ratio","pt ratio",100,-10.,10.)
d0all = TH1F("d0 all","d0 all",100,-5.,5.)
d0miss = TH1F("d0 miss","d0 miss",100,-5.,5.)
d0r = TH1F("d0 ratio","d0 ratio",100,-5.,5.)
dpall = TH1F("dp all","dp all",100,-0.5,0.5)
dpmiss = TH1F("dp miss","dp miss",100,-0.5,0.5)
dpr = TH1F("dp ratio","dp ratio",100,-0.5,0.5)
algoall = TH1F("algo all","algo all",20,0,20)
algomiss = TH1F("algo miss","algo miss",20,0,20)
algor = TH1F("algo ratio","algo ratio",20,0,20)
# for event in eventsRef:
for i in range(0, eventsRef.size()):
a= eventsRef.to(i)
a= eventsNew.to(i)
print "Event", i
a=eventsRef.getByLabel(label, tracksRef)
a=eventsNew.getByLabel(label, tracksNew)
trRef = []
j = 0
for track in tracksRef.product():
if (track.found()<8) : continue
if (track.quality(track.qualityByName(quality))) :
dp = track.outerPosition().phi()-track.outerMomentum().phi()
trRef.append((j,track.charge()*track.pt(), track.phi()+track.eta(),track.eta(),track.found(), track.hitPattern(), track.ndof(), track.chi2(), track.dxy(),dp, track.algo() ))
j += 1
a = trRef.sort(key=lambda tr: tr[2])
print j
trNew = []
示例8: EOSEventsWithDownload
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
class EOSEventsWithDownload(object):
def __init__(self, files, tree_name):
query = ["edmFileUtil", "--ls", "-j"]+[("file:"+f if f[0]=="/" else f) for f in files]
retjson = subprocess.check_output(query)
retobj = json.loads(retjson)
self._files = []
self._nevents = 0
for entry in retobj:
self._files.append( (str(entry['file']), self._nevents, self._nevents+entry['events'] ) ) # str() is needed since the output is a unicode string
self._nevents += entry['events']
self._fileindex = -1
self._localCopy = None
self.events = None
## Discover where I am
self.inMeyrin = True
if 'LSB_JOBID' in os.environ and 'HOSTNAME' in os.environ:
hostname = os.environ['HOSTNAME'].replace(".cern.ch","")
try:
wigners = subprocess.check_output(["bmgroup","g_wigner"]).split()
if hostname in wigners:
self.inMeyrin = False
print "Host %s is in bmgroup g_wigner, so I assume I'm in Wigner and not Meyrin" % hostname
except:
pass
## How aggressive should I be?
# 0 = default; 1 = always fetch from Wigner; 2 = always fetch from anywhere if it's a xrootd url
self.aggressive = getattr(self.__class__, 'aggressive', 0)
print "Aggressive prefetching level %d" % self.aggressive
def __len__(self):
return self._nevents
def __getattr__(self, key):
return getattr(self.events, key)
def isLocal(self,filename):
if self.aggressive >= 2: return False
if self.aggressive >= 1 and not self.inMeyrin: return False
fpath = filename.replace("root://eoscms.cern.ch//","/").replace("root://eoscms//","/")
if "?" in fpath: fpath = fpath.split["?"][0]
try:
finfo = subprocess.check_output(["/afs/cern.ch/project/eos/installation/pro/bin/eos.select", "fileinfo", fpath])
replicas = False
nears = False
for line in finfo.split("\n"):
if line.endswith("geotag"):
replicas = True
elif replicas and ".cern.ch" in line:
geotag = int(line.split()[-1])
print "Found a replica with geotag %d" % geotag
if self.inMeyrin:
if geotag > 9000: return False # far replica: bad (EOS sometimes gives the far even if there's a near!)
else: nears = True # we have found a replica that is far away
else:
if geotag < 1000: return False # far replica: bad (EOS sometimes gives the far even if there's a near!)
else: nears = True # we have found a replica that is far away
# if we have found some near replicas, and no far replicas
if nears: return True
except:
pass
# we don't know, so we don't transfer (better slow than messed up)
return True
def __getitem__(self, iEv):
if self._fileindex == -1 or not(self._files[self._fileindex][1] <= iEv and iEv < self._files[self._fileindex][2]):
self.events = None # so it's closed
if self._localCopy:
print "Removing local cache file %s" % self._localCopy
try:
os.remove(self._localCopy)
except:
pass
self._localCopy = None
for i,(fname,first,last) in enumerate(self._files):
if first <= iEv and iEv < last:
print "For event range [ %d, %d ) will use file %r " % (first,last,fname)
self._fileindex = i
if fname.startswith("root://eoscms") or (self.aggressive >= 2 and fname.startswith("root://")):
if not self.isLocal(fname):
tmpdir = os.environ['TMPDIR'] if 'TMPDIR' in os.environ else "/tmp"
rndchars = "".join([hex(ord(i))[2:] for i in os.urandom(8)])
localfile = "%s/%s-%s.root" % (tmpdir, os.path.basename(fname).replace(".root",""), rndchars)
try:
print "Filename %s is remote (geotag >= 9000), will do a copy to local path %s " % (fname,localfile)
start = timeit.default_timer()
subprocess.check_output(["xrdcp","-f","-N",fname,localfile])
print "Time used for transferring the file locally: %s s" % (timeit.default_timer() - start)
self._localCopy = localfile
fname = localfile
except:
print "Could not save file locally, will run from remote"
if os.path.exists(localfile): os.remove(localfile) # delete in case of incomplete transfer
print "Will run from "+fname
self.events = FWLiteEvents([fname])
break
self.events.to(iEv - self._files[self._fileindex][1])
return self
def endLoop(self):
if '_localCopy' not in self.__dict__:
return
todelete = self.__dict__['_localCopy']
if todelete:
print "Removing local cache file ",todelete
os.remove(todelete)
#.........这里部分代码省略.........
示例9: range
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
c.Draw(">>eList", commoncf)
elist = ROOT.gDirectory.Get("eList")
number_events = elist.GetN()
print "Reading: ", sample["name"], bin, "with",number_events,"Events using cut", commoncf
if small:
if number_events>1000:
number_events=1000
for i in range(0, number_events):
if (i%10000 == 0) and i>0 :
print i
# # Update all the Tuples
if elist.GetN()>0 and ntot>0:
c.GetEntry(elist.GetEntry(i))
# MC specific part
if not sample['name'].lower().count('data'):
events.to(elist.GetEntry(i))
events.getByLabel(label,handle)
gps = handle.product()
if storeVectors:
lgp = []
lgp2 = []
igp = 0
for gp in gps:
if gp.status() == 3:
lgp.append(gp)
if (abs(gp.pdgId()==11) or abs(gp.pdgId()==13)) and gp.pt() > 3.:
lgp2.append(gp)
lgp2 = sorted(lgp2, key=lambda k: -k.pt())
s.ngp = min(len(lgp)+len(lgp2),20)
for igp,gp in enumerate(lgp):
s.gpPdg[igp] = gp.pdgId()
示例10: loop
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
def loop(fname) :
genPars = Handle("vector<reco::GenParticle>")
genParsLabel = "prunedGenParticles"
gPar = [Handle("vector<pat::PackedGenParticle>"), "packedGenParticles"]
vertices = [Handle("vector<reco::Vertex>"), "offlineSlimmedPrimaryVertices" ]
mus = [Handle("vector<pat::Muon>"), "slimmedMuons"]
sip2d = TH1F("SIP2D","SIP2D",40,-10.,10.)
sip3d = TH1F("SIP3D","SIP3D",40,-10.,10.)
sipxy = TH1F("tk2d","TK SIPXY",40,-10.,10.)
sipz = TH1F("tk3z","TK SIPZ",40,-10.,10.)
sip3d_l = TH1F("SIP2D l","SIP2D l",40,-10.,10.)
sip3d_h = TH1F("SIP2D h","SIP2D h",40,-10.,10.)
sip3d_best = TH1F("SIP2D best","SIP2D best",40,-10.,10.)
vert = TH1F("zpv","zpv",100,-10.,10.)
sip_v = TProfile("SIP2D vs zpv","SIP2D best vs zpv",50,0.,5.,0.,10.)
#
eventsRef = Events(fname)
nw=0
nehpt=0
nwhpt=0
nech=0
nwch=0
#
for i in range(0, eventsRef.size()):
a= eventsRef.to(i)
print "Event", i
a=eventsRef.getByLabel(genParsLabel, genPars)
zpv=0
gpvp = genPars.product()[0].vertex()
for part in genPars.product():
if (part.vz()!=0) :
zpv = part.vz()
gpvp = part.vertex()
break
print "zpv " , zpv
#
nmu=0
nel=0
nch1=0
nch2=0
gmu = []
for part in genPars.product():
if (part.status()!=1) : continue
if (abs(part.pdgId())==13 and part.pt()>5 and abs(part.eta())<2.4) :
gmu.append((part.phi(),part.eta(), part.charge()*part.pt()))
if (abs(part.pdgId())==13 and part.pt()>5 and abs(part.eta())<2.4) : nmu+=1
if (abs(part.pdgId())==11 and part.pt()>7 and abs(part.eta())<2.4) : nel+=1
if (abs(part.pdgId())==13 and part.pt()>8 and abs(part.eta())<2.4) : nch1+=1
if (abs(part.pdgId())==11 and part.pt()>10 and abs(part.eta())<2.4) : nch1+=1
if (abs(part.pdgId())==13 and part.pt()>20 and abs(part.eta())<2.4) : nch2+=1
if (abs(part.pdgId())==11 and part.pt()>20 and abs(part.eta())<2.4) : nch2+=1
# if (abs(part.pdgId())==13):
# print "part", part.phi(),part.eta(), part.pt(), part.vz(), part.vx(), part.vy(), part.mass(), part.pdgId(), part.status()
# print "nmu ", nmu,nel
# print gmu
a=eventsRef.getByLabel(vertices[1],vertices[0])
minz=99999.
iv=0
ii=0
pv = vertices[0].product()[0]
pvp = vertices[0].product()[0].position()
nv = vertices[0].product().size()
for v in vertices[0].product() :
if (abs(v.z()-zpv) < minz) :
minz=abs(v.z()-zpv)
iv = ii
ii+=1
print "pv ", iv, minz
if (iv!=0) : nw+=1
# if (nmu+nel>3) :
if (nmu>1) :
nehpt+=1
if (iv!=0) : nwhpt+=1
# if (nch1>0 and nch2>0) :
if (nch1<1) : continue
#
nech+=1
if (iv!=0) : nwch+=1
a=eventsRef.getByLabel(mus[1],mus[0])
pmus = []
for mu in mus[0].product() :
if (mu.pt()<5) : continue
# if ( mu.isTrackerMuon() or mu.isGlobalMuon()) :
if ( mu.isGlobalMuon()) :
pmus.append(( mu.phi(), mu.eta(), mu.pt()*mu.charge(), mu.dB(2)/mu.edB(2), mu.dB(1)/mu.edB(1),
mu.track().dxy(gpvp)/mu.track().dxyError(),
mu.track().dz(gpvp)/mu.track().dzError(), mu.track().hitPattern().pixelLayersWithMeasurement() ))
# print 'mu', iv, mu.phi(), mu.eta(), mu.pt(), mu.dB(2)/mu.edB(2), mu.dB(1)/mu.edB(1), mu.isTrackerMuon(), mu.isGlobalMuon()
# print pmus
matches = []
i=0
for g in gmu :
j = 0
#.........这里部分代码省略.........
示例11: Events
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
eventsRef = Events(fname+'.root')
tracksRef = Handle("std::vector<reco::Track>")
label = "generalTracks"
quality = "highPurity"
#quality = "tight"
#quality = "loose"
mvaRef = Handle("std::vector<float>")
mcMatchRef = Handle("std::vector<float>")
for i in range(0, eventsRef.size()):
#for i in range(0, 200):
a= eventsRef.to(i)
print "Event", i
a=eventsRef.getByLabel(label, tracksRef)
a=eventsRef.getByLabel(label, 'MVAValues',mvaRef)
a=eventsRef.getByLabel("trackMCQuality",mcMatchRef)
mcMatch = mcMatchRef.product()
mva = mvaRef.product()
trVal = []
k = -1
for track in tracksRef.product():
k+=1
# if (track.phi()<0) : continue
# if (abs(track.eta())>2.3) : continue
# if (track.pt()<4) : continue
# if (track.quality(track.qualityByName(quality))) :
writer.writerow([i,track.eta(), track.phi(), track.pt(),
示例12: H2TauTauAnalyzer
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
class H2TauTauAnalyzer( Looper ):
def __init__(self, name, component, cfg):
self.name = name
self.cmp = component
self.cfg = cfg
self.events = Events( glob.glob( self.cmp.files) )
self.triggerList = TriggerList( self.cmp.triggers )
#SPEC?
if self.cmp.isMC or self.cmp.isEmbed:
self.trigEff = TriggerEfficiency()
self.trigEff.tauEff = None
self.trigEff.lepEff = None
if self.cmp.tauEffWeight is not None:
self.trigEff.tauEff = getattr( self.trigEff,
self.cmp.tauEffWeight )
if self.cmp.muEffWeight is not None:
self.trigEff.lepEff = getattr( self.trigEff,
self.cmp.muEffWeight )
# here create outputs
self.regions = H2TauTauRegions( self.cfg.cuts )
self.output = H2TauTauOutput( self.name, self.regions )
if self.cmp.name == 'DYJets':
self.outputFakes = H2TauTauOutput( self.name + '_Fakes', self.regions )
self.logger = logging.getLogger(self.name)
self.logger.addHandler(logging.FileHandler('/'.join([self.output.name,
'log.txt'])))
self.counters = Counters()
self.averages = {}
self.InitHandles()
self.InitCounters()
def LoadCollections(self, event ):
'''Load all collections'''
for str,handle in self.handles.iteritems():
handle.Load( event )
# could do something clever to get the products... a setattr maybe?
if self.cmp.isMC:
for str,handle in self.mchandles.iteritems():
handle.Load( event )
if self.cmp.isEmbed:
for str,handle in self.embhandles.iteritems():
handle.Load( event )
def InitHandles(self):
'''Initialize all handles for the products we want to read'''
self.handles = {}
self.mchandles = {}
self.embhandles = {}
self.handles['cmgTriggerObjectSel'] = AutoHandle( 'cmgTriggerObjectSel',
'std::vector<cmg::TriggerObject>>')
if self.cmp.isMC and self.cmp.vertexWeight is not None:
self.handles['vertexWeight'] = AutoHandle( self.cmp.vertexWeight,
'double' )
self.handles['vertices'] = AutoHandle( 'offlinePrimaryVertices',
'std::vector<reco::Vertex>' )
self.handles['jets'] = AutoHandle( 'cmgPFJetSel',
'std::vector<cmg::PFJet>' )
self.mchandles['genParticles'] = AutoHandle( 'genParticlesStatus3',
'std::vector<reco::GenParticle>' )
self.embhandles['generatorWeight'] = AutoHandle( ('generator', 'weight'),
'double')
self.InitSpecificHandles()
def InitCounters(self):
'''Initialize histograms physics objects, counters.'''
# declaring counters and averages
self.counters = Counters()
self.counters.addCounter('triggerPassed')
self.counters.addCounter('exactlyOneDiTau')
self.counters.addCounter('singleDiTau')
self.counters.addCounter('VBF')
# self.averages['triggerWeight']=Average('triggerWeight')
self.averages['lepEffWeight']=Average('lepEffWeight')
self.averages['tauEffWeight']=Average('tauEffWeight')
self.averages['vertexWeight']=Average('vertexWeight')
self.averages['generatorWeight']=Average('generatorWeight')
self.averages['eventWeight']=Average('eventWeight')
def process( self, iEv ):
'''Navigate to a given event and process it.'''
# output event structure
self.event = Event()
# navigating to the correct FWLite event
self.iEvent = iEv
self.events.to(iEv)
self.LoadCollections(self.events)
#.........这里部分代码省略.........
示例13: DiMuAnalyzer
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
class DiMuAnalyzer( Looper ):
def __init__(self, name, component, cfg):
super( DiMuAnalyzer, self).__init__(component.fraction)
self.name = name
self.cmp = component
self.cfg = cfg
self.events = Events( glob.glob( self.cmp.files) )
self.triggerList = TriggerList( self.cmp.triggers )
## if self.cmp.isMC or self.cmp.isEmbed:
## self.trigEff = TriggerEfficiency()
## self.trigEff.tauEff = None
## self.trigEff.lepEff = None
## if self.cmp.tauEffWeight is not None:
## self.trigEff.tauEff = getattr( self.trigEff,
## self.cmp.tauEffWeight )
## if self.cmp.muEffWeight is not None:
## self.trigEff.lepEff = getattr( self.trigEff,
## self.cmp.muEffWeight )
# here create outputs
## self.regions = H2TauTauRegions( self.cfg.cuts )
## self.output = Output( self.name, self.regions )
## if self.cmp.name == 'DYJets':
## self.outputFakes = Output( self.name + '_Fakes', self.regions )
self.output = DiMuOutput( self.name )
self.counters = Counters()
self.averages = {}
self.InitHandles()
self.InitCounters()
self.logger = logging.getLogger(self.name)
self.logger.addHandler(logging.FileHandler('/'.join([self.output.name,
'log.txt'])))
def LoadCollections(self, event ):
'''Load all collections'''
for str,handle in self.handles.iteritems():
handle.Load( event )
# could do something clever to get the products... a setattr maybe?
if self.cmp.isMC:
for str,handle in self.mchandles.iteritems():
handle.Load( event )
if self.cmp.isEmbed:
for str,handle in self.embhandles.iteritems():
handle.Load( event )
def InitHandles(self):
'''Initialize all handles for the products we want to read'''
self.handles = {}
self.mchandles = {}
self.embhandles = {}
self.handles['cmgTriggerObjectSel'] = AutoHandle( 'cmgTriggerObjectSel',
'std::vector<cmg::TriggerObject>>')
if self.cmp.isMC and self.cmp.vertexWeight is not None:
self.handles['vertexWeight'] = AutoHandle( self.cmp.vertexWeight,
'double' )
self.handles['vertices'] = AutoHandle( 'offlinePrimaryVertices',
'std::vector<reco::Vertex>' )
self.handles['jets'] = AutoHandle( 'cmgPFJetSel',
'std::vector<cmg::PFJet>' )
self.mchandles['genParticles'] = AutoHandle( 'genParticlesStatus3',
'std::vector<reco::GenParticle>' )
self.embhandles['generatorWeight'] = AutoHandle( ('generator', 'weight'),
'double')
self.handles['diMu'] = AutoHandle( 'cmgDiMuonSel',
'std::vector<cmg::DiObject<cmg::Muon,cmg::Muon>>')
def InitCounters(self):
'''Initialize histograms physics objects, counters.'''
# declaring counters and averages
self.counters = Counters()
self.counters.addCounter('triggerPassed')
self.counters.addCounter('exactlyOneDiMu')
self.counters.addCounter('singleDiMu')
self.counters.addCounter('VBF')
# self.averages['triggerWeight']=Average('triggerWeight')
## self.averages['lepEffWeight']=Average('lepEffWeight')
## self.averages['tauEffWeight']=Average('tauEffWeight')
self.averages['vertexWeight']=Average('vertexWeight')
## self.averages['generatorWeight']=Average('generatorWeight')
self.averages['eventWeight']=Average('eventWeight')
def process( self, iEv ):
'''Navigate to a given event and process it.'''
cuts = self.cfg.cuts
# output event structure
self.event = Event()
#.........这里部分代码省略.........
示例14: range
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
for event in events:
newIndicies = event.fileIndicies()
if indicies != newIndicies:
print "new file"
indicies = newIndicies
event.getByLabel ('Thing', thingHandle)
thing = thingHandle.product()
for loop in range (thing.size()):
print thing.at (loop).a
events.toBegin()
for event in events:
pass
events.toBegin()
for event in events:
event.getByLabel ('Thing', thingHandle)
thing = thingHandle.product()
for loop in range (thing.size()):
print thing.at (loop).a
for i in xrange(events.size()):
if not events.to(i):
print "failed to go to index ",i
exit(1)
print "Python test succeeded!"
示例15: Events
# 需要导入模块: from DataFormats.FWLite import Events [as 别名]
# 或者: from DataFormats.FWLite.Events import to [as 别名]
import ROOT
from DataFormats.FWLite import Events, Handle
from PhysicsTools.PythonAnalysis import *
events_new = Events(['step3_newCalib.root'])
events_old = Events(['step3_RAW2DIGI_RECO.root'])
edmCollections = [ {'name':'pfMet', 'label':("pfMet"), 'edmType':"vector<reco::PFMET>"} ]
handles={v['name']:Handle(v['edmType']) for v in edmCollections}
for i in range(10):
events_new.to(i)
products_new = {}
for v in edmCollections:
events_new.getByLabel(v['label'],handles[v['name']])
products_new[v['name']] =handles[v['name']].product()
events_old.to(i)
products_old = {}
for v in edmCollections:
events_old.getByLabel(v['label'],handles[v['name']])
products_old[v['name']] =handles[v['name']].product()
print "new",products_new['pfMet'][0].pt(), 'old', products_old['pfMet'][0].pt()