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 loopDatasets(dataS,silent=False): plts = {} for l,j in dataS.iteritems(): if not silent: print "dataSet job ",l crabJ = json.load(open(j["crabJson"])) plts[l] = {'plots':{},'additive':[]}; if crabJ.has_key('sample') and crabJ['sample'].has_key('xSec'): plts[l]['color'] = crabJ['sample']['color'] plts[l]['label'] = crabJ['sample']['label'] plts[l]['xSec'] = crabJ['sample']['xSec'];plts[l]['additive'].append('xSec') plts[l]['inputEvents'] = j['EventsRead'];plts[l]['additive'].append('inputEvents') if not silent: print "adding additional information ","color ",crabJ['sample']['color']," label ",crabJ['sample']['label']," xSec ",crabJ['sample']['xSec']," inputEvts ",j['EventsRead'] if j['EventsRead'] != int(j['dasNeventsInput']): print "warning ",l," input events differ ",j['EventsRead']," ",j['dasNeventsInput'] if j.has_key('crabIntLumi'): plts[l]['intLumi'] = j['crabIntLumi']; plts[l]['additive'].append('intLumi') mergedFile = str(crabJ['mergedFilename']) if not silent: print "mergedFile: ",mergedFile events = Events(mergedFile) if not silent: print "events ",events.size() dists = fillDistributions(events,l) dists.loop() plts[l]['plots'].update(copy.deepcopy(dists.plots)) return plts
def setUp(self): self.exEvents = Events([options.expectedPath]) self.acEvents = Events([options.actualPath]) self.exHandleGenMETs = Handle("std::vector<reco::GenMET>") self.exHandlePFMETs = Handle("std::vector<reco::PFMET>") self.exHandleCaloMETs = Handle("std::vector<reco::CaloMET>") self.exHandleMETs = Handle("std::vector<reco::MET>") self.exHandlePFClusterMETs = Handle("std::vector<reco::PFClusterMET>") self.acHandleGenMETs = Handle("std::vector<reco::GenMET>") self.acHandlePFMETs = Handle("std::vector<reco::PFMET>") self.acHandleCaloMETs = Handle("std::vector<reco::CaloMET>") self.acHandleMETs = Handle("std::vector<reco::MET>") self.acHandlePFClusterMETs = Handle("std::vector<reco::PFClusterMET>") self.nameChangeMap = { "caloType1CorrectedMet" : "caloMetT1", "caloType1p2CorrectedMet" : "caloMetT1T2", "pfType0CorrectedMet" : "pfMetT0rt", "pfType0p1CorrectedMet" : "pfMetT0rtT1", "pfType0p1p2CorrectedMet" : "pfMetT0rtT1T2", "pfType0p2CorrectedMet" : "pfMetT0rtT2", "pfType0pfcCorrectedMet" : "pfMetT0pc", "pfType0pfcp1CorrectedMet" : "pfMetT0pcT1", "pfType1CorrectedMet" : "pfMetT1", "pfType1p2CorrectedMet" : "pfMetT1T2", }
def event_iterator(filename, handles=None): """handles is a list of tuples: (varname, type, InputTag)""" events = Events(filename) if not handles: handles = [] for evt in events.__iter__(): for name,typ,inputtag in handles: handle = Handle(typ) evt.getByLabel(inputtag, handle) setattr(evt, "hndl_" + name, handle) yield evt
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 getEventsLumisInFile(infile): from DataFormats.FWLite import Lumis, Handle, Events events = Events(infile) lumis = Lumis(infile) ret = {} for lum in lumis: run = lum.aux().run() if not ret.has_key(run): ret[run] = [] ret[run] += [lum.aux().id().luminosityBlock()] return events.size(), ret
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
def __init__(self, inputFiles = '', **kwargs): """Initialize the AnalysisEvent like a standard Event, plus additional features.""" # initialization of base functionalities Events.__init__(self,inputFiles,**kwargs) # additional features: # 1. instrumentation for event weight self._weightCache = {} self._weightEngines = {} # 2. a list of event products used in the analysis self._collections = {} # 3. a list of "producers" of analysis high-level quantities self._producers = {} # 4. volatile dictionary. User can add any quantity to the event and it will be # properly erased in the iteration step. self.__dict__["vardict"] = {}
def setUp(self): self.exEvents = Events([options.expectedPath]) self.acEvents = Events([options.actualPath]) self.exHandleCorrMETData = Handle("CorrMETData") self.acHandleCorrMETData = Handle("CorrMETData") self.nameChangeMap = { "pfJetMETcorr" : "corrPfMetType1", "pfMETcorrType0" : "corrPfMetType0PfCand", "caloJetMETcorr" : "corrCaloMetType1", "pfCandMETcorr" : "pfCandMETcorr", "pfchsMETcorr" : "pfchsMETcorr", "muonCaloMETcorr" : "muonCaloMETcorr", }
def setUp(self): self.exEvents = Events([options.expectedPath]) self.acEvents = Events([options.actualPath]) self.exHandleGenMETs = Handle("std::vector<reco::GenMET>") self.exHandlePFMETs = Handle("std::vector<reco::PFMET>") self.exHandleCaloMETs = Handle("std::vector<reco::CaloMET>") self.exHandleMETs = Handle("std::vector<reco::MET>") self.exHandlePFClusterMETs = Handle("std::vector<reco::PFClusterMET>") self.acHandleGenMETs = Handle("std::vector<reco::GenMET>") self.acHandlePFMETs = Handle("std::vector<reco::PFMET>") self.acHandleCaloMETs = Handle("std::vector<reco::CaloMET>") self.acHandleMETs = Handle("std::vector<reco::MET>") self.acHandlePFClusterMETs = Handle("std::vector<reco::PFClusterMET>")
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
class EventLooper(object): def __init__(self,sequence,inputPath=None): self.sequence = sequence if inputPath: if type(inputPath) != list: self.inputPath = [ inputPath ] else: inputPath = [] self.inputPath = inputPath def loadEvents(self,nEvents = -1): self.events = Events( self.inputPath ) def loop(self,nEvents = -1): self.loadEvents(nEvents) print "Total Number of events to be run: %s"%self.events.size() for ana in self.sequence: ana.beginJob() for i,event in enumerate(self.events): if (i+1) % 10000 == 0: print "Processed events: %s"%i if (i > nEvents) and (nEvents != -1): break for ana in self.sequence: if not ana.applySelection(event): continue ana.analyze(event) for ana in self.sequence: ana.endJob()
def __init__(self , files , basic_histos , track_histos , vertex_histos , sorting_histos , index , onlineTauCollections = ['onlTausPixVtx2'] , keepAllTaus = False ) : self.events = Events ( files ) self.declareHandles() self.breakLoop = False self.keepAllTaus = keepAllTaus self.allEvents = 0 self.failinRecoHLT = 0 self.failinDMHLT = 0 self.failinIsoHLT = 0 self.hasNoOnlineTrk = 0 self.hasRegionJet = 0 self.hasRegionTrk = 0 self.hasRegion = 0 self.basic_histos = basic_histos self.track_histos = track_histos self.vertex_histos = vertex_histos self.sorting_histos = sorting_histos self.index = index self.onlineTauCollections = onlineTauCollections
def __init__( self, name, cfg_comp, sequence, nEvents=None, firstEvent=0, nPrint=0): '''Handles the processing of an event sample. An Analyzer is built for each Config.Analyzer present in sequence. The Looper can now be used to process an event, or a collection of events in the sample. name : name of the Looper, will be used as the output directory name cfg_comp: information for the input sample, see Config sequence: an ordered list of Config.Analyzer nPrint : number of events to print at the beginning ''' self.name = self._prepareOutput(name) self.outDir = self.name self.logger = logging.getLogger( self.name ) self.logger.addHandler(logging.FileHandler('/'.join([self.name, 'log.txt']))) self.logger.addHandler( logging.StreamHandler(sys.stdout) ) self.cfg_comp = cfg_comp self.classes = {} #TODO: should be a diclist? self.analyzers = map( self._buildAnalyzer, sequence ) self.nEvents = nEvents self.firstEvent = firstEvent self.nPrint = int(nPrint) # initialize FWLite chain on input file: # import pdb ; pdb.set_trace() try: self.events = Events( self.cfg_comp.files ) except RuntimeError: #import pdb ; pdb.set_trace() print 'cannot find any file matching pattern', self.cfg_comp.files raise
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 __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 open(self, filename=None): """ Open edm file and show first event """ self._filename=filename self._branches=[] if os.path.splitext(filename)[1].lower()==".txt": file = open(filename) for line in file.readlines(): if "\"" in line: linecontent=[l.strip(" \n").rstrip(".") for l in line.split("\"")] self._branches+=[(linecontent[0]+"_"+linecontent[1]+"_"+linecontent[3]+"_"+linecontent[5],None,linecontent[1],linecontent[3],linecontent[5])] else: linecontent=line.strip("\n").split(" ")[0].split("_") if len(linecontent)>3: self._branches+=[(linecontent[0]+"_"+linecontent[1]+"_"+linecontent[2]+"_"+linecontent[3],None,linecontent[1],linecontent[2],linecontent[3])] elif os.path.splitext(filename)[1].lower()==".root": from DataFormats.FWLite import Events, Handle self._events = Events(self._filename) self._numEvents=self._events.size() branches=self._events.object().getBranchDescriptions() for branch in branches: try: branchname=branch.friendlyClassName()+"_"+branch.moduleLabel()+"_"+branch.productInstanceName()+"_"+branch.processName() handle=Handle(branch.fullClassName()) self._branches+=[(branchname,handle,branch.moduleLabel(),branch.productInstanceName(),branch.processName())] except Exception as e: logging.warning("Cannot read branch "+branchname+":"+str(e)) self._branches.sort(lambda x, y: cmp(x[0], y[0])) self._filteredBranches=self._branches[:] return self.goto(1)
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")
def processSample(self, sample, maxEv=-1): print 'Processing Files' print sample.files events = Events(sample.files) print "%s events available for processing" % events.size() ts = time.time() for N, event in enumerate(events): if maxEv >= 0 and (N + 1) >= maxEv: break if N % 1000000 == 0: t2 = time.time() print "%s events processed in %s seconds" % (N + 1, t2 - ts) weight = 1 box = EventBox() self.readCollections(event, box) if not self.analyze(box): continue self.addEvent(box) self.fillHistos(box, sample.type, weight) tf = time.time() print "%s events processed in %s seconds" % (N + 1, tf - ts)
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
def __init__(self, filename, **optional): if not os.path.exists(filename): sys.exit("** file not found: %s" % filename) # cache input variables self.filename = filename # create options by scanning file print "reading file %s ..." % filename os.system("edmDumpEventContent %s >& .dumpevent" % filename) records = open(".dumpevent").readlines() for ii, record in enumerate(records): if record[:4] != "----": continue records = records[ii+1:] break objects = {} for ii, record in enumerate(records): record = simplify.sub(">", strip(record)) t = split(record) s = extract.findall(record) if len(s) > 0: name = s[0] else: name = t[0] objects[name] = (t[0], dequote.sub("",t[1]), dequote.sub("",t[2])) # create event buffer, get event iterator, # and create handles self.events = Events(filename) self.iter = self.events.__iter__() self.event = self.iter.next() self.numberOfEvents = self.event.size() print "\n Number of events: %d" % self.numberOfEvents self.handles= {} print " %-20s %s" % ("Key", "Type") print "-"*78 keys = objects.keys() keys.sort() for key in keys: edmtype, label1, label2 = objects[key] h = Handle(edmtype) self.handles[key] = h print " %-20s %s" % (key, edmtype) self.entry = 0 self.buffer = {} self.objects = objects self.keys = keys
def plotMuQuantities_pat(patTuple_list, label, handle, plottingVariables): # Book histograms particleHistorgrams = [] for plottingVar in plottingVariables: histo = makeHistogram(plottingVar.title, plottingVar.binning, plottingVar.quantity) particleHistorgrams.append(histo) for patTuple in patTuple_list: f_patTree = ROOT.TFile.Open(patTuple) events = Events(f_patTree) events.toBegin() # loop over events for event in events: # use getByLabel, just like in cmsRun event.getByLabel(label, handle) # get the product muons = handle.product() # use muons to make J/Psi peak numMuons = len(muons) if numMuons != 2: print "Number of muons: " + str(numMuons) for mu in xrange(numMuons - 1): muon = muons[mu] for plottingVar, hist in izip(plottingVariables, particleHistorgrams): if plottingVar.quantity == "eta": hist.Fill(muon.eta()) elif plottingVar.quantity == "phi": hist.Fill(muon.phi()) elif plottingVar.quantity == "pt": hist.Fill(muon.pt()) elif plottingVar.quantity == "ch": hist.Fill(muon.ch()) return particleHistorgrams
class Events(object): def __init__(self, dataset): self._edmEvents = EDMEvents(dataset.files) self.iEvent = -1 self.nEvents = self._edmEvents.size() def __iter__(self): it = iter(self._edmEvents) while True: try: self.edm_event = next(it) self.iEvent = self.edm_event._eventCounts self.nEvents = self.edm_event.size() yield self except StopIteration: break
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 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.logger = logging.getLogger(self.name) self.logger.addHandler(logging.FileHandler('/'.join([self.name, 'log.txt']))) self.counters = Counters() self.averages = {} # self.histograms = [] self.InitHandles() self.InitCounters()
def sdms_fwlite(argv): ## _____________ __.____ .__ __ _________ __ _____ _____ ## \_ _____/ \ / \ | |__|/ |_ ____ / _____// |_ __ ___/ ____\/ ____\ ## | __) \ \/\/ / | | \ __\/ __ \ \_____ \\ __\ | \ __\\ __\ ## | \ \ /| |___| || | \ ___/ / \| | | | /| | | | ## \___ / \__/\ / |_______ \__||__| \___ > /_______ /|__| |____/ |__| |__| ## \/ \/ \/ \/ \/ options = getUserOptions(argv) ROOT.gROOT.Macro("rootlogon.C") #print argv #print options #jets, jetLabel = Handle("std::vector<pat::Jet>"), "slimmedJets" muons, muonLabel = Handle("std::vector<pat::Muon>"), "slimmedMuons" #electrons, electronLabel = Handle("std::vector<pat::Electron>"), "slimmedElectrons" #packedgens, packedgenLabel = Handle("std::vector<reco::packedGenParticle>"), "PACKEDgENpARTICLES" #packedgens, packedgenLabel = Handle("std::vector<pat::PackedGenParticle>"), "packedGenParticles" #genInfo, genInfoLabel = Handle("GenEventInfoProduct"), "generator" #mets, metLabel = Handle("std::vector<pat::MET>"), "slimmedMETs" f = ROOT.TFile(options.output, "RECREATE") f.cd() outtree = ROOT.TTree("T", "Our tree of everything") def bookFloatBranch(name, default): tmp = array('f', [default]) outtree.Branch(name, tmp, '%s/F' % name) return tmp def bookIntBranch(name, default): tmp = array('i', [default]) outtree.Branch(name, tmp, '%s/I' % name) return tmp def bookLongIntBranch(name, default): tmp = array('l', [default]) outtree.Branch(name, tmp, '%s/L' % name) return tmp # Muons # https://twiki.cern.ch/twiki/bin/viewauth/CMS/SWGuideCMSDataAnalysisSchoolLPC2018Muons # https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideMuonIdRun2 nmuon = array('i', [-1]) outtree.Branch('nmuon', nmuon, 'nmuon/I') muonpt = array('f', 16 * [-1.]) outtree.Branch('muonpt', muonpt, 'muonpt[nmuon]/F') muoneta = array('f', 16 * [-1.]) outtree.Branch('muoneta', muoneta, 'muoneta[nmuon]/F') muonphi = array('f', 16 * [-1.]) outtree.Branch('muonphi', muonphi, 'muonphi[nmuon]/F') muonq = array('f', 16 * [-1.]) outtree.Branch('muonq', muonq, 'muonq[nmuon]/F') muonpx = array('f', 16 * [-1.]) outtree.Branch('muonpx', muonpx, 'muonpx[nmuon]/F') muonpy = array('f', 16 * [-1.]) outtree.Branch('muonpy', muonpy, 'muonpy[nmuon]/F') muonpz = array('f', 16 * [-1.]) outtree.Branch('muonpz', muonpz, 'muonpz[nmuon]/F') muone = array('f', 16 * [-1.]) outtree.Branch('muone', muone, 'muone[nmuon]/F') muonsumchhadpt = array('f', 16 * [-1.]) outtree.Branch('muonsumchhadpt', muonsumchhadpt, 'muonsumchhadpt[nmuon]/F') muonsumnhadpt = array('f', 16 * [-1.]) outtree.Branch('muonsumnhadpt', muonsumnhadpt, 'muonsumnhadpt[nmuon]/F') muonsumphotEt = array('f', 16 * [-1.]) outtree.Branch('muonsumphotEt', muonsumphotEt, 'muonsumphotEt[nmuon]/F') muonsumPUPt = array('f', 16 * [-1.]) outtree.Branch('muonsumPUPt', muonsumPUPt, 'muonsumPUPt[nmuon]/F') muonisLoose = array('i', 16 * [-1]) outtree.Branch('muonisLoose', muonisLoose, 'muonisLoose[nmuon]/I') muonisMedium = array('i', 16 * [-1]) outtree.Branch('muonisMedium', muonisMedium, 'muonisMedium[nmuon]/I') muonPFiso = array('f', 16 * [-1.]) outtree.Branch('muonPFiso', muonPFiso, 'muonPFiso[nmuon]/F') ################################################################################# ## ___________ __ .____ ## \_ _____/__ __ ____ _____/ |_ | | ____ ____ ______ ## | __)_\ \/ // __ \ / \ __\ | | / _ \ / _ \\____ \ ## | \\ /\ ___/| | \ | | |__( <_> | <_> ) |_> > ## /_______ / \_/ \___ >___| /__| |_______ \____/ \____/| __/ ## \/ \/ \/ \/ |__| # IMPORTANT : Run one FWLite instance per file. Otherwise, # FWLite aggregates ALL of the information immediately, which # can take a long time to parse. ################################################################################# def processEvent(iev, event): runnumber = event.eventAuxiliary().run() if options.verbose: print "\nProcessing %d: run %6d, lumi %4d, event %12d" % \ (iev,event.eventAuxiliary().run(), \ event.eventAuxiliary().luminosityBlock(), \ event.eventAuxiliary().event()) ########### MUONS ################## event.getByLabel(muonLabel, muons) nmuons2write = 0 if len(muons.product()) > 0: for i, muon in enumerate(muons.product()): #if muon.pt() > options.minMuonPt and abs(muon.eta()) < options.maxMuonEta and muon.isMediumMuon(): if 1: muonpt[i] = muon.pt() muoneta[i] = muon.eta() muonphi[i] = muon.phi() muone[i] = muon.energy() muonq[i] = muon.charge() muonpx[i] = muon.px() muonpy[i] = muon.py() muonpz[i] = muon.pz() #pfi = muon.pfIsolationR03() pfi = muon.pfIsolationR04() #print( pfi.sumChargedHadronPt, pfi.sumChargedParticlePt, pfi.sumNeutralHadronEt, pfi.sumPhotonEt, pfi.sumNeutralHadronEtHighThreshold, pfi.sumPhotonEtHighThreshold, pfi.sumPUPt) muonsumchhadpt[i] = pfi.sumChargedHadronPt muonsumnhadpt[i] = pfi.sumNeutralHadronEt muonsumphotEt[i] = pfi.sumPhotonEt muonsumPUPt[i] = pfi.sumPUPt muonisLoose[i] = int(muon.isLooseMuon()) muonisMedium[i] = int(muon.isMediumMuon()) #(mu->pfIsolationR04().sumChargedHadronPt + max(0., mu->pfIsolationR04().sumNeutralHadronEt + mu->pfIsolationR04().sumPhotonEt - 0.5*mu->pfIsolationR04().sumPUPt))/mu->pt() muonPFiso[i] = (muonsumchhadpt[i] + max( 0., muonsumnhadpt[i] + muonsumphotEt[i] - 0.5 * muonsumPUPt[i])) / muonpt[i] nmuons2write += 1 nmuon[0] = nmuons2write print("--------") for i in range(0, nmuon[0] - 1): for j in range(i + 1, nmuon[0]): #dpt = np.fabs(muonpt[i]/muone[i] - muonpt[j]/muone[j]) dpt = np.fabs(muone[i] - muone[j]) / muone[i] sumdx = np.fabs(muonpx[i] / muone[i] + muonpx[j] / muone[j]) sumdy = np.fabs(muonpy[i] / muone[i] + muonpy[j] / muone[j]) sumdz = np.fabs(muonpz[i] / muone[i] + muonpz[j] / muone[j]) if dpt < 0.1 and sumdx < .10 and sumdy < .10 and sumdz < .10: #print(muonpt[i] , muonpt[j], muonpx[i] , muonpx[j], muonpy[i] , muonpy[j], muonpz[i] , muonpz[j]) print(muoneta[i], muoneta[j]) print(muone[i], muone[j], muonpx[i], muonpx[j], muonpy[i], muonpy[j], muonpz[i], muonpz[j]) #print(muonpt[i]/muone[i] , muonpt[j]/muone[j], muonpx[i]/muone[i] , muonpx[j]/muone[j], muonpy[i]/muone[i] , muonpy[j]/muone[j], muonpz[i]/muone[i] , muonpz[j]/muone[j]) ## ___________.__.__ .__ ___________ ## \_ _____/|__| | | | \__ ___/______ ____ ____ ## | __) | | | | | | | \_ __ \_/ __ \_/ __ \ ## | \ | | |_| |__ | | | | \/\ ___/\ ___/ ## \___ / |__|____/____/ |____| |__| \___ >\___ > ## \/ \/ \/ outtree.Fill() return 1 ######################################### # Main event loop #genoutputfile = open("generator_information.dat",'w') nevents = 0 maxevents = int(options.maxevents) for ifile in getInputFiles(options): print('Processing file ' + ifile) events = Events(ifile) if maxevents > 0 and nevents > maxevents: break # loop over events in this file for iev, event in enumerate(events): if maxevents > 0 and nevents > maxevents: break nevents += 1 #if nevents % 1000 == 0: if nevents % 100 == 0: print('===============================================') print(' ---> Event ' + str(nevents)) elif options.verbose: print(' ---> Event ' + str(nevents)) returnVal = processEvent(iev, events) # Close the output ROOT file f.cd() f.Write() f.Close()
import ROOT import sys from DataFormats.FWLite import Events, Handle events = Events([ 'root://cms-xrd-global.cern.ch//store/mc/RunIISummer16MiniAODv3/WJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/PUMoriond17_94X_mcRun2_asymptotic_v3_ext2-v1/30000/B8C1F9F9-871F-E911-BC4D-0CC47AC52AFC.root' ]) mets, metLabel = Handle("std::vector<pat::MET>"), "slimmedMETs" puppimets, puppimetLabel = Handle("std::vector<pat::MET>"), "slimmedMETsPuppi" for event in events: if event.eventAuxiliary().event() != 1183564: continue if event.eventAuxiliary().luminosityBlock() != 2595: continue print "run %6d, lumi %4d, event %12d" % ( event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(), event.eventAuxiliary().event()) event.getByLabel(metLabel, mets) event.getByLabel(puppimetLabel, puppimets) met = mets.product().front() print "met.pt() = " + str(met.pt()) print "met.px() = " + str(met.px()) print "met.py() = " + str(met.py()) print "met.uncorPt() = " + str(met.uncorPt())
info['qual3'].Fill(0) info['dxy3'].Fill(0) info['ptSTA3'].Fill(0) ############################## BUNCHES=[0] events=Events([tag+'.root']) counter=-1 for event in events: counter=counter+1 #fetch stubs stubs=fetchStubsOLD(event,True) unpacker=fetchKMTF(event,100.0,'bmtfDigis:kBMTF') emulator=fetchKMTF(event,100.0,'simKBmtfDigis:BMTF') for processor in range(0,12): for bx in BUNCHES: emu=filter(lambda x: x.processor()==processor,emulator[bx]) data=filter(lambda x: x.processor()==processor,unpacker[bx]) if (len(emu)+len(data))>0:
# # Original Author:Julie Hogan (FNAL) # edite by: Jhovanny Andres Mejia Guisao # from DataFormats.FWLite import Handle, Events import ROOT events = Events( 'root://cms-xrd-global.cern.ch//store/data/Run2017B/Charmonium/MINIAOD/PromptReco-v1/000/297/046/00000/88DF6C6A-4556-E711-A5C0-02163E01A630.root' ) tracks = Handle("std::vector<pat::PackedCandidate>") histogram = ROOT.TH1F("histogram", "histogram", 100, 0, 8) i = 0 for event in events: print "Event", i event.getByLabel("packedPFCandidates", tracks) j = 0 for track in tracks.product(): print " Track", j, track.charge() / track.pt(), track.phi( ), track.eta(), track.dxy(), track.dz() histogram.Fill(track.pt()) j += 1 i += 1 if i >= 5: break c = ROOT.TCanvas("c", "c", 800, 800) c.cd() histogram.Draw()
genPartsLabel = "genParticles" genPartsHandle = Handle("vector<reco::GenParticle>") ##### histos HistBR = ROOT.TH1D("HistBR", "W Decay Branching Ratio", 5, 0, 5) ## ##### Reading in files from 'TTTT_TuneZ2star_8TeV-madgraph-tauola.txt' TTJetsFiles = open('TTTT_TuneZ2star_8TeV-madgraph-tauola.txt') files = TTJetsFiles.readlines() TTJetsFiles = [] for f in files: TTJetsFiles.append( 'dcap://grid-dcap-extern.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms' + f.rstrip('\n')) events = Events(TTJetsFiles) #maxEvents = 1000 dimuonic = 0. numbersignalevents = 0 ### ##### event processing for i, event in enumerate(events): #if i >= maxEvents: #break numbersignalevents += 1 event.getByLabel(genPartsLabel, genPartsHandle) genParts = genPartsHandle.product() Counter_e = 0 Counter_mu = 0
import ROOT import sys from DataFormats.FWLite import Events, Handle #events = Events (['root://cms-xrd-global.cern.ch//store/mc/RunIISummer16DR80Premix/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1/80000/EEF150FB-C5B1-E611-87B0-FA163EFD20EB.root']) #events = Events (['root://cms-xrd-global.cern.ch//store/mc/RunIISummer16DR80Premix/WJetsToLNu_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/AODSIM/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext2-v2/70001/901B42AA-D229-E711-AD84-A4BF0101202F.root']) #events = Events (['root://cms-xrd-global.cern.ch//store/mc/RunIISpring15PrePremix/Neutrino_E-10_gun/GEN-SIM-DIGI-RAW/PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v2-v2/80008/9C1072E7-FC82-E611-A3CD-0CC47A78A3F8.root']) events = Events (['/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.1.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.2.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.3.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.4.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.5.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.6.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.7.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.8.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.9.root','/afs/cern.ch/work/a/amlevin/wjets_prod/CMSSW_8_0_21/src/SMP-RunIISummer16DR80Premix-00199.10.root']) genparticles, genParticlesLabel = Handle("vector<reco::GenParticle>"), "genParticles" from math import hypot, pi def deltaPhi(phi1,phi2): ## Catch if being called with two objects if type(phi1) != float and type(phi1) != int: phi1 = phi1.phi if type(phi2) != float and type(phi2) != int: phi2 = phi2.phi ## Otherwise dphi = (phi1-phi2) while dphi > pi: dphi -= 2*pi while dphi < -pi: dphi += 2*pi return dphi def deltaR(eta1,phi1,eta2=None,phi2=None): ## catch if called with objects if eta2 == None:
cmssw_miniaod = "test_particle_net_ak4_MINIAODSIM.root" jetsLabel = "selectedUpdatedPatJets" from RecoBTag.ONNXRuntime.pfParticleNetAK4_cff import _pfParticleNetAK4JetTagsAll disc_names = _pfParticleNetAK4JetTagsAll #disc_names = _pfParticleNetJetTagsProbs+_pfParticleNetSonicJetTagsProbs jet_pt = "fj_pt" jet_eta = "fj_eta" c_numbers = ['event_n'] c_cmssw = {d_name: [] for d_name in disc_names + [jet_pt, jet_eta] + c_numbers} jetsHandle = Handle("std::vector<pat::Jet>") cmssw_evs = Events(cmssw_miniaod) max_n_jets = 1000000 max_n_events = 500000 n_jets = 0 for i, ev in enumerate(cmssw_evs): event_number = ev.object().id().event() if (n_jets >= max_n_jets): break ev.getByLabel(jetsLabel, jetsHandle) jets = jetsHandle.product() for i_j, j in enumerate(jets): uncorr = j.jecFactor("Uncorrected") ptRaw = j.pt() * uncorr if ptRaw < 200.0 or abs(j.eta()) > 2.4: continue if (n_jets >= max_n_jets): break
parser.error("Too many or too few arguments") options.config = args[0] options.file1 = args[1] options.file2 = args[2] # Parse object name and label out of Charles format tName, objName, lName = options.label[0].split('^') label = lName.split(',') ROOT.gROOT.SetBatch() ROOT.gSystem.Load("libFWCoreFWLite.so") ROOT.gSystem.Load("libDataFormatsFWLite.so") ROOT.FWLiteEnabler.enable() chain1 = Events([options.file1], forceEvent=True) chain2 = Events([options.file2], forceEvent=True) if chain1.size() != chain1.size(): raise RuntimeError("Files have different #'s of events") numEvents = min(options.numEvents, chain1.size()) # Parameters to this script are the same regardless if the # product is double or vector<double> so have to try both productsCompared = 0 totalCount = 0 mismatches = 0 for handleName in typeMap[objName]: try: chain1.toBegin() chain2.toBegin()
#! /usr/bin/env python from DataFormats.FWLite import Events, Handle import optparse print "starting python test" files = ['empty.root', 'good.root', 'empty.root', 'good_delta5.root'] events = Events (files) thingHandle = Handle ('std::vector<edmtest::Thing>') indicies = events.fileIndicies() 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)
binning=range(20)+[x*10 for x in range(2,20)]+[x*100 for x in range(2,20)] m0_energy = ROOT.TH1F("m0_energy","m0_energy",len(binning)-1,array('d',binning)) m21_energy = ROOT.TH1F("m21_energy","m21_energy",len(binning)-1,array('d',binning)) m23_energy = ROOT.TH1F("m23_energy","m23_energy",len(binning)-1,array('d',binning)) m0_multiplicity = ROOT.TH1F("m0_multiplicity","m0_multiplicity",len(binning)-1,array('d',binning)) m21_multiplicity = ROOT.TH1F("m21_multiplicity","m21_multiplicity",len(binning)-1,array('d',binning)) m23_multiplicity = ROOT.TH1F("m23_multiplicity","m23_multiplicity",len(binning)-1,array('d',binning)) from files import * #events = Events(RelValZMM_13_CMSSW_7_4_1_MCRUN2_74_V9_gensim_740pre7_v1_PhilFixRecHitFlag[:1]) #prefix="RelValZMM_13_CMSSW_7_4_1-MCRUN2_74_V9_gensim_740pre7-v1_PhilFixRecHitFlag" #events = Events(RelValZMM_13_CMSSW_7_4_1_PU25ns_MCRUN2_74_V9_gensim_740pre7_v1_PhilFixRecHitFlag) #prefix="RelValZMM_13_CMSSW_7_4_1_PU25ns_MCRUN2_74_V9_gensim_740pre7_v1_PhilFixRecHitFlag" events = Events(RelValZMM_13_CMSSW_7_4_1_PU50ns_MCRUN2_74_V8_gensim_740pre7_v1_PhilFixRecHitFlag) prefix="RelValZMM_13_CMSSW_7_4_1_PU50ns_MCRUN2_74_V8_gensim_740pre7_v1_PhilFixRecHitFlag" nevents = 10 if small else events.size() for i in range(nevents): events.to(i) if i%10==0:print "At event %i/%i"%(i,nevents) # eaux=events.eventAuxiliary() # run=eaux.run() # event=eaux.event() # lumi=eaux.luminosityBlock() pfClusters = getProd('pfClusters') caloRecHits = getProd('caloRecHits') for i_c, c in enumerate(pfClusters): hitsAndFractions = c.hitsAndFractions()
''' FWLite example ''' # Standard imports import ROOT from DataFormats.FWLite import Events, Handle from PhysicsTools.PythonAnalysis import * from math import atan, sin, sqrt, log, exp, tan, asin small = True collection = 'rechits' #2016 MC events = Events([ 'root://cms-xrd-global.cern.ch//store/mc/RunIISummer16DR80Premix/SingleNeutrino/AODSIM/PUMoriond17_magnetOff_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/110000/0006AA18-32B3-E611-806C-001E67DFF4F6.root' ]) filename = "MC_%s_2016" % collection #2017MC #events = Events(['root://cms-xrd-global.cern.ch//store/relval/CMSSW_9_3_0_pre1/RelValNuGun/GEN-SIM-RECO/PUpmx25ns_92X_upgrade2017_realistic_v7-v1/00000/14A49577-9561-E711-A501-0CC47A78A2F6.root']) #filename = "MC_%s_2017"%collection #2016 data #events = Events(['root://cms-xrd-global.cern.ch//store/data/Run2016H/ZeroBias/AOD/PromptReco-v2/000/282/037/00000/080C0CFD-7A89-E611-AC65-02163E011D59.root']) #filename = "Data_%s_2016"%collection ##2017 data #events = Events(['root://cms-xrd-global.cern.ch//store/data/Run2017B/ZeroBias/AOD/PromptReco-v1/000/297/723/00000/061EEF62-E25E-E711-975D-02163E0143BC.root']) #filename = "Data_%s_2017"%collection
import ROOT ROOT.gROOT.SetBatch() from DataFormats.FWLite import Events, Handle # events = Events('root://cms-xrd-global.cern.ch//store/mc/RunIIFall17MiniAODv2/VBFHToTauTau_M125_13TeV_powheg_pythia8/MINIAODSIM/PU2017_12Apr2018_94X_mc2017_realistic_v14-v1/90000/549B2DC8-C443-E811-9DAF-A0369FE2C17C.root') events = Events('test.root') # handle = Handle ('std::vector<pat::Electron>') handle = Handle('edm::View<pat::Electron>') for i, event in enumerate(events): event.getByLabel(('slimmedElectrons'), handle) import pdb pdb.set_trace() for i in range(len(handle)): eleptr = handle.ptrAt(i) print eleptr electrons = handle.product() if not len(electrons): continue import pdb pdb.set_trace() if i == 100: break
def writeTree(inputFile): print('######## Creating branches ########') events = Events(inputFile) print('Took the input file successfully') for i, event in enumerate(events): event.getByLabel(photonLabel, photons) event.getByLabel(genParticlesLabel, genParticles) event.getByLabel(triggerBitLabel, triggerBits) event.getByLabel(photonL1Label, photonL1) event.getByLabel(triggerObjectLabel, triggerObjects) hltPhotons[0] = 0 hltCollection = [] recoCollection = [] l1Collection = [] genCollection = [] for j, to in enumerate(triggerObjects.product()): to.unpackNamesAndLabels(event.object(), triggerBits.product()) if to.collection() == 'hltGtStage2Digis:EGamma:HLT': if to.pt() > 5: hltCollection.append(to) hltPhotons[0] += 1 if hltPhotons[0] == 2: fourPBoth = hltCollection[0].p4() + hltCollection[1].p4() invariantMass = fourPBoth.M() hltInvariantMass[0] = invariantMass numPhotons_gen[0] = 0 nPhoton[0] = 0 failedPhotons[0] = 0 triggerBits_ = triggerBits.product() photons_ = photons.product() genParticles_ = genParticles.product() #nPhoton[0] = len(photons_) nParticles[0] = len(genParticles_) names = event.object().triggerNames(triggerBits_) for i in range(triggerBits_.size()): if names.triggerNames()[i] == 'HLT_Photon20_v2': if triggerBits_.accept(i): hltPhoton20[0] = 1 else: hltPhoton20[0] = 0 #if names.triggerNames()[i]=='HLT_Photon33_v5': #if triggerBits_.accept(i): #hltPhoton33[0] = 1 #else: #hltPhoton33[0] = 0 #if names.triggerNames()[i]=='HLT_Photon20_HoverELoose_v10': #if triggerBits_.accept(i): #hltP20H[0] = 1 #else: #hltP20H[0] = 0 #if names.triggerNames()[i]=='HLT_Photon30_HoverELoose_v10': #if triggerBits_.accept(i): #hltP30H[0] = 1 #else: #hltP30H[0] = 0 #if names.triggerNames()[i]=='HLT_Diphoton30_18_R9IdL_AND_HE_AND_IsoCaloId_NoPixelVeto_v2': #if triggerBits_.accept(i): #hltDP30[0] = 1 #else: #hltDP30[0] = 0 j = 0 for i, prt in enumerate(genParticles_): pdgId[i] = prt.pdgId() particleStatus[i] = prt.status() nMothers[i] = prt.numberOfMothers() if prt.pdgId() == 22: photonEnergyg[j] = prt.energy() photonPxg[j] = prt.px() photonPyg[j] = prt.py() photonPzg[j] = prt.pz() photonPhig[j] = prt.phi() photonEtag[j] = prt.eta() photonPtg[j] = prt.pt() genCollection.append(prt) numPhotons_gen[0] += 1 j += 1 #print('in if loop') if i > 1: mothers[i] = prt.mother(0).pdgId() if numPhotons_gen[0] == 2 and len(genCollection) == 2: fourPBoth = genCollection[0].p4() + genCollection[1].p4() invariantMass = fourPBoth.M() genInvariantMass[0] = invariantMass for i, ph in enumerate(photons_): #if ph.photonID('cutBasedPhotonID-Fall17-94X-V1-medium') == 1: photonPt[i] = ph.pt() photonPhi[i] = ph.phi() photonEta[i] = ph.eta() photonEnergy[i] = ph.energy() photonPx[i] = ph.px() photonPy[i] = ph.py() photonPz[i] = ph.pz() recoCollection.append(ph) nPhoton[0] += 1 #else: #failedPhotonPt[i] = ph.pt() #failedPhotonEnergy[i] = ph.energy() #failedPhotons[0] += 1 if nPhoton[0] == 2 and len(recoCollection) == 2: fourPBoth = recoCollection[0].p4(0) + recoCollection[1].p4(0) invariantMass = fourPBoth.M() recoInvariantMass[0] = invariantMass bxVector_photon = photonL1.product() bx = 0 for i, ph in enumerate(bxVector_photon): if ph.pt() > 5: l1Collection.append(ph) nPhoton_L1[0] = bxVector_photon.size(bx) for i in range(bxVector_photon.size(bx)): photon = bxVector_photon.at(bx, i) l1photonPt[i] = photon.pt() l1photonEta[i] = photon.eta() l1photonPhi[i] = photon.phi() l1photonEnergy[i] = photon.energy() l1photonPx[i] = photon.px() l1photonPy[i] = photon.py() l1photonPz[i] = photon.pz() if nPhoton_L1[0] == 2 and len(l1Collection) == 2: fourPBoth = l1Collection[0].p4() + l1Collection[1].p4() invariantMass = fourPBoth.M() l1InvariantMass[0] = invariantMass eventTree.Fill()
#! /usr/bin/env python3 from __future__ import print_function from builtins import range from DataFormats.FWLite import Events, Handle import optparse print("starting python test") files = ['empty_a.root', 'good_a.root', 'empty_a.root', 'good_b.root'] events = Events(files) thingHandle = Handle('std::vector<edmtest::Thing>') indicies = events.fileIndicies() 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()
import numpy as n # load FWLite C++ libraries ROOT.gSystem.Load("libFWCoreFWLite.so") ROOT.gSystem.Load("libDataFormatsFWLite.so") ROOT.AutoLibraryLoader.enable() # load FWlite python libraries from DataFormats.FWLite import Handle, Events lheeventproduct, label = Handle("LHEEventProduct"), "externalLHEProducer" # open file (you can use 'edmFileUtil -d /store/whatever.root' to get the physical file name) events = Events( "root://xrootd-cms.infn.it//store/mc/RunIIWinter15wmLHE/ZNuNuGJets_MonoPhoton_PtG-130_TuneCUETP8M1_13TeV-madgraph/LHE/MCRUN2_71_V1-v1/50000/9A7D08C2-E172-E511-A43B-0025905A60F4.root" ) f = ROOT.TFile("test.root", "recreate") t = ROOT.TTree("genTree", "Simple gen tree") p3 = ROOT.TVector3() p4 = ROOT.TVector3() p5 = ROOT.TVector3() p6 = ROOT.TVector3() p7 = ROOT.TVector3() t.Branch('p3', p3) t.Branch('p4', p4) t.Branch('p5', p5) t.Branch('p6', p5) t.Branch('p7', p7)
fil = filter( lambda x : '.root' in x and "super" in x, files) for f in fil: thefiles.append( subdir + '/' + f) datasets[dataset]['files'] = thefiles outputDict[dataset]['total'] = 0 for b in bins: outputDict[dataset]['fired' + str(b) + "_q12"] = 0 outputDict[dataset]['fired' + str(b) + "_q4"] = 0 outputDict[dataset]['fired' + str(b) + "_q0"] = 0 muonHandle, muonLabel = Handle("BXVector<l1t::RegionalMuonCand>"), ("simOmtfDigis", "OMTF", "L1TMuonEmulation" ) for dataset in datasets: print 'starting to process', dataset events = Events(datasets[dataset]['files']) print 'we got the events' count = 0 for ev in events: if not count%1000: print count, events.size() count += 1 outputDict[dataset]['total'] = outputDict[dataset]['total'] + 1 ev.getByLabel(muonLabel, muonHandle) muons = muonHandle.product() goodIndex = 0 for bxNumber in range(muons.getFirstBX(), muons.getLastBX()+1): size = muons.size(bxNumber) for i in range(size): muon = muons[i+goodIndex] if muon.trackFinderType() not in [1,2]: continue #Only OMTF for b in bins:
graph_error = ROOT.TGraphErrors() for i in range(1,hist_2d.GetNbinsX()+1): proj_y = hist_2d.ProjectionY("",i,i) k = (hist_2d.GetXaxis()).GetBinCenter(i) rms = proj_y.GetRMS() rms_error = proj_y.GetRMSError() graph_error.SetPoint(i,k,rms) graph_error.SetPointError(i,0,rms_error) return graph_error def resolution(u,v,k): return math.sqrt(u**2+(v**2)*k**2) events = Events(['file:/scratch2/Leah/CMSSW_10_1_7/src/cscHits.root']) N=0 tantheta_k_112 = ROOT.TH2D("tantheta_k_121","$\Delta$$\Tantheta$ vs k; k; $\Delta\Theta$",100,-0.4,0.4,100,-0.5,0.5) tantheta_k_212 = ROOT.TH2D("tantheta_k_221","$\Delta$$\Tantheta$ vs k; k; $\Delta\Theta$",100,-0.4,0.4,100,-0.5,0.5) for event in events: N=N+1 # if N > 50000: # break if N in [50000,100000,150000,200000]: print ('analyzing event {}').format(N) # if N > 100000: # break
def loadEvents(self,nEvents = -1): self.events = Events( self.inputPath )
import sys from DataFormats.FWLite import Events, Handle # Make VarParsing object # https://twiki.cern.ch/twiki/bin/view/CMS/SWGuideAboutPythonConfigFile#VarParsing_Example from FWCore.ParameterSet.VarParsing import VarParsing options = VarParsing('python') options.parseArguments() # Events takes either # - single file name # - list of file names # - VarParsing options # use Varparsing object events = Events(options) # create handle outside of loop handle = Handle("std::vector<pat::Muon>") # for now, label is just a tuple of strings that is initialized just # like and edm::InputTag label = ("selectedLayer1Muons") # Create histograms, etc. ROOT.gROOT.SetBatch() # don't pop up canvases ROOT.gROOT.SetStyle('Plain') # white background zmassHist = ROOT.TH1F("zmass", "Z Candidate Mass", 50, 20, 220) # loop over events for event in events:
t.Branch('PID', PID, 'PID[5]/F') t.Branch('CSV', CSV, 'CSV[5]/F') t.Branch('nbTags', nbTags, 'nbTags/i') t.Branch('nValidJets', nValidJets, 'nValidJets/i') f.cd() #Read in input files FILES = options.directory + '/*.root' print FILES files = glob.glob(FILES) print 'Getting these files : ' for fname in files: print fname postfix = "" events = Events(files) #Width and Central Value of Wmass peak wmass = 80.08 wwidth = 33.5 #Set up handles and labels for use #muon variables if options.lep == "mu": if options.leptonCut == 'tight': leptonPtHandle = Handle("std::vector<float>") leptonPtLabel = ("pfShyftTupleMuons" + postfix, "pt") leptonEtaHandle = Handle("std::vector<float>") leptonEtaLabel = ("pfShyftTupleMuons" + postfix, "eta") leptonPhiHandle = Handle("std::vector<float>") leptonPhiLabel = ("pfShyftTupleMuons" + postfix, "phi")
self.tests = tests or [] def __call__(self, event): event.getByLabel(*(list(self.inlabel) + [self.inhandle])) event.getByLabel(*(list(self.outlabel) + [self.outhandle])) print self.msg for a, b in compare_bx_vector(self.inhandle.product(), self.outhandle.product()): for t in self.tests: t(a, b) def test_type(a, b): if a.getType() != b.getType(): print ">>> Type different:", a.getType(), "vs", b.getType() events = Events(sys.argv[1]) run = [ Test( 'Checking spare rings', 'BXVector<l1t::CaloSpare>', ('simCaloStage1FinalDigis', 'HFRingSums'), ('l1tRawToDigi', 'HFRingSums'), [test_type] ), Test( 'Checking spare bits', 'BXVector<l1t::CaloSpare>', ('simCaloStage1FinalDigis', 'HFBitCounts'), ('l1tRawToDigi', 'HFBitCounts'), [test_type]
def compare(quantity, input_dev, input_ref, tau_type, ranges, outdir, max_taus, nbins, name): e_dev = Events(input_dev) e_ref = Events(input_ref) tau_handle = Handle("std::vector<pat::Tau>") c1 = ROOT.TCanvas() r = [0.0, 1.01] if quantity in ranges.keys(): r = ranges[quantity] isID = False idxID = -1 if quantity.startswith("id:"): isID = True quantity = quantity.replace("id:", "") h_ref = ROOT.TH1F(quantity, quantity, nbins, r[0], r[1]) h_dev = ROOT.TH1F(quantity + "_dev", quantity + "_dev", nbins, r[0], r[1]) max = max_taus for event in e_ref: if max == 0: break event.getByLabel(tau_type, tau_handle) taus = tau_handle.product() for tau in taus: if max == 0: break if isID: if idxID == -1: for i, ID in enumerate(tau.tauIDs()): if ID.first == quantity: idxID = i break h_ref.Fill(tau.tauIDs()[idxID].second) else: h_ref.Fill(getattr(tau, quantity)()) max -= 1 max = max_taus for event in e_dev: if max == 0: break event.getByLabel(tau_type, tau_handle) taus = tau_handle.product() for tau in taus: if max == 0: break if isID: h_dev.Fill(tau.tauIDs()[idxID].second) else: h_dev.Fill(getattr(tau, quantity)()) max -= 1 equal = True for i in range(1, nbins + 1): if h_ref.GetBinContent(i) != h_dev.GetBinContent(i): equal = False break h_ref.SetLineWidth(2) h_dev.SetLineWidth(2) h_dev.SetLineColor(8 if equal else 2) h_dev.SetLineStyle(7) h_ref.Draw("hist") h_dev.Draw("histsame") c1.SaveAs(os.path.join(outdir, "%s_%s.png" % (name, quantity))) return equal
import ROOT from DataFormats.FWLite import Events, Handle from PhysicsTools.PythonAnalysis import * events_new = Events([ '~/eos/cms/store/group/phys_jetmet/schoef/pickEvents/jack_metTailPhys14_susyHadronic/merged_bad_GEN-SIM_rereco_740_newPFHadCalib.root' ]) #events_old = Events(['~/eos/cms/store/group/phys_jetmet/schoef/pickEvents/jack_metTailPhys14_susyHadronic/merged_bad_GEN-SIM.root']) edmCollections = [{ 'name': 'pfMet', 'label': ("pfMet"), 'edmType': "vector<reco::PFMET>" }] handles = {v['name']: Handle(v['edmType']) for v in edmCollections} for i in range(events_new.size()): 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()
gen_handle, gen_label = Handle( "std::vector<reco::GenParticle>"), "genParticles" weights = EvtWeights(args.weights) to_remove = [] for file in args.in_filename: file_temp = ROOT.TFile(file) if (file_temp.IsZombie()): print "******** remove file **********" to_remove.append(file) new_list = [x for x in args.in_filename if x not in to_remove] print "AFTER REMOVING ALL ZOMBIES, this is the new list of files " print new_list events = Events(new_list) #events = Events(args.in_filename) #ele_seed_time_EB = ROOT.TH1D("ele_seed_time_EB",";ele seed time;#entries",600,-6,6) ele_my_sieie_default_EB = ROOT.TH1D("ele_my_sieie_default_EB", ";my_sieie_default;#entries", 2000, 0, 2) ele_my_sieie_NC_EB = ROOT.TH1D("ele_my_sieie_NC_EB", ";my_sieie_NC;#entries", 2000, 0, 2) ele_saved_sieie_default_EB = ROOT.TH1D("ele_saved_sieie_default_EB", ";saved_sieie_default;#entries", 2000, 0, 2) ele_E5x5 = ROOT.TH1D("ele_E5x5", "E5x5;#entries", 100, 0, 100) noise_vs_ieta = ROOT.TH2D("noise_vs_ieta", ";ieta;PF recHit threshold", 200, -100, 100, 500, 0, 5)
def fill2DHistos(histo_dict): ''' Given the dict containing all histograms, fills the histograms by doing an event loop. ''' #No stat box in the histograms ROOT.gStyle.SetOptStat(0) mjj_histo = histo_dict['mjj_histo'] leadJetPt_histo = histo_dict['leadJetPt_histo'] trailJetPt_histo = histo_dict['trailJetPt_histo'] leadJetEta_histo = histo_dict['leadJetEta_histo'] trailJetEta_histo = histo_dict['trailJetEta_histo'] jets, jetLabel = Handle('std::vector<pat::Jet>'), 'slimmedJets' events = Events( 'root://cmsxrootd.fnal.gov///store/mc/RunIIFall17MiniAODv2/VBF_HToInvisible_M125_13TeV_TuneCP5_powheg_pythia8/MINIAODSIM/PU2017_12Apr2018_94X_mc2017_realistic_v14-v1/00000/14347E60-56F2-E811-81F4-24BE05C6C7E1.root' ) ####################### #Event loop starts here ####################### for iev, event in enumerate(events): #if iev == 1000: break #For testing if iev % 1000 == 0: print('Working on event {}'.format(iev)) event.getByLabel(jetLabel, jets) ###################### #Implementing tight jet ID, 2017 recommendations ###################### jets_ = jets.product() AK4_tightJets = [] for jet in jets_: if isTightJet(jet): AK4_tightJets.append(jet) nJet = len(AK4_tightJets) if nJet < 2: continue #Discard the events with number of jets smaller than 2 mjj_values = invMassJetCombos( AK4_tightJets) #Get all the mjj values for all possible combos maxCombo = getMaxCombo( mjj_values ) #Get the jet pair for which the maximum mjj happens to be ################################# #In the following, max_ variables stand for "the pair with highest mjj" #In contrast, leadingPair_ stands for "the highest pt jet pair" ################################# leadingPair_mjj = mjj_values['leadingJet_trailingJet'] leadingPair_leadJetPt = AK4_tightJets[0].pt() leadingPair_trailJetPt = AK4_tightJets[1].pt() leadingPair_leadJetEta = AK4_tightJets[0].eta() leadingPair_trailJetEta = AK4_tightJets[1].eta() if maxCombo == (0, 1): max_mjj = leadingPair_mjj max_leadJetPt = leadingPair_leadJetPt max_trailJetPt = leadingPair_trailJetPt max_leadJetEta = leadingPair_leadJetEta max_trailJetEta = leadingPair_trailJetEta else: max_mjj = mjj_values['otherCombos'][maxCombo] #Identify the jet with larger pt in the max mjj combo idx_jetWithLargerPt, idx_jetWithSmallerPt = sortJets( AK4_tightJets, maxCombo) max_leadJetPt = AK4_tightJets[idx_jetWithLargerPt].pt() max_trailJetPt = AK4_tightJets[idx_jetWithSmallerPt].pt() max_leadJetEta = AK4_tightJets[idx_jetWithLargerPt].eta() max_trailJetEta = AK4_tightJets[idx_jetWithSmallerPt].eta() mjj_histo.Fill(max_mjj, leadingPair_mjj) leadJetPt_histo.Fill(max_leadJetPt, leadingPair_leadJetPt) trailJetPt_histo.Fill(max_trailJetPt, leadingPair_trailJetPt) leadJetEta_histo.Fill(max_leadJetEta, leadingPair_leadJetEta) trailJetEta_histo.Fill(max_trailJetEta, leadingPair_trailJetEta) #Plot the histograms and save them for hist in histo_dict.values(): print2DHisto(hist)
# FWLite aggregates ALL of the information immediately, which # can take a long time to parse. filelist = file(options.files) filesraw = filelist.readlines() files = [] nevents = 0 for ifile in filesraw: if len(ifile) > 2: s = 'root://' + options.xrootd + '/' + ifile.rstrip() files.append(s) print 'Added ' + s # loop over files for ifile in files: print 'Processing file ' + ifile events = Events(ifile) if options.maxevents > 0 and nevents > options.maxevents: break # loop over events in this file i = 0 for event in events: if options.maxevents > 0 and nevents > options.maxevents: break i += 1 nevents += 1 if i % 1000 == 0: print ' ---> Event ' + str(i) ## _____ ____ __. _____ ____. __ __________.__ __
# test for invalid files: sane_files = [] for arg in args: if "mimes" in arg: continue test = TFile(arg) if not (test.IsZombie() or test.TestBit(TFile.kRecovered)): sane_files.append(arg) else: print "ignoring file: %s" % arg os.system("rm %s" % arg) test.Close() print "sane_files", sane_files events = Events(sane_files) # create handle outside of loop muons_handle = Handle("std::vector<reco::Muon>") pfcands_handle = Handle("std::vector<reco::PFCandidate>") tracks_handle = Handle("std::vector<reco::Track>") muons_rereco_handle = Handle("std::vector<reco::Muon>") tracks_rereco_handle = Handle("std::vector<reco::Track>") offlinePrimaryVertices_reco_handle = Handle("std::vector<reco::Vertex>") offlinePrimaryVertices_rereco_handle = Handle("std::vector<reco::Vertex>") # handles for isotrk producer isotrk_matchedCaloEnergy_handle = Handle("std::vector<double>") isotrk_trackerLayersWithMeasurement_handle = Handle("std::vector<int>") isotrk_chi2perNdof_handle = Handle("std::vector<double>") isotrk_trackQualityHighPurity_handle = Handle("std::vector<bool>")
def runGenTreeProducer(infiles='./step*root', outfilename='out.root', this_mass=1, this_ctau=500, this_vv=0.0013, doBtoD=False, doFromMini=False): # input and output files = glob.glob(infiles) if len(files) == 0: raise RuntimeError( 'No files to be run!, glob expression = {}'.format(infiles)) outfile = ROOT.TFile.Open(outfilename, 'recreate') handles = OrderedDict() if doFromMini: handles['genP'] = ('packedGenParticles', Handle('std::vector<pat::PackedGenParticle>') ) # does not seem to be working quite well else: handles['genP'] = ('genParticles', Handle('std::vector<reco::GenParticle>')) #handles['lhe'] = ('externalLHEProducer', Handle('LHEEventProduct')) # output file and tree gymnastics ntuple = ROOT.TNtuple('tree', 'tree', ':'.join(branches)) tofill = OrderedDict(zip( branches, [-99.] * len(branches))) # initialise all branches to unphysical -99 # get to the real thing print 'loading the file ...' events = Events(files) print '... done!' for i, event in enumerate(events): # access the handles for k, v in handles.iteritems(): event.getByLabel(v[0], v[1]) setattr(event, k, v[1].product()) if i % 1000 == 0: percentage = float(i) / events.size() * 100. print '\t===> processing %d / %d event \t completed %.1f%s' % ( i, events.size(), percentage, '%') #print '\n Event {a}'.format(a=i) # get the heavy neutrino the_hns = [ ip for ip in event.genP if abs(ip.pdgId()) == 9900015 and ip.isLastCopy() ] if len(the_hns): event.the_hn = the_hns[0] # one per event # print( '\n\nNEW EVENT run={} event={}'.format( event.eventAuxiliary().run(),event.eventAuxiliary().event() )) # if event.the_hn: # print('FOUND HNL, status={} isLastCopy()={} vx={:10} vy={:10} vz={:10} pt={:10} eta={:10} phi={:10}'.format(event.the_hn.status(), event.the_hn.isLastCopy(), event.the_hn.vx(), event.the_hn.vy(), event.the_hn.vz(), event.the_hn.pt(), event.the_hn.eta(), event.the_hn.phi())) # for iD in range(event.the_hn.numberOfDaughters()): # print(' , daughter pdg={:10}, status={:10} isLastCopy={:10} vx={:10} vy={:10} vz={:10} pt={:10} eta={:10} phi={:10}'.format(event.the_hn.daughter(iD).pdgId(),event.the_hn.daughter(iD).status(), event.the_hn.daughter(iD).isLastCopy(), event.the_hn.daughter(iD).vx(), event.the_hn.daughter(iD).vy(), event.the_hn.daughter(iD).vz(), event.the_hn.daughter(iD).pt(), event.the_hn.daughter(iD).eta(), event.the_hn.daughter(iD).phi())) # for iM in range(event.the_hn.numberOfMothers()): # print(' , mother pdg={:10}, status={:10} isLastCopy={:10} vx={:10} vy={:10} vz={:10} pt={:10} eta={:10} phi={:10}'.format(event.the_hn.mother(iM).pdgId(),event.the_hn.mother(iM).status(), event.the_hn.mother(iM).isLastCopy(), event.the_hn.mother(iM).vx(), event.the_hn.mother(iM).vy(), event.the_hn.mother(iM).vz(), event.the_hn.mother(iM).pt(), event.the_hn.mother(iM).eta(), event.the_hn.mother(iM).phi())) # for iDM in range(event.the_hn.mother(iM).numberOfDaughters()): # print(' daughter pdg={:10}, status={:10} isLastCopy={:10} vx={:10} vy={:10} vz={:10} pt={:10} eta={:10} phi={:10}'.format(event.the_hn.mother(iM).daughter(iDM).pdgId(), event.the_hn.mother(iM).daughter(iDM).status(), event.the_hn.mother(iM).daughter(iDM).isLastCopy(), event.the_hn.mother(iM).daughter(iDM).vx(), event.the_hn.mother(iM).daughter(iDM).vy(), event.the_hn.mother(iM).daughter(iDM).vz(), event.the_hn.mother(iM).daughter(iDM).pt(), event.the_hn.mother(iM).daughter(iDM).eta(), event.the_hn.mother(iM).daughter(iDM).phi())) # find the B mother event.the_hn.mothers = [ event.the_hn.mother(jj) for jj in range(event.the_hn.numberOfMothers()) ] the_b_mothers = sorted([ ii for ii in event.the_hn.mothers if (abs(ii.pdgId()) == 521 or abs(ii.pdgId()) == 511 or abs(ii.pdgId()) == 531 or abs(ii.pdgId()) == 541) ], key=lambda x: x.pt(), reverse=True) if len(the_b_mothers): event.the_b_mother = the_b_mothers[0] else: event.the_b_mother = None # get the other daughters of the B meson event.the_b_mother.daughters = [ event.the_b_mother.daughter(jj) for jj in range(event.the_b_mother.numberOfDaughters()) ] #print [ii.pdgId() for ii in event.the_b_mother.daughters] # # first the D0 meson, if it exists if doBtoD: the_ds = sorted([ ii for ii in event.the_b_mother.daughters if abs(ii.pdgId()) == 421 ], key=lambda x: x.pt(), reverse=True) if len(the_ds): event.the_d = the_ds[0] else: event.the_d = None # # then the trigger lepton the_pls = sorted([ ii for ii in event.the_b_mother.daughters if abs(ii.pdgId()) in [11, 13, 15] ], key=lambda x: x.pt(), reverse=True) if len(the_pls): event.the_pl = the_pls[0] else: event.the_pl = None # D0s daughters if doBtoD and len(the_ds): event.the_d.daughters = [ event.the_d.daughter(jj) for jj in range(event.the_d.numberOfDaughters()) ] # #find the pion the_pis = sorted( [ii for ii in event.the_d.daughters if abs(ii.pdgId()) == 211], key=lambda x: x.pt(), reverse=True) if len(the_pis): event.the_pi = the_pis[0] else: event.the_pi = None # find the kaon the_ks = sorted( [ii for ii in event.the_d.daughters if abs(ii.pdgId()) == 321], key=lambda x: x.pt(), reverse=True) if len(the_ks): event.the_k = the_ks[0] else: event.the_k = None # HNL daughters event.the_hn.initialdaus = [ event.the_hn.daughter(jj) for jj in range(event.the_hn.numberOfDaughters()) ] # # the lepton the_lep_daughters = sorted([ ii for ii in event.the_hn.initialdaus if abs(ii.pdgId()) in [11, 13, 15] ], key=lambda x: x.pt(), reverse=True) if len(the_lep_daughters): event.the_hn.lep = the_lep_daughters[0] else: event.the_hn.lep = None # # the pion the_pi_daughters = sorted( [ii for ii in event.the_hn.initialdaus if abs(ii.pdgId()) == 211], key=lambda x: x.pt(), reverse=True) if len(the_pi_daughters): event.the_hn.pi = the_pi_daughters[0] else: event.the_hn.pi = None # invariant masses # # to get the invariant mass of the HNL daughters if len(the_pi_daughters) and len(the_lep_daughters): event.the_hnldaughters = event.the_hn.lep.p4( ) + event.the_hn.pi.p4() # # to get the invariant mass of the D0 daughters if doBtoD and len(the_ds): if len(the_ks) and len(the_pis): event.the_d0daughters = event.the_k.p4() + event.the_pi.p4() # # to get the full or partial invariant mass of the B # # # partial if len(the_pls) and len(the_hns): event.the_bdaughters_partial = event.the_hn.p4() + event.the_pl.p4( ) # # # total #event.the_bdaughters_all = sum([ii.p4() for ii in event.the_b_mother.daughters]) #if doBtoD and len(the_ds) and len(the_pls) and len(the_hns): # event.the_bdaughters = event.the_hn.p4() + event.the_d.p4() + event.the_pl.p4() ##elif not len(the_ds): #elif not doBtoD: # event.the_bdaughters = event.the_hn.p4() + event.the_pl.p4() # identify the primary vertex # for that, needs the trigger lepton if len(the_pls): event.the_hn.the_pv = event.the_pl.vertex() # identify the secondary vertex if len(the_lep_daughters): event.the_hn.the_sv = event.the_hn.lep.vertex() # 2D transverse and 3D displacement, Pythagoras if len(the_pls) and len(the_lep_daughters): event.Lz = np.sqrt( (event.the_hn.the_pv.z() - event.the_hn.the_sv.z())** 2) * 10 # everything in mm event.Lxy = np.sqrt((event.the_hn.the_pv.x() - event.the_hn.the_sv.x())**2 + \ (event.the_hn.the_pv.y() - event.the_hn.the_sv.y())**2) * 10 # everything in mm event.Lxyz = np.sqrt((event.the_hn.the_pv.x() - event.the_hn.the_sv.x())**2 + \ (event.the_hn.the_pv.y() - event.the_hn.the_sv.y())**2 + \ (event.the_hn.the_pv.z() - event.the_hn.the_sv.z())**2) * 10 # everything in mm # per event ct, as derived from the flight distance and Lorentz boost event.the_hn.beta = event.the_hn.p4().Beta() event.the_hn.gamma = event.the_hn.p4().Gamma() # we get the lifetime from the kinematics if len(the_pls) and len(the_lep_daughters): event.the_hn.ct_reco = event.Lxyz / (event.the_hn.beta * event.the_hn.gamma) # pointing angle #if len(the_pls) and len(the_lep_daughters): # hn_pt_vect = ROOT.math.XYZVector(event.the_hnldaughters.px(), # event.the_hnldaughters.py(), # 0.) # Lxy_vect = ROOT.GlobalPoint(-1*((event.the_hn.the_pv.x() - event.the_hn.the_sv.x())), # -1*((event.the_hn.the_pv.y() - event.the_hn.the_sv.y())), # 0) # vperptau = ROOT.math.XYZVector(Lxy_vect.x(), Lxy_vect.y(), 0.) #event.cos_pointing = vperptau.Dot(hn_pt_vect)/(vperptau.R()*hn_pt_vect.R()) event.Lxyz_pl = np.sqrt((event.the_b_mother.vx() - event.the_pl.vx())**2 + \ (event.the_b_mother.vy() - event.the_pl.vy())**2 + \ (event.the_b_mother.vz() - event.the_pl.vz())**2) * 10 # everything in mm # get the lifetime of the B event.the_b_mother.beta = event.the_b_mother.p4().Beta() event.the_b_mother.gamma = event.the_b_mother.p4().Gamma() event.the_b_mother.ct_reco = event.Lxyz_pl / (event.the_b_mother.beta * event.the_b_mother.gamma) tofill['run'] = event.eventAuxiliary().run() tofill['lumi'] = event.eventAuxiliary().luminosityBlock() tofill['event'] = event.eventAuxiliary().event() if event.the_b_mother: tofill['b_pt'] = event.the_b_mother.pt() tofill['b_eta'] = event.the_b_mother.eta() tofill['b_phi'] = event.the_b_mother.phi() tofill['b_mass'] = event.the_b_mother.mass() tofill['b_q'] = event.the_b_mother.charge() tofill['b_pdgid'] = event.the_b_mother.pdgId() tofill['b_ct_reco'] = event.the_b_mother.ct_reco tofill['hnl_pt'] = event.the_hn.pt() #tofill['hnl_p' ] = event.the_hn.pt() * ROOT.TMath.CosH(event.the_hn.eta()) tofill['hnl_eta'] = event.the_hn.eta() tofill['hnl_phi'] = event.the_hn.phi() tofill['hnl_mass'] = event.the_hn.mass() #tofill['hnl_ct_lhe' ] = event.hnl_ct_lhe if len(the_lep_daughters): tofill['hnl_ct_reco'] = event.the_hn.ct_reco tofill['hnl_beta'] = event.the_hn.beta tofill['hnl_gamma'] = event.the_hn.gamma tofill['hnl_pdgid'] = event.the_hn.pdgId() if doBtoD and event.the_d: tofill['d_pt'] = event.the_d.pt() tofill['d_eta'] = event.the_d.eta() tofill['d_phi'] = event.the_d.phi() tofill['d_mass'] = event.the_d.mass() tofill['d_q'] = event.the_d.charge() tofill['d_pdgid'] = event.the_d.pdgId() if event.the_k: tofill['k_pt'] = event.the_k.pt() tofill['k_eta'] = event.the_k.eta() tofill['k_phi'] = event.the_k.phi() tofill['k_mass'] = event.the_k.mass() tofill['k_q'] = event.the_k.charge() tofill['k_pdgid'] = event.the_k.pdgId() if event.the_pi: tofill['pi_pt'] = event.the_pi.pt() tofill['pi_eta'] = event.the_pi.eta() tofill['pi_phi'] = event.the_pi.phi() tofill['pi_mass'] = event.the_pi.mass() tofill['pi_q'] = event.the_pi.charge() tofill['pi_pdgid'] = event.the_pi.pdgId() if event.the_pl: tofill['l0_pt'] = event.the_pl.pt() tofill['l0_eta'] = event.the_pl.eta() tofill['l0_phi'] = event.the_pl.phi() tofill['l0_mass'] = event.the_pl.mass() tofill['l0_q'] = event.the_pl.charge() tofill['l0_pdgid'] = event.the_pl.pdgId() if event.the_hn.lep: tofill['l1_pt'] = event.the_hn.lep.pt() tofill['l1_eta'] = event.the_hn.lep.eta() tofill['l1_phi'] = event.the_hn.lep.phi() tofill['l1_mass'] = event.the_hn.lep.mass() tofill['l1_q'] = event.the_hn.lep.charge() tofill['l1_pdgid'] = event.the_hn.lep.pdgId() if event.the_hn.pi: tofill['pi1_pt'] = event.the_hn.pi.pt() tofill['pi1_eta'] = event.the_hn.pi.eta() tofill['pi1_phi'] = event.the_hn.pi.phi() tofill['pi1_mass'] = event.the_hn.pi.mass() tofill['pi1_q'] = event.the_hn.pi.charge() tofill['pi1_pdgid'] = event.the_hn.pi.pdgId() # invariant mass tofill['lep_pi_invmass'] = event.the_hnldaughters.mass() if doBtoD and len(the_ds): tofill['k_pi_invmass'] = event.the_d0daughters.mass() #tofill['b_invmass'] = event.the_bdaughters_all.mass() tofill['bpartial_invmass'] = event.the_bdaughters_partial.mass() # hnl charge tofill['hnl_q'] = event.the_hn.lep.charge() + event.the_hn.pi.charge() tofill['hnl_qprop'] = event.the_hn.charge() if len(the_pls) and len(the_lep_daughters): tofill['Lz'] = event.Lz tofill['Lxy'] = event.Lxy tofill['Lxyz'] = event.Lxyz #tofill['Lxy_cos' ] = event.cos_pointing tofill['Lxyz_l0'] = event.Lxyz_pl # weights for ctau reweighting for vv in new_vvs: tofill['weight_%s' % (str(vv).replace('-', 'm'))] = weight_to_new_ctau( old_ctau=this_ctau, old_v2=this_vv, new_v2=vv, ct=event.the_hn.ct_reco)[0] tofill['ctau_%s' % (str(vv).replace('-', 'm'))] = weight_to_new_ctau( old_ctau=this_ctau, old_v2=this_vv, new_v2=vv, ct=event.the_hn.ct_reco)[1] tofill['xs_scale_to_%s' % (str(vv).replace('-', 'm'))] = vv / this_vv ntuple.Fill(array('f', tofill.values())) outfile.cd() ntuple.Write() outfile.Close()
if options.set != 'data': #Load up scale factors (to be used for MC only) #TrigFile = TFile(di+"Triggerweight_"+options.set+".root") TrigFile = TFile(di+"Triggerweight_signalright2000btags.root") TrigPlot = TrigFile.Get("TriggerWeight_"+tnamestr) #PileFile = TFile(di+"PileUp_Ratio_"+settype+".root") #PilePlot = PileFile.Get("Pileup_Ratio") # We select all the events: events = Events (files) #Here we load up handles and labels. #These are used to grab entries from the Ntuples. #To see all the current types in an Ntuple use edmDumpEventContent /PathtoNtuple/Ntuple.root AK8HL = Initlv("jetsAK8") GeneratorHandle = Handle ( "GenEventInfoProduct") GeneratorLabel = ( "generator" , "") BDiscHandle = Handle ( "vector<float> " ) BDiscLabel = ( "jetsAK8" , "jetAK8CSV")
filename = '' if runtype == 'ZTT': filename = 'root://eoscms//eos/cms/store/cmst3/user/ytakahas/TauPOG/ZTT_CMSSW_' + RelVal + '_RelValZTT_13_MINIAODSIM_76X_mcRun2_asymptotic_' + tag + '-v1_' + str(ii) + '.root' elif runtype == 'ZEE': filename = 'root://eoscms//eos/cms/store/cmst3/user/ytakahas/TauPOG/ZEE_CMSSW_' + RelVal + '_RelValZEE_13_MINIAODSIM_76X_mcRun2_asymptotic_' + tag + '-v1_' + str(ii) + '.root' elif runtype == 'ZMM': filename = 'root://eoscms//eos/cms/store/cmst3/user/ytakahas/TauPOG/ZMM_CMSSW_' + RelVal + '_RelValZMM_13_MINIAODSIM_76X_mcRun2_asymptotic_' + tag + '-v1_' + str(ii) + '.root' elif runtype == 'QCD': filename = 'root://eoscms//eos/cms/store/cmst3/user/ytakahas/TauPOG/QCD_CMSSW_' + RelVal + '_QCD_FlatPt_15_3000HS_13_MINIAODSIM_76X_mcRun2_asymptotic_v11-v1_' + str(ii) + '.root' print(filename) filelist.append(filename) events = Events(filelist) print(len(filelist), 'files will be analyzed') outputname = 'Myroot_' + RelVal + '_' + runtype + '.root' file = ROOT.TFile(outputname, 'recreate') h_ngen = ROOT.TH1F("h_ngen", "h_ngen",10,0,10) tau_tree = ROOT.TTree('per_tau','per_tau') tau_eventid = num.zeros(1, dtype=int) tau_id = num.zeros(1, dtype=int) tau_dm = num.zeros(1, dtype=int) tau_dm_rough = num.zeros(1, dtype=int) tau_pt = num.zeros(1, dtype=float)
# initialise output files to save the flat ntuples outfile_gen = ROOT.TFile('tau_gentau_tuple_{}_{}.root'.format(sample,ifile), 'recreate') ntuple_gen = ROOT.TNtuple('tree', 'tree', ':'.join(branches)) tofill_gen = OrderedDict(list(zip(branches, [-99.]*len(branches)))) # initialise all branches to unphysical -99 # outfile_jet = ROOT.TFile('tau_jet_tuple_{}_{}.root'.format(sample,ifile), 'recreate') # ntuple_jet = ROOT.TNtuple('tree', 'tree', ':'.join(branches)) # tofill_jet = OrderedDict(zip(branches, [-99.]*len(branches))) # initialise all branches to unphysical -99 ########################################################################################## # Get ahold of the events f = open('%s_filelist.txt'%args.sample) infile = f.readlines()[ifile] #events = Events('root://cms-xrd-global.cern.ch/'+infile) # make sure this corresponds to your file name! events = Events(infile.strip()) # make sure this corresponds to your file name! #events = Events('/eos/user/b/bskipwor/HNL_M_5/HNL_miniAOD_1_3.root') # make sure this corresponds to your file name! maxevents = -1 # max events to process totevents = events.size() # total number of events in the files def isAncestor(a, p): if a == p : return True for i in range(0,p.numberOfMothers()): if isAncestor(a,p.mother(i)): return True return False ########################################################################################## # instantiate the handles to the relevant collections. # Do this *outside* the event loop
class EdmDataAccessor(BasicDataAccessor, RelativeDataAccessor, ParticleDataAccessor, EventFileAccessor): def __init__(self): logging.debug(__name__ + ": __init__") self._dataObjects = [] self._edmLabel = {} self._edmParent = {} self._edmChildren = {} self._edmMotherRelations = {} self._edmDaughterRelations = {} self._edmChildrenObjects = {} self._eventIndex = 0 self._numEvents = 0 self._filename = "" self._branches = [] self._filteredBranches = [] self._events = None self._readOnDemand = True self._underscore = False self._filterBranches = True self.maxLevels = 2 self.maxDaughters = 1000 def isRead(self, object, levels=1): if not id(object) in self._edmChildrenObjects.keys(): return False if levels > 1 and id(object) in self._edmChildren.keys(): for child in self._edmChildren[id(object)]: if not self.isRead(child, levels - 1): return False return True def children(self, object): """ Get children of an object """ if id(object) in self._edmChildren.keys() and self.isRead(object): return self._edmChildren[id(object)] else: return () def isContainer(self, object): """ Get children of an object """ if id(object) in self._edmChildren.keys() and self.isRead(object): return len(self._edmChildren[id(object)]) > 0 else: return True def motherRelations(self, object): """ Get motherRelations of an object """ if id(object) in self._edmMotherRelations.keys(): return self._edmMotherRelations[id(object)] else: return () def daughterRelations(self, object): """ Get daughterRelations of an object """ if id(object) in self._edmDaughterRelations.keys(): return self._edmDaughterRelations[id(object)] else: return () def label(self, object): return self.getShortLabel(object) def getShortLabel(self, object): if id(object) in self._edmLabel.keys(): splitlabel = self._edmLabel[id(object)].strip(".").split(".") return splitlabel[len(splitlabel) - 1] else: return "" def getShortLabelWithType(self, object): return self.getShortLabel(object) + " <" + self.getShortType( object) + ">" def getObjectLabel(self, object): splitlabel = self._edmLabel[id(object)].strip(".").split(".") return ".".join(splitlabel[1:-1]) def getType(self, object): typ = str(object.__class__) if "\'" in typ: typ = typ.split("\'")[1] if "." in typ: typ = typ.split(".")[len(typ.split(".")) - 1] return typ.strip(" ") def getShortType(self, object): typ = self.getType(object).split("<")[0].strip(" ") return typ def getBranch(self, object): entry = object while id(entry) in self._edmParent.keys( ) and self._edmParent[id(entry)] != None: entry = self._edmParent[id(entry)] return entry def getDepth(self, object): entry = object i = 0 while id(entry) in self._edmParent.keys( ) and self._edmParent[id(entry)] != None: entry = self._edmParent[id(entry)] i += 1 return i def getObjectProperties(self, object): """ get all method properties of an object """ objects = [] for attr in dir(object): prop = getattr(object, attr) if not attr.startswith("__") and (self._underscore or attr.strip("_") == attr): objects += [(attr, prop)] return objects def getObjectRef(self, object): """ get object and resolve references """ typshort = self.getShortType(object) ref_types = [ "edm::Ref", "edm::RefProd", "edm::RefToBase", "edm::RefToBaseProd", "edm::Ptr" ] value = object ref = False if typshort in ref_types: try: if hasattr(object, "isNull") and object.isNull(): value = "ERROR: " + self.getType( object) + " object is null" elif hasattr(object, "isAvailable") and not object.isAvailable(): value = "ERROR: " + self.getType( object) + " object is not available" else: value = object.get() if type(value) == type(None): value = "ERROR: Could not get " + self.getType(object) else: ref = True except Exception as message: value = "ERROR: " + str(message) return value, ref def getObjectContent(self, object): """ get string value of a method """ if not callable(object): return object else: typ = "" if not object.__doc__ or str(object.__doc__) == "": return "ERROR: Empty __doc__ string" docs = str(object.__doc__).split("\n") for doc in docs: parameters = [] for p in doc[doc.find("(") + 1:doc.find(")")].split(","): if p != "" and not "=" in p: parameters += [p] if len(parameters) != 0: continue typestring = doc[:doc.find("(")] split_typestring = typestring.split(" ") templates = 0 end_typestring = 0 for i in reversed(range(len(split_typestring))): templates += split_typestring[i].count("<") templates -= split_typestring[i].count(">") if templates == 0: end_typestring = i break typ = " ".join(split_typestring[:end_typestring]) hidden_types = ["iterator", "Iterator"] root_types = ["ROOT::"] if typ == "" or "void" in typ or True in [ t in typ for t in hidden_types ]: return None from ROOT import TClass if True in [t in typ for t in root_types] and TClass.GetClass(typ) == None: return "ERROR: Cannot display object of type " + typ try: object = object() value = object except Exception as message: value = "ERROR: " + str(message) if "Buffer" in str(type(value)): return "ERROR: Cannot display object of type " + typ else: return value def isVectorObject(self, object): typ = self.getShortType(object) return typ == "list" or typ[-6:].lower() == "vector" or typ[-3:].lower( ) == "map" or typ[-10:].lower() == "collection" or hasattr( object, "size") def compareObjects(self, a, b): same = False if hasattr(a,"px") and hasattr(a,"py") and hasattr(a,"pz") and hasattr(a,"energy") and \ hasattr(b,"px") and hasattr(b,"py") and hasattr(b,"pz") and hasattr(b,"energy"): same = a.px() == b.px() and a.py() == b.py() and a.pz() == b.pz( ) and a.energy() == b.energy() return same def getDaughterObjects(self, object): """ get list of daughter objects from properties """ objects = [] # subobjects objectdict = {} hidden_attr = [ "front", "back", "IsA", "clone", "masterClone", "masterClonePtr", "mother", "motherRef", "motherPtr", "daughter", "daughterRef", "daughterPtr", "is_back_safe" ] broken_attr = [] #["jtaRef"] for attr1, property1 in self.getObjectProperties(object): if attr1 in hidden_attr: pass elif attr1 in broken_attr: objectdict[attr1] = ("ERROR: Cannot read property", False) else: (value, ref) = self.getObjectRef(self.getObjectContent(property1)) if not isinstance(value, type(None)) and ( not self.isVectorObject(object) or self._propertyType(value) != None): objectdict[attr1] = (value, ref) for name in sorted(objectdict.keys()): objects += [(name, objectdict[name][0], objectdict[name][1], self._propertyType(objectdict[name][0]))] # entries in vector if self.isVectorObject(object): n = 0 for o in all(object): (value, ref) = self.getObjectRef(o) typ = self._propertyType(value) if typ != None: name = "[" + str(n) + "]" elif "GenParticle" in str(value): name = defaultParticleDataList.getNameFromId(value.pdgId()) else: name = self.getType(value) + " [" + str(n) + "]" objects += [(name, value, ref, typ)] n += 1 # read candidate relations for name, mother, ref, propertyType in objects: if hasattr(mother, "numberOfDaughters") and hasattr( mother, "daughter"): try: for n in range(mother.numberOfDaughters()): daughter = mother.daughter(n) found = False for na, da, re, st in objects: if self.compareObjects(daughter, da): daughter = da found = True if not id(mother) in self._edmDaughterRelations.keys(): self._edmDaughterRelations[id(mother)] = [] self._edmDaughterRelations[id(mother)] += [daughter] if not id(daughter) in self._edmMotherRelations.keys(): self._edmMotherRelations[id(daughter)] = [] self._edmMotherRelations[id(daughter)] += [mother] except Exception as message: logging.error("Cannot read candidate relations: " + str(message)) return objects def _propertyType(self, value): if type(value) in (bool, ): return "Boolean" elif type(value) in (int, long): return "Integer" elif type(value) in (float, ): return "Double" elif type(value) in (complex, str, unicode): return "String" else: return None def properties(self, object): """ Make list of all properties """ logging.debug(__name__ + ": properties: " + self.label(object)) properties = [] objectproperties = {} objectproperties_sorted = [] if id(object) in self._edmChildrenObjects.keys(): for name, value, ref, propertyType in self._edmChildrenObjects[id( object)]: if propertyType != None: objectproperties[name] = (value, propertyType) objectproperties_sorted += [name] properties += [("Category", "Object info", "")] shortlabel = self.getShortLabel(object) properties += [("String", "label", shortlabel)] properties += [("String", "type", self.getType(object))] objectlabel = self.getObjectLabel(object) if objectlabel != "": properties += [("String", "object", objectlabel)] branchlabel = self.label(self.getBranch(object)) if shortlabel.strip(".") != branchlabel.strip("."): properties += [("String", "branch", branchlabel)] else: properties += [("Category", "Branch info", "")] properties += [("String", "Type", branchlabel.split("_")[0])] properties += [("String", "Label", branchlabel.split("_")[1])] properties += [("String", "Product", branchlabel.split("_")[2])] properties += [("String", "Process", branchlabel.split("_")[3])] for property in ["pdgId", "charge", "status"]: if property in objectproperties.keys(): properties += [(objectproperties[property][1], property, objectproperties[property][0])] del objectproperties[property] if "px" in objectproperties.keys(): properties += [("Category", "Vector", "")] for property in [ "energy", "px", "py", "pz", "mass", "pt", "eta", "phi", "p", "theta", "y", "rapidity", "et", "mt", "mtSqr", "massSqr" ]: if property in objectproperties.keys(): properties += [(objectproperties[property][1], property, objectproperties[property][0])] del objectproperties[property] if "x" in objectproperties.keys(): properties += [("Category", "Vector", "")] for property in ["x", "y", "z"]: if property in objectproperties.keys(): properties += [(objectproperties[property][1], property, objectproperties[property][0])] del objectproperties[property] if False in [ str(value[0]).startswith("ERROR") for value in objectproperties.values() ]: properties += [("Category", "Values", "")] for property in objectproperties_sorted: if property in objectproperties.keys(): if not str( objectproperties[property][0]).startswith("ERROR"): properties += [ (objectproperties[property][1], property, objectproperties[property][0]) ] del objectproperties[property] if len(objectproperties.keys()) > 0: properties += [("Category", "Errors", "")] for property in objectproperties_sorted: if property in objectproperties.keys(): properties += [(objectproperties[property][1], property, objectproperties[property][0])] return tuple(properties) def readObjectsRecursive(self, mother, label, edmobject, levels=1): """ read edm objects recursive """ logging.debug(__name__ + ": readObjectsRecursive (levels=" + str(levels) + "): " + label) # save object information if not id(edmobject) in self._edmLabel.keys(): if not isinstance(edmobject, (int, float, long, complex, str, unicode, bool)): # override comparison operator of object try: type(edmobject).__eq__ = eq type(edmobject).__ne__ = ne except: pass self._edmLabel[id(edmobject)] = label self._edmParent[id(edmobject)] = mother self._edmChildren[id(edmobject)] = [] if not id(mother) in self._edmChildren.keys(): self._edmChildren[id(mother)] = [] self._edmChildren[id(mother)] += [edmobject] if levels == 0: # do not read more daughters return [edmobject], True else: # read daughters return self.readDaughtersRecursive(edmobject, [edmobject], levels) def readDaughtersRecursive(self, edmobject, objects, levels=1): """ read daughter objects of an edmobject """ logging.debug(__name__ + ": readDaughtersRecursive (levels=" + str(levels) + "): " + str(edmobject)) # read children information if not id(edmobject) in self._edmChildrenObjects.keys(): self._edmChildrenObjects[id(edmobject)] = self.getDaughterObjects( edmobject) # analyze children information ok = True daughters = self._edmChildrenObjects[id(edmobject)] i = 0 for name, daughter, ref, propertyType in daughters: # create children objects if propertyType == None: if ref: label = "* " + name else: label = name if id(edmobject) in self._edmLabel.keys( ) and self._edmLabel[id(edmobject)] != "": label = self._edmLabel[id(edmobject)] + "." + label (res, ok) = self.readObjectsRecursive(edmobject, label, daughter, levels - 1) objects += res i += 1 if i > self.maxDaughters: logging.warning( "Did not read all daughter objects. Maximum is set to " + str(self.maxDaughters) + ".") return objects, False return objects, ok def read(self, object, levels=1): """ reads contents of a branch """ logging.debug(__name__ + ": read") if isinstance(object, BranchDummy): if hasattr(object, "product"): return object.product if not self._events: return object try: self._events.getByLabel(object.branchtuple[2], object.branchtuple[3], object.branchtuple[4], object.branchtuple[1]) if object.branchtuple[1].isValid(): product = object.branchtuple[1].product() if not isinstance( product, (int, float, long, complex, str, unicode, bool)): # override comparison operator of object try: type(product).__eq__ = eq type(product).__ne__ = ne except: pass self._dataObjects.insert(self._dataObjects.index(object), product) self._dataObjects.remove(object) self._edmLabel[id(product)] = object.branchtuple[0] object.product = product object = product else: self._edmChildrenObjects[id(object)] = [ ("ERROR", "ERROR: Branch is not valid.", False, True) ] logging.info("Branch is not valid: " + object.branchtuple[0] + ".") object.invalid = True return object except Exception as e: self._edmChildrenObjects[id(object)] = [ ("ERROR", "ERROR: Unable to read branch : " + str(e), False, True) ] object.unreadable = True logging.warning("Unable to read branch " + object.branchtuple[0] + " : " + exception_traceback()) return object if self.isRead(object, levels): return object if levels > 0: self.readDaughtersRecursive(object, [], levels) return object def goto(self, index): """ Goto event number index in file. """ self._eventIndex = index - 1 self._edmLabel = {} self._edmChildren = {} self._edmMotherRelations = {} self._edmDaughterRelations = {} self._edmChildrenObjects = {} if self._events: self._events.to(self._eventIndex) self._dataObjects = [] i = 0 for branchtuple in self._filteredBranches: branch = BranchDummy(branchtuple) self._dataObjects += [branch] self._edmLabel[id(branch)] = branchtuple[0] if not self._readOnDemand: self.read(branch, self.maxLevels) i += 1 if self._filterBranches and self._events: self.setFilterBranches(True) return True def eventNumber(self): return self._eventIndex + 1 def numberOfEvents(self): return self._numEvents def topLevelObjects(self): return self._dataObjects def open(self, filename=None): """ Open edm file and show first event """ self._filename = filename self._branches = [] if os.path.splitext(filename)[1].lower() == ".txt": file = open(filename) for line in file.readlines(): if "\"" in line: linecontent = [ l.strip(" \n").rstrip(".") for l in line.split("\"") ] self._branches += [ (linecontent[0] + "_" + linecontent[1] + "_" + linecontent[3] + "_" + linecontent[5], None, linecontent[1], linecontent[3], linecontent[5]) ] else: linecontent = line.strip("\n").split(" ")[0].split("_") if len(linecontent) > 3: self._branches += [ (linecontent[0] + "_" + linecontent[1] + "_" + linecontent[2] + "_" + linecontent[3], None, linecontent[1], linecontent[2], linecontent[3]) ] elif os.path.splitext(filename)[1].lower() == ".root": from DataFormats.FWLite import Events, Handle self._events = Events(self._filename) self._numEvents = self._events.size() branches = self._events.object().getBranchDescriptions() for branch in branches: try: branchname = branch.friendlyClassName( ) + "_" + branch.moduleLabel( ) + "_" + branch.productInstanceName( ) + "_" + branch.processName() handle = Handle(branch.fullClassName()) self._branches += [ (branchname, handle, branch.moduleLabel(), branch.productInstanceName(), branch.processName()) ] except Exception as e: logging.warning("Cannot read branch " + branchname + ":" + str(e)) self._branches.sort(lambda x, y: cmp(x[0], y[0])) self._filteredBranches = self._branches[:] return self.goto(1) def particleId(self, object): charge = self.property(object, "pdgId") if charge == None: charge = 0 return charge def isQuark(self, object): particleId = self.particleId(object) if not particleId: return False return defaultParticleDataList.isQuarkId(particleId) def isLepton(self, object): particleId = self.particleId(object) if not particleId: return False return defaultParticleDataList.isLeptonId(particleId) def isGluon(self, object): particleId = self.particleId(object) if not particleId: return False return defaultParticleDataList.isGluonId(particleId) def isBoson(self, object): particleId = self.particleId(object) if not particleId: return False return defaultParticleDataList.isBosonId(particleId) def isPhoton(self, object): particleId = self.particleId(object) if not particleId: return False if not hasattr(defaultParticleDataList, "isPhotonId"): return False return defaultParticleDataList.isPhotonId(particleId) def isHiggs(self, object): particleId = self.particleId(object) if not particleId: return False if not hasattr(defaultParticleDataList, "isHiggsId"): return False return defaultParticleDataList.isHiggsId(particleId) def lineStyle(self, object): particleId = self.particleId(object) if hasattr(defaultParticleDataList, "isPhotonId" ) and defaultParticleDataList.isPhotonId(particleId): return self.LINE_STYLE_WAVE elif defaultParticleDataList.isGluonId(particleId): return self.LINE_STYLE_SPIRAL elif defaultParticleDataList.isBosonId(particleId): return self.LINE_STYLE_DASH return self.LINE_STYLE_SOLID def color(self, object): particleId = self.particleId(object) if defaultParticleDataList.isLeptonId(particleId): return QColor(244, 164, 96) elif defaultParticleDataList.isQuarkId(particleId): return QColor(0, 100, 0) elif hasattr( defaultParticleDataList, "isHiggsId") and defaultParticleDataList.isHiggsId(particleId): return QColor(247, 77, 251) elif defaultParticleDataList.isBosonId(particleId): return QColor(253, 74, 74) return QColor(176, 179, 177) def charge(self, object): charge = self.property(object, "charge") if charge == None: charge = 0 return charge def linkMother(self, object, mother): pass def linkDaughter(self, object, daughter): pass def underscoreProperties(self): return self._underscore def setUnderscoreProperties(self, check): self._underscore = check def filterBranches(self): return self._filterBranches def setFilterBranches(self, check): if not self._events: return True self._filterBranches = check if check: for branch in self._dataObjects[:]: result = self.read(branch, 0) if isinstance(result, BranchDummy): self._dataObjects.remove(result) if hasattr(result, "invalid"): self._filteredBranches.remove(result.branchtuple) return True else: self._filteredBranches = self._branches[:] self.goto(self.eventNumber()) return False def filteredBranches(self): return self._filteredBranches
#! /usr/bin/env python import ROOT from DataFormats.FWLite import Events, Handle import FWCore.ParameterSet.VarParsing as VarParsing options = VarParsing.VarParsing ('analysis') options.parseArguments() events = Events(options) print "In total there are %d events" % events.size() print "Trying an event loop" for i,event in enumerate(events): print "I am processing an event" if i > 10: break print "Done with the event loops"
from random import gauss, choice, sample from string import letters # load FWLite C++ libraries ROOT.gSystem.Load("libFWCoreFWLite.so") ROOT.gSystem.Load("libDataFormatsFWLite.so") ROOT.AutoLibraryLoader.enable() # import FWlite python objects from DataFormats.FWLite import Handle, Events # open file (you can use # 'edmFileUtil -d /store/whatever.root' # to get the physical file name) events = Events( "/hdfs/TopQuarkGroup/test/TT_Tune4C_13TeV-pythia8-tauola_PU_S14_PAT_miniAOD.root" ) f = root_open("test.root", "recreate") # define the model class Muon(TreeModel): eta = FloatCol(default=-1111.) phi = FloatCol(default=-1111.) pt = FloatCol() class Event(Muon.prefix('muon1_'), Muon.prefix('muon2_')): run_number = IntCol()
files = filelist print len(files), " total filenames" if not TXT_FILE_INPUT: print "getting all files at this local path" files = glob.glob(sys.argv[1]) # Make TFile to hold histograms if len(sys.argv) >= 4: outputfilename = sys.argv[3] else: outputfilename = "histos.root" outputfile = ROOT.TFile(outputfilename, "recreate") # Make event collection events = Events(files) # Make Handles for objects outside event loop print datetime.datetime.now(), " Creating handles..." ak4handle, ak4label = Handle("std::vector<pat::Jet>"), "slimmedJets" pfcandhandle, pfcandlabel = Handle("std::vector<pat::PackedCandidate>"), "packedPFCandidates" genhandle, genlabel = Handle("vector<reco::GenParticle>"), "prunedGenParticles" pvhandle, pvlabel = Handle("vector<reco::Vertex>"), "offlineSlimmedPrimaryVertices" # Book Histograms num_pfcands = ROOT.TH1F('num_pfcands', 'Number of PF cands', 100, 0, 5000) pvqual = ROOT.TH1F('pvqual', 'PV Quality of PF cands part of CH pair', 10, 0, 10) impact = ROOT.TH1F('impact', 'impact param dxy()', 200, -0.1, 0.1) impact_sig = ROOT.TH1F('impact_sig', 'impact param significance dxyError()', 100, 0, 0.1) num_pairs = ROOT.TH1F('num_pairs', 'Number of pairs of CH+/CH- within DR', 80, 0, 80)
def count(): ''' Counts the number of events where one of two scenarios occur: --- Max mjj is for two leading jets --- Max mjj is for other jet combos Counts the number of events for three cases for leading two jets: --- Two central jets --- Two forward jets --- Mixed (one central, one forward jet) ''' jets, jetLabel = Handle('std::vector<pat::Jet>'), 'slimmedJets' events = Events( 'root://cmsxrootd.fnal.gov///store/mc/RunIIFall17MiniAODv2/VBF_HToInvisible_M125_13TeV_TuneCP5_powheg_pythia8/MINIAODSIM/PU2017_12Apr2018_94X_mc2017_realistic_v14-v1/00000/14347E60-56F2-E811-81F4-24BE05C6C7E1.root' ) mother_dict = {} counter_twoLeadingJets = { } #Counts the number of events where mjj is max for the two leading jets counter_otherCombos = { } #Counts the number of events where mjj is max for other combinations mjjValues_leadingPair = [ ] #Stores max mjj for the case where max mjj comes from leading two pairs mjjValues_otherMaxPair = [ ] #Stores max mjj for the case where max mjj comes from other combos ptValues1_leadingPair = [ ] #Stores jet_pt[0] for the case where max mjj comes from leading two pairs ptValues2_leadingPair = [ ] #Stores jet_pt[1] for the case where max mjj comes from leading two pairs leadingJetPtValues_otherMaxPair = [ ] #Stores jet_pt[0] for the case where max mjj comes from other combos trailingJetPtValues_otherMaxPair = [ ] #Stores jet_pt[1] for the case where max mjj comes from other combos ptValues1_otherMaxPair = [ ] #Stores jet_pt of jet with larger pt in the case where this pair have the max mjj ptValues2_otherMaxPair = [ ] #Stores jet_pt of jet with smaller pt in the case where this pair have the max mjj cases = ['twoCentralJets', 'twoForwardJets', 'mixed'] for case in cases: counter_twoLeadingJets[case] = 0 counter_otherCombos[case] = 0 mother_dict['counter_twoLeadingJets'] = counter_twoLeadingJets mother_dict['counter_otherCombos'] = counter_otherCombos mother_dict['mjjValues_leadingPair'] = mjjValues_leadingPair mother_dict['mjjValues_otherMaxPair'] = mjjValues_otherMaxPair mother_dict['ptValues1_leadingPair'] = ptValues1_leadingPair mother_dict['ptValues2_leadingPair'] = ptValues2_leadingPair mother_dict[ 'leadingJetPtValues_otherMaxPair'] = leadingJetPtValues_otherMaxPair mother_dict[ 'trailingJetPtValues_otherMaxPair'] = trailingJetPtValues_otherMaxPair mother_dict['ptValues1_otherMaxPair'] = ptValues1_otherMaxPair mother_dict['ptValues2_otherMaxPair'] = ptValues2_otherMaxPair ##################### #Event loop starts here ##################### for iev, event in enumerate(events): #if iev == 10: break #For testing if iev % 1000 == 0: print('Working on event {}'.format(iev)) event.getByLabel(jetLabel, jets) ###################### #Implementing tight jet ID, 2017 recommendations ###################### jets_ = jets.product() AK4_tightJets = [] for jet in jets_: if isTightJet(jet): AK4_tightJets.append(jet) nJet = len(AK4_tightJets) if nJet < 2: continue #Discard the events with number of jets smaller than 2 mjj_values = invMassJetCombos( AK4_tightJets) #Get all the mjj values for all possible combos maxCombo = getMaxCombo( mjj_values ) #Get the jet pair for which the maximum mjj happens to be #print('Event: {0}, maxCombo: {1}'.format(iev, maxCombo)) #################### #Counting the number of cases #################### leadJetEta = AK4_tightJets[0].eta() trailJetEta = AK4_tightJets[1].eta() if abs(leadJetEta) > 2.5 and abs(trailJetEta) > 2.5: case = 'twoForwardJets' elif abs(leadJetEta) <= 2.5 and abs(trailJetEta) <= 2.5: case = 'twoCentralJets'