CMS 3D CMS Logo

jetCollectionTools.py
Go to the documentation of this file.
1 import FWCore.ParameterSet.Config as cms
2 
4 
5 from Configuration.Eras.Modifier_run2_miniAOD_80XLegacy_cff import run2_miniAOD_80XLegacy
6 from Configuration.Eras.Modifier_run2_nanoAOD_94X2016_cff import run2_nanoAOD_94X2016
7 
8 from RecoJets.JetProducers.PFJetParameters_cfi import PFJetParameters
9 from RecoJets.JetProducers.GenJetParameters_cfi import GenJetParameters
10 from RecoJets.JetProducers.AnomalousCellParameters_cfi import AnomalousCellParameters
11 from RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets
12 from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJetsCS
13 
14 from PhysicsTools.PatAlgos.tools.jetTools import addJetCollection, supportedJetAlgos
16 from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors
17 
18 from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociation
19 
20 from CommonTools.PileupAlgos.Puppi_cff import puppi
21 from CommonTools.PileupAlgos.softKiller_cfi import softKiller
22 
23 import re
24 
25 #============================================
26 #
27 # GenJetInfo
28 #
29 #============================================
31  """
32  Class to hold information of a genjet collection
33  """
34  def __init__(self, jet, inputCollection):
35  self.jet = jet
36  self.jetLower = jet.lower()
37  self.jetUpper = jet.upper()
38  self.jetTagName = self.jetUpper
39  self.inputCollection = inputCollection
40  algoKey = 'algo'
41  sizeKey = 'size'
42  recoKey = 'reco'
43  jetRegex = re.compile(
44  r'(?P<{algo}>({algoList}))(?P<{size}>[0-9]+)gen'.format(
45  algo = algoKey,
46  algoList = '|'.join(supportedJetAlgos.keys()),
47  size = sizeKey,
48  )
49  )
50  jetMatch = jetRegex.match(jet.lower())
51  if not jetMatch:
52  raise RuntimeError('Invalid jet collection: %s' % jet)
53  self.jetAlgo = jetMatch.group(algoKey)
54  self.jetSize = jetMatch.group(sizeKey)
55  self.jetSizeNr = float(self.jetSize) / 10.
56 
57 #============================================
58 #
59 # GenJetAdder
60 #
61 #============================================
63  """
64  Tool to schedule modules for building a genjet collection with input MiniAODs
65  """
66  def __init__(self):
67  self.prerequisites = []
68  self.main = []
69  self.gpLabel = "prunedGenParticles"
70 
71  def getSequence(self, proc):
72  tasks = self.prerequisites + self.main
73 
74  resultSequence = cms.Sequence()
75  for idx, task in enumerate(tasks):
76  if idx == 0:
77  resultSequence = cms.Sequence(getattr(proc, task))
78  else:
79  resultSequence.insert(idx, getattr(proc, task))
80  return resultSequence
81 
82  def addGenJetCollection(self,
83  proc,
84  jet,
85  inputCollection = "",
86  genName = "",
87  minPt = 5.,
88  ):
89  print("jetCollectionTools::GenJetAdder::addGenJetCollection: Adding Gen Jet Collection: {}".format(jet))
90  currentTasks = []
91 
92  #
93  # Decide which jet collection we're dealing with
94  #
95  jetLower = jet.lower()
96  jetUpper = jet.upper()
97  tagName = jetUpper
98  genJetInfo = GenJetInfo(jet,inputCollection)
99 
100  #=======================================================
101  #
102  # If gen jet collection in MiniAOD is not
103  # specified, build the genjet collection.
104  #
105  #========================================================
106  if not inputCollection:
107  print("jetCollectionTools::GenJetAdder::addGenJetCollection: inputCollection not specified. Building genjet collection now")
108  #
109  # Setup GenParticles
110  #
111  packedGenPartNoNu = "packedGenParticlesForJetsNoNu"
112  if packedGenPartNoNu not in self.prerequisites:
113  setattr(proc, packedGenPartNoNu, cms.EDFilter("CandPtrSelector",
114  src = cms.InputTag("packedGenParticles"),
115  cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16"),
116  )
117  )
118  self.prerequisites.append(packedGenPartNoNu)
119  #
120  # Create the GenJet collection
121  #
122  genJetsCollection = "{}{}{}".format(genJetInfo.jetAlgo.upper(), genJetInfo.jetSize, 'GenJetsNoNu')
123  setattr(proc, genJetsCollection, ak4GenJets.clone(
124  src = packedGenPartNoNu,
125  jetAlgorithm = cms.string(supportedJetAlgos[genJetInfo.jetAlgo]),
126  rParam = cms.double(genJetInfo.jetSizeNr),
127  )
128  )
129  self.prerequisites.append(genJetsCollection)
130  #
131  # GenJet Flavour Labelling
132  #
133  genFlavour = "{}Flavour".format(genJetInfo.jetTagName)
134  setattr(proc, genFlavour, patJetFlavourAssociation.clone(
135  jets = cms.InputTag(genJetsCollection),
136  jetAlgorithm = cms.string(supportedJetAlgos[genJetInfo.jetAlgo]),
137  rParam = cms.double(genJetInfo.jetSizeNr),
138  )
139  )
140 
141  currentTasks.append(genFlavour)
142  self.main.extend(currentTasks)
143 
144  return genJetInfo
145 
146 #============================================
147 #
148 # RecoJetInfo
149 #
150 #============================================
152  """
153  Class to hold information of a recojet collection
154  """
155  def __init__(self, jet, inputCollection):
156  self.jet = jet
157  self.jetLower = jet.lower()
158  self.jetUpper = jet.upper()
159  self.jetTagName = self.jetUpper
160  self.inputCollection = inputCollection
161  algoKey = 'algo'
162  sizeKey = 'size'
163  recoKey = 'reco'
164  puMethodKey = 'puMethod'
165  jetRegex = re.compile(
166  r'(?P<{algo}>({algoList}))(?P<{size}>[0-9]+)(?P<{reco}>(pf|calo))(?P<{puMethod}>(chs|puppi|sk|cs|))'.format(
167  algo = algoKey,
168  algoList = '|'.join(supportedJetAlgos.keys()),
169  size = sizeKey,
170  reco = recoKey,
171  puMethod = puMethodKey,
172  )
173  )
174  jetMatch = jetRegex.match(jet.lower())
175  if not jetMatch:
176  raise RuntimeError('Invalid jet collection: %s' % jet)
177 
178  self.jetAlgo = jetMatch.group(algoKey)
179  self.jetSize = jetMatch.group(sizeKey)
180  self.jetReco = jetMatch.group(recoKey)
181  self.jetPUMethod = jetMatch.group(puMethodKey)
182 
183  self.jetSizeNr = float(self.jetSize) / 10.
184 
185  self.doCalo = self.jetReco == "calo"
186  self.doCS = self.jetPUMethod == "cs"
187  self.skipUserData = self.doCalo or (self.jetPUMethod in [ "puppi", "sk" ] and inputCollection == "")
188 
189  self.jetCorrPayload = "{}{}{}".format(
190  self.jetAlgo.upper(), self.jetSize, "Calo" if self.doCalo else self.jetReco.upper()
191  )
192  if self.jetPUMethod == "puppi":
193  self.jetCorrPayload += "Puppi"
194  elif self.jetPUMethod in [ "cs", "sk" ]:
195  self.jetCorrPayload += "chs"
196  else:
197  self.jetCorrPayload += self.jetPUMethod.lower()
198 
199 #============================================
200 #
201 # RecoJetAdder
202 #
203 #============================================
205  """
206  Tool to schedule modules for building a recojet collection with input MiniAODs
207  """
208  def __init__(self):
209  self.prerequisites = []
210  self.main = []
211  self.bTagDiscriminators = ["None"] # No b-tagging by default
212  self.JETCorrLevels = [ "L1FastJet", "L2Relative", "L3Absolute" ]
213  self.pfLabel = "packedPFCandidates"
214  self.pvLabel = "offlineSlimmedPrimaryVertices"
215  self.svLabel = "slimmedSecondaryVertices"
216  self.muLabel = "slimmedMuons"
217  self.elLabel = "slimmedElectrons"
218  self.gpLabel = "prunedGenParticles"
219 
220  def getSequence(self, proc):
221  tasks = self.prerequisites + self.main
222 
223  resultSequence = cms.Sequence()
224  for idx, task in enumerate(tasks):
225  if idx == 0:
226  resultSequence = cms.Sequence(getattr(proc, task))
227  else:
228  resultSequence.insert(idx, getattr(proc, task))
229  return resultSequence
230 
231  def addRecoJetCollection(self,
232  proc,
233  jet,
234  inputCollection = "",
235  genJetsCollection = "",
236  minPt = 5.,
237  bTagDiscriminators = None,
238  JETCorrLevels = None,
239  ):
240  print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: Adding Reco Jet Collection: {}".format(jet))
241 
242  currentTasks = []
243 
244  if inputCollection and inputCollection not in [
245  "slimmedJets", "slimmedJetsAK8", "slimmedJetsPuppi", "slimmedCaloJets",
246  ]:
247  raise RuntimeError("Invalid input collection: %s" % inputCollection)
248 
249  if bTagDiscriminators is None:
250  bTagDiscriminators = self.bTagDiscriminators
251 
252  if JETCorrLevels is None:
253  JETCorrLevels = self.JETCorrLevels
254 
255  #
256  # Decide which jet collection we're dealing with
257  #
258  recoJetInfo = RecoJetInfo(jet, inputCollection)
259  jetLower = recoJetInfo.jetLower
260  jetUpper = recoJetInfo.jetUpper
261  tagName = recoJetInfo.jetTagName
262 
263  if inputCollection == "slimmedJets":
264  assert(jetLower == "ak4pfchs")
265  elif inputCollection == "slimmedJetsAK8":
266  assert(jetLower == "ak8pfpuppi")
267  elif inputCollection == "slimmedJetsPuppi":
268  assert(jetLower == "ak4pfpuppi")
269  elif inputCollection == "slimmedCaloJets":
270  assert(jetLower == "ak4calo")
271 
272  #=======================================================
273  #
274  # If jet collection in MiniAOD is not
275  # specified, build the jet collection.
276  #
277  #========================================================
278  if not inputCollection or recoJetInfo.doCalo:
279  print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: inputCollection not specified. Building recojet collection now")
280 
281  #=======================================================
282  #
283  # Prepare the inputs to jet clustering
284  #
285  #========================================================
286  #
287  # Set up PF candidates
288  #
289  pfCand = self.pfLabel
290  #
291  # Setup PU method for PF candidates
292  #
293  if recoJetInfo.jetPUMethod not in [ "", "cs" ]:
294  pfCand += recoJetInfo.jetPUMethod
295  #
296  #
297  #
298  if pfCand not in self.prerequisites:
299  #
300  # Skip if no PU Method or CS specified
301  #
302  if recoJetInfo.jetPUMethod in [ "", "cs" ]:
303  pass
304  #
305  # CHS
306  #
307  elif recoJetInfo.jetPUMethod == "chs":
308  setattr(proc, pfCand,
309  cms.EDFilter("CandPtrSelector",
310  src = cms.InputTag(self.pfLabel),
311  cut = cms.string("fromPV"),
312  )
313  )
314  self.prerequisites.append(pfCand)
315  #
316  # PUPPI
317  #
318  elif recoJetInfo.jetPUMethod == "puppi":
319  setattr(proc, pfCand,
320  puppi.clone(
321  candName = self.pfLabel,
322  vertexName = self.pvLabel,
323  )
324  )
325  self.prerequisites.append(pfCand)
326  #
327  # Softkiller
328  #
329  elif recoJetInfo.jetPUMethod == "sk":
330  setattr(proc, pfCand,
331  softKiller.clone(
332  PFCandidates = self.pfLabel,
333  rParam = recoJetInfo.jetSizeNr,
334  )
335  )
336  self.prerequisites.append(pfCand)
337  else:
338  raise RuntimeError("Currently unsupported PU method: '%s'" % recoJetInfo.jetPUMethod)
339 
340  #============================================
341  #
342  # Create the recojet collection
343  #
344  #============================================
345  if not recoJetInfo.doCalo:
346  jetCollection = '{}Collection'.format(tagName)
347 
348  if jetCollection in self.main:
349  raise ValueError("Step '%s' already implemented" % jetCollection)
350 
351  setattr(proc, jetCollection, ak4PFJetsCS.clone(
352  src = pfCand,
353  doAreaFastjet = True,
354  jetPtMin = minPt,
355  jetAlgorithm = supportedJetAlgos[recoJetInfo.jetAlgo],
356  rParam = recoJetInfo.jetSizeNr,
357  useConstituentSubtraction = recoJetInfo.doCS,
358  csRParam = 0.4 if recoJetInfo.doCS else -1.,
359  csRho_EtaMax = PFJetParameters.Rho_EtaMax if recoJetInfo.doCS else -1.,
360  useExplicitGhosts = recoJetInfo.doCS or recoJetInfo.jetPUMethod == "sk",
361  )
362  )
363  currentTasks.append(jetCollection)
364  else:
365  jetCollection = inputCollection
366 
367  #
368  # PATify
369  #
370  if recoJetInfo.jetPUMethod == "puppi":
371  jetCorrLabel = "Puppi"
372  elif recoJetInfo.jetPUMethod in [ "cs", "sk" ]:
373  jetCorrLabel = "chs"
374  else:
375  jetCorrLabel = recoJetInfo.jetPUMethod
376 
377  #
378  # Jet correction
379  #
380  jetCorrections = (
381  "{}{}{}{}".format(
382  recoJetInfo.jetAlgo.upper(),
383  recoJetInfo.jetSize,
384  "Calo" if recoJetInfo.doCalo else recoJetInfo.jetReco.upper(),
385  jetCorrLabel
386  ),
387  JETCorrLevels,
388  "None",
389  )
390 
391  addJetCollection(
392  proc,
393  labelName = tagName,
394  jetSource = cms.InputTag(jetCollection),
395  algo = recoJetInfo.jetAlgo,
396  rParam = recoJetInfo.jetSizeNr,
397  pvSource = cms.InputTag(self.pvLabel),
398  pfCandidates = cms.InputTag(self.pfLabel),
399  svSource = cms.InputTag(self.svLabel),
400  muSource = cms.InputTag(self.muLabel),
401  elSource = cms.InputTag(self.elLabel),
402  btagDiscriminators = bTagDiscriminators if not recoJetInfo.doCalo else [ "None" ],
403  jetCorrections = jetCorrections,
404  genJetCollection = cms.InputTag(genJetsCollection),
405  genParticles = cms.InputTag(self.gpLabel),
406  )
407 
408  getJetMCFlavour = not recoJetInfo.doCalo and recoJetInfo.jetPUMethod != "cs"
409 
410  setattr(getattr(proc, "patJets{}".format(tagName)), "getJetMCFlavour", cms.bool(getJetMCFlavour))
411  setattr(getattr(proc, "patJetCorrFactors{}".format(tagName)), "payload", cms.string(recoJetInfo.jetCorrPayload))
412  selJet = "selectedPatJets{}".format(tagName)
413  else:
414  selJet = inputCollection
415 
416  if not recoJetInfo.skipUserData:
417  #
418  #
419  #
420  jercVar = "jercVars{}".format(tagName)
421  if jercVar in self.main:
422  raise ValueError("Step '%s' already implemented" % jercVar)
423  setattr(proc, jercVar, proc.jercVars.clone(srcJet = selJet))
424  currentTasks.append(jercVar)
425  #
426  #
427  #
428  looseJetId = "looseJetId{}".format(tagName)
429  if looseJetId in self.main:
430  raise ValueError("Step '%s' already implemented" % looseJetId)
431  setattr(proc, looseJetId, proc.looseJetId.clone(src = selJet))
432  #
433  #
434  #
435  tightJetId = "tightJetId{}".format(tagName)
436  if tightJetId in self.main:
437  raise ValueError("Step '%s' already implemented" % tightJetId)
438  setattr(proc, tightJetId, proc.tightJetId.clone(src = selJet))
439  currentTasks.append(tightJetId)
440  #
441  #
442  #
443  tightJetIdLepVeto = "tightJetIdLepVeto{}".format(tagName)
444  if tightJetIdLepVeto in self.main:
445  raise ValueError("Step '%s' already implemented" % tightJetIdLepVeto)
446  setattr(proc, tightJetIdLepVeto, proc.tightJetIdLepVeto.clone(src = selJet))
447  currentTasks.append(tightJetIdLepVeto)
448  #
449  #
450  #
451  selectedPatJetsWithUserData = "{}WithUserData".format(selJet)
452  if selectedPatJetsWithUserData in self.main:
453  raise ValueError("Step '%s' already implemented" % selectedPatJetsWithUserData)
454  setattr(proc, selectedPatJetsWithUserData,
455  cms.EDProducer("PATJetUserDataEmbedder",
456  src = cms.InputTag(selJet),
457  userFloats = cms.PSet(
458  jercCHPUF = cms.InputTag("{}:chargedHadronPUEnergyFraction".format(jercVar)),
459  jercCHF = cms.InputTag("{}:chargedHadronCHSEnergyFraction".format(jercVar)),
460  ),
461  userInts = cms.PSet(
462  tightId = cms.InputTag(tightJetId),
463  tightIdLepVeto = cms.InputTag(tightJetIdLepVeto),
464  ),
465  )
466  )
467  for modifier in run2_miniAOD_80XLegacy, run2_nanoAOD_94X2016:
468  selectedPatJetsWithUserDataObj = getattr(proc, selectedPatJetsWithUserData)
469  modifier.toModify(selectedPatJetsWithUserDataObj.userInts,
470  looseId = looseJetId,
471  tightIdLepVeto = None,
472  )
473  currentTasks.append(selectedPatJetsWithUserData)
474  else:
475  selectedPatJetsWithUserData = "selectedPatJets{}".format(tagName)
476 
477  #
478  # Not sure why we can't re-use patJetCorrFactors* created by addJetCollection()
479  # (even cloning doesn't work) Let's just create our own
480  #
481  jetCorrFactors = "jetCorrFactors{}".format(tagName)
482  if jetCorrFactors in self.main:
483  raise ValueError("Step '%s' already implemented" % jetCorrFactors)
484 
485  setattr(proc, jetCorrFactors, patJetCorrFactors.clone(
486  src = selectedPatJetsWithUserData,
487  levels = JETCorrLevels,
488  primaryVertices = self.pvLabel,
489  payload = recoJetInfo.jetCorrPayload,
490  rho = "fixedGridRhoFastjetAll{}".format("Calo" if recoJetInfo.doCalo else ""),
491  )
492  )
493  currentTasks.append(jetCorrFactors)
494 
495  updatedJets = "updatedJets{}".format(tagName)
496  if updatedJets in self.main:
497  raise ValueError("Step '%s' already implemented" % updatedJets)
498 
499  setattr(proc, updatedJets, updatedPatJets.clone(
500  addBTagInfo = False,
501  jetSource = selectedPatJetsWithUserData,
502  jetCorrFactorsSource = [jetCorrFactors],
503  )
504  )
505 
506  currentTasks.append(updatedJets)
507  self.main.extend(currentTasks)
508 
509  return recoJetInfo
def addGenJetCollection(self, proc, jet, inputCollection="", genName="", minPt=5.)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def __init__(self, jet, inputCollection)
def __init__(self, jet, inputCollection)
def addRecoJetCollection(self, proc, jet, inputCollection="", genJetsCollection="", minPt=5., bTagDiscriminators=None, JETCorrLevels=None)
static std::string join(char **cmd)
Definition: RemoteFile.cc:18