CMS 3D CMS Logo

adaptToRunAtMiniAOD.py
Go to the documentation of this file.
1 import FWCore.ParameterSet.Config as cms
2 
3 
9 
10 import PhysicsTools.PatAlgos.tools.helpers as configtools
11 
13  def __init__(self, process, runBoosted=False, postfix=""):
14  self.process = process
15  self.runBoosted = runBoosted
16  self.postfix = postfix
17  if runBoosted:
18  self.postfix = 'Boosted'+postfix
19  #print("Adapting boosted tau reconstruction to run at miniAOD; postfix = \"%s\"" % self.postfix)
20  #else:
21  # print("Adapting tau reconstruction to run at miniAOD; postfix = \"%s\"" % self.postfix)
22 
23 
24  def addTauReReco(self):
25  #PAT
26  self.process.load('PhysicsTools.PatAlgos.producersLayer1.tauProducer_cff')
27  self.process.load('PhysicsTools.PatAlgos.selectionLayer1.tauSelector_cfi')
28  self.process.selectedPatTaus.cut="pt > 18. && tauID(\'decayModeFindingNewDMs\')> 0.5" #Cut as in MiniAOD
29  #Tau RECO
30  self.process.load("RecoTauTag.Configuration.RecoPFTauTag_cff")
31  #Task/Sequence for tau rereco
32  self.process.miniAODTausTask = cms.Task(
33  self.process.PFTauTask,
34  self.process.makePatTausTask,
35  self.process.selectedPatTaus
36  )
37  #Add Run-2 tauIDs for boostedTaus
38  if self.runBoosted:
39  self.process.PFTauMVAIsoTask = cms.Task(
40  self.process.hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLTraw,
41  self.process.hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLT,
42  self.process.hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLTraw,
43  self.process.hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLT
44  )
45  self.process.PFTauTask.add(self.process.PFTauMVAIsoTask)
46  self.miniAODTausTask = configtools.cloneProcessingSnippetTask(
47  self.process,self.process.miniAODTausTask,postfix=self.postfix)
48  setattr(self.process,'miniAODTausSequence'+self.postfix,cms.Sequence(self.miniAODTausTask))
49  if not self.postfix=="":
50  del self.process.miniAODTausTask
51 
52 
54  module = getattr(self.process, name)
55  if hasattr(module, 'particleFlowSrc'):
56  module.particleFlowSrc = cms.InputTag("packedPFCandidates", "", "")
57  if hasattr(module, 'vertexSrc'):
58  module.vertexSrc = cms.InputTag('offlineSlimmedPrimaryVertices')
59  if hasattr(module, 'qualityCuts') and hasattr(module.qualityCuts, 'primaryVertexSrc'):
60  module.qualityCuts.primaryVertexSrc = cms.InputTag('offlineSlimmedPrimaryVertices')
61 
62 
63  def adaptTauToMiniAODReReco(self,reclusterJets=True):
64  # TRYING TO MAKE THINGS MINIAOD COMPATIBLE, FROM THE START, TO THE END, 1 BY 1
65  #print '[adaptTauToMiniAODReReco]: Start'
66  jetCollection = 'slimmedJets'
67  # Add new jet collections if reclustering is demanded
68  if self.runBoosted:
69  jetCollection = 'boostedTauSeedsPAT'+self.postfix
70  from RecoTauTag.Configuration.boostedHPSPFTaus_cff import ca8PFJetsCHSprunedForBoostedTaus
71  setattr(self.process,'ca8PFJetsCHSprunedForBoostedTausPAT'+self.postfix,ca8PFJetsCHSprunedForBoostedTaus.clone(
72  src = 'packedPFCandidates',
73  jetCollInstanceName = 'subJetsForSeedingBoostedTausPAT'
74  ))
75  setattr(self.process,'boostedTauSeedsPAT'+self.postfix,
76  cms.EDProducer("PATBoostedTauSeedsProducer",
77  subjetSrc = cms.InputTag('ca8PFJetsCHSprunedForBoostedTausPAT'+self.postfix,'subJetsForSeedingBoostedTausPAT'),
78  pfCandidateSrc = cms.InputTag('packedPFCandidates'),
79  verbosity = cms.int32(0)
80  ))
81  self.miniAODTausTask.add(getattr(self.process,'ca8PFJetsCHSprunedForBoostedTausPAT'+self.postfix))
82  self.miniAODTausTask.add(getattr(self.process,'boostedTauSeedsPAT'+self.postfix))
83  elif reclusterJets:
84  jetCollection = 'patJetsPAT'+self.postfix
85  from RecoJets.JetProducers.ak4PFJets_cfi import ak4PFJets
86  setattr(self.process,'ak4PFJetsPAT'+self.postfix,ak4PFJets.clone(
87  src = "packedPFCandidates"
88  ))
89  # trivial PATJets
91  setattr(self.process,'patJetsPAT'+self.postfix,_patJets.clone(
92  jetSource = "ak4PFJetsPAT"+self.postfix,
93  addJetCorrFactors = False,
94  jetCorrFactorsSource = [],
95  addBTagInfo = False,
96  addDiscriminators = False,
97  discriminatorSources = [],
98  addAssociatedTracks = False,
99  addJetCharge = False,
100  addGenPartonMatch = False,
101  embedGenPartonMatch = False,
102  addGenJetMatch = False,
103  getJetMCFlavour = False,
104  addJetFlavourInfo = False,
105  ))
106  self.miniAODTausTask.add(getattr(self.process,'ak4PFJetsPAT'+self.postfix))
107  self.miniAODTausTask.add(getattr(self.process,'patJetsPAT'+self.postfix))
108 
109  # so this adds all tracks to jet in some deltaR region. we don't have tracks so don't need it :D
110  # self.process.ak4PFJetTracksAssociatorAtVertex.jets = cms.InputTag(jetCollection)
111 
112  # Remove ak4PFJetTracksAssociatorAtVertex from recoTauCommonSequence
113  # Remove pfRecoTauTagInfoProducer from recoTauCommonSequence since it uses the jet-track association
114  # HOWEVER, may use https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookMiniAOD2017#Isolated_Tracks
115  # probably needs recovery of the two modules above
116  self.miniAODTausTask.remove(getattr(self.process,'ak4PFJetTracksAssociatorAtVertex'+self.postfix))
117  self.miniAODTausTask.remove(getattr(self.process,'pfRecoTauTagInfoProducer'+self.postfix))
118 
119  self.miniAODTausTask.remove(getattr(self.process,'recoTauAK4PFJets08Region'+self.postfix))
120  setattr(self.process,'recoTauAK4Jets08RegionPAT'+self.postfix,
121  cms.EDProducer("RecoTauPatJetRegionProducer",
122  deltaR = self.process.recoTauAK4PFJets08Region.deltaR,
123  maxJetAbsEta = self.process.recoTauAK4PFJets08Region.maxJetAbsEta,
124  minJetPt = self.process.recoTauAK4PFJets08Region.minJetPt,
125  pfCandAssocMapSrc = cms.InputTag(""),
126  pfCandSrc = cms.InputTag("packedPFCandidates"),
127  src = cms.InputTag(jetCollection)
128  ))
129  _jetRegionProducer = getattr(self.process,'recoTauAK4Jets08RegionPAT'+self.postfix)
130  self.miniAODTausTask.add(_jetRegionProducer)
131  if self.runBoosted:
132  _jetRegionProducer.pfCandAssocMapSrc = cms.InputTag(jetCollection, 'pfCandAssocMapForIsolation')
133 
134  getattr(self.process,'recoTauPileUpVertices'+self.postfix).src = "offlineSlimmedPrimaryVertices"
135 
136  for moduleName in self.miniAODTausTask.moduleNames():
137  self.convertModuleToMiniAODInput(moduleName)
138 
139 
140  # Adapt TauPiZeros producer
141  _piZeroProducer = getattr(self.process,'ak4PFJetsLegacyHPSPiZeros'+self.postfix)
142  for builder in _piZeroProducer.builders:
143  builder.qualityCuts.primaryVertexSrc = "offlineSlimmedPrimaryVertices"
144  _piZeroProducer.jetSrc = jetCollection
145 
146  # Adapt TauChargedHadrons producer
147  _chargedHadronProducer = getattr(self.process,'ak4PFJetsRecoTauChargedHadrons'+self.postfix)
148  for builder in _chargedHadronProducer.builders:
149  builder.qualityCuts.primaryVertexSrc = "offlineSlimmedPrimaryVertices"
150  if builder.name.value() == 'tracks': #replace plugin based on generalTracks by one based on lostTracks
151  builder.name = 'lostTracks'
152  builder.plugin = 'PFRecoTauChargedHadronFromLostTrackPlugin'
153  builder.srcTracks = "lostTracks"
154  if self.runBoosted:
155  builder.dRcone = 0.3
156  builder.dRconeLimitedToJetArea = True
157  _chargedHadronProducer.jetSrc = jetCollection
158 
159  # Adapt combinatoricRecoTau producer
160  _combinatoricRecoTauProducer = getattr(self.process,'combinatoricRecoTaus'+self.postfix)
161  _combinatoricRecoTauProducer.jetRegionSrc = 'recoTauAK4Jets08RegionPAT'+self.postfix
162  _combinatoricRecoTauProducer.jetSrc = jetCollection
163  # Adapt builders
164  for builder in _combinatoricRecoTauProducer.builders:
165  for name,value in builder.parameters_().items():
166  if name == 'qualityCuts':
167  builder.qualityCuts.primaryVertexSrc = 'offlineSlimmedPrimaryVertices'
168  elif name == 'pfCandSrc':
169  builder.pfCandSrc = 'packedPFCandidates'
170  # Adapt supported modifiers and remove unsupported ones
171  _modifiersToRemove = cms.VPSet()
172  for mod in _combinatoricRecoTauProducer.modifiers:
173  if mod.name.value() == 'elec_rej':
174  _modifiersToRemove.append(mod)
175  continue
176  elif mod.name.value() == 'TTIworkaround':
177  _modifiersToRemove.append(mod)
178  continue
179  elif mod.name.value() == 'tau_lost_tracks':
180  _modifiersToRemove.append(mod)
181  continue
182  for name,value in mod.parameters_().items():
183  if name == 'qualityCuts':
184  mod.qualityCuts.primaryVertexSrc = 'offlineSlimmedPrimaryVertices'
185  for mod in _modifiersToRemove:
186  _combinatoricRecoTauProducer.modifiers.remove(mod)
187  #print "\t\t Removing '%s' modifier from 'combinatoricRecoTaus'" %mod.name.value()
188 
189  # Redefine tau PV producer
190  _tauPVProducer = getattr(self.process,'hpsPFTauPrimaryVertexProducer'+self.postfix)
191  _tauPVProducer.__dict__['_TypedParameterizable__type'] = 'PFTauMiniAODPrimaryVertexProducer'
192  _tauPVProducer.PVTag = 'offlineSlimmedPrimaryVertices'
193  _tauPVProducer.packedCandidatesTag = cms.InputTag("packedPFCandidates")
194  _tauPVProducer.lostCandidatesTag = cms.InputTag("lostTracks")
195 
196  # Redefine tau SV producer
197  setattr(self.process,'hpsPFTauSecondaryVertexProducer'+self.postfix,
198  cms.EDProducer("PFTauSecondaryVertexProducer",
199  PFTauTag = cms.InputTag("hpsPFTauProducer"+self.postfix)
200  ))
201 
202  # Remove RecoTau producers which are not supported (yet?), i.e. against-e/mu discriminats
203  for moduleName in self.miniAODTausTask.moduleNames():
204  if 'ElectronRejection' in moduleName or 'MuonRejection' in moduleName:
205  if 'ByDeadECALElectronRejection' in moduleName: continue
206  self.miniAODTausTask.remove(getattr(self.process, moduleName))
207 
208  # Instead add against-mu discriminants which are MiniAOD compatible
209  from RecoTauTag.RecoTau.hpsPFTauDiscriminationByMuonRejectionSimple_cff import hpsPFTauDiscriminationByMuonRejectionSimple
210 
211  setattr(self.process,'hpsPFTauDiscriminationByMuonRejectionSimple'+self.postfix,
212  hpsPFTauDiscriminationByMuonRejectionSimple.clone(
213  PFTauProducer = "hpsPFTauProducer"+self.postfix))
214  _tauIDAntiMuSimple = getattr(self.process,'hpsPFTauDiscriminationByMuonRejectionSimple'+self.postfix)
215  if self.runBoosted:
216  _tauIDAntiMuSimple.dRmuonMatch = 0.1
217  self.miniAODTausTask.add(_tauIDAntiMuSimple)
218 
219 
221 
222  getattr(self.process,'tauGenJets'+self.postfix).GenParticles = "prunedGenParticles"
223  getattr(self.process,'tauMatch'+self.postfix).matched = "prunedGenParticles"
224 
225  # Remove unsupported tauIDs
226  _patTauProducer = getattr(self.process,'patTaus'+self.postfix)
227  for name,src in _patTauProducer.tauIDSources.parameters_().items():
228  if name.find('againstElectron') > -1 or name.find('againstMuon') > -1:
229  if name.find('againstElectronDeadECAL') > -1: continue
230  delattr(_patTauProducer.tauIDSources,name)
231  # Add MiniAOD specific ones
232  setattr(_patTauProducer.tauIDSources,'againstMuonLooseSimple',
233  cms.PSet(inputTag = cms.InputTag('hpsPFTauDiscriminationByMuonRejectionSimple'+self.postfix),
234  provenanceConfigLabel = cms.string('IDWPdefinitions'),
235  idLabel = cms.string('ByLooseMuonRejectionSimple')
236  ))
237  setattr(_patTauProducer.tauIDSources,'againstMuonTightSimple',
238  cms.PSet(inputTag = cms.InputTag('hpsPFTauDiscriminationByMuonRejectionSimple'+self.postfix),
239  provenanceConfigLabel = cms.string('IDWPdefinitions'),
240  idLabel = cms.string('ByTightMuonRejectionSimple')
241  ))
242  #Add Run-2 tauIDs still used for boostedTaus
243  if self.runBoosted:
245  containerID(_patTauProducer.tauIDSources,
246  "hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLT"+self.postfix,
247  "rawValues", [
248  ["byIsolationMVArun2DBoldDMwLTraw", "discriminator"]
249  ])
250  containerID(_patTauProducer.tauIDSources,
251  "hpsPFTauDiscriminationByIsolationMVArun2v1DBoldDMwLT"+self.postfix,
252  "workingPoints", [
253  ["byVVLooseIsolationMVArun2DBoldDMwLT", "_VVLoose"],
254  ["byVLooseIsolationMVArun2DBoldDMwLT", "_VLoose"],
255  ["byLooseIsolationMVArun2DBoldDMwLT", "_Loose"],
256  ["byMediumIsolationMVArun2DBoldDMwLT", "_Medium"],
257  ["byTightIsolationMVArun2DBoldDMwLT", "_Tight"],
258  ["byVTightIsolationMVArun2DBoldDMwLT", "_VTight"],
259  ["byVVTightIsolationMVArun2DBoldDMwLT", "_VVTight"]
260  ])
261  containerID(_patTauProducer.tauIDSources,
262  "hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLT"+self.postfix,
263  "rawValues", [
264  ["byIsolationMVArun2DBnewDMwLTraw", "discriminator"]
265  ])
266  containerID(_patTauProducer.tauIDSources,
267  "hpsPFTauDiscriminationByIsolationMVArun2v1DBnewDMwLT"+self.postfix,
268  "workingPoints", [
269  ["byVVLooseIsolationMVArun2DBnewDMwLT", "_VVLoose"],
270  ["byVLooseIsolationMVArun2DBnewDMwLT", "_VLoose"],
271  ["byLooseIsolationMVArun2DBnewDMwLT", "_Loose"],
272  ["byMediumIsolationMVArun2DBnewDMwLT", "_Medium"],
273  ["byTightIsolationMVArun2DBnewDMwLT", "_Tight"],
274  ["byVTightIsolationMVArun2DBnewDMwLT", "_VTight"],
275  ["byVVTightIsolationMVArun2DBnewDMwLT", "_VVTight"]
276  ])
277 
278  # Run TauIDs (anti-e && deepTau) on top of selectedPatTaus
279  _updatedTauName = 'selectedPatTausNewIDs'+self.postfix
280  _noUpdatedTauName = 'selectedPatTausNoNewIDs'+self.postfix
281  toKeep = ['deepTau2017v2p1']
282  #For boosted do not run deepTauIDs, but add still used Run-2 anti-e MVA
283  if self.runBoosted:
284  toKeep = ['againstEle']
285  import RecoTauTag.RecoTau.tools.runTauIdMVA as tauIdConfig
286  tauIdEmbedder = tauIdConfig.TauIDEmbedder(
287  self.process, debug = False,
288  originalTauName = _noUpdatedTauName,
289  updatedTauName = _updatedTauName,
290  postfix = "MiniAODTaus"+self.postfix,
291  toKeep = toKeep
292  )
293  tauIdEmbedder.runTauID()
294  setattr(self.process, _noUpdatedTauName, getattr(self.process,'selectedPatTaus'+self.postfix).clone())
295  self.miniAODTausTask.add(getattr(self.process,_noUpdatedTauName))
296  delattr(self.process, 'selectedPatTaus'+self.postfix)
297  setattr(self.process,'selectedPatTaus'+self.postfix,getattr(self.process, _updatedTauName).clone())
298  delattr(self.process, _updatedTauName)
299  setattr(self.process,'newTauIDsTask'+self.postfix,cms.Task(
300  getattr(self.process,'rerunMvaIsolationTaskMiniAODTaus'+self.postfix),
301  getattr(self.process,'selectedPatTaus'+self.postfix)
302  ))
303  self.miniAODTausTask.add(getattr(self.process,'newTauIDsTask'+self.postfix))
304 
305  #print '[adaptTauToMiniAODReReco]: Done!'
306 
307 
308  def setOutputModule(self,mode=0):
309  #mode = 0: store original MiniAOD and new selectedPatTaus
310  #mode = 1: store original MiniAOD, new selectedPatTaus, and all PFTau products as in AOD (except of unsuported ones), plus a few additional collections (charged hadrons, pi zeros, combinatoric reco taus)
311 
313  output = cms.OutputModule(
314  'PoolOutputModule',
315  fileName=cms.untracked.string('miniAOD_TauReco.root'),
316  fastCloning=cms.untracked.bool(False),
317  dataset=cms.untracked.PSet(
318  dataTier=cms.untracked.string('MINIAODSIM'),
319  filterName=cms.untracked.string('')
320  ),
321  outputCommands = evtContent.MINIAODSIMEventContent.outputCommands,
322  SelectEvents=cms.untracked.PSet(
323  SelectEvents=cms.vstring('*',)
324  )
325  )
326  output.outputCommands.append('keep *_selectedPatTaus'+self.postfix+'_*_*')
327  if mode==1:
328  import re
329  for prod in evtContent.RecoTauTagAOD.outputCommands:
330  if prod.find('ElectronRejection') > -1 and prod.find('DeadECAL') == -1:
331  continue
332  if prod.find('MuonRejection') > -1:
333  continue
334  if prod.find("_*_*")>-1: # products w/o instance
335  output.outputCommands.append(prod.replace("_*_*",self.postfix+"_*_*"))
336  else: # check if there are prods with instance
337  m = re.search(r'_[A-Za-z0-9]+_\*', prod)
338  if m!=None:
339  inst = m.group(0)
340  output.outputCommands.append(prod.replace(inst,self.postfix+inst))
341  else:
342  print("Warning: \"%s\" do not match known name patterns; trying to keep w/o postfix" % prod)
343  output.outputCommands.append(prod)
344 
345  output.outputCommands.append('keep *_hpsPFTauDiscriminationByMuonRejectionSimple'+self.postfix+'_*_*')
346  output.outputCommands.append('keep *_combinatoricReco*_*_*')
347  output.outputCommands.append('keep *_ak4PFJetsRecoTauChargedHadrons'+self.postfix+'_*_*')
348  output.outputCommands.append('keep *_ak4PFJetsLegacyHPSPiZeros'+self.postfix+'_*_*')
349  output.outputCommands.append('keep *_patJetsPAT'+self.postfix+'_*_*')
350  output.outputCommands.append('keep *_boostedTauSeedsPAT'+self.postfix+'_*_*')
351 
352  return output
353 
354 
def containerID(pset, inputID, provCfgLabel, wps)
def adaptTauToMiniAODReReco(self, reclusterJets=True)
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:47
def load(fileName)
Definition: svgfig.py:547
def remove(d, key, TELL=False)
Definition: MatrixUtil.py:234
TEveGeoShape * clone(const TEveElement *element, TEveElement *parent)
Definition: eve_macros.cc:135
void add(std::map< std::string, TH1 *> &h, TH1 *hist)
def __init__(self, process, runBoosted=False, postfix="")