CMS 3D CMS Logo

ConfigBuilder.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 from __future__ import print_function
4 __version__ = "$Revision: 1.19 $"
5 __source__ = "$Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v $"
6 
7 import FWCore.ParameterSet.Config as cms
8 from FWCore.ParameterSet.Modules import _Module
9 import six
10 # The following import is provided for backward compatibility reasons.
11 # The function used to be defined in this file.
12 from FWCore.ParameterSet.MassReplace import massReplaceInputTag as MassReplaceInputTag
13 
14 import hashlib
15 import sys
16 import re
17 import collections
18 from subprocess import Popen,PIPE
19 import FWCore.ParameterSet.DictTypes as DictTypes
20 class Options:
21  pass
22 
23 # the canonical defaults
24 defaultOptions = Options()
25 defaultOptions.datamix = 'DataOnSim'
26 defaultOptions.isMC=False
27 defaultOptions.isData=True
28 defaultOptions.step=''
29 defaultOptions.pileup='NoPileUp'
30 defaultOptions.pileup_input = None
31 defaultOptions.pileup_dasoption = ''
32 defaultOptions.geometry = 'SimDB'
33 defaultOptions.geometryExtendedOptions = ['ExtendedGFlash','Extended','NoCastor']
34 defaultOptions.magField = ''
35 defaultOptions.conditions = None
36 defaultOptions.scenarioOptions=['pp','cosmics','nocoll','HeavyIons']
37 defaultOptions.harvesting= 'AtRunEnd'
38 defaultOptions.gflash = False
39 defaultOptions.number = -1
40 defaultOptions.number_out = None
41 defaultOptions.arguments = ""
42 defaultOptions.name = "NO NAME GIVEN"
43 defaultOptions.evt_type = ""
44 defaultOptions.filein = ""
45 defaultOptions.dasquery=""
46 defaultOptions.dasoption=""
47 defaultOptions.secondfilein = ""
48 defaultOptions.customisation_file = []
49 defaultOptions.customisation_file_unsch = []
50 defaultOptions.customise_commands = ""
51 defaultOptions.inline_custom=False
52 defaultOptions.particleTable = 'pythiapdt'
53 defaultOptions.particleTableList = ['pythiapdt','pdt']
54 defaultOptions.dirin = ''
55 defaultOptions.dirout = ''
56 defaultOptions.filetype = 'EDM'
57 defaultOptions.fileout = 'output.root'
58 defaultOptions.filtername = ''
59 defaultOptions.lazy_download = False
60 defaultOptions.custom_conditions = ''
61 defaultOptions.hltProcess = ''
62 defaultOptions.eventcontent = None
63 defaultOptions.datatier = None
64 defaultOptions.inlineEventContent = True
65 defaultOptions.inlineObjets =''
66 defaultOptions.hideGen=False
67 from Configuration.StandardSequences.VtxSmeared import VtxSmearedDefaultKey,VtxSmearedHIDefaultKey
68 defaultOptions.beamspot=None
69 defaultOptions.outputDefinition =''
70 defaultOptions.inputCommands = None
71 defaultOptions.outputCommands = None
72 defaultOptions.inputEventContent = ''
73 defaultOptions.dropDescendant = False
74 defaultOptions.relval = None
75 defaultOptions.profile = None
76 defaultOptions.isRepacked = False
77 defaultOptions.restoreRNDSeeds = False
78 defaultOptions.donotDropOnInput = ''
79 defaultOptions.python_filename =''
80 defaultOptions.io=None
81 defaultOptions.lumiToProcess=None
82 defaultOptions.fast=False
83 defaultOptions.runsAndWeightsForMC = None
84 defaultOptions.runsScenarioForMC = None
85 defaultOptions.runUnscheduled = False
86 defaultOptions.timeoutOutput = False
87 defaultOptions.nThreads = '1'
88 defaultOptions.nStreams = '0'
89 defaultOptions.nConcurrentLumis = '1'
90 
91 # some helper routines
92 def dumpPython(process,name):
93  theObject = getattr(process,name)
94  if isinstance(theObject,cms.Path) or isinstance(theObject,cms.EndPath) or isinstance(theObject,cms.Sequence):
95  return "process."+name+" = " + theObject.dumpPython()
96  elif isinstance(theObject,_Module) or isinstance(theObject,cms.ESProducer):
97  return "process."+name+" = " + theObject.dumpPython()+"\n"
98  else:
99  return "process."+name+" = " + theObject.dumpPython()+"\n"
100 def filesFromList(fileName,s=None):
101  import os
102  import FWCore.ParameterSet.Config as cms
103  prim=[]
104  sec=[]
105  for line in open(fileName,'r'):
106  if line.count(".root")>=2:
107  #two files solution...
108  entries=line.replace("\n","").split()
109  prim.append(entries[0])
110  sec.append(entries[1])
111  elif (line.find(".root")!=-1):
112  entry=line.replace("\n","")
113  prim.append(entry)
114  # remove any duplicates
115  prim = sorted(list(set(prim)))
116  sec = sorted(list(set(sec)))
117  if s:
118  if not hasattr(s,"fileNames"):
119  s.fileNames=cms.untracked.vstring(prim)
120  else:
121  s.fileNames.extend(prim)
122  if len(sec)!=0:
123  if not hasattr(s,"secondaryFileNames"):
124  s.secondaryFileNames=cms.untracked.vstring(sec)
125  else:
126  s.secondaryFileNames.extend(sec)
127  print("found files: ",prim)
128  if len(prim)==0:
129  raise Exception("There are not files in input from the file list")
130  if len(sec)!=0:
131  print("found parent files:",sec)
132  return (prim,sec)
133 
134 def filesFromDASQuery(query,option="",s=None):
135  import os,time
136  import FWCore.ParameterSet.Config as cms
137  prim=[]
138  sec=[]
139  print("the query is",query)
140  eC=5
141  count=0
142  while eC!=0 and count<3:
143  if count!=0:
144  print('Sleeping, then retrying DAS')
145  time.sleep(100)
146  p = Popen('dasgoclient %s --query "%s"'%(option,query), stdout=PIPE,shell=True, universal_newlines=True)
147  pipe=p.stdout.read()
148  tupleP = os.waitpid(p.pid, 0)
149  eC=tupleP[1]
150  count=count+1
151  if eC==0:
152  print("DAS succeeded after",count,"attempts",eC)
153  else:
154  print("DAS failed 3 times- I give up")
155  for line in pipe.split('\n'):
156  if line.count(".root")>=2:
157  #two files solution...
158  entries=line.replace("\n","").split()
159  prim.append(entries[0])
160  sec.append(entries[1])
161  elif (line.find(".root")!=-1):
162  entry=line.replace("\n","")
163  prim.append(entry)
164  # remove any duplicates
165  prim = sorted(list(set(prim)))
166  sec = sorted(list(set(sec)))
167  if s:
168  if not hasattr(s,"fileNames"):
169  s.fileNames=cms.untracked.vstring(prim)
170  else:
171  s.fileNames.extend(prim)
172  if len(sec)!=0:
173  if not hasattr(s,"secondaryFileNames"):
174  s.secondaryFileNames=cms.untracked.vstring(sec)
175  else:
176  s.secondaryFileNames.extend(sec)
177  print("found files: ",prim)
178  if len(sec)!=0:
179  print("found parent files:",sec)
180  return (prim,sec)
181 
182 def anyOf(listOfKeys,dict,opt=None):
183  for k in listOfKeys:
184  if k in dict:
185  toReturn=dict[k]
186  dict.pop(k)
187  return toReturn
188  if opt!=None:
189  return opt
190  else:
191  raise Exception("any of "+','.join(listOfKeys)+" are mandatory entries of --output options")
192 
194  """The main building routines """
195 
196  def __init__(self, options, process = None, with_output = False, with_input = False ):
197  """options taken from old cmsDriver and optparse """
198 
199  options.outfile_name = options.dirout+options.fileout
200 
201  self._options = options
202 
203  if self._options.isData and options.isMC:
204  raise Exception("ERROR: You may specify only --data or --mc, not both")
205  #if not self._options.conditions:
206  # raise Exception("ERROR: No conditions given!\nPlease specify conditions. E.g. via --conditions=IDEAL_30X::All")
207 
208  # check that MEtoEDMConverter (running in ENDJOB) and DQMIO don't run in the same job
209  if 'ENDJOB' in self._options.step:
210  if (hasattr(self._options,"outputDefinition") and \
211  self._options.outputDefinition != '' and \
212  any(anyOf(['t','tier','dataTier'],outdic) == 'DQMIO' for outdic in eval(self._options.outputDefinition))) or \
213  (hasattr(self._options,"datatier") and \
214  self._options.datatier and \
215  'DQMIO' in self._options.datatier):
216  print("removing ENDJOB from steps since not compatible with DQMIO dataTier")
217  self._options.step=self._options.step.replace(',ENDJOB','')
218 
219 
220 
221  # what steps are provided by this class?
222  stepList = [re.sub(r'^prepare_', '', methodName) for methodName in ConfigBuilder.__dict__ if methodName.startswith('prepare_')]
223  self.stepMap={}
224  self.stepKeys=[]
225  for step in self._options.step.split(","):
226  if step=='': continue
227  stepParts = step.split(":")
228  stepName = stepParts[0]
229  if stepName not in stepList and not stepName.startswith('re'):
230  raise ValueError("Step "+stepName+" unknown")
231  if len(stepParts)==1:
232  self.stepMap[stepName]=""
233  elif len(stepParts)==2:
234  self.stepMap[stepName]=stepParts[1].split('+')
235  elif len(stepParts)==3:
236  self.stepMap[stepName]=(stepParts[2].split('+'),stepParts[1])
237  else:
238  raise ValueError("Step definition "+step+" invalid")
239  self.stepKeys.append(stepName)
240 
241  #print "map of steps is:",self.stepMap
242 
243  self.with_output = with_output
244  self.process=process
245 
246  if hasattr(self._options,"no_output_flag") and self._options.no_output_flag:
247  self.with_output = False
248  self.with_input = with_input
249  self.imports = []
250  self.create_process()
251  self.define_Configs()
252  self.schedule = list()
253 
254  # we are doing three things here:
255  # creating a process to catch errors
256  # building the code to re-create the process
257 
259  # TODO: maybe a list of to be dumped objects would help as well
260  self.blacklist_paths = []
261  self.addedObjects = []
263 
269 
270  def profileOptions(self):
271  """
272  addIgProfService
273  Function to add the igprof profile service so that you can dump in the middle
274  of the run.
275  """
276  profileOpts = self._options.profile.split(':')
277  profilerStart = 1
278  profilerInterval = 100
279  profilerFormat = None
280  profilerJobFormat = None
281 
282  if len(profileOpts):
283  #type, given as first argument is unused here
284  profileOpts.pop(0)
285  if len(profileOpts):
286  startEvent = profileOpts.pop(0)
287  if not startEvent.isdigit():
288  raise Exception("%s is not a number" % startEvent)
289  profilerStart = int(startEvent)
290  if len(profileOpts):
291  eventInterval = profileOpts.pop(0)
292  if not eventInterval.isdigit():
293  raise Exception("%s is not a number" % eventInterval)
294  profilerInterval = int(eventInterval)
295  if len(profileOpts):
296  profilerFormat = profileOpts.pop(0)
297 
298 
299  if not profilerFormat:
300  profilerFormat = "%s___%s___%%I.gz" % (
301  self._options.evt_type.replace("_cfi", ""),
302  hashlib.md5(
303  str(self._options.step) + str(self._options.pileup) + str(self._options.conditions) +
304  str(self._options.datatier) + str(self._options.profileTypeLabel)
305  ).hexdigest()
306  )
307  if not profilerJobFormat and profilerFormat.endswith(".gz"):
308  profilerJobFormat = profilerFormat.replace(".gz", "_EndOfJob.gz")
309  elif not profilerJobFormat:
310  profilerJobFormat = profilerFormat + "_EndOfJob.gz"
311 
312  return (profilerStart,profilerInterval,profilerFormat,profilerJobFormat)
313 
314  def load(self,includeFile):
315  includeFile = includeFile.replace('/','.')
316  self.process.load(includeFile)
317  return sys.modules[includeFile]
318 
319  def loadAndRemember(self, includeFile):
320  """helper routine to load am memorize imports"""
321  # we could make the imports a on-the-fly data method of the process instance itself
322  # not sure if the latter is a good idea
323  includeFile = includeFile.replace('/','.')
324  self.imports.append(includeFile)
325  self.process.load(includeFile)
326  return sys.modules[includeFile]
327 
328  def executeAndRemember(self, command):
329  """helper routine to remember replace statements"""
330  self.additionalCommands.append(command)
331  if not command.strip().startswith("#"):
332  # substitute: process.foo = process.bar -> self.process.foo = self.process.bar
333  import re
334  exec(re.sub(r"([^a-zA-Z_0-9]|^)(process)([^a-zA-Z_0-9])",r"\1self.process\3",command))
335  #exec(command.replace("process.","self.process."))
336 
337  def addCommon(self):
338  if 'HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys():
339  self.process.options = cms.untracked.PSet( Rethrow = cms.untracked.vstring('ProductNotFound'),fileMode = cms.untracked.string('FULLMERGE'))
340  else:
341  self.process.options = cms.untracked.PSet( )
342 
343  self.addedObjects.append(("","options"))
344 
345  if self._options.lazy_download:
346  self.process.AdaptorConfig = cms.Service("AdaptorConfig",
347  stats = cms.untracked.bool(True),
348  enable = cms.untracked.bool(True),
349  cacheHint = cms.untracked.string("lazy-download"),
350  readHint = cms.untracked.string("read-ahead-buffered")
351  )
352  self.addedObjects.append(("Setup lazy download","AdaptorConfig"))
353 
354  #self.process.cmsDriverCommand = cms.untracked.PSet( command=cms.untracked.string('cmsDriver.py '+self._options.arguments) )
355  #self.addedObjects.append(("what cmsDriver command was used","cmsDriverCommand"))
356 
357  if self._options.profile:
358  (start, interval, eventFormat, jobFormat)=self.profileOptions()
359  self.process.IgProfService = cms.Service("IgProfService",
360  reportFirstEvent = cms.untracked.int32(start),
361  reportEventInterval = cms.untracked.int32(interval),
362  reportToFileAtPostEvent = cms.untracked.string("| gzip -c > %s"%(eventFormat)),
363  reportToFileAtPostEndJob = cms.untracked.string("| gzip -c > %s"%(jobFormat)))
364  self.addedObjects.append(("Setup IGProf Service for profiling","IgProfService"))
365 
366  def addMaxEvents(self):
367  """Here we decide how many evts will be processed"""
368  self.process.maxEvents=cms.untracked.PSet(input=cms.untracked.int32(int(self._options.number)))
369  if self._options.number_out:
370  self.process.maxEvents.output = cms.untracked.int32(int(self._options.number_out))
371  self.addedObjects.append(("","maxEvents"))
372 
373  def addSource(self):
374  """Here the source is built. Priority: file, generator"""
375  self.addedObjects.append(("Input source","source"))
376 
377  def filesFromOption(self):
378  for entry in self._options.filein.split(','):
379  print("entry",entry)
380  if entry.startswith("filelist:"):
381  filesFromList(entry[9:],self.process.source)
382  elif entry.startswith("dbs:") or entry.startswith("das:"):
383  filesFromDASQuery('file dataset = %s'%(entry[4:]),self._options.dasoption,self.process.source)
384  else:
385  self.process.source.fileNames.append(self._options.dirin+entry)
386  if self._options.secondfilein:
387  if not hasattr(self.process.source,"secondaryFileNames"):
388  raise Exception("--secondfilein not compatible with "+self._options.filetype+"input type")
389  for entry in self._options.secondfilein.split(','):
390  print("entry",entry)
391  if entry.startswith("filelist:"):
392  self.process.source.secondaryFileNames.extend((filesFromList(entry[9:]))[0])
393  elif entry.startswith("dbs:") or entry.startswith("das:"):
394  self.process.source.secondaryFileNames.extend((filesFromDASQuery('file dataset = %s'%(entry[4:]),self._options.dasoption))[0])
395  else:
396  self.process.source.secondaryFileNames.append(self._options.dirin+entry)
397 
398  if self._options.filein or self._options.dasquery:
399  if self._options.filetype == "EDM":
400  self.process.source=cms.Source("PoolSource",
401  fileNames = cms.untracked.vstring(),
402  secondaryFileNames= cms.untracked.vstring())
403  filesFromOption(self)
404  elif self._options.filetype == "DAT":
405  self.process.source=cms.Source("NewEventStreamFileReader",fileNames = cms.untracked.vstring())
406  filesFromOption(self)
407  elif self._options.filetype == "LHE":
408  self.process.source=cms.Source("LHESource", fileNames = cms.untracked.vstring())
409  if self._options.filein.startswith("lhe:"):
410  #list the article directory automatically
411  args=self._options.filein.split(':')
412  article=args[1]
413  print('LHE input from article ',article)
414  location='/store/lhe/'
415  import os
416  textOfFiles=os.popen('cmsLHEtoEOSManager.py -l '+article)
417  for line in textOfFiles:
418  for fileName in [x for x in line.split() if '.lhe' in x]:
419  self.process.source.fileNames.append(location+article+'/'+fileName)
420  #check first if list of LHE files is loaded (not empty)
421  if len(line)<2:
422  print('Issue to load LHE files, please check and try again.')
423  sys.exit(-1)
424  #Additional check to protect empty fileNames in process.source
425  if len(self.process.source.fileNames)==0:
426  print('Issue with empty filename, but can pass line check')
427  sys.exit(-1)
428  if len(args)>2:
429  self.process.source.skipEvents = cms.untracked.uint32(int(args[2]))
430  else:
431  filesFromOption(self)
432 
433  elif self._options.filetype == "DQM":
434  self.process.source=cms.Source("DQMRootSource",
435  fileNames = cms.untracked.vstring())
436  filesFromOption(self)
437 
438  elif self._options.filetype == "DQMDAQ":
439  # FIXME: how to configure it if there are no input files specified?
440  self.process.source=cms.Source("DQMStreamerReader")
441 
442 
443  if ('HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys()) and (not self._options.filetype == "DQM"):
444  self.process.source.processingMode = cms.untracked.string("RunsAndLumis")
445 
446  if self._options.dasquery!='':
447  self.process.source=cms.Source("PoolSource", fileNames = cms.untracked.vstring(),secondaryFileNames = cms.untracked.vstring())
448  filesFromDASQuery(self._options.dasquery,self._options.dasoption,self.process.source)
449 
450  if ('HARVESTING' in self.stepMap.keys() or 'ALCAHARVEST' in self.stepMap.keys()) and (not self._options.filetype == "DQM"):
451  self.process.source.processingMode = cms.untracked.string("RunsAndLumis")
452 
453 
454  if 'GEN' in self.stepMap.keys() and not self._options.filetype == "LHE":
455  if self._options.inputCommands:
456  self._options.inputCommands+=',drop LHEXMLStringProduct_*_*_*,'
457  else:
458  self._options.inputCommands='keep *, drop LHEXMLStringProduct_*_*_*,'
459 
460  if self.process.source and self._options.inputCommands and not self._options.filetype == "LHE":
461  if not hasattr(self.process.source,'inputCommands'): self.process.source.inputCommands=cms.untracked.vstring()
462  for command in self._options.inputCommands.split(','):
463  # remove whitespace around the keep/drop statements
464  command = command.strip()
465  if command=='': continue
466  self.process.source.inputCommands.append(command)
467  if not self._options.dropDescendant:
468  self.process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(False)
469 
470  if self._options.lumiToProcess:
471  import FWCore.PythonUtilities.LumiList as LumiList
472  self.process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange( LumiList.LumiList(self._options.lumiToProcess).getCMSSWString().split(',') )
473 
474  if 'GEN' in self.stepMap.keys() or 'LHE' in self.stepMap or (not self._options.filein and hasattr(self._options, "evt_type")):
475  if self.process.source is None:
476  self.process.source=cms.Source("EmptySource")
477 
478  # modify source in case of run-dependent MC
479  self.runsAndWeights=None
480  if self._options.runsAndWeightsForMC or self._options.runsScenarioForMC :
481  if not self._options.isMC :
482  raise Exception("options --runsAndWeightsForMC and --runsScenarioForMC are only valid for MC")
483  if self._options.runsAndWeightsForMC:
484  self.runsAndWeights = eval(self._options.runsAndWeightsForMC)
485  else:
486  from Configuration.StandardSequences.RunsAndWeights import RunsAndWeights
487  if isinstance(RunsAndWeights[self._options.runsScenarioForMC], str):
488  __import__(RunsAndWeights[self._options.runsScenarioForMC])
489  self.runsAndWeights = sys.modules[RunsAndWeights[self._options.runsScenarioForMC]].runProbabilityDistribution
490  else:
491  self.runsAndWeights = RunsAndWeights[self._options.runsScenarioForMC]
492 
493  if self.runsAndWeights:
494  import SimGeneral.Configuration.ThrowAndSetRandomRun as ThrowAndSetRandomRun
496  self.additionalCommands.append('import SimGeneral.Configuration.ThrowAndSetRandomRun as ThrowAndSetRandomRun')
497  self.additionalCommands.append('ThrowAndSetRandomRun.throwAndSetRandomRun(process.source,%s)'%(self.runsAndWeights))
498 
499  return
500 
501  def addOutput(self):
502  """ Add output module to the process """
503  result=""
504  if self._options.outputDefinition:
505  if self._options.datatier:
506  print("--datatier & --eventcontent options ignored")
507 
508  #new output convention with a list of dict
509  outList = eval(self._options.outputDefinition)
510  for (id,outDefDict) in enumerate(outList):
511  outDefDictStr=outDefDict.__str__()
512  if not isinstance(outDefDict,dict):
513  raise Exception("--output needs to be passed a list of dict"+self._options.outputDefinition+" is invalid")
514  #requires option: tier
515  theTier=anyOf(['t','tier','dataTier'],outDefDict)
516  #optional option: eventcontent, filtername, selectEvents, moduleLabel, filename
517 
518  theStreamType=anyOf(['e','ec','eventContent','streamType'],outDefDict,theTier)
519  theFilterName=anyOf(['f','ftN','filterName'],outDefDict,'')
520  theSelectEvent=anyOf(['s','sE','selectEvents'],outDefDict,'')
521  theModuleLabel=anyOf(['l','mL','moduleLabel'],outDefDict,'')
522  theExtraOutputCommands=anyOf(['o','oC','outputCommands'],outDefDict,'')
523  # module label has a particular role
524  if not theModuleLabel:
525  tryNames=[theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+'output',
526  theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+theFilterName+'output',
527  theStreamType.replace(theTier.replace('-',''),'')+theTier.replace('-','')+theFilterName+theSelectEvent.split(',')[0].replace(':','for').replace(' ','')+'output'
528  ]
529  for name in tryNames:
530  if not hasattr(self.process,name):
531  theModuleLabel=name
532  break
533  if not theModuleLabel:
534  raise Exception("cannot find a module label for specification: "+outDefDictStr)
535  if id==0:
536  defaultFileName=self._options.outfile_name
537  else:
538  defaultFileName=self._options.outfile_name.replace('.root','_in'+theTier+'.root')
539 
540  theFileName=self._options.dirout+anyOf(['fn','fileName'],outDefDict,defaultFileName)
541  if not theFileName.endswith('.root'):
542  theFileName+='.root'
543 
544  if len(outDefDict):
545  raise Exception("unused keys from --output options: "+','.join(outDefDict.keys()))
546  if theStreamType=='DQMIO': theStreamType='DQM'
547  if theStreamType=='ALL':
548  theEventContent = cms.PSet(outputCommands = cms.untracked.vstring('keep *'))
549  else:
550  theEventContent = getattr(self.process, theStreamType+"EventContent")
551 
552 
553  addAlCaSelects=False
554  if theStreamType=='ALCARECO' and not theFilterName:
555  theFilterName='StreamALCACombined'
556  addAlCaSelects=True
557 
558  CppType='PoolOutputModule'
559  if self._options.timeoutOutput:
560  CppType='TimeoutPoolOutputModule'
561  if theStreamType=='DQM' and theTier=='DQMIO': CppType='DQMRootOutputModule'
562  output = cms.OutputModule(CppType,
563  theEventContent.clone(),
564  fileName = cms.untracked.string(theFileName),
565  dataset = cms.untracked.PSet(
566  dataTier = cms.untracked.string(theTier),
567  filterName = cms.untracked.string(theFilterName))
568  )
569  if not theSelectEvent and hasattr(self.process,'generation_step') and theStreamType!='LHE':
570  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('generation_step'))
571  if not theSelectEvent and hasattr(self.process,'filtering_step'):
572  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filtering_step'))
573  if theSelectEvent:
574  output.SelectEvents =cms.untracked.PSet(SelectEvents = cms.vstring(theSelectEvent))
575 
576  if addAlCaSelects:
577  if not hasattr(output,'SelectEvents'):
578  output.SelectEvents=cms.untracked.PSet(SelectEvents=cms.vstring())
579  for alca in self.AlCaPaths:
580  output.SelectEvents.SelectEvents.extend(getattr(self.process,'OutALCARECO'+alca).SelectEvents.SelectEvents)
581 
582 
583  if hasattr(self.process,theModuleLabel):
584  raise Exception("the current process already has a module "+theModuleLabel+" defined")
585  #print "creating output module ",theModuleLabel
586  setattr(self.process,theModuleLabel,output)
587  outputModule=getattr(self.process,theModuleLabel)
588  setattr(self.process,theModuleLabel+'_step',cms.EndPath(outputModule))
589  path=getattr(self.process,theModuleLabel+'_step')
590  self.schedule.append(path)
591 
592  if not self._options.inlineEventContent and hasattr(self.process,theStreamType+"EventContent"):
593  def doNotInlineEventContent(instance,label = "cms.untracked.vstring(process."+theStreamType+"EventContent.outputCommands)"): return label
594  outputModule.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
595  if theExtraOutputCommands:
596  if not isinstance(theExtraOutputCommands,list):
597  raise Exception("extra ouput command in --option must be a list of strings")
598  if hasattr(self.process,theStreamType+"EventContent"):
599  self.executeAndRemember('process.%s.outputCommands.extend(%s)'%(theModuleLabel,theExtraOutputCommands))
600  else:
601  outputModule.outputCommands.extend(theExtraOutputCommands)
602 
603  result+="\nprocess."+theModuleLabel+" = "+outputModule.dumpPython()
604 
605 
606  return result
607 
608  streamTypes=self._options.eventcontent.split(',')
609  tiers=self._options.datatier.split(',')
610  if not self._options.outputDefinition and len(streamTypes)!=len(tiers):
611  raise Exception("number of event content arguments does not match number of datatier arguments")
612 
613  # if the only step is alca we don't need to put in an output
614  if self._options.step.split(',')[0].split(':')[0] == 'ALCA':
615  return "\n"
616 
617  for i,(streamType,tier) in enumerate(zip(streamTypes,tiers)):
618  if streamType=='': continue
619  if streamType == 'ALCARECO' and not 'ALCAPRODUCER' in self._options.step: continue
620  if streamType=='DQMIO': streamType='DQM'
621  eventContent=streamType
622 
623  if streamType == "NANOEDMAOD" :
624  eventContent = "NANOAOD"
625  elif streamType == "NANOEDMAODSIM" :
626  eventContent = "NANOAODSIM"
627  theEventContent = getattr(self.process, eventContent+"EventContent")
628  if i==0:
629  theFileName=self._options.outfile_name
630  theFilterName=self._options.filtername
631  else:
632  theFileName=self._options.outfile_name.replace('.root','_in'+streamType+'.root')
633  theFilterName=self._options.filtername
634  CppType='PoolOutputModule'
635  if self._options.timeoutOutput:
636  CppType='TimeoutPoolOutputModule'
637  if streamType=='DQM' and tier=='DQMIO': CppType='DQMRootOutputModule'
638  if "NANOAOD" in streamType : CppType='NanoAODOutputModule'
639  output = cms.OutputModule(CppType,
640  theEventContent,
641  fileName = cms.untracked.string(theFileName),
642  dataset = cms.untracked.PSet(dataTier = cms.untracked.string(tier),
643  filterName = cms.untracked.string(theFilterName)
644  )
645  )
646  if hasattr(self.process,"generation_step") and streamType!='LHE':
647  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('generation_step'))
648  if hasattr(self.process,"filtering_step"):
649  output.SelectEvents = cms.untracked.PSet(SelectEvents = cms.vstring('filtering_step'))
650 
651  if streamType=='ALCARECO':
652  output.dataset.filterName = cms.untracked.string('StreamALCACombined')
653 
654  if "MINIAOD" in streamType:
655  from PhysicsTools.PatAlgos.slimming.miniAOD_tools import miniAOD_customizeOutput
657 
658  outputModuleName=streamType+'output'
659  setattr(self.process,outputModuleName,output)
660  outputModule=getattr(self.process,outputModuleName)
661  setattr(self.process,outputModuleName+'_step',cms.EndPath(outputModule))
662  path=getattr(self.process,outputModuleName+'_step')
663  self.schedule.append(path)
664 
665  if self._options.outputCommands and streamType!='DQM':
666  for evct in self._options.outputCommands.split(','):
667  if not evct: continue
668  self.executeAndRemember("process.%s.outputCommands.append('%s')"%(outputModuleName,evct.strip()))
669 
670  if not self._options.inlineEventContent:
671  tmpstreamType=streamType
672  if "NANOEDM" in tmpstreamType :
673  tmpstreamType=tmpstreamType.replace("NANOEDM","NANO")
674  def doNotInlineEventContent(instance,label = "process."+tmpstreamType+"EventContent.outputCommands"):
675  return label
676  outputModule.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
677 
678  result+="\nprocess."+outputModuleName+" = "+outputModule.dumpPython()
679 
680  return result
681 
682  def addStandardSequences(self):
683  """
684  Add selected standard sequences to the process
685  """
686  # load the pile up file
687  if self._options.pileup:
688  pileupSpec=self._options.pileup.split(',')[0]
689 
690  # Does the requested pile-up scenario exist?
691  from Configuration.StandardSequences.Mixing import Mixing,defineMixing
692  if not pileupSpec in Mixing and '.' not in pileupSpec and 'file:' not in pileupSpec:
693  message = pileupSpec+' is not a know mixing scenario:\n available are: '+'\n'.join(Mixing.keys())
694  raise Exception(message)
695 
696  # Put mixing parameters in a dictionary
697  if '.' in pileupSpec:
698  mixingDict={'file':pileupSpec}
699  elif pileupSpec.startswith('file:'):
700  mixingDict={'file':pileupSpec[5:]}
701  else:
702  import copy
703  mixingDict=copy.copy(Mixing[pileupSpec])
704  if len(self._options.pileup.split(','))>1:
705  mixingDict.update(eval(self._options.pileup[self._options.pileup.find(',')+1:]))
706 
707  # Load the pu cfg file corresponding to the requested pu scenario
708  if 'file:' in pileupSpec:
709  #the file is local
710  self.process.load(mixingDict['file'])
711  print("inlining mixing module configuration")
712  self._options.inlineObjets+=',mix'
713  else:
714  self.loadAndRemember(mixingDict['file'])
715 
716  mixingDict.pop('file')
717  if not "DATAMIX" in self.stepMap.keys(): # when DATAMIX is present, pileup_input refers to pre-mixed GEN-RAW
718  if self._options.pileup_input:
719  if self._options.pileup_input.startswith('dbs:') or self._options.pileup_input.startswith('das:'):
720  mixingDict['F']=filesFromDASQuery('file dataset = %s'%(self._options.pileup_input[4:],),self._options.pileup_dasoption)[0]
721  elif self._options.pileup_input.startswith("filelist:"):
722  mixingDict['F']=(filesFromList(self._options.pileup_input[9:]))[0]
723  else:
724  mixingDict['F']=self._options.pileup_input.split(',')
725  specialization=defineMixing(mixingDict)
726  for command in specialization:
727  self.executeAndRemember(command)
728  if len(mixingDict)!=0:
729  raise Exception('unused mixing specification: '+mixingDict.keys().__str__())
730 
731 
732  # load the geometry file
733  try:
734  if len(self.stepMap):
735  self.loadAndRemember(self.GeometryCFF)
736  if ('SIM' in self.stepMap or 'reSIM' in self.stepMap) and not self._options.fast:
738  if self.geometryDBLabel:
739  self.executeAndRemember('process.XMLFromDBSource.label = cms.string("%s")'%(self.geometryDBLabel))
740  except ImportError:
741  print("Geometry option",self._options.geometry,"unknown.")
742  raise
743 
744  if len(self.stepMap):
745  self.loadAndRemember(self.magFieldCFF)
746 
747  for stepName in self.stepKeys:
748  stepSpec = self.stepMap[stepName]
749  print("Step:", stepName,"Spec:",stepSpec)
750  if stepName.startswith('re'):
751 
752  if stepName[2:] not in self._options.donotDropOnInput:
753  self._options.inputEventContent='%s,%s'%(stepName.upper(),self._options.inputEventContent)
754  stepName=stepName[2:]
755  if stepSpec=="":
756  getattr(self,"prepare_"+stepName)(sequence = getattr(self,stepName+"DefaultSeq"))
757  elif isinstance(stepSpec, list):
758  getattr(self,"prepare_"+stepName)(sequence = '+'.join(stepSpec))
759  elif isinstance(stepSpec, tuple):
760  getattr(self,"prepare_"+stepName)(sequence = ','.join([stepSpec[1],'+'.join(stepSpec[0])]))
761  else:
762  raise ValueError("Invalid step definition")
763 
764  if self._options.restoreRNDSeeds!=False:
765  #it is either True, or a process name
766  if self._options.restoreRNDSeeds==True:
767  self.executeAndRemember('process.RandomNumberGeneratorService.restoreStateLabel=cms.untracked.string("randomEngineStateProducer")')
768  else:
769  self.executeAndRemember('process.RandomNumberGeneratorService.restoreStateTag=cms.untracked.InputTag("randomEngineStateProducer","","%s")'%(self._options.restoreRNDSeeds))
770  if self._options.inputEventContent or self._options.inputCommands:
771  if self._options.inputCommands:
772  self._options.inputCommands+='keep *_randomEngineStateProducer_*_*,'
773  else:
774  self._options.inputCommands='keep *_randomEngineStateProducer_*_*,'
775 
776 
777  def completeInputCommand(self):
778  if self._options.inputEventContent:
779  import copy
780  def dropSecondDropStar(iec):
781  #drop occurence of 'drop *' in the list
782  count=0
783  for item in iec:
784  if item=='drop *':
785  if count!=0:
786  iec.remove(item)
787  count+=1
788 
789 
790  if not hasattr(self.process.source,'inputCommands'): self.process.source.inputCommands=cms.untracked.vstring()
791  for evct in self._options.inputEventContent.split(','):
792  if evct=='': continue
793  theEventContent = getattr(self.process, evct+"EventContent")
794  if hasattr(theEventContent,'outputCommands'):
795  self.process.source.inputCommands.extend(copy.copy(theEventContent.outputCommands))
796  if hasattr(theEventContent,'inputCommands'):
797  self.process.source.inputCommands.extend(copy.copy(theEventContent.inputCommands))
798 
799  dropSecondDropStar(self.process.source.inputCommands)
800 
801  if not self._options.dropDescendant:
802  self.process.source.dropDescendantsOfDroppedBranches = cms.untracked.bool(False)
803 
804 
805  return
806 
807  def addConditions(self):
808  """Add conditions to the process"""
809  if not self._options.conditions: return
810 
811  if 'FrontierConditions_GlobalTag' in self._options.conditions:
812  print('using FrontierConditions_GlobalTag in --conditions is not necessary anymore and will be deprecated soon. please update your command line')
813  self._options.conditions = self._options.conditions.replace("FrontierConditions_GlobalTag,",'')
814 
816  from Configuration.AlCa.GlobalTag import GlobalTag
817  self.process.GlobalTag = GlobalTag(self.process.GlobalTag, self._options.conditions, self._options.custom_conditions)
818  self.additionalCommands.append('from Configuration.AlCa.GlobalTag import GlobalTag')
819  self.additionalCommands.append('process.GlobalTag = GlobalTag(process.GlobalTag, %s, %s)' % (repr(self._options.conditions), repr(self._options.custom_conditions)))
820 
821 
822  def addCustomise(self,unsch=0):
823  """Include the customise code """
824 
825  custOpt=[]
826  if unsch==0:
827  for c in self._options.customisation_file:
828  custOpt.extend(c.split(","))
829  else:
830  for c in self._options.customisation_file_unsch:
831  custOpt.extend(c.split(","))
832 
833  custMap=DictTypes.SortedKeysDict()
834  for opt in custOpt:
835  if opt=='': continue
836  if opt.count('.')>1:
837  raise Exception("more than . in the specification:"+opt)
838  fileName=opt.split('.')[0]
839  if opt.count('.')==0: rest='customise'
840  else:
841  rest=opt.split('.')[1]
842  if rest=='py': rest='customise' #catch the case of --customise file.py
843 
844  if fileName in custMap:
845  custMap[fileName].extend(rest.split('+'))
846  else:
847  custMap[fileName]=rest.split('+')
848 
849  if len(custMap)==0:
850  final_snippet='\n'
851  else:
852  final_snippet='\n# customisation of the process.\n'
853 
854  allFcn=[]
855  for opt in custMap:
856  allFcn.extend(custMap[opt])
857  for fcn in allFcn:
858  if allFcn.count(fcn)!=1:
859  raise Exception("cannot specify twice "+fcn+" as a customisation method")
860 
861  for f in custMap:
862  # let python search for that package and do syntax checking at the same time
863  packageName = f.replace(".py","").replace("/",".")
864  __import__(packageName)
865  package = sys.modules[packageName]
866 
867  # now ask the package for its definition and pick .py instead of .pyc
868  customiseFile = re.sub(r'\.pyc$', '.py', package.__file__)
869 
870  final_snippet+='\n# Automatic addition of the customisation function from '+packageName+'\n'
871  if self._options.inline_custom:
872  for line in file(customiseFile,'r'):
873  if "import FWCore.ParameterSet.Config" in line:
874  continue
875  final_snippet += line
876  else:
877  final_snippet += 'from %s import %s \n'%(packageName,','.join(custMap[f]))
878  for fcn in custMap[f]:
879  print("customising the process with",fcn,"from",f)
880  if not hasattr(package,fcn):
881  #bound to fail at run time
882  raise Exception("config "+f+" has no function "+fcn)
883  #execute the command
884  self.process=getattr(package,fcn)(self.process)
885  #and print it in the configuration
886  final_snippet += "\n#call to customisation function "+fcn+" imported from "+packageName
887  final_snippet += "\nprocess = %s(process)\n"%(fcn,)
888 
889  if len(custMap)!=0:
890  final_snippet += '\n# End of customisation functions\n'
891 
892 
893  return final_snippet
894 
895  def addCustomiseCmdLine(self):
896  final_snippet='\n# Customisation from command line\n'
897  if self._options.customise_commands:
898  import string
899  for com in self._options.customise_commands.split('\\n'):
900  com=com.lstrip()
901  self.executeAndRemember(com)
902  final_snippet +='\n'+com
903 
904  return final_snippet
905 
906  #----------------------------------------------------------------------------
907  # here the methods to define the python includes for each step or
908  # conditions
909  #----------------------------------------------------------------------------
910  def define_Configs(self):
911  if len(self.stepMap):
912  self.loadAndRemember('Configuration/StandardSequences/Services_cff')
913  if self._options.particleTable not in defaultOptions.particleTableList:
914  print('Invalid particle table provided. Options are:')
915  print(defaultOptions.particleTable)
916  sys.exit(-1)
917  else:
918  if len(self.stepMap):
919  self.loadAndRemember('SimGeneral.HepPDTESSource.'+self._options.particleTable+'_cfi')
920 
921  self.loadAndRemember('FWCore/MessageService/MessageLogger_cfi')
922 
923  self.ALCADefaultCFF="Configuration/StandardSequences/AlCaRecoStreams_cff"
924  self.GENDefaultCFF="Configuration/StandardSequences/Generator_cff"
925  self.SIMDefaultCFF="Configuration/StandardSequences/Sim_cff"
926  self.DIGIDefaultCFF="Configuration/StandardSequences/Digi_cff"
927  self.DIGI2RAWDefaultCFF="Configuration/StandardSequences/DigiToRaw_cff"
928  self.L1EMDefaultCFF='Configuration/StandardSequences/SimL1Emulator_cff'
929  self.L1MENUDefaultCFF="Configuration/StandardSequences/L1TriggerDefaultMenu_cff"
930  self.HLTDefaultCFF="Configuration/StandardSequences/HLTtable_cff"
931  self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_Data_cff"
932  if self._options.isRepacked: self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_DataMapper_cff"
933  self.L1RecoDefaultCFF="Configuration/StandardSequences/L1Reco_cff"
934  self.L1TrackTriggerDefaultCFF="Configuration/StandardSequences/L1TrackTrigger_cff"
935  self.RECODefaultCFF="Configuration/StandardSequences/Reconstruction_Data_cff"
936  self.RECOSIMDefaultCFF="Configuration/StandardSequences/RecoSim_cff"
937  self.PATDefaultCFF="Configuration/StandardSequences/PAT_cff"
938  self.NANODefaultCFF="PhysicsTools/NanoAOD/nano_cff"
939  self.NANOGENDefaultCFF="PhysicsTools/NanoAOD/nanogen_cff"
940  self.EIDefaultCFF=None
941  self.SKIMDefaultCFF="Configuration/StandardSequences/Skims_cff"
942  self.POSTRECODefaultCFF="Configuration/StandardSequences/PostRecoGenerator_cff"
943  self.VALIDATIONDefaultCFF="Configuration/StandardSequences/Validation_cff"
944  self.L1HwValDefaultCFF = "Configuration/StandardSequences/L1HwVal_cff"
945  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOffline_cff"
946  self.HARVESTINGDefaultCFF="Configuration/StandardSequences/Harvesting_cff"
947  self.ALCAHARVESTDefaultCFF="Configuration/StandardSequences/AlCaHarvesting_cff"
948  self.ENDJOBDefaultCFF="Configuration/StandardSequences/EndOfProcess_cff"
949  self.ConditionsDefaultCFF = "Configuration/StandardSequences/FrontierConditions_GlobalTag_cff"
950  self.CFWRITERDefaultCFF = "Configuration/StandardSequences/CrossingFrameWriter_cff"
951  self.REPACKDefaultCFF="Configuration/StandardSequences/DigiToRaw_Repack_cff"
952 
953  if "DATAMIX" in self.stepMap.keys():
954  self.DATAMIXDefaultCFF="Configuration/StandardSequences/DataMixer"+self._options.datamix+"_cff"
955  self.DIGIDefaultCFF="Configuration/StandardSequences/DigiDM_cff"
956  self.DIGI2RAWDefaultCFF="Configuration/StandardSequences/DigiToRawDM_cff"
957  self.L1EMDefaultCFF='Configuration/StandardSequences/SimL1EmulatorDM_cff'
958 
959  self.ALCADefaultSeq=None
960  self.LHEDefaultSeq='externalLHEProducer'
961  self.GENDefaultSeq='pgen'
962  self.SIMDefaultSeq='psim'
963  self.DIGIDefaultSeq='pdigi'
965  self.DIGI2RAWDefaultSeq='DigiToRaw'
966  self.HLTDefaultSeq='GRun'
967  self.L1DefaultSeq=None
972  self.RAW2DIGIDefaultSeq='RawToDigi'
973  self.L1RecoDefaultSeq='L1Reco'
974  self.L1TrackTriggerDefaultSeq='L1TrackTrigger'
975  if self._options.fast or ('RAW2DIGI' in self.stepMap and 'RECO' in self.stepMap):
976  self.RECODefaultSeq='reconstruction'
977  else:
978  self.RECODefaultSeq='reconstruction_fromRECO'
979  self.RECOSIMDefaultSeq='recosim'
980  self.EIDefaultSeq='top'
982  self.L1HwValDefaultSeq='L1HwVal'
983  self.DQMDefaultSeq='DQMOffline'
985  self.ENDJOBDefaultSeq='endOfProcess'
986  self.REPACKDefaultSeq='DigiToRawRepack'
987  self.PATDefaultSeq='miniAOD'
988  self.PATGENDefaultSeq='miniGEN'
989  #TODO: Check based of file input
990  self.NANOGENDefaultSeq='nanogenSequence'
991  self.NANODefaultSeq='nanoSequence'
992 
993  self.EVTCONTDefaultCFF="Configuration/EventContent/EventContent_cff"
994 
995  if not self._options.beamspot:
996  self._options.beamspot=VtxSmearedDefaultKey
997 
998  # if its MC then change the raw2digi
999  if self._options.isMC==True:
1000  self.RAW2DIGIDefaultCFF="Configuration/StandardSequences/RawToDigi_cff"
1001  self.RECODefaultCFF="Configuration/StandardSequences/Reconstruction_cff"
1002  self.PATDefaultCFF="Configuration/StandardSequences/PATMC_cff"
1003  self.PATGENDefaultCFF="Configuration/StandardSequences/PATGEN_cff"
1004  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineMC_cff"
1005  self.ALCADefaultCFF="Configuration/StandardSequences/AlCaRecoStreamsMC_cff"
1006  self.NANODefaultSeq='nanoSequenceMC'
1007  else:
1008  self._options.beamspot = None
1009 
1010  #patch for gen, due to backward incompatibility
1011  if 'reGEN' in self.stepMap:
1012  self.GENDefaultSeq='fixGenInfo'
1013 
1014  if self._options.scenario=='cosmics':
1015  self._options.pileup='Cosmics'
1016  self.DIGIDefaultCFF="Configuration/StandardSequences/DigiCosmics_cff"
1017  self.RECODefaultCFF="Configuration/StandardSequences/ReconstructionCosmics_cff"
1018  self.SKIMDefaultCFF="Configuration/StandardSequences/SkimsCosmics_cff"
1019  self.EVTCONTDefaultCFF="Configuration/EventContent/EventContentCosmics_cff"
1020  self.VALIDATIONDefaultCFF="Configuration/StandardSequences/ValidationCosmics_cff"
1021  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineCosmics_cff"
1022  if self._options.isMC==True:
1023  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineCosmicsMC_cff"
1024  self.HARVESTINGDefaultCFF="Configuration/StandardSequences/HarvestingCosmics_cff"
1025  self.RECODefaultSeq='reconstructionCosmics'
1026  self.DQMDefaultSeq='DQMOfflineCosmics'
1027 
1028  if self._options.scenario=='HeavyIons':
1029  if not self._options.beamspot:
1030  self._options.beamspot=VtxSmearedHIDefaultKey
1031  self.HLTDefaultSeq = 'HIon'
1032  self.VALIDATIONDefaultCFF="Configuration/StandardSequences/ValidationHeavyIons_cff"
1033  self.VALIDATIONDefaultSeq=''
1034  self.EVTCONTDefaultCFF="Configuration/EventContent/EventContentHeavyIons_cff"
1035  self.RECODefaultCFF="Configuration/StandardSequences/ReconstructionHeavyIons_cff"
1036  self.RECODefaultSeq='reconstructionHeavyIons'
1037  self.ALCADefaultCFF = "Configuration/StandardSequences/AlCaRecoStreamsHeavyIons_cff"
1038  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineHeavyIons_cff"
1039  self.DQMDefaultSeq='DQMOfflineHeavyIons'
1040  self.SKIMDefaultCFF="Configuration/StandardSequences/SkimsHeavyIons_cff"
1041  self.HARVESTINGDefaultCFF="Configuration/StandardSequences/HarvestingHeavyIons_cff"
1042  if self._options.isMC==True:
1043  self.DQMOFFLINEDefaultCFF="DQMOffline/Configuration/DQMOfflineHeavyIonsMC_cff"
1044 
1045 
1048  self.USERDefaultSeq='user'
1049  self.USERDefaultCFF=None
1051  # the magnetic field
1052  self.magFieldCFF = 'Configuration/StandardSequences/MagneticField_'+self._options.magField.replace('.','')+'_cff'
1053  self.magFieldCFF = self.magFieldCFF.replace("__",'_')
1054 
1055  # the geometry
1056  self.GeometryCFF='Configuration/StandardSequences/GeometryRecoDB_cff'
1058  simGeometry=''
1059  if self._options.fast:
1060  if 'start' in self._options.conditions.lower():
1061  self.GeometryCFF='FastSimulation/Configuration/Geometries_START_cff'
1062  else:
1063  self.GeometryCFF='FastSimulation/Configuration/Geometries_MC_cff'
1064  else:
1065  def inGeometryKeys(opt):
1066  from Configuration.StandardSequences.GeometryConf import GeometryConf
1067  if opt in GeometryConf:
1068  return GeometryConf[opt]
1069  else:
1070  return opt
1071 
1072  geoms=self._options.geometry.split(',')
1073  if len(geoms)==1: geoms=inGeometryKeys(geoms[0]).split(',')
1074  if len(geoms)==2:
1075  #may specify the reco geometry
1076  if '/' in geoms[1] or '_cff' in geoms[1]:
1077  self.GeometryCFF=geoms[1]
1078  else:
1079  self.GeometryCFF='Configuration/Geometry/Geometry'+geoms[1]+'_cff'
1080 
1081  if (geoms[0].startswith('DB:')):
1082  self.SimGeometryCFF='Configuration/StandardSequences/GeometrySimDB_cff'
1083  self.geometryDBLabel=geoms[0][3:]
1084  print("with DB:")
1085  else:
1086  if '/' in geoms[0] or '_cff' in geoms[0]:
1087  self.SimGeometryCFF=geoms[0]
1088  else:
1089  simGeometry=geoms[0]
1090  if self._options.gflash==True:
1091  self.SimGeometryCFF='Configuration/Geometry/Geometry'+geoms[0]+'GFlash_cff'
1092  else:
1093  self.SimGeometryCFF='Configuration/Geometry/Geometry'+geoms[0]+'_cff'
1094 
1095  # synchronize the geometry configuration and the FullSimulation sequence to be used
1096  if simGeometry not in defaultOptions.geometryExtendedOptions:
1097  self.SIMDefaultCFF="Configuration/StandardSequences/SimIdeal_cff"
1098 
1099  if self._options.scenario=='nocoll' or self._options.scenario=='cosmics':
1100  self.SIMDefaultCFF="Configuration/StandardSequences/SimNOBEAM_cff"
1101  self._options.beamspot='NoSmear'
1102 
1103  # fastsim requires some changes to the default cff files and sequences
1104  if self._options.fast:
1105  self.SIMDefaultCFF = 'FastSimulation.Configuration.SimIdeal_cff'
1106  self.RECODefaultCFF= 'FastSimulation.Configuration.Reconstruction_AftMix_cff'
1107  self.RECOBEFMIXDefaultCFF = 'FastSimulation.Configuration.Reconstruction_BefMix_cff'
1108  self.RECOBEFMIXDefaultSeq = 'reconstruction_befmix'
1109  self.NANODefaultSeq = 'nanoSequenceFS'
1110  self.DQMOFFLINEDefaultCFF="DQMOffline.Configuration.DQMOfflineFS_cff"
1111 
1112  # Mixing
1113  if self._options.pileup=='default':
1114  from Configuration.StandardSequences.Mixing import MixingDefaultKey
1115  self._options.pileup=MixingDefaultKey
1116 
1117 
1118  #not driven by a default cff anymore
1119  if self._options.isData:
1120  self._options.pileup=None
1121 
1122 
1125  # for alca, skims, etc
1126  def addExtraStream(self,name,stream,workflow='full'):
1127  # define output module and go from there
1128  output = cms.OutputModule("PoolOutputModule")
1129  if stream.selectEvents.parameters_().__len__()!=0:
1130  output.SelectEvents = stream.selectEvents
1131  else:
1132  output.SelectEvents = cms.untracked.PSet()
1133  output.SelectEvents.SelectEvents=cms.vstring()
1134  if isinstance(stream.paths,tuple):
1135  for path in stream.paths:
1136  output.SelectEvents.SelectEvents.append(path.label())
1137  else:
1138  output.SelectEvents.SelectEvents.append(stream.paths.label())
1139 
1140 
1141 
1142  if isinstance(stream.content,str):
1143  evtPset=getattr(self.process,stream.content)
1144  for p in evtPset.parameters_():
1145  setattr(output,p,getattr(evtPset,p))
1146  if not self._options.inlineEventContent:
1147  def doNotInlineEventContent(instance,label = "process."+stream.content+".outputCommands"):
1148  return label
1149  output.outputCommands.__dict__["dumpPython"] = doNotInlineEventContent
1150  else:
1151  output.outputCommands = stream.content
1152 
1153 
1154  output.fileName = cms.untracked.string(self._options.dirout+stream.name+'.root')
1155 
1156  output.dataset = cms.untracked.PSet( dataTier = stream.dataTier,
1157  filterName = cms.untracked.string(stream.name))
1158 
1159  if self._options.filtername:
1160  output.dataset.filterName= cms.untracked.string(self._options.filtername+"_"+stream.name)
1161 
1162  #add an automatic flushing to limit memory consumption
1163  output.eventAutoFlushCompressedSize=cms.untracked.int32(5*1024*1024)
1164 
1165  if workflow in ("producers,full"):
1166  if isinstance(stream.paths,tuple):
1167  for path in stream.paths:
1168  self.schedule.append(path)
1169  else:
1170  self.schedule.append(stream.paths)
1171 
1172 
1173  # in case of relvals we don't want to have additional outputs
1174  if (not self._options.relval) and workflow in ("full","output"):
1175  self.additionalOutputs[name] = output
1176  setattr(self.process,name,output)
1177 
1178  if workflow == 'output':
1179  # adjust the select events to the proper trigger results from previous process
1180  filterList = output.SelectEvents.SelectEvents
1181  for i, filter in enumerate(filterList):
1182  filterList[i] = filter+":"+self._options.triggerResultsProcess
1183 
1184  return output
1185 
1186  #----------------------------------------------------------------------------
1187  # here the methods to create the steps. Of course we are doing magic here ;)
1188  # prepare_STEPNAME modifies self.process and what else's needed.
1189  #----------------------------------------------------------------------------
1190 
1191  def loadDefaultOrSpecifiedCFF(self, sequence,defaultCFF):
1192  if ( len(sequence.split('.'))==1 ):
1193  l=self.loadAndRemember(defaultCFF)
1194  elif ( len(sequence.split('.'))==2 ):
1195  l=self.loadAndRemember(sequence.split('.')[0])
1196  sequence=sequence.split('.')[1]
1197  else:
1198  print("sub sequence configuration must be of the form dir/subdir/cff.a+b+c or cff.a")
1199  print(sequence,"not recognized")
1200  raise
1201  return l
1202 
1203  def scheduleSequence(self,seq,prefix,what='Path'):
1204  if '*' in seq:
1205  #create only one path with all sequences in it
1206  for i,s in enumerate(seq.split('*')):
1207  if i==0:
1208  setattr(self.process,prefix,getattr(cms,what)( getattr(self.process, s) ))
1209  else:
1210  p=getattr(self.process,prefix)
1211  tmp = getattr(self.process, s)
1212  if isinstance(tmp, cms.Task):
1213  p.associate(tmp)
1214  else:
1215  p+=tmp
1216  self.schedule.append(getattr(self.process,prefix))
1217  return
1218  else:
1219  #create as many path as many sequences
1220  if not '+' in seq:
1221  if self.nextScheduleIsConditional:
1222  self.conditionalPaths.append(prefix)
1223  setattr(self.process,prefix,getattr(cms,what)( getattr(self.process, seq) ))
1224  self.schedule.append(getattr(self.process,prefix))
1225  else:
1226  for i,s in enumerate(seq.split('+')):
1227  sn=prefix+'%d'%(i)
1228  setattr(self.process,sn,getattr(cms,what)( getattr(self.process, s) ))
1229  self.schedule.append(getattr(self.process,sn))
1230  return
1231 
1232  def scheduleSequenceAtEnd(self,seq,prefix):
1233  self.scheduleSequence(seq,prefix,what='EndPath')
1234  return
1235 
1236  def prepare_ALCAPRODUCER(self, sequence = None):
1237  self.prepare_ALCA(sequence, workflow = "producers")
1238 
1239  def prepare_ALCAOUTPUT(self, sequence = None):
1240  self.prepare_ALCA(sequence, workflow = "output")
1241 
1242  def prepare_ALCA(self, sequence = None, workflow = 'full'):
1243  """ Enrich the process with alca streams """
1244  alcaConfig=self.loadDefaultOrSpecifiedCFF(sequence,self.ALCADefaultCFF)
1245  sequence = sequence.split('.')[-1]
1246 
1247  # decide which ALCA paths to use
1248  alcaList = sequence.split("+")
1249  maxLevel=0
1250  from Configuration.AlCa.autoAlca import autoAlca
1251  # support @X from autoAlca.py, and recursion support: i.e T0:@Mu+@EG+...
1252  self.expandMapping(alcaList,autoAlca)
1253  self.AlCaPaths=[]
1254  for name in alcaConfig.__dict__:
1255  alcastream = getattr(alcaConfig,name)
1256  shortName = name.replace('ALCARECOStream','')
1257  if shortName in alcaList and isinstance(alcastream,cms.FilteredStream):
1258  output = self.addExtraStream(name,alcastream, workflow = workflow)
1259  self.executeAndRemember('process.ALCARECOEventContent.outputCommands.extend(process.OutALCARECO'+shortName+'_noDrop.outputCommands)')
1260  self.AlCaPaths.append(shortName)
1261  if 'DQM' in alcaList:
1262  if not self._options.inlineEventContent and hasattr(self.process,name):
1263  self.executeAndRemember('process.' + name + '.outputCommands.append("keep *_MEtoEDMConverter_*_*")')
1264  else:
1265  output.outputCommands.append("keep *_MEtoEDMConverter_*_*")
1266 
1267  #rename the HLT process name in the alca modules
1268  if self._options.hltProcess or 'HLT' in self.stepMap:
1269  if isinstance(alcastream.paths,tuple):
1270  for path in alcastream.paths:
1271  self.renameHLTprocessInSequence(path.label())
1272  else:
1273  self.renameHLTprocessInSequence(alcastream.paths.label())
1274 
1275  for i in range(alcaList.count(shortName)):
1276  alcaList.remove(shortName)
1277 
1278  # DQM needs a special handling
1279  elif name == 'pathALCARECODQM' and 'DQM' in alcaList:
1280  path = getattr(alcaConfig,name)
1281  self.schedule.append(path)
1282  alcaList.remove('DQM')
1283 
1284  if isinstance(alcastream,cms.Path):
1285  #black list the alca path so that they do not appear in the cfg
1286  self.blacklist_paths.append(alcastream)
1287 
1288 
1289  if len(alcaList) != 0:
1290  available=[]
1291  for name in alcaConfig.__dict__:
1292  alcastream = getattr(alcaConfig,name)
1293  if isinstance(alcastream,cms.FilteredStream):
1294  available.append(name.replace('ALCARECOStream',''))
1295  print("The following alcas could not be found "+str(alcaList))
1296  print("available ",available)
1297  #print "verify your configuration, ignoring for now"
1298  raise Exception("The following alcas could not be found "+str(alcaList))
1299 
1300  def prepare_LHE(self, sequence = None):
1301  #load the fragment
1302 
1303  loadFragment = self._options.evt_type.replace('.py','',).replace('.','_').replace('python/','').replace('/','.')
1304  print("Loading lhe fragment from",loadFragment)
1305  __import__(loadFragment)
1306  self.process.load(loadFragment)
1307 
1308  self._options.inlineObjets+=','+sequence
1309 
1310  getattr(self.process,sequence).nEvents = int(self._options.number)
1311 
1312  #schedule it
1313  self.process.lhe_step = cms.Path( getattr( self.process,sequence) )
1314  self.excludedPaths.append("lhe_step")
1315  self.schedule.append( self.process.lhe_step )
1316 
1317  def prepare_GEN(self, sequence = None):
1318  """ load the fragment of generator configuration """
1319  loadFailure=False
1320  #remove trailing .py
1321  #support old style .cfi by changing into something.cfi into something_cfi
1322  #remove python/ from the name
1323  loadFragment = self._options.evt_type.replace('.py','',).replace('.','_').replace('python/','')
1324  #standard location of fragments
1325  if not '/' in loadFragment:
1326  loadFragment='Configuration.Generator.'+loadFragment
1327  else:
1328  loadFragment=loadFragment.replace('/','.')
1329  try:
1330  print("Loading generator fragment from",loadFragment)
1331  __import__(loadFragment)
1332  except:
1333  loadFailure=True
1334  #if self.process.source and self.process.source.type_()=='EmptySource':
1335  if not (self._options.filein or self._options.dasquery):
1336  raise Exception("Neither gen fragment of input files provided: this is an inconsistent GEN step configuration")
1337 
1338  if not loadFailure:
1339  generatorModule=sys.modules[loadFragment]
1340  genModules=generatorModule.__dict__
1341  #remove lhe producer module since this should have been
1342  #imported instead in the LHE step
1343  if self.LHEDefaultSeq in genModules:
1344  del genModules[self.LHEDefaultSeq]
1345 
1346  if self._options.hideGen:
1347  self.loadAndRemember(loadFragment)
1348  else:
1349  self.process.load(loadFragment)
1350  # expose the objects from that fragment to the configuration
1351  import FWCore.ParameterSet.Modules as cmstypes
1352  for name in genModules:
1353  theObject = getattr(generatorModule,name)
1354  if isinstance(theObject, cmstypes._Module):
1355  self._options.inlineObjets=name+','+self._options.inlineObjets
1356  elif isinstance(theObject, cms.Sequence) or isinstance(theObject, cmstypes.ESProducer):
1357  self._options.inlineObjets+=','+name
1358 
1359  if sequence == self.GENDefaultSeq or sequence == 'pgen_genonly':
1360  if 'ProductionFilterSequence' in genModules and ('generator' in genModules):
1361  self.productionFilterSequence = 'ProductionFilterSequence'
1362  elif 'generator' in genModules:
1363  self.productionFilterSequence = 'generator'
1364 
1365  """ Enrich the schedule with the rest of the generation step """
1366  self.loadDefaultOrSpecifiedCFF(sequence,self.GENDefaultCFF)
1367  genSeqName=sequence.split('.')[-1]
1368 
1369  if True:
1370  try:
1371  from Configuration.StandardSequences.VtxSmeared import VtxSmeared
1372  cffToBeLoaded=VtxSmeared[self._options.beamspot]
1373  self.loadAndRemember(cffToBeLoaded)
1374  except ImportError:
1375  raise Exception("VertexSmearing type or beamspot "+self._options.beamspot+" unknown.")
1376 
1377  if self._options.scenario == 'HeavyIons':
1378  if self._options.pileup=='HiMixGEN':
1379  self.loadAndRemember("Configuration/StandardSequences/GeneratorMix_cff")
1380  elif self._options.pileup=='HiMixEmbGEN':
1381  self.loadAndRemember("Configuration/StandardSequences/GeneratorEmbMix_cff")
1382  else:
1383  self.loadAndRemember("Configuration/StandardSequences/GeneratorHI_cff")
1384 
1385  self.process.generation_step = cms.Path( getattr(self.process,genSeqName) )
1386  self.schedule.append(self.process.generation_step)
1387 
1388  #register to the genstepfilter the name of the path (static right now, but might evolve)
1389  self.executeAndRemember('process.genstepfilter.triggerConditions=cms.vstring("generation_step")')
1390 
1391  if 'reGEN' in self.stepMap:
1392  #stop here
1393  return
1394 
1395  """ Enrich the schedule with the summary of the filter step """
1396  #the gen filter in the endpath
1397  self.loadAndRemember("GeneratorInterface/Core/genFilterSummary_cff")
1398  self.scheduleSequenceAtEnd('genFilterSummary','genfiltersummary_step')
1399  return
1400 
1401  def prepare_SIM(self, sequence = None):
1402  """ Enrich the schedule with the simulation step"""
1403  self.loadDefaultOrSpecifiedCFF(sequence,self.SIMDefaultCFF)
1404  if not self._options.fast:
1405  if self._options.gflash==True:
1406  self.loadAndRemember("Configuration/StandardSequences/GFlashSIM_cff")
1407 
1408  if self._options.magField=='0T':
1409  self.executeAndRemember("process.g4SimHits.UseMagneticField = cms.bool(False)")
1410  else:
1411  if self._options.magField=='0T':
1412  self.executeAndRemember("process.fastSimProducer.detectorDefinition.magneticFieldZ = cms.untracked.double(0.)")
1413 
1414  self.scheduleSequence(sequence.split('.')[-1],'simulation_step')
1415  return
1416 
1417  def prepare_DIGI(self, sequence = None):
1418  """ Enrich the schedule with the digitisation step"""
1419  self.loadDefaultOrSpecifiedCFF(sequence,self.DIGIDefaultCFF)
1420 
1421  if self._options.gflash==True:
1422  self.loadAndRemember("Configuration/StandardSequences/GFlashDIGI_cff")
1423 
1424  if sequence == 'pdigi_valid' or sequence == 'pdigi_hi':
1425  self.executeAndRemember("process.mix.digitizers = cms.PSet(process.theDigitizersValid)")
1426 
1427  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":
1428  if self._options.inputEventContent=='':
1429  self._options.inputEventContent='REGEN'
1430  else:
1431  self._options.inputEventContent=self._options.inputEventContent+',REGEN'
1432 
1433 
1434  self.scheduleSequence(sequence.split('.')[-1],'digitisation_step')
1435  return
1436 
1437  def prepare_CFWRITER(self, sequence = None):
1438  """ Enrich the schedule with the crossing frame writer step"""
1440  self.scheduleSequence('pcfw','cfwriter_step')
1441  return
1442 
1443  def prepare_DATAMIX(self, sequence = None):
1444  """ Enrich the schedule with the digitisation step"""
1446  self.scheduleSequence('pdatamix','datamixing_step')
1447 
1448  if self._options.pileup_input:
1449  theFiles=''
1450  if self._options.pileup_input.startswith('dbs:') or self._options.pileup_input.startswith('das:'):
1451  theFiles=filesFromDASQuery('file dataset = %s'%(self._options.pileup_input[4:],),self._options.pileup_dasoption)[0]
1452  elif self._options.pileup_input.startswith("filelist:"):
1453  theFiles= (filesFromList(self._options.pileup_input[9:]))[0]
1454  else:
1455  theFiles=self._options.pileup_input.split(',')
1456  #print theFiles
1457  self.executeAndRemember( "process.mixData.input.fileNames = cms.untracked.vstring(%s)"%( theFiles ) )
1458 
1459  return
1460 
1461  def prepare_DIGI2RAW(self, sequence = None):
1463  self.scheduleSequence(sequence.split('.')[-1],'digi2raw_step')
1464  return
1465 
1466  def prepare_REPACK(self, sequence = None):
1468  self.scheduleSequence(sequence.split('.')[-1],'digi2repack_step')
1469  return
1470 
1471  def prepare_L1(self, sequence = None):
1472  """ Enrich the schedule with the L1 simulation step"""
1473  assert(sequence == None)
1474  self.loadAndRemember(self.L1EMDefaultCFF)
1475  self.scheduleSequence('SimL1Emulator','L1simulation_step')
1476  return
1477 
1478  def prepare_L1REPACK(self, sequence = None):
1479  """ 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"""
1480  supported = ['GT','GT1','GT2','GCTGT','Full','FullSimTP','FullMC','Full2015Data','uGT','CalouGT']
1481  if sequence in supported:
1482  self.loadAndRemember('Configuration/StandardSequences/SimL1EmulatorRepack_%s_cff'%sequence)
1483  if self._options.scenario == 'HeavyIons':
1484  self.renameInputTagsInSequence("SimL1Emulator","rawDataCollector","rawDataRepacker")
1485  self.scheduleSequence('SimL1Emulator','L1RePack_step')
1486  else:
1487  print("L1REPACK with '",sequence,"' is not supported! Supported choices are: ",supported)
1488  raise Exception('unsupported feature')
1489 
1490 
1491  def prepare_HLT(self, sequence = None):
1492  """ Enrich the schedule with the HLT simulation step"""
1493  if not sequence:
1494  print("no specification of the hlt menu has been given, should never happen")
1495  raise Exception('no HLT sequence provided')
1496 
1497  if '@' in sequence:
1498  # case where HLT:@something was provided
1499  from Configuration.HLT.autoHLT import autoHLT
1500  key = sequence[1:]
1501  if key in autoHLT:
1502  sequence = autoHLT[key]
1503  else:
1504  raise ValueError('no HLT mapping key "%s" found in autoHLT' % key)
1505 
1506  if ',' in sequence:
1507  #case where HLT:something:something was provided
1508  self.executeAndRemember('import HLTrigger.Configuration.Utilities')
1509  optionsForHLT = {}
1510  if self._options.scenario == 'HeavyIons':
1511  optionsForHLT['type'] = 'HIon'
1512  else:
1513  optionsForHLT['type'] = 'GRun'
1514  optionsForHLTConfig = ', '.join('%s=%s' % (key, repr(val)) for (key, val) in six.iteritems(optionsForHLT))
1515  if sequence == 'run,fromSource':
1516  if hasattr(self.process.source,'firstRun'):
1517  self.executeAndRemember('process.loadHltConfiguration("run:%%d"%%(process.source.firstRun.value()),%s)'%(optionsForHLTConfig))
1518  elif hasattr(self.process.source,'setRunNumber'):
1519  self.executeAndRemember('process.loadHltConfiguration("run:%%d"%%(process.source.setRunNumber.value()),%s)'%(optionsForHLTConfig))
1520  else:
1521  raise Exception('Cannot replace menu to load %s'%(sequence))
1522  else:
1523  self.executeAndRemember('process.loadHltConfiguration("%s",%s)'%(sequence.replace(',',':'),optionsForHLTConfig))
1524  else:
1525  self.loadAndRemember('HLTrigger/Configuration/HLT_%s_cff' % sequence)
1526 
1527  if self._options.isMC:
1528  self._options.customisation_file.append("HLTrigger/Configuration/customizeHLTforMC.customizeHLTforMC")
1529 
1530  if self._options.name != 'HLT':
1531  self.additionalCommands.append('from HLTrigger.Configuration.CustomConfigs import ProcessName')
1532  self.additionalCommands.append('process = ProcessName(process)')
1533  self.additionalCommands.append('')
1534  from HLTrigger.Configuration.CustomConfigs import ProcessName
1535  self.process = ProcessName(self.process)
1536 
1537  self.schedule.append(self.process.HLTSchedule)
1538  [self.blacklist_paths.append(path) for path in self.process.HLTSchedule if isinstance(path,(cms.Path,cms.EndPath))]
1539 
1540  #this is a fake, to be removed with fastim migration and HLT menu dump
1541  if self._options.fast:
1542  if not hasattr(self.process,'HLTEndSequence'):
1543  self.executeAndRemember("process.HLTEndSequence = cms.Sequence( process.dummyModule )")
1544 
1545 
1546  def prepare_RAW2RECO(self, sequence = None):
1547  if ','in sequence:
1548  seqReco=sequence.split(',')[1]
1549  seqDigi=sequence.split(',')[0]
1550  else:
1551  print("RAW2RECO requires two specifications",sequence,"insufficient")
1552 
1553  self.prepare_RAW2DIGI(seqDigi)
1554  self.prepare_RECO(seqReco)
1555  return
1556 
1557  def prepare_RAW2DIGI(self, sequence = "RawToDigi"):
1559  self.scheduleSequence(sequence,'raw2digi_step')
1560  # if self._options.isRepacked:
1561  #self.renameInputTagsInSequence(sequence)
1562  return
1563 
1564  def prepare_PATFILTER(self, sequence=None):
1565  self.loadAndRemember("PhysicsTools/PatAlgos/slimming/metFilterPaths_cff")
1566  from PhysicsTools.PatAlgos.slimming.metFilterPaths_cff import allMetFilterPaths
1567  for filt in allMetFilterPaths:
1568  self.schedule.append(getattr(self.process,'Flag_'+filt))
1569 
1570  def prepare_L1HwVal(self, sequence = 'L1HwVal'):
1571  ''' Enrich the schedule with L1 HW validation '''
1572  self.loadDefaultOrSpecifiedCFF(sequence,self.L1HwValDefaultCFF)
1573  #self.scheduleSequence(sequence.split('.')[-1],'l1hwval_step')
1574  print('\n\n\n DEPRECATED this has no action \n\n\n')
1575  return
1576 
1577  def prepare_L1Reco(self, sequence = "L1Reco"):
1578  ''' Enrich the schedule with L1 reconstruction '''
1579  self.loadDefaultOrSpecifiedCFF(sequence,self.L1RecoDefaultCFF)
1580  self.scheduleSequence(sequence.split('.')[-1],'L1Reco_step')
1581  return
1582 
1583  def prepare_L1TrackTrigger(self, sequence = "L1TrackTrigger"):
1584  ''' Enrich the schedule with L1 reconstruction '''
1586  self.scheduleSequence(sequence.split('.')[-1],'L1TrackTrigger_step')
1587  return
1588 
1589  def prepare_FILTER(self, sequence = None):
1590  ''' Enrich the schedule with a user defined filter sequence '''
1591 
1592  filterConfig=self.load(sequence.split('.')[0])
1593  filterSeq=sequence.split('.')[-1]
1594 
1595  class PrintAllModules(object):
1596  def __init__(self):
1597  self.inliner=''
1598  pass
1599  def enter(self,visitee):
1600  try:
1601  label=visitee.label()
1602 
1603  self.inliner=label+','+self.inliner
1604  except:
1605  pass
1606  def leave(self,v): pass
1607 
1608  expander=PrintAllModules()
1609  getattr(self.process,filterSeq).visit( expander )
1610  self._options.inlineObjets+=','+expander.inliner
1611  self._options.inlineObjets+=','+filterSeq
1612 
1613 
1614  self.scheduleSequence(filterSeq,'filtering_step')
1615  self.nextScheduleIsConditional=True
1616 
1617  self.productionFilterSequence = filterSeq
1618 
1619  return
1620 
1621  def prepare_RECO(self, sequence = "reconstruction"):
1622  ''' Enrich the schedule with reconstruction '''
1623  self.loadDefaultOrSpecifiedCFF(sequence,self.RECODefaultCFF)
1624  self.scheduleSequence(sequence.split('.')[-1],'reconstruction_step')
1625  return
1626 
1627  def prepare_RECOSIM(self, sequence = "recosim"):
1628  ''' Enrich the schedule with reconstruction '''
1629  self.loadDefaultOrSpecifiedCFF(sequence,self.RECOSIMDefaultCFF)
1630  self.scheduleSequence(sequence.split('.')[-1],'recosim_step')
1631  return
1632 
1633  def prepare_RECOBEFMIX(self, sequence = "reconstruction"):
1634  ''' Enrich the schedule with the part of reconstruction that is done before mixing in FastSim'''
1635  if not self._options.fast:
1636  print("ERROR: this step is only implemented for FastSim")
1637  sys.exit()
1639  self.scheduleSequence(sequence.split('.')[-1],'reconstruction_befmix_step')
1640  return
1641 
1642  def prepare_PAT(self, sequence = "miniAOD"):
1643  ''' Enrich the schedule with PAT '''
1644  self.prepare_PATFILTER(self)
1645  self.loadDefaultOrSpecifiedCFF(sequence,self.PATDefaultCFF)
1646  self.labelsToAssociate.append('patTask')
1647  if self._options.isData:
1648  self._options.customisation_file_unsch.insert(0,"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllData")
1649  else:
1650  if self._options.fast:
1651  self._options.customisation_file_unsch.insert(0,"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllMCFastSim")
1652  else:
1653  self._options.customisation_file_unsch.insert(0,"PhysicsTools/PatAlgos/slimming/miniAOD_tools.miniAOD_customizeAllMC")
1654 
1655  if self._options.hltProcess:
1656  if len(self._options.customise_commands) > 1:
1657  self._options.customise_commands = self._options.customise_commands + " \n"
1658  self._options.customise_commands = self._options.customise_commands + "process.patTrigger.processName = \""+self._options.hltProcess+"\"\n"
1659  self._options.customise_commands = self._options.customise_commands + "process.slimmedPatTrigger.triggerResults= cms.InputTag( 'TriggerResults::"+self._options.hltProcess+"' )\n"
1660  self._options.customise_commands = self._options.customise_commands + "process.patMuons.triggerResults= cms.InputTag( 'TriggerResults::"+self._options.hltProcess+"' )\n"
1661 
1662 # self.renameHLTprocessInSequence(sequence)
1663 
1664  return
1665 
1666  def prepare_PATGEN(self, sequence = "miniGEN"):
1667  ''' Enrich the schedule with PATGEN '''
1668  self.loadDefaultOrSpecifiedCFF(sequence,self.PATGENDefaultCFF) #this is unscheduled
1669  self.labelsToAssociate.append('patGENTask')
1670  if self._options.isData:
1671  raise Exception("PATGEN step can only run on MC")
1672  return
1673 
1674  def prepare_NANO(self, sequence = "nanoAOD"):
1675  ''' Enrich the schedule with NANO '''
1676  self.loadDefaultOrSpecifiedCFF(sequence,self.NANODefaultCFF)
1677  self.scheduleSequence(sequence.split('.')[-1],'nanoAOD_step')
1678  custom = "nanoAOD_customizeData" if self._options.isData else "nanoAOD_customizeMC"
1679  self._options.customisation_file.insert(0,"PhysicsTools/NanoAOD/nano_cff."+custom)
1680  if self._options.hltProcess:
1681  if len(self._options.customise_commands) > 1:
1682  self._options.customise_commands = self._options.customise_commands + " \n"
1683  self._options.customise_commands = self._options.customise_commands + "process.unpackedPatTrigger.triggerResults= cms.InputTag( 'TriggerResults::"+self._options.hltProcess+"' )\n"
1684 
1685  def prepare_NANOGEN(self, sequence = "nanoAOD"):
1686  ''' Enrich the schedule with NANOGEN '''
1687  # TODO: Need to modify this based on the input file type
1688  fromGen = any([x in self.stepMap for x in ['LHE', 'GEN', 'AOD']])
1689  self.loadDefaultOrSpecifiedCFF(sequence,self.NANOGENDefaultCFF)
1690  self.scheduleSequence(sequence.split('.')[-1],'nanoAOD_step')
1691  custom = "customizeNanoGEN" if fromGen else "customizeNanoGENFromMini"
1692  if self._options.runUnscheduled:
1693  self._options.customisation_file_unsch.insert(0, '.'.join([self.NANOGENDefaultCFF, custom]))
1694  else:
1695  self._options.customisation_file.insert(0, '.'.join([self.NANOGENDefaultCFF, custom]))
1696 
1697  def prepare_EI(self, sequence = None):
1698  ''' Enrich the schedule with event interpretation '''
1699  from Configuration.StandardSequences.EventInterpretation import EventInterpretation
1700  if sequence in EventInterpretation:
1701  self.EIDefaultCFF = EventInterpretation[sequence]
1702  sequence = 'EIsequence'
1703  else:
1704  raise Exception('Cannot set %s event interpretation'%( sequence) )
1705  self.loadDefaultOrSpecifiedCFF(sequence,self.EIDefaultCFF)
1706  self.scheduleSequence(sequence.split('.')[-1],'eventinterpretaion_step')
1707  return
1708 
1709  def prepare_SKIM(self, sequence = "all"):
1710  ''' Enrich the schedule with skimming fragments'''
1711  skimConfig = self.loadDefaultOrSpecifiedCFF(sequence,self.SKIMDefaultCFF)
1712  sequence = sequence.split('.')[-1]
1713 
1714  skimlist=sequence.split('+')
1715 
1716  from Configuration.Skimming.autoSkim import autoSkim
1717  self.expandMapping(skimlist,autoSkim)
1718 
1719  #print "dictionnary for skims:",skimConfig.__dict__
1720  for skim in skimConfig.__dict__:
1721  skimstream = getattr(skimConfig,skim)
1722  if isinstance(skimstream,cms.Path):
1723  #black list the alca path so that they do not appear in the cfg
1724  self.blacklist_paths.append(skimstream)
1725  if (not isinstance(skimstream,cms.FilteredStream)):
1726  continue
1727  shortname = skim.replace('SKIMStream','')
1728  if (sequence=="all"):
1729  self.addExtraStream(skim,skimstream)
1730  elif (shortname in skimlist):
1731  self.addExtraStream(skim,skimstream)
1732  #add a DQM eventcontent for this guy
1733  if self._options.datatier=='DQM':
1734  self.process.load(self.EVTCONTDefaultCFF)
1735  skimstreamDQM = cms.FilteredStream(
1736  responsible = skimstream.responsible,
1737  name = skimstream.name+'DQM',
1738  paths = skimstream.paths,
1739  selectEvents = skimstream.selectEvents,
1740  content = self._options.datatier+'EventContent',
1741  dataTier = cms.untracked.string(self._options.datatier)
1742  )
1743  self.addExtraStream(skim+'DQM',skimstreamDQM)
1744  for i in range(skimlist.count(shortname)):
1745  skimlist.remove(shortname)
1746 
1747 
1748 
1749  if (skimlist.__len__()!=0 and sequence!="all"):
1750  print('WARNING, possible typo with SKIM:'+'+'.join(skimlist))
1751  raise Exception('WARNING, possible typo with SKIM:'+'+'.join(skimlist))
1752 
1753  def prepare_USER(self, sequence = None):
1754  ''' Enrich the schedule with a user defined sequence '''
1755  self.loadDefaultOrSpecifiedCFF(sequence,self.USERDefaultCFF)
1756  self.scheduleSequence(sequence.split('.')[-1],'user_step')
1757  return
1758 
1759  def prepare_POSTRECO(self, sequence = None):
1760  """ Enrich the schedule with the postreco step """
1762  self.scheduleSequence('postreco_generator','postreco_step')
1763  return
1764 
1765 
1766  def prepare_VALIDATION(self, sequence = 'validation'):
1767  print(sequence,"in preparing validation")
1769  from Validation.Configuration.autoValidation import autoValidation
1770  #in case VALIDATION:something:somethingelse -> something,somethingelse
1771  sequence=sequence.split('.')[-1]
1772  if sequence.find(',')!=-1:
1773  prevalSeqName=sequence.split(',')[0].split('+')
1774  valSeqName=sequence.split(',')[1].split('+')
1775  self.expandMapping(prevalSeqName,autoValidation,index=0)
1776  self.expandMapping(valSeqName,autoValidation,index=1)
1777  else:
1778  if '@' in sequence:
1779  prevalSeqName=sequence.split('+')
1780  valSeqName=sequence.split('+')
1781  self.expandMapping(prevalSeqName,autoValidation,index=0)
1782  self.expandMapping(valSeqName,autoValidation,index=1)
1783  else:
1784  postfix=''
1785  if sequence:
1786  postfix='_'+sequence
1787  prevalSeqName=['prevalidation'+postfix]
1788  valSeqName=['validation'+postfix]
1789  if not hasattr(self.process,valSeqName[0]):
1790  prevalSeqName=['']
1791  valSeqName=[sequence]
1792 
1793  def NFI(index):
1794 
1795  if index==0:
1796  return ''
1797  else:
1798  return '%s'%index
1799 
1800 
1801  #rename the HLT process in validation steps
1802  if ('HLT' in self.stepMap and not self._options.fast) or self._options.hltProcess:
1803  for s in valSeqName+prevalSeqName:
1804  if s:
1806  for (i,s) in enumerate(prevalSeqName):
1807  if s:
1808  setattr(self.process,'prevalidation_step%s'%NFI(i), cms.Path( getattr(self.process, s)) )
1809  self.schedule.append(getattr(self.process,'prevalidation_step%s'%NFI(i)))
1810 
1811  for (i,s) in enumerate(valSeqName):
1812  setattr(self.process,'validation_step%s'%NFI(i), cms.EndPath( getattr(self.process, s)))
1813  self.schedule.append(getattr(self.process,'validation_step%s'%NFI(i)))
1814 
1815  #needed in case the miniAODValidation sequence is run starting from AODSIM
1816  if 'PAT' in self.stepMap and not 'RECO' in self.stepMap:
1817  return
1818 
1819  if not 'DIGI' in self.stepMap and not self._options.fast and not any(map( lambda s : s.startswith('genvalid'), valSeqName)):
1820  if self._options.restoreRNDSeeds==False and not self._options.restoreRNDSeeds==True:
1821  self._options.restoreRNDSeeds=True
1822 
1823  if not 'DIGI' in self.stepMap and not self._options.fast:
1824  self.executeAndRemember("process.mix.playback = True")
1825  self.executeAndRemember("process.mix.digitizers = cms.PSet()")
1826  self.executeAndRemember("for a in process.aliases: delattr(process, a)")
1827  self._options.customisation_file.append("SimGeneral/MixingModule/fullMixCustomize_cff.setCrossingFrameOn")
1828 
1829  if hasattr(self.process,"genstepfilter") and len(self.process.genstepfilter.triggerConditions):
1830  #will get in the schedule, smoothly
1831  for (i,s) in enumerate(valSeqName):
1832  getattr(self.process,'validation_step%s'%NFI(i)).insert(0, self.process.genstepfilter)
1833 
1834  return
1835 
1836 
1838  """Visitor that travels within a cms.Sequence, looks for a parameter and replace its value
1839  It will climb down within PSets, VPSets and VInputTags to find its target"""
1840  def __init__(self, paramSearch, paramReplace, verbose=False, whitelist=()):
1841  self._paramReplace = paramReplace
1842  self._paramSearch = paramSearch
1843  self._verbose = verbose
1844  self._whitelist = whitelist
1846  def doIt(self,pset,base):
1847  if isinstance(pset, cms._Parameterizable):
1848  for name in pset.parameters_().keys():
1849  # skip whitelisted parameters
1850  if name in self._whitelist:
1851  continue
1852  # if I use pset.parameters_().items() I get copies of the parameter values
1853  # so I can't modify the nested pset
1854  value = getattr(pset,name)
1855  type = value.pythonTypeName()
1856  if type in ('cms.PSet', 'cms.untracked.PSet'):
1857  self.doIt(value,base+"."+name)
1858  elif type in ('cms.VPSet', 'cms.untracked.VPSet'):
1859  for (i,ps) in enumerate(value): self.doIt(ps, "%s.%s[%d]"%(base,name,i) )
1860  elif type in ('cms.string', 'cms.untracked.string'):
1861  if value.value() == self._paramSearch:
1862  if self._verbose: print("set string process name %s.%s %s ==> %s"% (base, name, value, self._paramReplace))
1863  setattr(pset, name,self._paramReplace)
1864  elif type in ('cms.VInputTag', 'cms.untracked.VInputTag'):
1865  for (i,n) in enumerate(value):
1866  if not isinstance(n, cms.InputTag):
1867  n=cms.InputTag(n)
1868  if n.processName == self._paramSearch:
1869  # VInputTag can be declared as a list of strings, so ensure that n is formatted correctly
1870  if self._verbose:print("set process name %s.%s[%d] %s ==> %s " % (base, name, i, n, self._paramReplace))
1871  setattr(n,"processName",self._paramReplace)
1872  value[i]=n
1873  elif type in ('cms.vstring', 'cms.untracked.vstring'):
1874  for (i,n) in enumerate(value):
1875  if n==self._paramSearch:
1876  getattr(pset,name)[i]=self._paramReplace
1877  elif type in ('cms.InputTag', 'cms.untracked.InputTag'):
1878  if value.processName == self._paramSearch:
1879  if self._verbose: print("set process name %s.%s %s ==> %s " % (base, name, value, self._paramReplace))
1880  setattr(getattr(pset, name),"processName",self._paramReplace)
1881 
1882  def enter(self,visitee):
1883  label = ''
1884  try:
1885  label = visitee.label()
1886  except AttributeError:
1887  label = '<Module not in a Process>'
1888  except:
1889  label = 'other execption'
1890  self.doIt(visitee, label)
1891 
1892  def leave(self,visitee):
1893  pass
1894 
1895  #visit a sequence to repalce all input tags
1896  def renameInputTagsInSequence(self,sequence,oldT="rawDataCollector",newT="rawDataRepacker"):
1897  print("Replacing all InputTag %s => %s"%(oldT,newT))
1898  from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag
1899  massSearchReplaceAnyInputTag(getattr(self.process,sequence),oldT,newT)
1900  loadMe='from PhysicsTools.PatAlgos.tools.helpers import massSearchReplaceAnyInputTag'
1901  if not loadMe in self.additionalCommands:
1902  self.additionalCommands.append(loadMe)
1903  self.additionalCommands.append('massSearchReplaceAnyInputTag(process.%s,"%s","%s",False,True)'%(sequence,oldT,newT))
1904 
1905  #change the process name used to address HLT results in any sequence
1906  def renameHLTprocessInSequence(self,sequence,proc=None,HLTprocess='HLT'):
1907  if self._options.hltProcess:
1908  proc=self._options.hltProcess
1909  else:
1910  proc=self.process.name_()
1911  if proc==HLTprocess: return
1912  # look up all module in dqm sequence
1913  print("replacing %s process name - sequence %s will use '%s'" % (HLTprocess,sequence, proc))
1914  getattr(self.process,sequence).visit(ConfigBuilder.MassSearchReplaceProcessNameVisitor(HLTprocess,proc,whitelist = ("subSystemFolder",)))
1915  if 'from Configuration.Applications.ConfigBuilder import ConfigBuilder' not in self.additionalCommands:
1916  self.additionalCommands.append('from Configuration.Applications.ConfigBuilder import ConfigBuilder')
1917  self.additionalCommands.append('process.%s.visit(ConfigBuilder.MassSearchReplaceProcessNameVisitor("%s", "%s", whitelist = ("subSystemFolder",)))'% (sequence,HLTprocess, proc))
1918 
1919 
1920  def expandMapping(self,seqList,mapping,index=None):
1921  maxLevel=30
1922  level=0
1923  while '@' in repr(seqList) and level<maxLevel:
1924  level+=1
1925  for specifiedCommand in seqList:
1926  if specifiedCommand.startswith('@'):
1927  location=specifiedCommand[1:]
1928  if not location in mapping:
1929  raise Exception("Impossible to map "+location+" from "+repr(mapping))
1930  mappedTo=mapping[location]
1931  if index!=None:
1932  mappedTo=mappedTo[index]
1933  seqList.remove(specifiedCommand)
1934  seqList.extend(mappedTo.split('+'))
1935  break;
1936  if level==maxLevel:
1937  raise Exception("Could not fully expand "+repr(seqList)+" from "+repr(mapping))
1938 
1939  def prepare_DQM(self, sequence = 'DQMOffline'):
1940  # this one needs replacement
1941 
1942  # any 'DQM' job should use DQMStore in non-legacy mode (but not HARVESTING)
1943  self.loadAndRemember("DQMServices/Core/DQMStoreNonLegacy_cff")
1945  sequenceList=sequence.split('.')[-1].split('+')
1946  postSequenceList=sequence.split('.')[-1].split('+')
1947  from DQMOffline.Configuration.autoDQM import autoDQM
1948  self.expandMapping(sequenceList,autoDQM,index=0)
1949  self.expandMapping(postSequenceList,autoDQM,index=1)
1950 
1951  if len(set(sequenceList))!=len(sequenceList):
1952  sequenceList=list(set(sequenceList))
1953  print("Duplicate entries for DQM:, using",sequenceList)
1954 
1955  pathName='dqmoffline_step'
1956  for (i,sequence) in enumerate(sequenceList):
1957  if (i!=0):
1958  pathName='dqmoffline_%d_step'%(i)
1959 
1960  if 'HLT' in self.stepMap.keys() or self._options.hltProcess:
1961  self.renameHLTprocessInSequence(sequence)
1962 
1963  setattr(self.process,pathName, cms.EndPath( getattr(self.process,sequence ) ) )
1964  self.schedule.append(getattr(self.process,pathName))
1965 
1966  if hasattr(self.process,"genstepfilter") and len(self.process.genstepfilter.triggerConditions):
1967  #will get in the schedule, smoothly
1968  getattr(self.process,pathName).insert(0,self.process.genstepfilter)
1969 
1970 
1971  pathName='dqmofflineOnPAT_step'
1972  for (i,sequence) in enumerate(postSequenceList):
1973  #Fix needed to avoid duplication of sequences not defined in autoDQM or without a PostDQM
1974  if (sequenceList[i]==postSequenceList[i]):
1975  continue
1976  if (i!=0):
1977  pathName='dqmofflineOnPAT_%d_step'%(i)
1978 
1979  setattr(self.process,pathName, cms.EndPath( getattr(self.process, sequence ) ) )
1980  self.schedule.append(getattr(self.process,pathName))
1981 
1982  def prepare_HARVESTING(self, sequence = None):
1983  """ Enrich the process with harvesting step """
1984  self.DQMSaverCFF='Configuration/StandardSequences/DQMSaver'+self._options.harvesting+'_cff'
1986 
1987  harvestingConfig = self.loadDefaultOrSpecifiedCFF(sequence,self.HARVESTINGDefaultCFF)
1988  sequence = sequence.split('.')[-1]
1989 
1990  # decide which HARVESTING paths to use
1991  harvestingList = sequence.split("+")
1992  from DQMOffline.Configuration.autoDQM import autoDQM
1993  from Validation.Configuration.autoValidation import autoValidation
1994  import copy
1995  combined_mapping = copy.deepcopy( autoDQM )
1996  combined_mapping.update( autoValidation )
1997  self.expandMapping(harvestingList,combined_mapping,index=-1)
1998 
1999  if len(set(harvestingList))!=len(harvestingList):
2000  harvestingList=list(set(harvestingList))
2001  print("Duplicate entries for HARVESTING, using",harvestingList)
2002 
2003  for name in harvestingList:
2004  if not name in harvestingConfig.__dict__:
2005  print(name,"is not a possible harvesting type. Available are",harvestingConfig.__dict__.keys())
2006  # trigger hard error, like for other sequence types
2007  getattr(self.process, name)
2008  continue
2009  harvestingstream = getattr(harvestingConfig,name)
2010  if isinstance(harvestingstream,cms.Path):
2011  self.schedule.append(harvestingstream)
2012  self.blacklist_paths.append(harvestingstream)
2013  if isinstance(harvestingstream,cms.Sequence):
2014  setattr(self.process,name+"_step",cms.Path(harvestingstream))
2015  self.schedule.append(getattr(self.process,name+"_step"))
2016 
2017  self.scheduleSequence('DQMSaver','dqmsave_step')
2018  return
2019 
2020  def prepare_ALCAHARVEST(self, sequence = None):
2021  """ Enrich the process with AlCaHarvesting step """
2022  harvestingConfig = self.loadAndRemember(self.ALCAHARVESTDefaultCFF)
2023  sequence=sequence.split(".")[-1]
2024 
2025  # decide which AlcaHARVESTING paths to use
2026  harvestingList = sequence.split("+")
2027 
2028 
2029 
2030  from Configuration.AlCa.autoPCL import autoPCL
2031  self.expandMapping(harvestingList,autoPCL)
2032 
2033  for name in harvestingConfig.__dict__:
2034  harvestingstream = getattr(harvestingConfig,name)
2035  if name in harvestingList and isinstance(harvestingstream,cms.Path):
2036  self.schedule.append(harvestingstream)
2037  if isinstance(getattr(harvestingConfig,"ALCAHARVEST" + name + "_dbOutput"), cms.VPSet) and \
2038  isinstance(getattr(harvestingConfig,"ALCAHARVEST" + name + "_metadata"), cms.VPSet):
2039  self.executeAndRemember("process.PoolDBOutputService.toPut.extend(process.ALCAHARVEST" + name + "_dbOutput)")
2040  self.executeAndRemember("process.pclMetadataWriter.recordsToMap.extend(process.ALCAHARVEST" + name + "_metadata)")
2041  else:
2042  self.executeAndRemember("process.PoolDBOutputService.toPut.append(process.ALCAHARVEST" + name + "_dbOutput)")
2043  self.executeAndRemember("process.pclMetadataWriter.recordsToMap.append(process.ALCAHARVEST" + name + "_metadata)")
2044  harvestingList.remove(name)
2045  # append the common part at the end of the sequence
2046  lastStep = getattr(harvestingConfig,"ALCAHARVESTDQMSaveAndMetadataWriter")
2047  self.schedule.append(lastStep)
2048 
2049  if len(harvestingList) != 0 and 'dummyHarvesting' not in harvestingList :
2050  print("The following harvesting could not be found : ", harvestingList)
2051  raise Exception("The following harvesting could not be found : "+str(harvestingList))
2052 
2053 
2054 
2055  def prepare_ENDJOB(self, sequence = 'endOfProcess'):
2057  self.scheduleSequenceAtEnd(sequence.split('.')[-1],'endjob_step')
2058  return
2059 
2060  def finalizeFastSimHLT(self):
2061  self.process.reconstruction = cms.Path(self.process.reconstructionWithFamos)
2062  self.schedule.append(self.process.reconstruction)
2063 
2064 
2065  def build_production_info(self, evt_type, evtnumber):
2066  """ Add useful info for the production. """
2067  self.process.configurationMetadata=cms.untracked.PSet\
2068  (version=cms.untracked.string("$Revision: 1.19 $"),
2069  name=cms.untracked.string("Applications"),
2070  annotation=cms.untracked.string(evt_type+ " nevts:"+str(evtnumber))
2071  )
2072 
2073  self.addedObjects.append(("Production Info","configurationMetadata"))
2074 
2075 
2076  def create_process(self):
2077  self.pythonCfgCode = "# Auto generated configuration file\n"
2078  self.pythonCfgCode += "# using: \n# "+__version__[1:-1]+"\n# "+__source__[1:-1]+'\n'
2079  self.pythonCfgCode += "# with command line options: "+self._options.arguments+'\n'
2080  self.pythonCfgCode += "import FWCore.ParameterSet.Config as cms\n\n"
2081 
2082  # now set up the modifies
2083  modifiers=[]
2084  modifierStrings=[]
2085  modifierImports=[]
2086 
2087  if hasattr(self._options,"era") and self._options.era :
2088  # Multiple eras can be specified in a comma seperated list
2089  from Configuration.StandardSequences.Eras import eras
2090  for requestedEra in self._options.era.split(",") :
2091  modifierStrings.append(requestedEra)
2092  modifierImports.append(eras.pythonCfgLines[requestedEra])
2093  modifiers.append(getattr(eras,requestedEra))
2094 
2095 
2096  if hasattr(self._options,"procModifiers") and self._options.procModifiers:
2097  import importlib
2098  thingsImported=[]
2099  for pm in self._options.procModifiers.split(','):
2100  modifierStrings.append(pm)
2101  modifierImports.append('from Configuration.ProcessModifiers.'+pm+'_cff import '+pm)
2102  modifiers.append(getattr(importlib.import_module('Configuration.ProcessModifiers.'+pm+'_cff'),pm))
2103 
2104  self.pythonCfgCode += '\n'.join(modifierImports)+'\n\n'
2105  self.pythonCfgCode += "process = cms.Process('"+self._options.name+"'" # Start of the line, finished after the loop
2106 
2107 
2108  if len(modifierStrings)>0:
2109  self.pythonCfgCode+= ','+','.join(modifierStrings)
2110  self.pythonCfgCode+=')\n\n'
2111 
2112  #yes, the cfg code gets out of sync here if a process is passed in. That could be fixed in the future
2113  #assuming there is some way for the fwk to get the list of modifiers (and their stringified name)
2114  if self.process == None:
2115  if len(modifiers)>0:
2116  self.process = cms.Process(self._options.name,*modifiers)
2117  else:
2118  self.process = cms.Process(self._options.name)
2119 
2120 
2121 
2122 
2123  def prepare(self, doChecking = False):
2124  """ Prepare the configuration string and add missing pieces."""
2125 
2126  self.loadAndRemember(self.EVTCONTDefaultCFF) #load the event contents regardless
2127  self.addMaxEvents()
2128  if self.with_input:
2129  self.addSource()
2130  self.addStandardSequences()
2131 
2132  self.completeInputCommand()
2133  self.addConditions()
2134 
2135 
2136  outputModuleCfgCode=""
2137  if not 'HARVESTING' in self.stepMap.keys() and not 'ALCAHARVEST' in self.stepMap.keys() and not 'ALCAOUTPUT' in self.stepMap.keys() and self.with_output:
2138  outputModuleCfgCode=self.addOutput()
2139 
2140  self.addCommon()
2141 
2142  self.pythonCfgCode += "# import of standard configurations\n"
2143  for module in self.imports:
2144  self.pythonCfgCode += ("process.load('"+module+"')\n")
2145 
2146  # production info
2147  if not hasattr(self.process,"configurationMetadata"):
2148  self.build_production_info(self._options.evt_type, self._options.number)
2149  else:
2150  #the PSet was added via a load
2151  self.addedObjects.append(("Production Info","configurationMetadata"))
2152 
2153  self.pythonCfgCode +="\n"
2154  for comment,object in self.addedObjects:
2155  if comment!="":
2156  self.pythonCfgCode += "\n# "+comment+"\n"
2157  self.pythonCfgCode += dumpPython(self.process,object)
2158 
2159  # dump the output definition
2160  self.pythonCfgCode += "\n# Output definition\n"
2161  self.pythonCfgCode += outputModuleCfgCode
2162 
2163  # dump all additional outputs (e.g. alca or skim streams)
2164  self.pythonCfgCode += "\n# Additional output definition\n"
2165  #I do not understand why the keys are not normally ordered.
2166  nl=sorted(self.additionalOutputs.keys())
2167  for name in nl:
2168  output = self.additionalOutputs[name]
2169  self.pythonCfgCode += "process.%s = %s" %(name, output.dumpPython())
2170  tmpOut = cms.EndPath(output)
2171  setattr(self.process,name+'OutPath',tmpOut)
2172  self.schedule.append(tmpOut)
2173 
2174  # dump all additional commands
2175  self.pythonCfgCode += "\n# Other statements\n"
2176  for command in self.additionalCommands:
2177  self.pythonCfgCode += command + "\n"
2178 
2179  #comma separated list of objects that deserve to be inlined in the configuration (typically from a modified config deep down)
2180  for object in self._options.inlineObjets.split(','):
2181  if not object:
2182  continue
2183  if not hasattr(self.process,object):
2184  print('cannot inline -'+object+'- : not known')
2185  else:
2186  self.pythonCfgCode +='\n'
2187  self.pythonCfgCode +=dumpPython(self.process,object)
2188 
2189  if self._options.pileup=='HiMixEmbGEN':
2190  self.pythonCfgCode += "\nprocess.generator.embeddingMode=cms.bool(True)\n"
2191 
2192  # dump all paths
2193  self.pythonCfgCode += "\n# Path and EndPath definitions\n"
2194  for path in self.process.paths:
2195  if getattr(self.process,path) not in self.blacklist_paths:
2196  self.pythonCfgCode += dumpPython(self.process,path)
2197 
2198  for endpath in self.process.endpaths:
2199  if getattr(self.process,endpath) not in self.blacklist_paths:
2200  self.pythonCfgCode += dumpPython(self.process,endpath)
2201 
2202  # dump the schedule
2203  self.pythonCfgCode += "\n# Schedule definition\n"
2204  result = "process.schedule = cms.Schedule("
2205 
2206  # handling of the schedule
2207  self.process.schedule = cms.Schedule()
2208  for item in self.schedule:
2209  if not isinstance(item, cms.Schedule):
2210  self.process.schedule.append(item)
2211  else:
2212  self.process.schedule.extend(item)
2213 
2214  if hasattr(self.process,"HLTSchedule"):
2215  beforeHLT = self.schedule[:self.schedule.index(self.process.HLTSchedule)]
2216  afterHLT = self.schedule[self.schedule.index(self.process.HLTSchedule)+1:]
2217  pathNames = ['process.'+p.label_() for p in beforeHLT]
2218  result += ','.join(pathNames)+')\n'
2219  result += 'process.schedule.extend(process.HLTSchedule)\n'
2220  pathNames = ['process.'+p.label_() for p in afterHLT]
2221  result += 'process.schedule.extend(['+','.join(pathNames)+'])\n'
2222  else:
2223  pathNames = ['process.'+p.label_() for p in self.schedule]
2224  result ='process.schedule = cms.Schedule('+','.join(pathNames)+')\n'
2225 
2226  self.pythonCfgCode += result
2227 
2228  for labelToAssociate in self.labelsToAssociate:
2229  self.process.schedule.associate(getattr(self.process, labelToAssociate))
2230  self.pythonCfgCode += 'process.schedule.associate(process.' + labelToAssociate + ')\n'
2231 
2232  from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask
2234  self.pythonCfgCode+="from PhysicsTools.PatAlgos.tools.helpers import associatePatAlgosToolsTask\n"
2235  self.pythonCfgCode+="associatePatAlgosToolsTask(process)\n"
2236 
2237  if self._options.nThreads is not "1":
2238  self.pythonCfgCode +="\n"
2239  self.pythonCfgCode +="#Setup FWK for multithreaded\n"
2240  self.pythonCfgCode +="process.options.numberOfThreads=cms.untracked.uint32("+self._options.nThreads+")\n"
2241  self.pythonCfgCode +="process.options.numberOfStreams=cms.untracked.uint32("+self._options.nStreams+")\n"
2242  self.pythonCfgCode +="process.options.numberOfConcurrentLuminosityBlocks=cms.untracked.uint32("+self._options.nConcurrentLumis+")\n"
2243  if int(self._options.nConcurrentLumis) > 1:
2244  self.pythonCfgCode +="if hasattr(process, 'DQMStore'): process.DQMStore.assertLegacySafe=cms.untracked.bool(False)\n"
2245  self.process.options.numberOfThreads=cms.untracked.uint32(int(self._options.nThreads))
2246  self.process.options.numberOfStreams=cms.untracked.uint32(int(self._options.nStreams))
2247  self.process.options.numberOfConcurrentLuminosityBlocks=cms.untracked.uint32(int(self._options.nConcurrentLumis))
2248  #repacked version
2249  if self._options.isRepacked:
2250  self.pythonCfgCode +="\n"
2251  self.pythonCfgCode +="from Configuration.Applications.ConfigBuilder import MassReplaceInputTag\n"
2252  self.pythonCfgCode +="MassReplaceInputTag(process, new=\"rawDataMapperByLabel\", old=\"rawDataCollector\")\n"
2253  MassReplaceInputTag(self.process, new="rawDataMapperByLabel", old="rawDataCollector")
2254 
2255  # special treatment in case of production filter sequence 2/2
2256  if self.productionFilterSequence and not (self._options.pileup=='HiMixEmbGEN'):
2257  self.pythonCfgCode +='# filter all path with the production filter sequence\n'
2258  self.pythonCfgCode +='for path in process.paths:\n'
2259  if len(self.conditionalPaths):
2260  self.pythonCfgCode +='\tif not path in %s: continue\n'%str(self.conditionalPaths)
2261  if len(self.excludedPaths):
2262  self.pythonCfgCode +='\tif path in %s: continue\n'%str(self.excludedPaths)
2263  self.pythonCfgCode +='\tgetattr(process,path).insert(0, process.%s)\n'%(self.productionFilterSequence,)
2264  pfs = getattr(self.process,self.productionFilterSequence)
2265  for path in self.process.paths:
2266  if not path in self.conditionalPaths: continue
2267  if path in self.excludedPaths: continue
2268  getattr(self.process,path).insert(0, pfs)
2269 
2270 
2271  # dump customise fragment
2272  self.pythonCfgCode += self.addCustomise()
2273 
2274  if self._options.runUnscheduled:
2275  print("--runUnscheduled is deprecated and not necessary anymore, and will be removed soon. Please update your command line.")
2276  # Keep the "unscheduled customise functions" separate for now,
2277  # there are customize functions given by users (in our unit
2278  # tests) that need to be run before the "unscheduled customise
2279  # functions"
2280  self.pythonCfgCode += self.addCustomise(1)
2281 
2282  self.pythonCfgCode += self.addCustomiseCmdLine()
2283 
2284  if hasattr(self.process,"logErrorHarvester"):
2285  #configure logErrorHarvester to wait for same EDProducers to finish as the OutputModules
2286  self.pythonCfgCode +="\n#Have logErrorHarvester wait for the same EDProducers to finish as those providing data for the OutputModule\n"
2287  self.pythonCfgCode +="from FWCore.Modules.logErrorHarvester_cff import customiseLogErrorHarvesterUsingOutputCommands\n"
2288  self.pythonCfgCode +="process = customiseLogErrorHarvesterUsingOutputCommands(process)\n"
2289  from FWCore.Modules.logErrorHarvester_cff import customiseLogErrorHarvesterUsingOutputCommands
2291 
2292  # Temporary hack to put the early delete customization after
2293  # everything else
2294  #
2295  # FIXME: remove when no longer needed
2296  self.pythonCfgCode += "\n# Add early deletion of temporary data products to reduce peak memory need\n"
2297  self.pythonCfgCode += "from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete\n"
2298  self.pythonCfgCode += "process = customiseEarlyDelete(process)\n"
2299  self.pythonCfgCode += "# End adding early deletion\n"
2300  from Configuration.StandardSequences.earlyDeleteSettings_cff import customiseEarlyDelete
2301  self.process = customiseEarlyDelete(self.process)
2302 
2303  imports = cms.specialImportRegistry.getSpecialImports()
2304  if len(imports) > 0:
2305  #need to inject this at the top
2306  index = self.pythonCfgCode.find("import FWCore.ParameterSet.Config")
2307  #now find the end of line
2308  index = self.pythonCfgCode.find("\n",index)
2309  self.pythonCfgCode = self.pythonCfgCode[:index]+ "\n" + "\n".join(imports)+"\n" +self.pythonCfgCode[index:]
2310 
2311 
2312  # make the .io file
2313 
2314  if self._options.io:
2315  #io=open(self._options.python_filename.replace('.py','.io'),'w')
2316  if not self._options.io.endswith('.io'): self._option.io+='.io'
2317  io=open(self._options.io,'w')
2318  ioJson={}
2319  if hasattr(self.process.source,"fileNames"):
2320  if len(self.process.source.fileNames.value()):
2321  ioJson['primary']=self.process.source.fileNames.value()
2322  if hasattr(self.process.source,"secondaryFileNames"):
2323  if len(self.process.source.secondaryFileNames.value()):
2324  ioJson['secondary']=self.process.source.secondaryFileNames.value()
2325  if self._options.pileup_input and (self._options.pileup_input.startswith('dbs:') or self._options.pileup_input.startswith('das:')):
2326  ioJson['pileup']=self._options.pileup_input[4:]
2327  for (o,om) in self.process.outputModules_().items():
2328  ioJson[o]=om.fileName.value()
2329  ioJson['GT']=self.process.GlobalTag.globaltag.value()
2330  if self.productionFilterSequence:
2331  ioJson['filter']=self.productionFilterSequence
2332  import json
2333  io.write(json.dumps(ioJson))
2334  return
2335 
2336 
ConfigBuilder.ConfigBuilder.GENDefaultSeq
GENDefaultSeq
Definition: ConfigBuilder.py:962
helpers.associatePatAlgosToolsTask
def associatePatAlgosToolsTask(process)
Definition: helpers.py:25
ConfigBuilder.ConfigBuilder.RECODefaultSeq
RECODefaultSeq
Definition: ConfigBuilder.py:977
LumiList.LumiList
Definition: LumiList.py:22
ConfigBuilder.ConfigBuilder.DIGIDefaultSeq
DIGIDefaultSeq
Definition: ConfigBuilder.py:964
ConfigBuilder.ConfigBuilder.prepare_GEN
def prepare_GEN(self, sequence=None)
Definition: ConfigBuilder.py:1318
ConfigBuilder.ConfigBuilder.VALIDATIONDefaultSeq
VALIDATIONDefaultSeq
Definition: ConfigBuilder.py:985
ConfigBuilder.ConfigBuilder.prepare_CFWRITER
def prepare_CFWRITER(self, sequence=None)
Definition: ConfigBuilder.py:1438
ConfigBuilder.ConfigBuilder.RECODefaultCFF
RECODefaultCFF
Definition: ConfigBuilder.py:936
FastTimerService_cff.range
range
Definition: FastTimerService_cff.py:34
ConfigBuilder.ConfigBuilder.prepare_L1Reco
def prepare_L1Reco(self, sequence="L1Reco")
Definition: ConfigBuilder.py:1578
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.enter
def enter(self, visitee)
Definition: ConfigBuilder.py:1883
logErrorHarvester_cff.customiseLogErrorHarvesterUsingOutputCommands
def customiseLogErrorHarvesterUsingOutputCommands(process)
Definition: logErrorHarvester_cff.py:5
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._whitelist
_whitelist
Definition: ConfigBuilder.py:1845
ConfigBuilder.ConfigBuilder.prepare_EI
def prepare_EI(self, sequence=None)
Definition: ConfigBuilder.py:1698
ConfigBuilder.ConfigBuilder.finalizeFastSimHLT
def finalizeFastSimHLT(self)
Definition: ConfigBuilder.py:2061
ConfigBuilder.ConfigBuilder.NANODefaultCFF
NANODefaultCFF
Definition: ConfigBuilder.py:939
resolutioncreator_cfi.object
object
Definition: resolutioncreator_cfi.py:4
ConfigBuilder.ConfigBuilder.EVTCONTDefaultCFF
EVTCONTDefaultCFF
Definition: ConfigBuilder.py:994
ConfigBuilder.ConfigBuilder.REPACKDefaultSeq
REPACKDefaultSeq
Definition: ConfigBuilder.py:987
ConfigBuilder.ConfigBuilder.prepare_NANOGEN
def prepare_NANOGEN(self, sequence="nanoAOD")
Definition: ConfigBuilder.py:1686
ConfigBuilder.ConfigBuilder.addMaxEvents
def addMaxEvents(self)
Definition: ConfigBuilder.py:366
ConfigBuilder.ConfigBuilder.LHEDefaultSeq
LHEDefaultSeq
Definition: ConfigBuilder.py:961
ConfigBuilder.ConfigBuilder.additionalOutputs
additionalOutputs
Definition: ConfigBuilder.py:262
ConfigBuilder.ConfigBuilder.productionFilterSequence
productionFilterSequence
put it before all the other paths
Definition: ConfigBuilder.py:264
ConfigBuilder.ConfigBuilder.DQMDefaultSeq
DQMDefaultSeq
Definition: ConfigBuilder.py:984
ConfigBuilder.ConfigBuilder.prepare_RECOSIM
def prepare_RECOSIM(self, sequence="recosim")
Definition: ConfigBuilder.py:1628
ConfigBuilder.ConfigBuilder.prepare_VALIDATION
def prepare_VALIDATION(self, sequence='validation')
Definition: ConfigBuilder.py:1767
ConfigBuilder.ConfigBuilder.VALIDATIONDefaultCFF
VALIDATIONDefaultCFF
Definition: ConfigBuilder.py:944
ConfigBuilder.ConfigBuilder.prepare_LHE
def prepare_LHE(self, sequence=None)
Definition: ConfigBuilder.py:1301
ConfigBuilder.ConfigBuilder.prepare_REPACK
def prepare_REPACK(self, sequence=None)
Definition: ConfigBuilder.py:1467
ConfigBuilder.ConfigBuilder.HARVESTINGDefaultCFF
HARVESTINGDefaultCFF
Definition: ConfigBuilder.py:947
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.__init__
def __init__(self, paramSearch, paramReplace, verbose=False, whitelist=())
Definition: ConfigBuilder.py:1841
ConfigBuilder.ConfigBuilder.GENDefaultCFF
GENDefaultCFF
Definition: ConfigBuilder.py:925
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.doIt
def doIt(self, pset, base)
Definition: ConfigBuilder.py:1847
ConfigBuilder.ConfigBuilder.prepare_DIGI2RAW
def prepare_DIGI2RAW(self, sequence=None)
Definition: ConfigBuilder.py:1462
ConfigBuilder.ConfigBuilder.addCommon
def addCommon(self)
Definition: ConfigBuilder.py:337
ConfigBuilder.ConfigBuilder.stepMap
stepMap
Definition: ConfigBuilder.py:223
ConfigBuilder.ConfigBuilder.L1TrackTriggerDefaultSeq
L1TrackTriggerDefaultSeq
Definition: ConfigBuilder.py:975
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._paramSearch
_paramSearch
Definition: ConfigBuilder.py:1843
ConfigBuilder.ConfigBuilder.SIMDefaultSeq
SIMDefaultSeq
Definition: ConfigBuilder.py:963
join
static std::string join(char **cmd)
Definition: RemoteFile.cc:17
ConfigBuilder.ConfigBuilder
Definition: ConfigBuilder.py:193
ConfigBuilder.ConfigBuilder.geometryDBLabel
geometryDBLabel
Definition: ConfigBuilder.py:1058
cms::cuda::assert
assert(be >=bs)
ConfigBuilder.ConfigBuilder.NANOGENDefaultCFF
NANOGENDefaultCFF
Definition: ConfigBuilder.py:940
ConfigBuilder.ConfigBuilder.RAW2DIGIDefaultSeq
RAW2DIGIDefaultSeq
Definition: ConfigBuilder.py:973
ConfigBuilder.ConfigBuilder.ALCAHARVESTDefaultSeq
ALCAHARVESTDefaultSeq
Definition: ConfigBuilder.py:971
relativeConstraints.keys
keys
Definition: relativeConstraints.py:89
ConfigBuilder.ConfigBuilder.pythonCfgCode
pythonCfgCode
Definition: ConfigBuilder.py:2078
ConfigBuilder.ConfigBuilder.PATGENDefaultCFF
PATGENDefaultCFF
Definition: ConfigBuilder.py:1004
earlyDeleteSettings_cff.customiseEarlyDelete
def customiseEarlyDelete(process)
Definition: earlyDeleteSettings_cff.py:41
ConfigBuilder.ConfigBuilder.with_input
with_input
Definition: ConfigBuilder.py:248
ConfigBuilder.ConfigBuilder.build_production_info
def build_production_info(self, evt_type, evtnumber)
Definition: ConfigBuilder.py:2066
ConfigBuilder.ConfigBuilder.executeAndRemember
def executeAndRemember(self, command)
Definition: ConfigBuilder.py:328
ConfigBuilder.ConfigBuilder.renameHLTprocessInSequence
def renameHLTprocessInSequence(self, sequence, proc=None, HLTprocess='HLT')
Definition: ConfigBuilder.py:1907
spr::find
void find(edm::Handle< EcalRecHitCollection > &hits, DetId thisDet, std::vector< EcalRecHitCollection::const_iterator > &hit, bool debug=false)
Definition: FindCaloHit.cc:19
ConfigBuilder.filesFromList
def filesFromList(fileName, s=None)
Definition: ConfigBuilder.py:100
ConfigBuilder.filesFromDASQuery
def filesFromDASQuery(query, option="", s=None)
Definition: ConfigBuilder.py:134
ConfigBuilder.ConfigBuilder.RECOBEFMIXDefaultCFF
RECOBEFMIXDefaultCFF
Definition: ConfigBuilder.py:1108
mps_monitormerge.items
list items
Definition: mps_monitormerge.py:29
ConfigBuilder.ConfigBuilder.expandMapping
def expandMapping(self, seqList, mapping, index=None)
Definition: ConfigBuilder.py:1921
any
bool any(const std::vector< T > &v, const T &what)
Definition: ECalSD.cc:38
ConfigBuilder.ConfigBuilder.prepare_FILTER
def prepare_FILTER(self, sequence=None)
Definition: ConfigBuilder.py:1590
ConfigBuilder.ConfigBuilder.PATDefaultCFF
PATDefaultCFF
Definition: ConfigBuilder.py:938
ConfigBuilder.ConfigBuilder.NANODefaultSeq
NANODefaultSeq
Definition: ConfigBuilder.py:992
ConfigBuilder.ConfigBuilder.prepare_PATGEN
def prepare_PATGEN(self, sequence="miniGEN")
Definition: ConfigBuilder.py:1667
ConfigBuilder.ConfigBuilder.scheduleSequence
def scheduleSequence(self, seq, prefix, what='Path')
Definition: ConfigBuilder.py:1204
ConfigBuilder.ConfigBuilder.conditionalPaths
conditionalPaths
Definition: ConfigBuilder.py:267
ConfigBuilder.ConfigBuilder.PATGENDefaultSeq
PATGENDefaultSeq
Definition: ConfigBuilder.py:989
ConfigBuilder.ConfigBuilder.RECOSIMDefaultSeq
RECOSIMDefaultSeq
Definition: ConfigBuilder.py:980
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._verbose
_verbose
Definition: ConfigBuilder.py:1844
ConfigBuilder.ConfigBuilder.addedObjects
addedObjects
Definition: ConfigBuilder.py:261
ConfigBuilder.ConfigBuilder.L1DefaultSeq
L1DefaultSeq
Definition: ConfigBuilder.py:968
CustomConfigs.ProcessName
def ProcessName(process)
Definition: CustomConfigs.py:8
ConfigBuilder.ConfigBuilder.create_process
def create_process(self)
Definition: ConfigBuilder.py:2077
ConfigBuilder.ConfigBuilder.__init__
def __init__(self, options, process=None, with_output=False, with_input=False)
Definition: ConfigBuilder.py:196
ConfigBuilder.Options
Definition: ConfigBuilder.py:20
ConfigBuilder.ConfigBuilder.prepare_ENDJOB
def prepare_ENDJOB(self, sequence='endOfProcess')
Definition: ConfigBuilder.py:2056
ConfigBuilder.ConfigBuilder.CFWRITERDefaultCFF
CFWRITERDefaultCFF
Definition: ConfigBuilder.py:951
submitPVValidationJobs.split
def split(sequence, size)
Definition: submitPVValidationJobs.py:352
ConfigBuilder.ConfigBuilder.ALCAHARVESTDefaultCFF
ALCAHARVESTDefaultCFF
Definition: ConfigBuilder.py:948
ConfigBuilder.ConfigBuilder.magFieldCFF
magFieldCFF
Definition: ConfigBuilder.py:1053
ConfigBuilder.ConfigBuilder.POSTRECODefaultCFF
POSTRECODefaultCFF
Definition: ConfigBuilder.py:943
ConfigBuilder.ConfigBuilder.imports
imports
Definition: ConfigBuilder.py:249
ConfigBuilder.ConfigBuilder.DQMSaverCFF
DQMSaverCFF
Definition: ConfigBuilder.py:1985
ConfigBuilder.ConfigBuilder.prepare_SIM
def prepare_SIM(self, sequence=None)
Definition: ConfigBuilder.py:1402
ConfigBuilder.ConfigBuilder.NANOGENDefaultSeq
NANOGENDefaultSeq
Definition: ConfigBuilder.py:991
str
#define str(s)
Definition: TestProcessor.cc:51
ConfigBuilder.ConfigBuilder.loadAndRemember
def loadAndRemember(self, includeFile)
Definition: ConfigBuilder.py:319
ConfigBuilder.ConfigBuilder.ALCADefaultSeq
ALCADefaultSeq
Definition: ConfigBuilder.py:960
ConfigBuilder.ConfigBuilder.ENDJOBDefaultCFF
ENDJOBDefaultCFF
Definition: ConfigBuilder.py:949
ConfigBuilder.ConfigBuilder.L1TrackTriggerDefaultCFF
L1TrackTriggerDefaultCFF
Definition: ConfigBuilder.py:935
ConfigBuilder.ConfigBuilder.addSource
def addSource(self)
Definition: ConfigBuilder.py:373
ConfigBuilder.ConfigBuilder.L1RecoDefaultSeq
L1RecoDefaultSeq
Definition: ConfigBuilder.py:974
ConfigBuilder.ConfigBuilder.prepare_ALCA
def prepare_ALCA(self, sequence=None, workflow='full')
Definition: ConfigBuilder.py:1243
ConfigBuilder.ConfigBuilder.prepare_RECOBEFMIX
def prepare_RECOBEFMIX(self, sequence="reconstruction")
Definition: ConfigBuilder.py:1634
ConfigBuilder.ConfigBuilder.L1REPACKDefaultSeq
L1REPACKDefaultSeq
Definition: ConfigBuilder.py:969
ConfigBuilder.ConfigBuilder.prepare_DIGI
def prepare_DIGI(self, sequence=None)
Definition: ConfigBuilder.py:1418
ConfigBuilder.ConfigBuilder.DIGI2RAWDefaultSeq
DIGI2RAWDefaultSeq
Definition: ConfigBuilder.py:966
ConfigBuilder.ConfigBuilder.ConditionsDefaultCFF
ConditionsDefaultCFF
Definition: ConfigBuilder.py:950
ConfigBuilder.ConfigBuilder.HLTDefaultSeq
HLTDefaultSeq
Definition: ConfigBuilder.py:967
ConfigBuilder.ConfigBuilder.prepare_SKIM
def prepare_SKIM(self, sequence="all")
Definition: ConfigBuilder.py:1710
ConfigBuilder.ConfigBuilder.L1EMDefaultCFF
L1EMDefaultCFF
Definition: ConfigBuilder.py:929
GlobalTag
Definition: GlobalTag.h:4
ConfigBuilder.ConfigBuilder.addOutput
def addOutput(self)
Definition: ConfigBuilder.py:501
DictTypes.SortedKeysDict
Definition: DictTypes.py:3
ConfigBuilder.ConfigBuilder.prepare_RECO
def prepare_RECO(self, sequence="reconstruction")
Definition: ConfigBuilder.py:1622
ConfigBuilder.ConfigBuilder.prepare_L1HwVal
def prepare_L1HwVal(self, sequence='L1HwVal')
Definition: ConfigBuilder.py:1571
ConfigBuilder.ConfigBuilder.excludedPaths
excludedPaths
Definition: ConfigBuilder.py:268
ConfigBuilder.ConfigBuilder.prepare_L1
def prepare_L1(self, sequence=None)
Definition: ConfigBuilder.py:1472
print
void print(TMatrixD &m, const char *label=nullptr, bool mathematicaFormat=false)
Definition: Utilities.cc:46
ConfigBuilder.ConfigBuilder.RECOBEFMIXDefaultSeq
RECOBEFMIXDefaultSeq
Definition: ConfigBuilder.py:1109
Mixing.defineMixing
def defineMixing(dict)
Definition: Mixing.py:188
Exception
mps_setup.append
append
Definition: mps_setup.py:85
ConfigBuilder.ConfigBuilder.EIDefaultCFF
EIDefaultCFF
Definition: ConfigBuilder.py:941
ConfigBuilder.ConfigBuilder.with_output
with_output
Definition: ConfigBuilder.py:243
ConfigBuilder.ConfigBuilder.define_Configs
def define_Configs(self)
Definition: ConfigBuilder.py:911
ConfigBuilder.ConfigBuilder.loadDefaultOrSpecifiedCFF
def loadDefaultOrSpecifiedCFF(self, sequence, defaultCFF)
Definition: ConfigBuilder.py:1192
ConfigBuilder.ConfigBuilder.profileOptions
def profileOptions(self)
Definition: ConfigBuilder.py:270
createfilelist.int
int
Definition: createfilelist.py:10
FrontierConditions_GlobalTag_cff.file
file
Definition: FrontierConditions_GlobalTag_cff.py:13
metFilterPaths_cff
ConfigBuilder.ConfigBuilder.L1RecoDefaultCFF
L1RecoDefaultCFF
Definition: ConfigBuilder.py:934
ConfigBuilder.ConfigBuilder.prepare_ALCAOUTPUT
def prepare_ALCAOUTPUT(self, sequence=None)
Definition: ConfigBuilder.py:1240
ConfigBuilder.ConfigBuilder.scheduleSequenceAtEnd
def scheduleSequenceAtEnd(self, seq, prefix)
Definition: ConfigBuilder.py:1233
ConfigBuilder.ConfigBuilder.addCustomiseCmdLine
def addCustomiseCmdLine(self)
Definition: ConfigBuilder.py:896
ConfigBuilder.ConfigBuilder.prepare_HLT
def prepare_HLT(self, sequence=None)
Definition: ConfigBuilder.py:1492
helpers
ConfigBuilder.anyOf
def anyOf(listOfKeys, dict, opt=None)
Definition: ConfigBuilder.py:182
ConfigBuilder.ConfigBuilder.DATAMIXDefaultSeq
DATAMIXDefaultSeq
Definition: ConfigBuilder.py:965
ConfigBuilder.ConfigBuilder.POSTRECODefaultSeq
POSTRECODefaultSeq
Definition: ConfigBuilder.py:982
ConfigBuilder.ConfigBuilder.prepare_POSTRECO
def prepare_POSTRECO(self, sequence=None)
Definition: ConfigBuilder.py:1760
ConfigBuilder.ConfigBuilder.HLTDefaultCFF
HLTDefaultCFF
Definition: ConfigBuilder.py:931
TriggerAnalyzer.__str__
def __str__(self)
Definition: TriggerAnalyzer.py:103
ConfigBuilder.ConfigBuilder.SKIMDefaultCFF
SKIMDefaultCFF
Definition: ConfigBuilder.py:942
ConfigBuilder.ConfigBuilder.prepare_ALCAPRODUCER
def prepare_ALCAPRODUCER(self, sequence=None)
Definition: ConfigBuilder.py:1237
ConfigBuilder.ConfigBuilder.RAW2DIGIDefaultCFF
RAW2DIGIDefaultCFF
Definition: ConfigBuilder.py:932
ConfigBuilder.ConfigBuilder.EIDefaultSeq
EIDefaultSeq
Definition: ConfigBuilder.py:981
ConfigBuilder.ConfigBuilder.stepKeys
stepKeys
Definition: ConfigBuilder.py:224
ConfigBuilder.ConfigBuilder.prepare_DQM
def prepare_DQM(self, sequence='DQMOffline')
Definition: ConfigBuilder.py:1940
ConfigBuilder.ConfigBuilder.DQMOFFLINEDefaultCFF
DQMOFFLINEDefaultCFF
Definition: ConfigBuilder.py:946
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor
Definition: ConfigBuilder.py:1838
ConfigBuilder.ConfigBuilder.labelsToAssociate
labelsToAssociate
Definition: ConfigBuilder.py:265
ConfigBuilder.ConfigBuilder.renameInputTagsInSequence
def renameInputTagsInSequence(self, sequence, oldT="rawDataCollector", newT="rawDataRepacker")
Definition: ConfigBuilder.py:1897
ConfigBuilder.ConfigBuilder.RAW2RECODefaultSeq
RAW2RECODefaultSeq
Definition: ConfigBuilder.py:1047
ComparisonHelper::zip
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
Definition: L1TStage2CaloLayer1.h:41
ConfigBuilder.ConfigBuilder.USERDefaultSeq
USERDefaultSeq
Definition: ConfigBuilder.py:1049
ConfigBuilder.ConfigBuilder.DIGIDefaultCFF
DIGIDefaultCFF
Definition: ConfigBuilder.py:927
ConfigBuilder.ConfigBuilder.L1MENUDefaultCFF
L1MENUDefaultCFF
Definition: ConfigBuilder.py:930
miniAOD_tools.miniAOD_customizeOutput
def miniAOD_customizeOutput(out)
Definition: miniAOD_tools.py:614
ConfigBuilder.ConfigBuilder.additionalCommands
additionalCommands
Definition: ConfigBuilder.py:258
ConfigBuilder.ConfigBuilder.load
def load(self, includeFile)
Definition: ConfigBuilder.py:314
ConfigBuilder.ConfigBuilder.REDIGIDefaultSeq
REDIGIDefaultSeq
Definition: ConfigBuilder.py:1124
ConfigBuilder.ConfigBuilder.HARVESTINGDefaultSeq
HARVESTINGDefaultSeq
Definition: ConfigBuilder.py:970
ConfigBuilder.ConfigBuilder.PATDefaultSeq
PATDefaultSeq
Definition: ConfigBuilder.py:988
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor.leave
def leave(self, visitee)
Definition: ConfigBuilder.py:1893
ConfigBuilder.ConfigBuilder.SimGeometryCFF
SimGeometryCFF
Definition: ConfigBuilder.py:1083
ConfigBuilder.ConfigBuilder.prepare_HARVESTING
def prepare_HARVESTING(self, sequence=None)
Definition: ConfigBuilder.py:1983
ConfigBuilder.ConfigBuilder.L1HwValDefaultSeq
L1HwValDefaultSeq
Definition: ConfigBuilder.py:983
ConfigBuilder.dumpPython
def dumpPython(process, name)
Definition: ConfigBuilder.py:92
ConfigBuilder.ConfigBuilder.runsAndWeights
runsAndWeights
drop LHEXMLStringProduct on input to save memory if appropriate
Definition: ConfigBuilder.py:479
ConfigBuilder.ConfigBuilder._options
_options
Definition: ConfigBuilder.py:201
ThrowAndSetRandomRun.throwAndSetRandomRun
def throwAndSetRandomRun(source, runsAndProbs)
Definition: ThrowAndSetRandomRun.py:7
ConfigBuilder.ConfigBuilder.L1HwValDefaultCFF
L1HwValDefaultCFF
Definition: ConfigBuilder.py:945
ConfigBuilder.ConfigBuilder.ALCADefaultCFF
ALCADefaultCFF
Definition: ConfigBuilder.py:924
edm::eventsetup::heterocontainer::insert
bool insert(Storage &iStorage, ItemType *iItem, const IdTag &iIdTag)
Definition: HCMethods.h:50
ConfigBuilder.ConfigBuilder.prepare_PAT
def prepare_PAT(self, sequence="miniAOD")
Definition: ConfigBuilder.py:1643
ConfigBuilder.ConfigBuilder.blacklist_paths
blacklist_paths
Definition: ConfigBuilder.py:260
MassReplace.massSearchReplaceAnyInputTag
def massSearchReplaceAnyInputTag(sequence, oldInputTag, newInputTag, verbose=False, moduleLabelOnly=False, skipLabelTest=False)
Definition: MassReplace.py:79
ConfigBuilder.ConfigBuilder.USERDefaultCFF
USERDefaultCFF
Definition: ConfigBuilder.py:1050
ConfigBuilder.ConfigBuilder.addCustomise
def addCustomise(self, unsch=0)
Definition: ConfigBuilder.py:823
ConfigBuilder.ConfigBuilder.prepare_ALCAHARVEST
def prepare_ALCAHARVEST(self, sequence=None)
Definition: ConfigBuilder.py:2021
ConfigBuilder.ConfigBuilder.completeInputCommand
def completeInputCommand(self)
Definition: ConfigBuilder.py:778
ConfigBuilder.ConfigBuilder.nextScheduleIsConditional
nextScheduleIsConditional
put the filtering path in the schedule
Definition: ConfigBuilder.py:266
AlignmentPI::index
index
Definition: AlignmentPayloadInspectorHelper.h:46
ConfigBuilder.ConfigBuilder.RECOSIMDefaultCFF
RECOSIMDefaultCFF
Definition: ConfigBuilder.py:937
ConfigBuilder.ConfigBuilder.prepare
def prepare(self, doChecking=False)
Definition: ConfigBuilder.py:2124
ConfigBuilder.ConfigBuilder.MassSearchReplaceProcessNameVisitor._paramReplace
_paramReplace
Definition: ConfigBuilder.py:1842
ConfigBuilder.ConfigBuilder.addExtraStream
def addExtraStream(self, name, stream, workflow='full')
Definition: ConfigBuilder.py:1127
ConfigBuilder.ConfigBuilder.process
process
adding standard sequences might change the inputEventContent option and therefore needs to be finaliz...
Definition: ConfigBuilder.py:244
ConfigBuilder.ConfigBuilder.addStandardSequences
def addStandardSequences(self)
Definition: ConfigBuilder.py:683
genParticles_cff.map
map
Definition: genParticles_cff.py:11
ConfigBuilder.ConfigBuilder.prepare_NANO
def prepare_NANO(self, sequence="nanoAOD")
Definition: ConfigBuilder.py:1675
ConfigBuilder.ConfigBuilder.prepare_RAW2RECO
def prepare_RAW2RECO(self, sequence=None)
Definition: ConfigBuilder.py:1547
ConfigBuilder.ConfigBuilder.prepare_DATAMIX
def prepare_DATAMIX(self, sequence=None)
Definition: ConfigBuilder.py:1444
ConfigBuilder.ConfigBuilder.REPACKDefaultCFF
REPACKDefaultCFF
Definition: ConfigBuilder.py:952
ConfigBuilder.ConfigBuilder.DATAMIXDefaultCFF
DATAMIXDefaultCFF
Definition: ConfigBuilder.py:955
ConfigBuilder.ConfigBuilder.prepare_L1REPACK
def prepare_L1REPACK(self, sequence=None)
Definition: ConfigBuilder.py:1479
ConfigBuilder.ConfigBuilder.GeometryCFF
GeometryCFF
Definition: ConfigBuilder.py:1057
ConfigBuilder.ConfigBuilder.inliner
inliner
load the relevant part
Definition: ConfigBuilder.py:1598
ConfigBuilder.ConfigBuilder.CFWRITERDefaultSeq
CFWRITERDefaultSeq
Definition: ConfigBuilder.py:972
ConfigBuilder.ConfigBuilder.DIGI2RAWDefaultCFF
DIGI2RAWDefaultCFF
Definition: ConfigBuilder.py:928
ConfigBuilder.ConfigBuilder.AlCaPaths
AlCaPaths
Definition: ConfigBuilder.py:1254
ConfigBuilder.ConfigBuilder.SIMDefaultCFF
SIMDefaultCFF
Definition: ConfigBuilder.py:926
ConfigBuilder.ConfigBuilder.prepare_L1TrackTrigger
def prepare_L1TrackTrigger(self, sequence="L1TrackTrigger")
Definition: ConfigBuilder.py:1584
ConfigBuilder.ConfigBuilder.schedule
schedule
Definition: ConfigBuilder.py:252
ConfigBuilder.ConfigBuilder.prepare_RAW2DIGI
def prepare_RAW2DIGI(self, sequence="RawToDigi")
Definition: ConfigBuilder.py:1558
ConfigBuilder.ConfigBuilder.prepare_PATFILTER
def prepare_PATFILTER(self, sequence=None)
Definition: ConfigBuilder.py:1565
ConfigBuilder.ConfigBuilder.ENDJOBDefaultSeq
ENDJOBDefaultSeq
Definition: ConfigBuilder.py:986
python.rootplot.root2matplotlib.replace
def replace(string, replacements)
Definition: root2matplotlib.py:444
ConfigBuilder.ConfigBuilder.prepare_USER
def prepare_USER(self, sequence=None)
Definition: ConfigBuilder.py:1754
ConfigBuilder.ConfigBuilder.addConditions
def addConditions(self)
Definition: ConfigBuilder.py:808