CMS 3D CMS Logo

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