Пример #1
0
 def __init__(self, label, type, mayFail=False, fallbackLabel=None):
     '''Note: label can be a tuple : (module_label, collection_label, process)'''
     self.label = label
     self.fallbackLabel = fallbackLabel
     self.type = type
     self.mayFail = mayFail
     Handle.__init__(self, self.type)
Пример #2
0
    def processSample(self):
        self.nTot = 0
        self.nFailPF = 0
        self.nPFMatched = 0

        print self.files
        events = Events(self.files)

        vertices = Handle("std::vector<reco::Vertex>")
        leps = Handle("std::vector<{}>".format(self.__class__.lepTypeStr))
        pfCands = Handle("std::vector<pat::PackedCandidate>")

        for iEv, ev in enumerate(events):
            if iEv % 5000 == 0:
                print "{} processing event {}".format(self.name, iEv)

            ev.getByLabel(self.__class__.vtxCollection, vertices)
            try:
                pv = vertices.product()[0]
            except:
                print "WARNING: No good vertices in event {}. Skipping.".format(iEv)
                continue

            ev.getByLabel(self.__class__.lepCollection, leps)
            ev.getByLabel(self.__class__.pfCandCollection, pfCands)

            candHolder = PFCandHolder(pfCands)

            for lep in leps.product():
                self.bookLepton(lep, candHolder)

        print "{} done! {} events processed.".format(self.name, iEv)
Пример #3
0
    def ReallyLoad(self, event):
        '''Load self from a given event.

        Call this function, and then just call self.product() to get the collection'''
        try:
            event.getByLabel( self.label, self)
            if not self.isValid(): raise RuntimeError    
        except RuntimeError:
            Handle.__init__(self, self.type) # must re-init, since otherwise after a failure it becomes unusable
            errstr = '''
            Cannot find collection with:
            type = {type}
            label = {label}
            '''.format(type = self.type, label = self.label)
            if not self.mayFail and self.fallbackLabel == None:
                raise Exception(errstr)
            if self.fallbackLabel != None:
                try:
                    event.getByLabel( self.fallbackLabel, self)
                    if not self.isValid(): raise RuntimeError
                    ## if I succeeded, swap default and fallback assuming that the next event will be like this one
                    self.fallbackLabel, self.label = self.label, self.fallbackLabel
                except RuntimeError:
                    Handle.__init__(self, self.type) # must re-init, since otherwise after a failure it becomes unusable
                    errstr = '''
                    Cannot find collection with:
                    type = {type}
                    label = {label} or {lab2}
                    '''.format(type = self.type, label = self.label, lab2 = self.fallbackLabel)
                    if not self.mayFail:
                        raise Exception(errstr)
Пример #4
0
    def __init__(self, outfile, useGenWeight=False, triggerWeight = "noWeight"):
        """Initialization"""
        self.outfileStr = outfile
        self.useGenWeight = useGenWeight
        self.triggerFile = ROOT.TFile("TRIGGER_EFFIC.root")
        self.triggerHist = self.triggerFile.Get("TYPE12_TRIGGER_EFFIC").Clone()
        self.triggerWeight = triggerWeight
        self.allTopTagHandle         = Handle (  "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >"  )
        self.allTopTagLabel          = ( "ttbsmAna",   "topTagP4")
        self.allTopTagMinMassHandle  = Handle( "std::vector<double>" )
        self.allTopTagMinMassLabel   = ( "ttbsmAna",   "topTagMinMass" )
        self.allTopTagNSubsHandle    = Handle("std::vector<double>" )
        self.allTopTagNSubsLabel     = ( "ttbsmAna",   "topTagNSubjets" )
        self.hemis0Handle            = Handle ("vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >")
        self.hemis0Label             = ( "ttbsmAna", "topTagP4Hemis0" )
        self.hemis0MinMassHandle     = Handle( "std::vector<double>" )
        self.hemis0MinMassLabel      = ( "ttbsmAna", "topTagMinMassHemis0" )
        self.hemis0NSubjetsHandle    = Handle( "std::vector<double>" )
        self.hemis0NSubjetsLabel     = ( "ttbsmAna", "topTagNSubjetsHemis0"  )
        self.hemis0TopMassHandle     = Handle( "std::vector<double>" )
        self.hemis0TopMassLabel      = ( "ttbsmAna", "topTagTopMassHemis0" )
        self.hemis0PassHandle        = Handle( "std::vector<int>")
        self.hemis0PassLabel         = ( "ttbsmAna", "topTagPassHemis0" )
        self.hemis1Handle            = Handle( "vector<ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> > >")
        self.hemis1Label             = ( "ttbsmAna", "wTagP4Hemis1" )
        self.hemis1BdiscHandle       = Handle( "std::vector<double>" )
        self.hemis1BdiscLabel        = ( "ttbsmAna",   "wTagBDiscHemis1" )
        self.hemis1MuHandle          = Handle( "std::vector<double>")
        self.hemis1MuLabel           = ( "ttbsmAna",  "wTagMuHemis1" )
        self.hemis1Jet3Handle        = Handle("int")
        self.hemis1Jet3Label         = ( "ttbsmAna", "jet3Hemis1" )
        self.weightsHandle           = Handle( "double" )
        self.weightsLabel            = ( "ttbsmAna", "weight" )

        self.__book__()
def getWeightsFromEDMFile(edm_file_name, cross_section=1):
    if "/store/" in edm_file_name:
        edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/",
            edm_file_name])
    elif not os.path.isfile(edm_file_name):
        raise FileNotFoundException("File %s was not found." % edm_file_name)
    events = Events(edm_file_name)
    eventsHandle = Handle("LHEEventProduct")
    lheLabel = getLHEInfoTag(events, eventsHandle)
    lhe_weight_sums = []
    weight_ids = []
    for i, event in enumerate(events):
        event.getByLabel(lheLabel, eventsHandle)
        lheStuff = eventsHandle.product()
        weights = lheStuff.weights()
        #orig = lheStuff.originalXWGTUP()    
        if i == 0:
            weight_ids = [w.id for w in weights]
            lhe_weight_sums = [w.wgt for w in weights]
        else:
            for j, weight in enumerate(weights):
                lhe_weight_sums[j] += weight.wgt
    if cross_section != 0:
        norm = cross_section/lhe_weight_sums[0]
        lhe_weight_sums = [w*norm for w in lhe_weight_sums]
    return getVariations(weight_ids, lhe_weight_sums)
Пример #6
0
def main():

  from FWCore.ParameterSet.VarParsing import VarParsing
  
  options = VarParsing ('analysis')
  options.inputFiles = "/afs/cern.ch/work/d/devdatta/CMSREL/Flashgg/CMSSW_9_4_2/src/flashgg/myMicroAODOutputFile.root"
  options.parseArguments()

  events = Events(options.inputFiles)
  nevents = 0
  for event in events:

    h_jets = Handle("std::vector<std::vector<flashgg::Jet> >")
    event.getByLabel("flashggFinalJets", h_jets)

    print( "N(jets) = %i" % len(h_jets.product()) )
    jets = h_jets.product()[0]
    for jet in jets:
      print( "jet pt = %f DeepCSVBDisc = %f" % (jet.pt(), jet.bDiscriminator("pfDeepCSVJetTags:probb")+jet.bDiscriminator("pfDeepCSVJetTags:probbb")) )

    h_dipho = Handle("std::vector<flashgg::DiPhotonCandidate>")
    event.getByLabel("flashggDiPhotons", h_dipho)

    diphos = h_dipho.product()
    print( "N(diphotons) = %i" %len(diphos) )
    for dipho in diphos:
      print( "Diphoton pt = %f" % dipho.pt() )
	def __init__(self, cutsConfig, data_files):
		"""
		TwoMuonAnalyzer initializer
		"""

		self.muonHandle = Handle('std::vector<pat::Muon>')
		self.vertexHandle = Handle('std::vector<reco::Vertex>')	
		self.cutsConfig = cutsConfig
		self.events = Events(data_files)
		self.zMass = []
		self.badZMass = []
		self.zPt = []
		self.badZPt = []
		self.zPt1 = []
		self.badZPt1 = []
		self.zPt2 = []
		self.badZPt2 = []
		self.eta = []
		self.badEta = []
		self.chi2 = []
		self.badChi2 = []
		self.numValidHits = []
		self.badNumValidHits = []
		self.dB = []
		self.distance = []
		self.charge=[]
		self.edB = []
def getWeightIDs(edm_file_name) :
    if "/store/" in edm_file_name :
        edm_file_name = "/".join(["root://cmsxrootd.fnal.gov/",
            edm_file_name])
    elif not os.path.isfile(edm_file_name) :
        raise FileNotFoundException("File %s was not found." % edm_file_name)
    runs = Runs(edm_file_name)
    runInfoHandle = Handle("LHERunInfoProduct")
    lheLabel = WeightTools.getLHEInfoTag(runs, runInfoHandle)
    run = runs.__iter__().next()
    run.getByLabel(lheLabel, runInfoHandle)
    lheStuff = runInfoHandle.product()
    lines = []
    for i, h in enumerate(lheStuff.headers_begin()) :
        if i == lheStuff.headers_size() :
            break
        hlines = []
        isWeights = False
        for line in h.lines() :
            hlines.append(line)
            if 'weightgroup' in line :
                isWeights = True
        if isWeights :
            lines.extend(hlines)
            break
    return ''.join(lines).rstrip("<")
Пример #9
0
def fetchBMTF(event,isData,etaMax=1.2):
    bmtfH  = Handle  ('BXVector<l1t::RegionalMuonCand>')
    if isData:
        event.getByLabel('BMTFStage2Digis:BMTF',bmtfH)
    else:
        event.getByLabel('simBmtfDigis:BMTF',bmtfH)

    bmtf=bmtfH.product()
    bmtfMuons=[]
    for bx in [0]:
        for j in range(0,bmtf.size(bx)):
            mu = bmtf.at(bx,j)
            pt = mu.hwPt()*0.5
            K=1.0/pt
            K=1.181*K/(1+0.4867*K)
            pt=1.0/K
            ####          
            phi=globalBMTFPhi(mu,'BMTF')
            rawP = rawPhi(mu)
            eta = mu.hwEta()*0.010875           
            if abs(eta)<=etaMax:
                b = BMTFMuon(mu,pt,eta,phi)
                b.rawPhi=rawP
                bmtfMuons.append(b)
    return sorted(bmtfMuons,key=lambda x: x.pt(),reverse=True)
Пример #10
0
def count(inputPath):

    files = [inputPath]

    events = Events(files)

    handlePFMETs = Handle("std::vector<reco::PFMET>")

    for event in events:

        run = event.eventAuxiliary().run()
        lumi = event.eventAuxiliary().luminosityBlock()
        eventId = event.eventAuxiliary().event()

        event.getByLabel(("pfMet", "", "RECO"), handlePFMETs)
        met = handlePFMETs.product().front()

        print '%6d'    % run,
        print '%10d'   % lumi,
        print '%9d'    % eventId,
        print '%10.3f' % met.pt(),
        print '%10.3f' % met.px(),
        print '%10.3f' % met.py(),
        print '%10.2f' % (met.phi()/math.pi*180.0),
        print
Пример #11
0
def main():

    preFnal = 'dcache:/pnfs/cms/WAX/11'
    preCern = 'rfio:/castor/cern.ch/cms'
    pre = preCern
    
    files = [pre+'/store/express/Run2010A/ExpressPhysics/FEVT/v4/000/138/737/FEC10B07-5281-DF11-B3D2-0030487A3DE0.root']
    
    events = Events (files)

    handleBSpot  = Handle ("reco::BeamSpot")

    label    = ("offlineBeamSpot")

    #f = ROOT.TFile("analyzerPython.root", "RECREATE")
    #f.cd()

    #muonPt  = ROOT.TH1F("muonPt", "pt",    100,  0.,300.)
    
    # loop over events
    i = 0
    
    for event in events:
        i = i + 1
        if i%10 == 0:
            print  i

        event.getByLabel (label, handleBSpot)
        # get the product
        spot = handleBSpot.product()

        print " x = "+str(spot.x0())
                        
        if i==10: break
Пример #12
0
def analyze_gen():
	events = Events ('/nfs/dust/cms/user/usaiem/gen/genall.root')
	handle  = Handle ('LHEEventProduct')
	label = ("source")
	ROOT.gROOT.SetBatch()
	ROOT.gROOT.SetStyle('Plain') # white background
	zmassHist = ROOT.TH1F ("zmass", "Z Candidate Mass", 50, 20, 220)
	zevts=0
	wevts=0
	hevts=0
	for event in events:
		event.getByLabel (label, handle)
		lhe = handle.product()
		hepeup=lhe.hepeup()
		pup= hepeup.PUP
		idup= hepeup.IDUP
		mothup= hepeup.MOTHUP
		for i in idup:
			if abs(i)==23:
				zevts+=1
				break
			elif abs(i)==24:
				wevts+=1
				break
			elif abs(i)==25:
				hevts+=1
				break
	print 'zevts',zevts
	print 'wevts',wevts
	print 'hevts',hevts
Пример #13
0
class Histo:
    def __init__(self, src, fillfn, *args):
        self.handle = Handle(src[0])
        self.label = src[1]
        self.hist = ROOT.TH1F(*args)
        self.hist.Sumw2()
        if not fillfn:
            self.fillfn = lambda x: x[0] if len(x)>0 else 0
        else:
            self.fillfn = fillfn
        self.weight_handle = None
        self.weight_label = None
    def fill(self, event):
        try:
            event.getByLabel(self.label, self.handle)
            if self.weight_handle:
                event.getByLabel(self.weight_label, self.weight_handle)

            if self.handle.isValid():
                prod = self.handle.product()
                if self.weight_handle and self.weight_handle.isValid():
                    w = self.weight_handle.product()[0]
                else:
                    w = 1.0
                self.hist.Fill(self.fillfn(prod), w)
        except ValueError as e:
            print "Error while filling histogram: ", self.label, " ", str(e)
            sys.exit(1)
Пример #14
0
def fetchStubsOLDTheta(event,isData=True):
    phiSeg    = Handle  ('L1MuDTChambThContainer')
    if not isData:
        event.getByLabel('dtTriggerPrimitiveDigis',phiSeg)
    else:
        event.getByLabel('BMTFStage2Digis',phiSeg)
    return phiSeg.product().getContainer()
Пример #15
0
 def __init__(self, msg, type, inlabel, outlabel, tests):
     self.msg = msg
     self.inhandle = Handle(type)
     self.outhandle = Handle(type)
     self.inlabel = inlabel
     self.outlabel = outlabel,
     self.tests = tests or []
	def __init__(self, data_files):

		self.muonHandle = Handle('std::vector<pat::Muon>')
		self.vertexHandle = Handle('std::vector<reco::Vertex>')	
		self.electronHandle = Handle('std::vector<pat::Electron>')

		self.events = Events(data_files)

		self.f = ROOT.TFile("mytree.root","RECREATE")
		self.tree=ROOT.TTree("muons","muons tree")
		
		self.Muon_pt = array.array("d", [-999.0]*50)
		self.Muon_eta = array.array("d", [-999.0]*50)
		self.Muon_px = array.array("d", [-999.0]*50)
		self.Muon_py = array.array("d", [-999.0]*50)
		self.Muon_pz = array.array("d", [-999.0]*50)
		self.Muon_energy = array.array("d", [-999.0]*50)
		self.Muon_vertex_z = array.array("d", [-999.0]*50)
		self.Muon_isGlobalMuon = array.array("i", [-999]*50)
		self.Muon_isTrackerMuon = array.array("i", [-999]*50)
		self.Muon_dB = array.array("d", [-999.0]*50)
		self.Muon_edB = array.array("d", [-999.0]*50)
		self.Muon_isolation_sumPt = array.array("d", [-999.0]*50)
		self.Muon_isolation_emEt = array.array("d", [-999.0]*50)
		self.Muon_isolation_hadEt = array.array("d", [-999.0]*50)
		self.Muon_numberOfValidHits = array.array("i", [0]*50)
		self.Muon_normChi2 = array.array("d", [-999.0]*50)
		self.Muon_charge = array.array("i", [-999]*50)

		self.Vertex_z = array.array("d", [-999.0])
		self.npart = array.array("i", [-999])
Пример #17
0
    def setEventTree(self, event, expand_key_func=None):
        self.clear()
        handle = Handle("vector<reco::GenParticle>")
        event.getByLabel(self.collection, handle)
        def fill_tree(gen_particle, parent_item):
            expanded = False
            for p in xrange(gen_particle.numberOfDaughters()):
                p = gen_particle.daughter(p)
                item = QtGui.QTreeWidgetItem(
                    parent_item,
                    [
                        "%d" % p.pdgId(),
                        "%d" % p.status(),
                        "%f" % p.energy(),
                        "%f" % p.px(),
                        "%f" % p.py(),
                        "%f" % p.pz(),
                    ]
                )
                if not parent_item:
                    self.addTopLevelItem(item)
                if expand_key_func and expand_key_func(p):
                    expanded = True
                expanded = fill_tree(p, item) or expanded
            if parent_item and expanded:
                parent_item.setExpanded(True)
            return expanded

        for gp in iter(handle.product()):
            if not gp.mother():
                fill_tree(gp, None)
Пример #18
0
def fetchStubs(event,ontime=True):
    phiSeg2    = Handle  ('std::vector<L1MuKBMTCombinedStub>')
    event.getByLabel('simKBmtfStubs',phiSeg2)
    if ontime:
        filtered=filter(lambda x: x.bxNum()==0, phiSeg2.product())
        return filtered
    else:
        return phiSeg2.product()
Пример #19
0
def fetchSegmentsEta(event,ontime=True):
    thetaSeg  = Handle  ('L1MuDTChambThContainer')
    event.getByLabel('dtTriggerPrimitiveDigis',thetaSeg)
    if ontime:
        filtered=filter(lambda x: x.bxNum()==0, thetaSeg.product().getContainer())
        return filtered
    else:
        return thetaSeg.product().getContainer()    
Пример #20
0
def get_info(infile,particle, outfile, histo, variable):
#####################################

	################# File
	#file = ROOT.TFile(particle+"_tmp.root", "recreate")  			# open new root file
	#tree = ROOT.TTree("plots", "plots")					# Open a tree
	#t.Branch(particle, n, particle'/D')

        events = Events (infile)
        handleGen = Handle ("vector<reco::GenParticle>")
        #label = "prunedGenParticles"
        label = "genParticles"
	#print handleGen
	histo.UseCurrentStyle()

	if particle in PDG.keys():
		for event in events:
			#print event
			#nparticles = 0
			event.getByLabel (label, handleGen)
			gens = handleGen.product()
			#storeParticles = std.vector(float)()
			Ptvector=[]
#    
			for p in gens:
				infoParticle = TLorentzVector()
				#print 'id',p.pdgId(), p.status(), 'status'
				#print 'name', p.pdgId(), p.status(), p.p4()
				tmpValue=0
				if abs( int(p.pdgId()) ) == int(PDG[particle]):
					if p.status() == 3:    
						#nparticles += 1
						infoParticle.SetPxPyPzE(p.px(),p.py(),p.pz(),p.et())
						Ptvector.append(infoParticle.Pt())
						if int(Variables[variable])==1: histo.Fill(infoParticle.Pt())
						if int(Variables[variable])==2: histo.Fill(infoParticle.M())
						if int(Variables[variable])==3: histo.Fill(infoParticle.Eta())
						#histo.Fill(infoParticle.E())
			if int(Variables[variable])==4: histo.Fill(len(Ptvector))
			if int(Variables[variable])==11: histo.Fill(max(Ptvector))
						
						#storeParticles.push_back(infoParticle.Et())

	can = TCanvas('can', '', 800,600)
	can.cd()
	histo.Draw()
#if histo.GetNbinsX() > 50:
#histo.GetXaxis().SetLabelSize(0.02)
#else:
#histo.GetXaxis().SetLabelSize(0.03)
	can.SetBorderMode(0)
	can.SetBorderSize(0)
	can.SetFillColor(kWhite)
	can.SetLeftMargin(0.10)
#can.SaveAs(allnames.replace('_','')+'temp.png')
	can.SaveAs(particle+'_'+variable+'temp.pdf')
	del can
Пример #21
0
    def __init__(self):
        self.vertexHandle  = Handle ('std::vector<reco::Vertex>')
        self.muonHandle    = Handle('std::vector<pat::Muon>')
        self.selections = {}
        self.signal=0
        self.background=0
        self.corrector = ROOT.MuScleFitCorrector(getFullPath("MuScleFit/Calibration/data/MuScleFit_2012D_DATA_53X.txt"))
#        self.corrector = ROOT.rochcor2012()
#        self.corrector = ROOT.MuScleFitCorrector(getFullPath("MuScleFit/Calibration/data/MuScleFit_2012ABC_DATA_53X.txt"))
        self.processFunc = None
 def __init__(self):
     self.vertexHandle = Handle('std::vector<reco::Vertex>')
     self.muonHandle = Handle('std::vector<pat::Muon>')
     self.electronHandle = Handle('std::vector<pat::Electron>')
     self.histograms = {}
     self.samples = ['data']
     self.plots = {}
     for sample in self.samples:
         self.histograms[sample] = {}
     self.data = []
 def __init__(self, inputTrigs):
     self.rhoHandle           = Handle("double")
     self.rhoLabel            = ( "ttbsmAna", "rho" )
     self.myTrigIndexHandle   = Handle( "std::vector<int>")
     self.myTrigIndexLabel    = ( "ttbsmAna",  "myTrigIndex" )
     self.prescalesHandle     = Handle( "std::vector<int>")
     self.prescalesLabel      = ( "ttbsmAna",  "prescales" )
     self.trigNamesHandle     = Handle( "std::vector<string>")
     self.trigNamesLabel      = ( "ttbsmAna",  "trigNames" )
     self.trigs               = inputTrigs
Пример #24
0
def get_info(infile,particle, outfile):
#####################################
        events = Events (infile)
        handleGen = Handle ("vector<reco::GenParticle>")
        label = "genParticles"

	if particle in PDG.keys():
		# For histos 
		hmass = TH1F( particle+' mass', particle+' mass',100,480,520) # gh 500 MeV 
		#hmass = TH1F( particle+' mass', particle+' mass',100,980,1020)  # gh 1 TeV
		#hmass = TH1F( particle+' mass', particle+' mass',100,160,180)  # 4Top 
		hmass.SetXTitle(particle+' Mass [GeV]')
		hnparticles = TH1F('number of '+particle+' and '+particle+'bar','number of '+particle+' and '+particle+'bar',5,2,6)
		#hpt2 = TH1F(particle +' pt', 'hardest '+ particle + 'pt',100,0,500)
		#hpt = TH1F('pt','pt',100,0,500)
		hpt = TH1F(particle+' pt','pt',500,0,1000)
		hpt.SetXTitle(particle+' pt [GeV]')
		heta = TH1F(particle+' eta',particle+' eta',100,-5,5)
		heta.SetXTitle(particle+' eta')

#		entry = 0
		for event in events:
			#entry += 1
			nparticles = 0
		#	print "Event ", count
			event.getByLabel (label, handleGen)
			gens = handleGen.product()
			highpt = []
    
			for p in gens:
				#print 'id',p.pdgId(), p.status(), 'status'
				if abs( int(p.pdgId()) ) == int(PDG[particle]):
					if p.status() == 22:     # 22 for ttbar, W and gh, 23 for 'final' particles
						nparticles += 1
#						highpt.append(p.pt())
#						print 'nparticles', nparticles
						hpt.Fill(float(p.pt())) 
						heta.Fill(float(p.eta())) 
						hmass.Fill(float(p.mass()))
			hnparticles.Fill(nparticles)
#			hpt2.Fill(max(highpt))

		hmass.Draw()
		c1.SaveAs(outfile+'_'+particle+'_mass.png')
#		hpt2.SetFillColor(kBlue)
#		hpt.SetFillColor(kWhite)
#		hpt2.GetYaxis().SetRangeUser(0.,400)
#	        hpt2.Draw()
#		hpt.Draw("same")
	        hpt.Draw()
	        c1.SaveAs(outfile+'_'+particle+'_pt.png')
	        heta.Draw()
	        c1.SaveAs(outfile+'_'+particle+'_eta.png')
	        hnparticles.Draw()
	        c1.SaveAs(outfile+'_'+particle+'_nparticles.png')
Пример #25
0
 def make_handle(self, dtype):
     if dtype=="vfloat":
         self.handle = Handle("std::vector<float>")
     elif dtype=="float":
         self.handle = Handle("float")
     elif dtype=="double":
         self.handle = Handle("double")
     elif dtype=="int":
         self.handle = Handle("int")
     else:
         raise ValueError("Undefined type: %s" % dtype)
Пример #26
0
def test_dumb():
    """Generator for events"""
    files = ["/Users/nic/cms/August11MC/Signal/BsmMassesSkim_Summer11_Sync.root"]

    fwlite_events = Events(files)
    handle = Handle("std::vector<pat::MET>")

    for fwlite_event in fwlite_events:
        fwlite_event.getByLabel("patMETsPFlow", handle)
        met = handle.product()[0]
        print met.pt()
Пример #27
0
def fetchStubsOLD(event,ontime=False,isData=True):
    phiSeg    = Handle  ('L1MuDTChambPhContainer')
    if not isData:
        event.getByLabel('simTwinMuxDigis',phiSeg)
    else:
        event.getByLabel('BMTFStage2Digis',phiSeg)
    if ontime:
        filtered=filter(lambda x: x.bxNum()==0, phiSeg.product().getContainer())
        return filtered
    else:
        return phiSeg.product().getContainer()
Пример #28
0
 def __init__(self, label, type, mayFail=False, fallbackLabel=None, lazy=True,disableAtFirstFail=True):
     '''Note: label can be a tuple : (module_label, collection_label, process)'''
     self.label = label
     self.fallbackLabel = fallbackLabel
     self.type = type
     self.mayFail = mayFail
     self.lazy = lazy
     self.isLoaded = False
     self.autoDisable = disableAtFirstFail;
     self.disabled= False
     Handle.__init__(self, self.type)
Пример #29
0
def fetchSegmentsPhi(event,ontime=True,twinMux=True):
    phiSeg    = Handle  ('L1MuDTChambPhContainer')
    if twinMux:
        event.getByLabel('simTwinMuxDigis',phiSeg)
    else:
        event.getByLabel('simDtTriggerPrimitiveDigis',phiSeg)
    if ontime:
        filtered=filter(lambda x: x.bxNum()==0, phiSeg.product().getContainer())
        return filtered
    else:
        return phiSeg.product().getContainer()
Пример #30
0
def fetchKMTF(event,etaMax=0.83,chi2=800000,dxyCut=100000):
    kmtfH  = Handle('BXVector<L1MuKBMTrack>')
    event.getByLabel('simKBmtfDigis',kmtfH)
    kmtf=kmtfH.product()
    out=[]
    for bx in [0]:
        for j in range(0,kmtf.size(bx)):
            mu =  kmtf.at(bx,j)
            if abs(mu.eta())<etaMax and mu.approxChi2()<chi2 and abs(mu.dxy())<dxyCut:
                out.append(mu)
    return sorted(out,key=lambda x: x.pt(),reverse=True)
Пример #31
0
import ROOT, sys
from DataFormats.FWLite import Events, Handle
import numpy as np

ROOT.gROOT.SetStyle('Plain')
ROOT.gROOT.SetBatch()

#jobs=np.linspace(100, 1, 100)
#jobs=[90]

masses = [10, 30, 50]
#masses=[50]
#masses=[50]

handleGenJet = Handle('vector<reco::GenJet>')
labelGenJet = ('ak4GenJets')

handleGenParticle = Handle('vector<reco::GenParticle>')
labelGenParticle = ('genParticles')

#prefix="root://cmseos.fnal.gov//eos/uscms/store/user/zhangj/events/ALP/RunIISummer16DR80Premix/"
prefix = "/afs/cern.ch/work/r/rhabibul/UL-Samples/2018/"
#for mass in masses:
out = ROOT.TFile("h_plotSignalGen_2018.root", 'recreate')

hJet1Pt = ROOT.TH1F("hJet1Pt", "leading jet Pt;P_{t};N_{events}", 150, 0, 1500)
hDiTauM = ROOT.TH1F("hDiTauM ", "di-tau mass;M_{#tau#tau};N_{events}", 100, 0,
                    100)
hDiMuM = ROOT.TH1F("hDiMuM ", "di-mu mass;M_{#mu#mu};N_{events}", 100, 0, 100)
hDiMuDiTau = ROOT.TH1F("hDiMuDiTau ",
                       "di-mu_di-tau mass;M_{#mu#mu#tau#tau};N_{events}", 200,
Пример #32
0
# 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:
    # use getByLabel, just like in cmsRun
    event.getByLabel(label, handle)
    # get the product
Пример #33
0
events = Events(args.file)

VERBOSE = args.verbose
EVENTS = int(args.numEvents)
SAVE = args.save

# vertexing information to store
data = {
    "genParticles": {},
    "sortedPrimaryVertices": {},
    "offlinePrimaryVertices": {},
    "offlinePrimaryVerticesWithBS": {}
}

sortedPV_handle = Handle('vector<reco::Vertex>')
offlinePV_handle = Handle('vector<reco::Vertex>')
offlinePVwithBS_handle = Handle('vector<reco::Vertex>')
genParticles_handle = Handle("vector<reco::GenParticle>")

print_indx = int(events.size()) / 10
if EVENTS > 0:
    print_indx = EVENTS / 10

for i, event in enumerate(events):
    # gen particles
    gen_pv_count = 0
    event.getByLabel("genParticles", genParticles_handle)
    genParticles = genParticles_handle.product()
    data["genParticles"][i] = []
    for P in genParticles:
Пример #34
0
def main():

    from FWCore.ParameterSet.VarParsing import VarParsing

    options = VarParsing('analysis')
    options.inputFiles = [
        "/afs/cern.ch/work/l/lata/HH_bbyy/CMSSW_9_4_2/src/flashgg/root_files/myMicroAODOutput_6.root"
    ]
    options.maxEvents = -1
    options.outputFile = "fout.root"
    options.parseArguments()

    ###### save hisots in root file ######

    fout = ROOT.TFile("output_3.root", 'RECREATE')
    fout.cd()

    ##### define Histograms ######

    h_H_pt = ROOT.TH1F("gen_H_pT", ";Higgs p_{T} [GeV];Events;;", 50, 0., 500.)
    h_H_eta = ROOT.TH1F("gen_H_eta", ";Higgs #eta;Events;;", 50, -5., 5.)
    h_b_pt = ROOT.TH1F("gen_b_pT", ";p_{T}of b [GeV];Events;;", 50, 0., 500.)
    h_b_eta = ROOT.TH1F("gen_b_eta", ";#eta of b;Events;;", 50, -5., 5.)
    h_y_pt = ROOT.TH1F("gen_y_pT", ";p_{T}of #gamma[GeV];Events;;", 50, 0.,
                       500)
    h_y_eta = ROOT.TH1F("gen_y_eta", ";#eta of #gamma;Events;;", 50, -5., 5.)

    h_jet_pt = ROOT.TH1F("jet_pt", ";jet p_{T} [GeV];Events;;", 50, 0., 500.)
    h_jet_eta = ROOT.TH1F("jet_eta", ";jet #eta;Events;;", 50, -5., 5.)
    h_jet_deepcsv = ROOT.TH1F("jet_deepcsv", ";jet DeepCSV [GeV];Events;;", 50,
                              0., 1.)
    h_btaggedjet0_pt = ROOT.TH1F("btagged_jet0_pt",
                                 ";b-tagged leading jet p_{T} [GeV];Events;;",
                                 50, 0., 500.)
    h_btaggedjet0_eta = ROOT.TH1F("btagged_jet0_eta",
                                  ";b-tagged leading jet #eta;Events;;", 50,
                                  -5., 5.)
    h_btaggedjet1_pt = ROOT.TH1F(
        "btagged_jet1_pt", ";b-tagged subleading jet p_{T} [GeV];Events;;", 50,
        0, 500)
    h_btaggedjet1_eta = ROOT.TH1F("btagged_jet1_eta",
                                  ";b-tagged subleading jet #eta;Events;;", 50,
                                  -5, 5)

    h_photon_pt = ROOT.TH1F("photon_pt", ";#gamma p_{T} [GeV];Events;;", 50,
                            0., 500.)
    h_photon_eta = ROOT.TH1F("photon_eta", ";#gamma #eta [GeV];Events;;", 50,
                             -5, 5)
    h_photon0_pt = ROOT.TH1F("photon0_pt",
                             ";leading #gamma p_{T} [GeV];Events;;", 50, 0.,
                             500.)
    h_photon0_eta = ROOT.TH1F("photon0_eta",
                              ";leading #gamma #eta [GeV];Events;;", 50, -5, 5)
    h_photon1_pt = ROOT.TH1F("photon1_pt",
                             ";subleading #gamma p_{T} [GeV];Events;;", 50, 0.,
                             500)
    h_photon1_eta = ROOT.TH1F("photon1_eta",
                              ";subleading #gamma #eta [GeV];Events;;", 50, -5,
                              5)
    h_njet = ROOT.TH1D("njet", ";Njet;Events;;", 15, 0, 15)
    h_nphoton = ROOT.TH1D("nphoton", ";Nphoton;Events;;", 5, 0, 5)

    h_dipho_mass = ROOT.TH1F("dipho_mass ", ";diphoton mass [GeV];Events;;",
                             50, 0., 200.)
    h_reconsM_photon = ROOT.TH1F("photon_recomass",
                                 ";M_{#gamma#gamma} [GeV];Events;;", 50, 0.,
                                 200.)
    h_reconsM_bb = ROOT.TH1F("bb_recomass", ";M_{bb} [GeV];Events;;", 50, 0.,
                             200)

    events = Events(options.inputFiles)
    nevents = 0
    for event in events:

        if options.maxEvents > 0 and nevents > options.maxEvents: break

        ### Find gen particles
        h_prunedGenpar = Handle("std::vector<reco::GenParticle>")
        event.getByLabel("flashggPrunedGenParticles", h_prunedGenpar)

        particles = h_prunedGenpar.product()
        for p in particles:
            print('prunedgenparticles P pid = {} status = {}'.format(
                p.pdgId(), p.status()))
            if p.pdgId() == 25:
                h_H_pt.Fill(p.pt())
                h_H_eta.Fill(p.eta())
            if abs(p.pdgId()) == 5:
                h_b_pt.Fill(p.pt())
                h_b_eta.Fill(p.eta())
            if p.pdgId() == 22:
                h_y_pt.Fill(p.pt())
                h_y_eta.Fill(p.eta())

        h_photons = Handle("std::vector<flashgg::Photon>")
        event.getByLabel("flashggRandomizedPhotons", h_photons)
        print("N(photons) = {}".format(len(h_photons.product())))
        photons = h_photons.product()
        h_nphoton.Fill(len(photons))
        if (len(photons) >= 2):
            p4_g0 = ROOT.TLorentzVector()
            p4_g1 = ROOT.TLorentzVector()
            p4_g0.SetPtEtaPhiM(photons[0].pt(), photons[0].eta(),
                               photons[0].phi(), photons[0].mass())
            p4_g1.SetPtEtaPhiM(photons[1].pt(), photons[1].eta(),
                               photons[1].phi(), photons[1].mass())
            h_photon0_pt.Fill(photons[0].pt())
            h_photon1_pt.Fill(photons[1].pt())
            h_photon0_eta.Fill(photons[0].eta())
            h_photon1_eta.Fill(photons[1].eta())
            if photons[0].pt() > 20 and photons[1].pt() > 20:
                h_reconsM_photon.Fill((p4_g0 + p4_g1).M())
        for gam in photons:
            print('photon pt = {}'.format(gam.pt()))
            h_photon_eta.Fill(gam.eta())
            h_photon_pt.Fill(gam.pt())

        h_packedGenpar = Handle("std::vector<pat::PackedGenParticle>")
        event.getByLabel("flashggGenPhotons", h_packedGenpar)
        particles = h_packedGenpar.product()
        for p in particles:
            print('packedgenparticles P pid = {} status = {}'.format(
                p.pdgId(), p.status()))

        h_jets = Handle("std::vector<std::vector<flashgg::Jet> >")
        event.getByLabel("flashggFinalJets", h_jets)

        print("N(jets) = %i" % len(h_jets.product()))
        if len(h_jets.product()) <= 0: continue
        jets = h_jets.product()[0]
        h_njet.Fill(len(jets))
        if (len(jets) >= 2):
            disc1 = jets[0].bDiscriminator("pfDeepCSVJetTags:probb") + jets[
                0].bDiscriminator("pfDeepCSVJetTags:probbb")
            disc2 = jets[1].bDiscriminator("pfDeepCSVJetTags:probb") + jets[
                1].bDiscriminator("pfDeepCSVJetTags:probbb")
            pt0 = jets[0].pt()
            pt1 = jets[1].pt()
            eta0 = jets[0].eta()
            eta1 = jets[1].eta()
            p4_b0 = ROOT.TLorentzVector()
            p4_b1 = ROOT.TLorentzVector()
            p4_b0.SetPtEtaPhiM(jets[0].pt(), jets[0].eta(), jets[0].phi(),
                               jets[0].mass())
            p4_b1.SetPtEtaPhiM(jets[1].pt(), jets[1].eta(), jets[1].phi(),
                               jets[1].mass())
            if disc1 > 0.4941 and disc2 > 0.4941:
                h_btaggedjet0_pt.Fill(pt0)
                h_btaggedjet1_pt.Fill(pt1)
                h_btaggedjet0_eta.Fill(eta0)
                h_btaggedjet1_eta.Fill(eta1)
                if pt0 > 25 and pt1 > 25 and abs(eta0) <= 2.5 and abs(
                        eta1) <= 2.5:
                    h_reconsM_bb.Fill((p4_b0 + p4_b1).M())
        for jet in jets:
            print("jet pt = %f DeepCSVBDisc = %f" %
                  (jet.pt(), jet.bDiscriminator("pfDeepCSVJetTags:probb") +
                   jet.bDiscriminator("pfDeepCSVJetTags:probbb")))

            deepCSV = jet.bDiscriminator(
                "pfDeepCSVJetTags:probb") + jet.bDiscriminator(
                    "pfDeepCSVJetTags:probbb")
            h_jet_pt.Fill(jet.pt())
            h_jet_eta.Fill(jet.eta())
            h_jet_deepcsv.Fill(deepCSV)

        h_dipho = Handle("std::vector<flashgg::DiPhotonCandidate>")
        event.getByLabel("flashggDiPhotons", h_dipho)

        diphos = h_dipho.product()
        print("N(diphotons) = %i" % len(diphos))
        for dipho in diphos:
            print("Diphoton pt = %f" % dipho.pt())
            h_dipho_mass.Fill(dipho.mass())

        nevents += 1
    fout.Write()
    fout.Close()
Пример #35
0
		foundRecoMatchesForAllObjects = True
		objsAndFoundMatchesList.append(1)
		objsAndFoundMatchesList.append(recoLeptonMatchedToWrDau)
		objsAndFoundMatchesList.append(recoLeptonMatchedToNuDau)
		objsAndFoundMatchesList.append(recoJetMatchedToLeadNuDauQrk)
		objsAndFoundMatchesList.append(recoJetMatchedToSubleadNuDauQrk)
	
	if(foundRecoMatchesForAllObjects == False):
		objsAndFoundMatchesList.append(0)
	
	return objsAndFoundMatchesList
#end foundMatchingRecoObjects()


# define handles and labels for TriggerResults, TriggerObjectStandAlone, and GenParticle collections
trigResultsHandl, trigResultsLabel = Handle("edm::TriggerResults"), ("TriggerResults","","HLT")
trigObjsHandl, trigObjsLabel = Handle("std::vector<pat::TriggerObjectStandAlone>"), "selectedPatTrigger"
genParticleHandl, genParticleLabel = Handle("std::vector<reco::GenParticle>"), "prunedGenParticles"
recoJetsHandl, recoJetsLabel = Handle("std::vector<pat::Jet>"), "slimmedJets"
recoLeptonHandl, recoLeptonLabel = Handle("std::vector<pat::Muon>"), "slimmedMuons"

# open one or more miniAOD .root files, and create an iterator to loop over the Event objects in the file(s)
doMuonChannel = False 
doRECOCuts = True	#apply cuts on reco objects which are matched to gen particles from WR decay chain
allEvents = Events("/eos/uscms/store/user/skalafut/WR/13TeV/RunIISpring15_MiniAODSignalSamples/WRToNuMuToMuMuJJ_MW-800_MNu-400_TuneCUETP8M1_pythia8_13TeV_1.root")

#dR matching thresholds for leptons and jets
dRforJets = 0.4
dRforLeptons = 0.2

if(doMuonChannel == False):
Пример #36
0
# 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('output_v2.root')

# create handle outside of loop
handle_ele = Handle("std::vector<pat::Electron>")
handle_map = Handle("vector<pair<edm::Ptr<pat::Electron>,reco::Track>>")

# for now, label is just a tuple of strings that is initialized just
# like and edm::InputTag
label_ele = ("slimmedElectrons")
label_map = ("ttk", "eleTtkMap", "TTK")

# Create histograms, etc.
ROOT.gROOT.SetBatch()  # don't pop up canvases
ROOT.gROOT.SetStyle('Plain')  # white background

# loop over events
for ii, event in enumerate(events):
    if event.eventAuxiliary().run() != 316060:
        continue
Пример #37
0
sys.argv = ['-b-']
import ROOT
ROOT.gROOT.SetBatch(True)
sys.argv = oldargv

# load FWLite C++ libraries
ROOT.gSystem.Load("libFWCoreFWLite.so")
ROOT.gSystem.Load("libDataFormatsFWLite.so")
ROOT.FWLiteEnabler.enable()

print 'Hello!'

# load FWlite python libraries
from DataFormats.FWLite import Handle, Events

muons, muonLabel = Handle("std::vector<pat::Muon>"), "slimmedMuons"
electrons, electronLabel = Handle(
    "std::vector<pat::Electron>"), "slimmedElectrons"
photons, photonLabel = Handle("std::vector<pat::Photon>"), "slimmedPhotons"
taus, tauLabel = Handle("std::vector<pat::Tau>"), "slimmedTaus"
tauLabelb = "slimmedTausBoosted"
jets = Handle("std::vector<pat::Jet>")
fatjets, fatjetLabel = Handle("std::vector<pat::Jet>"), "slimmedJetsAK8"
fatgenjets, fatgenjetLabel = Handle(
    "std::vector<reco::GenJet>"), "slimmedGenJetsAK8"
mets, metLabel = Handle("std::vector<pat::MET>"), "slimmedMETs"
vertices, vertexLabel = Handle(
    "std::vector<reco::Vertex>"), "offlineSlimmedPrimaryVertices"
verticesScore = Handle("edm::ValueMap<float>")
seenIt = {
}  # list of things we've seen (so that we dump them in full only once)
Пример #38
0
    def __init__(self, label, edmtype, eval_list):
        self.label = label
        self.edmtype = edmtype
        self.eval_list = eval_list

        self.handle = Handle(self.edmtype)
Пример #39
0
    mid = m.pdgId()
    while mid != 0 and mid != 2212:
        mid = traceHistory(m)
    return mid


from FWCore.ParameterSet.VarParsing import VarParsing
options = VarParsing('python')
options.parseArguments()
outF = options.outputFile

#get the events branch
events = Events(options)

# create handles
genParticlesHandle = Handle('std::vector<reco::GenParticle>')
genJetsHandle = Handle('std::vector<reco::GenJet>')

# Create histograms, etc.
mon = {}
mon['zpt'] = ROOT.TH1F('zpt', ";p_{T} [GeV]; Events", 100, 0, 1000)
mon['njets'] = ROOT.TH1F('njets', ";Jet multiplicity; Events", 10, 0, 10)
mon['mjj'] = ROOT.TH1F('mjj', ";M_{jj} [GeV]; Events", 100, 0, 3000)
mon['spt'] = ROOT.TH1F('spt', ";S_{p_{T}} ; Events", 100, 0, 1)
mon['detajj'] = ROOT.TH1F('detajj', ";|#Delta #eta_{jj}|; Events", 100, 0, 8)
mon['leadetaj'] = ROOT.TH1F('leadetaj', ";max |#eta_{j}|; Events", 100, 0, 6)
mon['traileretaj'] = ROOT.TH1F('traileretaj', ";min |#eta_{j}|; Events", 100,
                               0, 6)
mon['mjj_mpi'] = mon['mjj'].Clone('mjj_mpi')
mon['spt_mpi'] = mon['spt'].Clone('mjj_mpi')
mon['detajj_mpi'] = mon['detajj'].Clone('detajj_mpi')
def createPlots(sample,prefix,xsec,massbins,year):
    files=[]
    if sample.endswith(".txt"):
        filelist=open(sample)
	for line in filelist.readlines():
	    if ".root" in line:
	        files+=[line.strip()]
    elif "HT" in sample:
      files+=["dcap://dcache-cms-dcap.desy.de//pnfs/desy.de/cms/tier2/store/user/hinzmann/dijetangular/qcd"+year+"/"+sample+".root"]
    else:
        folders=os.listdir("/pnfs/desy.de/cms/tier2/store/user/hinzmann/dijetangular/dijet_angular/")
	for folder in folders:
	  if sample in folder:
            files+=["/pnfs/desy.de/cms/tier2/store/user/hinzmann/dijetangular/dijet_angular/"+folder+"/GEN.root"]
	    #break

    prunedgenjets_handle=Handle("std::vector<reco::GenJet>")
    prunedgenjets_label="ak4GenJets"

    plots=[]
    for massbin in massbins:
      plots += [TH1F(prefix+'#chi'+str(massbin).strip("()").replace(',',"_").replace(' ',""),';#chi;N',15,1,16)]
    plots += [TH1F(prefix+'mass',';dijet mass;N',260,0,13000)]
    for massbin in massbins:
     plots += [TH1F(prefix+'#chi'+str(massbin).strip("()").replace(',',"_").replace(' ',"")+"_PU_Up",';#chi;N',15,1,16)]
    plots += [TH1F(prefix+'mass'+"_PU_Up",';dijet mass;N',260,0,13000)]
    for massbin in massbins:
     plots += [TH1F(prefix+'#chi'+str(massbin).strip("()").replace(',',"_").replace(' ',"")+"_PU_Down",';#chi;N',15,1,16)]
    plots += [TH1F(prefix+'mass'+"_PU_Down",';dijet mass;N',260,0,13000)]
    
    for plot in plots:
        plot.Sumw2()
	print plot.GetName()

    event_count=0
    tree='Events'
    if "HT" in sample: tree="tree"
    events=TChain(tree)
    for f in files[:]:
      events.Add(f)
    
    nevents=events.GetEntries()
    print sample,nevents,xsec

    scales=["Nominal","PU_Up","PU_Down"]

    for event in events:
       #if event_count>10000000:break
       #if event_count>1000000:break
       #if event_count>100000:break
      
       event_count+=1
       if event_count%10000==1: print "event",event_count

       jet1=TLorentzVector()
       jet2=TLorentzVector()
       if "HT" in sample:
         if event.jetAK4_pt2<30: continue
         jet1.SetPtEtaPhiM(event.jetAK4_pt1,event.jetAK4_eta1,event.jetAK4_phi1,event.jetAK4_mass1)
         jet2.SetPtEtaPhiM(event.jetAK4_pt2,event.jetAK4_eta2,event.jetAK4_phi2,event.jetAK4_mass2)
	 nPuVtxTrue=event.nPuVtxTrue
       else:
         if len(event.recoGenJets_ak4GenJets__GEN.product())<2: continue
         jet1.SetPtEtaPhiM(event.recoGenJets_ak4GenJets__GEN.product()[0].pt(),event.recoGenJets_ak4GenJets__GEN.product()[0].eta(),event.recoGenJets_ak4GenJets__GEN.product()[0].phi(),event.recoGenJets_ak4GenJets__GEN.product()[0].mass())
         jet2.SetPtEtaPhiM(event.recoGenJets_ak4GenJets__GEN.product()[1].pt(),event.recoGenJets_ak4GenJets__GEN.product()[1].eta(),event.recoGenJets_ak4GenJets__GEN.product()[1].phi(),event.recoGenJets_ak4GenJets__GEN.product()[1].mass())
	 nPuVtxTrue=event.PileupSummaryInfo_genInfo__GEN.product().pileup_TrueNumInteractions()
       if jet1.Pt()<100 or jet2.Pt()<100 or abs(jet1.Eta())>3 or abs(jet2.Eta())>3: continue
              
       irec=0
       mjj=(jet1+jet2).M()
       chi=exp(abs(jet1.Rapidity()-jet2.Rapidity()))
       yboost=abs(jet1.Rapidity()+jet2.Rapidity())/2.
       for scale in scales:
	 if scale[-1]=="p":
	  weight=pileup_hists[year+"data_up"].Interpolate(nPuVtxTrue)/pileup_hists[year+"data_nom"].Interpolate(nPuVtxTrue)
	 elif scale[-1]=="n":
	  weight=pileup_hists[year+"data_down"].Interpolate(nPuVtxTrue)/pileup_hists[year+"data_nom"].Interpolate(nPuVtxTrue)
         else:
	  weight=1.
	 print weight, scale, event.nPuVtxTrue
	 for massbin in massbins:
           if yboost<1.11 and mjj>=massbin[0] and mjj<massbin[1]:
             plots[irec].Fill(chi, weight)
           irec+=1
         plots[irec].Fill(mjj, weight)
         irec+=1

    #jets="recoGenJets_ak4GenJets__GEN.obj"
    #yboost='abs('+jets+'[0].y()+'+jets+'[1].y())/2.'
    #chi='exp(abs('+jets+'[0].y()-'+jets+'[1].y()))'
    #mass='sqrt(pow('+jets+'[0].energy()+'+jets+'[1].energy(),2)-pow('+jets+'[0].px()+'+jets+'[1].px(),2)-pow('+jets+'[0].py()+'+jets+'[1].py(),2)-pow('+jets+'[0].pz()+'+jets+'[1].pz(),2))'
    #for massbin in massbins:
    #  events.Project(prefix+'#chi'+str(massbin).strip("()").replace(',',"_").replace(' ',""),chi,'('+yboost+'<1.11)*('+mass+'>='+str(massbin[0])+')*('+mass+'<'+str(massbin[1])+')')
    #  #events.Project(prefix+'y_{boost}'+str(massbin).strip("()").replace(',',"_").replace(' ',""),yboost,'('+chi+'<16)*('+mass+'>='+str(massbin[0])+')*('+mass+'<='+str(massbin[1])+')')
    if "HT" in sample:
      event_count/=nevents
    for plot in plots:
      if event_count>0:
        plot.Scale(xsec/event_count)
    return plots
Пример #41
0
gSystem.Load("libFWCoreFWLite.so")
AutoLibraryLoader.enable()

#import EcalDetId
#from DataFormats.EcalDetId import *
#
import sys, os

file = 'EcalRecalElectron.root'
file = 'root://eoscms//eos/cms/store/data/Run2015D/DoubleEG/MINIAOD/PromptReco-v4/000/259/862/00000/389D079E-EA7B-E511-9506-02163E0141D8.root'
file = 'root://eoscms//eos/cms//store/mc/RunIISpring15DR74/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/Asympt25ns_MCRUN2_74_V9-v3/10000/72F7A0B6-8E14-E511-8EBA-6C3BE5B58198.root'
print file
events = Events(file)

#handleElectrons = Handle('std::vector<reco::GsfElectron>')
handleElectrons = Handle('std::vector<pat::Electron>')
handleRecHitsEB = Handle(
    'edm::SortedCollection<EcalRecHit,edm::StrictWeakOrdering<EcalRecHit> >')
handleRecHitsEE = Handle(
    'edm::SortedCollection<EcalRecHit,edm::StrictWeakOrdering<EcalRecHit> >')
handleRecHitsES = Handle(
    'edm::SortedCollection<EcalRecHit,edm::StrictWeakOrdering<EcalRecHit> >')
handleRhoFastJet = Handle('double')
handleVertices = Handle('vector<reco::Vertex>')
electronTAG = 'gedGsfElectrons'
#electronTAG = 'electronRecalibSCAssociator'
electronTAG = 'slimmedElectrons'

print "run    lumi  event     isEB    energy     eSC  rawESC    e5x5    E_ES, etaEle, phiEle, etaSC, phiSC, clustersSize, nRecHits"
for event in events:
    event.getByLabel('offlineSlimmedPrimaryVertices', handleVertices)
Пример #42
0
def fetchCSCGEANT(event):
    geantH = Handle('vector<PSimHit>')
    event.getByLabel('g4SimHits:MuonCSCHits', geantH)
    geant = filter(lambda x: x.pabs() > 0.5 and abs(x.particleType()) == 13,
                   geantH.product())
    return geant
Пример #43
0
from __future__ import print_function
import ROOT
from DataFormats.FWLite import Handle, Events

events_c = Events('output_test_DDX.root')

handleJ = Handle("std::vector<pat::Jet>")
labelJ = ("selectedUpdatedPatJets", "", "PATtest")

h_probQ_ddb = ROOT.TH1F('h_probQ_ddb', ';prob Q;', 40, 0., 1.)
h_probH_ddb = ROOT.TH1F('h_probH_ddb', ';prob H;', 40, 0., 1.)

h_probQ_ddc = ROOT.TH1F('h_probQ_ddc', ';prob Q;', 40, 0., 1.)
h_probH_ddc = ROOT.TH1F('h_probH_ddc', ';prob H;', 40, 0., 1.)

for iev, event in enumerate(events_c):
    event.getByLabel(labelJ, handleJ)
    jets = handleJ.product()
    for jet in jets:
        if jet.pt() < 300 or jet.pt() > 2000: continue
        if jet.mass() < 40 or jet.mass() > 200: continue

        print(jet.pt(), jet.mass())
        print("DDB", jet.bDiscriminator("pfDeepDoubleBvLJetTags:probQCD"),
              jet.bDiscriminator("pfDeepDoubleBvLJetTags:probHbb"))
        print(
            "DDB",
            jet.bDiscriminator(
                "pfMassIndependentDeepDoubleBvLJetTags:probQCD"),
            jet.bDiscriminator(
                "pfMassIndependentDeepDoubleBvLJetTags:probHbb"))
Пример #44
0
def cscSegmentsPhi(event, ontime=True, twinMux=True):

    phiSeg = Handle('std::vector<std::pair<CSCDetId,CSCCorrelatedLCTDigi> >')
    event.getByLabel('cscTriggerHits', phiSeg)
    digis = phiSeg.product()
    return digis
Пример #45
0
ROOT.gROOT.SetBatch(True)
argv.remove('-b-')

ROOT.gSystem.Load("libFWCoreFWLite.so")
ROOT.gSystem.Load("libDataFormatsFWLite.so")
ROOT.AutoLibraryLoader.enable()

from DataFormats.FWLite import Handle, Events

if len(argv) == 1:
    print "Usage: %s file.root"
    exit()

events = Events(argv[1])

triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), (
    "TriggerResults", "", "HLT")
triggerObjects, triggerObjectLabel = Handle(
    "std::vector<pat::TriggerObjectStandAlone>"), "selectedPatTrigger"
triggerPrescales, triggerPrescaleLabel = Handle(
    "pat::PackedTriggerPrescales"), "patTrigger"

for iev, event in enumerate(events):
    event.getByLabel(triggerBitLabel, triggerBits)
    event.getByLabel(triggerObjectLabel, triggerObjects)
    event.getByLabel(triggerPrescaleLabel, triggerPrescales)

    print "\nEvent %d: run %6d, lumi %4d, event %12d" % (
        iev,
        event.eventAuxiliary().run(), event.eventAuxiliary().luminosityBlock(),
        event.eventAuxiliary().event())
Пример #46
0
ROOT.gROOT.SetBatch(True)
sys.argv = oldargv

c = ROOT.TChain("Events")
c.Add(sys.argv[1])
entries = c.GetEntries()

# load FWLite C++ libraries
ROOT.gSystem.Load("libFWCoreFWLite.so")
ROOT.gSystem.Load("libDataFormatsFWLite.so")
ROOT.FWLiteEnabler.enable()

# load FWlite python libraries
from DataFormats.FWLite import Handle, Events

triggerBits, triggerBitLabel = Handle("edm::TriggerResults"), (
    "TriggerResults", "", "HLT")
triggerObjects, triggerObjectLabel = Handle(
    "std::vector<pat::TriggerObjectStandAlone>"), "selectedPatTrigger"
triggerPrescales, triggerPrescaleLabel = Handle(
    "pat::PackedTriggerPrescales"), "patTrigger"

events = Events(sys.argv[1])
result = {}

for iev, event in enumerate(events):
    event.getByLabel(triggerBitLabel, triggerBits)
    event.getByLabel(triggerObjectLabel, triggerObjects)
    event.getByLabel(triggerPrescaleLabel, triggerPrescales)

    result['run'] = event.eventAuxiliary().run()
Пример #47
0
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
import ROOT
from DataFormats.FWLite import Events, Handle

ROOT.gROOT.SetBatch()



events = Events(sys.argv[1])

for event in events:
    lh = (("gedPhotons", "", "RECO"), Handle("vector<reco::Photon>"))
    event.getByLabel(*lh)
    photons = lh[1].product()
    for i, g in enumerate(photons):
        print(i, g.pt(), g.hasPixelSeed(), g.hadronicOverEm())
    print('-'*80)
Пример #48
0
ROOT.gROOT.SetBatch()  # don't pop up canvases

creator = ComponentCreator()

DYJetsToLL_M10to50 = creator.makeMCComponent(
    name='DYJetsToLL_M10to50',
    dataset=
    '/DYJetsToLL_M-10to50_TuneCP5_13TeV-madgraphMLM-pythia8/RunIIFall17MiniAODv2-PU2017_12Apr2018_94X_mc2017_realistic_v14-v1/MINIAODSIM',
    user='******',
    pattern='.*root',
    xSec=(1.581e+04) * 1.23,  # +- 2.890e+01 pb
    useAAA=True)

# fill with true interactions

handle = Handle('std::vector<PileupSummaryInfo>')
label = ("slimmedAddPileupInfo")

nfiles = len(DYJetsToLL_M10to50.files)
batch = 10
maxend = (nfiles - nfiles % batch) / batch + 1

print('\nnumber of batches: %d' % maxend)


def makehistos(batch, i, maxend):
    totevents = 0
    h_ti = ROOT.TH1F('pileup', 'pileup', 200, 0, 200)
    outfile = ROOT.TFile.Open('pileup_DYJetsToLL_M10to50_batch_%i.root' % i,
                              'recreate')
    begin = batch * (i)
                #['/eos/cms/store/user/lecriste/muonSelectors/AODSIM/store+mc+RunIIAutumn18DR+JpsiToMuMu_JpsiPt8_TuneCP5_13TeV-pythia8+AODSIM+PUAvg50ForMUOVal_102X_upgrade2018_realistic_v15-v2+90001+FD1B7E39-EBD0-AB4F-A8F1-B0FF2C232CCB.root',
                #'/eos/cms/store/user/lecriste/muonSelectors/AODSIM/store+mc+RunIIAutumn18DR+JpsiToMuMu_JpsiPt8_TuneCP5_13TeV-pythia8+AODSIM+PUAvg50ForMUOVal_102X_]
                # MiniAODSIM
                #open(inputDatasets+"JpsiToMuMu_JpsiPt8_13TeV-RunIIAutumn18MiniAOD_102X_upgrade2018-MINIAODSIM.txt").readlines()
                #['/eos/cms/store/user/lecriste/muonSelectors/MiniAODSIM/store+mc+RunIIAutumn18MiniAOD+JpsiToMuMu_JpsiPt8_TuneCP5_13TeV-pythia8+MINIAODSIM+102X_upgrade2018_realistic_v15-v1+270000+FE27B4EF-BB0C-F94F-8FFA-34ACC0934406.root',
                #'/eos/cms/store/user/lecriste/muonSelectors/MiniAODSIM/store+mc+RunIIAutumn18MiniAOD+JpsiToMuMu_JpsiPt8_TuneCP5_13TeV-pythia8+MINIAODSIM+102X_upgrade2018_realistic_v15-v1+270000+FE663B04-41AE-7F42-892C-22891454BB2C.root']
                # ForMUOVal
                #open(inputDatasets+"JpsiToMuMu_JpsiPt8_13TeV-RunIIAutumn18DR_PUAvg50ForMUOVal_102X_upgrade2018-MINIAODSIM-eos.txt").readlines()
                ['/eos/cms/store/user/lecriste/muonSelectors/MiniAODSIM/ForMUOVal/JpsiToMuMu/store+mc+RunIIAutumn18MiniAOD+JpsiToMuMu_JpsiPt8_TuneCP5_13TeV-pythia8+MINIAODSIM+PUAvg50+102X_upgrade2018_realistic_v15-v1+90000+FF849E84-E9A2-544B-86A9-DA963C26EF9D.root']
            },
        'maxBkgEff':0.15,
        'name':'JPsiToMuMu'
        }
    }

muonHandle, muonLabel = Handle("std::vector<pat::Muon>"), "slimmedMuons"

ROOT.gROOT.SetBatch(True)

##
## Main part
##


def LeptonMVA(muon, mva_threshold):
    dB2D = abs(muon.dB(ROOT.pat.Muon.BS2D))
    dB3D = abs(muon.dB(ROOT.pat.Muon.PV3D))
    edB3D = abs(muon.edB(ROOT.pat.Muon.PV3D))
    sip3D = 0.0
    if edB3D > 0: sip3D = dB3D / edB3D
    # dz = abs(muon.muonBestTrack().dz(primaryVertex.position()));
Пример #50
0
#eventsRef = Events('SinglePiPt1_ori.root')
#eventsNew = Events('SinglePi1_vinpotmatch.root')
#dir = "pi1"

#eventsRef = Events("TTBAR_relval_ori.root")
#eventsNew = Events("TTBAR_relval_vinpoptmatch.root")
#dir = 'ttbar'

eventsNew = Events("jetHT_reco_new2.root")
# eventsNew = Events('jetHT_reco_newTkGeom.root')

eventsRef = Events("jetHT_reco_710_ori.root")
# eventsNew = Events('jetHT_vinoptmatch_3.root')
dir = 'run2012C'

tracksRef = Handle("std::vector<reco::Track>")
tracksNew = Handle("std::vector<reco::Track>")
label = "generalTracks"
#quality = "tight"
quality = "highPurity"

#tracksRef = Handle("std::vector<reco::GsfTrack>")
#tracksNew = Handle("std::vector<reco::GsfTrack>")
#label = "electronGsfTracks"
# quality = "loose"

c1 = TCanvas('c1', 'vi', 200, 10, 1000, 500)
gStyle.SetOptStat(111111)
gStyle.SetHistLineWidth(2)

hh = TH1F("pt diff", "pt diff", 100, -0.001, 0.001)
Пример #51
0
def Match(inFiles, sample):

    h_npv = Handle("std::int")
    h_genparticles = Handle("vector<reco::GenParticle>")

    h_ak8_pt = Handle("std::vector<float>")
    h_ak8_eta = Handle("std::vector<float>")
    h_ak8_phi = Handle("std::vector<float>")
    h_ak8_e = Handle("std::vector<float>")

    l_npv = ("vertexInfo", "npv")

    l_genparticles = ("filteredPrunedGenParticles")

    l_ak8_pt = ("jetsAK8CHS", "jetAK8CHSPt")
    l_ak8_eta = ("jetsAK8CHS", "jetAK8CHSEta")
    l_ak8_phi = ("jetsAK8CHS", "jetAK8CHSPhi")
    l_ak8_e = ("jetsAK8CHS", "jetAK8CHSE")

    fileOut = rt.TFile.Open("jetMatchingTree_Hbb_t_" + sample + "_.root",
                            "RECREATE")

    tree = Tree("jetMatchingTree",
                "Tree for matching AK8 jets to gen H and t",
                model=Event)
    evts_processed = 0
    nOverallTop = 0
    nOverallHiggs = 0
    nPair = 0
    for f in inFiles:

        events = Events(f)

        nevents = 0

        for event in events:
            if evts_processed % 1000 == 0:
                print 'Events processed: ', evts_processed
            #if int(evts_processed) == 10000: break
            evts_processed += 1
            event.getByLabel(l_npv, h_npv)
            event.getByLabel(l_genparticles, h_genparticles)

            event.getByLabel(l_ak8_pt, h_ak8_pt)
            event.getByLabel(l_ak8_eta, h_ak8_eta)
            event.getByLabel(l_ak8_phi, h_ak8_phi)
            event.getByLabel(l_ak8_e, h_ak8_e)

            if len(h_npv.product()) < 1: continue

            #if len(h_ak8_pt.product()) < 1: continue

            tree.npv = h_npv.product()[0]

            n_AK8 = 0
            n_Higgs = 0
            n_Top = 0

            n_MatchedToHiggs = 0
            n_MatchedToTop = 0
            n_AK8MatchedToHiggs = 0
            n_AK8MatchedToTop = 0
            m_tH = 0
            p4_Higgs = []
            p4_Hdau0 = []
            p4_Hdau1 = []
            p4_Top = []
            p4_W = []
            p4_Tdau0 = []
            p4_Tdau1 = []
            p4_AK8 = []
            if h_genparticles.product().size() > 0:
                for igen in xrange(h_genparticles.product().size()):

                    pdgid = h_genparticles.product()[igen].pdgId()

                    nDaughters = h_genparticles.product(
                    )[igen].numberOfDaughters()

                    if abs(pdgid) == 25:
                        if nDaughters != 2: continue

                        firstDaughter = h_genparticles.product(
                        )[igen].daughter(0).pdgId()
                        secondDaughter = h_genparticles.product(
                        )[igen].daughter(1).pdgId()
                        if abs(firstDaughter) != 5 or abs(secondDaughter) != 5:
                            continue

                        genPt = h_genparticles.product()[igen].pt()
                        genEta = h_genparticles.product()[igen].eta()
                        genPhi = h_genparticles.product()[igen].phi()
                        genE = h_genparticles.product()[igen].energy()

                        dau0Pt = h_genparticles.product()[igen].daughter(
                            0).pt()
                        dau0Eta = h_genparticles.product()[igen].daughter(
                            0).eta()
                        dau0Phi = h_genparticles.product()[igen].daughter(
                            0).phi()
                        dau0E = h_genparticles.product()[igen].daughter(
                            0).energy()

                        dau1Pt = h_genparticles.product()[igen].daughter(
                            1).pt()
                        dau1Eta = h_genparticles.product()[igen].daughter(
                            1).eta()
                        dau1Phi = h_genparticles.product()[igen].daughter(
                            1).phi()
                        dau1E = h_genparticles.product()[igen].daughter(
                            1).energy()

                        p4GenHiggs = rt.TLorentzVector()
                        p4GenHiggs.SetPtEtaPhiE(genPt, genEta, genPhi, genE)

                        p4Hdau0 = rt.TLorentzVector()
                        p4Hdau0.SetPtEtaPhiE(dau0Pt, dau0Eta, dau0Phi, dau0E)

                        p4Hdau1 = rt.TLorentzVector()
                        p4Hdau1.SetPtEtaPhiE(dau1Pt, dau1Eta, dau1Phi, dau1E)

                        p4_Higgs.append(p4GenHiggs)
                        p4_Hdau0.append(p4Hdau0)
                        p4_Hdau1.append(p4Hdau1)

                        tree.pt_Higgs[n_Higgs] = p4GenHiggs.Pt()
                        tree.eta_Higgs[n_Higgs] = p4GenHiggs.Eta()
                        tree.phi_Higgs[n_Higgs] = p4GenHiggs.Phi()
                        tree.e_Higgs[n_Higgs] = p4GenHiggs.Energy()
                        tree.m_Higgs[n_Higgs] = p4GenHiggs.Mag()

                        n_Higgs += 1

                    elif abs(pdgid) == 6:
                        if nDaughters != 2: continue

                        firstDaughter = h_genparticles.product(
                        )[igen].daughter(0).pdgId()
                        secondDaughter = h_genparticles.product(
                        )[igen].daughter(1).pdgId()
                        hadronic = False
                        if abs(firstDaughter) == 24 and abs(
                                secondDaughter) == 5 or abs(
                                    firstDaughter) == 5 and abs(
                                        secondDaughter) == 24:
                            for idaughter in xrange(nDaughters):
                                if abs(h_genparticles.product()[igen].daughter(
                                        idaughter).pdgId()) != 24:
                                    continue
                                nGDaughters = h_genparticles.product(
                                )[igen].daughter(
                                    idaughter).numberOfDaughters()
                                for igDaughter in xrange(nGDaughters):
                                    gDaughter = h_genparticles.product(
                                    )[igen].daughter(idaughter).daughter(
                                        igDaughter).pdgId()
                                    if abs(gDaughter) == 24:
                                        nggDaughters = h_genparticles.product(
                                        )[igen].daughter(idaughter).daughter(
                                            igDaughter).numberOfDaughters()
                                        for iggDaughter in xrange(
                                                nggDaughters):
                                            ggDaughter = h_genparticles.product(
                                            )[igen].daughter(
                                                idaughter).daughter(
                                                    igDaughter).daughter(
                                                        iggDaughter).pdgId()
                                            if abs(ggDaughter) in xrange(1, 7):
                                                hadronic = True
                                            else:
                                                hadronic = False
                                    else:
                                        if abs(gDaughter) in xrange(1, 7):
                                            hadronic = True
                                        else:
                                            hadronic = False
                            if not hadronic: continue

                            genPt = h_genparticles.product()[igen].pt()
                            genEta = h_genparticles.product()[igen].eta()
                            genPhi = h_genparticles.product()[igen].phi()
                            genE = h_genparticles.product()[igen].energy()

                            dau0Pt = h_genparticles.product()[igen].daughter(
                                0).pt()
                            dau0Eta = h_genparticles.product()[igen].daughter(
                                0).eta()
                            dau0Phi = h_genparticles.product()[igen].daughter(
                                0).phi()
                            dau0E = h_genparticles.product()[igen].daughter(
                                0).energy()

                            dau1Pt = h_genparticles.product()[igen].daughter(
                                1).pt()
                            dau1Eta = h_genparticles.product()[igen].daughter(
                                1).eta()
                            dau1Phi = h_genparticles.product()[igen].daughter(
                                1).phi()
                            dau1E = h_genparticles.product()[igen].daughter(
                                1).energy()

                            p4GenTop = rt.TLorentzVector()
                            p4GenTop.SetPtEtaPhiE(genPt, genEta, genPhi, genE)

                            p4Tdau0 = rt.TLorentzVector()
                            p4Tdau0.SetPtEtaPhiE(dau0Pt, dau0Eta, dau0Phi,
                                                 dau0E)

                            p4Tdau1 = rt.TLorentzVector()
                            p4Tdau1.SetPtEtaPhiE(dau1Pt, dau1Eta, dau1Phi,
                                                 dau1E)

                            p4_Top.append(p4GenTop)
                            p4_Tdau0.append(p4Tdau0)
                            p4_Tdau1.append(p4Tdau1)

                            tree.pt_Top[n_Top] = p4GenTop.Pt()
                            tree.eta_Top[n_Top] = p4GenTop.Eta()
                            tree.phi_Top[n_Top] = p4GenTop.Phi()
                            tree.e_Top[n_Top] = p4GenTop.Energy()
                            tree.m_Top[n_Top] = p4GenTop.Mag()

                            if firstDaughter == 24:
                                tree.pt_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).pt()
                                tree.eta_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).eta()
                                tree.phi_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).phi()
                                tree.e_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(0).energy()

                                tree.m_W[n_Top] = p4Tdau0.Mag()
                            elif secondDaughter == 24:
                                p4_W.append(p4Tdau1)
                                tree.pt_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).pt()
                                tree.eta_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).eta()
                                tree.phi_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).phi()
                                tree.e_W[n_Top] = h_genparticles.product(
                                )[igen].daughter(1).energy()

                                tree.m_W[n_Top] = p4Tdau1.Mag()

                            n_Top += 1

            for ijet in xrange(len(h_ak8_pt.product())):
                jetPt = h_ak8_pt.product()[ijet]
                jetEta = h_ak8_eta.product()[ijet]
                jetPhi = h_ak8_phi.product()[ijet]
                jetE = h_ak8_e.product()[ijet]

                if abs(jetPt) < 300: continue
                if abs(jetEta) > 2.4: continue

                p4AK8 = rt.TLorentzVector()
                p4AK8.SetPtEtaPhiE(jetPt, jetEta, jetPhi, jetE)

                p4_AK8.append(p4AK8)

                tree.pt_AK8[n_AK8] = p4AK8.Pt()
                tree.eta_AK8[n_AK8] = p4AK8.Eta()
                tree.phi_AK8[n_AK8] = p4AK8.Phi()
                tree.e_AK8[n_AK8] = p4AK8.Energy()
                n_AK8 += 1
                if p4_Higgs:
                    for iHiggs in xrange(n_Higgs):
                        if p4AK8.DeltaR(p4_Higgs[iHiggs]) > 0.3: continue
                        if p4AK8.DeltaR(p4_Hdau0[iHiggs]) > 0.8: continue
                        if p4AK8.DeltaR(p4_Hdau1[iHiggs]) > 0.8: continue

                        tree.pt_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Pt()
                        tree.eta_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Eta()
                        tree.phi_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Phi()
                        tree.e_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Energy()
                        tree.m_MatchedHiggs[n_AK8MatchedToHiggs] = p4_Higgs[
                            iHiggs].Mag()

                        tree.pt_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Pt()
                        tree.eta_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Eta()
                        tree.phi_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Phi()
                        tree.e_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Energy()
                        tree.m_AK8MatchedToHiggs[
                            n_AK8MatchedToHiggs] = p4AK8.Mag()

                        n_AK8MatchedToHiggs = n_AK8MatchedToHiggs + 1
                if p4_Top:
                    for iTop in xrange(n_Top):
                        if p4AK8.DeltaR(p4_Top[iTop]) > 0.3: continue
                        if p4AK8.DeltaR(p4_Tdau0[iTop]) > 0.8: continue
                        if p4AK8.DeltaR(p4_Tdau1[iTop]) > 0.8: continue

                        tree.pt_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Pt()
                        tree.eta_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Eta(
                        )
                        tree.phi_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Phi(
                        )
                        tree.e_MatchedTop[n_MatchedToTop] = p4_Top[
                            iTop].Energy()
                        tree.m_MatchedTop[n_MatchedToTop] = p4_Top[iTop].Mag()

                        tree.pt_AK8MatchedToTop[n_AK8MatchedToTop] = p4AK8.Pt()
                        tree.eta_AK8MatchedToTop[
                            n_AK8MatchedToTop] = p4AK8.Eta()
                        tree.phi_AK8MatchedToTop[
                            n_AK8MatchedToTop] = p4AK8.Phi()
                        tree.e_AK8MatchedToTop[
                            n_AK8MatchedToTop] = p4AK8.Energy()
                        tree.m_AK8MatchedToTop[n_AK8MatchedToTop] = p4AK8.Mag()

                        n_AK8MatchedToTop = n_AK8MatchedToTop + 1

            if p4_Higgs and p4_Top:
                m_tH = (p4_Higgs[0] + p4_Top[0]).Mag()
                tree.m_tH = m_tH
            if n_AK8MatchedToTop > 0:
                nOverallTop += 1
            if n_AK8MatchedToHiggs > 0:
                nOverallHiggs += 1
            if n_AK8MatchedToTop > 0 and n_AK8MatchedToHiggs > 0:
                nPair += 1
            tree.n_AK8 = n_AK8
            tree.n_Higgs = n_Higgs
            tree.n_Top = n_Top
            tree.n_AK8MatchedToHiggs = n_AK8MatchedToHiggs
            tree.n_AK8MatchedToTop = n_AK8MatchedToTop
            tree.nevents = nevents
            tree.fill()

            nevents += 1
    print nOverallTop
    print nOverallHiggs
    print nPair
    tree.Write()
    fileOut.Close()
Пример #52
0
def processSubsample(file):
    events = Events (file)

    # create handle outside of loop
    genhandle          = Handle ('std::vector<reco::GenParticle>')
    elehandle          = Handle ('std::vector<cmg::DiObject<cmg::Electron,cmg::Electron> >')
    muhandle           = Handle ('std::vector<cmg::DiObject<cmg::Muon,cmg::Muon> >')
    jethandle          = Handle ('std::vector<cmg::VJet>')
    # like and edm::InputTag
    nevent = 0 
    for event in events:
        nevent += 1
        if nevent % 10000 ==0:
            print "event: " + str(nevent)
            
        #print str(event.eventAuxiliary().run())
        #print str(event.object().triggerResultsByName("CMG").accept("preselEleMergedPath"))
        # determine generated flavor and get generated kinematics
        haveleptons=0
        havejet=0
        havez=0
        flavor=""
        genZlep      = root.TLorentzVector()
        genlepton1p4 = root.TLorentzVector()
        genlepton1C  = 0
        genlepton2p4 = root.TLorentzVector()
        genlepton2C  = 0
        genjetp4     = root.TLorentzVector()
        event.getByLabel ("genParticles", genhandle)
        genparticles = genhandle.product()
        for genp in genparticles:
            if (abs(genp.pdgId())==11 or abs(genp.pdgId())==13) and genp.mother().pdgId()==23:
                #print "found lepton "+str(genp.pdgId())
                if(abs(genp.pdgId())==11):
                    flavor = "ele"
                if(abs(genp.pdgId())==13):
                    flavor = "mu"                    
                if haveleptons==0:
                    genlepton1p4 = genp.p4()
                    genlepton1C = genp.charge()
                    haveleptons=1                
                elif haveleptons==1:
                    genlepton2p4 = genp.p4()
                    genlepton2C = genp.charge()
                    haveleptons=2
            if abs(genp.pdgId())==23 and genp.numberOfDaughters()>0 and abs(genp.daughter(1).pdgId())<7:
                genjetp4=genp.p4()
                havejet=1
            if abs(genp.pdgId())==23 and genp.numberOfDaughters()>0 and abs(genp.daughter(1).pdgId())>7:
                genZlep=genp.p4()
                havez=1

            if haveleptons==2 and havejet==1 and havez==1:
                break

        #print str(nevent)+ "  " + flavor
        # gen-level acceptance cuts:
        if genjetp4.pt()<80: # hadronic Z acceptance cut
            continue
        if genjetp4.mass()<70 or genjetp4.mass()>110: # hadronic Z acceptance cut
            continue        
        if (genlepton1p4 + genlepton2p4).pt() < 80: # leptonic Z acceptance cut
            continue 
        if (genlepton1p4 + genlepton2p4).mass() < 70 or(genlepton1p4 + genlepton2p4).mass() >110 :
            continue 
        if flavor == "ele": # electron acceptance
            if abs(genlepton1p4.eta())>2.5:
                continue
            if abs(genlepton2p4.eta())>2.5:
                continue
            if genlepton1p4.pt()<40 or genlepton2p4.pt()<40:
                continue
        if flavor == "mu": # muon acceptance
            if abs(genlepton1p4.eta())>2.4:
                continue
            if abs(genlepton2p4.eta())>2.4:
                continue
            if genlepton1p4.pt()<20 or genlepton2p4.pt()<20:
                continue
            if genlepton1p4.pt()<40 and genlepton2p4.pt()<40:
                contine
        if genjetp4.pt() <30: # jet acceptance
            continue
        if abs(genjetp4.eta())>2.4:
            continue

            
        #fill pure gen info
        if flavor == "ele":
            histo_ele_gen.Fill(genZlep.pt(),abs(genZlep.Eta()))
        if flavor == "mu":
            histo_mu_gen.Fill(genZlep.pt(),abs(genZlep.Eta()))
        histo_jet_gen.Fill(genjetp4.pt(),abs(genjetp4.eta()))

        if(event.eventAuxiliary().event() ==  2434343111):# strange fualty event
            continue
        if(event.eventAuxiliary().event() ==  43111):# strange fualty event
            continue
        #print str(event.eventAuxiliary().event())
        # fill matched jets objects
        event.getByLabel ("jetIDMerged", jethandle)
        recojets = jethandle.product()
        closest = -1
        closestDr = 99999.
        index = -1
        for jet in recojets:
            index += 1
            #acceptance cuts
            if jet.prunedMass() < 70 or jet.prunedMass() > 110:
                continue
            if jet.pt() < 80:
                continue
            if abs(jet.eta())>2.4:
                continue
            if not jet.getSelection("cuts_looseJetId"):
                continue
            if not jet.getSelection("cuts_TOBTECjetsId"):
                continue
            if jet.sourcePtr().get().userFloat("tau2")/jet.sourcePtr().get().userFloat("tau1") > 0.5:
                continue
            
            histo_jet_reco.Fill(jet.pt(),abs(jet.eta()))
            dr = deltaR(jet.eta(),jet.phi(),genjetp4.eta(),genjetp4.phi())
            if dr < closestDr:
                closestDr = dr
                closest = index

        if index != -1 and closestDr < 0.8: # found a matching VJet
            histo_jet_genMatch.Fill(genjetp4.pt(),abs(genjetp4.eta()))
            histo_jet_recoMatch.Fill(recojets[index].pt(),abs(recojets[index].eta()))
            if histo_jet_genMatch.FindBin(genjetp4.pt(),abs(genjetp4.eta())) == histo_jet_genMatch.FindBin(recojets[index].pt(),abs(recojets[index].eta())):
                histo_jet_stab.Fill(genjetp4.pt(),abs(genjetp4.eta()))
                histo_jet_pur.Fill(recojets[index].pt(),abs(recojets[index].eta()))

        #only proceed to leptons if event filters pass
        #this ensures trigger eff is taken into account
        #other event fitlers could go anywhere but need to be restricted to
        #either leptons or jets to avoid double counting
        if not event.object().triggerResultsByName("CMG").accept("eventFilterPath"):
            #print "failed trigger"
            continue

        #print "startele"
        # fill matched electrons objects
        if flavor == "ele":
            event.getByLabel ("ZeeCand", elehandle)
            recoeles = elehandle.product()
            closest1 = -1
            closestDr1 = 99999.
            index1 = -1
            for ele in recoeles:
                index1 += 1
            #acceptance cuts
                if ele.pt() < 80:
                    continue
            
                histo_ele_reco.Fill(ele.pt(),abs(ele.eta()))
                dr1 = deltaR(ele.eta(),ele.phi(),genZlep.eta(),genZlep.phi())
                if dr1 < closestDr1 :
                    closestDr1 = dr1
                    closest1 = index1

            if index1 != -1 and closestDr1 < 0.5: # found a matching electron for genlepon1
                histo_ele_genMatch.Fill(genZlep.pt(),abs(genZlep.Eta()))
                if histo_ele_genMatch.FindBin(genZlep.pt(),abs(genZlep.Eta())) == histo_ele_genMatch.FindBin(recoeles[index1].pt(),abs(recoeles[index1].eta())):
                    histo_ele_stab.Fill(genZlep.pt(),abs(genZlep.Eta()))
                    histo_ele_pur.Fill(recoeles[index1].pt(),abs(recoeles[index1].eta()))

    
           
       # fill matched muon objects
        if flavor == "mu":
            event.getByLabel ("ZmmCand", muhandle)
            recomus = muhandle.product()
            closest1 = -1
            closestDr1 = 99999.
            index1 = -1
            for mu in recomus:
                index1 += 1
            #acceptance cuts
                if mu.pt() < 80:
                    continue
                
                histo_mu_reco.Fill(mu.pt(),abs(mu.eta()))
                dr1 = deltaR(mu.eta(),mu.phi(),genZlep.eta(),genZlep.phi())
                if dr1 < closestDr1 :
                    closestDr1 = dr1
                    closest1 = index1


            if index1 != -1 and closestDr1 < 0.1: # found a matching muctron for genlepon1
                histo_mu_genMatch.Fill(genZlep.pt(),abs(genZlep.Eta()))
                histo_mu_recoMatch.Fill(recomus[index1].pt(),abs(recomus[index1].eta()))
                if histo_mu_genMatch.FindBin(genZlep.pt(),abs(genZlep.Eta())) == histo_mu_genMatch.FindBin(recomus[index1].pt(),abs(recomus[index1].eta())):
                    histo_mu_stab.Fill(genZlep.pt(),abs(genZlep.Eta()))
                    histo_mu_pur.Fill(recomus[index1].pt(),abs(recomus[index1].eta()))
Пример #53
0
import ROOT
from DataFormats.FWLite import Handle, Events

events = Events(
    "root://cmseos.fnal.gov//store/user/jmanagan/TrackingHATS2017/tracks_and_vertices_DoubleMuon2017C_299370.root"
)

clusterSummary = Handle("ClusterSummary")

h = ROOT.TH2F("h", "h", 100, 0, 20000, 100, 0, 100000)

events.toBegin()
for event in events:
    event.getByLabel("clusterSummaryProducer", clusterSummary)
    cs = clusterSummary.product()
    try:
        h.Fill(
            cs.GetGenericVariable(cs.NMODULESPIXELS, cs.BPIX) +
            cs.GetGenericVariable(cs.NMODULESPIXELS, cs.FPIX),
            cs.GetGenericVariable(cs.NMODULES, cs.TRACKER))
    except TypeError:
        pass

h.Draw()
h.Fit("pol1")
#events_wgjets_3 = Events(['/afs/cern.ch/work/a/amlevin/delete_this/HIG-RunIIFall17wmLHEGS-01060.root.bak','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.43.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.55.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.57.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.64.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.59.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.73.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.45.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.61.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.77.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.51.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.44.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.65.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.75.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.42.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.41.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.54.root','/afs/cern.ch/work/a/amlevin/tmp/HIG-RunIIFall17wmLHEGS-01060.53.root'])

#events_wgjets_3 = Events(['/afs/cern.ch/work/a/amlevin/delete_this/HIG-RunIIFall17wmLHEGS-01060_NLO_POWHEG.root'])

xs_wgjets_1 = 60670
#xs_wgjets_1 = 10980
#xs_wgjets_1 = 495.8
#xs_wgjets_1 = 196.4
#xs_wgjets_1 = 179.1
xs_wgjets_2 = 178.6

xs_wgjets_3 = 10908

#xs_wgjets = xs_wjets

lheinfo, lheinfoLabel = Handle("LHEEventProduct"), "externalLHEProducer"
geninfo, geninfoLabel = Handle("GenEventInfoProduct"), "generator"
genparticles, genParticlesLabel = Handle(
    "vector<reco::GenParticle>"), "genParticles"

# loop over events
count = 0
countweighted = 0

th1f_wgjets_1_njets = ROOT.TH1F("wgjets 1 njets", "", 7, -0.5, 6.5)
th1f_wgjets_2_njets = ROOT.TH1F("wgjets 2 njets", "", 7, -0.5, 6.5)
th1f_wgjets_3_njets = ROOT.TH1F("wgjets 3 njets", "", 7, -0.5, 6.5)

th1f_wgjets_1_nphotons = ROOT.TH1F("wgjets 1 nphotons", "", 7, -0.5, 6.5)
th1f_wgjets_2_nphotons = ROOT.TH1F("wgjets 2 nphotons", "", 7, -0.5, 6.5)
th1f_wgjets_3_nphotons = ROOT.TH1F("wgjets 3 nphotons", "", 7, -0.5, 6.5)
from ROOT import *
from math import sqrt
from DataFormats.FWLite import Handle, Events
events = Events("output.root")
secondaryVertices = Handle("std::vector<reco::VertexCompositeCandidate>")
mass_histogram = TH1F("mass", "mass", 100, 0.4, 0.6)
dxy_histogram = TH1F("dxy", "dxy", 100, 0, 50)

i = 0
events.toBegin()
for event in events:
    print "Event:", i
    event.getByLabel("SecondaryVerticesFromLooseTracks", "Kshort",
                     secondaryVertices)
    j = 0
    sv = secondaryVertices.product()
    for vertex in sv:
        print "    Vertex:", j, vertex.vx(), vertex.vy(), vertex.vz()
        mass_histogram.Fill(vertex.mass())
        dxy_histogram.Fill(sqrt(vertex.vx()**2 + vertex.vy()**2))
        j += 1

    i += 1
c = TCanvas("c", "c", 800, 800)
mass_histogram.Draw()
c.SaveAs("sec_vert_mass.png")

c2 = TCanvas("c2", "c2", 800, 800)
dxy_histogram.Draw()
c2.SaveAs("sec_vert_dxy.png")
Пример #56
0
def main():
    vhdl_dict = VHDLConstantsParser.parse_vhdl_file(
        "../data/ugmt_constants.vhd")

    opts = parse_options()
    nSkip = opts.skip
    fname_dict = discover_emu_files(opts.emudirectory)
    # rankLUT = l1t.MicroGMTRankPtQualLUT()

    ALGODELAY = opts.delay + 27  #first frame with valid = 1

    max_events = int((1024 - ALGODELAY) / 6)

    for pattern, fnames in fname_dict.iteritems():
        print "+" * 30, pattern, "+" * 30
        events = Events(fnames['root'])

        start = time.time()

        out_handle = Handle('BXVector<l1t::Muon>')
        imd_bmtf_handle = Handle('BXVector<l1t::Muon>')
        imd_emtf_p_handle = Handle('BXVector<l1t::Muon>')
        imd_emtf_n_handle = Handle('BXVector<l1t::Muon>')
        imd_omtf_p_handle = Handle('BXVector<l1t::Muon>')
        imd_omtf_n_handle = Handle('BXVector<l1t::Muon>')
        bar_handle = Handle('BXVector<l1t::RegionalMuonCand>')
        fwd_handle = Handle('BXVector<l1t::RegionalMuonCand>')
        ovl_handle = Handle('BXVector<l1t::RegionalMuonCand>')
        calo_handle = Handle('BXVector<l1t::MuonCaloSum>')

        basedir_mp7 = "../data/patterns/compressed/"
        path = '{path}/{pattern}/'.format(path=basedir_mp7, pattern=pattern)

        input_buffer = PatternDumper(path + pattern + ".txt", vhdl_dict,
                                     BufferWriter)
        output_buffer = PatternDumper(path + pattern + "_out.txt", vhdl_dict,
                                      BufferWriter)

        if opts.delay > 0:
            input_buffer.writeEmptyFrames(opts.delay)

        setup_time = time.time() - start

        avg_get_label_time = 0
        avg_conversion_time = 0
        avg_write_time = 0

        output_buffer.writeEmptyFrames(ALGODELAY)
        cntr = 0
        for i, event in enumerate(events):
            if i < nSkip:
                continue

            #print 'event: {evt} {evNr}'.format(evt=i, evNr=event.eventAuxiliary().event())

            evt_start = time.time()
            event.getByLabel("simGmtStage2Digis", out_handle)
            event.getByLabel("simGmtStage2Digis", "imdMuonsBMTF",
                             imd_bmtf_handle)
            event.getByLabel("simGmtStage2Digis", "imdMuonsEMTFPos",
                             imd_emtf_p_handle)
            event.getByLabel("simGmtStage2Digis", "imdMuonsEMTFNeg",
                             imd_emtf_n_handle)
            event.getByLabel("simGmtStage2Digis", "imdMuonsOMTFPos",
                             imd_omtf_p_handle)
            event.getByLabel("simGmtStage2Digis", "imdMuonsOMTFNeg",
                             imd_omtf_n_handle)
            event.getByLabel("simBmtfDigis", "BMTF", bar_handle)
            event.getByLabel("simEmtfDigis", "EMTF", fwd_handle)
            event.getByLabel("simOmtfDigis", "OMTF", ovl_handle)
            #event.getByLabel("gmtStage2Digis", "BMTF", bar_handle)
            #event.getByLabel("gmtStage2Digis", "EMTF", fwd_handle)
            #event.getByLabel("gmtStage2Digis", "OMTF", ovl_handle)

            event.getByLabel("simGmtCaloSumDigis", "TriggerTowerSums",
                             calo_handle)
            #event.getByLabel("emptyCaloCollsProducer", "EmptyTriggerTowerSums", calo_handle)
            #event.getByLabel("simGmtCaloSumDigis", "TriggerTower2x2s", calo_handle)
            get_label_time = time.time() - evt_start
            calo_sums_raw = calo_handle.product()
            calo_sums = get_calo_list(calo_sums_raw)

            emu_out_muons = out_handle.product()
            outmuons = get_muon_list_out(emu_out_muons, "OUT", vhdl_dict)
            imd_emtf_p_prod = imd_emtf_p_handle.product()
            imdmuons = get_muon_list_out(imd_emtf_p_prod, "IMD", vhdl_dict, 4)
            imd_omtf_p_prod = imd_omtf_p_handle.product()
            imdmuons += get_muon_list_out(imd_omtf_p_prod, "IMD", vhdl_dict, 4)
            imd_bmtf_prod = imd_bmtf_handle.product()
            imdmuons += get_muon_list_out(imd_bmtf_prod, "IMD", vhdl_dict, 8)
            imd_omtf_n_prod = imd_omtf_n_handle.product()
            imdmuons += get_muon_list_out(imd_omtf_n_prod, "IMD", vhdl_dict, 4)
            imd_emtf_n_prod = imd_emtf_n_handle.product()
            imdmuons += get_muon_list_out(imd_emtf_n_prod, "IMD", vhdl_dict, 4)

            emu_bar_muons = bar_handle.product()
            bar_muons = get_muon_list(emu_bar_muons, "BMTF", vhdl_dict, i)
            emu_ovl_muons = ovl_handle.product()
            ovlp_muons = get_muon_list(emu_ovl_muons, "OMTF_POS", vhdl_dict, i)
            ovln_muons = get_muon_list(emu_ovl_muons, "OMTF_NEG", vhdl_dict, i)
            emu_fwd_muons = fwd_handle.product()
            fwdp_muons = get_muon_list(emu_fwd_muons, "EMTF_POS", vhdl_dict, i)
            fwdn_muons = get_muon_list(emu_fwd_muons, "EMTF_NEG", vhdl_dict, i)

            conversion_time = time.time() - evt_start - get_label_time

            for mu in outmuons:
                if mu.bitword != 0:
                    cntr += 1
            input_buffer.writeFrameBasedInputBX(bar_muons, fwdp_muons,
                                                fwdn_muons, ovlp_muons,
                                                ovln_muons, calo_sums)
            output_buffer.writeFrameBasedOutputBX(outmuons, imdmuons)

            if i % (max_events - 1) == 0 and i != 0:  # dump every max_events
                ifile = i / max_events
                print "Writing file {pattern}_{ifile}.zip for event {i}".format(
                    pattern=pattern, ifile=ifile, i=i)
                dump_files(path, pattern, ifile, input_buffer, output_buffer,
                           opts.delay, ALGODELAY)

            if (i + 1) % 1000 == 0:
                print "  processing the {i}th event".format(i=i + 1)

            write_time = time.time() - evt_start - conversion_time
            avg_get_label_time += get_label_time
            avg_conversion_time += conversion_time
            avg_write_time += write_time
        print "total: ", time.time() - start
        print "setup: ", setup_time
        print "get_label:", "avg", avg_get_label_time / float(
            i + 1), "last", get_label_time
        print "conversion: avg", avg_conversion_time / float(
            i + 1), "last", conversion_time
        print "write: avg", avg_write_time / float(i + 1), "last", write_time
        print 'n final muons: ', cntr
        if i % (max_events - 1) != 0:
            ifile = i / max_events
            dump_files(path, pattern, ifile, input_buffer, output_buffer,
                       opts.delay, ALGODELAY)

        print(i + 1) / max_events
Пример #57
0

## _____________      __.____    .__  __             _________ __          _____  _____
## \_   _____/  \    /  \    |   |__|/  |_  ____    /   _____//  |_ __ ___/ ____\/ ____\
##  |    __) \   \/\/   /    |   |  \   __\/ __ \   \_____  \\   __\  |  \   __\\   __\
##  |     \   \        /|    |___|  ||  | \  ___/   /        \|  | |  |  /|  |   |  |
##  \___  /    \__/\  / |_______ \__||__|  \___  > /_______  /|__| |____/ |__|   |__|
##      \/          \/          \/             \/          \/

import ROOT
import sys
import copy
from array import array
from DataFormats.FWLite import Events, Handle
ROOT.gROOT.Macro("rootlogon.C")
jethandle0  = Handle ("std::vector<pat::Jet>")
jetlabel0 = ("slimmedJets")
jethandle1  = Handle ("std::vector<pat::Jet>")
jetlabel1 = ("slimmedJetsAK8")

rhoHandle = Handle ("double")
rhoLabel = ("fixedGridRhoAll")

pvHandle = Handle("std::vector<reco::Vertex>")
pvLabel = ("offlineSlimmedPrimaryVertices")




if options.smearJets and options.isData :
    print 'Misconfiguration. I cannot access generator-level jets on data. Not smearing jets.'
Пример #58
0
    0.0003, 
    0.0005, 
    0.0012,
]

# ctau weights, each coupling gets its own weight
weights = OrderedDict(zip(new_v2s, np.ones(len(new_v2s))))

# add weight branches
for vv in new_v2s:
    branches.append('weight_%s'      %(str(vv).replace('-', 'm')))
    branches.append('ctau_%s'        %(str(vv).replace('-', 'm')))
    branches.append('xs_scale_to_%s' %(str(vv).replace('-', 'm')))

handles = OrderedDict()
handles['genP'] = ('genParticles' , Handle('std::vector<reco::GenParticle>'))
#handles['genp_packed'] = ('packedGenParticles' , Handle('std::vector<pat::PackedGenParticle>'))
#handles['lhe']         = ('externalLHEProducer', Handle('LHEEventProduct'))

# output file and tree gymnastics
#outfile = ROOT.TFile.Open('genNTuples_ctau100mm_fullEvtGen_10k.root', 'recreate')
outfile = ROOT.TFile.Open('myGen_V31.root', 'recreate')
#outfile = ROOT.TFile.Open('outputfiles/genNTuples_V04_semileptonic_higherDisplacement.root', 'recreate')
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('/pnfs/psi.ch/cms/trivcat/store/user/anlyon/BHNLsGen/V02_testLeptonic_n450000_njt100/mass1.5_ctau51.922757246/step1_nj95.root')
Пример #59
0
import ROOT
import itertools
import math
from DataFormats.FWLite import Events, Handle
from Display import *

hfH  = Handle('std::vector<reco::PFRecHit>')
ecalH  = Handle ('std::vector<reco::PFRecHit>')
ekH = Handle('std::vector<reco::PFRecHit>')
hcalH  = Handle ('std::vector<reco::PFRecHit>')
genParticlesH  = Handle ('std::vector<reco::GenParticle>')
tracksH  = Handle ('std::vector<reco::PFRecTrack>')
ecalClustersH  = Handle ('std::vector<reco::PFCluster>')
hcalClustersH  = Handle ('std::vector<reco::PFCluster>')
#arborH  = Handle ('std::vector<reco::PFCluster>')
hcalSeedsH  = Handle ('std::vector<reco::PFRecHit>')
simH = Handle('std::vector<reco::PFSimParticle>')
simHitsH = Handle('std::vector<PCaloHit>')
simTrackH = Handle('std::vector<SimTrack>')
simVertexH = Handle('std::vector<SimVertex>')
events = Events('reco.root')


for event in events:
    event.getByLabel('particleFlowRecHitHF',hfH)
    #event.getByLabel('particleFlowRecHitECALWithTime',ecalH)
    #event.getByLabel('particleFlowRecHitEK',ekH)
    event.getByLabel('particleFlowRecHitHBHEHO',hcalH)
    event.getByLabel('genParticles',genParticlesH)
    event.getByLabel('pfTrack',tracksH)
    #event.getByLabel('particleFlowClusterECAL',ecalClustersH)
Пример #60
0
 def __init__(self, dtype, label):
     self.handle = Handle(dtype)
     if isinstance(label, tuple) or isinstance(label, list):
         self.label = tuple(label)
     else:
         self.label = (label, )