def Count(): events = FWLite.Events(sys.argv[1:]) geninfo = FWLite.Handle('GenEventInfoProduct') lheinfo = FWLite.Handle('LHEEventProduct') label_gen = 'generator' #label_lhe = 'externalLHEProducer' label_lhe = 'source' weight_sum_gen = 0 weight_sum_lhe = 0 event_sum = 0 neg_sum = 0 for event in events: event.getByLabel(label_gen, geninfo) event.getByLabel(label_lhe, lheinfo) weight_gen = geninfo.product().weight() weight_lhe = lheinfo.product().originalXWGTUP() weight_sum_gen += weight_gen weight_sum_lhe += weight_lhe #print lheinfo.product().weights().at(0) event_sum += 1 if weight_gen < 0.: neg_sum += 1 if event_sum % 10000 == 0: print event_sum print "GEN: sum of event weights / number of events ", weight_sum_gen * 1.0 / event_sum print "LHE: sum of event weights / number of events ", weight_sum_lhe * 1.0 / event_sum print "#neg./#all. ", neg_sum * 1.0 / event_sum print "#pos-#neg/#pos+#neg ", (event_sum - 2 * neg_sum) * 1.0 / (event_sum) print "sum of all weighted events: ", weight_sum_gen
def analysisLoop(inputFile, sampleLabel, histos, effs, rocs): muons = fwlite.Handle("std::vector<pat::Muon>") vtxs = fwlite.Handle("std::vector<reco::Vertex>") events = fwlite.Events(inputFile) for iEv, event in enumerate(events): if iEv % 10000 == 0: print "[muonIsolation.py] processed %i %s entries" % (iEv, sampleLabel) if iEv > MAX_EVENTS: break event.getByLabel("slimmedMuons", muons) event.getByLabel("offlineSlimmedPrimaryVertices", vtxs) nVtx = vtxs.product().size() for mu in muons.product(): muPt = mu.pt() muEta = mu.eta() muPhi = mu.phi() if muPt < MIN_PT: continue pfIso04 = mu.pfIsolationR04() pfRelIso = (pfIso04.sumChargedHadronPt + \ max(0., pfIso04.sumPhotonEt + pfIso04.sumNeutralHadronEt - 0.5 * pfIso04.sumPUPt)) / muPt # For DY we still use flavour to # ensure we look at prompt muons, this is not # true for QCD, hence the following logic isGoodMu = (sampleLabel == "QCD" or mu.simFlavour() == 13) # We want to study isolation for # events that already pass and ID muIsTight = mu.passed(mu.CutBasedIdTight) if muIsTight and isGoodMu: histos["hPt%s" % sampleLabel].Fill(muPt) histos["hNVtx%s" % sampleLabel].Fill(nVtx) histos["hPfRelIso%s" % sampleLabel].Fill(min(pfRelIso, 0.99)) rocs["pfRelIso"].fill(sampleLabel, pfRelIso)
def Count(): #events = FWLite.Events(sys.argv[1:]) #events = FWLite.Events(file_names_[1:100]) geninfo = FWLite.Handle('GenEventInfoProduct') lheinfo = FWLite.Handle('LHEEventProduct') label_gen = 'generator' #label_lhe = 'externalLHEProducer' label_lhe = 'externalLHEProducer' weight_sum_gen = 0 weight_sum_lhe = 0 event_sum = 0 neg_sum = 0 for file_name in file_names_: if event_sum > 1000000: break events = None try: events = FWLite.Events(file_name) for event in events: if event_sum % 1000 == 0: print event_sum event.getByLabel(label_gen, geninfo) event.getByLabel(label_lhe, lheinfo) weight_gen = geninfo.product().weight() weight_lhe = lheinfo.product().originalXWGTUP() weight_sum_gen += weight_gen weight_sum_lhe += weight_lhe #print lheinfo.product().weights().at(0) event_sum += 1 if weight_gen < 0.: neg_sum += 1 #if event_sum % 10000 == 0: #print event_sum except TypeError: continue print "GEN: sum of event weights / number of events ", weight_sum_gen * 1.0 / event_sum print "LHE: sum of event weights / number of events ", weight_sum_lhe * 1.0 / event_sum print "#neg./#all. ", neg_sum * 1.0 / event_sum print "#pos-#neg/#pos+#neg ", (event_sum - 2 * neg_sum) * 1.0 / (event_sum) print "sum of all weighted events: ", weight_sum_gen
# # Parse ID of event to be selected # eventIDRegex = re.compile(r'^(\d+):(\d+):(\d+)$') # match = re.match(eventIDRegex, args.event) # if not match: # raise RuntimeError('Failed to parse event ID "{}".'.format(args.event)) # else: # eventToSelect = (int(match.group(1)), int(match.group(2)), int(match.group(3))) # Allow loading CMSSW classes ROOT.gSystem.Load('libFWCoreFWLite.so') ROOT.FWLiteEnabler.enable() ROOT.gSystem.Load('libDataFormatsFWLite.so') # Open input file events = FWLite.Events(args.inputFile) # Read events triggerResultsHandle = FWLite.Handle('edm::TriggerResults') triggerAcceptDict = {} for event in events: # # Skip to the desired event # if event.eventAuxiliary().run() != eventToSelect[0] or \ # event.eventAuxiliary().luminosityBlock() != eventToSelect[1] or \ # event.eventAuxiliary().event() != eventToSelect[2]: # continue # Read trigger results in the selected event event.getByLabel(args.label, triggerResultsHandle)
def dumpTheFloat( fileName, variables ): events = fwlite.Events( fileName ) # create handleEl outside of loop handleEl = fwlite.Handle ('std::vector<pat::Electron>') handleMu = fwlite.Handle ('std::vector<pat::Muon>') # a label is just a tuple of strings that is initialized just # like and edm::InputTag labelEl = ("boostedElectrons") labelMu = ("boostedMuons") if len(variables)==0: elDone = False muDone = False for event in events: event.getByLabel(labelEl,handleEl) event.getByLabel(labelMu,handleMu) electrons = handleEl.product() muons = handleMu.product() # print len(electrons) # print len(muons) hline = '-'*80 if not elDone: for e in electrons: print hline names = e.userFloatNames() for name in names: print name, e.userFloat(name) print hline for elId in e.electronIDs(): print elId.first, elId.second elDone = True break if not muDone: for m in muons: print hline names = m.userFloatNames() for name in names: print name, m.userFloat(name) muDone = True break if elDone and muDone: break; else: print '|'.join([v.ljust(20) for v in variables]) for event in events: event.getByLabel(labelEl,handleEl) event.getByLabel(labelMu,handleMu) electrons = handleEl.product() muons = handleMu.product() for e in electrons: names = e.userFloatNames() for v in variables: if not v in names: raise RuntimeError(v+" not found!") print '|','| '.join([str(e.userFloat(v)).ljust(20) for v in variables])
#print d for f in d['file']: #print f #if not 'nevents' in f: #continue files.append(file_prefix + f['name']) return files files = get_first_file(str(sys.argv[1]).replace('"', '')) #print files file_names = [str(file) for file in files] print file_names sample = str(sys.argv[2]) events = FWLite.Events(file_names) met = FWLite.Handle('std::vector<pat::MET>') eventinfo = FWLite.Handle('GenEventInfoProduct') label = 'slimmedMETs' root_file = ROOT.TFile( "/nfs/dust/cms/user/mwassmer/DarkMatter/useful_scripts/met_histos_" + sample + ".root", "RECREATE") hist = ROOT.TH1D("met_pt_unw", "met_pt_unweighted", 150, 0., 2000.) hist_w = ROOT.TH1D("met_pt_w", "met_pt_weighted", 150, 0., 2000.) hist.Sumw2() hist_w.Sumw2() canvas = ROOT.TCanvas() for number, event in enumerate(events): event.getByLabel(label, met) event.getByLabel('generator', eventinfo) met_pt = met.product()[0].pt()
import DataFormats.FWLite as fwlite import numpy as np ## Open miniAOD fileName = 'test.root' events = fwlite.Events(fileName) ## Create handle outside of loop handle = fwlite.Handle("vector<pat::Jet>") ## Collection label label = ('slimmedJetsAK8') ## Loop over events for ievt, event in enumerate(events): # If you just want to loop over a limited number of events #if ievt == 5: break # Example of code # Looking at AK8 jet pT for events having more than 4 AK8 jets with pT>170 GeV event.getByLabel(label, handle) jets = handle.product() njets = jets.size() pts = np.array([jets[ijet].pt() for ijet in range(njets)]) nJetPtGt170 = np.sum(pts >= 170) if nJetPtGt170 > 3: print("\n%d jets in event %d" % (njets, ievt)) for ijet in range(njets): print(jets[ijet].pt())
import sys import optparse if __name__ == '__main__': usage = 'usage: %prog [options]' parser = optparse.OptionParser(usage) (opt, args) = parser.parse_args() sys.argv.append('-b') ROOT.gROOT.SetBatch() # don't pop up canvases fileName = args[0] events = fwlite.Events( fileName ) # create handleEl outside of loop handleLHE = fwlite.Handle('LHEEventProduct') handleGens = fwlite.Handle("std::vector<reco::GenParticle>") # a label is just a tuple of strings that is initialized just # like and edm::InputTag #labelGens = ('prunedGenParticles') labelGens = ('genParticles') for event in events:
# this script print the trigger paths / filters of a MINIAOD file you give as an argument # trigger paths if you use TriggerResults::HLT # filters if you use TriggerResults::RECO for data or TriggerResults::PAT for mc import ROOT import sys from DataFormats import FWLite ROOT.gSystem.Load('libFWCoreFWLite.so') ROOT.FWLiteEnabler.enable() ROOT.gSystem.Load('libDataFormatsFWLite.so') events = FWLite.Events(sys.argv[1]) triggerResultsHandle = FWLite.Handle('edm::TriggerResults') label = 'TriggerResults::HLT' #label = 'TriggerResults::RECO' #label = 'TriggerResults::PAT' triggerObjects, triggerObjectLabel = FWLite.Handle( "std::vector<pat::TriggerObjectStandAlone>"), "selectedPatTrigger" k = 0 for event in events: if k > 0: break event.getByLabel(label, triggerResultsHandle) event.getByLabel(triggerObjectLabel, triggerObjects) triggerResults = triggerResultsHandle.product() triggerNames = event.object().triggerNames(triggerResults) for i in range(triggerResults.size()): #if not "MET" in triggerNames.triggerName(i): #continue print '#{0:03} {2:5} {1}'.format(i, triggerNames.triggerName(i), str(triggerResults.accept(i))) #for j,to in enumerate(triggerObjects.product()): #print j
# # Parse ID of event to be selected # eventIDRegex = re.compile(r'^(\d+):(\d+):(\d+)$') # match = re.match(eventIDRegex, args.event) # if not match: # raise RuntimeError('Failed to parse event ID "{}".'.format(args.event)) # else: # eventToSelect = (int(match.group(1)), int(match.group(2)), int(match.group(3))) # Allow loading CMSSW classes ROOT.gSystem.Load('libFWCoreFWLite.so') ROOT.FWLiteEnabler.enable() ROOT.gSystem.Load('libDataFormatsFWLite.so') # Open input file events = FWLite.Events(args.inputFile) # Read events fedRawDataCollectionHandle = FWLite.Handle('FEDRawDataCollection') triggerAcceptDict = {} for event in events: # # Skip to the desired event # if event.eventAuxiliary().run() != eventToSelect[0] or \ # event.eventAuxiliary().luminosityBlock() != eventToSelect[1] or \ # event.eventAuxiliary().event() != eventToSelect[2]: # continue # Read trigger results in the selected event event.getByLabel(args.label, fedRawDataCollectionHandle)
import DataFormats.FWLite as fwlite import argparse parser = argparse.ArgumentParser() parser.add_argument("rtfile", type=str, help="EDM file") args = parser.parse_args() if "/store" in args.rtfile[:6]: args.rtfile = "root://cms-xrd-global.cern.ch/"+args.rtfile lumis = fwlite.Lumis(args.rtfile) handle = fwlite.Handle("GenLumiInfoHeader") lumis.getByLabel("generator", handle) genlumi = handle.product() print "Length of weight names is", len(genlumi.weightNames())
ROOT.TH1.SetDefaultSumw2(True) try: inputfiles = glob(sys.argv[1]) except: # inputfiles = glob("/afs/desy.de/user/s/spak/dust/DisappearingTracks/FastSim/output/smallchunks/SUS-RunIISummer15GS-00734_T2btLLFastSim_*.root") inputfiles = [ "root://xrootd-cms.infn.it//store/mc/RunIISummer16DR80Premix/SMS-T2bt-LLChipm_ctau-200_mLSP-900_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/PUMoriond17_longlived_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v2/260000/DED79FC2-74A5-E911-8BA3-002590E39D90.root", "root://xrootd-cms.infn.it//store/mc/RunIISummer16DR80Premix/SMS-T2bt-LLChipm_ctau-200_mLSP-900_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/PUMoriond17_longlived_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v2/260000/32262683-5EA5-E911-BFC3-3C4A92F8DC66.root", "root://xrootd-cms.infn.it//store/mc/RunIISummer16DR80Premix/SMS-T2bt-LLChipm_ctau-200_mLSP-900_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/PUMoriond17_longlived_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v2/260000/08D82DA4-5DA5-E911-8F9A-A0369FE2C22E.root", "root://xrootd-cms.infn.it//store/mc/RunIISummer16DR80Premix/SMS-T2bt-LLChipm_ctau-200_mLSP-900_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/PUMoriond17_longlived_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v2/260000/B64B10BA-6BA5-E911-B5B2-AC1F6B0DE348.root", "root://xrootd-cms.infn.it//store/mc/RunIISummer16DR80Premix/SMS-T2bt-LLChipm_ctau-200_mLSP-900_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/AODSIM/PUMoriond17_longlived_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v2/260000/0AABDACD-7AA5-E911-8B31-AC1F6B0DE33E.root", ] events = fwlite.Events(inputfiles) primaryVertices = fwlite.Handle("std::vector<reco::Vertex>") genParticles = fwlite.Handle("std::vector<reco::GenParticle>") tracks_handle = fwlite.Handle("std::vector<reco::Track>") dEdxPixelTrackHandle = fwlite.Handle("edm::ValueMap<reco::DeDxData>") dEdxStripsTrackHandle = fwlite.Handle("edm::ValueMap<reco::DeDxData>") #label_dEdXtrack = 'dedxPixelHarmonic2' #label_dEdXtrack = 'dedxHarmonic2' tlegend = ROOT.TLegend(0.17, 0.77, 0.51, 0.88) outDir = './LLchargino' if not os.path.exists(outDir): os.system('mkdir -p ' + outDir)
import DataFormats.FWLite as fwlite N_EVENTS = 5 events = fwlite.Events("/gpfs/ddn/cms/user/cmsdas/2019/muon/data/DY.root") muons = fwlite.Handle("std::vector<pat::Muon>") for iEv, event in enumerate(events): if iEv >= N_EVENTS: break print "***** Event", iEv event.getByLabel("slimmedMuons", muons) print "Muon collection size:", len(muons.product()) for iMu, mu in enumerate(muons.product()): print " Muon #:", iMu print "\t===== KINEMATICS:" print "\t charge:", mu.charge() print "\t pT:", mu.pt() print "\t phi:", mu.phi() print "\t eta:", mu.eta() print "\t===== ID VARIABLES:" print "\t segment compatibility:", mu.segmentCompatibility() print "\t===== ID SELECTIONS:" print "\t is TIGHT:", mu.passed(mu.CutBasedIdTight) print "\t===== ISOLATION:" print "\t TRK based relIso:", mu.isolationR03().sumPt / mu.pt() print "\t===== SIM INFO:" print "\t sim flavour:", mu.simFlavour()
ROOT.FWLiteEnabler.enable() ROOT.gSystem.Load('libDataFormatsFWLite.so') ROOT.gROOT.SetBatch(True) def FillVectorPtEta(vector, hist_pt, hist_eta, ptmin=-1., etamax=999.): for element in vector: if element.pt() > ptmin and abs(element.eta()) < etamax: hist_pt.Fill(element.pt()) hist_eta.Fill(element.eta()) files = args #print(files) events = FWLite.Events(files) #eventinfo_handle = FWLite.Handle("edm::EventAuxiliary") pfmet_handle = FWLite.Handle("std::vector<pat::MET") puppimet_handle = FWLite.Handle("std::vector<pat::MET") ak15jet_handle = FWLite.Handle("std::vector<pat::Jet>") ak4jet_handle = FWLite.Handle("std::vector<pat::Jet>") ak4puppijet_handle = FWLite.Handle("std::vector<pat::Jet>") electron_handle = FWLite.Handle("std::vector<pat::Electron>") muon_handle = FWLite.Handle("std::vector<pat::Muon>") photon_handle = FWLite.Handle("std::vector<pat::Photon>") #eventinfo_label = "EventAuxiliary" pfmet_label = "slimmedMETs::SKIM" puppimet_label = "slimmedMETsPuppi::SKIM" ak15jet_label = "AK15PFPuppiComplete"