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_jme_2016_cff import run2_jme_2016
6 from Configuration.Eras.Modifier_run2_jme_2017_cff import run2_jme_2017
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,runOnMC=True):
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  self.runOnMC = runOnMC
220 
221  def getSequence(self, proc):
222  tasks = self.prerequisites + self.main
223 
224  resultSequence = cms.Sequence()
225  for idx, task in enumerate(tasks):
226  if idx == 0:
227  resultSequence = cms.Sequence(getattr(proc, task))
228  else:
229  resultSequence.insert(idx, getattr(proc, task))
230  return resultSequence
231 
232  def addRecoJetCollection(self,
233  proc,
234  jet,
235  inputCollection = "",
236  genJetsCollection = "",
237  minPt = 5.,
238  bTagDiscriminators = None,
239  JETCorrLevels = None,
240  ):
241  print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: Adding Reco Jet Collection: {}".format(jet))
242 
243  currentTasks = []
244 
245  if inputCollection and inputCollection not in [
246  "slimmedJets", "slimmedJetsAK8", "slimmedJetsPuppi", "slimmedCaloJets",
247  ]:
248  raise RuntimeError("Invalid input collection: %s" % inputCollection)
249 
250  if bTagDiscriminators is None:
251  bTagDiscriminators = self.bTagDiscriminators
252 
253  if JETCorrLevels is None:
254  JETCorrLevels = self.JETCorrLevels
255 
256  #
257  # Decide which jet collection we're dealing with
258  #
259  recoJetInfo = RecoJetInfo(jet, inputCollection)
260  jetLower = recoJetInfo.jetLower
261  jetUpper = recoJetInfo.jetUpper
262  tagName = recoJetInfo.jetTagName
263 
264  if inputCollection == "slimmedJets":
265  assert(jetLower == "ak4pfchs")
266  elif inputCollection == "slimmedJetsAK8":
267  assert(jetLower == "ak8pfpuppi")
268  elif inputCollection == "slimmedJetsPuppi":
269  assert(jetLower == "ak4pfpuppi")
270  elif inputCollection == "slimmedCaloJets":
271  assert(jetLower == "ak4calo")
272 
273  #=======================================================
274  #
275  # If jet collection in MiniAOD is not
276  # specified, build the jet collection.
277  #
278  #========================================================
279  if not inputCollection or recoJetInfo.doCalo:
280  print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: inputCollection not specified. Building recojet collection now")
281 
282  #=======================================================
283  #
284  # Prepare the inputs to jet clustering
285  #
286  #========================================================
287  #
288  # Set up PF candidates
289  #
290  pfCand = self.pfLabel
291  #
292  # Setup PU method for PF candidates
293  #
294  if recoJetInfo.jetPUMethod not in [ "", "cs" ]:
295  pfCand += recoJetInfo.jetPUMethod
296  #
297  #
298  #
299  if pfCand not in self.prerequisites:
300  #
301  # Skip if no PU Method or CS specified
302  #
303  if recoJetInfo.jetPUMethod in [ "", "cs" ]:
304  pass
305  #
306  # CHS
307  #
308  elif recoJetInfo.jetPUMethod == "chs":
309  setattr(proc, pfCand,
310  cms.EDFilter("CandPtrSelector",
311  src = cms.InputTag(self.pfLabel),
312  cut = cms.string("fromPV"),
313  )
314  )
315  self.prerequisites.append(pfCand)
316  #
317  # PUPPI
318  #
319  elif recoJetInfo.jetPUMethod == "puppi":
320  setattr(proc, pfCand,
321  puppi.clone(
322  candName = self.pfLabel,
323  vertexName = self.pvLabel,
324  )
325  )
326  self.prerequisites.append(pfCand)
327  #
328  # Softkiller
329  #
330  elif recoJetInfo.jetPUMethod == "sk":
331  setattr(proc, pfCand,
332  softKiller.clone(
333  PFCandidates = self.pfLabel,
334  rParam = recoJetInfo.jetSizeNr,
335  )
336  )
337  self.prerequisites.append(pfCand)
338  else:
339  raise RuntimeError("Currently unsupported PU method: '%s'" % recoJetInfo.jetPUMethod)
340 
341  #============================================
342  #
343  # Create the recojet collection
344  #
345  #============================================
346  if not recoJetInfo.doCalo:
347  jetCollection = '{}Collection'.format(tagName)
348 
349  if jetCollection in self.main:
350  raise ValueError("Step '%s' already implemented" % jetCollection)
351 
352  setattr(proc, jetCollection, ak4PFJetsCS.clone(
353  src = pfCand,
354  doAreaFastjet = True,
355  jetPtMin = minPt,
356  jetAlgorithm = supportedJetAlgos[recoJetInfo.jetAlgo],
357  rParam = recoJetInfo.jetSizeNr,
358  useConstituentSubtraction = recoJetInfo.doCS,
359  csRParam = 0.4 if recoJetInfo.doCS else -1.,
360  csRho_EtaMax = PFJetParameters.Rho_EtaMax if recoJetInfo.doCS else -1.,
361  useExplicitGhosts = recoJetInfo.doCS or recoJetInfo.jetPUMethod == "sk",
362  )
363  )
364  currentTasks.append(jetCollection)
365  else:
366  jetCollection = inputCollection
367 
368  #
369  # PATify
370  #
371  if recoJetInfo.jetPUMethod == "puppi":
372  jetCorrLabel = "Puppi"
373  elif recoJetInfo.jetPUMethod in [ "cs", "sk" ]:
374  jetCorrLabel = "chs"
375  else:
376  jetCorrLabel = recoJetInfo.jetPUMethod
377 
378  #
379  # Jet correction
380  #
381  jetCorrections = (
382  "{}{}{}{}".format(
383  recoJetInfo.jetAlgo.upper(),
384  recoJetInfo.jetSize,
385  "Calo" if recoJetInfo.doCalo else recoJetInfo.jetReco.upper(),
386  jetCorrLabel
387  ),
388  JETCorrLevels,
389  "None",
390  )
391 
392  addJetCollection(
393  proc,
394  labelName = tagName,
395  jetSource = cms.InputTag(jetCollection),
396  algo = recoJetInfo.jetAlgo,
397  rParam = recoJetInfo.jetSizeNr,
398  pvSource = cms.InputTag(self.pvLabel),
399  pfCandidates = cms.InputTag(self.pfLabel),
400  svSource = cms.InputTag(self.svLabel),
401  muSource = cms.InputTag(self.muLabel),
402  elSource = cms.InputTag(self.elLabel),
403  btagDiscriminators = bTagDiscriminators if not recoJetInfo.doCalo else [ "None" ],
404  jetCorrections = jetCorrections,
405  genJetCollection = cms.InputTag(genJetsCollection),
406  genParticles = cms.InputTag(self.gpLabel),
407  )
408 
409  getJetMCFlavour = not recoJetInfo.doCalo and recoJetInfo.jetPUMethod != "cs"
410 
411  if not self.runOnMC: #Remove modules for Gen-level object matching
412  delattr(proc, 'patJetGenJetMatch{}'.format(tagName))
413  delattr(proc, 'patJetPartonMatch{}'.format(tagName))
414  getJetMCFlavour = False
415 
416  setattr(getattr(proc, "patJets{}".format(tagName)), "getJetMCFlavour", cms.bool(getJetMCFlavour))
417  setattr(getattr(proc, "patJetCorrFactors{}".format(tagName)), "payload", cms.string(recoJetInfo.jetCorrPayload))
418  selJet = "selectedPatJets{}".format(tagName)
419  else:
420  selJet = inputCollection
421 
422  if not recoJetInfo.skipUserData:
423  #
424  #
425  #
426  jercVar = "jercVars{}".format(tagName)
427  if jercVar in self.main:
428  raise ValueError("Step '%s' already implemented" % jercVar)
429  setattr(proc, jercVar, proc.jercVars.clone(srcJet = selJet))
430  currentTasks.append(jercVar)
431  #
432  # JetID Loose
433  #
434  looseJetId = "looseJetId{}".format(tagName)
435  if looseJetId in self.main:
436  raise ValueError("Step '%s' already implemented" % looseJetId)
437  setattr(proc, looseJetId, proc.looseJetId.clone(
438  src = selJet,
439  filterParams=proc.looseJetId.filterParams.clone(
440  version ="WINTER16"
441  ),
442  )
443  )
444  currentTasks.append(looseJetId)
445  #
446  # JetID Tight
447  #
448  tightJetId = "tightJetId{}".format(tagName)
449  if tightJetId in self.main:
450  raise ValueError("Step '%s' already implemented" % tightJetId)
451  setattr(proc, tightJetId, proc.tightJetId.clone(
452  src = selJet,
453  filterParams=proc.tightJetId.filterParams.clone(
454  version = "SUMMER18{}".format("PUPPI" if recoJetInfo.jetPUMethod == "puppi" else "")
455  ),
456  )
457  )
458  tightJetIdObj = getattr(proc, tightJetId)
459  run2_jme_2016.toModify(
460  tightJetIdObj.filterParams,
461  version = "WINTER16"
462  )
463  run2_jme_2017.toModify(
464  tightJetIdObj.filterParams,
465  version = 'WINTER17{}'.format("PUPPI" if recoJetInfo.jetPUMethod == "puppi" else "")
466  )
467  currentTasks.append(tightJetId)
468  #
469  # JetID TightLepVeto
470  #
471  tightJetIdLepVeto = "tightJetIdLepVeto{}".format(tagName)
472  if tightJetIdLepVeto in self.main:
473  raise ValueError("Step '%s' already implemented" % tightJetIdLepVeto)
474  setattr(proc, tightJetIdLepVeto, proc.tightJetIdLepVeto.clone(
475  src = selJet,
476  filterParams=proc.tightJetIdLepVeto.filterParams.clone(
477  version = "SUMMER18{}".format("PUPPI" if recoJetInfo.jetPUMethod == "puppi" else "")
478  ),
479  )
480  )
481  tightJetIdLepVetoObj = getattr(proc, tightJetIdLepVeto)
482  run2_jme_2016.toModify(
483  tightJetIdLepVetoObj.filterParams,
484  version = "WINTER16"
485  )
486  run2_jme_2017.toModify(
487  tightJetIdLepVetoObj.filterParams,
488  version = 'WINTER17{}'.format("PUPPI" if recoJetInfo.jetPUMethod == "puppi" else ""),
489  )
490  currentTasks.append(tightJetIdLepVeto)
491  #
492  #
493  #
494  selectedPatJetsWithUserData = "{}WithUserData".format(selJet)
495  if selectedPatJetsWithUserData in self.main:
496  raise ValueError("Step '%s' already implemented" % selectedPatJetsWithUserData)
497  setattr(proc, selectedPatJetsWithUserData,
498  cms.EDProducer("PATJetUserDataEmbedder",
499  src = cms.InputTag(selJet),
500  userFloats = cms.PSet(
501  jercCHPUF = cms.InputTag("{}:chargedHadronPUEnergyFraction".format(jercVar)),
502  jercCHF = cms.InputTag("{}:chargedHadronCHSEnergyFraction".format(jercVar)),
503  ),
504  userInts = cms.PSet(
505  tightId = cms.InputTag(tightJetId),
506  tightIdLepVeto = cms.InputTag(tightJetIdLepVeto),
507  ),
508  )
509  )
510  selectedPatJetsWithUserDataObj = getattr(proc, selectedPatJetsWithUserData)
511  run2_jme_2016.toModify(selectedPatJetsWithUserDataObj.userInts,
512  looseId = cms.InputTag(looseJetId),
513  )
514  currentTasks.append(selectedPatJetsWithUserData)
515  else:
516  selectedPatJetsWithUserData = "selectedPatJets{}".format(tagName)
517 
518  #
519  # Not sure why we can't re-use patJetCorrFactors* created by addJetCollection()
520  # (even cloning doesn't work) Let's just create our own
521  #
522  jetCorrFactors = "jetCorrFactors{}".format(tagName)
523  if jetCorrFactors in self.main:
524  raise ValueError("Step '%s' already implemented" % jetCorrFactors)
525 
526  setattr(proc, jetCorrFactors, patJetCorrFactors.clone(
527  src = selectedPatJetsWithUserData,
528  levels = JETCorrLevels,
529  primaryVertices = self.pvLabel,
530  payload = recoJetInfo.jetCorrPayload,
531  rho = "fixedGridRhoFastjetAll{}".format("Calo" if recoJetInfo.doCalo else ""),
532  )
533  )
534  currentTasks.append(jetCorrFactors)
535 
536  updatedJets = "updatedJets{}".format(tagName)
537  if updatedJets in self.main:
538  raise ValueError("Step '%s' already implemented" % updatedJets)
539 
540  setattr(proc, updatedJets, updatedPatJets.clone(
541  addBTagInfo = False,
542  jetSource = selectedPatJetsWithUserData,
543  jetCorrFactorsSource = [jetCorrFactors],
544  )
545  )
546  currentTasks.append(updatedJets)
547 
548  self.main.extend(currentTasks)
549 
550  return recoJetInfo
def __init__(self, runOnMC=True)
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