4 from Options
import Options
10 from Mixins
import PrintOptions,_ParameterTypeBase,_SimpleParameterTypeBase, _Parameterizable, _ConfigureComponent, _TypedParameterizable, _Labelable, _Unlabelable, _ValidatingListBase
14 from Modules
import _Module
15 from SequenceTypes
import *
16 from SequenceTypes
import _ModuleSequenceType, _Sequenceable
17 from SequenceVisitors
import PathValidator, EndPathValidator
18 from Utilities
import *
21 from ExceptionHandling
import *
24 if sys.getrecursionlimit()<5000:
25 sys.setrecursionlimit(5000)
29 Raise an exception if called by special config files. This checks
30 the call or import stack for the importing file. An exception is raised if
31 the importing module is not in allowedPatterns and if it is called too deeply:
32 minLevel = 2: inclusion by top lvel cfg only
33 minLevel = 1: No inclusion allowed
34 allowedPatterns = ['Module1','Module2/SubModule1'] allows import
35 by any module in Module1 or Submodule1
41 ignorePatterns = [
'FWCore/ParameterSet/Config.py',
'<string>']
42 CMSSWPath = [os.environ[
'CMSSW_BASE'],os.environ[
'CMSSW_RELEASE_BASE']]
46 for item
in inspect.stack():
50 for pattern
in CMSSWPath:
51 if item[1].
find(pattern) != -1:
54 if item[1].
find(
'/') == -1:
57 for pattern
in ignorePatterns:
58 if item[1].
find(pattern) != -1:
62 if inPath
and not ignore:
63 trueStack.append(item[1])
65 importedFile = trueStack[0]
67 if len(trueStack) > 1:
68 importedBy = trueStack[1]
70 for pattern
in allowedPatterns:
71 if importedBy.find(pattern) > -1:
74 if len(trueStack) <= minLevel:
77 raise ImportError(
"Inclusion of %s is allowed only by cfg or specified cfi files."
81 """Look inside the module and find the Processes it contains"""
85 if isinstance(module,dict):
86 if 'process' in module:
90 if hasattr(module,
'process'):
91 if isinstance(module.process,Process):
92 process = module.process
94 raise RuntimeError(
"The attribute named 'process' does not inherit from the Process class")
96 raise RuntimeError(
"no 'process' attribute found in the module, please add one")
101 """Root class for a CMS configuration process"""
103 """The argument 'name' will be the name applied to this Process
104 Can optionally pass as additional arguments cms.Modifier instances
105 which will be used ot modify the Process as it is built
107 self.__dict__[
'_Process__name'] = name
108 if not name.isalnum():
109 raise RuntimeError(
"Error: The process name is an empty string or contains non-alphanumeric characters")
110 self.__dict__[
'_Process__filters'] = {}
111 self.__dict__[
'_Process__producers'] = {}
112 self.__dict__[
'_Process__source'] =
None
113 self.__dict__[
'_Process__looper'] =
None
114 self.__dict__[
'_Process__subProcess'] =
None
115 self.__dict__[
'_Process__schedule'] =
None
116 self.__dict__[
'_Process__analyzers'] = {}
117 self.__dict__[
'_Process__outputmodules'] = {}
120 self.__dict__[
'_Process__sequences'] = {}
121 self.__dict__[
'_Process__services'] = {}
122 self.__dict__[
'_Process__essources'] = {}
123 self.__dict__[
'_Process__esproducers'] = {}
124 self.__dict__[
'_Process__esprefers'] = {}
125 self.__dict__[
'_Process__aliases'] = {}
126 self.__dict__[
'_Process__psets']={}
127 self.__dict__[
'_Process__vpsets']={}
128 self.__dict__[
'_cloneToObjectDict'] = {}
130 self.__dict__[
'_Process__InExtendCall'] =
False
131 self.__dict__[
'_Process__partialschedules'] = {}
133 self.__dict__[
'_Process__modifiers'] = Mods
134 for m
in self.__modifiers:
139 _Module.__isStrict__ =
True
143 """Returns a string containing all the EDProducer labels separated by a blank"""
146 """Returns a string containing all the EDAnalyzer labels separated by a blank"""
149 """Returns a string containing all the EDFilter labels separated by a blank"""
152 """Returns a string containing all the Path names separated by a blank"""
159 Since cloneToObjectDict stores a hash of objects by their
160 id() it needs to be updated when unpickling to use the
161 new object id values instantiated during the unpickle.
164 self.__dict__.update(pkldict)
166 for value
in self._cloneToObjectDict.values():
167 tmpDict[id(value)] = value
168 self.__dict__[
'_cloneToObjectDict'] = tmpDict
173 """returns a dict of the filters which have been added to the Process"""
175 filters = property(filters_, doc=
"dictionary containing the filters for the process")
179 if not name.isalnum():
180 raise RuntimeError(
"Error: The process name is an empty string or contains non-alphanumeric characters")
181 self.__dict__[
'_Process__name'] = name
182 process = property(name_,setName_, doc=
"name of the process")
184 """returns a dict of the producers which have been added to the Process"""
186 producers = property(producers_,doc=
"dictionary containing the producers for the process")
188 """returns the source which has been added to the Process or None if none have been added"""
192 source = property(source_,setSource_,doc=
'the main source or None if not set')
194 """returns the looper which has been added to the Process or None if none have been added"""
198 looper = property(looper_,setLooper_,doc=
'the main looper or None if not set')
200 """returns the sub-process which has been added to the Process or None if none have been added"""
201 return self.__subProcess
204 subProcess = property(subProcess_,setSubProcess_,doc=
'the SubProcess or None if not set')
206 """returns a dict of the analyzers which have been added to the Process"""
208 analyzers = property(analyzers_,doc=
"dictionary containing the analyzers for the process")
210 """returns a dict of the output modules which have been added to the Process"""
212 outputModules = property(outputModules_,doc=
"dictionary containing the output_modules for the process")
214 """returns a dict of the paths which have been added to the Process"""
216 paths = property(paths_,doc=
"dictionary containing the paths for the process")
218 """returns a dict of the endpaths which have been added to the Process"""
220 endpaths = property(endpaths_,doc=
"dictionary containing the endpaths for the process")
222 """returns a dict of the sequences which have been added to the Process"""
224 sequences = property(sequences_,doc=
"dictionary containing the sequences for the process")
226 """returns the schedule which has been added to the Process or None if none have been added"""
227 return self.__schedule
229 if label ==
"schedule":
232 self.
_place(label, sch, self.__partialschedules)
241 raise RuntimeError(
"The path at index "+str(index)+
" in the Schedule was not attached to the process.")
243 self.__dict__[
'_Process__schedule'] = sch
244 schedule = property(schedule_,setSchedule_,doc=
'the schedule or None if not set')
246 """returns a dict of the services which have been added to the Process"""
248 services = property(services_,doc=
"dictionary containing the services for the process")
250 """returns a dict of the esproducers which have been added to the Process"""
252 es_producers = property(es_producers_,doc=
"dictionary containing the es_producers for the process")
254 """returns a the es_sources which have been added to the Process"""
256 es_sources = property(es_sources_,doc=
"dictionary containing the es_sources for the process")
258 """returns a dict of the es_prefers which have been added to the Process"""
260 es_prefers = property(es_prefers_,doc=
"dictionary containing the es_prefers for the process")
262 """returns a dict of the aliases that have been added to the Process"""
264 aliases = property(aliases_,doc=
"dictionary containing the aliases for the process")
266 """returns a dict of the PSets which have been added to the Process"""
268 psets = property(psets_,doc=
"dictionary containing the PSets for the process")
270 """returns a dict of the VPSets which have been added to the Process"""
272 vpsets = property(vpsets_,doc=
"dictionary containing the PSets for the process")
275 if not object.hasLabel_() :
276 object.setLabel(newLabel)
278 if newLabel == object.label_() :
280 if newLabel
is None :
281 object.setLabel(
None)
283 if (hasattr(self, object.label_())
and id(getattr(self, object.label_())) == id(object)) :
284 msg100 =
"Attempting to change the label of an attribute of the Process\n"
285 msg101 =
"Old label = "+object.label_()+
" New label = "+newLabel+
"\n"
286 msg102 =
"Type = "+str(type(object))+
"\n"
287 msg103 =
"Some possible solutions:\n"
288 msg104 =
" 1. Clone modules instead of using simple assignment. Cloning is\n"
289 msg105 =
" also preferred for other types when possible.\n"
290 msg106 =
" 2. Declare new names starting with an underscore if they are\n"
291 msg107 =
" for temporaries you do not want propagated into the Process. The\n"
292 msg108 =
" underscore tells \"from x import *\" and process.load not to import\n"
293 msg109 =
" the name.\n"
294 msg110 =
" 3. Reorganize so the assigment is not necessary. Giving a second\n"
295 msg111 =
" name to the same object usually causes confusion and problems.\n"
296 msg112 =
" 4. Compose Sequences: newName = cms.Sequence(oldName)\n"
297 raise ValueError(msg100+msg101+msg102+msg103+msg104+msg105+msg106+msg107+msg108+msg109+msg110+msg111+msg112)
298 object.setLabel(
None)
299 object.setLabel(newLabel)
303 if not name.replace(
'_',
'').isalnum():
304 raise ValueError(
'The label '+name+
' contains forbiden characters')
307 if name.startswith(
'_Process__'):
308 self.__dict__[name]=value
310 if not isinstance(value,_ConfigureComponent):
311 raise TypeError(
"can only assign labels to an object which inherits from '_ConfigureComponent'\n"
312 +
"an instance of "+str(type(value))+
" will not work")
313 if not isinstance(value,_Labelable)
and not isinstance(value,Source)
and not isinstance(value,Looper)
and not isinstance(value,Schedule):
314 if name == value.type_():
318 raise TypeError(
"an instance of "+str(type(value))+
" can not be assigned the label '"+name+
"'.\n"+
319 "Please either use the label '"+value.type_()+
" or use the 'add_' method instead.")
322 newValue =value.copy()
324 newValue._filename = value._filename
330 if not self.
_okToPlace(name, value, self.__dict__):
331 newFile=
'top level config'
332 if hasattr(value,
'_filename'):
333 newFile = value._filename
334 oldFile=
'top level config'
335 oldValue = getattr(self,name)
336 if hasattr(oldValue,
'_filename'):
337 oldFile = oldValue._filename
338 msg =
"Trying to override definition of process."+name
339 msg +=
"\n new object defined in: "+newFile
340 msg +=
"\n existing object defined in: "+oldFile
341 raise ValueError(msg)
343 if hasattr(self,name)
and not (getattr(self,name)==newValue):
347 if isinstance(newValue, _Sequenceable):
348 if not self.__InExtendCall:
352 newFile=
'top level config'
353 if hasattr(value,
'_filename'):
354 newFile = value._filename
355 oldFile=
'top level config'
356 oldValue = getattr(self,name)
357 if hasattr(oldValue,
'_filename'):
358 oldFile = oldValue._filename
359 msg1 =
"Trying to override definition of "+name+
" while it is used by the sequence "
360 msg2 =
"\n new object defined in: "+newFile
361 msg2 +=
"\n existing object defined in: "+oldFile
364 raise ValueError(msg1+s.label_()+msg2)
367 raise ValueError(msg1+s.label_()+msg2)
370 raise ValueError(msg1+s.label_()+msg2)
372 self.__dict__[name]=newValue
373 if isinstance(newValue,_Labelable):
375 self._cloneToObjectDict[id(value)] = newValue
376 self._cloneToObjectDict[id(newValue)] = newValue
378 newValue._place(name,self)
380 """Given a container of sequences, find the first sequence containing mod
381 and return the sequence. If no sequence is found, return None"""
383 for sequenceable
in seqs.itervalues():
386 sequenceable.visit(v)
391 if not hasattr(self,name):
392 raise KeyError(
'process does not know about '+name)
393 elif name.startswith(
'_Process__'):
394 raise ValueError(
'this attribute cannot be deleted')
399 if reg.has_key(name): del reg[name]
401 obj = getattr(self,name)
402 if isinstance(obj,_Labelable):
403 getattr(self,name).setLabel(
None)
406 del self.__dict__[name]
411 """Allows addition of components which do not have to have a label, e.g. Services"""
412 if not isinstance(value,_ConfigureComponent):
414 if not isinstance(value,_Unlabelable):
419 newValue =value.copy()
423 newValue._place(
'',self)
426 if not self.__InExtendCall:
437 if d[name]._isModified:
448 if self.
__isStrict and isinstance(mod, _ModuleSequenceType):
449 d[name] = mod._postProcessFixup(self._cloneToObjectDict)
452 if isinstance(mod,_Labelable):
455 self.
_place(name, mod, self.__outputmodules)
457 self.
_place(name, mod, self.__producers)
459 self.
_place(name, mod, self.__filters)
461 self.
_place(name, mod, self.__analyzers)
465 self.
_place(name, mod, self.__paths)
466 except ModuleCloneError, msg:
468 raise Exception(
"%sThe module %s in path %s is unknown to the process %s." %(context, msg, name, self._Process__name))
472 self.
_place(name, mod, self.__endpaths)
473 except ModuleCloneError, msg:
475 raise Exception(
"%sThe module %s in endpath %s is unknown to the process %s." %(context, msg, name, self._Process__name))
478 self.
_place(name, mod, self.__sequences)
480 self.
_place(name, mod, self.__esproducers)
482 self.
_place(name, mod, self.__esprefers)
484 self.
_place(name, mod, self.__essources)
486 self.
_place(name, mod, self.__aliases)
488 self.
_place(name, mod, self.__psets)
490 self.
_place(name, mod, self.__vpsets)
492 """Allow the source to be referenced by 'source' or by type name"""
494 raise ValueError(
"The label '"+name+
"' can not be used for a Source. Only 'source' is allowed.")
495 if self.__dict__[
'_Process__source']
is not None :
496 del self.__dict__[self.__dict__[
'_Process__source'].type_()]
497 self.__dict__[
'_Process__source'] = mod
498 self.__dict__[mod.type_()] = mod
501 raise ValueError(
"The label '"+name+
"' can not be used for a Looper. Only 'looper' is allowed.")
502 self.__dict__[
'_Process__looper'] = mod
503 self.__dict__[mod.type_()] = mod
505 if name !=
'subProcess':
506 raise ValueError(
"The label '"+name+
"' can not be used for a SubProcess. Only 'subProcess' is allowed.")
507 self.__dict__[
'_Process__subProcess'] = mod
508 self.__dict__[mod.type_()] = mod
510 self.
_place(typeName, mod, self.__services)
511 self.__dict__[typeName]=mod
513 moduleName = moduleName.replace(
"/",
".")
514 module = __import__(moduleName)
515 self.
extend(sys.modules[moduleName])
517 """Look in other and find types which we can use"""
519 self.__dict__[
'_Process__InExtendCall'] =
True
522 for name
in dir(other):
524 if name.startswith(
'_'):
526 item = getattr(other,name)
527 if name ==
"source" or name ==
"looper" or name ==
"subProcess":
529 elif isinstance(item,_ModuleSequenceType):
531 elif isinstance(item,_Labelable):
533 if not item.hasLabel_() :
535 elif isinstance(item,Schedule):
537 elif isinstance(item,_Unlabelable):
539 elif isinstance(item,ProcessModifier):
541 elif isinstance(item,ProcessFragment):
545 for name
in seqs.iterkeys():
549 if id(seq)
not in self._cloneToObjectDict:
552 newSeq = self._cloneToObjectDict[id(seq)]
553 self.__dict__[name]=newSeq
556 newSeq._place(name,self)
557 self.__dict__[
'_Process__InExtendCall'] =
False
561 for name,item
in items:
562 returnValue +=options.indentation()+typeName+
' '+name+
' = '+item.dumpConfig(options)
566 for name,item
in items:
567 returnValue +=options.indentation()+typeName+
' = '+item.dumpConfig(options)
571 for name,item
in items:
572 if name == item.type_():
574 returnValue +=options.indentation()+typeName+
' '+name+
' = '+item.dumpConfig(options)
577 """return a string containing the equivalent process defined using the old configuration language"""
578 config =
"process "+self.__name+
" = {\n"
623 for name,item
in self.psets.iteritems():
624 config +=options.indentation()+item.configTypeName()+
' '+name+
' = '+item.configValue(options)
625 for name,item
in self.vpsets.iteritems():
626 config +=options.indentation()+
'VPSet '+name+
' = '+item.configValue(options)
628 pathNames = [p.label_()
for p
in self.
schedule]
629 config +=options.indentation()+
'schedule = {'+
','.
join(pathNames)+
'}\n'
640 result +=options.indentation()+
'es_prefer '+item.targetLabel_()+
' = '+item.dumpConfig(options)
645 for name,item
in d.items():
646 returnValue +=
'process.'+name+
' = '+item.dumpPython(options)+
'\n\n'
648 for name,item
in sorted(d.items()):
649 returnValue +=
'process.'+name+
' = '+item.dumpPython(options)+
'\n\n'
656 sequence.visit(nameVisitor)
658 raise RuntimeError(
"An entry in sequence "+label +
' has no label')
663 for label,seq
in self.sequences.iteritems():
667 dependencies[label]=[dep.label_()
for dep
in d
if dep.hasLabel_()]
668 resolvedDependencies=
True
672 while resolvedDependencies:
674 resolvedDependencies = (0 != len(dependencies))
675 oldDeps =
dict(dependencies)
676 for label,deps
in oldDeps.iteritems():
678 if len(deps)==0
or iterCount > 100:
680 resolvedDependencies=
True
683 del dependencies[label]
684 for lb2,deps2
in dependencies.iteritems():
685 while deps2.count(label):
687 if len(dependencies):
688 raise RuntimeError(
"circular sequence dependency discovered \n"+
689 ",".
join([label
for label,junk
in dependencies.iteritems()]))
693 for name, value
in sorted(d.iteritems()):
694 result += value.dumpPythonAs(name,options)+
'\n'
697 """return a string containing the equivalent process defined using python"""
698 result =
"import FWCore.ParameterSet.Config as cms\n\n"
699 result +=
"process = cms.Process(\""+self.__name+
"\")\n\n"
721 pathNames = [
'process.'+p.label_()
for p
in self.
schedule]
722 result +=
'process.schedule = cms.Schedule(*[ ' +
', '.
join(pathNames) +
' ])\n'
726 old = getattr(self,label)
728 for sequenceable
in self.sequences.itervalues():
729 sequenceable.replace(old,new)
730 for sequenceable
in self.paths.itervalues():
731 sequenceable.replace(old,new)
732 for sequenceable
in self.endpaths.itervalues():
733 sequenceable.replace(old,new)
735 """ Replace the item with label 'label' by object 'new' in the process and all sequences/paths"""
736 if not hasattr(self,label):
737 raise LookupError(
"process has no item of label "+label)
739 setattr(self,label,new)
741 for name,value
in itemDict.iteritems():
742 value.insertInto(parameterSet, name)
746 newlabel = item.nameInProcessDesc_(label)
748 item.insertInto(parameterSet, newlabel)
749 parameterSet.addVString(tracked, label, vitems)
752 for name,value
in itemDict.iteritems():
753 newLabel = value.nameInProcessDesc_(name)
755 value.insertInto(parameterSet, name)
758 parameterSet.addVString(tracked, label, l)
765 for name,value
in self.
paths_().iteritems():
766 scheduledPaths.append(name)
767 triggerPaths.append(name)
768 for name,value
in self.
endpaths_().iteritems():
769 scheduledPaths.append(name)
770 endpaths.append(name)
773 pathname = path.label_()
774 scheduledPaths.append(pathname)
776 endpaths.append(pathname)
778 triggerPaths.append(pathname)
779 processPSet.addVString(
True,
"@end_paths", endpaths)
780 processPSet.addVString(
True,
"@paths", scheduledPaths)
782 p = processPSet.newPSet()
783 p.addVString(
True,
"@trigger_paths", triggerPaths)
784 processPSet.addPSet(
True,
"@trigger_paths", p)
788 for triggername
in triggerPaths:
790 pathValidator.setLabel(triggername)
792 self.
paths_()[triggername].insertInto(processPSet, triggername, self.__dict__)
793 for endpathname
in endpaths:
795 endpathValidator.setLabel(endpathname)
797 self.
endpaths_()[endpathname].insertInto(processPSet, endpathname, self.__dict__)
798 processPSet.addVString(
False,
"@filters_on_endpaths", endpathValidator.filtersOnEndpaths)
801 """ Remove clutter from the process which we think is unnecessary:
802 tracked PSets, VPSets and unused modules and sequences. If a Schedule has been set, then Paths and EndPaths
803 not in the schedule will also be removed, along with an modules and sequences used only by
804 those removed Paths and EndPaths."""
813 for x
in self.paths.itervalues():
814 x.resolve(self.__dict__)
815 for x
in self.endpaths.itervalues():
816 x.resolve(self.__dict__)
818 unneededPaths = set()
820 usedModules=set(self.
schedule_().moduleNames())
822 schedNames = set(( x.label_()
for x
in self.
schedule_()))
823 names = set(self.
paths)
825 unneededPaths = names - schedNames
826 for n
in unneededPaths:
829 pths =
list(self.paths.itervalues())
830 pths.extend(self.endpaths.itervalues())
832 usedModules=set(temp.moduleNames())
839 for p
in self.paths.itervalues():
841 for p
in self.endpaths.itervalues():
843 keepSeqSet = set(( s
for s
in seqs
if s.hasLabel_()))
844 availableSeqs = set(self.sequences.itervalues())
845 unneededSeqs = availableSeqs-keepSeqSet
846 unneededSeqLabels = []
847 for s
in unneededSeqs:
848 unneededSeqLabels.append(s.label_())
849 delattr(self,s.label_())
851 print "prune removed the following:"
852 print " modules:"+
",".
join(unneededModules)
853 print " sequences:"+
",".
join(unneededSeqLabels)
854 print " paths/endpaths:"+
",".
join(unneededPaths)
856 moduleNames = set(d.keys())
857 junk = moduleNames - scheduledNames
863 """Used by the framework to convert python to C++ objects"""
864 class ServiceInjectorAdaptor(
object):
868 def addService(self,pset):
869 self.__thelist.append(pset)
871 return self.__processPSet.newPSet()
875 class TopLevelPSetAcessorAdaptor(
object):
879 def __getattr__(self,attr):
880 return getattr(self.
__ppset,attr)
881 def getTopPSet_(self,label):
884 return TopLevelPSetAcessorAdaptor(self.__ppset.newPSet(),self.
__process)
885 def addPSet(self,tracked,name,ppset):
886 return self.__ppset.addPSet(tracked,name,self.__extractPSet(ppset))
887 def addVPSet(self,tracked,name,vpset):
888 return self.__ppset.addVPSet(tracked,name,[self.__extractPSet(x)
for x
in vpset])
889 def __extractPSet(self,pset):
890 if isinstance(pset,TopLevelPSetAcessorAdaptor):
895 processPSet.addString(
True,
"@process_name", self.
name_())
900 adaptor = TopLevelPSetAcessorAdaptor(processPSet,self)
915 getattr(self,n).insertInto(ServiceInjectorAdaptor(adaptor,services))
916 adaptor.addVPSet(
False,
"services",services)
926 def prefer(self, esmodule,*args,**kargs):
927 """Prefer this ES source or producer. The argument can
928 either be an object label, e.g.,
929 process.prefer(process.juicerProducer) (not supported yet)
930 or a name of an ESSource or ESProducer
931 process.prefer("juicer")
932 or a type of unnamed ESSource or ESProducer
933 process.prefer("JuicerProducer")
934 In addition, you can pass as a labelled arguments the name of the Record you wish to
935 prefer where the type passed is a cms.vstring and that vstring can contain the
936 name of the C++ types in the Record which are being preferred, e.g.,
937 #prefer all data in record 'OrangeRecord' from 'juicer'
938 process.prefer("juicer", OrangeRecord=cms.vstring())
940 #prefer only "Orange" data in "OrangeRecord" from "juicer"
941 process.prefer("juicer", OrangeRecord=cms.vstring("Orange"))
943 #prefer only "Orange" data with label "ExtraPulp" in "OrangeRecord" from "juicer"
944 ESPrefer("ESJuicerProd", OrangeRecord=cms.vstring("Orange/ExtraPulp"))
947 if isinstance(esmodule, ESSource)
or isinstance(esmodule, ESProducer):
948 raise RuntimeError(
"Syntax of process.prefer(process.esmodule) not supported yet")
949 elif self._findPreferred(esmodule, self.es_producers_(),*args,**kargs)
or \
950 self._findPreferred(esmodule, self.es_sources_(),*args,**kargs):
953 raise RuntimeError(
"Cannot resolve prefer for "+repr(esmodule))
958 typ = d[esname].type_()
967 for name, value
in d.iteritems():
968 if value.type_() == esname:
970 raise RuntimeError(
"More than one ES module for "+esname)
978 if isinstance(process, Process):
980 elif isinstance(process, str):
983 raise TypeError(
'a ProcessFragment can only be constructed from an existig Process or from process name')
985 return [ x
for x
in dir(self.
__process)
if isinstance(getattr(self.
__process, x), _ConfigureComponent) ]
987 if name ==
'_ProcessFragment__process':
988 return object.__getattribute__(self,
'_ProcessFragment__process')
992 if name ==
'_ProcessFragment__process':
993 object.__setattr__(self, name, value)
997 if name ==
'_ProcessFragment__process':
1004 """a dictionary with fixed keys"""
1006 raise AttributeError,
"An FilteredStream defintion cannot be modified after creation."
1007 _blocked_attribute = property(_blocked_attribute)
1008 __setattr__ = __delitem__ = __setitem__ = clear = _blocked_attribute
1009 pop = popitem = setdefault = update = _blocked_attribute
1011 new = dict.__new__(cls)
1012 dict.__init__(new, *args, **kw)
1015 if keys != [
'content',
'dataTier',
'name',
'paths',
'responsible',
'selectEvents']:
1016 raise ValueError(
"The needed parameters are: content, dataTier, name, paths, responsible, selectEvents")
1017 if not isinstance(kw[
'name'],str):
1018 raise ValueError(
"name must be of type string")
1019 if not isinstance(kw[
'content'], vstring)
and not isinstance(kw[
'content'],str):
1020 raise ValueError(
"content must be of type vstring or string")
1021 if not isinstance(kw[
'dataTier'], string):
1022 raise ValueError(
"dataTier must be of type string")
1023 if not isinstance(kw[
'selectEvents'], PSet):
1024 raise ValueError(
"selectEvents must be of type PSet")
1025 if not isinstance(kw[
'paths'],(tuple, Path)):
1026 raise ValueError(
"'paths' must be a tuple of paths")
1031 return "FilteredStream object: %s" %self[
"name"]
1036 """Allows embedding another process within a parent process. This allows one to
1037 chain processes together directly in one cmsRun job rather than having to run
1038 separate jobs which are connected via a temporary file.
1040 def __init__(self,process, SelectEvents = untracked.PSet(), outputCommands = untracked.vstring()):
1043 if not isinstance(process, Process):
1044 raise ValueError(
"the 'process' argument must be of type cms.Process")
1045 if not isinstance(SelectEvents,PSet):
1046 raise ValueError(
"the 'SelectEvents' argument must be of type cms.untracked.PSet")
1047 if not isinstance(outputCommands,vstring):
1048 raise ValueError(
"the 'outputCommands' argument must be of type cms.untracked.vstring")
1053 out =
"parentProcess"+str(
hash(self))+
" = process\n"
1054 out += self.__process.dumpPython()
1055 out +=
"childProcess = process\n"
1056 out +=
"process = parentProcess"+str(
hash(self))+
"\n"
1057 out +=
"process.subProcess = cms.SubProcess( process = childProcess, SelectEvents = "+self.__SelectEvents.dumpPython(options) +
", outputCommands = "+self.__outputCommands.dumpPython(options) +
")\n"
1062 return '@sub_process'
1064 process._placeSubProcess(
'subProcess',self)
1066 topPSet = parameterSet.newPSet()
1067 self.__process.fillProcessDesc(topPSet)
1068 subProcessPSet = parameterSet.newPSet()
1069 self.__SelectEvents.insertInto(subProcessPSet,
"SelectEvents")
1070 self.__outputCommands.insertInto(subProcessPSet,
"outputCommands")
1071 subProcessPSet.addPSet(
False,
"process",topPSet)
1075 """Helper class for Modifier which takes key/value pairs and uses them to reset parameters of the object"""
1079 for k,v
in self.__args.iteritems():
1083 """This class is used to define standard modifications to a Process.
1084 An instance of this class is declared to denote a specific modification,e.g. era2017 could
1085 reconfigure items in a process to match our expectation of running in 2017. Once declared,
1086 these Modifier instances are imported into a configuration and items which need to be modified
1087 are then associated with the Modifier and with the action to do the modification.
1088 The registered modifications will only occur if the Modifier was passed to
1089 the cms.Process' constructor.
1095 """This is used to create a ProcessModifer which can perform actions on the process as a whole.
1096 This takes as argument a callable object (e.g. function) which takes as its sole argument an instance of Process.
1097 In order to work, the value returned from this function must be assigned to a uniquely named variable.
1101 """This is used to register an action to be performed on the specific object. Two different forms are allowed
1102 Form 1: A callable object (e.g. function) can be passed as the second. This callable object is expected to take one argument
1103 which will be the object passed in as the first argument.
1104 Form 2: A list of parameter name, value pairs can be passed
1105 mod.toModify(foo, fred=cms.int32(7), barney = cms.double(3.14))
1107 if func
is not None and len(kw) != 0:
1108 raise TypeError(
"toModify takes either two arguments or one argument and key/value pairs")
1111 if func
is not None:
1117 """Should only be called by cms.Process instances"""
1123 """A Modifier made up of a list of Modifiers
1129 """Should only be called by cms.Process instances
1130 applies list of accumulated changes to the process"""
1132 m._applyNewProcessModifiers(process)
1134 """Should only be called by cms.Process instances"""
1142 """A class used by a Modifier to affect an entire Process instance.
1143 When a Process 'loads' a module containing a ProcessModifier, that
1144 ProcessModifier will be applied to the Process if and only if the
1145 Modifier passed to the constructor has been chosen.
1152 if self.__modifier.isChosen():
1155 self.__seenProcesses.add(process)
1157 if __name__==
"__main__":
1162 """Has same interface as the C++ object which creates PSets
1167 self.
values[label]=(tracked,value)
1225 """Nothing to do """
1229 self.assertEqual(len(p.parameterNames_()),0)
1231 self.assert_(
'a' in p.parameterNames_())
1232 self.assertEqual(p.a.value(), 1)
1234 self.assertEqual(p.a.value(), 10)
1236 self.assertEqual(p.a.value(), 1)
1237 self.failIf(p.a.isTracked())
1238 p.a = untracked.int32(1)
1239 self.assertEqual(p.a.value(), 1)
1240 self.failIf(p.a.isTracked())
1242 self.assertEqual(p.foo.value(), 10)
1243 self.assertEqual(p.bar.value(),1.0)
1244 self.failIf(p.bar.isTracked())
1245 self.assertRaises(TypeError,setattr,(p,
'c',1))
1247 self.assertEqual(p.a.foo.value(),10)
1248 self.assertEqual(p.a.bar.value(),1.0)
1250 self.assertEqual(p.b.fii.value(),1)
1251 self.failIf(p.b.isTracked())
1256 self.assertEqual(p.a.value(),11)
1258 self.assertEqual(p.a.value(),12)
1259 self.assertEqual(v.value(),12)
1265 self.assertNotEqual(p.b,other.b)
1270 self.assert_(
'a' in p.analyzers_() )
1271 self.assert_(
'a' in p.analyzers)
1272 p.add_(
Service(
"MessageLogger"))
1273 self.assert_(
'MessageLogger' in p.services_())
1274 self.assertEqual(p.MessageLogger.type_(),
"MessageLogger")
1276 self.assert_(
'Tracer' in p.services_())
1277 self.assertRaises(TypeError, setattr, *(p,
'b',
"this should fail"))
1278 self.assertRaises(TypeError, setattr, *(p,
'bad',
Service(
"MessageLogger")))
1279 self.assertRaises(ValueError, setattr, *(p,
'bad',
Source(
"PoolSource")))
1281 self.assertEqual(p.out.type_(),
'Outer')
1282 self.assert_(
'out' in p.outputModules_() )
1285 self.assert_(
'geom' in p.es_sources_())
1287 self.assert_(
'ConfigDB' in p.es_sources_())
1290 self.assert_(
'aliasfoo1' in p.aliases_())
1295 for name
in args.iterkeys():
1296 self.__dict__[name]=args[name]
1315 self.assertEqual(p.a.type_(),
"MyAnalyzer")
1316 self.assertEqual(p.a.label_(),
"a")
1317 self.assertRaises(AttributeError,getattr,p,
'b')
1318 self.assertEqual(p.Full.type_(),
"Full")
1319 self.assertEqual(str(p.c),
'a')
1320 self.assertEqual(str(p.d),
'a')
1335 self.assertRaises(ValueError, p1.extend, z1)
1344 aaa=copy.deepcopy(a),
1345 s4=copy.deepcopy(s3),
1352 self.assertEqual(p2.s4.label_(),
"s4")
1354 self.assertRaises(ValueError, p2.s4.setLabel,
"foo")
1355 p2.s4.setLabel(
"s4")
1356 p2.s4.setLabel(
None)
1357 p2.s4.setLabel(
"foo")
1358 p2._Process__setObjectLabel(p2.s4,
"foo")
1359 p2._Process__setObjectLabel(p2.s4,
None)
1360 p2._Process__setObjectLabel(p2.s4,
"bar")
1372 """import FWCore.ParameterSet.Config as cms
1374 process = cms.Process("test")
1376 process.a = cms.EDAnalyzer("MyAnalyzer")
1379 process.s = cms.Sequence(process.a)
1382 process.r = cms.Sequence(process.s)
1385 process.p = cms.Path(process.a)
1388 process.p2 = cms.Path(process.s)
1391 process.schedule = cms.Schedule(*[ process.p2, process.p ])
1404 """import FWCore.ParameterSet.Config as cms
1406 process = cms.Process("test")
1408 process.a = cms.EDAnalyzer("MyAnalyzer")
1411 process.b = cms.EDAnalyzer("YourAnalyzer")
1414 process.r = cms.Sequence(process.a)
1417 process.s = cms.Sequence(process.r)
1420 process.p = cms.Path(process.a)
1423 process.p2 = cms.Path(process.r)
1426 process.schedule = cms.Schedule(*[ process.p2, process.p ])
1438 """import FWCore.ParameterSet.Config as cms
1440 process = cms.Process("test")
1442 process.a = cms.EDAnalyzer("MyAnalyzer")
1445 process.r = cms.Sequence((process.a))
1448 process.p = cms.Path(process.a)
1451 process.p2 = cms.Path(process.r)
1454 process.schedule = cms.Schedule(*[ process.p2, process.p ])
1460 self.assertEqual(p.dumpPython().
replace(
'\n',
''),
'import FWCore.ParameterSet.Config as cmsprocess = cms.Process("test")process.a = cms.SecSource("MySecSource")')
1468 p.p =
Path(p.c+p.s+p.a)
1470 p.globalReplace(
"a",new)
1478 self.assertEqual(str(p.s),
'a+b')
1479 self.assertEqual(p.s.label_(),
's')
1480 path =
Path(p.c+p.s)
1481 self.assertEqual(str(path),
'c+a+b')
1482 p._validateSequence(path,
'p1')
1484 p2 =
Path(p.c+p.s*notInProcess)
1485 self.assertRaises(RuntimeError, p._validateSequence, p2,
'p2')
1495 self.assertRaises(ValueError, p.__setattr__,
"y", testseq)
1505 self.assertEqual(str(path),
'a+b+c')
1506 path =
Path(p.a*p.b+p.c)
1507 self.assertEqual(str(path),
'a+b+c')
1510 path =
Path(p.a+ p.b*p.c)
1511 self.assertEqual(str(path),
'a+b+c')
1512 path =
Path(p.a*(p.b+p.c))
1513 self.assertEqual(str(path),
'a+b+c')
1514 path =
Path(p.a*(p.b+~p.c))
1515 self.assertEqual(str(path),
'a+b+~c')
1517 self.assertRaises(TypeError,Path,p.es)
1528 p.path =
Path(p.a*p.b)
1529 lookuptable = {id(a): p.a, id(b): p.b}
1533 self.assertEqual(str(path),str(p.path))
1546 self.assertEqual(s[0],p.path1)
1547 self.assertEqual(s[1],p.path2)
1549 self.assert_(
'b' in p.schedule.moduleNames())
1550 self.assert_(hasattr(p,
'b'))
1551 self.assert_(hasattr(p,
'c'))
1552 self.assert_(hasattr(p,
'd'))
1553 self.assert_(hasattr(p,
'path1'))
1554 self.assert_(hasattr(p,
'path2'))
1555 self.assert_(hasattr(p,
'path3'))
1557 self.assert_(
'b' in p.schedule.moduleNames())
1558 self.assert_(hasattr(p,
'b'))
1559 self.assert_(
not hasattr(p,
'c'))
1560 self.assert_(
not hasattr(p,
'd'))
1561 self.assert_(hasattr(p,
'path1'))
1562 self.assert_(hasattr(p,
'path2'))
1563 self.assert_(
not hasattr(p,
'path3'))
1570 self.assertRaises(RuntimeError,
lambda : p.setSchedule_(s) )
1579 self.assert_(
'a' in s.moduleNames())
1580 self.assert_(
'b' in s.moduleNames())
1581 self.assert_(
'c' in s.moduleNames())
1585 self.assert_(
'a' in s.moduleNames())
1586 self.assert_(
'b' in s.moduleNames())
1587 self.assert_(
'c' in s.moduleNames())
1596 self.assert_(p.schedule
is None)
1599 self.assertEqual(pths[keys[0]],p.path1)
1600 self.assertEqual(pths[keys[1]],p.path2)
1602 self.assert_(hasattr(p,
'a'))
1603 self.assert_(hasattr(p,
'b'))
1604 self.assert_(
not hasattr(p,
'c'))
1605 self.assert_(hasattr(p,
'path1'))
1606 self.assert_(hasattr(p,
'path2'))
1615 self.assert_(p.schedule
is None)
1618 self.assertEqual(pths[keys[1]],p.path1)
1619 self.assertEqual(pths[keys[0]],p.path2)
1626 self.assertEqual(p.modu.a.value(),1)
1627 self.assertEqual(p.modu.b.value(),2)
1632 self.assert_(
not a.isModified())
1634 self.assert_(a.isModified())
1636 self.assertEqual(p.a.a1.value(), 1)
1640 self.assertEqual(p.a.a1.value(), 2)
1649 self.assertRaises(ValueError, EDProducer,
'C', ps1, ps2)
1650 self.assertRaises(ValueError, EDProducer,
'C', ps1, a=
int32(3))
1658 p.bars.foos =
'Foosball'
1659 self.assertEqual(p.bars.foos,
InputTag(
'Foosball'))
1660 p.p =
Path(p.foos*p.bars)
1662 p.add_(
Service(
"MessageLogger"))
1668 p.prefer(
"ForceSource")
1670 self.assertEqual(p.dumpConfig(),
1672 es_module juicer = JuicerProducer {
1674 es_source = ForceSource {
1676 es_prefer = ForceSource {
1678 es_prefer juicer = JuicerProducer {
1682 p.prefer(
"juicer",fooRcd=
vstring(
"Foo"))
1683 self.assertEqual(p.dumpConfig(),
1685 es_module juicer = JuicerProducer {
1687 es_source = ForceSource {
1689 es_prefer = ForceSource {
1691 es_prefer juicer = JuicerProducer {
1699 self.assertEqual(p.dumpPython(),
1700 """import FWCore.ParameterSet.Config as cms
1702 process = cms.Process("Test")
1704 process.juicer = cms.ESProducer("JuicerProducer")
1707 process.ForceSource = cms.ESSource("ForceSource")
1710 process.prefer("ForceSource")
1712 process.prefer("juicer",
1713 fooRcd = cms.vstring('Foo')
1730 self.assertEqual(process.m.p.i.value(), 4)
1740 subProcess.p =
Path(subProcess.a)
1741 subProcess.add_(
Service(
"Foo"))
1743 d = process.dumpPython()
1744 equalD =
"""import FWCore.ParameterSet.Config as cms
1746 process = cms.Process("Parent")
1748 parentProcess = process
1749 import FWCore.ParameterSet.Config as cms
1751 process = cms.Process("Child")
1753 process.a = cms.EDProducer("A")
1756 process.p = cms.Path(process.a)
1759 process.Foo = cms.Service("Foo")
1762 childProcess = process
1763 process = parentProcess
1764 process.subProcess = cms.SubProcess( process = childProcess, SelectEvents = cms.untracked.PSet(
1766 ), outputCommands = cms.untracked.vstring())
1768 equalD = equalD.replace(
"parentProcess",
"parentProcess"+str(
hash(process.subProcess)))
1769 self.assertEqual(d,equalD)
1771 process.subProcess.insertInto(p,
"dummy")
1772 self.assertEqual((
True,[
'a']),p.values[
"@sub_process"][1].values[
"process"][1].values[
'@all_modules'])
1773 self.assertEqual((
True,[
'p']),p.values[
"@sub_process"][1].values[
"process"][1].values[
'@paths'])
1774 self.assertEqual({
'@service_type':(
True,
'Foo')}, p.values[
"@sub_process"][1].values[
"process"][1].values[
"services"][1][0].values)
1784 proc.fillProcessDesc(p)
1785 self.assertEqual((
True,1),p.values[
"ref"][1].values[
"a"])
1786 self.assertEqual((
True,1),p.values[
"ref3"][1].values[
"a"])
1787 self.assertEqual((
True,1),p.values[
"ref2"][1].values[
"a"])
1788 self.assertEqual((
True,1),p.values[
"ref2"][1].values[
"b"][1].values[
"a"])
1789 self.assertEqual((
True,1),p.values[
"ref4"][1][0].values[
"a"])
1790 self.assertEqual((
True,1),p.values[
"ref4"][1][1].values[
"a"])
1800 self.assert_(p.schedule
is None)
1803 self.assertEqual(pths[keys[0]],p.path1)
1804 self.assertEqual(pths[keys[1]],p.path2)
1806 p.pset2 = untracked.PSet(parA =
string(
"pset2"))
1808 p.vpset2 = untracked.VPSet()
1810 self.assert_(hasattr(p,
'a'))
1811 self.assert_(hasattr(p,
'b'))
1812 self.assert_(
not hasattr(p,
'c'))
1813 self.assert_(
not hasattr(p,
'd'))
1814 self.assert_(
not hasattr(p,
's'))
1815 self.assert_(hasattr(p,
'path1'))
1816 self.assert_(hasattr(p,
'path2'))
1833 p.path3 =
Path(p.b+p.s2)
1834 p.path4 =
Path(p.b+p.s3)
1835 p.schedule =
Schedule(p.path1,p.path2,p.path3)
1838 self.assertEqual(pths[keys[0]],p.path1)
1839 self.assertEqual(pths[keys[1]],p.path2)
1841 self.assert_(hasattr(p,
'a'))
1842 self.assert_(hasattr(p,
'b'))
1843 self.assert_(
not hasattr(p,
'c'))
1844 self.assert_(
not hasattr(p,
'd'))
1845 self.assert_(
not hasattr(p,
'e'))
1846 self.assert_(
not hasattr(p,
's'))
1847 self.assert_(hasattr(p,
's2'))
1848 self.assert_(
not hasattr(p,
's3'))
1849 self.assert_(hasattr(p,
'path1'))
1850 self.assert_(hasattr(p,
'path2'))
1851 self.assert_(hasattr(p,
'path3'))
1852 self.assert_(
not hasattr(p,
'path4'))
1860 self.assert_(hasattr(p,
'a'))
1861 self.assert_(hasattr(p,
'b'))
1862 self.assert_(hasattr(p,
's'))
1863 self.assert_(hasattr(p,
'pth'))
1870 m1.toModify(p.a,_mod_fred)
1871 self.assertEqual(p.a.fred.value(),2)
1873 m1.toModify(p.b, wilma = 2)
1874 self.assertEqual(p.b.wilma.value(),2)
1879 m1.toModify(p.a,_mod_fred)
1881 m1.toModify(p.b, wilma = 2)
1882 self.assertEqual(p.a.fred.value(),1)
1883 self.assertEqual(p.b.wilma.value(),1)
1888 m1.toModify(p.a, fred =
int32(2))
1889 p.b = p.a.clone(wilma =
int32(3))
1890 self.assertEqual(p.a.fred.value(),2)
1891 self.assertEqual(p.a.wilma.value(),1)
1892 self.assertEqual(p.b.fred.value(),2)
1893 self.assertEqual(p.b.wilma.value(),3)
1897 class ProcModifierMod(
object):
1903 testMod = DummyMod()
1905 self.assert_(hasattr(p,
"a"))
1908 testProcMod = ProcModifierMod(m1,_rem_a)
1910 p.extend(testProcMod)
1911 self.assert_(
not hasattr(p,
"a"))
1916 testMod = DummyMod()
1918 m1.toModify(p.b, fred =
int32(3))
1920 testProcMod = ProcModifierMod(m1,_rem_a)
1921 p.extend(testProcMod)
1922 self.assert_(
not hasattr(p,
"a"))
1923 self.assertEqual(p.b.fred.value(),3)
def _dumpConfigUnnamedList
def testProcessDumpPython
def _dumpConfigOptionallyNamedList
def visit
Retrieve data from a perf suite output (sub) directory, only examines TimeSize at the moment...
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
def _sequencesInDependencyOrder
def __findFirstSequenceUsingModule
static std::string join(char **cmd)
def _applyNewProcessModifiers
def checkImportPermission
def testTypedParameterizable
How EventSelector::AcceptEvent() decides whether to accept an event for output otherwise it is excluding the probing of A single or multiple positive and the trigger will pass if any such matching triggers are PASS or EXCEPTION[A criterion thatmatches no triggers at all is detected and causes a throw.] A single negative with an expectation of appropriate bit checking in the decision and the trigger will pass if any such matching triggers are FAIL or EXCEPTION A wildcarded negative criterion that matches more than one trigger in the trigger list("!*","!HLTx*"if it matches 2 triggers or more) will accept the event if all the matching triggers are FAIL.It will reject the event if any of the triggers are PASS or EXCEPTION(this matches the behavior of"!*"before the partial wildcard feature was incorporated).Triggers which are in the READY state are completely ignored.(READY should never be returned since the trigger paths have been run