1 from __future__
import print_function
2 import FWCore.ParameterSet.Config
as cms
11 from FWCore.ParameterSet.MassReplace
import massSearchReplaceAnyInputTag, MassSearchReplaceAnyInputTagVisitor
12 from FWCore.ParameterSet.MassReplace
import massSearchReplaceParam, MassSearchParamVisitor, MassSearchReplaceParamVisitor
15 taskName =
"patAlgosToolsTask" 16 if hasattr(process, taskName):
17 task = getattr(process, taskName)
18 if not isinstance(task, cms.Task):
19 raise Exception(
"patAlgosToolsTask does not have type Task")
21 setattr(process, taskName, cms.Task())
22 task = getattr(process, taskName)
27 process.schedule.associate(task)
30 setattr(process, label, module)
31 task.add(getattr(process, label))
34 config = config.replace(
"/",
".")
37 module = __import__(config)
38 for name
in dir(sys.modules[config]):
39 item = getattr(sys.modules[config],name)
40 if isinstance(item,cms._Labelable)
and not isinstance(item,cms._ModuleSequenceType)
and not name.startswith(
'_')
and not (name ==
"source" or name ==
"looper" or name ==
"subProcess")
and not isinstance(item, cms.PSet):
41 if 'ESProducer' in item.type_():
42 setattr(process,name,item)
44 def loadWithPrefix(process,moduleName,prefix='',loadedProducersAndFilters=None):
47 def loadWithPostfix(process,moduleName,postfix='',loadedProducersAndFilters=None):
51 moduleName = moduleName.replace(
"/",
".")
52 module = __import__(moduleName)
57 if loadedProducersAndFilters:
58 if isinstance(module, cms.EDProducer)
or isinstance(module, cms.EDFilter):
59 loadedProducersAndFilters.add(module)
62 """Look in other and find types which we can use""" 66 if loadedProducersAndFilters:
67 task = getattr(process, loadedProducersAndFilters)
68 if not isinstance(task, cms.Task):
69 raise Exception(
"extendWithPrePostfix argument must be name of Task type object attached to the process or None")
73 sequence = cms.Sequence()
74 sequence._moduleLabels = []
75 for name
in dir(other):
77 if name.startswith(
'_'):
79 item = getattr(other,name)
80 if name ==
"source" or name ==
"looper" or name ==
"subProcess":
82 elif isinstance(item,cms._ModuleSequenceType):
84 elif isinstance(item,cms.Task):
86 elif isinstance(item,cms.Schedule):
88 elif isinstance(item,cms.VPSet)
or isinstance(item,cms.PSet):
90 elif isinstance(item,cms._Labelable):
91 if not item.hasLabel_():
93 if prefix !=
'' or postfix !=
'':
94 newModule = item.clone()
95 if isinstance(item,cms.ESProducer):
98 if 'TauDiscrimination' in name:
99 process.__setattr__(name,item)
101 newName = prefix+name+postfix
102 process.__setattr__(newName,newModule)
104 if isinstance(newModule, cms._Sequenceable)
and not newName == name:
105 sequence +=getattr(process,newName)
106 sequence._moduleLabels.append(item.label())
108 process.__setattr__(name,item)
111 if prefix !=
'' or postfix !=
'':
112 for label
in sequence._moduleLabels:
117 if hasattr(process, label+postfix):
118 result = getattr(process, label + postfix)
120 raise ValueError(
"Error in <applyPostfix>: No module of name = %s attached to process !!" % (label + postfix))
125 if target+postfix
in labels:
126 getattr(process, sequenceLabel+postfix).
remove(
127 getattr(process, target+postfix)
131 position = -len(postfix)
135 result = [ m.label()[:position]
for m
in listModules( getattr(process,sequenceLabel+postfix))]
136 result.extend([ m.label()[:position]
for m
in listSequences( getattr(process,sequenceLabel+postfix))] )
138 result = [ m.label()
for m
in listModules( getattr(process,sequenceLabel+postfix))]
139 result.extend([ m.label()
for m
in listSequences( getattr(process,sequenceLabel+postfix))] )
144 """Visitor that travels within a cms.Sequence, and returns a list of objects of type gatheredInance(e.g. modules) that have it""" 150 self._modules.append(visitee)
157 """Visitor that travels within a cms.Sequence, and returns a cloned version of the Sequence. 158 All modules and sequences are cloned and a postfix is added""" 159 def __init__(self, process, label, postfix, removePostfix="", noClones = [], addToTask = False):
172 if isinstance(visitee, cms._Module):
173 label = visitee.label()
176 newModule = getattr(self.
_process, label)
180 self._moduleLabels.append(label)
181 newModule = visitee.clone()
191 for label
in self._moduleLabels:
193 self._moduleLabels = []
194 return self._clonedSequence
201 raise Exception(
"Tried to remove postfix %s from label %s, but it wasn't there" % (self.
_removePostfix, label))
209 sequence.visit(visitor)
210 return visitor.modules()
214 sequence.visit(visitor)
215 return visitor.modules()
219 ------------------------------------------------------------------ 220 return the string of the jet collection module depending on the 221 input vaules. The default return value will be 'patAK5CaloJets'. 223 algo : indicating the algorithm type of the jet [expected are 224 'AK5', 'IC5', 'SC7', ...] 225 type : indicating the type of constituents of the jet [expec- 226 ted are 'Calo', 'PFlow', 'JPT', ...] 227 prefix : prefix indicating the type of pat collection module (ex- 228 pected are '', 'selected', 'clean'). 229 ------------------------------------------------------------------ 232 jetCollectionString =
'pat' 234 jetCollectionString =prefix
235 jetCollectionString+=
'Pat' 236 jetCollectionString+=
'Jets' 237 jetCollectionString+=algo
238 jetCollectionString+=type
239 return jetCollectionString
243 ------------------------------------------------------------------ 244 return True if a module with name 'module' is contained in the 245 sequence with name 'sequence' and False otherwise. This version 246 is not so nice as it also returns True for any substr of the name 247 of a contained module. 249 sequence : sequence [e.g. process.patDefaultSequence] 250 module : module name as a string 251 ------------------------------------------------------------------ 253 return not sequence.__str__().
find(moduleName)==-1
259 ------------------------------------------------------------------ 260 copy a sequence plus the modules and sequences therein 261 both are renamed by getting a postfix 262 input tags are automatically adjusted 263 ------------------------------------------------------------------ 266 if not postfix ==
"":
267 visitor =
CloneSequenceVisitor(process, sequence.label(), postfix, removePostfix, noClones, addToTask)
268 sequence.visit(visitor)
269 result = visitor.clonedSequence()
274 Walk up the dependencies of a module to find any that depend on any of the listed sources 276 def allDirectInputModules(moduleOrPSet,moduleName,attrName):
278 for name,value
in six.iteritems(moduleOrPSet.parameters_()):
279 type = value.pythonTypeName()
280 if type ==
'cms.PSet':
281 ret.update(allDirectInputModules(value,moduleName,moduleName+
"."+name))
282 elif type ==
'cms.VPSet':
283 for (i,ps)
in enumerate(value):
284 ret.update(allDirectInputModules(ps,moduleName,
"%s.%s[%d]"%(moduleName,name,i)))
285 elif type ==
'cms.VInputTag':
286 inputs = [ MassSearchReplaceAnyInputTagVisitor.standardizeInputTagFmt(it)
for it
in value ]
287 inputLabels = [ tag.moduleLabel
for tag
in inputs
if tag.processName ==
'' or tag.processName == process.name_() ]
288 ret.update(inputLabels)
289 if verbose
and inputLabels:
print(
"%s depends on %s via %s" % (moduleName, inputLabels, attrName+
"."+name))
290 elif type.endswith(
'.InputTag'):
291 if value.processName ==
'' or value.processName == process.name_():
292 ret.add(value.moduleLabel)
293 if verbose:
print(
"%s depends on %s via %s" % (moduleName, value.moduleLabel, attrName+
"."+name))
296 def fillDirectDepGraphs(root,fwdepgraph,revdepgraph):
297 if root.label_()
in fwdepgraph:
return 298 deps = allDirectInputModules(root,root.label_(),root.label_())
299 fwdepgraph[root.label_()] = []
301 fwdepgraph[root.label_()].
append(d)
302 if d
not in revdepgraph: revdepgraph[d] = []
303 revdepgraph[d].
append(root.label_())
304 depmodule = getattr(process,d,
None)
306 fillDirectDepGraphs(depmodule,fwdepgraph,revdepgraph)
307 return (fwdepgraph,revdepgraph)
308 fwdepgraph, revdepgraph = fillDirectDepGraphs(module, {}, {})
309 def flattenRevDeps(flatgraph, revdepgraph, tip):
310 """Make a graph that for each module lists all the ones that depend on it, directly or indirectly""" 312 if tip
in flatgraph:
return 314 if tip
not in revdepgraph:
return 318 for d
in revdepgraph[tip]:
320 flattenRevDeps(flatgraph, revdepgraph, d)
324 mydeps.update(flatgraph[d])
325 flatgraph[tip] = mydeps
329 flattenRevDeps(flatdeps, revdepgraph, s)
330 if s
in flatdeps: allmodules.update(f
for f
in flatdeps[s])
331 livemodules = [ a
for a
in allmodules
if hasattr(process,a) ]
332 if not livemodules:
return None 333 modulelist = [livemodules.pop()]
334 for module
in livemodules:
335 for i,m
in enumerate(modulelist):
336 if module
in flatdeps
and m
in flatdeps[module]:
337 modulelist.insert(i, module)
339 if module
not in modulelist:
340 modulelist.append(module)
342 for i,m1
in enumerate(modulelist):
343 for j,m2
in enumerate(modulelist):
345 if m2
in flatdeps
and m1
in flatdeps[m2]:
346 raise RuntimeError(
"BAD ORDER %s BEFORE %s" % (m1,m2))
347 modules = [ getattr(process,p)
for p
in modulelist ]
352 return task,cms.Sequence(task)
355 """Add new keep statements to any PoolOutputModule of the process that has the old keep statements""" 356 for name,out
in six.iteritems(process.outputModules):
357 if out.type_() ==
'PoolOutputModule' and hasattr(out,
"outputCommands"):
358 if oldKeep
in out.outputCommands:
359 out.outputCommands += newKeeps
361 print(
"Adding the following keep statements to output module %s: " % name)
362 for k
in newKeeps:
print(
"\t'%s'," % k)
365 if __name__==
"__main__":
372 p = cms.Process(
"test")
373 p.a = cms.EDProducer(
"a", src=cms.InputTag(
"gen"))
374 p.b = cms.EDProducer(
"b", src=cms.InputTag(
"a"))
375 p.c = cms.EDProducer(
"c", src=cms.InputTag(
"b",
"instance"))
376 p.s = cms.Sequence(p.a*p.b*p.c *p.a)
378 self.assertEqual(p.dumpPython(),
379 """import FWCore.ParameterSet.Config as cms 381 process = cms.Process("test") 383 process.a = cms.EDProducer("a", 384 src = cms.InputTag("gen") 388 process.aNew = cms.EDProducer("a", 389 src = cms.InputTag("gen") 393 process.b = cms.EDProducer("b", 394 src = cms.InputTag("a") 398 process.bNew = cms.EDProducer("b", 399 src = cms.InputTag("aNew") 403 process.c = cms.EDProducer("c", 404 src = cms.InputTag("b","instance") 408 process.cNew = cms.EDProducer("c", 409 src = cms.InputTag("bNew","instance") 413 process.patAlgosToolsTask = cms.Task(process.aNew, process.bNew, process.cNew) 416 process.s = cms.Sequence(process.a+process.b+process.c+process.a) 419 process.sNew = cms.Sequence(process.aNew+process.bNew+process.cNew+process.aNew) 424 p = cms.Process(
"test")
425 p.a = cms.EDProducer(
"a", src=cms.InputTag(
"gen"))
426 p.b = cms.EDProducer(
"ab", src=cms.InputTag(
"a"))
427 p.c = cms.EDProducer(
"ac", src=cms.InputTag(
"b"))
428 p.s1 = cms.Sequence(p.a*p.b*p.c)
429 p.s2 = cms.Sequence(p.b*p.c)
431 self.assert_(
not contains(p.s2,
"a") )
434 self.assertEqual(
jetCollectionString(prefix =
'prefix', algo =
'Foo', type =
'Bar'),
'prefixPatJetsFooBar')
436 p = cms.Process(
"test")
437 p.a = cms.EDProducer(
"a", src=cms.InputTag(
"gen"))
438 p.b = cms.EDProducer(
"ab", src=cms.InputTag(
"a"))
439 p.c = cms.EDProducer(
"ac", src=cms.InputTag(
"b"))
440 p.s = cms.Sequence(p.a*p.b*p.c)
def extendWithPrePostfix(process, other, prefix, postfix, loadedProducersAndFilters=None)
def cloneProcessingSnippet(process, sequence, postfix, removePostfix="", noClones=[], addToTask=False)
def loadWithPrePostfix(process, moduleName, prefix='', postfix='', loadedProducersAndFilters=None)
def contains(sequence, moduleName)
def massSearchReplaceAnyInputTag(sequence, oldInputTag, newInputTag, verbose=False, moduleLabelOnly=False, skipLabelTest=False)
def addToProcessAndTask(label, module, process, task)
def _newLabel(self, label)
def testJetCollectionString(self)
S & print(S &os, JobReport::InputFile const &f)
def removeIfInSequence(process, target, sequenceLabel, postfix="")
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
def __init__(self, process, label, postfix, removePostfix="", noClones=[], addToTask=False)
def addKeepStatement(process, oldKeep, newKeeps, verbose=False)
def testListModules(self)
def applyPostfix(process, label, postfix)
def listModules(sequence)
def addESProducers(process, config)
def loadWithPrefix(process, moduleName, prefix='', loadedProducersAndFilters=None)
def __init__(self, gatheredInstance=cms._Module)
def addToTask(loadedProducersAndFilters, module)
def listSequences(sequence)
def __labelsInSequence(process, sequenceLabel, postfix="", keepPostFix=False)
def listDependencyChain(process, module, sources, verbose=False)
def jetCollectionString(prefix='', algo='', type='')
def remove(d, key, TELL=False)
def associatePatAlgosToolsTask(process)
def __appendToTopSequence(self, visitee)
def getPatAlgosToolsTask(process)
def loadWithPostfix(process, moduleName, postfix='', loadedProducersAndFilters=None)