1 from __future__
import print_function
12 import FWCore.ParameterSet.Config
as cms
13 import FWCore.ParameterSet.Modules
as mod
14 import FWCore.ParameterSet.Types
as typ
21 def __init__(self, label, parent=None, parameters=None):
26 parent._configChildren += [self]
27 if parameters !=
None:
38 logging.debug(__name__ +
": __init__")
72 """ Read cms objects recursively from path """ 74 if isinstance(pth, (cms.Path, cms.EndPath, cms.Sequence, cms.SequencePlaceholder, cms.Source, mod._Module, cms.Service, cms.ESSource, cms.ESProducer, cms.ESPrefer, cms.PSet, cms.VPSet)):
76 entry._configChildren=[]
79 if not pth
in mother._configChildren:
80 mother._configChildren += [pth]
86 if isinstance(pth, list):
89 if hasattr(sqt,
"_SequenceCollection"):
91 if isinstance(pth, (sqt._ModuleSequenceType)):
92 if isinstance(pth._seq, (sqt._SequenceCollection)):
93 for o
in pth._seq._collection:
97 elif isinstance(pth, sqt._UnarySequenceOperator):
103 if isinstance(o, sqt._Sequenceable):
107 """ Read connection between objects """ 109 checkedObjects = set()
115 compareObjectList+=[(obj,o)
for o
in self.
_allObjects]
116 compareObjectList+=[(o,obj)
for o
in self.
_allObjects]
118 compareObjectList=[(o1,o2)
for o1
in objects
for o2
in objects]
119 for connection
in compareObjectList:
123 if (
not connection
in checkedObjects)
and (connection
not in self.
_connections):
124 checkedObjects.add(connection)
125 for key, value
in self.
inputTags(connection[1]):
132 if module == self.
label(connection[0]):
152 result.sort(
lambda x, y: cmp(self.
label(x).lower(), self.
label(y).lower()))
156 """ Open config file and read it. 158 logging.debug(__name__ +
": open")
161 global imported_configs
166 for i
in imported_configs.iterkeys():
167 if i
in sys.modules.keys():
169 sys.path.insert(0, os.path.dirname(self.
_filename))
170 common_imports = sys.modules.copy()
177 imported_configs = sys.modules.copy() 178 for i
in common_imports.iterkeys():
179 del imported_configs[i]
182 for j
in six.itervalues(imported_configs):
185 if entry[0] !=
"_" and entry !=
"cms":
187 for k
in six.itervalues(imported_configs):
188 if hasattr(k, entry):
190 if len(setk) < len(setj)
and setk < setj:
194 if hasattr(j,
"__file__"):
196 file_dict[entry] = filen
208 o=getattr(self.
_file, entry)
209 if entry[0] !=
"_" and entry !=
"cms" and hasattr(o,
"label_"):
210 getattr(self.
_file, entry).setLabel(entry)
211 text = os.path.splitext(os.path.basename(file_dict[o.label_()]))[0]
220 for obj
in reversed(self.
children(object)):
228 self._file.process=process
230 parameters = {
"name": self.
process().process}
231 process_folder =
ConfigFolder(
"process",
None, parameters)
237 folder_list += [(
"source", [self.
process().source])]
238 if self.
process().schedule !=
None:
239 folder_list += [(
"paths", self.
process().schedule)]
241 folder_list += [(
"paths", six.itervalues(self.
process().paths))]
242 folder_list += [(
"endpaths", six.itervalues(self.
process().endpaths))]
247 folder_list += [(
"essources", self.
_sort_list(self.
process().es_sources.values()))]
248 folder_list += [(
"esproducers", self.
_sort_list(self.
process().es_producers.values()))]
249 folder_list += [(
"esprefers", self.
_sort_list(self.
process().es_prefers.values()))]
251 for foldername, entry
in folder_list:
254 folders[foldername]=folder
258 print(
"Creating schedule...", end=
' ')
261 self._scheduledObjects.reverse()
264 if str(obj)
in names:
266 scheduled_folder =
ConfigFolder(
"scheduled", folders[
"paths"])
268 folders[
"paths"]._configChildren.remove(scheduled_folder)
269 folders[
"paths"]._configChildren.insert(0,scheduled_folder)
276 if hasattr(self.
_file,
"process"):
277 return self._file.process
282 foundHeaderPart1 =
False 283 foundHeaderPart2 =
False 285 search_paths=[os.path.abspath(os.path.dirname(self.
_filename))]
286 while theFile
and not (foundHeaderPart1
and foundHeaderPart2)
and lines > 0:
287 line = theFile.readline()
289 if "Generated by ConfigEditor" in line:
290 foundHeaderPart1 =
True 291 splitline = line.split(
"'")
292 if foundHeaderPart1
and len(splitline) == 5
and splitline[0] ==
"sys.path.append(os.path.abspath(os.path.expandvars(os.path.join(" and splitline[4] ==
"))))\n":
293 search_paths+=[os.path.abspath(os.path.expandvars(os.path.join(splitline[1],splitline[3])))]
294 splitline = line.split()
295 if foundHeaderPart1
and len(splitline) == 4
and splitline[0] ==
"from" and splitline[2] ==
"import":
296 for search_path
in search_paths:
297 if os.path.exists(os.path.join(search_path,splitline[1]+
".py")):
298 self.
_filename = os.path.join(search_path,splitline[1]+
".py")
301 foundHeaderPart2 =
True 305 """ dump python configuration """ 306 logging.debug(__name__ +
": dumpPython")
313 """ configuration history """ 314 logging.debug(__name__ +
": history")
321 """ Get label of an object """ 323 if hasattr(object,
"label_")
and (
not hasattr(object,
"hasLabel_")
or object.hasLabel_()):
324 text =
str(object.label_())
328 if hasattr(object,
"_name"):
329 text =
str(object._name)
331 if hasattr(object,
"type_"):
332 text =
str(object.type_())
338 """ Get children of an object """ 339 if hasattr(object,
"_configChildren"):
340 return tuple(object._configChildren)
345 return isinstance(object, (ConfigFolder, list, cms.Path, cms.EndPath, cms.Sequence))
360 """ Get motherRelations of an object """ 361 if object
in self._motherRelationsDict.keys():
370 """ Get daughterRelations of an object """ 371 if object
in self._daughterRelationsDict.keys():
380 """ Get type of an object """ 381 return object.__class__.__name__
384 """ Get classname of an object """ 386 if hasattr(object,
"type_"):
387 text = object.type_()
391 """ Get full filename """ 395 if text ==
"" or text.find(
"FWCore/ParameterSet") >= 0
or text.find(
"/build/") >= 0:
396 if self.
label(object)
in file_dict:
397 text = file_dict[self.
label(object)]
400 root = os.path.splitext(text)[0]
406 """ Get linenumber """ 408 if hasattr(object,
"_filename"):
409 if object._filename.find(
"FWCore/ParameterSet") < 0
and object._filename.find(
"ConfigEditor") < 0:
410 if hasattr(object,
"_lineNumber"):
411 text =
str(object._lineNumber)
416 text = os.path.splitext(os.path.basename(self.
fullFilename(object)))[0]
420 match_compiled = re.match(
r'(?:^|.*?/)CMSSW[0-9_]*/python/((?:\w*/)*\w*)\.py$',self.
fullFilename(object))
422 return match_compiled.group(1).
replace(
'/',
'.')
424 match_norm = re.match(
r'(?:^|.*?/)(\w*)/(\w*)/(?:test|python)/((?:\w*/)*)(\w*)\.py$',self.
fullFilename(object))
426 return '%s.%s.%s%s' % (match_norm.group(1),match_norm.group(2),match_norm.group(3).
replace(
'/',
'.'),match_norm.group(4))
430 match_compiled = re.match(
r'(?:^|.*?/)CMSSW[0-9_]*/python/((?:\w*/){2})((?:\w*/)*)(\w*\.py)$',self.
fullFilename(object))
432 return '%spython/%s%s' % (match_compiled.group(1),match_compiled.group(2),match_compiled.group(3))
433 match_norm = re.match(
r'(?:^|.*?/)(\w*/\w*/(?:test|python)/(?:\w*/)*\w*\.py)$',self.
fullFilename(object))
435 return match_norm.group(1)
439 """ Get Package of an object file """ 442 if len(shortdirname) > 1:
443 text = shortdirname[1]
447 """ Get parameters of an object """ 449 if hasattr(object,
"parameters_"):
450 this_parameters = object.parameters_().
items()
451 elif hasattr(object,
"_seq"):
452 if hasattr(object._seq,
"dumpSequencePython"):
453 this_parameters = [(
'sequence', object._seq.dumpSequencePython())]
455 this_parameters = [(
'sequence',
'WARNING: object was removed from a sequence.')]
456 if hasattr(object,
"tarlabel_"):
457 this_parameters += [(
'tarlabel', object.tarlabel_())]
458 return this_parameters
461 """ Add alls inputtags of value to a list """ 462 if isinstance(value, cms.VInputTag):
463 for i
in range(len(value)):
464 if isinstance(value[i], str):
465 self.
_addInputTag(cms.InputTag(value[i]), this_key+
"["+
str(i)+
"]", this_inputtags)
468 elif isinstance(value, list):
471 if hasattr(value,
"parameters_"):
473 if isinstance(value, cms.InputTag):
474 pythonValue = value.value()
475 this_inputtags += [(
str(this_key), value.value())]
478 """ Make list of inputtags from parameter dict """ 480 for key, value
in this_parameters:
486 return this_inputtags
489 """ Make list of inputtags from parameter dict """ 491 v = self._inputTagsDict.get(object)
500 """ Get list of all config objects that are used as input """ 501 if not object
in self._usesDict.keys():
503 for key, value
in self.
inputTags(object):
506 if module
not in uses:
515 """ Make list of all mother sequences """ 516 if not object
in self._foundInDict.keys():
519 for daughter
in self.
children(entry):
520 if self.
label(object) == self.
label(daughter)
and len(self.
children(entry)) > 0
and not self.
label(entry)
in foundin:
521 foundin += [self.
label(entry)]
529 """ Find config objects that use this as input """ 530 if not object
in self._usedByDict.keys():
533 for uses
in self.
uses(entry):
534 if self.
label(object) == uses
and not self.
label(entry)
in usedby:
535 usedby += [self.
label(entry)]
545 if name !=
"" and not isinstance(object, typ.PSet):
547 partyp=
str(type(object)).
split(
"'")[1].
replace(
"FWCore.ParameterSet.Types",
"cms")
548 if isinstance(object, cms.InputTag):
549 inputtagValue=object.pythonValue()
550 for i
in range(3-len(inputtagValue.split(
","))):
551 inputtagValue+=
', ""' 552 properties += [(
"String", name,
"cms.InputTag("+inputtagValue+
")", partyp, readonly)]
553 elif isinstance(object, cms.bool):
554 properties += [(
"Boolean", name, object.value(), partyp, readonly)]
555 elif isinstance(object, (cms.int32, cms.uint32, cms.int64, cms.uint64)):
556 properties += [(
"Integer", name, object.value(), partyp, readonly)]
557 elif isinstance(object, cms.double):
558 properties += [(
"Double", name, object.value(), partyp, readonly)]
559 elif hasattr(object,
"pythonValue"):
560 properties += [(
"String", name,
str(object.pythonValue()).
strip(
"\"'"), partyp, readonly)]
561 elif hasattr(object,
"value"):
562 properties += [(
"MultilineString", name,
str(object.value()), partyp, readonly)]
564 properties += [(
"MultilineString", name,
str(object), partyp, readonly)]
568 if isinstance(object, ConfigFolder):
572 params.sort(
lambda x, y: cmp(x[0].lower(), y[0].lower()))
573 for key, value
in params:
582 """ Make list of all properties """ 585 properties += [(
"Category",
"Object info",
"")]
586 if self.
label(object) !=
"":
587 properties += [(
"String",
"label", self.
label(object),
None,
True)]
588 if self.
type(object) !=
"":
589 text = self.
type(object)
591 text +=
" <" + self.
classname(object) +
">" 592 properties += [(
"String",
"type", text,
None,
True)]
597 properties += [(
"String",
"file", text,
None,
True)]
599 properties += [(
"String",
"package", self.
package(object),
None,
True)]
601 properties += [(
"String",
"full filename", self.
fullFilename(object),
None,
True)]
605 for entry
in foundIn:
609 properties += [(
"String",
"in sequence", text,
"This module/sequence is used the listed sequences",
True)]
610 uses=self.
uses(object)
611 usedBy=self.
usedBy(object)
612 if len(uses) + len(usedBy) > 0:
613 properties += [(
"Category",
"Connections",
"")]
620 properties += [(
"MultilineString",
"uses", text,
"This module/sequence depends on the output of the listes modules/seuquences",
True)]
628 properties += [(
"MultilineString",
"used by", text,
"The listed modules/sequences depend on the output of this module/sequence",
True)]
630 properties += [(
"Category",
"Parameters",
"")]
632 return tuple(properties)
635 """ Sets a property with given name to value. 637 if hasattr(object,
"_seq")
and name==
"sequence":
638 return "Modification of sequences not supported yet." 642 if isinstance(value,str)
and\
643 not value[0]==
"[" and\
644 not value[0:4]==
"cms.":
645 exec(
"object." + name +
"='''" + value +
"'''")
647 exec(
"object." + name +
"=" +
str(value))
648 except Exception
as e:
649 error=
"Cannot set parameter "+name+
" (see logfile for details):\n"+
str(e)
650 logging.warning(__name__ +
": setProperty: Cannot set parameter "+name+
": "+
exception_traceback())
659 for key, value
in self.
inputTags(object):
663 product = elements[1]
667 process = elements[2]
670 if not module
in allLabels:
671 if not (
"*",module,product,process)
in content:
672 content += [(
"*",module,product,process)]
673 if "*_"+module+
"_"+product+
"_"+process
in content_objects.keys():
674 content_objects[
"*_"+module+
"_"+product+
"_"+process]+=
","+self.
label(object)
676 content_objects[
"*_"+module+
"_"+product+
"_"+process]=self.
label(object)
677 return (content,content_objects)
681 if self.
type(object)
in [
"EDProducer",
"EDFilter",
"EDAnalyzer"]]
685 inputModules = [object
for object
in self.
_allObjects\
686 if self.
type(object) ==
"Source"]
687 if len(inputModules) > 0
and hasattr(inputModules[0],
"inputCommands"):
688 return inputModules[0].inputCommands
693 outputModules = [object
for object
in self.
_allObjects\
694 if self.
type(object) ==
"OutputModule"]
695 if len(outputModules) > 0
and hasattr(outputModules[0],
"outputCommands"):
696 return outputModules[0].outputCommands
702 if len(outputCommands)>0
and outputCommands[0]!=
"keep *":
703 for object
in content:
706 for object
in content:
708 for o
in outputCommands:
710 command, filter = [ x
for x
in o.split(
" ")
if x]
711 if len(filter.split(
"_")) > 1:
712 module = filter.split(
"_")[1]
713 product = filter.split(
"_")[2]
714 process = filter.split(
"_")[3]
719 for object
in content:
721 match = module.strip(
"*")
in object[1]
723 match = module == object[1]
725 match = match
and product.strip(
"*")
in object[2]
727 match = match
and product == object[2]
729 match = match
and process.strip(
"*")
in object[3]
731 match = match
and process == object[3]
733 keep[object] = command ==
"keep" 734 return [object
for object
in content
if keep[object]]
def nonSequenceChildren(self, object)
def topLevelObjects(self)
def parameters(self, object)
def _readHeaderInfo(self)
def motherRelations(self, object)
def children(self, object)
def exception_traceback()
def replace(string, replacements)
def package(self, object)
S & print(S &os, JobReport::InputFile const &f)
def _addInputTag(self, value, this_key, this_inputtags)
def fullFilename(self, object)
def lineNumber(self, object)
def open(self, filename=None)
def classname(self, object)
def pypackage(self, object)
def foundIn(self, object)
def isReplaceConfig(self)
def _readInputTagsRecursive(self, this_parameters, start_key="")
def daughterRelations(self, object)
def cancelOperations(self)
def setProperty(self, object, name, value, categoryName)
def _scheduleRecursive(self, object)
def setIsReplaceConfig(self)
def __init__(self, label, parent=None, parameters=None)
static std::string join(char **cmd)
def inputTags(self, object)
def readConnections(self, objects, toNeighbors=False)
def recursePSetProperties(self, name, object, readonly=None)
def properties(self, object)
def outputEventContent(self)
def _readRecursive(self, mother, pth)
def setProcess(self, process)
def inputEventContent(self)
def applyCommands(self, content, outputCommands)
def allChildren(self, object)
def isContainer(self, object)
def filename(self, object)