3 from __future__
import print_function
4 __version__ =
"$Revision: 1.19 $"
5 __source__ =
"$Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v $"
7 import FWCore.ParameterSet.Config
as cms
8 from FWCore.ParameterSet.Modules
import _Module
11 from FWCore.ParameterSet.MassReplace
import massReplaceInputTag
as MassReplaceInputTag
17 from subprocess
import Popen,PIPE
18 import FWCore.ParameterSet.DictTypes
as DictTypes
24 defaultOptions.datamix =
'DataOnSim'
25 defaultOptions.isMC=
False
26 defaultOptions.isData=
True
27 defaultOptions.step=
''
28 defaultOptions.pileup=
'NoPileUp'
29 defaultOptions.pileup_input =
None
30 defaultOptions.pileup_dasoption =
''
31 defaultOptions.geometry =
'SimDB'
32 defaultOptions.geometryExtendedOptions = [
'ExtendedGFlash',
'Extended',
'NoCastor']
33 defaultOptions.magField =
''
34 defaultOptions.conditions =
None
35 defaultOptions.scenarioOptions=[
'pp',
'cosmics',
'nocoll',
'HeavyIons']
36 defaultOptions.harvesting=
'AtRunEnd'
37 defaultOptions.gflash =
False
38 defaultOptions.number = -1
39 defaultOptions.number_out =
None
40 defaultOptions.arguments =
""
41 defaultOptions.name =
"NO NAME GIVEN"
42 defaultOptions.evt_type =
""
43 defaultOptions.filein =
""
44 defaultOptions.dasquery=
""
45 defaultOptions.dasoption=
""
46 defaultOptions.secondfilein =
""
47 defaultOptions.customisation_file = []
48 defaultOptions.customisation_file_unsch = []
49 defaultOptions.customise_commands =
""
50 defaultOptions.inline_custom=
False
51 defaultOptions.particleTable =
'pythiapdt'
52 defaultOptions.particleTableList = [
'pythiapdt',
'pdt']
53 defaultOptions.dirin =
''
54 defaultOptions.dirout =
''
55 defaultOptions.filetype =
'EDM'
56 defaultOptions.fileout =
'output.root'
57 defaultOptions.filtername =
''
58 defaultOptions.lazy_download =
False
59 defaultOptions.custom_conditions =
''
60 defaultOptions.hltProcess =
''
61 defaultOptions.eventcontent =
None
62 defaultOptions.datatier =
None
63 defaultOptions.inlineEventContent =
True
64 defaultOptions.inlineObjets =
''
65 defaultOptions.hideGen=
False
66 from Configuration.StandardSequences.VtxSmeared
import VtxSmearedDefaultKey,VtxSmearedHIDefaultKey
67 defaultOptions.beamspot=
None
68 defaultOptions.outputDefinition =
''
69 defaultOptions.inputCommands =
None
70 defaultOptions.outputCommands =
None
71 defaultOptions.inputEventContent =
''
72 defaultOptions.dropDescendant =
False
73 defaultOptions.relval =
None
74 defaultOptions.profile =
None
75 defaultOptions.isRepacked =
False
76 defaultOptions.restoreRNDSeeds =
False
77 defaultOptions.donotDropOnInput =
''
78 defaultOptions.python_filename =
''
79 defaultOptions.io=
None
80 defaultOptions.lumiToProcess=
None
81 defaultOptions.fast=
False
82 defaultOptions.runsAndWeightsForMC =
None
83 defaultOptions.runsScenarioForMC =
None
84 defaultOptions.runsAndWeightsForMCIntegerWeights =
None
85 defaultOptions.runsScenarioForMCIntegerWeights =
None
86 defaultOptions.runUnscheduled =
False
87 defaultOptions.timeoutOutput =
False
88 defaultOptions.nThreads =
'1'
89 defaultOptions.nStreams =
'0'
90 defaultOptions.nConcurrentLumis =
'0'
91 defaultOptions.nConcurrentIOVs =
'1'
95 theObject = getattr(process,name)
96 if isinstance(theObject,cms.Path)
or isinstance(theObject,cms.EndPath)
or isinstance(theObject,cms.Sequence):
97 return "process."+name+
" = " + theObject.dumpPython()
98 elif isinstance(theObject,_Module)
or isinstance(theObject,cms.ESProducer):
99 return "process."+name+
" = " + theObject.dumpPython()+
"\n"
101 return "process."+name+
" = " + theObject.dumpPython()+
"\n"
104 import FWCore.ParameterSet.Config
as cms
107 for line
in open(fileName,
'r'):
108 if line.count(
".root")>=2:
110 entries=line.replace(
"\n",
"").
split()
111 prim.append(entries[0])
112 sec.append(entries[1])
113 elif (line.find(
".root")!=-1):
114 entry=line.replace(
"\n",
"")
117 prim = sorted(list(set(prim)))
118 sec = sorted(list(set(sec)))
120 if not hasattr(s,
"fileNames"):
121 s.fileNames=cms.untracked.vstring(prim)
123 s.fileNames.extend(prim)
125 if not hasattr(s,
"secondaryFileNames"):
126 s.secondaryFileNames=cms.untracked.vstring(sec)
128 s.secondaryFileNames.extend(sec)
129 print(
"found files: ",prim)
131 raise Exception(
"There are not files in input from the file list")
133 print(
"found parent files:",sec)
138 import FWCore.ParameterSet.Config
as cms
141 print(
"the query is",query)
144 while eC!=0
and count<3:
146 print(
'Sleeping, then retrying DAS')
148 p = Popen(
'dasgoclient %s --query "%s"'%(option,query), stdout=PIPE,shell=
True, universal_newlines=
True)
150 tupleP = os.waitpid(p.pid, 0)
154 print(
"DAS succeeded after",count,
"attempts",eC)
156 print(
"DAS failed 3 times- I give up")
157 for line
in pipe.split(
'\n'):
158 if line.count(
".root")>=2:
160 entries=line.replace(
"\n",
"").
split()
161 prim.append(entries[0])
162 sec.append(entries[1])
163 elif (line.find(
".root")!=-1):
164 entry=line.replace(
"\n",
"")
167 prim = sorted(list(set(prim)))
168 sec = sorted(list(set(sec)))
170 if not hasattr(s,
"fileNames"):
171 s.fileNames=cms.untracked.vstring(prim)
173 s.fileNames.extend(prim)
175 if not hasattr(s,
"secondaryFileNames"):
176 s.secondaryFileNames=cms.untracked.vstring(sec)
178 s.secondaryFileNames.extend(sec)
179 print(
"found files: ",prim)
181 print(
"found parent files:",sec)
184 def anyOf(listOfKeys,dict,opt=None):
193 raise Exception(
"any of "+
','.
join(listOfKeys)+
" are mandatory entries of --output options")
196 """The main building routines """
198 def __init__(self, options, process = None, with_output = False, with_input = False ):
199 """options taken from old cmsDriver and optparse """
201 options.outfile_name = options.dirout+options.fileout
205 if self.
_options.isData
and options.isMC:
206 raise Exception(
"ERROR: You may specify only --data or --mc, not both")
212 if (hasattr(self.
_options,
"outputDefinition")
and \
213 self.
_options.outputDefinition !=
'' and \
214 any(
anyOf([
't',
'tier',
'dataTier'],outdic) ==
'DQMIO' for outdic
in eval(self.
_options.outputDefinition)))
or \
215 (hasattr(self.
_options,
"datatier")
and \
218 print(
"removing ENDJOB from steps since not compatible with DQMIO dataTier")
224 stepList = [re.sub(
r'^prepare_',
'', methodName)
for methodName
in ConfigBuilder.__dict__
if methodName.startswith(
'prepare_')]
227 for step
in self.
_options.step.split(
","):
228 if step==
'':
continue
229 stepParts = step.split(
":")
230 stepName = stepParts[0]
231 if stepName
not in stepList
and not stepName.startswith(
're'):
232 raise ValueError(
"Step "+stepName+
" unknown")
233 if len(stepParts)==1:
235 elif len(stepParts)==2:
237 elif len(stepParts)==3:
238 self.
stepMap[stepName]=(stepParts[2].
split(
'+'),stepParts[1])
240 raise ValueError(
"Step definition "+step+
" invalid")
248 if hasattr(self.
_options,
"no_output_flag")
and self.
_options.no_output_flag:
275 Function to add the igprof profile service so that you can dump in the middle
278 profileOpts = self.
_options.profile.split(
':')
280 profilerInterval = 100
281 profilerFormat =
None
282 profilerJobFormat =
None
288 startEvent = profileOpts.pop(0)
289 if not startEvent.isdigit():
290 raise Exception(
"%s is not a number" % startEvent)
291 profilerStart =
int(startEvent)
293 eventInterval = profileOpts.pop(0)
294 if not eventInterval.isdigit():
295 raise Exception(
"%s is not a number" % eventInterval)
296 profilerInterval =
int(eventInterval)
298 profilerFormat = profileOpts.pop(0)
301 if not profilerFormat:
302 profilerFormat =
"%s___%s___%%I.gz" % (
303 self.
_options.evt_type.replace(
"_cfi",
""),
309 if not profilerJobFormat
and profilerFormat.endswith(
".gz"):
310 profilerJobFormat = profilerFormat.replace(
".gz",
"_EndOfJob.gz")
311 elif not profilerJobFormat:
312 profilerJobFormat = profilerFormat +
"_EndOfJob.gz"
314 return (profilerStart,profilerInterval,profilerFormat,profilerJobFormat)
317 includeFile = includeFile.replace(
'/',
'.')
319 return sys.modules[includeFile]
322 """helper routine to load am memorize imports"""
325 includeFile = includeFile.replace(
'/',
'.')
328 return sys.modules[includeFile]
331 """helper routine to remember replace statements"""
333 if not command.strip().startswith(
"#"):
336 exec(re.sub(
r"([^a-zA-Z_0-9]|^)(process)([^a-zA-Z_0-9])",
r"\1self.process\3",command))
341 self.
process.options.Rethrow = [
'ProductNotFound']
342 self.
process.options.fileMode =
'FULLMERGE'
347 self.
process.AdaptorConfig = cms.Service(
"AdaptorConfig",
348 stats = cms.untracked.bool(
True),
349 enable = cms.untracked.bool(
True),
350 cacheHint = cms.untracked.string(
"lazy-download"),
351 readHint = cms.untracked.string(
"read-ahead-buffered")
360 self.
process.IgProfService = cms.Service(
"IgProfService",
361 reportFirstEvent = cms.untracked.int32(start),
362 reportEventInterval = cms.untracked.int32(interval),
363 reportToFileAtPostEvent = cms.untracked.string(
"| gzip -c > %s"%(eventFormat)),
364 reportToFileAtPostEndJob = cms.untracked.string(
"| gzip -c > %s"%(jobFormat)))
368 """Here we decide how many evts will be processed"""
375 """Here the source is built. Priority: file, generator"""
378 def filesFromOption(self):
379 for entry
in self.
_options.filein.split(
','):
381 if entry.startswith(
"filelist:"):
383 elif entry.startswith(
"dbs:")
or entry.startswith(
"das:"):
388 if not hasattr(self.
process.source,
"secondaryFileNames"):
389 raise Exception(
"--secondfilein not compatible with "+self.
_options.filetype+
"input type")
390 for entry
in self.
_options.secondfilein.split(
','):
392 if entry.startswith(
"filelist:"):
394 elif entry.startswith(
"dbs:")
or entry.startswith(
"das:"):
397 self.
process.source.secondaryFileNames.append(self.
_options.dirin+entry)
401 self.
process.source=cms.Source(
"PoolSource",
402 fileNames = cms.untracked.vstring(),
403 secondaryFileNames= cms.untracked.vstring())
404 filesFromOption(self)
405 elif self.
_options.filetype ==
"DAT":
406 self.
process.source=cms.Source(
"NewEventStreamFileReader",fileNames = cms.untracked.vstring())
407 filesFromOption(self)
408 elif self.
_options.filetype ==
"LHE":
409 self.
process.source=cms.Source(
"LHESource", fileNames = cms.untracked.vstring())
410 if self.
_options.filein.startswith(
"lhe:"):
412 args=self.
_options.filein.split(
':')
414 print(
'LHE input from article ',article)
415 location=
'/store/lhe/'
417 textOfFiles=os.popen(
'cmsLHEtoEOSManager.py -l '+article)
418 for line
in textOfFiles:
419 for fileName
in [x
for x
in line.split()
if '.lhe' in x]:
420 self.
process.source.fileNames.append(location+article+
'/'+fileName)
423 print(
'Issue to load LHE files, please check and try again.')
426 if len(self.
process.source.fileNames)==0:
427 print(
'Issue with empty filename, but can pass line check')
430 self.
process.source.skipEvents = cms.untracked.uint32(
int(args[2]))
432 filesFromOption(self)
434 elif self.
_options.filetype ==
"DQM":
435 self.
process.source=cms.Source(
"DQMRootSource",
436 fileNames = cms.untracked.vstring())
437 filesFromOption(self)
439 elif self.
_options.filetype ==
"DQMDAQ":
441 self.
process.source=cms.Source(
"DQMStreamerReader")
445 self.
process.source.processingMode = cms.untracked.string(
"RunsAndLumis")
448 self.
process.source=cms.Source(
"PoolSource", fileNames = cms.untracked.vstring(),secondaryFileNames = cms.untracked.vstring())
452 self.
process.source.processingMode = cms.untracked.string(
"RunsAndLumis")
457 self.
_options.inputCommands+=
',drop LHEXMLStringProduct_*_*_*,'
459 self.
_options.inputCommands=
'keep *, drop LHEXMLStringProduct_*_*_*,'
462 if not hasattr(self.
process.source,
'inputCommands'): self.
process.source.inputCommands=cms.untracked.vstring()
463 for command
in self.
_options.inputCommands.split(
','):
465 command = command.strip()
466 if command==
'':
continue
467 self.
process.source.inputCommands.append(command)
468 if not self.
_options.dropDescendant:
469 self.
process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(
False)
472 import FWCore.PythonUtilities.LumiList
as LumiList
476 if self.
process.source
is None:
477 self.
process.source=cms.Source(
"EmptySource")
483 raise Exception(
"options --runsAndWeightsForMC and --runsScenarioForMC are only valid for MC")
484 if self.
_options.runsAndWeightsForMC:
487 from Configuration.StandardSequences.RunsAndWeights
import RunsAndWeights
488 if isinstance(RunsAndWeights[self.
_options.runsScenarioForMC], str):
489 __import__(RunsAndWeights[self.
_options.runsScenarioForMC])
490 self.
runsAndWeights = sys.modules[RunsAndWeights[self.
_options.runsScenarioForMC]].runProbabilityDistribution
495 import SimGeneral.Configuration.ThrowAndSetRandomRun
as ThrowAndSetRandomRun
502 if self.
_options.runsAndWeightsForMCIntegerWeights
or self.
_options.runsScenarioForMCIntegerWeights:
504 raise Exception(
"options --runsAndWeightsForMCIntegerWeights and --runsScenarioForMCIntegerWeights are only valid for MC")
505 if self.
_options.runsAndWeightsForMCIntegerWeights:
508 from Configuration.StandardSequences.RunsAndWeights
import RunsAndWeights
509 if isinstance(RunsAndWeights[self.
_options.runsScenarioForMCIntegerWeights], str):
510 __import__(RunsAndWeights[self.
_options.runsScenarioForMCIntegerWeights])
511 self.
runsAndWeightsInt = sys.modules[RunsAndWeights[self.
_options.runsScenarioForMCIntegerWeights]].runProbabilityDistribution
517 raise Exception(
"--relval option required when using --runsAndWeightsInt")
519 from SimGeneral.Configuration.LumiToRun
import lumi_to_run
520 total_events, events_per_job = self.
_options.relval.split(
',')
522 self.
additionalCommands.
append(
"process.source.firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID(*[cms.LuminosityBlockID(x,y) for x,y in " +
str(lumi_to_run_mapping) +
"])")
527 """ Add output module to the process """
531 print(
"--datatier & --eventcontent options ignored")
534 outList = eval(self.
_options.outputDefinition)
535 for (id,outDefDict)
in enumerate(outList):
536 outDefDictStr=outDefDict.__str__()
537 if not isinstance(outDefDict,dict):
538 raise Exception(
"--output needs to be passed a list of dict"+self.
_options.outputDefinition+
" is invalid")
540 theTier=
anyOf([
't',
'tier',
'dataTier'],outDefDict)
543 theStreamType=
anyOf([
'e',
'ec',
'eventContent',
'streamType'],outDefDict,theTier)
544 theFilterName=
anyOf([
'f',
'ftN',
'filterName'],outDefDict,
'')
545 theSelectEvent=
anyOf([
's',
'sE',
'selectEvents'],outDefDict,
'')
546 theModuleLabel=
anyOf([
'l',
'mL',
'moduleLabel'],outDefDict,
'')
547 theExtraOutputCommands=
anyOf([
'o',
'oC',
'outputCommands'],outDefDict,
'')
549 if not theModuleLabel:
550 tryNames=[theStreamType.replace(theTier.replace(
'-',
''),
'')+theTier.replace(
'-',
'')+
'output',
551 theStreamType.replace(theTier.replace(
'-',
''),
'')+theTier.replace(
'-',
'')+theFilterName+
'output',
552 theStreamType.replace(theTier.replace(
'-',
''),
'')+theTier.replace(
'-',
'')+theFilterName+theSelectEvent.split(
',')[0].
replace(
':',
'for').
replace(
' ',
'')+
'output'
554 for name
in tryNames:
555 if not hasattr(self.
process,name):
558 if not theModuleLabel:
559 raise Exception(
"cannot find a module label for specification: "+outDefDictStr)
561 defaultFileName=self.
_options.outfile_name
563 defaultFileName=self.
_options.outfile_name.replace(
'.root',
'_in'+theTier+
'.root')
565 theFileName=self.
_options.dirout+
anyOf([
'fn',
'fileName'],outDefDict,defaultFileName)
566 if not theFileName.endswith(
'.root'):
570 raise Exception(
"unused keys from --output options: "+
','.
join(outDefDict.keys()))
571 if theStreamType==
'DQMIO': theStreamType=
'DQM'
572 if theStreamType==
'ALL':
573 theEventContent = cms.PSet(outputCommands = cms.untracked.vstring(
'keep *'))
575 theEventContent = getattr(self.
process, theStreamType+
"EventContent")
579 if theStreamType==
'ALCARECO' and not theFilterName:
580 theFilterName=
'StreamALCACombined'
583 CppType=
'PoolOutputModule'
585 CppType=
'TimeoutPoolOutputModule'
586 if theStreamType==
'DQM' and theTier==
'DQMIO': CppType=
'DQMRootOutputModule'
587 output = cms.OutputModule(CppType,
588 theEventContent.clone(),
589 fileName = cms.untracked.string(theFileName),
590 dataset = cms.untracked.PSet(
591 dataTier = cms.untracked.string(theTier),
592 filterName = cms.untracked.string(theFilterName))
594 if not theSelectEvent
and hasattr(self.
process,
'generation_step')
and theStreamType!=
'LHE':
595 output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(
'generation_step'))
596 if not theSelectEvent
and hasattr(self.
process,
'filtering_step'):
597 output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(
'filtering_step'))
599 output.SelectEvents =cms.untracked.PSet(SelectEvents = cms.vstring(theSelectEvent))
602 if not hasattr(output,
'SelectEvents'):
603 output.SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring())
605 output.SelectEvents.SelectEvents.extend(getattr(self.
process,
'OutALCARECO'+alca).SelectEvents.SelectEvents)
608 if hasattr(self.
process,theModuleLabel):
609 raise Exception(
"the current process already has a module "+theModuleLabel+
" defined")
611 setattr(self.
process,theModuleLabel,output)
612 outputModule=getattr(self.
process,theModuleLabel)
613 setattr(self.
process,theModuleLabel+
'_step',cms.EndPath(outputModule))
614 path=getattr(self.
process,theModuleLabel+
'_step')
617 if not self.
_options.inlineEventContent
and hasattr(self.
process,theStreamType+
"EventContent"):
618 def doNotInlineEventContent(instance,label = "cms.untracked.vstring(process.
"+theStreamType+"EventContent.outputCommands)
"): return label
619 outputModule.outputCommands.__dict__[
"dumpPython"] = doNotInlineEventContent
620 if theExtraOutputCommands:
621 if not isinstance(theExtraOutputCommands,list):
622 raise Exception(
"extra ouput command in --option must be a list of strings")
623 if hasattr(self.
process,theStreamType+
"EventContent"):
624 self.
executeAndRemember(
'process.%s.outputCommands.extend(%s)'%(theModuleLabel,theExtraOutputCommands))
626 outputModule.outputCommands.extend(theExtraOutputCommands)
628 result+=
"\nprocess."+theModuleLabel+
" = "+outputModule.dumpPython()
633 streamTypes=self.
_options.eventcontent.split(
',')
634 tiers=self.
_options.datatier.split(
',')
635 if not self.
_options.outputDefinition
and len(streamTypes)!=len(tiers):
636 raise Exception(
"number of event content arguments does not match number of datatier arguments")
642 for i,(streamType,tier)
in enumerate(
zip(streamTypes,tiers)):
643 if streamType==
'':
continue
644 if streamType ==
'ALCARECO' and not 'ALCAPRODUCER' in self.
_options.step:
continue
645 if streamType==
'DQMIO': streamType=
'DQM'
646 eventContent=streamType
648 if streamType ==
"NANOEDMAOD" :
649 eventContent =
"NANOAOD"
650 elif streamType ==
"NANOEDMAODSIM" :
651 eventContent =
"NANOAODSIM"
652 theEventContent = getattr(self.
process, eventContent+
"EventContent")
654 theFileName=self.
_options.outfile_name
655 theFilterName=self.
_options.filtername
657 theFileName=self.
_options.outfile_name.replace(
'.root',
'_in'+streamType+
'.root')
658 theFilterName=self.
_options.filtername
659 CppType=
'PoolOutputModule'
661 CppType=
'TimeoutPoolOutputModule'
662 if streamType==
'DQM' and tier==
'DQMIO': CppType=
'DQMRootOutputModule'
663 if "NANOAOD" in streamType : CppType=
'NanoAODOutputModule'
664 output = cms.OutputModule(CppType,
666 fileName = cms.untracked.string(theFileName),
667 dataset = cms.untracked.PSet(dataTier = cms.untracked.string(tier),
668 filterName = cms.untracked.string(theFilterName)
671 if hasattr(self.
process,
"generation_step")
and streamType!=
'LHE':
672 output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(
'generation_step'))
673 if hasattr(self.
process,
"filtering_step"):
674 output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring(
'filtering_step'))
676 if streamType==
'ALCARECO':
677 output.dataset.filterName = cms.untracked.string(
'StreamALCACombined')
679 if "MINIAOD" in streamType:
680 from PhysicsTools.PatAlgos.slimming.miniAOD_tools
import miniAOD_customizeOutput
683 outputModuleName=streamType+
'output'
684 setattr(self.
process,outputModuleName,output)
685 outputModule=getattr(self.
process,outputModuleName)
686 setattr(self.
process,outputModuleName+
'_step',cms.EndPath(outputModule))
687 path=getattr(self.
process,outputModuleName+
'_step')
690 if self.
_options.outputCommands
and streamType!=
'DQM':
691 for evct
in self.
_options.outputCommands.split(
','):
692 if not evct:
continue
693 self.
executeAndRemember(
"process.%s.outputCommands.append('%s')"%(outputModuleName,evct.strip()))
695 if not self.
_options.inlineEventContent:
696 tmpstreamType=streamType
697 if "NANOEDM" in tmpstreamType :
698 tmpstreamType=tmpstreamType.replace(
"NANOEDM",
"NANO")
699 def doNotInlineEventContent(instance,label = "process."+tmpstreamType+"EventContent.outputCommands"):
701 outputModule.outputCommands.__dict__[
"dumpPython"] = doNotInlineEventContent
703 result+=
"\nprocess."+outputModuleName+
" = "+outputModule.dumpPython()
709 Add selected standard sequences to the process
713 pileupSpec=self.
_options.pileup.split(
',')[0]
716 from Configuration.StandardSequences.Mixing
import Mixing,defineMixing
717 if not pileupSpec
in Mixing
and '.' not in pileupSpec
and 'file:' not in pileupSpec:
718 message = pileupSpec+
' is not a know mixing scenario:\n available are: '+
'\n'.
join(Mixing.keys())
722 if '.' in pileupSpec:
723 mixingDict={
'file':pileupSpec}
724 elif pileupSpec.startswith(
'file:'):
725 mixingDict={
'file':pileupSpec[5:]}
728 mixingDict=copy.copy(Mixing[pileupSpec])
729 if len(self.
_options.pileup.split(
','))>1:
730 mixingDict.update(eval(self.
_options.pileup[self.
_options.pileup.find(
',')+1:]))
733 if 'file:' in pileupSpec:
736 print(
"inlining mixing module configuration")
741 mixingDict.pop(
'file')
744 if self.
_options.pileup_input.startswith(
'dbs:')
or self.
_options.pileup_input.startswith(
'das:'):
746 elif self.
_options.pileup_input.startswith(
"filelist:"):
749 mixingDict[
'F']=self.
_options.pileup_input.split(
',')
751 for command
in specialization:
753 if len(mixingDict)!=0:
754 raise Exception(
'unused mixing specification: '+mixingDict.keys().
__str__())
775 stepSpec = self.
stepMap[stepName]
776 print(
"Step:", stepName,
"Spec:",stepSpec)
777 if stepName.startswith(
're'):
779 if stepName[2:]
not in self.
_options.donotDropOnInput:
780 self.
_options.inputEventContent=
'%s,%s'%(stepName.upper(),self.
_options.inputEventContent)
781 stepName=stepName[2:]
783 getattr(self,
"prepare_"+stepName)(sequence = getattr(self,stepName+
"DefaultSeq"))
784 elif isinstance(stepSpec, list):
785 getattr(self,
"prepare_"+stepName)(sequence =
'+'.
join(stepSpec))
786 elif isinstance(stepSpec, tuple):
787 getattr(self,
"prepare_"+stepName)(sequence =
','.
join([stepSpec[1],
'+'.
join(stepSpec[0])]))
789 raise ValueError(
"Invalid step definition")
791 if self.
_options.restoreRNDSeeds!=
False:
793 if self.
_options.restoreRNDSeeds==
True:
794 self.
executeAndRemember(
'process.RandomNumberGeneratorService.restoreStateLabel=cms.untracked.string("randomEngineStateProducer")')
796 self.
executeAndRemember(
'process.RandomNumberGeneratorService.restoreStateTag=cms.untracked.InputTag("randomEngineStateProducer","","%s")'%(self.
_options.restoreRNDSeeds))
799 self.
_options.inputCommands+=
'keep *_randomEngineStateProducer_*_*,'
801 self.
_options.inputCommands=
'keep *_randomEngineStateProducer_*_*,'
807 def dropSecondDropStar(iec):
817 if not hasattr(self.
process.source,
'inputCommands'): self.
process.source.inputCommands=cms.untracked.vstring()
818 for evct
in self.
_options.inputEventContent.split(
','):
819 if evct==
'':
continue
820 theEventContent = getattr(self.
process, evct+
"EventContent")
821 if hasattr(theEventContent,
'outputCommands'):
822 self.
process.source.inputCommands.extend(copy.copy(theEventContent.outputCommands))
823 if hasattr(theEventContent,
'inputCommands'):
824 self.
process.source.inputCommands.extend(copy.copy(theEventContent.inputCommands))
826 dropSecondDropStar(self.
process.source.inputCommands)
828 if not self.
_options.dropDescendant:
829 self.
process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(
False)
835 """Add conditions to the process"""
836 if not self.
_options.conditions:
return
838 if 'FrontierConditions_GlobalTag' in self.
_options.conditions:
839 print(
'using FrontierConditions_GlobalTag in --conditions is not necessary anymore and will be deprecated soon. please update your command line')
840 self.
_options.conditions = self.
_options.conditions.replace(
"FrontierConditions_GlobalTag,",
'')
843 from Configuration.AlCa.GlobalTag
import GlobalTag
850 """Include the customise code """
854 for c
in self.
_options.customisation_file:
855 custOpt.extend(c.split(
","))
857 for c
in self.
_options.customisation_file_unsch:
858 custOpt.extend(c.split(
","))
864 raise Exception(
"more than . in the specification:"+opt)
865 fileName=opt.split(
'.')[0]
866 if opt.count(
'.')==0: rest=
'customise'
868 rest=opt.split(
'.')[1]
869 if rest==
'py': rest=
'customise'
871 if fileName
in custMap:
872 custMap[fileName].extend(rest.split(
'+'))
874 custMap[fileName]=rest.split(
'+')
879 final_snippet=
'\n# customisation of the process.\n'
883 allFcn.extend(custMap[opt])
885 if allFcn.count(fcn)!=1:
886 raise Exception(
"cannot specify twice "+fcn+
" as a customisation method")
890 packageName = f.replace(
".py",
"").
replace(
"/",
".")
891 __import__(packageName)
892 package = sys.modules[packageName]
895 customiseFile = re.sub(
r'\.pyc$',
'.py', package.__file__)
897 final_snippet+=
'\n# Automatic addition of the customisation function from '+packageName+
'\n'
899 for line
in file(customiseFile,
'r'):
900 if "import FWCore.ParameterSet.Config" in line:
902 final_snippet += line
904 final_snippet +=
'from %s import %s \n'%(packageName,
','.
join(custMap[f]))
905 for fcn
in custMap[f]:
906 print(
"customising the process with",fcn,
"from",f)
907 if not hasattr(package,fcn):
909 raise Exception(
"config "+f+
" has no function "+fcn)
913 final_snippet +=
"\n#call to customisation function "+fcn+
" imported from "+packageName
914 final_snippet +=
"\nprocess = %s(process)\n"%(fcn,)
917 final_snippet +=
'\n# End of customisation functions\n'
923 final_snippet=
'\n# Customisation from command line\n'
924 if self.
_options.customise_commands:
926 for com
in self.
_options.customise_commands.split(
'\\n'):
929 final_snippet +=
'\n'+com
940 if self.
_options.particleTable
not in defaultOptions.particleTableList:
941 print(
'Invalid particle table provided. Options are:')
942 print(defaultOptions.particleTable)
950 self.
ALCADefaultCFF=
"Configuration/StandardSequences/AlCaRecoStreams_cff"
984 self.
L1EMDefaultCFF=
'Configuration/StandardSequences/SimL1EmulatorDM_cff'
1023 self.
_options.beamspot=VtxSmearedDefaultKey
1028 self.
RECODefaultCFF=
"Configuration/StandardSequences/Reconstruction_cff"
1029 self.
PATDefaultCFF=
"Configuration/StandardSequences/PATMC_cff"
1032 self.
ALCADefaultCFF=
"Configuration/StandardSequences/AlCaRecoStreamsMC_cff"
1041 if self.
_options.scenario==
'cosmics':
1043 self.
DIGIDefaultCFF=
"Configuration/StandardSequences/DigiCosmics_cff"
1044 self.
RECODefaultCFF=
"Configuration/StandardSequences/ReconstructionCosmics_cff"
1045 self.
SKIMDefaultCFF=
"Configuration/StandardSequences/SkimsCosmics_cff"
1055 if self.
_options.scenario==
'HeavyIons':
1057 self.
_options.beamspot=VtxSmearedHIDefaultKey
1062 self.
RECODefaultCFF=
"Configuration/StandardSequences/ReconstructionHeavyIons_cff"
1064 self.
ALCADefaultCFF =
"Configuration/StandardSequences/AlCaRecoStreamsHeavyIons_cff"
1067 self.
SKIMDefaultCFF=
"Configuration/StandardSequences/SkimsHeavyIons_cff"
1079 self.
magFieldCFF =
'Configuration/StandardSequences/MagneticField_'+self.
_options.magField.replace(
'.',
'')+
'_cff'
1083 self.
GeometryCFF=
'Configuration/StandardSequences/GeometryRecoDB_cff'
1087 if 'start' in self.
_options.conditions.lower():
1088 self.
GeometryCFF=
'FastSimulation/Configuration/Geometries_START_cff'
1090 self.
GeometryCFF=
'FastSimulation/Configuration/Geometries_MC_cff'
1092 def inGeometryKeys(opt):
1093 from Configuration.StandardSequences.GeometryConf
import GeometryConf
1094 if opt
in GeometryConf:
1095 return GeometryConf[opt]
1099 geoms=self.
_options.geometry.split(
',')
1100 if len(geoms)==1: geoms=inGeometryKeys(geoms[0]).
split(
',')
1103 if '/' in geoms[1]
or '_cff' in geoms[1]:
1106 self.
GeometryCFF=
'Configuration/Geometry/Geometry'+geoms[1]+
'_cff'
1108 if (geoms[0].startswith(
'DB:')):
1109 self.
SimGeometryCFF=
'Configuration/StandardSequences/GeometrySimDB_cff'
1113 if '/' in geoms[0]
or '_cff' in geoms[0]:
1116 simGeometry=geoms[0]
1118 self.
SimGeometryCFF=
'Configuration/Geometry/Geometry'+geoms[0]+
'GFlash_cff'
1120 self.
SimGeometryCFF=
'Configuration/Geometry/Geometry'+geoms[0]+
'_cff'
1123 if simGeometry
not in defaultOptions.geometryExtendedOptions:
1124 self.
SIMDefaultCFF=
"Configuration/StandardSequences/SimIdeal_cff"
1127 self.
SIMDefaultCFF=
"Configuration/StandardSequences/SimNOBEAM_cff"
1132 self.
SIMDefaultCFF =
'FastSimulation.Configuration.SimIdeal_cff'
1133 self.
RECODefaultCFF=
'FastSimulation.Configuration.Reconstruction_AftMix_cff'
1140 if self.
_options.pileup==
'default':
1141 from Configuration.StandardSequences.Mixing
import MixingDefaultKey
1142 self.
_options.pileup=MixingDefaultKey
1155 output = cms.OutputModule(
"PoolOutputModule")
1156 if stream.selectEvents.parameters_().__len__()!=0:
1157 output.SelectEvents = stream.selectEvents
1159 output.SelectEvents = cms.untracked.PSet()
1160 output.SelectEvents.SelectEvents=cms.vstring()
1161 if isinstance(stream.paths,tuple):
1162 for path
in stream.paths:
1163 output.SelectEvents.SelectEvents.append(path.label())
1165 output.SelectEvents.SelectEvents.append(stream.paths.label())
1169 if isinstance(stream.content,str):
1170 evtPset=getattr(self.process,stream.content)
1171 for p
in evtPset.parameters_():
1172 setattr(output,p,getattr(evtPset,p))
1173 if not self._options.inlineEventContent:
1174 def doNotInlineEventContent(instance,label = "process."+stream.content+".outputCommands"):
1176 output.outputCommands.__dict__[
"dumpPython"] = doNotInlineEventContent
1178 output.outputCommands = stream.content
1181 output.fileName = cms.untracked.string(self._options.dirout+stream.name+
'.root')
1183 output.dataset = cms.untracked.PSet( dataTier = stream.dataTier,
1184 filterName = cms.untracked.string(stream.name))
1186 if self._options.filtername:
1187 output.dataset.filterName= cms.untracked.string(self._options.filtername+
"_"+stream.name)
1190 output.eventAutoFlushCompressedSize=cms.untracked.int32(5*1024*1024)
1192 if workflow
in (
"producers,full"):
1193 if isinstance(stream.paths,tuple):
1194 for path
in stream.paths:
1195 self.schedule.
append(path)
1197 self.schedule.
append(stream.paths)
1201 if (
not self._options.relval)
and workflow
in (
"full",
"output"):
1202 self.additionalOutputs[name] = output
1203 setattr(self.process,name,output)
1205 if workflow ==
'output':
1207 filterList = output.SelectEvents.SelectEvents
1208 for i, filter
in enumerate(filterList):
1209 filterList[i] = filter+
":"+self._options.triggerResultsProcess
1219 if ( len(sequence.split(
'.'))==1 ):
1221 elif ( len(sequence.split(
'.'))==2 ):
1223 sequence=sequence.split(
'.')[1]
1225 print(
"sub sequence configuration must be of the form dir/subdir/cff.a+b+c or cff.a")
1226 print(sequence,
"not recognized")
1233 for i,s
in enumerate(seq.split(
'*')):
1235 setattr(self.
process,prefix,getattr(cms,what)( getattr(self.
process, s) ))
1237 p=getattr(self.
process,prefix)
1238 tmp = getattr(self.
process, s)
1239 if isinstance(tmp, cms.Task):
1250 setattr(self.
process,prefix,getattr(cms,what)( getattr(self.
process, seq) ))
1253 for i,s
in enumerate(seq.split(
'+')):
1255 setattr(self.
process,sn,getattr(cms,what)( getattr(self.
process, s) ))
1269 def prepare_ALCA(self, sequence = None, workflow = 'full'):
1270 """ Enrich the process with alca streams """
1272 sequence = sequence.split(
'.')[-1]
1275 alcaList = sequence.split(
"+")
1277 from Configuration.AlCa.autoAlca
import autoAlca
1281 for name
in alcaConfig.__dict__:
1282 alcastream = getattr(alcaConfig,name)
1283 shortName = name.replace(
'ALCARECOStream',
'')
1284 if shortName
in alcaList
and isinstance(alcastream,cms.FilteredStream):
1285 output = self.
addExtraStream(name,alcastream, workflow = workflow)
1286 self.
executeAndRemember(
'process.ALCARECOEventContent.outputCommands.extend(process.OutALCARECO'+shortName+
'_noDrop.outputCommands)')
1288 if 'DQM' in alcaList:
1289 if not self.
_options.inlineEventContent
and hasattr(self.
process,name):
1290 self.
executeAndRemember(
'process.' + name +
'.outputCommands.append("keep *_MEtoEDMConverter_*_*")')
1292 output.outputCommands.append(
"keep *_MEtoEDMConverter_*_*")
1296 if isinstance(alcastream.paths,tuple):
1297 for path
in alcastream.paths:
1302 for i
in range(alcaList.count(shortName)):
1303 alcaList.remove(shortName)
1306 elif name ==
'pathALCARECODQM' and 'DQM' in alcaList:
1307 path = getattr(alcaConfig,name)
1309 alcaList.remove(
'DQM')
1311 if isinstance(alcastream,cms.Path):
1316 if len(alcaList) != 0:
1318 for name
in alcaConfig.__dict__:
1319 alcastream = getattr(alcaConfig,name)
1320 if isinstance(alcastream,cms.FilteredStream):
1321 available.append(name.replace(
'ALCARECOStream',
''))
1322 print(
"The following alcas could not be found "+
str(alcaList))
1323 print(
"available ",available)
1325 raise Exception(
"The following alcas could not be found "+
str(alcaList))
1330 loadFragment = self._options.evt_type.replace(
'.py',
'',).
replace(
'.',
'_').
replace(
'python/',
'').
replace(
'/',
'.')
1331 print(
"Loading lhe fragment from",loadFragment)
1332 __import__(loadFragment)
1333 self.process.
load(loadFragment)
1335 self._options.inlineObjets+=
','+sequence
1337 getattr(self.process,sequence).nEvents =
int(self._options.number)
1340 self.process.lhe_step = cms.Path( getattr( self.process,sequence) )
1341 self.excludedPaths.
append(
"lhe_step")
1342 self.schedule.
append( self.process.lhe_step )
1345 """ load the fragment of generator configuration """
1352 if not '/' in loadFragment:
1353 loadFragment=
'Configuration.Generator.'+loadFragment
1355 loadFragment=loadFragment.replace(
'/',
'.')
1357 print(
"Loading generator fragment from",loadFragment)
1358 __import__(loadFragment)
1363 raise Exception(
"Neither gen fragment of input files provided: this is an inconsistent GEN step configuration")
1366 generatorModule=sys.modules[loadFragment]
1367 genModules=generatorModule.__dict__
1378 import FWCore.ParameterSet.Modules
as cmstypes
1379 for name
in genModules:
1380 theObject = getattr(generatorModule,name)
1381 if isinstance(theObject, cmstypes._Module):
1383 elif isinstance(theObject, cms.Sequence)
or isinstance(theObject, cmstypes.ESProducer):
1384 self.
_options.inlineObjets+=
','+name
1386 if sequence == self.
GENDefaultSeq or sequence ==
'pgen_genonly':
1387 if 'ProductionFilterSequence' in genModules
and (
'generator' in genModules):
1389 elif 'generator' in genModules:
1392 """ Enrich the schedule with the rest of the generation step """
1394 genSeqName=sequence.split(
'.')[-1]
1398 from Configuration.StandardSequences.VtxSmeared
import VtxSmeared
1399 cffToBeLoaded=VtxSmeared[self.
_options.beamspot]
1402 raise Exception(
"VertexSmearing type or beamspot "+self.
_options.beamspot+
" unknown.")
1404 if self.
_options.scenario ==
'HeavyIons':
1405 if self.
_options.pileup==
'HiMixGEN':
1406 self.
loadAndRemember(
"Configuration/StandardSequences/GeneratorMix_cff")
1407 elif self.
_options.pileup==
'HiMixEmbGEN':
1408 self.
loadAndRemember(
"Configuration/StandardSequences/GeneratorEmbMix_cff")
1410 self.
loadAndRemember(
"Configuration/StandardSequences/GeneratorHI_cff")
1412 self.
process.generation_step = cms.Path( getattr(self.
process,genSeqName) )
1416 self.
executeAndRemember(
'process.genstepfilter.triggerConditions=cms.vstring("generation_step")')
1422 """ Enrich the schedule with the summary of the filter step """
1429 """ Enrich the schedule with the simulation step"""
1439 self.
executeAndRemember(
"process.fastSimProducer.detectorDefinition.magneticFieldZ = cms.untracked.double(0.)")
1445 """ Enrich the schedule with the digitisation step"""
1449 self.
loadAndRemember(
"Configuration/StandardSequences/GFlashDIGI_cff")
1451 if sequence ==
'pdigi_valid' or sequence ==
'pdigi_hi':
1452 self.
executeAndRemember(
"process.mix.digitizers = cms.PSet(process.theDigitizersValid)")
1454 if sequence !=
'pdigi_nogen' and sequence !=
'pdigi_valid_nogen' and sequence !=
'pdigi_hi_nogen' and not self.
process.source.type_()==
'EmptySource' and not self.
_options.filetype ==
"LHE":
1455 if self.
_options.inputEventContent==
'':
1456 self.
_options.inputEventContent=
'REGEN'
1465 """ Enrich the schedule with the crossing frame writer step"""
1471 """ Enrich the schedule with the digitisation step"""
1477 if self.
_options.pileup_input.startswith(
'dbs:')
or self.
_options.pileup_input.startswith(
'das:'):
1479 elif self.
_options.pileup_input.startswith(
"filelist:"):
1482 theFiles=self.
_options.pileup_input.split(
',')
1484 self.
executeAndRemember(
"process.mixData.input.fileNames = cms.untracked.vstring(%s)"%( theFiles ) )
1499 """ Enrich the schedule with the L1 simulation step"""
1506 """ Enrich the schedule with the L1 simulation step, running the L1 emulator on data unpacked from the RAW collection, and repacking the result in a new RAW collection"""
1507 supported = [
'GT',
'GT1',
'GT2',
'GCTGT',
'Full',
'FullSimTP',
'FullMC',
'Full2015Data',
'uGT',
'CalouGT']
1508 if sequence
in supported:
1509 self.
loadAndRemember(
'Configuration/StandardSequences/SimL1EmulatorRepack_%s_cff'%sequence)
1510 if self.
_options.scenario ==
'HeavyIons':
1514 print(
"L1REPACK with '",sequence,
"' is not supported! Supported choices are: ",supported)
1519 """ Enrich the schedule with the HLT simulation step"""
1521 print(
"no specification of the hlt menu has been given, should never happen")
1522 raise Exception(
'no HLT sequence provided')
1526 from Configuration.HLT.autoHLT
import autoHLT
1529 sequence = autoHLT[key]
1531 raise ValueError(
'no HLT mapping key "%s" found in autoHLT' % key)
1537 if self.
_options.scenario ==
'HeavyIons':
1538 optionsForHLT[
'type'] =
'HIon'
1540 optionsForHLT[
'type'] =
'GRun'
1541 optionsForHLTConfig =
', '.
join(
'%s=%s' % (key, repr(val))
for (key, val)
in optionsForHLT.items())
1542 if sequence ==
'run,fromSource':
1543 if hasattr(self.
process.source,
'firstRun'):
1544 self.
executeAndRemember(
'process.loadHltConfiguration("run:%%d"%%(process.source.firstRun.value()),%s)'%(optionsForHLTConfig))
1545 elif hasattr(self.
process.source,
'setRunNumber'):
1546 self.
executeAndRemember(
'process.loadHltConfiguration("run:%%d"%%(process.source.setRunNumber.value()),%s)'%(optionsForHLTConfig))
1548 raise Exception(
'Cannot replace menu to load %s'%(sequence))
1550 self.
executeAndRemember(
'process.loadHltConfiguration("%s",%s)'%(sequence.replace(
',',
':'),optionsForHLTConfig))
1555 self.
_options.customisation_file.append(
"HLTrigger/Configuration/customizeHLTforMC.customizeHLTforMC")
1561 from HLTrigger.Configuration.CustomConfigs
import ProcessName
1569 if not hasattr(self.
process,
'HLTEndSequence'):
1570 self.
executeAndRemember(
"process.HLTEndSequence = cms.Sequence( process.dummyModule )")
1575 seqReco=sequence.split(
',')[1]
1576 seqDigi=sequence.split(
',')[0]
1578 print(
"RAW2RECO requires two specifications",sequence,
"insufficient")
1594 for filt
in allMetFilterPaths:
1598 ''' Enrich the schedule with L1 HW validation '''
1601 print(
'\n\n\n DEPRECATED this has no action \n\n\n')
1605 ''' Enrich the schedule with L1 reconstruction '''
1611 ''' Enrich the schedule with L1 reconstruction '''
1617 ''' Enrich the schedule with a user defined filter sequence '''
1619 filterConfig=self.
load(sequence.split(
'.')[0])
1620 filterSeq=sequence.split(
'.')[-1]
1622 class PrintAllModules(
object):
1626 def enter(self,visitee):
1628 label=visitee.label()
1633 def leave(self,v):
pass
1635 expander=PrintAllModules()
1636 getattr(self.
process,filterSeq).visit( expander )
1637 self.
_options.inlineObjets+=
','+expander.inliner
1638 self.
_options.inlineObjets+=
','+filterSeq
1649 ''' Enrich the schedule with reconstruction '''
1655 ''' Enrich the schedule with reconstruction '''
1661 ''' Enrich the schedule with the part of reconstruction that is done before mixing in FastSim'''
1663 print(
"ERROR: this step is only implemented for FastSim")
1666 self.
scheduleSequence(sequence.split(
'.')[-1],
'reconstruction_befmix_step')
1670 ''' Enrich the schedule with PAT '''
1675 self.
_options.customisation_file_unsch.insert(0,
"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllData")
1678 self.
_options.customisation_file_unsch.insert(0,
"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllMCFastSim")
1680 self.
_options.customisation_file_unsch.insert(0,
"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllMC")
1683 if len(self.
_options.customise_commands) > 1:
1684 self.
_options.customise_commands = self.
_options.customise_commands +
" \n"
1685 self.
_options.customise_commands = self.
_options.customise_commands +
"process.patTrigger.processName = \""+self.
_options.hltProcess+
"\"\n"
1686 self.
_options.customise_commands = self.
_options.customise_commands +
"process.slimmedPatTrigger.triggerResults= cms.InputTag( 'TriggerResults::"+self.
_options.hltProcess+
"' )\n"
1687 self.
_options.customise_commands = self.
_options.customise_commands +
"process.patMuons.triggerResults= cms.InputTag( 'TriggerResults::"+self.
_options.hltProcess+
"' )\n"
1694 ''' Enrich the schedule with PATGEN '''
1698 raise Exception(
"PATGEN step can only run on MC")
1702 ''' Enrich the schedule with NANO '''
1705 custom =
"nanoAOD_customizeData" if self.
_options.isData
else "nanoAOD_customizeMC"
1706 self.
_options.customisation_file.insert(0,
"PhysicsTools/NanoAOD/nano_cff."+custom)
1708 if len(self.
_options.customise_commands) > 1:
1709 self.
_options.customise_commands = self.
_options.customise_commands +
" \n"
1710 self.
_options.customise_commands = self.
_options.customise_commands +
"process.unpackedPatTrigger.triggerResults= cms.InputTag( 'TriggerResults::"+self.
_options.hltProcess+
"' )\n"
1713 ''' Enrich the schedule with NANOGEN '''
1715 fromGen =
any([x
in self.
stepMap for x
in [
'LHE',
'GEN',
'AOD']])
1718 custom =
"customizeNanoGEN" if fromGen
else "customizeNanoGENFromMini"
1725 ''' Enrich the schedule with event interpretation '''
1726 from Configuration.StandardSequences.EventInterpretation
import EventInterpretation
1727 if sequence
in EventInterpretation:
1729 sequence =
'EIsequence'
1731 raise Exception(
'Cannot set %s event interpretation'%( sequence) )
1737 ''' Enrich the schedule with skimming fragments'''
1739 sequence = sequence.split(
'.')[-1]
1741 skimlist=sequence.split(
'+')
1743 from Configuration.Skimming.autoSkim
import autoSkim
1747 for skim
in skimConfig.__dict__:
1748 skimstream = getattr(skimConfig,skim)
1749 if isinstance(skimstream,cms.Path):
1752 if (
not isinstance(skimstream,cms.FilteredStream)):
1754 shortname = skim.replace(
'SKIMStream',
'')
1755 if (sequence==
"all"):
1757 elif (shortname
in skimlist):
1762 skimstreamDQM = cms.FilteredStream(
1763 responsible = skimstream.responsible,
1764 name = skimstream.name+
'DQM',
1765 paths = skimstream.paths,
1766 selectEvents = skimstream.selectEvents,
1767 content = self.
_options.datatier+
'EventContent',
1768 dataTier = cms.untracked.string(self.
_options.datatier)
1771 for i
in range(skimlist.count(shortname)):
1772 skimlist.remove(shortname)
1776 if (skimlist.__len__()!=0
and sequence!=
"all"):
1777 print(
'WARNING, possible typo with SKIM:'+
'+'.
join(skimlist))
1778 raise Exception(
'WARNING, possible typo with SKIM:'+
'+'.
join(skimlist))
1781 ''' Enrich the schedule with a user defined sequence '''
1787 """ Enrich the schedule with the postreco step """
1794 print(sequence,
"in preparing validation")
1796 from Validation.Configuration.autoValidation
import autoValidation
1798 sequence=sequence.split(
'.')[-1]
1799 if sequence.find(
',')!=-1:
1800 prevalSeqName=sequence.split(
',')[0].
split(
'+')
1801 valSeqName=sequence.split(
',')[1].
split(
'+')
1806 prevalSeqName=sequence.split(
'+')
1807 valSeqName=sequence.split(
'+')
1813 postfix=
'_'+sequence
1814 prevalSeqName=[
'prevalidation'+postfix]
1815 valSeqName=[
'validation'+postfix]
1816 if not hasattr(self.
process,valSeqName[0]):
1818 valSeqName=[sequence]
1830 for s
in valSeqName+prevalSeqName:
1833 for (i,s)
in enumerate(prevalSeqName):
1835 setattr(self.
process,
'prevalidation_step%s'%NFI(i), cms.Path( getattr(self.
process, s)) )
1838 for (i,s)
in enumerate(valSeqName):
1839 setattr(self.
process,
'validation_step%s'%NFI(i), cms.EndPath( getattr(self.
process, s)))
1846 if not 'DIGI' in self.
stepMap and not self.
_options.fast
and not any(
map(
lambda s : s.startswith(
'genvalid'), valSeqName)):
1847 if self.
_options.restoreRNDSeeds==
False and not self.
_options.restoreRNDSeeds==
True:
1854 self.
_options.customisation_file.append(
"SimGeneral/MixingModule/fullMixCustomize_cff.setCrossingFrameOn")
1856 if hasattr(self.
process,
"genstepfilter")
and len(self.
process.genstepfilter.triggerConditions):
1858 for (i,s)
in enumerate(valSeqName):
1865 """Visitor that travels within a cms.Sequence, looks for a parameter and replace its value
1866 It will climb down within PSets, VPSets and VInputTags to find its target"""
1867 def __init__(self, paramSearch, paramReplace, verbose=False, whitelist=()):
1873 def doIt(self,pset,base):
1874 if isinstance(pset, cms._Parameterizable):
1875 for name
in pset.parameters_().
keys():
1881 value = getattr(pset,name)
1882 type = value.pythonTypeName()
1883 if type
in (
'cms.PSet',
'cms.untracked.PSet'):
1884 self.
doIt(value,base+
"."+name)
1885 elif type
in (
'cms.VPSet',
'cms.untracked.VPSet'):
1886 for (i,ps)
in enumerate(value): self.
doIt(ps,
"%s.%s[%d]"%(base,name,i) )
1887 elif type
in (
'cms.string',
'cms.untracked.string'):
1891 elif type
in (
'cms.VInputTag',
'cms.untracked.VInputTag'):
1892 for (i,n)
in enumerate(value):
1893 if not isinstance(n, cms.InputTag):
1900 elif type
in (
'cms.vstring',
'cms.untracked.vstring'):
1901 for (i,n)
in enumerate(value):
1904 elif type
in (
'cms.InputTag',
'cms.untracked.InputTag'):
1907 setattr(getattr(pset, name),
"processName",self.
_paramReplace)
1909 def enter(self,visitee):
1912 label = visitee.label()
1913 except AttributeError:
1914 label =
'<Module not in a Process>'
1916 label =
'other execption'
1917 self.
doIt(visitee, label)
1919 def leave(self,visitee):
1924 print(
"Replacing all InputTag %s => %s"%(oldT,newT))
1927 loadMe=
'from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag'
1930 self.
additionalCommands.
append(
'massSearchReplaceAnyInputTag(process.%s,"%s","%s",False,True)'%(sequence,oldT,newT))
1938 if proc==HLTprocess:
return
1940 print(
"replacing %s process name - sequence %s will use '%s'" % (HLTprocess,sequence, proc))
1942 if 'from Configuration.Applications.ConfigBuilder import ConfigBuilder' not in self.
additionalCommands:
1944 self.
additionalCommands.
append(
'process.%s.visit(ConfigBuilder.MassSearchReplaceProcessNameVisitor("%s", "%s", whitelist = ("subSystemFolder",)))'% (sequence,HLTprocess, proc))
1950 while '@' in repr(seqList)
and level<maxLevel:
1952 for specifiedCommand
in seqList:
1953 if specifiedCommand.startswith(
'@'):
1954 location=specifiedCommand[1:]
1955 if not location
in mapping:
1956 raise Exception(
"Impossible to map "+location+
" from "+repr(mapping))
1957 mappedTo=mapping[location]
1959 mappedTo=mappedTo[index]
1960 seqList.remove(specifiedCommand)
1961 seqList.extend(mappedTo.split(
'+'))
1964 raise Exception(
"Could not fully expand "+repr(seqList)+
" from "+repr(mapping))
1972 sequenceList=sequence.split(
'.')[-1].
split(
'+')
1973 postSequenceList=sequence.split(
'.')[-1].
split(
'+')
1974 from DQMOffline.Configuration.autoDQM
import autoDQM
1978 if len(set(sequenceList))!=len(sequenceList):
1979 sequenceList=list(set(sequenceList))
1980 print(
"Duplicate entries for DQM:, using",sequenceList)
1982 pathName=
'dqmoffline_step'
1983 for (i,sequence)
in enumerate(sequenceList):
1985 pathName=
'dqmoffline_%d_step'%(i)
1990 setattr(self.
process,pathName, cms.EndPath( getattr(self.
process,sequence ) ) )
1993 if hasattr(self.
process,
"genstepfilter")
and len(self.
process.genstepfilter.triggerConditions):
1998 pathName=
'dqmofflineOnPAT_step'
1999 for (i,sequence)
in enumerate(postSequenceList):
2001 if (sequenceList[i]==postSequenceList[i]):
2004 pathName=
'dqmofflineOnPAT_%d_step'%(i)
2006 setattr(self.
process,pathName, cms.EndPath( getattr(self.
process, sequence ) ) )
2010 """ Enrich the process with harvesting step """
2011 self.
DQMSaverCFF=
'Configuration/StandardSequences/DQMSaver'+self.
_options.harvesting+
'_cff'
2015 sequence = sequence.split(
'.')[-1]
2018 harvestingList = sequence.split(
"+")
2019 from DQMOffline.Configuration.autoDQM
import autoDQM
2020 from Validation.Configuration.autoValidation
import autoValidation
2022 combined_mapping = copy.deepcopy( autoDQM )
2023 combined_mapping.update( autoValidation )
2024 self.
expandMapping(harvestingList,combined_mapping,index=-1)
2026 if len(set(harvestingList))!=len(harvestingList):
2027 harvestingList=list(set(harvestingList))
2028 print(
"Duplicate entries for HARVESTING, using",harvestingList)
2030 for name
in harvestingList:
2031 if not name
in harvestingConfig.__dict__:
2032 print(name,
"is not a possible harvesting type. Available are",harvestingConfig.__dict__.keys())
2036 harvestingstream = getattr(harvestingConfig,name)
2037 if isinstance(harvestingstream,cms.Path):
2040 if isinstance(harvestingstream,cms.Sequence):
2041 setattr(self.
process,name+
"_step",cms.Path(harvestingstream))
2048 """ Enrich the process with AlCaHarvesting step """
2050 sequence=sequence.split(
".")[-1]
2053 harvestingList = sequence.split(
"+")
2057 from Configuration.AlCa.autoPCL
import autoPCL
2060 for name
in harvestingConfig.__dict__:
2061 harvestingstream = getattr(harvestingConfig,name)
2062 if name
in harvestingList
and isinstance(harvestingstream,cms.Path):
2064 if isinstance(getattr(harvestingConfig,
"ALCAHARVEST" + name +
"_dbOutput"), cms.VPSet)
and \
2065 isinstance(getattr(harvestingConfig,
"ALCAHARVEST" + name +
"_metadata"), cms.VPSet):
2066 self.
executeAndRemember(
"process.PoolDBOutputService.toPut.extend(process.ALCAHARVEST" + name +
"_dbOutput)")
2067 self.
executeAndRemember(
"process.pclMetadataWriter.recordsToMap.extend(process.ALCAHARVEST" + name +
"_metadata)")
2069 self.
executeAndRemember(
"process.PoolDBOutputService.toPut.append(process.ALCAHARVEST" + name +
"_dbOutput)")
2070 self.
executeAndRemember(
"process.pclMetadataWriter.recordsToMap.append(process.ALCAHARVEST" + name +
"_metadata)")
2071 harvestingList.remove(name)
2073 lastStep = getattr(harvestingConfig,
"ALCAHARVESTDQMSaveAndMetadataWriter")
2076 if len(harvestingList) != 0
and 'dummyHarvesting' not in harvestingList :
2077 print(
"The following harvesting could not be found : ", harvestingList)
2078 raise Exception(
"The following harvesting could not be found : "+
str(harvestingList))
2093 """ Add useful info for the production. """
2094 self.
process.configurationMetadata=cms.untracked.PSet\
2095 (version=cms.untracked.string(
"$Revision: 1.19 $"),
2096 name=cms.untracked.string(
"Applications"),
2097 annotation=cms.untracked.string(evt_type+
" nevts:"+
str(evtnumber))
2105 self.
pythonCfgCode +=
"# using: \n# "+__version__[1:-1]+
"\n# "+__source__[1:-1]+
'\n'
2107 self.
pythonCfgCode +=
"import FWCore.ParameterSet.Config as cms\n\n"
2116 from Configuration.StandardSequences.Eras
import eras
2117 for requestedEra
in self.
_options.era.split(
",") :
2118 modifierStrings.append(requestedEra)
2119 modifierImports.append(eras.pythonCfgLines[requestedEra])
2120 modifiers.append(getattr(eras,requestedEra))
2126 for pm
in self.
_options.procModifiers.split(
','):
2127 modifierStrings.append(pm)
2128 modifierImports.append(
'from Configuration.ProcessModifiers.'+pm+
'_cff import '+pm)
2129 modifiers.append(getattr(importlib.import_module(
'Configuration.ProcessModifiers.'+pm+
'_cff'),pm))
2135 if len(modifierStrings)>0:
2142 if len(modifiers)>0:
2150 def prepare(self, doChecking = False):
2151 """ Prepare the configuration string and add missing pieces."""
2163 outputModuleCfgCode=
""
2169 self.
pythonCfgCode +=
"# import of standard configurations\n"
2174 if not hasattr(self.
process,
"configurationMetadata"):
2196 self.
pythonCfgCode +=
"process.%s = %s" %(name, output.dumpPython())
2197 tmpOut = cms.EndPath(output)
2198 setattr(self.
process,name+
'OutPath',tmpOut)
2207 for object
in self.
_options.inlineObjets.split(
','):
2210 if not hasattr(self.
process,object):
2211 print(
'cannot inline -'+object+
'- : not known')
2216 if self.
_options.pileup==
'HiMixEmbGEN':
2217 self.
pythonCfgCode +=
"\nprocess.generator.embeddingMode=cms.bool(True)\n"
2221 for path
in self.
process.paths:
2225 for endpath
in self.
process.endpaths:
2231 result =
"process.schedule = cms.Schedule("
2234 self.
process.schedule = cms.Schedule()
2236 if not isinstance(item, cms.Schedule):
2237 self.
process.schedule.append(item)
2239 self.
process.schedule.extend(item)
2241 if hasattr(self.
process,
"HLTSchedule"):
2244 pathNames = [
'process.'+p.label_()
for p
in beforeHLT]
2245 result +=
','.
join(pathNames)+
')\n'
2246 result +=
'process.schedule.extend(process.HLTSchedule)\n'
2247 pathNames = [
'process.'+p.label_()
for p
in afterHLT]
2248 result +=
'process.schedule.extend(['+
','.
join(pathNames)+
'])\n'
2250 pathNames = [
'process.'+p.label_()
for p
in self.
schedule]
2251 result =
'process.schedule = cms.Schedule('+
','.
join(pathNames)+
')\n'
2256 self.
process.schedule.associate(getattr(self.
process, labelToAssociate))
2257 self.
pythonCfgCode +=
'process.schedule.associate(process.' + labelToAssociate +
')\n'
2261 self.
pythonCfgCode+=
"from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask\n"
2269 self.
pythonCfgCode +=
"process.options.numberOfConcurrentLuminosityBlocks = "+self.
_options.nConcurrentLumis+
"\n"
2270 self.
pythonCfgCode +=
"process.options.eventSetup.numberOfConcurrentIOVs = "+self.
_options.nConcurrentIOVs+
"\n"
2272 self.
pythonCfgCode +=
"if hasattr(process, 'DQMStore'): process.DQMStore.assertLegacySafe=cms.untracked.bool(False)\n"
2275 self.
process.options.numberOfConcurrentLuminosityBlocks =
int(self.
_options.nConcurrentLumis)
2276 self.
process.options.eventSetup.numberOfConcurrentIOVs =
int(self.
_options.nConcurrentIOVs)
2280 self.
pythonCfgCode +=
"from Configuration.Applications.ConfigBuilder import MassReplaceInputTag\n"
2281 self.
pythonCfgCode +=
"MassReplaceInputTag(process, new=\"rawDataMapperByLabel\", old=\"rawDataCollector\")\n"
2282 MassReplaceInputTag(self.
process, new=
"rawDataMapperByLabel", old=
"rawDataCollector")
2286 self.
pythonCfgCode +=
'# filter all path with the production filter sequence\n'
2294 for path
in self.
process.paths:
2304 print(
"--runUnscheduled is deprecated and not necessary anymore, and will be removed soon. Please update your command line.")
2313 if hasattr(self.
process,
"logErrorHarvester"):
2315 self.
pythonCfgCode +=
"\n#Have logErrorHarvester wait for the same EDProducers to finish as those providing data for the OutputModule\n"
2316 self.
pythonCfgCode +=
"from FWCore.Modules.logErrorHarvester_cff import customiseLogErrorHarvesterUsingOutputCommands\n"
2317 self.
pythonCfgCode +=
"process = customiseLogErrorHarvesterUsingOutputCommands(process)\n"
2318 from FWCore.Modules.logErrorHarvester_cff
import customiseLogErrorHarvesterUsingOutputCommands
2325 self.
pythonCfgCode +=
"\n# Add early deletion of temporary data products to reduce peak memory need\n"
2326 self.
pythonCfgCode +=
"from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete\n"
2327 self.
pythonCfgCode +=
"process = customiseEarlyDelete(process)\n"
2329 from Configuration.StandardSequences.earlyDeleteSettings_cff
import customiseEarlyDelete
2332 imports = cms.specialImportRegistry.getSpecialImports()
2333 if len(imports) > 0:
2345 if not self.
_options.io.endswith(
'.io'): self._option.io+=
'.io'
2348 if hasattr(self.
process.source,
"fileNames"):
2349 if len(self.
process.source.fileNames.value()):
2350 ioJson[
'primary']=self.
process.source.fileNames.value()
2351 if hasattr(self.
process.source,
"secondaryFileNames"):
2352 if len(self.
process.source.secondaryFileNames.value()):
2353 ioJson[
'secondary']=self.
process.source.secondaryFileNames.value()
2354 if self.
_options.pileup_input
and (self.
_options.pileup_input.startswith(
'dbs:')
or self.
_options.pileup_input.startswith(
'das:')):
2355 ioJson[
'pileup']=self.
_options.pileup_input[4:]
2357 ioJson[o]=om.fileName.value()
2358 ioJson[
'GT']=self.
process.GlobalTag.globaltag.value()
2362 io.write(json.dumps(ioJson))