CMS 3D CMS Logo

coreTools.py
Go to the documentation of this file.
1 from __future__ import print_function
2 from builtins import range
4 
6 
8 
9  """ Remove monte carlo matching from a given collection or all PAT
10  candidate collections and adapt the JEC's:
11  """
12  _label='runOnData'
13  _defaultParameters=dicttypes.SortedKeysDict()
14  def __init__(self):
15  ConfigToolBase.__init__(self)
16  self.addParameter(self._defaultParameters,'names',['All'], "collection name; supported are 'Photons', 'Electrons', 'LowPtElectrons', 'Muons', 'Taus', 'TausBoosted', 'Jets', 'METs', 'All', 'PFAll', 'PFElectrons','PFTaus','PFMuons'", allowedValues=['Photons', 'Electrons', 'LowPtElectrons', 'Muons', 'Taus', 'TausBoosted', 'Jets', 'METs', 'All', 'PFAll', 'PFElectrons','PFTaus','PFMuons'])
17  self.addParameter(self._defaultParameters,'postfix',"", "postfix of default sequence")
18  self.addParameter(self._defaultParameters,'outputModules',['out'], "names of all output modules specified to be adapted (default is ['out'])")
19  self._parameters=copy.deepcopy(self._defaultParameters)
20  self._comment = ""
21 
23  return self._defaultParameters
24 
25  def __call__(self,process,
26  names = None,
27  postfix = None,
28  outputModules = None) :
29  if names is None:
30  names=self._defaultParameters['names'].value
31  if postfix is None:
32  postfix=self._defaultParameters['postfix'].value
33  if outputModules is None:
34  outputModules=self._defaultParameters['outputModules'].value
35  self.setParameter('names',names)
36  self.setParameter('postfix',postfix)
37  self.setParameter('outputModules',outputModules)
38  self.apply(process)
39 
40  def toolCode(self, process):
41  names=self._parameters['names'].value
42  postfix=self._parameters['postfix'].value
43  outputModules=self._parameters['outputModules'].value
44 
45  print('******************* RunOnData *******************')
46  removeMCMatching(process, names=names, postfix=postfix, outputModules=outputModules)
47  for mod in process.producerNames().split():
48  if mod.startswith('patJetCorrFactors'):
49  prefix = getattr(process, mod).payload.pythonValue().replace("'","")
50  if 'L3Absolute' in getattr(process,mod).levels:
51  if not 'L2L3Residual' in getattr(process,mod).levels:
52  getattr(process,mod).levels.insert(getattr(process,mod).levels.index('L3Absolute')+1, 'L2L3Residual')
53  print('adding L2L3Residual JEC for:', getattr(process,mod).label_())
54  if hasattr(process, prefix+'CombinedCorrector'+postfix):
55  if prefix+'L3Absolute' in getattr(process,prefix+'CombinedCorrector'+postfix).correctors:
56  if not prefix+'L2L3Residual' in getattr(process,prefix+'CombinedCorrector'+postfix).correctors:
57  idx = getattr(process,prefix+'CombinedCorrector'+postfix).correctors.index(prefix+'L3Absolute')+1
58  getattr(process,prefix+'CombinedCorrector'+postfix).correctors.insert(idx, prefix+'L2L3Residual')
59  print('adding L2L3Residual for TypeI MET correction:', getattr(process,prefix+'CombinedCorrector'+postfix).label_())
60 
61 runOnData=RunOnData()
62 
63 
65 
66  """ Remove monte carlo matching from a given collection or all PAT
67  candidate collections:
68  """
69  _label='removeMCMatching'
70  _defaultParameters=dicttypes.SortedKeysDict()
71  def __init__(self):
72  ConfigToolBase.__init__(self)
73  self.addParameter(self._defaultParameters,'names',['All'],
74  "collection name; supported are 'Photons', 'OOTPhotons', 'Electrons', 'LowPtElectrons', 'Muons', 'Taus', 'TausBoosted', 'Jets', 'METs', 'All', 'PFAll', 'PFElectrons','PFTaus','PFMuons'",
75  allowedValues=['Photons', 'OOTPhotons' ,'Electrons', 'LowPtElectrons', 'Muons', 'Taus', 'TausBoosted', 'Jets', 'METs', 'All', 'PFAll', 'PFElectrons','PFTaus','PFMuons'])
76  self.addParameter(self._defaultParameters,'postfix',"", "postfix of default sequence")
77  self.addParameter(self._defaultParameters,'outputModules',['out'], "names of all output modules specified to be adapted (default is ['out'])")
78  self._parameters=copy.deepcopy(self._defaultParameters)
79  self._comment = ""
80 
82  return self._defaultParameters
83 
84  def __call__(self,process,
85  names = None,
86  postfix = None,
87  outputModules = None) :
88  if names is None:
89  names=self._defaultParameters['names'].value
90  if postfix is None:
91  postfix=self._defaultParameters['postfix'].value
92  if outputModules is None:
93  outputModules=self._defaultParameters['outputModules'].value
94  self.setParameter('names',names)
95  self.setParameter('postfix',postfix)
96  self.setParameter('outputModules',outputModules)
97  self.apply(process)
98 
99  def toolCode(self, process):
100  names=self._parameters['names'].value
101  postfix=self._parameters['postfix'].value
102  outputModules=self._parameters['outputModules'].value
103 
104  print("************** MC dependence removal ************")
105  attrsToDelete = []
106  for obj in range(len(names)):
107  if( names[obj] == 'Photons' or names[obj] == 'All' ):
108  print("removing MC dependencies for photons")
109  _removeMCMatchingForPATObject(process, 'photonMatch', 'patPhotons', postfix)
110  if( names[obj] == 'OOTPhotons' or names[obj] == 'All' ):
111  print("removing MC dependencies for out of time photons")
112  _removeMCMatchingForPATObject(process, 'ootPhotonMatch', 'patOOTPhotons', postfix)
113  if( names[obj] == 'Electrons' or names[obj] == 'All' ):
114  print("removing MC dependencies for electrons")
115  _removeMCMatchingForPATObject(process, 'electronMatch', 'patElectrons', postfix)
116  if( names[obj] == 'LowPtElectrons' or names[obj] == 'All' ):
117  print("removing MC dependencies for LowPtElectrons")
118  _removeMCMatchingForPATObject(process, 'lowPtElectronMatch', 'patLowPtElectrons', postfix)
119  if( names[obj] == 'Muons' or names[obj] == 'All' ):
120  print("removing MC dependencies for muons")
121  _removeMCMatchingForPATObject(process, 'muonMatch', 'patMuons', postfix)
122  if( names[obj] == 'Taus' or names[obj] == 'All' ):
123  print("removing MC dependencies for taus")
124  _removeMCMatchingForPATObject(process, 'tauMatch', 'patTaus', postfix)
125  ## remove mc extra configs for taus
126  tauProducer = getattr(process,'patTaus'+postfix)
127  tauProducer.addGenJetMatch = False
128  tauProducer.embedGenJetMatch = False
129  attrsToDelete += [tauProducer.genJetMatch.getModuleLabel()]
130  tauProducer.genJetMatch = ''
131  attrsToDelete += ['tauGenJets'+postfix]
132  attrsToDelete += ['tauGenJetsSelectorAllHadrons'+postfix]
133  #Boosted Taus
134  if( names[obj] == 'TausBoosted' or names[obj] == 'All' ):
135  print("removing MC dependencies for taus boosted %s" %postfix)
136  if hasattr(process, 'tauMatchBoosted'+postfix) and hasattr(process, 'patTausBoosted'+postfix) :
137  _removeMCMatchingForPATObject(process, 'tauMatchBoosted', 'patTausBoosted', postfix)
138  ## remove mc extra configs for taus
139  tauProducer = getattr(process,'patTausBoosted'+postfix)
140  tauProducer.addGenJetMatch = False
141  tauProducer.embedGenJetMatch = False
142  attrsToDelete += [tauProducer.genJetMatch.getModuleLabel()]
143  tauProducer.genJetMatch = ''
144  attrsToDelete += ['tauGenJetsBoosted'+postfix]
145  attrsToDelete += ['tauGenJetsSelectorAllHadronsBoosted'+postfix]
146  else :
147  print("...skipped since taus boosted %s" %postfix, "are not part of process.")
148  if( names[obj] == 'Jets' or names[obj] == 'All' ):
149  print("removing MC dependencies for jets")
150  jetPostfixes = []
151  for mod in process.producerNames().split():
152  if mod.startswith('patJets') and getattr(process,mod).type_() == "PATJetProducer":
153  jetPostfixes.append(getattr(process, mod).label_().replace("patJets",""))
154  for pfix in jetPostfixes:
155  ## remove mc extra configs for jets
156  jetProducer = getattr(process, jetCollectionString()+pfix)
157  jetProducer.addGenPartonMatch = False
158  jetProducer.embedGenPartonMatch = False
159  #attrsToDelete += [jetProducer.genPartonMatch.getModuleLabel()] #MM needed for potential jet backuping
160  jetProducer.genPartonMatch = ''
161  jetProducer.addGenJetMatch = False
162  #attrsToDelete += [jetProducer.genJetMatch.getModuleLabel()] #MM needed for potential jet backuping
163  jetProducer.genJetMatch = ''
164  jetProducer.getJetMCFlavour = False
165  jetProducer.useLegacyJetMCFlavour = False
166  jetProducer.addJetFlavourInfo = False
167  #attrsToDelete += [jetProducer.JetPartonMapSource.getModuleLabel()] #MM needed for potential jet backuping
168  jetProducer.JetPartonMapSource = ''
169  #attrsToDelete += [jetProducer.JetFlavourInfoSource.getModuleLabel()] #MM needed for potential jet backuping
170  jetProducer.JetFlavourInfoSource = ''
171  attrsToDelete += ['slimmedGenJets'+pfix]
172  ## adjust output
173  for outMod in outputModules:
174  if hasattr(process,outMod):
175  getattr(process,outMod).outputCommands.append("drop *_selectedPatJets*_genJets_*")
176  getattr(process,outMod).outputCommands.append("drop recoGenJets_*_*_*")
177  else:
178  raise KeyError("process has no OutModule named " + outMod)
179 
180  if( names[obj] == 'METs' or names[obj] == 'All' ):
181  for mod in process.producerNames().split():
182  if mod.startswith('pat') and getattr(process,mod).type_() == "PATMETProducer":
183  ## remove mc extra configs for MET
184  metProducer = getattr(process, mod)
185  metProducer.addGenMET = False
186  attrsToDelete += [metProducer.genMETSource.getModuleLabel()]
187  metProducer.genMETSource = ''
188  attrsToDelete += [
189  'prunedGenParticles',
190  'prunedGenParticlesWithStatusOne',
191  'packedGenParticles',
192  'packedPFCandidateToGenAssociation',
193  'lostTracksToGenAssociation',
194  ]
195  for attr in attrsToDelete:
196  if hasattr(process,attr): delattr(process,attr)
197 
198 removeMCMatching=RemoveMCMatching()
199 
200 def _removeMCMatchingForPATObject(process, matcherName, producerName, postfix=""):
201  if hasattr(process, matcherName+postfix):
202  objectMatcher = getattr(process, matcherName+postfix)
203  if hasattr(process, producerName+postfix):
204  objectProducer = getattr(process, producerName+postfix)
205  objectProducer.addGenMatch = False
206  objectProducer.embedGenMatch = False
207  attr = objectProducer.genParticleMatch.getModuleLabel()
208  objectProducer.genParticleMatch = ''
209  if hasattr(process,attr): delattr(process,attr)
210 
def _removeMCMatchingForPATObject(process, matcherName, producerName, postfix="")
Definition: coreTools.py:200
def replace(string, replacements)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
def getDefaultParameters(self)
Definition: coreTools.py:22
def toolCode(self, process)
Definition: coreTools.py:99
def jetCollectionString(prefix='', algo='', type='')
Definition: helpers.py:217
def __init__(self)
Definition: coreTools.py:14
def __call__(self, process, names=None, postfix=None, outputModules=None)
Definition: coreTools.py:28
def getDefaultParameters(self)
Definition: coreTools.py:81
double split
Definition: MVATrainer.cc:139
def toolCode(self, process)
Definition: coreTools.py:40
def __call__(self, process, names=None, postfix=None, outputModules=None)
Definition: coreTools.py:87