CMS 3D CMS Logo

JetAnalyzer.py
Go to the documentation of this file.
1 import math, os
2 from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer
3 from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle
4 from PhysicsTools.Heppy.physicsobjects.PhysicsObjects import Jet
5 from PhysicsTools.HeppyCore.utils.deltar import deltaR2, deltaPhi, matchObjectCollection, matchObjectCollection2, bestMatch,matchObjectCollection3
6 from PhysicsTools.Heppy.physicsutils.JetReCalibrator import JetReCalibrator
7 import PhysicsTools.HeppyCore.framework.config as cfg
8 
9 from PhysicsTools.Heppy.physicsutils.QGLikelihoodCalculator import QGLikelihoodCalculator
10 
11 import six
12 import copy
13 def cleanNearestJetOnly(jets,leptons,deltaR):
14  dr2 = deltaR**2
15  good = [ True for j in jets ]
16  for l in leptons:
17  ibest, d2m = -1, dr2
18  for i,j in enumerate(jets):
19  d2i = deltaR2(l.eta(),l.phi(), j.eta(),j.phi())
20  if d2i < d2m:
21  ibest, d2m = i, d2i
22  if ibest != -1: good[ibest] = False
23  return [ j for (i,j) in enumerate(jets) if good[i] == True ]
24 
25 def cleanJetsAndLeptons(jets,leptons,deltaR,arbitration):
26  dr2 = deltaR**2
27  goodjet = [ True for j in jets ]
28  goodlep = [ True for l in leptons ]
29  for il, l in enumerate(leptons):
30  ibest, d2m = -1, dr2
31  for i,j in enumerate(jets):
32  d2i = deltaR2(l.eta(),l.phi(), j.eta(),j.phi())
33  if d2i < dr2:
34  choice = arbitration(j,l)
35  if choice == j:
36  # if the two match, and we prefer the jet, then drop the lepton and be done
37  goodlep[il] = False
38  break
39  elif choice == (j,l) or choice == (l,j):
40  # asked to keep both, so we don't consider this match
41  continue
42  if d2i < d2m:
43  ibest, d2m = i, d2i
44  # this lepton has been killed by a jet, then we clean the jet that best matches it
45  if not goodlep[il]: continue
46  if ibest != -1: goodjet[ibest] = False
47  return ( [ j for (i ,j) in enumerate(jets) if goodjet[i ] == True ],
48  [ l for (il,l) in enumerate(leptons) if goodlep[il] == True ] )
49 
50 
51 
52 def shiftJERfactor(JERShift, aeta):
53  factor = 1.079 + JERShift*0.026
54  if aeta > 3.2: factor = 1.056 + JERShift * 0.191
55  elif aeta > 2.8: factor = 1.395 + JERShift * 0.063
56  elif aeta > 2.3: factor = 1.254 + JERShift * 0.062
57  elif aeta > 1.7: factor = 1.208 + JERShift * 0.046
58  elif aeta > 1.1: factor = 1.121 + JERShift * 0.029
59  elif aeta > 0.5: factor = 1.099 + JERShift * 0.028
60  return factor
61 
62 
63 
64 
65 
66 class JetAnalyzer( Analyzer ):
67  """Taken from RootTools.JetAnalyzer, simplified, modified, added corrections """
68  def __init__(self, cfg_ana, cfg_comp, looperName):
69  super(JetAnalyzer,self).__init__(cfg_ana, cfg_comp, looperName)
70  mcGT = cfg_ana.mcGT if hasattr(cfg_ana,'mcGT') else "PHYS14_25_V2"
71  dataGT = cfg_ana.dataGT if hasattr(cfg_ana,'dataGT') else "GR_70_V2_AN1"
72  self.shiftJEC = self.cfg_ana.shiftJEC if hasattr(self.cfg_ana, 'shiftJEC') else 0
73  self.recalibrateJets = self.cfg_ana.recalibrateJets
74  self.addJECShifts = self.cfg_ana.addJECShifts if hasattr(self.cfg_ana, 'addJECShifts') else 0
75  if self.recalibrateJets == "MC" : self.recalibrateJets = self.cfg_comp.isMC
76  elif self.recalibrateJets == "Data": self.recalibrateJets = not self.cfg_comp.isMC
77  elif self.recalibrateJets not in [True,False]: raise RuntimeError("recalibrateJets must be any of { True, False, 'MC', 'Data' }, while it is %r " % self.recalibrateJets)
78 
79  calculateSeparateCorrections = getattr(cfg_ana,"calculateSeparateCorrections", False);
80  calculateType1METCorrection = getattr(cfg_ana,"calculateType1METCorrection", False);
81  self.doJEC = self.recalibrateJets or (self.shiftJEC != 0) or self.addJECShifts or calculateSeparateCorrections or calculateType1METCorrection
82  if self.doJEC:
83  doResidual = getattr(cfg_ana, 'applyL2L3Residual', 'Data')
84  if doResidual == "MC": doResidual = self.cfg_comp.isMC
85  elif doResidual == "Data": doResidual = not self.cfg_comp.isMC
86  elif doResidual not in [True,False]: raise RuntimeError("If specified, applyL2L3Residual must be any of { True, False, 'MC', 'Data'(default)}")
87  GT = getattr(cfg_comp, 'jecGT', mcGT if self.cfg_comp.isMC else dataGT)
88  # Now take care of the optional arguments
89  kwargs = { 'calculateSeparateCorrections':calculateSeparateCorrections,
90  'calculateType1METCorrection' :calculateType1METCorrection, }
91  if kwargs['calculateType1METCorrection']: kwargs['type1METParams'] = cfg_ana.type1METParams
92  # instantiate the jet re-calibrator
93  self.jetReCalibrator = JetReCalibrator(GT, cfg_ana.recalibrationType, doResidual, cfg_ana.jecPath, **kwargs)
94  self.doPuId = getattr(self.cfg_ana, 'doPuId', True)
95  self.jetLepDR = getattr(self.cfg_ana, 'jetLepDR', 0.4)
96  self.jetLepArbitration = getattr(self.cfg_ana, 'jetLepArbitration', lambda jet,lepton: lepton)
97  self.lepPtMin = getattr(self.cfg_ana, 'minLepPt', -1)
98  self.lepSelCut = getattr(self.cfg_ana, 'lepSelCut', lambda lep : True)
99  self.jetGammaDR = getattr(self.cfg_ana, 'jetGammaDR', 0.4)
100  self.jetGammaLepDR = getattr(self.cfg_ana, 'jetGammaLepDR', 0.4)
101  self.cleanFromLepAndGammaSimultaneously = getattr(self.cfg_ana, 'cleanFromLepAndGammaSimultaneously', False)
103  if hasattr(self.cfg_ana, 'jetGammaLepDR'):
104  self.jetGammaLepDR = self.jetGammaLepDR
105  elif (self.jetGammaDR == self.jetLepDR):
106  self.jetGammaLepDR = self.jetGammaDR
107  else:
108  raise RuntimeError("DR for simultaneous cleaning of jets from leptons and photons is not defined, and dR(gamma, jet)!=dR(lep, jet)")
109  if(self.cfg_ana.doQG):
110  qgdefname="{CMSSW_BASE}/src/PhysicsTools/Heppy/data/pdfQG_AK4chs_13TeV_v2b.root"
111  self.qglcalc = QGLikelihoodCalculator(getattr(self.cfg_ana,"QGpath",qgdefname).format(CMSSW_BASE= os.environ['CMSSW_BASE']))
112  if not hasattr(self.cfg_ana ,"collectionPostFix"):self.cfg_ana.collectionPostFix=""
113 
114  def declareHandles(self):
115  super(JetAnalyzer, self).declareHandles()
116  self.handles['jets'] = AutoHandle( self.cfg_ana.jetCol, 'std::vector<pat::Jet>' )
117  self.handles['genJet'] = AutoHandle( self.cfg_ana.genJetCol, 'vector<reco::GenJet>' )
118  self.shiftJER = self.cfg_ana.shiftJER if hasattr(self.cfg_ana, 'shiftJER') else 0
119  self.addJERShifts = self.cfg_ana.addJERShifts if hasattr(self.cfg_ana, 'addJERShifts') else 0
120  self.handles['rho'] = AutoHandle( self.cfg_ana.rho, 'double' )
121 
122  def beginLoop(self, setup):
123  super(JetAnalyzer,self).beginLoop(setup)
124 
125  def process(self, event):
126  self.readCollections( event.input )
127  rho = float(self.handles['rho'].product()[0])
128  self.rho = rho
129 
130  ## Read jets, if necessary recalibrate and shift MET
131  if self.cfg_ana.copyJetsByValue:
132  import ROOT
133  #from ROOT.heppy import JetUtils
134  allJets = map(lambda j:Jet(ROOT.heppy.JetUtils.copyJet(j)), self.handles['jets'].product()) #copy-by-value is safe if JetAnalyzer is ran more than once
135  else:
136  allJets = map(Jet, self.handles['jets'].product())
137 
138  #set dummy MC flavour for all jets in case we want to ntuplize discarded jets later
139  for jet in allJets:
140  jet.mcFlavour = 0
141 
142  self.deltaMetFromJEC = [0.,0.]
143  self.type1METCorr = [0.,0.,0.]
144 # print "before. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]
145  if self.doJEC:
146  if not self.recalibrateJets: # check point that things won't change
147  jetsBefore = [ (j.pt(),j.eta(),j.phi(),j.rawFactor()) for j in allJets ]
148  self.jetReCalibrator.correctAll(allJets, rho, delta=self.shiftJEC,
149  addCorr=True, addShifts=self.addJECShifts,
150  metShift=self.deltaMetFromJEC, type1METCorr=self.type1METCorr )
151  if not self.recalibrateJets:
152  jetsAfter = [ (j.pt(),j.eta(),j.phi(),j.rawFactor()) for j in allJets ]
153  if len(jetsBefore) != len(jetsAfter):
154  print "ERROR: I had to recompute jet corrections, and they rejected some of the jets:\nold = %s\n new = %s\n" % (jetsBefore,jetsAfter)
155  else:
156  for (told, tnew) in zip(jetsBefore,jetsAfter):
157  if (deltaR2(told[1],told[2],tnew[1],tnew[2])) > 0.0001:
158  print "ERROR: I had to recompute jet corrections, and one jet direction moved: old = %s, new = %s\n" % (told, tnew)
159  elif abs(told[0]-tnew[0])/(told[0]+tnew[0]) > 0.5e-3 or abs(told[3]-tnew[3]) > 0.5e-3:
160  print "ERROR: I had to recompute jet corrections, and one jet pt or corr changed: old = %s, new = %s\n" % (told, tnew)
161  self.allJetsUsedForMET = allJets
162 # print "after. rho",self.rho,self.cfg_ana.collectionPostFix,'allJets len ',len(allJets),'pt', [j.pt() for j in allJets]
163 
164  if self.cfg_comp.isMC:
165  self.genJets = [ x for x in self.handles['genJet'].product() ]
166  if self.cfg_ana.do_mc_match:
167  for igj, gj in enumerate(self.genJets):
168  gj.index = igj
169 # self.matchJets(event, allJets)
170  self.matchJets(event, [ j for j in allJets if j.pt()>self.cfg_ana.jetPt ]) # To match only jets above chosen threshold
171  if getattr(self.cfg_ana, 'smearJets', False):
172  self.smearJets(event, allJets)
173 
174 
175 
176 
177  ##Sort Jets by pT
178  allJets.sort(key = lambda j : j.pt(), reverse = True)
179 
180  leptons = []
181  if hasattr(event, 'selectedLeptons'):
182  leptons = [ l for l in event.selectedLeptons if l.pt() > self.lepPtMin and self.lepSelCut(l) ]
183  if self.cfg_ana.cleanJetsFromTaus and hasattr(event, 'selectedTaus'):
184  leptons = leptons[:] + event.selectedTaus
185  if self.cfg_ana.cleanJetsFromIsoTracks and hasattr(event, 'selectedIsoCleanTrack'):
186  leptons = leptons[:] + event.selectedIsoCleanTrack
187 
188  ## Apply jet selection
189  self.jets = []
190  self.jetsFailId = []
191  self.jetsAllNoID = []
192  self.jetsIdOnly = []
193  for jet in allJets:
194  #Check if lepton and jet have overlapping PF candidates
195  leps_with_overlaps = []
196  if getattr(self.cfg_ana, 'checkLeptonPFOverlap', True):
197  for i in range(jet.numberOfSourceCandidatePtrs()):
198  p1 = jet.sourceCandidatePtr(i) #Ptr<Candidate> p1
199  for lep in leptons:
200  for j in range(lep.numberOfSourceCandidatePtrs()):
201  p2 = lep.sourceCandidatePtr(j)
202  has_overlaps = p1.key() == p2.key() and p1.refCore().id().productIndex() == p2.refCore().id().productIndex() and p1.refCore().id().processIndex() == p2.refCore().id().processIndex()
203  if has_overlaps:
204  leps_with_overlaps += [lep]
205  if len(leps_with_overlaps)>0:
206  for lep in leps_with_overlaps:
207  lep.jetOverlap = jet
208  if self.testJetNoID( jet ):
209  self.jetsAllNoID.append(jet)
210  if(self.cfg_ana.doQG):
211  jet.qgl_calc = self.qglcalc.computeQGLikelihood
212  jet.qgl_rho = rho
213  if self.testJetID( jet ):
214  self.jets.append(jet)
215  self.jetsIdOnly.append(jet)
216  else:
217  self.jetsFailId.append(jet)
218  elif self.testJetID (jet ):
219  self.jetsIdOnly.append(jet)
220 
221  jetsEtaCut = [j for j in self.jets if abs(j.eta()) < self.cfg_ana.jetEta ]
222  self.cleanJetsAll, cleanLeptons = cleanJetsAndLeptons(jetsEtaCut, leptons, self.jetLepDR, self.jetLepArbitration)
223 
224  self.cleanJets = [j for j in self.cleanJetsAll if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
225  self.cleanJetsFwd = [j for j in self.cleanJetsAll if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
226  self.discardedJets = [j for j in self.jets if j not in self.cleanJetsAll]
227  if hasattr(event, 'selectedLeptons') and self.cfg_ana.cleanSelectedLeptons:
228  event.discardedLeptons = [ l for l in leptons if l not in cleanLeptons ]
229  event.selectedLeptons = [ l for l in event.selectedLeptons if l not in event.discardedLeptons ]
230  for lep in leptons:
231  if hasattr(lep, "jetOverlap"):
232  if lep.jetOverlap in self.cleanJetsAll:
233  #print "overlap reco", lep.p4().pt(), lep.p4().eta(), lep.p4().phi(), lep.jetOverlap.p4().pt(), lep.jetOverlap.p4().eta(), lep.jetOverlap.p4().phi()
234  lep.jetOverlapIdx = self.cleanJetsAll.index(lep.jetOverlap)
235  elif lep.jetOverlap in self.discardedJets:
236  #print "overlap discarded", lep.p4().pt(), lep.p4().eta(), lep.p4().phi(), lep.jetOverlap.p4().pt(), lep.jetOverlap.p4().eta(), lep.jetOverlap.p4().phi()
237  lep.jetOverlapIdx = 1000 + self.discardedJets.index(lep.jetOverlap)
238 
239  ## First cleaning, then Jet Id
240  self.noIdCleanJetsAll, cleanLeptons = cleanJetsAndLeptons(self.jetsAllNoID, leptons, self.jetLepDR, self.jetLepArbitration)
241  self.noIdCleanJets = [j for j in self.noIdCleanJetsAll if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
242  self.noIdCleanJetsFwd = [j for j in self.noIdCleanJetsAll if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
243  self.noIdDiscardedJets = [j for j in self.jetsAllNoID if j not in self.noIdCleanJetsAll]
244 
245  ## Clean Jets from photons (first cleaning, then Jet Id)
246  photons = []
247  if hasattr(event, 'selectedPhotons'):
248  if self.cfg_ana.cleanJetsFromFirstPhoton:
249  photons = event.selectedPhotons[:1]
250  else:
251  photons = [ g for g in event.selectedPhotons ]
252 
255 
257  self.gamma_cleanJetsAll = cleanNearestJetOnly(jetsEtaCut, photons+leptons, self.jetGammaLepDR)
258  self.gamma_noIdCleanJetsAll = cleanNearestJetOnly(self.jetsAllNoID, photons+leptons, self.jetGammaLepDR)
259  else:
262 
263  self.gamma_cleanJets = [j for j in self.gamma_cleanJetsAll if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
264  self.gamma_cleanJetsFwd = [j for j in self.gamma_cleanJetsAll if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
265 
266  self.gamma_noIdCleanJets = [j for j in self.gamma_noIdCleanJetsAll if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
267  self.gamma_noIdCleanJetsFwd = [j for j in self.gamma_noIdCleanJetsAll if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
268  ###
269 
270  if self.cfg_ana.alwaysCleanPhotons:
271  self.cleanJets = self.gamma_cleanJets
272  self.cleanJetsAll = self.gamma_cleanJetsAll
273  self.cleanJetsFwd = self.gamma_cleanJetsFwd
274  #
278 
279  ## Jet Id, after jet/lepton cleaning
281  for jet in self.noIdCleanJetsAll:
282  if not self.testJetID( jet ):
283  self.cleanJetsFailIdAll.append(jet)
284 
285  self.cleanJetsFailId = [j for j in self.cleanJetsFailIdAll if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
286 
287  ## Jet Id, after jet/photon cleaning
289  for jet in self.gamma_noIdCleanJetsAll:
290  if not self.testJetID( jet ):
291  self.gamma_cleanJetsFailIdAll.append(jet)
292 
293  self.gamma_cleanJetsFailId = [j for j in self.gamma_cleanJetsFailIdAll if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
294 
295  ## Associate jets to leptons
296  incleptons = event.inclusiveLeptons if hasattr(event, 'inclusiveLeptons') else event.selectedLeptons
297  jlpairs = matchObjectCollection(incleptons, allJets, self.jetLepDR**2)
298 
299  for jet in allJets:
300  jet.leptons = [l for l in jlpairs if jlpairs[l] == jet ]
301  for lep in incleptons:
302  jet = jlpairs[lep]
303  if jet is None:
304  setattr(lep,"jet"+self.cfg_ana.collectionPostFix,lep)
305  else:
306  setattr(lep,"jet"+self.cfg_ana.collectionPostFix,jet)
307  ## Associate jets to taus
308  taus = getattr(event,'selectedTaus',[])
309  jtaupairs = matchObjectCollection( taus, allJets, self.jetLepDR**2)
310 
311  for jet in allJets:
312  jet.taus = [l for l in jtaupairs if jtaupairs[l] == jet ]
313  for tau in taus:
314  setattr(tau,"jet"+self.cfg_ana.collectionPostFix,jtaupairs[tau])
315 
316  #MC stuff
317  if self.cfg_comp.isMC:
319  for j in self.cleanJetsAll:
320  if hasattr(j, 'deltaMetFromJetSmearing'):
321  self.deltaMetFromJetSmearing[0] += j.deltaMetFromJetSmearing[0]
322  self.deltaMetFromJetSmearing[1] += j.deltaMetFromJetSmearing[1]
323 
324  self.cleanGenJets = cleanNearestJetOnly(self.genJets, leptons, self.jetLepDR)
325 
326  if self.cfg_ana.cleanGenJetsFromPhoton:
327  self.cleanGenJets = cleanNearestJetOnly(self.cleanGenJets, photons, self.jetLepDR)
328 
329  if getattr(self.cfg_ana, 'attachNeutrinos', True) and hasattr(self.cfg_ana,"genNuSelection") :
330  jetNus=[x for x in event.genParticles if abs(x.pdgId()) in [12,14,16] and self.cfg_ana.genNuSelection(x) ]
331  pairs= matchObjectCollection (jetNus, self.genJets, 0.4**2)
332 
333  for (nu,genJet) in six.iteritems(pairs) :
334  if genJet is not None :
335  if not hasattr(genJet,"nu") :
336  genJet.nu=nu.p4()
337  else :
338  genJet.nu+=nu.p4()
339 
340 
341  if self.cfg_ana.do_mc_match:
342  self.jetFlavour(event)
343 
344  if hasattr(event,"jets"+self.cfg_ana.collectionPostFix): raise RuntimeError("Event already contains a jet collection with the following postfix: "+self.cfg_ana.collectionPostFix)
345  setattr(event,"rho" +self.cfg_ana.collectionPostFix, self.rho )
346  setattr(event,"deltaMetFromJEC" +self.cfg_ana.collectionPostFix, self.deltaMetFromJEC )
347  setattr(event,"type1METCorr" +self.cfg_ana.collectionPostFix, self.type1METCorr )
348  setattr(event,"allJetsUsedForMET" +self.cfg_ana.collectionPostFix, self.allJetsUsedForMET )
349  setattr(event,"jets" +self.cfg_ana.collectionPostFix, self.jets )
350  setattr(event,"jetsFailId" +self.cfg_ana.collectionPostFix, self.jetsFailId )
351  setattr(event,"jetsAllNoID" +self.cfg_ana.collectionPostFix, self.jetsAllNoID )
352  setattr(event,"jetsIdOnly" +self.cfg_ana.collectionPostFix, self.jetsIdOnly )
353  setattr(event,"cleanJetsAll" +self.cfg_ana.collectionPostFix, self.cleanJetsAll )
354  setattr(event,"cleanJets" +self.cfg_ana.collectionPostFix, self.cleanJets )
355  setattr(event,"cleanJetsFwd" +self.cfg_ana.collectionPostFix, self.cleanJetsFwd )
356  setattr(event,"cleanJetsFailIdAll" +self.cfg_ana.collectionPostFix, self.cleanJetsFailIdAll )
357  setattr(event,"cleanJetsFailId" +self.cfg_ana.collectionPostFix, self.cleanJetsFailId )
358  setattr(event,"discardedJets" +self.cfg_ana.collectionPostFix, self.discardedJets )
359  setattr(event,"gamma_cleanJetsAll" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsAll )
360  setattr(event,"gamma_cleanJets" +self.cfg_ana.collectionPostFix, self.gamma_cleanJets )
361  setattr(event,"gamma_cleanJetsFwd" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsFwd )
362  setattr(event,"gamma_cleanJetsFailIdAll" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsFailIdAll )
363  setattr(event,"gamma_cleanJetsFailId" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsFailId )
364 
365 
366  if self.cfg_comp.isMC:
367  setattr(event,"deltaMetFromJetSmearing"+self.cfg_ana.collectionPostFix, self.deltaMetFromJetSmearing)
368  setattr(event,"cleanGenJets" +self.cfg_ana.collectionPostFix, self.cleanGenJets )
369  setattr(event,"genJets" +self.cfg_ana.collectionPostFix, self.genJets )
370  if self.cfg_ana.do_mc_match:
371  setattr(event,"bqObjects" +self.cfg_ana.collectionPostFix, self.bqObjects )
372  setattr(event,"cqObjects" +self.cfg_ana.collectionPostFix, self.cqObjects )
373  setattr(event,"partons" +self.cfg_ana.collectionPostFix, self.partons )
374  setattr(event,"heaviestQCDFlavour" +self.cfg_ana.collectionPostFix, self.heaviestQCDFlavour )
375 
376 
377  return True
378 
379 
380 
381  def testJetID(self, jet):
382  jet.puJetIdPassed = jet.puJetId()
383  jet.pfJetIdPassed = jet.jetID('POG_PFID_Loose')
384  if self.cfg_ana.relaxJetId:
385  return True
386  else:
387  return jet.pfJetIdPassed and (jet.puJetIdPassed or not(self.doPuId))
388 
389  def testJetNoID( self, jet ):
390  # 2 is loose pile-up jet id
391  return jet.pt() > self.cfg_ana.jetPt and \
392  abs( jet.eta() ) < self.cfg_ana.jetEta;
393 
394  def jetFlavour(self,event):
395  def isFlavour(x,f):
396  id = abs(x.pdgId())
397  if id > 999: return (id/1000)%10 == f
398  if id > 99: return (id/100)%10 == f
399  return id % 100 == f
400 
401 
402 
403  self.bqObjects = [ p for p in event.genParticles if (p.status() == 2 and isFlavour(p,5)) ]
404  self.cqObjects = [ p for p in event.genParticles if (p.status() == 2 and isFlavour(p,4)) ]
405 
406  self.partons = [ p for p in event.genParticles if ((p.status() == 23 or p.status() == 3) and abs(p.pdgId())>0 and (abs(p.pdgId()) in [1,2,3,4,5,21]) ) ]
408  self.partons,
409  deltaRMax = 0.3)
410 
411  for jet in self.cleanJetsAll:
412  parton = match[jet]
413  jet.partonId = (parton.pdgId() if parton != None else 0)
414  jet.partonMotherId = (parton.mother(0).pdgId() if parton != None and parton.numberOfMothers()>0 else 0)
415 
416  for jet in self.jets:
417  (bmatch, dr) = bestMatch(jet, self.bqObjects)
418  if dr < 0.4:
419  jet.mcFlavour = 5
420  else:
421  (cmatch, dr) = bestMatch(jet, self.cqObjects)
422  if dr < 0.4:
423  jet.mcFlavour = 4
424  else:
425  jet.mcFlavour = 0
426 
427  self.heaviestQCDFlavour = 5 if len(self.bqObjects) else (4 if len(self.cqObjects) else 1);
428 
429  def matchJets(self, event, jets):
430  match = matchObjectCollection2(jets,
431  event.genbquarks + event.genwzquarks,
432  deltaRMax = 0.3)
433  for jet in jets:
434  gen = match[jet]
435  jet.mcParton = gen
436  jet.mcMatchId = (gen.sourceId if gen != None else 0)
437  jet.mcMatchFlav = (abs(gen.pdgId()) if gen != None else 0)
438 
439  match = matchObjectCollection2(jets,
440  self.genJets,
441  deltaRMax = 0.3)
442  for jet in jets:
443  jet.mcJet = match[jet]
444 
445 
446 
447  def smearJets(self, event, jets):
448  # https://twiki.cern.ch/twiki/bin/viewauth/CMS/TWikiTopRefSyst#Jet_energy_resolution
449  for jet in jets:
450  gen = jet.mcJet
451  if gen != None:
452  genpt, jetpt, aeta = gen.pt(), jet.pt(), abs(jet.eta())
453  # from https://twiki.cern.ch/twiki/bin/view/CMS/JetResolution
454  #8 TeV tables
455  factor = shiftJERfactor(self.shiftJER, aeta)
456  ptscale = max(0.0, (jetpt + (factor-1)*(jetpt-genpt))/jetpt)
457  #print "get with pt %.1f (gen pt %.1f, ptscale = %.3f)" % (jetpt,genpt,ptscale)
458  jet.deltaMetFromJetSmearing = [ -(ptscale-1)*jet.rawFactor()*jet.px(), -(ptscale-1)*jet.rawFactor()*jet.py() ]
459  if ptscale != 0:
460  jet.setP4(jet.p4()*ptscale)
461  # leave the uncorrected unchanged for sync
462  jet.setRawFactor(jet.rawFactor()/ptscale)
463  #else: print "jet with pt %.1d, eta %.2f is unmatched" % (jet.pt(), jet.eta())
464  if (self.shiftJER==0) and (self.addJERShifts):
465  setattr(jet, "corrJER", ptscale )
466  factorJERUp= shiftJERfactor(1, aeta)
467  ptscaleJERUp = max(0.0, (jetpt + (factorJERUp-1)*(jetpt-genpt))/jetpt)
468  setattr(jet, "corrJERUp", ptscaleJERUp)
469  factorJERDown= shiftJERfactor(-1, aeta)
470  ptscaleJERDown = max(0.0, (jetpt + (factorJERDown-1)*(jetpt-genpt))/jetpt)
471  setattr(jet, "corrJERDown", ptscaleJERDown)
472 
473 
474 
475 
476 
477 setattr(JetAnalyzer,"defaultConfig", cfg.Analyzer(
478  class_object = JetAnalyzer,
479  jetCol = 'slimmedJets',
480  copyJetsByValue = False, #Whether or not to copy the input jets or to work with references (should be 'True' if JetAnalyzer is run more than once)
481  genJetCol = 'slimmedGenJets',
482  rho = ('fixedGridRhoFastjetAll','',''),
483  jetPt = 25.,
484  jetEta = 4.7,
485  jetEtaCentral = 2.4,
486  jetLepDR = 0.4,
487  jetLepArbitration = (lambda jet,lepton : lepton), # you can decide which to keep in case of overlaps; e.g. if the jet is b-tagged you might want to keep the jet
488  cleanSelectedLeptons = True, #Whether to clean 'selectedLeptons' after disambiguation. Treat with care (= 'False') if running Jetanalyzer more than once
489  minLepPt = 10,
490  lepSelCut = lambda lep : True,
491  relaxJetId = False,
492  doPuId = False, # Not commissioned in 7.0.X
493  doQG = False,
494  checkLeptonPFOverlap = True,
495  recalibrateJets = False,
496  applyL2L3Residual = 'Data', # if recalibrateJets, apply L2L3Residual to Data only
497  recalibrationType = "AK4PFchs",
498  shiftJEC = 0, # set to +1 or -1 to apply +/-1 sigma shift to the nominal jet energies
499  addJECShifts = False, # if true, add "corr", "corrJECUp", and "corrJECDown" for each jet (requires uncertainties to be available!)
500  smearJets = True,
501  shiftJER = 0, # set to +1 or -1 to get +/-1 sigma shifts
502  jecPath = "",
503  calculateSeparateCorrections = False,
504  calculateType1METCorrection = False,
505  type1METParams = { 'jetPtThreshold':15., 'skipEMfractionThreshold':0.9, 'skipMuons':True },
506  addJERShifts = 0, # add +/-1 sigma shifts to jets, intended to be used with shiftJER=0
507  cleanJetsFromFirstPhoton = False,
508  cleanJetsFromTaus = False,
509  cleanJetsFromIsoTracks = False,
510  alwaysCleanPhotons = False,
511  do_mc_match=True,
512  cleanGenJetsFromPhoton = False,
513  jetGammaDR=0.4,
514  cleanFromLepAndGammaSimultaneously = False,
515  jetGammaLepDR=0.4,
516  attachNeutrinos = True,
517  genNuSelection = lambda nu : True, #FIXME: add here check for ispromptfinalstate
518  collectionPostFix = ""
519  )
520 )
deltaMetFromJEC
Read jets, if necessary recalibrate and shift MET.
Definition: JetAnalyzer.py:142
cleanJetsFailIdAll
Jet Id, after jet/lepton cleaning.
Definition: JetAnalyzer.py:280
def matchObjectCollection
Definition: deltar.py:151
def matchJets(self, event, jets)
Definition: JetAnalyzer.py:429
Definition: Jet.py:1
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
noIdCleanJetsAll
First cleaning, then Jet Id.
Definition: JetAnalyzer.py:240
Abs< T >::type abs(const T &t)
Definition: Abs.h:22
jets
Apply jet selection.
Definition: JetAnalyzer.py:189
constexpr auto deltaR2(const T1 &t1, const T2 &t2) -> decltype(t1.eta())
Definition: deltaR.h:16
def cleanNearestJetOnly(jets, leptons, deltaR)
Definition: JetAnalyzer.py:13
def bestMatch(object, matchCollection)
Definition: deltar.py:138
def cleanJetsAndLeptons(jets, leptons, deltaR, arbitration)
Definition: JetAnalyzer.py:25
def shiftJERfactor(JERShift, aeta)
Definition: JetAnalyzer.py:52
def __init__(self, cfg_ana, cfg_comp, looperName)
Definition: JetAnalyzer.py:68
def matchObjectCollection2(objects, matchCollection, deltaRMax=0.3)
Definition: deltar.py:166
gamma_cleanJetsFailIdAll
Jet Id, after jet/photon cleaning.
Definition: JetAnalyzer.py:288