CMS 3D CMS Logo

jetCollectionTools.py
Go to the documentation of this file.
1 import FWCore.ParameterSet.Config as cms
2 
4 
5 from CommonTools.PileupAlgos.Puppi_cff import puppi
6 from CommonTools.PileupAlgos.softKiller_cfi import softKiller
7 
8 from RecoJets.JetProducers.PFJetParameters_cfi import PFJetParameters
9 from RecoJets.JetProducers.GenJetParameters_cfi import GenJetParameters
10 from RecoJets.JetProducers.GenJetParameters_cfi import GenJetParameters
11 from RecoJets.JetProducers.AnomalousCellParameters_cfi import AnomalousCellParameters
12 
13 from RecoJets.JetProducers.ak4GenJets_cfi import ak4GenJets
14 from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets, ak4PFJetsCHS, ak4PFJetsPuppi, ak4PFJetsSK, ak4PFJetsCS
15 from RecoJets.JetProducers.ak4CaloJets_cfi import ak4CaloJets
16 
18 from PhysicsTools.PatAlgos.recoLayer0.jetCorrFactors_cfi import patJetCorrFactors
19 from PhysicsTools.PatAlgos.mcMatchLayer0.jetFlavourId_cff import patJetFlavourAssociation
20 
21 from PhysicsTools.PatAlgos.tools.jetTools import supportedJetAlgos, addJetCollection, updateJetCollection
22 from PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask, addToProcessAndTask
23 
24 import re
25 
26 #============================================
27 #
28 # GenJetInfo
29 #
30 #============================================
32  """
33  Class to hold information of a genjet collection
34  """
35  def __init__(self, jet, inputCollection):
36  self.jet = jet
37  self.jetLower = jet.lower()
38  self.jetUpper = jet.upper()
39  self.jetTagName = self.jetUpper
40  self.inputCollection = inputCollection
41  algoKey = 'algo'
42  sizeKey = 'size'
43  recoKey = 'reco'
44  jetRegex = re.compile(
45  r'(?P<{algo}>({algoList}))(?P<{size}>[0-9]+)gen'.format(
46  algo = algoKey,
47  algoList = '|'.join(supportedJetAlgos.keys()),
48  size = sizeKey,
49  )
50  )
51  jetMatch = jetRegex.match(jet.lower())
52  if not jetMatch:
53  raise RuntimeError('Invalid jet collection: %s' % jet)
54  self.jetAlgo = jetMatch.group(algoKey)
55  self.jetSize = jetMatch.group(sizeKey)
56  self.jetSizeNr = float(self.jetSize) / 10.
57 
58 #============================================
59 #
60 # GenJetAdder
61 #
62 #============================================
64  """
65  Tool to schedule modules for building a genjet collection with input MiniAODs
66  """
67  def __init__(self):
68  self.prerequisites = []
69  self.main = []
70  self.gpLabel = "prunedGenParticles"
71 
72  def addProcessAndTask(self, proc, label, module):
73  task = getPatAlgosToolsTask(proc)
74  addToProcessAndTask(label, module, proc, task)
75 
77  proc,
78  jet,
79  inputCollection = "",
80  minPtFastjet = None,
81  ):
82  print("jetCollectionTools::GenJetAdder::addGenJetCollection: Adding Gen Jet Collection: {}".format(jet))
83 
84  #
85  # Decide which genJet collection we are dealing with
86  #
87  genJetInfo = GenJetInfo(jet,inputCollection)
88  jetLower = genJetInfo.jetLower
89  jetUpper = genJetInfo.jetUpper
90 
91  #=======================================================
92  #
93  # If genJet collection in MiniAOD is not
94  # specified, build the genjet collection.
95  #
96  #========================================================
97  if not inputCollection:
98  print("jetCollectionTools::GenJetAdder::addGenJetCollection: inputCollection not specified. Building genjet collection now")
99  #
100  # Setup GenParticles
101  #
102  packedGenPartNoNu = "packedGenParticlesForJetsNoNu"
103  if packedGenPartNoNu not in self.prerequisites:
104  self.addProcessAndTask(proc, packedGenPartNoNu, cms.EDFilter("CandPtrSelector",
105  src = cms.InputTag("packedGenParticles"),
106  cut = cms.string("abs(pdgId) != 12 && abs(pdgId) != 14 && abs(pdgId) != 16"),
107  )
108  )
109  self.prerequisites.append(packedGenPartNoNu)
110  #
111  # Create the GenJet collection
112  #
113  genJetsCollection = "{}{}{}".format(genJetInfo.jetAlgo.upper(), genJetInfo.jetSize, 'GenJetsNoNu')
114  self.addProcessAndTask(proc, genJetsCollection, ak4GenJets.clone(
115  src = packedGenPartNoNu,
116  jetAlgorithm = cms.string(supportedJetAlgos[genJetInfo.jetAlgo]),
117  rParam = cms.double(genJetInfo.jetSizeNr),
118  )
119  )
120  #
121  # Set minimum pt threshold of gen jets to be saved after fastjet clustering
122  #
123  if minPtFastjet != None:
124  getattr(proc, genJetsCollection).jetPtMin = minPtFastjet
125  self.prerequisites.append(genJetsCollection)
126 
127  return genJetInfo
128 #============================================
129 #
130 # RecoJetInfo
131 #
132 #============================================
134  """
135  Class to hold information of a recojet collection
136  """
137  def __init__(self, jet, inputCollection):
138  self.jet = jet
139  self.jetLower = jet.lower()
140  self.jetUpper = jet.upper()
141  self.jetTagName = self.jetUpper
142  self.inputCollection = inputCollection
143  algoKey = 'algo'
144  sizeKey = 'size'
145  recoKey = 'reco'
146  puMethodKey = 'puMethod'
147  jetRegex = re.compile(
148  r'(?P<{algo}>({algoList}))(?P<{size}>[0-9]+)(?P<{reco}>(pf|calo))(?P<{puMethod}>(chs|puppi|sk|cs|))'.format(
149  algo = algoKey,
150  algoList = '|'.join(supportedJetAlgos.keys()),
151  size = sizeKey,
152  reco = recoKey,
153  puMethod = puMethodKey,
154  )
155  )
156  jetMatch = jetRegex.match(jet.lower())
157  if not jetMatch:
158  raise RuntimeError('Invalid jet collection: %s' % jet)
159 
160  self.jetAlgo = jetMatch.group(algoKey)
161  self.jetSize = jetMatch.group(sizeKey)
162  self.jetReco = jetMatch.group(recoKey)
163  self.jetPUMethod = jetMatch.group(puMethodKey)
164 
165  self.jetSizeNr = float(self.jetSize) / 10.
166 
167  self.doCalo = self.jetReco == "calo"
168  self.doPF = self.jetReco == "pf"
169 
170  self.doCS = self.jetPUMethod == "cs"
171  self.skipUserData = self.doCalo or (self.jetPUMethod in [ "puppi", "sk" ] and inputCollection == "")
172 
173  self.jetCorrPayload = "{}{}{}".format(
174  self.jetAlgo.upper(), self.jetSize, "Calo" if self.doCalo else self.jetReco.upper()
175  )
176 
177  if self.jetPUMethod == "puppi":
178  self.jetCorrPayload += "Puppi"
179  elif self.jetPUMethod in [ "cs", "sk" ]:
180  self.jetCorrPayload += "chs"
181  else:
182  self.jetCorrPayload += self.jetPUMethod.lower()
183 
185 
186 #============================================
187 #
188 # RecoJetAdder
189 #
190 #============================================
192  """
193  Tool to schedule modules for building a patJet collection from MiniAODs
194  """
195  def __init__(self,runOnMC=True):
196  self.prerequisites = []
197  self.main = []
198  self.pfLabel = "packedPFCandidates"
199  self.pvLabel = "offlineSlimmedPrimaryVertices"
200  self.svLabel = "slimmedSecondaryVertices"
201  self.muLabel = "slimmedMuons"
202  self.elLabel = "slimmedElectrons"
203  self.gpLabel = "prunedGenParticles"
204  self.runOnMC = runOnMC
205  self.patJetsInMiniAOD = ["slimmedJets", "slimmedJetsAK8", "slimmedJetsPuppi", "slimmedCaloJets"]
206 
207  def addProcessAndTask(self, proc, label, module):
208  task = getPatAlgosToolsTask(proc)
209  addToProcessAndTask(label, module, proc, task)
210 
212  proc,
213  jet,
214  inputCollection = "",
215  minPtFastjet = None,
216  genJetsCollection = "",
217  bTagDiscriminators = ["None"],
218  JETCorrLevels = ["L1FastJet", "L2Relative", "L3Absolute", "L2L3Residual"],
219  ):
220  print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: Adding Reco Jet Collection: {}".format(jet))
221 
222  currentTasks = []
223 
224  if inputCollection and inputCollection not in self.patJetsInMiniAOD:
225  raise RuntimeError("Invalid input collection: %s" % inputCollection)
226 
227  #=======================================================
228  #
229  # Figure out which jet collection we're dealing with
230  #
231  #=======================================================
232  recoJetInfo = RecoJetInfo(jet, inputCollection)
233  jetLower = recoJetInfo.jetLower
234  jetUpper = recoJetInfo.jetUpper
235  tagName = recoJetInfo.jetTagName
236 
237  if inputCollection == "slimmedJets":
238  assert(jetLower == "ak4pfchs")
239  elif inputCollection == "slimmedJetsAK8":
240  assert(jetLower == "ak8pfpuppi")
241  elif inputCollection == "slimmedJetsPuppi":
242  assert(jetLower == "ak4pfpuppi")
243  elif inputCollection == "slimmedCaloJets":
244  assert(jetLower == "ak4calo")
245 
246  #=======================================================
247  #
248  # If the patJet collection in MiniAOD is not specified,
249  # we have to build the patJet collection from scratch.
250  #
251  #========================================================
252  if not inputCollection or recoJetInfo.doCalo:
253  print("jetCollectionTools::RecoJetAdder::addRecoJetCollection: inputCollection not specified. Building recojet collection now")
254 
255  #=======================================================
256  #
257  # Prepare the inputs to jet clustering
258  #
259  #========================================================
260  #
261  # Specify PF candidates
262  #
263  pfCand = self.pfLabel
264  #
265  # Setup PU method for PF candidates
266  #
267  if recoJetInfo.jetPUMethod not in [ "", "cs" ]:
268  pfCand += recoJetInfo.jetPUMethod
269 
270 
271  #
272  # Setup modules to perform PU mitigation for
273  # PF candidates
274  #
275  if pfCand not in self.prerequisites:
276  #
277  # Skip if no PU Method or CS specified
278  #
279  if recoJetInfo.jetPUMethod in [ "", "cs" ]:
280  pass
281  #
282  # CHS
283  #
284  elif recoJetInfo.jetPUMethod == "chs":
285  self.addProcessAndTask(proc, pfCand, cms.EDFilter("CandPtrSelector",
286  src = cms.InputTag(self.pfLabel),
287  cut = cms.string("fromPV"),
288  )
289  )
290  self.prerequisites.append(pfCand)
291  #
292  # PUPPI
293  #
294  elif recoJetInfo.jetPUMethod == "puppi":
295  self.addProcessAndTask(proc, pfCand, puppi.clone(
296  candName = self.pfLabel,
297  vertexName = self.pvLabel,
298  )
299  )
300  self.prerequisites.append(pfCand)
301  #
302  # Softkiller
303  #
304  elif recoJetInfo.jetPUMethod == "sk":
305  self.addProcessAndTask(proc, pfCand, softKiller.clone(
306  PFCandidates = self.pfLabel,
307  rParam = recoJetInfo.jetSizeNr,
308  )
309  )
310  self.prerequisites.append(pfCand)
311  else:
312  raise RuntimeError("Currently unsupported PU method: '%s'" % recoJetInfo.jetPUMethod)
313 
314  #============================================
315  #
316  # Create the recojet collection
317  #
318  #============================================
319  if not recoJetInfo.doCalo:
320  jetCollection = '{}Collection'.format(jetUpper)
321 
322  if jetCollection in self.main:
323  raise ValueError("Step '%s' already implemented" % jetCollection)
324  #
325  # Cluster new jet
326  #
327  if recoJetInfo.jetPUMethod == "chs":
328  self.addProcessAndTask(proc, jetCollection, ak4PFJetsCHS.clone(
329  src = pfCand,
330  )
331  )
332  elif recoJetInfo.jetPUMethod == "puppi":
333  self.addProcessAndTask(proc, jetCollection, ak4PFJetsPuppi.clone(
334  src = self.pfLabel,
335  srcWeights = pfCand
336  )
337  )
338  elif recoJetInfo.jetPUMethod == "sk":
339  self.addProcessAndTask(proc, pfCand, ak4PFJetsSK.clone(
340  src = pfCand,
341  )
342  )
343  elif recoJetInfo.jetPUMethod == "cs":
344  self.addProcessAndTask(proc, jetCollection, ak4PFJetsCS.clone(
345  src = pfCand,
346  )
347  )
348  else:
349  self.addProcessAndTask(proc, jetCollection, ak4PFJets.clone(
350  src = pfCand,
351  )
352  )
353  getattr(proc, jetCollection).jetAlgorithm = supportedJetAlgos[recoJetInfo.jetAlgo]
354  getattr(proc, jetCollection).rParam = recoJetInfo.jetSizeNr
355  #
356  # Set minimum pt threshold of reco jets to be saved after fastjet clustering
357  #
358  if minPtFastjet != None:
359  getattr(proc, jetCollection).jetPtMin = minPtFastjet
360  currentTasks.append(jetCollection)
361  else:
362  jetCollection = inputCollection
363 
364 
365  #=============================================
366  #
367  # Make patJet collection
368  #
369  #=============================================
370  #
371  # Jet correction
372  #
373  if recoJetInfo.jetPUMethod == "puppi":
374  jetCorrLabel = "Puppi"
375  elif recoJetInfo.jetPUMethod in [ "cs", "sk" ]:
376  jetCorrLabel = "chs"
377  else:
378  jetCorrLabel = recoJetInfo.jetPUMethod
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  postfix = "Recluster" if inputCollection == "" else ""
392  addJetCollection(
393  proc,
394  labelName = jetUpper,
395  postfix = postfix,
396  jetSource = cms.InputTag(jetCollection),
397  algo = recoJetInfo.jetAlgo,
398  rParam = recoJetInfo.jetSizeNr,
399  pvSource = cms.InputTag(self.pvLabel),
400  pfCandidates = cms.InputTag(self.pfLabel),
401  svSource = cms.InputTag(self.svLabel),
402  muSource = cms.InputTag(self.muLabel),
403  elSource = cms.InputTag(self.elLabel),
404  genJetCollection = cms.InputTag(genJetsCollection),
405  genParticles = cms.InputTag(self.gpLabel),
406  jetCorrections = jetCorrections,
407  )
408 
409  #
410  # Need to set this explicitly for PUPPI jets
411  #
412  if recoJetInfo.jetPUMethod == "puppi":
413  getattr(proc, "patJetFlavourAssociation{}{}".format(jetUpper,postfix)).weights = cms.InputTag(pfCand)
414 
415  getJetMCFlavour = not recoJetInfo.doCalo and recoJetInfo.jetPUMethod != "cs"
416  if not self.runOnMC: #Remove modules for Gen-level object matching
417  delattr(proc, 'patJetGenJetMatch{}{}'.format(jetUpper,postfix))
418  delattr(proc, 'patJetPartonMatch{}{}'.format(jetUpper,postfix))
419  getJetMCFlavour = False
420  setattr(getattr(proc, "patJets{}{}".format(jetUpper,postfix)), "getJetMCFlavour", cms.bool(getJetMCFlavour))
421 
422  selectedPatJets = "selectedPatJets{}{}".format(jetUpper,postfix)
423  #=============================================
424  #
425  # Update the patJet collection.
426  # This is where we setup
427  # - JEC
428  # - b-tagging discriminators
429  #
430  #=============================================
431  updateJetCollection(
432  proc,
433  labelName = jetUpper,
434  postfix = "Final",
435  jetSource = cms.InputTag(selectedPatJets),
436  jetCorrections = jetCorrections,
437  btagDiscriminators = bTagDiscriminators,
438  )
439 
440  recoJetInfo.patJetFinalCollection = "selectedUpdatedPatJets{}{}".format(jetUpper,"Final")
441  else:
442  recoJetInfo.patJetFinalCollection = inputCollection
443 
444  self.main.extend(currentTasks)
445 
446  return recoJetInfo
AnomalousCellParameters_cfi
jetCollectionTools.RecoJetInfo.jetLower
jetLower
Definition: jetCollectionTools.py:139
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
dqmMemoryStats.float
float
Definition: dqmMemoryStats.py:127
jetCollectionTools.GenJetInfo.jetSizeNr
jetSizeNr
Definition: jetCollectionTools.py:56
helpers.getPatAlgosToolsTask
def getPatAlgosToolsTask(process)
Definition: helpers.py:14
jetCollectionTools.RecoJetAdder.muLabel
muLabel
Definition: jetCollectionTools.py:201
jetCollectionTools.RecoJetAdder.patJetsInMiniAOD
patJetsInMiniAOD
Definition: jetCollectionTools.py:205
jetCollectionTools.GenJetAdder.addProcessAndTask
def addProcessAndTask(self, proc, label, module)
Definition: jetCollectionTools.py:72
jetCollectionTools.GenJetInfo.jetTagName
jetTagName
Definition: jetCollectionTools.py:39
Puppi_cff
jetCollectionTools.RecoJetInfo.jetPUMethod
jetPUMethod
Definition: jetCollectionTools.py:163
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
cms::cuda::assert
assert(be >=bs)
jetCollectionTools.RecoJetInfo.jetUpper
jetUpper
Definition: jetCollectionTools.py:140
jetCollectionTools.GenJetInfo.jetSize
jetSize
Definition: jetCollectionTools.py:55
jetCollectionTools.RecoJetAdder.addRecoJetCollection
def addRecoJetCollection(self, proc, jet, inputCollection="", minPtFastjet=None, genJetsCollection="", bTagDiscriminators=["None"], JETCorrLevels=["L1FastJet", "L2Relative", "L3Absolute", "L2L3Residual"])
Definition: jetCollectionTools.py:211
jetCollectionTools.RecoJetAdder.main
main
Definition: jetCollectionTools.py:197
jetCollectionTools.GenJetInfo
Definition: jetCollectionTools.py:31
jetCollectionTools.RecoJetInfo.patJetFinalCollection
patJetFinalCollection
Definition: jetCollectionTools.py:184
jetCollectionTools.GenJetAdder.addGenJetCollection
def addGenJetCollection(self, proc, jet, inputCollection="", minPtFastjet=None)
Definition: jetCollectionTools.py:76
jetCollectionTools.GenJetAdder
Definition: jetCollectionTools.py:63
jetCollectionTools.RecoJetInfo.jetCorrPayload
jetCorrPayload
Definition: jetCollectionTools.py:173
jetCorrFactors_cfi
jetCollectionTools.RecoJetInfo.doCalo
doCalo
Definition: jetCollectionTools.py:167
jetCollectionTools.GenJetAdder.prerequisites
prerequisites
Definition: jetCollectionTools.py:68
jetCollectionTools.RecoJetAdder
Definition: jetCollectionTools.py:191
jetCollectionTools.RecoJetInfo.doPF
doPF
Definition: jetCollectionTools.py:168
jetCollectionTools.RecoJetInfo.jetSize
jetSize
Definition: jetCollectionTools.py:161
jetTools
jetCollectionTools.RecoJetInfo.jetTagName
jetTagName
Definition: jetCollectionTools.py:141
jetFlavourId_cff
jetCollectionTools.GenJetInfo.jet
jet
Definition: jetCollectionTools.py:36
ak4PFJets_cfi
jetCollectionTools.GenJetAdder.__init__
def __init__(self)
Definition: jetCollectionTools.py:67
jetCollectionTools.GenJetInfo.jetLower
jetLower
Definition: jetCollectionTools.py:37
jetCollectionTools.RecoJetInfo.jetReco
jetReco
Definition: jetCollectionTools.py:162
jetCollectionTools.GenJetInfo.inputCollection
inputCollection
Definition: jetCollectionTools.py:40
jetCollectionTools.RecoJetAdder.__init__
def __init__(self, runOnMC=True)
Definition: jetCollectionTools.py:195
print
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:46
mps_setup.append
append
Definition: mps_setup.py:85
jetCollectionTools.RecoJetAdder.prerequisites
prerequisites
Definition: jetCollectionTools.py:196
jetCollectionTools.GenJetInfo.__init__
def __init__(self, jet, inputCollection)
Definition: jetCollectionTools.py:35
jetCollectionTools.RecoJetInfo.jetSizeNr
jetSizeNr
Definition: jetCollectionTools.py:165
jetCollectionTools.RecoJetAdder.gpLabel
gpLabel
Definition: jetCollectionTools.py:203
helpers
jetCollectionTools.RecoJetAdder.addProcessAndTask
def addProcessAndTask(self, proc, label, module)
Definition: jetCollectionTools.py:207
jetCollectionTools.RecoJetAdder.pfLabel
pfLabel
Definition: jetCollectionTools.py:198
jetCollectionTools.GenJetInfo.jetUpper
jetUpper
Definition: jetCollectionTools.py:38
jetCollectionTools.RecoJetInfo.inputCollection
inputCollection
Definition: jetCollectionTools.py:142
jetCollectionTools.GenJetAdder.gpLabel
gpLabel
Definition: jetCollectionTools.py:70
jetCollectionTools.RecoJetAdder.pvLabel
pvLabel
Definition: jetCollectionTools.py:199
jetUpdater_cfi
jetCollectionTools.RecoJetInfo
Definition: jetCollectionTools.py:133
jetCollectionTools.RecoJetInfo.skipUserData
skipUserData
Definition: jetCollectionTools.py:171
format
pileupCalc.upper
upper
Definition: pileupCalc.py:214
jetCollectionTools.RecoJetInfo.jetAlgo
jetAlgo
Definition: jetCollectionTools.py:160
jetCollectionTools.RecoJetAdder.runOnMC
runOnMC
Definition: jetCollectionTools.py:204
jetCollectionTools.GenJetAdder.main
main
Definition: jetCollectionTools.py:69
jetCollectionTools.RecoJetInfo.__init__
def __init__(self, jet, inputCollection)
Definition: jetCollectionTools.py:137
jetCollectionTools.RecoJetAdder.elLabel
elLabel
Definition: jetCollectionTools.py:202
jetCollectionTools.RecoJetInfo.doCS
doCS
Definition: jetCollectionTools.py:170
PFJetParameters_cfi
GenJetParameters_cfi
jetCollectionTools.RecoJetInfo.jet
jet
Definition: jetCollectionTools.py:138
helpers.addToProcessAndTask
def addToProcessAndTask(label, module, process, task)
Definition: helpers.py:29
jetCollectionTools.RecoJetAdder.svLabel
svLabel
Definition: jetCollectionTools.py:200
ConfigToolBase
jetCollectionTools.GenJetInfo.jetAlgo
jetAlgo
Definition: jetCollectionTools.py:54